xref: /XiangShan/src/main/scala/xiangshan/frontend/icache/ICache.scala (revision 602aa9f1a8fb63310bea30e8b3e247e5aca5f123)
1/***************************************************************************************
2* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
4* Copyright (c) 2020-2021 Peng Cheng Laboratory
5*
6* XiangShan is licensed under Mulan PSL v2.
7* You can use this software according to the terms and conditions of the Mulan PSL v2.
8* You may obtain a copy of Mulan PSL v2 at:
9*          http://license.coscl.org.cn/MulanPSL2
10*
11* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
12* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
13* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
14*
15* See the Mulan PSL v2 for more details.
16*
17*
18* Acknowledgement
19*
20* This implementation is inspired by several key papers:
21* [1] Glenn Reinman, Brad Calder, and Todd Austin. "[Fetch directed instruction prefetching.]
22* (https://doi.org/10.1109/MICRO.1999.809439)" 32nd Annual ACM/IEEE International Symposium on Microarchitecture
23* (MICRO). 1999.
24***************************************************************************************/
25
26package xiangshan.frontend.icache
27
28import chisel3._
29import chisel3.util._
30import freechips.rocketchip.diplomacy.AddressSet
31import freechips.rocketchip.diplomacy.IdRange
32import freechips.rocketchip.diplomacy.LazyModule
33import freechips.rocketchip.diplomacy.LazyModuleImp
34import freechips.rocketchip.tilelink._
35import freechips.rocketchip.util.BundleFieldBase
36import huancun.AliasField
37import huancun.PrefetchField
38import org.chipsalliance.cde.config.Parameters
39import utility._
40import utility.mbist.MbistPipeline
41import utility.sram.SplittedSRAMTemplate
42import utility.sram.SRAMReadBus
43import utility.sram.SRAMTemplate
44import utility.sram.SRAMWriteBus
45import utils._
46import xiangshan._
47import xiangshan.cache._
48import xiangshan.cache.mmu.TlbRequestIO
49import xiangshan.frontend._
50
51case class ICacheParameters(
52    nSets:               Int = 256,
53    nWays:               Int = 4,
54    rowBits:             Int = 64,
55    nTLBEntries:         Int = 32,
56    tagECC:              Option[String] = None,
57    dataECC:             Option[String] = None,
58    replacer:            Option[String] = Some("random"),
59    PortNumber:          Int = 2,
60    nFetchMshr:          Int = 4,
61    nPrefetchMshr:       Int = 10,
62    nWayLookupSize:      Int = 32,
63    DataCodeUnit:        Int = 64,
64    ICacheDataBanks:     Int = 8,
65    ICacheDataSRAMWidth: Int = 66,
66    // TODO: hard code, need delete
67    partWayNum:          Int = 4,
68    nMMIOs:              Int = 1,
69    blockBytes:          Int = 64,
70    cacheCtrlAddressOpt: Option[AddressSet] = None
71) extends L1CacheParameters {
72
73  val setBytes:     Int         = nSets * blockBytes
74  val aliasBitsOpt: Option[Int] = Option.when(setBytes > pageSize)(log2Ceil(setBytes / pageSize))
75  val reqFields: Seq[BundleFieldBase] = Seq(
76    PrefetchField(),
77    ReqSourceField()
78  ) ++ aliasBitsOpt.map(AliasField)
79  val echoFields: Seq[BundleFieldBase] = Nil
80  def tagCode:    Code                 = Code.fromString(tagECC)
81  def dataCode:   Code                 = Code.fromString(dataECC)
82  def replacement = ReplacementPolicy.fromString(replacer, nWays, nSets)
83}
84
85trait HasICacheParameters extends HasL1CacheParameters with HasInstrMMIOConst with HasIFUConst {
86  val cacheParams: ICacheParameters = icacheParameters
87
88  def ctrlUnitParamsOpt: Option[L1ICacheCtrlParams] = OptionWrapper(
89    cacheParams.cacheCtrlAddressOpt.nonEmpty,
90    L1ICacheCtrlParams(
91      address = cacheParams.cacheCtrlAddressOpt.get,
92      regWidth = XLEN
93    )
94  )
95
96  def ICacheSets:          Int = cacheParams.nSets
97  def ICacheWays:          Int = cacheParams.nWays
98  def PortNumber:          Int = cacheParams.PortNumber
99  def nFetchMshr:          Int = cacheParams.nFetchMshr
100  def nPrefetchMshr:       Int = cacheParams.nPrefetchMshr
101  def nWayLookupSize:      Int = cacheParams.nWayLookupSize
102  def DataCodeUnit:        Int = cacheParams.DataCodeUnit
103  def ICacheDataBanks:     Int = cacheParams.ICacheDataBanks
104  def ICacheDataSRAMWidth: Int = cacheParams.ICacheDataSRAMWidth
105  def partWayNum:          Int = cacheParams.partWayNum
106
107  def ICacheMetaBits:      Int = tagBits // FIXME: unportable: maybe use somemethod to get width
108  def ICacheMetaCodeBits:  Int = 1       // FIXME: unportable: maybe use cacheParams.tagCode.somemethod to get width
109  def ICacheMetaEntryBits: Int = ICacheMetaBits + ICacheMetaCodeBits
110
111  def ICacheDataBits: Int = blockBits / ICacheDataBanks
112  def ICacheDataCodeSegs: Int =
113    math.ceil(ICacheDataBits / DataCodeUnit).toInt // split data to segments for ECC checking
114  def ICacheDataCodeBits: Int =
115    ICacheDataCodeSegs * 1 // FIXME: unportable: maybe use cacheParams.dataCode.somemethod to get width
116  def ICacheDataEntryBits: Int = ICacheDataBits + ICacheDataCodeBits
117  def ICacheBankVisitNum:  Int = 32 * 8 / ICacheDataBits + 1
118  def highestIdxBit:       Int = log2Ceil(nSets) - 1
119
120  require((ICacheDataBanks >= 2) && isPow2(ICacheDataBanks))
121  require(ICacheDataSRAMWidth >= ICacheDataEntryBits)
122  require(isPow2(ICacheSets), s"nSets($ICacheSets) must be pow2")
123  require(isPow2(ICacheWays), s"nWays($ICacheWays) must be pow2")
124
125  def generatePipeControl(lastFire: Bool, thisFire: Bool, thisFlush: Bool, lastFlush: Bool): Bool = {
126    val valid = RegInit(false.B)
127    when(thisFlush)(valid := false.B)
128      .elsewhen(lastFire && !lastFlush)(valid := true.B)
129      .elsewhen(thisFire)(valid := false.B)
130    valid
131  }
132
133  def ResultHoldBypass[T <: Data](data: T, valid: Bool): T =
134    Mux(valid, data, RegEnable(data, valid))
135
136  def ResultHoldBypass[T <: Data](data: T, init: T, valid: Bool): T =
137    Mux(valid, data, RegEnable(data, init, valid))
138
139  def holdReleaseLatch(valid: Bool, release: Bool, flush: Bool): Bool = {
140    val bit = RegInit(false.B)
141    when(flush)(bit := false.B)
142      .elsewhen(valid && !release)(bit := true.B)
143      .elsewhen(release)(bit := false.B)
144    bit || valid
145  }
146
147  def blockCounter(block: Bool, flush: Bool, threshold: Int): Bool = {
148    val counter = RegInit(0.U(log2Up(threshold + 1).W))
149    when(block)(counter := counter + 1.U)
150    when(flush)(counter := 0.U)
151    counter > threshold.U
152  }
153
154  def InitQueue[T <: Data](entry: T, size: Int): Vec[T] =
155    RegInit(VecInit(Seq.fill(size)(0.U.asTypeOf(entry.cloneType))))
156
157  def getBankSel(blkOffset: UInt, valid: Bool = true.B): Vec[UInt] = {
158    val bankIdxLow  = (Cat(0.U(1.W), blkOffset) >> log2Ceil(blockBytes / ICacheDataBanks)).asUInt
159    val bankIdxHigh = ((Cat(0.U(1.W), blkOffset) + 32.U) >> log2Ceil(blockBytes / ICacheDataBanks)).asUInt
160    val bankSel     = VecInit((0 until ICacheDataBanks * 2).map(i => (i.U >= bankIdxLow) && (i.U <= bankIdxHigh)))
161    assert(
162      !valid || PopCount(bankSel) === ICacheBankVisitNum.U,
163      "The number of bank visits must be %d, but bankSel=0x%x",
164      ICacheBankVisitNum.U,
165      bankSel.asUInt
166    )
167    bankSel.asTypeOf(UInt((ICacheDataBanks * 2).W)).asTypeOf(Vec(2, UInt(ICacheDataBanks.W)))
168  }
169
170  def getLineSel(blkOffset: UInt): Vec[Bool] = {
171    val bankIdxLow = (blkOffset >> log2Ceil(blockBytes / ICacheDataBanks)).asUInt
172    val lineSel    = VecInit((0 until ICacheDataBanks).map(i => i.U < bankIdxLow))
173    lineSel
174  }
175
176  def getBlkAddr(addr:        UInt): UInt = (addr >> blockOffBits).asUInt
177  def getPhyTagFromBlk(addr:  UInt): UInt = (addr >> (pgUntagBits - blockOffBits)).asUInt
178  def getIdxFromBlk(addr:     UInt): UInt = addr(idxBits - 1, 0)
179  def getPaddrFromPtag(vaddr: UInt, ptag: UInt): UInt = Cat(ptag, vaddr(pgUntagBits - 1, 0))
180  def getPaddrFromPtag(vaddrVec: Vec[UInt], ptagVec: Vec[UInt]): Vec[UInt] =
181    VecInit((vaddrVec zip ptagVec).map { case (vaddr, ptag) => getPaddrFromPtag(vaddr, ptag) })
182}
183
184trait HasICacheECCHelper extends HasICacheParameters {
185  def encodeMetaECC(meta: UInt, poison: Bool = false.B): UInt = {
186    require(meta.getWidth == ICacheMetaBits)
187    val code = cacheParams.tagCode.encode(meta, poison) >> ICacheMetaBits
188    code.asTypeOf(UInt(ICacheMetaCodeBits.W))
189  }
190
191  def encodeDataECC(data: UInt, poison: Bool = false.B): UInt = {
192    require(data.getWidth == ICacheDataBits)
193    val datas = data.asTypeOf(Vec(ICacheDataCodeSegs, UInt((ICacheDataBits / ICacheDataCodeSegs).W)))
194    val codes = VecInit(datas.map(cacheParams.dataCode.encode(_, poison) >> (ICacheDataBits / ICacheDataCodeSegs)))
195    codes.asTypeOf(UInt(ICacheDataCodeBits.W))
196  }
197}
198
199abstract class ICacheBundle(implicit p: Parameters) extends XSBundle
200    with HasICacheParameters
201
202abstract class ICacheModule(implicit p: Parameters) extends XSModule
203    with HasICacheParameters
204
205abstract class ICacheArray(implicit p: Parameters) extends XSModule
206    with HasICacheParameters
207
208class ICacheMetadata(implicit p: Parameters) extends ICacheBundle {
209  val tag: UInt = UInt(tagBits.W)
210}
211
212object ICacheMetadata {
213  def apply(tag: Bits)(implicit p: Parameters): ICacheMetadata = {
214    val meta = Wire(new ICacheMetadata)
215    meta.tag := tag
216    meta
217  }
218}
219
220class ICacheMetaArrayIO(implicit p: Parameters) extends ICacheBundle {
221  val write:    DecoupledIO[ICacheMetaWriteBundle] = Flipped(DecoupledIO(new ICacheMetaWriteBundle))
222  val read:     DecoupledIO[ICacheReadBundle]      = Flipped(DecoupledIO(new ICacheReadBundle))
223  val readResp: ICacheMetaRespBundle               = Output(new ICacheMetaRespBundle)
224  val flush:    Vec[Valid[ICacheMetaFlushBundle]]  = Vec(PortNumber, Flipped(ValidIO(new ICacheMetaFlushBundle)))
225  val flushAll: Bool                               = Input(Bool())
226}
227
228class ICacheMetaArray(implicit p: Parameters) extends ICacheArray with HasICacheECCHelper {
229  class ICacheMetaEntry(implicit p: Parameters) extends ICacheBundle {
230    val meta: ICacheMetadata = new ICacheMetadata
231    val code: UInt           = UInt(ICacheMetaCodeBits.W)
232  }
233
234  private object ICacheMetaEntry {
235    def apply(meta: ICacheMetadata, poison: Bool)(implicit p: Parameters): ICacheMetaEntry = {
236      val entry = Wire(new ICacheMetaEntry)
237      entry.meta := meta
238      entry.code := encodeMetaECC(meta.asUInt, poison)
239      entry
240    }
241  }
242
243  // sanity check
244  require(ICacheMetaEntryBits == (new ICacheMetaEntry).getWidth)
245
246  val io: ICacheMetaArrayIO = IO(new ICacheMetaArrayIO)
247
248  private val port_0_read_0 = io.read.valid && !io.read.bits.vSetIdx(0)(0)
249  private val port_0_read_1 = io.read.valid && io.read.bits.vSetIdx(0)(0)
250  private val port_1_read_1 = io.read.valid && io.read.bits.vSetIdx(1)(0) && io.read.bits.isDoubleLine
251  private val port_1_read_0 = io.read.valid && !io.read.bits.vSetIdx(1)(0) && io.read.bits.isDoubleLine
252
253  private val port_0_read_0_reg = RegEnable(port_0_read_0, 0.U.asTypeOf(port_0_read_0), io.read.fire)
254  private val port_0_read_1_reg = RegEnable(port_0_read_1, 0.U.asTypeOf(port_0_read_1), io.read.fire)
255  private val port_1_read_1_reg = RegEnable(port_1_read_1, 0.U.asTypeOf(port_1_read_1), io.read.fire)
256  private val port_1_read_0_reg = RegEnable(port_1_read_0, 0.U.asTypeOf(port_1_read_0), io.read.fire)
257
258  private val bank_0_idx = Mux(port_0_read_0, io.read.bits.vSetIdx(0), io.read.bits.vSetIdx(1))
259  private val bank_1_idx = Mux(port_0_read_1, io.read.bits.vSetIdx(0), io.read.bits.vSetIdx(1))
260
261  private val write_bank_0 = io.write.valid && !io.write.bits.bankIdx
262  private val write_bank_1 = io.write.valid && io.write.bits.bankIdx
263
264  private val write_meta_bits = ICacheMetaEntry(
265    meta = ICacheMetadata(
266      tag = io.write.bits.phyTag
267    ),
268    poison = io.write.bits.poison
269  )
270
271  private val tagArrays = (0 until PortNumber) map { bank =>
272    val tagArray = Module(new SplittedSRAMTemplate(
273      new ICacheMetaEntry(),
274      set = nSets / PortNumber,
275      way = nWays,
276      waySplit = 2,
277      dataSplit = 1,
278      shouldReset = true,
279      holdRead = true,
280      singlePort = true,
281      withClockGate = true,
282      hasMbist = hasMbist
283    ))
284
285    // meta connection
286    if (bank == 0) {
287      tagArray.io.r.req.valid := port_0_read_0 || port_1_read_0
288      tagArray.io.r.req.bits.apply(setIdx = bank_0_idx(highestIdxBit, 1))
289      tagArray.io.w.req.valid := write_bank_0
290      tagArray.io.w.req.bits.apply(
291        data = write_meta_bits,
292        setIdx = io.write.bits.virIdx(highestIdxBit, 1),
293        waymask = io.write.bits.waymask
294      )
295    } else {
296      tagArray.io.r.req.valid := port_0_read_1 || port_1_read_1
297      tagArray.io.r.req.bits.apply(setIdx = bank_1_idx(highestIdxBit, 1))
298      tagArray.io.w.req.valid := write_bank_1
299      tagArray.io.w.req.bits.apply(
300        data = write_meta_bits,
301        setIdx = io.write.bits.virIdx(highestIdxBit, 1),
302        waymask = io.write.bits.waymask
303      )
304    }
305
306    tagArray
307  }
308  private val mbistPl = MbistPipeline.PlaceMbistPipeline(1, "MbistPipeIcacheTag", hasMbist)
309
310  private val read_set_idx_next = RegEnable(io.read.bits.vSetIdx, 0.U.asTypeOf(io.read.bits.vSetIdx), io.read.fire)
311  private val valid_array       = RegInit(VecInit(Seq.fill(nWays)(0.U(nSets.W))))
312  private val valid_metas       = Wire(Vec(PortNumber, Vec(nWays, Bool())))
313  // valid read
314  (0 until PortNumber).foreach(i =>
315    (0 until nWays).foreach(way =>
316      valid_metas(i)(way) := valid_array(way)(read_set_idx_next(i))
317    )
318  )
319  io.readResp.entryValid := valid_metas
320
321  io.read.ready := !io.write.valid && !io.flush.map(_.valid).reduce(_ || _) && !io.flushAll &&
322    tagArrays.map(_.io.r.req.ready).reduce(_ && _)
323
324  // valid write
325  private val way_num = OHToUInt(io.write.bits.waymask)
326  when(io.write.valid) {
327    valid_array(way_num) := valid_array(way_num).bitSet(io.write.bits.virIdx, true.B)
328  }
329
330  XSPerfAccumulate("meta_refill_num", io.write.valid)
331
332  io.readResp.metas <> DontCare
333  io.readResp.codes <> DontCare
334  private val readMetaEntries = tagArrays.map(port => port.io.r.resp.asTypeOf(Vec(nWays, new ICacheMetaEntry())))
335  private val readMetas       = readMetaEntries.map(_.map(_.meta))
336  private val readCodes       = readMetaEntries.map(_.map(_.code))
337
338  // TEST: force ECC to fail by setting readCodes to 0
339  if (ICacheForceMetaECCError) {
340    readCodes.foreach(_.foreach(_ := 0.U))
341  }
342
343  when(port_0_read_0_reg) {
344    io.readResp.metas(0) := readMetas(0)
345    io.readResp.codes(0) := readCodes(0)
346  }.elsewhen(port_0_read_1_reg) {
347    io.readResp.metas(0) := readMetas(1)
348    io.readResp.codes(0) := readCodes(1)
349  }
350
351  when(port_1_read_0_reg) {
352    io.readResp.metas(1) := readMetas(0)
353    io.readResp.codes(1) := readCodes(0)
354  }.elsewhen(port_1_read_1_reg) {
355    io.readResp.metas(1) := readMetas(1)
356    io.readResp.codes(1) := readCodes(1)
357  }
358
359  io.write.ready := true.B // TODO : has bug ? should be !io.cacheOp.req.valid
360
361  /*
362   * flush logic
363   */
364  // flush standalone set (e.g. flushed by mainPipe before doing re-fetch)
365  when(io.flush.map(_.valid).reduce(_ || _)) {
366    (0 until nWays).foreach { w =>
367      valid_array(w) := (0 until PortNumber).map { i =>
368        Mux(
369          // check if set `virIdx` in way `w` is requested to be flushed by port `i`
370          io.flush(i).valid && io.flush(i).bits.waymask(w),
371          valid_array(w).bitSet(io.flush(i).bits.virIdx, false.B),
372          valid_array(w)
373        )
374      }.reduce(_ & _)
375    }
376  }
377
378  // flush all (e.g. fence.i)
379  when(io.flushAll) {
380    (0 until nWays).foreach(w => valid_array(w) := 0.U)
381  }
382
383  // PERF: flush counter
384  XSPerfAccumulate("flush", io.flush.map(_.valid).reduce(_ || _))
385  XSPerfAccumulate("flush_all", io.flushAll)
386}
387
388class ICacheDataArrayIO(implicit p: Parameters) extends ICacheBundle {
389  val write:    DecoupledIO[ICacheDataWriteBundle] = Flipped(DecoupledIO(new ICacheDataWriteBundle))
390  val read:     Vec[DecoupledIO[ICacheReadBundle]] = Flipped(Vec(partWayNum, DecoupledIO(new ICacheReadBundle)))
391  val readResp: ICacheDataRespBundle               = Output(new ICacheDataRespBundle)
392}
393
394class ICacheDataArray(implicit p: Parameters) extends ICacheArray with HasICacheECCHelper {
395  class ICacheDataEntry(implicit p: Parameters) extends ICacheBundle {
396    val data: UInt = UInt(ICacheDataBits.W)
397    val code: UInt = UInt(ICacheDataCodeBits.W)
398  }
399
400  private object ICacheDataEntry {
401    def apply(data: UInt, poison: Bool)(implicit p: Parameters): ICacheDataEntry = {
402      val entry = Wire(new ICacheDataEntry)
403      entry.data := data
404      entry.code := encodeDataECC(data, poison)
405      entry
406    }
407  }
408
409  val io: ICacheDataArrayIO = IO(new ICacheDataArrayIO)
410
411  /**
412    ******************************************************************************
413    * data array
414    ******************************************************************************
415    */
416  private val writeDatas   = io.write.bits.data.asTypeOf(Vec(ICacheDataBanks, UInt(ICacheDataBits.W)))
417  private val writeEntries = writeDatas.map(ICacheDataEntry(_, io.write.bits.poison).asUInt)
418
419  // io.read() are copies to control fan-out, we can simply use .head here
420  private val bankSel  = getBankSel(io.read.head.bits.blkOffset, io.read.head.valid)
421  private val lineSel  = getLineSel(io.read.head.bits.blkOffset)
422  private val waymasks = io.read.head.bits.waymask
423  private val masks    = Wire(Vec(nWays, Vec(ICacheDataBanks, Bool())))
424  (0 until nWays).foreach { way =>
425    (0 until ICacheDataBanks).foreach { bank =>
426      masks(way)(bank) := Mux(
427        lineSel(bank),
428        waymasks(1)(way) && bankSel(1)(bank).asBool,
429        waymasks(0)(way) && bankSel(0)(bank).asBool
430      )
431    }
432  }
433
434  private val dataArrays = (0 until nWays).map { way =>
435    val banks = (0 until ICacheDataBanks).map { bank =>
436      val sramBank = Module(new SRAMTemplateWithFixedWidth(
437        UInt(ICacheDataEntryBits.W),
438        set = nSets,
439        width = ICacheDataSRAMWidth,
440        shouldReset = true,
441        holdRead = true,
442        singlePort = true,
443        withClockGate = false, // enable signal timing is bad, no gating here
444        hasMbist = hasMbist
445      ))
446
447      // read
448      sramBank.io.r.req.valid := io.read(bank % 4).valid && masks(way)(bank)
449      sramBank.io.r.req.bits.apply(setIdx =
450        Mux(lineSel(bank), io.read(bank % 4).bits.vSetIdx(1), io.read(bank % 4).bits.vSetIdx(0))
451      )
452      // write
453      sramBank.io.w.req.valid := io.write.valid && io.write.bits.waymask(way).asBool
454      sramBank.io.w.req.bits.apply(
455        data = writeEntries(bank),
456        setIdx = io.write.bits.virIdx,
457        // waymask is invalid when way of SRAMTemplate <= 1
458        waymask = 0.U
459      )
460      sramBank
461    }
462    MbistPipeline.PlaceMbistPipeline(1, s"MbistPipeIcacheDataWay${way}", hasMbist)
463    banks
464  }
465
466  /**
467    ******************************************************************************
468    * read logic
469    ******************************************************************************
470    */
471  private val masksReg = RegEnable(masks, 0.U.asTypeOf(masks), io.read(0).valid)
472  private val readDataWithCode = (0 until ICacheDataBanks).map { bank =>
473    Mux1H(VecInit(masksReg.map(_(bank))).asTypeOf(UInt(nWays.W)), dataArrays.map(_(bank).io.r.resp.asUInt))
474  }
475  private val readEntries = readDataWithCode.map(_.asTypeOf(new ICacheDataEntry()))
476  private val readDatas   = VecInit(readEntries.map(_.data))
477  private val readCodes   = VecInit(readEntries.map(_.code))
478
479  // TEST: force ECC to fail by setting readCodes to 0
480  if (ICacheForceDataECCError) {
481    readCodes.foreach(_ := 0.U)
482  }
483
484  /**
485    ******************************************************************************
486    * IO
487    ******************************************************************************
488    */
489  io.readResp.datas := readDatas
490  io.readResp.codes := readCodes
491  io.write.ready    := true.B
492  io.read.foreach(_.ready := !io.write.valid)
493}
494
495class ICacheReplacerIO(implicit p: Parameters) extends ICacheBundle {
496  val touch:  Vec[Valid[ReplacerTouch]] = Vec(PortNumber, Flipped(ValidIO(new ReplacerTouch)))
497  val victim: ReplacerVictim            = Flipped(new ReplacerVictim)
498}
499
500class ICacheReplacer(implicit p: Parameters) extends ICacheModule {
501  val io: ICacheReplacerIO = IO(new ICacheReplacerIO)
502
503  private val replacers =
504    Seq.fill(PortNumber)(ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets / PortNumber))
505
506  // touch
507  private val touch_sets = Seq.fill(PortNumber)(Wire(Vec(PortNumber, UInt(log2Ceil(nSets / PortNumber).W))))
508  private val touch_ways = Seq.fill(PortNumber)(Wire(Vec(PortNumber, Valid(UInt(wayBits.W)))))
509  (0 until PortNumber).foreach { i =>
510    touch_sets(i)(0) := Mux(
511      io.touch(i).bits.vSetIdx(0),
512      io.touch(1).bits.vSetIdx(highestIdxBit, 1),
513      io.touch(0).bits.vSetIdx(highestIdxBit, 1)
514    )
515    touch_ways(i)(0).bits  := Mux(io.touch(i).bits.vSetIdx(0), io.touch(1).bits.way, io.touch(0).bits.way)
516    touch_ways(i)(0).valid := Mux(io.touch(i).bits.vSetIdx(0), io.touch(1).valid, io.touch(0).valid)
517  }
518
519  // victim
520  io.victim.way := Mux(
521    io.victim.vSetIdx.bits(0),
522    replacers(1).way(io.victim.vSetIdx.bits(highestIdxBit, 1)),
523    replacers(0).way(io.victim.vSetIdx.bits(highestIdxBit, 1))
524  )
525
526  // touch the victim in next cycle
527  private val victim_vSetIdx_reg =
528    RegEnable(io.victim.vSetIdx.bits, 0.U.asTypeOf(io.victim.vSetIdx.bits), io.victim.vSetIdx.valid)
529  private val victim_way_reg = RegEnable(io.victim.way, 0.U.asTypeOf(io.victim.way), io.victim.vSetIdx.valid)
530  (0 until PortNumber).foreach { i =>
531    touch_sets(i)(1)       := victim_vSetIdx_reg(highestIdxBit, 1)
532    touch_ways(i)(1).bits  := victim_way_reg
533    touch_ways(i)(1).valid := RegNext(io.victim.vSetIdx.valid) && (victim_vSetIdx_reg(0) === i.U)
534  }
535
536  ((replacers zip touch_sets) zip touch_ways).foreach { case ((r, s), w) => r.access(s, w) }
537}
538
539class ICacheIO(implicit p: Parameters) extends ICacheBundle {
540  val hartId: UInt = Input(UInt(hartIdLen.W))
541  // FTQ
542  val fetch:       ICacheMainPipeBundle = new ICacheMainPipeBundle
543  val ftqPrefetch: FtqToPrefetchIO      = Flipped(new FtqToPrefetchIO)
544  // memblock
545  val softPrefetch: Vec[Valid[SoftIfetchPrefetchBundle]] =
546    Vec(backendParams.LduCnt, Flipped(Valid(new SoftIfetchPrefetchBundle)))
547  // IFU
548  val stop:  Bool = Input(Bool())
549  val toIFU: Bool = Output(Bool())
550  // PMP: mainPipe & prefetchPipe need PortNumber each
551  val pmp: Vec[ICachePMPBundle] = Vec(2 * PortNumber, new ICachePMPBundle)
552  // iTLB
553  val itlb:          Vec[TlbRequestIO] = Vec(PortNumber, new TlbRequestIO)
554  val itlbFlushPipe: Bool              = Bool()
555  // backend/BEU
556  val error: Valid[L1CacheErrorInfo] = ValidIO(new L1CacheErrorInfo)
557  // backend/CSR
558  val csr_pf_enable: Bool = Input(Bool())
559  // flush
560  val fencei: Bool = Input(Bool())
561  val flush:  Bool = Input(Bool())
562
563  // perf
564  val perfInfo: ICachePerfInfo = Output(new ICachePerfInfo)
565}
566
567class ICache()(implicit p: Parameters) extends LazyModule with HasICacheParameters {
568  override def shouldBeInlined: Boolean = false
569
570  val clientParameters: TLMasterPortParameters = TLMasterPortParameters.v1(
571    Seq(TLMasterParameters.v1(
572      name = "icache",
573      sourceId = IdRange(0, cacheParams.nFetchMshr + cacheParams.nPrefetchMshr + 1)
574    )),
575    requestFields = cacheParams.reqFields,
576    echoFields = cacheParams.echoFields
577  )
578
579  val clientNode: TLClientNode = TLClientNode(Seq(clientParameters))
580
581  val ctrlUnitOpt: Option[ICacheCtrlUnit] = ctrlUnitParamsOpt.map(params => LazyModule(new ICacheCtrlUnit(params)))
582
583  lazy val module: ICacheImp = new ICacheImp(this)
584}
585
586class ICacheImp(outer: ICache) extends LazyModuleImp(outer) with HasICacheParameters with HasPerfEvents {
587  val io: ICacheIO = IO(new ICacheIO)
588
589  println("ICache:")
590  println("  TagECC: " + cacheParams.tagECC)
591  println("  DataECC: " + cacheParams.dataECC)
592  println("  ICacheSets: " + cacheParams.nSets)
593  println("  ICacheWays: " + cacheParams.nWays)
594  println("  PortNumber: " + cacheParams.PortNumber)
595  println("  nFetchMshr: " + cacheParams.nFetchMshr)
596  println("  nPrefetchMshr: " + cacheParams.nPrefetchMshr)
597  println("  nWayLookupSize: " + cacheParams.nWayLookupSize)
598  println("  DataCodeUnit: " + cacheParams.DataCodeUnit)
599  println("  ICacheDataBanks: " + cacheParams.ICacheDataBanks)
600  println("  ICacheDataSRAMWidth: " + cacheParams.ICacheDataSRAMWidth)
601
602  val (bus, edge) = outer.clientNode.out.head
603
604  private val metaArray  = Module(new ICacheMetaArray)
605  private val dataArray  = Module(new ICacheDataArray)
606  private val mainPipe   = Module(new ICacheMainPipe)
607  private val missUnit   = Module(new ICacheMissUnit(edge))
608  private val replacer   = Module(new ICacheReplacer)
609  private val prefetcher = Module(new IPrefetchPipe)
610  private val wayLookup  = Module(new WayLookup)
611
612  private val ecc_enable = if (outer.ctrlUnitOpt.nonEmpty) outer.ctrlUnitOpt.get.module.io.ecc_enable else true.B
613
614  // dataArray io
615  if (outer.ctrlUnitOpt.nonEmpty) {
616    val ctrlUnit = outer.ctrlUnitOpt.get.module
617    when(ctrlUnit.io.injecting) {
618      dataArray.io.write <> ctrlUnit.io.dataWrite
619      missUnit.io.data_write.ready := false.B
620    }.otherwise {
621      ctrlUnit.io.dataWrite.ready := false.B
622      dataArray.io.write <> missUnit.io.data_write
623    }
624  } else {
625    dataArray.io.write <> missUnit.io.data_write
626  }
627  dataArray.io.read <> mainPipe.io.dataArray.toIData
628  mainPipe.io.dataArray.fromIData := dataArray.io.readResp
629
630  // metaArray io
631  metaArray.io.flushAll := io.fencei
632  metaArray.io.flush <> mainPipe.io.metaArrayFlush
633  if (outer.ctrlUnitOpt.nonEmpty) {
634    val ctrlUnit = outer.ctrlUnitOpt.get.module
635    when(ctrlUnit.io.injecting) {
636      metaArray.io.write <> ctrlUnit.io.metaWrite
637      metaArray.io.read <> ctrlUnit.io.metaRead
638      missUnit.io.meta_write.ready         := false.B
639      prefetcher.io.metaRead.toIMeta.ready := false.B
640    }.otherwise {
641      ctrlUnit.io.metaWrite.ready := false.B
642      ctrlUnit.io.metaRead.ready  := false.B
643      metaArray.io.write <> missUnit.io.meta_write
644      metaArray.io.read <> prefetcher.io.metaRead.toIMeta
645    }
646    ctrlUnit.io.metaReadResp := metaArray.io.readResp
647  } else {
648    metaArray.io.write <> missUnit.io.meta_write
649    metaArray.io.read <> prefetcher.io.metaRead.toIMeta
650  }
651  prefetcher.io.metaRead.fromIMeta := metaArray.io.readResp
652
653  prefetcher.io.flush         := io.flush
654  prefetcher.io.csr_pf_enable := io.csr_pf_enable
655  prefetcher.io.ecc_enable    := ecc_enable
656  prefetcher.io.MSHRResp      := missUnit.io.fetch_resp
657  prefetcher.io.flushFromBpu  := io.ftqPrefetch.flushFromBpu
658  // cache softPrefetch
659  private val softPrefetchValid = RegInit(false.B)
660  private val softPrefetch      = RegInit(0.U.asTypeOf(new IPrefetchReq))
661  /* FIXME:
662   * If there is already a pending softPrefetch request, it will be overwritten.
663   * Also, if there are multiple softPrefetch requests in the same cycle, only the first one will be accepted.
664   * We should implement a softPrefetchQueue (like ibuffer, multi-in, single-out) to solve this.
665   * However, the impact on performance still needs to be assessed.
666   * Considering that the frequency of prefetch.i may not be high, let's start with a temporary dummy solution.
667   */
668  when(io.softPrefetch.map(_.valid).reduce(_ || _)) {
669    softPrefetchValid := true.B
670    softPrefetch.fromSoftPrefetch(MuxCase(
671      0.U.asTypeOf(new SoftIfetchPrefetchBundle),
672      io.softPrefetch.map(req => req.valid -> req.bits)
673    ))
674  }.elsewhen(prefetcher.io.req.fire) {
675    softPrefetchValid := false.B
676  }
677  // pass ftqPrefetch
678  private val ftqPrefetch = WireInit(0.U.asTypeOf(new IPrefetchReq))
679  ftqPrefetch.fromFtqICacheInfo(io.ftqPrefetch.req.bits)
680  // software prefetch has higher priority
681  prefetcher.io.req.valid                 := softPrefetchValid || io.ftqPrefetch.req.valid
682  prefetcher.io.req.bits                  := Mux(softPrefetchValid, softPrefetch, ftqPrefetch)
683  prefetcher.io.req.bits.backendException := io.ftqPrefetch.backendException
684  io.ftqPrefetch.req.ready                := prefetcher.io.req.ready && !softPrefetchValid
685
686  missUnit.io.hartId := io.hartId
687  missUnit.io.fencei := io.fencei
688  missUnit.io.flush  := io.flush
689  missUnit.io.fetch_req <> mainPipe.io.mshr.req
690  missUnit.io.prefetch_req <> prefetcher.io.MSHRReq
691  missUnit.io.mem_grant.valid := false.B
692  missUnit.io.mem_grant.bits  := DontCare
693  missUnit.io.mem_grant <> bus.d
694
695  mainPipe.io.flush      := io.flush
696  mainPipe.io.respStall  := io.stop
697  mainPipe.io.ecc_enable := ecc_enable
698  mainPipe.io.hartId     := io.hartId
699  mainPipe.io.mshr.resp  := missUnit.io.fetch_resp
700  mainPipe.io.fetch.req <> io.fetch.req
701  mainPipe.io.wayLookupRead <> wayLookup.io.read
702
703  wayLookup.io.flush := io.flush
704  wayLookup.io.write <> prefetcher.io.wayLookupWrite
705  wayLookup.io.update := missUnit.io.fetch_resp
706
707  replacer.io.touch <> mainPipe.io.touch
708  replacer.io.victim <> missUnit.io.victim
709
710  io.pmp(0) <> mainPipe.io.pmp(0)
711  io.pmp(1) <> mainPipe.io.pmp(1)
712  io.pmp(2) <> prefetcher.io.pmp(0)
713  io.pmp(3) <> prefetcher.io.pmp(1)
714
715  io.itlb(0) <> prefetcher.io.itlb(0)
716  io.itlb(1) <> prefetcher.io.itlb(1)
717  io.itlbFlushPipe := prefetcher.io.itlbFlushPipe
718
719  // notify IFU that Icache pipeline is available
720  io.toIFU    := mainPipe.io.fetch.req.ready
721  io.perfInfo := mainPipe.io.perfInfo
722
723  io.fetch.resp <> mainPipe.io.fetch.resp
724  io.fetch.topdownIcacheMiss := mainPipe.io.fetch.topdownIcacheMiss
725  io.fetch.topdownItlbMiss   := mainPipe.io.fetch.topdownItlbMiss
726
727  bus.b.ready := false.B
728  bus.c.valid := false.B
729  bus.c.bits  := DontCare
730  bus.e.valid := false.B
731  bus.e.bits  := DontCare
732
733  bus.a <> missUnit.io.mem_acquire
734
735  // Parity error port
736  private val errors       = mainPipe.io.errors
737  private val errors_valid = errors.map(e => e.valid).reduce(_ | _)
738  io.error.bits <> RegEnable(
739    PriorityMux(errors.map(e => e.valid -> e.bits)),
740    0.U.asTypeOf(errors(0).bits),
741    errors_valid
742  )
743  io.error.valid := RegNext(errors_valid, false.B)
744
745  XSPerfAccumulate(
746    "softPrefetch_drop_not_ready",
747    io.softPrefetch.map(_.valid).reduce(_ || _) && softPrefetchValid && !prefetcher.io.req.fire
748  )
749  XSPerfAccumulate("softPrefetch_drop_multi_req", PopCount(io.softPrefetch.map(_.valid)) > 1.U)
750  XSPerfAccumulate("softPrefetch_block_ftq", softPrefetchValid && io.ftqPrefetch.req.valid)
751
752  val perfEvents: Seq[(String, Bool)] = Seq(
753    ("icache_miss_cnt  ", false.B),
754    ("icache_miss_penalty", BoolStopWatch(start = false.B, stop = false.B || false.B, startHighPriority = true))
755  )
756  generatePerfEvent()
757}
758
759//class ICachePartWayReadBundle[T <: Data](gen: T, pWay: Int)(implicit p: Parameters)
760//    extends ICacheBundle {
761//  val req = Flipped(Vec(
762//    PortNumber,
763//    Decoupled(new Bundle {
764//      val ridx = UInt((log2Ceil(nSets) - 1).W)
765//    })
766//  ))
767//  val resp = Output(new Bundle {
768//    val rdata = Vec(PortNumber, Vec(pWay, gen))
769//  })
770//}
771
772//class ICacheWriteBundle[T <: Data](gen: T, pWay: Int)(implicit p: Parameters)
773//    extends ICacheBundle {
774//  val wdata    = gen
775//  val widx     = UInt((log2Ceil(nSets) - 1).W)
776//  val wbankidx = Bool()
777//  val wmask    = Vec(pWay, Bool())
778//}
779
780//class ICachePartWayArray[T <: Data](gen: T, pWay: Int)(implicit p: Parameters) extends ICacheArray {
781//
782//  // including part way data
783//  val io = IO {
784//    new Bundle {
785//      val read  = new ICachePartWayReadBundle(gen, pWay)
786//      val write = Flipped(ValidIO(new ICacheWriteBundle(gen, pWay)))
787//    }
788//  }
789//
790//  io.read.req.map(_.ready := !io.write.valid)
791//
792//  val srams = (0 until PortNumber) map { bank =>
793//    val sramBank = Module(new SRAMTemplate(
794//      gen,
795//      set = nSets / 2,
796//      way = pWay,
797//      shouldReset = true,
798//      holdRead = true,
799//      singlePort = true,
800//      withClockGate = true
801//    ))
802//
803//    sramBank.io.r.req.valid := io.read.req(bank).valid
804//    sramBank.io.r.req.bits.apply(setIdx = io.read.req(bank).bits.ridx)
805//
806//    if (bank == 0) sramBank.io.w.req.valid := io.write.valid && !io.write.bits.wbankidx
807//    else sramBank.io.w.req.valid           := io.write.valid && io.write.bits.wbankidx
808//    sramBank.io.w.req.bits.apply(
809//      data = io.write.bits.wdata,
810//      setIdx = io.write.bits.widx,
811//      waymask = io.write.bits.wmask.asUInt
812//    )
813//
814//    sramBank
815//  }
816//
817//  io.read.req.map(_.ready := !io.write.valid && srams.map(_.io.r.req.ready).reduce(_ && _))
818//
819//  io.read.resp.rdata := VecInit(srams.map(bank => bank.io.r.resp.asTypeOf(Vec(pWay, gen))))
820//
821//}
822
823class SRAMTemplateWithFixedWidthIO[T <: Data](gen: T, set: Int, way: Int) extends Bundle {
824  val r: SRAMReadBus[T]  = Flipped(new SRAMReadBus(gen, set, way))
825  val w: SRAMWriteBus[T] = Flipped(new SRAMWriteBus(gen, set, way))
826}
827
828// Automatically partition the SRAM based on the width of the data and the desired width.
829// final SRAM width = width * way
830class SRAMTemplateWithFixedWidth[T <: Data](
831    gen:           T,
832    set:           Int,
833    width:         Int,
834    way:           Int = 1,
835    shouldReset:   Boolean = false,
836    holdRead:      Boolean = false,
837    singlePort:    Boolean = false,
838    bypassWrite:   Boolean = false,
839    withClockGate: Boolean = false,
840    hasMbist:      Boolean = false
841) extends Module {
842
843  private val dataBits  = gen.getWidth
844  private val bankNum   = math.ceil(dataBits.toDouble / width.toDouble).toInt
845  private val totalBits = bankNum * width
846
847  val io: SRAMTemplateWithFixedWidthIO[T] = IO(new SRAMTemplateWithFixedWidthIO(gen, set, way))
848
849  private val wordType = UInt(width.W)
850  private val writeDatas = (0 until bankNum).map { bank =>
851    VecInit((0 until way).map { i =>
852      io.w.req.bits.data(i).asTypeOf(UInt(totalBits.W)).asTypeOf(Vec(bankNum, wordType))(bank)
853    })
854  }
855
856  private val srams = (0 until bankNum) map { bank =>
857    val sramBank = Module(new SRAMTemplate(
858      wordType,
859      set = set,
860      way = way,
861      shouldReset = shouldReset,
862      holdRead = holdRead,
863      singlePort = singlePort,
864      bypassWrite = bypassWrite,
865      withClockGate = withClockGate,
866      hasMbist = hasMbist
867    ))
868    // read req
869    sramBank.io.r.req.valid       := io.r.req.valid
870    sramBank.io.r.req.bits.setIdx := io.r.req.bits.setIdx
871
872    // write req
873    sramBank.io.w.req.valid       := io.w.req.valid
874    sramBank.io.w.req.bits.setIdx := io.w.req.bits.setIdx
875    sramBank.io.w.req.bits.data   := writeDatas(bank)
876    sramBank.io.w.req.bits.waymask.foreach(_ := io.w.req.bits.waymask.get)
877
878    sramBank
879  }
880
881  io.r.req.ready := !io.w.req.valid
882  (0 until way).foreach { i =>
883    io.r.resp.data(i) := VecInit((0 until bankNum).map(bank =>
884      srams(bank).io.r.resp.data(i)
885    )).asTypeOf(UInt(totalBits.W))(dataBits - 1, 0).asTypeOf(gen.cloneType)
886  }
887
888  io.r.req.ready := srams.head.io.r.req.ready
889  io.w.req.ready := srams.head.io.w.req.ready
890}
891