xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/TLB.scala (revision d29457077dba131b5b0f793bbf7a71463640ac2a)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.cache.mmu
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import difftest._
23import freechips.rocketchip.util.SRAMAnnotation
24import xiangshan._
25import utils._
26import utility._
27import xiangshan.backend.fu.{PMPChecker, PMPReqBundle, PMPConfig => XSPMPConfig}
28import xiangshan.backend.rob.RobPtr
29import xiangshan.backend.fu.util.HasCSRConst
30import freechips.rocketchip.rocket.PMPConfig
31
32/** TLB module
33  * support block request and non-block request io at the same time
34  * return paddr at next cycle, then go for pmp/pma check
35  * @param Width: The number of requestors
36  * @param Block: Blocked or not for each requestor ports
37  * @param q: TLB Parameters, like entry number, each TLB has its own parameters
38  * @param p: XiangShan Paramemters, like XLEN
39  */
40
41class TLB(Width: Int, nRespDups: Int = 1, Block: Seq[Boolean], q: TLBParameters)(implicit p: Parameters) extends TlbModule
42  with HasCSRConst
43  with HasPerfEvents
44{
45  val io = IO(new TlbIO(Width, nRespDups, q))
46
47  val req = io.requestor.map(_.req)
48  val resp = io.requestor.map(_.resp)
49  val ptw = io.ptw
50  val pmp = io.pmp
51  val refill_to_mem = io.refill_to_mem
52
53  /** Sfence.vma & Svinval
54    * Sfence.vma will 1. flush old entries 2. flush inflight 3. flush pipe
55    * Svinval will 1. flush old entries 2. flush inflight
56    * So, Svinval will not flush pipe, which means
57    * it should not drop reqs from pipe and should return right resp
58    */
59  val sfence = DelayN(io.sfence, q.fenceDelay)
60  val csr = io.csr
61  val satp = DelayN(io.csr.satp, q.fenceDelay)
62  val 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    val ptw_already_back = RegNext(ptw.resp.fire) && RegNext(ptw.resp.bits).hit(get_pn(req_out(idx).vaddr), asid = io.csr.satp.asid, allType = true)
196    io.ptw.req(idx).valid := req_out_v(idx) && missVec(idx) && !(ptw_just_back || ptw_already_back) // TODO: remove the regnext, timing
197    io.tlbreplay(idx) := req_out_v(idx) && missVec(idx) && (ptw_just_back || ptw_already_back)
198    when (io.requestor(idx).req_kill && RegNext(io.requestor(idx).req.fire)) {
199      io.ptw.req(idx).valid := false.B
200      io.tlbreplay(idx) := true.B
201    }
202    io.ptw.req(idx).bits.vpn := get_pn(req_out(idx).vaddr)
203    io.ptw.req(idx).bits.memidx := req_out(idx).memidx
204  }
205
206  def handle_block(idx: Int): Unit = {
207    // three valid: 1.if exist a entry; 2.if sent to ptw; 3.unset resp.valid
208    io.requestor(idx).req.ready := !req_out_v(idx) || io.requestor(idx).resp.fire
209    // req_out_v for if there is a request, may long latency, fixme
210
211    // miss request entries
212    val miss_req_vpn = get_pn(req_out(idx).vaddr)
213    val miss_req_memidx = req_out(idx).memidx
214    val hit = io.ptw.resp.bits.hit(miss_req_vpn, io.csr.satp.asid, allType = true) && io.ptw.resp.valid
215
216    val new_coming = RegNext(req_in(idx).fire && !req_in(idx).bits.kill && !flush_pipe(idx), false.B)
217    val miss_wire = new_coming && missVec(idx)
218    val miss_v = ValidHoldBypass(miss_wire, resp(idx).fire, flush_pipe(idx))
219    val miss_req_v = ValidHoldBypass(miss_wire || (miss_v && flush_mmu && !mmu_flush_pipe),
220      io.ptw.req(idx).fire || resp(idx).fire, flush_pipe(idx))
221
222    // when ptw resp, check if hit, reset miss_v, resp to lsu/ifu
223    resp(idx).valid := req_out_v(idx) && !(miss_v && portTranslateEnable(idx))
224    when (io.ptw.resp.fire && hit && req_out_v(idx) && portTranslateEnable(idx)) {
225      val pte = io.ptw.resp.bits
226      resp(idx).valid := true.B
227      resp(idx).bits.miss := false.B // for blocked tlb, this is useless
228      for (d <- 0 until nRespDups) {
229        resp(idx).bits.paddr(d) := Cat(pte.genPPN(get_pn(req_out(idx).vaddr)), get_off(req_out(idx).vaddr))
230        perm_check(pte, req_out(idx).cmd, idx, d)
231      }
232      pmp_check(resp(idx).bits.paddr(0), req_out(idx).size, req_out(idx).cmd, idx)
233
234      // NOTE: the unfiltered req would be handled by Repeater
235    }
236    assert(RegNext(!resp(idx).valid || resp(idx).ready, true.B), "when tlb resp valid, ready should be true, must")
237    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")
238
239    val ptw_req = io.ptw.req(idx)
240    ptw_req.valid := miss_req_v
241    ptw_req.bits.vpn := miss_req_vpn
242    ptw_req.bits.memidx := miss_req_memidx
243
244    io.tlbreplay(idx) := false.B
245
246    // NOTE: when flush pipe, tlb should abandon last req
247    // however, some outside modules like icache, dont care flushPipe, and still waiting for tlb resp
248    // just resp valid and raise page fault to go through. The pipe(ifu) will abandon it.
249    if (!q.outsideRecvFlush) {
250      when (req_out_v(idx) && flush_pipe(idx) && portTranslateEnable(idx)) {
251        resp(idx).valid := true.B
252        for (d <- 0 until nRespDups) {
253          resp(idx).bits.excp(d).pf.ld := true.B // sfence happened, pf for not to use this addr
254          resp(idx).bits.excp(d).pf.st := true.B
255          resp(idx).bits.excp(d).pf.instr := true.B
256        }
257      }
258    }
259  }
260
261  // when ptw resp, tlb at refill_idx maybe set to miss by force.
262  // Bypass ptw resp to check.
263  def ptw_resp_bypass(vpn: UInt) = {
264    val p_hit = RegNext(ptw.resp.bits.hit(vpn, io.csr.satp.asid, allType = true) && io.ptw.resp.fire)
265    val p_ppn = RegEnable(ptw.resp.bits.genPPN(vpn), io.ptw.resp.fire)
266    val p_perm = RegEnable(ptwresp_to_tlbperm(ptw.resp.bits), io.ptw.resp.fire)
267    (p_hit, p_ppn, p_perm)
268  }
269
270  // assert
271  for(i <- 0 until Width) {
272    TimeOutAssert(req_out_v(i) && !resp(i).valid, timeOutThreshold, s"{q.name} port{i} long time no resp valid.")
273  }
274
275  // perf event
276  val result_ok = req_in.map(a => RegNext(a.fire))
277  val perfEvents =
278    Seq(
279      ("access", PopCount((0 until Width).map{i => if (Block(i)) io.requestor(i).req.fire else portTranslateEnable(i) && result_ok(i) })),
280      ("miss  ", PopCount((0 until Width).map{i => if (Block(i)) portTranslateEnable(i) && result_ok(i) && missVec(i) else ptw.req(i).fire })),
281    )
282  generatePerfEvent()
283
284  // perf log
285  for (i <- 0 until Width) {
286    if (Block(i)) {
287      XSPerfAccumulate(s"access${i}",result_ok(i) && portTranslateEnable(i))
288      XSPerfAccumulate(s"miss${i}", result_ok(i) && missVec(i))
289    } else {
290      XSPerfAccumulate("first_access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && RegNext(req(i).bits.debug.isFirstIssue))
291      XSPerfAccumulate("access" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i))
292      XSPerfAccumulate("first_miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i) && RegNext(req(i).bits.debug.isFirstIssue))
293      XSPerfAccumulate("miss" + Integer.toString(i, 10), result_ok(i) && portTranslateEnable(i) && missVec(i))
294    }
295  }
296  XSPerfAccumulate("ptw_resp_count", ptw.resp.fire)
297  XSPerfAccumulate("ptw_resp_pf_count", ptw.resp.fire && ptw.resp.bits.pf)
298
299  // Log
300  for(i <- 0 until Width) {
301    XSDebug(req(i).valid, p"req(${i.U}): (${req(i).valid} ${req(i).ready}) ${req(i).bits}\n")
302    XSDebug(resp(i).valid, p"resp(${i.U}): (${resp(i).valid} ${resp(i).ready}) ${resp(i).bits}\n")
303  }
304
305  XSDebug(io.sfence.valid, p"Sfence: ${io.sfence}\n")
306  XSDebug(ParallelOR(req_out_v) || ptw.resp.valid, p"vmEnable:${vmEnable} hit:${Binary(VecInit(hitVec).asUInt)} miss:${Binary(VecInit(missVec).asUInt)}\n")
307  for (i <- ptw.req.indices) {
308    XSDebug(ptw.req(i).fire, p"L2TLB req:${ptw.req(i).bits}\n")
309  }
310  XSDebug(ptw.resp.valid, p"L2TLB resp:${ptw.resp.bits} (v:${ptw.resp.valid}r:${ptw.resp.ready}) \n")
311
312  println(s"${q.name}: page: ${q.NWays} ${q.Associative} ${q.Replacer.get}")
313
314  if (env.EnableDifftest) {
315    for (i <- 0 until Width) {
316      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
317      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
318      val difftest = DifftestModule(new DiffL1TLBEvent)
319      difftest.coreid := io.hartId
320      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 && portTranslateEnable(i)
321      if (!Seq("itlb", "ldtlb", "sttlb").contains(q.name)) {
322        difftest.valid := false.B
323      }
324      difftest.index := TLBDiffId(p(XSCoreParamsKey).HartId).U
325      difftest.satp := io.csr.satp.ppn
326      difftest.vpn := RegNext(get_pn(req_in(i).bits.vaddr))
327      difftest.ppn := get_pn(io.requestor(i).resp.bits.paddr(0))
328    }
329  }
330}
331
332object TLBDiffId {
333  var i: Int = 0
334  var lastHartId: Int = -1
335  def apply(hartId: Int): Int = {
336    if (lastHartId != hartId) {
337      i = 0
338      lastHartId = hartId
339    }
340    i += 1
341    i - 1
342  }
343}
344
345class TLBNonBlock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(false), q)
346class TLBBLock(Width: Int, nRespDups: Int = 1, q: TLBParameters)(implicit p: Parameters) extends TLB(Width, nRespDups, Seq.fill(Width)(true), q)
347
348class TlbReplace(Width: Int, q: TLBParameters)(implicit p: Parameters) extends TlbModule {
349  val io = IO(new TlbReplaceIO(Width, q))
350
351  if (q.Associative == "fa") {
352    val re = ReplacementPolicy.fromString(q.Replacer, q.NWays)
353    re.access(io.page.access.map(_.touch_ways))
354    io.page.refillIdx := re.way
355  } else { // set-acco && plru
356    val re = ReplacementPolicy.fromString(q.Replacer, q.NSets, q.NWays)
357    re.access(io.page.access.map(_.sets), io.page.access.map(_.touch_ways))
358    io.page.refillIdx := { if (q.NWays == 1) 0.U else re.way(io.page.chosen_set) }
359  }
360}
361