xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/TLB.scala (revision c1eb2883d47de2b393febf6448b5cdd8a779f8bb)
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)
68*c1eb2883SHaoyuan Feng  val csr = DelayN(io.csr, q.fenceDelay)
69d0de7e4aSpeixiaokun
70*c1eb2883SHaoyuan Feng  val flush_mmu = sfence.valid || csr.satp.changed || csr.vsatp.changed || csr.hgatp.changed
71*c1eb2883SHaoyuan Feng  val mmu_flush_pipe = sfence.valid && sfence.bits.flushPipe // for svinval, won't flush pipe
72f1fe8698SLemover  val flush_pipe = io.flushPipe
73a4f9c77fSpeixiaokun  val redirect = io.redirect
74189833a1SHaoyuan Feng  val EffectiveVa = Wire(Vec(Width, UInt(XLEN.W)))
75ffa711ffSpeixiaokun  val req_in = req
76189833a1SHaoyuan Feng  val req_out = Reg(Vec(Width, new TlbReq))
77189833a1SHaoyuan Feng  for (i <- 0 until Width) {
78189833a1SHaoyuan Feng    when (req(i).fire) {
79189833a1SHaoyuan Feng      req_out(i) := req(i).bits
80189833a1SHaoyuan Feng      req_out(i).fullva := EffectiveVa(i)
81189833a1SHaoyuan Feng    }
82189833a1SHaoyuan Feng  }
83ffa711ffSpeixiaokun  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)))
84ffa711ffSpeixiaokun
85ffa711ffSpeixiaokun  val isHyperInst = (0 until Width).map(i => req_out_v(i) && req_out(i).hyperinst)
8650c7aa78Speixiaokun
87f1fe8698SLemover  // ATTENTION: csr and flush from backend are delayed. csr should not be later than flush.
88f1fe8698SLemover  // because, csr will influence tlb behavior.
89189833a1SHaoyuan Feng  val ifetch = if (q.fetchi) true.B else false.B
90d0de7e4aSpeixiaokun  val mode_tmp = if (q.useDmode) csr.priv.dmode else csr.priv.imode
91d0de7e4aSpeixiaokun  val mode = (0 until Width).map(i => Mux(isHyperInst(i), csr.priv.spvp, mode_tmp))
9282e4705bSpeixiaokun  val virt_in = csr.priv.virt
9382e4705bSpeixiaokun  val virt_out = req.map(a => RegEnable(csr.priv.virt, a.fire))
94*c1eb2883SHaoyuan Feng  val sum = (0 until Width).map(i => Mux(virt_out(i) || isHyperInst(i), csr.priv.vsum, csr.priv.sum))
95*c1eb2883SHaoyuan Feng  val mxr = (0 until Width).map(i => Mux(virt_out(i) || isHyperInst(i), csr.priv.vmxr || csr.priv.mxr, csr.priv.mxr))
96ffa711ffSpeixiaokun  val req_in_s2xlate = (0 until Width).map(i => MuxCase(noS2xlate, Seq(
9782e4705bSpeixiaokun      (!(virt_in || req_in(i).bits.hyperinst)) -> noS2xlate,
98251a1ca9Speixiaokun      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
99251a1ca9Speixiaokun      (csr.vsatp.mode === 0.U) -> onlyStage2,
100251a1ca9Speixiaokun      (csr.hgatp.mode === 0.U) -> onlyStage1
101ffa711ffSpeixiaokun    )))
102ffa711ffSpeixiaokun  val req_out_s2xlate = (0 until Width).map(i => MuxCase(noS2xlate, Seq(
10382e4705bSpeixiaokun    (!(virt_out(i) || isHyperInst(i))) -> noS2xlate,
104251a1ca9Speixiaokun    (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
105251a1ca9Speixiaokun    (csr.vsatp.mode === 0.U) -> onlyStage2,
106251a1ca9Speixiaokun    (csr.hgatp.mode === 0.U) -> onlyStage1
1073106de0aSpeixiaokun  )))
108e9027bcdSpeixiaokun  val need_gpa = RegInit(false.B)
109e9ba7f28SHaoyuan Feng  val need_gpa_wire = WireInit(false.B)
110a4f9c77fSpeixiaokun  val need_gpa_robidx = Reg(new RobPtr)
111e9027bcdSpeixiaokun  val need_gpa_vpn = Reg(UInt(vpnLen.W))
112ad8d4021SXiaokun-Pei  val resp_gpa_gvpn = Reg(UInt(ptePPNLen.W))
113e9566d21Speixiaokun  val resp_gpa_refill = RegInit(false.B)
114ad8d4021SXiaokun-Pei  val resp_s1_level = RegInit(0.U(log2Up(Level + 1).W))
115ad8d4021SXiaokun-Pei  val resp_s1_isLeaf = RegInit(false.B)
116ad8d4021SXiaokun-Pei  val resp_s1_isFakePte = RegInit(false.B)
117e9027bcdSpeixiaokun  val hasGpf = Wire(Vec(Width, Bool()))
118d0de7e4aSpeixiaokun
119*c1eb2883SHaoyuan Feng  val Sv39Enable = csr.satp.mode === 8.U
120*c1eb2883SHaoyuan Feng  val Sv48Enable = csr.satp.mode === 9.U
121*c1eb2883SHaoyuan Feng  val Sv39x4Enable = csr.vsatp.mode === 8.U || csr.hgatp.mode === 8.U
122*c1eb2883SHaoyuan Feng  val Sv48x4Enable = csr.vsatp.mode === 9.U || csr.hgatp.mode === 9.U
1230841a83fSXuan Hu  val vmEnable = (0 until Width).map(i => !(isHyperInst(i) || virt_out(i)) && (
1243ea4388cSHaoyuan Feng    if (EnbaleTlbDebug) (Sv39Enable || Sv48Enable)
1253ea4388cSHaoyuan Feng    else (Sv39Enable || Sv48Enable) && (mode(i) < ModeM))
1260841a83fSXuan Hu  )
1273ea4388cSHaoyuan Feng  val s2xlateEnable = (0 until Width).map(i => (isHyperInst(i) || virt_out(i)) && (Sv39x4Enable || Sv48x4Enable) && (mode(i) < ModeM))
1285adc4829SYanqin Li  val portTranslateEnable = (0 until Width).map(i => (vmEnable(i) || s2xlateEnable(i)) && RegEnable(!req(i).bits.no_translate, req(i).valid))
1296d5ddbceSLemover
130db6cfb5aSHaoyuan Feng  // pre fault: check fault before real do translate
131db6cfb5aSHaoyuan Feng  val prepf = WireInit(VecInit(Seq.fill(Width)(false.B)))
132db6cfb5aSHaoyuan Feng  val pregpf = WireInit(VecInit(Seq.fill(Width)(false.B)))
133db6cfb5aSHaoyuan Feng  val preaf = WireInit(VecInit(Seq.fill(Width)(false.B)))
134189833a1SHaoyuan Feng  val premode = (0 until Width).map(i => Mux(req_in(i).bits.hyperinst, csr.priv.spvp, mode_tmp))
135189833a1SHaoyuan Feng  for (i <- 0 until Width) {
136189833a1SHaoyuan Feng    resp(i).bits.fullva := RegEnable(EffectiveVa(i), req(i).valid)
137189833a1SHaoyuan Feng  }
13809223e00SHaoyuan Feng  val prevmEnable = (0 until Width).map(i => !(virt_in || req_in(i).bits.hyperinst) && (
13909223e00SHaoyuan Feng    if (EnbaleTlbDebug) (Sv39Enable || Sv48Enable)
140189833a1SHaoyuan Feng    else (Sv39Enable || Sv48Enable) && (premode(i) < ModeM))
14109223e00SHaoyuan Feng  )
142189833a1SHaoyuan Feng  val pres2xlateEnable = (0 until Width).map(i => (virt_in || req_in(i).bits.hyperinst) && (Sv39x4Enable || Sv48x4Enable) && (premode(i) < ModeM))
143189833a1SHaoyuan Feng
144db6cfb5aSHaoyuan Feng  (0 until Width).foreach{i =>
145189833a1SHaoyuan Feng
146189833a1SHaoyuan Feng    val pmm = WireInit(0.U(2.W))
147189833a1SHaoyuan Feng
148189833a1SHaoyuan Feng    when (ifetch || req(i).bits.hlvx) {
149189833a1SHaoyuan Feng      pmm := 0.U
150189833a1SHaoyuan Feng    } .elsewhen (premode(i) === ModeM) {
151189833a1SHaoyuan Feng      pmm := csr.pmm.mseccfg
152189833a1SHaoyuan Feng    } .elsewhen (!(virt_in || req_in(i).bits.hyperinst) && premode(i) === ModeS) {
153189833a1SHaoyuan Feng      pmm := csr.pmm.menvcfg
154189833a1SHaoyuan Feng    } .elsewhen ((virt_in || req_in(i).bits.hyperinst) && premode(i) === ModeS) {
155189833a1SHaoyuan Feng      pmm := csr.pmm.henvcfg
156189833a1SHaoyuan Feng    } .elsewhen (req_in(i).bits.hyperinst && csr.priv.imode === ModeU) {
157189833a1SHaoyuan Feng      pmm := csr.pmm.hstatus
158189833a1SHaoyuan Feng    } .elsewhen (premode(i) === ModeU) {
159189833a1SHaoyuan Feng      pmm := csr.pmm.senvcfg
160189833a1SHaoyuan Feng    }
161189833a1SHaoyuan Feng
162*c1eb2883SHaoyuan Feng    when (prevmEnable(i) || (pres2xlateEnable(i) && csr.vsatp.mode =/= 0.U)) {
163189833a1SHaoyuan Feng      when (pmm === PMLEN7) {
164189833a1SHaoyuan Feng        EffectiveVa(i) := SignExt(req_in(i).bits.fullva(56, 0), XLEN)
165189833a1SHaoyuan Feng      } .elsewhen (pmm === PMLEN16) {
166189833a1SHaoyuan Feng        EffectiveVa(i) := SignExt(req_in(i).bits.fullva(47, 0), XLEN)
167189833a1SHaoyuan Feng      } .otherwise {
168189833a1SHaoyuan Feng        EffectiveVa(i) := req_in(i).bits.fullva
169189833a1SHaoyuan Feng      }
170189833a1SHaoyuan Feng    } .otherwise {
171189833a1SHaoyuan Feng      when (pmm === PMLEN7) {
172189833a1SHaoyuan Feng        EffectiveVa(i) := ZeroExt(req_in(i).bits.fullva(56, 0), XLEN)
173189833a1SHaoyuan Feng      } .elsewhen (pmm === PMLEN16) {
174189833a1SHaoyuan Feng        EffectiveVa(i) := ZeroExt(req_in(i).bits.fullva(47, 0), XLEN)
175189833a1SHaoyuan Feng      } .otherwise {
176189833a1SHaoyuan Feng        EffectiveVa(i) := req_in(i).bits.fullva
177189833a1SHaoyuan Feng      }
178189833a1SHaoyuan Feng    }
179189833a1SHaoyuan Feng
180189833a1SHaoyuan Feng    val pf48 = SignExt(EffectiveVa(i)(47, 0), XLEN) =/= EffectiveVa(i)
181189833a1SHaoyuan Feng    val pf39 = SignExt(EffectiveVa(i)(38, 0), XLEN) =/= EffectiveVa(i)
182189833a1SHaoyuan Feng    val gpf48 = EffectiveVa(i)(XLEN - 1, 48 + 2) =/= 0.U
183189833a1SHaoyuan Feng    val gpf39 = EffectiveVa(i)(XLEN - 1, 39 + 2) =/= 0.U
184189833a1SHaoyuan Feng    val af = EffectiveVa(i)(XLEN - 1, PAddrBits) =/= 0.U
185db6cfb5aSHaoyuan Feng    when (req(i).valid && req(i).bits.checkfullva) {
18609223e00SHaoyuan Feng      when (prevmEnable(i) || pres2xlateEnable(i)) {
187db6cfb5aSHaoyuan Feng        when (req_in_s2xlate(i) === onlyStage2) {
188db6cfb5aSHaoyuan Feng          when (Sv48x4Enable) {
189db6cfb5aSHaoyuan Feng            pregpf(i) := gpf48
190db6cfb5aSHaoyuan Feng          } .elsewhen (Sv39x4Enable) {
191db6cfb5aSHaoyuan Feng            pregpf(i) := gpf39
192db6cfb5aSHaoyuan Feng          }
193db6cfb5aSHaoyuan Feng        } .otherwise {
194db6cfb5aSHaoyuan Feng          when (Sv48Enable) {
195db6cfb5aSHaoyuan Feng            prepf(i) := pf48
196db6cfb5aSHaoyuan Feng          } .elsewhen (Sv39Enable) {
197db6cfb5aSHaoyuan Feng            prepf(i) := pf39
198db6cfb5aSHaoyuan Feng          }
199db6cfb5aSHaoyuan Feng        }
200db6cfb5aSHaoyuan Feng      } .otherwise {
201db6cfb5aSHaoyuan Feng        preaf(i) := af
202db6cfb5aSHaoyuan Feng      }
203db6cfb5aSHaoyuan Feng    }
204db6cfb5aSHaoyuan Feng  }
2056d5ddbceSLemover
206e9ba7f28SHaoyuan Feng  val refill = ptw.resp.fire && !(ptw.resp.bits.getGpa) && !need_gpa && !need_gpa_wire && !flush_mmu
2074fc3a30cSXu, Zefan  // prevent ptw refill when: 1) it's a getGpa request; 2) l1tlb is in need_gpa state; 3) mmu is being flushed.
2084fc3a30cSXu, Zefan
209eb4bf3f2Speixiaokun  refill_to_mem := DontCare
21003efd994Shappy-lx  val entries = Module(new TlbStorageWrapper(Width, q, nRespDups))
211*c1eb2883SHaoyuan Feng  entries.io.base_connect(sfence, csr, csr.satp)
212f1fe8698SLemover  if (q.outReplace) { io.replace <> entries.io.replace }
2136d5ddbceSLemover  for (i <- 0 until Width) {
214ffa711ffSpeixiaokun    entries.io.r_req_apply(io.requestor(i).req.valid, get_pn(req_in(i).bits.vaddr), i, req_in_s2xlate(i))
215ec159517SXiaokun-Pei    entries.io.w_apply(refill, ptw.resp.bits)
2165adc4829SYanqin Li    // TODO: RegNext enable:req.valid
2175adc4829SYanqin Li    resp(i).bits.debug.isFirstIssue := RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid)
2185adc4829SYanqin Li    resp(i).bits.debug.robIdx := RegEnable(req(i).bits.debug.robIdx, req(i).valid)
219a0301c0dSLemover  }
220e9027bcdSpeixiaokun
221f1fe8698SLemover  // read TLB, get hit/miss, paddr, perm bits
222f1fe8698SLemover  val readResult = (0 until Width).map(TLBRead(_))
223f1fe8698SLemover  val hitVec = readResult.map(_._1)
224f1fe8698SLemover  val missVec = readResult.map(_._2)
225f1fe8698SLemover  val pmp_addr = readResult.map(_._3)
226f9ac118cSHaoyuan Feng  val perm = readResult.map(_._4)
2273106de0aSpeixiaokun  val g_perm = readResult.map(_._5)
228002c10a4SYanqin Li  val pbmt = readResult.map(_._6)
229002c10a4SYanqin Li  val g_pbmt = readResult.map(_._7)
230f1fe8698SLemover  // check pmp use paddr (for timing optization, use pmp_addr here)
231f1fe8698SLemover  // check permisson
232f1fe8698SLemover  (0 until Width).foreach{i =>
23308b0bc30Shappy-lx    val noTranslateReg = RegNext(req(i).bits.no_translate)
23408b0bc30Shappy-lx    val addr = Mux(noTranslateReg, req(i).bits.pmp_addr, pmp_addr(i))
23508b0bc30Shappy-lx    pmp_check(addr, req_out(i).size, req_out(i).cmd, noTranslateReg, i)
23603efd994Shappy-lx    for (d <- 0 until nRespDups) {
237002c10a4SYanqin Li      pbmt_check(i, d, pbmt(i)(d), g_pbmt(i)(d), req_out_s2xlate(i))
238db6cfb5aSHaoyuan 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))
23903efd994Shappy-lx    }
2407acf8b76SXiaokun-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)
241f1fe8698SLemover  }
2426d5ddbceSLemover
243f1fe8698SLemover  // handle block or non-block io
244f1fe8698SLemover  // for non-block io, just return the above result, send miss to ptw
245f1fe8698SLemover  // for block io, hold the request, send miss to ptw,
246f1fe8698SLemover  //   when ptw back, return the result
247f1fe8698SLemover  (0 until Width) foreach {i =>
248f1fe8698SLemover    if (Block(i)) handle_block(i)
249f1fe8698SLemover    else handle_nonblock(i)
250f1fe8698SLemover  }
251f1fe8698SLemover  io.ptw.resp.ready := true.B
252a0301c0dSLemover
253f1fe8698SLemover  /************************  main body above | method/log/perf below ****************************/
254f1fe8698SLemover  def TLBRead(i: Int) = {
255002c10a4SYanqin Li    val (e_hit, e_ppn, e_perm, e_g_perm, e_s2xlate, e_pbmt, e_g_pbmt) = entries.io.r_resp_apply(i)
256ad8d4021SXiaokun-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))
257292bea3fSWilliam Wang    val enable = portTranslateEnable(i)
258f86480a7Speixiaokun    val isOnlys2xlate = req_out_s2xlate(i) === onlyStage2
2599cb05b4dSXiaokun-Pei    val need_gpa_vpn_hit = need_gpa_vpn === get_pn(req_out(i).vaddr)
260a4f9c77fSpeixiaokun    val isitlb = TlbCmd.isExec(req_out(i).cmd)
2618a4dab4dSHaoyuan Feng    val isPrefetch = req_out(i).isPrefetch
2628a4dab4dSHaoyuan Feng    val currentRedirect = req_out(i).debug.robIdx.needFlush(redirect)
2638a4dab4dSHaoyuan Feng    val lastCycleRedirect = req_out(i).debug.robIdx.needFlush(RegNext(redirect))
264a4f9c77fSpeixiaokun
265a4f9c77fSpeixiaokun    when (!isitlb && need_gpa_robidx.needFlush(redirect) || isitlb && flush_pipe(i)){
266a4f9c77fSpeixiaokun      need_gpa := false.B
267a4f9c77fSpeixiaokun      resp_gpa_refill := false.B
268a4f9c77fSpeixiaokun      need_gpa_vpn := 0.U
2698a4dab4dSHaoyuan 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) {
270e9ba7f28SHaoyuan Feng      need_gpa_wire := true.B
271c3d5cfb3Speixiaokun      need_gpa := true.B
2723106de0aSpeixiaokun      need_gpa_vpn := get_pn(req_out(i).vaddr)
2733106de0aSpeixiaokun      resp_gpa_refill := false.B
274a4f9c77fSpeixiaokun      need_gpa_robidx := req_out(i).debug.robIdx
2759cb05b4dSXiaokun-Pei    }.elsewhen (ptw.resp.fire && need_gpa && need_gpa_vpn === ptw.resp.bits.getVpn(need_gpa_vpn)) {
2762ea10b44SXiaokun-Pei      resp_gpa_gvpn := Mux(ptw.resp.bits.s2xlate === onlyStage2, ptw.resp.bits.s2.entry.tag, ptw.resp.bits.s1.genGVPN(need_gpa_vpn))
277ad8d4021SXiaokun-Pei      resp_s1_level := ptw.resp.bits.s1.entry.level.get
278ad8d4021SXiaokun-Pei      resp_s1_isLeaf := ptw.resp.bits.s1.isLeaf()
279ad8d4021SXiaokun-Pei      resp_s1_isFakePte := ptw.resp.bits.s1.isFakePte()
2803106de0aSpeixiaokun      resp_gpa_refill := true.B
2813106de0aSpeixiaokun    }
2823106de0aSpeixiaokun
2839cb05b4dSXiaokun-Pei    when (req_out_v(i) && hasGpf(i) && resp_gpa_refill && need_gpa_vpn_hit){
284c3d5cfb3Speixiaokun      need_gpa := false.B
285c3d5cfb3Speixiaokun    }
286c3d5cfb3Speixiaokun
287cb8f2f2aSLemover    val hit = e_hit || p_hit
2888a4dab4dSHaoyuan Feng    val miss = (!hit && enable) || hasGpf(i) && !p_hit && !(resp_gpa_refill && need_gpa_vpn_hit) && !isOnlys2xlate && !isPrefetch && !lastCycleRedirect
289f1fe8698SLemover    hit.suggestName(s"hit_read_${i}")
290f1fe8698SLemover    miss.suggestName(s"miss_read_${i}")
2916d5ddbceSLemover
292f1fe8698SLemover    val vaddr = SignExt(req_out(i).vaddr, PAddrBits)
293f1fe8698SLemover    resp(i).bits.miss := miss
294935edac4STang Haojin    resp(i).bits.ptwBack := ptw.resp.fire
2955adc4829SYanqin Li    resp(i).bits.memidx := RegEnable(req_in(i).bits.memidx, req_in(i).valid)
29608b0bc30Shappy-lx    resp(i).bits.fastMiss := !hit && enable
2976d5ddbceSLemover
29803efd994Shappy-lx    val ppn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ppnLen.W))))
299002c10a4SYanqin Li    val pbmt = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePbmtLen.W))))
30003efd994Shappy-lx    val perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle))))
301faf7d50bSXiaokun-Pei    val gvpn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePPNLen.W))))
302ad8d4021SXiaokun-Pei    val level = WireInit(VecInit(Seq.fill(nRespDups)(0.U(log2Up(Level + 1).W))))
303ad8d4021SXiaokun-Pei    val isLeaf = WireInit(VecInit(Seq.fill(nRespDups)(false.B)))
304ad8d4021SXiaokun-Pei    val isFakePte = WireInit(VecInit(Seq.fill(nRespDups)(false.B)))
305002c10a4SYanqin Li    val g_pbmt = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePbmtLen.W))))
306d0de7e4aSpeixiaokun    val g_perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle))))
30750c7aa78Speixiaokun    val r_s2xlate = WireInit(VecInit(Seq.fill(nRespDups)(0.U(2.W))))
30803efd994Shappy-lx    for (d <- 0 until nRespDups) {
30903efd994Shappy-lx      ppn(d) := Mux(p_hit, p_ppn, e_ppn(d))
310002c10a4SYanqin Li      pbmt(d) := Mux(p_hit, p_pbmt, e_pbmt(d))
31103efd994Shappy-lx      perm(d) := Mux(p_hit, p_perm, e_perm(d))
312ad8d4021SXiaokun-Pei      gvpn(d) :=  Mux(p_hit, p_gvpn, resp_gpa_gvpn)
313ad8d4021SXiaokun-Pei      level(d) := Mux(p_hit, p_s1_level, resp_s1_level)
314ad8d4021SXiaokun-Pei      isLeaf(d) := Mux(p_hit, p_s1_isLeaf, resp_s1_isLeaf)
315ad8d4021SXiaokun-Pei      isFakePte(d) := Mux(p_hit, p_s1_isFakePte, resp_s1_isFakePte)
316002c10a4SYanqin Li      g_pbmt(d) := Mux(p_hit, p_g_pbmt, e_g_pbmt(d))
317d0de7e4aSpeixiaokun      g_perm(d) := Mux(p_hit, p_g_perm, e_g_perm(d))
31850c7aa78Speixiaokun      r_s2xlate(d) := Mux(p_hit, p_s2xlate, e_s2xlate(d))
31903efd994Shappy-lx      val paddr = Cat(ppn(d), get_off(req_out(i).vaddr))
320ad8d4021SXiaokun-Pei      val vpn_idx = Mux1H(Seq(
321*c1eb2883SHaoyuan Feng        (isFakePte(d) && csr.vsatp.mode === Sv39) -> 2.U,
322*c1eb2883SHaoyuan Feng        (isFakePte(d) && csr.vsatp.mode === Sv48) -> 3.U,
323ad8d4021SXiaokun-Pei        (!isFakePte(d)) -> (level(d) - 1.U),
324ad8d4021SXiaokun-Pei      ))
3257eef70ffSgood-circle      // We use `fullva` here when `isLeaf`, in order to cope with the situation of an unaligned load/store cross page
3267eef70ffSgood-circle      // for example, a `ld` instruction on address 0x81000ffb will be splited into two loads
3277eef70ffSgood-circle      // 1. ld 0x81000ff8. vaddr = 0x81000ff8, fullva = 0x80000ffb
3287eef70ffSgood-circle      // 2. ld 0x81001000. vaddr = 0x81001000, fullva = 0x80000ffb
3297eef70ffSgood-circle      // When load 1 trigger a guest page fault, we should use offset of fullva when generate gpaddr
3307eef70ffSgood-circle      // and when load 2 trigger a guest page fault, we should just use offset of vaddr(all zero).
331e80f666eSHaoyuan Feng      // Also, when onlyS2, if crosspage, gpaddr = vaddr(start address of a new page), else gpaddr = fullva(original vaddr)
332e3e0af7dSXu, Zefan      // By the way, frontend handles the cross page instruction fetch by itself, so TLB doesn't need to do anything extra.
333e3e0af7dSXu, Zefan      // Also, the fullva of iTLB is not used and always zero. crossPageVaddr should never use fullva in iTLB.
334e3e0af7dSXu, Zefan      val crossPageVaddr = Mux(isitlb || req_out(i).fullva(12) =/= vaddr(12), vaddr, req_out(i).fullva)
335e80f666eSHaoyuan Feng      val gpaddr_offset = Mux(isLeaf(d), get_off(crossPageVaddr), Cat(getVpnn(get_pn(crossPageVaddr), vpn_idx), 0.U(log2Up(XLEN/8).W)))
336ad8d4021SXiaokun-Pei      val gpaddr = Cat(gvpn(d), gpaddr_offset)
337292bea3fSWilliam Wang      resp(i).bits.paddr(d) := Mux(enable, paddr, vaddr)
338e80f666eSHaoyuan Feng      resp(i).bits.gpaddr(d) := Mux(r_s2xlate(d) === onlyStage2, crossPageVaddr, gpaddr)
33903efd994Shappy-lx    }
34003efd994Shappy-lx
34103efd994Shappy-lx    XSDebug(req_out_v(i), p"(${i.U}) hit:${hit} miss:${miss} ppn:${Hexadecimal(ppn(0))} perm:${perm(0)}\n")
34203efd994Shappy-lx
343f9ac118cSHaoyuan Feng    val pmp_paddr = resp(i).bits.paddr(0)
344f1fe8698SLemover
345002c10a4SYanqin Li    (hit, miss, pmp_paddr, perm, g_perm, pbmt, g_pbmt)
346f1fe8698SLemover  }
347f1fe8698SLemover
348ad8d4021SXiaokun-Pei  def getVpnn(vpn: UInt, idx: UInt): UInt = {
349ad8d4021SXiaokun-Pei    MuxLookup(idx, 0.U)(Seq(
350ad8d4021SXiaokun-Pei      0.U -> vpn(vpnnLen - 1, 0),
351ad8d4021SXiaokun-Pei      1.U -> vpn(vpnnLen * 2 - 1, vpnnLen),
352ad8d4021SXiaokun-Pei      2.U -> vpn(vpnnLen * 3 - 1, vpnnLen * 2),
353ad8d4021SXiaokun-Pei      3.U -> vpn(vpnnLen * 4 - 1, vpnnLen * 3))
354ad8d4021SXiaokun-Pei    )
355ad8d4021SXiaokun-Pei  }
356ad8d4021SXiaokun-Pei
35708b0bc30Shappy-lx  def pmp_check(addr: UInt, size: UInt, cmd: UInt, noTranslate: Bool, idx: Int): Unit = {
35808b0bc30Shappy-lx    pmp(idx).valid := resp(idx).valid || noTranslate
359f1fe8698SLemover    pmp(idx).bits.addr := addr
360f1fe8698SLemover    pmp(idx).bits.size := size
361f1fe8698SLemover    pmp(idx).bits.cmd := cmd
362f1fe8698SLemover  }
363f1fe8698SLemover
364002c10a4SYanqin Li  def pbmt_check(idx: Int, d: Int, pbmt: UInt, g_pbmt: UInt, s2xlate: UInt):Unit = {
365002c10a4SYanqin Li    val onlyS1 = s2xlate === onlyStage1 || s2xlate === noS2xlate
366e11ec86cSYanqin Li    val pbmtRes = pbmt
367e11ec86cSYanqin Li    val gpbmtRes = g_pbmt
3683adbf906SYanqin Li    val res = MuxLookup(s2xlate, 0.U)(Seq(
369dd286b6aSYanqin Li      onlyStage1 -> pbmtRes,
370dd286b6aSYanqin Li      onlyStage2 -> gpbmtRes,
371dd286b6aSYanqin Li      allStage -> Mux(pbmtRes =/= 0.U, pbmtRes, gpbmtRes),
372dd286b6aSYanqin Li      noS2xlate -> pbmtRes
3733adbf906SYanqin Li    ))
3743adbf906SYanqin Li    resp(idx).bits.pbmt(d) := Mux(portTranslateEnable(idx), res, 0.U)
375002c10a4SYanqin Li  }
376002c10a4SYanqin Li
3775b7ef044SLemover  // for timing optimization, pmp check is divided into dynamic and static
378db6cfb5aSHaoyuan 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) = {
3795b7ef044SLemover    // dynamic: superpage (or full-connected reg entries) -> check pmp when translation done
3805b7ef044SLemover    // static: 4K pages (or sram entries) -> check pmp with pre-checked results
381c3d5cfb3Speixiaokun    val hasS2xlate = s2xlate =/= noS2xlate
382cfa0c506SXiaokun-Pei    val onlyS1 = s2xlate === onlyStage1
38307f77bf0Speixiaokun    val onlyS2 = s2xlate === onlyStage2
38457504f48SHaoyuan Feng    val allS2xlate = s2xlate === allStage
38557504f48SHaoyuan Feng    // noS2xlate || onlyS1 -> perm.af
38657504f48SHaoyuan Feng    // onlyS2 -> g_perm.af
38757504f48SHaoyuan Feng    // allS2xlate -> perm.af || g_perm.af
38857504f48SHaoyuan Feng    val af = (!onlyS2 && perm.af) || ((onlyS2 || allS2xlate) && g_perm.af)
389d0de7e4aSpeixiaokun
390d0de7e4aSpeixiaokun    // Stage 1 perm check
391e5831642Speixiaokun    val pf = perm.pf
392db6cfb5aSHaoyuan Feng    val isLd = TlbCmd.isRead(cmd) && !TlbCmd.isAmo(cmd)
393db6cfb5aSHaoyuan Feng    val isSt = TlbCmd.isWrite(cmd) || TlbCmd.isAmo(cmd)
394db6cfb5aSHaoyuan Feng    val isInst = TlbCmd.isExec(cmd)
395db6cfb5aSHaoyuan Feng    val ldUpdate = !perm.a && isLd // update A/D through exception
396db6cfb5aSHaoyuan Feng    val stUpdate = (!perm.a || !perm.d) && isSt // update A/D through exception
397db6cfb5aSHaoyuan Feng    val instrUpdate = !perm.a && isInst // update A/D through exception
398189833a1SHaoyuan Feng    val modeCheck = !(mode(idx) === ModeU && !perm.u || mode(idx) === ModeS && perm.u && (!sum(idx) || ifetch))
399e5831642Speixiaokun    val ldPermFail = !(modeCheck && Mux(hlvx, perm.x, perm.r || mxr(idx) && perm.x))
400a79fef67Swakafa    val stPermFail = !(modeCheck && perm.w)
401a79fef67Swakafa    val instrPermFail = !(modeCheck && perm.x)
402db6cfb5aSHaoyuan Feng    val ldPf = (ldPermFail || pf) && isLd
403db6cfb5aSHaoyuan Feng    val stPf = (stPermFail || pf) && isSt
404db6cfb5aSHaoyuan Feng    val instrPf = (instrPermFail || pf) && isInst
405ad415ae0SXiaokun-Pei    val isFakePte = !perm.v && !perm.pf && !perm.af && !onlyS2
4062ea10b44SXiaokun-Pei    val isNonLeaf = !(perm.r || perm.w || perm.x) && perm.v && !perm.pf && !perm.af
4072ea10b44SXiaokun-Pei    val s1_valid = portTranslateEnable(idx) && !onlyS2
408d0de7e4aSpeixiaokun
409d0de7e4aSpeixiaokun    // Stage 2 perm check
410e5831642Speixiaokun    val gpf = g_perm.pf
411db6cfb5aSHaoyuan Feng    val g_ldUpdate = !g_perm.a && isLd
412db6cfb5aSHaoyuan Feng    val g_stUpdate = (!g_perm.a || !g_perm.d) && isSt
413db6cfb5aSHaoyuan Feng    val g_instrUpdate = !g_perm.a && isInst
414*c1eb2883SHaoyuan Feng    val g_ldPermFail = !Mux(hlvx, g_perm.x, (g_perm.r || csr.priv.mxr && g_perm.x))
415d0de7e4aSpeixiaokun    val g_stPermFail = !g_perm.w
416d0de7e4aSpeixiaokun    val g_instrPermFail = !g_perm.x
417db6cfb5aSHaoyuan Feng    val ldGpf = (g_ldPermFail || gpf) && isLd
418db6cfb5aSHaoyuan Feng    val stGpf = (g_stPermFail || gpf) && isSt
419db6cfb5aSHaoyuan Feng    val instrGpf = (g_instrPermFail || gpf) && isInst
42057504f48SHaoyuan Feng    val s2_valid = portTranslateEnable(idx) && (onlyS2 || allS2xlate)
421d0de7e4aSpeixiaokun
422d0de7e4aSpeixiaokun    val fault_valid = s1_valid || s2_valid
423d0de7e4aSpeixiaokun
424c794d992Speixiaokun    // when pf and gpf can't happens simultaneously
4252ea10b44SXiaokun-Pei    val hasPf = (ldPf || ldUpdate || stPf || stUpdate || instrPf || instrUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
426db6cfb5aSHaoyuan Feng    // Only lsu need check related to high address truncation
427db6cfb5aSHaoyuan Feng    when (RegNext(prepf || pregpf || preaf)) {
428ad415ae0SXiaokun-Pei      resp(idx).bits.isForVSnonLeafPTE := false.B
429db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).pf.ld := RegNext(prepf) && isLd
430db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).pf.st := RegNext(prepf) && isSt
431db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).pf.instr := false.B
432db6cfb5aSHaoyuan Feng
433db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).gpf.ld := RegNext(pregpf) && isLd
434db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).gpf.st := RegNext(pregpf) && isSt
435db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).gpf.instr := false.B
436db6cfb5aSHaoyuan Feng
437db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).af.ld := RegNext(preaf) && TlbCmd.isRead(cmd)
438db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).af.st := RegNext(preaf) && TlbCmd.isWrite(cmd)
439db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).af.instr := false.B
44046e9ee74SHaoyuan Feng
44146e9ee74SHaoyuan Feng      resp(idx).bits.excp(nDups).vaNeedExt := false.B
442a94d0abaSHaoyuan Feng      // overwrite miss & gpaddr when exception related to high address truncation happens
443a94d0abaSHaoyuan Feng      resp(idx).bits.miss := false.B
444189833a1SHaoyuan Feng      resp(idx).bits.gpaddr(nDups) := req_out(idx).fullva
445db6cfb5aSHaoyuan Feng    } .otherwise {
446ad415ae0SXiaokun-Pei      // isForVSnonLeafPTE is used only when gpf happens and it caused by a G-stage translation which supports VS-stage translation
447ad415ae0SXiaokun-Pei      // it will be sent to CSR in order to modify the m/htinst.
448ad415ae0SXiaokun-Pei      // Ref: The RISC-V Instruction Set Manual: Volume II: Privileged Architecture - 19.6.3. Transformed Instruction or Pseudoinstruction for mtinst or htinst
449ad415ae0SXiaokun-Pei      val isForVSnonLeafPTE = isNonLeaf || isFakePte
450ad415ae0SXiaokun-Pei      resp(idx).bits.isForVSnonLeafPTE := isForVSnonLeafPTE
4512ea10b44SXiaokun-Pei      resp(idx).bits.excp(nDups).pf.ld := (ldPf || ldUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
4522ea10b44SXiaokun-Pei      resp(idx).bits.excp(nDups).pf.st := (stPf || stUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
4532ea10b44SXiaokun-Pei      resp(idx).bits.excp(nDups).pf.instr := (instrPf || instrUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
454b6982e83SLemover      // NOTE: pf need && with !af, page fault has higher priority than access fault
455b6982e83SLemover      // but ptw may also have access fault, then af happens, the translation is wrong.
456b6982e83SLemover      // In this case, pf has lower priority than af
4576d5ddbceSLemover
458c794d992Speixiaokun      resp(idx).bits.excp(nDups).gpf.ld := (ldGpf || g_ldUpdate) && s2_valid && !af && !hasPf
459c794d992Speixiaokun      resp(idx).bits.excp(nDups).gpf.st := (stGpf || g_stUpdate) && s2_valid && !af && !hasPf
460c794d992Speixiaokun      resp(idx).bits.excp(nDups).gpf.instr := (instrGpf || g_instrUpdate) && s2_valid && !af && !hasPf
461d0de7e4aSpeixiaokun
462f9ac118cSHaoyuan Feng      resp(idx).bits.excp(nDups).af.ld    := af && TlbCmd.isRead(cmd) && fault_valid
463f9ac118cSHaoyuan Feng      resp(idx).bits.excp(nDups).af.st    := af && TlbCmd.isWrite(cmd) && fault_valid
464f9ac118cSHaoyuan Feng      resp(idx).bits.excp(nDups).af.instr := af && TlbCmd.isExec(cmd) && fault_valid
46546e9ee74SHaoyuan Feng
46646e9ee74SHaoyuan Feng      resp(idx).bits.excp(nDups).vaNeedExt := true.B
467db6cfb5aSHaoyuan Feng    }
46846e9ee74SHaoyuan Feng
46946e9ee74SHaoyuan Feng    resp(idx).bits.excp(nDups).isHyper := isHyperInst(idx)
4706d5ddbceSLemover  }
4716d5ddbceSLemover
472f1fe8698SLemover  def handle_nonblock(idx: Int): Unit = {
473f1fe8698SLemover    io.requestor(idx).resp.valid := req_out_v(idx)
474f1fe8698SLemover    io.requestor(idx).req.ready := io.requestor(idx).resp.ready // should always be true
4759930e66fSLemover    XSError(!io.requestor(idx).resp.ready, s"${q.name} port ${idx} is non-block, resp.ready must be true.B")
476cb8f2f2aSLemover
477c3d5cfb3Speixiaokun    val req_need_gpa = hasGpf(idx)
478d0de7e4aSpeixiaokun    val req_s2xlate = Wire(UInt(2.W))
47982978df9Speixiaokun    req_s2xlate := MuxCase(noS2xlate, Seq(
48082e4705bSpeixiaokun      (!(virt_out(idx) || req_out(idx).hyperinst)) -> noS2xlate,
48182e4705bSpeixiaokun      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
48282e4705bSpeixiaokun      (csr.vsatp.mode === 0.U) -> onlyStage2,
48382e4705bSpeixiaokun      (csr.hgatp.mode === 0.U || req_need_gpa) -> onlyStage1
48482978df9Speixiaokun    ))
4854c4af37cSpeixiaokun
486*c1eb2883SHaoyuan Feng    val ptw_just_back = ptw.resp.fire && req_s2xlate === ptw.resp.bits.s2xlate && ptw.resp.bits.hit(get_pn(req_out(idx).vaddr), csr.satp.asid, csr.vsatp.asid, csr.hgatp.vmid, true, false)
4875adc4829SYanqin Li    // TODO: RegNext enable: ptw.resp.valid ? req.valid
4885adc4829SYanqin Li    val ptw_resp_bits_reg = RegEnable(ptw.resp.bits, ptw.resp.valid)
489*c1eb2883SHaoyuan Feng    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), csr.satp.asid, csr.vsatp.asid, csr.hgatp.vmid, allType = true)
490d4078d6eSXiaokun-Pei    val ptw_getGpa = req_need_gpa && hitVec(idx)
491976c97c3SXiaokun-Pei    val need_gpa_vpn_hit = need_gpa_vpn === get_pn(req_out(idx).vaddr)
4924fc3a30cSXu, Zefan
4934fc3a30cSXu, Zefan    io.ptw.req(idx).valid := false.B;
4944fc3a30cSXu, Zefan    io.tlbreplay(idx) := false.B;
4954fc3a30cSXu, Zefan
4964fc3a30cSXu, Zefan    when (req_out_v(idx) && missVec(idx)) {
4974fc3a30cSXu, Zefan      // NOTE: for an miss tlb request: either send a ptw request, or ask for a replay
4984fc3a30cSXu, Zefan      when (ptw_just_back || ptw_already_back) {
4994fc3a30cSXu, Zefan        io.tlbreplay(idx) := true.B;
5004fc3a30cSXu, Zefan      } .elsewhen (need_gpa && !need_gpa_vpn_hit && !resp_gpa_refill) {
5014fc3a30cSXu, Zefan        // not send any unrelated ptw request when l1tlb is in need_gpa state
5024fc3a30cSXu, Zefan        io.tlbreplay(idx) := true.B;
5034fc3a30cSXu, Zefan      } .otherwise {
5044fc3a30cSXu, Zefan        io.ptw.req(idx).valid := true.B;
5054fc3a30cSXu, Zefan      }
5064fc3a30cSXu, Zefan    }
5074fc3a30cSXu, Zefan
5085adc4829SYanqin Li    when (io.requestor(idx).req_kill && GatedValidRegNext(io.requestor(idx).req.fire)) {
509c3b763d0SYinan Xu      io.ptw.req(idx).valid := false.B
510185e6164SHaoyuan Feng      io.tlbreplay(idx) := true.B
511c3b763d0SYinan Xu    }
5124fc3a30cSXu, Zefan
513185e6164SHaoyuan Feng    io.ptw.req(idx).bits.vpn := get_pn(req_out(idx).vaddr)
5144c4af37cSpeixiaokun    io.ptw.req(idx).bits.s2xlate := req_s2xlate
515d4078d6eSXiaokun-Pei    io.ptw.req(idx).bits.getGpa := ptw_getGpa
516185e6164SHaoyuan Feng    io.ptw.req(idx).bits.memidx := req_out(idx).memidx
517149086eaSLemover  }
518a0301c0dSLemover
519f1fe8698SLemover  def handle_block(idx: Int): Unit = {
520f1fe8698SLemover    // three valid: 1.if exist a entry; 2.if sent to ptw; 3.unset resp.valid
521935edac4STang Haojin    io.requestor(idx).req.ready := !req_out_v(idx) || io.requestor(idx).resp.fire
522f1fe8698SLemover    // req_out_v for if there is a request, may long latency, fixme
523f1fe8698SLemover
524f1fe8698SLemover    // miss request entries
525c3d5cfb3Speixiaokun    val req_need_gpa = hasGpf(idx)
526f1fe8698SLemover    val miss_req_vpn = get_pn(req_out(idx).vaddr)
5278744445eSMaxpicca-Li    val miss_req_memidx = req_out(idx).memidx
528d0de7e4aSpeixiaokun    val miss_req_s2xlate = Wire(UInt(2.W))
52982978df9Speixiaokun    miss_req_s2xlate := MuxCase(noS2xlate, Seq(
53082e4705bSpeixiaokun      (!(virt_out(idx) || req_out(idx).hyperinst)) -> noS2xlate,
53182e4705bSpeixiaokun      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
53282e4705bSpeixiaokun      (csr.vsatp.mode === 0.U) -> onlyStage2,
53382e4705bSpeixiaokun      (csr.hgatp.mode === 0.U || req_need_gpa) -> onlyStage1
53482978df9Speixiaokun    ))
5353222d00fSpeixiaokun    val miss_req_s2xlate_reg = RegEnable(miss_req_s2xlate, io.ptw.req(idx).fire)
536c3d5cfb3Speixiaokun    val hasS2xlate = miss_req_s2xlate_reg =/= noS2xlate
537c3d5cfb3Speixiaokun    val onlyS2 = miss_req_s2xlate_reg === onlyStage2
538*c1eb2883SHaoyuan Feng    val hit_s1 = io.ptw.resp.bits.s1.hit(miss_req_vpn, Mux(hasS2xlate, csr.vsatp.asid, csr.satp.asid), csr.hgatp.vmid, allType = true, false, hasS2xlate)
539*c1eb2883SHaoyuan Feng    val hit_s2 = io.ptw.resp.bits.s2.hit(miss_req_vpn, csr.hgatp.vmid)
540c3d5cfb3Speixiaokun    val hit = Mux(onlyS2, hit_s2, hit_s1) && io.ptw.resp.valid && miss_req_s2xlate_reg === io.ptw.resp.bits.s2xlate
541f1fe8698SLemover
5425adc4829SYanqin Li    val new_coming_valid = WireInit(false.B)
5435adc4829SYanqin Li    new_coming_valid := req_in(idx).fire && !req_in(idx).bits.kill && !flush_pipe(idx)
5445adc4829SYanqin Li    val new_coming = GatedValidRegNext(new_coming_valid)
545f1fe8698SLemover    val miss_wire = new_coming && missVec(idx)
546935edac4STang Haojin    val miss_v = ValidHoldBypass(miss_wire, resp(idx).fire, flush_pipe(idx))
547f1fe8698SLemover    val miss_req_v = ValidHoldBypass(miss_wire || (miss_v && flush_mmu && !mmu_flush_pipe),
548935edac4STang Haojin      io.ptw.req(idx).fire || resp(idx).fire, flush_pipe(idx))
549f1fe8698SLemover
550f1fe8698SLemover    // when ptw resp, check if hit, reset miss_v, resp to lsu/ifu
551292bea3fSWilliam Wang    resp(idx).valid := req_out_v(idx) && !(miss_v && portTranslateEnable(idx))
552935edac4STang Haojin    when (io.ptw.resp.fire && hit && req_out_v(idx) && portTranslateEnable(idx)) {
553d0de7e4aSpeixiaokun      val stage1 = io.ptw.resp.bits.s1
554d0de7e4aSpeixiaokun      val stage2 = io.ptw.resp.bits.s2
555d0de7e4aSpeixiaokun      val s2xlate = io.ptw.resp.bits.s2xlate
556f1fe8698SLemover      resp(idx).valid := true.B
557c3d5cfb3Speixiaokun      resp(idx).bits.miss := false.B
558d0de7e4aSpeixiaokun      val s1_paddr = Cat(stage1.genPPN(get_pn(req_out(idx).vaddr)), get_off(req_out(idx).vaddr))
559cda84113Speixiaokun      val s2_paddr = Cat(stage2.genPPNS2(get_pn(req_out(idx).vaddr)), get_off(req_out(idx).vaddr))
56003efd994Shappy-lx      for (d <- 0 until nRespDups) {
56182978df9Speixiaokun        resp(idx).bits.paddr(d) := Mux(s2xlate =/= noS2xlate, s2_paddr, s1_paddr)
562d0de7e4aSpeixiaokun        resp(idx).bits.gpaddr(d) := s1_paddr
563002c10a4SYanqin Li        pbmt_check(idx, d, io.ptw.resp.bits.s1.entry.pbmt, io.ptw.resp.bits.s2.entry.pbmt, s2xlate)
564cca17e78Speixiaokun        perm_check(stage1, req_out(idx).cmd, idx, d, stage2, req_out(idx).hlvx, s2xlate)
56503efd994Shappy-lx      }
56608b0bc30Shappy-lx      pmp_check(resp(idx).bits.paddr(0), req_out(idx).size, req_out(idx).cmd, false.B, idx)
567f1fe8698SLemover
568f1fe8698SLemover      // NOTE: the unfiltered req would be handled by Repeater
569f1fe8698SLemover    }
570f1fe8698SLemover    assert(RegNext(!resp(idx).valid || resp(idx).ready, true.B), "when tlb resp valid, ready should be true, must")
571f1fe8698SLemover    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")
572f1fe8698SLemover
573f1fe8698SLemover    val ptw_req = io.ptw.req(idx)
574f1fe8698SLemover    ptw_req.valid := miss_req_v
575f1fe8698SLemover    ptw_req.bits.vpn := miss_req_vpn
576d0de7e4aSpeixiaokun    ptw_req.bits.s2xlate := miss_req_s2xlate
577a4f9c77fSpeixiaokun    ptw_req.bits.getGpa := req_need_gpa && hitVec(idx)
5788744445eSMaxpicca-Li    ptw_req.bits.memidx := miss_req_memidx
579f1fe8698SLemover
580185e6164SHaoyuan Feng    io.tlbreplay(idx) := false.B
581185e6164SHaoyuan Feng
582f1fe8698SLemover    // NOTE: when flush pipe, tlb should abandon last req
583f1fe8698SLemover    // however, some outside modules like icache, dont care flushPipe, and still waiting for tlb resp
584f1fe8698SLemover    // just resp valid and raise page fault to go through. The pipe(ifu) will abandon it.
585f1fe8698SLemover    if (!q.outsideRecvFlush) {
586292bea3fSWilliam Wang      when (req_out_v(idx) && flush_pipe(idx) && portTranslateEnable(idx)) {
587f1fe8698SLemover        resp(idx).valid := true.B
58803efd994Shappy-lx        for (d <- 0 until nRespDups) {
589002c10a4SYanqin Li          resp(idx).bits.pbmt(d) := 0.U
59003efd994Shappy-lx          resp(idx).bits.excp(d).pf.ld := true.B // sfence happened, pf for not to use this addr
59103efd994Shappy-lx          resp(idx).bits.excp(d).pf.st := true.B
59203efd994Shappy-lx          resp(idx).bits.excp(d).pf.instr := true.B
59303efd994Shappy-lx        }
594f1fe8698SLemover      }
595f1fe8698SLemover    }
596f1fe8698SLemover  }
597cb8f2f2aSLemover
598cb8f2f2aSLemover  // when ptw resp, tlb at refill_idx maybe set to miss by force.
599cb8f2f2aSLemover  // Bypass ptw resp to check.
600d0de7e4aSpeixiaokun  def ptw_resp_bypass(vpn: UInt, s2xlate: UInt) = {
6015adc4829SYanqin Li    // TODO: RegNext enable: ptw.resp.valid
602cca17e78Speixiaokun    val hasS2xlate = s2xlate =/= noS2xlate
603cca17e78Speixiaokun    val onlyS2 = s2xlate === onlyStage2
604c3d5cfb3Speixiaokun    val onlyS1 = s2xlate === onlyStage1
605d0de7e4aSpeixiaokun    val s2xlate_hit = s2xlate === ptw.resp.bits.s2xlate
606*c1eb2883SHaoyuan Feng    val resp_hit = ptw.resp.bits.hit(vpn, csr.satp.asid, csr.vsatp.asid, csr.hgatp.vmid, true, false)
6075adc4829SYanqin Li    val p_hit = GatedValidRegNext(resp_hit && io.ptw.resp.fire && s2xlate_hit)
608d0de7e4aSpeixiaokun    val ppn_s1 = ptw.resp.bits.s1.genPPN(vpn)
609cda84113Speixiaokun    val gvpn = Mux(onlyS2, vpn, ppn_s1)
610cda84113Speixiaokun    val ppn_s2 = ptw.resp.bits.s2.genPPNS2(gvpn)
611242cafeeSXu, Zefan    val p_ppn = RegEnable(Mux(s2xlate === onlyStage2 || s2xlate === allStage, ppn_s2, ppn_s1), io.ptw.resp.fire)
612002c10a4SYanqin Li    val p_pbmt = RegEnable(ptw.resp.bits.s1.entry.pbmt,io.ptw.resp.fire)
613d0de7e4aSpeixiaokun    val p_perm = RegEnable(ptwresp_to_tlbperm(ptw.resp.bits.s1), io.ptw.resp.fire)
6142ea10b44SXiaokun-Pei    val p_gvpn = RegEnable(Mux(onlyS2, ptw.resp.bits.s2.entry.tag, ptw.resp.bits.s1.genGVPN(vpn)), io.ptw.resp.fire)
615002c10a4SYanqin Li    val p_g_pbmt = RegEnable(ptw.resp.bits.s2.entry.pbmt,io.ptw.resp.fire)
616d0de7e4aSpeixiaokun    val p_g_perm = RegEnable(hptwresp_to_tlbperm(ptw.resp.bits.s2), io.ptw.resp.fire)
617d0de7e4aSpeixiaokun    val p_s2xlate = RegEnable(ptw.resp.bits.s2xlate, io.ptw.resp.fire)
618ad8d4021SXiaokun-Pei    val p_s1_level = RegEnable(ptw.resp.bits.s1.entry.level.get, io.ptw.resp.fire)
619ad8d4021SXiaokun-Pei    val p_s1_isLeaf = RegEnable(ptw.resp.bits.s1.isLeaf(), io.ptw.resp.fire)
620ad8d4021SXiaokun-Pei    val p_s1_isFakePte = RegEnable(ptw.resp.bits.s1.isFakePte(), io.ptw.resp.fire)
621ad8d4021SXiaokun-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)
622cb8f2f2aSLemover  }
623cb8f2f2aSLemover
624f1fe8698SLemover  // perf event
6255adc4829SYanqin Li  val result_ok = req_in.map(a => GatedValidRegNext(a.fire))
626f1fe8698SLemover  val perfEvents =
627f1fe8698SLemover    Seq(
628935edac4STang Haojin      ("access", PopCount((0 until Width).map{i => if (Block(i)) io.requestor(i).req.fire else portTranslateEnable(i) && result_ok(i) })),
629935edac4STang Haojin      ("miss  ", PopCount((0 until Width).map{i => if (Block(i)) portTranslateEnable(i) && result_ok(i) && missVec(i) else ptw.req(i).fire })),
630a0301c0dSLemover    )
631f1fe8698SLemover  generatePerfEvent()
632a0301c0dSLemover
633f1fe8698SLemover  // perf log
6346d5ddbceSLemover  for (i <- 0 until Width) {
635f1fe8698SLemover    if (Block(i)) {
636292bea3fSWilliam Wang      XSPerfAccumulate(s"access${i}",result_ok(i) && portTranslateEnable(i))
637f1fe8698SLemover      XSPerfAccumulate(s"miss${i}", result_ok(i) && missVec(i))
6386d5ddbceSLemover    } else {
6395adc4829SYanqin Li      XSPerfAccumulate("first_access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid))
640292bea3fSWilliam Wang      XSPerfAccumulate("access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i))
6415adc4829SYanqin Li      XSPerfAccumulate("first_miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i) && RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid))
642292bea3fSWilliam Wang      XSPerfAccumulate("miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i))
643a0301c0dSLemover    }
6446d5ddbceSLemover  }
645935edac4STang Haojin  XSPerfAccumulate("ptw_resp_count", ptw.resp.fire)
646cca17e78Speixiaokun  XSPerfAccumulate("ptw_resp_pf_count", ptw.resp.fire && ptw.resp.bits.s1.pf)
6476d5ddbceSLemover
6486d5ddbceSLemover  // Log
6496d5ddbceSLemover  for(i <- 0 until Width) {
6506d5ddbceSLemover    XSDebug(req(i).valid, p"req(${i.U}): (${req(i).valid} ${req(i).ready}) ${req(i).bits}\n")
6516d5ddbceSLemover    XSDebug(resp(i).valid, p"resp(${i.U}): (${resp(i).valid} ${resp(i).ready}) ${resp(i).bits}\n")
6526d5ddbceSLemover  }
6536d5ddbceSLemover
654f1fe8698SLemover  XSDebug(io.sfence.valid, p"Sfence: ${io.sfence}\n")
655f1fe8698SLemover  XSDebug(ParallelOR(req_out_v) || ptw.resp.valid, p"vmEnable:${vmEnable} hit:${Binary(VecInit(hitVec).asUInt)} miss:${Binary(VecInit(missVec).asUInt)}\n")
6566d5ddbceSLemover  for (i <- ptw.req.indices) {
657935edac4STang Haojin    XSDebug(ptw.req(i).fire, p"L2TLB req:${ptw.req(i).bits}\n")
6586d5ddbceSLemover  }
65992e3bfefSLemover  XSDebug(ptw.resp.valid, p"L2TLB resp:${ptw.resp.bits} (v:${ptw.resp.valid}r:${ptw.resp.ready}) \n")
6606d5ddbceSLemover
661f9ac118cSHaoyuan Feng  println(s"${q.name}: page: ${q.NWays} ${q.Associative} ${q.Replacer.get}")
662a0301c0dSLemover
6635ab1b84dSHaoyuan Feng  if (env.EnableDifftest) {
6645ab1b84dSHaoyuan Feng    for (i <- 0 until Width) {
6655ab1b84dSHaoyuan 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
666d0de7e4aSpeixiaokun      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
6675ab1b84dSHaoyuan 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
6687d45a146SYinan Xu      val difftest = DifftestModule(new DiffL1TLBEvent)
669254e4960SHaoyuan Feng      difftest.coreid := io.hartId
670d0de7e4aSpeixiaokun      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)
6717d45a146SYinan Xu      if (!Seq("itlb", "ldtlb", "sttlb").contains(q.name)) {
6727d45a146SYinan Xu        difftest.valid := false.B
6737d45a146SYinan Xu      }
6747d45a146SYinan Xu      difftest.index := TLBDiffId(p(XSCoreParamsKey).HartId).U
6755adc4829SYanqin Li      difftest.vpn := RegEnable(get_pn(req_in(i).bits.vaddr), req_in(i).valid)
6767d45a146SYinan Xu      difftest.ppn := get_pn(io.requestor(i).resp.bits.paddr(0))
677*c1eb2883SHaoyuan Feng      difftest.satp := Cat(csr.satp.mode, csr.satp.asid, csr.satp.ppn)
678*c1eb2883SHaoyuan Feng      difftest.vsatp := Cat(csr.vsatp.mode, csr.vsatp.asid, csr.vsatp.ppn)
679*c1eb2883SHaoyuan Feng      difftest.hgatp := Cat(csr.hgatp.mode, csr.hgatp.vmid, csr.hgatp.ppn)
680dd103903Speixiaokun      val req_need_gpa = gpf
681dd103903Speixiaokun      val req_s2xlate = Wire(UInt(2.W))
682dd103903Speixiaokun      req_s2xlate := MuxCase(noS2xlate, Seq(
68382e4705bSpeixiaokun        (!RegNext(virt_in || req_in(i).bits.hyperinst)) -> noS2xlate,
684*c1eb2883SHaoyuan Feng        (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
685*c1eb2883SHaoyuan Feng        (csr.vsatp.mode === 0.U) -> onlyStage2,
686*c1eb2883SHaoyuan Feng        (csr.hgatp.mode === 0.U || req_need_gpa) -> onlyStage1
68782978df9Speixiaokun      ))
688dd103903Speixiaokun      difftest.s2xlate := req_s2xlate
6897d45a146SYinan Xu    }
6905ab1b84dSHaoyuan Feng  }
6915ab1b84dSHaoyuan Feng}
6925ab1b84dSHaoyuan Feng
6937d45a146SYinan Xuobject TLBDiffId {
6947d45a146SYinan Xu  var i: Int = 0
6957d45a146SYinan Xu  var lastHartId: Int = -1
6967d45a146SYinan Xu  def apply(hartId: Int): Int = {
6977d45a146SYinan Xu    if (lastHartId != hartId) {
6987d45a146SYinan Xu      i = 0
6997d45a146SYinan Xu      lastHartId = hartId
7007d45a146SYinan Xu    }
7017d45a146SYinan Xu    i += 1
7027d45a146SYinan Xu    i - 1
7037d45a146SYinan Xu  }
704f1fe8698SLemover}
7051ca0e4f3SYinan Xu
70603efd994Shappy-lxclass TLBNonBlock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(false), q)
70703efd994Shappy-lxclass TLBBLock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(true), q)
7086d5ddbceSLemover
709a0301c0dSLemoverclass TlbReplace(Width: Int, q: TLBParameters)(implicit p: Parameters) extends TlbModule {
710a0301c0dSLemover  val io = IO(new TlbReplaceIO(Width, q))
711a0301c0dSLemover
712f9ac118cSHaoyuan Feng  if (q.Associative == "fa") {
713f9ac118cSHaoyuan Feng    val re = ReplacementPolicy.fromString(q.Replacer, q.NWays)
714f9ac118cSHaoyuan Feng    re.access(io.page.access.map(_.touch_ways))
715f9ac118cSHaoyuan Feng    io.page.refillIdx := re.way
716a0301c0dSLemover  } else { // set-acco && plru
717f9ac118cSHaoyuan Feng    val re = ReplacementPolicy.fromString(q.Replacer, q.NSets, q.NWays)
718f9ac118cSHaoyuan Feng    re.access(io.page.access.map(_.sets), io.page.access.map(_.touch_ways))
719f9ac118cSHaoyuan Feng    io.page.refillIdx := { if (q.NWays == 1) 0.U else re.way(io.page.chosen_set) }
720a0301c0dSLemover  }
721a0301c0dSLemover}
722