xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/MMUBundle.scala (revision 1545277abc67bbe5123a324f0b61142535bfe61f)
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(vpn: UInt) : UInt = {
218    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
230  override def toPrintable: Printable = {
231    val inner_level = level.getOrElse(2.U)
232    p"asid: ${asid} level:${inner_level} vpn:${Hexadecimal(tag)} ppn:${Hexadecimal(ppn)} perm:${perm}"
233  }
234
235  override def cloneType: this.type = (new TlbEntry(pageNormal, pageSuper)).asInstanceOf[this.type]
236}
237
238object TlbCmd {
239  def read  = "b00".U
240  def write = "b01".U
241  def exec  = "b10".U
242
243  def atom_read  = "b100".U // lr
244  def atom_write = "b101".U // sc / amo
245
246  def apply() = UInt(3.W)
247  def isRead(a: UInt) = a(1,0)===read
248  def isWrite(a: UInt) = a(1,0)===write
249  def isExec(a: UInt) = a(1,0)===exec
250
251  def isAtom(a: UInt) = a(2)
252  def isAmo(a: UInt) = a===atom_write // NOTE: sc mixed
253}
254
255class TlbStorageIO(nSets: Int, nWays: Int, ports: Int)(implicit p: Parameters) extends MMUIOBaseBundle {
256  val r = new Bundle {
257    val req = Vec(ports, Flipped(DecoupledIO(new Bundle {
258      val vpn = Output(UInt(vpnLen.W))
259    })))
260    val resp = Vec(ports, ValidIO(new Bundle{
261      val hit = Output(Bool())
262      val ppn = Output(UInt(ppnLen.W))
263      val perm = Output(new TlbPermBundle())
264    }))
265    val resp_hit_sameCycle = Output(Vec(ports, Bool())) // req hit or not same cycle with req
266  }
267  val w = Flipped(ValidIO(new Bundle {
268    val wayIdx = Output(UInt(log2Up(nWays).W))
269    val data = Output(new PtwResp)
270  }))
271  val victim = new Bundle {
272    val out = ValidIO(Output(new Bundle {
273      val entry = new TlbEntry(pageNormal = true, pageSuper = false)
274    }))
275    val in = Flipped(ValidIO(Output(new Bundle {
276      val entry = new TlbEntry(pageNormal = true, pageSuper = false)
277    })))
278  }
279  val access = Vec(ports, new ReplaceAccessBundle(nSets, nWays))
280
281  def r_req_apply(valid: Bool, vpn: UInt, asid: UInt, i: Int): Unit = {
282    this.r.req(i).valid := valid
283    this.r.req(i).bits.vpn := vpn
284  }
285
286  def r_resp_apply(i: Int) = {
287    (this.r.resp_hit_sameCycle(i), this.r.resp(i).bits.hit, this.r.resp(i).bits.ppn, this.r.resp(i).bits.perm)
288  }
289
290  def w_apply(valid: Bool, wayIdx: UInt, data: PtwResp): Unit = {
291    this.w.valid := valid
292    this.w.bits.wayIdx := wayIdx
293    this.w.bits.data := data
294  }
295
296  override def cloneType: this.type = new TlbStorageIO(nSets, nWays, ports).asInstanceOf[this.type]
297}
298
299class ReplaceAccessBundle(nSets: Int, nWays: Int)(implicit p: Parameters) extends TlbBundle {
300  val sets = Output(UInt(log2Up(nSets).W))
301  val touch_ways = ValidIO(Output(UInt(log2Up(nWays).W)))
302
303  override def cloneType: this.type =new ReplaceAccessBundle(nSets, nWays).asInstanceOf[this.type]
304}
305
306class ReplaceIO(Width: Int, nSets: Int, nWays: Int)(implicit p: Parameters) extends TlbBundle {
307  val access = Vec(Width, Flipped(new ReplaceAccessBundle(nSets, nWays)))
308
309  val refillIdx = Output(UInt(log2Up(nWays).W))
310  val chosen_set = Flipped(Output(UInt(log2Up(nSets).W)))
311
312  def apply_sep(in: Seq[ReplaceIO], vpn: UInt): Unit = {
313    for (i <- 0 until Width) {
314      this.access(i) := in(i).access(0)
315      this.chosen_set := get_set_idx(vpn, nSets)
316      in(i).refillIdx := this.refillIdx
317    }
318  }
319}
320
321class TlbReplaceIO(Width: Int, q: TLBParameters)(implicit p: Parameters) extends
322  TlbBundle {
323  val normalPage = new ReplaceIO(Width, q.normalNSets, q.normalNWays)
324  val superPage = new ReplaceIO(Width, q.superNSets, q.superNWays)
325
326  def apply_sep(in: Seq[TlbReplaceIO], vpn: UInt) = {
327    this.normalPage.apply_sep(in.map(_.normalPage), vpn)
328    this.superPage.apply_sep(in.map(_.superPage), vpn)
329  }
330
331  override def cloneType = (new TlbReplaceIO(Width, q)).asInstanceOf[this.type]
332}
333
334class TlbReq(implicit p: Parameters) extends TlbBundle {
335  val vaddr = Output(UInt(VAddrBits.W))
336  val cmd = Output(TlbCmd())
337  val size = Output(UInt(log2Ceil(log2Ceil(XLEN/8)+1).W))
338  val robIdx = Output(new RobPtr)
339  val debug = new Bundle {
340    val pc = Output(UInt(XLEN.W))
341    val isFirstIssue = Output(Bool())
342  }
343
344  override def toPrintable: Printable = {
345    p"vaddr:0x${Hexadecimal(vaddr)} cmd:${cmd} pc:0x${Hexadecimal(debug.pc)} robIdx:${robIdx}"
346  }
347}
348
349class TlbExceptionBundle(implicit p: Parameters) extends TlbBundle {
350  val ld = Output(Bool())
351  val st = Output(Bool())
352  val instr = Output(Bool())
353}
354
355class TlbResp(implicit p: Parameters) extends TlbBundle {
356  val paddr = Output(UInt(PAddrBits.W))
357  val miss = Output(Bool())
358  val excp = new Bundle {
359    val pf = new TlbExceptionBundle()
360    val af = new TlbExceptionBundle()
361  }
362  val ptwBack = Output(Bool()) // when ptw back, wake up replay rs's state
363
364  override def toPrintable: Printable = {
365    p"paddr:0x${Hexadecimal(paddr)} miss:${miss} excp.pf: ld:${excp.pf.ld} st:${excp.pf.st} instr:${excp.pf.instr} ptwBack:${ptwBack}"
366  }
367}
368
369class TlbRequestIO()(implicit p: Parameters) extends TlbBundle {
370  val req = DecoupledIO(new TlbReq)
371  val resp = Flipped(DecoupledIO(new TlbResp))
372}
373
374class BlockTlbRequestIO()(implicit p: Parameters) extends TlbBundle {
375  val req = DecoupledIO(new TlbReq)
376  val resp = Flipped(DecoupledIO(new TlbResp))
377}
378
379class TlbPtwIO(Width: Int = 1)(implicit p: Parameters) extends TlbBundle {
380  val req = Vec(Width, DecoupledIO(new PtwReq))
381  val resp = Flipped(DecoupledIO(new PtwResp))
382
383  override def cloneType: this.type = (new TlbPtwIO(Width)).asInstanceOf[this.type]
384
385  override def toPrintable: Printable = {
386    p"req(0):${req(0).valid} ${req(0).ready} ${req(0).bits} | resp:${resp.valid} ${resp.ready} ${resp.bits}"
387  }
388}
389
390class MMUIOBaseBundle(implicit p: Parameters) extends TlbBundle {
391  val sfence = Input(new SfenceBundle)
392  val csr = Input(new TlbCsrBundle)
393}
394
395class TlbIO(Width: Int, q: TLBParameters)(implicit p: Parameters) extends
396  MMUIOBaseBundle {
397  val requestor = Vec(Width, Flipped(new TlbRequestIO))
398  val ptw = new TlbPtwIO(Width)
399  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(Width, q)) else null
400  val pmp = Vec(Width, ValidIO(new PMPReqBundle()))
401
402  override def cloneType: this.type = (new TlbIO(Width, q)).asInstanceOf[this.type]
403}
404
405class BTlbPtwIO(Width: Int)(implicit p: Parameters) extends TlbBundle {
406  val req = Vec(Width, DecoupledIO(new PtwReq))
407  val resp = Flipped(DecoupledIO(new Bundle {
408    val data = new PtwResp
409    val vector = Output(Vec(Width, Bool()))
410  }))
411
412  override def cloneType: this.type = (new BTlbPtwIO(Width)).asInstanceOf[this.type]
413}
414/****************************  Bridge TLB *******************************/
415
416class BridgeTLBIO(Width: Int)(implicit p: Parameters) extends MMUIOBaseBundle {
417  val requestor = Vec(Width, Flipped(new TlbPtwIO()))
418  val ptw = new BTlbPtwIO(Width)
419
420  override def cloneType: this.type = (new BridgeTLBIO(Width)).asInstanceOf[this.type]
421}
422
423
424/****************************  PTW  *************************************/
425abstract class PtwBundle(implicit p: Parameters) extends XSBundle with HasPtwConst
426abstract class PtwModule(outer: PTW) extends LazyModuleImp(outer)
427  with HasXSParameter with HasPtwConst
428
429class PteBundle(implicit p: Parameters) extends PtwBundle{
430  val reserved  = UInt(pteResLen.W)
431  val ppn  = UInt(ppnLen.W)
432  val rsw  = UInt(2.W)
433  val perm = new Bundle {
434    val d    = Bool()
435    val a    = Bool()
436    val g    = Bool()
437    val u    = Bool()
438    val x    = Bool()
439    val w    = Bool()
440    val r    = Bool()
441    val v    = Bool()
442  }
443
444  def unaligned(level: UInt) = {
445    isLeaf() && !(level === 2.U ||
446                  level === 1.U && ppn(vpnnLen-1,   0) === 0.U ||
447                  level === 0.U && ppn(vpnnLen*2-1, 0) === 0.U)
448  }
449
450  def isPf(level: UInt) = {
451    !perm.v || (!perm.r && perm.w) || unaligned(level)
452  }
453
454  def isLeaf() = {
455    perm.r || perm.x || perm.w
456  }
457
458  def getPerm() = {
459    val pm = Wire(new PtePermBundle)
460    pm.d := perm.d
461    pm.a := perm.a
462    pm.g := perm.g
463    pm.u := perm.u
464    pm.x := perm.x
465    pm.w := perm.w
466    pm.r := perm.r
467    pm
468  }
469
470  override def toPrintable: Printable = {
471    p"ppn:0x${Hexadecimal(ppn)} perm:b${Binary(perm.asUInt)}"
472  }
473}
474
475class PtwEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwBundle {
476  val tag = UInt(tagLen.W)
477  val asid = UInt(asidLen.W)
478  val ppn = UInt(ppnLen.W)
479  val perm = if (hasPerm) Some(new PtePermBundle) else None
480  val level = if (hasLevel) Some(UInt(log2Up(Level).W)) else None
481  val prefetch = Bool()
482
483  def hit(vpn: UInt, asid: UInt, allType: Boolean = false, ignoreAsid: Boolean = false) = {
484    require(vpn.getWidth == vpnLen)
485    require(this.asid.getWidth <= asid.getWidth)
486    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
487    if (allType) {
488      require(hasLevel)
489      val hit0 = tag(tagLen - 1,    vpnnLen*2) === vpn(tagLen - 1, vpnnLen*2)
490      val hit1 = tag(vpnnLen*2 - 1, vpnnLen)   === vpn(vpnnLen*2 - 1,  vpnnLen)
491      val hit2 = tag(vpnnLen - 1,     0)         === vpn(vpnnLen - 1, 0)
492
493      asid_hit && Mux(level.getOrElse(0.U) === 2.U, hit2 && hit1 && hit0, Mux(level.getOrElse(0.U) === 1.U, hit1 && hit0, hit0))
494    } else if (hasLevel) {
495      val hit0 = tag(tagLen - 1, tagLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
496      val hit1 = tag(tagLen - vpnnLen - 1, tagLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
497
498      asid_hit && Mux(level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1)
499    } else {
500      asid_hit && tag === vpn(vpnLen - 1, vpnLen - tagLen)
501    }
502  }
503
504  def refill(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool) {
505    require(this.asid.getWidth <= asid.getWidth) // maybe equal is better, but ugly outside
506
507    tag := vpn(vpnLen - 1, vpnLen - tagLen)
508    ppn := pte.asTypeOf(new PteBundle().cloneType).ppn
509    perm.map(_ := pte.asTypeOf(new PteBundle().cloneType).perm)
510    this.asid := asid
511    this.prefetch := prefetch
512    this.level.map(_ := level)
513  }
514
515  def genPtwEntry(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool) = {
516    val e = Wire(new PtwEntry(tagLen, hasPerm, hasLevel))
517    e.refill(vpn, asid, pte, level, prefetch)
518    e
519  }
520
521  override def cloneType: this.type = (new PtwEntry(tagLen, hasPerm, hasLevel)).asInstanceOf[this.type]
522
523  override def toPrintable: Printable = {
524    // p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} perm:${perm}"
525    p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} " +
526      (if (hasPerm) p"perm:${perm.getOrElse(0.U.asTypeOf(new PtePermBundle))} " else p"") +
527      (if (hasLevel) p"level:${level.getOrElse(0.U)}" else p"") +
528      p"prefetch:${prefetch}"
529  }
530}
531
532class PtwEntries(num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
533  require(log2Up(num)==log2Down(num))
534
535  val tag  = UInt(tagLen.W)
536  val asid = UInt(asidLen.W)
537  val ppns = Vec(num, UInt(ppnLen.W))
538  val vs   = Vec(num, Bool())
539  val perms = if (hasPerm) Some(Vec(num, new PtePermBundle)) else None
540  val prefetch = Bool()
541  // println(s"PtwEntries: tag:1*${tagLen} ppns:${num}*${ppnLen} vs:${num}*1")
542
543  def tagClip(vpn: UInt) = {
544    require(vpn.getWidth == vpnLen)
545    vpn(vpnLen - 1, vpnLen - tagLen)
546  }
547
548  def sectorIdxClip(vpn: UInt, level: Int) = {
549    getVpnClip(vpn, level)(log2Up(num) - 1, 0)
550  }
551
552  def hit(vpn: UInt, asid: UInt, ignoreAsid: Boolean = false) = {
553    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
554    asid_hit && tag === tagClip(vpn) && vs(sectorIdxClip(vpn, level)) // TODO: optimize this. don't need to compare each with tag
555  }
556
557  def genEntries(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
558    require((data.getWidth / XLEN) == num,
559      s"input data length must be multiple of pte length: data.length:${data.getWidth} num:${num}")
560
561    val ps = Wire(new PtwEntries(num, tagLen, level, hasPerm))
562    ps.tag := tagClip(vpn)
563    ps.asid := asid
564    ps.prefetch := prefetch
565    for (i <- 0 until num) {
566      val pte = data((i+1)*XLEN-1, i*XLEN).asTypeOf(new PteBundle)
567      ps.ppns(i) := pte.ppn
568      ps.vs(i)   := !pte.isPf(levelUInt) && (if (hasPerm) pte.isLeaf() else !pte.isLeaf())
569      ps.perms.map(_(i) := pte.perm)
570    }
571    ps
572  }
573
574  override def cloneType: this.type = (new PtwEntries(num, tagLen, level, hasPerm)).asInstanceOf[this.type]
575  override def toPrintable: Printable = {
576    // require(num == 4, "if num is not 4, please comment this toPrintable")
577    // NOTE: if num is not 4, please comment this toPrintable
578    val permsInner = perms.getOrElse(0.U.asTypeOf(Vec(num, new PtePermBundle)))
579    p"asid: ${Hexadecimal(asid)} tag:0x${Hexadecimal(tag)} ppns:${printVec(ppns)} vs:${Binary(vs.asUInt)} " +
580      (if (hasPerm) p"perms:${printVec(permsInner)}" else p"")
581  }
582}
583
584class PTWEntriesWithEcc(eccCode: Code, num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
585  val entries = new PtwEntries(num, tagLen, level, hasPerm)
586
587  val ecc_block = XLEN
588  val ecc_info = get_ecc_info()
589  val ecc = UInt(ecc_info._1.W)
590
591  def get_ecc_info(): (Int, Int, Int, Int) = {
592    val eccBits_per = eccCode.width(ecc_block) - ecc_block
593
594    val data_length = entries.getWidth
595    val data_align_num = data_length / ecc_block
596    val data_not_align = (data_length % ecc_block) != 0 // ugly code
597    val data_unalign_length = data_length - data_align_num * ecc_block
598    val eccBits_unalign = eccCode.width(data_unalign_length) - data_unalign_length
599
600    val eccBits = eccBits_per * data_align_num + eccBits_unalign
601    (eccBits, eccBits_per, data_align_num, data_unalign_length)
602  }
603
604  def encode() = {
605    val data = entries.asUInt()
606    val ecc_slices = Wire(Vec(ecc_info._3, UInt(ecc_info._2.W)))
607    for (i <- 0 until ecc_info._3) {
608      ecc_slices(i) := eccCode.encode(data((i+1)*ecc_block-1, i*ecc_block)) >> ecc_block
609    }
610    if (ecc_info._4 != 0) {
611      val ecc_unaligned = eccCode.encode(data(data.getWidth-1, ecc_info._3*ecc_block)) >> ecc_info._4
612      ecc := Cat(ecc_unaligned, ecc_slices.asUInt())
613    } else { ecc := ecc_slices.asUInt() }
614  }
615
616  def decode(): Bool = {
617    val data = entries.asUInt()
618    val res = Wire(Vec(ecc_info._3 + 1, Bool()))
619    for (i <- 0 until ecc_info._3) {
620      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
621    }
622    if (ecc_info._4 != 0) {
623      res(ecc_info._3) := eccCode.decode(
624        Cat(ecc(ecc_info._1-1, ecc_info._2*ecc_info._3), data(data.getWidth-1, ecc_info._3*ecc_block))).error
625    } else { res(ecc_info._3) := false.B }
626
627    Cat(res).orR
628  }
629
630  def gen(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
631    this.entries := entries.genEntries(vpn, asid, data, levelUInt, prefetch)
632    this.encode()
633  }
634
635  override def cloneType: this.type = new PTWEntriesWithEcc(eccCode, num, tagLen, level, hasPerm).asInstanceOf[this.type]
636}
637
638class PtwReq(implicit p: Parameters) extends PtwBundle {
639  val vpn = UInt(vpnLen.W)
640
641  override def toPrintable: Printable = {
642    p"vpn:0x${Hexadecimal(vpn)}"
643  }
644}
645
646class PtwResp(implicit p: Parameters) extends PtwBundle {
647  val entry = new PtwEntry(tagLen = vpnLen, hasPerm = true, hasLevel = true)
648  val pf = Bool()
649  val af = Bool()
650
651
652  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, asid: UInt) = {
653    this.entry.level.map(_ := level)
654    this.entry.tag := vpn
655    this.entry.perm.map(_ := pte.getPerm())
656    this.entry.ppn := pte.ppn
657    this.entry.prefetch := DontCare
658    this.entry.asid := asid
659    this.pf := pf
660    this.af := af
661  }
662
663  override def toPrintable: Printable = {
664    p"entry:${entry} pf:${pf} af:${af}"
665  }
666}
667
668class PtwIO(implicit p: Parameters) extends PtwBundle {
669  val tlb = Vec(PtwWidth, Flipped(new TlbPtwIO))
670  val sfence = Input(new SfenceBundle)
671  val csr = new Bundle {
672    val tlb = Input(new TlbCsrBundle)
673    val distribute_csr = Flipped(new DistributedCSRIO)
674  }
675  val perfEvents      = Output(new PerfEventsBundle(numPCntPtw))
676}
677
678class L2TlbMemReqBundle(implicit p: Parameters) extends PtwBundle {
679  val addr = UInt(PAddrBits.W)
680  val id = UInt(bMemID.W)
681}
682
683class L2TlbInnerBundle(implicit p: Parameters) extends PtwReq {
684  val source = UInt(bSourceWidth.W)
685}
686