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