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