xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/TLB.scala (revision 1ca0e4f33f402f31daec0e57d270079d2db13562)
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.internal.naming.chiselName
22import chisel3.util._
23import freechips.rocketchip.util.SRAMAnnotation
24import xiangshan._
25import utils._
26import xiangshan.backend.fu.{PMPChecker, PMPReqBundle}
27import xiangshan.backend.rob.RobPtr
28import xiangshan.backend.fu.util.HasCSRConst
29
30
31@chiselName
32class TLB(Width: Int, q: TLBParameters)(implicit p: Parameters) extends TlbModule with HasCSRConst with HasPerfEvents {
33  val io = IO(new TlbIO(Width, q))
34
35  require(q.superAssociative == "fa")
36  if (q.sameCycle || q.missSameCycle) {
37    require(q.normalAssociative == "fa")
38  }
39
40  val req = io.requestor.map(_.req)
41  val resp = io.requestor.map(_.resp)
42  val ptw = io.ptw
43  val pmp = io.pmp
44
45  val sfence = io.sfence
46  val csr = io.csr
47  val satp = csr.satp
48  val priv = csr.priv
49  val ifecth = if (q.fetchi) true.B else false.B
50  val mode = if (q.useDmode) priv.dmode else priv.imode
51  // val vmEnable = satp.mode === 8.U // && (mode < ModeM) // FIXME: fix me when boot xv6/linux...
52  val vmEnable = if (EnbaleTlbDebug) (satp.mode === 8.U)
53  else (satp.mode === 8.U && (mode < ModeM))
54
55  val reqAddr = req.map(_.bits.vaddr.asTypeOf((new VaBundle).cloneType))
56  val vpn = reqAddr.map(_.vpn)
57  val cmd = req.map(_.bits.cmd)
58  val valid = req.map(_.valid)
59
60  def widthMapSeq[T <: Seq[Data]](f: Int => T) = (0 until Width).map(f)
61
62  def widthMap[T <: Data](f: Int => T) = (0 until Width).map(f)
63
64  // Normal page && Super page
65  val normalPage = TlbStorage(
66    name = "normal",
67    associative = q.normalAssociative,
68    sameCycle = q.sameCycle,
69    ports = Width,
70    nSets = q.normalNSets,
71    nWays = q.normalNWays,
72    sramSinglePort = sramSinglePort,
73    saveLevel = q.saveLevel,
74    normalPage = true,
75    superPage = false
76  )
77  val superPage = TlbStorage(
78    name = "super",
79    associative = q.superAssociative,
80    sameCycle = q.sameCycle,
81    ports = Width,
82    nSets = q.superNSets,
83    nWays = q.superNWays,
84    sramSinglePort = sramSinglePort,
85    saveLevel = q.saveLevel,
86    normalPage = q.normalAsVictim,
87    superPage = true,
88  )
89
90
91  for (i <- 0 until Width) {
92    normalPage.r_req_apply(
93      valid = io.requestor(i).req.valid,
94      vpn = vpn(i),
95      asid = csr.satp.asid,
96      i = i
97    )
98    superPage.r_req_apply(
99      valid = io.requestor(i).req.valid,
100      vpn = vpn(i),
101      asid = csr.satp.asid,
102      i = i
103    )
104  }
105
106  normalPage.victim.in <> superPage.victim.out
107  normalPage.victim.out <> superPage.victim.in
108  normalPage.sfence <> io.sfence
109  superPage.sfence <> io.sfence
110  normalPage.csr <> io.csr
111  superPage.csr <> io.csr
112
113  def TLBNormalRead(i: Int) = {
114    val (n_hit_sameCycle, normal_hit, normal_ppn, normal_perm) = normalPage.r_resp_apply(i)
115    val (s_hit_sameCycle, super_hit, super_ppn, super_perm) = superPage.r_resp_apply(i)
116    assert(!(normal_hit && super_hit && vmEnable && RegNext(req(i).valid, init = false.B)))
117
118    val hit = normal_hit || super_hit
119    val hit_sameCycle = n_hit_sameCycle || s_hit_sameCycle
120    val ppn = Mux(super_hit, super_ppn, normal_ppn)
121    val perm = Mux(super_hit, super_perm, normal_perm)
122
123    val pf = perm.pf
124    val af = perm.af
125    val cmdReg = if (!q.sameCycle) RegNext(cmd(i)) else cmd(i)
126    val validReg = if (!q.sameCycle) RegNext(valid(i)) else valid(i)
127    val offReg = if (!q.sameCycle) RegNext(reqAddr(i).off) else reqAddr(i).off
128    val sizeReg = if (!q.sameCycle) RegNext(req(i).bits.size) else req(i).bits.size
129
130    /** *************** next cycle when two cycle is false******************* */
131    val miss = !hit && vmEnable
132    val fast_miss = !super_hit && vmEnable
133    val miss_sameCycle = !hit_sameCycle && vmEnable
134    hit.suggestName(s"hit_${i}")
135    miss.suggestName(s"miss_${i}")
136
137    XSDebug(validReg, p"(${i.U}) hit:${hit} miss:${miss} ppn:${Hexadecimal(ppn)} perm:${perm}\n")
138
139    val paddr = Cat(ppn, offReg)
140    val vaddr = SignExt(req(i).bits.vaddr, PAddrBits)
141
142    req(i).ready := resp(i).ready
143    resp(i).valid := validReg
144    resp(i).bits.paddr := Mux(vmEnable, paddr, if (!q.sameCycle) RegNext(vaddr) else vaddr)
145    resp(i).bits.miss := { if (q.missSameCycle) miss_sameCycle else miss }
146    resp(i).bits.fast_miss := fast_miss
147    resp(i).bits.ptwBack := io.ptw.resp.fire()
148
149    pmp(i).valid := resp(i).valid
150    pmp(i).bits.addr := resp(i).bits.paddr
151    pmp(i).bits.size := sizeReg
152    pmp(i).bits.cmd := cmdReg
153
154    val ldUpdate = !perm.a && TlbCmd.isRead(cmdReg) && !TlbCmd.isAmo(cmdReg) // update A/D through exception
155    val stUpdate = (!perm.a || !perm.d) && (TlbCmd.isWrite(cmdReg) || TlbCmd.isAmo(cmdReg)) // update A/D through exception
156    val instrUpdate = !perm.a && TlbCmd.isExec(cmdReg) // update A/D through exception
157    val modeCheck = !(mode === ModeU && !perm.u || mode === ModeS && perm.u && (!priv.sum || ifecth))
158    val ldPermFail = !(modeCheck && (perm.r || priv.mxr && perm.x))
159    val stPermFail = !(modeCheck && perm.w)
160    val instrPermFail = !(modeCheck && perm.x)
161    val ldPf = (ldPermFail || pf) && (TlbCmd.isRead(cmdReg) && !TlbCmd.isAmo(cmdReg))
162    val stPf = (stPermFail || pf) && (TlbCmd.isWrite(cmdReg) || TlbCmd.isAmo(cmdReg))
163    val fault_valid = vmEnable
164    val instrPf = (instrPermFail || pf) && TlbCmd.isExec(cmdReg)
165    resp(i).bits.excp.pf.ld := (ldPf || ldUpdate) && fault_valid && !af
166    resp(i).bits.excp.pf.st := (stPf || stUpdate) && fault_valid && !af
167    resp(i).bits.excp.pf.instr := (instrPf || instrUpdate) && fault_valid && !af
168    // NOTE: pf need && with !af, page fault has higher priority than access fault
169    // but ptw may also have access fault, then af happens, the translation is wrong.
170    // In this case, pf has lower priority than af
171
172    resp(i).bits.excp.af.ld := af && TlbCmd.isRead(cmdReg) && fault_valid
173    resp(i).bits.excp.af.st := af && TlbCmd.isWrite(cmdReg) && fault_valid
174    resp(i).bits.excp.af.instr := af && TlbCmd.isExec(cmdReg) && fault_valid
175
176    (hit, miss, validReg)
177  }
178
179  val readResult = (0 until Width).map(TLBNormalRead(_))
180  val hitVec = readResult.map(_._1)
181  val missVec = readResult.map(_._2)
182  val validRegVec = readResult.map(_._3)
183
184  // replacement
185  def get_access(one_hot: UInt, valid: Bool): Valid[UInt] = {
186    val res = Wire(Valid(UInt(log2Up(one_hot.getWidth).W)))
187    res.valid := Cat(one_hot).orR && valid
188    res.bits := OHToUInt(one_hot)
189    res
190  }
191
192  val normal_refill_idx = if (q.outReplace) {
193    io.replace.normalPage.access <> normalPage.access
194    io.replace.normalPage.chosen_set := get_set_idx(io.ptw.resp.bits.entry.tag, q.normalNSets)
195    io.replace.normalPage.refillIdx
196  } else if (q.normalAssociative == "fa") {
197    val re = ReplacementPolicy.fromString(q.normalReplacer, q.normalNWays)
198    re.access(normalPage.access.map(_.touch_ways)) // normalhitVecVec.zipWithIndex.map{ case (hv, i) => get_access(hv, validRegVec(i))})
199    re.way
200  } else { // set-acco && plru
201    val re = ReplacementPolicy.fromString(q.normalReplacer, q.normalNSets, q.normalNWays)
202    re.access(normalPage.access.map(_.sets), normalPage.access.map(_.touch_ways))
203    re.way(get_set_idx(io.ptw.resp.bits.entry.tag, q.normalNSets))
204  }
205
206  val super_refill_idx = if (q.outReplace) {
207    io.replace.superPage.access <> superPage.access
208    io.replace.superPage.chosen_set := DontCare
209    io.replace.superPage.refillIdx
210  } else {
211    val re = ReplacementPolicy.fromString(q.superReplacer, q.superNWays)
212    re.access(superPage.access.map(_.touch_ways))
213    re.way
214  }
215
216  val refill = ptw.resp.fire() && !sfence.valid && !satp.changed
217  normalPage.w_apply(
218    valid = { if (q.normalAsVictim) false.B
219    else refill && ptw.resp.bits.entry.level.get === 2.U },
220    wayIdx = normal_refill_idx,
221    data = ptw.resp.bits
222  )
223  superPage.w_apply(
224    valid = { if (q.normalAsVictim) refill
225    else refill && ptw.resp.bits.entry.level.get =/= 2.U },
226    wayIdx = super_refill_idx,
227    data = ptw.resp.bits
228  )
229
230  for (i <- 0 until Width) {
231    io.ptw.req(i).valid := validRegVec(i) && missVec(i) && !RegNext(refill)
232    io.ptw.req(i).bits.vpn := RegNext(reqAddr(i).vpn)
233  }
234  io.ptw.resp.ready := true.B
235
236  if (!q.shouldBlock) {
237    for (i <- 0 until Width) {
238      XSPerfAccumulate("first_access" + Integer.toString(i, 10), validRegVec(i) && vmEnable && RegNext(req(i).bits.debug.isFirstIssue))
239      XSPerfAccumulate("access" + Integer.toString(i, 10), validRegVec(i) && vmEnable)
240    }
241    for (i <- 0 until Width) {
242      XSPerfAccumulate("first_miss" + Integer.toString(i, 10), validRegVec(i) && vmEnable && missVec(i) && RegNext(req(i).bits.debug.isFirstIssue))
243      XSPerfAccumulate("miss" + Integer.toString(i, 10), validRegVec(i) && vmEnable && missVec(i))
244    }
245  } else {
246    // NOTE: ITLB is blocked, so every resp will be valid only when hit
247    // every req will be ready only when hit
248    for (i <- 0 until Width) {
249      XSPerfAccumulate(s"access${i}", io.requestor(i).req.fire() && vmEnable)
250      XSPerfAccumulate(s"miss${i}", ptw.req(i).fire())
251    }
252
253  }
254  //val reqCycleCnt = Reg(UInt(16.W))
255  //reqCycleCnt := reqCycleCnt + BoolStopWatch(ptw.req(0).fire(), ptw.resp.fire || sfence.valid)
256  //XSPerfAccumulate("ptw_req_count", ptw.req.fire())
257  //XSPerfAccumulate("ptw_req_cycle", Mux(ptw.resp.fire(), reqCycleCnt, 0.U))
258  XSPerfAccumulate("ptw_resp_count", ptw.resp.fire())
259  XSPerfAccumulate("ptw_resp_pf_count", ptw.resp.fire() && ptw.resp.bits.pf)
260
261  // Log
262  for(i <- 0 until Width) {
263    XSDebug(req(i).valid, p"req(${i.U}): (${req(i).valid} ${req(i).ready}) ${req(i).bits}\n")
264    XSDebug(resp(i).valid, p"resp(${i.U}): (${resp(i).valid} ${resp(i).ready}) ${resp(i).bits}\n")
265  }
266
267  XSDebug(sfence.valid, p"Sfence: ${sfence}\n")
268  XSDebug(ParallelOR(valid)|| ptw.resp.valid, p"CSR: ${csr}\n")
269  XSDebug(ParallelOR(valid) || ptw.resp.valid, p"vmEnable:${vmEnable} hit:${Binary(VecInit(hitVec).asUInt)} miss:${Binary(VecInit(missVec).asUInt)}\n")
270  for (i <- ptw.req.indices) {
271    XSDebug(ptw.req(i).fire(), p"PTW req:${ptw.req(i).bits}\n")
272  }
273  XSDebug(ptw.resp.valid, p"PTW resp:${ptw.resp.bits} (v:${ptw.resp.valid}r:${ptw.resp.ready}) \n")
274
275  println(s"${q.name}: normal page: ${q.normalNWays} ${q.normalAssociative} ${q.normalReplacer.get} super page: ${q.superNWays} ${q.superAssociative} ${q.superReplacer.get}")
276
277//   // NOTE: just for simple tlb debug, comment it after tlb's debug
278  // assert(!io.ptw.resp.valid || io.ptw.resp.bits.entry.tag === io.ptw.resp.bits.entry.ppn, "Simple tlb debug requires vpn === ppn")
279
280  val perfEvents = if(!q.shouldBlock) {
281    Seq(
282      ("access", PopCount((0 until Width).map(i => vmEnable && validRegVec(i)))              ),
283      ("miss  ", PopCount((0 until Width).map(i => vmEnable && validRegVec(i) && missVec(i)))),
284    )
285  } else {
286    Seq(
287      ("access", PopCount((0 until Width).map(i => io.requestor(i).req.fire()))),
288      ("miss  ", PopCount((0 until Width).map(i => ptw.req(i).fire()))         ),
289    )
290  }
291  generatePerfEvent()
292}
293
294class TlbReplace(Width: Int, q: TLBParameters)(implicit p: Parameters) extends TlbModule {
295  val io = IO(new TlbReplaceIO(Width, q))
296
297  if (q.normalAssociative == "fa") {
298    val re = ReplacementPolicy.fromString(q.normalReplacer, q.normalNWays)
299    re.access(io.normalPage.access.map(_.touch_ways))
300    io.normalPage.refillIdx := re.way
301  } else { // set-acco && plru
302    val re = ReplacementPolicy.fromString(q.normalReplacer, q.normalNSets, q.normalNWays)
303    re.access(io.normalPage.access.map(_.sets), io.normalPage.access.map(_.touch_ways))
304    io.normalPage.refillIdx := { if (q.normalNWays == 1) 0.U else re.way(io.normalPage.chosen_set) }
305  }
306
307  if (q.superAssociative == "fa") {
308    val re = ReplacementPolicy.fromString(q.superReplacer, q.superNWays)
309    re.access(io.superPage.access.map(_.touch_ways))
310    io.superPage.refillIdx := re.way
311  } else { // set-acco && plru
312    val re = ReplacementPolicy.fromString(q.superReplacer, q.superNSets, q.superNWays)
313    re.access(io.superPage.access.map(_.sets), io.superPage.access.map(_.touch_ways))
314    io.superPage.refillIdx := { if (q.superNWays == 1) 0.U else re.way(io.superPage.chosen_set) }
315  }
316}
317
318object TLB {
319  def apply
320  (
321    in: Seq[BlockTlbRequestIO],
322    sfence: SfenceBundle,
323    csr: TlbCsrBundle,
324    width: Int,
325    shouldBlock: Boolean,
326    q: TLBParameters
327  )(implicit p: Parameters) = {
328    require(in.length == width)
329
330    val tlb = Module(new TLB(width, q))
331
332    tlb.io.sfence <> sfence
333    tlb.io.csr <> csr
334    tlb.suggestName(s"tlb_${q.name}")
335
336    if (!shouldBlock) { // dtlb
337      for (i <- 0 until width) {
338        tlb.io.requestor(i) <> in(i)
339        // tlb.io.requestor(i).req.valid := in(i).req.valid
340        // tlb.io.requestor(i).req.bits := in(i).req.bits
341        // in(i).req.ready := tlb.io.requestor(i).req.ready
342
343        // in(i).resp.valid := tlb.io.requestor(i).resp.valid
344        // in(i).resp.bits := tlb.io.requestor(i).resp.bits
345        // tlb.io.requestor(i).resp.ready := in(i).resp.ready
346      }
347    } else { // itlb
348      //require(width == 1)
349      (0 until width).map{ i =>
350        tlb.io.requestor(i).req.valid := in(i).req.valid
351        tlb.io.requestor(i).req.bits := in(i).req.bits
352        in(i).req.ready := !tlb.io.requestor(i).resp.bits.miss && in(i).resp.ready && tlb.io.requestor(i).req.ready
353
354        require(q.missSameCycle || q.sameCycle)
355        // NOTE: the resp.valid seems to be useless, it must be true when need
356        //       But don't know what happens when true but not need, so keep it correct value, not just true.B
357        if (q.missSameCycle && !q.sameCycle) {
358          in(i).resp.valid := tlb.io.requestor(i).resp.valid && !RegNext(tlb.io.requestor(i).resp.bits.miss)
359        } else {
360          in(i).resp.valid := tlb.io.requestor(i).resp.valid && !tlb.io.requestor(i).resp.bits.miss
361        }
362        in(i).resp.bits := tlb.io.requestor(i).resp.bits
363        tlb.io.requestor(i).resp.ready := in(i).resp.ready
364      }
365    }
366    tlb.io.ptw
367  }
368}
369