xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/L2TLB.scala (revision 039cdc35f5f3b68b6295ec5ace90f22a77322e02)
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.experimental.ExtModule
22import chisel3.util._
23import xiangshan._
24import xiangshan.cache.{HasDCacheParameters, MemoryOpConstants}
25import utils._
26import utility._
27import freechips.rocketchip.diplomacy.{IdRange, LazyModule, LazyModuleImp}
28import freechips.rocketchip.tilelink._
29import xiangshan.backend.fu.{PMP, PMPChecker, PMPReqBundle, PMPRespBundle}
30import xiangshan.backend.fu.util.HasCSRConst
31import difftest._
32
33class L2TLB()(implicit p: Parameters) extends LazyModule with HasPtwConst {
34  override def shouldBeInlined: Boolean = false
35
36  val node = TLClientNode(Seq(TLMasterPortParameters.v1(
37    clients = Seq(TLMasterParameters.v1(
38      "ptw",
39      sourceId = IdRange(0, MemReqWidth)
40    )),
41    requestFields = Seq(ReqSourceField())
42  )))
43
44  lazy val module = new L2TLBImp(this)
45}
46
47class L2TLBImp(outer: L2TLB)(implicit p: Parameters) extends PtwModule(outer) with HasCSRConst with HasPerfEvents {
48
49  val (mem, edge) = outer.node.out.head
50
51  val io = IO(new L2TLBIO)
52  val difftestIO = IO(new Bundle() {
53    val ptwResp = Output(Bool())
54    val ptwAddr = Output(UInt(64.W))
55    val ptwData = Output(Vec(4, UInt(64.W)))
56  })
57
58  /* Ptw processes multiple requests
59   * Divide Ptw procedure into two stages: cache access ; mem access if cache miss
60   *           miss queue itlb       dtlb
61   *               |       |         |
62   *               ------arbiter------
63   *                            |
64   *                    l1 - l2 - l3 - sp
65   *                            |
66   *          -------------------------------------------
67   *    miss  |  queue                                  | hit
68   *    [][][][][][]                                    |
69   *          |                                         |
70   *    state machine accessing mem                     |
71   *          |                                         |
72   *          ---------------arbiter---------------------
73   *                 |                    |
74   *                itlb                 dtlb
75   */
76
77  difftestIO <> DontCare
78
79  val sfence_tmp = DelayN(io.sfence, 1)
80  val csr_tmp    = DelayN(io.csr.tlb, 1)
81  val sfence_dup = Seq.fill(9)(RegNext(sfence_tmp))
82  val csr_dup = Seq.fill(8)(RegNext(csr_tmp)) // TODO: add csr_modified?
83  val satp   = csr_dup(0).satp
84  val vsatp  = csr_dup(0).vsatp
85  val hgatp  = csr_dup(0).hgatp
86  val priv   = csr_dup(0).priv
87  val flush  = sfence_dup(0).valid || satp.changed || vsatp.changed || hgatp.changed
88
89  val pmp = Module(new PMP())
90  val pmp_check = VecInit(Seq.fill(3)(Module(new PMPChecker(lgMaxSize = 3, sameCycle = true)).io))
91  pmp.io.distribute_csr := io.csr.distribute_csr
92  pmp_check.foreach(_.check_env.apply(ModeS, pmp.io.pmp, pmp.io.pma))
93
94  val missQueue = Module(new L2TlbMissQueue)
95  val cache = Module(new PtwCache)
96  val ptw = Module(new PTW)
97  val hptw = Module(new HPTW)
98  val llptw = Module(new LLPTW)
99  val blockmq = Module(new BlockHelper(3))
100  val arb1 = Module(new Arbiter(new PtwReq, PtwWidth))
101  val arb2 = Module(new Arbiter(new L2TlbWithHptwIdBundle, ((if (l2tlbParams.enablePrefetch) 4 else 3) + (if(HasHExtension) 1 else 0))))
102  val hptw_req_arb = Module(new Arbiter(new Bundle {
103    val id = UInt(log2Up(l2tlbParams.llptwsize).W)
104    val source = UInt(bSourceWidth.W)
105    val gvpn = UInt(vpnLen.W)
106  }, 2))
107  val hptw_resp_arb = Module(new Arbiter(new Bundle {
108    val resp = new HptwResp()
109    val id = UInt(log2Up(l2tlbParams.llptwsize).W)
110  }, 2))
111  val outArb = (0 until PtwWidth).map(i => Module(new Arbiter(new Bundle {
112    val s2xlate = UInt(2.W)
113    val s1 = new PtwSectorResp ()
114    val s2 = new HptwResp()
115  }, 1)).io)
116  val mergeArb = (0 until PtwWidth).map(i => Module(new Arbiter(new Bundle {
117    val s2xlate = UInt(2.W)
118    val s1 = new PtwMergeResp()
119    val s2 = new HptwResp()
120  }, 3)).io)
121  val outArbCachePort = 0
122  val outArbFsmPort = 1
123  val outArbMqPort = 2
124
125  // hptw arb input port
126  val InHptwArbPTWPort = 0
127  val InHptwArbLLPTWPort = 1
128  hptw_req_arb.io.in(InHptwArbPTWPort).valid := ptw.io.hptw.req.valid
129  hptw_req_arb.io.in(InHptwArbPTWPort).bits.gvpn := ptw.io.hptw.req.bits.gvpn
130  hptw_req_arb.io.in(InHptwArbPTWPort).bits.id := ptw.io.hptw.req.bits.id
131  hptw_req_arb.io.in(InHptwArbPTWPort).bits.source := ptw.io.hptw.req.bits.source
132  ptw.io.hptw.req.ready := hptw_req_arb.io.in(InHptwArbPTWPort).ready
133
134  hptw_req_arb.io.in(InHptwArbLLPTWPort).valid := llptw.io.hptw.req.valid
135  hptw_req_arb.io.in(InHptwArbLLPTWPort).bits.gvpn := llptw.io.hptw.req.bits.gvpn
136  hptw_req_arb.io.in(InHptwArbLLPTWPort).bits.id := llptw.io.hptw.req.bits.id
137  hptw_req_arb.io.in(InHptwArbLLPTWPort).bits.source := llptw.io.hptw.req.bits.source
138  llptw.io.hptw.req.ready := hptw_req_arb.io.in(InHptwArbLLPTWPort).ready
139
140  // arb2 input port
141  val InArbHPTWPort = 0
142  val InArbPTWPort = 1
143  val InArbMissQueuePort = 2
144  val InArbTlbPort = 3
145  val InArbPrefetchPort = 4
146  // NOTE: when cache out but miss and ptw doesnt accept,
147  arb1.io.in <> VecInit(io.tlb.map(_.req(0)))
148
149
150  arb2.io.in(InArbPTWPort).valid := ptw.io.llptw.valid
151  arb2.io.in(InArbPTWPort).bits.req_info := ptw.io.llptw.bits.req_info
152  arb2.io.in(InArbPTWPort).bits.isHptwReq := false.B
153  arb2.io.in(InArbPTWPort).bits.isLLptw := false.B
154  arb2.io.in(InArbPTWPort).bits.hptwId := DontCare
155  ptw.io.llptw.ready := arb2.io.in(InArbPTWPort).ready
156  block_decoupled(missQueue.io.out, arb2.io.in(InArbMissQueuePort), Mux(missQueue.io.out.bits.isLLptw, !llptw.io.in.ready, !ptw.io.req.ready))
157
158  arb2.io.in(InArbTlbPort).valid := arb1.io.out.valid
159  arb2.io.in(InArbTlbPort).bits.req_info.vpn := arb1.io.out.bits.vpn
160  arb2.io.in(InArbTlbPort).bits.req_info.s2xlate := arb1.io.out.bits.s2xlate
161  arb2.io.in(InArbTlbPort).bits.req_info.source := arb1.io.chosen
162  arb2.io.in(InArbTlbPort).bits.isHptwReq := false.B
163  arb2.io.in(InArbTlbPort).bits.isLLptw := false.B
164  arb2.io.in(InArbTlbPort).bits.hptwId := DontCare
165  arb1.io.out.ready := arb2.io.in(InArbTlbPort).ready
166
167  arb2.io.in(InArbHPTWPort).valid := hptw_req_arb.io.out.valid
168  arb2.io.in(InArbHPTWPort).bits.req_info.vpn := hptw_req_arb.io.out.bits.gvpn
169  arb2.io.in(InArbHPTWPort).bits.req_info.s2xlate := onlyStage2
170  arb2.io.in(InArbHPTWPort).bits.req_info.source := hptw_req_arb.io.out.bits.source
171  arb2.io.in(InArbHPTWPort).bits.isHptwReq := true.B
172  arb2.io.in(InArbHPTWPort).bits.isLLptw := false.B
173  arb2.io.in(InArbHPTWPort).bits.hptwId := hptw_req_arb.io.out.bits.id
174  hptw_req_arb.io.out.ready := arb2.io.in(InArbHPTWPort).ready
175  val hartId = p(XSCoreParamsKey).HartId
176  if (l2tlbParams.enablePrefetch) {
177    val prefetch = Module(new L2TlbPrefetch())
178    val recv = cache.io.resp
179    // NOTE: 1. prefetch doesn't gen prefetch 2. req from mq doesn't gen prefetch
180    // NOTE: 1. miss req gen prefetch 2. hit but prefetched gen prefetch
181    prefetch.io.in.valid := recv.fire && !from_pre(recv.bits.req_info.source) && (!recv.bits.hit  ||
182      recv.bits.prefetch) && recv.bits.isFirst
183    prefetch.io.in.bits.vpn := recv.bits.req_info.vpn
184    prefetch.io.sfence := sfence_dup(0)
185    prefetch.io.csr := csr_dup(0)
186    arb2.io.in(InArbPrefetchPort) <> prefetch.io.out
187
188    val isWriteL2TlbPrefetchTable = Constantin.createRecord(s"isWriteL2TlbPrefetchTable$hartId")
189    val L2TlbPrefetchTable = ChiselDB.createTable(s"L2TlbPrefetch_hart$hartId", new L2TlbPrefetchDB)
190    val L2TlbPrefetchDB = Wire(new L2TlbPrefetchDB)
191    L2TlbPrefetchDB.vpn := prefetch.io.out.bits.req_info.vpn
192    L2TlbPrefetchTable.log(L2TlbPrefetchDB, isWriteL2TlbPrefetchTable.orR && prefetch.io.out.fire, "L2TlbPrefetch", clock, reset)
193  }
194  arb2.io.out.ready := cache.io.req.ready
195
196
197  val mq_arb = Module(new Arbiter(new L2TlbWithHptwIdBundle, 2))
198  mq_arb.io.in(0).valid := cache.io.resp.valid && !cache.io.resp.bits.hit &&
199    !from_pre(cache.io.resp.bits.req_info.source) && !cache.io.resp.bits.isHptwReq && // hptw reqs are not sent to missqueue
200    (cache.io.resp.bits.bypassed || (
201      ((!cache.io.resp.bits.toFsm.l2Hit || cache.io.resp.bits.toFsm.stage1Hit) && !cache.io.resp.bits.isHptwReq && (cache.io.resp.bits.isFirst || !ptw.io.req.ready)) // send to ptw, is first or ptw is busy;
202      || (cache.io.resp.bits.toFsm.l2Hit && !llptw.io.in.ready) // send to llptw, llptw is full
203    ))
204
205  mq_arb.io.in(0).bits.req_info :=  cache.io.resp.bits.req_info
206  mq_arb.io.in(0).bits.isHptwReq := false.B
207  mq_arb.io.in(0).bits.hptwId :=  DontCare
208  mq_arb.io.in(0).bits.isLLptw := cache.io.resp.bits.toFsm.l2Hit
209  mq_arb.io.in(1).bits.req_info := llptw.io.cache.bits
210  mq_arb.io.in(1).bits.isHptwReq := false.B
211  mq_arb.io.in(1).bits.hptwId := DontCare
212  mq_arb.io.in(1).bits.isLLptw := false.B
213  mq_arb.io.in(1).valid := llptw.io.cache.valid
214  llptw.io.cache.ready := mq_arb.io.in(1).ready
215  missQueue.io.in <> mq_arb.io.out
216  missQueue.io.sfence  := sfence_dup(6)
217  missQueue.io.csr := csr_dup(5)
218
219  blockmq.io.start := missQueue.io.out.fire
220  blockmq.io.enable := ptw.io.req.fire
221
222  llptw.io.in.valid := cache.io.resp.valid &&
223    !cache.io.resp.bits.hit &&
224    cache.io.resp.bits.toFsm.l2Hit &&
225    !cache.io.resp.bits.bypassed &&
226    !cache.io.resp.bits.isHptwReq
227  llptw.io.in.bits.req_info := cache.io.resp.bits.req_info
228  llptw.io.in.bits.ppn := cache.io.resp.bits.toFsm.ppn
229  llptw.io.sfence := sfence_dup(1)
230  llptw.io.csr := csr_dup(1)
231
232  cache.io.req.valid := arb2.io.out.valid
233  cache.io.req.bits.req_info := arb2.io.out.bits.req_info
234  cache.io.req.bits.isFirst := (arb2.io.chosen =/= InArbMissQueuePort.U && !arb2.io.out.bits.isHptwReq)
235  cache.io.req.bits.isHptwReq := arb2.io.out.bits.isHptwReq
236  cache.io.req.bits.hptwId := arb2.io.out.bits.hptwId
237  cache.io.req.bits.bypassed.map(_ := false.B)
238  cache.io.sfence := sfence_dup(2)
239  cache.io.csr := csr_dup(2)
240  cache.io.sfence_dup.zip(sfence_dup.drop(2).take(4)).map(s => s._1 := s._2)
241  cache.io.csr_dup.zip(csr_dup.drop(2).take(3)).map(c => c._1 := c._2)
242  cache.io.resp.ready := MuxCase(mq_arb.io.in(0).ready || ptw.io.req.ready, Seq(
243    (!cache.io.resp.bits.hit && cache.io.resp.bits.isHptwReq) -> hptw.io.req.ready,
244    (cache.io.resp.bits.hit && cache.io.resp.bits.isHptwReq) -> hptw_resp_arb.io.in(HptwRespArbCachePort).ready,
245    cache.io.resp.bits.hit -> outReady(cache.io.resp.bits.req_info.source, outArbCachePort),
246    (cache.io.resp.bits.toFsm.l2Hit && !cache.io.resp.bits.bypassed && llptw.io.in.ready) -> llptw.io.in.ready,
247    (cache.io.resp.bits.bypassed || cache.io.resp.bits.isFirst) -> mq_arb.io.in(0).ready
248  ))
249
250  // NOTE: missQueue req has higher priority
251  ptw.io.req.valid := cache.io.resp.valid && !cache.io.resp.bits.hit && !cache.io.resp.bits.toFsm.l2Hit &&
252    !cache.io.resp.bits.bypassed &&
253    !cache.io.resp.bits.isFirst &&
254    !cache.io.resp.bits.isHptwReq
255  ptw.io.req.bits.req_info := cache.io.resp.bits.req_info
256  ptw.io.req.bits.l1Hit := cache.io.resp.bits.toFsm.l1Hit
257  ptw.io.req.bits.ppn := cache.io.resp.bits.toFsm.ppn
258  ptw.io.req.bits.stage1Hit := cache.io.resp.bits.toFsm.stage1Hit
259  ptw.io.req.bits.stage1 := cache.io.resp.bits.toTlb
260  ptw.io.sfence := sfence_dup(7)
261  ptw.io.csr := csr_dup(6)
262  ptw.io.resp.ready := outReady(ptw.io.resp.bits.source, outArbFsmPort)
263
264  hptw.io.req.valid := cache.io.resp.valid && !cache.io.resp.bits.hit && cache.io.resp.bits.isHptwReq
265  hptw.io.req.bits.gvpn := cache.io.resp.bits.req_info.vpn
266  hptw.io.req.bits.id := cache.io.resp.bits.toHptw.id
267  hptw.io.req.bits.source := cache.io.resp.bits.req_info.source
268  hptw.io.req.bits.l1Hit := cache.io.resp.bits.toHptw.l1Hit
269  hptw.io.req.bits.l2Hit := cache.io.resp.bits.toHptw.l2Hit
270  hptw.io.req.bits.ppn := cache.io.resp.bits.toHptw.ppn
271  hptw.io.req.bits.bypassed := cache.io.resp.bits.toHptw.bypassed
272  hptw.io.sfence := sfence_dup(8)
273  hptw.io.csr := csr_dup(7)
274  // mem req
275  def blockBytes_align(addr: UInt) = {
276    Cat(addr(PAddrBits - 1, log2Up(l2tlbParams.blockBytes)), 0.U(log2Up(l2tlbParams.blockBytes).W))
277  }
278  def addr_low_from_vpn(vpn: UInt) = {
279    vpn(log2Ceil(l2tlbParams.blockBytes)-log2Ceil(XLEN/8)-1, 0)
280  }
281  def addr_low_from_paddr(paddr: UInt) = {
282    paddr(log2Up(l2tlbParams.blockBytes)-1, log2Up(XLEN/8))
283  }
284  def from_llptw(id: UInt) = {
285    id < l2tlbParams.llptwsize.U
286  }
287  def from_ptw(id: UInt) = {
288    id === l2tlbParams.llptwsize.U
289  }
290  def from_hptw(id: UInt) = {
291    id === l2tlbParams.llptwsize.U + 1.U
292  }
293  val waiting_resp = RegInit(VecInit(Seq.fill(MemReqWidth)(false.B)))
294  val flush_latch = RegInit(VecInit(Seq.fill(MemReqWidth)(false.B)))
295  val hptw_bypassed = RegInit(false.B)
296  for (i <- waiting_resp.indices) {
297    assert(!flush_latch(i) || waiting_resp(i)) // when sfence_latch wait for mem resp, waiting_resp should be true
298  }
299
300  val llptw_out = llptw.io.out
301  val llptw_mem = llptw.io.mem
302  llptw_mem.req_mask := waiting_resp.take(l2tlbParams.llptwsize)
303  ptw.io.mem.mask := waiting_resp.apply(l2tlbParams.llptwsize)
304  hptw.io.mem.mask := waiting_resp.apply(l2tlbParams.llptwsize + 1)
305
306  val mem_arb = Module(new Arbiter(new L2TlbMemReqBundle(), 3))
307  mem_arb.io.in(0) <> ptw.io.mem.req
308  mem_arb.io.in(1) <> llptw_mem.req
309  mem_arb.io.in(2) <> hptw.io.mem.req
310  mem_arb.io.out.ready := mem.a.ready && !flush
311
312  // assert, should not send mem access at same addr for twice.
313  val last_resp_vpn = RegEnable(cache.io.refill.bits.req_info_dup(0).vpn, cache.io.refill.valid)
314  val last_resp_s2xlate = RegEnable(cache.io.refill.bits.req_info_dup(0).s2xlate, cache.io.refill.valid)
315  val last_resp_level = RegEnable(cache.io.refill.bits.level_dup(0), cache.io.refill.valid)
316  val last_resp_v = RegInit(false.B)
317  val last_has_invalid = !Cat(cache.io.refill.bits.ptes.asTypeOf(Vec(blockBits/XLEN, UInt(XLEN.W))).map(a => a(0))).andR || cache.io.refill.bits.sel_pte_dup(0).asTypeOf(new PteBundle).isAf()
318  when (cache.io.refill.valid) { last_resp_v := !last_has_invalid}
319  when (flush) { last_resp_v := false.B }
320  XSError(last_resp_v && cache.io.refill.valid &&
321    (cache.io.refill.bits.req_info_dup(0).vpn === last_resp_vpn) &&
322    (cache.io.refill.bits.level_dup(0) === last_resp_level) &&
323    (cache.io.refill.bits.req_info_dup(0).s2xlate === last_resp_s2xlate),
324    "l2tlb should not access mem at same addr for twice")
325  // ATTENTION: this may wrongly assert when: a ptes is l2, last part is valid,
326  // but the current part is invalid, so one more mem access happened
327  // If this happened, remove the assert.
328
329  val req_addr_low = Reg(Vec(MemReqWidth, UInt((log2Up(l2tlbParams.blockBytes)-log2Up(XLEN/8)).W)))
330
331  when (llptw.io.in.fire) {
332    // when enq miss queue, set the req_addr_low to receive the mem resp data part
333    req_addr_low(llptw_mem.enq_ptr) := addr_low_from_vpn(llptw.io.in.bits.req_info.vpn)
334  }
335  when (mem_arb.io.out.fire) {
336    req_addr_low(mem_arb.io.out.bits.id) := addr_low_from_paddr(mem_arb.io.out.bits.addr)
337    waiting_resp(mem_arb.io.out.bits.id) := true.B
338    hptw_bypassed := from_hptw(mem_arb.io.out.bits.id) && mem_arb.io.out.bits.hptw_bypassed
339  }
340  // mem read
341  val memRead =  edge.Get(
342    fromSource = mem_arb.io.out.bits.id,
343    // toAddress  = memAddr(log2Up(CacheLineSize / 2 / 8) - 1, 0),
344    toAddress  = blockBytes_align(mem_arb.io.out.bits.addr),
345    lgSize     = log2Up(l2tlbParams.blockBytes).U
346  )._2
347  mem.a.bits := memRead
348  mem.a.valid := mem_arb.io.out.valid && !flush
349  mem.a.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.PTW.id.U)
350  mem.d.ready := true.B
351  // mem -> data buffer
352  val refill_data = Reg(Vec(blockBits / l1BusDataWidth, UInt(l1BusDataWidth.W)))
353  val refill_helper = edge.firstlastHelper(mem.d.bits, mem.d.fire)
354  val mem_resp_done = refill_helper._3
355  val mem_resp_from_llptw = from_llptw(mem.d.bits.source)
356  val mem_resp_from_ptw = from_ptw(mem.d.bits.source)
357  val mem_resp_from_hptw = from_hptw(mem.d.bits.source)
358  when (mem.d.valid) {
359    assert(mem.d.bits.source < MemReqWidth.U)
360    refill_data(refill_helper._4) := mem.d.bits.data
361  }
362  // refill_data_tmp is the wire fork of refill_data, but one cycle earlier
363  val refill_data_tmp = WireInit(refill_data)
364  refill_data_tmp(refill_helper._4) := mem.d.bits.data
365
366  // save only one pte for each id
367  // (miss queue may can't resp to tlb with low latency, it should have highest priority, but diffcult to design cache)
368  val resp_pte = VecInit((0 until MemReqWidth).map(i =>
369    if (i == l2tlbParams.llptwsize + 1) {RegEnable(get_part(refill_data_tmp, req_addr_low(i)), mem_resp_done && mem_resp_from_hptw) }
370    else if (i == l2tlbParams.llptwsize) {RegEnable(get_part(refill_data_tmp, req_addr_low(i)), mem_resp_done && mem_resp_from_ptw) }
371    else { DataHoldBypass(get_part(refill_data, req_addr_low(i)), llptw_mem.buffer_it(i)) }
372    // llptw could not use refill_data_tmp, because enq bypass's result works at next cycle
373  ))
374
375  // save eight ptes for each id when sector tlb
376  // (miss queue may can't resp to tlb with low latency, it should have highest priority, but diffcult to design cache)
377  val resp_pte_sector = VecInit((0 until MemReqWidth).map(i =>
378    if (i == l2tlbParams.llptwsize + 1) {RegEnable(refill_data_tmp, mem_resp_done && mem_resp_from_hptw) }
379    else if (i == l2tlbParams.llptwsize) {RegEnable(refill_data_tmp, mem_resp_done && mem_resp_from_ptw) }
380    else { DataHoldBypass(refill_data, llptw_mem.buffer_it(i)) }
381    // llptw could not use refill_data_tmp, because enq bypass's result works at next cycle
382  ))
383
384  // mem -> llptw
385  llptw_mem.resp.valid := mem_resp_done && mem_resp_from_llptw
386  llptw_mem.resp.bits.id := DataHoldBypass(mem.d.bits.source, mem.d.valid)
387  llptw_mem.resp.bits.value := DataHoldBypass(refill_data_tmp.asUInt, mem.d.valid)
388  // mem -> ptw
389  ptw.io.mem.resp.valid := mem_resp_done && mem_resp_from_ptw
390  ptw.io.mem.resp.bits := resp_pte.apply(l2tlbParams.llptwsize)
391  // mem -> hptw
392  hptw.io.mem.resp.valid := mem_resp_done && mem_resp_from_hptw
393  hptw.io.mem.resp.bits := resp_pte.apply(l2tlbParams.llptwsize + 1)
394  // mem -> cache
395  val refill_from_llptw = mem_resp_from_llptw
396  val refill_from_ptw = mem_resp_from_ptw
397  val refill_from_hptw = mem_resp_from_hptw
398  val refill_level = Mux(refill_from_llptw, 2.U, Mux(refill_from_ptw, RegEnable(ptw.io.refill.level, 0.U, ptw.io.mem.req.fire), RegEnable(hptw.io.refill.level, 0.U, hptw.io.mem.req.fire)))
399  val refill_valid = mem_resp_done && !flush && !flush_latch(mem.d.bits.source) && !hptw_bypassed
400
401  cache.io.refill.valid := GatedValidRegNext(refill_valid, false.B)
402  cache.io.refill.bits.ptes := refill_data.asUInt
403  cache.io.refill.bits.req_info_dup.map(_ := RegEnable(Mux(refill_from_llptw, llptw_mem.refill, Mux(refill_from_ptw, ptw.io.refill.req_info, hptw.io.refill.req_info)), refill_valid))
404  cache.io.refill.bits.level_dup.map(_ := RegEnable(refill_level, refill_valid))
405  cache.io.refill.bits.levelOH(refill_level, refill_valid)
406  cache.io.refill.bits.sel_pte_dup.map(_ := RegEnable(sel_data(refill_data_tmp.asUInt, req_addr_low(mem.d.bits.source)), refill_valid))
407
408  if (env.EnableDifftest) {
409    val difftest_ptw_addr = RegInit(VecInit(Seq.fill(MemReqWidth)(0.U(PAddrBits.W))))
410    when (mem.a.valid) {
411      difftest_ptw_addr(mem.a.bits.source) := mem.a.bits.address
412    }
413
414    val difftest = DifftestModule(new DiffRefillEvent, dontCare = true)
415    difftest.coreid := io.hartId
416    difftest.index := 2.U
417    difftest.valid := cache.io.refill.valid
418    difftest.addr := difftest_ptw_addr(RegEnable(mem.d.bits.source, mem.d.valid))
419    difftest.data := refill_data.asTypeOf(difftest.data)
420    difftest.idtfr := DontCare
421  }
422
423  if (env.EnableDifftest) {
424    for (i <- 0 until PtwWidth) {
425      val difftest = DifftestModule(new DiffL2TLBEvent)
426      difftest.coreid := io.hartId
427      difftest.valid := io.tlb(i).resp.fire && !io.tlb(i).resp.bits.s1.af && !io.tlb(i).resp.bits.s2.gaf
428      difftest.index := i.U
429      difftest.vpn := Cat(io.tlb(i).resp.bits.s1.entry.tag, 0.U(sectortlbwidth.W))
430      for (j <- 0 until tlbcontiguous) {
431        difftest.ppn(j) := Cat(io.tlb(i).resp.bits.s1.entry.ppn, io.tlb(i).resp.bits.s1.ppn_low(j))
432        difftest.valididx(j) := io.tlb(i).resp.bits.s1.valididx(j)
433        difftest.pteidx(j) := io.tlb(i).resp.bits.s1.pteidx(j)
434      }
435      difftest.perm := io.tlb(i).resp.bits.s1.entry.perm.getOrElse(0.U.asTypeOf(new PtePermBundle)).asUInt
436      difftest.level := io.tlb(i).resp.bits.s1.entry.level.getOrElse(0.U.asUInt)
437      difftest.pf := io.tlb(i).resp.bits.s1.pf
438      difftest.satp := Cat(io.csr.tlb.satp.mode, io.csr.tlb.satp.asid, io.csr.tlb.satp.ppn)
439      difftest.vsatp := Cat(io.csr.tlb.vsatp.mode, io.csr.tlb.vsatp.asid, io.csr.tlb.vsatp.ppn)
440      difftest.hgatp := Cat(io.csr.tlb.hgatp.mode, io.csr.tlb.hgatp.asid, io.csr.tlb.hgatp.ppn)
441      difftest.gvpn := io.tlb(i).resp.bits.s2.entry.tag
442      difftest.g_perm := io.tlb(i).resp.bits.s2.entry.perm.getOrElse(0.U.asTypeOf(new PtePermBundle)).asUInt
443      difftest.g_level := io.tlb(i).resp.bits.s2.entry.level.getOrElse(0.U.asUInt)
444      difftest.s2ppn := io.tlb(i).resp.bits.s2.entry.ppn
445      difftest.gpf := io.tlb(i).resp.bits.s2.gpf
446      difftest.s2xlate := io.tlb(i).resp.bits.s2xlate
447    }
448  }
449
450  // pmp
451  pmp_check(0).req <> ptw.io.pmp.req
452  ptw.io.pmp.resp <> pmp_check(0).resp
453  pmp_check(1).req <> llptw.io.pmp.req
454  llptw.io.pmp.resp <> pmp_check(1).resp
455  pmp_check(2).req <> hptw.io.pmp.req
456  hptw.io.pmp.resp <> pmp_check(2).resp
457
458  llptw_out.ready := outReady(llptw_out.bits.req_info.source, outArbMqPort)
459
460  // hptw and page cache -> ptw and llptw
461  val HptwRespArbCachePort = 0
462  val HptwRespArbHptw = 1
463  hptw_resp_arb.io.in(HptwRespArbCachePort).valid := cache.io.resp.valid && cache.io.resp.bits.hit && cache.io.resp.bits.isHptwReq
464  hptw_resp_arb.io.in(HptwRespArbCachePort).bits.id := cache.io.resp.bits.toHptw.id
465  hptw_resp_arb.io.in(HptwRespArbCachePort).bits.resp := cache.io.resp.bits.toHptw.resp
466  hptw_resp_arb.io.in(HptwRespArbHptw).valid := hptw.io.resp.valid
467  hptw_resp_arb.io.in(HptwRespArbHptw).bits.id := hptw.io.resp.bits.id
468  hptw_resp_arb.io.in(HptwRespArbHptw).bits.resp := hptw.io.resp.bits.resp
469  hptw.io.resp.ready := hptw_resp_arb.io.in(HptwRespArbHptw).ready
470
471  ptw.io.hptw.resp.valid := hptw_resp_arb.io.out.valid && hptw_resp_arb.io.out.bits.id === FsmReqID.U
472  ptw.io.hptw.resp.bits.h_resp := hptw_resp_arb.io.out.bits.resp
473  llptw.io.hptw.resp.valid := hptw_resp_arb.io.out.valid && hptw_resp_arb.io.out.bits.id =/= FsmReqID.U
474  llptw.io.hptw.resp.bits.id := hptw_resp_arb.io.out.bits.id
475  llptw.io.hptw.resp.bits.h_resp := hptw_resp_arb.io.out.bits.resp
476  hptw_resp_arb.io.out.ready := true.B
477
478  // Timing: Maybe need to do some optimization or even add one more cycle
479  for (i <- 0 until PtwWidth) {
480    mergeArb(i).in(outArbCachePort).valid := cache.io.resp.valid && cache.io.resp.bits.hit && cache.io.resp.bits.req_info.source===i.U && !cache.io.resp.bits.isHptwReq
481    mergeArb(i).in(outArbCachePort).bits.s2xlate := cache.io.resp.bits.req_info.s2xlate
482    mergeArb(i).in(outArbCachePort).bits.s1 := cache.io.resp.bits.toTlb
483    mergeArb(i).in(outArbCachePort).bits.s2 := cache.io.resp.bits.toHptw.resp
484    mergeArb(i).in(outArbFsmPort).valid := ptw.io.resp.valid && ptw.io.resp.bits.source===i.U
485    mergeArb(i).in(outArbFsmPort).bits.s2xlate := ptw.io.resp.bits.s2xlate
486    mergeArb(i).in(outArbFsmPort).bits.s1 := ptw.io.resp.bits.resp
487    mergeArb(i).in(outArbFsmPort).bits.s2 := ptw.io.resp.bits.h_resp
488    mergeArb(i).in(outArbMqPort).valid := llptw_out.valid && llptw_out.bits.req_info.source===i.U
489    mergeArb(i).in(outArbMqPort).bits.s2xlate := llptw_out.bits.req_info.s2xlate
490    mergeArb(i).in(outArbMqPort).bits.s1 := contiguous_pte_to_merge_ptwResp(resp_pte_sector(llptw_out.bits.id).asUInt, llptw_out.bits.req_info.vpn, llptw_out.bits.af, true, s2xlate = llptw_out.bits.req_info.s2xlate)
491    mergeArb(i).in(outArbMqPort).bits.s2 := llptw_out.bits.h_resp
492    mergeArb(i).out.ready := outArb(i).in(0).ready
493  }
494
495  for (i <- 0 until PtwWidth) {
496    outArb(i).in(0).valid := mergeArb(i).out.valid
497    outArb(i).in(0).bits.s2xlate := mergeArb(i).out.bits.s2xlate
498    outArb(i).in(0).bits.s1 := merge_ptwResp_to_sector_ptwResp(mergeArb(i).out.bits.s1)
499    outArb(i).in(0).bits.s2 := mergeArb(i).out.bits.s2
500  }
501
502  // io.tlb.map(_.resp) <> outArb.map(_.out)
503  io.tlb.map(_.resp).zip(outArb.map(_.out)).map{
504    case (resp, out) => resp <> out
505  }
506
507  // sfence
508  when (flush) {
509    for (i <- 0 until MemReqWidth) {
510      when (waiting_resp(i)) {
511        flush_latch(i) := true.B
512      }
513    }
514  }
515  // mem -> control signal
516  // waiting_resp and sfence_latch will be reset when mem_resp_done
517  when (mem_resp_done) {
518    waiting_resp(mem.d.bits.source) := false.B
519    flush_latch(mem.d.bits.source) := false.B
520  }
521
522  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
523    sink.valid   := source.valid && !block_signal
524    source.ready := sink.ready   && !block_signal
525    sink.bits    := source.bits
526  }
527
528  def get_part(data: Vec[UInt], index: UInt): UInt = {
529    val inner_data = data.asTypeOf(Vec(data.getWidth / XLEN, UInt(XLEN.W)))
530    inner_data(index)
531  }
532
533  // not_super means that this is a normal page
534  // valididx(i) will be all true when super page to be convenient for l1 tlb matching
535  def contiguous_pte_to_merge_ptwResp(pte: UInt, vpn: UInt, af: Bool, af_first: Boolean, not_super: Boolean = true, s2xlate: UInt) : PtwMergeResp = {
536    assert(tlbcontiguous == 8, "Only support tlbcontiguous = 8!")
537    val ptw_merge_resp = Wire(new PtwMergeResp())
538    val hasS2xlate = s2xlate =/= noS2xlate
539    for (i <- 0 until tlbcontiguous) {
540      val pte_in = pte(64 * i + 63, 64 * i).asTypeOf(new PteBundle())
541      val ptw_resp = Wire(new PtwMergeEntry(tagLen = sectorvpnLen, hasPerm = true, hasLevel = true))
542      ptw_resp.ppn := pte_in.ppn(ppnLen - 1, sectortlbwidth)
543      ptw_resp.ppn_low := pte_in.ppn(sectortlbwidth - 1, 0)
544      ptw_resp.level.map(_ := 2.U)
545      ptw_resp.perm.map(_ := pte_in.getPerm())
546      ptw_resp.tag := vpn(vpnLen - 1, sectortlbwidth)
547      ptw_resp.pf := (if (af_first) !af else true.B) && (pte_in.isPf(2.U) || !pte_in.isLeaf())
548      ptw_resp.af := (if (!af_first) pte_in.isPf(2.U) else true.B) && (af || pte_in.isAf())
549      ptw_resp.v := !ptw_resp.pf
550      ptw_resp.prefetch := DontCare
551      ptw_resp.asid := Mux(hasS2xlate, vsatp.asid, satp.asid)
552      ptw_resp.vmid.map(_ := hgatp.asid)
553      ptw_merge_resp.entry(i) := ptw_resp
554    }
555    ptw_merge_resp.pteidx := UIntToOH(vpn(sectortlbwidth - 1, 0)).asBools
556    ptw_merge_resp.not_super := not_super.B
557    ptw_merge_resp
558  }
559
560  def merge_ptwResp_to_sector_ptwResp(pte: PtwMergeResp) : PtwSectorResp = {
561    assert(tlbcontiguous == 8, "Only support tlbcontiguous = 8!")
562    val ptw_sector_resp = Wire(new PtwSectorResp)
563    ptw_sector_resp.entry.tag := pte.entry(OHToUInt(pte.pteidx)).tag
564    ptw_sector_resp.entry.asid := pte.entry(OHToUInt(pte.pteidx)).asid
565    ptw_sector_resp.entry.vmid.map(_ := pte.entry(OHToUInt(pte.pteidx)).vmid.getOrElse(0.U))
566    ptw_sector_resp.entry.ppn := pte.entry(OHToUInt(pte.pteidx)).ppn
567    ptw_sector_resp.entry.perm.map(_ := pte.entry(OHToUInt(pte.pteidx)).perm.getOrElse(0.U.asTypeOf(new PtePermBundle)))
568    ptw_sector_resp.entry.level.map(_ := pte.entry(OHToUInt(pte.pteidx)).level.getOrElse(0.U(2.W)))
569    ptw_sector_resp.entry.prefetch := pte.entry(OHToUInt(pte.pteidx)).prefetch
570    ptw_sector_resp.entry.v := pte.entry(OHToUInt(pte.pteidx)).v
571    ptw_sector_resp.af := pte.entry(OHToUInt(pte.pteidx)).af
572    ptw_sector_resp.pf := pte.entry(OHToUInt(pte.pteidx)).pf
573    ptw_sector_resp.addr_low := OHToUInt(pte.pteidx)
574    ptw_sector_resp.pteidx := pte.pteidx
575    for (i <- 0 until tlbcontiguous) {
576      val ppn_equal = pte.entry(i).ppn === pte.entry(OHToUInt(pte.pteidx)).ppn
577      val perm_equal = pte.entry(i).perm.getOrElse(0.U.asTypeOf(new PtePermBundle)).asUInt === pte.entry(OHToUInt(pte.pteidx)).perm.getOrElse(0.U.asTypeOf(new PtePermBundle)).asUInt
578      val v_equal = pte.entry(i).v === pte.entry(OHToUInt(pte.pteidx)).v
579      val af_equal = pte.entry(i).af === pte.entry(OHToUInt(pte.pteidx)).af
580      val pf_equal = pte.entry(i).pf === pte.entry(OHToUInt(pte.pteidx)).pf
581      ptw_sector_resp.valididx(i) := (ppn_equal && perm_equal && v_equal && af_equal && pf_equal) || !pte.not_super
582      ptw_sector_resp.ppn_low(i) := pte.entry(i).ppn_low
583    }
584    ptw_sector_resp.valididx(OHToUInt(pte.pteidx)) := true.B
585    ptw_sector_resp
586  }
587
588  def outReady(source: UInt, port: Int): Bool = {
589    MuxLookup(source, true.B)((0 until PtwWidth).map(i => i.U -> mergeArb(i).in(port).ready))
590  }
591
592  // debug info
593  for (i <- 0 until PtwWidth) {
594    XSDebug(p"[io.tlb(${i.U})] ${io.tlb(i)}\n")
595  }
596  XSDebug(p"[sfence] ${io.sfence}\n")
597  XSDebug(p"[io.csr.tlb] ${io.csr.tlb}\n")
598
599  for (i <- 0 until PtwWidth) {
600    XSPerfAccumulate(s"req_count${i}", io.tlb(i).req(0).fire)
601    XSPerfAccumulate(s"req_blocked_count_${i}", io.tlb(i).req(0).valid && !io.tlb(i).req(0).ready)
602  }
603  XSPerfAccumulate(s"req_blocked_by_mq", arb1.io.out.valid && missQueue.io.out.valid)
604  for (i <- 0 until (MemReqWidth + 1)) {
605    XSPerfAccumulate(s"mem_req_util${i}", PopCount(waiting_resp) === i.U)
606  }
607  XSPerfAccumulate("mem_cycle", PopCount(waiting_resp) =/= 0.U)
608  XSPerfAccumulate("mem_count", mem.a.fire)
609  for (i <- 0 until PtwWidth) {
610    XSPerfAccumulate(s"llptw_ppn_af${i}", mergeArb(i).in(outArbMqPort).valid && mergeArb(i).in(outArbMqPort).bits.s1.entry(OHToUInt(mergeArb(i).in(outArbMqPort).bits.s1.pteidx)).af && !llptw_out.bits.af)
611    XSPerfAccumulate(s"access_fault${i}", io.tlb(i).resp.fire && io.tlb(i).resp.bits.s1.af)
612  }
613
614  // print configs
615  println(s"${l2tlbParams.name}: a ptw, a llptw with size ${l2tlbParams.llptwsize}, miss queue size ${MissQueueSize} l1:${l2tlbParams.l1Size} fa l2: nSets ${l2tlbParams.l2nSets} nWays ${l2tlbParams.l2nWays} l3: ${l2tlbParams.l3nSets} nWays ${l2tlbParams.l3nWays} blockBytes:${l2tlbParams.blockBytes}")
616
617  // time out assert
618  for (i <- 0 until MemReqWidth) {
619    TimeOutAssert(waiting_resp(i), timeOutThreshold, s"ptw mem resp time out wait_resp${i}")
620    TimeOutAssert(flush_latch(i), timeOutThreshold, s"ptw mem resp time out flush_latch${i}")
621  }
622
623
624  val perfEvents  = Seq(llptw, cache, ptw).flatMap(_.getPerfEvents)
625  generatePerfEvent()
626
627  val isWriteL1TlbTable = Constantin.createRecord(s"isWriteL1TlbTable$hartId")
628  val L1TlbTable = ChiselDB.createTable(s"L1Tlb_hart$hartId", new L1TlbDB)
629  val ITlbReqDB, DTlbReqDB, ITlbRespDB, DTlbRespDB = Wire(new L1TlbDB)
630  ITlbReqDB.vpn := io.tlb(0).req(0).bits.vpn
631  DTlbReqDB.vpn := io.tlb(1).req(0).bits.vpn
632  ITlbRespDB.vpn := io.tlb(0).resp.bits.s1.entry.tag
633  DTlbRespDB.vpn := io.tlb(1).resp.bits.s1.entry.tag
634  L1TlbTable.log(ITlbReqDB, isWriteL1TlbTable.orR && io.tlb(0).req(0).fire, "ITlbReq", clock, reset)
635  L1TlbTable.log(DTlbReqDB, isWriteL1TlbTable.orR && io.tlb(1).req(0).fire, "DTlbReq", clock, reset)
636  L1TlbTable.log(ITlbRespDB, isWriteL1TlbTable.orR && io.tlb(0).resp.fire, "ITlbResp", clock, reset)
637  L1TlbTable.log(DTlbRespDB, isWriteL1TlbTable.orR && io.tlb(1).resp.fire, "DTlbResp", clock, reset)
638
639  val isWritePageCacheTable = Constantin.createRecord(s"isWritePageCacheTable$hartId")
640  val PageCacheTable = ChiselDB.createTable(s"PageCache_hart$hartId", new PageCacheDB)
641  val PageCacheDB = Wire(new PageCacheDB)
642  PageCacheDB.vpn := Cat(cache.io.resp.bits.toTlb.entry(0).tag, OHToUInt(cache.io.resp.bits.toTlb.pteidx))
643  PageCacheDB.source := cache.io.resp.bits.req_info.source
644  PageCacheDB.bypassed := cache.io.resp.bits.bypassed
645  PageCacheDB.is_first := cache.io.resp.bits.isFirst
646  PageCacheDB.prefetched := cache.io.resp.bits.toTlb.entry(0).prefetch
647  PageCacheDB.prefetch := cache.io.resp.bits.prefetch
648  PageCacheDB.l2Hit := cache.io.resp.bits.toFsm.l2Hit
649  PageCacheDB.l1Hit := cache.io.resp.bits.toFsm.l1Hit
650  PageCacheDB.hit := cache.io.resp.bits.hit
651  PageCacheTable.log(PageCacheDB, isWritePageCacheTable.orR && cache.io.resp.fire, "PageCache", clock, reset)
652
653  val isWritePTWTable = Constantin.createRecord(s"isWritePTWTable$hartId")
654  val PTWTable = ChiselDB.createTable(s"PTW_hart$hartId", new PTWDB)
655  val PTWReqDB, PTWRespDB, LLPTWReqDB, LLPTWRespDB = Wire(new PTWDB)
656  PTWReqDB.vpn := ptw.io.req.bits.req_info.vpn
657  PTWReqDB.source := ptw.io.req.bits.req_info.source
658  PTWRespDB.vpn := ptw.io.refill.req_info.vpn
659  PTWRespDB.source := ptw.io.refill.req_info.source
660  LLPTWReqDB.vpn := llptw.io.in.bits.req_info.vpn
661  LLPTWReqDB.source := llptw.io.in.bits.req_info.source
662  LLPTWRespDB.vpn := llptw.io.mem.refill.vpn
663  LLPTWRespDB.source := llptw.io.mem.refill.source
664  PTWTable.log(PTWReqDB, isWritePTWTable.orR && ptw.io.req.fire, "PTWReq", clock, reset)
665  PTWTable.log(PTWRespDB, isWritePTWTable.orR && ptw.io.mem.resp.fire, "PTWResp", clock, reset)
666  PTWTable.log(LLPTWReqDB, isWritePTWTable.orR && llptw.io.in.fire, "LLPTWReq", clock, reset)
667  PTWTable.log(LLPTWRespDB, isWritePTWTable.orR && llptw.io.mem.resp.fire, "LLPTWResp", clock, reset)
668
669  val isWriteL2TlbMissQueueTable = Constantin.createRecord(s"isWriteL2TlbMissQueueTable$hartId")
670  val L2TlbMissQueueTable = ChiselDB.createTable(s"L2TlbMissQueue_hart$hartId", new L2TlbMissQueueDB)
671  val L2TlbMissQueueInDB, L2TlbMissQueueOutDB = Wire(new L2TlbMissQueueDB)
672  L2TlbMissQueueInDB.vpn := missQueue.io.in.bits.req_info.vpn
673  L2TlbMissQueueOutDB.vpn := missQueue.io.out.bits.req_info.vpn
674  L2TlbMissQueueTable.log(L2TlbMissQueueInDB, isWriteL2TlbMissQueueTable.orR && missQueue.io.in.fire, "L2TlbMissQueueIn", clock, reset)
675  L2TlbMissQueueTable.log(L2TlbMissQueueOutDB, isWriteL2TlbMissQueueTable.orR && missQueue.io.out.fire, "L2TlbMissQueueOut", clock, reset)
676}
677
678/** BlockHelper, block missqueue, not to send too many req to cache
679 *  Parameter:
680 *    enable: enable BlockHelper, mq should not send too many reqs
681 *    start: when miss queue out fire and need, block miss queue's out
682 *    block: block miss queue's out
683 *    latency: last missqueue out's cache access latency
684 */
685class BlockHelper(latency: Int)(implicit p: Parameters) extends XSModule {
686  val io = IO(new Bundle {
687    val enable = Input(Bool())
688    val start = Input(Bool())
689    val block = Output(Bool())
690  })
691
692  val count = RegInit(0.U(log2Ceil(latency).W))
693  val valid = RegInit(false.B)
694  val work = RegInit(true.B)
695
696  io.block := valid
697
698  when (io.start && work) { valid := true.B }
699  when (valid) { count := count + 1.U }
700  when (count === (latency.U) || io.enable) {
701    valid := false.B
702    work := io.enable
703    count := 0.U
704  }
705}
706
707class PTEHelper() extends ExtModule {
708  val clock  = IO(Input(Clock()))
709  val enable = IO(Input(Bool()))
710  val satp   = IO(Input(UInt(64.W)))
711  val vpn    = IO(Input(UInt(64.W)))
712  val pte    = IO(Output(UInt(64.W)))
713  val level  = IO(Output(UInt(8.W)))
714  val pf     = IO(Output(UInt(8.W)))
715}
716
717class PTWDelayN[T <: Data](gen: T, n: Int, flush: Bool) extends Module {
718  val io = IO(new Bundle() {
719    val in = Input(gen)
720    val out = Output(gen)
721    val ptwflush = Input(flush.cloneType)
722  })
723  val out = RegInit(VecInit(Seq.fill(n)(0.U.asTypeOf(gen))))
724  val t = RegInit(VecInit(Seq.fill(n)(0.U.asTypeOf(gen))))
725  out(0) := io.in
726  if (n == 1) {
727    io.out := out(0)
728  } else {
729    when (io.ptwflush) {
730      for (i <- 0 until n) {
731        t(i) := 0.U.asTypeOf(gen)
732        out(i) := 0.U.asTypeOf(gen)
733      }
734      io.out := 0.U.asTypeOf(gen)
735    } .otherwise {
736      for (i <- 1 until n) {
737        t(i-1) := out(i-1)
738        out(i) := t(i-1)
739      }
740      io.out := out(n-1)
741    }
742  }
743}
744
745object PTWDelayN {
746  def apply[T <: Data](in: T, n: Int, flush: Bool): T = {
747    val delay = Module(new PTWDelayN(in.cloneType, n, flush))
748    delay.io.in := in
749    delay.io.ptwflush := flush
750    delay.io.out
751  }
752}
753
754class FakePTW()(implicit p: Parameters) extends XSModule with HasPtwConst {
755  val io = IO(new L2TLBIO)
756  val flush = VecInit(Seq.fill(PtwWidth)(false.B))
757  flush(0) := DelayN(io.sfence.valid || io.csr.tlb.satp.changed, itlbParams.fenceDelay)
758  flush(1) := DelayN(io.sfence.valid || io.csr.tlb.satp.changed, ldtlbParams.fenceDelay)
759  for (i <- 0 until PtwWidth) {
760    val helper = Module(new PTEHelper())
761    helper.clock := clock
762    helper.satp := io.csr.tlb.satp.ppn
763
764    if (coreParams.softPTWDelay == 1) {
765      helper.enable := io.tlb(i).req(0).fire
766      helper.vpn := io.tlb(i).req(0).bits.vpn
767    } else {
768      helper.enable := PTWDelayN(io.tlb(i).req(0).fire, coreParams.softPTWDelay - 1, flush(i))
769      helper.vpn := PTWDelayN(io.tlb(i).req(0).bits.vpn, coreParams.softPTWDelay - 1, flush(i))
770    }
771
772    val pte = helper.pte.asTypeOf(new PteBundle)
773    val level = helper.level
774    val pf = helper.pf
775    val empty = RegInit(true.B)
776    when (io.tlb(i).req(0).fire) {
777      empty := false.B
778    } .elsewhen (io.tlb(i).resp.fire || flush(i)) {
779      empty := true.B
780    }
781
782    io.tlb(i).req(0).ready := empty || io.tlb(i).resp.fire
783    io.tlb(i).resp.valid := PTWDelayN(io.tlb(i).req(0).fire, coreParams.softPTWDelay, flush(i))
784    assert(!io.tlb(i).resp.valid || io.tlb(i).resp.ready)
785    io.tlb(i).resp.bits.s1.entry.tag := PTWDelayN(io.tlb(i).req(0).bits.vpn, coreParams.softPTWDelay, flush(i))
786    io.tlb(i).resp.bits.s1.entry.ppn := pte.ppn
787    io.tlb(i).resp.bits.s1.entry.perm.map(_ := pte.getPerm())
788    io.tlb(i).resp.bits.s1.entry.level.map(_ := level)
789    io.tlb(i).resp.bits.s1.pf := pf
790    io.tlb(i).resp.bits.s1.af := DontCare // TODO: implement it
791    io.tlb(i).resp.bits.s1.entry.v := !pf
792    io.tlb(i).resp.bits.s1.entry.prefetch := DontCare
793    io.tlb(i).resp.bits.s1.entry.asid := io.csr.tlb.satp.asid
794  }
795}
796
797class L2TLBWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
798  override def shouldBeInlined: Boolean = false
799  val useSoftPTW = coreParams.softPTW
800  val node = if (!useSoftPTW) TLIdentityNode() else null
801  val ptw = if (!useSoftPTW) LazyModule(new L2TLB()) else null
802  if (!useSoftPTW) {
803    node := ptw.node
804  }
805
806  class L2TLBWrapperImp(wrapper: LazyModule) extends LazyModuleImp(wrapper) with HasPerfEvents {
807    val io = IO(new L2TLBIO)
808    val perfEvents = if (useSoftPTW) {
809      val fake_ptw = Module(new FakePTW())
810      io <> fake_ptw.io
811      Seq()
812    }
813    else {
814        io <> ptw.module.io
815        ptw.module.getPerfEvents
816    }
817    generatePerfEvent()
818  }
819
820  lazy val module = new L2TLBWrapperImp(this)
821}
822