xref: /XiangShan/src/main/scala/xiangshan/frontend/icache/ICache.scala (revision f80535c3dab17c3dc62a4808e412d7501fa6c75b)
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
18package  xiangshan.frontend.icache
19
20import chisel3._
21import chisel3.util._
22import freechips.rocketchip.diplomacy.{IdRange, LazyModule, LazyModuleImp}
23import freechips.rocketchip.tilelink._
24import freechips.rocketchip.util.BundleFieldBase
25import huancun.{AliasField, PrefetchField}
26import org.chipsalliance.cde.config.Parameters
27import utility._
28import utils._
29import xiangshan._
30import xiangshan.cache._
31import xiangshan.cache.mmu.TlbRequestIO
32import xiangshan.frontend._
33
34case class ICacheParameters(
35    nSets: Int = 256,
36    nWays: Int = 4,
37    rowBits: Int = 64,
38    nTLBEntries: Int = 32,
39    tagECC: Option[String] = None,
40    dataECC: Option[String] = None,
41    replacer: Option[String] = Some("random"),
42
43    PortNumber: Int = 2,
44    nFetchMshr: Int = 4,
45    nPrefetchMshr: Int = 10,
46    nWayLookupSize: Int = 32,
47    DataCodeUnit: Int = 64,
48    ICacheDataBanks: Int = 8,
49    ICacheDataSRAMWidth: Int = 66,
50    // TODO: hard code, need delete
51    partWayNum: Int = 4,
52
53    nMMIOs: Int = 1,
54    blockBytes: Int = 64
55)extends L1CacheParameters {
56
57  val setBytes = nSets * blockBytes
58  val aliasBitsOpt = DCacheParameters().aliasBitsOpt //if(setBytes > pageSize) Some(log2Ceil(setBytes / pageSize)) else None
59  val reqFields: Seq[BundleFieldBase] = Seq(
60    PrefetchField(),
61    ReqSourceField()
62  ) ++ aliasBitsOpt.map(AliasField)
63  val echoFields: Seq[BundleFieldBase] = Nil
64  def tagCode: Code = Code.fromString(tagECC)
65  def dataCode: Code = Code.fromString(dataECC)
66  def replacement = ReplacementPolicy.fromString(replacer,nWays,nSets)
67}
68
69trait HasICacheParameters extends HasL1CacheParameters with HasInstrMMIOConst with HasIFUConst{
70  val cacheParams = icacheParameters
71
72  def ICacheSets            = cacheParams.nSets
73  def ICacheWays            = cacheParams.nWays
74  def PortNumber            = cacheParams.PortNumber
75  def nFetchMshr            = cacheParams.nFetchMshr
76  def nPrefetchMshr         = cacheParams.nPrefetchMshr
77  def nWayLookupSize        = cacheParams.nWayLookupSize
78  def DataCodeUnit          = cacheParams.DataCodeUnit
79  def ICacheDataBanks       = cacheParams.ICacheDataBanks
80  def ICacheDataSRAMWidth   = cacheParams.ICacheDataSRAMWidth
81  def partWayNum            = cacheParams.partWayNum
82
83  def ICacheDataBits        = blockBits / ICacheDataBanks
84  def ICacheCodeBits        = math.ceil(ICacheDataBits / DataCodeUnit).toInt
85  def ICacheEntryBits       = ICacheDataBits + ICacheCodeBits
86  def ICacheBankVisitNum    = 32 * 8 / ICacheDataBits + 1
87  def highestIdxBit         = log2Ceil(nSets) - 1
88
89  require((ICacheDataBanks >= 2) && isPow2(ICacheDataBanks))
90  require(ICacheDataSRAMWidth >= ICacheEntryBits)
91  require(isPow2(ICacheSets), s"nSets($ICacheSets) must be pow2")
92  require(isPow2(ICacheWays), s"nWays($ICacheWays) must be pow2")
93
94  def getBits(num: Int) = log2Ceil(num).W
95
96  def generatePipeControl(lastFire: Bool, thisFire: Bool, thisFlush: Bool, lastFlush: Bool): Bool = {
97    val valid  = RegInit(false.B)
98    when(thisFlush)                    {valid  := false.B}
99      .elsewhen(lastFire && !lastFlush)  {valid  := true.B}
100      .elsewhen(thisFire)                 {valid  := false.B}
101    valid
102  }
103
104  def ResultHoldBypass[T<:Data](data: T, valid: Bool): T = {
105    Mux(valid, data, RegEnable(data, valid))
106  }
107
108  def ResultHoldBypass[T <: Data](data: T, init: T, valid: Bool): T = {
109    Mux(valid, data, RegEnable(data, init, valid))
110  }
111
112  def holdReleaseLatch(valid: Bool, release: Bool, flush: Bool): Bool ={
113    val bit = RegInit(false.B)
114    when(flush)                   { bit := false.B  }
115      .elsewhen(valid && !release)  { bit := true.B   }
116      .elsewhen(release)            { bit := false.B  }
117    bit || valid
118  }
119
120  def blockCounter(block: Bool, flush: Bool, threshold: Int): Bool = {
121    val counter = RegInit(0.U(log2Up(threshold + 1).W))
122    when (block) { counter := counter + 1.U }
123    when (flush) { counter := 0.U}
124    counter > threshold.U
125  }
126
127  def InitQueue[T <: Data](entry: T, size: Int): Vec[T] ={
128    return RegInit(VecInit(Seq.fill(size)(0.U.asTypeOf(entry.cloneType))))
129  }
130
131  def encode(data: UInt): UInt = {
132    val datas = data.asTypeOf(Vec(ICacheCodeBits, UInt((ICacheDataBits / ICacheCodeBits).W)))
133    val codes = VecInit(datas.map(cacheParams.dataCode.encode(_) >> (ICacheDataBits / ICacheCodeBits)))
134    codes.asTypeOf(UInt(ICacheCodeBits.W))
135  }
136
137  def getBankSel(blkOffset: UInt, valid: Bool = true.B): Vec[UInt] = {
138    val bankIdxLow  = Cat(0.U(1.W), blkOffset) >> log2Ceil(blockBytes/ICacheDataBanks)
139    val bankIdxHigh = (Cat(0.U(1.W), blkOffset) + 32.U) >> log2Ceil(blockBytes/ICacheDataBanks)
140    val bankSel = VecInit((0 until ICacheDataBanks * 2).map(i => (i.U >= bankIdxLow) && (i.U <= bankIdxHigh)))
141    assert(!valid || PopCount(bankSel) === ICacheBankVisitNum.U, "The number of bank visits must be %d, but bankSel=0x%x", ICacheBankVisitNum.U, bankSel.asUInt)
142    bankSel.asTypeOf(UInt((ICacheDataBanks * 2).W)).asTypeOf(Vec(2, UInt(ICacheDataBanks.W)))
143  }
144
145  def getLineSel(blkOffset: UInt)(implicit p: Parameters): Vec[Bool] = {
146    val bankIdxLow  = blkOffset >> log2Ceil(blockBytes/ICacheDataBanks)
147    val lineSel = VecInit((0 until ICacheDataBanks).map(i => i.U < bankIdxLow))
148    lineSel
149  }
150
151  def getBlkAddr(addr: UInt) = addr >> blockOffBits
152  def getPhyTagFromBlk(addr: UInt) = addr >> (pgUntagBits - blockOffBits)
153  def getIdxFromBlk(addr: UInt) = addr(idxBits - 1, 0)
154  def get_paddr_from_ptag(vaddr: UInt, ptag: UInt) = Cat(ptag, vaddr(pgUntagBits - 1, 0))
155}
156
157abstract class ICacheBundle(implicit p: Parameters) extends XSBundle
158  with HasICacheParameters
159
160abstract class ICacheModule(implicit p: Parameters) extends XSModule
161  with HasICacheParameters
162
163abstract class ICacheArray(implicit p: Parameters) extends XSModule
164  with HasICacheParameters
165
166class ICacheMetadata(implicit p: Parameters) extends ICacheBundle {
167  val tag = UInt(tagBits.W)
168}
169
170object ICacheMetadata {
171  def apply(tag: Bits)(implicit p: Parameters) = {
172    val meta = Wire(new ICacheMetadata)
173    meta.tag := tag
174    meta
175  }
176}
177
178
179class ICacheMetaArray()(implicit p: Parameters) extends ICacheArray
180{
181  def onReset = ICacheMetadata(0.U)
182  val metaBits = onReset.getWidth
183  val metaEntryBits = cacheParams.tagCode.width(metaBits)
184
185  val io=IO{new Bundle{
186    val write    = Flipped(DecoupledIO(new ICacheMetaWriteBundle))
187    val read     = Flipped(DecoupledIO(new ICacheReadBundle))
188    val readResp = Output(new ICacheMetaRespBundle)
189    val fencei   = Input(Bool())
190  }}
191
192  io.read.ready := !io.write.valid
193
194  val port_0_read_0 = io.read.valid  && !io.read.bits.vSetIdx(0)(0)
195  val port_0_read_1 = io.read.valid  &&  io.read.bits.vSetIdx(0)(0)
196  val port_1_read_1  = io.read.valid &&  io.read.bits.vSetIdx(1)(0) && io.read.bits.isDoubleLine
197  val port_1_read_0  = io.read.valid && !io.read.bits.vSetIdx(1)(0) && io.read.bits.isDoubleLine
198
199  val port_0_read_0_reg = RegEnable(port_0_read_0, 0.U.asTypeOf(port_0_read_0), io.read.fire)
200  val port_0_read_1_reg = RegEnable(port_0_read_1, 0.U.asTypeOf(port_0_read_1), io.read.fire)
201  val port_1_read_1_reg = RegEnable(port_1_read_1, 0.U.asTypeOf(port_1_read_1), io.read.fire)
202  val port_1_read_0_reg = RegEnable(port_1_read_0, 0.U.asTypeOf(port_1_read_0), io.read.fire)
203
204  val bank_0_idx = Mux(port_0_read_0, io.read.bits.vSetIdx(0), io.read.bits.vSetIdx(1))
205  val bank_1_idx = Mux(port_0_read_1, io.read.bits.vSetIdx(0), io.read.bits.vSetIdx(1))
206  val bank_idx   = Seq(bank_0_idx, bank_1_idx)
207
208  val write_bank_0 = io.write.valid && !io.write.bits.bankIdx
209  val write_bank_1 = io.write.valid &&  io.write.bits.bankIdx
210
211  val write_meta_bits = Wire(UInt(metaEntryBits.W))
212
213  val tagArrays = (0 until 2) map { bank =>
214    val tagArray = Module(new SRAMTemplate(
215      UInt(metaEntryBits.W),
216      set=nSets/2,
217      way=nWays,
218      shouldReset = true,
219      holdRead = true,
220      singlePort = true
221    ))
222
223    //meta connection
224    if(bank == 0) {
225      tagArray.io.r.req.valid := port_0_read_0 || port_1_read_0
226      tagArray.io.r.req.bits.apply(setIdx=bank_0_idx(highestIdxBit,1))
227      tagArray.io.w.req.valid := write_bank_0
228      tagArray.io.w.req.bits.apply(data=write_meta_bits, setIdx=io.write.bits.virIdx(highestIdxBit,1), waymask=io.write.bits.waymask)
229    }
230    else {
231      tagArray.io.r.req.valid := port_0_read_1 || port_1_read_1
232      tagArray.io.r.req.bits.apply(setIdx=bank_1_idx(highestIdxBit,1))
233      tagArray.io.w.req.valid := write_bank_1
234      tagArray.io.w.req.bits.apply(data=write_meta_bits, setIdx=io.write.bits.virIdx(highestIdxBit,1), waymask=io.write.bits.waymask)
235    }
236
237    tagArray
238  }
239
240  val read_set_idx_next = RegEnable(io.read.bits.vSetIdx, 0.U.asTypeOf(io.read.bits.vSetIdx), io.read.fire)
241  val valid_array = RegInit(VecInit(Seq.fill(nWays)(0.U(nSets.W))))
242  val valid_metas = Wire(Vec(PortNumber, Vec(nWays, Bool())))
243  // valid read
244  (0 until PortNumber).foreach( i =>
245    (0 until nWays).foreach( way =>
246      valid_metas(i)(way) := valid_array(way)(read_set_idx_next(i))
247    ))
248  io.readResp.entryValid := valid_metas
249
250  io.read.ready := !io.write.valid && !io.fencei && tagArrays.map(_.io.r.req.ready).reduce(_&&_)
251
252  //Parity Decode
253  val read_fire_delay1 = RegNext(io.read.fire, init = false.B)
254  val read_fire_delay2 = RegNext(read_fire_delay1, init = false.B)
255  val read_metas = Wire(Vec(2,Vec(nWays,new ICacheMetadata())))
256  for((tagArray,i) <- tagArrays.zipWithIndex){
257    val read_meta_bits = tagArray.io.r.resp.asTypeOf(Vec(nWays,UInt(metaEntryBits.W)))
258    val read_meta_decoded = read_meta_bits.map{ way_bits => cacheParams.tagCode.decode(way_bits)}
259    val read_meta_wrong = read_meta_decoded.map{ way_bits_decoded => way_bits_decoded.error}
260    val read_meta_corrected = VecInit(read_meta_decoded.map{ way_bits_decoded => way_bits_decoded.corrected})
261    read_metas(i) := read_meta_corrected.asTypeOf(Vec(nWays,new ICacheMetadata()))
262    (0 until nWays).foreach{ w => io.readResp.errors(i)(w) := RegEnable(read_meta_wrong(w), 0.U.asTypeOf(read_meta_wrong(w)), read_fire_delay1) && read_fire_delay2}
263  }
264
265  // TEST: force ECC to fail by setting errors to true.B
266  if (ICacheForceMetaECCError) {
267    (0 until PortNumber).foreach( p =>
268      (0 until nWays).foreach( w =>
269        io.readResp.errors(p)(w) := true.B
270      )
271    )
272  }
273
274  //Parity Encode
275  val write = io.write.bits
276  write_meta_bits := cacheParams.tagCode.encode(ICacheMetadata(tag = write.phyTag).asUInt)
277
278  // valid write
279  val way_num = OHToUInt(io.write.bits.waymask)
280  when (io.write.valid) {
281    valid_array(way_num) := valid_array(way_num).bitSet(io.write.bits.virIdx, true.B)
282  }
283
284  XSPerfAccumulate("meta_refill_num", io.write.valid)
285
286  io.readResp.metaData <> DontCare
287  when(port_0_read_0_reg){
288    io.readResp.metaData(0) := read_metas(0)
289  }.elsewhen(port_0_read_1_reg){
290    io.readResp.metaData(0) := read_metas(1)
291  }
292
293  when(port_1_read_0_reg){
294    io.readResp.metaData(1) := read_metas(0)
295  }.elsewhen(port_1_read_1_reg){
296    io.readResp.metaData(1) := read_metas(1)
297  }
298
299
300  io.write.ready := true.B // TODO : has bug ? should be !io.cacheOp.req.valid
301
302  // fencei logic : reset valid_array
303  when (io.fencei) {
304    (0 until nWays).foreach( way =>
305      valid_array(way) := 0.U
306    )
307  }
308}
309
310// Vec(2,Vec(nWays, Bool()))
311
312class ICacheDataArray(implicit p: Parameters) extends ICacheArray
313{
314  class ICacheDataEntry(implicit p: Parameters) extends ICacheBundle {
315    val data = UInt(ICacheDataBits.W)
316    val code = UInt(ICacheCodeBits.W)
317  }
318
319  object ICacheDataEntry {
320    def apply(data: UInt)(implicit p: Parameters) = {
321      require(data.getWidth == ICacheDataBits)
322      val entry = Wire(new ICacheDataEntry)
323      entry.data := data
324      entry.code := encode(data)
325      entry
326    }
327  }
328
329  val io=IO{new Bundle{
330    val write    = Flipped(DecoupledIO(new ICacheDataWriteBundle))
331    // TODO: fix hard code
332    val read     = Flipped(Vec(4, DecoupledIO(new ICacheReadBundle)))
333    val readResp = Output(new ICacheDataRespBundle)
334  }}
335
336  /**
337    ******************************************************************************
338    * data array
339    ******************************************************************************
340    */
341  val writeDatas   = io.write.bits.data.asTypeOf(Vec(ICacheDataBanks, UInt(ICacheDataBits.W)))
342  val writeEntries = writeDatas.map(ICacheDataEntry(_).asUInt)
343
344  val bankSel = getBankSel(io.read(0).bits.blkOffset, io.read(0).valid)
345  val lineSel = getLineSel(io.read(0).bits.blkOffset)
346  val waymasks = io.read(0).bits.wayMask
347  val masks = Wire(Vec(nWays, Vec(ICacheDataBanks, Bool())))
348  (0 until nWays).foreach{way =>
349    (0 until ICacheDataBanks).foreach{bank =>
350      masks(way)(bank) := Mux(lineSel(bank), waymasks(1)(way) && bankSel(1)(bank).asBool,
351                                             waymasks(0)(way) && bankSel(0)(bank).asBool)
352    }
353  }
354
355  val dataArrays = (0 until nWays).map{ way =>
356    (0 until ICacheDataBanks).map { bank =>
357      val sramBank = Module(new SRAMTemplateWithFixedWidth(
358        UInt(ICacheEntryBits.W),
359        set=nSets,
360        width=ICacheDataSRAMWidth,
361        shouldReset = true,
362        holdRead = true,
363        singlePort = true
364      ))
365
366      // read
367      sramBank.io.r.req.valid := io.read(bank % 4).valid && masks(way)(bank)
368      sramBank.io.r.req.bits.apply(setIdx=Mux(lineSel(bank),
369                                              io.read(bank % 4).bits.vSetIdx(1),
370                                              io.read(bank % 4).bits.vSetIdx(0)))
371      // write
372      sramBank.io.w.req.valid := io.write.valid && io.write.bits.waymask(way).asBool
373      sramBank.io.w.req.bits.apply(
374        data    = writeEntries(bank),
375        setIdx  = io.write.bits.virIdx,
376        // waymask is invalid when way of SRAMTemplate <= 1
377        waymask = 0.U
378      )
379      sramBank
380    }
381  }
382
383  /**
384    ******************************************************************************
385    * read logic
386    ******************************************************************************
387    */
388  val masksReg          = RegEnable(masks, 0.U.asTypeOf(masks), io.read(0).valid)
389  val readDataWithCode  = (0 until ICacheDataBanks).map(bank =>
390                            Mux1H(VecInit(masksReg.map(_(bank))).asTypeOf(UInt(nWays.W)),
391                                  dataArrays.map(_(bank).io.r.resp.asUInt)))
392  val readEntries       = readDataWithCode.map(_.asTypeOf(new ICacheDataEntry()))
393  val readDatas         = VecInit(readEntries.map(_.data))
394  val readCodes         = VecInit(readEntries.map(_.code))
395
396  // TEST: force ECC to fail by setting readCodes to 0
397  if (ICacheForceDataECCError) {
398    readCodes.foreach(_ := 0.U)
399  }
400
401  /**
402    ******************************************************************************
403    * IO
404    ******************************************************************************
405    */
406  io.readResp.datas   := readDatas
407  io.readResp.codes   := readCodes
408  io.write.ready      := true.B
409  io.read.foreach( _.ready := !io.write.valid)
410}
411
412
413class ICacheReplacer(implicit p: Parameters) extends ICacheModule {
414  val io = IO(new Bundle {
415    val touch   = Vec(PortNumber, Flipped(ValidIO(new ReplacerTouch)))
416    val victim  = Flipped(new ReplacerVictim)
417  })
418
419  val replacers = Seq.fill(PortNumber)(ReplacementPolicy.fromString(cacheParams.replacer,nWays,nSets/PortNumber))
420
421  // touch
422  val touch_sets = Seq.fill(PortNumber)(Wire(Vec(2, UInt(log2Ceil(nSets/2).W))))
423  val touch_ways = Seq.fill(PortNumber)(Wire(Vec(2, Valid(UInt(log2Ceil(nWays).W)))))
424  (0 until PortNumber).foreach {i =>
425    touch_sets(i)(0)        := Mux(io.touch(i).bits.vSetIdx(0), io.touch(1).bits.vSetIdx(highestIdxBit, 1), io.touch(0).bits.vSetIdx(highestIdxBit, 1))
426    touch_ways(i)(0).bits   := Mux(io.touch(i).bits.vSetIdx(0), io.touch(1).bits.way, io.touch(0).bits.way)
427    touch_ways(i)(0).valid  := Mux(io.touch(i).bits.vSetIdx(0), io.touch(1).valid, io.touch(0).valid)
428  }
429
430  // victim
431  io.victim.way := Mux(io.victim.vSetIdx.bits(0),
432                       replacers(1).way(io.victim.vSetIdx.bits(highestIdxBit, 1)),
433                       replacers(0).way(io.victim.vSetIdx.bits(highestIdxBit, 1)))
434
435  // touch the victim in next cycle
436  val victim_vSetIdx_reg = RegEnable(io.victim.vSetIdx.bits, 0.U.asTypeOf(io.victim.vSetIdx.bits), io.victim.vSetIdx.valid)
437  val victim_way_reg     = RegEnable(io.victim.way,          0.U.asTypeOf(io.victim.way),          io.victim.vSetIdx.valid)
438  (0 until PortNumber).foreach {i =>
439    touch_sets(i)(1)        := victim_vSetIdx_reg(highestIdxBit, 1)
440    touch_ways(i)(1).bits   := victim_way_reg
441    touch_ways(i)(1).valid  := RegNext(io.victim.vSetIdx.valid) && (victim_vSetIdx_reg(0) === i.U)
442  }
443
444  ((replacers zip touch_sets) zip touch_ways).map{case ((r, s),w) => r.access(s,w)}
445}
446
447class ICacheIO(implicit p: Parameters) extends ICacheBundle
448{
449  val hartId      = Input(UInt(hartIdLen.W))
450  val prefetch    = Flipped(new FtqToPrefetchIO)
451  val stop        = Input(Bool())
452  val fetch       = new ICacheMainPipeBundle
453  val toIFU       = Output(Bool())
454  val pmp         = Vec(2 * PortNumber, new ICachePMPBundle)
455  val itlb        = Vec(PortNumber, new TlbRequestIO)
456  val perfInfo    = Output(new ICachePerfInfo)
457  val error       = ValidIO(new L1CacheErrorInfo)
458  /* CSR control signal */
459  val csr_pf_enable = Input(Bool())
460  val csr_parity_enable = Input(Bool())
461  val fencei      = Input(Bool())
462  val flush       = Input(Bool())
463}
464
465class ICache()(implicit p: Parameters) extends LazyModule with HasICacheParameters {
466  override def shouldBeInlined: Boolean = false
467
468  val clientParameters = TLMasterPortParameters.v1(
469    Seq(TLMasterParameters.v1(
470      name = "icache",
471      sourceId = IdRange(0, cacheParams.nFetchMshr + cacheParams.nPrefetchMshr + 1),
472    )),
473    requestFields = cacheParams.reqFields,
474    echoFields = cacheParams.echoFields
475  )
476
477  val clientNode = TLClientNode(Seq(clientParameters))
478
479  lazy val module = new ICacheImp(this)
480}
481
482class ICacheImp(outer: ICache) extends LazyModuleImp(outer) with HasICacheParameters with HasPerfEvents {
483  val io = IO(new ICacheIO)
484
485  println("ICache:")
486  println("  TagECC: "                + cacheParams.tagECC)
487  println("  DataECC: "               + cacheParams.dataECC)
488  println("  ICacheSets: "            + cacheParams.nSets)
489  println("  ICacheWays: "            + cacheParams.nWays)
490  println("  PortNumber: "            + cacheParams.PortNumber)
491  println("  nFetchMshr: "            + cacheParams.nFetchMshr)
492  println("  nPrefetchMshr: "         + cacheParams.nPrefetchMshr)
493  println("  nWayLookupSize: "        + cacheParams.nWayLookupSize)
494  println("  DataCodeUnit: "          + cacheParams.DataCodeUnit)
495  println("  ICacheDataBanks: "       + cacheParams.ICacheDataBanks)
496  println("  ICacheDataSRAMWidth: "   + cacheParams.ICacheDataSRAMWidth)
497
498  val (bus, edge) = outer.clientNode.out.head
499
500  val metaArray         = Module(new ICacheMetaArray)
501  val dataArray         = Module(new ICacheDataArray)
502  val mainPipe          = Module(new ICacheMainPipe)
503  val missUnit          = Module(new ICacheMissUnit(edge))
504  val replacer          = Module(new ICacheReplacer)
505  val prefetcher        = Module(new IPrefetchPipe)
506  val wayLookup         = Module(new WayLookup)
507
508  dataArray.io.write    <> missUnit.io.data_write
509  dataArray.io.read     <> mainPipe.io.dataArray.toIData
510  dataArray.io.readResp <> mainPipe.io.dataArray.fromIData
511
512  metaArray.io.fencei   := io.fencei
513  metaArray.io.write    <> missUnit.io.meta_write
514  metaArray.io.read     <> prefetcher.io.metaRead.toIMeta
515  metaArray.io.readResp <> prefetcher.io.metaRead.fromIMeta
516
517  prefetcher.io.flush             := io.flush
518  prefetcher.io.csr_pf_enable     := io.csr_pf_enable
519  prefetcher.io.csr_parity_enable := io.csr_parity_enable
520  prefetcher.io.ftqReq            <> io.prefetch
521  prefetcher.io.MSHRResp          := missUnit.io.fetch_resp
522
523  missUnit.io.hartId            := io.hartId
524  missUnit.io.fencei            := io.fencei
525  missUnit.io.flush             := io.flush
526  missUnit.io.fetch_req         <> mainPipe.io.mshr.req
527  missUnit.io.prefetch_req      <> prefetcher.io.MSHRReq
528  missUnit.io.mem_grant.valid   := false.B
529  missUnit.io.mem_grant.bits    := DontCare
530  missUnit.io.mem_grant         <> bus.d
531
532  mainPipe.io.flush             := io.flush
533  mainPipe.io.respStall         := io.stop
534  mainPipe.io.csr_parity_enable := io.csr_parity_enable
535  mainPipe.io.hartId            := io.hartId
536  mainPipe.io.mshr.resp         := missUnit.io.fetch_resp
537  mainPipe.io.fetch.req         <> io.fetch.req
538  mainPipe.io.wayLookupRead     <> wayLookup.io.read
539
540  wayLookup.io.flush            := io.flush
541  wayLookup.io.write            <> prefetcher.io.wayLookupWrite
542  wayLookup.io.update           := missUnit.io.fetch_resp
543
544  replacer.io.touch   <> mainPipe.io.touch
545  replacer.io.victim  <> missUnit.io.victim
546
547  io.pmp(0) <> mainPipe.io.pmp(0)
548  io.pmp(1) <> mainPipe.io.pmp(1)
549  io.pmp(2) <> prefetcher.io.pmp(0)
550  io.pmp(3) <> prefetcher.io.pmp(1)
551
552  io.itlb(0) <> prefetcher.io.itlb(0)
553  io.itlb(1) <> prefetcher.io.itlb(1)
554
555  //notify IFU that Icache pipeline is available
556  io.toIFU := mainPipe.io.fetch.req.ready
557  io.perfInfo := mainPipe.io.perfInfo
558
559  io.fetch.resp              <> mainPipe.io.fetch.resp
560  io.fetch.topdownIcacheMiss := mainPipe.io.fetch.topdownIcacheMiss
561  io.fetch.topdownItlbMiss   := mainPipe.io.fetch.topdownItlbMiss
562
563  bus.b.ready := false.B
564  bus.c.valid := false.B
565  bus.c.bits  := DontCare
566  bus.e.valid := false.B
567  bus.e.bits  := DontCare
568
569  bus.a <> missUnit.io.mem_acquire
570
571  //Parity error port
572  val errors = mainPipe.io.errors
573  val errors_valid = errors.map(e => e.valid).reduce(_ | _)
574  io.error.bits <> RegEnable(Mux1H(errors.map(e => e.valid -> e.bits)), 0.U.asTypeOf(errors(0).bits), errors_valid)
575  io.error.valid := RegNext(errors_valid, false.B)
576
577  val perfEvents = Seq(
578    ("icache_miss_cnt  ", false.B),
579    ("icache_miss_penalty", BoolStopWatch(start = false.B, stop = false.B || false.B, startHighPriority = true)),
580  )
581  generatePerfEvent()
582}
583
584class ICachePartWayReadBundle[T <: Data](gen: T, pWay: Int)(implicit p: Parameters)
585  extends ICacheBundle
586{
587  val req = Flipped(Vec(PortNumber, Decoupled(new Bundle{
588    val ridx = UInt((log2Ceil(nSets) - 1).W)
589  })))
590  val resp = Output(new Bundle{
591    val rdata  = Vec(PortNumber,Vec(pWay, gen))
592  })
593}
594
595class ICacheWriteBundle[T <: Data](gen: T, pWay: Int)(implicit p: Parameters)
596  extends ICacheBundle
597{
598  val wdata = gen
599  val widx = UInt((log2Ceil(nSets) - 1).W)
600  val wbankidx = Bool()
601  val wmask = Vec(pWay, Bool())
602}
603
604class ICachePartWayArray[T <: Data](gen: T, pWay: Int)(implicit p: Parameters) extends ICacheArray
605{
606
607  //including part way data
608  val io = IO{new Bundle {
609    val read      = new  ICachePartWayReadBundle(gen,pWay)
610    val write     = Flipped(ValidIO(new ICacheWriteBundle(gen, pWay)))
611  }}
612
613  io.read.req.map(_.ready := !io.write.valid)
614
615  val srams = (0 until PortNumber) map { bank =>
616    val sramBank = Module(new SRAMTemplate(
617      gen,
618      set=nSets/2,
619      way=pWay,
620      shouldReset = true,
621      holdRead = true,
622      singlePort = true
623    ))
624
625    sramBank.io.r.req.valid := io.read.req(bank).valid
626    sramBank.io.r.req.bits.apply(setIdx= io.read.req(bank).bits.ridx)
627
628    if(bank == 0) sramBank.io.w.req.valid := io.write.valid && !io.write.bits.wbankidx
629    else sramBank.io.w.req.valid := io.write.valid && io.write.bits.wbankidx
630    sramBank.io.w.req.bits.apply(data=io.write.bits.wdata, setIdx=io.write.bits.widx, waymask=io.write.bits.wmask.asUInt)
631
632    sramBank
633  }
634
635  io.read.req.map(_.ready := !io.write.valid && srams.map(_.io.r.req.ready).reduce(_&&_))
636
637  io.read.resp.rdata := VecInit(srams.map(bank => bank.io.r.resp.asTypeOf(Vec(pWay,gen))))
638
639}
640
641// Automatically partition the SRAM based on the width of the data and the desired width.
642// final SRAM width = width * way
643class SRAMTemplateWithFixedWidth[T <: Data]
644(
645  gen: T, set: Int, width: Int, way: Int = 1,
646  shouldReset: Boolean = false, holdRead: Boolean = false,
647  singlePort: Boolean = false, bypassWrite: Boolean = false
648) extends Module {
649
650  val dataBits  = gen.getWidth
651  val bankNum = math.ceil(dataBits.toDouble / width.toDouble).toInt
652  val totalBits = bankNum * width
653
654  val io = IO(new Bundle {
655    val r = Flipped(new SRAMReadBus(gen, set, way))
656    val w = Flipped(new SRAMWriteBus(gen, set, way))
657  })
658
659  val wordType   = UInt(width.W)
660  val writeDatas = (0 until bankNum).map(bank =>
661    VecInit((0 until way).map(i =>
662      io.w.req.bits.data(i).asTypeOf(UInt(totalBits.W)).asTypeOf(Vec(bankNum, wordType))(bank)
663    ))
664  )
665
666  val srams = (0 until bankNum) map { bank =>
667    val sramBank = Module(new SRAMTemplate(
668      wordType,
669      set=set,
670      way=way,
671      shouldReset = shouldReset,
672      holdRead = holdRead,
673      singlePort = singlePort,
674      bypassWrite = bypassWrite,
675    ))
676    // read req
677    sramBank.io.r.req.valid       := io.r.req.valid
678    sramBank.io.r.req.bits.setIdx := io.r.req.bits.setIdx
679
680    // write req
681    sramBank.io.w.req.valid       := io.w.req.valid
682    sramBank.io.w.req.bits.setIdx := io.w.req.bits.setIdx
683    sramBank.io.w.req.bits.data   := writeDatas(bank)
684    sramBank.io.w.req.bits.waymask.map(_ := io.w.req.bits.waymask.get)
685
686    sramBank
687  }
688
689  io.r.req.ready := !io.w.req.valid
690  (0 until way).foreach{i =>
691    io.r.resp.data(i) := VecInit((0 until bankNum).map(bank =>
692                           srams(bank).io.r.resp.data(i)
693                         )).asTypeOf(UInt(totalBits.W))(dataBits-1, 0).asTypeOf(gen.cloneType)
694  }
695
696  io.r.req.ready := srams.head.io.r.req.ready
697  io.w.req.ready := srams.head.io.w.req.ready
698}