xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/L2TLB.scala (revision 9473e04d5cab97eaf63add958b2392eec3d876a2)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.cache.mmu
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.experimental.ExtModule
22import chisel3.util._
23import chisel3.internal.naming.chiselName
24import xiangshan._
25import xiangshan.cache.{HasDCacheParameters, MemoryOpConstants}
26import utils._
27import utility._
28import freechips.rocketchip.diplomacy.{IdRange, LazyModule, LazyModuleImp}
29import freechips.rocketchip.tilelink._
30import xiangshan.backend.fu.{PMP, PMPChecker, PMPReqBundle, PMPRespBundle}
31import xiangshan.backend.fu.util.HasCSRConst
32import utility.ChiselDB
33import difftest._
34
35class L2TLB()(implicit p: Parameters) extends LazyModule with HasPtwConst {
36
37  val node = TLClientNode(Seq(TLMasterPortParameters.v1(
38    clients = Seq(TLMasterParameters.v1(
39      "ptw",
40      sourceId = IdRange(0, MemReqWidth)
41    ))
42  )))
43
44  lazy val module = new L2TLBImp(this)
45}
46
47@chiselName
48class L2TLBImp(outer: L2TLB)(implicit p: Parameters) extends PtwModule(outer) with HasCSRConst with HasPerfEvents {
49
50  val (mem, edge) = outer.node.out.head
51
52  val io = IO(new L2TLBIO)
53  val difftestIO = IO(new Bundle() {
54    val ptwResp = Output(Bool())
55    val ptwAddr = Output(UInt(64.W))
56    val ptwData = Output(Vec(4, UInt(64.W)))
57  })
58
59  /* Ptw processes multiple requests
60   * Divide Ptw procedure into two stages: cache access ; mem access if cache miss
61   *           miss queue itlb       dtlb
62   *               |       |         |
63   *               ------arbiter------
64   *                            |
65   *                    l1 - l2 - l3 - sp
66   *                            |
67   *          -------------------------------------------
68   *    miss  |  queue                                  | hit
69   *    [][][][][][]                                    |
70   *          |                                         |
71   *    state machine accessing mem                     |
72   *          |                                         |
73   *          ---------------arbiter---------------------
74   *                 |                    |
75   *                itlb                 dtlb
76   */
77
78  difftestIO <> DontCare
79
80  val sfence_tmp = DelayN(io.sfence, 1)
81  val csr_tmp    = DelayN(io.csr.tlb, 1)
82  val sfence_dup = Seq.fill(8)(RegNext(sfence_tmp))
83  val csr_dup = Seq.fill(7)(RegNext(csr_tmp))
84  val satp   = csr_dup(0).satp
85  val priv   = csr_dup(0).priv
86  val flush  = sfence_dup(0).valid || satp.changed
87
88  val pmp = Module(new PMP())
89  val pmp_check = VecInit(Seq.fill(2)(Module(new PMPChecker(lgMaxSize = 3, sameCycle = true)).io))
90  pmp.io.distribute_csr := io.csr.distribute_csr
91  pmp_check.foreach(_.check_env.apply(ModeS, pmp.io.pmp, pmp.io.pma))
92
93  val missQueue = Module(new L2TlbMissQueue)
94  val cache = Module(new PtwCache)
95  val ptw = Module(new PTW)
96  val llptw = Module(new LLPTW)
97  val blockmq = Module(new BlockHelper(3))
98  val arb1 = Module(new Arbiter(new PtwReq, PtwWidth))
99  val arb2 = Module(new Arbiter(new Bundle {
100    val vpn = UInt(vpnLen.W)
101    val source = UInt(bSourceWidth.W)
102  }, if (l2tlbParams.enablePrefetch) 4 else 3))
103  val outArb = (0 until PtwWidth).map(i => Module(new Arbiter(new PtwResp, 3)).io)
104  val outArbCachePort = 0
105  val outArbFsmPort = 1
106  val outArbMqPort = 2
107
108  // arb2 input port
109  val InArbPTWPort = 0
110  val InArbMissQueuePort = 1
111  val InArbTlbPort = 2
112  val InArbPrefetchPort = 3
113  // NOTE: when cache out but miss and ptw doesnt accept,
114  arb1.io.in <> VecInit(io.tlb.map(_.req(0)))
115  arb1.io.out.ready := arb2.io.in(InArbTlbPort).ready
116
117  arb2.io.in(InArbPTWPort).valid := ptw.io.llptw.valid
118  arb2.io.in(InArbPTWPort).bits.vpn := ptw.io.llptw.bits.req_info.vpn
119  arb2.io.in(InArbPTWPort).bits.source := ptw.io.llptw.bits.req_info.source
120  ptw.io.llptw.ready := arb2.io.in(InArbPTWPort).ready
121  block_decoupled(missQueue.io.out, arb2.io.in(InArbMissQueuePort), !ptw.io.req.ready)
122
123  arb2.io.in(InArbTlbPort).valid := arb1.io.out.valid
124  arb2.io.in(InArbTlbPort).bits.vpn := arb1.io.out.bits.vpn
125  arb2.io.in(InArbTlbPort).bits.source := arb1.io.chosen
126  if (l2tlbParams.enablePrefetch) {
127    val prefetch = Module(new L2TlbPrefetch())
128    val recv = cache.io.resp
129    // NOTE: 1. prefetch doesn't gen prefetch 2. req from mq doesn't gen prefetch
130    // NOTE: 1. miss req gen prefetch 2. hit but prefetched gen prefetch
131    prefetch.io.in.valid := recv.fire() && !from_pre(recv.bits.req_info.source) && (!recv.bits.hit  ||
132      recv.bits.prefetch) && recv.bits.isFirst
133    prefetch.io.in.bits.vpn := recv.bits.req_info.vpn
134    prefetch.io.sfence := sfence_dup(0)
135    prefetch.io.csr := csr_dup(0)
136    arb2.io.in(InArbPrefetchPort) <> prefetch.io.out
137
138    val L2TlbPrefetchTable = ChiselDB.createTable("L2TlbPrefetch_hart" + p(XSCoreParamsKey).HartId.toString, new L2TlbPrefetchDB)
139    val L2TlbPrefetchDB = Wire(new L2TlbPrefetchDB)
140    L2TlbPrefetchDB.vpn := prefetch.io.out.bits.vpn
141    L2TlbPrefetchTable.log(L2TlbPrefetchDB, prefetch.io.out.fire, "L2TlbPrefetch", clock, reset)
142  }
143  arb2.io.out.ready := cache.io.req.ready
144
145
146  val mq_arb = Module(new Arbiter(new L2TlbInnerBundle, 2))
147  mq_arb.io.in(0).valid := cache.io.resp.valid && !cache.io.resp.bits.hit &&
148    (!cache.io.resp.bits.toFsm.l2Hit || cache.io.resp.bits.bypassed) &&
149    !from_pre(cache.io.resp.bits.req_info.source) &&
150    (cache.io.resp.bits.bypassed || cache.io.resp.bits.isFirst || !ptw.io.req.ready)
151  mq_arb.io.in(0).bits :=  cache.io.resp.bits.req_info
152  mq_arb.io.in(1) <> llptw.io.cache
153  missQueue.io.in <> mq_arb.io.out
154  missQueue.io.sfence  := sfence_dup(6)
155  missQueue.io.csr := csr_dup(5)
156
157  blockmq.io.start := missQueue.io.out.fire
158  blockmq.io.enable := ptw.io.req.fire()
159
160  llptw.io.in.valid := cache.io.resp.valid && !cache.io.resp.bits.hit && cache.io.resp.bits.toFsm.l2Hit && !cache.io.resp.bits.bypassed
161  llptw.io.in.bits.req_info := cache.io.resp.bits.req_info
162  llptw.io.in.bits.ppn := cache.io.resp.bits.toFsm.ppn
163  llptw.io.sfence := sfence_dup(1)
164  llptw.io.csr := csr_dup(1)
165
166  cache.io.req.valid := arb2.io.out.valid
167  cache.io.req.bits.req_info.vpn := arb2.io.out.bits.vpn
168  cache.io.req.bits.req_info.source := arb2.io.out.bits.source
169  cache.io.req.bits.isFirst := arb2.io.chosen =/= InArbMissQueuePort.U
170  cache.io.req.bits.bypassed.map(_ := false.B)
171  cache.io.sfence := sfence_dup(2)
172  cache.io.csr := csr_dup(2)
173  cache.io.sfence_dup.zip(sfence_dup.drop(2).take(4)).map(s => s._1 := s._2)
174  cache.io.csr_dup.zip(csr_dup.drop(2).take(3)).map(c => c._1 := c._2)
175  cache.io.resp.ready := Mux(cache.io.resp.bits.hit,
176    outReady(cache.io.resp.bits.req_info.source, outArbCachePort),
177    Mux(cache.io.resp.bits.toFsm.l2Hit && !cache.io.resp.bits.bypassed, llptw.io.in.ready,
178    Mux(cache.io.resp.bits.bypassed || cache.io.resp.bits.isFirst, mq_arb.io.in(0).ready, mq_arb.io.in(0).ready || ptw.io.req.ready)))
179
180  // NOTE: missQueue req has higher priority
181  ptw.io.req.valid := cache.io.resp.valid && !cache.io.resp.bits.hit && !cache.io.resp.bits.toFsm.l2Hit &&
182    !cache.io.resp.bits.bypassed &&
183    !cache.io.resp.bits.isFirst
184  ptw.io.req.bits.req_info := cache.io.resp.bits.req_info
185  ptw.io.req.bits.l1Hit := cache.io.resp.bits.toFsm.l1Hit
186  ptw.io.req.bits.ppn := cache.io.resp.bits.toFsm.ppn
187  ptw.io.sfence := sfence_dup(7)
188  ptw.io.csr := csr_dup(6)
189  ptw.io.resp.ready := outReady(ptw.io.resp.bits.source, outArbFsmPort)
190
191  // mem req
192  def blockBytes_align(addr: UInt) = {
193    Cat(addr(PAddrBits - 1, log2Up(l2tlbParams.blockBytes)), 0.U(log2Up(l2tlbParams.blockBytes).W))
194  }
195  def addr_low_from_vpn(vpn: UInt) = {
196    vpn(log2Ceil(l2tlbParams.blockBytes)-log2Ceil(XLEN/8)-1, 0)
197  }
198  def addr_low_from_paddr(paddr: UInt) = {
199    paddr(log2Up(l2tlbParams.blockBytes)-1, log2Up(XLEN/8))
200  }
201  def from_missqueue(id: UInt) = {
202    (id =/= l2tlbParams.llptwsize.U)
203  }
204  val waiting_resp = RegInit(VecInit(Seq.fill(MemReqWidth)(false.B)))
205  val flush_latch = RegInit(VecInit(Seq.fill(MemReqWidth)(false.B)))
206  for (i <- waiting_resp.indices) {
207    assert(!flush_latch(i) || waiting_resp(i)) // when sfence_latch wait for mem resp, waiting_resp should be true
208  }
209
210  val llptw_out = llptw.io.out
211  val llptw_mem = llptw.io.mem
212  llptw_mem.req_mask := waiting_resp.take(l2tlbParams.llptwsize)
213  ptw.io.mem.mask := waiting_resp.last
214
215  val mem_arb = Module(new Arbiter(new L2TlbMemReqBundle(), 2))
216  mem_arb.io.in(0) <> ptw.io.mem.req
217  mem_arb.io.in(1) <> llptw_mem.req
218  mem_arb.io.out.ready := mem.a.ready && !flush
219
220  // assert, should not send mem access at same addr for twice.
221  val last_resp_vpn = RegEnable(cache.io.refill.bits.req_info_dup(0).vpn, cache.io.refill.valid)
222  val last_resp_level = RegEnable(cache.io.refill.bits.level_dup(0), cache.io.refill.valid)
223  val last_resp_v = RegInit(false.B)
224  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()
225  when (cache.io.refill.valid) { last_resp_v := !last_has_invalid}
226  when (flush) { last_resp_v := false.B }
227  XSError(last_resp_v && cache.io.refill.valid &&
228    (cache.io.refill.bits.req_info_dup(0).vpn === last_resp_vpn) &&
229    (cache.io.refill.bits.level_dup(0) === last_resp_level),
230    "l2tlb should not access mem at same addr for twice")
231  // ATTENTION: this may wronngly assert when: a ptes is l2, last part is valid,
232  // but the current part is invalid, so one more mem access happened
233  // If this happened, remove the assert.
234
235  val req_addr_low = Reg(Vec(MemReqWidth, UInt((log2Up(l2tlbParams.blockBytes)-log2Up(XLEN/8)).W)))
236
237  when (llptw.io.in.fire()) {
238    // when enq miss queue, set the req_addr_low to receive the mem resp data part
239    req_addr_low(llptw_mem.enq_ptr) := addr_low_from_vpn(llptw.io.in.bits.req_info.vpn)
240  }
241  when (mem_arb.io.out.fire()) {
242    req_addr_low(mem_arb.io.out.bits.id) := addr_low_from_paddr(mem_arb.io.out.bits.addr)
243    waiting_resp(mem_arb.io.out.bits.id) := true.B
244  }
245  // mem read
246  val memRead =  edge.Get(
247    fromSource = mem_arb.io.out.bits.id,
248    // toAddress  = memAddr(log2Up(CacheLineSize / 2 / 8) - 1, 0),
249    toAddress  = blockBytes_align(mem_arb.io.out.bits.addr),
250    lgSize     = log2Up(l2tlbParams.blockBytes).U
251  )._2
252  mem.a.bits := memRead
253  mem.a.valid := mem_arb.io.out.valid && !flush
254  mem.d.ready := true.B
255  // mem -> data buffer
256  val refill_data = Reg(Vec(blockBits / l1BusDataWidth, UInt(l1BusDataWidth.W)))
257  val refill_helper = edge.firstlastHelper(mem.d.bits, mem.d.fire())
258  val mem_resp_done = refill_helper._3
259  val mem_resp_from_mq = from_missqueue(mem.d.bits.source)
260  when (mem.d.valid) {
261    assert(mem.d.bits.source <= l2tlbParams.llptwsize.U)
262    refill_data(refill_helper._4) := mem.d.bits.data
263  }
264  // refill_data_tmp is the wire fork of refill_data, but one cycle earlier
265  val refill_data_tmp = WireInit(refill_data)
266  refill_data_tmp(refill_helper._4) := mem.d.bits.data
267
268  // save only one pte for each id
269  // (miss queue may can't resp to tlb with low latency, it should have highest priority, but diffcult to design cache)
270  val resp_pte = VecInit((0 until MemReqWidth).map(i =>
271    if (i == l2tlbParams.llptwsize) {RegEnable(get_part(refill_data_tmp, req_addr_low(i)), mem_resp_done && !mem_resp_from_mq) }
272    else { DataHoldBypass(get_part(refill_data, req_addr_low(i)), llptw_mem.buffer_it(i)) }
273    // llptw could not use refill_data_tmp, because enq bypass's result works at next cycle
274  ))
275
276  // mem -> miss queue
277  llptw_mem.resp.valid := mem_resp_done && mem_resp_from_mq
278  llptw_mem.resp.bits.id := DataHoldBypass(mem.d.bits.source, mem.d.valid)
279  // mem -> ptw
280  ptw.io.mem.req.ready := mem.a.ready
281  ptw.io.mem.resp.valid := mem_resp_done && !mem_resp_from_mq
282  ptw.io.mem.resp.bits := resp_pte.last
283  // mem -> cache
284  val refill_from_mq = mem_resp_from_mq
285  val refill_level = Mux(refill_from_mq, 2.U, RegEnable(ptw.io.refill.level, init = 0.U, ptw.io.mem.req.fire()))
286  val refill_valid = mem_resp_done && !flush && !flush_latch(mem.d.bits.source)
287
288  cache.io.refill.valid := RegNext(refill_valid, false.B)
289  cache.io.refill.bits.ptes := refill_data.asUInt
290  cache.io.refill.bits.req_info_dup.map(_ := RegEnable(Mux(refill_from_mq, llptw_mem.refill, ptw.io.refill.req_info), refill_valid))
291  cache.io.refill.bits.level_dup.map(_ := RegEnable(refill_level, refill_valid))
292  cache.io.refill.bits.levelOH(refill_level, refill_valid)
293  cache.io.refill.bits.sel_pte_dup.map(_ := RegNext(sel_data(refill_data_tmp.asUInt, req_addr_low(mem.d.bits.source))))
294
295  if (env.EnableDifftest) {
296    val difftest_ptw_addr = RegInit(VecInit(Seq.fill(MemReqWidth)(0.U(PAddrBits.W))))
297    when (mem.a.valid) {
298      difftest_ptw_addr(mem.a.bits.source) := mem.a.bits.address
299    }
300
301    val difftest = Module(new DifftestRefillEvent)
302    difftest.io.clock := clock
303    difftest.io.coreid := p(XSCoreParamsKey).HartId.asUInt
304    difftest.io.cacheid := 2.U
305    difftest.io.valid := cache.io.refill.valid
306    difftest.io.addr := difftest_ptw_addr(RegNext(mem.d.bits.source))
307    difftest.io.data := refill_data.asTypeOf(difftest.io.data)
308  }
309
310  if (env.EnableDifftest) {
311    for (i <- 0 until PtwWidth) {
312      val difftest = Module(new DifftestL2TLBEvent)
313      difftest.io.clock := clock
314      difftest.io.coreid := p(XSCoreParamsKey).HartId.asUInt
315      difftest.io.valid := io.tlb(i).resp.fire && !io.tlb(i).resp.bits.af
316      difftest.io.index := i.U
317      difftest.io.satp := io.csr.tlb.satp.ppn
318      difftest.io.vpn := io.tlb(i).resp.bits.entry.tag
319      difftest.io.ppn := io.tlb(i).resp.bits.entry.ppn
320      difftest.io.perm := io.tlb(i).resp.bits.entry.perm.getOrElse(0.U.asTypeOf(new PtePermBundle)).asUInt
321      difftest.io.level := io.tlb(i).resp.bits.entry.level.getOrElse(0.U.asUInt)
322      difftest.io.pf := io.tlb(i).resp.bits.pf
323    }
324  }
325
326  // pmp
327  pmp_check(0).req <> ptw.io.pmp.req
328  ptw.io.pmp.resp <> pmp_check(0).resp
329  pmp_check(1).req <> llptw.io.pmp.req
330  llptw.io.pmp.resp <> pmp_check(1).resp
331
332  llptw_out.ready := outReady(llptw_out.bits.req_info.source, outArbMqPort)
333  for (i <- 0 until PtwWidth) {
334    outArb(i).in(outArbCachePort).valid := cache.io.resp.valid && cache.io.resp.bits.hit && cache.io.resp.bits.req_info.source===i.U
335    outArb(i).in(outArbCachePort).bits.entry := cache.io.resp.bits.toTlb
336    outArb(i).in(outArbCachePort).bits.pf := !cache.io.resp.bits.toTlb.v
337    outArb(i).in(outArbCachePort).bits.af := false.B
338    outArb(i).in(outArbFsmPort).valid := ptw.io.resp.valid && ptw.io.resp.bits.source===i.U
339    outArb(i).in(outArbFsmPort).bits := ptw.io.resp.bits.resp
340    outArb(i).in(outArbMqPort).valid := llptw_out.valid && llptw_out.bits.req_info.source===i.U
341    outArb(i).in(outArbMqPort).bits := pte_to_ptwResp(resp_pte(llptw_out.bits.id), llptw_out.bits.req_info.vpn, llptw_out.bits.af, true)
342  }
343
344  // io.tlb.map(_.resp) <> outArb.map(_.out)
345  io.tlb.map(_.resp).zip(outArb.map(_.out)).map{
346    case (resp, out) => resp <> out
347  }
348
349  // sfence
350  when (flush) {
351    for (i <- 0 until MemReqWidth) {
352      when (waiting_resp(i)) {
353        flush_latch(i) := true.B
354      }
355    }
356  }
357  // mem -> control signal
358  // waiting_resp and sfence_latch will be reset when mem_resp_done
359  when (mem_resp_done) {
360    waiting_resp(mem.d.bits.source) := false.B
361    flush_latch(mem.d.bits.source) := false.B
362  }
363
364  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
365    sink.valid   := source.valid && !block_signal
366    source.ready := sink.ready   && !block_signal
367    sink.bits    := source.bits
368  }
369
370  def get_part(data: Vec[UInt], index: UInt): UInt = {
371    val inner_data = data.asTypeOf(Vec(data.getWidth / XLEN, UInt(XLEN.W)))
372    inner_data(index)
373  }
374
375  def pte_to_ptwResp(pte: UInt, vpn: UInt, af: Bool, af_first: Boolean) : PtwResp = {
376    val pte_in = pte.asTypeOf(new PteBundle())
377    val ptw_resp = Wire(new PtwResp())
378    ptw_resp.entry.ppn := pte_in.ppn
379    ptw_resp.entry.level.map(_ := 2.U)
380    ptw_resp.entry.perm.map(_ := pte_in.getPerm())
381    ptw_resp.entry.tag := vpn
382    ptw_resp.pf := (if (af_first) !af else true.B) && pte_in.isPf(2.U)
383    ptw_resp.af := (if (!af_first) pte_in.isPf(2.U) else true.B) && (af || pte_in.isAf())
384    ptw_resp.entry.v := !ptw_resp.pf
385    ptw_resp.entry.prefetch := DontCare
386    ptw_resp.entry.asid := satp.asid
387    ptw_resp
388  }
389
390  def outReady(source: UInt, port: Int): Bool = {
391    MuxLookup(source, true.B,
392      (0 until PtwWidth).map(i => i.U -> outArb(i).in(port).ready))
393  }
394
395  // debug info
396  for (i <- 0 until PtwWidth) {
397    XSDebug(p"[io.tlb(${i.U})] ${io.tlb(i)}\n")
398  }
399  XSDebug(p"[sfence] ${io.sfence}\n")
400  XSDebug(p"[io.csr.tlb] ${io.csr.tlb}\n")
401
402  for (i <- 0 until PtwWidth) {
403    XSPerfAccumulate(s"req_count${i}", io.tlb(i).req(0).fire())
404    XSPerfAccumulate(s"req_blocked_count_${i}", io.tlb(i).req(0).valid && !io.tlb(i).req(0).ready)
405  }
406  XSPerfAccumulate(s"req_blocked_by_mq", arb1.io.out.valid && missQueue.io.out.valid)
407  for (i <- 0 until (MemReqWidth + 1)) {
408    XSPerfAccumulate(s"mem_req_util${i}", PopCount(waiting_resp) === i.U)
409  }
410  XSPerfAccumulate("mem_cycle", PopCount(waiting_resp) =/= 0.U)
411  XSPerfAccumulate("mem_count", mem.a.fire())
412  for (i <- 0 until PtwWidth) {
413    XSPerfAccumulate(s"llptw_ppn_af${i}", outArb(i).in(outArbMqPort).valid && outArb(i).in(outArbMqPort).bits.af && !llptw_out.bits.af)
414    XSPerfAccumulate(s"access_fault${i}", io.tlb(i).resp.fire && io.tlb(i).resp.bits.af)
415  }
416
417  // print configs
418  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}")
419
420  // time out assert
421  for (i <- 0 until MemReqWidth) {
422    TimeOutAssert(waiting_resp(i), timeOutThreshold, s"ptw mem resp time out wait_resp${i}")
423    TimeOutAssert(flush_latch(i), timeOutThreshold, s"ptw mem resp time out flush_latch${i}")
424  }
425
426
427  val perfEvents  = Seq(llptw, cache, ptw).flatMap(_.getPerfEvents)
428  generatePerfEvent()
429
430  val L1TlbTable = ChiselDB.createTable("L1Tlb_hart" + p(XSCoreParamsKey).HartId.toString, new L1TlbDB)
431  val ITlbReqDB, DTlbReqDB, ITlbRespDB, DTlbRespDB = Wire(new L1TlbDB)
432  ITlbReqDB.vpn := io.tlb(0).req(0).bits.vpn
433  DTlbReqDB.vpn := io.tlb(1).req(0).bits.vpn
434  ITlbRespDB.vpn := io.tlb(0).resp.bits.entry.tag
435  DTlbRespDB.vpn := io.tlb(1).resp.bits.entry.tag
436  L1TlbTable.log(ITlbReqDB, io.tlb(0).req(0).fire, "ITlbReq", clock, reset)
437  L1TlbTable.log(DTlbReqDB, io.tlb(1).req(0).fire, "DTlbReq", clock, reset)
438  L1TlbTable.log(ITlbRespDB, io.tlb(0).resp.fire, "ITlbResp", clock, reset)
439  L1TlbTable.log(DTlbRespDB, io.tlb(1).resp.fire, "DTlbResp", clock, reset)
440
441  val PageCacheTable = ChiselDB.createTable("PageCache_hart" + p(XSCoreParamsKey).HartId.toString, new PageCacheDB)
442  val PageCacheDB = Wire(new PageCacheDB)
443  PageCacheDB.vpn := cache.io.resp.bits.toTlb.tag
444  PageCacheDB.source := cache.io.resp.bits.req_info.source
445  PageCacheDB.bypassed := cache.io.resp.bits.bypassed
446  PageCacheDB.is_first := cache.io.resp.bits.isFirst
447  PageCacheDB.prefetched := cache.io.resp.bits.toTlb.prefetch
448  PageCacheDB.prefetch := cache.io.resp.bits.prefetch
449  PageCacheDB.l2Hit := cache.io.resp.bits.toFsm.l2Hit
450  PageCacheDB.l1Hit := cache.io.resp.bits.toFsm.l1Hit
451  PageCacheDB.hit := cache.io.resp.bits.hit
452  PageCacheTable.log(PageCacheDB, cache.io.resp.fire, "PageCache", clock, reset)
453
454  val PTWTable = ChiselDB.createTable("PTW_hart" + p(XSCoreParamsKey).HartId.toString, new PTWDB)
455  val PTWReqDB, PTWRespDB, LLPTWReqDB, LLPTWRespDB = Wire(new PTWDB)
456  PTWReqDB.vpn := ptw.io.req.bits.req_info.vpn
457  PTWReqDB.source := ptw.io.req.bits.req_info.source
458  PTWRespDB.vpn := ptw.io.refill.req_info.vpn
459  PTWRespDB.source := ptw.io.refill.req_info.source
460  LLPTWReqDB.vpn := llptw.io.in.bits.req_info.vpn
461  LLPTWReqDB.source := llptw.io.in.bits.req_info.source
462  LLPTWRespDB.vpn := llptw.io.mem.refill.vpn
463  LLPTWRespDB.source := llptw.io.mem.refill.source
464  PTWTable.log(PTWReqDB, ptw.io.req.fire, "PTWReq", clock, reset)
465  PTWTable.log(PTWRespDB, ptw.io.mem.resp.fire, "PTWResp", clock, reset)
466  PTWTable.log(LLPTWReqDB, llptw.io.in.fire, "LLPTWReq", clock, reset)
467  PTWTable.log(LLPTWRespDB, llptw.io.mem.resp.fire, "LLPTWResp", clock, reset)
468
469  val L2TlbMissQueueTable = ChiselDB.createTable("L2TlbMissQueue_hart" + p(XSCoreParamsKey).HartId.toString, new L2TlbMissQueueDB)
470  val L2TlbMissQueueInDB, L2TlbMissQueueOutDB = Wire(new L2TlbMissQueueDB)
471  L2TlbMissQueueInDB.vpn := missQueue.io.in.bits.vpn
472  L2TlbMissQueueOutDB.vpn := missQueue.io.out.bits.vpn
473  L2TlbMissQueueTable.log(L2TlbMissQueueInDB, missQueue.io.in.fire, "L2TlbMissQueueIn", clock, reset)
474  L2TlbMissQueueTable.log(L2TlbMissQueueOutDB, missQueue.io.out.fire, "L2TlbMissQueueOut", clock, reset)
475}
476
477/** BlockHelper, block missqueue, not to send too many req to cache
478 *  Parameter:
479 *    enable: enable BlockHelper, mq should not send too many reqs
480 *    start: when miss queue out fire and need, block miss queue's out
481 *    block: block miss queue's out
482 *    latency: last missqueue out's cache access latency
483 */
484class BlockHelper(latency: Int)(implicit p: Parameters) extends XSModule {
485  val io = IO(new Bundle {
486    val enable = Input(Bool())
487    val start = Input(Bool())
488    val block = Output(Bool())
489  })
490
491  val count = RegInit(0.U(log2Ceil(latency).W))
492  val valid = RegInit(false.B)
493  val work = RegInit(true.B)
494
495  io.block := valid
496
497  when (io.start && work) { valid := true.B }
498  when (valid) { count := count + 1.U }
499  when (count === (latency.U) || io.enable) {
500    valid := false.B
501    work := io.enable
502    count := 0.U
503  }
504}
505
506class PTEHelper() extends ExtModule {
507  val clock  = IO(Input(Clock()))
508  val enable = IO(Input(Bool()))
509  val satp   = IO(Input(UInt(64.W)))
510  val vpn    = IO(Input(UInt(64.W)))
511  val pte    = IO(Output(UInt(64.W)))
512  val level  = IO(Output(UInt(8.W)))
513  val pf     = IO(Output(UInt(8.W)))
514}
515
516class PTWDelayN[T <: Data](gen: T, n: Int, flush: Bool) extends Module {
517  val io = IO(new Bundle() {
518    val in = Input(gen)
519    val out = Output(gen)
520    val ptwflush = Input(flush.cloneType)
521  })
522  val out = RegInit(VecInit(Seq.fill(n)(0.U.asTypeOf(gen))))
523  val t = RegInit(VecInit(Seq.fill(n)(0.U.asTypeOf(gen))))
524  out(0) := io.in
525  if (n == 1) {
526    io.out := out(0)
527  } else {
528    when (io.ptwflush) {
529      for (i <- 0 until n) {
530        t(i) := 0.U.asTypeOf(gen)
531        out(i) := 0.U.asTypeOf(gen)
532      }
533      io.out := 0.U.asTypeOf(gen)
534    } .otherwise {
535      for (i <- 1 until n) {
536        t(i-1) := out(i-1)
537        out(i) := t(i-1)
538      }
539      io.out := out(n-1)
540    }
541  }
542}
543
544object PTWDelayN {
545  def apply[T <: Data](in: T, n: Int, flush: Bool): T = {
546    val delay = Module(new PTWDelayN(in.cloneType, n, flush))
547    delay.io.in := in
548    delay.io.ptwflush := flush
549    delay.io.out
550  }
551}
552
553class FakePTW()(implicit p: Parameters) extends XSModule with HasPtwConst {
554  val io = IO(new L2TLBIO)
555  val flush = VecInit(Seq.fill(PtwWidth)(false.B))
556  flush(0) := DelayN(io.sfence.valid || io.csr.tlb.satp.changed, itlbParams.fenceDelay)
557  flush(1) := DelayN(io.sfence.valid || io.csr.tlb.satp.changed, ldtlbParams.fenceDelay)
558  for (i <- 0 until PtwWidth) {
559    val helper = Module(new PTEHelper())
560    helper.clock := clock
561    helper.satp := io.csr.tlb.satp.ppn
562
563    if (coreParams.softPTWDelay == 1) {
564      helper.enable := io.tlb(i).req(0).fire
565      helper.vpn := io.tlb(i).req(0).bits.vpn
566    } else {
567      helper.enable := PTWDelayN(io.tlb(i).req(0).fire, coreParams.softPTWDelay - 1, flush(i))
568      helper.vpn := PTWDelayN(io.tlb(i).req(0).bits.vpn, coreParams.softPTWDelay - 1, flush(i))
569    }
570
571    val pte = helper.pte.asTypeOf(new PteBundle)
572    val level = helper.level
573    val pf = helper.pf
574    val empty = RegInit(true.B)
575    when (io.tlb(i).req(0).fire) {
576      empty := false.B
577    } .elsewhen (io.tlb(i).resp.fire || flush(i)) {
578      empty := true.B
579    }
580
581    io.tlb(i).req(0).ready := empty || io.tlb(i).resp.fire
582    io.tlb(i).resp.valid := PTWDelayN(io.tlb(i).req(0).fire, coreParams.softPTWDelay, flush(i))
583    assert(!io.tlb(i).resp.valid || io.tlb(i).resp.ready)
584    io.tlb(i).resp.bits.entry.tag := PTWDelayN(io.tlb(i).req(0).bits.vpn, coreParams.softPTWDelay, flush(i))
585    io.tlb(i).resp.bits.entry.ppn := pte.ppn
586    io.tlb(i).resp.bits.entry.perm.map(_ := pte.getPerm())
587    io.tlb(i).resp.bits.entry.level.map(_ := level)
588    io.tlb(i).resp.bits.pf := pf
589    io.tlb(i).resp.bits.af := DontCare // TODO: implement it
590    io.tlb(i).resp.bits.entry.v := !pf
591    io.tlb(i).resp.bits.entry.prefetch := DontCare
592    io.tlb(i).resp.bits.entry.asid := io.csr.tlb.satp.asid
593  }
594}
595
596class L2TLBWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
597  val useSoftPTW = coreParams.softPTW
598  val node = if (!useSoftPTW) TLIdentityNode() else null
599  val ptw = if (!useSoftPTW) LazyModule(new L2TLB()) else null
600  if (!useSoftPTW) {
601    node := ptw.node
602  }
603
604  lazy val module = new LazyModuleImp(this) with HasPerfEvents {
605    val io = IO(new L2TLBIO)
606    val perfEvents = if (useSoftPTW) {
607      val fake_ptw = Module(new FakePTW())
608      io <> fake_ptw.io
609      Seq()
610    }
611    else {
612        io <> ptw.module.io
613        ptw.module.getPerfEvents
614    }
615    generatePerfEvent()
616  }
617}
618