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