xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/TLBStorage.scala (revision d61cd5eecdc204c74ec210166665a10f4eb680f1)
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 utils._
23import utility._
24import freechips.rocketchip.formal.PropertyClass
25import xiangshan.backend.fu.util.HasCSRConst
26
27import scala.math.min
28
29// For Direct-map TLBs, we do not use it now
30class BankedAsyncDataModuleTemplateWithDup[T <: Data](
31  gen: T,
32  numEntries: Int,
33  numRead: Int,
34  numDup: Int,
35  numBanks: Int
36) extends Module {
37  val io = IO(new Bundle {
38    val raddr = Vec(numRead, Input(UInt(log2Ceil(numEntries).W)))
39    val rdata = Vec(numRead, Vec(numDup, Output(gen)))
40    val wen   = Input(Bool())
41    val waddr = Input(UInt(log2Ceil(numEntries).W))
42    val wdata = Input(gen)
43  })
44  require(numBanks > 1)
45  require(numEntries > numBanks)
46
47  val numBankEntries = numEntries / numBanks
48  def bankOffset(address: UInt): UInt = {
49    address(log2Ceil(numBankEntries) - 1, 0)
50  }
51
52  def bankIndex(address: UInt): UInt = {
53    address(log2Ceil(numEntries) - 1, log2Ceil(numBankEntries))
54  }
55
56  val dataBanks = Seq.tabulate(numBanks)(i => {
57    val bankEntries = if (i < numBanks - 1) numBankEntries else (numEntries - (i * numBankEntries))
58    Mem(bankEntries, gen)
59  })
60
61  // async read, but regnext
62  for (i <- 0 until numRead) {
63    val data_read = Reg(Vec(numDup, Vec(numBanks, gen)))
64    val bank_index = Reg(Vec(numDup, UInt(numBanks.W)))
65    for (j <- 0 until numDup) {
66      bank_index(j) := UIntToOH(bankIndex(io.raddr(i)))
67      for (k <- 0 until numBanks) {
68        data_read(j)(k) := Mux(io.wen && (io.waddr === io.raddr(i)),
69          io.wdata, dataBanks(k)(bankOffset(io.raddr(i))))
70      }
71    }
72    // next cycle
73    for (j <- 0 until numDup) {
74      io.rdata(i)(j) := Mux1H(bank_index(j), data_read(j))
75    }
76  }
77
78  // write
79  for (i <- 0 until numBanks) {
80    when (io.wen && (bankIndex(io.waddr) === i.U)) {
81      dataBanks(i)(bankOffset(io.waddr)) := io.wdata
82    }
83  }
84}
85
86class TLBFA(
87  parentName: String,
88  ports: Int,
89  nDups: Int,
90  nSets: Int,
91  nWays: Int,
92  saveLevel: Boolean = false,
93  normalPage: Boolean,
94  superPage: Boolean
95)(implicit p: Parameters) extends TlbModule with HasPerfEvents {
96
97  val io = IO(new TlbStorageIO(nSets, nWays, ports, nDups))
98  io.r.req.map(_.ready := true.B)
99
100  val v = RegInit(VecInit(Seq.fill(nWays)(false.B)))
101  val entries = Reg(Vec(nWays, new TlbSectorEntry(normalPage, superPage)))
102  val g = entries.map(_.perm.g)
103
104  for (i <- 0 until ports) {
105    val req = io.r.req(i)
106    val resp = io.r.resp(i)
107    val access = io.access(i)
108
109    val vpn = req.bits.vpn
110    val vpn_reg = RegEnable(vpn, req.fire())
111    val vpn_gen_ppn = if(saveLevel) vpn else vpn_reg
112    val hasS2xlate = req.bits.s2xlate =/= noS2xlate
113    val OnlyS2 = req.bits.s2xlate === onlyStage2
114    val refill_mask = Mux(io.w.valid, UIntToOH(io.w.bits.wayIdx), 0.U(nWays.W))
115    val hitVec = VecInit((entries.zipWithIndex).zip(v zip refill_mask.asBools).map{
116      case (e, m) => {
117        val s2xlate_hit = e._1.s2xlate === req.bits.s2xlate
118        val hit = e._1.hit(vpn, Mux(req.bits.s2xlate(0), io.csr.vsatp.asid, io.csr.satp.asid), vmid = io.csr.hgatp.asid, hasS2xlate = hasS2xlate, onlyS2 = OnlyS2)
119        s2xlate_hit && hit && m._1 && !m._2
120      }
121    })
122
123    hitVec.suggestName("hitVec")
124
125    val hitVecReg = RegEnable(hitVec, req.fire)
126    // Sector tlb may trigger multi-hit, see def "wbhit"
127    XSPerfAccumulate(s"port${i}_multi_hit", !(!resp.valid || (PopCount(hitVecReg) === 0.U || PopCount(hitVecReg) === 1.U)))
128
129    resp.valid := RegNext(req.valid)
130    resp.bits.hit := Cat(hitVecReg).orR
131    if (nWays == 1) {
132      for (d <- 0 until nDups) {
133        resp.bits.ppn(d) := RegEnable(entries(0).genPPN(saveLevel, req.valid)(vpn), req.fire)
134        resp.bits.perm(d) := RegEnable(entries(0).perm, req.fire)
135      }
136    } else {
137      for (d <- 0 until nDups) {
138        resp.bits.ppn(d) := RegEnable(ParallelMux(hitVec zip entries.map(_.genPPN(saveLevel, req.valid)(vpn))), req.fire)
139        resp.bits.perm(d) := RegEnable(ParallelMux(hitVec zip entries.map(_.perm)), req.fire)
140      }
141    }
142
143    access.sets := get_set_idx(vpn_reg(vpn_reg.getWidth - 1, sectortlbwidth), nSets) // no use
144    access.touch_ways.valid := resp.valid && Cat(hitVecReg).orR
145    access.touch_ways.bits := OHToUInt(hitVecReg)
146
147    resp.bits.hit.suggestName("hit")
148    resp.bits.ppn.suggestName("ppn")
149    resp.bits.perm.suggestName("perm")
150    resp.bits.g_perm.suggestName("g_perm")
151  }
152
153  when (io.w.valid) {
154    v(io.w.bits.wayIdx) := true.B
155    entries(io.w.bits.wayIdx).apply(io.w.bits.data, io.csr.satp.asid)
156  }
157  // write assert, should not duplicate with the existing entries
158  val w_hit_vec = VecInit(entries.zip(v).map{case (e, vi) => e.wbhit(io.w.bits.data, io.csr.satp.asid) && vi })
159  XSError(io.w.valid && Cat(w_hit_vec).orR, s"${parentName} refill, duplicate with existing entries")
160
161  val refill_vpn_reg = RegNext(io.w.bits.data.s1.entry.tag)
162  val refill_wayIdx_reg = RegNext(io.w.bits.wayIdx)
163  when (RegNext(io.w.valid)) {
164    io.access.map { access =>
165      access.sets := get_set_idx(refill_vpn_reg, nSets)
166      access.touch_ways.valid := true.B
167      access.touch_ways.bits := refill_wayIdx_reg
168    }
169  }
170
171  val sfence = io.sfence
172  val sfence_valid = sfence.valid && !sfence.bits.hg && !sfence.bits.hv
173  val sfence_vpn = sfence.bits.addr(VAddrBits - 1, offLen)
174  val sfenceHit = entries.map(_.hit(sfence_vpn, sfence.bits.id, vmid = io.csr.hgatp.asid, hasS2xlate = io.csr.priv.virt, onlyS2 = false.B))
175  val sfenceHit_noasid = entries.map(_.hit(sfence_vpn, sfence.bits.id, ignoreAsid = true, vmid = io.csr.hgatp.asid, hasS2xlate = io.csr.priv.virt, onlyS2 = false.B))
176  // Sfence will flush all sectors of an entry when hit
177  when (sfence_valid) {
178    when (sfence.bits.rs1) { // virtual address *.rs1 <- (rs1===0.U)
179      when (sfence.bits.rs2) { // asid, but i do not want to support asid, *.rs2 <- (rs2===0.U)
180        // all addr and all asid
181        v.zipWithIndex.map{ case(a, i) => a := a && !((io.csr.priv.virt === false.B && entries(i).s2xlate === noS2xlate) ||
182          (io.csr.priv.virt && entries(i).s2xlate =/= noS2xlate && entries(i).vmid === io.csr.hgatp.asid))}
183      }.otherwise {
184        // all addr but specific asid
185        v.zipWithIndex.map{ case (a, i) => a := a && !(!g(i) && ((!io.csr.priv.virt && entries(i).s2xlate === noS2xlate && entries(i).asid === sfence.bits.id) ||
186          (io.csr.priv.virt && entries(i).s2xlate =/= noS2xlate && entries(i).asid === sfence.bits.id && entries(i).vmid === io.csr.hgatp.asid)))}
187      }
188    }.otherwise {
189      when (sfence.bits.rs2) {
190        // specific addr but all asid
191        v.zipWithIndex.map{ case (a, i) => a := a & !sfenceHit_noasid(i) }
192      }.otherwise {
193        // specific addr and specific asid
194        v.zipWithIndex.map{ case (a, i) => a := a & !(sfenceHit(i) && !g(i)) }
195      }
196    }
197  }
198
199  val hfencev_valid = sfence.valid && sfence.bits.hv
200  val hfenceg_valid = sfence.valid && sfence.bits.hg
201  val hfencev = io.sfence
202  val hfencev_vpn = sfence_vpn
203  val hfencevHit = entries.map(_.hit(hfencev_vpn, hfencev.bits.id, vmid = io.csr.hgatp.asid, hasS2xlate = true.B, onlyS2 = false.B))
204  val hfencevHit_noasid = entries.map(_.hit(hfencev_vpn, 0.U, ignoreAsid = true, vmid = io.csr.hgatp.asid, hasS2xlate = true.B, onlyS2 = false.B))
205  when (hfencev_valid) {
206    when (hfencev.bits.rs1) {
207      when (hfencev.bits.rs2) {
208        v.zipWithIndex.map { case (a, i) => a := a && !(entries(i).s2xlate =/= noS2xlate && entries(i).vmid === io.csr.hgatp.asid)}
209      }.otherwise {
210        v.zipWithIndex.map { case (a, i) => a := a && !(!g(i) && (entries(i).s2xlate =/= noS2xlate && entries(i).asid === sfence.bits.id && entries(i).vmid === io.csr.hgatp.asid))
211        }
212      }
213    }.otherwise {
214      when (hfencev.bits.rs2) {
215        v.zipWithIndex.map{ case (a, i) => a := a && !hfencevHit_noasid(i) }
216      }.otherwise {
217        v.zipWithIndex.map{ case (a, i) => a := a && !(hfencevHit(i) && !g(i)) }
218      }
219    }
220  }
221
222
223  val hfenceg = io.sfence
224  val hfenceg_gvpn = sfence_vpn
225  when (hfenceg_valid) {
226    when(hfenceg.bits.rs2) {
227      v.zipWithIndex.map { case (a, i) => a := a && !(entries(i).s2xlate =/= noS2xlate) }
228    }.otherwise {
229      v.zipWithIndex.map { case (a, i) => a := a && !(entries(i).s2xlate =/= noS2xlate && entries(i).vmid === sfence.bits.id) }
230    }
231  }
232
233  XSPerfAccumulate(s"access", io.r.resp.map(_.valid.asUInt).fold(0.U)(_ + _))
234  XSPerfAccumulate(s"hit", io.r.resp.map(a => a.valid && a.bits.hit).fold(0.U)(_.asUInt + _.asUInt))
235
236  for (i <- 0 until nWays) {
237    XSPerfAccumulate(s"access${i}", io.r.resp.zip(io.access.map(acc => UIntToOH(acc.touch_ways.bits))).map{ case (a, b) =>
238      a.valid && a.bits.hit && b(i)}.fold(0.U)(_.asUInt + _.asUInt))
239  }
240  for (i <- 0 until nWays) {
241    XSPerfAccumulate(s"refill${i}", io.w.valid && io.w.bits.wayIdx === i.U)
242  }
243
244  val perfEvents = Seq(
245    ("tlbstore_access", io.r.resp.map(_.valid.asUInt).fold(0.U)(_ + _)                            ),
246    ("tlbstore_hit   ", io.r.resp.map(a => a.valid && a.bits.hit).fold(0.U)(_.asUInt + _.asUInt)),
247  )
248  generatePerfEvent()
249
250  println(s"${parentName} tlb_fa: nSets${nSets} nWays:${nWays}")
251}
252
253class TLBFakeFA(
254             ports: Int,
255             nDups: Int,
256             nSets: Int,
257             nWays: Int,
258             useDmode: Boolean = false
259           )(implicit p: Parameters) extends TlbModule with HasCSRConst{
260
261  val io = IO(new TlbStorageIO(nSets, nWays, ports, nDups))
262  io.r.req.map(_.ready := true.B)
263  val mode = if (useDmode) io.csr.priv.dmode else io.csr.priv.imode
264  val vmEnable = if (EnbaleTlbDebug) (io.csr.satp.mode === 8.U)
265    else (io.csr.satp.mode === 8.U && (mode < ModeM))
266
267  for (i <- 0 until ports) {
268    val req = io.r.req(i)
269    val resp = io.r.resp(i)
270
271    val helper = Module(new PTEHelper())
272    helper.clock := clock
273    helper.satp := io.csr.satp.ppn
274    helper.enable := req.fire && vmEnable
275    helper.vpn := req.bits.vpn
276
277    val pte = helper.pte.asTypeOf(new PteBundle)
278    val ppn = pte.ppn
279    val vpn_reg = RegNext(req.bits.vpn)
280    val pf = helper.pf
281    val level = helper.level
282
283    resp.valid := RegNext(req.valid)
284    resp.bits.hit := true.B
285    for (d <- 0 until nDups) {
286      resp.bits.perm(d).pf := pf
287      resp.bits.perm(d).af := false.B
288      resp.bits.perm(d).d := pte.perm.d
289      resp.bits.perm(d).a := pte.perm.a
290      resp.bits.perm(d).g := pte.perm.g
291      resp.bits.perm(d).u := pte.perm.u
292      resp.bits.perm(d).x := pte.perm.x
293      resp.bits.perm(d).w := pte.perm.w
294      resp.bits.perm(d).r := pte.perm.r
295
296      resp.bits.ppn(d) := MuxLookup(level, 0.U)(Seq(
297        0.U -> Cat(ppn(ppn.getWidth-1, vpnnLen*2), vpn_reg(vpnnLen*2-1, 0)),
298        1.U -> Cat(ppn(ppn.getWidth-1, vpnnLen), vpn_reg(vpnnLen-1, 0)),
299        2.U -> ppn)
300      )
301    }
302  }
303
304  io.access := DontCare
305}
306
307object TlbStorage {
308  def apply
309  (
310    parentName: String,
311    associative: String,
312    ports: Int,
313    nDups: Int = 1,
314    nSets: Int,
315    nWays: Int,
316    saveLevel: Boolean = false,
317    normalPage: Boolean,
318    superPage: Boolean,
319    useDmode: Boolean,
320    SoftTLB: Boolean
321  )(implicit p: Parameters) = {
322    if (SoftTLB) {
323      val storage = Module(new TLBFakeFA(ports, nDups, nSets, nWays, useDmode))
324      storage.suggestName(s"${parentName}_fake_fa")
325      storage.io
326    } else {
327       val storage = Module(new TLBFA(parentName, ports, nDups, nSets, nWays, saveLevel, normalPage, superPage))
328       storage.suggestName(s"${parentName}_fa")
329       storage.io
330    }
331  }
332}
333
334class TlbStorageWrapper(ports: Int, q: TLBParameters, nDups: Int = 1)(implicit p: Parameters) extends TlbModule {
335  val io = IO(new TlbStorageWrapperIO(ports, q, nDups))
336
337  val page = TlbStorage(
338    parentName = q.name + "_storage",
339    associative = q.Associative,
340    ports = ports,
341    nDups = nDups,
342    nSets = q.NSets,
343    nWays = q.NWays,
344    normalPage = true,
345    superPage = true,
346    useDmode = q.useDmode,
347    SoftTLB = coreParams.softTLB
348  )
349
350  for (i <- 0 until ports) {
351    page.r_req_apply(
352      valid = io.r.req(i).valid,
353      vpn = io.r.req(i).bits.vpn,
354      i = i,
355      s2xlate = io.r.req(i).bits.s2xlate
356    )
357  }
358
359  for (i <- 0 until ports) {
360    val q = page.r.req(i)
361    val p = page.r.resp(i)
362    val rq = io.r.req(i)
363    val rp = io.r.resp(i)
364    rq.ready := q.ready // actually, not used
365    rp.valid := p.valid // actually, not used
366    rp.bits.hit := p.bits.hit
367    for (d <- 0 until nDups) {
368      rp.bits.ppn(d) := p.bits.ppn(d)
369      rp.bits.perm(d).pf := p.bits.perm(d).pf
370      rp.bits.perm(d).af := p.bits.perm(d).af
371      rp.bits.perm(d).d := p.bits.perm(d).d
372      rp.bits.perm(d).a := p.bits.perm(d).a
373      rp.bits.perm(d).g := p.bits.perm(d).g
374      rp.bits.perm(d).u := p.bits.perm(d).u
375      rp.bits.perm(d).x := p.bits.perm(d).x
376      rp.bits.perm(d).w := p.bits.perm(d).w
377      rp.bits.perm(d).r := p.bits.perm(d).r
378    }
379  }
380
381  page.sfence <> io.sfence
382  page.csr <> io.csr
383
384  val refill_idx = if (q.outReplace) {
385    io.replace.page.access <> page.access
386    io.replace.page.chosen_set := DontCare
387    io.replace.page.refillIdx
388  } else {
389    val re = ReplacementPolicy.fromString(q.Replacer, q.NWays)
390    re.access(page.access.map(_.touch_ways))
391    re.way
392  }
393
394  page.w_apply(
395    valid = io.w.valid,
396    wayIdx = refill_idx,
397    data = io.w.bits.data
398  )
399
400    // replacement
401  def get_access(one_hot: UInt, valid: Bool): Valid[UInt] = {
402    val res = Wire(Valid(UInt(log2Up(one_hot.getWidth).W)))
403    res.valid := Cat(one_hot).orR && valid
404    res.bits := OHToUInt(one_hot)
405    res
406  }
407}
408