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