xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/TLB.scala (revision d61cd5eecdc204c74ec210166665a10f4eb680f1)
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 difftest._
23import freechips.rocketchip.util.SRAMAnnotation
24import xiangshan._
25import utils._
26import utility._
27import xiangshan.backend.fu.{PMPChecker, PMPReqBundle, PMPConfig => XSPMPConfig}
28import xiangshan.backend.rob.RobPtr
29import xiangshan.backend.fu.util.HasCSRConst
30import freechips.rocketchip.rocket.PMPConfig
31
32/** TLB module
33  * support block request and non-block request io at the same time
34  * return paddr at next cycle, then go for pmp/pma check
35  * @param Width: The number of requestors
36  * @param Block: Blocked or not for each requestor ports
37  * @param q: TLB Parameters, like entry number, each TLB has its own parameters
38  * @param p: XiangShan Paramemters, like XLEN
39  */
40
41class TLB(Width: Int, nRespDups: Int = 1, Block: Seq[Boolean], q: TLBParameters)(implicit p: Parameters) extends TlbModule
42  with HasCSRConst
43  with HasPerfEvents
44{
45  val io = IO(new TlbIO(Width, nRespDups, q))
46
47  val req = io.requestor.map(_.req)
48  val resp = io.requestor.map(_.resp)
49  val ptw = io.ptw
50  val pmp = io.pmp
51  val refill_to_mem = io.refill_to_mem
52
53  /** Sfence.vma & Svinval
54    * Sfence.vma will 1. flush old entries 2. flush inflight 3. flush pipe
55    * Svinval will 1. flush old entries 2. flush inflight
56    * So, Svinval will not flush pipe, which means
57    * it should not drop reqs from pipe and should return right resp
58    */
59  val sfence = DelayN(io.sfence, q.fenceDelay)
60  val csr = io.csr
61  val satp = DelayN(io.csr.satp, q.fenceDelay)
62  val vsatp = DelayN(io.csr.vsatp, q.fenceDelay)
63  val hgatp = DelayN(io.csr.hgatp, q.fenceDelay)
64  val isHyperInst = (0 until Width).map(i => ValidHold(req(i).fire && !req(i).bits.kill && req(i).bits.hyperinst, resp(i).fire, flush_pipe(i)))
65  val isHlvx = (0 until Width).map(i => ValidHold(req(i).fire && !req(i).bits.kill && req(i).bits.hlvx, resp(i).fire, flush_pipe(i)))
66  val onlyS2xlate = vsatp.mode === 0.U && hgatp.mode === 8.U
67
68  val flush_mmu = DelayN(sfence.valid || csr.satp.changed || csr.vsatp.changed || csr.hgatp.changed, q.fenceDelay)
69  val mmu_flush_pipe = DelayN(sfence.valid && sfence.bits.flushPipe, q.fenceDelay) // for svinval, won't flush pipe
70  val flush_pipe = io.flushPipe
71
72  // ATTENTION: csr and flush from backend are delayed. csr should not be later than flush.
73  // because, csr will influence tlb behavior.
74  val ifecth = if (q.fetchi) true.B else false.B
75  val mode_tmp = if (q.useDmode) csr.priv.dmode else csr.priv.imode
76  val mode = (0 until Width).map(i => Mux(isHyperInst(i), csr.priv.spvp, mode_tmp))
77  val virt = csr.priv.virt
78  val sum = (0 until Width).map(i => Mux(virt || isHyperInst(i), io.csr.priv.vsum, io.csr.priv.sum))
79  val mxr = (0 until Width).map(i => Mux(virt || isHyperInst(i), io.csr.priv.vmxr || io.csr.priv.mxr, io.csr.priv.mxr))
80
81  // val vmEnable = satp.mode === 8.U // && (mode < ModeM) // FIXME: fix me when boot xv6/linux...
82  val vmEnable = (0 until Width).map(i => if (EnbaleTlbDebug) (satp.mode === 8.U)
83    else (satp.mode === 8.U) && (mode(i) < ModeM))
84  val s2xlateEnable = (0 until Width).map(i => (isHyperInst(i) || virt) && (vsatp.mode === 8.U || hgatp.mode === 8.U) && (mode(i) < ModeM))
85  val portTranslateEnable = (0 until Width).map(i => (vmEnable(i) || s2xlateEnable(i)) && RegNext(!req(i).bits.no_translate))
86
87  val req_in = req
88  val req_out = req.map(a => RegEnable(a.bits, a.fire))
89  val req_out_v = (0 until Width).map(i => ValidHold(req_in(i).fire && !req_in(i).bits.kill, resp(i).fire, flush_pipe(i)))
90
91  val refill = (0 until Width).map(i => ptw.resp.fire && !flush_mmu && (vmEnable(i) || ptw.resp.bits.s2xlate =/= noS2xlate))
92
93  val entries = Module(new TlbStorageWrapper(Width, q, nRespDups))
94  entries.io.base_connect(sfence, csr, satp)
95  if (q.outReplace) { io.replace <> entries.io.replace }
96  for (i <- 0 until Width) {
97    val s2xlate = Wire(UInt(2.W))
98    s2xlate := MuxCase(noS2xlate, Seq(
99      !(virt || req_in(i).bits.hyperinst) -> noS2xlate,
100      vsatp.mode =/= 0.U && hgatp.mode =/= 0.U -> allStage,
101      vsatp.mode === 0.U -> onlyStage2,
102      hgatp.mode === 0.U -> onlyStage1
103    ))
104    entries.io.r_req_apply(io.requestor(i).req.valid, get_pn(req_in(i).bits.vaddr), i, s2xlate)
105    entries.io.w_apply(refill, ptw.resp.bits)
106    resp(i).bits.debug.isFirstIssue := RegNext(req(i).bits.debug.isFirstIssue)
107    resp(i).bits.debug.robIdx := RegNext(req(i).bits.debug.robIdx)
108  }
109
110  // read TLB, get hit/miss, paddr, perm bits
111  val readResult = (0 until Width).map(TLBRead(_))
112  val hitVec = readResult.map(_._1)
113  val missVec = readResult.map(_._2)
114  val pmp_addr = readResult.map(_._3)
115  val perm = readResult.map(_._4)
116  val g_perm = readResult.map(_._7)
117  val s2xlate = readResult.map(_._8)
118  val need_gpa = readResult.map(_._9)
119  // check pmp use paddr (for timing optization, use pmp_addr here)
120  // check permisson
121  (0 until Width).foreach{i =>
122    pmp_check(pmp_addr(i), req_out(i).size, req_out(i).cmd, i)
123    for (d <- 0 until nRespDups) {
124      perm_check(perm(i)(d), req_out(i).cmd, i, d, g_perm(i)(d), req_out(i).hlvx, s2xlate(i))
125    }
126  }
127
128  // handle block or non-block io
129  // for non-block io, just return the above result, send miss to ptw
130  // for block io, hold the request, send miss to ptw,
131  //   when ptw back, return the result
132  (0 until Width) foreach {i =>
133    if (Block(i)) handle_block(i)
134    else handle_nonblock(i)
135  }
136  io.ptw.resp.ready := true.B
137
138  /************************  main body above | method/log/perf below ****************************/
139  def TLBRead(i: Int) = {
140    val s2xlate = Wire(UInt(2.W))
141    s2xlate := MuxCase(noS2xlate, Seq(
142      !(virt || req_in(i).bits.hyperinst) -> noS2xlate,
143      vsatp.mode =/= 0.U && hgatp.mode =/= 0.U -> allStage,
144      vsatp.mode === 0.U -> onlyStage2,
145      hgatp.mode === 0.U -> onlyStage1
146    ))
147    val (e_hit_tmp, e_ppn, e_perm, e_super_hit_tmp, e_super_ppn, static_pm, e_g_perm, e_s2xlate) = entries.io.r_resp_apply(i)
148    val (p_hit, p_ppn, p_perm, p_gvpn, p_g_perm, p_s2xlate) = ptw_resp_bypass(get_pn(req_in(i).bits.vaddr), s2xlate)
149    val enable = portTranslateEnable(i)
150
151    val need_gpa = Mux(p_hit, false.B, !(s2xlate === onlyStage2) && (resp(i).bits.excp(0).gpf.ld || resp(i).bits.excp(0).gpf.st || resp(i).bits.excp(0).gpf.instr))
152    val e_hit = e_hit_tmp && !need_gpa
153    val e_super_hit = e_super_hit_tmp && !need_gpa
154    val hit = e_hit || p_hit
155    val miss = !hit && enable
156    hit.suggestName(s"hit_read_${i}")
157    miss.suggestName(s"miss_read_${i}")
158
159    val vaddr = SignExt(req_out(i).vaddr, PAddrBits)
160    resp(i).bits.miss := miss
161    resp(i).bits.ptwBack := ptw.resp.fire
162    resp(i).bits.memidx := RegNext(req_in(i).bits.memidx)
163
164    val ppn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ppnLen.W))))
165    val perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle))))
166    val gvpn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(vpnLen.W))))
167    val g_perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle))))
168    for (d <- 0 until nRespDups) {
169      ppn(d) := Mux(p_hit, p_ppn, e_ppn(d))
170      perm(d) := Mux(p_hit, p_perm, e_perm(d))
171      gvpn(d) :=  p_gvpn
172      g_perm(d) := Mux(p_hit, p_g_perm, e_g_perm(d))
173      s2xlate(d) := Mux(p_hit, p_s2xlate, e_s2xlate(d))
174      val paddr = Cat(ppn(d), get_off(req_out(i).vaddr))
175      val gpaddr = Cat(gvpn(d), get_off(req_out(i).vaddr))
176      resp(i).bits.paddr(d) := Mux(enable, paddr, vaddr)
177      resp(i).bits.gpaddr(d) := Mux(s2xlate === onlyStage2, vaddr, gpaddr)
178    }
179
180    XSDebug(req_out_v(i), p"(${i.U}) hit:${hit} miss:${miss} ppn:${Hexadecimal(ppn(0))} perm:${perm(0)}\n")
181
182    val pmp_paddr = resp(i).bits.paddr(0)
183
184    (hit, miss, pmp_paddr, perm, g_perm, s2xlate, need_gpa)
185  }
186
187  def pmp_check(addr: UInt, size: UInt, cmd: UInt, idx: Int): Unit = {
188    pmp(idx).valid := resp(idx).valid
189    pmp(idx).bits.addr := addr
190    pmp(idx).bits.size := size
191    pmp(idx).bits.cmd := cmd
192  }
193
194  def perm_check(perm: TlbPermBundle, cmd: UInt, idx: Int, nDups: Int, g_perm: TlbPermBundle, hlvx: Bool, s2xlate: UInt) = {
195    // for timing optimization, pmp check is divided into dynamic and static
196    // dynamic: superpage (or full-connected reg entries) -> check pmp when translation done
197    // static: 4K pages (or sram entries) -> check pmp with pre-checked results
198    val hasS2xlate = s2xlate(0) === 1.U
199    val onlyS2 = s2xlate === 11.U
200    val af = perm.af || (hasS2xlate && g_perm.af)
201
202    // Stage 1 perm check
203    val pf = perm.pf
204    val ldUpdate = !perm.a && TlbCmd.isRead(cmd) && !TlbCmd.isAmo(cmd) // update A/D through exception
205    val stUpdate = (!perm.a || !perm.d) && (TlbCmd.isWrite(cmd) || TlbCmd.isAmo(cmd)) // update A/D through exception
206    val instrUpdate = !perm.a && TlbCmd.isExec(cmd) // update A/D through exception
207    val modeCheck = !(mode(idx) === ModeU && !perm.u || mode(idx) === ModeS && perm.u && (!sum(idx) || ifecth))
208    val ldPermFail = !(modeCheck && (perm.r || mxr(idx) && perm.x))
209    val stPermFail = !(modeCheck && perm.w)
210    val instrPermFail = !(modeCheck && perm.x)
211    val ldPf = (ldPermFail || pf) && (TlbCmd.isRead(cmd) && !TlbCmd.isAmo(cmd))
212    val stPf = (stPermFail || pf) && (TlbCmd.isWrite(cmd) || TlbCmd.isAmo(cmd))
213    val instrPf = (instrPermFail || pf) && TlbCmd.isExec(cmd)
214    val s1_valid = portTranslateEnable(idx) && !onlyS2
215
216    // Stage 2 perm check
217    val gpf = g_perm.pf
218    val g_ldUpdate = !g_perm.a && TlbCmd.isRead(cmd) && !TlbCmd.isAmo(cmd)
219    val g_stUpdate = (!g_perm.a || !g_perm.d) && (TlbCmd.isWrite(cmd) || TlbCmd.isAmo(cmd))
220    val g_instrUpdate = !g_perm.a && TlbCmd.isExec(cmd)
221    val g_ldPermFail = !(g_perm.r || io.csr.priv.mxr && g_perm.x)
222    val g_stPermFail = !g_perm.w
223    val g_instrPermFail = !g_perm.x
224    val ldGpf = (g_ldPermFail || gpf) && (TlbCmd.isRead(cmd) && !TlbCmd.isAmo(cmd))
225    val stGpf = (g_stPermFail || gpf) && (TlbCmd.isWrite(cmd) || TlbCmd.isAmo(cmd))
226    val instrGpf = (g_instrPermFail || gpf) && TlbCmd.isExec(cmd)
227    val s2_valid = hasS2xlate
228
229    val fault_valid = s1_valid || s2_valid
230
231    resp(idx).bits.excp(nDups).pf.ld := (ldPf || ldUpdate) && s1_valid && !af
232    resp(idx).bits.excp(nDups).pf.st := (stPf || stUpdate) && s1_valid && !af
233    resp(idx).bits.excp(nDups).pf.instr := (instrPf || instrUpdate) && s1_valid && !af
234    // NOTE: pf need && with !af, page fault has higher priority than access fault
235    // but ptw may also have access fault, then af happens, the translation is wrong.
236    // In this case, pf has lower priority than af
237
238    resp(idx).bits.excp(nDups).gpf.ld := (ldGpf || g_ldUpdate) && s2_valid && !af
239    resp(idx).bits.excp(nDups).gpf.st := (stGpf || g_stUpdate) && s2_valid && !af
240    resp(idx).bits.excp(nDups).gpf.instr := (instrGpf || g_instrUpdate) && s2_valid && !af
241
242    resp(idx).bits.excp(nDups).af.ld    := af && TlbCmd.isRead(cmd) && fault_valid
243    resp(idx).bits.excp(nDups).af.st    := af && TlbCmd.isWrite(cmd) && fault_valid
244    resp(idx).bits.excp(nDups).af.instr := af && TlbCmd.isExec(cmd) && fault_valid
245
246
247  }
248
249  def handle_nonblock(idx: Int): Unit = {
250    io.requestor(idx).resp.valid := req_out_v(idx)
251    io.requestor(idx).req.ready := io.requestor(idx).resp.ready // should always be true
252    XSError(!io.requestor(idx).resp.ready, s"${q.name} port ${idx} is non-block, resp.ready must be true.B")
253
254    val req_s2xlate = Wire(UInt(2.W))
255    req_s2xlate := MuxCase(noS2xlate, Seq(
256      !(virt || req_in(idx).bits.hyperinst) -> noS2xlate,
257      vsatp.mode =/= 0.U && hgatp.mode =/= 0.U -> allStage,
258      vsatp.mode === 0.U -> onlyStage2,
259      hgatp.mode === 0.U || need_gpa(idx) -> onlyStage1
260    ))
261    val ptw_s2xlate = ptw.resp.bits.s2xlate =/= noS2xlate
262    val onlyS2 = ptw_s2xlate === onlyStage2
263    val ptw_s1_hit = ptw.resp.bits.s1.hit(get_pn(req_out(idx).vaddr), Mux(ptw_s2xlate, io.csr.vsatp.asid, io.csr.satp.asid), io.csr.hgatp.asid, true, false, ptw_s2xlate)
264    val ptw_s2_hit = ptw.resp.bits.s2.hit(get_pn(req_out(idx).vaddr), io.csr.hgatp.asid)
265    val ptw_just_back = ptw.resp.fire && req_s2xlate === ptw_s2xlate&& Mux(onlyS2, ptw_s2_hit, ptw_s1_hit)
266    val ptw_already_back = RegNext(ptw.resp.fire) && RegNext(ptw.resp.bits).hit(get_pn(req_out(idx).vaddr), asid = io.csr.satp.asid, allType = true)
267    io.ptw.req(idx).valid := req_out_v(idx) && missVec(idx) && !(ptw_just_back || ptw_already_back) // TODO: remove the regnext, timing
268    io.tlbreplay(idx) := req_out_v(idx) && missVec(idx) && (ptw_just_back || ptw_already_back)
269    when (io.requestor(idx).req_kill && RegNext(io.requestor(idx).req.fire)) {
270      io.ptw.req(idx).valid := false.B
271      io.tlbreplay(idx) := true.B
272    }
273    io.ptw.req(idx).bits.vpn := get_pn(req_out(idx).vaddr)
274    io.ptw.req(idx).bits.s2xlate := RegNext(req_s2xlate)
275    io.ptw.req(idx).bits.memidx := req_out(idx).memidx
276  }
277
278  def handle_block(idx: Int): Unit = {
279    // three valid: 1.if exist a entry; 2.if sent to ptw; 3.unset resp.valid
280    io.requestor(idx).req.ready := !req_out_v(idx) || io.requestor(idx).resp.fire
281    // req_out_v for if there is a request, may long latency, fixme
282
283    // miss request entries
284    val miss_req_vpn = get_pn(req_out(idx).vaddr)
285    val miss_req_memidx = req_out(idx).memidx
286    val miss_req_s2xlate = Wire(UInt(2.W))
287    miss_req_s2xlate := MuxCase(noS2xlate, Seq(
288      !(virt || req_in(idx).bits.hyperinst) -> noS2xlate,
289      vsatp.mode =/= 0.U && hgatp.mode =/= 0.U -> allStage,
290      vsatp.mode === 0.U -> onlyStage2,
291      hgatp.mode === 0.U || need_gpa -> onlyStage1
292    ))
293    val hasS2xlate = miss_req_s2xlate =/= noS2xlate
294    val onlyS2 = miss_req_s2xlate === onlyStage2
295    val hit_s1 = io.ptw.resp.bits.s1.hit(miss_req_vpn, Mux(hasS2xlate, io.csr.vsatp.asid, io.csr.satp.asid), io.csr.hgatp.asid, allType = true, false, hasS2xlate)
296    val hit_s2 = io.ptw.resp.bits.s2.hit(miss_req_vpn, io.csr.hgatp.asid)
297    val hit = Mux(onlyS2, hit_s2, hit_s1) && io.ptw.resp.valid && miss_req_s2xlate === io.ptw.resp.bits.s2xlate
298
299    val new_coming = RegNext(req_in(idx).fire && !req_in(idx).bits.kill && !flush_pipe(idx), false.B)
300    val miss_wire = new_coming && missVec(idx)
301    val miss_v = ValidHoldBypass(miss_wire, resp(idx).fire, flush_pipe(idx))
302    val miss_req_v = ValidHoldBypass(miss_wire || (miss_v && flush_mmu && !mmu_flush_pipe),
303      io.ptw.req(idx).fire || resp(idx).fire, flush_pipe(idx))
304
305    // when ptw resp, check if hit, reset miss_v, resp to lsu/ifu
306    resp(idx).valid := req_out_v(idx) && !(miss_v && portTranslateEnable(idx))
307    when (io.ptw.resp.fire && hit && req_out_v(idx) && portTranslateEnable(idx)) {
308      val stage1 = io.ptw.resp.bits.s1
309      val stage2 = io.ptw.resp.bits.s2
310      val s2xlate = io.ptw.resp.bits.s2xlate
311      resp(idx).valid := true.B
312      resp(idx).bits.miss := false.B // for blocked tlb, this is useless
313      val s1_paddr = Cat(stage1.genPPN(get_pn(req_out(idx).vaddr)), get_off(req_out(idx).vaddr))
314      val s2_paddr = Cat(stage2.genPPNS2(), get_off(req_out(idx).vaddr))
315      for (d <- 0 until nRespDups) {
316        resp(idx).bits.paddr(d) := Mux(s2xlate =/= noS2xlate, s2_paddr, s1_paddr)
317        resp(idx).bits.gpaddr(d) := s1_paddr
318        perm_check(stage1.entry.perm.get(), req_out(idx).cmd, idx, d, stage2.entry.perm, req_out(idx).hlvx, s2xlate)
319      }
320      pmp_check(resp(idx).bits.paddr(0), req_out(idx).size, req_out(idx).cmd, idx)
321
322      // NOTE: the unfiltered req would be handled by Repeater
323    }
324    assert(RegNext(!resp(idx).valid || resp(idx).ready, true.B), "when tlb resp valid, ready should be true, must")
325    assert(RegNext(req_out_v(idx) || !(miss_v || miss_req_v), true.B), "when not req_out_v, should not set miss_v/miss_req_v")
326
327    val ptw_req = io.ptw.req(idx)
328    ptw_req.valid := miss_req_v
329    ptw_req.bits.vpn := miss_req_vpn
330    ptw_req.bits.s2xlate := miss_req_s2xlate
331    ptw_req.bits.memidx := miss_req_memidx
332
333    io.tlbreplay(idx) := false.B
334
335    // NOTE: when flush pipe, tlb should abandon last req
336    // however, some outside modules like icache, dont care flushPipe, and still waiting for tlb resp
337    // just resp valid and raise page fault to go through. The pipe(ifu) will abandon it.
338    if (!q.outsideRecvFlush) {
339      when (req_out_v(idx) && flush_pipe(idx) && portTranslateEnable(idx)) {
340        resp(idx).valid := true.B
341        for (d <- 0 until nRespDups) {
342          resp(idx).bits.excp(d).pf.ld := true.B // sfence happened, pf for not to use this addr
343          resp(idx).bits.excp(d).pf.st := true.B
344          resp(idx).bits.excp(d).pf.instr := true.B
345        }
346      }
347    }
348  }
349
350  // when ptw resp, tlb at refill_idx maybe set to miss by force.
351  // Bypass ptw resp to check.
352  def ptw_resp_bypass(vpn: UInt, s2xlate: UInt) = {
353    val hasS2xlate = s2xlate(0) === 1.U
354    val onlyS2 = s2xlate(1) === 1.U && hasS2xlate
355    val s2xlate_hit = s2xlate === ptw.resp.bits.s2xlate
356    val normal_hit = ptw.resp.bits.s1.hit(vpn, Mux(hasS2xlate, io.csr.vsatp.asid, io.csr.satp.asid), io.csr.hgatp.asid, true, false, hasS2xlate)
357    val onlyS2_hit = ptw.resp.bits.s2.hit(vpn, io.csr.hgatp.asid)
358    val p_hit = RegNext(Mux(onlyS2, onlyS2_hit, normal_hit) && io.ptw.resp.fire && s2xlate_hit)
359    val ppn_s1 = ptw.resp.bits.s1.genPPN(vpn)
360    val ppn_s2 = ptw.resp.bits.s2.genPPNS2()
361    val p_ppn = RegEnable(Mux(hasS2xlate, ppn_s2, ppn_s1), io.ptw.resp.fire)
362    val p_perm = RegEnable(ptwresp_to_tlbperm(ptw.resp.bits.s1), io.ptw.resp.fire)
363    val p_gvpn = RegEnable(ptw.resp.bits.s2.entry.tag, io.ptw.resp.fire)
364    val p_g_perm = RegEnable(hptwresp_to_tlbperm(ptw.resp.bits.s2), io.ptw.resp.fire)
365    val p_s2xlate = RegEnable(ptw.resp.bits.s2xlate, io.ptw.resp.fire)
366    (p_hit, p_ppn, p_perm, p_gvpn, p_g_perm, p_s2xlate)
367  }
368
369  // assert
370  for(i <- 0 until Width) {
371    TimeOutAssert(req_out_v(i) && !resp(i).valid, timeOutThreshold, s"{q.name} port{i} long time no resp valid.")
372  }
373
374  // perf event
375  val result_ok = req_in.map(a => RegNext(a.fire))
376  val perfEvents =
377    Seq(
378      ("access", PopCount((0 until Width).map{i => if (Block(i)) io.requestor(i).req.fire else portTranslateEnable(i) && result_ok(i) })),
379      ("miss  ", PopCount((0 until Width).map{i => if (Block(i)) portTranslateEnable(i) && result_ok(i) && missVec(i) else ptw.req(i).fire })),
380    )
381  generatePerfEvent()
382
383  // perf log
384  for (i <- 0 until Width) {
385    if (Block(i)) {
386      XSPerfAccumulate(s"access${i}",result_ok(i) && portTranslateEnable(i))
387      XSPerfAccumulate(s"miss${i}", result_ok(i) && missVec(i))
388    } else {
389      XSPerfAccumulate("first_access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && RegNext(req(i).bits.debug.isFirstIssue))
390      XSPerfAccumulate("access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i))
391      XSPerfAccumulate("first_miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i) && RegNext(req(i).bits.debug.isFirstIssue))
392      XSPerfAccumulate("miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i))
393    }
394  }
395  XSPerfAccumulate("ptw_resp_count", ptw.resp.fire)
396  XSPerfAccumulate("ptw_resp_pf_count", ptw.resp.fire && ptw.resp.bits.pf)
397
398  // Log
399  for(i <- 0 until Width) {
400    XSDebug(req(i).valid, p"req(${i.U}): (${req(i).valid} ${req(i).ready}) ${req(i).bits}\n")
401    XSDebug(resp(i).valid, p"resp(${i.U}): (${resp(i).valid} ${resp(i).ready}) ${resp(i).bits}\n")
402  }
403
404  XSDebug(io.sfence.valid, p"Sfence: ${io.sfence}\n")
405  XSDebug(ParallelOR(req_out_v) || ptw.resp.valid, p"vmEnable:${vmEnable} hit:${Binary(VecInit(hitVec).asUInt)} miss:${Binary(VecInit(missVec).asUInt)}\n")
406  for (i <- ptw.req.indices) {
407    XSDebug(ptw.req(i).fire, p"L2TLB req:${ptw.req(i).bits}\n")
408  }
409  XSDebug(ptw.resp.valid, p"L2TLB resp:${ptw.resp.bits} (v:${ptw.resp.valid}r:${ptw.resp.ready}) \n")
410
411  println(s"${q.name}: page: ${q.NWays} ${q.Associative} ${q.Replacer.get}")
412
413  if (env.EnableDifftest) {
414    for (i <- 0 until Width) {
415      val pf = io.requestor(i).resp.bits.excp(0).pf.instr || io.requestor(i).resp.bits.excp(0).pf.st || io.requestor(i).resp.bits.excp(0).pf.ld
416      val gpf = io.requestor(i).resp.bits.excp(0).gpf.instr || io.requestor(i).resp.bits.excp(0).gpf.st || io.requestor(i).resp.bits.excp(0).gpf.ld
417      val af = io.requestor(i).resp.bits.excp(0).af.instr || io.requestor(i).resp.bits.excp(0).af.st || io.requestor(i).resp.bits.excp(0).af.ld
418      val difftest = DifftestModule(new DiffL1TLBEvent)
419      difftest.coreid := io.hartId
420      difftest.valid := RegNext(io.requestor(i).req.fire) && !io.requestor(i).req_kill && io.requestor(i).resp.fire && !io.requestor(i).resp.bits.miss && !pf && !af && !gpf && portTranslateEnable(i)
421      if (!Seq("itlb", "ldtlb", "sttlb").contains(q.name)) {
422        difftest.valid := false.B
423      }
424      difftest.index := TLBDiffId(p(XSCoreParamsKey).HartId).U
425      difftest.satp := io.csr.satp
426      difftest.vpn := RegNext(get_pn(req_in(i).bits.vaddr))
427      difftest.ppn := get_pn(io.requestor(i).resp.bits.paddr(0))
428      difftest.io.vsatp := io.csr.vsatp
429      difftest.io.hgatp := io.csr.hgatp
430      val s2xlate = Wire(UInt(2.W))
431      s2xlate := MuxCase(noS2xlate, Seq(
432        !(virt || req_in(idx).bits.hyperinst) -> noS2xlate,
433        vsatp.mode =/= 0.U && hgatp.mode =/= 0.U -> allStage,
434        vsatp.mode === 0.U -> onlyStage2,
435        hgatp.mode === 0.U || need_gpa -> onlyStage1
436      ))
437      difftest.io.s2xlate := s2xlate
438    }
439  }
440}
441
442object TLBDiffId {
443  var i: Int = 0
444  var lastHartId: Int = -1
445  def apply(hartId: Int): Int = {
446    if (lastHartId != hartId) {
447      i = 0
448      lastHartId = hartId
449    }
450    i += 1
451    i - 1
452  }
453}
454
455class TLBNonBlock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(false), q)
456class TLBBLock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(true), q)
457
458class TlbReplace(Width: Int, q: TLBParameters)(implicit p: Parameters) extends TlbModule {
459  val io = IO(new TlbReplaceIO(Width, q))
460
461  if (q.Associative == "fa") {
462    val re = ReplacementPolicy.fromString(q.Replacer, q.NWays)
463    re.access(io.page.access.map(_.touch_ways))
464    io.page.refillIdx := re.way
465  } else { // set-acco && plru
466    val re = ReplacementPolicy.fromString(q.Replacer, q.NSets, q.NWays)
467    re.access(io.page.access.map(_.sets), io.page.access.map(_.touch_ways))
468    io.page.refillIdx := { if (q.NWays == 1) 0.U else re.way(io.page.chosen_set) }
469  }
470}
471