xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/PageTableCache.scala (revision 382a2ebdf328e8147e67aad81c929b5587bdfda4)
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 org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import xiangshan._
23import xiangshan.cache.{HasDCacheParameters, MemoryOpConstants}
24import utils._
25import utility._
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 = if (HasHExtension) UInt((vpnLen max ppnLen).W) else 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 PageCacheMergePespBundle(implicit p: Parameters) extends PtwBundle {
57  assert(tlbcontiguous == 8, "Only support tlbcontiguous = 8!")
58  val hit = Bool()
59  val pre = Bool()
60  val ppn = Vec(tlbcontiguous, if(HasHExtension) UInt((vpnLen max ppnLen).W) else UInt(ppnLen.W))
61  val perm = Vec(tlbcontiguous, new PtePermBundle())
62  val ecc = Bool()
63  val level = UInt(2.W)
64  val v = Vec(tlbcontiguous, Bool())
65
66  def apply(hit: Bool, pre: Bool, ppn: Vec[UInt], perm: Vec[PtePermBundle] = Vec(tlbcontiguous, 0.U.asTypeOf(new PtePermBundle())),
67            ecc: Bool = false.B, level: UInt = 0.U, valid: Vec[Bool] = Vec(tlbcontiguous, true.B)) {
68    this.hit := hit && !ecc
69    this.pre := pre
70    this.ppn := ppn
71    this.perm := perm
72    this.ecc := ecc && hit
73    this.level := level
74    this.v := valid
75  }
76}
77
78class PageCacheRespBundle(implicit p: Parameters) extends PtwBundle {
79  val l1 = new PageCachePerPespBundle
80  val l2 = new PageCachePerPespBundle
81  val l3 = new PageCacheMergePespBundle
82  val sp = new PageCachePerPespBundle
83}
84
85class PtwCacheReq(implicit p: Parameters) extends PtwBundle {
86  val req_info = new L2TlbInnerBundle()
87  val isFirst = Bool()
88  val bypassed = Vec(3, Bool())
89  val isHptw = Bool()
90  val hptwId = UInt(log2Up(l2tlbParams.llptwsize).W)
91}
92
93class PtwCacheIO()(implicit p: Parameters) extends MMUIOBaseBundle with HasPtwConst {
94  val req = Flipped(DecoupledIO(new PtwCacheReq()))
95  val resp = DecoupledIO(new Bundle {
96    val req_info = new L2TlbInnerBundle()
97    val isFirst = Bool()
98    val hit = Bool()
99    val prefetch = Bool() // is the entry fetched by prefetch
100    val bypassed = Bool()
101    val toFsm = new Bundle {
102      val l1Hit = Bool()
103      val l2Hit = Bool()
104      val ppn = if(HasHExtension) UInt((vpnLen.max(ppnLen)).W) else UInt(ppnLen.W)
105    }
106    val toTlb = new PtwMergeResp()
107    val isHptw = Bool()
108    val toHptw = new Bundle {
109      val l1Hit = Bool()
110      val l2Hit = Bool()
111      val ppn = UInt(ppnLen.W)
112      val id = UInt(log2Up(l2tlbParams.llptwsize).W)
113      val resp = new HptwResp() // used if hit
114    }
115  })
116  val refill = Flipped(ValidIO(new Bundle {
117    val ptes = UInt(blockBits.W)
118    val levelOH = new Bundle {
119      // NOTE: levelOH has (Level+1) bits, each stands for page cache entries
120      val sp = Bool()
121      val l3 = Bool()
122      val l2 = Bool()
123      val l1 = Bool()
124      def apply(levelUInt: UInt, valid: Bool) = {
125        sp := RegNext((levelUInt === 0.U || levelUInt === 1.U) && valid, false.B)
126        l3 := RegNext((levelUInt === 2.U) & valid, false.B)
127        l2 := RegNext((levelUInt === 1.U) & valid, false.B)
128        l1 := RegNext((levelUInt === 0.U) & valid, false.B)
129      }
130    }
131    // duplicate level and sel_pte for each page caches, for better fanout
132    val req_info_dup = Vec(3, new L2TlbInnerBundle())
133    val level_dup = Vec(3, UInt(log2Up(Level).W))
134    val sel_pte_dup = Vec(3, UInt(XLEN.W))
135  }))
136  val sfence_dup = Vec(4, Input(new SfenceBundle()))
137  val csr_dup = Vec(3, Input(new TlbCsrBundle()))
138}
139
140class PtwCache()(implicit p: Parameters) extends XSModule with HasPtwConst with HasPerfEvents {
141  val io = IO(new PtwCacheIO)
142  val ecc = Code.fromString(l2tlbParams.ecc)
143  val l2EntryType = new PTWEntriesWithEcc(ecc, num = PtwL2SectorSize, tagLen = PtwL2TagLen, level = 1, hasPerm = false)
144  val l3EntryType = new PTWEntriesWithEcc(ecc, num = PtwL3SectorSize, tagLen = PtwL3TagLen, level = 2, hasPerm = true)
145
146  // TODO: four caches make the codes dirty, think about how to deal with it
147
148  val sfence_dup = io.sfence_dup
149  val refill = io.refill.bits
150  val refill_prefetch_dup = io.refill.bits.req_info_dup.map(a => from_pre(a.source))
151  val flush_dup = sfence_dup.zip(io.csr_dup).map(f => f._1.valid || f._2.satp.changed || f._2.vsatp.changed || f._2.hgatp.changed)
152  val flush = flush_dup(0)
153
154  // when refill, refuce to accept new req
155  val rwHarzad = if (sramSinglePort) io.refill.valid else false.B
156
157  // handle hand signal and req_info
158  // TODO: replace with FlushableQueue
159  val stageReq = Wire(Decoupled(new PtwCacheReq()))         // enq stage & read page cache valid
160  val stageDelay = Wire(Vec(2, Decoupled(new PtwCacheReq()))) // page cache resp
161  val stageCheck = Wire(Vec(2, Decoupled(new PtwCacheReq()))) // check hit & check ecc
162  val stageResp = Wire(Decoupled(new PtwCacheReq()))         // deq stage
163
164  val stageDelay_valid_1cycle = OneCycleValid(stageReq.fire, flush)      // catch ram data
165  val stageCheck_valid_1cycle = OneCycleValid(stageDelay(1).fire, flush) // replace & perf counter
166  val stageResp_valid_1cycle_dup = Wire(Vec(2, Bool()))
167  stageResp_valid_1cycle_dup.map(_ := OneCycleValid(stageCheck(1).fire, flush))  // ecc flush
168
169  stageReq <> io.req
170  PipelineConnect(stageReq, stageDelay(0), stageDelay(1).ready, flush, rwHarzad)
171  InsideStageConnect(stageDelay(0), stageDelay(1), stageDelay_valid_1cycle)
172  PipelineConnect(stageDelay(1), stageCheck(0), stageCheck(1).ready, flush)
173  InsideStageConnect(stageCheck(0), stageCheck(1), stageCheck_valid_1cycle)
174  PipelineConnect(stageCheck(1), stageResp, io.resp.ready, flush)
175  stageResp.ready := !stageResp.valid || io.resp.ready
176
177  // l1: level 0 non-leaf pte
178  val l1 = Reg(Vec(l2tlbParams.l1Size, new PtwEntry(tagLen = PtwL1TagLen)))
179  val l1v = RegInit(0.U(l2tlbParams.l1Size.W))
180  val l1g = Reg(UInt(l2tlbParams.l1Size.W))
181  val l1asids = l1.map(_.asid)
182  val l1vmids = l1.map(_.vmid)
183  val l1h = Reg(Vec(l2tlbParams.l1Size, UInt(2.W))) // 0 bit: s2xlate, 1 bit: stage 1 or stage 2
184
185  // l2: level 1 non-leaf pte
186  val l2 = Module(new SRAMTemplate(
187    l2EntryType,
188    set = l2tlbParams.l2nSets,
189    way = l2tlbParams.l2nWays,
190    singlePort = sramSinglePort
191  ))
192  val l2v = RegInit(0.U((l2tlbParams.l2nSets * l2tlbParams.l2nWays).W))
193  val l2g = Reg(UInt((l2tlbParams.l2nSets * l2tlbParams.l2nWays).W))
194  val l2h = Reg(Vec(l2tlbParams.l2nSets, Vec(l2tlbParams.l2nWays, UInt(2.W))))
195  def getl2vSet(vpn: UInt) = {
196    require(log2Up(l2tlbParams.l2nWays) == log2Down(l2tlbParams.l2nWays))
197    val set = genPtwL2SetIdx(vpn)
198    require(set.getWidth == log2Up(l2tlbParams.l2nSets))
199    val l2vVec = l2v.asTypeOf(Vec(l2tlbParams.l2nSets, UInt(l2tlbParams.l2nWays.W)))
200    l2vVec(set)
201  }
202  def getl2hSet(vpn: UInt) = {
203    require(log2Up(l2tlbParams.l2nWays) == log2Down(l2tlbParams.l2nWays))
204    val set = genPtwL2SetIdx(vpn)
205    require(set.getWidth == log2Up(l2tlbParams.l2nSets))
206    l2h(set)
207  }
208
209
210
211  // l3: level 2 leaf pte of 4KB pages
212  val l3 = Module(new SRAMTemplate(
213    l3EntryType,
214    set = l2tlbParams.l3nSets,
215    way = l2tlbParams.l3nWays,
216    singlePort = sramSinglePort
217  ))
218  val l3v = RegInit(0.U((l2tlbParams.l3nSets * l2tlbParams.l3nWays).W))
219  val l3g = Reg(UInt((l2tlbParams.l3nSets * l2tlbParams.l3nWays).W))
220  val l3h = Reg(Vec(l2tlbParams.l3nSets, Vec(l2tlbParams.l3nWays, UInt(2.W))))
221  def getl3vSet(vpn: UInt) = {
222    require(log2Up(l2tlbParams.l3nWays) == log2Down(l2tlbParams.l3nWays))
223    val set = genPtwL3SetIdx(vpn)
224    require(set.getWidth == log2Up(l2tlbParams.l3nSets))
225    val l3vVec = l3v.asTypeOf(Vec(l2tlbParams.l3nSets, UInt(l2tlbParams.l3nWays.W)))
226    l3vVec(set)
227  }
228  def getl3hSet(vpn: UInt) = {
229    require(log2Up(l2tlbParams.l3nWays) == log2Down(l2tlbParams.l3nWays))
230    val set = genPtwL3SetIdx(vpn)
231    require(set.getWidth == log2Up(l2tlbParams.l3nSets))
232    l3h(set)
233  }
234
235  // sp: level 0/1 leaf pte of 1GB/2MB super pages
236  val sp = Reg(Vec(l2tlbParams.spSize, new PtwEntry(tagLen = SPTagLen, hasPerm = true, hasLevel = true)))
237  val spv = RegInit(0.U(l2tlbParams.spSize.W))
238  val spg = Reg(UInt(l2tlbParams.spSize.W))
239  val spasids = sp.map(_.asid)
240  val spvmids = sp.map(_.vmid)
241  val sph = Reg(Vec(l2tlbParams.spSize, UInt(2.W)))
242
243  // Access Perf
244  val l1AccessPerf = Wire(Vec(l2tlbParams.l1Size, Bool()))
245  val l2AccessPerf = Wire(Vec(l2tlbParams.l2nWays, Bool()))
246  val l3AccessPerf = Wire(Vec(l2tlbParams.l3nWays, Bool()))
247  val spAccessPerf = Wire(Vec(l2tlbParams.spSize, Bool()))
248  l1AccessPerf.map(_ := false.B)
249  l2AccessPerf.map(_ := false.B)
250  l3AccessPerf.map(_ := false.B)
251  spAccessPerf.map(_ := false.B)
252
253
254
255  def vpn_match(vpn1: UInt, vpn2: UInt, level: Int) = {
256    (vpn1(vpnLen-1, vpnnLen*(2-level)+3) === vpn2(vpnLen-1, vpnnLen*(2-level)+3))
257  }
258  // NOTE: not actually bypassed, just check if hit, re-access the page cache
259  def refill_bypass(vpn: UInt, level: Int, h_search: UInt) = {
260    val refill_vpn = io.refill.bits.req_info_dup(0).vpn
261    io.refill.valid && (level.U === io.refill.bits.level_dup(0)) && vpn_match(refill_vpn, vpn, level) && h_search === io.refill.bits.req_info_dup(0).s2xlate
262  }
263
264  val vpn_search = stageReq.bits.req_info.vpn
265  val h_search = stageReq.bits.req_info.s2xlate
266  // l1
267  val ptwl1replace = ReplacementPolicy.fromString(l2tlbParams.l1Replacer, l2tlbParams.l1Size)
268  val (l1Hit, l1HitPPN, l1Pre) = {
269    val hitVecT = l1.zipWithIndex.map {
270      case (e, i) => (e.hit(vpn_search, io.csr_dup(0).satp.asid, io.csr_dup(0).hgatp.asid, s2xlate = h_search =/= noS2xlate)
271        && l1v(i) && h_search === l1h(i))
272    }
273    val hitVec = hitVecT.map(RegEnable(_, stageReq.fire))
274
275    // stageDelay, but check for l1
276    val hitPPN = DataHoldBypass(ParallelPriorityMux(hitVec zip l1.map(_.ppn)), stageDelay_valid_1cycle)
277    val hitPre = DataHoldBypass(ParallelPriorityMux(hitVec zip l1.map(_.prefetch)), stageDelay_valid_1cycle)
278    val hit = DataHoldBypass(ParallelOR(hitVec), stageDelay_valid_1cycle)
279
280    when (hit && stageDelay_valid_1cycle) { ptwl1replace.access(OHToUInt(hitVec)) }
281
282    l1AccessPerf.zip(hitVec).map{ case (l, h) => l := h && stageDelay_valid_1cycle}
283    for (i <- 0 until l2tlbParams.l1Size) {
284      XSDebug(stageReq.fire, p"[l1] l1(${i.U}) ${l1(i)} hit:${l1(i).hit(vpn_search, Mux(h_search =/= noS2xlate, io.csr_dup(0).vsatp.asid, io.csr_dup(0).satp.asid), io.csr_dup(0).hgatp.asid, s2xlate = h_search =/= noS2xlate)}\n")
285    }
286    XSDebug(stageReq.fire, p"[l1] l1v:${Binary(l1v)} hitVecT:${Binary(VecInit(hitVecT).asUInt)}\n")
287    XSDebug(stageDelay(0).valid, p"[l1] l1Hit:${hit} l1HitPPN:0x${Hexadecimal(hitPPN)} hitVec:${VecInit(hitVec).asUInt}\n")
288
289    VecInit(hitVecT).suggestName(s"l1_hitVecT")
290    VecInit(hitVec).suggestName(s"l1_hitVec")
291
292    // synchronize with other entries with RegEnable
293    (RegEnable(hit, stageDelay(1).fire),
294     RegEnable(hitPPN, stageDelay(1).fire),
295     RegEnable(hitPre, stageDelay(1).fire))
296  }
297
298  // l2
299  val ptwl2replace = ReplacementPolicy.fromString(l2tlbParams.l2Replacer,l2tlbParams.l2nWays,l2tlbParams.l2nSets)
300  val (l2Hit, l2HitPPN, l2Pre, l2eccError) = {
301    val ridx = genPtwL2SetIdx(vpn_search)
302    l2.io.r.req.valid := stageReq.fire
303    l2.io.r.req.bits.apply(setIdx = ridx)
304    val vVec_req = getl2vSet(vpn_search)
305    val hVec_req = getl2hSet(vpn_search)
306
307    // delay one cycle after sram read
308    val delay_vpn = stageDelay(0).bits.req_info.vpn
309    val delay_h = stageDelay(0).bits.req_info.s2xlate
310    val data_resp = DataHoldBypass(l2.io.r.resp.data, stageDelay_valid_1cycle)
311    val vVec_delay = RegEnable(vVec_req, stageReq.fire)
312    val hVec_delay = RegEnable(hVec_req, stageReq.fire)
313    val hitVec_delay = VecInit(data_resp.zip(vVec_delay.asBools).zip(hVec_delay).map { case ((wayData, v), h) =>
314      wayData.entries.hit(delay_vpn, io.csr_dup(1).satp.asid, io.csr_dup(1).hgatp.asid, s2xlate = delay_h =/= noS2xlate) && v && (delay_h === h)})
315
316    // check hit and ecc
317    val check_vpn = stageCheck(0).bits.req_info.vpn
318    val ramDatas = RegEnable(data_resp, stageDelay(1).fire)
319    val vVec = RegEnable(vVec_delay, stageDelay(1).fire).asBools
320
321    val hitVec = RegEnable(hitVec_delay, stageDelay(1).fire)
322    val hitWayEntry = ParallelPriorityMux(hitVec zip ramDatas)
323    val hitWayData = hitWayEntry.entries
324    val hit = ParallelOR(hitVec)
325    val hitWay = ParallelPriorityMux(hitVec zip (0 until l2tlbParams.l2nWays).map(_.U(log2Up(l2tlbParams.l2nWays).W)))
326    val eccError = hitWayEntry.decode()
327
328    ridx.suggestName(s"l2_ridx")
329    ramDatas.suggestName(s"l2_ramDatas")
330    hitVec.suggestName(s"l2_hitVec")
331    hitWayData.suggestName(s"l2_hitWayData")
332    hitWay.suggestName(s"l2_hitWay")
333
334    when (hit && stageCheck_valid_1cycle) { ptwl2replace.access(genPtwL2SetIdx(check_vpn), hitWay) }
335
336    l2AccessPerf.zip(hitVec).map{ case (l, h) => l := h && stageCheck_valid_1cycle }
337    XSDebug(stageDelay_valid_1cycle, p"[l2] ridx:0x${Hexadecimal(ridx)}\n")
338    for (i <- 0 until l2tlbParams.l2nWays) {
339      XSDebug(stageCheck_valid_1cycle, p"[l2] ramDatas(${i.U}) ${ramDatas(i)}  l2v:${vVec(i)}  hit:${hit}\n")
340    }
341    XSDebug(stageCheck_valid_1cycle, p"[l2] l2Hit:${hit} l2HitPPN:0x${Hexadecimal(hitWayData.ppns(genPtwL2SectorIdx(check_vpn)))} hitVec:${Binary(hitVec.asUInt)} hitWay:${hitWay} vidx:${vVec}\n")
342
343    (hit, hitWayData.ppns(genPtwL2SectorIdx(check_vpn)), hitWayData.prefetch, eccError)
344  }
345
346  // l3
347  val ptwl3replace = ReplacementPolicy.fromString(l2tlbParams.l3Replacer,l2tlbParams.l3nWays,l2tlbParams.l3nSets)
348  val (l3Hit, l3HitData, l3Pre, l3eccError) = {
349    val ridx = genPtwL3SetIdx(vpn_search)
350    l3.io.r.req.valid := stageReq.fire
351    l3.io.r.req.bits.apply(setIdx = ridx)
352    val vVec_req = getl3vSet(vpn_search)
353    val hVec_req = getl3hSet(vpn_search)
354
355    // delay one cycle after sram read
356    val delay_vpn = stageDelay(0).bits.req_info.vpn
357    val delay_h = stageDelay(0).bits.req_info.s2xlate
358    val data_resp = DataHoldBypass(l3.io.r.resp.data, stageDelay_valid_1cycle)
359    val vVec_delay = RegEnable(vVec_req, stageReq.fire)
360    val hVec_delay = RegEnable(hVec_req, stageReq.fire)
361    val hitVec_delay = VecInit(data_resp.zip(vVec_delay.asBools).zip(hVec_delay).map { case ((wayData, v), h) =>
362      wayData.entries.hit(delay_vpn, io.csr_dup(2).satp.asid, io.csr_dup(2).hgatp.asid, s2xlate = delay_h =/= noS2xlate) && v && (delay_h === h)})
363
364    // check hit and ecc
365    val check_vpn = stageCheck(0).bits.req_info.vpn
366    val ramDatas = RegEnable(data_resp, stageDelay(1).fire)
367    val vVec = RegEnable(vVec_delay, stageDelay(1).fire).asBools
368
369    val hitVec = RegEnable(hitVec_delay, stageDelay(1).fire)
370    val hitWayEntry = ParallelPriorityMux(hitVec zip ramDatas)
371    val hitWayData = hitWayEntry.entries
372    val hitWayEcc = hitWayEntry.ecc
373    val hit = ParallelOR(hitVec)
374    val hitWay = ParallelPriorityMux(hitVec zip (0 until l2tlbParams.l3nWays).map(_.U(log2Up(l2tlbParams.l3nWays).W)))
375    val eccError = hitWayEntry.decode()
376
377    when (hit && stageCheck_valid_1cycle) { ptwl3replace.access(genPtwL3SetIdx(check_vpn), hitWay) }
378
379    l3AccessPerf.zip(hitVec).map{ case (l, h) => l := h && stageCheck_valid_1cycle }
380    XSDebug(stageReq.fire, p"[l3] ridx:0x${Hexadecimal(ridx)}\n")
381    for (i <- 0 until l2tlbParams.l3nWays) {
382      XSDebug(stageCheck_valid_1cycle, p"[l3] ramDatas(${i.U}) ${ramDatas(i)}  l3v:${vVec(i)}  hit:${hitVec(i)}\n")
383    }
384    XSDebug(stageCheck_valid_1cycle, p"[l3] l3Hit:${hit} l3HitData:${hitWayData} hitVec:${Binary(hitVec.asUInt)} hitWay:${hitWay} v:${vVec}\n")
385
386    ridx.suggestName(s"l3_ridx")
387    ramDatas.suggestName(s"l3_ramDatas")
388    hitVec.suggestName(s"l3_hitVec")
389    hitWay.suggestName(s"l3_hitWay")
390
391    (hit, hitWayData, hitWayData.prefetch, eccError)
392  }
393  val l3HitPPN = l3HitData.ppns
394  val l3HitPerm = l3HitData.perms.getOrElse(0.U.asTypeOf(Vec(PtwL3SectorSize, new PtePermBundle)))
395  val l3HitValid = l3HitData.vs
396
397  // super page
398  val spreplace = ReplacementPolicy.fromString(l2tlbParams.spReplacer, l2tlbParams.spSize)
399  val (spHit, spHitData, spPre, spValid) = {
400    val hitVecT = sp.zipWithIndex.map { case (e, i) => e.hit(vpn_search, Mux(h_search =/= noS2xlate, io.csr_dup(0).vsatp.asid, io.csr_dup(0).satp.asid), io.csr_dup(0).hgatp.asid, s2xlate = h_search =/= noS2xlate) && spv(i) && (sph(i) === h_search) }
401    val hitVec = hitVecT.map(RegEnable(_, stageReq.fire))
402    val hitData = ParallelPriorityMux(hitVec zip sp)
403    val hit = ParallelOR(hitVec)
404
405    when (hit && stageDelay_valid_1cycle) { spreplace.access(OHToUInt(hitVec)) }
406
407    spAccessPerf.zip(hitVec).map{ case (s, h) => s := h && stageDelay_valid_1cycle }
408    for (i <- 0 until l2tlbParams.spSize) {
409      XSDebug(stageReq.fire, p"[sp] sp(${i.U}) ${sp(i)} hit:${sp(i).hit(vpn_search, Mux(h_search =/= noS2xlate, io.csr_dup(0).vsatp.asid, io.csr_dup(0).satp.asid), io.csr_dup(0).hgatp.asid, s2xlate = h_search =/= noS2xlate)} spv:${spv(i)}\n")
410    }
411    XSDebug(stageDelay_valid_1cycle, p"[sp] spHit:${hit} spHitData:${hitData} hitVec:${Binary(VecInit(hitVec).asUInt)}\n")
412
413    VecInit(hitVecT).suggestName(s"sp_hitVecT")
414    VecInit(hitVec).suggestName(s"sp_hitVec")
415
416    (RegEnable(hit, stageDelay(1).fire),
417     RegEnable(hitData, stageDelay(1).fire),
418     RegEnable(hitData.prefetch, stageDelay(1).fire),
419     RegEnable(hitData.v, stageDelay(1).fire))
420  }
421  val spHitPerm = spHitData.perm.getOrElse(0.U.asTypeOf(new PtePermBundle))
422  val spHitLevel = spHitData.level.getOrElse(0.U)
423
424  val check_res = Wire(new PageCacheRespBundle)
425  check_res.l1.apply(l1Hit, l1Pre, l1HitPPN)
426  check_res.l2.apply(l2Hit, l2Pre, l2HitPPN, ecc = l2eccError)
427  check_res.l3.apply(l3Hit, l3Pre, l3HitPPN, l3HitPerm, l3eccError, valid = l3HitValid)
428  check_res.sp.apply(spHit, spPre, spHitData.ppn, spHitPerm, false.B, spHitLevel, spValid)
429
430  val resp_res = Reg(new PageCacheRespBundle)
431  when (stageCheck(1).fire) { resp_res := check_res }
432
433  // stageResp bypass
434  val bypassed = Wire(Vec(3, Bool()))
435  bypassed.indices.foreach(i =>
436    bypassed(i) := stageResp.bits.bypassed(i) ||
437      ValidHoldBypass(refill_bypass(vpn_search, i, h_search),
438        OneCycleValid(stageCheck(1).fire, false.B) || io.refill.valid)
439  )
440
441  io.resp.bits.req_info   := stageResp.bits.req_info
442  io.resp.bits.isFirst  := stageResp.bits.isFirst
443  io.resp.bits.hit      := resp_res.l3.hit || resp_res.sp.hit
444  io.resp.bits.bypassed := bypassed(2) || (bypassed(1) && !resp_res.l2.hit) || (bypassed(0) && !resp_res.l1.hit)
445  io.resp.bits.prefetch := resp_res.l3.pre && resp_res.l3.hit || resp_res.sp.pre && resp_res.sp.hit
446  io.resp.bits.toFsm.l1Hit := resp_res.l1.hit
447  io.resp.bits.toFsm.l2Hit := resp_res.l2.hit
448  io.resp.bits.toFsm.ppn   := Mux(resp_res.l2.hit, resp_res.l2.ppn, resp_res.l1.ppn)
449
450  io.resp.bits.isHptw := stageResp.bits.isHptw
451  io.resp.bits.toHptw.id := stageResp.bits.hptwId
452  io.resp.bits.toHptw.l1Hit := resp_res.l1.hit
453  io.resp.bits.toHptw.l2Hit := resp_res.l2.hit
454  io.resp.bits.toHptw.ppn := Mux(resp_res.l2.hit, resp_res.l2.ppn, resp_res.l1.ppn)
455  val idx = stageResp.bits.req_info.vpn(2, 0)
456  io.resp.bits.toHptw.resp.entry.tag := stageResp.bits.req_info.vpn
457  io.resp.bits.toHptw.resp.entry.asid := DontCare
458  io.resp.bits.toHptw.resp.entry.vmid.map(_ := io.csr_dup(0).hgatp.asid)
459  io.resp.bits.toHptw.resp.entry.level.map(_ := Mux(resp_res.l3.hit, 2.U, resp_res.sp.level))
460  io.resp.bits.toHptw.resp.entry.prefetch := from_pre(stageResp.bits.req_info.source)
461  io.resp.bits.toHptw.resp.entry.ppn := Mux(resp_res.l3.hit, resp_res.l3.ppn(idx), resp_res.sp.ppn)
462  io.resp.bits.toHptw.resp.entry.perm.map(_ := Mux(resp_res.l3.hit, resp_res.l3.perm(idx), resp_res.sp.perm))
463  io.resp.bits.toHptw.resp.entry.v := Mux(resp_res.l3.hit, resp_res.l3.v(idx), resp_res.sp.v)
464  io.resp.bits.toHptw.resp.gpf := !io.resp.bits.toHptw.resp.entry.v
465  io.resp.bits.toHptw.resp.gaf := false.B
466
467  io.resp.bits.toTlb.entry.map(_.tag := stageResp.bits.req_info.vpn(vpnLen - 1, 3))
468  io.resp.bits.toTlb.entry.map(_.asid := Mux(stageResp.bits.req_info.hasS2xlate(), io.csr_dup(0).vsatp.asid, io.csr_dup(0).satp.asid)) // DontCare
469  io.resp.bits.toTlb.entry.map(_.vmid.map(_ := io.csr_dup(0).hgatp.asid))
470  io.resp.bits.toTlb.entry.map(_.level.map(_ := Mux(resp_res.l3.hit, 2.U, resp_res.sp.level)))
471  io.resp.bits.toTlb.entry.map(_.prefetch := from_pre(stageResp.bits.req_info.source))
472  for (i <- 0 until tlbcontiguous) {
473    io.resp.bits.toTlb.entry(i).ppn := Mux(resp_res.l3.hit, resp_res.l3.ppn(i)(ppnLen - 1, sectortlbwidth), resp_res.sp.ppn(ppnLen - 1, sectortlbwidth))
474    io.resp.bits.toTlb.entry(i).ppn_low := Mux(resp_res.l3.hit, resp_res.l3.ppn(i)(sectortlbwidth - 1, 0), resp_res.sp.ppn(sectortlbwidth - 1, 0))
475    io.resp.bits.toTlb.entry(i).perm.map(_ := Mux(resp_res.l3.hit, resp_res.l3.perm(i), resp_res.sp.perm))
476    io.resp.bits.toTlb.entry(i).v := Mux(resp_res.l3.hit, resp_res.l3.v(i), resp_res.sp.v)
477    io.resp.bits.toTlb.entry(i).pf := !io.resp.bits.toTlb.entry(i).v
478    io.resp.bits.toTlb.entry(i).af := false.B
479  }
480  io.resp.bits.toTlb.pteidx := UIntToOH(stageResp.bits.req_info.vpn(2, 0)).asBools
481  io.resp.bits.toTlb.not_super := Mux(resp_res.l3.hit, true.B, false.B)
482  io.resp.valid := stageResp.valid
483  XSError(stageResp.valid && resp_res.l3.hit && resp_res.sp.hit, "normal page and super page both hit")
484  XSError(stageResp.valid && io.resp.bits.hit && bypassed(2), "page cache, bypassed but hit")
485
486  // refill Perf
487  val l1RefillPerf = Wire(Vec(l2tlbParams.l1Size, Bool()))
488  val l2RefillPerf = Wire(Vec(l2tlbParams.l2nWays, Bool()))
489  val l3RefillPerf = Wire(Vec(l2tlbParams.l3nWays, Bool()))
490  val spRefillPerf = Wire(Vec(l2tlbParams.spSize, Bool()))
491  l1RefillPerf.map(_ := false.B)
492  l2RefillPerf.map(_ := false.B)
493  l3RefillPerf.map(_ := false.B)
494  spRefillPerf.map(_ := false.B)
495
496  // refill
497  l2.io.w.req <> DontCare
498  l3.io.w.req <> DontCare
499  l2.io.w.req.valid := false.B
500  l3.io.w.req.valid := false.B
501
502  val memRdata = refill.ptes
503  val memPtes = (0 until (l2tlbParams.blockBytes/(XLEN/8))).map(i => memRdata((i+1)*XLEN-1, i*XLEN).asTypeOf(new PteBundle))
504  val memSelData = io.refill.bits.sel_pte_dup
505  val memPte = memSelData.map(a => a.asTypeOf(new PteBundle))
506
507  // TODO: handle sfenceLatch outsize
508  when (!flush_dup(0) && refill.levelOH.l1 && !memPte(0).isLeaf() && !memPte(0).isPf(refill.level_dup(0)) && !memPte(0).isAf()) {
509    // val refillIdx = LFSR64()(log2Up(l2tlbParams.l1Size)-1,0) // TODO: may be LRU
510    val refillIdx = replaceWrapper(l1v, ptwl1replace.way)
511    refillIdx.suggestName(s"PtwL1RefillIdx")
512    val rfOH = UIntToOH(refillIdx)
513    l1(refillIdx).refill(
514      refill.req_info_dup(0).vpn,
515      Mux(refill.req_info_dup(0).s2xlate(0).asBool(), io.csr_dup(0).vsatp.asid, io.csr_dup(0).satp.asid),
516      io.csr_dup(0).hgatp.asid,
517      memSelData(0),
518      0.U,
519      refill_prefetch_dup(0)
520    )
521    ptwl1replace.access(refillIdx)
522    l1v := l1v | rfOH
523    l1g := (l1g & ~rfOH) | Mux(memPte(0).perm.g, rfOH, 0.U)
524    l1h(refillIdx) := refill.req_info_dup(0).s2xlate
525
526    for (i <- 0 until l2tlbParams.l1Size) {
527      l1RefillPerf(i) := i.U === refillIdx
528    }
529
530    XSDebug(p"[l1 refill] refillIdx:${refillIdx} refillEntry:${l1(refillIdx).genPtwEntry(refill.req_info_dup(0).vpn, io.csr_dup(0).satp.asid, memSelData(0), 0.U, prefetch = refill_prefetch_dup(0))}\n")
531    XSDebug(p"[l1 refill] l1v:${Binary(l1v)}->${Binary(l1v | rfOH)} l1g:${Binary(l1g)}->${Binary((l1g & ~rfOH) | Mux(memPte(0).perm.g, rfOH, 0.U))}\n")
532
533    refillIdx.suggestName(s"l1_refillIdx")
534    rfOH.suggestName(s"l1_rfOH")
535  }
536
537  when (!flush_dup(1) && refill.levelOH.l2 && !memPte(1).isLeaf() && !memPte(1).isPf(refill.level_dup(1)) && !memPte(1).isAf()) {
538    val refillIdx = genPtwL2SetIdx(refill.req_info_dup(1).vpn)
539    val victimWay = replaceWrapper(getl2vSet(refill.req_info_dup(1).vpn), ptwl2replace.way(refillIdx))
540    val victimWayOH = UIntToOH(victimWay)
541    val rfvOH = UIntToOH(Cat(refillIdx, victimWay))
542    val wdata = Wire(l2EntryType)
543    wdata.gen(
544      vpn = refill.req_info_dup(1).vpn,
545      asid = Mux(refill.req_info_dup(1).s2xlate =/= noS2xlate, io.csr_dup(1).vsatp.asid, io.csr_dup(1).satp.asid),
546      vmid = io.csr_dup(1).hgatp.asid,
547      data = memRdata,
548      levelUInt = 1.U,
549      refill_prefetch_dup(1)
550    )
551    l2.io.w.apply(
552      valid = true.B,
553      setIdx = refillIdx,
554      data = wdata,
555      waymask = victimWayOH
556    )
557    ptwl2replace.access(refillIdx, victimWay)
558    l2v := l2v | rfvOH
559    l2g := l2g & ~rfvOH | Mux(Cat(memPtes.map(_.perm.g)).andR, rfvOH, 0.U)
560    l2h(refillIdx)(victimWay) := refill.req_info_dup(0).s2xlate
561
562    for (i <- 0 until l2tlbParams.l2nWays) {
563      l2RefillPerf(i) := i.U === victimWay
564    }
565
566    XSDebug(p"[l2 refill] refillIdx:0x${Hexadecimal(refillIdx)} victimWay:${victimWay} victimWayOH:${Binary(victimWayOH)} rfvOH(in UInt):${Cat(refillIdx, victimWay)}\n")
567    XSDebug(p"[l2 refill] refilldata:0x${wdata}\n")
568    XSDebug(p"[l2 refill] l2v:${Binary(l2v)} -> ${Binary(l2v | rfvOH)}\n")
569    XSDebug(p"[l2 refill] l2g:${Binary(l2g)} -> ${Binary(l2g & ~rfvOH | Mux(Cat(memPtes.map(_.perm.g)).andR, rfvOH, 0.U))}\n")
570
571    refillIdx.suggestName(s"l2_refillIdx")
572    victimWay.suggestName(s"l2_victimWay")
573    victimWayOH.suggestName(s"l2_victimWayOH")
574    rfvOH.suggestName(s"l2_rfvOH")
575  }
576
577  when (!flush_dup(2) && refill.levelOH.l3 && !memPte(2).isAf()) {
578    val refillIdx = genPtwL3SetIdx(refill.req_info_dup(2).vpn)
579    val victimWay = replaceWrapper(getl3vSet(refill.req_info_dup(2).vpn), ptwl3replace.way(refillIdx))
580    val victimWayOH = UIntToOH(victimWay)
581    val rfvOH = UIntToOH(Cat(refillIdx, victimWay))
582    val wdata = Wire(l3EntryType)
583    wdata.gen(
584      vpn =  refill.req_info_dup(2).vpn,
585      asid = Mux(refill.req_info_dup(2).s2xlate =/= noS2xlate, io.csr_dup(2).vsatp.asid, io.csr_dup(2).satp.asid),
586      vmid = io.csr_dup(2).hgatp.asid,
587      data = memRdata,
588      levelUInt = 2.U,
589      refill_prefetch_dup(2)
590    )
591    l3.io.w.apply(
592      valid = true.B,
593      setIdx = refillIdx,
594      data = wdata,
595      waymask = victimWayOH
596    )
597    ptwl3replace.access(refillIdx, victimWay)
598    l3v := l3v | rfvOH
599    l3g := l3g & ~rfvOH | Mux(Cat(memPtes.map(_.perm.g)).andR, rfvOH, 0.U)
600    l3h(refillIdx)(victimWay) := refill.req_info_dup(2).s2xlate
601
602    for (i <- 0 until l2tlbParams.l3nWays) {
603      l3RefillPerf(i) := i.U === victimWay
604    }
605
606    XSDebug(p"[l3 refill] refillIdx:0x${Hexadecimal(refillIdx)} victimWay:${victimWay} victimWayOH:${Binary(victimWayOH)} rfvOH(in UInt):${Cat(refillIdx, victimWay)}\n")
607    XSDebug(p"[l3 refill] refilldata:0x${wdata}\n")
608    XSDebug(p"[l3 refill] l3v:${Binary(l3v)} -> ${Binary(l3v | rfvOH)}\n")
609    XSDebug(p"[l3 refill] l3g:${Binary(l3g)} -> ${Binary(l3g & ~rfvOH | Mux(Cat(memPtes.map(_.perm.g)).andR, rfvOH, 0.U))}\n")
610
611    refillIdx.suggestName(s"l3_refillIdx")
612    victimWay.suggestName(s"l3_victimWay")
613    victimWayOH.suggestName(s"l3_victimWayOH")
614    rfvOH.suggestName(s"l3_rfvOH")
615  }
616
617
618  // misc entries: super & invalid
619  when (!flush_dup(0) && refill.levelOH.sp && (memPte(0).isLeaf() || memPte(0).isPf(refill.level_dup(0))) && !memPte(0).isAf()) {
620    val refillIdx = spreplace.way// LFSR64()(log2Up(l2tlbParams.spSize)-1,0) // TODO: may be LRU
621    val rfOH = UIntToOH(refillIdx)
622    sp(refillIdx).refill(
623      refill.req_info_dup(0).vpn,
624      io.csr_dup(0).satp.asid,
625      io.csr_dup(0).hgatp.asid,
626      memSelData(0),
627      refill.level_dup(2),
628      refill_prefetch_dup(0),
629      !memPte(0).isPf(refill.level_dup(0)),
630    )
631    spreplace.access(refillIdx)
632    spv := spv | rfOH
633    spg := spg & ~rfOH | Mux(memPte(0).perm.g, rfOH, 0.U)
634    sph(refillIdx) := refill.req_info_dup(0).s2xlate
635
636    for (i <- 0 until l2tlbParams.spSize) {
637      spRefillPerf(i) := i.U === refillIdx
638    }
639
640    XSDebug(p"[sp refill] refillIdx:${refillIdx} refillEntry:${sp(refillIdx).genPtwEntry(refill.req_info_dup(0).vpn, io.csr_dup(0).satp.asid, memSelData(0), refill.level_dup(0), refill_prefetch_dup(0))}\n")
641    XSDebug(p"[sp refill] spv:${Binary(spv)}->${Binary(spv | rfOH)} spg:${Binary(spg)}->${Binary(spg & ~rfOH | Mux(memPte(0).perm.g, rfOH, 0.U))}\n")
642
643    refillIdx.suggestName(s"sp_refillIdx")
644    rfOH.suggestName(s"sp_rfOH")
645  }
646
647  val l2eccFlush = resp_res.l2.ecc && stageResp_valid_1cycle_dup(0) // RegNext(l2eccError, init = false.B)
648  val l3eccFlush = resp_res.l3.ecc && stageResp_valid_1cycle_dup(1) // RegNext(l3eccError, init = false.B)
649  val eccVpn = stageResp.bits.req_info.vpn
650
651  XSError(l2eccFlush, "l2tlb.cache.l2 ecc error. Should not happen at sim stage")
652  XSError(l3eccFlush, "l2tlb.cache.l3 ecc error. Should not happen at sim stage")
653  when (l2eccFlush) {
654    val flushSetIdxOH = UIntToOH(genPtwL2SetIdx(eccVpn))
655    val flushMask = VecInit(flushSetIdxOH.asBools.map { a => Fill(l2tlbParams.l2nWays, a.asUInt) }).asUInt
656    l2v := l2v & ~flushMask
657    l2g := l2g & ~flushMask
658  }
659
660  when (l3eccFlush) {
661    val flushSetIdxOH = UIntToOH(genPtwL3SetIdx(eccVpn))
662    val flushMask = VecInit(flushSetIdxOH.asBools.map { a => Fill(l2tlbParams.l3nWays, a.asUInt) }).asUInt
663    l3v := l3v & ~flushMask
664    l3g := l3g & ~flushMask
665  }
666
667  // sfence for not-virtualization for l3、l2
668  val sfence_valid_l3 = sfence_dup(3).valid && !sfence_dup(3).bits.hg && !sfence_dup(3).bits.hv
669  when (sfence_valid_l3 && io.csr_dup(2).priv.virt === false.B) {
670    val sfence_vpn = sfence_dup(3).bits.addr(sfence_dup(3).bits.addr.getWidth-1, offLen)
671    when (sfence_dup(3).bits.rs1/*va*/) {
672      when (sfence_dup(3).bits.rs2) {
673        // all va && all asid
674        l3v := 0.U
675      } .otherwise {
676        // all va && specific asid except global
677        l3v := l3v & l3g
678      }
679    } .otherwise {
680      // val flushMask = UIntToOH(genTlbL2Idx(sfence.bits.addr(sfence.bits.addr.getWidth-1, offLen)))
681      val flushSetIdxOH = UIntToOH(genPtwL3SetIdx(sfence_vpn))
682      // val flushMask = VecInit(flushSetIdxOH.asBools.map(Fill(l2tlbParams.l3nWays, _.asUInt))).asUInt
683      val flushMask = VecInit(flushSetIdxOH.asBools.map { a => Fill(l2tlbParams.l3nWays, a.asUInt) }).asUInt
684      flushSetIdxOH.suggestName(s"sfence_nrs1_flushSetIdxOH")
685      flushMask.suggestName(s"sfence_nrs1_flushMask")
686
687      when (sfence_dup(3).bits.rs2) {
688        // specific leaf of addr && all asid
689        l3v := l3v & ~flushMask
690      } .otherwise {
691        // specific leaf of addr && specific asid
692        l3v := l3v & (~flushMask | l3g)
693      }
694    }
695  }
696
697  // sfence for virtualization and hfencev, simple implementation for l3、l2
698  val hfencev_valid_l3 = sfence_dup(3).valid && sfence_dup(3).bits.hv
699  when((hfencev_valid_l3 && io.csr_dup(2).priv.virt) || hfencev_valid_l3) {
700    val flushMask = VecInit(l3h.flatMap(_.map(_  === onlyStage1))).asUInt
701    l3v := l3v & ~flushMask // all VS-stage l3 pte
702  }
703
704  // hfenceg, simple implementation for l3
705  val hfenceg_valid_l3 = sfence_dup(3).valid && sfence_dup(3).bits.hg
706  when(hfenceg_valid_l3) {
707    val flushMask = VecInit(l3h.flatMap(_.map(_ === onlyStage2))).asUInt
708    l3v := l3v & ~flushMask // all G-stage l3 pte
709  }
710
711
712  val l1asidhit = VecInit(l1asids.map(_ === sfence_dup(0).bits.id)).asUInt
713  val spasidhit = VecInit(spasids.map(_ === sfence_dup(0).bits.id)).asUInt
714  val sfence_valid = sfence_dup(0).valid && !sfence_dup(0).bits.hg && !sfence_dup(0).bits.hv
715  when (sfence_valid) {
716    val l1vmidhit = VecInit(l1vmids.map(_.getOrElse(0.U) === io.csr_dup(0).hgatp.asid)).asUInt
717    val spvmidhit = VecInit(spvmids.map(_.getOrElse(0.U) === io.csr_dup(0).hgatp.asid)).asUInt
718    val l1hhit = VecInit(l1h.map(_ === onlyStage1 && io.csr_dup(0).priv.virt)).asUInt
719    val sphhit = VecInit(sph.map(_ === onlyStage1 && io.csr_dup(0).priv.virt)).asUInt
720    val l2hhit = VecInit(l2h.flatMap(_.map(_ === onlyStage1 && io.csr_dup(0).priv.virt))).asUInt
721    val sfence_vpn = sfence_dup(0).bits.addr(sfence_dup(0).bits.addr.getWidth-1, offLen)
722    val l2h_set = getl2hSet(sfence_vpn)
723
724    when (sfence_dup(0).bits.rs1/*va*/) {
725      when (sfence_dup(0).bits.rs2) {
726        // all va && all asid
727        l2v := l2v & ~l2hhit
728        l1v := l1v & ~(l1hhit & VecInit(UIntToOH(l1vmidhit).asBools().map{a => io.csr_dup(0).priv.virt && a || !io.csr_dup(0).priv.virt}).asUInt())
729        spv := spv & ~(l2hhit & VecInit(UIntToOH(spvmidhit).asBools().map{a => io.csr_dup(0).priv.virt && a || !io.csr_dup(0).priv.virt}).asUInt())
730      } .otherwise {
731        // all va && specific asid except global
732        l2v := l2v & (l2g | ~l2hhit)
733        l1v := l1v & ~(~l1g & l1hhit & l1asidhit & VecInit(UIntToOH(l1vmidhit).asBools().map{a => io.csr_dup(0).priv.virt && a || !io.csr_dup(0).priv.virt}).asUInt())
734        spv := spv & ~(~spg & sphhit & spasidhit & VecInit(UIntToOH(spvmidhit).asBools().map{a => io.csr_dup(0).priv.virt && a || !io.csr_dup(0).priv.virt}).asUInt())
735      }
736    } .otherwise {
737      when (sfence_dup(0).bits.rs2) {
738        // specific leaf of addr && all asid
739        spv := spv & (~VecInit(sp.map(_.hit(sfence_vpn, sfence_dup(0).bits.id, io.csr_dup(0).hgatp.asid, ignoreAsid = true, s2xlate = io.csr_dup(0).priv.virt))).asUInt)
740      } .otherwise {
741        // specific leaf of addr && specific asid
742        spv := spv & (~VecInit(sp.map(_.hit(sfence_vpn, sfence_dup(0).bits.id, io.csr_dup(0).hgatp.asid, s2xlate = io.csr_dup(0).priv.virt))).asUInt | spg)
743      }
744    }
745  }
746
747  val hfencev_valid = sfence_dup(0).valid && sfence_dup(0).bits.hv
748  when (hfencev_valid) {
749    val l1vmidhit = VecInit(l1vmids.map(_.getOrElse(0.U) === io.csr_dup(0).hgatp.asid)).asUInt
750    val spvmidhit = VecInit(spvmids.map(_.getOrElse(0.U) === io.csr_dup(0).hgatp.asid)).asUInt
751    val l1hhit = VecInit(l1h.map(_ === onlyStage1)).asUInt
752    val sphhit = VecInit(sph.map(_ === onlyStage1)).asUInt
753    val l2hhit = VecInit(l2h.flatMap(_.map(_ === onlyStage1))).asUInt
754    val hfencev_vpn = sfence_dup(0).bits.addr(sfence_dup(0).bits.addr.getWidth-1, offLen)
755    when(sfence_dup(0).bits.rs1) {
756      when(sfence_dup(0).bits.rs2) {
757        l2v := l2v & ~l2hhit
758        l1v := l1v & ~(l1hhit & l1vmidhit)
759        spv := spv & ~(l2hhit & spvmidhit)
760      }.otherwise {
761        l2v := l2v & (l2g | ~l2hhit)
762        l1v := l1v & ~(~l1g & l1hhit & l1asidhit & l1vmidhit)
763        spv := spv & ~(~spg & sphhit & spasidhit & spvmidhit)
764      }
765    }.otherwise {
766      when(sfence_dup(0).bits.rs2) {
767        spv := spv & (~VecInit(sp.map(_.hit(hfencev_vpn, sfence_dup(0).bits.id, io.csr_dup(0).hgatp.asid, ignoreAsid = true, s2xlate = true.B))).asUInt)
768      }.otherwise {
769        spv := spv & (~VecInit(sp.map(_.hit(hfencev_vpn, sfence_dup(0).bits.id, io.csr_dup(0).hgatp.asid, s2xlate = true.B))).asUInt | spg)
770      }
771    }
772  }
773
774
775  val hfenceg_valid = sfence_dup(0).valid && sfence_dup(0).bits.hg
776  when(hfenceg_valid) {
777    val l1vmidhit = VecInit(l1vmids.map(_.getOrElse(0.U) === sfence_dup(0).bits.id)).asUInt
778    val spvmidhit = VecInit(spvmids.map(_.getOrElse(0.U) === sfence_dup(0).bits.id)).asUInt
779    val l1hhit = VecInit(l1h.map(_ === onlyStage2)).asUInt
780    val sphhit = VecInit(sph.map(_ === onlyStage2)).asUInt
781    val l2hhit = VecInit(l2h.flatMap(_.map(_ === onlyStage2))).asUInt
782    val hfenceg_gvpn = sfence_dup(0).bits.addr(sfence_dup(0).bits.addr.getWidth - 1, offLen)
783    when(sfence_dup(0).bits.rs1) {
784      when(sfence_dup(0).bits.rs2) {
785        l2v := l2v & ~l2hhit
786        l1v := l1v & ~l1hhit
787        spv := spv & ~sphhit
788      }.otherwise {
789        l2v := l2v & ~l2hhit
790        l1v := l1v & ~(l1hhit & l1vmidhit)
791        spv := spv & ~(sphhit & spvmidhit)
792      }
793    }.otherwise {
794      when(sfence_dup(0).bits.rs2) {
795        spv := spv & (~VecInit(sp.map(_.hit(hfenceg_gvpn, 0.U, sfence_dup(0).bits.id, ignoreAsid = true, s2xlate = true.B))).asUInt)
796      }.otherwise {
797        spv := spv & (~VecInit(sp.map(_.hit(hfenceg_gvpn, 0.U, sfence_dup(0).bits.id, ignoreAsid = true, s2xlate = false.B))).asUInt)
798      }
799    }
800  }
801
802  def InsideStageConnect(in: DecoupledIO[PtwCacheReq], out: DecoupledIO[PtwCacheReq], inFire: Bool): Unit = {
803    in.ready := !in.valid || out.ready
804    out.valid := in.valid
805    out.bits := in.bits
806    out.bits.bypassed.zip(in.bits.bypassed).zipWithIndex.map{ case (b, i) =>
807      val bypassed_reg = Reg(Bool())
808      val bypassed_wire = refill_bypass(in.bits.req_info.vpn, i, in.bits.req_info.s2xlate) && io.refill.valid
809      when (inFire) { bypassed_reg := bypassed_wire }
810      .elsewhen (io.refill.valid) { bypassed_reg := bypassed_reg || bypassed_wire }
811
812      b._1 := b._2 || (bypassed_wire || (bypassed_reg && !inFire))
813    }
814  }
815
816  // Perf Count
817  val resp_l3 = resp_res.l3.hit
818  val resp_sp = resp_res.sp.hit
819  val resp_l1_pre = resp_res.l1.pre
820  val resp_l2_pre = resp_res.l2.pre
821  val resp_l3_pre = resp_res.l3.pre
822  val resp_sp_pre = resp_res.sp.pre
823  val base_valid_access_0 = !from_pre(io.resp.bits.req_info.source) && io.resp.fire
824  XSPerfAccumulate("access", base_valid_access_0)
825  XSPerfAccumulate("l1_hit", base_valid_access_0 && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
826  XSPerfAccumulate("l2_hit", base_valid_access_0 && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
827  XSPerfAccumulate("l3_hit", base_valid_access_0 && resp_l3)
828  XSPerfAccumulate("sp_hit", base_valid_access_0 && resp_sp)
829  XSPerfAccumulate("pte_hit",base_valid_access_0 && io.resp.bits.hit)
830
831  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)
832  XSPerfAccumulate("l2_hit_pre", base_valid_access_0 && resp_l2_pre && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
833  XSPerfAccumulate("l3_hit_pre", base_valid_access_0 && resp_l3_pre && resp_l3)
834  XSPerfAccumulate("sp_hit_pre", base_valid_access_0 && resp_sp_pre && resp_sp)
835  XSPerfAccumulate("pte_hit_pre",base_valid_access_0 && (resp_l3_pre && resp_l3 || resp_sp_pre && resp_sp) && io.resp.bits.hit)
836
837  val base_valid_access_1 = from_pre(io.resp.bits.req_info.source) && io.resp.fire
838  XSPerfAccumulate("pre_access", base_valid_access_1)
839  XSPerfAccumulate("pre_l1_hit", base_valid_access_1 && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
840  XSPerfAccumulate("pre_l2_hit", base_valid_access_1 && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
841  XSPerfAccumulate("pre_l3_hit", base_valid_access_1 && resp_l3)
842  XSPerfAccumulate("pre_sp_hit", base_valid_access_1 && resp_sp)
843  XSPerfAccumulate("pre_pte_hit",base_valid_access_1 && io.resp.bits.hit)
844
845  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)
846  XSPerfAccumulate("pre_l2_hit_pre", base_valid_access_1 && resp_l2_pre && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
847  XSPerfAccumulate("pre_l3_hit_pre", base_valid_access_1 && resp_l3_pre && resp_l3)
848  XSPerfAccumulate("pre_sp_hit_pre", base_valid_access_1 && resp_sp_pre && resp_sp)
849  XSPerfAccumulate("pre_pte_hit_pre",base_valid_access_1 && (resp_l3_pre && resp_l3 || resp_sp_pre && resp_sp) && io.resp.bits.hit)
850
851  val base_valid_access_2 = stageResp.bits.isFirst && !from_pre(io.resp.bits.req_info.source) && io.resp.fire
852  XSPerfAccumulate("access_first", base_valid_access_2)
853  XSPerfAccumulate("l1_hit_first", base_valid_access_2 && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
854  XSPerfAccumulate("l2_hit_first", base_valid_access_2 && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
855  XSPerfAccumulate("l3_hit_first", base_valid_access_2 && resp_l3)
856  XSPerfAccumulate("sp_hit_first", base_valid_access_2 && resp_sp)
857  XSPerfAccumulate("pte_hit_first",base_valid_access_2 && io.resp.bits.hit)
858
859  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)
860  XSPerfAccumulate("l2_hit_pre_first", base_valid_access_2 && resp_l2_pre && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
861  XSPerfAccumulate("l3_hit_pre_first", base_valid_access_2 && resp_l3_pre && resp_l3)
862  XSPerfAccumulate("sp_hit_pre_first", base_valid_access_2 && resp_sp_pre && resp_sp)
863  XSPerfAccumulate("pte_hit_pre_first",base_valid_access_2 && (resp_l3_pre && resp_l3 || resp_sp_pre && resp_sp) && io.resp.bits.hit)
864
865  val base_valid_access_3 = stageResp.bits.isFirst && from_pre(io.resp.bits.req_info.source) && io.resp.fire
866  XSPerfAccumulate("pre_access_first", base_valid_access_3)
867  XSPerfAccumulate("pre_l1_hit_first", base_valid_access_3 && io.resp.bits.toFsm.l1Hit && !io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
868  XSPerfAccumulate("pre_l2_hit_first", base_valid_access_3 && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
869  XSPerfAccumulate("pre_l3_hit_first", base_valid_access_3 && resp_l3)
870  XSPerfAccumulate("pre_sp_hit_first", base_valid_access_3 && resp_sp)
871  XSPerfAccumulate("pre_pte_hit_first", base_valid_access_3 && io.resp.bits.hit)
872
873  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)
874  XSPerfAccumulate("pre_l2_hit_pre_first", base_valid_access_3 && resp_l2_pre && io.resp.bits.toFsm.l2Hit && !io.resp.bits.hit)
875  XSPerfAccumulate("pre_l3_hit_pre_first", base_valid_access_3 && resp_l3_pre && resp_l3)
876  XSPerfAccumulate("pre_sp_hit_pre_first", base_valid_access_3 && resp_sp_pre && resp_sp)
877  XSPerfAccumulate("pre_pte_hit_pre_first",base_valid_access_3 && (resp_l3_pre && resp_l3 || resp_sp_pre && resp_sp) && io.resp.bits.hit)
878
879  XSPerfAccumulate("rwHarzad", io.req.valid && !io.req.ready)
880  XSPerfAccumulate("out_blocked", io.resp.valid && !io.resp.ready)
881  l1AccessPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L1AccessIndex${i}", l) }
882  l2AccessPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L2AccessIndex${i}", l) }
883  l3AccessPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L3AccessIndex${i}", l) }
884  spAccessPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"SPAccessIndex${i}", l) }
885  l1RefillPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L1RefillIndex${i}", l) }
886  l2RefillPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L2RefillIndex${i}", l) }
887  l3RefillPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"L3RefillIndex${i}", l) }
888  spRefillPerf.zipWithIndex.map{ case (l, i) => XSPerfAccumulate(s"SPRefillIndex${i}", l) }
889
890  XSPerfAccumulate("l1Refill", Cat(l1RefillPerf).orR)
891  XSPerfAccumulate("l2Refill", Cat(l2RefillPerf).orR)
892  XSPerfAccumulate("l3Refill", Cat(l3RefillPerf).orR)
893  XSPerfAccumulate("spRefill", Cat(spRefillPerf).orR)
894  XSPerfAccumulate("l1Refill_pre", Cat(l1RefillPerf).orR && refill_prefetch_dup(0))
895  XSPerfAccumulate("l2Refill_pre", Cat(l2RefillPerf).orR && refill_prefetch_dup(0))
896  XSPerfAccumulate("l3Refill_pre", Cat(l3RefillPerf).orR && refill_prefetch_dup(0))
897  XSPerfAccumulate("spRefill_pre", Cat(spRefillPerf).orR && refill_prefetch_dup(0))
898
899  // debug
900  XSDebug(sfence_dup(0).valid, p"[sfence] original v and g vector:\n")
901  XSDebug(sfence_dup(0).valid, p"[sfence] l1v:${Binary(l1v)}\n")
902  XSDebug(sfence_dup(0).valid, p"[sfence] l2v:${Binary(l2v)}\n")
903  XSDebug(sfence_dup(0).valid, p"[sfence] l3v:${Binary(l3v)}\n")
904  XSDebug(sfence_dup(0).valid, p"[sfence] l3g:${Binary(l3g)}\n")
905  XSDebug(sfence_dup(0).valid, p"[sfence] spv:${Binary(spv)}\n")
906  XSDebug(RegNext(sfence_dup(0).valid), p"[sfence] new v and g vector:\n")
907  XSDebug(RegNext(sfence_dup(0).valid), p"[sfence] l1v:${Binary(l1v)}\n")
908  XSDebug(RegNext(sfence_dup(0).valid), p"[sfence] l2v:${Binary(l2v)}\n")
909  XSDebug(RegNext(sfence_dup(0).valid), p"[sfence] l3v:${Binary(l3v)}\n")
910  XSDebug(RegNext(sfence_dup(0).valid), p"[sfence] l3g:${Binary(l3g)}\n")
911  XSDebug(RegNext(sfence_dup(0).valid), p"[sfence] spv:${Binary(spv)}\n")
912
913  val perfEvents = Seq(
914    ("access           ", base_valid_access_0             ),
915    ("l1_hit           ", l1Hit                           ),
916    ("l2_hit           ", l2Hit                           ),
917    ("l3_hit           ", l3Hit                           ),
918    ("sp_hit           ", spHit                           ),
919    ("pte_hit          ", l3Hit || spHit                  ),
920    ("rwHarzad         ",  io.req.valid && !io.req.ready  ),
921    ("out_blocked      ",  io.resp.valid && !io.resp.ready),
922  )
923  generatePerfEvent()
924}
925