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