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