xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/MMUBundle.scala (revision 066ac8a465b27b54ba22458ff1a67bcd28215d73)
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 excp = new Bundle {
363    val pf = new TlbExceptionBundle()
364    val af = new TlbExceptionBundle()
365  }
366  val ptwBack = Output(Bool()) // when ptw back, wake up replay rs's state
367
368  override def toPrintable: Printable = {
369    p"paddr:0x${Hexadecimal(paddr)} miss:${miss} excp.pf: ld:${excp.pf.ld} st:${excp.pf.st} instr:${excp.pf.instr} ptwBack:${ptwBack}"
370  }
371}
372
373class TlbRequestIO()(implicit p: Parameters) extends TlbBundle {
374  val req = DecoupledIO(new TlbReq)
375  val resp = Flipped(DecoupledIO(new TlbResp))
376}
377
378class BlockTlbRequestIO()(implicit p: Parameters) extends TlbBundle {
379  val req = DecoupledIO(new TlbReq)
380  val resp = Flipped(DecoupledIO(new TlbResp))
381}
382
383class TlbPtwIO(Width: Int = 1)(implicit p: Parameters) extends TlbBundle {
384  val req = Vec(Width, DecoupledIO(new PtwReq))
385  val resp = Flipped(DecoupledIO(new PtwResp))
386
387  override def cloneType: this.type = (new TlbPtwIO(Width)).asInstanceOf[this.type]
388
389  override def toPrintable: Printable = {
390    p"req(0):${req(0).valid} ${req(0).ready} ${req(0).bits} | resp:${resp.valid} ${resp.ready} ${resp.bits}"
391  }
392}
393
394class MMUIOBaseBundle(implicit p: Parameters) extends TlbBundle {
395  val sfence = Input(new SfenceBundle)
396  val csr = Input(new TlbCsrBundle)
397}
398
399class TlbIO(Width: Int, q: TLBParameters)(implicit p: Parameters) extends
400  MMUIOBaseBundle {
401  val requestor = Vec(Width, Flipped(new TlbRequestIO))
402  val ptw = new TlbPtwIO(Width)
403  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(Width, q)) else null
404  val pmp = Vec(Width, ValidIO(new PMPReqBundle()))
405
406  override def cloneType: this.type = (new TlbIO(Width, q)).asInstanceOf[this.type]
407}
408
409class BTlbPtwIO(Width: Int)(implicit p: Parameters) extends TlbBundle {
410  val req = Vec(Width, DecoupledIO(new PtwReq))
411  val resp = Flipped(DecoupledIO(new Bundle {
412    val data = new PtwResp
413    val vector = Output(Vec(Width, Bool()))
414  }))
415
416  override def cloneType: this.type = (new BTlbPtwIO(Width)).asInstanceOf[this.type]
417}
418/****************************  Bridge TLB *******************************/
419
420class BridgeTLBIO(Width: Int)(implicit p: Parameters) extends MMUIOBaseBundle {
421  val requestor = Vec(Width, Flipped(new TlbPtwIO()))
422  val ptw = new BTlbPtwIO(Width)
423
424  override def cloneType: this.type = (new BridgeTLBIO(Width)).asInstanceOf[this.type]
425}
426
427
428/****************************  PTW  *************************************/
429abstract class PtwBundle(implicit p: Parameters) extends XSBundle with HasPtwConst
430abstract class PtwModule(outer: PTW) extends LazyModuleImp(outer)
431  with HasXSParameter with HasPtwConst
432
433class PteBundle(implicit p: Parameters) extends PtwBundle{
434  val reserved  = UInt(pteResLen.W)
435  val ppn  = UInt(ppnLen.W)
436  val rsw  = UInt(2.W)
437  val perm = new Bundle {
438    val d    = Bool()
439    val a    = Bool()
440    val g    = Bool()
441    val u    = Bool()
442    val x    = Bool()
443    val w    = Bool()
444    val r    = Bool()
445    val v    = Bool()
446  }
447
448  def unaligned(level: UInt) = {
449    isLeaf() && !(level === 2.U ||
450                  level === 1.U && ppn(vpnnLen-1,   0) === 0.U ||
451                  level === 0.U && ppn(vpnnLen*2-1, 0) === 0.U)
452  }
453
454  def isPf(level: UInt) = {
455    !perm.v || (!perm.r && perm.w) || unaligned(level)
456  }
457
458  def isLeaf() = {
459    perm.r || perm.x || perm.w
460  }
461
462  def getPerm() = {
463    val pm = Wire(new PtePermBundle)
464    pm.d := perm.d
465    pm.a := perm.a
466    pm.g := perm.g
467    pm.u := perm.u
468    pm.x := perm.x
469    pm.w := perm.w
470    pm.r := perm.r
471    pm
472  }
473
474  override def toPrintable: Printable = {
475    p"ppn:0x${Hexadecimal(ppn)} perm:b${Binary(perm.asUInt)}"
476  }
477}
478
479class PtwEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwBundle {
480  val tag = UInt(tagLen.W)
481  val asid = UInt(asidLen.W)
482  val ppn = UInt(ppnLen.W)
483  val perm = if (hasPerm) Some(new PtePermBundle) else None
484  val level = if (hasLevel) Some(UInt(log2Up(Level).W)) else None
485  val prefetch = Bool()
486
487  def hit(vpn: UInt, asid: UInt, allType: Boolean = false, ignoreAsid: Boolean = false) = {
488    require(vpn.getWidth == vpnLen)
489    require(this.asid.getWidth <= asid.getWidth)
490    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
491    if (allType) {
492      require(hasLevel)
493      val hit0 = tag(tagLen - 1,    vpnnLen*2) === vpn(tagLen - 1, vpnnLen*2)
494      val hit1 = tag(vpnnLen*2 - 1, vpnnLen)   === vpn(vpnnLen*2 - 1,  vpnnLen)
495      val hit2 = tag(vpnnLen - 1,     0)         === vpn(vpnnLen - 1, 0)
496
497      asid_hit && Mux(level.getOrElse(0.U) === 2.U, hit2 && hit1 && hit0, Mux(level.getOrElse(0.U) === 1.U, hit1 && hit0, hit0))
498    } else if (hasLevel) {
499      val hit0 = tag(tagLen - 1, tagLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
500      val hit1 = tag(tagLen - vpnnLen - 1, tagLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
501
502      asid_hit && Mux(level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1)
503    } else {
504      asid_hit && tag === vpn(vpnLen - 1, vpnLen - tagLen)
505    }
506  }
507
508  def refill(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool) {
509    require(this.asid.getWidth <= asid.getWidth) // maybe equal is better, but ugly outside
510
511    tag := vpn(vpnLen - 1, vpnLen - tagLen)
512    ppn := pte.asTypeOf(new PteBundle().cloneType).ppn
513    perm.map(_ := pte.asTypeOf(new PteBundle().cloneType).perm)
514    this.asid := asid
515    this.prefetch := prefetch
516    this.level.map(_ := level)
517  }
518
519  def genPtwEntry(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool) = {
520    val e = Wire(new PtwEntry(tagLen, hasPerm, hasLevel))
521    e.refill(vpn, asid, pte, level, prefetch)
522    e
523  }
524
525  override def cloneType: this.type = (new PtwEntry(tagLen, hasPerm, hasLevel)).asInstanceOf[this.type]
526
527  override def toPrintable: Printable = {
528    // p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} perm:${perm}"
529    p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} " +
530      (if (hasPerm) p"perm:${perm.getOrElse(0.U.asTypeOf(new PtePermBundle))} " else p"") +
531      (if (hasLevel) p"level:${level.getOrElse(0.U)}" else p"") +
532      p"prefetch:${prefetch}"
533  }
534}
535
536class PtwEntries(num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
537  require(log2Up(num)==log2Down(num))
538
539  val tag  = UInt(tagLen.W)
540  val asid = UInt(asidLen.W)
541  val ppns = Vec(num, UInt(ppnLen.W))
542  val vs   = Vec(num, Bool())
543  val perms = if (hasPerm) Some(Vec(num, new PtePermBundle)) else None
544  val prefetch = Bool()
545  // println(s"PtwEntries: tag:1*${tagLen} ppns:${num}*${ppnLen} vs:${num}*1")
546
547  def tagClip(vpn: UInt) = {
548    require(vpn.getWidth == vpnLen)
549    vpn(vpnLen - 1, vpnLen - tagLen)
550  }
551
552  def sectorIdxClip(vpn: UInt, level: Int) = {
553    getVpnClip(vpn, level)(log2Up(num) - 1, 0)
554  }
555
556  def hit(vpn: UInt, asid: UInt, ignoreAsid: Boolean = false) = {
557    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
558    asid_hit && tag === tagClip(vpn) && vs(sectorIdxClip(vpn, level)) // TODO: optimize this. don't need to compare each with tag
559  }
560
561  def genEntries(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
562    require((data.getWidth / XLEN) == num,
563      s"input data length must be multiple of pte length: data.length:${data.getWidth} num:${num}")
564
565    val ps = Wire(new PtwEntries(num, tagLen, level, hasPerm))
566    ps.tag := tagClip(vpn)
567    ps.asid := asid
568    ps.prefetch := prefetch
569    for (i <- 0 until num) {
570      val pte = data((i+1)*XLEN-1, i*XLEN).asTypeOf(new PteBundle)
571      ps.ppns(i) := pte.ppn
572      ps.vs(i)   := !pte.isPf(levelUInt) && (if (hasPerm) pte.isLeaf() else !pte.isLeaf())
573      ps.perms.map(_(i) := pte.perm)
574    }
575    ps
576  }
577
578  override def cloneType: this.type = (new PtwEntries(num, tagLen, level, hasPerm)).asInstanceOf[this.type]
579  override def toPrintable: Printable = {
580    // require(num == 4, "if num is not 4, please comment this toPrintable")
581    // NOTE: if num is not 4, please comment this toPrintable
582    val permsInner = perms.getOrElse(0.U.asTypeOf(Vec(num, new PtePermBundle)))
583    p"asid: ${Hexadecimal(asid)} tag:0x${Hexadecimal(tag)} ppns:${printVec(ppns)} vs:${Binary(vs.asUInt)} " +
584      (if (hasPerm) p"perms:${printVec(permsInner)}" else p"")
585  }
586}
587
588class PTWEntriesWithEcc(eccCode: Code, num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
589  val entries = new PtwEntries(num, tagLen, level, hasPerm)
590
591  val ecc_block = XLEN
592  val ecc_info = get_ecc_info()
593  val ecc = UInt(ecc_info._1.W)
594
595  def get_ecc_info(): (Int, Int, Int, Int) = {
596    val eccBits_per = eccCode.width(ecc_block) - ecc_block
597
598    val data_length = entries.getWidth
599    val data_align_num = data_length / ecc_block
600    val data_not_align = (data_length % ecc_block) != 0 // ugly code
601    val data_unalign_length = data_length - data_align_num * ecc_block
602    val eccBits_unalign = eccCode.width(data_unalign_length) - data_unalign_length
603
604    val eccBits = eccBits_per * data_align_num + eccBits_unalign
605    (eccBits, eccBits_per, data_align_num, data_unalign_length)
606  }
607
608  def encode() = {
609    val data = entries.asUInt()
610    val ecc_slices = Wire(Vec(ecc_info._3, UInt(ecc_info._2.W)))
611    for (i <- 0 until ecc_info._3) {
612      ecc_slices(i) := eccCode.encode(data((i+1)*ecc_block-1, i*ecc_block)) >> ecc_block
613    }
614    if (ecc_info._4 != 0) {
615      val ecc_unaligned = eccCode.encode(data(data.getWidth-1, ecc_info._3*ecc_block)) >> ecc_info._4
616      ecc := Cat(ecc_unaligned, ecc_slices.asUInt())
617    } else { ecc := ecc_slices.asUInt() }
618  }
619
620  def decode(): Bool = {
621    val data = entries.asUInt()
622    val res = Wire(Vec(ecc_info._3 + 1, Bool()))
623    for (i <- 0 until ecc_info._3) {
624      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
625    }
626    if (ecc_info._4 != 0) {
627      res(ecc_info._3) := eccCode.decode(
628        Cat(ecc(ecc_info._1-1, ecc_info._2*ecc_info._3), data(data.getWidth-1, ecc_info._3*ecc_block))).error
629    } else { res(ecc_info._3) := false.B }
630
631    Cat(res).orR
632  }
633
634  def gen(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
635    this.entries := entries.genEntries(vpn, asid, data, levelUInt, prefetch)
636    this.encode()
637  }
638
639  override def cloneType: this.type = new PTWEntriesWithEcc(eccCode, num, tagLen, level, hasPerm).asInstanceOf[this.type]
640}
641
642class PtwReq(implicit p: Parameters) extends PtwBundle {
643  val vpn = UInt(vpnLen.W)
644
645  override def toPrintable: Printable = {
646    p"vpn:0x${Hexadecimal(vpn)}"
647  }
648}
649
650class PtwResp(implicit p: Parameters) extends PtwBundle {
651  val entry = new PtwEntry(tagLen = vpnLen, hasPerm = true, hasLevel = true)
652  val pf = Bool()
653  val af = Bool()
654
655
656  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, asid: UInt) = {
657    this.entry.level.map(_ := level)
658    this.entry.tag := vpn
659    this.entry.perm.map(_ := pte.getPerm())
660    this.entry.ppn := pte.ppn
661    this.entry.prefetch := DontCare
662    this.entry.asid := asid
663    this.pf := pf
664    this.af := af
665  }
666
667  override def toPrintable: Printable = {
668    p"entry:${entry} pf:${pf} af:${af}"
669  }
670}
671
672class PtwIO(implicit p: Parameters) extends PtwBundle {
673  val tlb = Vec(PtwWidth, Flipped(new TlbPtwIO))
674  val sfence = Input(new SfenceBundle)
675  val csr = new Bundle {
676    val tlb = Input(new TlbCsrBundle)
677    val distribute_csr = Flipped(new DistributedCSRIO)
678  }
679  val perfEvents      = Output(new PerfEventsBundle(numPCntPtw))
680}
681
682class L2TlbMemReqBundle(implicit p: Parameters) extends PtwBundle {
683  val addr = UInt(PAddrBits.W)
684  val id = UInt(bMemID.W)
685}
686
687class L2TlbInnerBundle(implicit p: Parameters) extends PtwReq {
688  val source = UInt(bSourceWidth.W)
689}
690