xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/MMUBundle.scala (revision d1fe0262af06443a68a6b9a8190eb017fdd74ca2)
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
116  def hit(vpn: UInt): Bool = {
117    val a = tag(vpnnLen*3-1, vpnnLen*2) === vpn(vpnnLen*3-1, vpnnLen*2)
118    val b = tag(vpnnLen*2-1, vpnnLen*1) === vpn(vpnnLen*2-1, vpnnLen*1)
119    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")
120    Mux(level.asBool, a&b, a)
121  }
122
123  def apply(vpn: UInt, level: UInt) = {
124    this.tag := vpn
125    this.level := level(0)
126
127    this
128  }
129
130}
131
132class TlbData(superpage: Boolean = false)(implicit p: Parameters) extends TlbBundle {
133  val level = if(superpage) Some(UInt(1.W)) else None // /*2 for 4KB,*/ 1 for 2MB, 0 for 1GB
134  val ppn = UInt(ppnLen.W)
135  val perm = new TlbPermBundle
136
137  def genPPN(vpn: UInt): UInt = {
138    if (superpage) {
139      val insideLevel = level.getOrElse(0.U)
140      Mux(insideLevel.asBool, Cat(ppn(ppn.getWidth-1, vpnnLen*1), vpn(vpnnLen*1-1, 0)),
141                              Cat(ppn(ppn.getWidth-1, vpnnLen*2), vpn(vpnnLen*2-1, 0)))
142    } else {
143      ppn
144    }
145  }
146
147  def apply(ppn: UInt, level: UInt, perm: UInt, pf: Bool, af: Bool) = {
148    this.level.map(_ := level(0))
149    this.ppn := ppn
150    // refill pagetable perm
151    val ptePerm = perm.asTypeOf(new PtePermBundle)
152    this.perm.pf:= pf
153    this.perm.af:= af
154    this.perm.d := ptePerm.d
155    this.perm.a := ptePerm.a
156    this.perm.g := ptePerm.g
157    this.perm.u := ptePerm.u
158    this.perm.x := ptePerm.x
159    this.perm.w := ptePerm.w
160    this.perm.r := ptePerm.r
161
162    // get pma perm
163    val (pmaMode, accessWidth) = AddressSpace.memmapAddrMatch(Cat(ppn, 0.U(12.W)))
164    this.perm.pr := PMAMode.read(pmaMode)
165    this.perm.pw := PMAMode.write(pmaMode)
166    this.perm.pe := PMAMode.execute(pmaMode)
167    this.perm.pa := PMAMode.atomic(pmaMode)
168    this.perm.pi := PMAMode.icache(pmaMode)
169    this.perm.pd := PMAMode.dcache(pmaMode)
170
171    this
172  }
173
174  override def toPrintable: Printable = {
175    val insideLevel = level.getOrElse(0.U)
176    p"level:${insideLevel} ppn:${Hexadecimal(ppn)} perm:${perm}"
177  }
178
179  override def cloneType: this.type = (new TlbData(superpage)).asInstanceOf[this.type]
180}
181
182class TlbEntry(pageNormal: Boolean, pageSuper: Boolean)(implicit p: Parameters) extends TlbBundle {
183  require(pageNormal || pageSuper)
184
185  val tag = if (!pageNormal) UInt((vpnLen - vpnnLen).W)
186            else UInt(vpnLen.W)
187  val level = if (!pageNormal) Some(UInt(1.W))
188              else if (!pageSuper) None
189              else Some(UInt(2.W))
190  val ppn = if (!pageNormal) UInt((ppnLen - vpnnLen).W)
191            else UInt(ppnLen.W)
192  val perm = new TlbPermBundle
193
194  def hit(vpn: UInt): Bool = {
195    if (!pageSuper) vpn === tag
196    else if (!pageNormal) MuxLookup(level.get, false.B, Seq(
197      0.U -> (tag(vpnnLen*2-1, vpnnLen) === vpn(vpnLen-1, vpnnLen*2)),
198      1.U -> (tag === vpn(vpnLen-1, vpnnLen)),
199    ))
200    else MuxLookup(level.get, false.B, Seq(
201      0.U -> (tag(vpnLen-1, vpnnLen*2) === vpn(vpnLen-1, vpnnLen*2)),
202      1.U -> (tag(vpnLen-1, vpnnLen) === vpn(vpnLen-1, vpnnLen)),
203      2.U -> (tag === vpn) // if pageNormal is false, this will always be false
204    ))
205  }
206
207  def apply(item: PtwResp): TlbEntry = {
208    this.tag := {if (pageNormal) item.entry.tag else item.entry.tag(vpnLen-1, vpnnLen)}
209    val inner_level = item.entry.level.getOrElse(0.U)
210    this.level.map(_ := { if (pageNormal && pageSuper) inner_level
211                          else if (pageSuper) inner_level(0)
212                          else 0.U})
213    this.ppn := { if (!pageNormal) item.entry.ppn(ppnLen-1, vpnnLen)
214                  else item.entry.ppn }
215    val ptePerm = item.entry.perm.get.asTypeOf(new PtePermBundle().cloneType)
216    this.perm.pf := item.pf
217    this.perm.af := item.af
218    this.perm.d := ptePerm.d
219    this.perm.a := ptePerm.a
220    this.perm.g := ptePerm.g
221    this.perm.u := ptePerm.u
222    this.perm.x := ptePerm.x
223    this.perm.w := ptePerm.w
224    this.perm.r := ptePerm.r
225
226    // get pma perm
227    val (pmaMode, accessWidth) = AddressSpace.memmapAddrMatch(Cat(item.entry.ppn, 0.U(12.W)))
228    this.perm.pr := PMAMode.read(pmaMode)
229    this.perm.pw := PMAMode.write(pmaMode)
230    this.perm.pe := PMAMode.execute(pmaMode)
231    this.perm.pa := PMAMode.atomic(pmaMode)
232    this.perm.pi := PMAMode.icache(pmaMode)
233    this.perm.pd := PMAMode.dcache(pmaMode)
234
235    this
236  }
237
238  def genPPN(vpn: UInt) : UInt = {
239    if (!pageSuper) ppn
240    else if (!pageNormal) MuxLookup(level.get, 0.U, Seq(
241      0.U -> Cat(ppn(ppn.getWidth-1, vpnnLen), vpn(vpnnLen*2-1, 0)),
242      1.U -> Cat(ppn, vpn(vpnnLen-1, 0))
243    ))
244    else MuxLookup(level.get, 0.U, Seq(
245      0.U -> Cat(ppn(ppn.getWidth-1, vpnnLen*2), vpn(vpnnLen*2-1, 0)),
246      1.U -> Cat(ppn(ppn.getWidth-1, vpnnLen), vpn(vpnnLen-1, 0)),
247      2.U -> ppn
248    ))
249  }
250
251  override def toPrintable: Printable = {
252    val inner_level = level.getOrElse(2.U)
253    p"level:${inner_level} vpn:${Hexadecimal(tag)} ppn:${Hexadecimal(ppn)} perm:${perm}"
254  }
255
256  override def cloneType: this.type = (new TlbEntry(pageNormal, pageSuper)).asInstanceOf[this.type]
257}
258
259object TlbCmd {
260  def read  = "b00".U
261  def write = "b01".U
262  def exec  = "b10".U
263
264  def atom_read  = "b100".U // lr
265  def atom_write = "b101".U // sc / amo
266
267  def apply() = UInt(3.W)
268  def isRead(a: UInt) = a(1,0)===read
269  def isWrite(a: UInt) = a(1,0)===write
270  def isExec(a: UInt) = a(1,0)===exec
271
272  def isAtom(a: UInt) = a(2)
273}
274
275class TlbStorageIO(nSets: Int, nWays: Int, ports: Int)(implicit p: Parameters) extends  TlbBundle {
276  val r = new Bundle {
277    val req = Vec(ports, Flipped(DecoupledIO(new Bundle {
278      val vpn = Output(UInt(vpnLen.W))
279    })))
280    val resp = Vec(ports, ValidIO(new Bundle{
281      val hit = Output(Bool())
282      val ppn = Output(UInt(ppnLen.W))
283      val perm = Output(new TlbPermBundle())
284      val hitVec = Output(UInt(nWays.W))
285    }))
286  }
287  val w = Flipped(ValidIO(new Bundle {
288    val wayIdx = Output(UInt(log2Up(nWays).W))
289    val data = Output(new PtwResp)
290  }))
291  val victim = new Bundle {
292    val out = ValidIO(Output(new TlbEntry(pageNormal = true, pageSuper = false)))
293    val in = Flipped(ValidIO(Output(new TlbEntry(pageNormal = true, pageSuper = false))))
294  }
295  val sfence = Input(new SfenceBundle())
296
297  def r_req_apply(valid: Bool, vpn: UInt, i: Int): Unit = {
298    this.r.req(i).valid := valid
299    this.r.req(i).bits.vpn := vpn
300  }
301
302  def r_resp_apply(i: Int) = {
303    (this.r.resp(i).bits.hit, this.r.resp(i).bits.ppn, this.r.resp(i).bits.perm, this.r.resp(i).bits.hitVec)
304  }
305
306  def w_apply(valid: Bool, wayIdx: UInt, data: PtwResp): Unit = {
307    this.w.valid := valid
308    this.w.bits.wayIdx := wayIdx
309    this.w.bits.data := data
310  }
311
312  override def cloneType: this.type = new TlbStorageIO(nSets, nWays, ports).asInstanceOf[this.type]
313}
314
315class ReplaceIO(Width: Int, nSets: Int, nWays: Int)(implicit p: Parameters) extends TlbBundle {
316  val access = Flipped(new Bundle {
317    val sets = Output(Vec(Width, UInt(log2Up(nSets).W)))
318    val touch_ways = Vec(Width, ValidIO(Output(UInt(log2Up(nWays).W))))
319  })
320
321  val refillIdx = Output(UInt(log2Up(nWays).W))
322  val chosen_set = Flipped(Output(UInt(log2Up(nSets).W)))
323
324  def apply_sep(in: Seq[ReplaceIO], vpn: UInt): Unit = {
325    for (i <- 0 until Width) {
326      this.access.sets(i) := in(i).access.sets(0)
327      this.access.touch_ways(i) := in(i).access.touch_ways(0)
328      this.chosen_set := get_idx(vpn, nSets)
329      in(i).refillIdx := this.refillIdx
330    }
331  }
332}
333
334class TlbReplaceIO(Width: Int, q: TLBParameters)(implicit p: Parameters) extends
335  TlbBundle {
336  val normalPage = new ReplaceIO(Width, q.normalNSets, q.normalNWays)
337  val superPage = new ReplaceIO(Width, q.superNSets, q.superNWays)
338
339  def apply_sep(in: Seq[TlbReplaceIO], vpn: UInt) = {
340    this.normalPage.apply_sep(in.map(_.normalPage), vpn)
341    this.superPage.apply_sep(in.map(_.superPage), vpn)
342  }
343
344  override def cloneType = (new TlbReplaceIO(Width, q)).asInstanceOf[this.type]
345}
346
347class TlbReq(implicit p: Parameters) extends TlbBundle {
348  val vaddr = UInt(VAddrBits.W)
349  val cmd = TlbCmd()
350  val size = UInt(log2Ceil(log2Ceil(XLEN/8)+1).W)
351  val robIdx = new RobPtr
352  val debug = new Bundle {
353    val pc = UInt(XLEN.W)
354    val isFirstIssue = Bool()
355  }
356
357  override def toPrintable: Printable = {
358    p"vaddr:0x${Hexadecimal(vaddr)} cmd:${cmd} pc:0x${Hexadecimal(debug.pc)} robIdx:${robIdx}"
359  }
360}
361
362class TlbExceptionBundle(implicit p: Parameters) extends TlbBundle {
363  val ld = Output(Bool())
364  val st = Output(Bool())
365  val instr = Output(Bool())
366}
367
368class TlbResp(implicit p: Parameters) extends TlbBundle {
369  val paddr = UInt(PAddrBits.W)
370  val miss = Bool()
371  val mmio = Bool()
372  val excp = new Bundle {
373    val pf = new TlbExceptionBundle()
374    val af = new TlbExceptionBundle()
375  }
376  val ptwBack = Bool() // when ptw back, wake up replay rs's state
377
378  override def toPrintable: Printable = {
379    p"paddr:0x${Hexadecimal(paddr)} miss:${miss} excp.pf: ld:${excp.pf.ld} st:${excp.pf.st} instr:${excp.pf.instr} ptwBack:${ptwBack}"
380  }
381}
382
383class TlbRequestIO()(implicit p: Parameters) extends TlbBundle {
384  val req = DecoupledIO(new TlbReq)
385  val resp = Flipped(DecoupledIO(new TlbResp))
386}
387
388class BlockTlbRequestIO()(implicit p: Parameters) extends TlbBundle {
389  val req = DecoupledIO(new TlbReq)
390  val resp = Flipped(DecoupledIO(new TlbResp))
391}
392
393class TlbPtwIO(Width: Int = 1)(implicit p: Parameters) extends TlbBundle {
394  val req = Vec(Width, DecoupledIO(new PtwReq))
395  val resp = Flipped(DecoupledIO(new PtwResp))
396
397  override def cloneType: this.type = (new TlbPtwIO(Width)).asInstanceOf[this.type]
398
399  override def toPrintable: Printable = {
400    p"req(0):${req(0).valid} ${req(0).ready} ${req(0).bits} | resp:${resp.valid} ${resp.ready} ${resp.bits}"
401  }
402}
403
404class TlbBaseBundle(implicit p: Parameters) extends TlbBundle {
405  val sfence = Input(new SfenceBundle)
406  val csr = Input(new TlbCsrBundle)
407}
408
409class TlbIO(Width: Int, q: TLBParameters)(implicit p: Parameters) extends
410  TlbBaseBundle {
411  val requestor = Vec(Width, Flipped(new TlbRequestIO))
412  val ptw = new TlbPtwIO(Width)
413  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(Width, q)) else null
414  val pmp = Vec(Width, ValidIO(new PMPReqBundle()))
415
416  override def cloneType: this.type = (new TlbIO(Width, q)).asInstanceOf[this.type]
417}
418
419class BTlbPtwIO(Width: Int)(implicit p: Parameters) extends TlbBundle {
420  val req = Vec(Width, DecoupledIO(new PtwReq))
421  val resp = Flipped(DecoupledIO(new Bundle {
422    val data = new PtwResp
423    val vector = Output(Vec(Width, Bool()))
424  }))
425
426  override def cloneType: this.type = (new BTlbPtwIO(Width)).asInstanceOf[this.type]
427}
428/****************************  Bridge TLB *******************************/
429
430class BridgeTLBIO(Width: Int)(implicit p: Parameters) extends TlbBaseBundle {
431  val requestor = Vec(Width, Flipped(new TlbPtwIO()))
432  val ptw = new BTlbPtwIO(Width)
433
434  override def cloneType: this.type = (new BridgeTLBIO(Width)).asInstanceOf[this.type]
435}
436
437
438/****************************  PTW  *************************************/
439abstract class PtwBundle(implicit p: Parameters) extends XSBundle with HasPtwConst
440abstract class PtwModule(outer: PTW) extends LazyModuleImp(outer)
441  with HasXSParameter with HasPtwConst
442
443class PteBundle(implicit p: Parameters) extends PtwBundle{
444  val reserved  = UInt(pteResLen.W)
445  val ppn  = UInt(ppnLen.W)
446  val rsw  = UInt(2.W)
447  val perm = new Bundle {
448    val d    = Bool()
449    val a    = Bool()
450    val g    = Bool()
451    val u    = Bool()
452    val x    = Bool()
453    val w    = Bool()
454    val r    = Bool()
455    val v    = Bool()
456  }
457
458  def unaligned(level: UInt) = {
459    isLeaf() && !(level === 2.U ||
460                  level === 1.U && ppn(vpnnLen-1,   0) === 0.U ||
461                  level === 0.U && ppn(vpnnLen*2-1, 0) === 0.U)
462  }
463
464  def isPf(level: UInt) = {
465    !perm.v || (!perm.r && perm.w) || unaligned(level)
466  }
467
468  def isLeaf() = {
469    perm.r || perm.x || perm.w
470  }
471
472  def getPerm() = {
473    val pm = Wire(new PtePermBundle)
474    pm.d := perm.d
475    pm.a := perm.a
476    pm.g := perm.g
477    pm.u := perm.u
478    pm.x := perm.x
479    pm.w := perm.w
480    pm.r := perm.r
481    pm
482  }
483
484  override def toPrintable: Printable = {
485    p"ppn:0x${Hexadecimal(ppn)} perm:b${Binary(perm.asUInt)}"
486  }
487}
488
489class PtwEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwBundle {
490  val tag = UInt(tagLen.W)
491  val ppn = UInt(ppnLen.W)
492  val perm = if (hasPerm) Some(new PtePermBundle) else None
493  val level = if (hasLevel) Some(UInt(log2Up(Level).W)) else None
494  val prefetch = Bool()
495
496  def hit(vpn: UInt, allType: Boolean = false) = {
497    require(vpn.getWidth == vpnLen)
498    if (allType) {
499      require(hasLevel)
500      val hit0 = tag(tagLen - 1,    vpnnLen*2) === vpn(tagLen - 1, vpnnLen*2)
501      val hit1 = tag(vpnnLen*2 - 1, vpnnLen)   === vpn(vpnnLen*2 - 1,  vpnnLen)
502      val hit2 = tag(vpnnLen - 1,     0)         === vpn(vpnnLen - 1, 0)
503      Mux(level.getOrElse(0.U) === 2.U, hit2 && hit1 && hit0, Mux(level.getOrElse(0.U) === 1.U, hit1 && hit0, hit0))
504    } else if (hasLevel) {
505      val hit0 = tag(tagLen - 1, tagLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
506      val hit1 = tag(tagLen - vpnnLen - 1, tagLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
507      Mux(level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1)
508    } else {
509      tag === vpn(vpnLen - 1, vpnLen - tagLen)
510    }
511  }
512
513  def refill(vpn: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool) {
514    tag := vpn(vpnLen - 1, vpnLen - tagLen)
515    ppn := pte.asTypeOf(new PteBundle().cloneType).ppn
516    perm.map(_ := pte.asTypeOf(new PteBundle().cloneType).perm)
517    this.prefetch := prefetch
518    this.level.map(_ := level)
519  }
520
521  def genPtwEntry(vpn: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool) = {
522    val e = Wire(new PtwEntry(tagLen, hasPerm, hasLevel))
523    e.refill(vpn, pte, level, prefetch)
524    e
525  }
526
527  override def cloneType: this.type = (new PtwEntry(tagLen, hasPerm, hasLevel)).asInstanceOf[this.type]
528
529  override def toPrintable: Printable = {
530    // p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} perm:${perm}"
531    p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} " +
532      (if (hasPerm) p"perm:${perm.getOrElse(0.U.asTypeOf(new PtePermBundle))} " else p"") +
533      (if (hasLevel) p"level:${level.getOrElse(0.U)}" else p"") +
534      p"prefetch:${prefetch}"
535  }
536}
537
538class PtwEntries(num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
539  require(log2Up(num)==log2Down(num))
540
541  val tag  = UInt(tagLen.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) = {
558    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, 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.prefetch := prefetch
568    for (i <- 0 until num) {
569      val pte = data((i+1)*XLEN-1, i*XLEN).asTypeOf(new PteBundle)
570      ps.ppns(i) := pte.ppn
571      ps.vs(i)   := !pte.isPf(levelUInt) && (if (hasPerm) pte.isLeaf() else !pte.isLeaf())
572      ps.perms.map(_(i) := pte.perm)
573    }
574    ps
575  }
576
577  override def cloneType: this.type = (new PtwEntries(num, tagLen, level, hasPerm)).asInstanceOf[this.type]
578  override def toPrintable: Printable = {
579    // require(num == 4, "if num is not 4, please comment this toPrintable")
580    // NOTE: if num is not 4, please comment this toPrintable
581    val permsInner = perms.getOrElse(0.U.asTypeOf(Vec(num, new PtePermBundle)))
582    p"tag:0x${Hexadecimal(tag)} ppns:${printVec(ppns)} vs:${Binary(vs.asUInt)} " +
583      (if (hasPerm) p"perms:${printVec(permsInner)}" else p"")
584  }
585}
586
587class PTWEntriesWithEcc(eccCode: Code, num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
588  val entries = new PtwEntries(num, tagLen, level, hasPerm)
589
590  private val encBits = eccCode.width(entries.getWidth)
591  private val eccBits = encBits - entries.getWidth
592  val ecc = UInt(eccBits.W)
593
594  override def cloneType: this.type = new PTWEntriesWithEcc(eccCode, num, tagLen, level, hasPerm).asInstanceOf[this.type]
595}
596
597class PtwReq(implicit p: Parameters) extends PtwBundle {
598  val vpn = UInt(vpnLen.W)
599
600  override def toPrintable: Printable = {
601    p"vpn:0x${Hexadecimal(vpn)}"
602  }
603}
604
605class PtwResp(implicit p: Parameters) extends PtwBundle {
606  val entry = new PtwEntry(tagLen = vpnLen, hasPerm = true, hasLevel = true)
607  val pf = Bool()
608  val af = Bool()
609
610  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt) = {
611    this.entry.level.map(_ := level)
612    this.entry.tag := vpn
613    this.entry.perm.map(_ := pte.getPerm())
614    this.entry.ppn := pte.ppn
615    this.entry.prefetch := DontCare
616    this.pf := pf
617    this.af := af
618  }
619
620  override def toPrintable: Printable = {
621    p"entry:${entry} pf:${pf} af:${af}"
622  }
623}
624
625class PtwIO(implicit p: Parameters) extends PtwBundle {
626  val tlb = Vec(PtwWidth, Flipped(new TlbPtwIO))
627  val sfence = Input(new SfenceBundle)
628  val csr = new Bundle {
629    val tlb = Input(new TlbCsrBundle)
630    val distribute_csr = Flipped(new DistributedCSRIO)
631  }
632}
633
634class L2TlbMemReqBundle(implicit p: Parameters) extends PtwBundle {
635  val addr = UInt(PAddrBits.W)
636  val id = UInt(bMemID.W)
637}
638