xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/MMUBundle.scala (revision 9473e04d5cab97eaf63add958b2392eec3d876a2)
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 utility._
25import xiangshan.backend.rob.RobPtr
26import xiangshan.backend.fu.util.HasCSRConst
27import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
28import freechips.rocketchip.tilelink._
29import xiangshan.backend.fu.{PMPReqBundle, PMPConfig}
30import xiangshan.backend.fu.PMPBundle
31
32
33abstract class TlbBundle(implicit p: Parameters) extends XSBundle with HasTlbConst
34abstract class TlbModule(implicit p: Parameters) extends XSModule with HasTlbConst
35
36class VaBundle(implicit p: Parameters) extends TlbBundle {
37  val vpn  = UInt(vpnLen.W)
38  val off  = UInt(offLen.W)
39}
40
41class PtePermBundle(implicit p: Parameters) extends TlbBundle {
42  val d = Bool()
43  val a = Bool()
44  val g = Bool()
45  val u = Bool()
46  val x = Bool()
47  val w = Bool()
48  val r = Bool()
49
50  override def toPrintable: Printable = {
51    p"d:${d} a:${a} g:${g} u:${u} x:${x} w:${w} r:${r}"// +
52    //(if(hasV) (p"v:${v}") else p"")
53  }
54}
55
56class TlbPMBundle(implicit p: Parameters) extends TlbBundle {
57  val r = Bool()
58  val w = Bool()
59  val x = Bool()
60  val c = Bool()
61  val atomic = Bool()
62
63  def assign_ap(pm: PMPConfig) = {
64    r := pm.r
65    w := pm.w
66    x := pm.x
67    c := pm.c
68    atomic := pm.atomic
69  }
70}
71
72class TlbPermBundle(implicit p: Parameters) extends TlbBundle {
73  val pf = Bool() // NOTE: if this is true, just raise pf
74  val af = Bool() // NOTE: if this is true, just raise af
75  // pagetable perm (software defined)
76  val d = Bool()
77  val a = Bool()
78  val g = Bool()
79  val u = Bool()
80  val x = Bool()
81  val w = Bool()
82  val r = Bool()
83
84  val pm = new TlbPMBundle
85
86  def apply(item: PtwResp, pm: PMPConfig) = {
87    val ptePerm = item.entry.perm.get.asTypeOf(new PtePermBundle().cloneType)
88    this.pf := item.pf
89    this.af := item.af
90    this.d := ptePerm.d
91    this.a := ptePerm.a
92    this.g := ptePerm.g
93    this.u := ptePerm.u
94    this.x := ptePerm.x
95    this.w := ptePerm.w
96    this.r := ptePerm.r
97
98    this.pm.assign_ap(pm)
99    this
100  }
101  override def toPrintable: Printable = {
102    p"pf:${pf} af:${af} d:${d} a:${a} g:${g} u:${u} x:${x} w:${w} r:${r} " +
103    p"pm:${pm}"
104  }
105}
106
107// multi-read && single-write
108// input is data, output is hot-code(not one-hot)
109class CAMTemplate[T <: Data](val gen: T, val set: Int, val readWidth: Int)(implicit p: Parameters) extends TlbModule {
110  val io = IO(new Bundle {
111    val r = new Bundle {
112      val req = Input(Vec(readWidth, gen))
113      val resp = Output(Vec(readWidth, Vec(set, Bool())))
114    }
115    val w = Input(new Bundle {
116      val valid = Bool()
117      val bits = new Bundle {
118        val index = UInt(log2Up(set).W)
119        val data = gen
120      }
121    })
122  })
123
124  val wordType = UInt(gen.getWidth.W)
125  val array = Reg(Vec(set, wordType))
126
127  io.r.resp.zipWithIndex.map{ case (a,i) =>
128    a := array.map(io.r.req(i).asUInt === _)
129  }
130
131  when (io.w.valid) {
132    array(io.w.bits.index) := io.w.bits.data.asUInt
133  }
134}
135
136class TlbEntry(pageNormal: Boolean, pageSuper: Boolean)(implicit p: Parameters) extends TlbBundle {
137  require(pageNormal || pageSuper)
138
139  val tag = if (!pageNormal) UInt((vpnLen - vpnnLen).W)
140            else UInt(vpnLen.W)
141  val asid = UInt(asidLen.W)
142  val level = if (!pageNormal) Some(UInt(1.W))
143              else if (!pageSuper) None
144              else Some(UInt(2.W))
145  val ppn = if (!pageNormal) UInt((ppnLen - vpnnLen).W)
146            else UInt(ppnLen.W)
147  val perm = new TlbPermBundle
148
149  /** level usage:
150   *  !PageSuper: page is only normal, level is None, match all the tag
151   *  !PageNormal: page is only super, level is a Bool(), match high 9*2 parts
152   *  bits0  0: need mid 9bits
153   *         1: no need mid 9bits
154   *  PageSuper && PageNormal: page hold all the three type,
155   *  bits0  0: need low 9bits
156   *  bits1  0: need mid 9bits
157   */
158
159  def hit(vpn: UInt, asid: UInt, nSets: Int = 1, ignoreAsid: Boolean = false): Bool = {
160    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
161
162    // NOTE: for timing, dont care low set index bits at hit check
163    //       do not need store the low bits actually
164    if (!pageSuper) asid_hit && drop_set_equal(vpn, tag, nSets)
165    else if (!pageNormal) {
166      val tag_match_hi = tag(vpnnLen*2-1, vpnnLen) === vpn(vpnnLen*3-1, vpnnLen*2)
167      val tag_match_mi = tag(vpnnLen-1, 0) === vpn(vpnnLen*2-1, vpnnLen)
168      val tag_match = tag_match_hi && (level.get.asBool() || tag_match_mi)
169      asid_hit && tag_match
170    }
171    else {
172      val tmp_level = level.get
173      val tag_match_hi = tag(vpnnLen*3-1, vpnnLen*2) === vpn(vpnnLen*3-1, vpnnLen*2)
174      val tag_match_mi = tag(vpnnLen*2-1, vpnnLen) === vpn(vpnnLen*2-1, vpnnLen)
175      val tag_match_lo = tag(vpnnLen-1, 0) === vpn(vpnnLen-1, 0) // if pageNormal is false, this will always be false
176      val tag_match = tag_match_hi && (tmp_level(1) || tag_match_mi) && (tmp_level(0) || tag_match_lo)
177      asid_hit && tag_match
178    }
179  }
180
181  def apply(item: PtwResp, asid: UInt, pm: PMPConfig): TlbEntry = {
182    this.tag := {if (pageNormal) item.entry.tag else item.entry.tag(vpnLen-1, vpnnLen)}
183    this.asid := asid
184    val inner_level = item.entry.level.getOrElse(0.U)
185    this.level.map(_ := { if (pageNormal && pageSuper) MuxLookup(inner_level, 0.U, Seq(
186                                                        0.U -> 3.U,
187                                                        1.U -> 1.U,
188                                                        2.U -> 0.U ))
189                          else if (pageSuper) ~inner_level(0)
190                          else 0.U })
191    this.ppn := { if (!pageNormal) item.entry.ppn(ppnLen-1, vpnnLen)
192                  else item.entry.ppn }
193    this.perm.apply(item, pm)
194    this
195  }
196
197  // 4KB is normal entry, 2MB/1GB is considered as super entry
198  def is_normalentry(): Bool = {
199    if (!pageSuper) { true.B }
200    else if (!pageNormal) { false.B }
201    else { level.get === 0.U }
202  }
203
204  def genPPN(saveLevel: Boolean = false, valid: Bool = false.B)(vpn: UInt) : UInt = {
205    val inner_level = level.getOrElse(0.U)
206    val ppn_res = if (!pageSuper) ppn
207      else if (!pageNormal) Cat(ppn(ppnLen-vpnnLen-1, vpnnLen),
208        Mux(inner_level(0), vpn(vpnnLen*2-1, vpnnLen), ppn(vpnnLen-1,0)),
209        vpn(vpnnLen-1, 0))
210      else Cat(ppn(ppnLen-1, vpnnLen*2),
211        Mux(inner_level(1), vpn(vpnnLen*2-1, vpnnLen), ppn(vpnnLen*2-1, vpnnLen)),
212        Mux(inner_level(0), vpn(vpnnLen-1, 0), ppn(vpnnLen-1, 0)))
213
214    if (saveLevel) Cat(ppn(ppn.getWidth-1, vpnnLen*2), RegEnable(ppn_res(vpnnLen*2-1, 0), valid))
215    else ppn_res
216  }
217
218  override def toPrintable: Printable = {
219    val inner_level = level.getOrElse(2.U)
220    p"asid: ${asid} level:${inner_level} vpn:${Hexadecimal(tag)} ppn:${Hexadecimal(ppn)} perm:${perm}"
221  }
222
223}
224
225object TlbCmd {
226  def read  = "b00".U
227  def write = "b01".U
228  def exec  = "b10".U
229
230  def atom_read  = "b100".U // lr
231  def atom_write = "b101".U // sc / amo
232
233  def apply() = UInt(3.W)
234  def isRead(a: UInt) = a(1,0)===read
235  def isWrite(a: UInt) = a(1,0)===write
236  def isExec(a: UInt) = a(1,0)===exec
237
238  def isAtom(a: UInt) = a(2)
239  def isAmo(a: UInt) = a===atom_write // NOTE: sc mixed
240}
241
242class TlbStorageIO(nSets: Int, nWays: Int, ports: Int, nDups: Int = 1)(implicit p: Parameters) extends MMUIOBaseBundle {
243  val r = new Bundle {
244    val req = Vec(ports, Flipped(DecoupledIO(new Bundle {
245      val vpn = Output(UInt(vpnLen.W))
246    })))
247    val resp = Vec(ports, ValidIO(new Bundle{
248      val hit = Output(Bool())
249      val ppn = Vec(nDups, Output(UInt(ppnLen.W)))
250      val perm = Vec(nDups, Output(new TlbPermBundle()))
251    }))
252  }
253  val w = Flipped(ValidIO(new Bundle {
254    val wayIdx = Output(UInt(log2Up(nWays).W))
255    val data = Output(new PtwResp)
256    val data_replenish = Output(new PMPConfig)
257  }))
258  val victim = new Bundle {
259    val out = ValidIO(Output(new Bundle {
260      val entry = new TlbEntry(pageNormal = true, pageSuper = false)
261    }))
262    val in = Flipped(ValidIO(Output(new Bundle {
263      val entry = new TlbEntry(pageNormal = true, pageSuper = false)
264    })))
265  }
266  val access = Vec(ports, new ReplaceAccessBundle(nSets, nWays))
267
268  def r_req_apply(valid: Bool, vpn: UInt, i: Int): Unit = {
269    this.r.req(i).valid := valid
270    this.r.req(i).bits.vpn := vpn
271  }
272
273  def r_resp_apply(i: Int) = {
274    (this.r.resp(i).bits.hit, this.r.resp(i).bits.ppn, this.r.resp(i).bits.perm)
275  }
276
277  def w_apply(valid: Bool, wayIdx: UInt, data: PtwResp, data_replenish: PMPConfig): Unit = {
278    this.w.valid := valid
279    this.w.bits.wayIdx := wayIdx
280    this.w.bits.data := data
281    this.w.bits.data_replenish := data_replenish
282  }
283
284}
285
286class TlbStorageWrapperIO(ports: Int, q: TLBParameters, nDups: Int = 1)(implicit p: Parameters) extends MMUIOBaseBundle {
287  val r = new Bundle {
288    val req = Vec(ports, Flipped(DecoupledIO(new Bundle {
289      val vpn = Output(UInt(vpnLen.W))
290    })))
291    val resp = Vec(ports, ValidIO(new Bundle{
292      val hit = Output(Bool())
293      val ppn = Vec(nDups, Output(UInt(ppnLen.W)))
294      val perm = Vec(nDups, Output(new TlbPermBundle()))
295      // below are dirty code for timing optimization
296      val super_hit = Output(Bool())
297      val super_ppn = Output(UInt(ppnLen.W))
298      val spm = Output(new TlbPMBundle)
299    }))
300  }
301  val w = Flipped(ValidIO(new Bundle {
302    val data = Output(new PtwResp)
303    val data_replenish = Output(new PMPConfig)
304  }))
305  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(ports, q)) else null
306
307  def r_req_apply(valid: Bool, vpn: UInt, i: Int): Unit = {
308    this.r.req(i).valid := valid
309    this.r.req(i).bits.vpn := vpn
310  }
311
312  def r_resp_apply(i: Int) = {
313    (this.r.resp(i).bits.hit, this.r.resp(i).bits.ppn, this.r.resp(i).bits.perm,
314    this.r.resp(i).bits.super_hit, this.r.resp(i).bits.super_ppn, this.r.resp(i).bits.spm)
315  }
316
317  def w_apply(valid: Bool, data: PtwResp, data_replenish: PMPConfig): Unit = {
318    this.w.valid := valid
319    this.w.bits.data := data
320    this.w.bits.data_replenish := data_replenish
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 ((ac_rep, ac_tlb) <- access.zip(in.map(a => a.access.map(b => b)).flatten)) {
338      ac_rep := ac_tlb
339    }
340    this.chosen_set := get_set_idx(vpn, nSets)
341    in.map(a => a.refillIdx := this.refillIdx)
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 MemBlockidxBundle(implicit p: Parameters) extends TlbBundle {
358  val is_ld = Bool()
359  val is_st = Bool()
360  val idx =
361    if (LoadQueueSize >= StoreQueueSize) {
362      val idx = UInt(log2Ceil(LoadQueueSize).W)
363      idx
364    } else {
365      val idx = UInt(log2Ceil(StoreQueueSize).W)
366      idx
367    }
368}
369
370class TlbReq(implicit p: Parameters) extends TlbBundle {
371  val vaddr = Output(UInt(VAddrBits.W))
372  val cmd = Output(TlbCmd())
373  val size = Output(UInt(log2Ceil(log2Ceil(XLEN/8)+1).W))
374  val kill = Output(Bool()) // Use for blocked tlb that need sync with other module like icache
375  val memidx = Output(new MemBlockidxBundle)
376  // do not translate, but still do pmp/pma check
377  val no_translate = Output(Bool())
378  val debug = new Bundle {
379    val pc = Output(UInt(XLEN.W))
380    val robIdx = Output(new RobPtr)
381    val isFirstIssue = Output(Bool())
382  }
383
384  // Maybe Block req needs a kill: for itlb, itlb and icache may not sync, itlb should wait icache to go ahead
385  override def toPrintable: Printable = {
386    p"vaddr:0x${Hexadecimal(vaddr)} cmd:${cmd} kill:${kill} pc:0x${Hexadecimal(debug.pc)} robIdx:${debug.robIdx}"
387  }
388}
389
390class TlbExceptionBundle(implicit p: Parameters) extends TlbBundle {
391  val ld = Output(Bool())
392  val st = Output(Bool())
393  val instr = Output(Bool())
394}
395
396class TlbResp(nDups: Int = 1)(implicit p: Parameters) extends TlbBundle {
397  val paddr = Vec(nDups, Output(UInt(PAddrBits.W)))
398  val miss = Output(Bool())
399  val fast_miss = Output(Bool()) // without sram part for timing optimization
400  val excp = Vec(nDups, new Bundle {
401    val pf = new TlbExceptionBundle()
402    val af = new TlbExceptionBundle()
403  })
404  val static_pm = Output(Valid(Bool())) // valid for static, bits for mmio result from normal entries
405  val ptwBack = Output(Bool()) // when ptw back, wake up replay rs's state
406  val memidx = Output(new MemBlockidxBundle)
407
408  val debug = new Bundle {
409    val robIdx = Output(new RobPtr)
410    val isFirstIssue = Output(Bool())
411  }
412  override def toPrintable: Printable = {
413    p"paddr:0x${Hexadecimal(paddr(0))} miss:${miss} excp.pf: ld:${excp(0).pf.ld} st:${excp(0).pf.st} instr:${excp(0).pf.instr} ptwBack:${ptwBack}"
414  }
415}
416
417class TlbRequestIO(nRespDups: Int = 1)(implicit p: Parameters) extends TlbBundle {
418  val req = DecoupledIO(new TlbReq)
419  val req_kill = Output(Bool())
420  val resp = Flipped(DecoupledIO(new TlbResp(nRespDups)))
421}
422
423class TlbPtwIO(Width: Int = 1)(implicit p: Parameters) extends TlbBundle {
424  val req = Vec(Width, DecoupledIO(new PtwReq))
425  val resp = Flipped(DecoupledIO(new PtwResp))
426
427
428  override def toPrintable: Printable = {
429    p"req(0):${req(0).valid} ${req(0).ready} ${req(0).bits} | resp:${resp.valid} ${resp.ready} ${resp.bits}"
430  }
431}
432
433class TlbPtwIOwithMemIdx(Width: Int = 1)(implicit p: Parameters) extends TlbBundle {
434  val req = Vec(Width, DecoupledIO(new PtwReqwithMemIdx))
435  val resp = Flipped(DecoupledIO(new PtwRespwithMemIdx))
436
437
438  override def toPrintable: Printable = {
439    p"req(0):${req(0).valid} ${req(0).ready} ${req(0).bits} | resp:${resp.valid} ${resp.ready} ${resp.bits}"
440  }
441}
442
443class MMUIOBaseBundle(implicit p: Parameters) extends TlbBundle {
444  val sfence = Input(new SfenceBundle)
445  val csr = Input(new TlbCsrBundle)
446
447  def base_connect(sfence: SfenceBundle, csr: TlbCsrBundle): Unit = {
448    this.sfence <> sfence
449    this.csr <> csr
450  }
451
452  // overwrite satp. write satp will cause flushpipe but csr.priv won't
453  // satp will be dealyed several cycles from writing, but csr.priv won't
454  // so inside mmu, these two signals should be divided
455  def base_connect(sfence: SfenceBundle, csr: TlbCsrBundle, satp: TlbSatpBundle) = {
456    this.sfence <> sfence
457    this.csr <> csr
458    this.csr.satp := satp
459  }
460}
461
462class TlbRefilltoMemIO()(implicit p: Parameters) extends TlbBundle {
463  val valid = Bool()
464  val memidx = new MemBlockidxBundle
465}
466
467class TlbIO(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends
468  MMUIOBaseBundle {
469  val requestor = Vec(Width, Flipped(new TlbRequestIO(nRespDups)))
470  val flushPipe = Vec(Width, Input(Bool()))
471  val ptw = new TlbPtwIOwithMemIdx(Width)
472  val refill_to_mem = Output(new TlbRefilltoMemIO())
473  val ptw_replenish = Input(new PMPConfig())
474  val replace = if (q.outReplace) Flipped(new TlbReplaceIO(Width, q)) else null
475  val pmp = Vec(Width, ValidIO(new PMPReqBundle()))
476
477}
478
479class VectorTlbPtwIO(Width: Int)(implicit p: Parameters) extends TlbBundle {
480  val req = Vec(Width, DecoupledIO(new PtwReqwithMemIdx()))
481  val resp = Flipped(DecoupledIO(new Bundle {
482    val data = new PtwRespwithMemIdx
483    val vector = Output(Vec(Width, Bool()))
484  }))
485
486  def connect(normal: TlbPtwIOwithMemIdx): Unit = {
487    req <> normal.req
488    resp.ready := normal.resp.ready
489    normal.resp.bits := resp.bits.data
490    normal.resp.valid := resp.valid
491  }
492}
493
494/****************************  L2TLB  *************************************/
495abstract class PtwBundle(implicit p: Parameters) extends XSBundle with HasPtwConst
496abstract class PtwModule(outer: L2TLB) extends LazyModuleImp(outer)
497  with HasXSParameter with HasPtwConst
498
499class PteBundle(implicit p: Parameters) extends PtwBundle{
500  val reserved  = UInt(pteResLen.W)
501  val ppn_high = UInt(ppnHignLen.W)
502  val ppn  = UInt(ppnLen.W)
503  val rsw  = UInt(2.W)
504  val perm = new Bundle {
505    val d    = Bool()
506    val a    = Bool()
507    val g    = Bool()
508    val u    = Bool()
509    val x    = Bool()
510    val w    = Bool()
511    val r    = Bool()
512    val v    = Bool()
513  }
514
515  def unaligned(level: UInt) = {
516    isLeaf() && !(level === 2.U ||
517                  level === 1.U && ppn(vpnnLen-1,   0) === 0.U ||
518                  level === 0.U && ppn(vpnnLen*2-1, 0) === 0.U)
519  }
520
521  def isPf(level: UInt) = {
522    !perm.v || (!perm.r && perm.w) || unaligned(level)
523  }
524
525  // paddr of Xiangshan is 36 bits but ppn of sv39 is 44 bits
526  // access fault will be raised when ppn >> ppnLen is not zero
527  def isAf() = {
528    !(ppn_high === 0.U)
529  }
530
531  def isLeaf() = {
532    perm.r || perm.x || perm.w
533  }
534
535  def getPerm() = {
536    val pm = Wire(new PtePermBundle)
537    pm.d := perm.d
538    pm.a := perm.a
539    pm.g := perm.g
540    pm.u := perm.u
541    pm.x := perm.x
542    pm.w := perm.w
543    pm.r := perm.r
544    pm
545  }
546
547  override def toPrintable: Printable = {
548    p"ppn:0x${Hexadecimal(ppn)} perm:b${Binary(perm.asUInt)}"
549  }
550}
551
552class PtwEntry(tagLen: Int, hasPerm: Boolean = false, hasLevel: Boolean = false)(implicit p: Parameters) extends PtwBundle {
553  val tag = UInt(tagLen.W)
554  val asid = UInt(asidLen.W)
555  val ppn = UInt(ppnLen.W)
556  val perm = if (hasPerm) Some(new PtePermBundle) else None
557  val level = if (hasLevel) Some(UInt(log2Up(Level).W)) else None
558  val prefetch = Bool()
559  val v = Bool()
560
561  def is_normalentry(): Bool = {
562    if (!hasLevel) true.B
563    else level.get === 2.U
564  }
565
566  def genPPN(vpn: UInt): UInt = {
567    if (!hasLevel) ppn
568    else MuxLookup(level.get, 0.U, Seq(
569          0.U -> Cat(ppn(ppn.getWidth-1, vpnnLen*2), vpn(vpnnLen*2-1, 0)),
570          1.U -> Cat(ppn(ppn.getWidth-1, vpnnLen), vpn(vpnnLen-1, 0)),
571          2.U -> ppn)
572    )
573  }
574
575  def hit(vpn: UInt, asid: UInt, allType: Boolean = false, ignoreAsid: Boolean = false) = {
576    require(vpn.getWidth == vpnLen)
577//    require(this.asid.getWidth <= asid.getWidth)
578    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
579    if (allType) {
580      require(hasLevel)
581      val hit0 = tag(tagLen - 1,    vpnnLen*2) === vpn(tagLen - 1, vpnnLen*2)
582      val hit1 = tag(vpnnLen*2 - 1, vpnnLen)   === vpn(vpnnLen*2 - 1,  vpnnLen)
583      val hit2 = tag(vpnnLen - 1,     0)         === vpn(vpnnLen - 1, 0)
584
585      asid_hit && Mux(level.getOrElse(0.U) === 2.U, hit2 && hit1 && hit0, Mux(level.getOrElse(0.U) === 1.U, hit1 && hit0, hit0))
586    } else if (hasLevel) {
587      val hit0 = tag(tagLen - 1, tagLen - vpnnLen) === vpn(vpnLen - 1, vpnLen - vpnnLen)
588      val hit1 = tag(tagLen - vpnnLen - 1, tagLen - vpnnLen * 2) === vpn(vpnLen - vpnnLen - 1, vpnLen - vpnnLen * 2)
589
590      asid_hit && Mux(level.getOrElse(0.U) === 0.U, hit0, hit0 && hit1)
591    } else {
592      asid_hit && tag === vpn(vpnLen - 1, vpnLen - tagLen)
593    }
594  }
595
596  def refill(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool, valid: Bool = false.B) {
597    require(this.asid.getWidth <= asid.getWidth) // maybe equal is better, but ugly outside
598
599    tag := vpn(vpnLen - 1, vpnLen - tagLen)
600    ppn := pte.asTypeOf(new PteBundle().cloneType).ppn
601    perm.map(_ := pte.asTypeOf(new PteBundle().cloneType).perm)
602    this.asid := asid
603    this.prefetch := prefetch
604    this.v := valid
605    this.level.map(_ := level)
606  }
607
608  def genPtwEntry(vpn: UInt, asid: UInt, pte: UInt, level: UInt = 0.U, prefetch: Bool, valid: Bool = false.B) = {
609    val e = Wire(new PtwEntry(tagLen, hasPerm, hasLevel))
610    e.refill(vpn, asid, pte, level, prefetch, valid)
611    e
612  }
613
614
615
616  override def toPrintable: Printable = {
617    // p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} perm:${perm}"
618    p"tag:0x${Hexadecimal(tag)} ppn:0x${Hexadecimal(ppn)} " +
619      (if (hasPerm) p"perm:${perm.getOrElse(0.U.asTypeOf(new PtePermBundle))} " else p"") +
620      (if (hasLevel) p"level:${level.getOrElse(0.U)}" else p"") +
621      p"prefetch:${prefetch}"
622  }
623}
624
625class PtwEntries(num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
626  require(log2Up(num)==log2Down(num))
627  // NOTE: hasPerm means that is leaf or not.
628
629  val tag  = UInt(tagLen.W)
630  val asid = UInt(asidLen.W)
631  val ppns = Vec(num, UInt(ppnLen.W))
632  val vs   = Vec(num, Bool())
633  val perms = if (hasPerm) Some(Vec(num, new PtePermBundle)) else None
634  val prefetch = Bool()
635  // println(s"PtwEntries: tag:1*${tagLen} ppns:${num}*${ppnLen} vs:${num}*1")
636  // NOTE: vs is used for different usage:
637  // for l3, which store the leaf(leaves), vs is page fault or not.
638  // for l2, which shoule not store leaf, vs is valid or not, that will anticipate in hit check
639  // Because, l2 should not store leaf(no perm), it doesn't store perm.
640  // If l2 hit a leaf, the perm is still unavailble. Should still page walk. Complex but nothing helpful.
641  // TODO: divide vs into validVec and pfVec
642  // for l2: may valid but pf, so no need for page walk, return random pte with pf.
643
644  def tagClip(vpn: UInt) = {
645    require(vpn.getWidth == vpnLen)
646    vpn(vpnLen - 1, vpnLen - tagLen)
647  }
648
649  def sectorIdxClip(vpn: UInt, level: Int) = {
650    getVpnClip(vpn, level)(log2Up(num) - 1, 0)
651  }
652
653  def hit(vpn: UInt, asid: UInt, ignoreAsid: Boolean = false) = {
654    val asid_hit = if (ignoreAsid) true.B else (this.asid === asid)
655    asid_hit && tag === tagClip(vpn) && (if (hasPerm) true.B else vs(sectorIdxClip(vpn, level)))
656  }
657
658  def genEntries(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
659    require((data.getWidth / XLEN) == num,
660      s"input data length must be multiple of pte length: data.length:${data.getWidth} num:${num}")
661
662    val ps = Wire(new PtwEntries(num, tagLen, level, hasPerm))
663    ps.tag := tagClip(vpn)
664    ps.asid := asid
665    ps.prefetch := prefetch
666    for (i <- 0 until num) {
667      val pte = data((i+1)*XLEN-1, i*XLEN).asTypeOf(new PteBundle)
668      ps.ppns(i) := pte.ppn
669      ps.vs(i)   := !pte.isPf(levelUInt) && (if (hasPerm) pte.isLeaf() else !pte.isLeaf())
670      ps.perms.map(_(i) := pte.perm)
671    }
672    ps
673  }
674
675  override def toPrintable: Printable = {
676    // require(num == 4, "if num is not 4, please comment this toPrintable")
677    // NOTE: if num is not 4, please comment this toPrintable
678    val permsInner = perms.getOrElse(0.U.asTypeOf(Vec(num, new PtePermBundle)))
679    p"asid: ${Hexadecimal(asid)} tag:0x${Hexadecimal(tag)} ppns:${printVec(ppns)} vs:${Binary(vs.asUInt)} " +
680      (if (hasPerm) p"perms:${printVec(permsInner)}" else p"")
681  }
682}
683
684class PTWEntriesWithEcc(eccCode: Code, num: Int, tagLen: Int, level: Int, hasPerm: Boolean)(implicit p: Parameters) extends PtwBundle {
685  val entries = new PtwEntries(num, tagLen, level, hasPerm)
686
687  val ecc_block = XLEN
688  val ecc_info = get_ecc_info()
689  val ecc = UInt(ecc_info._1.W)
690
691  def get_ecc_info(): (Int, Int, Int, Int) = {
692    val eccBits_per = eccCode.width(ecc_block) - ecc_block
693
694    val data_length = entries.getWidth
695    val data_align_num = data_length / ecc_block
696    val data_not_align = (data_length % ecc_block) != 0 // ugly code
697    val data_unalign_length = data_length - data_align_num * ecc_block
698    val eccBits_unalign = eccCode.width(data_unalign_length) - data_unalign_length
699
700    val eccBits = eccBits_per * data_align_num + eccBits_unalign
701    (eccBits, eccBits_per, data_align_num, data_unalign_length)
702  }
703
704  def encode() = {
705    val data = entries.asUInt()
706    val ecc_slices = Wire(Vec(ecc_info._3, UInt(ecc_info._2.W)))
707    for (i <- 0 until ecc_info._3) {
708      ecc_slices(i) := eccCode.encode(data((i+1)*ecc_block-1, i*ecc_block)) >> ecc_block
709    }
710    if (ecc_info._4 != 0) {
711      val ecc_unaligned = eccCode.encode(data(data.getWidth-1, ecc_info._3*ecc_block)) >> ecc_info._4
712      ecc := Cat(ecc_unaligned, ecc_slices.asUInt())
713    } else { ecc := ecc_slices.asUInt() }
714  }
715
716  def decode(): Bool = {
717    val data = entries.asUInt()
718    val res = Wire(Vec(ecc_info._3 + 1, Bool()))
719    for (i <- 0 until ecc_info._3) {
720      res(i) := {if (ecc_info._2 != 0) eccCode.decode(Cat(ecc((i+1)*ecc_info._2-1, i*ecc_info._2), data((i+1)*ecc_block-1, i*ecc_block))).error else false.B}
721    }
722    if (ecc_info._2 != 0 && ecc_info._4 != 0) {
723      res(ecc_info._3) := eccCode.decode(
724        Cat(ecc(ecc_info._1-1, ecc_info._2*ecc_info._3), data(data.getWidth-1, ecc_info._3*ecc_block))).error
725    } else { res(ecc_info._3) := false.B }
726
727    Cat(res).orR
728  }
729
730  def gen(vpn: UInt, asid: UInt, data: UInt, levelUInt: UInt, prefetch: Bool) = {
731    this.entries := entries.genEntries(vpn, asid, data, levelUInt, prefetch)
732    this.encode()
733  }
734}
735
736class PtwReq(implicit p: Parameters) extends PtwBundle {
737  val vpn = UInt(vpnLen.W)
738
739  override def toPrintable: Printable = {
740    p"vpn:0x${Hexadecimal(vpn)}"
741  }
742}
743
744class PtwReqwithMemIdx(implicit p: Parameters) extends PtwReq {
745  val memidx = new MemBlockidxBundle
746}
747
748class PtwResp(implicit p: Parameters) extends PtwBundle {
749  val entry = new PtwEntry(tagLen = vpnLen, hasPerm = true, hasLevel = true)
750  val pf = Bool()
751  val af = Bool()
752
753  def apply(pf: Bool, af: Bool, level: UInt, pte: PteBundle, vpn: UInt, asid: UInt) = {
754    this.entry.level.map(_ := level)
755    this.entry.tag := vpn
756    this.entry.perm.map(_ := pte.getPerm())
757    this.entry.ppn := pte.ppn
758    this.entry.prefetch := DontCare
759    this.entry.asid := asid
760    this.entry.v := !pf
761    this.pf := pf
762    this.af := af
763  }
764
765  override def toPrintable: Printable = {
766    p"entry:${entry} pf:${pf} af:${af}"
767  }
768}
769
770class PtwRespwithMemIdx(implicit p: Parameters) extends PtwResp {
771  val memidx = new MemBlockidxBundle
772}
773
774
775class L2TLBIO(implicit p: Parameters) extends PtwBundle {
776  val tlb = Vec(PtwWidth, Flipped(new TlbPtwIO))
777  val sfence = Input(new SfenceBundle)
778  val csr = new Bundle {
779    val tlb = Input(new TlbCsrBundle)
780    val distribute_csr = Flipped(new DistributedCSRIO)
781  }
782}
783
784class L2TlbMemReqBundle(implicit p: Parameters) extends PtwBundle {
785  val addr = UInt(PAddrBits.W)
786  val id = UInt(bMemID.W)
787}
788
789class L2TlbInnerBundle(implicit p: Parameters) extends PtwReq {
790  val source = UInt(bSourceWidth.W)
791}
792
793
794object ValidHoldBypass{
795  def apply(infire: Bool, outfire: Bool, flush: Bool = false.B) = {
796    val valid = RegInit(false.B)
797    when (infire) { valid := true.B }
798    when (outfire) { valid := false.B } // ATTENTION: order different with ValidHold
799    when (flush) { valid := false.B } // NOTE: the flush will flush in & out, is that ok?
800    valid || infire
801  }
802}
803
804class L1TlbDB(implicit p: Parameters) extends TlbBundle {
805  val vpn = UInt(vpnLen.W)
806}
807
808class PageCacheDB(implicit p: Parameters) extends TlbBundle with HasPtwConst {
809  val vpn = UInt(vpnLen.W)
810  val source = UInt(bSourceWidth.W)
811  val bypassed = Bool()
812  val is_first = Bool()
813  val prefetched = Bool()
814  val prefetch = Bool()
815  val l2Hit = Bool()
816  val l1Hit = Bool()
817  val hit = Bool()
818}
819
820class PTWDB(implicit p: Parameters) extends TlbBundle with HasPtwConst {
821  val vpn = UInt(vpnLen.W)
822  val source = UInt(bSourceWidth.W)
823}
824
825class L2TlbPrefetchDB(implicit p: Parameters) extends TlbBundle {
826  val vpn = UInt(vpnLen.W)
827}
828
829class L2TlbMissQueueDB(implicit p: Parameters) extends TlbBundle {
830  val vpn = UInt(vpnLen.W)
831}
832