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