xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/TLB.scala (revision a38d1eab87777ed93b417106a7dfd58a062cee18)
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 mPBMTE = DelayN(io.csr.mPBMTE, q.fenceDelay)
65  val hPBMTE = DelayN(io.csr.hPBMTE, q.fenceDelay)
66
67  val flush_mmu = DelayN(sfence.valid || csr.satp.changed || csr.vsatp.changed || csr.hgatp.changed, q.fenceDelay)
68  val mmu_flush_pipe = DelayN(sfence.valid && sfence.bits.flushPipe, q.fenceDelay) // for svinval, won't flush pipe
69  val flush_pipe = io.flushPipe
70  val redirect = io.redirect
71  val req_in = req
72  val req_out = req.map(a => RegEnable(a.bits, a.fire))
73  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)))
74
75  val isHyperInst = (0 until Width).map(i => req_out_v(i) && req_out(i).hyperinst)
76
77  // ATTENTION: csr and flush from backend are delayed. csr should not be later than flush.
78  // because, csr will influence tlb behavior.
79  val ifecth = if (q.fetchi) true.B else false.B
80  val mode_tmp = if (q.useDmode) csr.priv.dmode else csr.priv.imode
81  val mode = (0 until Width).map(i => Mux(isHyperInst(i), csr.priv.spvp, mode_tmp))
82  val virt_in = csr.priv.virt
83  val virt_out = req.map(a => RegEnable(csr.priv.virt, a.fire))
84  val sum = (0 until Width).map(i => Mux(virt_out(i) || isHyperInst(i), io.csr.priv.vsum, io.csr.priv.sum))
85  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))
86  val req_in_s2xlate = (0 until Width).map(i => MuxCase(noS2xlate, Seq(
87      (!(virt_in || req_in(i).bits.hyperinst)) -> noS2xlate,
88      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
89      (csr.vsatp.mode === 0.U) -> onlyStage2,
90      (csr.hgatp.mode === 0.U) -> onlyStage1
91    )))
92  val req_out_s2xlate = (0 until Width).map(i => MuxCase(noS2xlate, Seq(
93    (!(virt_out(i) || isHyperInst(i))) -> noS2xlate,
94    (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
95    (csr.vsatp.mode === 0.U) -> onlyStage2,
96    (csr.hgatp.mode === 0.U) -> onlyStage1
97  )))
98  val need_gpa = RegInit(false.B)
99  val need_gpa_robidx = Reg(new RobPtr)
100  val need_gpa_vpn = Reg(UInt(vpnLen.W))
101  val resp_gpa_gvpn = Reg(UInt(ptePPNLen.W))
102  val resp_gpa_refill = RegInit(false.B)
103  val resp_s1_level = RegInit(0.U(log2Up(Level + 1).W))
104  val resp_s1_isLeaf = RegInit(false.B)
105  val resp_s1_isFakePte = RegInit(false.B)
106  val hasGpf = Wire(Vec(Width, Bool()))
107
108  val Sv39Enable = satp.mode === 8.U
109  val Sv48Enable = satp.mode === 9.U
110  val Sv39x4Enable = vsatp.mode === 8.U || hgatp.mode === 8.U
111  val Sv48x4Enable = vsatp.mode === 9.U || hgatp.mode === 9.U
112  val vmEnable = (0 until Width).map(i => !(isHyperInst(i) || virt_out(i)) && (
113    if (EnbaleTlbDebug) (Sv39Enable || Sv48Enable)
114    else (Sv39Enable || Sv48Enable) && (mode(i) < ModeM))
115  )
116  val s2xlateEnable = (0 until Width).map(i => (isHyperInst(i) || virt_out(i)) && (Sv39x4Enable || Sv48x4Enable) && (mode(i) < ModeM))
117  val portTranslateEnable = (0 until Width).map(i => (vmEnable(i) || s2xlateEnable(i)) && RegEnable(!req(i).bits.no_translate, req(i).valid))
118
119  // pre fault: check fault before real do translate
120  val prepf = WireInit(VecInit(Seq.fill(Width)(false.B)))
121  val pregpf = WireInit(VecInit(Seq.fill(Width)(false.B)))
122  val preaf = WireInit(VecInit(Seq.fill(Width)(false.B)))
123  val prevmEnable = (0 until Width).map(i => !(virt_in || req_in(i).bits.hyperinst) && (
124    if (EnbaleTlbDebug) (Sv39Enable || Sv48Enable)
125    else (Sv39Enable || Sv48Enable) && (mode(i) < ModeM))
126  )
127  val pres2xlateEnable = (0 until Width).map(i => (virt_in || req_in(i).bits.hyperinst) && (Sv39x4Enable || Sv48x4Enable) && (mode(i) < ModeM))
128  (0 until Width).foreach{i =>
129    val pf48 = SignExt(req(i).bits.fullva(47, 0), XLEN) =/= req(i).bits.fullva
130    val pf39 = SignExt(req(i).bits.fullva(38, 0), XLEN) =/= req(i).bits.fullva
131    val gpf48 = req(i).bits.fullva(XLEN - 1, 48 + 2) =/= 0.U
132    val gpf39 = req(i).bits.fullva(XLEN - 1, 39 + 2) =/= 0.U
133    val af = req(i).bits.fullva(XLEN - 1, PAddrBits) =/= 0.U
134    when (req(i).valid && req(i).bits.checkfullva) {
135      when (prevmEnable(i) || pres2xlateEnable(i)) {
136        when (req_in_s2xlate(i) === onlyStage2) {
137          when (Sv48x4Enable) {
138            pregpf(i) := gpf48
139          } .elsewhen (Sv39x4Enable) {
140            pregpf(i) := gpf39
141          }
142        } .otherwise {
143          when (Sv48Enable) {
144            prepf(i) := pf48
145          } .elsewhen (Sv39Enable) {
146            prepf(i) := pf39
147          }
148        }
149      } .otherwise {
150        preaf(i) := af
151      }
152    }
153  }
154
155  val refill = ptw.resp.fire && !(ptw.resp.bits.getGpa) && !flush_mmu
156  refill_to_mem := DontCare
157  val entries = Module(new TlbStorageWrapper(Width, q, nRespDups))
158  entries.io.base_connect(sfence, csr, satp)
159  if (q.outReplace) { io.replace <> entries.io.replace }
160  for (i <- 0 until Width) {
161    entries.io.r_req_apply(io.requestor(i).req.valid, get_pn(req_in(i).bits.vaddr), i, req_in_s2xlate(i))
162    entries.io.w_apply(refill, ptw.resp.bits)
163    // TODO: RegNext enable:req.valid
164    resp(i).bits.debug.isFirstIssue := RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid)
165    resp(i).bits.debug.robIdx := RegEnable(req(i).bits.debug.robIdx, req(i).valid)
166  }
167
168  // read TLB, get hit/miss, paddr, perm bits
169  val readResult = (0 until Width).map(TLBRead(_))
170  val hitVec = readResult.map(_._1)
171  val missVec = readResult.map(_._2)
172  val pmp_addr = readResult.map(_._3)
173  val perm = readResult.map(_._4)
174  val g_perm = readResult.map(_._5)
175  val pbmt = readResult.map(_._6)
176  val g_pbmt = readResult.map(_._7)
177  // check pmp use paddr (for timing optization, use pmp_addr here)
178  // check permisson
179  (0 until Width).foreach{i =>
180    val noTranslateReg = RegNext(req(i).bits.no_translate)
181    val addr = Mux(noTranslateReg, req(i).bits.pmp_addr, pmp_addr(i))
182    pmp_check(addr, req_out(i).size, req_out(i).cmd, noTranslateReg, i)
183    for (d <- 0 until nRespDups) {
184      pbmt_check(i, d, pbmt(i)(d), g_pbmt(i)(d), req_out_s2xlate(i))
185      perm_check(perm(i)(d), req_out(i).cmd, i, d, g_perm(i)(d), req_out(i).hlvx, req_out_s2xlate(i), prepf(i), pregpf(i), preaf(i))
186    }
187    hasGpf(i) := hitVec(i) && (resp(i).bits.excp(0).gpf.ld || resp(i).bits.excp(0).gpf.st || resp(i).bits.excp(0).gpf.instr)
188  }
189
190  // handle block or non-block io
191  // for non-block io, just return the above result, send miss to ptw
192  // for block io, hold the request, send miss to ptw,
193  //   when ptw back, return the result
194  (0 until Width) foreach {i =>
195    if (Block(i)) handle_block(i)
196    else handle_nonblock(i)
197  }
198  io.ptw.resp.ready := true.B
199
200  /************************  main body above | method/log/perf below ****************************/
201  def TLBRead(i: Int) = {
202    val (e_hit, e_ppn, e_perm, e_g_perm, e_s2xlate, e_pbmt, e_g_pbmt) = entries.io.r_resp_apply(i)
203    val (p_hit, p_ppn, p_pbmt, p_perm, p_gvpn, p_g_pbmt, p_g_perm, p_s2xlate, p_s1_level, p_s1_isLeaf, p_s1_isFakePte) = ptw_resp_bypass(get_pn(req_in(i).bits.vaddr), req_in_s2xlate(i))
204    val enable = portTranslateEnable(i)
205    val isOnlys2xlate = req_out_s2xlate(i) === onlyStage2
206    val need_gpa_vpn_hit = need_gpa_vpn === get_pn(req_out(i).vaddr)
207    val isitlb = TlbCmd.isExec(req_out(i).cmd)
208    val isPrefetch = req_out(i).isPrefetch
209    val currentRedirect = req_out(i).debug.robIdx.needFlush(redirect)
210    val lastCycleRedirect = req_out(i).debug.robIdx.needFlush(RegNext(redirect))
211
212    when (!isitlb && need_gpa_robidx.needFlush(redirect) || isitlb && flush_pipe(i)){
213      need_gpa := false.B
214      resp_gpa_refill := false.B
215      need_gpa_vpn := 0.U
216    }.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 && !isPrefetch && !currentRedirect && !lastCycleRedirect) {
217      need_gpa := true.B
218      need_gpa_vpn := get_pn(req_out(i).vaddr)
219      resp_gpa_refill := false.B
220      need_gpa_robidx := req_out(i).debug.robIdx
221    }.elsewhen (ptw.resp.fire && need_gpa && need_gpa_vpn === ptw.resp.bits.getVpn(need_gpa_vpn)) {
222      resp_gpa_gvpn := Mux(ptw.resp.bits.s2xlate === onlyStage2, ptw.resp.bits.s2.entry.tag, ptw.resp.bits.s1.genGVPN(need_gpa_vpn))
223      resp_s1_level := ptw.resp.bits.s1.entry.level.get
224      resp_s1_isLeaf := ptw.resp.bits.s1.isLeaf()
225      resp_s1_isFakePte := ptw.resp.bits.s1.isFakePte()
226      resp_gpa_refill := true.B
227    }
228
229    when (req_out_v(i) && hasGpf(i) && resp_gpa_refill && need_gpa_vpn_hit){
230      need_gpa := false.B
231    }
232
233    val hit = e_hit || p_hit
234    val miss = (!hit && enable) || hasGpf(i) && !p_hit && !(resp_gpa_refill && need_gpa_vpn_hit) && !isOnlys2xlate && !isPrefetch && !lastCycleRedirect
235    hit.suggestName(s"hit_read_${i}")
236    miss.suggestName(s"miss_read_${i}")
237
238    val vaddr = SignExt(req_out(i).vaddr, PAddrBits)
239    resp(i).bits.miss := miss
240    resp(i).bits.ptwBack := ptw.resp.fire
241    resp(i).bits.memidx := RegEnable(req_in(i).bits.memidx, req_in(i).valid)
242    resp(i).bits.fastMiss := !hit && enable
243
244    val ppn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ppnLen.W))))
245    val pbmt = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePbmtLen.W))))
246    val perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle))))
247    val gvpn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(vpnLen.W))))
248    val level = WireInit(VecInit(Seq.fill(nRespDups)(0.U(log2Up(Level + 1).W))))
249    val isLeaf = WireInit(VecInit(Seq.fill(nRespDups)(false.B)))
250    val isFakePte = WireInit(VecInit(Seq.fill(nRespDups)(false.B)))
251    val g_pbmt = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePbmtLen.W))))
252    val g_perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle))))
253    val r_s2xlate = WireInit(VecInit(Seq.fill(nRespDups)(0.U(2.W))))
254    for (d <- 0 until nRespDups) {
255      ppn(d) := Mux(p_hit, p_ppn, e_ppn(d))
256      pbmt(d) := Mux(p_hit, p_pbmt, e_pbmt(d))
257      perm(d) := Mux(p_hit, p_perm, e_perm(d))
258      gvpn(d) :=  Mux(p_hit, p_gvpn, resp_gpa_gvpn)
259      level(d) := Mux(p_hit, p_s1_level, resp_s1_level)
260      isLeaf(d) := Mux(p_hit, p_s1_isLeaf, resp_s1_isLeaf)
261      isFakePte(d) := Mux(p_hit, p_s1_isFakePte, resp_s1_isFakePte)
262      g_pbmt(d) := Mux(p_hit, p_g_pbmt, e_g_pbmt(d))
263      g_perm(d) := Mux(p_hit, p_g_perm, e_g_perm(d))
264      r_s2xlate(d) := Mux(p_hit, p_s2xlate, e_s2xlate(d))
265      val paddr = Cat(ppn(d), get_off(req_out(i).vaddr))
266      val vpn_idx = Mux1H(Seq(
267        (isFakePte(d) && vsatp.mode === Sv39) -> 2.U,
268        (isFakePte(d) && vsatp.mode === Sv48) -> 3.U,
269        (!isFakePte(d)) -> (level(d) - 1.U),
270      ))
271      val gpaddr_offset = Mux(isLeaf(d), get_off(req_out(i).vaddr), Cat(getVpnn(get_pn(req_out(i).vaddr), vpn_idx),  0.U(log2Up(XLEN/8).W)))
272      val gpaddr = Cat(gvpn(d), gpaddr_offset)
273      resp(i).bits.paddr(d) := Mux(enable, paddr, vaddr)
274      resp(i).bits.gpaddr(d) := Mux(r_s2xlate(d) === onlyStage2, vaddr, gpaddr)
275    }
276
277    XSDebug(req_out_v(i), p"(${i.U}) hit:${hit} miss:${miss} ppn:${Hexadecimal(ppn(0))} perm:${perm(0)}\n")
278
279    val pmp_paddr = resp(i).bits.paddr(0)
280
281    (hit, miss, pmp_paddr, perm, g_perm, pbmt, g_pbmt)
282  }
283
284  def getVpnn(vpn: UInt, idx: UInt): UInt = {
285    MuxLookup(idx, 0.U)(Seq(
286      0.U -> vpn(vpnnLen - 1, 0),
287      1.U -> vpn(vpnnLen * 2 - 1, vpnnLen),
288      2.U -> vpn(vpnnLen * 3 - 1, vpnnLen * 2),
289      3.U -> vpn(vpnnLen * 4 - 1, vpnnLen * 3))
290    )
291  }
292
293  def pmp_check(addr: UInt, size: UInt, cmd: UInt, noTranslate: Bool, idx: Int): Unit = {
294    pmp(idx).valid := resp(idx).valid || noTranslate
295    pmp(idx).bits.addr := addr
296    pmp(idx).bits.size := size
297    pmp(idx).bits.cmd := cmd
298  }
299
300  def pbmt_check(idx: Int, d: Int, pbmt: UInt, g_pbmt: UInt, s2xlate: UInt):Unit = {
301    val onlyS1 = s2xlate === onlyStage1 || s2xlate === noS2xlate
302    val pbmtRes = pbmt
303    val gpbmtRes = g_pbmt
304    val res = MuxLookup(s2xlate, 0.U)(Seq(
305      onlyStage1 -> pbmtRes,
306      onlyStage2 -> gpbmtRes,
307      allStage -> Mux(pbmtRes =/= 0.U, pbmtRes, gpbmtRes),
308      noS2xlate -> pbmtRes
309    ))
310    resp(idx).bits.pbmt(d) := Mux(portTranslateEnable(idx), res, 0.U)
311  }
312
313  // for timing optimization, pmp check is divided into dynamic and static
314  def perm_check(perm: TlbPermBundle, cmd: UInt, idx: Int, nDups: Int, g_perm: TlbPermBundle, hlvx: Bool, s2xlate: UInt, prepf: Bool = false.B, pregpf: Bool = false.B, preaf: Bool = false.B) = {
315    // dynamic: superpage (or full-connected reg entries) -> check pmp when translation done
316    // static: 4K pages (or sram entries) -> check pmp with pre-checked results
317    val hasS2xlate = s2xlate =/= noS2xlate
318    val onlyS1 = s2xlate === onlyStage1
319    val onlyS2 = s2xlate === onlyStage2
320    val af = perm.af || (hasS2xlate && g_perm.af)
321
322    // Stage 1 perm check
323    val pf = perm.pf
324    val isLd = TlbCmd.isRead(cmd) && !TlbCmd.isAmo(cmd)
325    val isSt = TlbCmd.isWrite(cmd) || TlbCmd.isAmo(cmd)
326    val isInst = TlbCmd.isExec(cmd)
327    val ldUpdate = !perm.a && isLd // update A/D through exception
328    val stUpdate = (!perm.a || !perm.d) && isSt // update A/D through exception
329    val instrUpdate = !perm.a && isInst // update A/D through exception
330    val modeCheck = !(mode(idx) === ModeU && !perm.u || mode(idx) === ModeS && perm.u && (!sum(idx) || ifecth))
331    val ldPermFail = !(modeCheck && Mux(hlvx, perm.x, perm.r || mxr(idx) && perm.x))
332    val stPermFail = !(modeCheck && perm.w)
333    val instrPermFail = !(modeCheck && perm.x)
334    val ldPf = (ldPermFail || pf) && isLd
335    val stPf = (stPermFail || pf) && isSt
336    val instrPf = (instrPermFail || pf) && isInst
337    val isFakePte = !perm.v && !perm.pf && !perm.af && !onlyS2
338    val isNonLeaf = !(perm.r || perm.w || perm.x) && perm.v && !perm.pf && !perm.af
339    val s1_valid = portTranslateEnable(idx) && !onlyS2
340
341    // Stage 2 perm check
342    val gpf = g_perm.pf
343    val g_ldUpdate = !g_perm.a && isLd
344    val g_stUpdate = (!g_perm.a || !g_perm.d) && isSt
345    val g_instrUpdate = !g_perm.a && isInst
346    val g_ldPermFail = !Mux(hlvx, g_perm.x, (g_perm.r || io.csr.priv.mxr && g_perm.x))
347    val g_stPermFail = !g_perm.w
348    val g_instrPermFail = !g_perm.x
349    val ldGpf = (g_ldPermFail || gpf) && isLd
350    val stGpf = (g_stPermFail || gpf) && isSt
351    val instrGpf = (g_instrPermFail || gpf) && isInst
352    val s2_valid = portTranslateEnable(idx) && hasS2xlate && !onlyS1
353
354    val fault_valid = s1_valid || s2_valid
355
356    // when pf and gpf can't happens simultaneously
357    val hasPf = (ldPf || ldUpdate || stPf || stUpdate || instrPf || instrUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
358    // Only lsu need check related to high address truncation
359    when (RegNext(prepf || pregpf || preaf)) {
360      resp(idx).bits.isForVSnonLeafPTE := false.B
361      resp(idx).bits.excp(nDups).pf.ld := RegNext(prepf) && isLd
362      resp(idx).bits.excp(nDups).pf.st := RegNext(prepf) && isSt
363      resp(idx).bits.excp(nDups).pf.instr := false.B
364
365      resp(idx).bits.excp(nDups).gpf.ld := RegNext(pregpf) && isLd
366      resp(idx).bits.excp(nDups).gpf.st := RegNext(pregpf) && isSt
367      resp(idx).bits.excp(nDups).gpf.instr := false.B
368
369      resp(idx).bits.excp(nDups).af.ld := RegNext(preaf) && TlbCmd.isRead(cmd)
370      resp(idx).bits.excp(nDups).af.st := RegNext(preaf) && TlbCmd.isWrite(cmd)
371      resp(idx).bits.excp(nDups).af.instr := false.B
372
373      resp(idx).bits.excp(nDups).vaNeedExt := false.B
374      // overwrite miss & gpaddr when exception related to high address truncation happens
375      resp(idx).bits.miss := false.B
376      resp(idx).bits.gpaddr(nDups) := RegNext(req(idx).bits.fullva)
377    } .otherwise {
378      // isForVSnonLeafPTE is used only when gpf happens and it caused by a G-stage translation which supports VS-stage translation
379      // it will be sent to CSR in order to modify the m/htinst.
380      // Ref: The RISC-V Instruction Set Manual: Volume II: Privileged Architecture - 19.6.3. Transformed Instruction or Pseudoinstruction for mtinst or htinst
381      val isForVSnonLeafPTE = isNonLeaf || isFakePte
382      resp(idx).bits.isForVSnonLeafPTE := isForVSnonLeafPTE
383      resp(idx).bits.excp(nDups).pf.ld := (ldPf || ldUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
384      resp(idx).bits.excp(nDups).pf.st := (stPf || stUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
385      resp(idx).bits.excp(nDups).pf.instr := (instrPf || instrUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
386      // NOTE: pf need && with !af, page fault has higher priority than access fault
387      // but ptw may also have access fault, then af happens, the translation is wrong.
388      // In this case, pf has lower priority than af
389
390      resp(idx).bits.excp(nDups).gpf.ld := (ldGpf || g_ldUpdate) && s2_valid && !af && !hasPf
391      resp(idx).bits.excp(nDups).gpf.st := (stGpf || g_stUpdate) && s2_valid && !af && !hasPf
392      resp(idx).bits.excp(nDups).gpf.instr := (instrGpf || g_instrUpdate) && s2_valid && !af && !hasPf
393
394      resp(idx).bits.excp(nDups).af.ld    := af && TlbCmd.isRead(cmd) && fault_valid
395      resp(idx).bits.excp(nDups).af.st    := af && TlbCmd.isWrite(cmd) && fault_valid
396      resp(idx).bits.excp(nDups).af.instr := af && TlbCmd.isExec(cmd) && fault_valid
397
398      resp(idx).bits.excp(nDups).vaNeedExt := true.B
399    }
400
401    resp(idx).bits.excp(nDups).isHyper := isHyperInst(idx)
402  }
403
404  def handle_nonblock(idx: Int): Unit = {
405    io.requestor(idx).resp.valid := req_out_v(idx)
406    io.requestor(idx).req.ready := io.requestor(idx).resp.ready // should always be true
407    XSError(!io.requestor(idx).resp.ready, s"${q.name} port ${idx} is non-block, resp.ready must be true.B")
408
409    val req_need_gpa = hasGpf(idx)
410    val req_s2xlate = Wire(UInt(2.W))
411    req_s2xlate := MuxCase(noS2xlate, Seq(
412      (!(virt_out(idx) || req_out(idx).hyperinst)) -> noS2xlate,
413      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
414      (csr.vsatp.mode === 0.U) -> onlyStage2,
415      (csr.hgatp.mode === 0.U || req_need_gpa) -> onlyStage1
416    ))
417
418    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.vmid, true, false)
419    // TODO: RegNext enable: ptw.resp.valid ? req.valid
420    val ptw_resp_bits_reg = RegEnable(ptw.resp.bits, ptw.resp.valid)
421    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.vmid, allType = true)
422    val ptw_getGpa = req_need_gpa && hitVec(idx)
423    val need_gpa_vpn_hit = need_gpa_vpn === get_pn(req_out(idx).vaddr)
424    io.ptw.req(idx).valid := req_out_v(idx) && missVec(idx) && !(ptw_just_back || ptw_already_back || (!need_gpa_vpn_hit && req_out_v(idx) && need_gpa && !resp_gpa_refill && ptw_getGpa)) // TODO: remove the regnext, timing
425    io.tlbreplay(idx) := req_out_v(idx) && missVec(idx) && (ptw_just_back || ptw_already_back || (!need_gpa_vpn_hit && req_out_v(idx) && need_gpa && !resp_gpa_refill && ptw_getGpa))
426    when (io.requestor(idx).req_kill && GatedValidRegNext(io.requestor(idx).req.fire)) {
427      io.ptw.req(idx).valid := false.B
428      io.tlbreplay(idx) := true.B
429    }
430    io.ptw.req(idx).bits.vpn := get_pn(req_out(idx).vaddr)
431    io.ptw.req(idx).bits.s2xlate := req_s2xlate
432    io.ptw.req(idx).bits.getGpa := ptw_getGpa
433    io.ptw.req(idx).bits.memidx := req_out(idx).memidx
434  }
435
436  def handle_block(idx: Int): Unit = {
437    // three valid: 1.if exist a entry; 2.if sent to ptw; 3.unset resp.valid
438    io.requestor(idx).req.ready := !req_out_v(idx) || io.requestor(idx).resp.fire
439    // req_out_v for if there is a request, may long latency, fixme
440
441    // miss request entries
442    val req_need_gpa = hasGpf(idx)
443    val miss_req_vpn = get_pn(req_out(idx).vaddr)
444    val miss_req_memidx = req_out(idx).memidx
445    val miss_req_s2xlate = Wire(UInt(2.W))
446    miss_req_s2xlate := MuxCase(noS2xlate, Seq(
447      (!(virt_out(idx) || req_out(idx).hyperinst)) -> noS2xlate,
448      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
449      (csr.vsatp.mode === 0.U) -> onlyStage2,
450      (csr.hgatp.mode === 0.U || req_need_gpa) -> onlyStage1
451    ))
452    val miss_req_s2xlate_reg = RegEnable(miss_req_s2xlate, io.ptw.req(idx).fire)
453    val hasS2xlate = miss_req_s2xlate_reg =/= noS2xlate
454    val onlyS2 = miss_req_s2xlate_reg === onlyStage2
455    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.vmid, allType = true, false, hasS2xlate)
456    val hit_s2 = io.ptw.resp.bits.s2.hit(miss_req_vpn, io.csr.hgatp.vmid)
457    val hit = Mux(onlyS2, hit_s2, hit_s1) && io.ptw.resp.valid && miss_req_s2xlate_reg === io.ptw.resp.bits.s2xlate
458
459    val new_coming_valid = WireInit(false.B)
460    new_coming_valid := req_in(idx).fire && !req_in(idx).bits.kill && !flush_pipe(idx)
461    val new_coming = GatedValidRegNext(new_coming_valid)
462    val miss_wire = new_coming && missVec(idx)
463    val miss_v = ValidHoldBypass(miss_wire, resp(idx).fire, flush_pipe(idx))
464    val miss_req_v = ValidHoldBypass(miss_wire || (miss_v && flush_mmu && !mmu_flush_pipe),
465      io.ptw.req(idx).fire || resp(idx).fire, flush_pipe(idx))
466
467    // when ptw resp, check if hit, reset miss_v, resp to lsu/ifu
468    resp(idx).valid := req_out_v(idx) && !(miss_v && portTranslateEnable(idx))
469    when (io.ptw.resp.fire && hit && req_out_v(idx) && portTranslateEnable(idx)) {
470      val stage1 = io.ptw.resp.bits.s1
471      val stage2 = io.ptw.resp.bits.s2
472      val s2xlate = io.ptw.resp.bits.s2xlate
473      resp(idx).valid := true.B
474      resp(idx).bits.miss := false.B
475      val s1_paddr = Cat(stage1.genPPN(get_pn(req_out(idx).vaddr)), get_off(req_out(idx).vaddr))
476      val s2_paddr = Cat(stage2.genPPNS2(get_pn(req_out(idx).vaddr)), get_off(req_out(idx).vaddr))
477      for (d <- 0 until nRespDups) {
478        resp(idx).bits.paddr(d) := Mux(s2xlate =/= noS2xlate, s2_paddr, s1_paddr)
479        resp(idx).bits.gpaddr(d) := s1_paddr
480        pbmt_check(idx, d, io.ptw.resp.bits.s1.entry.pbmt, io.ptw.resp.bits.s2.entry.pbmt, s2xlate)
481        perm_check(stage1, req_out(idx).cmd, idx, d, stage2, req_out(idx).hlvx, s2xlate)
482      }
483      pmp_check(resp(idx).bits.paddr(0), req_out(idx).size, req_out(idx).cmd, false.B, idx)
484
485      // NOTE: the unfiltered req would be handled by Repeater
486    }
487    assert(RegNext(!resp(idx).valid || resp(idx).ready, true.B), "when tlb resp valid, ready should be true, must")
488    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")
489
490    val ptw_req = io.ptw.req(idx)
491    ptw_req.valid := miss_req_v
492    ptw_req.bits.vpn := miss_req_vpn
493    ptw_req.bits.s2xlate := miss_req_s2xlate
494    ptw_req.bits.getGpa := req_need_gpa && hitVec(idx)
495    ptw_req.bits.memidx := miss_req_memidx
496
497    io.tlbreplay(idx) := false.B
498
499    // NOTE: when flush pipe, tlb should abandon last req
500    // however, some outside modules like icache, dont care flushPipe, and still waiting for tlb resp
501    // just resp valid and raise page fault to go through. The pipe(ifu) will abandon it.
502    if (!q.outsideRecvFlush) {
503      when (req_out_v(idx) && flush_pipe(idx) && portTranslateEnable(idx)) {
504        resp(idx).valid := true.B
505        for (d <- 0 until nRespDups) {
506          resp(idx).bits.pbmt(d) := 0.U
507          resp(idx).bits.excp(d).pf.ld := true.B // sfence happened, pf for not to use this addr
508          resp(idx).bits.excp(d).pf.st := true.B
509          resp(idx).bits.excp(d).pf.instr := true.B
510        }
511      }
512    }
513  }
514
515  // when ptw resp, tlb at refill_idx maybe set to miss by force.
516  // Bypass ptw resp to check.
517  def ptw_resp_bypass(vpn: UInt, s2xlate: UInt) = {
518    // TODO: RegNext enable: ptw.resp.valid
519    val hasS2xlate = s2xlate =/= noS2xlate
520    val onlyS2 = s2xlate === onlyStage2
521    val onlyS1 = s2xlate === onlyStage1
522    val s2xlate_hit = s2xlate === ptw.resp.bits.s2xlate
523    val resp_hit = ptw.resp.bits.hit(vpn, io.csr.satp.asid, io.csr.vsatp.asid, io.csr.hgatp.vmid, true, false)
524    val p_hit = GatedValidRegNext(resp_hit && io.ptw.resp.fire && s2xlate_hit)
525    val ppn_s1 = ptw.resp.bits.s1.genPPN(vpn)
526    val gvpn = Mux(onlyS2, vpn, ppn_s1)
527    val ppn_s2 = ptw.resp.bits.s2.genPPNS2(gvpn)
528    val p_ppn = RegEnable(Mux(s2xlate === onlyStage2 || s2xlate === allStage, ppn_s2, ppn_s1), io.ptw.resp.fire)
529    val p_pbmt = RegEnable(ptw.resp.bits.s1.entry.pbmt,io.ptw.resp.fire)
530    val p_perm = RegEnable(ptwresp_to_tlbperm(ptw.resp.bits.s1), io.ptw.resp.fire)
531    val p_gvpn = RegEnable(Mux(onlyS2, ptw.resp.bits.s2.entry.tag, ptw.resp.bits.s1.genGVPN(vpn)), io.ptw.resp.fire)
532    val p_g_pbmt = RegEnable(ptw.resp.bits.s2.entry.pbmt,io.ptw.resp.fire)
533    val p_g_perm = RegEnable(hptwresp_to_tlbperm(ptw.resp.bits.s2), io.ptw.resp.fire)
534    val p_s2xlate = RegEnable(ptw.resp.bits.s2xlate, io.ptw.resp.fire)
535    val p_s1_level = RegEnable(ptw.resp.bits.s1.entry.level.get, io.ptw.resp.fire)
536    val p_s1_isLeaf = RegEnable(ptw.resp.bits.s1.isLeaf(), io.ptw.resp.fire)
537    val p_s1_isFakePte = RegEnable(ptw.resp.bits.s1.isFakePte(), io.ptw.resp.fire)
538    (p_hit, p_ppn, p_pbmt, p_perm, p_gvpn, p_g_pbmt, p_g_perm, p_s2xlate, p_s1_level, p_s1_isLeaf, p_s1_isFakePte)
539  }
540
541  // perf event
542  val result_ok = req_in.map(a => GatedValidRegNext(a.fire))
543  val perfEvents =
544    Seq(
545      ("access", PopCount((0 until Width).map{i => if (Block(i)) io.requestor(i).req.fire else portTranslateEnable(i) && result_ok(i) })),
546      ("miss  ", PopCount((0 until Width).map{i => if (Block(i)) portTranslateEnable(i) && result_ok(i) && missVec(i) else ptw.req(i).fire })),
547    )
548  generatePerfEvent()
549
550  // perf log
551  for (i <- 0 until Width) {
552    if (Block(i)) {
553      XSPerfAccumulate(s"access${i}",result_ok(i) && portTranslateEnable(i))
554      XSPerfAccumulate(s"miss${i}", result_ok(i) && missVec(i))
555    } else {
556      XSPerfAccumulate("first_access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid))
557      XSPerfAccumulate("access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i))
558      XSPerfAccumulate("first_miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i) && RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid))
559      XSPerfAccumulate("miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i))
560    }
561  }
562  XSPerfAccumulate("ptw_resp_count", ptw.resp.fire)
563  XSPerfAccumulate("ptw_resp_pf_count", ptw.resp.fire && ptw.resp.bits.s1.pf)
564
565  // Log
566  for(i <- 0 until Width) {
567    XSDebug(req(i).valid, p"req(${i.U}): (${req(i).valid} ${req(i).ready}) ${req(i).bits}\n")
568    XSDebug(resp(i).valid, p"resp(${i.U}): (${resp(i).valid} ${resp(i).ready}) ${resp(i).bits}\n")
569  }
570
571  XSDebug(io.sfence.valid, p"Sfence: ${io.sfence}\n")
572  XSDebug(ParallelOR(req_out_v) || ptw.resp.valid, p"vmEnable:${vmEnable} hit:${Binary(VecInit(hitVec).asUInt)} miss:${Binary(VecInit(missVec).asUInt)}\n")
573  for (i <- ptw.req.indices) {
574    XSDebug(ptw.req(i).fire, p"L2TLB req:${ptw.req(i).bits}\n")
575  }
576  XSDebug(ptw.resp.valid, p"L2TLB resp:${ptw.resp.bits} (v:${ptw.resp.valid}r:${ptw.resp.ready}) \n")
577
578  println(s"${q.name}: page: ${q.NWays} ${q.Associative} ${q.Replacer.get}")
579
580  if (env.EnableDifftest) {
581    for (i <- 0 until Width) {
582      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
583      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
584      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
585      val difftest = DifftestModule(new DiffL1TLBEvent)
586      difftest.coreid := io.hartId
587      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)
588      if (!Seq("itlb", "ldtlb", "sttlb").contains(q.name)) {
589        difftest.valid := false.B
590      }
591      difftest.index := TLBDiffId(p(XSCoreParamsKey).HartId).U
592      difftest.vpn := RegEnable(get_pn(req_in(i).bits.vaddr), req_in(i).valid)
593      difftest.ppn := get_pn(io.requestor(i).resp.bits.paddr(0))
594      difftest.satp := Cat(io.csr.satp.mode, io.csr.satp.asid, io.csr.satp.ppn)
595      difftest.vsatp := Cat(io.csr.vsatp.mode, io.csr.vsatp.asid, io.csr.vsatp.ppn)
596      difftest.hgatp := Cat(io.csr.hgatp.mode, io.csr.hgatp.vmid, io.csr.hgatp.ppn)
597      val req_need_gpa = gpf
598      val req_s2xlate = Wire(UInt(2.W))
599      req_s2xlate := MuxCase(noS2xlate, Seq(
600        (!RegNext(virt_in || req_in(i).bits.hyperinst)) -> noS2xlate,
601        (vsatp.mode =/= 0.U && hgatp.mode =/= 0.U) -> allStage,
602        (vsatp.mode === 0.U) -> onlyStage2,
603        (hgatp.mode === 0.U || req_need_gpa) -> onlyStage1
604      ))
605      difftest.s2xlate := req_s2xlate
606    }
607  }
608}
609
610object TLBDiffId {
611  var i: Int = 0
612  var lastHartId: Int = -1
613  def apply(hartId: Int): Int = {
614    if (lastHartId != hartId) {
615      i = 0
616      lastHartId = hartId
617    }
618    i += 1
619    i - 1
620  }
621}
622
623class TLBNonBlock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(false), q)
624class TLBBLock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(true), q)
625
626class TlbReplace(Width: Int, q: TLBParameters)(implicit p: Parameters) extends TlbModule {
627  val io = IO(new TlbReplaceIO(Width, q))
628
629  if (q.Associative == "fa") {
630    val re = ReplacementPolicy.fromString(q.Replacer, q.NWays)
631    re.access(io.page.access.map(_.touch_ways))
632    io.page.refillIdx := re.way
633  } else { // set-acco && plru
634    val re = ReplacementPolicy.fromString(q.Replacer, q.NSets, q.NWays)
635    re.access(io.page.access.map(_.sets), io.page.access.map(_.touch_ways))
636    io.page.refillIdx := { if (q.NWays == 1) 0.U else re.way(io.page.chosen_set) }
637  }
638}
639