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