xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/TLB.scala (revision 4fc3a30c9a0fc8037a144fb6b0a1f80effc7b4ef)
16d5ddbceSLemover/***************************************************************************************
26d5ddbceSLemover* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3f320e0f0SYinan Xu* Copyright (c) 2020-2021 Peng Cheng Laboratory
46d5ddbceSLemover*
56d5ddbceSLemover* XiangShan is licensed under Mulan PSL v2.
66d5ddbceSLemover* You can use this software according to the terms and conditions of the Mulan PSL v2.
76d5ddbceSLemover* You may obtain a copy of Mulan PSL v2 at:
86d5ddbceSLemover*          http://license.coscl.org.cn/MulanPSL2
9f1fe8698SLemover
106d5ddbceSLemover* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
116d5ddbceSLemover* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
126d5ddbceSLemover* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
136d5ddbceSLemover*
146d5ddbceSLemover* See the Mulan PSL v2 for more details.
15c49ebec8SHaoyuan Feng*
16c49ebec8SHaoyuan Feng*
17c49ebec8SHaoyuan Feng* Acknowledgement
18c49ebec8SHaoyuan Feng*
19c49ebec8SHaoyuan Feng* This implementation is inspired by several key papers:
20c49ebec8SHaoyuan Feng* [1] Binh Pham, Viswanathan Vaidyanathan, Aamer Jaleel, and Abhishek Bhattacharjee. "[Colt: Coalesced large-reach
21c49ebec8SHaoyuan Feng* tlbs.](https://doi.org/10.1109/MICRO.2012.32)" 45th Annual IEEE/ACM International Symposium on Microarchitecture
22c49ebec8SHaoyuan Feng* (MICRO). 2012.
236d5ddbceSLemover***************************************************************************************/
246d5ddbceSLemover
256d5ddbceSLemoverpackage xiangshan.cache.mmu
266d5ddbceSLemover
278891a219SYinan Xuimport org.chipsalliance.cde.config.Parameters
286d5ddbceSLemoverimport chisel3._
296d5ddbceSLemoverimport chisel3.util._
305ab1b84dSHaoyuan Fengimport difftest._
31a0301c0dSLemoverimport freechips.rocketchip.util.SRAMAnnotation
326d5ddbceSLemoverimport xiangshan._
336d5ddbceSLemoverimport utils._
343c02ee8fSwakafaimport utility._
35f1fe8698SLemoverimport xiangshan.backend.fu.{PMPChecker, PMPReqBundle, PMPConfig => XSPMPConfig}
369aca92b9SYinan Xuimport xiangshan.backend.rob.RobPtr
376d5ddbceSLemoverimport xiangshan.backend.fu.util.HasCSRConst
38f1fe8698SLemoverimport freechips.rocketchip.rocket.PMPConfig
396d5ddbceSLemover
40f1fe8698SLemover/** TLB module
41f1fe8698SLemover  * support block request and non-block request io at the same time
42f1fe8698SLemover  * return paddr at next cycle, then go for pmp/pma check
43f1fe8698SLemover  * @param Width: The number of requestors
44f1fe8698SLemover  * @param Block: Blocked or not for each requestor ports
45f1fe8698SLemover  * @param q: TLB Parameters, like entry number, each TLB has its own parameters
46f1fe8698SLemover  * @param p: XiangShan Paramemters, like XLEN
47f1fe8698SLemover  */
48a0301c0dSLemover
4903efd994Shappy-lxclass TLB(Width: Int, nRespDups: Int = 1, Block: Seq[Boolean], q: TLBParameters)(implicit p: Parameters) extends TlbModule
50f1fe8698SLemover  with HasCSRConst
51f1fe8698SLemover  with HasPerfEvents
52f1fe8698SLemover{
5303efd994Shappy-lx  val io = IO(new TlbIO(Width, nRespDups, q))
54a0301c0dSLemover
556d5ddbceSLemover  val req = io.requestor.map(_.req)
566d5ddbceSLemover  val resp = io.requestor.map(_.resp)
576d5ddbceSLemover  val ptw = io.ptw
58b6982e83SLemover  val pmp = io.pmp
598744445eSMaxpicca-Li  val refill_to_mem = io.refill_to_mem
606d5ddbceSLemover
61f1fe8698SLemover  /** Sfence.vma & Svinval
62f1fe8698SLemover    * Sfence.vma will 1. flush old entries 2. flush inflight 3. flush pipe
63f1fe8698SLemover    * Svinval will 1. flush old entries 2. flush inflight
64f1fe8698SLemover    * So, Svinval will not flush pipe, which means
65f1fe8698SLemover    * it should not drop reqs from pipe and should return right resp
66f1fe8698SLemover    */
67f1fe8698SLemover  val sfence = DelayN(io.sfence, q.fenceDelay)
686d5ddbceSLemover  val csr = io.csr
69f1fe8698SLemover  val satp = DelayN(io.csr.satp, q.fenceDelay)
70d0de7e4aSpeixiaokun  val vsatp = DelayN(io.csr.vsatp, q.fenceDelay)
71d0de7e4aSpeixiaokun  val hgatp = DelayN(io.csr.hgatp, q.fenceDelay)
72dd286b6aSYanqin Li  val mPBMTE = DelayN(io.csr.mPBMTE, q.fenceDelay)
73dd286b6aSYanqin Li  val hPBMTE = DelayN(io.csr.hPBMTE, q.fenceDelay)
74d0de7e4aSpeixiaokun
75d0de7e4aSpeixiaokun  val flush_mmu = DelayN(sfence.valid || csr.satp.changed || csr.vsatp.changed || csr.hgatp.changed, q.fenceDelay)
76f1fe8698SLemover  val mmu_flush_pipe = DelayN(sfence.valid && sfence.bits.flushPipe, q.fenceDelay) // for svinval, won't flush pipe
77f1fe8698SLemover  val flush_pipe = io.flushPipe
78a4f9c77fSpeixiaokun  val redirect = io.redirect
79ffa711ffSpeixiaokun  val req_in = req
803222d00fSpeixiaokun  val req_out = req.map(a => RegEnable(a.bits, a.fire))
81ffa711ffSpeixiaokun  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)))
82ffa711ffSpeixiaokun
83ffa711ffSpeixiaokun  val isHyperInst = (0 until Width).map(i => req_out_v(i) && req_out(i).hyperinst)
8450c7aa78Speixiaokun
85f1fe8698SLemover  // ATTENTION: csr and flush from backend are delayed. csr should not be later than flush.
86f1fe8698SLemover  // because, csr will influence tlb behavior.
87a0301c0dSLemover  val ifecth = if (q.fetchi) true.B else false.B
88d0de7e4aSpeixiaokun  val mode_tmp = if (q.useDmode) csr.priv.dmode else csr.priv.imode
89d0de7e4aSpeixiaokun  val mode = (0 until Width).map(i => Mux(isHyperInst(i), csr.priv.spvp, mode_tmp))
9082e4705bSpeixiaokun  val virt_in = csr.priv.virt
9182e4705bSpeixiaokun  val virt_out = req.map(a => RegEnable(csr.priv.virt, a.fire))
9282e4705bSpeixiaokun  val sum = (0 until Width).map(i => Mux(virt_out(i) || isHyperInst(i), io.csr.priv.vsum, io.csr.priv.sum))
9382e4705bSpeixiaokun  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))
94ffa711ffSpeixiaokun  val req_in_s2xlate = (0 until Width).map(i => MuxCase(noS2xlate, Seq(
9582e4705bSpeixiaokun      (!(virt_in || req_in(i).bits.hyperinst)) -> noS2xlate,
96251a1ca9Speixiaokun      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
97251a1ca9Speixiaokun      (csr.vsatp.mode === 0.U) -> onlyStage2,
98251a1ca9Speixiaokun      (csr.hgatp.mode === 0.U) -> onlyStage1
99ffa711ffSpeixiaokun    )))
100ffa711ffSpeixiaokun  val req_out_s2xlate = (0 until Width).map(i => MuxCase(noS2xlate, Seq(
10182e4705bSpeixiaokun    (!(virt_out(i) || isHyperInst(i))) -> noS2xlate,
102251a1ca9Speixiaokun    (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
103251a1ca9Speixiaokun    (csr.vsatp.mode === 0.U) -> onlyStage2,
104251a1ca9Speixiaokun    (csr.hgatp.mode === 0.U) -> onlyStage1
1053106de0aSpeixiaokun  )))
106e9027bcdSpeixiaokun  val need_gpa = RegInit(false.B)
107a4f9c77fSpeixiaokun  val need_gpa_robidx = Reg(new RobPtr)
108e9027bcdSpeixiaokun  val need_gpa_vpn = Reg(UInt(vpnLen.W))
109ad8d4021SXiaokun-Pei  val resp_gpa_gvpn = Reg(UInt(ptePPNLen.W))
110e9566d21Speixiaokun  val resp_gpa_refill = RegInit(false.B)
111ad8d4021SXiaokun-Pei  val resp_s1_level = RegInit(0.U(log2Up(Level + 1).W))
112ad8d4021SXiaokun-Pei  val resp_s1_isLeaf = RegInit(false.B)
113ad8d4021SXiaokun-Pei  val resp_s1_isFakePte = RegInit(false.B)
114e9027bcdSpeixiaokun  val hasGpf = Wire(Vec(Width, Bool()))
115d0de7e4aSpeixiaokun
1163ea4388cSHaoyuan Feng  val Sv39Enable = satp.mode === 8.U
1173ea4388cSHaoyuan Feng  val Sv48Enable = satp.mode === 9.U
1183ea4388cSHaoyuan Feng  val Sv39x4Enable = vsatp.mode === 8.U || hgatp.mode === 8.U
1193ea4388cSHaoyuan Feng  val Sv48x4Enable = vsatp.mode === 9.U || hgatp.mode === 9.U
1200841a83fSXuan Hu  val vmEnable = (0 until Width).map(i => !(isHyperInst(i) || virt_out(i)) && (
1213ea4388cSHaoyuan Feng    if (EnbaleTlbDebug) (Sv39Enable || Sv48Enable)
1223ea4388cSHaoyuan Feng    else (Sv39Enable || Sv48Enable) && (mode(i) < ModeM))
1230841a83fSXuan Hu  )
1243ea4388cSHaoyuan Feng  val s2xlateEnable = (0 until Width).map(i => (isHyperInst(i) || virt_out(i)) && (Sv39x4Enable || Sv48x4Enable) && (mode(i) < ModeM))
1255adc4829SYanqin Li  val portTranslateEnable = (0 until Width).map(i => (vmEnable(i) || s2xlateEnable(i)) && RegEnable(!req(i).bits.no_translate, req(i).valid))
1266d5ddbceSLemover
127db6cfb5aSHaoyuan Feng  // pre fault: check fault before real do translate
128db6cfb5aSHaoyuan Feng  val prepf = WireInit(VecInit(Seq.fill(Width)(false.B)))
129db6cfb5aSHaoyuan Feng  val pregpf = WireInit(VecInit(Seq.fill(Width)(false.B)))
130db6cfb5aSHaoyuan Feng  val preaf = WireInit(VecInit(Seq.fill(Width)(false.B)))
13109223e00SHaoyuan Feng  val prevmEnable = (0 until Width).map(i => !(virt_in || req_in(i).bits.hyperinst) && (
13209223e00SHaoyuan Feng    if (EnbaleTlbDebug) (Sv39Enable || Sv48Enable)
13309223e00SHaoyuan Feng    else (Sv39Enable || Sv48Enable) && (mode(i) < ModeM))
13409223e00SHaoyuan Feng  )
13509223e00SHaoyuan Feng  val pres2xlateEnable = (0 until Width).map(i => (virt_in || req_in(i).bits.hyperinst) && (Sv39x4Enable || Sv48x4Enable) && (mode(i) < ModeM))
136db6cfb5aSHaoyuan Feng  (0 until Width).foreach{i =>
137db6cfb5aSHaoyuan Feng    val pf48 = SignExt(req(i).bits.fullva(47, 0), XLEN) =/= req(i).bits.fullva
138db6cfb5aSHaoyuan Feng    val pf39 = SignExt(req(i).bits.fullva(38, 0), XLEN) =/= req(i).bits.fullva
139db6cfb5aSHaoyuan Feng    val gpf48 = req(i).bits.fullva(XLEN - 1, 48 + 2) =/= 0.U
140db6cfb5aSHaoyuan Feng    val gpf39 = req(i).bits.fullva(XLEN - 1, 39 + 2) =/= 0.U
141db6cfb5aSHaoyuan Feng    val af = req(i).bits.fullva(XLEN - 1, PAddrBits) =/= 0.U
142db6cfb5aSHaoyuan Feng    when (req(i).valid && req(i).bits.checkfullva) {
14309223e00SHaoyuan Feng      when (prevmEnable(i) || pres2xlateEnable(i)) {
144db6cfb5aSHaoyuan Feng        when (req_in_s2xlate(i) === onlyStage2) {
145db6cfb5aSHaoyuan Feng          when (Sv48x4Enable) {
146db6cfb5aSHaoyuan Feng            pregpf(i) := gpf48
147db6cfb5aSHaoyuan Feng          } .elsewhen (Sv39x4Enable) {
148db6cfb5aSHaoyuan Feng            pregpf(i) := gpf39
149db6cfb5aSHaoyuan Feng          }
150db6cfb5aSHaoyuan Feng        } .otherwise {
151db6cfb5aSHaoyuan Feng          when (Sv48Enable) {
152db6cfb5aSHaoyuan Feng            prepf(i) := pf48
153db6cfb5aSHaoyuan Feng          } .elsewhen (Sv39Enable) {
154db6cfb5aSHaoyuan Feng            prepf(i) := pf39
155db6cfb5aSHaoyuan Feng          }
156db6cfb5aSHaoyuan Feng        }
157db6cfb5aSHaoyuan Feng      } .otherwise {
158db6cfb5aSHaoyuan Feng        preaf(i) := af
159db6cfb5aSHaoyuan Feng      }
160db6cfb5aSHaoyuan Feng    }
161db6cfb5aSHaoyuan Feng  }
1626d5ddbceSLemover
163*4fc3a30cSXu, Zefan  val refill = ptw.resp.fire && !(ptw.resp.bits.getGpa) && !need_gpa && !flush_mmu
164*4fc3a30cSXu, Zefan  // prevent ptw refill when: 1) it's a getGpa request; 2) l1tlb is in need_gpa state; 3) mmu is being flushed.
165*4fc3a30cSXu, Zefan
166eb4bf3f2Speixiaokun  refill_to_mem := DontCare
16703efd994Shappy-lx  val entries = Module(new TlbStorageWrapper(Width, q, nRespDups))
168f1fe8698SLemover  entries.io.base_connect(sfence, csr, satp)
169f1fe8698SLemover  if (q.outReplace) { io.replace <> entries.io.replace }
1706d5ddbceSLemover  for (i <- 0 until Width) {
171ffa711ffSpeixiaokun    entries.io.r_req_apply(io.requestor(i).req.valid, get_pn(req_in(i).bits.vaddr), i, req_in_s2xlate(i))
172ec159517SXiaokun-Pei    entries.io.w_apply(refill, ptw.resp.bits)
1735adc4829SYanqin Li    // TODO: RegNext enable:req.valid
1745adc4829SYanqin Li    resp(i).bits.debug.isFirstIssue := RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid)
1755adc4829SYanqin Li    resp(i).bits.debug.robIdx := RegEnable(req(i).bits.debug.robIdx, req(i).valid)
176a0301c0dSLemover  }
177e9027bcdSpeixiaokun
178f1fe8698SLemover  // read TLB, get hit/miss, paddr, perm bits
179f1fe8698SLemover  val readResult = (0 until Width).map(TLBRead(_))
180f1fe8698SLemover  val hitVec = readResult.map(_._1)
181f1fe8698SLemover  val missVec = readResult.map(_._2)
182f1fe8698SLemover  val pmp_addr = readResult.map(_._3)
183f9ac118cSHaoyuan Feng  val perm = readResult.map(_._4)
1843106de0aSpeixiaokun  val g_perm = readResult.map(_._5)
185002c10a4SYanqin Li  val pbmt = readResult.map(_._6)
186002c10a4SYanqin Li  val g_pbmt = readResult.map(_._7)
187f1fe8698SLemover  // check pmp use paddr (for timing optization, use pmp_addr here)
188f1fe8698SLemover  // check permisson
189f1fe8698SLemover  (0 until Width).foreach{i =>
19008b0bc30Shappy-lx    val noTranslateReg = RegNext(req(i).bits.no_translate)
19108b0bc30Shappy-lx    val addr = Mux(noTranslateReg, req(i).bits.pmp_addr, pmp_addr(i))
19208b0bc30Shappy-lx    pmp_check(addr, req_out(i).size, req_out(i).cmd, noTranslateReg, i)
19303efd994Shappy-lx    for (d <- 0 until nRespDups) {
194002c10a4SYanqin Li      pbmt_check(i, d, pbmt(i)(d), g_pbmt(i)(d), req_out_s2xlate(i))
195db6cfb5aSHaoyuan Feng      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))
19603efd994Shappy-lx    }
1977acf8b76SXiaokun-Pei    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)
198f1fe8698SLemover  }
1996d5ddbceSLemover
200f1fe8698SLemover  // handle block or non-block io
201f1fe8698SLemover  // for non-block io, just return the above result, send miss to ptw
202f1fe8698SLemover  // for block io, hold the request, send miss to ptw,
203f1fe8698SLemover  //   when ptw back, return the result
204f1fe8698SLemover  (0 until Width) foreach {i =>
205f1fe8698SLemover    if (Block(i)) handle_block(i)
206f1fe8698SLemover    else handle_nonblock(i)
207f1fe8698SLemover  }
208f1fe8698SLemover  io.ptw.resp.ready := true.B
209a0301c0dSLemover
210f1fe8698SLemover  /************************  main body above | method/log/perf below ****************************/
211f1fe8698SLemover  def TLBRead(i: Int) = {
212002c10a4SYanqin Li    val (e_hit, e_ppn, e_perm, e_g_perm, e_s2xlate, e_pbmt, e_g_pbmt) = entries.io.r_resp_apply(i)
213ad8d4021SXiaokun-Pei    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))
214292bea3fSWilliam Wang    val enable = portTranslateEnable(i)
215f86480a7Speixiaokun    val isOnlys2xlate = req_out_s2xlate(i) === onlyStage2
2169cb05b4dSXiaokun-Pei    val need_gpa_vpn_hit = need_gpa_vpn === get_pn(req_out(i).vaddr)
217a4f9c77fSpeixiaokun    val isitlb = TlbCmd.isExec(req_out(i).cmd)
2188a4dab4dSHaoyuan Feng    val isPrefetch = req_out(i).isPrefetch
2198a4dab4dSHaoyuan Feng    val currentRedirect = req_out(i).debug.robIdx.needFlush(redirect)
2208a4dab4dSHaoyuan Feng    val lastCycleRedirect = req_out(i).debug.robIdx.needFlush(RegNext(redirect))
221a4f9c77fSpeixiaokun
222a4f9c77fSpeixiaokun    when (!isitlb && need_gpa_robidx.needFlush(redirect) || isitlb && flush_pipe(i)){
223a4f9c77fSpeixiaokun      need_gpa := false.B
224a4f9c77fSpeixiaokun      resp_gpa_refill := false.B
225a4f9c77fSpeixiaokun      need_gpa_vpn := 0.U
2268a4dab4dSHaoyuan Feng    }.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) {
227c3d5cfb3Speixiaokun      need_gpa := true.B
2283106de0aSpeixiaokun      need_gpa_vpn := get_pn(req_out(i).vaddr)
2293106de0aSpeixiaokun      resp_gpa_refill := false.B
230a4f9c77fSpeixiaokun      need_gpa_robidx := req_out(i).debug.robIdx
2319cb05b4dSXiaokun-Pei    }.elsewhen (ptw.resp.fire && need_gpa && need_gpa_vpn === ptw.resp.bits.getVpn(need_gpa_vpn)) {
2322ea10b44SXiaokun-Pei      resp_gpa_gvpn := Mux(ptw.resp.bits.s2xlate === onlyStage2, ptw.resp.bits.s2.entry.tag, ptw.resp.bits.s1.genGVPN(need_gpa_vpn))
233ad8d4021SXiaokun-Pei      resp_s1_level := ptw.resp.bits.s1.entry.level.get
234ad8d4021SXiaokun-Pei      resp_s1_isLeaf := ptw.resp.bits.s1.isLeaf()
235ad8d4021SXiaokun-Pei      resp_s1_isFakePte := ptw.resp.bits.s1.isFakePte()
2363106de0aSpeixiaokun      resp_gpa_refill := true.B
2373106de0aSpeixiaokun    }
2383106de0aSpeixiaokun
2399cb05b4dSXiaokun-Pei    when (req_out_v(i) && hasGpf(i) && resp_gpa_refill && need_gpa_vpn_hit){
240c3d5cfb3Speixiaokun      need_gpa := false.B
241c3d5cfb3Speixiaokun    }
242c3d5cfb3Speixiaokun
243cb8f2f2aSLemover    val hit = e_hit || p_hit
2448a4dab4dSHaoyuan Feng    val miss = (!hit && enable) || hasGpf(i) && !p_hit && !(resp_gpa_refill && need_gpa_vpn_hit) && !isOnlys2xlate && !isPrefetch && !lastCycleRedirect
245f1fe8698SLemover    hit.suggestName(s"hit_read_${i}")
246f1fe8698SLemover    miss.suggestName(s"miss_read_${i}")
2476d5ddbceSLemover
248f1fe8698SLemover    val vaddr = SignExt(req_out(i).vaddr, PAddrBits)
249f1fe8698SLemover    resp(i).bits.miss := miss
250935edac4STang Haojin    resp(i).bits.ptwBack := ptw.resp.fire
2515adc4829SYanqin Li    resp(i).bits.memidx := RegEnable(req_in(i).bits.memidx, req_in(i).valid)
25208b0bc30Shappy-lx    resp(i).bits.fastMiss := !hit && enable
2536d5ddbceSLemover
25403efd994Shappy-lx    val ppn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ppnLen.W))))
255002c10a4SYanqin Li    val pbmt = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePbmtLen.W))))
25603efd994Shappy-lx    val perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle))))
257faf7d50bSXiaokun-Pei    val gvpn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePPNLen.W))))
258ad8d4021SXiaokun-Pei    val level = WireInit(VecInit(Seq.fill(nRespDups)(0.U(log2Up(Level + 1).W))))
259ad8d4021SXiaokun-Pei    val isLeaf = WireInit(VecInit(Seq.fill(nRespDups)(false.B)))
260ad8d4021SXiaokun-Pei    val isFakePte = WireInit(VecInit(Seq.fill(nRespDups)(false.B)))
261002c10a4SYanqin Li    val g_pbmt = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePbmtLen.W))))
262d0de7e4aSpeixiaokun    val g_perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle))))
26350c7aa78Speixiaokun    val r_s2xlate = WireInit(VecInit(Seq.fill(nRespDups)(0.U(2.W))))
26403efd994Shappy-lx    for (d <- 0 until nRespDups) {
26503efd994Shappy-lx      ppn(d) := Mux(p_hit, p_ppn, e_ppn(d))
266002c10a4SYanqin Li      pbmt(d) := Mux(p_hit, p_pbmt, e_pbmt(d))
26703efd994Shappy-lx      perm(d) := Mux(p_hit, p_perm, e_perm(d))
268ad8d4021SXiaokun-Pei      gvpn(d) :=  Mux(p_hit, p_gvpn, resp_gpa_gvpn)
269ad8d4021SXiaokun-Pei      level(d) := Mux(p_hit, p_s1_level, resp_s1_level)
270ad8d4021SXiaokun-Pei      isLeaf(d) := Mux(p_hit, p_s1_isLeaf, resp_s1_isLeaf)
271ad8d4021SXiaokun-Pei      isFakePte(d) := Mux(p_hit, p_s1_isFakePte, resp_s1_isFakePte)
272002c10a4SYanqin Li      g_pbmt(d) := Mux(p_hit, p_g_pbmt, e_g_pbmt(d))
273d0de7e4aSpeixiaokun      g_perm(d) := Mux(p_hit, p_g_perm, e_g_perm(d))
27450c7aa78Speixiaokun      r_s2xlate(d) := Mux(p_hit, p_s2xlate, e_s2xlate(d))
27503efd994Shappy-lx      val paddr = Cat(ppn(d), get_off(req_out(i).vaddr))
276ad8d4021SXiaokun-Pei      val vpn_idx = Mux1H(Seq(
277ad8d4021SXiaokun-Pei        (isFakePte(d) && vsatp.mode === Sv39) -> 2.U,
278ad8d4021SXiaokun-Pei        (isFakePte(d) && vsatp.mode === Sv48) -> 3.U,
279ad8d4021SXiaokun-Pei        (!isFakePte(d)) -> (level(d) - 1.U),
280ad8d4021SXiaokun-Pei      ))
2817eef70ffSgood-circle      // We use `fullva` here when `isLeaf`, in order to cope with the situation of an unaligned load/store cross page
2827eef70ffSgood-circle      // for example, a `ld` instruction on address 0x81000ffb will be splited into two loads
2837eef70ffSgood-circle      // 1. ld 0x81000ff8. vaddr = 0x81000ff8, fullva = 0x80000ffb
2847eef70ffSgood-circle      // 2. ld 0x81001000. vaddr = 0x81001000, fullva = 0x80000ffb
2857eef70ffSgood-circle      // When load 1 trigger a guest page fault, we should use offset of fullva when generate gpaddr
2867eef70ffSgood-circle      // and when load 2 trigger a guest page fault, we should just use offset of vaddr(all zero).
287e80f666eSHaoyuan Feng      // Also, when onlyS2, if crosspage, gpaddr = vaddr(start address of a new page), else gpaddr = fullva(original vaddr)
288e3e0af7dSXu, Zefan      // By the way, frontend handles the cross page instruction fetch by itself, so TLB doesn't need to do anything extra.
289e3e0af7dSXu, Zefan      // Also, the fullva of iTLB is not used and always zero. crossPageVaddr should never use fullva in iTLB.
290e3e0af7dSXu, Zefan      val crossPageVaddr = Mux(isitlb || req_out(i).fullva(12) =/= vaddr(12), vaddr, req_out(i).fullva)
291e80f666eSHaoyuan Feng      val gpaddr_offset = Mux(isLeaf(d), get_off(crossPageVaddr), Cat(getVpnn(get_pn(crossPageVaddr), vpn_idx), 0.U(log2Up(XLEN/8).W)))
292ad8d4021SXiaokun-Pei      val gpaddr = Cat(gvpn(d), gpaddr_offset)
293292bea3fSWilliam Wang      resp(i).bits.paddr(d) := Mux(enable, paddr, vaddr)
294e80f666eSHaoyuan Feng      resp(i).bits.gpaddr(d) := Mux(r_s2xlate(d) === onlyStage2, crossPageVaddr, gpaddr)
29503efd994Shappy-lx    }
29603efd994Shappy-lx
29703efd994Shappy-lx    XSDebug(req_out_v(i), p"(${i.U}) hit:${hit} miss:${miss} ppn:${Hexadecimal(ppn(0))} perm:${perm(0)}\n")
29803efd994Shappy-lx
299f9ac118cSHaoyuan Feng    val pmp_paddr = resp(i).bits.paddr(0)
300f1fe8698SLemover
301002c10a4SYanqin Li    (hit, miss, pmp_paddr, perm, g_perm, pbmt, g_pbmt)
302f1fe8698SLemover  }
303f1fe8698SLemover
304ad8d4021SXiaokun-Pei  def getVpnn(vpn: UInt, idx: UInt): UInt = {
305ad8d4021SXiaokun-Pei    MuxLookup(idx, 0.U)(Seq(
306ad8d4021SXiaokun-Pei      0.U -> vpn(vpnnLen - 1, 0),
307ad8d4021SXiaokun-Pei      1.U -> vpn(vpnnLen * 2 - 1, vpnnLen),
308ad8d4021SXiaokun-Pei      2.U -> vpn(vpnnLen * 3 - 1, vpnnLen * 2),
309ad8d4021SXiaokun-Pei      3.U -> vpn(vpnnLen * 4 - 1, vpnnLen * 3))
310ad8d4021SXiaokun-Pei    )
311ad8d4021SXiaokun-Pei  }
312ad8d4021SXiaokun-Pei
31308b0bc30Shappy-lx  def pmp_check(addr: UInt, size: UInt, cmd: UInt, noTranslate: Bool, idx: Int): Unit = {
31408b0bc30Shappy-lx    pmp(idx).valid := resp(idx).valid || noTranslate
315f1fe8698SLemover    pmp(idx).bits.addr := addr
316f1fe8698SLemover    pmp(idx).bits.size := size
317f1fe8698SLemover    pmp(idx).bits.cmd := cmd
318f1fe8698SLemover  }
319f1fe8698SLemover
320002c10a4SYanqin Li  def pbmt_check(idx: Int, d: Int, pbmt: UInt, g_pbmt: UInt, s2xlate: UInt):Unit = {
321002c10a4SYanqin Li    val onlyS1 = s2xlate === onlyStage1 || s2xlate === noS2xlate
322e11ec86cSYanqin Li    val pbmtRes = pbmt
323e11ec86cSYanqin Li    val gpbmtRes = g_pbmt
3243adbf906SYanqin Li    val res = MuxLookup(s2xlate, 0.U)(Seq(
325dd286b6aSYanqin Li      onlyStage1 -> pbmtRes,
326dd286b6aSYanqin Li      onlyStage2 -> gpbmtRes,
327dd286b6aSYanqin Li      allStage -> Mux(pbmtRes =/= 0.U, pbmtRes, gpbmtRes),
328dd286b6aSYanqin Li      noS2xlate -> pbmtRes
3293adbf906SYanqin Li    ))
3303adbf906SYanqin Li    resp(idx).bits.pbmt(d) := Mux(portTranslateEnable(idx), res, 0.U)
331002c10a4SYanqin Li  }
332002c10a4SYanqin Li
3335b7ef044SLemover  // for timing optimization, pmp check is divided into dynamic and static
334db6cfb5aSHaoyuan Feng  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) = {
3355b7ef044SLemover    // dynamic: superpage (or full-connected reg entries) -> check pmp when translation done
3365b7ef044SLemover    // static: 4K pages (or sram entries) -> check pmp with pre-checked results
337c3d5cfb3Speixiaokun    val hasS2xlate = s2xlate =/= noS2xlate
338cfa0c506SXiaokun-Pei    val onlyS1 = s2xlate === onlyStage1
33907f77bf0Speixiaokun    val onlyS2 = s2xlate === onlyStage2
340d0de7e4aSpeixiaokun    val af = perm.af || (hasS2xlate && g_perm.af)
341d0de7e4aSpeixiaokun
342d0de7e4aSpeixiaokun    // Stage 1 perm check
343e5831642Speixiaokun    val pf = perm.pf
344db6cfb5aSHaoyuan Feng    val isLd = TlbCmd.isRead(cmd) && !TlbCmd.isAmo(cmd)
345db6cfb5aSHaoyuan Feng    val isSt = TlbCmd.isWrite(cmd) || TlbCmd.isAmo(cmd)
346db6cfb5aSHaoyuan Feng    val isInst = TlbCmd.isExec(cmd)
347db6cfb5aSHaoyuan Feng    val ldUpdate = !perm.a && isLd // update A/D through exception
348db6cfb5aSHaoyuan Feng    val stUpdate = (!perm.a || !perm.d) && isSt // update A/D through exception
349db6cfb5aSHaoyuan Feng    val instrUpdate = !perm.a && isInst // update A/D through exception
350d0de7e4aSpeixiaokun    val modeCheck = !(mode(idx) === ModeU && !perm.u || mode(idx) === ModeS && perm.u && (!sum(idx) || ifecth))
351e5831642Speixiaokun    val ldPermFail = !(modeCheck && Mux(hlvx, perm.x, perm.r || mxr(idx) && perm.x))
352a79fef67Swakafa    val stPermFail = !(modeCheck && perm.w)
353a79fef67Swakafa    val instrPermFail = !(modeCheck && perm.x)
354db6cfb5aSHaoyuan Feng    val ldPf = (ldPermFail || pf) && isLd
355db6cfb5aSHaoyuan Feng    val stPf = (stPermFail || pf) && isSt
356db6cfb5aSHaoyuan Feng    val instrPf = (instrPermFail || pf) && isInst
357ad415ae0SXiaokun-Pei    val isFakePte = !perm.v && !perm.pf && !perm.af && !onlyS2
3582ea10b44SXiaokun-Pei    val isNonLeaf = !(perm.r || perm.w || perm.x) && perm.v && !perm.pf && !perm.af
3592ea10b44SXiaokun-Pei    val s1_valid = portTranslateEnable(idx) && !onlyS2
360d0de7e4aSpeixiaokun
361d0de7e4aSpeixiaokun    // Stage 2 perm check
362e5831642Speixiaokun    val gpf = g_perm.pf
363db6cfb5aSHaoyuan Feng    val g_ldUpdate = !g_perm.a && isLd
364db6cfb5aSHaoyuan Feng    val g_stUpdate = (!g_perm.a || !g_perm.d) && isSt
365db6cfb5aSHaoyuan Feng    val g_instrUpdate = !g_perm.a && isInst
366e5831642Speixiaokun    val g_ldPermFail = !Mux(hlvx, g_perm.x, (g_perm.r || io.csr.priv.mxr && g_perm.x))
367d0de7e4aSpeixiaokun    val g_stPermFail = !g_perm.w
368d0de7e4aSpeixiaokun    val g_instrPermFail = !g_perm.x
369db6cfb5aSHaoyuan Feng    val ldGpf = (g_ldPermFail || gpf) && isLd
370db6cfb5aSHaoyuan Feng    val stGpf = (g_stPermFail || gpf) && isSt
371db6cfb5aSHaoyuan Feng    val instrGpf = (g_instrPermFail || gpf) && isInst
3727acf8b76SXiaokun-Pei    val s2_valid = portTranslateEnable(idx) && hasS2xlate && !onlyS1
373d0de7e4aSpeixiaokun
374d0de7e4aSpeixiaokun    val fault_valid = s1_valid || s2_valid
375d0de7e4aSpeixiaokun
376c794d992Speixiaokun    // when pf and gpf can't happens simultaneously
3772ea10b44SXiaokun-Pei    val hasPf = (ldPf || ldUpdate || stPf || stUpdate || instrPf || instrUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
378db6cfb5aSHaoyuan Feng    // Only lsu need check related to high address truncation
379db6cfb5aSHaoyuan Feng    when (RegNext(prepf || pregpf || preaf)) {
380ad415ae0SXiaokun-Pei      resp(idx).bits.isForVSnonLeafPTE := false.B
381db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).pf.ld := RegNext(prepf) && isLd
382db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).pf.st := RegNext(prepf) && isSt
383db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).pf.instr := false.B
384db6cfb5aSHaoyuan Feng
385db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).gpf.ld := RegNext(pregpf) && isLd
386db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).gpf.st := RegNext(pregpf) && isSt
387db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).gpf.instr := false.B
388db6cfb5aSHaoyuan Feng
389db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).af.ld := RegNext(preaf) && TlbCmd.isRead(cmd)
390db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).af.st := RegNext(preaf) && TlbCmd.isWrite(cmd)
391db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).af.instr := false.B
39246e9ee74SHaoyuan Feng
39346e9ee74SHaoyuan Feng      resp(idx).bits.excp(nDups).vaNeedExt := false.B
394a94d0abaSHaoyuan Feng      // overwrite miss & gpaddr when exception related to high address truncation happens
395a94d0abaSHaoyuan Feng      resp(idx).bits.miss := false.B
396a94d0abaSHaoyuan Feng      resp(idx).bits.gpaddr(nDups) := RegNext(req(idx).bits.fullva)
397db6cfb5aSHaoyuan Feng    } .otherwise {
398ad415ae0SXiaokun-Pei      // isForVSnonLeafPTE is used only when gpf happens and it caused by a G-stage translation which supports VS-stage translation
399ad415ae0SXiaokun-Pei      // it will be sent to CSR in order to modify the m/htinst.
400ad415ae0SXiaokun-Pei      // Ref: The RISC-V Instruction Set Manual: Volume II: Privileged Architecture - 19.6.3. Transformed Instruction or Pseudoinstruction for mtinst or htinst
401ad415ae0SXiaokun-Pei      val isForVSnonLeafPTE = isNonLeaf || isFakePte
402ad415ae0SXiaokun-Pei      resp(idx).bits.isForVSnonLeafPTE := isForVSnonLeafPTE
4032ea10b44SXiaokun-Pei      resp(idx).bits.excp(nDups).pf.ld := (ldPf || ldUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
4042ea10b44SXiaokun-Pei      resp(idx).bits.excp(nDups).pf.st := (stPf || stUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
4052ea10b44SXiaokun-Pei      resp(idx).bits.excp(nDups).pf.instr := (instrPf || instrUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
406b6982e83SLemover      // NOTE: pf need && with !af, page fault has higher priority than access fault
407b6982e83SLemover      // but ptw may also have access fault, then af happens, the translation is wrong.
408b6982e83SLemover      // In this case, pf has lower priority than af
4096d5ddbceSLemover
410c794d992Speixiaokun      resp(idx).bits.excp(nDups).gpf.ld := (ldGpf || g_ldUpdate) && s2_valid && !af && !hasPf
411c794d992Speixiaokun      resp(idx).bits.excp(nDups).gpf.st := (stGpf || g_stUpdate) && s2_valid && !af && !hasPf
412c794d992Speixiaokun      resp(idx).bits.excp(nDups).gpf.instr := (instrGpf || g_instrUpdate) && s2_valid && !af && !hasPf
413d0de7e4aSpeixiaokun
414f9ac118cSHaoyuan Feng      resp(idx).bits.excp(nDups).af.ld    := af && TlbCmd.isRead(cmd) && fault_valid
415f9ac118cSHaoyuan Feng      resp(idx).bits.excp(nDups).af.st    := af && TlbCmd.isWrite(cmd) && fault_valid
416f9ac118cSHaoyuan Feng      resp(idx).bits.excp(nDups).af.instr := af && TlbCmd.isExec(cmd) && fault_valid
41746e9ee74SHaoyuan Feng
41846e9ee74SHaoyuan Feng      resp(idx).bits.excp(nDups).vaNeedExt := true.B
419db6cfb5aSHaoyuan Feng    }
42046e9ee74SHaoyuan Feng
42146e9ee74SHaoyuan Feng    resp(idx).bits.excp(nDups).isHyper := isHyperInst(idx)
4226d5ddbceSLemover  }
4236d5ddbceSLemover
424f1fe8698SLemover  def handle_nonblock(idx: Int): Unit = {
425f1fe8698SLemover    io.requestor(idx).resp.valid := req_out_v(idx)
426f1fe8698SLemover    io.requestor(idx).req.ready := io.requestor(idx).resp.ready // should always be true
4279930e66fSLemover    XSError(!io.requestor(idx).resp.ready, s"${q.name} port ${idx} is non-block, resp.ready must be true.B")
428cb8f2f2aSLemover
429c3d5cfb3Speixiaokun    val req_need_gpa = hasGpf(idx)
430d0de7e4aSpeixiaokun    val req_s2xlate = Wire(UInt(2.W))
43182978df9Speixiaokun    req_s2xlate := MuxCase(noS2xlate, Seq(
43282e4705bSpeixiaokun      (!(virt_out(idx) || req_out(idx).hyperinst)) -> noS2xlate,
43382e4705bSpeixiaokun      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
43482e4705bSpeixiaokun      (csr.vsatp.mode === 0.U) -> onlyStage2,
43582e4705bSpeixiaokun      (csr.hgatp.mode === 0.U || req_need_gpa) -> onlyStage1
43682978df9Speixiaokun    ))
4374c4af37cSpeixiaokun
43897929664SXiaokun-Pei    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)
4395adc4829SYanqin Li    // TODO: RegNext enable: ptw.resp.valid ? req.valid
4405adc4829SYanqin Li    val ptw_resp_bits_reg = RegEnable(ptw.resp.bits, ptw.resp.valid)
44197929664SXiaokun-Pei    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)
442d4078d6eSXiaokun-Pei    val ptw_getGpa = req_need_gpa && hitVec(idx)
443976c97c3SXiaokun-Pei    val need_gpa_vpn_hit = need_gpa_vpn === get_pn(req_out(idx).vaddr)
444*4fc3a30cSXu, Zefan
445*4fc3a30cSXu, Zefan    io.ptw.req(idx).valid := false.B;
446*4fc3a30cSXu, Zefan    io.tlbreplay(idx) := false.B;
447*4fc3a30cSXu, Zefan
448*4fc3a30cSXu, Zefan    when (req_out_v(idx) && missVec(idx)) {
449*4fc3a30cSXu, Zefan      // NOTE: for an miss tlb request: either send a ptw request, or ask for a replay
450*4fc3a30cSXu, Zefan      when (ptw_just_back || ptw_already_back) {
451*4fc3a30cSXu, Zefan        io.tlbreplay(idx) := true.B;
452*4fc3a30cSXu, Zefan      } .elsewhen (need_gpa && !need_gpa_vpn_hit && !resp_gpa_refill) {
453*4fc3a30cSXu, Zefan        // not send any unrelated ptw request when l1tlb is in need_gpa state
454*4fc3a30cSXu, Zefan        io.tlbreplay(idx) := true.B;
455*4fc3a30cSXu, Zefan      } .otherwise {
456*4fc3a30cSXu, Zefan        io.ptw.req(idx).valid := true.B;
457*4fc3a30cSXu, Zefan      }
458*4fc3a30cSXu, Zefan    }
459*4fc3a30cSXu, Zefan
4605adc4829SYanqin Li    when (io.requestor(idx).req_kill && GatedValidRegNext(io.requestor(idx).req.fire)) {
461c3b763d0SYinan Xu      io.ptw.req(idx).valid := false.B
462185e6164SHaoyuan Feng      io.tlbreplay(idx) := true.B
463c3b763d0SYinan Xu    }
464*4fc3a30cSXu, Zefan
465185e6164SHaoyuan Feng    io.ptw.req(idx).bits.vpn := get_pn(req_out(idx).vaddr)
4664c4af37cSpeixiaokun    io.ptw.req(idx).bits.s2xlate := req_s2xlate
467d4078d6eSXiaokun-Pei    io.ptw.req(idx).bits.getGpa := ptw_getGpa
468185e6164SHaoyuan Feng    io.ptw.req(idx).bits.memidx := req_out(idx).memidx
469149086eaSLemover  }
470a0301c0dSLemover
471f1fe8698SLemover  def handle_block(idx: Int): Unit = {
472f1fe8698SLemover    // three valid: 1.if exist a entry; 2.if sent to ptw; 3.unset resp.valid
473935edac4STang Haojin    io.requestor(idx).req.ready := !req_out_v(idx) || io.requestor(idx).resp.fire
474f1fe8698SLemover    // req_out_v for if there is a request, may long latency, fixme
475f1fe8698SLemover
476f1fe8698SLemover    // miss request entries
477c3d5cfb3Speixiaokun    val req_need_gpa = hasGpf(idx)
478f1fe8698SLemover    val miss_req_vpn = get_pn(req_out(idx).vaddr)
4798744445eSMaxpicca-Li    val miss_req_memidx = req_out(idx).memidx
480d0de7e4aSpeixiaokun    val miss_req_s2xlate = Wire(UInt(2.W))
48182978df9Speixiaokun    miss_req_s2xlate := MuxCase(noS2xlate, Seq(
48282e4705bSpeixiaokun      (!(virt_out(idx) || req_out(idx).hyperinst)) -> noS2xlate,
48382e4705bSpeixiaokun      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
48482e4705bSpeixiaokun      (csr.vsatp.mode === 0.U) -> onlyStage2,
48582e4705bSpeixiaokun      (csr.hgatp.mode === 0.U || req_need_gpa) -> onlyStage1
48682978df9Speixiaokun    ))
4873222d00fSpeixiaokun    val miss_req_s2xlate_reg = RegEnable(miss_req_s2xlate, io.ptw.req(idx).fire)
488c3d5cfb3Speixiaokun    val hasS2xlate = miss_req_s2xlate_reg =/= noS2xlate
489c3d5cfb3Speixiaokun    val onlyS2 = miss_req_s2xlate_reg === onlyStage2
49097929664SXiaokun-Pei    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)
49197929664SXiaokun-Pei    val hit_s2 = io.ptw.resp.bits.s2.hit(miss_req_vpn, io.csr.hgatp.vmid)
492c3d5cfb3Speixiaokun    val hit = Mux(onlyS2, hit_s2, hit_s1) && io.ptw.resp.valid && miss_req_s2xlate_reg === io.ptw.resp.bits.s2xlate
493f1fe8698SLemover
4945adc4829SYanqin Li    val new_coming_valid = WireInit(false.B)
4955adc4829SYanqin Li    new_coming_valid := req_in(idx).fire && !req_in(idx).bits.kill && !flush_pipe(idx)
4965adc4829SYanqin Li    val new_coming = GatedValidRegNext(new_coming_valid)
497f1fe8698SLemover    val miss_wire = new_coming && missVec(idx)
498935edac4STang Haojin    val miss_v = ValidHoldBypass(miss_wire, resp(idx).fire, flush_pipe(idx))
499f1fe8698SLemover    val miss_req_v = ValidHoldBypass(miss_wire || (miss_v && flush_mmu && !mmu_flush_pipe),
500935edac4STang Haojin      io.ptw.req(idx).fire || resp(idx).fire, flush_pipe(idx))
501f1fe8698SLemover
502f1fe8698SLemover    // when ptw resp, check if hit, reset miss_v, resp to lsu/ifu
503292bea3fSWilliam Wang    resp(idx).valid := req_out_v(idx) && !(miss_v && portTranslateEnable(idx))
504935edac4STang Haojin    when (io.ptw.resp.fire && hit && req_out_v(idx) && portTranslateEnable(idx)) {
505d0de7e4aSpeixiaokun      val stage1 = io.ptw.resp.bits.s1
506d0de7e4aSpeixiaokun      val stage2 = io.ptw.resp.bits.s2
507d0de7e4aSpeixiaokun      val s2xlate = io.ptw.resp.bits.s2xlate
508f1fe8698SLemover      resp(idx).valid := true.B
509c3d5cfb3Speixiaokun      resp(idx).bits.miss := false.B
510d0de7e4aSpeixiaokun      val s1_paddr = Cat(stage1.genPPN(get_pn(req_out(idx).vaddr)), get_off(req_out(idx).vaddr))
511cda84113Speixiaokun      val s2_paddr = Cat(stage2.genPPNS2(get_pn(req_out(idx).vaddr)), get_off(req_out(idx).vaddr))
51203efd994Shappy-lx      for (d <- 0 until nRespDups) {
51382978df9Speixiaokun        resp(idx).bits.paddr(d) := Mux(s2xlate =/= noS2xlate, s2_paddr, s1_paddr)
514d0de7e4aSpeixiaokun        resp(idx).bits.gpaddr(d) := s1_paddr
515002c10a4SYanqin Li        pbmt_check(idx, d, io.ptw.resp.bits.s1.entry.pbmt, io.ptw.resp.bits.s2.entry.pbmt, s2xlate)
516cca17e78Speixiaokun        perm_check(stage1, req_out(idx).cmd, idx, d, stage2, req_out(idx).hlvx, s2xlate)
51703efd994Shappy-lx      }
51808b0bc30Shappy-lx      pmp_check(resp(idx).bits.paddr(0), req_out(idx).size, req_out(idx).cmd, false.B, idx)
519f1fe8698SLemover
520f1fe8698SLemover      // NOTE: the unfiltered req would be handled by Repeater
521f1fe8698SLemover    }
522f1fe8698SLemover    assert(RegNext(!resp(idx).valid || resp(idx).ready, true.B), "when tlb resp valid, ready should be true, must")
523f1fe8698SLemover    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")
524f1fe8698SLemover
525f1fe8698SLemover    val ptw_req = io.ptw.req(idx)
526f1fe8698SLemover    ptw_req.valid := miss_req_v
527f1fe8698SLemover    ptw_req.bits.vpn := miss_req_vpn
528d0de7e4aSpeixiaokun    ptw_req.bits.s2xlate := miss_req_s2xlate
529a4f9c77fSpeixiaokun    ptw_req.bits.getGpa := req_need_gpa && hitVec(idx)
5308744445eSMaxpicca-Li    ptw_req.bits.memidx := miss_req_memidx
531f1fe8698SLemover
532185e6164SHaoyuan Feng    io.tlbreplay(idx) := false.B
533185e6164SHaoyuan Feng
534f1fe8698SLemover    // NOTE: when flush pipe, tlb should abandon last req
535f1fe8698SLemover    // however, some outside modules like icache, dont care flushPipe, and still waiting for tlb resp
536f1fe8698SLemover    // just resp valid and raise page fault to go through. The pipe(ifu) will abandon it.
537f1fe8698SLemover    if (!q.outsideRecvFlush) {
538292bea3fSWilliam Wang      when (req_out_v(idx) && flush_pipe(idx) && portTranslateEnable(idx)) {
539f1fe8698SLemover        resp(idx).valid := true.B
54003efd994Shappy-lx        for (d <- 0 until nRespDups) {
541002c10a4SYanqin Li          resp(idx).bits.pbmt(d) := 0.U
54203efd994Shappy-lx          resp(idx).bits.excp(d).pf.ld := true.B // sfence happened, pf for not to use this addr
54303efd994Shappy-lx          resp(idx).bits.excp(d).pf.st := true.B
54403efd994Shappy-lx          resp(idx).bits.excp(d).pf.instr := true.B
54503efd994Shappy-lx        }
546f1fe8698SLemover      }
547f1fe8698SLemover    }
548f1fe8698SLemover  }
549cb8f2f2aSLemover
550cb8f2f2aSLemover  // when ptw resp, tlb at refill_idx maybe set to miss by force.
551cb8f2f2aSLemover  // Bypass ptw resp to check.
552d0de7e4aSpeixiaokun  def ptw_resp_bypass(vpn: UInt, s2xlate: UInt) = {
5535adc4829SYanqin Li    // TODO: RegNext enable: ptw.resp.valid
554cca17e78Speixiaokun    val hasS2xlate = s2xlate =/= noS2xlate
555cca17e78Speixiaokun    val onlyS2 = s2xlate === onlyStage2
556c3d5cfb3Speixiaokun    val onlyS1 = s2xlate === onlyStage1
557d0de7e4aSpeixiaokun    val s2xlate_hit = s2xlate === ptw.resp.bits.s2xlate
55897929664SXiaokun-Pei    val resp_hit = ptw.resp.bits.hit(vpn, io.csr.satp.asid, io.csr.vsatp.asid, io.csr.hgatp.vmid, true, false)
5595adc4829SYanqin Li    val p_hit = GatedValidRegNext(resp_hit && io.ptw.resp.fire && s2xlate_hit)
560d0de7e4aSpeixiaokun    val ppn_s1 = ptw.resp.bits.s1.genPPN(vpn)
561cda84113Speixiaokun    val gvpn = Mux(onlyS2, vpn, ppn_s1)
562cda84113Speixiaokun    val ppn_s2 = ptw.resp.bits.s2.genPPNS2(gvpn)
563242cafeeSXu, Zefan    val p_ppn = RegEnable(Mux(s2xlate === onlyStage2 || s2xlate === allStage, ppn_s2, ppn_s1), io.ptw.resp.fire)
564002c10a4SYanqin Li    val p_pbmt = RegEnable(ptw.resp.bits.s1.entry.pbmt,io.ptw.resp.fire)
565d0de7e4aSpeixiaokun    val p_perm = RegEnable(ptwresp_to_tlbperm(ptw.resp.bits.s1), io.ptw.resp.fire)
5662ea10b44SXiaokun-Pei    val p_gvpn = RegEnable(Mux(onlyS2, ptw.resp.bits.s2.entry.tag, ptw.resp.bits.s1.genGVPN(vpn)), io.ptw.resp.fire)
567002c10a4SYanqin Li    val p_g_pbmt = RegEnable(ptw.resp.bits.s2.entry.pbmt,io.ptw.resp.fire)
568d0de7e4aSpeixiaokun    val p_g_perm = RegEnable(hptwresp_to_tlbperm(ptw.resp.bits.s2), io.ptw.resp.fire)
569d0de7e4aSpeixiaokun    val p_s2xlate = RegEnable(ptw.resp.bits.s2xlate, io.ptw.resp.fire)
570ad8d4021SXiaokun-Pei    val p_s1_level = RegEnable(ptw.resp.bits.s1.entry.level.get, io.ptw.resp.fire)
571ad8d4021SXiaokun-Pei    val p_s1_isLeaf = RegEnable(ptw.resp.bits.s1.isLeaf(), io.ptw.resp.fire)
572ad8d4021SXiaokun-Pei    val p_s1_isFakePte = RegEnable(ptw.resp.bits.s1.isFakePte(), io.ptw.resp.fire)
573ad8d4021SXiaokun-Pei    (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)
574cb8f2f2aSLemover  }
575cb8f2f2aSLemover
576f1fe8698SLemover  // perf event
5775adc4829SYanqin Li  val result_ok = req_in.map(a => GatedValidRegNext(a.fire))
578f1fe8698SLemover  val perfEvents =
579f1fe8698SLemover    Seq(
580935edac4STang Haojin      ("access", PopCount((0 until Width).map{i => if (Block(i)) io.requestor(i).req.fire else portTranslateEnable(i) && result_ok(i) })),
581935edac4STang Haojin      ("miss  ", PopCount((0 until Width).map{i => if (Block(i)) portTranslateEnable(i) && result_ok(i) && missVec(i) else ptw.req(i).fire })),
582a0301c0dSLemover    )
583f1fe8698SLemover  generatePerfEvent()
584a0301c0dSLemover
585f1fe8698SLemover  // perf log
5866d5ddbceSLemover  for (i <- 0 until Width) {
587f1fe8698SLemover    if (Block(i)) {
588292bea3fSWilliam Wang      XSPerfAccumulate(s"access${i}",result_ok(i) && portTranslateEnable(i))
589f1fe8698SLemover      XSPerfAccumulate(s"miss${i}", result_ok(i) && missVec(i))
5906d5ddbceSLemover    } else {
5915adc4829SYanqin Li      XSPerfAccumulate("first_access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid))
592292bea3fSWilliam Wang      XSPerfAccumulate("access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i))
5935adc4829SYanqin Li      XSPerfAccumulate("first_miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i) && RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid))
594292bea3fSWilliam Wang      XSPerfAccumulate("miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i))
595a0301c0dSLemover    }
5966d5ddbceSLemover  }
597935edac4STang Haojin  XSPerfAccumulate("ptw_resp_count", ptw.resp.fire)
598cca17e78Speixiaokun  XSPerfAccumulate("ptw_resp_pf_count", ptw.resp.fire && ptw.resp.bits.s1.pf)
5996d5ddbceSLemover
6006d5ddbceSLemover  // Log
6016d5ddbceSLemover  for(i <- 0 until Width) {
6026d5ddbceSLemover    XSDebug(req(i).valid, p"req(${i.U}): (${req(i).valid} ${req(i).ready}) ${req(i).bits}\n")
6036d5ddbceSLemover    XSDebug(resp(i).valid, p"resp(${i.U}): (${resp(i).valid} ${resp(i).ready}) ${resp(i).bits}\n")
6046d5ddbceSLemover  }
6056d5ddbceSLemover
606f1fe8698SLemover  XSDebug(io.sfence.valid, p"Sfence: ${io.sfence}\n")
607f1fe8698SLemover  XSDebug(ParallelOR(req_out_v) || ptw.resp.valid, p"vmEnable:${vmEnable} hit:${Binary(VecInit(hitVec).asUInt)} miss:${Binary(VecInit(missVec).asUInt)}\n")
6086d5ddbceSLemover  for (i <- ptw.req.indices) {
609935edac4STang Haojin    XSDebug(ptw.req(i).fire, p"L2TLB req:${ptw.req(i).bits}\n")
6106d5ddbceSLemover  }
61192e3bfefSLemover  XSDebug(ptw.resp.valid, p"L2TLB resp:${ptw.resp.bits} (v:${ptw.resp.valid}r:${ptw.resp.ready}) \n")
6126d5ddbceSLemover
613f9ac118cSHaoyuan Feng  println(s"${q.name}: page: ${q.NWays} ${q.Associative} ${q.Replacer.get}")
614a0301c0dSLemover
6155ab1b84dSHaoyuan Feng  if (env.EnableDifftest) {
6165ab1b84dSHaoyuan Feng    for (i <- 0 until Width) {
6175ab1b84dSHaoyuan Feng      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
618d0de7e4aSpeixiaokun      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
6195ab1b84dSHaoyuan Feng      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
6207d45a146SYinan Xu      val difftest = DifftestModule(new DiffL1TLBEvent)
621254e4960SHaoyuan Feng      difftest.coreid := io.hartId
622d0de7e4aSpeixiaokun      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)
6237d45a146SYinan Xu      if (!Seq("itlb", "ldtlb", "sttlb").contains(q.name)) {
6247d45a146SYinan Xu        difftest.valid := false.B
6257d45a146SYinan Xu      }
6267d45a146SYinan Xu      difftest.index := TLBDiffId(p(XSCoreParamsKey).HartId).U
6275adc4829SYanqin Li      difftest.vpn := RegEnable(get_pn(req_in(i).bits.vaddr), req_in(i).valid)
6287d45a146SYinan Xu      difftest.ppn := get_pn(io.requestor(i).resp.bits.paddr(0))
62987d0ba30Speixiaokun      difftest.satp := Cat(io.csr.satp.mode, io.csr.satp.asid, io.csr.satp.ppn)
63087d0ba30Speixiaokun      difftest.vsatp := Cat(io.csr.vsatp.mode, io.csr.vsatp.asid, io.csr.vsatp.ppn)
63197929664SXiaokun-Pei      difftest.hgatp := Cat(io.csr.hgatp.mode, io.csr.hgatp.vmid, io.csr.hgatp.ppn)
632dd103903Speixiaokun      val req_need_gpa = gpf
633dd103903Speixiaokun      val req_s2xlate = Wire(UInt(2.W))
634dd103903Speixiaokun      req_s2xlate := MuxCase(noS2xlate, Seq(
63582e4705bSpeixiaokun        (!RegNext(virt_in || req_in(i).bits.hyperinst)) -> noS2xlate,
636cca17e78Speixiaokun        (vsatp.mode =/= 0.U && hgatp.mode =/= 0.U) -> allStage,
637cca17e78Speixiaokun        (vsatp.mode === 0.U) -> onlyStage2,
638dd103903Speixiaokun        (hgatp.mode === 0.U || req_need_gpa) -> onlyStage1
63982978df9Speixiaokun      ))
640dd103903Speixiaokun      difftest.s2xlate := req_s2xlate
6417d45a146SYinan Xu    }
6425ab1b84dSHaoyuan Feng  }
6435ab1b84dSHaoyuan Feng}
6445ab1b84dSHaoyuan Feng
6457d45a146SYinan Xuobject TLBDiffId {
6467d45a146SYinan Xu  var i: Int = 0
6477d45a146SYinan Xu  var lastHartId: Int = -1
6487d45a146SYinan Xu  def apply(hartId: Int): Int = {
6497d45a146SYinan Xu    if (lastHartId != hartId) {
6507d45a146SYinan Xu      i = 0
6517d45a146SYinan Xu      lastHartId = hartId
6527d45a146SYinan Xu    }
6537d45a146SYinan Xu    i += 1
6547d45a146SYinan Xu    i - 1
6557d45a146SYinan Xu  }
656f1fe8698SLemover}
6571ca0e4f3SYinan Xu
65803efd994Shappy-lxclass TLBNonBlock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(false), q)
65903efd994Shappy-lxclass TLBBLock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(true), q)
6606d5ddbceSLemover
661a0301c0dSLemoverclass TlbReplace(Width: Int, q: TLBParameters)(implicit p: Parameters) extends TlbModule {
662a0301c0dSLemover  val io = IO(new TlbReplaceIO(Width, q))
663a0301c0dSLemover
664f9ac118cSHaoyuan Feng  if (q.Associative == "fa") {
665f9ac118cSHaoyuan Feng    val re = ReplacementPolicy.fromString(q.Replacer, q.NWays)
666f9ac118cSHaoyuan Feng    re.access(io.page.access.map(_.touch_ways))
667f9ac118cSHaoyuan Feng    io.page.refillIdx := re.way
668a0301c0dSLemover  } else { // set-acco && plru
669f9ac118cSHaoyuan Feng    val re = ReplacementPolicy.fromString(q.Replacer, q.NSets, q.NWays)
670f9ac118cSHaoyuan Feng    re.access(io.page.access.map(_.sets), io.page.access.map(_.touch_ways))
671f9ac118cSHaoyuan Feng    io.page.refillIdx := { if (q.NWays == 1) 0.U else re.way(io.page.chosen_set) }
672a0301c0dSLemover  }
673a0301c0dSLemover}
674