1/*************************************************************************************** 2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences 3* Copyright (c) 2020-2021 Peng Cheng Laboratory 4* 5* XiangShan is licensed under Mulan PSL v2. 6* You can use this software according to the terms and conditions of the Mulan PSL v2. 7* You may obtain a copy of Mulan PSL v2 at: 8* http://license.coscl.org.cn/MulanPSL2 9 10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 13* 14* See the Mulan PSL v2 for more details. 15***************************************************************************************/ 16 17package xiangshan.cache.mmu 18 19import chipsalliance.rocketchip.config.Parameters 20import chisel3._ 21import chisel3.util._ 22import difftest._ 23import freechips.rocketchip.util.SRAMAnnotation 24import xiangshan._ 25import utils._ 26import utility._ 27import xiangshan.backend.fu.{PMPChecker, PMPReqBundle, PMPConfig => XSPMPConfig} 28import xiangshan.backend.rob.RobPtr 29import xiangshan.backend.fu.util.HasCSRConst 30import freechips.rocketchip.rocket.PMPConfig 31 32/** TLB module 33 * support block request and non-block request io at the same time 34 * return paddr at next cycle, then go for pmp/pma check 35 * @param Width: The number of requestors 36 * @param Block: Blocked or not for each requestor ports 37 * @param q: TLB Parameters, like entry number, each TLB has its own parameters 38 * @param p: XiangShan Paramemters, like XLEN 39 */ 40 41class TLB(Width: Int, nRespDups: Int = 1, Block: Seq[Boolean], q: TLBParameters)(implicit p: Parameters) extends TlbModule 42 with HasCSRConst 43 with HasPerfEvents 44{ 45 val io = IO(new TlbIO(Width, nRespDups, q)) 46 47 val req = io.requestor.map(_.req) 48 val resp = io.requestor.map(_.resp) 49 val ptw = io.ptw 50 val pmp = io.pmp 51 val refill_to_mem = io.refill_to_mem 52 53 /** Sfence.vma & Svinval 54 * Sfence.vma will 1. flush old entries 2. flush inflight 3. flush pipe 55 * Svinval will 1. flush old entries 2. flush inflight 56 * So, Svinval will not flush pipe, which means 57 * it should not drop reqs from pipe and should return right resp 58 */ 59 val sfence = DelayN(io.sfence, q.fenceDelay) 60 val csr = io.csr 61 val satp = DelayN(io.csr.satp, q.fenceDelay) 62 val flush_mmu = DelayN(sfence.valid || csr.satp.changed, q.fenceDelay) 63 val mmu_flush_pipe = DelayN(sfence.valid && sfence.bits.flushPipe, q.fenceDelay) // for svinval, won't flush pipe 64 val flush_pipe = io.flushPipe 65 66 // ATTENTION: csr and flush from backend are delayed. csr should not be later than flush. 67 // because, csr will influence tlb behavior. 68 val ifecth = if (q.fetchi) true.B else false.B 69 val mode = if (q.useDmode) csr.priv.dmode else csr.priv.imode 70 // val vmEnable = satp.mode === 8.U // && (mode < ModeM) // FIXME: fix me when boot xv6/linux... 71 val vmEnable = if (EnbaleTlbDebug) (satp.mode === 8.U) 72 else (satp.mode === 8.U && (mode < ModeM)) 73 val portTranslateEnable = (0 until Width).map(i => vmEnable && RegNext(!req(i).bits.no_translate)) 74 75 val req_in = req 76 val req_out = req.map(a => RegEnable(a.bits, a.fire)) 77 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))) 78 79 val refill = ptw.resp.fire && !flush_mmu && vmEnable 80 refill_to_mem.valid := refill 81 refill_to_mem.memidx := ptw.resp.bits.memidx 82 83 val entries = Module(new TlbStorageWrapper(Width, q, nRespDups)) 84 entries.io.base_connect(sfence, csr, satp) 85 if (q.outReplace) { io.replace <> entries.io.replace } 86 for (i <- 0 until Width) { 87 entries.io.r_req_apply(io.requestor(i).req.valid, get_pn(req_in(i).bits.vaddr), i) 88 entries.io.w_apply(refill, ptw.resp.bits) 89 resp(i).bits.debug.isFirstIssue := RegNext(req(i).bits.debug.isFirstIssue) 90 resp(i).bits.debug.robIdx := RegNext(req(i).bits.debug.robIdx) 91 } 92 93 // read TLB, get hit/miss, paddr, perm bits 94 val readResult = (0 until Width).map(TLBRead(_)) 95 val hitVec = readResult.map(_._1) 96 val missVec = readResult.map(_._2) 97 val pmp_addr = readResult.map(_._3) 98 val perm = readResult.map(_._4) 99 100 // check pmp use paddr (for timing optization, use pmp_addr here) 101 // check permisson 102 (0 until Width).foreach{i => 103 pmp_check(pmp_addr(i), req_out(i).size, req_out(i).cmd, i) 104 for (d <- 0 until nRespDups) { 105 perm_check(perm(i)(d), req_out(i).cmd, i, d) 106 } 107 } 108 109 // handle block or non-block io 110 // for non-block io, just return the above result, send miss to ptw 111 // for block io, hold the request, send miss to ptw, 112 // when ptw back, return the result 113 (0 until Width) foreach {i => 114 if (Block(i)) handle_block(i) 115 else handle_nonblock(i) 116 } 117 io.ptw.resp.ready := true.B 118 119 /************************ main body above | method/log/perf below ****************************/ 120 def TLBRead(i: Int) = { 121 val (e_hit, e_ppn, e_perm) = entries.io.r_resp_apply(i) 122 val (p_hit, p_ppn, p_perm) = ptw_resp_bypass(get_pn(req_in(i).bits.vaddr)) 123 val enable = portTranslateEnable(i) 124 125 val hit = e_hit || p_hit 126 val miss = !hit && enable 127 hit.suggestName(s"hit_read_${i}") 128 miss.suggestName(s"miss_read_${i}") 129 130 val vaddr = SignExt(req_out(i).vaddr, PAddrBits) 131 resp(i).bits.miss := miss 132 resp(i).bits.ptwBack := ptw.resp.fire 133 resp(i).bits.memidx := RegNext(req_in(i).bits.memidx) 134 135 val ppn = WireInit(VecInit(Seq.fill(nRespDups)(0.U(ppnLen.W)))) 136 val perm = WireInit(VecInit(Seq.fill(nRespDups)(0.U.asTypeOf(new TlbPermBundle)))) 137 138 for (d <- 0 until nRespDups) { 139 ppn(d) := Mux(p_hit, p_ppn, e_ppn(d)) 140 perm(d) := Mux(p_hit, p_perm, e_perm(d)) 141 142 val paddr = Cat(ppn(d), get_off(req_out(i).vaddr)) 143 resp(i).bits.paddr(d) := Mux(enable, paddr, vaddr) 144 } 145 146 XSDebug(req_out_v(i), p"(${i.U}) hit:${hit} miss:${miss} ppn:${Hexadecimal(ppn(0))} perm:${perm(0)}\n") 147 148 val pmp_paddr = resp(i).bits.paddr(0) 149 150 (hit, miss, pmp_paddr, perm) 151 } 152 153 def pmp_check(addr: UInt, size: UInt, cmd: UInt, idx: Int): Unit = { 154 pmp(idx).valid := resp(idx).valid 155 pmp(idx).bits.addr := addr 156 pmp(idx).bits.size := size 157 pmp(idx).bits.cmd := cmd 158 } 159 160 def perm_check(perm: TlbPermBundle, cmd: UInt, idx: Int, nDups: Int) = { 161 // for timing optimization, pmp check is divided into dynamic and static 162 // dynamic: superpage (or full-connected reg entries) -> check pmp when translation done 163 // static: 4K pages (or sram entries) -> check pmp with pre-checked results 164 val af = perm.af 165 val pf = perm.pf 166 val ldUpdate = !perm.a && TlbCmd.isRead(cmd) && !TlbCmd.isAmo(cmd) // update A/D through exception 167 val stUpdate = (!perm.a || !perm.d) && (TlbCmd.isWrite(cmd) || TlbCmd.isAmo(cmd)) // update A/D through exception 168 val instrUpdate = !perm.a && TlbCmd.isExec(cmd) // update A/D through exception 169 val modeCheck = !(mode === ModeU && !perm.u || mode === ModeS && perm.u && (!io.csr.priv.sum || ifecth)) 170 val ldPermFail = !(modeCheck && (perm.r || io.csr.priv.mxr && perm.x)) 171 val stPermFail = !(modeCheck && perm.w) 172 val instrPermFail = !(modeCheck && perm.x) 173 val ldPf = (ldPermFail || pf) && (TlbCmd.isRead(cmd) && !TlbCmd.isAmo(cmd)) 174 val stPf = (stPermFail || pf) && (TlbCmd.isWrite(cmd) || TlbCmd.isAmo(cmd)) 175 val instrPf = (instrPermFail || pf) && TlbCmd.isExec(cmd) 176 val fault_valid = portTranslateEnable(idx) 177 resp(idx).bits.excp(nDups).pf.ld := (ldPf || ldUpdate) && fault_valid && !af 178 resp(idx).bits.excp(nDups).pf.st := (stPf || stUpdate) && fault_valid && !af 179 resp(idx).bits.excp(nDups).pf.instr := (instrPf || instrUpdate) && fault_valid && !af 180 // NOTE: pf need && with !af, page fault has higher priority than access fault 181 // but ptw may also have access fault, then af happens, the translation is wrong. 182 // In this case, pf has lower priority than af 183 184 resp(idx).bits.excp(nDups).af.ld := af && TlbCmd.isRead(cmd) && fault_valid 185 resp(idx).bits.excp(nDups).af.st := af && TlbCmd.isWrite(cmd) && fault_valid 186 resp(idx).bits.excp(nDups).af.instr := af && TlbCmd.isExec(cmd) && fault_valid 187 } 188 189 def handle_nonblock(idx: Int): Unit = { 190 io.requestor(idx).resp.valid := req_out_v(idx) 191 io.requestor(idx).req.ready := io.requestor(idx).resp.ready // should always be true 192 XSError(!io.requestor(idx).resp.ready, s"${q.name} port ${idx} is non-block, resp.ready must be true.B") 193 194 val ptw_just_back = ptw.resp.fire && ptw.resp.bits.hit(get_pn(req_out(idx).vaddr), asid = io.csr.satp.asid, allType = true) 195 io.ptw.req(idx).valid := RegNext(req_out_v(idx) && missVec(idx) && !ptw_just_back, false.B) // TODO: remove the regnext, timing 196 when (RegEnable(io.requestor(idx).req_kill, RegNext(io.requestor(idx).req.fire))) { 197 io.ptw.req(idx).valid := false.B 198 } 199 io.ptw.req(idx).bits.vpn := RegNext(get_pn(req_out(idx).vaddr)) 200 io.ptw.req(idx).bits.memidx := RegNext(req_out(idx).memidx) 201 } 202 203 def handle_block(idx: Int): Unit = { 204 // three valid: 1.if exist a entry; 2.if sent to ptw; 3.unset resp.valid 205 io.requestor(idx).req.ready := !req_out_v(idx) || io.requestor(idx).resp.fire 206 // req_out_v for if there is a request, may long latency, fixme 207 208 // miss request entries 209 val miss_req_vpn = get_pn(req_out(idx).vaddr) 210 val miss_req_memidx = req_out(idx).memidx 211 val hit = io.ptw.resp.bits.hit(miss_req_vpn, io.csr.satp.asid, allType = true) && io.ptw.resp.valid 212 213 val new_coming = RegNext(req_in(idx).fire && !req_in(idx).bits.kill && !flush_pipe(idx), false.B) 214 val miss_wire = new_coming && missVec(idx) 215 val miss_v = ValidHoldBypass(miss_wire, resp(idx).fire, flush_pipe(idx)) 216 val miss_req_v = ValidHoldBypass(miss_wire || (miss_v && flush_mmu && !mmu_flush_pipe), 217 io.ptw.req(idx).fire || resp(idx).fire, flush_pipe(idx)) 218 219 // when ptw resp, check if hit, reset miss_v, resp to lsu/ifu 220 resp(idx).valid := req_out_v(idx) && !(miss_v && portTranslateEnable(idx)) 221 when (io.ptw.resp.fire && hit && req_out_v(idx) && portTranslateEnable(idx)) { 222 val pte = io.ptw.resp.bits 223 resp(idx).valid := true.B 224 resp(idx).bits.miss := false.B // for blocked tlb, this is useless 225 for (d <- 0 until nRespDups) { 226 resp(idx).bits.paddr(d) := Cat(pte.genPPN(get_pn(req_out(idx).vaddr)), get_off(req_out(idx).vaddr)) 227 perm_check(pte, req_out(idx).cmd, idx, d) 228 } 229 pmp_check(resp(idx).bits.paddr(0), req_out(idx).size, req_out(idx).cmd, idx) 230 231 // NOTE: the unfiltered req would be handled by Repeater 232 } 233 assert(RegNext(!resp(idx).valid || resp(idx).ready, true.B), "when tlb resp valid, ready should be true, must") 234 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") 235 236 val ptw_req = io.ptw.req(idx) 237 ptw_req.valid := miss_req_v 238 ptw_req.bits.vpn := miss_req_vpn 239 ptw_req.bits.memidx := miss_req_memidx 240 241 // NOTE: when flush pipe, tlb should abandon last req 242 // however, some outside modules like icache, dont care flushPipe, and still waiting for tlb resp 243 // just resp valid and raise page fault to go through. The pipe(ifu) will abandon it. 244 if (!q.outsideRecvFlush) { 245 when (req_out_v(idx) && flush_pipe(idx) && portTranslateEnable(idx)) { 246 resp(idx).valid := true.B 247 for (d <- 0 until nRespDups) { 248 resp(idx).bits.excp(d).pf.ld := true.B // sfence happened, pf for not to use this addr 249 resp(idx).bits.excp(d).pf.st := true.B 250 resp(idx).bits.excp(d).pf.instr := true.B 251 } 252 } 253 } 254 } 255 256 // when ptw resp, tlb at refill_idx maybe set to miss by force. 257 // Bypass ptw resp to check. 258 def ptw_resp_bypass(vpn: UInt) = { 259 val p_hit = RegNext(ptw.resp.bits.hit(vpn, io.csr.satp.asid, allType = true) && io.ptw.resp.fire) 260 val p_ppn = RegEnable(ptw.resp.bits.genPPN(vpn), io.ptw.resp.fire) 261 val p_perm = RegEnable(ptwresp_to_tlbperm(ptw.resp.bits), io.ptw.resp.fire) 262 (p_hit, p_ppn, p_perm) 263 } 264 265 // assert 266 for(i <- 0 until Width) { 267 TimeOutAssert(req_out_v(i) && !resp(i).valid, timeOutThreshold, s"{q.name} port{i} long time no resp valid.") 268 } 269 270 // perf event 271 val result_ok = req_in.map(a => RegNext(a.fire)) 272 val perfEvents = 273 Seq( 274 ("access", PopCount((0 until Width).map{i => if (Block(i)) io.requestor(i).req.fire else portTranslateEnable(i) && result_ok(i) })), 275 ("miss ", PopCount((0 until Width).map{i => if (Block(i)) portTranslateEnable(i) && result_ok(i) && missVec(i) else ptw.req(i).fire })), 276 ) 277 generatePerfEvent() 278 279 // perf log 280 for (i <- 0 until Width) { 281 if (Block(i)) { 282 XSPerfAccumulate(s"access${i}",result_ok(i) && portTranslateEnable(i)) 283 XSPerfAccumulate(s"miss${i}", result_ok(i) && missVec(i)) 284 } else { 285 XSPerfAccumulate("first_access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && RegNext(req(i).bits.debug.isFirstIssue)) 286 XSPerfAccumulate("access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i)) 287 XSPerfAccumulate("first_miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i) && RegNext(req(i).bits.debug.isFirstIssue)) 288 XSPerfAccumulate("miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i)) 289 } 290 } 291 XSPerfAccumulate("ptw_resp_count", ptw.resp.fire) 292 XSPerfAccumulate("ptw_resp_pf_count", ptw.resp.fire && ptw.resp.bits.pf) 293 294 // Log 295 for(i <- 0 until Width) { 296 XSDebug(req(i).valid, p"req(${i.U}): (${req(i).valid} ${req(i).ready}) ${req(i).bits}\n") 297 XSDebug(resp(i).valid, p"resp(${i.U}): (${resp(i).valid} ${resp(i).ready}) ${resp(i).bits}\n") 298 } 299 300 XSDebug(io.sfence.valid, p"Sfence: ${io.sfence}\n") 301 XSDebug(ParallelOR(req_out_v) || ptw.resp.valid, p"vmEnable:${vmEnable} hit:${Binary(VecInit(hitVec).asUInt)} miss:${Binary(VecInit(missVec).asUInt)}\n") 302 for (i <- ptw.req.indices) { 303 XSDebug(ptw.req(i).fire, p"L2TLB req:${ptw.req(i).bits}\n") 304 } 305 XSDebug(ptw.resp.valid, p"L2TLB resp:${ptw.resp.bits} (v:${ptw.resp.valid}r:${ptw.resp.ready}) \n") 306 307 println(s"${q.name}: page: ${q.NWays} ${q.Associative} ${q.Replacer.get}") 308 309 if (env.EnableDifftest) { 310 for (i <- 0 until Width) { 311 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 312 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 313 val difftest = DifftestModule(new DiffL1TLBEvent) 314 difftest.coreid := io.hartId 315 difftest.valid := RegNext(io.requestor(i).req.fire) && !RegNext(io.requestor(i).req_kill) && io.requestor(i).resp.fire && !io.requestor(i).resp.bits.miss && !pf && !af && portTranslateEnable(i) 316 if (!Seq("itlb", "ldtlb", "sttlb").contains(q.name)) { 317 difftest.valid := false.B 318 } 319 difftest.index := TLBDiffId(p(XSCoreParamsKey).HartId).U 320 difftest.satp := io.csr.satp.ppn 321 difftest.vpn := RegNext(get_pn(req_in(i).bits.vaddr)) 322 difftest.ppn := get_pn(io.requestor(i).resp.bits.paddr(0)) 323 } 324 } 325} 326 327object TLBDiffId { 328 var i: Int = 0 329 var lastHartId: Int = -1 330 def apply(hartId: Int): Int = { 331 if (lastHartId != hartId) { 332 i = 0 333 lastHartId = hartId 334 } 335 i += 1 336 i - 1 337 } 338} 339 340class TLBNonBlock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(false), q) 341class TLBBLock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(true), q) 342 343class TlbReplace(Width: Int, q: TLBParameters)(implicit p: Parameters) extends TlbModule { 344 val io = IO(new TlbReplaceIO(Width, q)) 345 346 if (q.Associative == "fa") { 347 val re = ReplacementPolicy.fromString(q.Replacer, q.NWays) 348 re.access(io.page.access.map(_.touch_ways)) 349 io.page.refillIdx := re.way 350 } else { // set-acco && plru 351 val re = ReplacementPolicy.fromString(q.Replacer, q.NSets, q.NWays) 352 re.access(io.page.access.map(_.sets), io.page.access.map(_.touch_ways)) 353 io.page.refillIdx := { if (q.NWays == 1) 0.U else re.way(io.page.chosen_set) } 354 } 355} 356