xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/MMUBundle.scala (revision 1b5e3cda2e8bbc4254b900b0321cbc4d396ef041)
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 chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import xiangshan._
23import utils._
24import xiangshan.backend.rob.RobPtr
25import xiangshan.backend.fu.util.HasCSRConst
26import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
27import freechips.rocketchip.tilelink._
28import xiangshan.backend.fu.PMPReqBundle
29
30abstract class TlbBundle(implicit p: Parameters) extends XSBundle with HasTlbConst
31abstract class TlbModule(implicit p: Parameters) extends XSModule with HasTlbConst
32
33class VaBundle(implicit p: Parameters) extends TlbBundle {
34  val vpn  = UInt(vpnLen.W)
35  val off  = UInt(offLen.W)
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 TlbPermBundle(implicit p: Parameters) extends TlbBundle {
54  val pf = Bool() // NOTE: if this is true, just raise pf
55  val af = Bool() // NOTE: if this is true, just raise af
56  // pagetable perm (software defined)
57  val d = Bool()
58  val a = Bool()
59  val g = Bool()
60  val u = Bool()
61  val x = Bool()
62  val w = Bool()
63  val r = Bool()
64
65  override def toPrintable: Printable = {
66    p"pf:${pf} af:${af} d:${d} a:${a} g:${g} u:${u} x:${x} w:${w} r:${r}"
67  }
68}
69
70// multi-read && single-write
71// input is data, output is hot-code(not one-hot)
72class CAMTemplate[T <: Data](val gen: T, val set: Int, val readWidth: Int)(implicit p: Parameters) extends TlbModule {
73  val io = IO(new Bundle {
74    val r = new Bundle {
75      val req = Input(Vec(readWidth, gen))
76      val resp = Output(Vec(readWidth, Vec(set, Bool())))
77    }
78    val w = Input(new Bundle {
79      val valid = Bool()
80      val bits = new Bundle {
81        val index = UInt(log2Up(set).W)
82        val data = gen
83      }
84    })
85  })
86
87  val wordType = UInt(gen.getWidth.W)
88  val array = Reg(Vec(set, wordType))
89
90  io.r.resp.zipWithIndex.map{ case (a,i) =>
91    a := array.map(io.r.req(i).asUInt === _)
92  }
93
94  when (io.w.valid) {
95    array(io.w.bits.index) := io.w.bits.data
96  }
97}
98
99class TlbSPMeta(implicit p: Parameters) extends TlbBundle {
100  val tag = UInt(vpnLen.W) // tag is vpn
101  val level = UInt(1.W) // 1 for 2MB, 0 for 1GB
102  val asid = UInt(asidLen.W)
103
104  def hit(vpn: UInt, asid: UInt): Bool = {
105    val a = tag(vpnnLen*3-1, vpnnLen*2) === vpn(vpnnLen*3-1, vpnnLen*2)
106    val b = tag(vpnnLen*2-1, vpnnLen*1) === vpn(vpnnLen*2-1, vpnnLen*1)
107    val asid_hit = this.asid === asid
108
109    XSDebug(Mux(level.asBool, a&b, a), p"Hit superpage: hit:${Mux(level.asBool, a&b, a)} tag:${Hexadecimal(tag)} level:${level} a:${a} b:${b} vpn:${Hexadecimal(vpn)}\n")
110    asid_hit && Mux(level.asBool, a&b, a)
111  }
112
113  def apply(vpn: UInt, asid: UInt, level: UInt) = {
114    this.tag := vpn
115    this.asid := asid
116    this.level := level(0)
117
118    this
119  }
120
121}
122
123class TlbData(superpage: Boolean = false)(implicit p: Parameters) extends TlbBundle {
124  val level = if(superpage) Some(UInt(1.W)) else None // /*2 for 4KB,*/ 1 for 2MB, 0 for 1GB
125  val ppn = UInt(ppnLen.W)
126  val perm = new TlbPermBundle
127
128  def genPPN(vpn: UInt): UInt = {
129    if (superpage) {
130      val insideLevel = level.getOrElse(0.U)
131      Mux(insideLevel.asBool, Cat(ppn(ppn.getWidth-1, vpnnLen*1), vpn(vpnnLen*1-1, 0)),
132                              Cat(ppn(ppn.getWidth-1, vpnnLen*2), vpn(vpnnLen*2-1, 0)))
133    } else {
134      ppn
135    }
136  }
137
138  def apply(ppn: UInt, level: UInt, perm: UInt, pf: Bool, af: Bool) = {
139    this.level.map(_ := level(0))
140    this.ppn := ppn
141    // refill pagetable perm
142    val ptePerm = perm.asTypeOf(new PtePermBundle)
143    this.perm.pf:= pf
144    this.perm.af:= af
145    this.perm.d := ptePerm.d
146    this.perm.a := ptePerm.a
147    this.perm.g := ptePerm.g
148    this.perm.u := ptePerm.u
149    this.perm.x := ptePerm.x
150    this.perm.w := ptePerm.w
151    this.perm.r := ptePerm.r
152
153    this
154  }
155
156  override def toPrintable: Printable = {
157    val insideLevel = level.getOrElse(0.U)
158    p"level:${insideLevel} ppn:${Hexadecimal(ppn)} perm:${perm}"
159  }
160
161  override def cloneType: this.type = (new TlbData(superpage)).asInstanceOf[this.type]
162}
163
164class TlbEntry(pageNormal: Boolean, pageSuper: Boolean)(implicit p: Parameters) extends TlbBundle {
165  require(pageNormal || pageSuper)
166
167  val tag = if (!pageNormal) UInt((vpnLen - vpnnLen).W)
168            else UInt(vpnLen.W)
169  val asid = UInt(asidLen.W)
170  val level = if (!pageNormal) Some(UInt(1.W))
171              else if (!pageSuper) None
172              else Some(UInt(2.W))
173  val ppn = if (!pageNormal) UInt((ppnLen - vpnnLen).W)
174            else UInt(ppnLen.W)
175  val perm = new TlbPermBundle
176
177  def hit(vpn: UInt, asid: UInt, nSets: Int = 1, ignoreAsid: Boolean = false): Bool = {
178    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
179
180    // NOTE: for timing, dont care low set index bits at hit check
181    //       do not need store the low bits actually
182    if (!pageSuper) asid_hit && drop_set_equal(vpn, tag, nSets)
183    else if (!pageNormal) asid_hit && MuxLookup(level.get, false.B, Seq(
184      0.U -> (tag(vpnnLen*2-1, vpnnLen) === vpn(vpnLen-1, vpnnLen*2)),
185      1.U -> (tag === vpn(vpnLen-1, vpnnLen)),
186    ))
187    else asid_hit && MuxLookup(level.get, false.B, Seq(
188      0.U -> (tag(vpnLen-1, vpnnLen*2) === vpn(vpnLen-1, vpnnLen*2)),
189      1.U -> (tag(vpnLen-1, vpnnLen) === vpn(vpnLen-1, vpnnLen)),
190      2.U -> drop_set_equal(tag, vpn, nSets) // if pageNormal is false, this will always be false
191    ))
192  }
193
194  def apply(item: PtwResp, asid: UInt): TlbEntry = {
195    this.tag := {if (pageNormal) item.entry.tag else item.entry.tag(vpnLen-1, vpnnLen)}
196    this.asid := asid
197    val inner_level = item.entry.level.getOrElse(0.U)
198    this.level.map(_ := { if (pageNormal && pageSuper) inner_level
199                          else if (pageSuper) inner_level(0)
200                          else 0.U})
201    this.ppn := { if (!pageNormal) item.entry.ppn(ppnLen-1, vpnnLen)
202                  else item.entry.ppn }
203    val ptePerm = item.entry.perm.get.asTypeOf(new PtePermBundle().cloneType)
204    this.perm.pf := item.pf
205    this.perm.af := item.af
206    this.perm.d := ptePerm.d
207    this.perm.a := ptePerm.a
208    this.perm.g := ptePerm.g
209    this.perm.u := ptePerm.u
210    this.perm.x := ptePerm.x
211    this.perm.w := ptePerm.w
212    this.perm.r := ptePerm.r
213
214    this
215  }
216
217  def genPPN(saveLevel: Boolean = false, valid: Bool = false.B)(vpn: UInt) : UInt = {
218    val ppn_res = if (!pageSuper) ppn
219    else if (!pageNormal) MuxLookup(level.get, 0.U, Seq(
220      0.U -> Cat(ppn(ppn.getWidth-1, vpnnLen), vpn(vpnnLen*2-1, 0)),
221      1.U -> Cat(ppn, vpn(vpnnLen-1, 0))
222    ))
223    else MuxLookup(level.get, 0.U, Seq(
224      0.U -> Cat(ppn(ppn.getWidth-1, vpnnLen*2), vpn(vpnnLen*2-1, 0)),
225      1.U -> Cat(ppn(ppn.getWidth-1, vpnnLen), vpn(vpnnLen-1, 0)),
226      2.U -> ppn
227    ))
228
229    val static_part_length = ppn_res.getWidth - vpnnLen*2
230    if (saveLevel) Cat(ppn(ppn.getWidth-1, ppn.getWidth-static_part_length), RegEnable(ppn_res(vpnnLen*2-1, 0), valid))
231    else ppn_res
232  }
233
234  override def toPrintable: Printable = {
235    val inner_level = level.getOrElse(2.U)
236    p"asid: ${asid} level:${inner_level} vpn:${Hexadecimal(tag)} ppn:${Hexadecimal(ppn)} perm:${perm}"
237  }
238
239  override def cloneType: this.type = (new TlbEntry(pageNormal, pageSuper)).asInstanceOf[this.type]
240}
241
242object TlbCmd {
243  def read  = "b00".U
244  def write = "b01".U
245  def exec  = "b10".U
246
247  def atom_read  = "b100".U // lr
248  def atom_write = "b101".U // sc / amo
249
250  def apply() = UInt(3.W)
251  def isRead(a: UInt) = a(1,0)===read
252  def isWrite(a: UInt) = a(1,0)===write
253  def isExec(a: UInt) = a(1,0)===exec
254
255  def isAtom(a: UInt) = a(2)
256  def isAmo(a: UInt) = a===atom_write // NOTE: sc mixed
257}
258
259class TlbStorageIO(nSets: Int, nWays: Int, ports: Int)(implicit p: Parameters) extends MMUIOBaseBundle {
260  val r = new Bundle {
261    val req = Vec(ports, Flipped(DecoupledIO(new Bundle {
262      val vpn = Output(UInt(vpnLen.W))
263    })))
264    val resp = Vec(ports, ValidIO(new Bundle{
265      val hit = Output(Bool())
266      val ppn = Output(UInt(ppnLen.W))
267      val perm = Output(new TlbPermBundle())
268    }))
269    val resp_hit_sameCycle = Output(Vec(ports, Bool())) // req hit or not same cycle with req
270  }
271  val w = Flipped(ValidIO(new Bundle {
272    val wayIdx = Output(UInt(log2Up(nWays).W))
273    val data = Output(new PtwResp)
274  }))
275  val victim = new Bundle {
276    val out = ValidIO(Output(new Bundle {
277      val entry = new TlbEntry(pageNormal = true, pageSuper = false)
278    }))
279    val in = Flipped(ValidIO(Output(new Bundle {
280      val entry = new TlbEntry(pageNormal = true, pageSuper = false)
281    })))
282  }
283  val access = Vec(ports, new ReplaceAccessBundle(nSets, nWays))
284
285  def r_req_apply(valid: Bool, vpn: UInt, asid: UInt, i: Int): Unit = {
286    this.r.req(i).valid := valid
287    this.r.req(i).bits.vpn := vpn
288  }
289
290  def r_resp_apply(i: Int) = {
291    (this.r.resp_hit_sameCycle(i), this.r.resp(i).bits.hit, this.r.resp(i).bits.ppn, this.r.resp(i).bits.perm)
292  }
293
294  def w_apply(valid: Bool, wayIdx: UInt, data: PtwResp): Unit = {
295    this.w.valid := valid
296    this.w.bits.wayIdx := wayIdx
297    this.w.bits.data := data
298  }
299
300  override def cloneType: this.type = new TlbStorageIO(nSets, nWays, ports).asInstanceOf[this.type]
301}
302
303class ReplaceAccessBundle(nSets: Int, nWays: Int)(implicit p: Parameters) extends TlbBundle {
304  val sets = Output(UInt(log2Up(nSets).W))
305  val touch_ways = ValidIO(Output(UInt(log2Up(nWays).W)))
306
307  override def cloneType: this.type =new ReplaceAccessBundle(nSets, nWays).asInstanceOf[this.type]
308}
309
310class ReplaceIO(Width: Int, nSets: Int, nWays: Int)(implicit p: Parameters) extends TlbBundle {
311  val access = Vec(Width, Flipped(new ReplaceAccessBundle(nSets, nWays)))
312
313  val refillIdx = Output(UInt(log2Up(nWays).W))
314  val chosen_set = Flipped(Output(UInt(log2Up(nSets).W)))
315
316  def apply_sep(in: Seq[ReplaceIO], vpn: UInt): Unit = {
317    for (i <- 0 until Width) {
318      this.access(i) := in(i).access(0)
319      this.chosen_set := get_set_idx(vpn, nSets)
320      in(i).refillIdx := this.refillIdx
321    }
322  }
323}
324
325class TlbReplaceIO(Width: Int, q: TLBParameters)(implicit p: Parameters) extends
326  TlbBundle {
327  val normalPage = new ReplaceIO(Width, q.normalNSets, q.normalNWays)
328  val superPage = new ReplaceIO(Width, q.superNSets, q.superNWays)
329
330  def apply_sep(in: Seq[TlbReplaceIO], vpn: UInt) = {
331    this.normalPage.apply_sep(in.map(_.normalPage), vpn)
332    this.superPage.apply_sep(in.map(_.superPage), vpn)
333  }
334
335  override def cloneType = (new TlbReplaceIO(Width, q)).asInstanceOf[this.type]
336}
337
338class TlbReq(implicit p: Parameters) extends TlbBundle {
339  val vaddr = Output(UInt(VAddrBits.W))
340  val cmd = Output(TlbCmd())
341  val size = Output(UInt(log2Ceil(log2Ceil(XLEN/8)+1).W))
342  val robIdx = Output(new RobPtr)
343  val debug = new Bundle {
344    val pc = Output(UInt(XLEN.W))
345    val isFirstIssue = Output(Bool())
346  }
347
348  override def toPrintable: Printable = {
349    p"vaddr:0x${Hexadecimal(vaddr)} cmd:${cmd} pc:0x${Hexadecimal(debug.pc)} robIdx:${robIdx}"
350  }
351}
352
353class TlbExceptionBundle(implicit p: Parameters) extends TlbBundle {
354  val ld = Output(Bool())
355  val st = Output(Bool())
356  val instr = Output(Bool())
357}
358
359class TlbResp(implicit p: Parameters) extends TlbBundle {
360  val paddr = Output(UInt(PAddrBits.W))
361  val miss = Output(Bool())
362  val fast_miss = Output(Bool()) // without sram part for timing optimization
363  val excp = new Bundle {
364    val pf = new TlbExceptionBundle()
365    val af = new TlbExceptionBundle()
366  }
367  val ptwBack = Output(Bool()) // when ptw back, wake up replay rs's state
368
369  override def toPrintable: Printable = {
370    p"paddr:0x${Hexadecimal(paddr)} miss:${miss} excp.pf: ld:${excp.pf.ld} st:${excp.pf.st} instr:${excp.pf.instr} ptwBack:${ptwBack}"
371  }
372}
373
374class TlbRequestIO()(implicit p: Parameters) extends TlbBundle {
375  val req = DecoupledIO(new TlbReq)
376  val resp = Flipped(DecoupledIO(new TlbResp))
377}
378
379class BlockTlbRequestIO()(implicit p: Parameters) extends TlbBundle {
380  val req = DecoupledIO(new TlbReq)
381  val resp = Flipped(DecoupledIO(new TlbResp))
382}
383
384class TlbPtwIO(Width: Int = 1)(implicit p: Parameters) extends TlbBundle {
385  val req = Vec(Width, DecoupledIO(new PtwReq))
386  val resp = Flipped(DecoupledIO(new PtwResp))
387
388  override def cloneType: this.type = (new TlbPtwIO(Width)).asInstanceOf[this.type]
389
390  override def toPrintable: Printable = {
391    p"req(0):${req(0).valid} ${req(0).ready} ${req(0).bits} | resp:${resp.valid} ${resp.ready} ${resp.bits}"
392  }
393}
394
395class MMUIOBaseBundle(implicit p: Parameters) extends TlbBundle {
396  val sfence = Input(new SfenceBundle)
397  val csr = Input(new TlbCsrBundle)
398}
399
400class TlbIO(Width: Int, q: TLBParameters)(implicit p: Parameters) extends
401  MMUIOBaseBundle {
402  val requestor = Vec(Width, Flipped(new TlbRequestIO))
403  val ptw = new TlbPtwIO(Width)
404  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(Width, q)) else null
405  val pmp = Vec(Width, ValidIO(new PMPReqBundle()))
406
407  override def cloneType: this.type = (new TlbIO(Width, q)).asInstanceOf[this.type]
408}
409
410class BTlbPtwIO(Width: Int)(implicit p: Parameters) extends TlbBundle {
411  val req = Vec(Width, DecoupledIO(new PtwReq))
412  val resp = Flipped(DecoupledIO(new Bundle {
413    val data = new PtwResp
414    val vector = Output(Vec(Width, Bool()))
415  }))
416
417  override def cloneType: this.type = (new BTlbPtwIO(Width)).asInstanceOf[this.type]
418}
419/****************************  Bridge TLB *******************************/
420
421class BridgeTLBIO(Width: Int)(implicit p: Parameters) extends MMUIOBaseBundle {
422  val requestor = Vec(Width, Flipped(new TlbPtwIO()))
423  val ptw = new BTlbPtwIO(Width)
424
425  override def cloneType: this.type = (new BridgeTLBIO(Width)).asInstanceOf[this.type]
426}
427
428
429/****************************  PTW  *************************************/
430abstract class PtwBundle(implicit p: Parameters) extends XSBundle with HasPtwConst
431abstract class PtwModule(outer: PTW) extends LazyModuleImp(outer)
432  with HasXSParameter with HasPtwConst
433
434class PteBundle(implicit p: Parameters) extends PtwBundle{
435  val reserved  = UInt(pteResLen.W)
436  val ppn  = UInt(ppnLen.W)
437  val rsw  = UInt(2.W)
438  val perm = new Bundle {
439    val d    = Bool()
440    val a    = Bool()
441    val g    = Bool()
442    val u    = Bool()
443    val x    = Bool()
444    val w    = Bool()
445    val r    = Bool()
446    val v    = Bool()
447  }
448
449  def unaligned(level: UInt) = {
450    isLeaf() && !(level === 2.U ||
451                  level === 1.U && ppn(vpnnLen-1,   0) === 0.U ||
452                  level === 0.U && ppn(vpnnLen*2-1, 0) === 0.U)
453  }
454
455  def isPf(level: UInt) = {
456    !perm.v || (!perm.r && perm.w) || unaligned(level)
457  }
458
459  def isLeaf() = {
460    perm.r || perm.x || perm.w
461  }
462
463  def getPerm() = {
464    val pm = Wire(new PtePermBundle)
465    pm.d := perm.d
466    pm.a := perm.a
467    pm.g := perm.g
468    pm.u := perm.u
469    pm.x := perm.x
470    pm.w := perm.w
471    pm.r := perm.r
472    pm
473  }
474
475  override def toPrintable: Printable = {
476    p"ppn:0x${Hexadecimal(ppn)} perm:b${Binary(perm.asUInt)}"
477  }
478}
479
480class PtwEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwBundle {
481  val tag = UInt(tagLen.W)
482  val asid = UInt(asidLen.W)
483  val ppn = UInt(ppnLen.W)
484  val perm = if (hasPerm) Some(new PtePermBundle) else None
485  val level = if (hasLevel) Some(UInt(log2Up(Level).W)) else None
486  val prefetch = Bool()
487
488  def hit(vpn: UInt, asid: UInt, allType: Boolean = false, ignoreAsid: Boolean = false) = {
489    require(vpn.getWidth == vpnLen)
490//    require(this.asid.getWidth <= asid.getWidth)
491    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
492    if (allType) {
493      require(hasLevel)
494      val hit0 = tag(tagLen - 1,    vpnnLen*2) === vpn(tagLen - 1, vpnnLen*2)
495      val hit1 = tag(vpnnLen*2 - 1, vpnnLen)   === vpn(vpnnLen*2 - 1,  vpnnLen)
496      val hit2 = tag(vpnnLen - 1,     0)         === vpn(vpnnLen - 1, 0)
497
498      asid_hit && Mux(level.getOrElse(0.U) === 2.U, hit2 && hit1 && hit0, Mux(level.getOrElse(0.U) === 1.U, hit1 && hit0, hit0))
499    } else if (hasLevel) {
500      val hit0 = tag(tagLen - 1, tagLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
501      val hit1 = tag(tagLen - vpnnLen - 1, tagLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
502
503      asid_hit && Mux(level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1)
504    } else {
505      asid_hit && tag === vpn(vpnLen - 1, vpnLen - tagLen)
506    }
507  }
508
509  def refill(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool) {
510    require(this.asid.getWidth <= asid.getWidth) // maybe equal is better, but ugly outside
511
512    tag := vpn(vpnLen - 1, vpnLen - tagLen)
513    ppn := pte.asTypeOf(new PteBundle().cloneType).ppn
514    perm.map(_ := pte.asTypeOf(new PteBundle().cloneType).perm)
515    this.asid := asid
516    this.prefetch := prefetch
517    this.level.map(_ := level)
518  }
519
520  def genPtwEntry(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool) = {
521    val e = Wire(new PtwEntry(tagLen, hasPerm, hasLevel))
522    e.refill(vpn, asid, pte, level, prefetch)
523    e
524  }
525
526  override def cloneType: this.type = (new PtwEntry(tagLen, hasPerm, hasLevel)).asInstanceOf[this.type]
527
528  override def toPrintable: Printable = {
529    // p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} perm:${perm}"
530    p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} " +
531      (if (hasPerm) p"perm:${perm.getOrElse(0.U.asTypeOf(new PtePermBundle))} " else p"") +
532      (if (hasLevel) p"level:${level.getOrElse(0.U)}" else p"") +
533      p"prefetch:${prefetch}"
534  }
535}
536
537class PtwEntries(num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
538  require(log2Up(num)==log2Down(num))
539
540  val tag  = UInt(tagLen.W)
541  val asid = UInt(asidLen.W)
542  val ppns = Vec(num, UInt(ppnLen.W))
543  val vs   = Vec(num, Bool())
544  val perms = if (hasPerm) Some(Vec(num, new PtePermBundle)) else None
545  val prefetch = Bool()
546  // println(s"PtwEntries: tag:1*${tagLen} ppns:${num}*${ppnLen} vs:${num}*1")
547
548  def tagClip(vpn: UInt) = {
549    require(vpn.getWidth == vpnLen)
550    vpn(vpnLen - 1, vpnLen - tagLen)
551  }
552
553  def sectorIdxClip(vpn: UInt, level: Int) = {
554    getVpnClip(vpn, level)(log2Up(num) - 1, 0)
555  }
556
557  def hit(vpn: UInt, asid: UInt, ignoreAsid: Boolean = false) = {
558    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
559    asid_hit && tag === tagClip(vpn) && vs(sectorIdxClip(vpn, level)) // TODO: optimize this. don't need to compare each with tag
560  }
561
562  def genEntries(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
563    require((data.getWidth / XLEN) == num,
564      s"input data length must be multiple of pte length: data.length:${data.getWidth} num:${num}")
565
566    val ps = Wire(new PtwEntries(num, tagLen, level, hasPerm))
567    ps.tag := tagClip(vpn)
568    ps.asid := asid
569    ps.prefetch := prefetch
570    for (i <- 0 until num) {
571      val pte = data((i+1)*XLEN-1, i*XLEN).asTypeOf(new PteBundle)
572      ps.ppns(i) := pte.ppn
573      ps.vs(i)   := !pte.isPf(levelUInt) && (if (hasPerm) pte.isLeaf() else !pte.isLeaf())
574      ps.perms.map(_(i) := pte.perm)
575    }
576    ps
577  }
578
579  override def cloneType: this.type = (new PtwEntries(num, tagLen, level, hasPerm)).asInstanceOf[this.type]
580  override def toPrintable: Printable = {
581    // require(num == 4, "if num is not 4, please comment this toPrintable")
582    // NOTE: if num is not 4, please comment this toPrintable
583    val permsInner = perms.getOrElse(0.U.asTypeOf(Vec(num, new PtePermBundle)))
584    p"asid: ${Hexadecimal(asid)} tag:0x${Hexadecimal(tag)} ppns:${printVec(ppns)} vs:${Binary(vs.asUInt)} " +
585      (if (hasPerm) p"perms:${printVec(permsInner)}" else p"")
586  }
587}
588
589class PTWEntriesWithEcc(eccCode: Code, num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
590  val entries = new PtwEntries(num, tagLen, level, hasPerm)
591
592  val ecc_block = XLEN
593  val ecc_info = get_ecc_info()
594  val ecc = UInt(ecc_info._1.W)
595
596  def get_ecc_info(): (Int, Int, Int, Int) = {
597    val eccBits_per = eccCode.width(ecc_block) - ecc_block
598
599    val data_length = entries.getWidth
600    val data_align_num = data_length / ecc_block
601    val data_not_align = (data_length % ecc_block) != 0 // ugly code
602    val data_unalign_length = data_length - data_align_num * ecc_block
603    val eccBits_unalign = eccCode.width(data_unalign_length) - data_unalign_length
604
605    val eccBits = eccBits_per * data_align_num + eccBits_unalign
606    (eccBits, eccBits_per, data_align_num, data_unalign_length)
607  }
608
609  def encode() = {
610    val data = entries.asUInt()
611    val ecc_slices = Wire(Vec(ecc_info._3, UInt(ecc_info._2.W)))
612    for (i <- 0 until ecc_info._3) {
613      ecc_slices(i) := eccCode.encode(data((i+1)*ecc_block-1, i*ecc_block)) >> ecc_block
614    }
615    if (ecc_info._4 != 0) {
616      val ecc_unaligned = eccCode.encode(data(data.getWidth-1, ecc_info._3*ecc_block)) >> ecc_info._4
617      ecc := Cat(ecc_unaligned, ecc_slices.asUInt())
618    } else { ecc := ecc_slices.asUInt() }
619  }
620
621  def decode(): Bool = {
622    val data = entries.asUInt()
623    val res = Wire(Vec(ecc_info._3 + 1, Bool()))
624    for (i <- 0 until ecc_info._3) {
625      res(i) := eccCode.decode(Cat(ecc((i+1)*ecc_info._2-1, i*ecc_info._2), data((i+1)*ecc_block-1, i*ecc_block))).error
626    }
627    if (ecc_info._4 != 0) {
628      res(ecc_info._3) := eccCode.decode(
629        Cat(ecc(ecc_info._1-1, ecc_info._2*ecc_info._3), data(data.getWidth-1, ecc_info._3*ecc_block))).error
630    } else { res(ecc_info._3) := false.B }
631
632    Cat(res).orR
633  }
634
635  def gen(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
636    this.entries := entries.genEntries(vpn, asid, data, levelUInt, prefetch)
637    this.encode()
638  }
639
640  override def cloneType: this.type = new PTWEntriesWithEcc(eccCode, num, tagLen, level, hasPerm).asInstanceOf[this.type]
641}
642
643class PtwReq(implicit p: Parameters) extends PtwBundle {
644  val vpn = UInt(vpnLen.W)
645
646  override def toPrintable: Printable = {
647    p"vpn:0x${Hexadecimal(vpn)}"
648  }
649}
650
651class PtwResp(implicit p: Parameters) extends PtwBundle {
652  val entry = new PtwEntry(tagLen = vpnLen, hasPerm = true, hasLevel = true)
653  val pf = Bool()
654  val af = Bool()
655
656
657  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, asid: UInt) = {
658    this.entry.level.map(_ := level)
659    this.entry.tag := vpn
660    this.entry.perm.map(_ := pte.getPerm())
661    this.entry.ppn := pte.ppn
662    this.entry.prefetch := DontCare
663    this.entry.asid := asid
664    this.pf := pf
665    this.af := af
666  }
667
668  override def toPrintable: Printable = {
669    p"entry:${entry} pf:${pf} af:${af}"
670  }
671}
672
673class PtwIO(implicit p: Parameters) extends PtwBundle {
674  val tlb = Vec(PtwWidth, Flipped(new TlbPtwIO))
675  val sfence = Input(new SfenceBundle)
676  val csr = new Bundle {
677    val tlb = Input(new TlbCsrBundle)
678    val distribute_csr = Flipped(new DistributedCSRIO)
679  }
680  val perfEvents      = Output(new PerfEventsBundle(numPCntPtw))
681}
682
683class L2TlbMemReqBundle(implicit p: Parameters) extends PtwBundle {
684  val addr = UInt(PAddrBits.W)
685  val id = UInt(bMemID.W)
686}
687
688class L2TlbInnerBundle(implicit p: Parameters) extends PtwReq {
689  val source = UInt(bSourceWidth.W)
690}
691