xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/TLB.scala (revision 0ca3be60970247caada08e6d323ce77703684fc2)
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)
68c1eb2883SHaoyuan Feng  val csr = DelayN(io.csr, q.fenceDelay)
69d0de7e4aSpeixiaokun
70c1eb2883SHaoyuan Feng  val flush_mmu = sfence.valid || csr.satp.changed || csr.vsatp.changed || csr.hgatp.changed
71c1eb2883SHaoyuan 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))
94c1eb2883SHaoyuan Feng  val sum = (0 until Width).map(i => Mux(virt_out(i) || isHyperInst(i), csr.priv.vsum, csr.priv.sum))
95c1eb2883SHaoyuan 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
119c1eb2883SHaoyuan Feng  val Sv39Enable = csr.satp.mode === 8.U
120c1eb2883SHaoyuan Feng  val Sv48Enable = csr.satp.mode === 9.U
121e6595665SXu, Zefan  val Sv39vsEnable = csr.vsatp.mode === 8.U
122e6595665SXu, Zefan  val Sv48vsEnable = csr.vsatp.mode === 9.U
123e6595665SXu, Zefan  val Sv39x4Enable = csr.hgatp.mode === 8.U
124e6595665SXu, Zefan  val Sv48x4Enable = csr.hgatp.mode === 9.U
125e6595665SXu, Zefan
1260841a83fSXuan Hu  val vmEnable = (0 until Width).map(i => !(isHyperInst(i) || virt_out(i)) && (
1273ea4388cSHaoyuan Feng    if (EnbaleTlbDebug) (Sv39Enable || Sv48Enable)
1283ea4388cSHaoyuan Feng    else (Sv39Enable || Sv48Enable) && (mode(i) < ModeM))
1290841a83fSXuan Hu  )
130e6595665SXu, Zefan  val s2xlateEnable = (0 until Width).map(i =>
131e6595665SXu, Zefan    (isHyperInst(i) || virt_out(i)) &&
132e6595665SXu, Zefan    (Sv39vsEnable || Sv48vsEnable || Sv39x4Enable || Sv48x4Enable) &&
133e6595665SXu, Zefan    (mode(i) < ModeM)
134e6595665SXu, Zefan  )
1355adc4829SYanqin Li  val portTranslateEnable = (0 until Width).map(i => (vmEnable(i) || s2xlateEnable(i)) && RegEnable(!req(i).bits.no_translate, req(i).valid))
1366d5ddbceSLemover
137db6cfb5aSHaoyuan Feng  // pre fault: check fault before real do translate
138db6cfb5aSHaoyuan Feng  val prepf = WireInit(VecInit(Seq.fill(Width)(false.B)))
139db6cfb5aSHaoyuan Feng  val pregpf = WireInit(VecInit(Seq.fill(Width)(false.B)))
140db6cfb5aSHaoyuan Feng  val preaf = WireInit(VecInit(Seq.fill(Width)(false.B)))
141189833a1SHaoyuan Feng  val premode = (0 until Width).map(i => Mux(req_in(i).bits.hyperinst, csr.priv.spvp, mode_tmp))
142189833a1SHaoyuan Feng  for (i <- 0 until Width) {
143189833a1SHaoyuan Feng    resp(i).bits.fullva := RegEnable(EffectiveVa(i), req(i).valid)
144189833a1SHaoyuan Feng  }
14509223e00SHaoyuan Feng  val prevmEnable = (0 until Width).map(i => !(virt_in || req_in(i).bits.hyperinst) && (
14609223e00SHaoyuan Feng    if (EnbaleTlbDebug) (Sv39Enable || Sv48Enable)
147189833a1SHaoyuan Feng    else (Sv39Enable || Sv48Enable) && (premode(i) < ModeM))
14809223e00SHaoyuan Feng  )
149e6595665SXu, Zefan  val pres2xlateEnable = (0 until Width).map(i =>
150e6595665SXu, Zefan    (virt_in || req_in(i).bits.hyperinst) &&
151e6595665SXu, Zefan    (Sv39vsEnable || Sv48vsEnable || Sv39x4Enable || Sv48x4Enable) &&
152e6595665SXu, Zefan    (premode(i) < ModeM)
153e6595665SXu, Zefan  )
154189833a1SHaoyuan Feng
155db6cfb5aSHaoyuan Feng  (0 until Width).foreach{i =>
156189833a1SHaoyuan Feng
157189833a1SHaoyuan Feng    val pmm = WireInit(0.U(2.W))
158189833a1SHaoyuan Feng
159189833a1SHaoyuan Feng    when (ifetch || req(i).bits.hlvx) {
160189833a1SHaoyuan Feng      pmm := 0.U
161189833a1SHaoyuan Feng    } .elsewhen (premode(i) === ModeM) {
162189833a1SHaoyuan Feng      pmm := csr.pmm.mseccfg
163189833a1SHaoyuan Feng    } .elsewhen (!(virt_in || req_in(i).bits.hyperinst) && premode(i) === ModeS) {
164189833a1SHaoyuan Feng      pmm := csr.pmm.menvcfg
165189833a1SHaoyuan Feng    } .elsewhen ((virt_in || req_in(i).bits.hyperinst) && premode(i) === ModeS) {
166189833a1SHaoyuan Feng      pmm := csr.pmm.henvcfg
167189833a1SHaoyuan Feng    } .elsewhen (req_in(i).bits.hyperinst && csr.priv.imode === ModeU) {
168189833a1SHaoyuan Feng      pmm := csr.pmm.hstatus
169189833a1SHaoyuan Feng    } .elsewhen (premode(i) === ModeU) {
170189833a1SHaoyuan Feng      pmm := csr.pmm.senvcfg
171189833a1SHaoyuan Feng    }
172189833a1SHaoyuan Feng
173c1eb2883SHaoyuan Feng    when (prevmEnable(i) || (pres2xlateEnable(i) && csr.vsatp.mode =/= 0.U)) {
174189833a1SHaoyuan Feng      when (pmm === PMLEN7) {
175189833a1SHaoyuan Feng        EffectiveVa(i) := SignExt(req_in(i).bits.fullva(56, 0), XLEN)
176189833a1SHaoyuan Feng      } .elsewhen (pmm === PMLEN16) {
177189833a1SHaoyuan Feng        EffectiveVa(i) := SignExt(req_in(i).bits.fullva(47, 0), XLEN)
178189833a1SHaoyuan Feng      } .otherwise {
179189833a1SHaoyuan Feng        EffectiveVa(i) := req_in(i).bits.fullva
180189833a1SHaoyuan Feng      }
181189833a1SHaoyuan Feng    } .otherwise {
182189833a1SHaoyuan Feng      when (pmm === PMLEN7) {
183189833a1SHaoyuan Feng        EffectiveVa(i) := ZeroExt(req_in(i).bits.fullva(56, 0), XLEN)
184189833a1SHaoyuan Feng      } .elsewhen (pmm === PMLEN16) {
185189833a1SHaoyuan Feng        EffectiveVa(i) := ZeroExt(req_in(i).bits.fullva(47, 0), XLEN)
186189833a1SHaoyuan Feng      } .otherwise {
187189833a1SHaoyuan Feng        EffectiveVa(i) := req_in(i).bits.fullva
188189833a1SHaoyuan Feng      }
189189833a1SHaoyuan Feng    }
190189833a1SHaoyuan Feng
191189833a1SHaoyuan Feng    val pf48 = SignExt(EffectiveVa(i)(47, 0), XLEN) =/= EffectiveVa(i)
192189833a1SHaoyuan Feng    val pf39 = SignExt(EffectiveVa(i)(38, 0), XLEN) =/= EffectiveVa(i)
193189833a1SHaoyuan Feng    val gpf48 = EffectiveVa(i)(XLEN - 1, 48 + 2) =/= 0.U
194189833a1SHaoyuan Feng    val gpf39 = EffectiveVa(i)(XLEN - 1, 39 + 2) =/= 0.U
195189833a1SHaoyuan Feng    val af = EffectiveVa(i)(XLEN - 1, PAddrBits) =/= 0.U
196db6cfb5aSHaoyuan Feng    when (req(i).valid && req(i).bits.checkfullva) {
19709223e00SHaoyuan Feng      when (prevmEnable(i) || pres2xlateEnable(i)) {
198db6cfb5aSHaoyuan Feng        when (req_in_s2xlate(i) === onlyStage2) {
199db6cfb5aSHaoyuan Feng          when (Sv48x4Enable) {
200db6cfb5aSHaoyuan Feng            pregpf(i) := gpf48
201db6cfb5aSHaoyuan Feng          } .elsewhen (Sv39x4Enable) {
202db6cfb5aSHaoyuan Feng            pregpf(i) := gpf39
203db6cfb5aSHaoyuan Feng          }
204e6595665SXu, Zefan        } .elsewhen (req_in_s2xlate(i) === onlyStage1 || req_in_s2xlate(i) === allStage) {
205e6595665SXu, Zefan          when (Sv48vsEnable) {
206e6595665SXu, Zefan            prepf(i) := pf48
207e6595665SXu, Zefan          } .elsewhen (Sv39vsEnable) {
208e6595665SXu, Zefan            prepf(i) := pf39
209e6595665SXu, Zefan          }
210e6595665SXu, Zefan        } .otherwise { // noS2xlate
211db6cfb5aSHaoyuan Feng          when (Sv48Enable) {
212db6cfb5aSHaoyuan Feng            prepf(i) := pf48
213db6cfb5aSHaoyuan Feng          } .elsewhen (Sv39Enable) {
214db6cfb5aSHaoyuan Feng            prepf(i) := pf39
215db6cfb5aSHaoyuan Feng          }
216db6cfb5aSHaoyuan Feng        }
217db6cfb5aSHaoyuan Feng      } .otherwise {
218db6cfb5aSHaoyuan Feng        preaf(i) := af
219db6cfb5aSHaoyuan Feng      }
220db6cfb5aSHaoyuan Feng    }
221db6cfb5aSHaoyuan Feng  }
2226d5ddbceSLemover
223e9ba7f28SHaoyuan Feng  val refill = ptw.resp.fire && !(ptw.resp.bits.getGpa) && !need_gpa && !need_gpa_wire && !flush_mmu
2244fc3a30cSXu, Zefan  // prevent ptw refill when: 1) it's a getGpa request; 2) l1tlb is in need_gpa state; 3) mmu is being flushed.
2254fc3a30cSXu, Zefan
226eb4bf3f2Speixiaokun  refill_to_mem := DontCare
22703efd994Shappy-lx  val entries = Module(new TlbStorageWrapper(Width, q, nRespDups))
228c1eb2883SHaoyuan Feng  entries.io.base_connect(sfence, csr, csr.satp)
229f1fe8698SLemover  if (q.outReplace) { io.replace <> entries.io.replace }
2306d5ddbceSLemover  for (i <- 0 until Width) {
231ffa711ffSpeixiaokun    entries.io.r_req_apply(io.requestor(i).req.valid, get_pn(req_in(i).bits.vaddr), i, req_in_s2xlate(i))
232ec159517SXiaokun-Pei    entries.io.w_apply(refill, ptw.resp.bits)
2335adc4829SYanqin Li    // TODO: RegNext enable:req.valid
2345adc4829SYanqin Li    resp(i).bits.debug.isFirstIssue := RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid)
2355adc4829SYanqin Li    resp(i).bits.debug.robIdx := RegEnable(req(i).bits.debug.robIdx, req(i).valid)
236a0301c0dSLemover  }
237e9027bcdSpeixiaokun
238f1fe8698SLemover  // read TLB, get hit/miss, paddr, perm bits
239f1fe8698SLemover  val readResult = (0 until Width).map(TLBRead(_))
240f1fe8698SLemover  val hitVec = readResult.map(_._1)
241f1fe8698SLemover  val missVec = readResult.map(_._2)
242f1fe8698SLemover  val pmp_addr = readResult.map(_._3)
243f9ac118cSHaoyuan Feng  val perm = readResult.map(_._4)
2443106de0aSpeixiaokun  val g_perm = readResult.map(_._5)
245002c10a4SYanqin Li  val pbmt = readResult.map(_._6)
246002c10a4SYanqin Li  val g_pbmt = readResult.map(_._7)
247f1fe8698SLemover  // check pmp use paddr (for timing optization, use pmp_addr here)
248f1fe8698SLemover  // check permisson
249f1fe8698SLemover  (0 until Width).foreach{i =>
25008b0bc30Shappy-lx    val noTranslateReg = RegNext(req(i).bits.no_translate)
25108b0bc30Shappy-lx    val addr = Mux(noTranslateReg, req(i).bits.pmp_addr, pmp_addr(i))
25208b0bc30Shappy-lx    pmp_check(addr, req_out(i).size, req_out(i).cmd, noTranslateReg, i)
25303efd994Shappy-lx    for (d <- 0 until nRespDups) {
254002c10a4SYanqin Li      pbmt_check(i, d, pbmt(i)(d), g_pbmt(i)(d), req_out_s2xlate(i))
255db6cfb5aSHaoyuan 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))
25603efd994Shappy-lx    }
2577acf8b76SXiaokun-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)
258f1fe8698SLemover  }
2596d5ddbceSLemover
260f1fe8698SLemover  // handle block or non-block io
261f1fe8698SLemover  // for non-block io, just return the above result, send miss to ptw
262f1fe8698SLemover  // for block io, hold the request, send miss to ptw,
263f1fe8698SLemover  //   when ptw back, return the result
264f1fe8698SLemover  (0 until Width) foreach {i =>
265f1fe8698SLemover    if (Block(i)) handle_block(i)
266f1fe8698SLemover    else handle_nonblock(i)
267f1fe8698SLemover  }
268f1fe8698SLemover  io.ptw.resp.ready := true.B
269a0301c0dSLemover
270f1fe8698SLemover  /************************  main body above | method/log/perf below ****************************/
271f1fe8698SLemover  def TLBRead(i: Int) = {
272002c10a4SYanqin Li    val (e_hit, e_ppn, e_perm, e_g_perm, e_s2xlate, e_pbmt, e_g_pbmt) = entries.io.r_resp_apply(i)
273ad8d4021SXiaokun-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))
274292bea3fSWilliam Wang    val enable = portTranslateEnable(i)
275f86480a7Speixiaokun    val isOnlys2xlate = req_out_s2xlate(i) === onlyStage2
2769cb05b4dSXiaokun-Pei    val need_gpa_vpn_hit = need_gpa_vpn === get_pn(req_out(i).vaddr)
277a4f9c77fSpeixiaokun    val isitlb = TlbCmd.isExec(req_out(i).cmd)
2788a4dab4dSHaoyuan Feng    val isPrefetch = req_out(i).isPrefetch
2798a4dab4dSHaoyuan Feng    val currentRedirect = req_out(i).debug.robIdx.needFlush(redirect)
2808a4dab4dSHaoyuan Feng    val lastCycleRedirect = req_out(i).debug.robIdx.needFlush(RegNext(redirect))
281a4f9c77fSpeixiaokun
282a4f9c77fSpeixiaokun    when (!isitlb && need_gpa_robidx.needFlush(redirect) || isitlb && flush_pipe(i)){
283a4f9c77fSpeixiaokun      need_gpa := false.B
284a4f9c77fSpeixiaokun      resp_gpa_refill := false.B
285a4f9c77fSpeixiaokun      need_gpa_vpn := 0.U
2868a4dab4dSHaoyuan 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) {
287e9ba7f28SHaoyuan Feng      need_gpa_wire := true.B
288c3d5cfb3Speixiaokun      need_gpa := true.B
2893106de0aSpeixiaokun      need_gpa_vpn := get_pn(req_out(i).vaddr)
2903106de0aSpeixiaokun      resp_gpa_refill := false.B
291a4f9c77fSpeixiaokun      need_gpa_robidx := req_out(i).debug.robIdx
2929cb05b4dSXiaokun-Pei    }.elsewhen (ptw.resp.fire && need_gpa && need_gpa_vpn === ptw.resp.bits.getVpn(need_gpa_vpn)) {
2932ea10b44SXiaokun-Pei      resp_gpa_gvpn := Mux(ptw.resp.bits.s2xlate === onlyStage2, ptw.resp.bits.s2.entry.tag, ptw.resp.bits.s1.genGVPN(need_gpa_vpn))
294ad8d4021SXiaokun-Pei      resp_s1_level := ptw.resp.bits.s1.entry.level.get
295ad8d4021SXiaokun-Pei      resp_s1_isLeaf := ptw.resp.bits.s1.isLeaf()
296ad8d4021SXiaokun-Pei      resp_s1_isFakePte := ptw.resp.bits.s1.isFakePte()
2973106de0aSpeixiaokun      resp_gpa_refill := true.B
2983106de0aSpeixiaokun    }
2993106de0aSpeixiaokun
3009cb05b4dSXiaokun-Pei    when (req_out_v(i) && hasGpf(i) && resp_gpa_refill && need_gpa_vpn_hit){
301c3d5cfb3Speixiaokun      need_gpa := false.B
302c3d5cfb3Speixiaokun    }
303c3d5cfb3Speixiaokun
304cb8f2f2aSLemover    val hit = e_hit || p_hit
3058a4dab4dSHaoyuan Feng    val miss = (!hit && enable) || hasGpf(i) && !p_hit && !(resp_gpa_refill && need_gpa_vpn_hit) && !isOnlys2xlate && !isPrefetch && !lastCycleRedirect
306f1fe8698SLemover    hit.suggestName(s"hit_read_${i}")
307f1fe8698SLemover    miss.suggestName(s"miss_read_${i}")
3086d5ddbceSLemover
309f1fe8698SLemover    val vaddr = SignExt(req_out(i).vaddr, PAddrBits)
310f1fe8698SLemover    resp(i).bits.miss := miss
311935edac4STang Haojin    resp(i).bits.ptwBack := ptw.resp.fire
3125adc4829SYanqin Li    resp(i).bits.memidx := RegEnable(req_in(i).bits.memidx, req_in(i).valid)
31308b0bc30Shappy-lx    resp(i).bits.fastMiss := !hit && enable
3146d5ddbceSLemover
31503efd994Shappy-lx    val ppn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ppnLen.W))))
316002c10a4SYanqin Li    val pbmt = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePbmtLen.W))))
31703efd994Shappy-lx    val perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle))))
318faf7d50bSXiaokun-Pei    val gvpn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePPNLen.W))))
319ad8d4021SXiaokun-Pei    val level = WireInit(VecInit(Seq.fill(nRespDups)(0.U(log2Up(Level + 1).W))))
320ad8d4021SXiaokun-Pei    val isLeaf = WireInit(VecInit(Seq.fill(nRespDups)(false.B)))
321ad8d4021SXiaokun-Pei    val isFakePte = WireInit(VecInit(Seq.fill(nRespDups)(false.B)))
322002c10a4SYanqin Li    val g_pbmt = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ptePbmtLen.W))))
323d0de7e4aSpeixiaokun    val g_perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle))))
32450c7aa78Speixiaokun    val r_s2xlate = WireInit(VecInit(Seq.fill(nRespDups)(0.U(2.W))))
32503efd994Shappy-lx    for (d <- 0 until nRespDups) {
32603efd994Shappy-lx      ppn(d) := Mux(p_hit, p_ppn, e_ppn(d))
327002c10a4SYanqin Li      pbmt(d) := Mux(p_hit, p_pbmt, e_pbmt(d))
32803efd994Shappy-lx      perm(d) := Mux(p_hit, p_perm, e_perm(d))
329ad8d4021SXiaokun-Pei      gvpn(d) :=  Mux(p_hit, p_gvpn, resp_gpa_gvpn)
330ad8d4021SXiaokun-Pei      level(d) := Mux(p_hit, p_s1_level, resp_s1_level)
331ad8d4021SXiaokun-Pei      isLeaf(d) := Mux(p_hit, p_s1_isLeaf, resp_s1_isLeaf)
332ad8d4021SXiaokun-Pei      isFakePte(d) := Mux(p_hit, p_s1_isFakePte, resp_s1_isFakePte)
333002c10a4SYanqin Li      g_pbmt(d) := Mux(p_hit, p_g_pbmt, e_g_pbmt(d))
334d0de7e4aSpeixiaokun      g_perm(d) := Mux(p_hit, p_g_perm, e_g_perm(d))
33550c7aa78Speixiaokun      r_s2xlate(d) := Mux(p_hit, p_s2xlate, e_s2xlate(d))
33603efd994Shappy-lx      val paddr = Cat(ppn(d), get_off(req_out(i).vaddr))
337ad8d4021SXiaokun-Pei      val vpn_idx = Mux1H(Seq(
338c1eb2883SHaoyuan Feng        (isFakePte(d) && csr.vsatp.mode === Sv39) -> 2.U,
339c1eb2883SHaoyuan Feng        (isFakePte(d) && csr.vsatp.mode === Sv48) -> 3.U,
340ad8d4021SXiaokun-Pei        (!isFakePte(d)) -> (level(d) - 1.U),
341ad8d4021SXiaokun-Pei      ))
3427eef70ffSgood-circle      // We use `fullva` here when `isLeaf`, in order to cope with the situation of an unaligned load/store cross page
3437eef70ffSgood-circle      // for example, a `ld` instruction on address 0x81000ffb will be splited into two loads
3447eef70ffSgood-circle      // 1. ld 0x81000ff8. vaddr = 0x81000ff8, fullva = 0x80000ffb
3457eef70ffSgood-circle      // 2. ld 0x81001000. vaddr = 0x81001000, fullva = 0x80000ffb
3467eef70ffSgood-circle      // When load 1 trigger a guest page fault, we should use offset of fullva when generate gpaddr
3477eef70ffSgood-circle      // and when load 2 trigger a guest page fault, we should just use offset of vaddr(all zero).
348e80f666eSHaoyuan Feng      // Also, when onlyS2, if crosspage, gpaddr = vaddr(start address of a new page), else gpaddr = fullva(original vaddr)
349e3e0af7dSXu, Zefan      // By the way, frontend handles the cross page instruction fetch by itself, so TLB doesn't need to do anything extra.
350e3e0af7dSXu, Zefan      // Also, the fullva of iTLB is not used and always zero. crossPageVaddr should never use fullva in iTLB.
351e3e0af7dSXu, Zefan      val crossPageVaddr = Mux(isitlb || req_out(i).fullva(12) =/= vaddr(12), vaddr, req_out(i).fullva)
352e80f666eSHaoyuan Feng      val gpaddr_offset = Mux(isLeaf(d), get_off(crossPageVaddr), Cat(getVpnn(get_pn(crossPageVaddr), vpn_idx), 0.U(log2Up(XLEN/8).W)))
353ad8d4021SXiaokun-Pei      val gpaddr = Cat(gvpn(d), gpaddr_offset)
354292bea3fSWilliam Wang      resp(i).bits.paddr(d) := Mux(enable, paddr, vaddr)
355e80f666eSHaoyuan Feng      resp(i).bits.gpaddr(d) := Mux(r_s2xlate(d) === onlyStage2, crossPageVaddr, gpaddr)
35603efd994Shappy-lx    }
35703efd994Shappy-lx
35803efd994Shappy-lx    XSDebug(req_out_v(i), p"(${i.U}) hit:${hit} miss:${miss} ppn:${Hexadecimal(ppn(0))} perm:${perm(0)}\n")
35903efd994Shappy-lx
360f9ac118cSHaoyuan Feng    val pmp_paddr = resp(i).bits.paddr(0)
361f1fe8698SLemover
362002c10a4SYanqin Li    (hit, miss, pmp_paddr, perm, g_perm, pbmt, g_pbmt)
363f1fe8698SLemover  }
364f1fe8698SLemover
365ad8d4021SXiaokun-Pei  def getVpnn(vpn: UInt, idx: UInt): UInt = {
366ad8d4021SXiaokun-Pei    MuxLookup(idx, 0.U)(Seq(
367ad8d4021SXiaokun-Pei      0.U -> vpn(vpnnLen - 1, 0),
368ad8d4021SXiaokun-Pei      1.U -> vpn(vpnnLen * 2 - 1, vpnnLen),
369ad8d4021SXiaokun-Pei      2.U -> vpn(vpnnLen * 3 - 1, vpnnLen * 2),
370ad8d4021SXiaokun-Pei      3.U -> vpn(vpnnLen * 4 - 1, vpnnLen * 3))
371ad8d4021SXiaokun-Pei    )
372ad8d4021SXiaokun-Pei  }
373ad8d4021SXiaokun-Pei
37408b0bc30Shappy-lx  def pmp_check(addr: UInt, size: UInt, cmd: UInt, noTranslate: Bool, idx: Int): Unit = {
37508b0bc30Shappy-lx    pmp(idx).valid := resp(idx).valid || noTranslate
376f1fe8698SLemover    pmp(idx).bits.addr := addr
377f1fe8698SLemover    pmp(idx).bits.size := size
378f1fe8698SLemover    pmp(idx).bits.cmd := cmd
379f1fe8698SLemover  }
380f1fe8698SLemover
381002c10a4SYanqin Li  def pbmt_check(idx: Int, d: Int, pbmt: UInt, g_pbmt: UInt, s2xlate: UInt):Unit = {
382002c10a4SYanqin Li    val onlyS1 = s2xlate === onlyStage1 || s2xlate === noS2xlate
383e11ec86cSYanqin Li    val pbmtRes = pbmt
384e11ec86cSYanqin Li    val gpbmtRes = g_pbmt
3853adbf906SYanqin Li    val res = MuxLookup(s2xlate, 0.U)(Seq(
386dd286b6aSYanqin Li      onlyStage1 -> pbmtRes,
387dd286b6aSYanqin Li      onlyStage2 -> gpbmtRes,
388dd286b6aSYanqin Li      allStage -> Mux(pbmtRes =/= 0.U, pbmtRes, gpbmtRes),
389dd286b6aSYanqin Li      noS2xlate -> pbmtRes
3903adbf906SYanqin Li    ))
3913adbf906SYanqin Li    resp(idx).bits.pbmt(d) := Mux(portTranslateEnable(idx), res, 0.U)
392002c10a4SYanqin Li  }
393002c10a4SYanqin Li
3945b7ef044SLemover  // for timing optimization, pmp check is divided into dynamic and static
395db6cfb5aSHaoyuan 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) = {
3965b7ef044SLemover    // dynamic: superpage (or full-connected reg entries) -> check pmp when translation done
3975b7ef044SLemover    // static: 4K pages (or sram entries) -> check pmp with pre-checked results
398c3d5cfb3Speixiaokun    val hasS2xlate = s2xlate =/= noS2xlate
399cfa0c506SXiaokun-Pei    val onlyS1 = s2xlate === onlyStage1
40007f77bf0Speixiaokun    val onlyS2 = s2xlate === onlyStage2
40157504f48SHaoyuan Feng    val allS2xlate = s2xlate === allStage
40257504f48SHaoyuan Feng    // noS2xlate || onlyS1 -> perm.af
40357504f48SHaoyuan Feng    // onlyS2 -> g_perm.af
40457504f48SHaoyuan Feng    // allS2xlate -> perm.af || g_perm.af
40557504f48SHaoyuan Feng    val af = (!onlyS2 && perm.af) || ((onlyS2 || allS2xlate) && g_perm.af)
406d0de7e4aSpeixiaokun
407d0de7e4aSpeixiaokun    // Stage 1 perm check
408e5831642Speixiaokun    val pf = perm.pf
409db6cfb5aSHaoyuan Feng    val isLd = TlbCmd.isRead(cmd) && !TlbCmd.isAmo(cmd)
410db6cfb5aSHaoyuan Feng    val isSt = TlbCmd.isWrite(cmd) || TlbCmd.isAmo(cmd)
411db6cfb5aSHaoyuan Feng    val isInst = TlbCmd.isExec(cmd)
412db6cfb5aSHaoyuan Feng    val ldUpdate = !perm.a && isLd // update A/D through exception
413db6cfb5aSHaoyuan Feng    val stUpdate = (!perm.a || !perm.d) && isSt // update A/D through exception
414db6cfb5aSHaoyuan Feng    val instrUpdate = !perm.a && isInst // update A/D through exception
415189833a1SHaoyuan Feng    val modeCheck = !(mode(idx) === ModeU && !perm.u || mode(idx) === ModeS && perm.u && (!sum(idx) || ifetch))
416e5831642Speixiaokun    val ldPermFail = !(modeCheck && Mux(hlvx, perm.x, perm.r || mxr(idx) && perm.x))
417a79fef67Swakafa    val stPermFail = !(modeCheck && perm.w)
418a79fef67Swakafa    val instrPermFail = !(modeCheck && perm.x)
419db6cfb5aSHaoyuan Feng    val ldPf = (ldPermFail || pf) && isLd
420db6cfb5aSHaoyuan Feng    val stPf = (stPermFail || pf) && isSt
421db6cfb5aSHaoyuan Feng    val instrPf = (instrPermFail || pf) && isInst
422ad415ae0SXiaokun-Pei    val isFakePte = !perm.v && !perm.pf && !perm.af && !onlyS2
4232ea10b44SXiaokun-Pei    val isNonLeaf = !(perm.r || perm.w || perm.x) && perm.v && !perm.pf && !perm.af
4242ea10b44SXiaokun-Pei    val s1_valid = portTranslateEnable(idx) && !onlyS2
425d0de7e4aSpeixiaokun
426d0de7e4aSpeixiaokun    // Stage 2 perm check
427e5831642Speixiaokun    val gpf = g_perm.pf
428db6cfb5aSHaoyuan Feng    val g_ldUpdate = !g_perm.a && isLd
429db6cfb5aSHaoyuan Feng    val g_stUpdate = (!g_perm.a || !g_perm.d) && isSt
430db6cfb5aSHaoyuan Feng    val g_instrUpdate = !g_perm.a && isInst
431c1eb2883SHaoyuan Feng    val g_ldPermFail = !Mux(hlvx, g_perm.x, (g_perm.r || csr.priv.mxr && g_perm.x))
432d0de7e4aSpeixiaokun    val g_stPermFail = !g_perm.w
433d0de7e4aSpeixiaokun    val g_instrPermFail = !g_perm.x
434db6cfb5aSHaoyuan Feng    val ldGpf = (g_ldPermFail || gpf) && isLd
435db6cfb5aSHaoyuan Feng    val stGpf = (g_stPermFail || gpf) && isSt
436db6cfb5aSHaoyuan Feng    val instrGpf = (g_instrPermFail || gpf) && isInst
43757504f48SHaoyuan Feng    val s2_valid = portTranslateEnable(idx) && (onlyS2 || allS2xlate)
438d0de7e4aSpeixiaokun
439d0de7e4aSpeixiaokun    val fault_valid = s1_valid || s2_valid
440d0de7e4aSpeixiaokun
441c794d992Speixiaokun    // when pf and gpf can't happens simultaneously
4422ea10b44SXiaokun-Pei    val hasPf = (ldPf || ldUpdate || stPf || stUpdate || instrPf || instrUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
443db6cfb5aSHaoyuan Feng    // Only lsu need check related to high address truncation
444db6cfb5aSHaoyuan Feng    when (RegNext(prepf || pregpf || preaf)) {
445ad415ae0SXiaokun-Pei      resp(idx).bits.isForVSnonLeafPTE := false.B
446db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).pf.ld := RegNext(prepf) && isLd
447db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).pf.st := RegNext(prepf) && isSt
448db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).pf.instr := false.B
449db6cfb5aSHaoyuan Feng
450db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).gpf.ld := RegNext(pregpf) && isLd
451db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).gpf.st := RegNext(pregpf) && isSt
452db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).gpf.instr := false.B
453db6cfb5aSHaoyuan Feng
454db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).af.ld := RegNext(preaf) && TlbCmd.isRead(cmd)
455db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).af.st := RegNext(preaf) && TlbCmd.isWrite(cmd)
456db6cfb5aSHaoyuan Feng      resp(idx).bits.excp(nDups).af.instr := false.B
45746e9ee74SHaoyuan Feng
45846e9ee74SHaoyuan Feng      resp(idx).bits.excp(nDups).vaNeedExt := false.B
459a94d0abaSHaoyuan Feng      // overwrite miss & gpaddr when exception related to high address truncation happens
460a94d0abaSHaoyuan Feng      resp(idx).bits.miss := false.B
461189833a1SHaoyuan Feng      resp(idx).bits.gpaddr(nDups) := req_out(idx).fullva
462db6cfb5aSHaoyuan Feng    } .otherwise {
463ad415ae0SXiaokun-Pei      // isForVSnonLeafPTE is used only when gpf happens and it caused by a G-stage translation which supports VS-stage translation
464ad415ae0SXiaokun-Pei      // it will be sent to CSR in order to modify the m/htinst.
465ad415ae0SXiaokun-Pei      // Ref: The RISC-V Instruction Set Manual: Volume II: Privileged Architecture - 19.6.3. Transformed Instruction or Pseudoinstruction for mtinst or htinst
466ad415ae0SXiaokun-Pei      val isForVSnonLeafPTE = isNonLeaf || isFakePte
467ad415ae0SXiaokun-Pei      resp(idx).bits.isForVSnonLeafPTE := isForVSnonLeafPTE
4682ea10b44SXiaokun-Pei      resp(idx).bits.excp(nDups).pf.ld := (ldPf || ldUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
4692ea10b44SXiaokun-Pei      resp(idx).bits.excp(nDups).pf.st := (stPf || stUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
4702ea10b44SXiaokun-Pei      resp(idx).bits.excp(nDups).pf.instr := (instrPf || instrUpdate) && s1_valid && !af && !isFakePte && !isNonLeaf
471b6982e83SLemover      // NOTE: pf need && with !af, page fault has higher priority than access fault
472b6982e83SLemover      // but ptw may also have access fault, then af happens, the translation is wrong.
473b6982e83SLemover      // In this case, pf has lower priority than af
4746d5ddbceSLemover
475c794d992Speixiaokun      resp(idx).bits.excp(nDups).gpf.ld := (ldGpf || g_ldUpdate) && s2_valid && !af && !hasPf
476c794d992Speixiaokun      resp(idx).bits.excp(nDups).gpf.st := (stGpf || g_stUpdate) && s2_valid && !af && !hasPf
477c794d992Speixiaokun      resp(idx).bits.excp(nDups).gpf.instr := (instrGpf || g_instrUpdate) && s2_valid && !af && !hasPf
478d0de7e4aSpeixiaokun
479f9ac118cSHaoyuan Feng      resp(idx).bits.excp(nDups).af.ld    := af && TlbCmd.isRead(cmd) && fault_valid
480f9ac118cSHaoyuan Feng      resp(idx).bits.excp(nDups).af.st    := af && TlbCmd.isWrite(cmd) && fault_valid
481f9ac118cSHaoyuan Feng      resp(idx).bits.excp(nDups).af.instr := af && TlbCmd.isExec(cmd) && fault_valid
48246e9ee74SHaoyuan Feng
48346e9ee74SHaoyuan Feng      resp(idx).bits.excp(nDups).vaNeedExt := true.B
484db6cfb5aSHaoyuan Feng    }
48546e9ee74SHaoyuan Feng
48646e9ee74SHaoyuan Feng    resp(idx).bits.excp(nDups).isHyper := isHyperInst(idx)
4876d5ddbceSLemover  }
4886d5ddbceSLemover
489f1fe8698SLemover  def handle_nonblock(idx: Int): Unit = {
490f1fe8698SLemover    io.requestor(idx).resp.valid := req_out_v(idx)
491f1fe8698SLemover    io.requestor(idx).req.ready := io.requestor(idx).resp.ready // should always be true
4929930e66fSLemover    XSError(!io.requestor(idx).resp.ready, s"${q.name} port ${idx} is non-block, resp.ready must be true.B")
493cb8f2f2aSLemover
494c3d5cfb3Speixiaokun    val req_need_gpa = hasGpf(idx)
495d0de7e4aSpeixiaokun    val req_s2xlate = Wire(UInt(2.W))
49682978df9Speixiaokun    req_s2xlate := MuxCase(noS2xlate, Seq(
49782e4705bSpeixiaokun      (!(virt_out(idx) || req_out(idx).hyperinst)) -> noS2xlate,
498667758b3SHaoyuan Feng      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
499667758b3SHaoyuan Feng      (csr.vsatp.mode === 0.U) -> onlyStage2,
500667758b3SHaoyuan Feng      (csr.hgatp.mode === 0.U) -> onlyStage1
50182978df9Speixiaokun    ))
5024c4af37cSpeixiaokun
503c1eb2883SHaoyuan 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)
5045adc4829SYanqin Li    // TODO: RegNext enable: ptw.resp.valid ? req.valid
5055adc4829SYanqin Li    val ptw_resp_bits_reg = RegEnable(ptw.resp.bits, ptw.resp.valid)
506c1eb2883SHaoyuan 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)
507d4078d6eSXiaokun-Pei    val ptw_getGpa = req_need_gpa && hitVec(idx)
508976c97c3SXiaokun-Pei    val need_gpa_vpn_hit = need_gpa_vpn === get_pn(req_out(idx).vaddr)
5094fc3a30cSXu, Zefan
5104fc3a30cSXu, Zefan    io.ptw.req(idx).valid := false.B;
5114fc3a30cSXu, Zefan    io.tlbreplay(idx) := false.B;
5124fc3a30cSXu, Zefan
5134fc3a30cSXu, Zefan    when (req_out_v(idx) && missVec(idx)) {
5144fc3a30cSXu, Zefan      // NOTE: for an miss tlb request: either send a ptw request, or ask for a replay
5154fc3a30cSXu, Zefan      when (ptw_just_back || ptw_already_back) {
5164fc3a30cSXu, Zefan        io.tlbreplay(idx) := true.B;
5174fc3a30cSXu, Zefan      } .elsewhen (need_gpa && !need_gpa_vpn_hit && !resp_gpa_refill) {
5184fc3a30cSXu, Zefan        // not send any unrelated ptw request when l1tlb is in need_gpa state
5194fc3a30cSXu, Zefan        io.tlbreplay(idx) := true.B;
5204fc3a30cSXu, Zefan      } .otherwise {
5214fc3a30cSXu, Zefan        io.ptw.req(idx).valid := true.B;
5224fc3a30cSXu, Zefan      }
5234fc3a30cSXu, Zefan    }
5244fc3a30cSXu, Zefan
5255adc4829SYanqin Li    when (io.requestor(idx).req_kill && GatedValidRegNext(io.requestor(idx).req.fire)) {
526c3b763d0SYinan Xu      io.ptw.req(idx).valid := false.B
527185e6164SHaoyuan Feng      io.tlbreplay(idx) := true.B
528c3b763d0SYinan Xu    }
5294fc3a30cSXu, Zefan
530185e6164SHaoyuan Feng    io.ptw.req(idx).bits.vpn := get_pn(req_out(idx).vaddr)
5314c4af37cSpeixiaokun    io.ptw.req(idx).bits.s2xlate := req_s2xlate
532d4078d6eSXiaokun-Pei    io.ptw.req(idx).bits.getGpa := ptw_getGpa
533185e6164SHaoyuan Feng    io.ptw.req(idx).bits.memidx := req_out(idx).memidx
534149086eaSLemover  }
535a0301c0dSLemover
536f1fe8698SLemover  def handle_block(idx: Int): Unit = {
537f1fe8698SLemover    // three valid: 1.if exist a entry; 2.if sent to ptw; 3.unset resp.valid
538935edac4STang Haojin    io.requestor(idx).req.ready := !req_out_v(idx) || io.requestor(idx).resp.fire
539f1fe8698SLemover    // req_out_v for if there is a request, may long latency, fixme
540f1fe8698SLemover
541f1fe8698SLemover    // miss request entries
542c3d5cfb3Speixiaokun    val req_need_gpa = hasGpf(idx)
543f1fe8698SLemover    val miss_req_vpn = get_pn(req_out(idx).vaddr)
5448744445eSMaxpicca-Li    val miss_req_memidx = req_out(idx).memidx
545d0de7e4aSpeixiaokun    val miss_req_s2xlate = Wire(UInt(2.W))
54682978df9Speixiaokun    miss_req_s2xlate := MuxCase(noS2xlate, Seq(
54782e4705bSpeixiaokun      (!(virt_out(idx) || req_out(idx).hyperinst)) -> noS2xlate,
548667758b3SHaoyuan Feng      (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
549667758b3SHaoyuan Feng      (csr.vsatp.mode === 0.U) -> onlyStage2,
550667758b3SHaoyuan Feng      (csr.hgatp.mode === 0.U) -> onlyStage1
55182978df9Speixiaokun    ))
5523222d00fSpeixiaokun    val miss_req_s2xlate_reg = RegEnable(miss_req_s2xlate, io.ptw.req(idx).fire)
553c3d5cfb3Speixiaokun    val hasS2xlate = miss_req_s2xlate_reg =/= noS2xlate
554c3d5cfb3Speixiaokun    val onlyS2 = miss_req_s2xlate_reg === onlyStage2
555c1eb2883SHaoyuan 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)
556c1eb2883SHaoyuan Feng    val hit_s2 = io.ptw.resp.bits.s2.hit(miss_req_vpn, csr.hgatp.vmid)
557c3d5cfb3Speixiaokun    val hit = Mux(onlyS2, hit_s2, hit_s1) && io.ptw.resp.valid && miss_req_s2xlate_reg === io.ptw.resp.bits.s2xlate
558f1fe8698SLemover
5595adc4829SYanqin Li    val new_coming_valid = WireInit(false.B)
5605adc4829SYanqin Li    new_coming_valid := req_in(idx).fire && !req_in(idx).bits.kill && !flush_pipe(idx)
5615adc4829SYanqin Li    val new_coming = GatedValidRegNext(new_coming_valid)
562f1fe8698SLemover    val miss_wire = new_coming && missVec(idx)
563935edac4STang Haojin    val miss_v = ValidHoldBypass(miss_wire, resp(idx).fire, flush_pipe(idx))
564f1fe8698SLemover    val miss_req_v = ValidHoldBypass(miss_wire || (miss_v && flush_mmu && !mmu_flush_pipe),
565935edac4STang Haojin      io.ptw.req(idx).fire || resp(idx).fire, flush_pipe(idx))
566f1fe8698SLemover
567f1fe8698SLemover    // when ptw resp, check if hit, reset miss_v, resp to lsu/ifu
568292bea3fSWilliam Wang    resp(idx).valid := req_out_v(idx) && !(miss_v && portTranslateEnable(idx))
569935edac4STang Haojin    when (io.ptw.resp.fire && hit && req_out_v(idx) && portTranslateEnable(idx)) {
570d0de7e4aSpeixiaokun      val stage1 = io.ptw.resp.bits.s1
571d0de7e4aSpeixiaokun      val stage2 = io.ptw.resp.bits.s2
572d0de7e4aSpeixiaokun      val s2xlate = io.ptw.resp.bits.s2xlate
573f1fe8698SLemover      resp(idx).valid := true.B
574c3d5cfb3Speixiaokun      resp(idx).bits.miss := false.B
575*0ca3be60SHaoyuan Feng      val s1_ppn = stage1.genPPN(get_pn(req_out(idx).vaddr))(ppnLen - 1, 0)
576*0ca3be60SHaoyuan Feng      val s2_ppn = stage2.genPPNS2(get_pn(req_out(idx).vaddr))(ppnLen - 1, 0)
577*0ca3be60SHaoyuan Feng      val s1_paddr = Cat(s1_ppn, get_off(req_out(idx).vaddr))
578*0ca3be60SHaoyuan Feng      val s2_paddr = Cat(s2_ppn, get_off(req_out(idx).vaddr))
57903efd994Shappy-lx      for (d <- 0 until nRespDups) {
580ddad696cSHaoyuan Feng        resp(idx).bits.paddr(d) := Mux(s2xlate === onlyStage2 || s2xlate === allStage, s2_paddr, s1_paddr)
581d0de7e4aSpeixiaokun        resp(idx).bits.gpaddr(d) := s1_paddr
582002c10a4SYanqin Li        pbmt_check(idx, d, io.ptw.resp.bits.s1.entry.pbmt, io.ptw.resp.bits.s2.entry.pbmt, s2xlate)
583cca17e78Speixiaokun        perm_check(stage1, req_out(idx).cmd, idx, d, stage2, req_out(idx).hlvx, s2xlate)
58403efd994Shappy-lx      }
58508b0bc30Shappy-lx      pmp_check(resp(idx).bits.paddr(0), req_out(idx).size, req_out(idx).cmd, false.B, idx)
586f1fe8698SLemover
587f1fe8698SLemover      // NOTE: the unfiltered req would be handled by Repeater
588f1fe8698SLemover    }
589f1fe8698SLemover    assert(RegNext(!resp(idx).valid || resp(idx).ready, true.B), "when tlb resp valid, ready should be true, must")
590f1fe8698SLemover    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")
591f1fe8698SLemover
592f1fe8698SLemover    val ptw_req = io.ptw.req(idx)
593f1fe8698SLemover    ptw_req.valid := miss_req_v
594f1fe8698SLemover    ptw_req.bits.vpn := miss_req_vpn
595d0de7e4aSpeixiaokun    ptw_req.bits.s2xlate := miss_req_s2xlate
596a4f9c77fSpeixiaokun    ptw_req.bits.getGpa := req_need_gpa && hitVec(idx)
5978744445eSMaxpicca-Li    ptw_req.bits.memidx := miss_req_memidx
598f1fe8698SLemover
599185e6164SHaoyuan Feng    io.tlbreplay(idx) := false.B
600185e6164SHaoyuan Feng
601f1fe8698SLemover    // NOTE: when flush pipe, tlb should abandon last req
602f1fe8698SLemover    // however, some outside modules like icache, dont care flushPipe, and still waiting for tlb resp
603f1fe8698SLemover    // just resp valid and raise page fault to go through. The pipe(ifu) will abandon it.
604f1fe8698SLemover    if (!q.outsideRecvFlush) {
605292bea3fSWilliam Wang      when (req_out_v(idx) && flush_pipe(idx) && portTranslateEnable(idx)) {
606f1fe8698SLemover        resp(idx).valid := true.B
60703efd994Shappy-lx        for (d <- 0 until nRespDups) {
608002c10a4SYanqin Li          resp(idx).bits.pbmt(d) := 0.U
60903efd994Shappy-lx          resp(idx).bits.excp(d).pf.ld := true.B // sfence happened, pf for not to use this addr
61003efd994Shappy-lx          resp(idx).bits.excp(d).pf.st := true.B
61103efd994Shappy-lx          resp(idx).bits.excp(d).pf.instr := true.B
61203efd994Shappy-lx        }
613f1fe8698SLemover      }
614f1fe8698SLemover    }
615f1fe8698SLemover  }
616cb8f2f2aSLemover
617cb8f2f2aSLemover  // when ptw resp, tlb at refill_idx maybe set to miss by force.
618cb8f2f2aSLemover  // Bypass ptw resp to check.
619d0de7e4aSpeixiaokun  def ptw_resp_bypass(vpn: UInt, s2xlate: UInt) = {
6205adc4829SYanqin Li    // TODO: RegNext enable: ptw.resp.valid
621cca17e78Speixiaokun    val hasS2xlate = s2xlate =/= noS2xlate
622cca17e78Speixiaokun    val onlyS2 = s2xlate === onlyStage2
623c3d5cfb3Speixiaokun    val onlyS1 = s2xlate === onlyStage1
624d0de7e4aSpeixiaokun    val s2xlate_hit = s2xlate === ptw.resp.bits.s2xlate
625c1eb2883SHaoyuan Feng    val resp_hit = ptw.resp.bits.hit(vpn, csr.satp.asid, csr.vsatp.asid, csr.hgatp.vmid, true, false)
6265adc4829SYanqin Li    val p_hit = GatedValidRegNext(resp_hit && io.ptw.resp.fire && s2xlate_hit)
627c8f765a6SHaoyuan Feng    val ppn_s1 = ptw.resp.bits.s1.genPPN(vpn)(ppnLen - 1, 0)
628cda84113Speixiaokun    val gvpn = Mux(onlyS2, vpn, ppn_s1)
629c8f765a6SHaoyuan Feng    val ppn_s2 = ptw.resp.bits.s2.genPPNS2(gvpn)(ppnLen - 1, 0)
630242cafeeSXu, Zefan    val p_ppn = RegEnable(Mux(s2xlate === onlyStage2 || s2xlate === allStage, ppn_s2, ppn_s1), io.ptw.resp.fire)
631002c10a4SYanqin Li    val p_pbmt = RegEnable(ptw.resp.bits.s1.entry.pbmt,io.ptw.resp.fire)
632d0de7e4aSpeixiaokun    val p_perm = RegEnable(ptwresp_to_tlbperm(ptw.resp.bits.s1), io.ptw.resp.fire)
6332ea10b44SXiaokun-Pei    val p_gvpn = RegEnable(Mux(onlyS2, ptw.resp.bits.s2.entry.tag, ptw.resp.bits.s1.genGVPN(vpn)), io.ptw.resp.fire)
634002c10a4SYanqin Li    val p_g_pbmt = RegEnable(ptw.resp.bits.s2.entry.pbmt,io.ptw.resp.fire)
635d0de7e4aSpeixiaokun    val p_g_perm = RegEnable(hptwresp_to_tlbperm(ptw.resp.bits.s2), io.ptw.resp.fire)
636d0de7e4aSpeixiaokun    val p_s2xlate = RegEnable(ptw.resp.bits.s2xlate, io.ptw.resp.fire)
637ad8d4021SXiaokun-Pei    val p_s1_level = RegEnable(ptw.resp.bits.s1.entry.level.get, io.ptw.resp.fire)
638ad8d4021SXiaokun-Pei    val p_s1_isLeaf = RegEnable(ptw.resp.bits.s1.isLeaf(), io.ptw.resp.fire)
639ad8d4021SXiaokun-Pei    val p_s1_isFakePte = RegEnable(ptw.resp.bits.s1.isFakePte(), io.ptw.resp.fire)
640ad8d4021SXiaokun-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)
641cb8f2f2aSLemover  }
642cb8f2f2aSLemover
643f1fe8698SLemover  // perf event
6445adc4829SYanqin Li  val result_ok = req_in.map(a => GatedValidRegNext(a.fire))
645f1fe8698SLemover  val perfEvents =
646f1fe8698SLemover    Seq(
647935edac4STang Haojin      ("access", PopCount((0 until Width).map{i => if (Block(i)) io.requestor(i).req.fire else portTranslateEnable(i) && result_ok(i) })),
648935edac4STang Haojin      ("miss  ", PopCount((0 until Width).map{i => if (Block(i)) portTranslateEnable(i) && result_ok(i) && missVec(i) else ptw.req(i).fire })),
649a0301c0dSLemover    )
650f1fe8698SLemover  generatePerfEvent()
651a0301c0dSLemover
652f1fe8698SLemover  // perf log
6536d5ddbceSLemover  for (i <- 0 until Width) {
654f1fe8698SLemover    if (Block(i)) {
655292bea3fSWilliam Wang      XSPerfAccumulate(s"access${i}",result_ok(i) && portTranslateEnable(i))
656f1fe8698SLemover      XSPerfAccumulate(s"miss${i}", result_ok(i) && missVec(i))
6576d5ddbceSLemover    } else {
6585adc4829SYanqin Li      XSPerfAccumulate("first_access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid))
659292bea3fSWilliam Wang      XSPerfAccumulate("access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i))
6605adc4829SYanqin Li      XSPerfAccumulate("first_miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i) && RegEnable(req(i).bits.debug.isFirstIssue, req(i).valid))
661292bea3fSWilliam Wang      XSPerfAccumulate("miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i))
662a0301c0dSLemover    }
6636d5ddbceSLemover  }
664935edac4STang Haojin  XSPerfAccumulate("ptw_resp_count", ptw.resp.fire)
665cca17e78Speixiaokun  XSPerfAccumulate("ptw_resp_pf_count", ptw.resp.fire && ptw.resp.bits.s1.pf)
6666d5ddbceSLemover
6676d5ddbceSLemover  // Log
6686d5ddbceSLemover  for(i <- 0 until Width) {
6696d5ddbceSLemover    XSDebug(req(i).valid, p"req(${i.U}): (${req(i).valid} ${req(i).ready}) ${req(i).bits}\n")
6706d5ddbceSLemover    XSDebug(resp(i).valid, p"resp(${i.U}): (${resp(i).valid} ${resp(i).ready}) ${resp(i).bits}\n")
6716d5ddbceSLemover  }
6726d5ddbceSLemover
673f1fe8698SLemover  XSDebug(io.sfence.valid, p"Sfence: ${io.sfence}\n")
674f1fe8698SLemover  XSDebug(ParallelOR(req_out_v) || ptw.resp.valid, p"vmEnable:${vmEnable} hit:${Binary(VecInit(hitVec).asUInt)} miss:${Binary(VecInit(missVec).asUInt)}\n")
6756d5ddbceSLemover  for (i <- ptw.req.indices) {
676935edac4STang Haojin    XSDebug(ptw.req(i).fire, p"L2TLB req:${ptw.req(i).bits}\n")
6776d5ddbceSLemover  }
67892e3bfefSLemover  XSDebug(ptw.resp.valid, p"L2TLB resp:${ptw.resp.bits} (v:${ptw.resp.valid}r:${ptw.resp.ready}) \n")
6796d5ddbceSLemover
680f9ac118cSHaoyuan Feng  println(s"${q.name}: page: ${q.NWays} ${q.Associative} ${q.Replacer.get}")
681a0301c0dSLemover
6825ab1b84dSHaoyuan Feng  if (env.EnableDifftest) {
6835ab1b84dSHaoyuan Feng    for (i <- 0 until Width) {
6845ab1b84dSHaoyuan 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
685d0de7e4aSpeixiaokun      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
6865ab1b84dSHaoyuan 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
6877d45a146SYinan Xu      val difftest = DifftestModule(new DiffL1TLBEvent)
688254e4960SHaoyuan Feng      difftest.coreid := io.hartId
689d0de7e4aSpeixiaokun      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)
6907d45a146SYinan Xu      if (!Seq("itlb", "ldtlb", "sttlb").contains(q.name)) {
6917d45a146SYinan Xu        difftest.valid := false.B
6927d45a146SYinan Xu      }
6937d45a146SYinan Xu      difftest.index := TLBDiffId(p(XSCoreParamsKey).HartId).U
6945adc4829SYanqin Li      difftest.vpn := RegEnable(get_pn(req_in(i).bits.vaddr), req_in(i).valid)
6957d45a146SYinan Xu      difftest.ppn := get_pn(io.requestor(i).resp.bits.paddr(0))
696c1eb2883SHaoyuan Feng      difftest.satp := Cat(csr.satp.mode, csr.satp.asid, csr.satp.ppn)
697c1eb2883SHaoyuan Feng      difftest.vsatp := Cat(csr.vsatp.mode, csr.vsatp.asid, csr.vsatp.ppn)
698c1eb2883SHaoyuan Feng      difftest.hgatp := Cat(csr.hgatp.mode, csr.hgatp.vmid, csr.hgatp.ppn)
699dd103903Speixiaokun      val req_need_gpa = gpf
700dd103903Speixiaokun      val req_s2xlate = Wire(UInt(2.W))
701dd103903Speixiaokun      req_s2xlate := MuxCase(noS2xlate, Seq(
70282e4705bSpeixiaokun        (!RegNext(virt_in || req_in(i).bits.hyperinst)) -> noS2xlate,
703c1eb2883SHaoyuan Feng        (csr.vsatp.mode =/= 0.U && csr.hgatp.mode =/= 0.U) -> allStage,
704c1eb2883SHaoyuan Feng        (csr.vsatp.mode === 0.U) -> onlyStage2,
705667758b3SHaoyuan Feng        (csr.hgatp.mode === 0.U) -> onlyStage1
70682978df9Speixiaokun      ))
707dd103903Speixiaokun      difftest.s2xlate := req_s2xlate
7087d45a146SYinan Xu    }
7095ab1b84dSHaoyuan Feng  }
7105ab1b84dSHaoyuan Feng}
7115ab1b84dSHaoyuan Feng
7127d45a146SYinan Xuobject TLBDiffId {
7137d45a146SYinan Xu  var i: Int = 0
7147d45a146SYinan Xu  var lastHartId: Int = -1
7157d45a146SYinan Xu  def apply(hartId: Int): Int = {
7167d45a146SYinan Xu    if (lastHartId != hartId) {
7177d45a146SYinan Xu      i = 0
7187d45a146SYinan Xu      lastHartId = hartId
7197d45a146SYinan Xu    }
7207d45a146SYinan Xu    i += 1
7217d45a146SYinan Xu    i - 1
7227d45a146SYinan Xu  }
723f1fe8698SLemover}
7241ca0e4f3SYinan Xu
72503efd994Shappy-lxclass TLBNonBlock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(false), q)
72603efd994Shappy-lxclass TLBBLock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(true), q)
7276d5ddbceSLemover
728a0301c0dSLemoverclass TlbReplace(Width: Int, q: TLBParameters)(implicit p: Parameters) extends TlbModule {
729a0301c0dSLemover  val io = IO(new TlbReplaceIO(Width, q))
730a0301c0dSLemover
731f9ac118cSHaoyuan Feng  if (q.Associative == "fa") {
732f9ac118cSHaoyuan Feng    val re = ReplacementPolicy.fromString(q.Replacer, q.NWays)
733f9ac118cSHaoyuan Feng    re.access(io.page.access.map(_.touch_ways))
734f9ac118cSHaoyuan Feng    io.page.refillIdx := re.way
735a0301c0dSLemover  } else { // set-acco && plru
736f9ac118cSHaoyuan Feng    val re = ReplacementPolicy.fromString(q.Replacer, q.NSets, q.NWays)
737f9ac118cSHaoyuan Feng    re.access(io.page.access.map(_.sets), io.page.access.map(_.touch_ways))
738f9ac118cSHaoyuan Feng    io.page.refillIdx := { if (q.NWays == 1) 0.U else re.way(io.page.chosen_set) }
739a0301c0dSLemover  }
740a0301c0dSLemover}
741