xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/MMUBundle.scala (revision 382a2ebdf328e8147e67aad81c929b5587bdfda4)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.cache.mmu
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import xiangshan._
23import utils._
24import utility._
25import xiangshan.backend.rob.RobPtr
26import xiangshan.backend.fu.util.HasCSRConst
27import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
28import freechips.rocketchip.tilelink._
29import xiangshan.backend.fu.{PMPReqBundle, PMPConfig}
30import xiangshan.backend.fu.PMPBundle
31
32
33abstract class TlbBundle(implicit p: Parameters) extends XSBundle with HasTlbConst
34abstract class TlbModule(implicit p: Parameters) extends XSModule with HasTlbConst
35
36
37class PtePermBundle(implicit p: Parameters) extends TlbBundle {
38  val d = Bool()
39  val a = Bool()
40  val g = Bool()
41  val u = Bool()
42  val x = Bool()
43  val w = Bool()
44  val r = Bool()
45
46  override def toPrintable: Printable = {
47    p"d:${d} a:${a} g:${g} u:${u} x:${x} w:${w} r:${r}"// +
48    //(if(hasV) (p"v:${v}") else p"")
49  }
50}
51
52class TlbPMBundle(implicit p: Parameters) extends TlbBundle {
53  val r = Bool()
54  val w = Bool()
55  val x = Bool()
56  val c = Bool()
57  val atomic = Bool()
58
59  def assign_ap(pm: PMPConfig) = {
60    r := pm.r
61    w := pm.w
62    x := pm.x
63    c := pm.c
64    atomic := pm.atomic
65  }
66}
67
68class TlbPermBundle(implicit p: Parameters) extends TlbBundle {
69  val pf = Bool() // NOTE: if this is true, just raise pf
70  val af = Bool() // NOTE: if this is true, just raise af
71  // pagetable perm (software defined)
72  val d = Bool()
73  val a = Bool()
74  val g = Bool()
75  val u = Bool()
76  val x = Bool()
77  val w = Bool()
78  val r = Bool()
79
80  def apply(item: PtwSectorResp) = {
81    val ptePerm = item.entry.perm.get.asTypeOf(new PtePermBundle().cloneType)
82    this.pf := item.pf
83    this.af := item.af
84    this.d := ptePerm.d
85    this.a := ptePerm.a
86    this.g := ptePerm.g
87    this.u := ptePerm.u
88    this.x := ptePerm.x
89    this.w := ptePerm.w
90    this.r := ptePerm.r
91
92    this
93  }
94
95  def applyS2(item: HptwResp) = {
96    val ptePerm = item.entry.perm.get.asTypeOf(new PtePermBundle().cloneType)
97    this.pf := item.gpf
98    this.af := item.gaf
99    this.d := ptePerm.d
100    this.a := ptePerm.a
101    this.g := ptePerm.g
102    this.u := ptePerm.u
103    this.x := ptePerm.x
104    this.w := ptePerm.w
105    this.r := ptePerm.r
106
107    this
108  }
109
110  override def toPrintable: Printable = {
111    p"pf:${pf} af:${af} d:${d} a:${a} g:${g} u:${u} x:${x} w:${w} r:${r} "
112  }
113}
114
115class TlbSectorPermBundle(implicit p: Parameters) extends TlbBundle {
116  val pf = Bool() // NOTE: if this is true, just raise pf
117  val af = Bool() // NOTE: if this is true, just raise af
118  // pagetable perm (software defined)
119  val d = Bool()
120  val a = Bool()
121  val g = Bool()
122  val u = Bool()
123  val x = Bool()
124  val w = Bool()
125  val r = Bool()
126
127  def apply(item: PtwSectorResp) = {
128    val ptePerm = item.entry.perm.get.asTypeOf(new PtePermBundle().cloneType)
129    this.pf := item.pf
130    this.af := item.af
131    this.d := ptePerm.d
132    this.a := ptePerm.a
133    this.g := ptePerm.g
134    this.u := ptePerm.u
135    this.x := ptePerm.x
136    this.w := ptePerm.w
137    this.r := ptePerm.r
138
139    this
140  }
141  override def toPrintable: Printable = {
142    p"pf:${pf} af:${af} d:${d} a:${a} g:${g} u:${u} x:${x} w:${w} r:${r} "
143  }
144}
145
146// multi-read && single-write
147// input is data, output is hot-code(not one-hot)
148class CAMTemplate[T <: Data](val gen: T, val set: Int, val readWidth: Int)(implicit p: Parameters) extends TlbModule {
149  val io = IO(new Bundle {
150    val r = new Bundle {
151      val req = Input(Vec(readWidth, gen))
152      val resp = Output(Vec(readWidth, Vec(set, Bool())))
153    }
154    val w = Input(new Bundle {
155      val valid = Bool()
156      val bits = new Bundle {
157        val index = UInt(log2Up(set).W)
158        val data = gen
159      }
160    })
161  })
162
163  val wordType = UInt(gen.getWidth.W)
164  val array = Reg(Vec(set, wordType))
165
166  io.r.resp.zipWithIndex.map{ case (a,i) =>
167    a := array.map(io.r.req(i).asUInt === _)
168  }
169
170  when (io.w.valid) {
171    array(io.w.bits.index) := io.w.bits.data.asUInt
172  }
173}
174
175class TlbEntry(pageNormal: Boolean, pageSuper: Boolean)(implicit p: Parameters) extends TlbBundle {
176  require(pageNormal || pageSuper)
177
178  val tag = if (!pageNormal) UInt((vpnLen - vpnnLen).W)
179  else UInt(vpnLen.W)
180  val asid = UInt(asidLen.W)
181  val level = if (!pageNormal) Some(UInt(1.W))
182  else if (!pageSuper) None
183  else Some(UInt(2.W))
184  val ppn = if (!pageNormal) UInt((ppnLen - vpnnLen).W)
185  else UInt(ppnLen.W)
186  val perm = new TlbPermBundle
187
188  val g_perm = new TlbPermBundle
189  val vmid = UInt(vmidLen.W)
190  val s2xlate = UInt(2.W)
191
192  /** s2xlate usage:
193    * bits0 0: disable s2xlate
194    *       1: enable s2xlate
195    * bits1 0: stage 1 and stage 2 if bits0 is 1
196    *       1: Only stage 2 if bits0 is 1
197    * */
198
199  /** level usage:
200    *  !PageSuper: page is only normal, level is None, match all the tag
201    *  !PageNormal: page is only super, level is a Bool(), match high 9*2 parts
202    *  bits0  0: need mid 9bits
203    *         1: no need mid 9bits
204    *  PageSuper && PageNormal: page hold all the three type,
205    *  bits0  0: need low 9bits
206    *  bits1  0: need mid 9bits
207    */
208
209
210  def hit(vpn: UInt, asid: UInt, nSets: Int = 1, ignoreAsid: Boolean = false, vmid: UInt, hasS2xlate: Bool, onlyS2: Bool): Bool = {
211    val asid_hit = Mux(hasS2xlate && onlyS2, true.B, if (ignoreAsid) true.B else (this.asid === asid))
212    val vmid_hit = Mux(hasS2xlate, this.vmid === vmid, true.B)
213
214    // NOTE: for timing, dont care low set index bits at hit check
215    //       do not need store the low bits actually
216    if (!pageSuper) asid_hit && drop_set_equal(vpn, tag, nSets) && vmid_hit
217    else if (!pageNormal) {
218      val tag_match_hi = tag(vpnnLen*2-1, vpnnLen) === vpn(vpnnLen*3-1, vpnnLen*2)
219      val tag_match_mi = tag(vpnnLen-1, 0) === vpn(vpnnLen*2-1, vpnnLen)
220      val tag_match = tag_match_hi && (level.get.asBool || tag_match_mi)
221      asid_hit && tag_match && vmid_hit
222    }
223    else {
224      val tmp_level = level.get
225      val tag_match_hi = tag(vpnnLen*3-1, vpnnLen*2) === vpn(vpnnLen*3-1, vpnnLen*2)
226      val tag_match_mi = tag(vpnnLen*2-1, vpnnLen) === vpn(vpnnLen*2-1, vpnnLen)
227      val tag_match_lo = tag(vpnnLen-1, 0) === vpn(vpnnLen-1, 0) // if pageNormal is false, this will always be false
228      val tag_match = tag_match_hi && (tmp_level(1) || tag_match_mi) && (tmp_level(0) || tag_match_lo)
229      asid_hit && tag_match && vmid_hit
230    }
231  }
232
233  def apply(item: PtwRespS2, pm: PMPConfig): TlbEntry = {
234    this.asid := item.s1.entry.asid
235    val inner_level = item.s1.entry.level.getOrElse(0.U) max item.s2.entry.level.getOrElse(0.U)
236    this.level.map(_ := { if (pageNormal && pageSuper) MuxLookup(inner_level, 0.U)(Seq(
237      0.U -> 3.U,
238      1.U -> 1.U,
239      2.U -> 0.U ))
240    else if (pageSuper) ~inner_level(0)
241    else 0.U })
242    val s1tag = {if (pageNormal) Cat(item.s1.entry.tag, OHToUInt(item.s1.pteidx)) else item.s1.entry.tag(sectorvpnLen - 1, vpnnLen - sectortlbwidth)}
243    val s2tag = {if (pageNormal) item.s2.entry.tag else item.s2.entry.tag(vpnLen - 1, vpnnLen)}
244    this.tag := Mux(item.s2xlate === onlyStage2, s2tag, s1tag)
245
246    val s1ppn = {
247      if (!pageNormal) item.s1.entry.ppn(sectorppnLen - 1, vpnnLen - sectortlbwidth)
248      else Cat(item.s1.entry.ppn, item.s1.ppn_low(OHToUInt(item.s1.pteidx)))
249    }
250    val s2ppn = {
251      if (!pageNormal) item.s2.entry.ppn(ppnLen - 1, vpnnLen)
252      else item.s2.entry.ppn
253    }
254    this.ppn := Mux(item.s2xlate === noS2xlate || item.s2xlate === onlyStage1, s1ppn, s2ppn)
255    this.perm.apply(item.s1)
256    this.vmid := item.s1.entry.vmid.getOrElse(0.U)
257    this.g_perm.applyS2(item.s2)
258    this.s2xlate := item.s2xlate
259    this
260  }
261
262  // 4KB is normal entry, 2MB/1GB is considered as super entry
263  def is_normalentry(): Bool = {
264    if (!pageSuper) { true.B }
265    else if (!pageNormal) { false.B }
266    else { level.get === 0.U }
267  }
268
269
270  def genPPN(saveLevel: Boolean = false, valid: Bool = false.B)(vpn: UInt) : UInt = {
271    val inner_level = level.getOrElse(0.U)
272    val ppn_res = if (!pageSuper) ppn
273    else if (!pageNormal) Cat(ppn(ppnLen-vpnnLen-1, vpnnLen),
274      Mux(inner_level(0), vpn(vpnnLen*2-1, vpnnLen), ppn(vpnnLen-1,0)),
275      vpn(vpnnLen-1, 0))
276    else Cat(ppn(ppnLen-1, vpnnLen*2),
277      Mux(inner_level(1), vpn(vpnnLen*2-1, vpnnLen), ppn(vpnnLen*2-1, vpnnLen)),
278      Mux(inner_level(0), vpn(vpnnLen-1, 0), ppn(vpnnLen-1, 0)))
279
280    if (saveLevel) Cat(ppn(ppn.getWidth-1, vpnnLen*2), RegEnable(ppn_res(vpnnLen*2-1, 0), valid))
281    else ppn_res
282  }
283
284  override def toPrintable: Printable = {
285    val inner_level = level.getOrElse(2.U)
286    p"asid: ${asid} level:${inner_level} vpn:${Hexadecimal(tag)} ppn:${Hexadecimal(ppn)} perm:${perm}"
287  }
288
289}
290
291class TlbSectorEntry(pageNormal: Boolean, pageSuper: Boolean)(implicit p: Parameters) extends TlbBundle {
292  require(pageNormal || pageSuper)
293
294  val tag = if (!pageNormal) UInt((vpnLen - vpnnLen).W)
295            else UInt(sectorvpnLen.W)
296  val asid = UInt(asidLen.W)
297  val level = if (!pageNormal) Some(UInt(1.W))
298              else if (!pageSuper) None
299              else Some(UInt(2.W))
300  val ppn = if (!pageNormal) UInt((ppnLen - vpnnLen).W)
301            else UInt(sectorppnLen.W) //only used when disable s2xlate
302  val perm = new TlbSectorPermBundle
303  val valididx = Vec(tlbcontiguous, Bool())
304  val pteidx = Vec(tlbcontiguous, Bool())
305  val ppn_low = Vec(tlbcontiguous, UInt(sectortlbwidth.W))
306
307  val g_perm = new TlbPermBundle
308  val vmid = UInt(vmidLen.W)
309  val s2xlate = UInt(2.W)
310
311  /** s2xlate usage:
312    * bits0 0: disable s2xlate
313    * 1: enable s2xlate
314    * bits1 0: stage 1 and stage 2 if bits0 is 1
315    * 1: Only stage 2 if bits0 is 1
316    * */
317
318  /** level usage:
319   *  !PageSuper: page is only normal, level is None, match all the tag
320   *  !PageNormal: page is only super, level is a Bool(), match high 9*2 parts
321   *  bits0  0: need mid 9bits
322   *         1: no need mid 9bits
323   *  PageSuper && PageNormal: page hold all the three type,
324   *  bits0  0: need low 9bits
325   *  bits1  0: need mid 9bits
326   */
327
328  def hit(vpn: UInt, asid: UInt, nSets: Int = 1, ignoreAsid: Boolean = false, vmid: UInt, hasS2xlate: Bool, onlyS2: Bool): Bool = {
329    val asid_hit = Mux(hasS2xlate && onlyS2, true.B, if (ignoreAsid) true.B else (this.asid === asid))
330    val addr_low_hit = valididx(vpn(2, 0))
331    val vmid_hit = Mux(hasS2xlate, this.vmid === vmid, true.B)
332    val pteidx_hit = Mux(hasS2xlate, pteidx(vpn(2, 0)), true.B)
333    // NOTE: for timing, dont care low set index bits at hit check
334    //       do not need store the low bits actually
335    if (!pageSuper) asid_hit && drop_set_equal(vpn(vpn.getWidth - 1, sectortlbwidth), tag, nSets) && addr_low_hit && vmid_hit && pteidx_hit
336    else if (!pageNormal) {
337      val tag_match_hi = tag(vpnnLen * 2 - 1, vpnnLen) === vpn(vpnnLen * 3 - 1, vpnnLen * 2)
338      val tag_match_mi = tag(vpnnLen - 1, 0) === vpn(vpnnLen * 2 - 1, vpnnLen)
339      val tag_match = tag_match_hi && (level.get.asBool || tag_match_mi)
340      asid_hit && tag_match && addr_low_hit && vmid_hit && pteidx_hit
341    }
342    else {
343      val tmp_level = level.get
344      val tag_match_hi = tag(vpnnLen * 3 - sectortlbwidth - 1, vpnnLen * 2 - sectortlbwidth) === vpn(vpnnLen * 3 - 1, vpnnLen * 2)
345      val tag_match_mi = tag(vpnnLen * 2 - sectortlbwidth - 1, vpnnLen - sectortlbwidth) === vpn(vpnnLen * 2 - 1, vpnnLen)
346      val tag_match_lo = tag(vpnnLen - sectortlbwidth - 1, 0) === vpn(vpnnLen - 1, sectortlbwidth) // if pageNormal is false, this will always be false
347      val tag_match = tag_match_hi && (tmp_level(1) || tag_match_mi) && (tmp_level(0) || tag_match_lo)
348      asid_hit && tag_match && addr_low_hit && vmid_hit && pteidx_hit
349    }
350  }
351
352  def wbhit(data: PtwSectorResp, asid: UInt, nSets: Int = 1, ignoreAsid: Boolean = false): Bool = {
353    val vpn = Cat(data.entry.tag, 0.U(sectortlbwidth.W))
354    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
355    val vpn_hit = Wire(Bool())
356    val index_hit = Wire(Vec(tlbcontiguous, Bool()))
357
358    // NOTE: for timing, dont care low set index bits at hit check
359    //       do not need store the low bits actually
360    if (!pageSuper) {
361      vpn_hit := asid_hit && drop_set_equal(vpn(vpn.getWidth - 1, sectortlbwidth), tag, nSets)
362    }
363    else if (!pageNormal) {
364      val tag_match_hi = tag(vpnnLen * 2 - 1, vpnnLen - sectortlbwidth) === vpn(vpnnLen * 3 - 1, vpnnLen * 2)
365      val tag_match_mi = tag(vpnnLen - 1, 0) === vpn(vpnnLen * 2 - 1, vpnnLen)
366      val tag_match = tag_match_hi && (level.get.asBool || tag_match_mi)
367      vpn_hit := asid_hit && tag_match
368    }
369    else {
370      val tmp_level = level.get
371      val tag_match_hi = tag(vpnnLen * 3 - sectortlbwidth - 1, vpnnLen * 2 - sectortlbwidth) === vpn(vpnnLen * 3 - 1, vpnnLen * 2)
372      val tag_match_mi = tag(vpnnLen * 2 - sectortlbwidth - 1, vpnnLen - sectortlbwidth) === vpn(vpnnLen * 2 - 1, vpnnLen)
373      val tag_match_lo = tag(vpnnLen - sectortlbwidth - 1, 0) === vpn(vpnnLen - 1, sectortlbwidth) // if pageNormal is false, this will always be false
374      val tag_match = tag_match_hi && (tmp_level(1) || tag_match_mi) && (tmp_level(0) || tag_match_lo)
375      vpn_hit := asid_hit && tag_match
376    }
377
378    for (i <- 0 until tlbcontiguous) {
379      index_hit(i) := data.valididx(i) && valididx(i)
380    }
381
382    // For example, tlb req to page cache with vpn 0x10
383    // At this time, 0x13 has not been paged, so page cache only resp 0x10
384    // When 0x13 refill to page cache, previous item will be flushed
385    // Now 0x10 and 0x13 are both valid in page cache
386    // However, when 0x13 refill to tlb, will trigger multi hit
387    // So will only trigger multi-hit when PopCount(data.valididx) = 1
388    vpn_hit && index_hit.reduce(_ || _) && PopCount(data.valididx) === 1.U
389  }
390
391  def apply(item: PtwRespS2): TlbSectorEntry = {
392    this.asid := item.s1.entry.asid
393    val inner_level = item.s1.entry.level.getOrElse(0.U) max item.s2.entry.level.getOrElse(0.U)
394    this.level.map(_ := { if (pageNormal && pageSuper) MuxLookup(inner_level, 0.U)(Seq(
395                                                        0.U -> 3.U,
396                                                        1.U -> 1.U,
397                                                        2.U -> 0.U ))
398                          else if (pageSuper) ~inner_level(0)
399                          else 0.U })
400    this.perm.apply(item.s1)
401
402    this.pteidx := Mux(item.s2xlate === noS2xlate || item.s2xlate === onlyStage1, item.s1.pteidx, VecInit(UIntToOH(item.s2.entry.tag(sectortlbwidth - 1, 0)).asBools))
403    this.valididx := Mux(item.s2xlate === noS2xlate || item.s2xlate === onlyStage1, item.s1.valididx, item.s1.pteidx)
404
405    val s1tag = {if (pageNormal) item.s1.entry.tag else item.s1.entry.tag(sectorvpnLen - 1, vpnnLen - sectortlbwidth)}
406    val s2tag = {if (pageNormal) item.s2.entry.tag else item.s2.entry.tag(sectorvpnLen - 1, vpnnLen - sectortlbwidth)}
407    this.tag := Mux(item.s2xlate === onlyStage2, s2tag, s1tag)
408
409    val s1ppn = {
410      if (!pageNormal) item.s1.entry.ppn(sectorppnLen - 1, vpnnLen - sectortlbwidth) else item.s1.entry.ppn
411    }
412    val s1ppn_low = item.s1.ppn_low
413    val s2ppn = {
414      if (!pageNormal) item.s2.entry.ppn(ppnLen - 1, vpnnLen) else item.s2.entry.ppn(ppnLen - 1, sectortlbwidth)
415    }
416    val s2ppn_low = VecInit(Seq.fill(tlbcontiguous)(item.s2.entry.ppn(sectortlbwidth - 1, 0)))
417    this.ppn := Mux(item.s2xlate === noS2xlate || item.s2xlate === onlyStage1, s1ppn, s2ppn)
418    this.ppn_low := Mux(item.s2xlate === noS2xlate || item.s2xlate === onlyStage1, s1ppn_low, s2ppn_low)
419    this.vmid := item.s1.entry.vmid.getOrElse(0.U)
420    this.g_perm.applyS2(item.s2)
421    this.s2xlate := item.s2xlate
422    this
423  }
424
425  // 4KB is normal entry, 2MB/1GB is considered as super entry
426  def is_normalentry(): Bool = {
427    if (!pageSuper) { true.B }
428    else if (!pageNormal) { false.B }
429    else { level.get === 0.U }
430  }
431
432
433  def genPPN(saveLevel: Boolean = false, valid: Bool = false.B)(vpn: UInt) : UInt = {
434    val inner_level = level.getOrElse(0.U)
435    val ppn_res = if (!pageSuper) Cat(ppn, ppn_low(vpn(sectortlbwidth - 1, 0)))
436      else if (!pageNormal) Cat(ppn(ppnLen - vpnnLen - 1, vpnnLen),
437        Mux(inner_level(0), vpn(vpnnLen * 2 - 1, vpnnLen), ppn(vpnnLen - 1,0)),
438        vpn(vpnnLen - 1, 0))
439      else Cat(ppn(sectorppnLen - 1, vpnnLen * 2 - sectortlbwidth),
440        Mux(inner_level(1), vpn(vpnnLen * 2 - 1, vpnnLen), ppn(vpnnLen * 2 - sectortlbwidth - 1, vpnnLen - sectortlbwidth)),
441        Mux(inner_level(0), vpn(vpnnLen - 1, 0), Cat(ppn(vpnnLen - sectortlbwidth - 1, 0), ppn_low(vpn(sectortlbwidth - 1, 0)))))
442
443    if (saveLevel) {
444      if (ppn.getWidth == ppnLen - vpnnLen) {
445        Cat(ppn(ppn.getWidth - 1, vpnnLen * 2), RegEnable(ppn_res(vpnnLen * 2 - 1, 0), valid))
446      } else {
447        require(ppn.getWidth == sectorppnLen)
448        Cat(ppn(ppn.getWidth - 1, vpnnLen * 2 - sectortlbwidth), RegEnable(ppn_res(vpnnLen * 2 - 1, 0), valid))
449      }
450    }
451    else ppn_res
452  }
453
454  def hasS2xlate(): Bool = {
455    this.s2xlate =/= noS2xlate
456  }
457
458  override def toPrintable: Printable = {
459    val inner_level = level.getOrElse(2.U)
460    p"asid: ${asid} level:${inner_level} vpn:${Hexadecimal(tag)} ppn:${Hexadecimal(ppn)} perm:${perm}"
461  }
462
463}
464
465object TlbCmd {
466  def read  = "b00".U
467  def write = "b01".U
468  def exec  = "b10".U
469
470  def atom_read  = "b100".U // lr
471  def atom_write = "b101".U // sc / amo
472
473  def apply() = UInt(3.W)
474  def isRead(a: UInt) = a(1,0)===read
475  def isWrite(a: UInt) = a(1,0)===write
476  def isExec(a: UInt) = a(1,0)===exec
477
478  def isAtom(a: UInt) = a(2)
479  def isAmo(a: UInt) = a===atom_write // NOTE: sc mixed
480}
481
482class TlbStorageIO(nSets: Int, nWays: Int, ports: Int, nDups: Int = 1)(implicit p: Parameters) extends MMUIOBaseBundle {
483  val r = new Bundle {
484    val req = Vec(ports, Flipped(DecoupledIO(new Bundle {
485      val vpn = Output(UInt(vpnLen.W))
486      val s2xlate = Output(UInt(2.W)) // 0 bit: has s2xlate, 1 bit: Only valid when 0 bit is 1. If 0, all stage; if 1, only stage 2
487    })))
488    val resp = Vec(ports, ValidIO(new Bundle{
489      val hit = Output(Bool())
490      val ppn = Vec(nDups, Output(UInt(ppnLen.W)))
491      val perm = Vec(nDups, Output(new TlbSectorPermBundle()))
492      val g_perm = Vec(nDups, Output(new TlbPermBundle()))
493      val s2xlate = Vec(nDups, Output(UInt(2.W)))
494    }))
495  }
496  val w = Flipped(ValidIO(new Bundle {
497    val wayIdx = Output(UInt(log2Up(nWays).W))
498    val data = Output(new PtwRespS2)
499  }))
500  val access = Vec(ports, new ReplaceAccessBundle(nSets, nWays))
501
502  def r_req_apply(valid: Bool, vpn: UInt, i: Int, s2xlate:UInt): Unit = {
503    this.r.req(i).valid := valid
504    this.r.req(i).bits.vpn := vpn
505    this.r.req(i).bits.s2xlate := s2xlate
506
507  }
508
509  def r_resp_apply(i: Int) = {
510    (this.r.resp(i).bits.hit, this.r.resp(i).bits.ppn, this.r.resp(i).bits.perm, this.r.resp(i).bits.g_perm)
511  }
512
513  def w_apply(valid: Bool, wayIdx: UInt, data: PtwRespS2): Unit = {
514    this.w.valid := valid
515    this.w.bits.wayIdx := wayIdx
516    this.w.bits.data := data
517  }
518
519}
520
521class TlbStorageWrapperIO(ports: Int, q: TLBParameters, nDups: Int = 1)(implicit p: Parameters) extends MMUIOBaseBundle {
522  val r = new Bundle {
523    val req = Vec(ports, Flipped(DecoupledIO(new Bundle {
524      val vpn = Output(UInt(vpnLen.W))
525      val s2xlate = Output(UInt(2.W))
526    })))
527    val resp = Vec(ports, ValidIO(new Bundle{
528      val hit = Output(Bool())
529      val ppn = Vec(nDups, Output(UInt(ppnLen.W)))
530      val perm = Vec(nDups, Output(new TlbPermBundle()))
531      val g_perm = Vec(nDups, Output(new TlbPermBundle()))
532      val s2xlate = Vec(nDups, Output(UInt(2.W)))
533    }))
534  }
535  val w = Flipped(ValidIO(new Bundle {
536    val data = Output(new PtwRespS2)
537  }))
538  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(ports, q)) else null
539
540  def r_req_apply(valid: Bool, vpn: UInt, i: Int, s2xlate: UInt): Unit = {
541    this.r.req(i).valid := valid
542    this.r.req(i).bits.vpn := vpn
543    this.r.req(i).bits.s2xlate := s2xlate
544  }
545
546  def r_resp_apply(i: Int) = {
547    (this.r.resp(i).bits.hit, this.r.resp(i).bits.ppn, this.r.resp(i).bits.perm,
548      this.r.resp(i).bits.super_hit, this.r.resp(i).bits.super_ppn, this.r.resp(i).bits.spm,
549       this.r.resp(i).bits.g_perm, this.r.resp(i).bits.s2xlate)
550  }
551
552  def w_apply(valid: Bool, data: PtwRespS2): Unit = {
553    this.w.valid := valid
554    this.w.bits.data := data
555  }
556}
557
558class ReplaceAccessBundle(nSets: Int, nWays: Int)(implicit p: Parameters) extends TlbBundle {
559  val sets = Output(UInt(log2Up(nSets).W))
560  val touch_ways = ValidIO(Output(UInt(log2Up(nWays).W)))
561}
562
563class ReplaceIO(Width: Int, nSets: Int, nWays: Int)(implicit p: Parameters) extends TlbBundle {
564  val access = Vec(Width, Flipped(new ReplaceAccessBundle(nSets, nWays)))
565
566  val refillIdx = Output(UInt(log2Up(nWays).W))
567  val chosen_set = Flipped(Output(UInt(log2Up(nSets).W)))
568
569  def apply_sep(in: Seq[ReplaceIO], vpn: UInt): Unit = {
570    for ((ac_rep, ac_tlb) <- access.zip(in.map(a => a.access.map(b => b)).flatten)) {
571      ac_rep := ac_tlb
572    }
573    this.chosen_set := get_set_idx(vpn, nSets)
574    in.map(a => a.refillIdx := this.refillIdx)
575  }
576}
577
578class TlbReplaceIO(Width: Int, q: TLBParameters)(implicit p: Parameters) extends
579  TlbBundle {
580  val page = new ReplaceIO(Width, q.NSets, q.NWays)
581
582  def apply_sep(in: Seq[TlbReplaceIO], vpn: UInt) = {
583    this.page.apply_sep(in.map(_.page), vpn)
584  }
585
586}
587
588class MemBlockidxBundle(implicit p: Parameters) extends TlbBundle {
589  val is_ld = Bool()
590  val is_st = Bool()
591  val idx =
592    if (VirtualLoadQueueSize >= StoreQueueSize) {
593      val idx = UInt(log2Ceil(VirtualLoadQueueSize).W)
594      idx
595    } else {
596      val idx = UInt(log2Ceil(StoreQueueSize).W)
597      idx
598    }
599}
600
601class TlbReq(implicit p: Parameters) extends TlbBundle {
602  val vaddr = Output(UInt(VAddrBits.W))
603  val cmd = Output(TlbCmd())
604  val hyperinst = Output(Bool())
605  val hlvx = Output(Bool())
606  val size = Output(UInt(log2Ceil(log2Ceil(XLEN/8)+1).W))
607  val kill = Output(Bool()) // Use for blocked tlb that need sync with other module like icache
608  val memidx = Output(new MemBlockidxBundle)
609  // do not translate, but still do pmp/pma check
610  val no_translate = Output(Bool())
611  val debug = new Bundle {
612    val pc = Output(UInt(XLEN.W))
613    val robIdx = Output(new RobPtr)
614    val isFirstIssue = Output(Bool())
615  }
616
617  // Maybe Block req needs a kill: for itlb, itlb and icache may not sync, itlb should wait icache to go ahead
618  override def toPrintable: Printable = {
619    p"vaddr:0x${Hexadecimal(vaddr)} cmd:${cmd} kill:${kill} pc:0x${Hexadecimal(debug.pc)} robIdx:${debug.robIdx}"
620  }
621}
622
623class TlbExceptionBundle(implicit p: Parameters) extends TlbBundle {
624  val ld = Output(Bool())
625  val st = Output(Bool())
626  val instr = Output(Bool())
627}
628
629class TlbResp(nDups: Int = 1)(implicit p: Parameters) extends TlbBundle {
630  val paddr = Vec(nDups, Output(UInt(PAddrBits.W)))
631  val gpaddr = Vec(nDups, Output(UInt(GPAddrBits.W)))
632  val miss = Output(Bool())
633  val excp = Vec(nDups, new Bundle {
634    val gpf = new TlbExceptionBundle()
635    val pf = new TlbExceptionBundle()
636    val af = new TlbExceptionBundle()
637  })
638  val ptwBack = Output(Bool()) // when ptw back, wake up replay rs's state
639  val memidx = Output(new MemBlockidxBundle)
640
641  val debug = new Bundle {
642    val robIdx = Output(new RobPtr)
643    val isFirstIssue = Output(Bool())
644  }
645  override def toPrintable: Printable = {
646    p"paddr:0x${Hexadecimal(paddr(0))} miss:${miss} excp.pf: ld:${excp(0).pf.ld} st:${excp(0).pf.st} instr:${excp(0).pf.instr} ptwBack:${ptwBack}"
647  }
648}
649
650class TlbRequestIO(nRespDups: Int = 1)(implicit p: Parameters) extends TlbBundle {
651  val req = DecoupledIO(new TlbReq)
652  val req_kill = Output(Bool())
653  val resp = Flipped(DecoupledIO(new TlbResp(nRespDups)))
654}
655
656class TlbPtwIO(Width: Int = 1)(implicit p: Parameters) extends TlbBundle {
657  val req = Vec(Width, DecoupledIO(new PtwReq))
658  val resp = Flipped(DecoupledIO(new PtwRespS2))
659
660
661  override def toPrintable: Printable = {
662    p"req(0):${req(0).valid} ${req(0).ready} ${req(0).bits} | resp:${resp.valid} ${resp.ready} ${resp.bits}"
663  }
664}
665
666class TlbPtwIOwithMemIdx(Width: Int = 1)(implicit p: Parameters) extends TlbBundle {
667  val req = Vec(Width, DecoupledIO(new PtwReqwithMemIdx))
668  val resp = Flipped(DecoupledIO(new PtwRespS2withMemIdx()))
669
670
671  override def toPrintable: Printable = {
672    p"req(0):${req(0).valid} ${req(0).ready} ${req(0).bits} | resp:${resp.valid} ${resp.ready} ${resp.bits}"
673  }
674}
675
676class TlbHintReq(implicit p: Parameters) extends TlbBundle {
677  val id = Output(UInt(log2Up(loadfiltersize).W))
678  val full = Output(Bool())
679}
680
681class TLBHintResp(implicit p: Parameters) extends TlbBundle {
682  val id = Output(UInt(log2Up(loadfiltersize).W))
683  // When there are multiple matching entries for PTW resp in filter
684  // e.g. vaddr 0, 0x80000000. vaddr 1, 0x80010000
685  // these two vaddrs are not in a same 4K Page, so will send to ptw twice
686  // However, when ptw resp, if they are in a 1G or 2M huge page
687  // The two entries will both hit, and both need to replay
688  val replay_all = Output(Bool())
689}
690
691class TlbHintIO(implicit p: Parameters) extends TlbBundle {
692  val req = Vec(exuParameters.LduCnt, new TlbHintReq)
693  val resp = ValidIO(new TLBHintResp)
694}
695
696class MMUIOBaseBundle(implicit p: Parameters) extends TlbBundle {
697  val sfence = Input(new SfenceBundle)
698  val csr = Input(new TlbCsrBundle)
699
700  def base_connect(sfence: SfenceBundle, csr: TlbCsrBundle): Unit = {
701    this.sfence <> sfence
702    this.csr <> csr
703  }
704
705  // overwrite satp. write satp will cause flushpipe but csr.priv won't
706  // satp will be dealyed several cycles from writing, but csr.priv won't
707  // so inside mmu, these two signals should be divided
708  def base_connect(sfence: SfenceBundle, csr: TlbCsrBundle, satp: TlbSatpBundle) = {
709    this.sfence <> sfence
710    this.csr <> csr
711    this.csr.satp := satp
712  }
713}
714
715class TlbRefilltoMemIO()(implicit p: Parameters) extends TlbBundle {
716  val valid = Bool()
717  val memidx = new MemBlockidxBundle
718}
719
720class TlbIO(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends
721  MMUIOBaseBundle {
722  val hartId = Input(UInt(hartIdLen.W))
723  val requestor = Vec(Width, Flipped(new TlbRequestIO(nRespDups)))
724  val flushPipe = Vec(Width, Input(Bool()))
725  val ptw = new TlbPtwIOwithMemIdx(Width)
726  val refill_to_mem = Output(new TlbRefilltoMemIO())
727  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(Width, q)) else null
728  val pmp = Vec(Width, ValidIO(new PMPReqBundle()))
729  val tlbreplay = Vec(Width, Output(Bool()))
730}
731
732class VectorTlbPtwIO(Width: Int)(implicit p: Parameters) extends TlbBundle {
733  val req = Vec(Width, DecoupledIO(new PtwReqwithMemIdx()))
734  val resp = Flipped(DecoupledIO(new Bundle {
735    val data = new PtwRespS2withMemIdx
736    val vector = Output(Vec(Width, Bool()))
737  }))
738
739  def connect(normal: TlbPtwIOwithMemIdx): Unit = {
740    req <> normal.req
741    resp.ready := normal.resp.ready
742    normal.resp.bits := resp.bits.data
743    normal.resp.valid := resp.valid
744  }
745}
746
747/****************************  L2TLB  *************************************/
748abstract class PtwBundle(implicit p: Parameters) extends XSBundle with HasPtwConst
749abstract class PtwModule(outer: L2TLB) extends LazyModuleImp(outer)
750  with HasXSParameter with HasPtwConst
751
752class PteBundle(implicit p: Parameters) extends PtwBundle{
753  val reserved  = UInt(pteResLen.W)
754  val ppn_high = UInt(ppnHignLen.W)
755  val ppn  = UInt(ppnLen.W)
756  val rsw  = UInt(2.W)
757  val perm = new Bundle {
758    val d    = Bool()
759    val a    = Bool()
760    val g    = Bool()
761    val u    = Bool()
762    val x    = Bool()
763    val w    = Bool()
764    val r    = Bool()
765    val v    = Bool()
766  }
767
768  def unaligned(level: UInt) = {
769    isLeaf() && !(level === 2.U ||
770                  level === 1.U && ppn(vpnnLen-1,   0) === 0.U ||
771                  level === 0.U && ppn(vpnnLen*2-1, 0) === 0.U)
772  }
773
774  def isPf(level: UInt) = {
775    !perm.v || (!perm.r && perm.w) || unaligned(level)
776  }
777
778  // paddr of Xiangshan is 36 bits but ppn of sv39 is 44 bits
779  // access fault will be raised when ppn >> ppnLen is not zero
780  def isAf() = {
781    !(ppn_high === 0.U)
782  }
783
784  def isLeaf() = {
785    perm.r || perm.x || perm.w
786  }
787
788  def getPerm() = {
789    val pm = Wire(new PtePermBundle)
790    pm.d := perm.d
791    pm.a := perm.a
792    pm.g := perm.g
793    pm.u := perm.u
794    pm.x := perm.x
795    pm.w := perm.w
796    pm.r := perm.r
797    pm
798  }
799
800  override def toPrintable: Printable = {
801    p"ppn:0x${Hexadecimal(ppn)} perm:b${Binary(perm.asUInt)}"
802  }
803}
804
805class PtwEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwBundle {
806  val tag = UInt(tagLen.W)
807  val asid = UInt(asidLen.W)
808  val vmid = if (HasHExtension) Some(UInt(vmidLen.W)) else None
809  val ppn = UInt(ppnLen.W)
810  val perm = if (hasPerm) Some(new PtePermBundle) else None
811  val level = if (hasLevel) Some(UInt(log2Up(Level).W)) else None
812  val prefetch = Bool()
813  val v = Bool()
814
815  def is_normalentry(): Bool = {
816    if (!hasLevel) true.B
817    else level.get === 2.U
818  }
819
820  def genPPN(vpn: UInt): UInt = {
821    if (!hasLevel) ppn
822    else MuxLookup(level.get, 0.U)(Seq(
823          0.U -> Cat(ppn(ppn.getWidth-1, vpnnLen*2), vpn(vpnnLen*2-1, 0)),
824          1.U -> Cat(ppn(ppn.getWidth-1, vpnnLen), vpn(vpnnLen-1, 0)),
825          2.U -> ppn)
826    )
827  }
828
829  //s2xlate control whether compare vmid or not
830  def hit(vpn: UInt, asid: UInt, vmid: UInt, allType: Boolean = false, ignoreAsid: Boolean = false, s2xlate: Bool) = {
831    require(vpn.getWidth == vpnLen)
832//    require(this.asid.getWidth <= asid.getWidth)
833    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
834    val vmid_hit = Mux(s2xlate, (this.vmid.getOrElse(0.U) === vmid), true.B)
835    if (allType) {
836      require(hasLevel)
837      val hit0 = tag(tagLen - 1,    vpnnLen*2) === vpn(tagLen - 1, vpnnLen*2)
838      val hit1 = tag(vpnnLen*2 - 1, vpnnLen)   === vpn(vpnnLen*2 - 1,  vpnnLen)
839      val hit2 = tag(vpnnLen - 1,     0)         === vpn(vpnnLen - 1, 0)
840
841      asid_hit && vmid_hit && Mux(level.getOrElse(0.U) === 2.U, hit2 && hit1 && hit0, Mux(level.getOrElse(0.U) === 1.U, hit1 && hit0, hit0))
842    } else if (hasLevel) {
843      val hit0 = tag(tagLen - 1, tagLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
844      val hit1 = tag(tagLen - vpnnLen - 1, tagLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
845
846      asid_hit && vmid_hit && Mux(level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1)
847    } else {
848      asid_hit && vmid_hit && tag === vpn(vpnLen - 1, vpnLen - tagLen)
849    }
850  }
851
852  def refill(vpn: UInt, asid: UInt, vmid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool, valid: Bool = false.B) {
853    require(this.asid.getWidth <= asid.getWidth) // maybe equal is better, but ugly outside
854
855    tag := vpn(vpnLen - 1, vpnLen - tagLen)
856    ppn := pte.asTypeOf(new PteBundle().cloneType).ppn
857    perm.map(_ := pte.asTypeOf(new PteBundle().cloneType).perm)
858    this.asid := asid
859    this.vmid.map(_ := vmid)
860    this.prefetch := prefetch
861    this.v := valid
862    this.level.map(_ := level)
863  }
864
865  def genPtwEntry(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool, valid: Bool = false.B) = {
866    val e = Wire(new PtwEntry(tagLen, hasPerm, hasLevel))
867    e.refill(vpn, asid, pte, level, prefetch, valid)
868    e
869  }
870
871
872
873  override def toPrintable: Printable = {
874    // p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} perm:${perm}"
875    p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} " +
876      (if (hasPerm) p"perm:${perm.getOrElse(0.U.asTypeOf(new PtePermBundle))} " else p"") +
877      (if (hasLevel) p"level:${level.getOrElse(0.U)}" else p"") +
878      p"prefetch:${prefetch}"
879  }
880}
881
882class PtwSectorEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwEntry(tagLen, hasPerm, hasLevel) {
883  override val ppn = UInt(sectorppnLen.W)
884}
885
886class PtwMergeEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwSectorEntry(tagLen, hasPerm, hasLevel) {
887  val ppn_low = UInt(sectortlbwidth.W)
888  val af = Bool()
889  val pf = Bool()
890}
891
892class HptwMergeEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwMergeEntry(tagLen, hasPerm, hasLevel)
893
894class PtwEntries(num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
895  require(log2Up(num)==log2Down(num))
896  // NOTE: hasPerm means that is leaf or not.
897
898  val tag  = UInt(tagLen.W)
899  val asid = UInt(asidLen.W)
900  val vmid = if (HasHExtension) Some(UInt(vmidLen.W)) else None
901  val ppns = if (HasHExtension) Vec(num, UInt((vpnLen.max(ppnLen)).W)) else Vec(num, UInt(ppnLen.W))
902  val vs   = Vec(num, Bool())
903  val perms = if (hasPerm) Some(Vec(num, new PtePermBundle)) else None
904  val prefetch = Bool()
905  // println(s"PtwEntries: tag:1*${tagLen} ppns:${num}*${ppnLen} vs:${num}*1")
906  // NOTE: vs is used for different usage:
907  // for l3, which store the leaf(leaves), vs is page fault or not.
908  // for l2, which shoule not store leaf, vs is valid or not, that will anticipate in hit check
909  // Because, l2 should not store leaf(no perm), it doesn't store perm.
910  // If l2 hit a leaf, the perm is still unavailble. Should still page walk. Complex but nothing helpful.
911  // TODO: divide vs into validVec and pfVec
912  // for l2: may valid but pf, so no need for page walk, return random pte with pf.
913
914  def tagClip(vpn: UInt) = {
915    require(vpn.getWidth == vpnLen)
916    vpn(vpnLen - 1, vpnLen - tagLen)
917  }
918
919  def sectorIdxClip(vpn: UInt, level: Int) = {
920    getVpnClip(vpn, level)(log2Up(num) - 1, 0)
921  }
922
923  def hit(vpn: UInt, asid: UInt, vmid:UInt, ignoreAsid: Boolean = false, s2xlate: Bool) = {
924    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
925    val vmid_hit = Mux(s2xlate, this.vmid.getOrElse(0.U) === vmid, true.B)
926    asid_hit && vmid_hit && tag === tagClip(vpn) && (if (hasPerm) true.B else vs(sectorIdxClip(vpn, level)))
927  }
928
929  def genEntries(vpn: UInt, asid: UInt, vmid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
930    require((data.getWidth / XLEN) == num,
931      s"input data length must be multiple of pte length: data.length:${data.getWidth} num:${num}")
932
933    val ps = Wire(new PtwEntries(num, tagLen, level, hasPerm))
934    ps.tag := tagClip(vpn)
935    ps.asid := asid
936    ps.vmid.map(_ := vmid)
937    ps.prefetch := prefetch
938    for (i <- 0 until num) {
939      val pte = data((i+1)*XLEN-1, i*XLEN).asTypeOf(new PteBundle)
940      ps.ppns(i) := pte.ppn
941      ps.vs(i)   := !pte.isPf(levelUInt) && (if (hasPerm) pte.isLeaf() else !pte.isLeaf())
942      ps.perms.map(_(i) := pte.perm)
943    }
944    ps
945  }
946
947  override def toPrintable: Printable = {
948    // require(num == 4, "if num is not 4, please comment this toPrintable")
949    // NOTE: if num is not 4, please comment this toPrintable
950    val permsInner = perms.getOrElse(0.U.asTypeOf(Vec(num, new PtePermBundle)))
951    p"asid: ${Hexadecimal(asid)} tag:0x${Hexadecimal(tag)} ppns:${printVec(ppns)} vs:${Binary(vs.asUInt)} " +
952      (if (hasPerm) p"perms:${printVec(permsInner)}" else p"")
953  }
954}
955
956class PTWEntriesWithEcc(eccCode: Code, num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
957  val entries = new PtwEntries(num, tagLen, level, hasPerm)
958
959  val ecc_block = XLEN
960  val ecc_info = get_ecc_info()
961  val ecc = UInt(ecc_info._1.W)
962
963  def get_ecc_info(): (Int, Int, Int, Int) = {
964    val eccBits_per = eccCode.width(ecc_block) - ecc_block
965
966    val data_length = entries.getWidth
967    val data_align_num = data_length / ecc_block
968    val data_not_align = (data_length % ecc_block) != 0 // ugly code
969    val data_unalign_length = data_length - data_align_num * ecc_block
970    val eccBits_unalign = eccCode.width(data_unalign_length) - data_unalign_length
971
972    val eccBits = eccBits_per * data_align_num + eccBits_unalign
973    (eccBits, eccBits_per, data_align_num, data_unalign_length)
974  }
975
976  def encode() = {
977    val data = entries.asUInt
978    val ecc_slices = Wire(Vec(ecc_info._3, UInt(ecc_info._2.W)))
979    for (i <- 0 until ecc_info._3) {
980      ecc_slices(i) := eccCode.encode(data((i+1)*ecc_block-1, i*ecc_block)) >> ecc_block
981    }
982    if (ecc_info._4 != 0) {
983      val ecc_unaligned = eccCode.encode(data(data.getWidth-1, ecc_info._3*ecc_block)) >> ecc_info._4
984      ecc := Cat(ecc_unaligned, ecc_slices.asUInt)
985    } else { ecc := ecc_slices.asUInt }
986  }
987
988  def decode(): Bool = {
989    val data = entries.asUInt
990    val res = Wire(Vec(ecc_info._3 + 1, Bool()))
991    for (i <- 0 until ecc_info._3) {
992      res(i) := {if (ecc_info._2 != 0) eccCode.decode(Cat(ecc((i+1)*ecc_info._2-1, i*ecc_info._2), data((i+1)*ecc_block-1, i*ecc_block))).error else false.B}
993    }
994    if (ecc_info._2 != 0 && ecc_info._4 != 0) {
995      res(ecc_info._3) := eccCode.decode(
996        Cat(ecc(ecc_info._1-1, ecc_info._2*ecc_info._3), data(data.getWidth-1, ecc_info._3*ecc_block))).error
997    } else { res(ecc_info._3) := false.B }
998
999    Cat(res).orR
1000  }
1001
1002  def gen(vpn: UInt, asid: UInt, vmid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
1003    this.entries := entries.genEntries(vpn, asid, vmid, data, levelUInt, prefetch)
1004    this.encode()
1005  }
1006}
1007
1008class PtwReq(implicit p: Parameters) extends PtwBundle {
1009  val vpn = UInt(vpnLen.W) //vpn or gvpn
1010  val s2xlate = UInt(2.W) // 0 bit: s2xlate, 1 bit: stage 1 or stage 2
1011  def hasS2xlate(): Bool = {
1012    this.s2xlate =/= noS2xlate
1013  }
1014  override def toPrintable: Printable = {
1015    p"vpn:0x${Hexadecimal(vpn)}"
1016  }
1017}
1018
1019class PtwReqwithMemIdx(implicit p: Parameters) extends PtwReq {
1020  val memidx = new MemBlockidxBundle
1021}
1022
1023class PtwResp(implicit p: Parameters) extends PtwBundle {
1024  val entry = new PtwEntry(tagLen = vpnLen, hasPerm = true, hasLevel = true)
1025  val pf = Bool()
1026  val af = Bool()
1027
1028  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, asid: UInt) = {
1029    this.entry.level.map(_ := level)
1030    this.entry.tag := vpn
1031    this.entry.perm.map(_ := pte.getPerm())
1032    this.entry.ppn := pte.ppn
1033    this.entry.prefetch := DontCare
1034    this.entry.asid := asid
1035    this.entry.v := !pf
1036    this.pf := pf
1037    this.af := af
1038  }
1039
1040  override def toPrintable: Printable = {
1041    p"entry:${entry} pf:${pf} af:${af}"
1042  }
1043}
1044
1045class HptwResp(implicit p: Parameters) extends PtwBundle {
1046  val entry = new PtwEntry(tagLen = vpnLen, hasPerm = true, hasLevel = true)
1047  val gpf = Bool()
1048  val gaf = Bool()
1049
1050  def apply(gpf: Bool, gaf: Bool, level: UInt, pte: PteBundle, vpn: UInt, vmid: UInt) = {
1051    this.entry.level.map(_ := level)
1052    this.entry.tag := vpn
1053    this.entry.perm.map(_ := pte.getPerm())
1054    this.entry.ppn := pte.ppn
1055    this.entry.prefetch := DontCare
1056    this.entry.asid := DontCare
1057    this.entry.vmid.map(_ := vmid)
1058    this.entry.v := !gpf
1059    this.gpf := gpf
1060    this.gaf := gaf
1061  }
1062
1063  def genPPNS2(): UInt = {
1064    MuxLookup(entry.level.get, 0.U, Seq(
1065      0.U -> Cat(entry.ppn(entry.ppn.getWidth - 1, vpnnLen * 2), entry.tag(vpnnLen * 2 - 1, 0)),
1066      1.U -> Cat(entry.ppn(entry.ppn.getWidth - 1, vpnnLen), entry.tag(vpnnLen - 1, 0)),
1067      2.U -> Cat(entry.ppn(entry.ppn.getWidth - 1, 0))
1068    ))
1069  }
1070
1071  def hit(gvpn: UInt, vmid: UInt): Bool = {
1072    val vmid_hit = this.entry.vmid.getOrElse(0.U) === vmid
1073    val hit0 = entry.tag(vpnLen - 1, vpnnLen * 2) === gvpn(vpnLen - 1, vpnnLen * 2)
1074    val hit1 = entry.tag(vpnnLen * 2  - 1, vpnnLen) === gvpn(vpnnLen * 2 - 1, vpnnLen)
1075    val hit2 = entry.tag(vpnnLen - 1, 0) === gvpn(vpnnLen - 1, 0)
1076    vmid_hit && Mux(entry.level.getOrElse(0.U) === 2.U, hit2 && hit1 && hit0, Mux(entry.level.getOrElse(0.U) === 1.U, hit1 && hit0, hit0))
1077  }
1078}
1079
1080class PtwResptomerge (implicit p: Parameters) extends PtwBundle {
1081  val entry = UInt(blockBits.W)
1082  val vpn = UInt(vpnLen.W)
1083  val level = UInt(log2Up(Level).W)
1084  val pf = Bool()
1085  val af = Bool()
1086  val asid = UInt(asidLen.W)
1087
1088  def apply(pf: Bool, af: Bool, level: UInt, pte: UInt, vpn: UInt, asid: UInt) = {
1089    this.entry := pte
1090    this.pf := pf
1091    this.af := af
1092    this.level := level
1093    this.vpn := vpn
1094    this.asid := asid
1095  }
1096
1097  override def toPrintable: Printable = {
1098    p"entry:${entry} pf:${pf} af:${af}"
1099  }
1100}
1101
1102class PtwRespwithMemIdx(implicit p: Parameters) extends PtwResp {
1103  val memidx = new MemBlockidxBundle
1104}
1105
1106class PtwSectorRespwithMemIdx(implicit p: Parameters) extends PtwSectorResp {
1107  val memidx = new MemBlockidxBundle
1108}
1109
1110class PtwSectorResp(implicit p: Parameters) extends PtwBundle {
1111  val entry = new PtwSectorEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true)
1112  val addr_low = UInt(sectortlbwidth.W)
1113  val ppn_low = Vec(tlbcontiguous, UInt(sectortlbwidth.W))
1114  val valididx = Vec(tlbcontiguous, Bool())
1115  val pteidx = Vec(tlbcontiguous, Bool())
1116  val pf = Bool()
1117  val af = Bool()
1118
1119
1120  def genPPN(vpn: UInt): UInt = {
1121    MuxLookup(entry.level.get, 0.U)(Seq(
1122      0.U -> Cat(entry.ppn(entry.ppn.getWidth-1, vpnnLen * 2 - sectortlbwidth), vpn(vpnnLen*2-1, 0)),
1123      1.U -> Cat(entry.ppn(entry.ppn.getWidth-1, vpnnLen - sectortlbwidth), vpn(vpnnLen-1, 0)),
1124      2.U -> Cat(entry.ppn(entry.ppn.getWidth-1, 0), ppn_low(vpn(sectortlbwidth - 1, 0))))
1125    )
1126  }
1127
1128  def hit(vpn: UInt, asid: UInt, vmid: UInt, allType: Boolean = false, ignoreAsid: Boolean = false, s2xlate: Bool): Bool = {
1129    require(vpn.getWidth == vpnLen)
1130    //    require(this.asid.getWidth <= asid.getWidth)
1131    val asid_hit = if (ignoreAsid) true.B else (this.entry.asid === asid)
1132    val vmid_hit = Mux(s2xlate, this.entry.vmid.getOrElse(0.U) === vmid, true.B)
1133    if (allType) {
1134      val hit0 = entry.tag(sectorvpnLen - 1, vpnnLen * 2 - sectortlbwidth) === vpn(vpnLen - 1, vpnnLen * 2)
1135      val hit1 = entry.tag(vpnnLen * 2 - sectortlbwidth - 1, vpnnLen - sectortlbwidth)   === vpn(vpnnLen * 2 - 1,  vpnnLen)
1136      val hit2 = entry.tag(vpnnLen - sectortlbwidth - 1, 0) === vpn(vpnnLen - 1, sectortlbwidth)
1137      val addr_low_hit = valididx(vpn(sectortlbwidth - 1, 0))
1138
1139      asid_hit && vmid_hit && Mux(entry.level.getOrElse(0.U) === 2.U, hit2 && hit1 && hit0, Mux(entry.level.getOrElse(0.U) === 1.U, hit1 && hit0, hit0)) && addr_low_hit
1140    } else {
1141      val hit0 = entry.tag(sectorvpnLen - 1, sectorvpnLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
1142      val hit1 = entry.tag(sectorvpnLen - vpnnLen - 1, sectorvpnLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
1143      val addr_low_hit = valididx(vpn(sectortlbwidth - 1, 0))
1144
1145      asid_hit && vmid_hit && Mux(entry.level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1) && addr_low_hit
1146    }
1147  }
1148}
1149
1150class PtwMergeResp(implicit p: Parameters) extends PtwBundle {
1151  val entry = Vec(tlbcontiguous, new PtwMergeEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true))
1152  val pteidx = Vec(tlbcontiguous, Bool())
1153  val not_super = Bool()
1154
1155  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, asid: UInt, vmid:UInt, addr_low : UInt, not_super : Boolean = true) = {
1156    assert(tlbcontiguous == 8, "Only support tlbcontiguous = 8!")
1157
1158    val ptw_resp = Wire(new PtwMergeEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true))
1159    ptw_resp.ppn := pte.ppn(ppnLen - 1, sectortlbwidth)
1160    ptw_resp.ppn_low := pte.ppn(sectortlbwidth - 1, 0)
1161    ptw_resp.level.map(_ := level)
1162    ptw_resp.perm.map(_ := pte.getPerm())
1163    ptw_resp.tag := vpn(vpnLen - 1, sectortlbwidth)
1164    ptw_resp.pf := pf
1165    ptw_resp.af := af
1166    ptw_resp.v := !pf
1167    ptw_resp.prefetch := DontCare
1168    ptw_resp.asid := asid
1169    ptw_resp.vmid.map(_ := vmid)
1170    this.pteidx := UIntToOH(addr_low).asBools
1171    this.not_super := not_super.B
1172
1173
1174    for (i <- 0 until tlbcontiguous) {
1175      this.entry(i) := ptw_resp
1176    }
1177  }
1178}
1179
1180class HptwMergeResp(implicit p: Parameters) extends PtwBundle {
1181  val entry = Vec(tlbcontiguous, new HptwMergeEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true))
1182  val pteidx = Vec(tlbcontiguous, Bool())
1183  val not_super = Bool()
1184
1185  def genPPN(): UInt = {
1186    val idx = OHToUInt(pteidx)
1187    MuxLookup(entry(idx).level.get, 0.U, Seq(
1188      0.U -> Cat(entry(idx).ppn(entry(idx).ppn.getWidth - 1, vpnnLen * 2 - sectortlbwidth), entry(idx).tag(vpnnLen * 2 - 1, 0)),
1189      1.U -> Cat(entry(idx).ppn(entry(idx).ppn.getWidth - 1, vpnnLen - sectortlbwidth), entry(idx).tag(vpnnLen - 1, 0)),
1190      2.U -> Cat(entry(idx).ppn(entry(idx).ppn.getWidth - 1, 0), entry(idx).ppn_low))
1191    )
1192  }
1193
1194  def isAf(): Bool = {
1195    val idx = OHToUInt(pteidx)
1196    entry(idx).af
1197  }
1198
1199  def isPf(): Bool = {
1200    val idx = OHToUInt(pteidx)
1201    entry(idx).pf
1202  }
1203
1204  def MergeRespToPte(): PteBundle = {
1205    val idx = OHToUInt(pteidx)
1206    val resp = Wire(new PteBundle())
1207    resp.ppn := Cat(entry(idx).ppn, entry(idx).ppn_low)
1208    resp.perm := entry(idx).perm.getOrElse(0.U)
1209    resp
1210  }
1211
1212  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, vmid: UInt, addr_low: UInt, not_super: Boolean = true) = {
1213    assert(tlbcontiguous == 8, "Only support tlbcontiguous = 8!")
1214
1215    val ptw_resp = Wire(new HptwMergeEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true))
1216    ptw_resp.ppn := pte.ppn(ppnLen - 1, sectortlbwidth)
1217    ptw_resp.ppn_low := pte.ppn(sectortlbwidth - 1, 0)
1218    ptw_resp.level.map(_ := level)
1219    ptw_resp.perm.map(_ := pte.getPerm())
1220    ptw_resp.tag := vpn(vpnLen - 1, sectortlbwidth)
1221    ptw_resp.pf := pf
1222    ptw_resp.af := af
1223    ptw_resp.v := !pf
1224    ptw_resp.prefetch := DontCare
1225    ptw_resp.vmid.map(_ := vmid)
1226    this.pteidx := UIntToOH(addr_low).asBools
1227    this.not_super := not_super.B
1228
1229
1230    for (i <- 0 until tlbcontiguous) {
1231      this.entry(i) := ptw_resp
1232    }
1233  }
1234}
1235
1236class PtwRespS2(implicit p: Parameters) extends PtwBundle {
1237  val s2xlate = UInt(2.W)
1238  val s1 = new PtwSectorResp()
1239  val s2 = new HptwResp()
1240  def getVpn: UInt = {
1241    Cat(s1.entry.tag, s1.ppn_low(OHToUInt(s1.pteidx)))
1242  }
1243  def genPPNS2(i: Int):UInt = {
1244    val s1ppn = Cat(this.s1.entry.ppn, this.s1.ppn_low(i), 0.U(12.W)).asUInt
1245    val s2ppn = this.s2.entry.ppn
1246    Mux(s2xlate =/= noS2xlate, s2ppn, s1ppn)
1247  }
1248}
1249
1250class PtwRespS2withMemIdx(implicit p: Parameters) extends PtwRespS2 {
1251  val memidx = new MemBlockidxBundle()
1252}
1253
1254class L2TLBIO(implicit p: Parameters) extends PtwBundle {
1255  val hartId = Input(UInt(hartIdLen.W))
1256  val tlb = Vec(PtwWidth, Flipped(new TlbPtwIO))
1257  val sfence = Input(new SfenceBundle)
1258  val csr = new Bundle {
1259    val tlb = Input(new TlbCsrBundle)
1260    val distribute_csr = Flipped(new DistributedCSRIO)
1261  }
1262}
1263
1264class L2TlbMemReqBundle(implicit p: Parameters) extends PtwBundle {
1265  val addr = UInt(PAddrBits.W)
1266  val id = UInt(bMemID.W)
1267}
1268
1269class L2TlbInnerBundle(implicit p: Parameters) extends PtwReq {
1270  val source = UInt(bSourceWidth.W)
1271}
1272
1273
1274object ValidHoldBypass{
1275  def apply(infire: Bool, outfire: Bool, flush: Bool = false.B) = {
1276    val valid = RegInit(false.B)
1277    when (infire) { valid := true.B }
1278    when (outfire) { valid := false.B } // ATTENTION: order different with ValidHold
1279    when (flush) { valid := false.B } // NOTE: the flush will flush in & out, is that ok?
1280    valid || infire
1281  }
1282}
1283
1284class L1TlbDB(implicit p: Parameters) extends TlbBundle {
1285  val vpn = UInt(vpnLen.W)
1286}
1287
1288class PageCacheDB(implicit p: Parameters) extends TlbBundle with HasPtwConst {
1289  val vpn = UInt(vpnLen.W)
1290  val source = UInt(bSourceWidth.W)
1291  val bypassed = Bool()
1292  val is_first = Bool()
1293  val prefetched = Bool()
1294  val prefetch = Bool()
1295  val l2Hit = Bool()
1296  val l1Hit = Bool()
1297  val hit = Bool()
1298}
1299
1300class PTWDB(implicit p: Parameters) extends TlbBundle with HasPtwConst {
1301  val vpn = UInt(vpnLen.W)
1302  val source = UInt(bSourceWidth.W)
1303}
1304
1305class L2TlbPrefetchDB(implicit p: Parameters) extends TlbBundle {
1306  val vpn = UInt(vpnLen.W)
1307}
1308
1309class L2TlbMissQueueDB(implicit p: Parameters) extends TlbBundle {
1310  val vpn = UInt(vpnLen.W)
1311}
1312