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