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