xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/MMUBundle.scala (revision 60ebee385ce85a25a994f6da0c84ecce9bb91bca)
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 chipsalliance.rocketchip.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
36class VaBundle(implicit p: Parameters) extends TlbBundle {
37  val vpn  = UInt(vpnLen.W)
38  val off  = UInt(offLen.W)
39}
40
41class PtePermBundle(implicit p: Parameters) extends TlbBundle {
42  val d = Bool()
43  val a = Bool()
44  val g = Bool()
45  val u = Bool()
46  val x = Bool()
47  val w = Bool()
48  val r = Bool()
49
50  override def toPrintable: Printable = {
51    p"d:${d} a:${a} g:${g} u:${u} x:${x} w:${w} r:${r}"// +
52    //(if(hasV) (p"v:${v}") else p"")
53  }
54}
55
56class TlbPMBundle(implicit p: Parameters) extends TlbBundle {
57  val r = Bool()
58  val w = Bool()
59  val x = Bool()
60  val c = Bool()
61  val atomic = Bool()
62
63  def assign_ap(pm: PMPConfig) = {
64    r := pm.r
65    w := pm.w
66    x := pm.x
67    c := pm.c
68    atomic := pm.atomic
69  }
70}
71
72class TlbPermBundle(implicit p: Parameters) extends TlbBundle {
73  val pf = Bool() // NOTE: if this is true, just raise pf
74  val af = Bool() // NOTE: if this is true, just raise af
75  // pagetable perm (software defined)
76  val d = Bool()
77  val a = Bool()
78  val g = Bool()
79  val u = Bool()
80  val x = Bool()
81  val w = Bool()
82  val r = Bool()
83
84  def apply(item: PtwSectorResp) = {
85    val ptePerm = item.entry.perm.get.asTypeOf(new PtePermBundle().cloneType)
86    this.pf := item.pf
87    this.af := item.af
88    this.d := ptePerm.d
89    this.a := ptePerm.a
90    this.g := ptePerm.g
91    this.u := ptePerm.u
92    this.x := ptePerm.x
93    this.w := ptePerm.w
94    this.r := ptePerm.r
95
96    this
97  }
98  override def toPrintable: Printable = {
99    p"pf:${pf} af:${af} d:${d} a:${a} g:${g} u:${u} x:${x} w:${w} r:${r} "
100  }
101}
102
103class TlbSectorPermBundle(implicit p: Parameters) extends TlbBundle {
104  val pf = Bool() // NOTE: if this is true, just raise pf
105  val af = Bool() // NOTE: if this is true, just raise af
106  // pagetable perm (software defined)
107  val d = Bool()
108  val a = Bool()
109  val g = Bool()
110  val u = Bool()
111  val x = Bool()
112  val w = Bool()
113  val r = Bool()
114
115  def apply(item: PtwSectorResp) = {
116    val ptePerm = item.entry.perm.get.asTypeOf(new PtePermBundle().cloneType)
117    this.pf := item.pf
118    this.af := item.af
119    this.d := ptePerm.d
120    this.a := ptePerm.a
121    this.g := ptePerm.g
122    this.u := ptePerm.u
123    this.x := ptePerm.x
124    this.w := ptePerm.w
125    this.r := ptePerm.r
126
127    this
128  }
129  override def toPrintable: Printable = {
130    p"pf:${pf} af:${af} d:${d} a:${a} g:${g} u:${u} x:${x} w:${w} r:${r} "
131  }
132}
133
134// multi-read && single-write
135// input is data, output is hot-code(not one-hot)
136class CAMTemplate[T <: Data](val gen: T, val set: Int, val readWidth: Int)(implicit p: Parameters) extends TlbModule {
137  val io = IO(new Bundle {
138    val r = new Bundle {
139      val req = Input(Vec(readWidth, gen))
140      val resp = Output(Vec(readWidth, Vec(set, Bool())))
141    }
142    val w = Input(new Bundle {
143      val valid = Bool()
144      val bits = new Bundle {
145        val index = UInt(log2Up(set).W)
146        val data = gen
147      }
148    })
149  })
150
151  val wordType = UInt(gen.getWidth.W)
152  val array = Reg(Vec(set, wordType))
153
154  io.r.resp.zipWithIndex.map{ case (a,i) =>
155    a := array.map(io.r.req(i).asUInt === _)
156  }
157
158  when (io.w.valid) {
159    array(io.w.bits.index) := io.w.bits.data.asUInt
160  }
161}
162
163class TlbEntry(pageNormal: Boolean, pageSuper: Boolean)(implicit p: Parameters) extends TlbBundle {
164  require(pageNormal || pageSuper)
165
166  val tag = if (!pageNormal) UInt((vpnLen - vpnnLen).W)
167  else UInt(vpnLen.W)
168  val asid = UInt(asidLen.W)
169  val level = if (!pageNormal) Some(UInt(1.W))
170  else if (!pageSuper) None
171  else Some(UInt(2.W))
172  val ppn = if (!pageNormal) UInt((ppnLen - vpnnLen).W)
173  else UInt(ppnLen.W)
174  val perm = new TlbPermBundle
175
176  /** level usage:
177    *  !PageSuper: page is only normal, level is None, match all the tag
178    *  !PageNormal: page is only super, level is a Bool(), match high 9*2 parts
179    *  bits0  0: need mid 9bits
180    *         1: no need mid 9bits
181    *  PageSuper && PageNormal: page hold all the three type,
182    *  bits0  0: need low 9bits
183    *  bits1  0: need mid 9bits
184    */
185
186  def hit(vpn: UInt, asid: UInt, nSets: Int = 1, ignoreAsid: Boolean = false): Bool = {
187    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
188
189    // NOTE: for timing, dont care low set index bits at hit check
190    //       do not need store the low bits actually
191    if (!pageSuper) asid_hit && drop_set_equal(vpn, tag, nSets)
192    else if (!pageNormal) {
193      val tag_match_hi = tag(vpnnLen*2-1, vpnnLen) === vpn(vpnnLen*3-1, vpnnLen*2)
194      val tag_match_mi = tag(vpnnLen-1, 0) === vpn(vpnnLen*2-1, vpnnLen)
195      val tag_match = tag_match_hi && (level.get.asBool() || tag_match_mi)
196      asid_hit && tag_match
197    }
198    else {
199      val tmp_level = level.get
200      val tag_match_hi = tag(vpnnLen*3-1, vpnnLen*2) === vpn(vpnnLen*3-1, vpnnLen*2)
201      val tag_match_mi = tag(vpnnLen*2-1, vpnnLen) === vpn(vpnnLen*2-1, vpnnLen)
202      val tag_match_lo = tag(vpnnLen-1, 0) === vpn(vpnnLen-1, 0) // if pageNormal is false, this will always be false
203      val tag_match = tag_match_hi && (tmp_level(1) || tag_match_mi) && (tmp_level(0) || tag_match_lo)
204      asid_hit && tag_match
205    }
206  }
207
208  def apply(item: PtwSectorResp, asid: UInt, pm: PMPConfig): TlbEntry = {
209    this.tag := {if (pageNormal) Cat(item.entry.tag, OHToUInt(item.pteidx)) else item.entry.tag(sectorvpnLen - 1, vpnnLen - sectortlbwidth)}
210    this.asid := asid
211    val inner_level = item.entry.level.getOrElse(0.U)
212    this.level.map(_ := { if (pageNormal && pageSuper) MuxLookup(inner_level, 0.U, Seq(
213      0.U -> 3.U,
214      1.U -> 1.U,
215      2.U -> 0.U ))
216    else if (pageSuper) ~inner_level(0)
217    else 0.U })
218    this.ppn := { if (!pageNormal) item.entry.ppn(sectorppnLen - 1, vpnnLen - sectortlbwidth)
219                  else Cat(item.entry.ppn, item.ppn_low(OHToUInt(item.pteidx))) }
220    this.perm.apply(item)
221    this
222  }
223
224  // 4KB is normal entry, 2MB/1GB is considered as super entry
225  def is_normalentry(): Bool = {
226    if (!pageSuper) { true.B }
227    else if (!pageNormal) { false.B }
228    else { level.get === 0.U }
229  }
230
231  def genPPN(saveLevel: Boolean = false, valid: Bool = false.B)(vpn: UInt) : UInt = {
232    val inner_level = level.getOrElse(0.U)
233    val ppn_res = if (!pageSuper) ppn
234    else if (!pageNormal) Cat(ppn(ppnLen-vpnnLen-1, vpnnLen),
235      Mux(inner_level(0), vpn(vpnnLen*2-1, vpnnLen), ppn(vpnnLen-1,0)),
236      vpn(vpnnLen-1, 0))
237    else Cat(ppn(ppnLen-1, vpnnLen*2),
238      Mux(inner_level(1), vpn(vpnnLen*2-1, vpnnLen), ppn(vpnnLen*2-1, vpnnLen)),
239      Mux(inner_level(0), vpn(vpnnLen-1, 0), ppn(vpnnLen-1, 0)))
240
241    if (saveLevel) Cat(ppn(ppn.getWidth-1, vpnnLen*2), RegEnable(ppn_res(vpnnLen*2-1, 0), valid))
242    else ppn_res
243  }
244
245  override def toPrintable: Printable = {
246    val inner_level = level.getOrElse(2.U)
247    p"asid: ${asid} level:${inner_level} vpn:${Hexadecimal(tag)} ppn:${Hexadecimal(ppn)} perm:${perm}"
248  }
249
250}
251
252class TlbSectorEntry(pageNormal: Boolean, pageSuper: Boolean)(implicit p: Parameters) extends TlbBundle {
253  require(pageNormal || pageSuper)
254
255  val tag = if (!pageNormal) UInt((vpnLen - vpnnLen).W)
256            else UInt(sectorvpnLen.W)
257  val asid = UInt(asidLen.W)
258  val level = if (!pageNormal) Some(UInt(1.W))
259              else if (!pageSuper) None
260              else Some(UInt(2.W))
261  val ppn = if (!pageNormal) UInt((ppnLen - vpnnLen).W)
262            else UInt(sectorppnLen.W)
263  val perm = new TlbSectorPermBundle
264  val valididx = Vec(tlbcontiguous, Bool())
265  val pteidx = Vec(tlbcontiguous, Bool())
266  val ppn_low = Vec(tlbcontiguous, UInt(sectortlbwidth.W))
267
268  /** level usage:
269   *  !PageSuper: page is only normal, level is None, match all the tag
270   *  !PageNormal: page is only super, level is a Bool(), match high 9*2 parts
271   *  bits0  0: need mid 9bits
272   *         1: no need mid 9bits
273   *  PageSuper && PageNormal: page hold all the three type,
274   *  bits0  0: need low 9bits
275   *  bits1  0: need mid 9bits
276   */
277
278  def hit(vpn: UInt, asid: UInt, nSets: Int = 1, ignoreAsid: Boolean = false): Bool = {
279    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
280    val addr_low_hit = valididx(vpn(2, 0))
281
282    // NOTE: for timing, dont care low set index bits at hit check
283    //       do not need store the low bits actually
284    if (!pageSuper) asid_hit && drop_set_equal(vpn(vpn.getWidth - 1, sectortlbwidth), tag, nSets) && addr_low_hit
285    else if (!pageNormal) {
286      val tag_match_hi = tag(vpnnLen * 2 - 1, vpnnLen) === vpn(vpnnLen * 3 - 1, vpnnLen * 2)
287      val tag_match_mi = tag(vpnnLen - 1, 0) === vpn(vpnnLen * 2 - 1, vpnnLen)
288      val tag_match = tag_match_hi && (level.get.asBool() || tag_match_mi)
289      asid_hit && tag_match && addr_low_hit
290    }
291    else {
292      val tmp_level = level.get
293      val tag_match_hi = tag(vpnnLen * 3 - sectortlbwidth - 1, vpnnLen * 2 - sectortlbwidth) === vpn(vpnnLen * 3 - 1, vpnnLen * 2)
294      val tag_match_mi = tag(vpnnLen * 2 - sectortlbwidth - 1, vpnnLen - sectortlbwidth) === vpn(vpnnLen * 2 - 1, vpnnLen)
295      val tag_match_lo = tag(vpnnLen - sectortlbwidth - 1, 0) === vpn(vpnnLen - 1, sectortlbwidth) // if pageNormal is false, this will always be false
296      val tag_match = tag_match_hi && (tmp_level(1) || tag_match_mi) && (tmp_level(0) || tag_match_lo)
297      asid_hit && tag_match && addr_low_hit
298    }
299  }
300
301  def wbhit(data: PtwSectorResp, asid: UInt, nSets: Int = 1, ignoreAsid: Boolean = false): Bool = {
302    val vpn = Cat(data.entry.tag, 0.U(sectortlbwidth.W))
303    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
304    val vpn_hit = Wire(Bool())
305    val index_hit = Wire(Vec(tlbcontiguous, Bool()))
306
307    // NOTE: for timing, dont care low set index bits at hit check
308    //       do not need store the low bits actually
309    if (!pageSuper) {
310      vpn_hit := asid_hit && drop_set_equal(vpn(vpn.getWidth - 1, sectortlbwidth), tag, nSets)
311    }
312    else if (!pageNormal) {
313      val tag_match_hi = tag(vpnnLen * 2 - 1, vpnnLen - sectortlbwidth) === vpn(vpnnLen * 3 - 1, vpnnLen * 2)
314      val tag_match_mi = tag(vpnnLen - 1, 0) === vpn(vpnnLen * 2 - 1, vpnnLen)
315      val tag_match = tag_match_hi && (level.get.asBool() || tag_match_mi)
316      vpn_hit := asid_hit && tag_match
317    }
318    else {
319      val tmp_level = level.get
320      val tag_match_hi = tag(vpnnLen * 3 - sectortlbwidth - 1, vpnnLen * 2 - sectortlbwidth) === vpn(vpnnLen * 3 - 1, vpnnLen * 2)
321      val tag_match_mi = tag(vpnnLen * 2 - sectortlbwidth - 1, vpnnLen - sectortlbwidth) === vpn(vpnnLen * 2 - 1, vpnnLen)
322      val tag_match_lo = tag(vpnnLen - sectortlbwidth - 1, 0) === vpn(vpnnLen - 1, sectortlbwidth) // if pageNormal is false, this will always be false
323      val tag_match = tag_match_hi && (tmp_level(1) || tag_match_mi) && (tmp_level(0) || tag_match_lo)
324      vpn_hit := asid_hit && tag_match
325    }
326
327    for (i <- 0 until tlbcontiguous) {
328      index_hit(i) := data.valididx(i) && valididx(i)
329    }
330
331    // For example, tlb req to page cache with vpn 0x10
332    // At this time, 0x13 has not been paged, so page cache only resp 0x10
333    // When 0x13 refill to page cache, previous item will be flushed
334    // Now 0x10 and 0x13 are both valid in page cache
335    // However, when 0x13 refill to tlb, will trigger multi hit
336    // So will only trigger multi-hit when PopCount(data.valididx) = 1
337    vpn_hit && index_hit.reduce(_ || _) && PopCount(data.valididx) === 1.U
338  }
339
340  def apply(item: PtwSectorResp, asid: UInt): TlbSectorEntry = {
341    this.tag := {if (pageNormal) item.entry.tag else item.entry.tag(sectorvpnLen - 1, vpnnLen - sectortlbwidth)}
342    this.asid := asid
343    val inner_level = item.entry.level.getOrElse(0.U)
344    this.level.map(_ := { if (pageNormal && pageSuper) MuxLookup(inner_level, 0.U, Seq(
345                                                        0.U -> 3.U,
346                                                        1.U -> 1.U,
347                                                        2.U -> 0.U ))
348                          else if (pageSuper) ~inner_level(0)
349                          else 0.U })
350    this.ppn := { if (!pageNormal) item.entry.ppn(sectorppnLen - 1, vpnnLen - sectortlbwidth)
351                  else item.entry.ppn }
352    this.perm.apply(item)
353    this.ppn_low := item.ppn_low
354    this.valididx := item.valididx
355    this.pteidx := item.pteidx
356    this
357  }
358
359  // 4KB is normal entry, 2MB/1GB is considered as super entry
360  def is_normalentry(): Bool = {
361    if (!pageSuper) { true.B }
362    else if (!pageNormal) { false.B }
363    else { level.get === 0.U }
364  }
365
366  def genPPN(saveLevel: Boolean = false, valid: Bool = false.B)(vpn: UInt) : UInt = {
367    val inner_level = level.getOrElse(0.U)
368    val ppn_res = if (!pageSuper) Cat(ppn, ppn_low(vpn(sectortlbwidth - 1, 0)))
369      else if (!pageNormal) Cat(ppn(ppnLen - vpnnLen - 1, vpnnLen),
370        Mux(inner_level(0), vpn(vpnnLen * 2 - 1, vpnnLen), ppn(vpnnLen - 1,0)),
371        vpn(vpnnLen - 1, 0))
372      else Cat(ppn(sectorppnLen - 1, vpnnLen * 2 - sectortlbwidth),
373        Mux(inner_level(1), vpn(vpnnLen * 2 - 1, vpnnLen), ppn(vpnnLen * 2 - sectortlbwidth - 1, vpnnLen - sectortlbwidth)),
374        Mux(inner_level(0), vpn(vpnnLen - 1, 0), Cat(ppn(vpnnLen - sectortlbwidth - 1, 0), ppn_low(vpn(sectortlbwidth - 1, 0)))))
375
376    if (saveLevel) {
377      if (ppn.getWidth == ppnLen - vpnnLen) {
378        Cat(ppn(ppn.getWidth - 1, vpnnLen * 2), RegEnable(ppn_res(vpnnLen * 2 - 1, 0), valid))
379      } else {
380        require(ppn.getWidth == sectorppnLen)
381        Cat(ppn(ppn.getWidth - 1, vpnnLen * 2 - sectortlbwidth), RegEnable(ppn_res(vpnnLen * 2 - 1, 0), valid))
382      }
383    }
384    else ppn_res
385  }
386
387  override def toPrintable: Printable = {
388    val inner_level = level.getOrElse(2.U)
389    p"asid: ${asid} level:${inner_level} vpn:${Hexadecimal(tag)} ppn:${Hexadecimal(ppn)} perm:${perm}"
390  }
391
392}
393
394object TlbCmd {
395  def read  = "b00".U
396  def write = "b01".U
397  def exec  = "b10".U
398
399  def atom_read  = "b100".U // lr
400  def atom_write = "b101".U // sc / amo
401
402  def apply() = UInt(3.W)
403  def isRead(a: UInt) = a(1,0)===read
404  def isWrite(a: UInt) = a(1,0)===write
405  def isExec(a: UInt) = a(1,0)===exec
406
407  def isAtom(a: UInt) = a(2)
408  def isAmo(a: UInt) = a===atom_write // NOTE: sc mixed
409}
410
411class TlbStorageIO(nSets: Int, nWays: Int, ports: Int, nDups: Int = 1)(implicit p: Parameters) extends MMUIOBaseBundle {
412  val r = new Bundle {
413    val req = Vec(ports, Flipped(DecoupledIO(new Bundle {
414      val vpn = Output(UInt(vpnLen.W))
415    })))
416    val resp = Vec(ports, ValidIO(new Bundle{
417      val hit = Output(Bool())
418      val ppn = Vec(nDups, Output(UInt(ppnLen.W)))
419      val perm = Vec(nDups, Output(new TlbSectorPermBundle()))
420    }))
421  }
422  val w = Flipped(ValidIO(new Bundle {
423    val wayIdx = Output(UInt(log2Up(nWays).W))
424    val data = Output(new PtwSectorResp)
425  }))
426  val access = Vec(ports, new ReplaceAccessBundle(nSets, nWays))
427
428  def r_req_apply(valid: Bool, vpn: UInt, i: Int): Unit = {
429    this.r.req(i).valid := valid
430    this.r.req(i).bits.vpn := vpn
431  }
432
433  def r_resp_apply(i: Int) = {
434    (this.r.resp(i).bits.hit, this.r.resp(i).bits.ppn, this.r.resp(i).bits.perm)
435  }
436
437  def w_apply(valid: Bool, wayIdx: UInt, data: PtwSectorResp): Unit = {
438    this.w.valid := valid
439    this.w.bits.wayIdx := wayIdx
440    this.w.bits.data := data
441  }
442
443}
444
445class TlbStorageWrapperIO(ports: Int, q: TLBParameters, nDups: Int = 1)(implicit p: Parameters) extends MMUIOBaseBundle {
446  val r = new Bundle {
447    val req = Vec(ports, Flipped(DecoupledIO(new Bundle {
448      val vpn = Output(UInt(vpnLen.W))
449    })))
450    val resp = Vec(ports, ValidIO(new Bundle{
451      val hit = Output(Bool())
452      val ppn = Vec(nDups, Output(UInt(ppnLen.W)))
453      val perm = Vec(nDups, Output(new TlbPermBundle()))
454    }))
455  }
456  val w = Flipped(ValidIO(new Bundle {
457    val data = Output(new PtwSectorResp)
458  }))
459  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(ports, q)) else null
460
461  def r_req_apply(valid: Bool, vpn: UInt, i: Int): Unit = {
462    this.r.req(i).valid := valid
463    this.r.req(i).bits.vpn := vpn
464  }
465
466  def r_resp_apply(i: Int) = {
467    (this.r.resp(i).bits.hit, this.r.resp(i).bits.ppn, this.r.resp(i).bits.perm)
468  }
469
470  def w_apply(valid: Bool, data: PtwSectorResp): Unit = {
471    this.w.valid := valid
472    this.w.bits.data := data
473  }
474}
475
476class ReplaceAccessBundle(nSets: Int, nWays: Int)(implicit p: Parameters) extends TlbBundle {
477  val sets = Output(UInt(log2Up(nSets).W))
478  val touch_ways = ValidIO(Output(UInt(log2Up(nWays).W)))
479}
480
481class ReplaceIO(Width: Int, nSets: Int, nWays: Int)(implicit p: Parameters) extends TlbBundle {
482  val access = Vec(Width, Flipped(new ReplaceAccessBundle(nSets, nWays)))
483
484  val refillIdx = Output(UInt(log2Up(nWays).W))
485  val chosen_set = Flipped(Output(UInt(log2Up(nSets).W)))
486
487  def apply_sep(in: Seq[ReplaceIO], vpn: UInt): Unit = {
488    for ((ac_rep, ac_tlb) <- access.zip(in.map(a => a.access.map(b => b)).flatten)) {
489      ac_rep := ac_tlb
490    }
491    this.chosen_set := get_set_idx(vpn, nSets)
492    in.map(a => a.refillIdx := this.refillIdx)
493  }
494}
495
496class TlbReplaceIO(Width: Int, q: TLBParameters)(implicit p: Parameters) extends
497  TlbBundle {
498  val page = new ReplaceIO(Width, q.NSets, q.NWays)
499
500  def apply_sep(in: Seq[TlbReplaceIO], vpn: UInt) = {
501    this.page.apply_sep(in.map(_.page), vpn)
502  }
503
504}
505
506class MemBlockidxBundle(implicit p: Parameters) extends TlbBundle {
507  val is_ld = Bool()
508  val is_st = Bool()
509  val idx =
510    if (VirtualLoadQueueSize >= StoreQueueSize) {
511      val idx = UInt(log2Ceil(VirtualLoadQueueSize).W)
512      idx
513    } else {
514      val idx = UInt(log2Ceil(StoreQueueSize).W)
515      idx
516    }
517}
518
519class TlbReq(implicit p: Parameters) extends TlbBundle {
520  val vaddr = Output(UInt(VAddrBits.W))
521  val cmd = Output(TlbCmd())
522  val size = Output(UInt(log2Ceil(log2Ceil(XLEN/8)+1).W))
523  val kill = Output(Bool()) // Use for blocked tlb that need sync with other module like icache
524  val memidx = Output(new MemBlockidxBundle)
525  // do not translate, but still do pmp/pma check
526  val no_translate = Output(Bool())
527  val debug = new Bundle {
528    val pc = Output(UInt(XLEN.W))
529    val robIdx = Output(new RobPtr)
530    val isFirstIssue = Output(Bool())
531  }
532
533  // Maybe Block req needs a kill: for itlb, itlb and icache may not sync, itlb should wait icache to go ahead
534  override def toPrintable: Printable = {
535    p"vaddr:0x${Hexadecimal(vaddr)} cmd:${cmd} kill:${kill} pc:0x${Hexadecimal(debug.pc)} robIdx:${debug.robIdx}"
536  }
537}
538
539class TlbExceptionBundle(implicit p: Parameters) extends TlbBundle {
540  val ld = Output(Bool())
541  val st = Output(Bool())
542  val instr = Output(Bool())
543}
544
545class TlbResp(nDups: Int = 1)(implicit p: Parameters) extends TlbBundle {
546  val paddr = Vec(nDups, Output(UInt(PAddrBits.W)))
547  val miss = Output(Bool())
548  val excp = Vec(nDups, new Bundle {
549    val pf = new TlbExceptionBundle()
550    val af = new TlbExceptionBundle()
551  })
552  val ptwBack = Output(Bool()) // when ptw back, wake up replay rs's state
553  val memidx = Output(new MemBlockidxBundle)
554
555  val debug = new Bundle {
556    val robIdx = Output(new RobPtr)
557    val isFirstIssue = Output(Bool())
558  }
559  override def toPrintable: Printable = {
560    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}"
561  }
562}
563
564class TlbRequestIO(nRespDups: Int = 1)(implicit p: Parameters) extends TlbBundle {
565  val req = DecoupledIO(new TlbReq)
566  val req_kill = Output(Bool())
567  val resp = Flipped(DecoupledIO(new TlbResp(nRespDups)))
568}
569
570class TlbPtwIO(Width: Int = 1)(implicit p: Parameters) extends TlbBundle {
571  val req = Vec(Width, DecoupledIO(new PtwReq))
572  val resp = Flipped(DecoupledIO(new PtwSectorResp))
573
574
575  override def toPrintable: Printable = {
576    p"req(0):${req(0).valid} ${req(0).ready} ${req(0).bits} | resp:${resp.valid} ${resp.ready} ${resp.bits}"
577  }
578}
579
580class TlbPtwIOwithMemIdx(Width: Int = 1)(implicit p: Parameters) extends TlbBundle {
581  val req = Vec(Width, DecoupledIO(new PtwReqwithMemIdx))
582  val resp = Flipped(DecoupledIO(new PtwSectorRespwithMemIdx))
583
584
585  override def toPrintable: Printable = {
586    p"req(0):${req(0).valid} ${req(0).ready} ${req(0).bits} | resp:${resp.valid} ${resp.ready} ${resp.bits}"
587  }
588}
589
590class MMUIOBaseBundle(implicit p: Parameters) extends TlbBundle {
591  val sfence = Input(new SfenceBundle)
592  val csr = Input(new TlbCsrBundle)
593
594  def base_connect(sfence: SfenceBundle, csr: TlbCsrBundle): Unit = {
595    this.sfence <> sfence
596    this.csr <> csr
597  }
598
599  // overwrite satp. write satp will cause flushpipe but csr.priv won't
600  // satp will be dealyed several cycles from writing, but csr.priv won't
601  // so inside mmu, these two signals should be divided
602  def base_connect(sfence: SfenceBundle, csr: TlbCsrBundle, satp: TlbSatpBundle) = {
603    this.sfence <> sfence
604    this.csr <> csr
605    this.csr.satp := satp
606  }
607}
608
609class TlbRefilltoMemIO()(implicit p: Parameters) extends TlbBundle {
610  val valid = Bool()
611  val memidx = new MemBlockidxBundle
612}
613
614class TlbIO(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends
615  MMUIOBaseBundle {
616  val requestor = Vec(Width, Flipped(new TlbRequestIO(nRespDups)))
617  val flushPipe = Vec(Width, Input(Bool()))
618  val ptw = new TlbPtwIOwithMemIdx(Width)
619  val refill_to_mem = Output(new TlbRefilltoMemIO())
620  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(Width, q)) else null
621  val pmp = Vec(Width, ValidIO(new PMPReqBundle()))
622
623}
624
625class VectorTlbPtwIO(Width: Int)(implicit p: Parameters) extends TlbBundle {
626  val req = Vec(Width, DecoupledIO(new PtwReqwithMemIdx()))
627  val resp = Flipped(DecoupledIO(new Bundle {
628    val data = new PtwSectorRespwithMemIdx
629    val vector = Output(Vec(Width, Bool()))
630  }))
631
632  def connect(normal: TlbPtwIOwithMemIdx): Unit = {
633    req <> normal.req
634    resp.ready := normal.resp.ready
635    normal.resp.bits := resp.bits.data
636    normal.resp.valid := resp.valid
637  }
638}
639
640/****************************  L2TLB  *************************************/
641abstract class PtwBundle(implicit p: Parameters) extends XSBundle with HasPtwConst
642abstract class PtwModule(outer: L2TLB) extends LazyModuleImp(outer)
643  with HasXSParameter with HasPtwConst
644
645class PteBundle(implicit p: Parameters) extends PtwBundle{
646  val reserved  = UInt(pteResLen.W)
647  val ppn_high = UInt(ppnHignLen.W)
648  val ppn  = UInt(ppnLen.W)
649  val rsw  = UInt(2.W)
650  val perm = new Bundle {
651    val d    = Bool()
652    val a    = Bool()
653    val g    = Bool()
654    val u    = Bool()
655    val x    = Bool()
656    val w    = Bool()
657    val r    = Bool()
658    val v    = Bool()
659  }
660
661  def unaligned(level: UInt) = {
662    isLeaf() && !(level === 2.U ||
663                  level === 1.U && ppn(vpnnLen-1,   0) === 0.U ||
664                  level === 0.U && ppn(vpnnLen*2-1, 0) === 0.U)
665  }
666
667  def isPf(level: UInt) = {
668    !perm.v || (!perm.r && perm.w) || unaligned(level)
669  }
670
671  // paddr of Xiangshan is 36 bits but ppn of sv39 is 44 bits
672  // access fault will be raised when ppn >> ppnLen is not zero
673  def isAf() = {
674    !(ppn_high === 0.U)
675  }
676
677  def isLeaf() = {
678    perm.r || perm.x || perm.w
679  }
680
681  def getPerm() = {
682    val pm = Wire(new PtePermBundle)
683    pm.d := perm.d
684    pm.a := perm.a
685    pm.g := perm.g
686    pm.u := perm.u
687    pm.x := perm.x
688    pm.w := perm.w
689    pm.r := perm.r
690    pm
691  }
692
693  override def toPrintable: Printable = {
694    p"ppn:0x${Hexadecimal(ppn)} perm:b${Binary(perm.asUInt)}"
695  }
696}
697
698class PtwEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwBundle {
699  val tag = UInt(tagLen.W)
700  val asid = UInt(asidLen.W)
701  val ppn = UInt(ppnLen.W)
702  val perm = if (hasPerm) Some(new PtePermBundle) else None
703  val level = if (hasLevel) Some(UInt(log2Up(Level).W)) else None
704  val prefetch = Bool()
705  val v = Bool()
706
707  def is_normalentry(): Bool = {
708    if (!hasLevel) true.B
709    else level.get === 2.U
710  }
711
712  def genPPN(vpn: UInt): UInt = {
713    if (!hasLevel) ppn
714    else MuxLookup(level.get, 0.U, Seq(
715          0.U -> Cat(ppn(ppn.getWidth-1, vpnnLen*2), vpn(vpnnLen*2-1, 0)),
716          1.U -> Cat(ppn(ppn.getWidth-1, vpnnLen), vpn(vpnnLen-1, 0)),
717          2.U -> ppn)
718    )
719  }
720
721  def hit(vpn: UInt, asid: UInt, allType: Boolean = false, ignoreAsid: Boolean = false) = {
722    require(vpn.getWidth == vpnLen)
723//    require(this.asid.getWidth <= asid.getWidth)
724    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
725    if (allType) {
726      require(hasLevel)
727      val hit0 = tag(tagLen - 1,    vpnnLen*2) === vpn(tagLen - 1, vpnnLen*2)
728      val hit1 = tag(vpnnLen*2 - 1, vpnnLen)   === vpn(vpnnLen*2 - 1,  vpnnLen)
729      val hit2 = tag(vpnnLen - 1,     0)         === vpn(vpnnLen - 1, 0)
730
731      asid_hit && Mux(level.getOrElse(0.U) === 2.U, hit2 && hit1 && hit0, Mux(level.getOrElse(0.U) === 1.U, hit1 && hit0, hit0))
732    } else if (hasLevel) {
733      val hit0 = tag(tagLen - 1, tagLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
734      val hit1 = tag(tagLen - vpnnLen - 1, tagLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
735
736      asid_hit && Mux(level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1)
737    } else {
738      asid_hit && tag === vpn(vpnLen - 1, vpnLen - tagLen)
739    }
740  }
741
742  def refill(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool, valid: Bool = false.B) {
743    require(this.asid.getWidth <= asid.getWidth) // maybe equal is better, but ugly outside
744
745    tag := vpn(vpnLen - 1, vpnLen - tagLen)
746    ppn := pte.asTypeOf(new PteBundle().cloneType).ppn
747    perm.map(_ := pte.asTypeOf(new PteBundle().cloneType).perm)
748    this.asid := asid
749    this.prefetch := prefetch
750    this.v := valid
751    this.level.map(_ := level)
752  }
753
754  def genPtwEntry(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool, valid: Bool = false.B) = {
755    val e = Wire(new PtwEntry(tagLen, hasPerm, hasLevel))
756    e.refill(vpn, asid, pte, level, prefetch, valid)
757    e
758  }
759
760
761
762  override def toPrintable: Printable = {
763    // p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} perm:${perm}"
764    p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} " +
765      (if (hasPerm) p"perm:${perm.getOrElse(0.U.asTypeOf(new PtePermBundle))} " else p"") +
766      (if (hasLevel) p"level:${level.getOrElse(0.U)}" else p"") +
767      p"prefetch:${prefetch}"
768  }
769}
770
771class PtwSectorEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwEntry(tagLen, hasPerm, hasLevel) {
772  override val ppn = UInt(sectorppnLen.W)
773}
774
775class PtwMergeEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwSectorEntry(tagLen, hasPerm, hasLevel) {
776  val ppn_low = UInt(sectortlbwidth.W)
777  val af = Bool()
778  val pf = Bool()
779}
780
781class PtwEntries(num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
782  require(log2Up(num)==log2Down(num))
783  // NOTE: hasPerm means that is leaf or not.
784
785  val tag  = UInt(tagLen.W)
786  val asid = UInt(asidLen.W)
787  val ppns = Vec(num, UInt(ppnLen.W))
788  val vs   = Vec(num, Bool())
789  val perms = if (hasPerm) Some(Vec(num, new PtePermBundle)) else None
790  val prefetch = Bool()
791  // println(s"PtwEntries: tag:1*${tagLen} ppns:${num}*${ppnLen} vs:${num}*1")
792  // NOTE: vs is used for different usage:
793  // for l3, which store the leaf(leaves), vs is page fault or not.
794  // for l2, which shoule not store leaf, vs is valid or not, that will anticipate in hit check
795  // Because, l2 should not store leaf(no perm), it doesn't store perm.
796  // If l2 hit a leaf, the perm is still unavailble. Should still page walk. Complex but nothing helpful.
797  // TODO: divide vs into validVec and pfVec
798  // for l2: may valid but pf, so no need for page walk, return random pte with pf.
799
800  def tagClip(vpn: UInt) = {
801    require(vpn.getWidth == vpnLen)
802    vpn(vpnLen - 1, vpnLen - tagLen)
803  }
804
805  def sectorIdxClip(vpn: UInt, level: Int) = {
806    getVpnClip(vpn, level)(log2Up(num) - 1, 0)
807  }
808
809  def hit(vpn: UInt, asid: UInt, ignoreAsid: Boolean = false) = {
810    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
811    asid_hit && tag === tagClip(vpn) && (if (hasPerm) true.B else vs(sectorIdxClip(vpn, level)))
812  }
813
814  def genEntries(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
815    require((data.getWidth / XLEN) == num,
816      s"input data length must be multiple of pte length: data.length:${data.getWidth} num:${num}")
817
818    val ps = Wire(new PtwEntries(num, tagLen, level, hasPerm))
819    ps.tag := tagClip(vpn)
820    ps.asid := asid
821    ps.prefetch := prefetch
822    for (i <- 0 until num) {
823      val pte = data((i+1)*XLEN-1, i*XLEN).asTypeOf(new PteBundle)
824      ps.ppns(i) := pte.ppn
825      ps.vs(i)   := !pte.isPf(levelUInt) && (if (hasPerm) pte.isLeaf() else !pte.isLeaf())
826      ps.perms.map(_(i) := pte.perm)
827    }
828    ps
829  }
830
831  override def toPrintable: Printable = {
832    // require(num == 4, "if num is not 4, please comment this toPrintable")
833    // NOTE: if num is not 4, please comment this toPrintable
834    val permsInner = perms.getOrElse(0.U.asTypeOf(Vec(num, new PtePermBundle)))
835    p"asid: ${Hexadecimal(asid)} tag:0x${Hexadecimal(tag)} ppns:${printVec(ppns)} vs:${Binary(vs.asUInt)} " +
836      (if (hasPerm) p"perms:${printVec(permsInner)}" else p"")
837  }
838}
839
840class PTWEntriesWithEcc(eccCode: Code, num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
841  val entries = new PtwEntries(num, tagLen, level, hasPerm)
842
843  val ecc_block = XLEN
844  val ecc_info = get_ecc_info()
845  val ecc = UInt(ecc_info._1.W)
846
847  def get_ecc_info(): (Int, Int, Int, Int) = {
848    val eccBits_per = eccCode.width(ecc_block) - ecc_block
849
850    val data_length = entries.getWidth
851    val data_align_num = data_length / ecc_block
852    val data_not_align = (data_length % ecc_block) != 0 // ugly code
853    val data_unalign_length = data_length - data_align_num * ecc_block
854    val eccBits_unalign = eccCode.width(data_unalign_length) - data_unalign_length
855
856    val eccBits = eccBits_per * data_align_num + eccBits_unalign
857    (eccBits, eccBits_per, data_align_num, data_unalign_length)
858  }
859
860  def encode() = {
861    val data = entries.asUInt()
862    val ecc_slices = Wire(Vec(ecc_info._3, UInt(ecc_info._2.W)))
863    for (i <- 0 until ecc_info._3) {
864      ecc_slices(i) := eccCode.encode(data((i+1)*ecc_block-1, i*ecc_block)) >> ecc_block
865    }
866    if (ecc_info._4 != 0) {
867      val ecc_unaligned = eccCode.encode(data(data.getWidth-1, ecc_info._3*ecc_block)) >> ecc_info._4
868      ecc := Cat(ecc_unaligned, ecc_slices.asUInt())
869    } else { ecc := ecc_slices.asUInt() }
870  }
871
872  def decode(): Bool = {
873    val data = entries.asUInt()
874    val res = Wire(Vec(ecc_info._3 + 1, Bool()))
875    for (i <- 0 until ecc_info._3) {
876      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}
877    }
878    if (ecc_info._2 != 0 && ecc_info._4 != 0) {
879      res(ecc_info._3) := eccCode.decode(
880        Cat(ecc(ecc_info._1-1, ecc_info._2*ecc_info._3), data(data.getWidth-1, ecc_info._3*ecc_block))).error
881    } else { res(ecc_info._3) := false.B }
882
883    Cat(res).orR
884  }
885
886  def gen(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
887    this.entries := entries.genEntries(vpn, asid, data, levelUInt, prefetch)
888    this.encode()
889  }
890}
891
892class PtwReq(implicit p: Parameters) extends PtwBundle {
893  val vpn = UInt(vpnLen.W)
894
895  override def toPrintable: Printable = {
896    p"vpn:0x${Hexadecimal(vpn)}"
897  }
898}
899
900class PtwReqwithMemIdx(implicit p: Parameters) extends PtwReq {
901  val memidx = new MemBlockidxBundle
902}
903
904class PtwResp(implicit p: Parameters) extends PtwBundle {
905  val entry = new PtwEntry(tagLen = vpnLen, hasPerm = true, hasLevel = true)
906  val pf = Bool()
907  val af = Bool()
908
909  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, asid: UInt) = {
910    this.entry.level.map(_ := level)
911    this.entry.tag := vpn
912    this.entry.perm.map(_ := pte.getPerm())
913    this.entry.ppn := pte.ppn
914    this.entry.prefetch := DontCare
915    this.entry.asid := asid
916    this.entry.v := !pf
917    this.pf := pf
918    this.af := af
919  }
920
921  override def toPrintable: Printable = {
922    p"entry:${entry} pf:${pf} af:${af}"
923  }
924}
925
926class PtwResptomerge (implicit p: Parameters) extends PtwBundle {
927  val entry = UInt(blockBits.W)
928  val vpn = UInt(vpnLen.W)
929  val level = UInt(log2Up(Level).W)
930  val pf = Bool()
931  val af = Bool()
932  val asid = UInt(asidLen.W)
933
934  def apply(pf: Bool, af: Bool, level: UInt, pte: UInt, vpn: UInt, asid: UInt) = {
935    this.entry := pte
936    this.pf := pf
937    this.af := af
938    this.level := level
939    this.vpn := vpn
940    this.asid := asid
941  }
942
943  override def toPrintable: Printable = {
944    p"entry:${entry} pf:${pf} af:${af}"
945  }
946}
947
948class PtwRespwithMemIdx(implicit p: Parameters) extends PtwResp {
949  val memidx = new MemBlockidxBundle
950}
951
952class PtwSectorRespwithMemIdx(implicit p: Parameters) extends PtwSectorResp {
953  val memidx = new MemBlockidxBundle
954}
955
956class PtwSectorResp(implicit p: Parameters) extends PtwBundle {
957  val entry = new PtwSectorEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true)
958  val addr_low = UInt(sectortlbwidth.W)
959  val ppn_low = Vec(tlbcontiguous, UInt(sectortlbwidth.W))
960  val valididx = Vec(tlbcontiguous, Bool())
961  val pteidx = Vec(tlbcontiguous, Bool())
962  val pf = Bool()
963  val af = Bool()
964
965  def genPPN(vpn: UInt): UInt = {
966    MuxLookup(entry.level.get, 0.U, Seq(
967      0.U -> Cat(entry.ppn(entry.ppn.getWidth-1, vpnnLen * 2 - sectortlbwidth), vpn(vpnnLen*2-1, 0)),
968      1.U -> Cat(entry.ppn(entry.ppn.getWidth-1, vpnnLen - sectortlbwidth), vpn(vpnnLen-1, 0)),
969      2.U -> Cat(entry.ppn(entry.ppn.getWidth-1, 0), ppn_low(vpn(sectortlbwidth - 1, 0))))
970    )
971  }
972
973  def hit(vpn: UInt, asid: UInt, allType: Boolean = false, ignoreAsid: Boolean = false) = {
974    require(vpn.getWidth == vpnLen)
975    //    require(this.asid.getWidth <= asid.getWidth)
976    val asid_hit = if (ignoreAsid) true.B else (this.entry.asid === asid)
977    if (allType) {
978      val hit0 = entry.tag(sectorvpnLen - 1, vpnnLen * 2 - sectortlbwidth) === vpn(vpnLen - 1, vpnnLen * 2)
979      val hit1 = entry.tag(vpnnLen * 2 - sectortlbwidth - 1, vpnnLen - sectortlbwidth)   === vpn(vpnnLen * 2 - 1,  vpnnLen)
980      val hit2 = entry.tag(vpnnLen - sectortlbwidth - 1, 0) === vpn(vpnnLen - 1, sectortlbwidth)
981      val addr_low_hit = valididx(vpn(sectortlbwidth - 1, 0))
982
983      asid_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
984    } else {
985      val hit0 = entry.tag(sectorvpnLen - 1, sectorvpnLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
986      val hit1 = entry.tag(sectorvpnLen - vpnnLen - 1, sectorvpnLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
987      val addr_low_hit = valididx(vpn(sectortlbwidth - 1, 0))
988
989      asid_hit && Mux(entry.level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1) && addr_low_hit
990    }
991  }
992}
993
994class PtwMergeResp(implicit p: Parameters) extends PtwBundle {
995  val entry = Vec(tlbcontiguous, new PtwMergeEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true))
996  val pteidx = Vec(tlbcontiguous, Bool())
997  val not_super = Bool()
998
999  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, asid: UInt, addr_low : UInt, not_super : Boolean = true) = {
1000    assert(tlbcontiguous == 8, "Only support tlbcontiguous = 8!")
1001
1002    val ptw_resp = Wire(new PtwMergeEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true))
1003    ptw_resp.ppn := pte.ppn(ppnLen - 1, sectortlbwidth)
1004    ptw_resp.ppn_low := pte.ppn(sectortlbwidth - 1, 0)
1005    ptw_resp.level.map(_ := level)
1006    ptw_resp.perm.map(_ := pte.getPerm())
1007    ptw_resp.tag := vpn(vpnLen - 1, sectortlbwidth)
1008    ptw_resp.pf := pf
1009    ptw_resp.af := af
1010    ptw_resp.v := !pf
1011    ptw_resp.prefetch := DontCare
1012    ptw_resp.asid := asid
1013    this.pteidx := UIntToOH(addr_low).asBools
1014    this.not_super := not_super.B
1015    for (i <- 0 until tlbcontiguous) {
1016      this.entry(i) := ptw_resp
1017    }
1018  }
1019}
1020
1021class L2TLBIO(implicit p: Parameters) extends PtwBundle {
1022  val tlb = Vec(PtwWidth, Flipped(new TlbPtwIO))
1023  val sfence = Input(new SfenceBundle)
1024  val csr = new Bundle {
1025    val tlb = Input(new TlbCsrBundle)
1026    val distribute_csr = Flipped(new DistributedCSRIO)
1027  }
1028}
1029
1030class L2TlbMemReqBundle(implicit p: Parameters) extends PtwBundle {
1031  val addr = UInt(PAddrBits.W)
1032  val id = UInt(bMemID.W)
1033}
1034
1035class L2TlbInnerBundle(implicit p: Parameters) extends PtwReq {
1036  val source = UInt(bSourceWidth.W)
1037}
1038
1039
1040object ValidHoldBypass{
1041  def apply(infire: Bool, outfire: Bool, flush: Bool = false.B) = {
1042    val valid = RegInit(false.B)
1043    when (infire) { valid := true.B }
1044    when (outfire) { valid := false.B } // ATTENTION: order different with ValidHold
1045    when (flush) { valid := false.B } // NOTE: the flush will flush in & out, is that ok?
1046    valid || infire
1047  }
1048}
1049
1050class L1TlbDB(implicit p: Parameters) extends TlbBundle {
1051  val vpn = UInt(vpnLen.W)
1052}
1053
1054class PageCacheDB(implicit p: Parameters) extends TlbBundle with HasPtwConst {
1055  val vpn = UInt(vpnLen.W)
1056  val source = UInt(bSourceWidth.W)
1057  val bypassed = Bool()
1058  val is_first = Bool()
1059  val prefetched = Bool()
1060  val prefetch = Bool()
1061  val l2Hit = Bool()
1062  val l1Hit = Bool()
1063  val hit = Bool()
1064}
1065
1066class PTWDB(implicit p: Parameters) extends TlbBundle with HasPtwConst {
1067  val vpn = UInt(vpnLen.W)
1068  val source = UInt(bSourceWidth.W)
1069}
1070
1071class L2TlbPrefetchDB(implicit p: Parameters) extends TlbBundle {
1072  val vpn = UInt(vpnLen.W)
1073}
1074
1075class L2TlbMissQueueDB(implicit p: Parameters) extends TlbBundle {
1076  val vpn = UInt(vpnLen.W)
1077}
1078