xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/TLBStorage.scala (revision 935edac446654a1880ac0112b2380315b5368504)
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 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
112    val refill_mask = Mux(io.w.valid, UIntToOH(io.w.bits.wayIdx), 0.U(nWays.W))
113    val hitVec = VecInit((entries.zipWithIndex).zip(v zip refill_mask.asBools).map{case (e, m) => e._1.hit(vpn, io.csr.satp.asid) && m._1 && !m._2 })
114
115    hitVec.suggestName("hitVec")
116
117    val hitVecReg = RegEnable(hitVec, req.fire)
118    // Sector tlb may trigger multi-hit, see def "wbhit"
119    XSPerfAccumulate(s"port${i}_multi_hit", !(!resp.valid || (PopCount(hitVecReg) === 0.U || PopCount(hitVecReg) === 1.U)))
120
121    resp.valid := RegNext(req.valid)
122    resp.bits.hit := Cat(hitVecReg).orR
123    if (nWays == 1) {
124      for (d <- 0 until nDups) {
125        resp.bits.ppn(d) := RegEnable(entries(0).genPPN(saveLevel, req.valid)(vpn), req.fire)
126        resp.bits.perm(d) := RegEnable(entries(0).perm, req.fire)
127      }
128    } else {
129      for (d <- 0 until nDups) {
130        resp.bits.ppn(d) := RegEnable(ParallelMux(hitVec zip entries.map(_.genPPN(saveLevel, req.valid)(vpn))), req.fire)
131        resp.bits.perm(d) := RegEnable(ParallelMux(hitVec zip entries.map(_.perm)), req.fire)
132      }
133    }
134
135    access.sets := get_set_idx(vpn_reg(vpn_reg.getWidth - 1, sectortlbwidth), nSets) // no use
136    access.touch_ways.valid := resp.valid && Cat(hitVecReg).orR
137    access.touch_ways.bits := OHToUInt(hitVecReg)
138
139    resp.bits.hit.suggestName("hit")
140    resp.bits.ppn.suggestName("ppn")
141    resp.bits.perm.suggestName("perm")
142  }
143
144  when (io.w.valid) {
145    v(io.w.bits.wayIdx) := true.B
146    entries(io.w.bits.wayIdx).apply(io.w.bits.data, io.csr.satp.asid)
147  }
148  // write assert, should not duplicate with the existing entries
149  val w_hit_vec = VecInit(entries.zip(v).map{case (e, vi) => e.wbhit(io.w.bits.data, io.csr.satp.asid) && vi })
150  XSError(io.w.valid && Cat(w_hit_vec).orR, s"${parentName} refill, duplicate with existing entries")
151
152  val refill_vpn_reg = RegNext(io.w.bits.data.entry.tag)
153  val refill_wayIdx_reg = RegNext(io.w.bits.wayIdx)
154  when (RegNext(io.w.valid)) {
155    io.access.map { access =>
156      access.sets := get_set_idx(refill_vpn_reg, nSets)
157      access.touch_ways.valid := true.B
158      access.touch_ways.bits := refill_wayIdx_reg
159    }
160  }
161
162  val sfence = io.sfence
163  val sfence_vpn = sfence.bits.addr.asTypeOf(new VaBundle().cloneType).vpn
164  val sfenceHit = entries.map(_.hit(sfence_vpn, sfence.bits.asid))
165  val sfenceHit_noasid = entries.map(_.hit(sfence_vpn, sfence.bits.asid, ignoreAsid = true))
166  // Sfence will flush all sectors of an entry when hit
167  when (io.sfence.valid) {
168    when (sfence.bits.rs1) { // virtual address *.rs1 <- (rs1===0.U)
169      when (sfence.bits.rs2) { // asid, but i do not want to support asid, *.rs2 <- (rs2===0.U)
170        // all addr and all asid
171        v.map(_ := false.B)
172      }.otherwise {
173        // all addr but specific asid
174        v.zipWithIndex.map{ case (a,i) => a := a & (g(i) | !(entries(i).asid === sfence.bits.asid)) }
175      }
176    }.otherwise {
177      when (sfence.bits.rs2) {
178        // specific addr but all asid
179        v.zipWithIndex.map{ case (a,i) => a := a & !sfenceHit_noasid(i) }
180      }.otherwise {
181        // specific addr and specific asid
182        v.zipWithIndex.map{ case (a,i) => a := a & !(sfenceHit(i) && !g(i)) }
183      }
184    }
185  }
186
187  XSPerfAccumulate(s"access", io.r.resp.map(_.valid.asUInt).fold(0.U)(_ + _))
188  XSPerfAccumulate(s"hit", io.r.resp.map(a => a.valid && a.bits.hit).fold(0.U)(_.asUInt + _.asUInt))
189
190  for (i <- 0 until nWays) {
191    XSPerfAccumulate(s"access${i}", io.r.resp.zip(io.access.map(acc => UIntToOH(acc.touch_ways.bits))).map{ case (a, b) =>
192      a.valid && a.bits.hit && b(i)}.fold(0.U)(_.asUInt + _.asUInt))
193  }
194  for (i <- 0 until nWays) {
195    XSPerfAccumulate(s"refill${i}", io.w.valid && io.w.bits.wayIdx === i.U)
196  }
197
198  val perfEvents = Seq(
199    ("tlbstore_access", io.r.resp.map(_.valid.asUInt).fold(0.U)(_ + _)                            ),
200    ("tlbstore_hit   ", io.r.resp.map(a => a.valid && a.bits.hit).fold(0.U)(_.asUInt + _.asUInt)),
201  )
202  generatePerfEvent()
203
204  println(s"${parentName} tlb_fa: nSets${nSets} nWays:${nWays}")
205}
206
207class TLBFakeFA(
208             ports: Int,
209             nDups: Int,
210             nSets: Int,
211             nWays: Int,
212             useDmode: Boolean = false
213           )(implicit p: Parameters) extends TlbModule with HasCSRConst{
214
215  val io = IO(new TlbStorageIO(nSets, nWays, ports, nDups))
216  io.r.req.map(_.ready := true.B)
217  val mode = if (useDmode) io.csr.priv.dmode else io.csr.priv.imode
218  val vmEnable = if (EnbaleTlbDebug) (io.csr.satp.mode === 8.U)
219    else (io.csr.satp.mode === 8.U && (mode < ModeM))
220
221  for (i <- 0 until ports) {
222    val req = io.r.req(i)
223    val resp = io.r.resp(i)
224
225    val helper = Module(new PTEHelper())
226    helper.clock := clock
227    helper.satp := io.csr.satp.ppn
228    helper.enable := req.fire && vmEnable
229    helper.vpn := req.bits.vpn
230
231    val pte = helper.pte.asTypeOf(new PteBundle)
232    val ppn = pte.ppn
233    val vpn_reg = RegNext(req.bits.vpn)
234    val pf = helper.pf
235    val level = helper.level
236
237    resp.valid := RegNext(req.valid)
238    resp.bits.hit := true.B
239    for (d <- 0 until nDups) {
240      resp.bits.perm(d).pf := pf
241      resp.bits.perm(d).af := false.B
242      resp.bits.perm(d).d := pte.perm.d
243      resp.bits.perm(d).a := pte.perm.a
244      resp.bits.perm(d).g := pte.perm.g
245      resp.bits.perm(d).u := pte.perm.u
246      resp.bits.perm(d).x := pte.perm.x
247      resp.bits.perm(d).w := pte.perm.w
248      resp.bits.perm(d).r := pte.perm.r
249
250      resp.bits.ppn(d) := MuxLookup(level, 0.U, Seq(
251        0.U -> Cat(ppn(ppn.getWidth-1, vpnnLen*2), vpn_reg(vpnnLen*2-1, 0)),
252        1.U -> Cat(ppn(ppn.getWidth-1, vpnnLen), vpn_reg(vpnnLen-1, 0)),
253        2.U -> ppn)
254      )
255    }
256  }
257
258  io.access := DontCare
259}
260
261object TlbStorage {
262  def apply
263  (
264    parentName: String,
265    associative: String,
266    ports: Int,
267    nDups: Int = 1,
268    nSets: Int,
269    nWays: Int,
270    saveLevel: Boolean = false,
271    normalPage: Boolean,
272    superPage: Boolean,
273    useDmode: Boolean,
274    SoftTLB: Boolean
275  )(implicit p: Parameters) = {
276    if (SoftTLB) {
277      val storage = Module(new TLBFakeFA(ports, nDups, nSets, nWays, useDmode))
278      storage.suggestName(s"${parentName}_fake_fa")
279      storage.io
280    } else {
281       val storage = Module(new TLBFA(parentName, ports, nDups, nSets, nWays, saveLevel, normalPage, superPage))
282       storage.suggestName(s"${parentName}_fa")
283       storage.io
284    }
285  }
286}
287
288class TlbStorageWrapper(ports: Int, q: TLBParameters, nDups: Int = 1)(implicit p: Parameters) extends TlbModule {
289  val io = IO(new TlbStorageWrapperIO(ports, q, nDups))
290
291  val page = TlbStorage(
292    parentName = q.name + "_storage",
293    associative = q.Associative,
294    ports = ports,
295    nDups = nDups,
296    nSets = q.NSets,
297    nWays = q.NWays,
298    normalPage = true,
299    superPage = true,
300    useDmode = q.useDmode,
301    SoftTLB = coreParams.softTLB
302  )
303
304  for (i <- 0 until ports) {
305    page.r_req_apply(
306      valid = io.r.req(i).valid,
307      vpn = io.r.req(i).bits.vpn,
308      i = i
309    )
310  }
311
312  for (i <- 0 until ports) {
313    val q = page.r.req(i)
314    val p = page.r.resp(i)
315    val rq = io.r.req(i)
316    val rp = io.r.resp(i)
317    rq.ready := q.ready // actually, not used
318    rp.valid := p.valid // actually, not used
319    rp.bits.hit := p.bits.hit
320    for (d <- 0 until nDups) {
321      rp.bits.ppn(d) := p.bits.ppn(d)
322      rp.bits.perm(d).pf := p.bits.perm(d).pf
323      rp.bits.perm(d).af := p.bits.perm(d).af
324      rp.bits.perm(d).d := p.bits.perm(d).d
325      rp.bits.perm(d).a := p.bits.perm(d).a
326      rp.bits.perm(d).g := p.bits.perm(d).g
327      rp.bits.perm(d).u := p.bits.perm(d).u
328      rp.bits.perm(d).x := p.bits.perm(d).x
329      rp.bits.perm(d).w := p.bits.perm(d).w
330      rp.bits.perm(d).r := p.bits.perm(d).r
331    }
332  }
333
334  page.sfence <> io.sfence
335  page.csr <> io.csr
336
337  val refill_idx = if (q.outReplace) {
338    io.replace.page.access <> page.access
339    io.replace.page.chosen_set := DontCare
340    io.replace.page.refillIdx
341  } else {
342    val re = ReplacementPolicy.fromString(q.Replacer, q.NWays)
343    re.access(page.access.map(_.touch_ways))
344    re.way
345  }
346
347  page.w_apply(
348    valid = io.w.valid,
349    wayIdx = refill_idx,
350    data = io.w.bits.data
351  )
352
353    // replacement
354  def get_access(one_hot: UInt, valid: Bool): Valid[UInt] = {
355    val res = Wire(Valid(UInt(log2Up(one_hot.getWidth).W)))
356    res.valid := Cat(one_hot).orR && valid
357    res.bits := OHToUInt(one_hot)
358    res
359  }
360}
361