xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/MMUBundle.scala (revision 51e45dbbf87325e45ff2af6ca86ed6c7eed04464)
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
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 hartId = Input(UInt(8.W))
617  val requestor = Vec(Width, Flipped(new TlbRequestIO(nRespDups)))
618  val flushPipe = Vec(Width, Input(Bool()))
619  val ptw = new TlbPtwIOwithMemIdx(Width)
620  val refill_to_mem = Output(new TlbRefilltoMemIO())
621  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(Width, q)) else null
622  val pmp = Vec(Width, ValidIO(new PMPReqBundle()))
623
624}
625
626class VectorTlbPtwIO(Width: Int)(implicit p: Parameters) extends TlbBundle {
627  val req = Vec(Width, DecoupledIO(new PtwReqwithMemIdx()))
628  val resp = Flipped(DecoupledIO(new Bundle {
629    val data = new PtwSectorRespwithMemIdx
630    val vector = Output(Vec(Width, Bool()))
631  }))
632
633  def connect(normal: TlbPtwIOwithMemIdx): Unit = {
634    req <> normal.req
635    resp.ready := normal.resp.ready
636    normal.resp.bits := resp.bits.data
637    normal.resp.valid := resp.valid
638  }
639}
640
641/****************************  L2TLB  *************************************/
642abstract class PtwBundle(implicit p: Parameters) extends XSBundle with HasPtwConst
643abstract class PtwModule(outer: L2TLB) extends LazyModuleImp(outer)
644  with HasXSParameter with HasPtwConst
645
646class PteBundle(implicit p: Parameters) extends PtwBundle{
647  val reserved  = UInt(pteResLen.W)
648  val ppn_high = UInt(ppnHignLen.W)
649  val ppn  = UInt(ppnLen.W)
650  val rsw  = UInt(2.W)
651  val perm = new Bundle {
652    val d    = Bool()
653    val a    = Bool()
654    val g    = Bool()
655    val u    = Bool()
656    val x    = Bool()
657    val w    = Bool()
658    val r    = Bool()
659    val v    = Bool()
660  }
661
662  def unaligned(level: UInt) = {
663    isLeaf() && !(level === 2.U ||
664                  level === 1.U && ppn(vpnnLen-1,   0) === 0.U ||
665                  level === 0.U && ppn(vpnnLen*2-1, 0) === 0.U)
666  }
667
668  def isPf(level: UInt) = {
669    !perm.v || (!perm.r && perm.w) || unaligned(level)
670  }
671
672  // paddr of Xiangshan is 36 bits but ppn of sv39 is 44 bits
673  // access fault will be raised when ppn >> ppnLen is not zero
674  def isAf() = {
675    !(ppn_high === 0.U)
676  }
677
678  def isLeaf() = {
679    perm.r || perm.x || perm.w
680  }
681
682  def getPerm() = {
683    val pm = Wire(new PtePermBundle)
684    pm.d := perm.d
685    pm.a := perm.a
686    pm.g := perm.g
687    pm.u := perm.u
688    pm.x := perm.x
689    pm.w := perm.w
690    pm.r := perm.r
691    pm
692  }
693
694  override def toPrintable: Printable = {
695    p"ppn:0x${Hexadecimal(ppn)} perm:b${Binary(perm.asUInt)}"
696  }
697}
698
699class PtwEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwBundle {
700  val tag = UInt(tagLen.W)
701  val asid = UInt(asidLen.W)
702  val ppn = UInt(ppnLen.W)
703  val perm = if (hasPerm) Some(new PtePermBundle) else None
704  val level = if (hasLevel) Some(UInt(log2Up(Level).W)) else None
705  val prefetch = Bool()
706  val v = Bool()
707
708  def is_normalentry(): Bool = {
709    if (!hasLevel) true.B
710    else level.get === 2.U
711  }
712
713  def genPPN(vpn: UInt): UInt = {
714    if (!hasLevel) ppn
715    else MuxLookup(level.get, 0.U, Seq(
716          0.U -> Cat(ppn(ppn.getWidth-1, vpnnLen*2), vpn(vpnnLen*2-1, 0)),
717          1.U -> Cat(ppn(ppn.getWidth-1, vpnnLen), vpn(vpnnLen-1, 0)),
718          2.U -> ppn)
719    )
720  }
721
722  def hit(vpn: UInt, asid: UInt, allType: Boolean = false, ignoreAsid: Boolean = false) = {
723    require(vpn.getWidth == vpnLen)
724//    require(this.asid.getWidth <= asid.getWidth)
725    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
726    if (allType) {
727      require(hasLevel)
728      val hit0 = tag(tagLen - 1,    vpnnLen*2) === vpn(tagLen - 1, vpnnLen*2)
729      val hit1 = tag(vpnnLen*2 - 1, vpnnLen)   === vpn(vpnnLen*2 - 1,  vpnnLen)
730      val hit2 = tag(vpnnLen - 1,     0)         === vpn(vpnnLen - 1, 0)
731
732      asid_hit && Mux(level.getOrElse(0.U) === 2.U, hit2 && hit1 && hit0, Mux(level.getOrElse(0.U) === 1.U, hit1 && hit0, hit0))
733    } else if (hasLevel) {
734      val hit0 = tag(tagLen - 1, tagLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
735      val hit1 = tag(tagLen - vpnnLen - 1, tagLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
736
737      asid_hit && Mux(level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1)
738    } else {
739      asid_hit && tag === vpn(vpnLen - 1, vpnLen - tagLen)
740    }
741  }
742
743  def refill(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool, valid: Bool = false.B) {
744    require(this.asid.getWidth <= asid.getWidth) // maybe equal is better, but ugly outside
745
746    tag := vpn(vpnLen - 1, vpnLen - tagLen)
747    ppn := pte.asTypeOf(new PteBundle().cloneType).ppn
748    perm.map(_ := pte.asTypeOf(new PteBundle().cloneType).perm)
749    this.asid := asid
750    this.prefetch := prefetch
751    this.v := valid
752    this.level.map(_ := level)
753  }
754
755  def genPtwEntry(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool, valid: Bool = false.B) = {
756    val e = Wire(new PtwEntry(tagLen, hasPerm, hasLevel))
757    e.refill(vpn, asid, pte, level, prefetch, valid)
758    e
759  }
760
761
762
763  override def toPrintable: Printable = {
764    // p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} perm:${perm}"
765    p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} " +
766      (if (hasPerm) p"perm:${perm.getOrElse(0.U.asTypeOf(new PtePermBundle))} " else p"") +
767      (if (hasLevel) p"level:${level.getOrElse(0.U)}" else p"") +
768      p"prefetch:${prefetch}"
769  }
770}
771
772class PtwSectorEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwEntry(tagLen, hasPerm, hasLevel) {
773  override val ppn = UInt(sectorppnLen.W)
774}
775
776class PtwMergeEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwSectorEntry(tagLen, hasPerm, hasLevel) {
777  val ppn_low = UInt(sectortlbwidth.W)
778  val af = Bool()
779  val pf = Bool()
780}
781
782class PtwEntries(num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
783  require(log2Up(num)==log2Down(num))
784  // NOTE: hasPerm means that is leaf or not.
785
786  val tag  = UInt(tagLen.W)
787  val asid = UInt(asidLen.W)
788  val ppns = Vec(num, UInt(ppnLen.W))
789  val vs   = Vec(num, Bool())
790  val perms = if (hasPerm) Some(Vec(num, new PtePermBundle)) else None
791  val prefetch = Bool()
792  // println(s"PtwEntries: tag:1*${tagLen} ppns:${num}*${ppnLen} vs:${num}*1")
793  // NOTE: vs is used for different usage:
794  // for l3, which store the leaf(leaves), vs is page fault or not.
795  // for l2, which shoule not store leaf, vs is valid or not, that will anticipate in hit check
796  // Because, l2 should not store leaf(no perm), it doesn't store perm.
797  // If l2 hit a leaf, the perm is still unavailble. Should still page walk. Complex but nothing helpful.
798  // TODO: divide vs into validVec and pfVec
799  // for l2: may valid but pf, so no need for page walk, return random pte with pf.
800
801  def tagClip(vpn: UInt) = {
802    require(vpn.getWidth == vpnLen)
803    vpn(vpnLen - 1, vpnLen - tagLen)
804  }
805
806  def sectorIdxClip(vpn: UInt, level: Int) = {
807    getVpnClip(vpn, level)(log2Up(num) - 1, 0)
808  }
809
810  def hit(vpn: UInt, asid: UInt, ignoreAsid: Boolean = false) = {
811    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
812    asid_hit && tag === tagClip(vpn) && (if (hasPerm) true.B else vs(sectorIdxClip(vpn, level)))
813  }
814
815  def genEntries(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
816    require((data.getWidth / XLEN) == num,
817      s"input data length must be multiple of pte length: data.length:${data.getWidth} num:${num}")
818
819    val ps = Wire(new PtwEntries(num, tagLen, level, hasPerm))
820    ps.tag := tagClip(vpn)
821    ps.asid := asid
822    ps.prefetch := prefetch
823    for (i <- 0 until num) {
824      val pte = data((i+1)*XLEN-1, i*XLEN).asTypeOf(new PteBundle)
825      ps.ppns(i) := pte.ppn
826      ps.vs(i)   := !pte.isPf(levelUInt) && (if (hasPerm) pte.isLeaf() else !pte.isLeaf())
827      ps.perms.map(_(i) := pte.perm)
828    }
829    ps
830  }
831
832  override def toPrintable: Printable = {
833    // require(num == 4, "if num is not 4, please comment this toPrintable")
834    // NOTE: if num is not 4, please comment this toPrintable
835    val permsInner = perms.getOrElse(0.U.asTypeOf(Vec(num, new PtePermBundle)))
836    p"asid: ${Hexadecimal(asid)} tag:0x${Hexadecimal(tag)} ppns:${printVec(ppns)} vs:${Binary(vs.asUInt)} " +
837      (if (hasPerm) p"perms:${printVec(permsInner)}" else p"")
838  }
839}
840
841class PTWEntriesWithEcc(eccCode: Code, num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
842  val entries = new PtwEntries(num, tagLen, level, hasPerm)
843
844  val ecc_block = XLEN
845  val ecc_info = get_ecc_info()
846  val ecc = UInt(ecc_info._1.W)
847
848  def get_ecc_info(): (Int, Int, Int, Int) = {
849    val eccBits_per = eccCode.width(ecc_block) - ecc_block
850
851    val data_length = entries.getWidth
852    val data_align_num = data_length / ecc_block
853    val data_not_align = (data_length % ecc_block) != 0 // ugly code
854    val data_unalign_length = data_length - data_align_num * ecc_block
855    val eccBits_unalign = eccCode.width(data_unalign_length) - data_unalign_length
856
857    val eccBits = eccBits_per * data_align_num + eccBits_unalign
858    (eccBits, eccBits_per, data_align_num, data_unalign_length)
859  }
860
861  def encode() = {
862    val data = entries.asUInt
863    val ecc_slices = Wire(Vec(ecc_info._3, UInt(ecc_info._2.W)))
864    for (i <- 0 until ecc_info._3) {
865      ecc_slices(i) := eccCode.encode(data((i+1)*ecc_block-1, i*ecc_block)) >> ecc_block
866    }
867    if (ecc_info._4 != 0) {
868      val ecc_unaligned = eccCode.encode(data(data.getWidth-1, ecc_info._3*ecc_block)) >> ecc_info._4
869      ecc := Cat(ecc_unaligned, ecc_slices.asUInt)
870    } else { ecc := ecc_slices.asUInt }
871  }
872
873  def decode(): Bool = {
874    val data = entries.asUInt
875    val res = Wire(Vec(ecc_info._3 + 1, Bool()))
876    for (i <- 0 until ecc_info._3) {
877      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}
878    }
879    if (ecc_info._2 != 0 && ecc_info._4 != 0) {
880      res(ecc_info._3) := eccCode.decode(
881        Cat(ecc(ecc_info._1-1, ecc_info._2*ecc_info._3), data(data.getWidth-1, ecc_info._3*ecc_block))).error
882    } else { res(ecc_info._3) := false.B }
883
884    Cat(res).orR
885  }
886
887  def gen(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
888    this.entries := entries.genEntries(vpn, asid, data, levelUInt, prefetch)
889    this.encode()
890  }
891}
892
893class PtwReq(implicit p: Parameters) extends PtwBundle {
894  val vpn = UInt(vpnLen.W)
895
896  override def toPrintable: Printable = {
897    p"vpn:0x${Hexadecimal(vpn)}"
898  }
899}
900
901class PtwReqwithMemIdx(implicit p: Parameters) extends PtwReq {
902  val memidx = new MemBlockidxBundle
903}
904
905class PtwResp(implicit p: Parameters) extends PtwBundle {
906  val entry = new PtwEntry(tagLen = vpnLen, hasPerm = true, hasLevel = true)
907  val pf = Bool()
908  val af = Bool()
909
910  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, asid: UInt) = {
911    this.entry.level.map(_ := level)
912    this.entry.tag := vpn
913    this.entry.perm.map(_ := pte.getPerm())
914    this.entry.ppn := pte.ppn
915    this.entry.prefetch := DontCare
916    this.entry.asid := asid
917    this.entry.v := !pf
918    this.pf := pf
919    this.af := af
920  }
921
922  override def toPrintable: Printable = {
923    p"entry:${entry} pf:${pf} af:${af}"
924  }
925}
926
927class PtwResptomerge (implicit p: Parameters) extends PtwBundle {
928  val entry = UInt(blockBits.W)
929  val vpn = UInt(vpnLen.W)
930  val level = UInt(log2Up(Level).W)
931  val pf = Bool()
932  val af = Bool()
933  val asid = UInt(asidLen.W)
934
935  def apply(pf: Bool, af: Bool, level: UInt, pte: UInt, vpn: UInt, asid: UInt) = {
936    this.entry := pte
937    this.pf := pf
938    this.af := af
939    this.level := level
940    this.vpn := vpn
941    this.asid := asid
942  }
943
944  override def toPrintable: Printable = {
945    p"entry:${entry} pf:${pf} af:${af}"
946  }
947}
948
949class PtwRespwithMemIdx(implicit p: Parameters) extends PtwResp {
950  val memidx = new MemBlockidxBundle
951}
952
953class PtwSectorRespwithMemIdx(implicit p: Parameters) extends PtwSectorResp {
954  val memidx = new MemBlockidxBundle
955}
956
957class PtwSectorResp(implicit p: Parameters) extends PtwBundle {
958  val entry = new PtwSectorEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true)
959  val addr_low = UInt(sectortlbwidth.W)
960  val ppn_low = Vec(tlbcontiguous, UInt(sectortlbwidth.W))
961  val valididx = Vec(tlbcontiguous, Bool())
962  val pteidx = Vec(tlbcontiguous, Bool())
963  val pf = Bool()
964  val af = Bool()
965
966  def genPPN(vpn: UInt): UInt = {
967    MuxLookup(entry.level.get, 0.U, Seq(
968      0.U -> Cat(entry.ppn(entry.ppn.getWidth-1, vpnnLen * 2 - sectortlbwidth), vpn(vpnnLen*2-1, 0)),
969      1.U -> Cat(entry.ppn(entry.ppn.getWidth-1, vpnnLen - sectortlbwidth), vpn(vpnnLen-1, 0)),
970      2.U -> Cat(entry.ppn(entry.ppn.getWidth-1, 0), ppn_low(vpn(sectortlbwidth - 1, 0))))
971    )
972  }
973
974  def hit(vpn: UInt, asid: UInt, allType: Boolean = false, ignoreAsid: Boolean = false) = {
975    require(vpn.getWidth == vpnLen)
976    //    require(this.asid.getWidth <= asid.getWidth)
977    val asid_hit = if (ignoreAsid) true.B else (this.entry.asid === asid)
978    if (allType) {
979      val hit0 = entry.tag(sectorvpnLen - 1, vpnnLen * 2 - sectortlbwidth) === vpn(vpnLen - 1, vpnnLen * 2)
980      val hit1 = entry.tag(vpnnLen * 2 - sectortlbwidth - 1, vpnnLen - sectortlbwidth)   === vpn(vpnnLen * 2 - 1,  vpnnLen)
981      val hit2 = entry.tag(vpnnLen - sectortlbwidth - 1, 0) === vpn(vpnnLen - 1, sectortlbwidth)
982      val addr_low_hit = valididx(vpn(sectortlbwidth - 1, 0))
983
984      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
985    } else {
986      val hit0 = entry.tag(sectorvpnLen - 1, sectorvpnLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
987      val hit1 = entry.tag(sectorvpnLen - vpnnLen - 1, sectorvpnLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
988      val addr_low_hit = valididx(vpn(sectortlbwidth - 1, 0))
989
990      asid_hit && Mux(entry.level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1) && addr_low_hit
991    }
992  }
993}
994
995class PtwMergeResp(implicit p: Parameters) extends PtwBundle {
996  val entry = Vec(tlbcontiguous, new PtwMergeEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true))
997  val pteidx = Vec(tlbcontiguous, Bool())
998  val not_super = Bool()
999
1000  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, asid: UInt, addr_low : UInt, not_super : Boolean = true) = {
1001    assert(tlbcontiguous == 8, "Only support tlbcontiguous = 8!")
1002
1003    val ptw_resp = Wire(new PtwMergeEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true))
1004    ptw_resp.ppn := pte.ppn(ppnLen - 1, sectortlbwidth)
1005    ptw_resp.ppn_low := pte.ppn(sectortlbwidth - 1, 0)
1006    ptw_resp.level.map(_ := level)
1007    ptw_resp.perm.map(_ := pte.getPerm())
1008    ptw_resp.tag := vpn(vpnLen - 1, sectortlbwidth)
1009    ptw_resp.pf := pf
1010    ptw_resp.af := af
1011    ptw_resp.v := !pf
1012    ptw_resp.prefetch := DontCare
1013    ptw_resp.asid := asid
1014    this.pteidx := UIntToOH(addr_low).asBools
1015    this.not_super := not_super.B
1016    for (i <- 0 until tlbcontiguous) {
1017      this.entry(i) := ptw_resp
1018    }
1019  }
1020}
1021
1022class L2TLBIO(implicit p: Parameters) extends PtwBundle {
1023  val hartId = Input(UInt(8.W))
1024  val tlb = Vec(PtwWidth, Flipped(new TlbPtwIO))
1025  val sfence = Input(new SfenceBundle)
1026  val csr = new Bundle {
1027    val tlb = Input(new TlbCsrBundle)
1028    val distribute_csr = Flipped(new DistributedCSRIO)
1029  }
1030}
1031
1032class L2TlbMemReqBundle(implicit p: Parameters) extends PtwBundle {
1033  val addr = UInt(PAddrBits.W)
1034  val id = UInt(bMemID.W)
1035}
1036
1037class L2TlbInnerBundle(implicit p: Parameters) extends PtwReq {
1038  val source = UInt(bSourceWidth.W)
1039}
1040
1041
1042object ValidHoldBypass{
1043  def apply(infire: Bool, outfire: Bool, flush: Bool = false.B) = {
1044    val valid = RegInit(false.B)
1045    when (infire) { valid := true.B }
1046    when (outfire) { valid := false.B } // ATTENTION: order different with ValidHold
1047    when (flush) { valid := false.B } // NOTE: the flush will flush in & out, is that ok?
1048    valid || infire
1049  }
1050}
1051
1052class L1TlbDB(implicit p: Parameters) extends TlbBundle {
1053  val vpn = UInt(vpnLen.W)
1054}
1055
1056class PageCacheDB(implicit p: Parameters) extends TlbBundle with HasPtwConst {
1057  val vpn = UInt(vpnLen.W)
1058  val source = UInt(bSourceWidth.W)
1059  val bypassed = Bool()
1060  val is_first = Bool()
1061  val prefetched = Bool()
1062  val prefetch = Bool()
1063  val l2Hit = Bool()
1064  val l1Hit = Bool()
1065  val hit = Bool()
1066}
1067
1068class PTWDB(implicit p: Parameters) extends TlbBundle with HasPtwConst {
1069  val vpn = UInt(vpnLen.W)
1070  val source = UInt(bSourceWidth.W)
1071}
1072
1073class L2TlbPrefetchDB(implicit p: Parameters) extends TlbBundle {
1074  val vpn = UInt(vpnLen.W)
1075}
1076
1077class L2TlbMissQueueDB(implicit p: Parameters) extends TlbBundle {
1078  val vpn = UInt(vpnLen.W)
1079}
1080