xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/PageTableCache.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 chisel3.internal.naming.chiselName
23import xiangshan._
24import xiangshan.cache.{HasDCacheParameters, MemoryOpConstants}
25import utils._
26import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
27import freechips.rocketchip.tilelink._
28
29/* ptw cache caches the page table of all the three layers
30 * ptw cache resp at next cycle
31 * the cache should not be blocked
32 * when miss queue if full, just block req outside
33 */
34
35class PageCachePerPespBundle(implicit p: Parameters) extends PtwBundle {
36  val hit = Bool()
37  val pre = Bool()
38  val ppn = UInt(ppnLen.W)
39  val perm = new PtePermBundle()
40  val ecc = Bool()
41  val level = UInt(2.W)
42  val v = Bool()
43
44  def apply(hit: Bool, pre: Bool, ppn: UInt, perm: PtePermBundle = 0.U.asTypeOf(new PtePermBundle()),
45            ecc: Bool = false.B, level: UInt = 0.U, valid: Bool = true.B) {
46    this.hit := hit && !ecc
47    this.pre := pre
48    this.ppn := ppn
49    this.perm := perm
50    this.ecc := ecc && hit
51    this.level := level
52    this.v := valid
53  }
54}
55
56class PageCacheRespBundle(implicit p: Parameters) extends PtwBundle {
57  val l1 = new PageCachePerPespBundle
58  val l2 = new PageCachePerPespBundle
59  val l3 = new PageCachePerPespBundle
60  val sp = new PageCachePerPespBundle
61}
62
63class PtwCacheReq(implicit p: Parameters) extends PtwBundle {
64  val req_info = new L2TlbInnerBundle()
65  val isFirst = Bool()
66}
67
68class PtwCacheIO()(implicit p: Parameters) extends MMUIOBaseBundle with HasPtwConst {
69  val req = Flipped(DecoupledIO(new PtwCacheReq()))
70  val resp = DecoupledIO(new Bundle {
71    val req_info = new L2TlbInnerBundle()
72    val isFirst = Bool()
73    val hit = Bool()
74    val prefetch = Bool() // is the entry fetched by prefetch
75    val toFsm = new Bundle {
76      val l1Hit = Bool()
77      val l2Hit = Bool()
78      val ppn = UInt(ppnLen.W)
79    }
80    val toTlb = new PtwEntry(tagLen = vpnLen, hasPerm = true, hasLevel = true)
81  })
82  val refill = Flipped(ValidIO(new Bundle {
83    val ptes = UInt(blockBits.W)
84    val req_info = new L2TlbInnerBundle()
85    val level = UInt(log2Up(Level).W)
86    val addr_low = UInt((log2Up(l2tlbParams.blockBytes) - log2Up(XLEN/8)).W)
87  }))
88}
89
90@chiselName
91class PtwCache()(implicit p: Parameters) extends XSModule with HasPtwConst with HasPerfEvents {
92  val io = IO(new PtwCacheIO)
93
94  val ecc = Code.fromString(l2tlbParams.ecc)
95  val l2EntryType = new PTWEntriesWithEcc(ecc, num = PtwL2SectorSize, tagLen = PtwL2TagLen, level = 1, hasPerm = false)
96  val l3EntryType = new PTWEntriesWithEcc(ecc, num = PtwL3SectorSize, tagLen = PtwL3TagLen, level = 2, hasPerm = true)
97
98  // TODO: four caches make the codes dirty, think about how to deal with it
99
100  val sfence = io.sfence
101  val refill = io.refill.bits
102  val refill_prefetch = from_pre(io.refill.bits.req_info.source)
103  val flush = sfence.valid || io.csr.satp.changed
104
105  // when refill, refuce to accept new req
106  val rwHarzad = if (sramSinglePort) io.refill.valid else false.B
107
108  // handle hand signal and req_info
109  val stage1 = Wire(Decoupled(new PtwCacheReq())) // enq stage & read page cache valid
110  val stage2 = Wire(Vec(2, Decoupled(new PtwCacheReq()))) // page cache resp & check hit & check ecc
111  val stage3 = Wire(Decoupled(new PtwCacheReq())) // deq stage
112  /* stage1.valid && stage2(0).ready  : stage1 (in)  -> stage2
113   * stage2(1).valid && stage3.ready  : stage2       -> stage3
114   * stage3.valid && io.resp.ready    : stage3 (out) -> outside
115   */
116  stage1 <> io.req
117  PipelineConnect(stage1, stage2(0), stage2(1).ready, flush, rwHarzad)
118  InsideStageConnect(stage2(0), stage2(1))
119  PipelineConnect(stage2(1), stage3, io.resp.ready, flush)
120  stage3.ready := !stage3.valid || io.resp.ready
121
122  // l1: level 0 non-leaf pte
123  val l1 = Reg(Vec(l2tlbParams.l1Size, new PtwEntry(tagLen = PtwL1TagLen)))
124  val l1v = RegInit(0.U(l2tlbParams.l1Size.W))
125  val l1g = Reg(UInt(l2tlbParams.l1Size.W))
126  val l1asids = Reg(Vec(l2tlbParams.l1Size, UInt(AsidLength.W)))
127
128  // l2: level 1 non-leaf pte
129  val l2 = Module(new SRAMTemplate(
130    l2EntryType,
131    set = l2tlbParams.l2nSets,
132    way = l2tlbParams.l2nWays,
133    singlePort = sramSinglePort
134  ))
135  val l2v = RegInit(0.U((l2tlbParams.l2nSets * l2tlbParams.l2nWays).W))
136  val l2g = Reg(UInt((l2tlbParams.l2nSets * l2tlbParams.l2nWays).W))
137  val l2asids = Reg(Vec(l2tlbParams.l2nSets, Vec(l2tlbParams.l2nWays, UInt(AsidLength.W))))
138  def getl2vSet(vpn: UInt) = {
139    require(log2Up(l2tlbParams.l2nWays) == log2Down(l2tlbParams.l2nWays))
140    val set = genPtwL2SetIdx(vpn)
141    require(set.getWidth == log2Up(l2tlbParams.l2nSets))
142    val l2vVec = l2v.asTypeOf(Vec(l2tlbParams.l2nSets, UInt(l2tlbParams.l2nWays.W)))
143    l2vVec(set)
144  }
145  def getl2asidSet(vpn: UInt) = {
146    require(log2Up(l2tlbParams.l2nWays) == log2Down(l2tlbParams.l2nWays))
147    val set = genPtwL2SetIdx(vpn)
148    require(set.getWidth == log2Up(l2tlbParams.l2nSets))
149    l2asids(set)
150  }
151
152  // l3: level 2 leaf pte of 4KB pages
153  val l3 = Module(new SRAMTemplate(
154    l3EntryType,
155    set = l2tlbParams.l3nSets,
156    way = l2tlbParams.l3nWays,
157    singlePort = sramSinglePort
158  ))
159  val l3v = RegInit(0.U((l2tlbParams.l3nSets * l2tlbParams.l3nWays).W))
160  val l3g = Reg(UInt((l2tlbParams.l3nSets * l2tlbParams.l3nWays).W))
161  val l3asids = Reg(Vec(l2tlbParams.l3nSets, Vec(l2tlbParams.l3nWays, UInt(AsidLength.W))))
162  def getl3vSet(vpn: UInt) = {
163    require(log2Up(l2tlbParams.l3nWays) == log2Down(l2tlbParams.l3nWays))
164    val set = genPtwL3SetIdx(vpn)
165    require(set.getWidth == log2Up(l2tlbParams.l3nSets))
166    val l3vVec = l3v.asTypeOf(Vec(l2tlbParams.l3nSets, UInt(l2tlbParams.l3nWays.W)))
167    l3vVec(set)
168  }
169  def getl3asidSet(vpn: UInt) = {
170    require(log2Up(l2tlbParams.l3nWays) == log2Down(l2tlbParams.l3nWays))
171    val set = genPtwL3SetIdx(vpn)
172    require(set.getWidth == log2Up(l2tlbParams.l3nSets))
173    l3asids(set)
174  }
175
176  // sp: level 0/1 leaf pte of 1GB/2MB super pages
177  val sp = Reg(Vec(l2tlbParams.spSize, new PtwEntry(tagLen = SPTagLen, hasPerm = true, hasLevel = true)))
178  val spv = RegInit(0.U(l2tlbParams.spSize.W))
179  val spg = Reg(UInt(l2tlbParams.spSize.W))
180  val spasids = Reg(Vec(l2tlbParams.spSize, UInt(AsidLength.W)))
181
182  // Access Perf
183  val l1AccessPerf = Wire(Vec(l2tlbParams.l1Size, Bool()))
184  val l2AccessPerf = Wire(Vec(l2tlbParams.l2nWays, Bool()))
185  val l3AccessPerf = Wire(Vec(l2tlbParams.l3nWays, Bool()))
186  val spAccessPerf = Wire(Vec(l2tlbParams.spSize, Bool()))
187  l1AccessPerf.map(_ := false.B)
188  l2AccessPerf.map(_ := false.B)
189  l3AccessPerf.map(_ := false.B)
190  spAccessPerf.map(_ := false.B)
191
192  // stage1 & stage2, read page cache and data resp
193
194  val cache_read_valid = OneCycleValid(stage1.fire, flush)
195  // l1
196  val ptwl1replace = ReplacementPolicy.fromString(l2tlbParams.l1Replacer, l2tlbParams.l1Size)
197  val (l1Hit, l1HitPPN, l1Pre) = {
198    val hitVecT = l1.zipWithIndex.map { case (e, i) => e.hit(stage1.bits.req_info.vpn, io.csr.satp.asid) && l1v(i) }
199    val hitVec = hitVecT.map(RegEnable(_, stage1.fire))
200    val hitPPN = ParallelPriorityMux(hitVec zip l1.map(_.ppn))
201    val hitPre = ParallelPriorityMux(hitVec zip l1.map(_.prefetch))
202    val hit = ParallelOR(hitVec) && cache_read_valid
203
204    when (hit) { ptwl1replace.access(OHToUInt(hitVec)) }
205
206    l1AccessPerf.zip(hitVec).map{ case (l, h) => l := h && RegNext(stage1.fire)}
207    for (i <- 0 until l2tlbParams.l1Size) {
208      XSDebug(stage1.fire, p"[l1] l1(${i.U}) ${l1(i)} hit:${l1(i).hit(stage1.bits.req_info.vpn, io.csr.satp.asid)}\n")
209    }
210    XSDebug(stage1.fire, p"[l1] l1v:${Binary(l1v)} hitVecT:${Binary(VecInit(hitVecT).asUInt)}\n")
211    XSDebug(stage2(0).valid, p"[l1] l1Hit:${hit} l1HitPPN:0x${Hexadecimal(hitPPN)} hitVec:${VecInit(hitVec).asUInt}\n")
212
213    VecInit(hitVecT).suggestName(s"l1_hitVecT")
214    VecInit(hitVec).suggestName(s"l1_hitVec")
215
216    (hit, hitPPN, hitPre)
217  }
218
219  // l2
220  val ptwl2replace = ReplacementPolicy.fromString(l2tlbParams.l2Replacer,l2tlbParams.l2nWays,l2tlbParams.l2nSets)
221  val (l2Hit, l2HitPPN, l2Pre, l2eccError) = {
222    val ridx = genPtwL2SetIdx(stage1.bits.req_info.vpn)
223    val vidx = RegEnable(VecInit(getl2vSet(stage1.bits.req_info.vpn).asBools), stage1.fire)
224    val asids_idx = RegEnable(getl2asidSet(stage1.bits.req_info.vpn), stage1.fire)
225    l2.io.r.req.valid := stage1.fire
226    l2.io.r.req.bits.apply(setIdx = ridx)
227    val ramDatas = l2.io.r.resp.data
228    val hitVec = VecInit(ramDatas.zip(vidx).map { case (wayData, v) => wayData.entries.hit(stage2(0).bits.req_info.vpn, io.csr.satp.asid) && v })
229    val hitWayEntry = ParallelPriorityMux(hitVec zip ramDatas)
230    val hitWayData = hitWayEntry.entries
231    val hit = ParallelOR(hitVec) && cache_read_valid && RegNext(l2.io.r.req.ready, init = false.B)
232    val hitWay = ParallelPriorityMux(hitVec zip (0 until l2tlbParams.l2nWays).map(_.U))
233    val eccError = hitWayEntry.decode()
234
235    ridx.suggestName(s"l2_ridx")
236    vidx.suggestName(s"l2_vidx")
237    ramDatas.suggestName(s"l2_ramDatas")
238    hitVec.suggestName(s"l2_hitVec")
239    hitWayData.suggestName(s"l2_hitWayData")
240    hitWay.suggestName(s"l2_hitWay")
241
242    when (hit) { ptwl2replace.access(genPtwL2SetIdx(stage2(0).bits.req_info.vpn), hitWay) }
243
244    l2AccessPerf.zip(hitVec).map{ case (l, h) => l := h && RegNext(stage1.fire) }
245    XSDebug(stage1.fire, p"[l2] ridx:0x${Hexadecimal(ridx)}\n")
246    for (i <- 0 until l2tlbParams.l2nWays) {
247      XSDebug(RegNext(stage1.fire), p"[l2] ramDatas(${i.U}) ${ramDatas(i)}  l2v:${vidx(i)}  hit:${ramDatas(i).entries.hit(stage2(0).bits.req_info.vpn, io.csr.satp.asid)}\n")
248    }
249    XSDebug(stage2(0).valid, p"[l2] l2Hit:${hit} l2HitPPN:0x${Hexadecimal(hitWayData.ppns(genPtwL2SectorIdx(stage2(0).bits.req_info.vpn)))} hitVec:${Binary(hitVec.asUInt)} hitWay:${hitWay} vidx:${Binary(vidx.asUInt)}\n")
250
251    (hit, hitWayData.ppns(genPtwL2SectorIdx(stage2(0).bits.req_info.vpn)), hitWayData.prefetch, eccError)
252  }
253
254  // l3
255  val ptwl3replace = ReplacementPolicy.fromString(l2tlbParams.l3Replacer,l2tlbParams.l3nWays,l2tlbParams.l3nSets)
256  val (l3Hit, l3HitData, l3Pre, l3eccError) = {
257    val ridx = genPtwL3SetIdx(stage1.bits.req_info.vpn)
258    val vidx = RegEnable(VecInit(getl3vSet(stage1.bits.req_info.vpn).asBools), stage1.fire)
259    val asids_idx = RegEnable(getl3asidSet(stage1.bits.req_info.vpn), stage1.fire)
260    l3.io.r.req.valid := stage1.fire
261    l3.io.r.req.bits.apply(setIdx = ridx)
262    val ramDatas = l3.io.r.resp.data
263    val hitVec = VecInit(ramDatas.zip(vidx).map{ case (wayData, v) => wayData.entries.hit(stage2(0).bits.req_info.vpn, io.csr.satp.asid) && v })
264    val hitWayEntry = ParallelPriorityMux(hitVec zip ramDatas)
265    val hitWayData = hitWayEntry.entries
266    val hitWayEcc = hitWayEntry.ecc
267    val hit = ParallelOR(hitVec) && cache_read_valid && RegNext(l3.io.r.req.ready, init = false.B)
268    val hitWay = ParallelPriorityMux(hitVec zip (0 until l2tlbParams.l3nWays).map(_.U))
269    val eccError = hitWayEntry.decode()
270
271    when (hit) { ptwl3replace.access(genPtwL3SetIdx(stage2(0).bits.req_info.vpn), hitWay) }
272
273    l3AccessPerf.zip(hitVec).map{ case (l, h) => l := h && RegNext(stage1.fire) }
274    XSDebug(stage1.fire, p"[l3] ridx:0x${Hexadecimal(ridx)}\n")
275    for (i <- 0 until l2tlbParams.l3nWays) {
276      XSDebug(RegNext(stage1.fire), p"[l3] ramDatas(${i.U}) ${ramDatas(i)}  l3v:${vidx(i)}  hit:${ramDatas(i).entries.hit(stage2(0).bits.req_info.vpn, io.csr.satp.asid)}\n")
277    }
278    XSDebug(stage2(0).valid, p"[l3] l3Hit:${hit} l3HitData:${hitWayData} hitVec:${Binary(hitVec.asUInt)} hitWay:${hitWay} vidx:${Binary(vidx.asUInt)}\n")
279
280    ridx.suggestName(s"l3_ridx")
281    vidx.suggestName(s"l3_vidx")
282    ramDatas.suggestName(s"l3_ramDatas")
283    hitVec.suggestName(s"l3_hitVec")
284    hitWay.suggestName(s"l3_hitWay")
285
286    (hit, hitWayData, hitWayData.prefetch, eccError)
287  }
288  val l3HitPPN = l3HitData.ppns(genPtwL3SectorIdx(stage2(0).bits.req_info.vpn))
289  val l3HitPerm = l3HitData.perms.getOrElse(0.U.asTypeOf(Vec(PtwL3SectorSize, new PtePermBundle)))(genPtwL3SectorIdx(stage2(0).bits.req_info.vpn))
290
291  // super page
292  val spreplace = ReplacementPolicy.fromString(l2tlbParams.spReplacer, l2tlbParams.spSize)
293  val (spHit, spHitData, spPre, spValid) = {
294    val hitVecT = sp.zipWithIndex.map { case (e, i) => e.hit(stage1.bits.req_info.vpn, io.csr.satp.asid) && spv(i) }
295    val hitVec = hitVecT.map(RegEnable(_, stage1.fire))
296    val hitData = ParallelPriorityMux(hitVec zip sp)
297    val hit = ParallelOR(hitVec) && cache_read_valid
298
299    when (hit) { spreplace.access(OHToUInt(hitVec)) }
300
301    spAccessPerf.zip(hitVec).map{ case (s, h) => s := h && RegNext(stage1.fire) }
302    for (i <- 0 until l2tlbParams.spSize) {
303      XSDebug(stage1.fire, p"[sp] sp(${i.U}) ${sp(i)} hit:${sp(i).hit(stage1.bits.req_info.vpn, io.csr.satp.asid)} spv:${spv(i)}\n")
304    }
305    XSDebug(stage2(0).valid, p"[sp] spHit:${hit} spHitData:${hitData} hitVec:${Binary(VecInit(hitVec).asUInt)}\n")
306
307    VecInit(hitVecT).suggestName(s"sp_hitVecT")
308    VecInit(hitVec).suggestName(s"sp_hitVec")
309
310    (hit, hitData, hitData.prefetch, hitData.v)
311  }
312  val spHitPerm = spHitData.perm.getOrElse(0.U.asTypeOf(new PtePermBundle))
313  val spHitLevel = spHitData.level.getOrElse(0.U)
314
315  val s2_res = Wire(new PageCacheRespBundle)
316  s2_res.l1.apply(l1Hit, l1Pre, l1HitPPN)
317  s2_res.l2.apply(l2Hit, l2Pre, l2HitPPN, ecc = l2eccError)
318  s2_res.l3.apply(l3Hit, l3Pre, l3HitPPN, l3HitPerm, l3eccError)
319  s2_res.sp.apply(spHit, spPre, spHitData.ppn, spHitPerm, false.B, spHitLevel, spValid)
320  val s2_res_reg = DataHoldBypass(s2_res, RegNext(stage1.fire()))
321
322  // stage3, add stage 3 for ecc check...
323  val s3_res = Reg(new PageCacheRespBundle)
324  when (stage2(1).fire()) {
325    s3_res := s2_res_reg
326  }
327
328  io.resp.bits.req_info   := stage3.bits.req_info
329  io.resp.bits.isFirst  := stage3.bits.isFirst
330  io.resp.bits.hit      := s3_res.l3.hit || s3_res.sp.hit
331  io.resp.bits.prefetch := s3_res.l3.pre && s3_res.l3.hit || s3_res.sp.pre && s3_res.sp.hit
332  io.resp.bits.toFsm.l1Hit := s3_res.l1.hit
333  io.resp.bits.toFsm.l2Hit := s3_res.l2.hit
334  io.resp.bits.toFsm.ppn   := Mux(s3_res.l2.hit, s3_res.l2.ppn, s3_res.l1.ppn)
335  io.resp.bits.toTlb.tag   := stage3.bits.req_info.vpn
336  io.resp.bits.toTlb.asid  := io.csr.satp.asid // DontCare
337  io.resp.bits.toTlb.ppn   := Mux(s3_res.l3.hit, s3_res.l3.ppn, s3_res.sp.ppn)
338  io.resp.bits.toTlb.perm.map(_ := Mux(s3_res.l3.hit, s3_res.l3.perm, s3_res.sp.perm))
339  io.resp.bits.toTlb.level.map(_ := Mux(s3_res.l3.hit, 2.U, s3_res.sp.level))
340  io.resp.bits.toTlb.prefetch := from_pre(stage3.bits.req_info.source)
341  io.resp.bits.toTlb.v := Mux(s3_res.sp.hit, s3_res.sp.v, s3_res.l3.v)
342  io.resp.valid := stage3.valid
343  assert(!(l3Hit && spHit), "normal page and super page both hit")
344
345  // refill Perf
346  val l1RefillPerf = Wire(Vec(l2tlbParams.l1Size, Bool()))
347  val l2RefillPerf = Wire(Vec(l2tlbParams.l2nWays, Bool()))
348  val l3RefillPerf = Wire(Vec(l2tlbParams.l3nWays, Bool()))
349  val spRefillPerf = Wire(Vec(l2tlbParams.spSize, Bool()))
350  l1RefillPerf.map(_ := false.B)
351  l2RefillPerf.map(_ := false.B)
352  l3RefillPerf.map(_ := false.B)
353  spRefillPerf.map(_ := false.B)
354
355  // refill
356  l2.io.w.req <> DontCare
357  l3.io.w.req <> DontCare
358  l2.io.w.req.valid := false.B
359  l3.io.w.req.valid := false.B
360
361  def get_part(data: UInt, index: UInt): UInt = {
362    val inner_data = data.asTypeOf(Vec(data.getWidth / XLEN, UInt(XLEN.W)))
363    inner_data(index)
364  }
365
366  val memRdata = refill.ptes
367  val memSelData = get_part(memRdata, refill.addr_low)
368  val memPtes = (0 until (l2tlbParams.blockBytes/(XLEN/8))).map(i => memRdata((i+1)*XLEN-1, i*XLEN).asTypeOf(new PteBundle))
369  val memPte = memSelData.asTypeOf(new PteBundle)
370
371  memPte.suggestName("memPte")
372
373  // TODO: handle sfenceLatch outsize
374  when (io.refill.valid && !memPte.isPf(refill.level) && !flush ) {
375    when (refill.level === 0.U && !memPte.isLeaf()) {
376      // val refillIdx = LFSR64()(log2Up(l2tlbParams.l1Size)-1,0) // TODO: may be LRU
377      val refillIdx = replaceWrapper(l1v, ptwl1replace.way)
378      refillIdx.suggestName(s"PtwL1RefillIdx")
379      val rfOH = UIntToOH(refillIdx)
380      l1(refillIdx).refill(
381        refill.req_info.vpn,
382        io.csr.satp.asid,
383        memSelData,
384        0.U,
385        refill_prefetch
386      )
387      ptwl1replace.access(refillIdx)
388      l1v := l1v | rfOH
389      l1g := (l1g & ~rfOH) | Mux(memPte.perm.g, rfOH, 0.U)
390
391      for (i <- 0 until l2tlbParams.l1Size) {
392        l1RefillPerf(i) := i.U === refillIdx
393      }
394
395      XSDebug(p"[l1 refill] refillIdx:${refillIdx} refillEntry:${l1(refillIdx).genPtwEntry(refill.req_info.vpn, io.csr.satp.asid, memSelData, 0.U, prefetch = refill_prefetch)}\n")
396      XSDebug(p"[l1 refill] l1v:${Binary(l1v)}->${Binary(l1v | rfOH)} l1g:${Binary(l1g)}->${Binary((l1g & ~rfOH) | Mux(memPte.perm.g, rfOH, 0.U))}\n")
397
398      refillIdx.suggestName(s"l1_refillIdx")
399      rfOH.suggestName(s"l1_rfOH")
400    }
401
402    when (refill.level === 1.U && !memPte.isLeaf()) {
403      val refillIdx = genPtwL2SetIdx(refill.req_info.vpn)
404      val victimWay = replaceWrapper(RegEnable(VecInit(getl2vSet(refill.req_info.vpn).asBools).asUInt, stage1.fire), ptwl2replace.way(refillIdx))
405      val victimWayOH = UIntToOH(victimWay)
406      val rfvOH = UIntToOH(Cat(refillIdx, victimWay))
407      val wdata = Wire(l2EntryType)
408      wdata.gen(
409        vpn = refill.req_info.vpn,
410        asid = io.csr.satp.asid,
411        data = memRdata,
412        levelUInt = 1.U,
413        refill_prefetch
414      )
415      l2.io.w.apply(
416        valid = true.B,
417        setIdx = refillIdx,
418        data = wdata,
419        waymask = victimWayOH
420      )
421      ptwl2replace.access(refillIdx, victimWay)
422      l2v := l2v | rfvOH
423      l2g := l2g & ~rfvOH | Mux(Cat(memPtes.map(_.perm.g)).andR, rfvOH, 0.U)
424
425      for (i <- 0 until l2tlbParams.l2nWays) {
426        l2RefillPerf(i) := i.U === victimWay
427      }
428
429      XSDebug(p"[l2 refill] refillIdx:0x${Hexadecimal(refillIdx)} victimWay:${victimWay} victimWayOH:${Binary(victimWayOH)} rfvOH(in UInt):${Cat(refillIdx, victimWay)}\n")
430      XSDebug(p"[l2 refill] refilldata:0x${wdata}\n")
431      XSDebug(p"[l2 refill] l2v:${Binary(l2v)} -> ${Binary(l2v | rfvOH)}\n")
432      XSDebug(p"[l2 refill] l2g:${Binary(l2g)} -> ${Binary(l2g & ~rfvOH | Mux(Cat(memPtes.map(_.perm.g)).andR, rfvOH, 0.U))}\n")
433
434      refillIdx.suggestName(s"l2_refillIdx")
435      victimWay.suggestName(s"l2_victimWay")
436      victimWayOH.suggestName(s"l2_victimWayOH")
437      rfvOH.suggestName(s"l2_rfvOH")
438    }
439
440    when (refill.level === 2.U && memPte.isLeaf()) {
441      val refillIdx = genPtwL3SetIdx(refill.req_info.vpn)
442      val victimWay = replaceWrapper(RegEnable(VecInit(getl3vSet(refill.req_info.vpn).asBools).asUInt, stage1.fire), ptwl3replace.way(refillIdx))
443      val victimWayOH = UIntToOH(victimWay)
444      val rfvOH = UIntToOH(Cat(refillIdx, victimWay))
445      val wdata = Wire(l3EntryType)
446      wdata.gen(
447        vpn = refill.req_info.vpn,
448        asid = io.csr.satp.asid,
449        data = memRdata,
450        levelUInt = 2.U,
451        refill_prefetch
452      )
453      l3.io.w.apply(
454        valid = true.B,
455        setIdx = refillIdx,
456        data = wdata,
457        waymask = victimWayOH
458      )
459      ptwl3replace.access(refillIdx, victimWay)
460      l3v := l3v | rfvOH
461      l3g := l3g & ~rfvOH | Mux(Cat(memPtes.map(_.perm.g)).andR, rfvOH, 0.U)
462
463      for (i <- 0 until l2tlbParams.l3nWays) {
464        l3RefillPerf(i) := i.U === victimWay
465      }
466
467      XSDebug(p"[l3 refill] refillIdx:0x${Hexadecimal(refillIdx)} victimWay:${victimWay} victimWayOH:${Binary(victimWayOH)} rfvOH(in UInt):${Cat(refillIdx, victimWay)}\n")
468      XSDebug(p"[l3 refill] refilldata:0x${wdata}\n")
469      XSDebug(p"[l3 refill] l3v:${Binary(l3v)} -> ${Binary(l3v | rfvOH)}\n")
470      XSDebug(p"[l3 refill] l3g:${Binary(l3g)} -> ${Binary(l3g & ~rfvOH | Mux(Cat(memPtes.map(_.perm.g)).andR, rfvOH, 0.U))}\n")
471
472      refillIdx.suggestName(s"l3_refillIdx")
473      victimWay.suggestName(s"l3_victimWay")
474      victimWayOH.suggestName(s"l3_victimWayOH")
475      rfvOH.suggestName(s"l3_rfvOH")
476    }
477  }
478
479  // misc entries: super & invalid
480  when (io.refill.valid && !flush && (refill.level === 0.U || refill.level === 1.U) && (memPte.isLeaf() || memPte.isPf(refill.level))) {
481    val refillIdx = spreplace.way// LFSR64()(log2Up(l2tlbParams.spSize)-1,0) // TODO: may be LRU
482    val rfOH = UIntToOH(refillIdx)
483    sp(refillIdx).refill(
484      refill.req_info.vpn,
485      io.csr.satp.asid,
486      memSelData,
487      refill.level,
488      refill_prefetch,
489      !memPte.isPf(refill.level),
490    )
491    spreplace.access(refillIdx)
492    spv := spv | rfOH
493    spg := spg & ~rfOH | Mux(memPte.perm.g, rfOH, 0.U)
494
495    for (i <- 0 until l2tlbParams.spSize) {
496      spRefillPerf(i) := i.U === refillIdx
497    }
498
499    XSDebug(p"[sp refill] refillIdx:${refillIdx} refillEntry:${sp(refillIdx).genPtwEntry(refill.req_info.vpn, io.csr.satp.asid, memSelData, refill.level, refill_prefetch)}\n")
500    XSDebug(p"[sp refill] spv:${Binary(spv)}->${Binary(spv | rfOH)} spg:${Binary(spg)}->${Binary(spg & ~rfOH | Mux(memPte.perm.g, rfOH, 0.U))}\n")
501
502    refillIdx.suggestName(s"sp_refillIdx")
503    rfOH.suggestName(s"sp_rfOH")
504  }
505
506  val l2eccFlush = s3_res.l2.ecc && stage3.fire() // RegNext(l2eccError, init = false.B)
507  val l3eccFlush = s3_res.l3.ecc && stage3.fire() // RegNext(l3eccError, init = false.B)
508  val eccVpn = stage3.bits.req_info.vpn
509
510  assert(!l2eccFlush)
511  assert(!l3eccFlush)
512  when (l2eccFlush) {
513    val flushSetIdxOH = UIntToOH(genPtwL2SetIdx(eccVpn))
514    val flushMask = VecInit(flushSetIdxOH.asBools.map { a => Fill(l2tlbParams.l2nWays, a.asUInt) }).asUInt
515    l2v := l2v & ~flushMask
516    l2g := l2g & ~flushMask
517  }
518
519  when (l3eccFlush) {
520    val flushSetIdxOH = UIntToOH(genPtwL3SetIdx(eccVpn))
521    val flushMask = VecInit(flushSetIdxOH.asBools.map { a => Fill(l2tlbParams.l3nWays, a.asUInt) }).asUInt
522    l3v := l3v & ~flushMask
523    l3g := l3g & ~flushMask
524  }
525
526  // sfence
527  when (sfence.valid) {
528    val l1asidhit = VecInit(l1asids.map(_ === sfence.bits.asid)).asUInt
529    val spasidhit = VecInit(spasids.map(_ === sfence.bits.asid)).asUInt
530    val sfence_vpn = sfence.bits.addr(sfence.bits.addr.getWidth-1, offLen)
531
532    when (sfence.bits.rs1/*va*/) {
533      when (sfence.bits.rs2) {
534        // all va && all asid
535        l1v := 0.U
536        l2v := 0.U
537        l3v := 0.U
538        spv := 0.U
539      } .otherwise {
540        // all va && specific asid except global
541
542        l1v := l1v & (~l1asidhit | l1g)
543        l2v := l2v & l2g
544        l3v := l3v & l3g
545        spv := spv & (~spasidhit | spg)
546      }
547    } .otherwise {
548      // val flushMask = UIntToOH(genTlbL2Idx(sfence.bits.addr(sfence.bits.addr.getWidth-1, offLen)))
549      val flushSetIdxOH = UIntToOH(genPtwL3SetIdx(sfence_vpn))
550      // val flushMask = VecInit(flushSetIdxOH.asBools.map(Fill(l2tlbParams.l3nWays, _.asUInt))).asUInt
551      val flushMask = VecInit(flushSetIdxOH.asBools.map { a => Fill(l2tlbParams.l3nWays, a.asUInt) }).asUInt
552      flushSetIdxOH.suggestName(s"sfence_nrs1_flushSetIdxOH")
553      flushMask.suggestName(s"sfence_nrs1_flushMask")
554
555      when (sfence.bits.rs2) {
556        // specific leaf of addr && all asid
557        l3v := l3v & ~flushMask
558        spv := spv & (~VecInit(sp.map(_.hit(sfence_vpn, sfence.bits.asid, ignoreAsid = true))).asUInt | spg)
559      } .otherwise {
560        // specific leaf of addr && specific asid
561        l3v := l3v & (~flushMask | l3g)
562        spv := spv & (~VecInit(sp.map(_.hit(sfence_vpn, sfence.bits.asid))).asUInt | spg)
563      }
564    }
565  }
566
567  def InsideStageConnect[T <:Data](in: DecoupledIO[T], out: DecoupledIO[T], block: Bool = false.B): Unit = {
568    in.ready := !in.valid || out.ready
569    out.valid := in.valid
570    out.bits := in.bits
571  }
572
573  // Perf Count
574  val resp_l3 = s3_res.l3.hit
575  val resp_sp = s3_res.sp.hit
576  val resp_l1_pre = s3_res.l1.pre
577  val resp_l2_pre = s3_res.l2.pre
578  val resp_l3_pre = s3_res.l3.pre
579  val resp_sp_pre = s3_res.sp.pre
580  val base_valid_access_0 = !from_pre(io.resp.bits.req_info.source) && io.resp.fire()
581  XSPerfAccumulate("access", base_valid_access_0)
582  XSPerfAccumulate("l1_hit", base_valid_access_0 && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
583  XSPerfAccumulate("l2_hit", base_valid_access_0 && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
584  XSPerfAccumulate("l3_hit", base_valid_access_0 && resp_l3)
585  XSPerfAccumulate("sp_hit", base_valid_access_0 && resp_sp)
586  XSPerfAccumulate("pte_hit",base_valid_access_0 && io.resp.bits.hit)
587
588  XSPerfAccumulate("l1_hit_pre", base_valid_access_0 && resp_l1_pre && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
589  XSPerfAccumulate("l2_hit_pre", base_valid_access_0 && resp_l2_pre && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
590  XSPerfAccumulate("l3_hit_pre", base_valid_access_0 && resp_l3_pre && resp_l3)
591  XSPerfAccumulate("sp_hit_pre", base_valid_access_0 && resp_sp_pre && resp_sp)
592  XSPerfAccumulate("pte_hit_pre",base_valid_access_0 && (resp_l3_pre && resp_l3 || resp_sp_pre && resp_sp) && io.resp.bits.hit)
593
594  val base_valid_access_1 = from_pre(io.resp.bits.req_info.source) && io.resp.fire()
595  XSPerfAccumulate("pre_access", base_valid_access_1)
596  XSPerfAccumulate("pre_l1_hit", base_valid_access_1 && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
597  XSPerfAccumulate("pre_l2_hit", base_valid_access_1 && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
598  XSPerfAccumulate("pre_l3_hit", base_valid_access_1 && resp_l3)
599  XSPerfAccumulate("pre_sp_hit", base_valid_access_1 && resp_sp)
600  XSPerfAccumulate("pre_pte_hit",base_valid_access_1 && io.resp.bits.hit)
601
602  XSPerfAccumulate("pre_l1_hit_pre", base_valid_access_1 && resp_l1_pre && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
603  XSPerfAccumulate("pre_l2_hit_pre", base_valid_access_1 && resp_l2_pre && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
604  XSPerfAccumulate("pre_l3_hit_pre", base_valid_access_1 && resp_l3_pre && resp_l3)
605  XSPerfAccumulate("pre_sp_hit_pre", base_valid_access_1 && resp_sp_pre && resp_sp)
606  XSPerfAccumulate("pre_pte_hit_pre",base_valid_access_1 && (resp_l3_pre && resp_l3 || resp_sp_pre && resp_sp) && io.resp.bits.hit)
607
608  val base_valid_access_2 = stage3.bits.isFirst && !from_pre(io.resp.bits.req_info.source) && io.resp.fire()
609  XSPerfAccumulate("access_first", base_valid_access_2)
610  XSPerfAccumulate("l1_hit_first", base_valid_access_2 && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
611  XSPerfAccumulate("l2_hit_first", base_valid_access_2 && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
612  XSPerfAccumulate("l3_hit_first", base_valid_access_2 && resp_l3)
613  XSPerfAccumulate("sp_hit_first", base_valid_access_2 && resp_sp)
614  XSPerfAccumulate("pte_hit_first",base_valid_access_2 && io.resp.bits.hit)
615
616  XSPerfAccumulate("l1_hit_pre_first", base_valid_access_2 && resp_l1_pre && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
617  XSPerfAccumulate("l2_hit_pre_first", base_valid_access_2 && resp_l2_pre && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
618  XSPerfAccumulate("l3_hit_pre_first", base_valid_access_2 && resp_l3_pre && resp_l3)
619  XSPerfAccumulate("sp_hit_pre_first", base_valid_access_2 && resp_sp_pre && resp_sp)
620  XSPerfAccumulate("pte_hit_pre_first",base_valid_access_2 && (resp_l3_pre && resp_l3 || resp_sp_pre && resp_sp) && io.resp.bits.hit)
621
622  val base_valid_access_3 = stage3.bits.isFirst && from_pre(io.resp.bits.req_info.source) && io.resp.fire()
623  XSPerfAccumulate("pre_access_first", base_valid_access_3)
624  XSPerfAccumulate("pre_l1_hit_first", base_valid_access_3 && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
625  XSPerfAccumulate("pre_l2_hit_first", base_valid_access_3 && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
626  XSPerfAccumulate("pre_l3_hit_first", base_valid_access_3 && resp_l3)
627  XSPerfAccumulate("pre_sp_hit_first", base_valid_access_3 && resp_sp)
628  XSPerfAccumulate("pre_pte_hit_first", base_valid_access_3 && io.resp.bits.hit)
629
630  XSPerfAccumulate("pre_l1_hit_pre_first", base_valid_access_3 && resp_l1_pre && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
631  XSPerfAccumulate("pre_l2_hit_pre_first", base_valid_access_3 && resp_l2_pre && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
632  XSPerfAccumulate("pre_l3_hit_pre_first", base_valid_access_3 && resp_l3_pre && resp_l3)
633  XSPerfAccumulate("pre_sp_hit_pre_first", base_valid_access_3 && resp_sp_pre && resp_sp)
634  XSPerfAccumulate("pre_pte_hit_pre_first",base_valid_access_3 && (resp_l3_pre && resp_l3 || resp_sp_pre && resp_sp) && io.resp.bits.hit)
635
636  XSPerfAccumulate("rwHarzad", io.req.valid && !io.req.ready)
637  XSPerfAccumulate("out_blocked", io.resp.valid && !io.resp.ready)
638  l1AccessPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L1AccessIndex${i}", l) }
639  l2AccessPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L2AccessIndex${i}", l) }
640  l3AccessPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L3AccessIndex${i}", l) }
641  spAccessPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"SPAccessIndex${i}", l) }
642  l1RefillPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L1RefillIndex${i}", l) }
643  l2RefillPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L2RefillIndex${i}", l) }
644  l3RefillPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L3RefillIndex${i}", l) }
645  spRefillPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"SPRefillIndex${i}", l) }
646
647  XSPerfAccumulate("l1Refill", Cat(l1RefillPerf).orR)
648  XSPerfAccumulate("l2Refill", Cat(l2RefillPerf).orR)
649  XSPerfAccumulate("l3Refill", Cat(l3RefillPerf).orR)
650  XSPerfAccumulate("spRefill", Cat(spRefillPerf).orR)
651  XSPerfAccumulate("l1Refill_pre", Cat(l1RefillPerf).orR && refill_prefetch)
652  XSPerfAccumulate("l2Refill_pre", Cat(l2RefillPerf).orR && refill_prefetch)
653  XSPerfAccumulate("l3Refill_pre", Cat(l3RefillPerf).orR && refill_prefetch)
654  XSPerfAccumulate("spRefill_pre", Cat(spRefillPerf).orR && refill_prefetch)
655
656  // debug
657  XSDebug(sfence.valid, p"[sfence] original v and g vector:\n")
658  XSDebug(sfence.valid, p"[sfence] l1v:${Binary(l1v)}\n")
659  XSDebug(sfence.valid, p"[sfence] l2v:${Binary(l2v)}\n")
660  XSDebug(sfence.valid, p"[sfence] l3v:${Binary(l3v)}\n")
661  XSDebug(sfence.valid, p"[sfence] l3g:${Binary(l3g)}\n")
662  XSDebug(sfence.valid, p"[sfence] spv:${Binary(spv)}\n")
663  XSDebug(RegNext(sfence.valid), p"[sfence] new v and g vector:\n")
664  XSDebug(RegNext(sfence.valid), p"[sfence] l1v:${Binary(l1v)}\n")
665  XSDebug(RegNext(sfence.valid), p"[sfence] l2v:${Binary(l2v)}\n")
666  XSDebug(RegNext(sfence.valid), p"[sfence] l3v:${Binary(l3v)}\n")
667  XSDebug(RegNext(sfence.valid), p"[sfence] l3g:${Binary(l3g)}\n")
668  XSDebug(RegNext(sfence.valid), p"[sfence] spv:${Binary(spv)}\n")
669
670  val perfEvents = Seq(
671    ("access           ", base_valid_access_0             ),
672    ("l1_hit           ", l1Hit                           ),
673    ("l2_hit           ", l2Hit                           ),
674    ("l3_hit           ", l3Hit                           ),
675    ("sp_hit           ", spHit                           ),
676    ("pte_hit          ", l3Hit || spHit                  ),
677    ("rwHarzad         ",  io.req.valid && !io.req.ready  ),
678    ("out_blocked      ",  io.resp.valid && !io.resp.ready),
679  )
680  generatePerfEvent()
681}
682