xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/DCacheWrapper.scala (revision 8b1251e1740d3b3b7d390a9d52d957debd943146)
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
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.experimental.ExtModule
22import chisel3.util._
23import xiangshan._
24import utils._
25import freechips.rocketchip.diplomacy.{IdRange, LazyModule, LazyModuleImp, TransferSizes}
26import freechips.rocketchip.tilelink._
27import freechips.rocketchip.util.{BundleFieldBase, UIntToOH1}
28import device.RAMHelper
29import huancun.{AliasField, AliasKey, DirtyField, PreferCacheField, PrefetchField}
30import huancun.utils.FastArbiter
31import mem.{AddPipelineReg}
32
33import scala.math.max
34
35// DCache specific parameters
36case class DCacheParameters
37(
38  nSets: Int = 256,
39  nWays: Int = 8,
40  rowBits: Int = 64,
41  tagECC: Option[String] = None,
42  dataECC: Option[String] = None,
43  replacer: Option[String] = Some("setplru"),
44  nMissEntries: Int = 1,
45  nProbeEntries: Int = 1,
46  nReleaseEntries: Int = 1,
47  nMMIOEntries: Int = 1,
48  nMMIOs: Int = 1,
49  blockBytes: Int = 64,
50  alwaysReleaseData: Boolean = true
51) extends L1CacheParameters {
52  // if sets * blockBytes > 4KB(page size),
53  // cache alias will happen,
54  // we need to avoid this by recoding additional bits in L2 cache
55  val setBytes = nSets * blockBytes
56  val aliasBitsOpt = if(setBytes > pageSize) Some(log2Ceil(setBytes / pageSize)) else None
57  val reqFields: Seq[BundleFieldBase] = Seq(
58    PrefetchField(),
59    PreferCacheField()
60  ) ++ aliasBitsOpt.map(AliasField)
61  val echoFields: Seq[BundleFieldBase] = Seq(DirtyField())
62
63  def tagCode: Code = Code.fromString(tagECC)
64
65  def dataCode: Code = Code.fromString(dataECC)
66}
67
68//           Physical Address
69// --------------------------------------
70// |   Physical Tag |  PIndex  | Offset |
71// --------------------------------------
72//                  |
73//                  DCacheTagOffset
74//
75//           Virtual Address
76// --------------------------------------
77// | Above index  | Set | Bank | Offset |
78// --------------------------------------
79//                |     |      |        |
80//                |     |      |        0
81//                |     |      DCacheBankOffset
82//                |     DCacheSetOffset
83//                DCacheAboveIndexOffset
84
85// Default DCache size = 64 sets * 8 ways * 8 banks * 8 Byte = 32K Byte
86
87trait HasDCacheParameters extends HasL1CacheParameters {
88  val cacheParams = dcacheParameters
89  val cfg = cacheParams
90
91  def encWordBits = cacheParams.dataCode.width(wordBits)
92
93  def encRowBits = encWordBits * rowWords // for DuplicatedDataArray only
94  def eccBits = encWordBits - wordBits
95
96  def encTagBits = cacheParams.tagCode.width(tagBits)
97  def eccTagBits = encTagBits - tagBits
98
99  def blockProbeAfterGrantCycles = 8 // give the processor some time to issue a request after a grant
100
101  def nSourceType = 3
102  def sourceTypeWidth = log2Up(nSourceType)
103  def LOAD_SOURCE = 0
104  def STORE_SOURCE = 1
105  def AMO_SOURCE = 2
106  def SOFT_PREFETCH = 3
107
108  // each source use a id to distinguish its multiple reqs
109  def reqIdWidth = log2Up(nEntries) max log2Up(StoreBufferSize)
110
111  require(isPow2(cfg.nMissEntries)) // TODO
112  // require(isPow2(cfg.nReleaseEntries))
113  require(cfg.nMissEntries < cfg.nReleaseEntries)
114  val nEntries = cfg.nMissEntries + cfg.nReleaseEntries
115  val releaseIdBase = cfg.nMissEntries
116
117  // banked dcache support
118  val DCacheSets = cacheParams.nSets
119  val DCacheWays = cacheParams.nWays
120  val DCacheBanks = 8 // hardcoded
121  val DCacheSRAMRowBits = cacheParams.rowBits // hardcoded
122  val DCacheWordBits = 64 // hardcoded
123  val DCacheWordBytes = DCacheWordBits / 8
124  require(DCacheSRAMRowBits == 64)
125
126  val DCacheSizeBits = DCacheSRAMRowBits * DCacheBanks * DCacheWays * DCacheSets
127  val DCacheSizeBytes = DCacheSizeBits / 8
128  val DCacheSizeWords = DCacheSizeBits / 64 // TODO
129
130  val DCacheSameVPAddrLength = 12
131
132  val DCacheSRAMRowBytes = DCacheSRAMRowBits / 8
133  val DCacheWordOffset = log2Up(DCacheWordBytes)
134
135  val DCacheBankOffset = log2Up(DCacheSRAMRowBytes)
136  val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks)
137  val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets)
138  val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength
139  val DCacheLineOffset = DCacheSetOffset
140
141  def addr_to_dcache_bank(addr: UInt) = {
142    require(addr.getWidth >= DCacheSetOffset)
143    addr(DCacheSetOffset-1, DCacheBankOffset)
144  }
145
146  def addr_to_dcache_set(addr: UInt) = {
147    require(addr.getWidth >= DCacheAboveIndexOffset)
148    addr(DCacheAboveIndexOffset-1, DCacheSetOffset)
149  }
150
151  def get_data_of_bank(bank: Int, data: UInt) = {
152    require(data.getWidth >= (bank+1)*DCacheSRAMRowBits)
153    data(DCacheSRAMRowBits * (bank + 1) - 1, DCacheSRAMRowBits * bank)
154  }
155
156  def get_mask_of_bank(bank: Int, data: UInt) = {
157    require(data.getWidth >= (bank+1)*DCacheSRAMRowBytes)
158    data(DCacheSRAMRowBytes * (bank + 1) - 1, DCacheSRAMRowBytes * bank)
159  }
160
161  def arbiter[T <: Bundle](
162    in: Seq[DecoupledIO[T]],
163    out: DecoupledIO[T],
164    name: Option[String] = None): Unit = {
165    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
166    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
167    for ((a, req) <- arb.io.in.zip(in)) {
168      a <> req
169    }
170    out <> arb.io.out
171  }
172
173  def arbiter_with_pipereg[T <: Bundle](
174    in: Seq[DecoupledIO[T]],
175    out: DecoupledIO[T],
176    name: Option[String] = None): Unit = {
177    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
178    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
179    for ((a, req) <- arb.io.in.zip(in)) {
180      a <> req
181    }
182    AddPipelineReg(arb.io.out, out, false.B)
183  }
184
185  def arbiter_with_pipereg_N_dup[T <: Bundle](
186    in: Seq[DecoupledIO[T]],
187    out: DecoupledIO[T],
188    dups: Seq[DecoupledIO[T]],
189    name: Option[String] = None): Unit = {
190    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
191    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
192    for ((a, req) <- arb.io.in.zip(in)) {
193      a <> req
194    }
195    for (dup <- dups) {
196      AddPipelineReg(arb.io.out, dup, false.B)
197    }
198    AddPipelineReg(arb.io.out, out, false.B)
199  }
200
201  def rrArbiter[T <: Bundle](
202    in: Seq[DecoupledIO[T]],
203    out: DecoupledIO[T],
204    name: Option[String] = None): Unit = {
205    val arb = Module(new RRArbiter[T](chiselTypeOf(out.bits), in.size))
206    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
207    for ((a, req) <- arb.io.in.zip(in)) {
208      a <> req
209    }
210    out <> arb.io.out
211  }
212
213  def fastArbiter[T <: Bundle](
214    in: Seq[DecoupledIO[T]],
215    out: DecoupledIO[T],
216    name: Option[String] = None): Unit = {
217    val arb = Module(new FastArbiter[T](chiselTypeOf(out.bits), in.size))
218    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
219    for ((a, req) <- arb.io.in.zip(in)) {
220      a <> req
221    }
222    out <> arb.io.out
223  }
224
225  val numReplaceRespPorts = 2
226
227  require(isPow2(nSets), s"nSets($nSets) must be pow2")
228  require(isPow2(nWays), s"nWays($nWays) must be pow2")
229  require(full_divide(rowBits, wordBits), s"rowBits($rowBits) must be multiple of wordBits($wordBits)")
230  require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)")
231}
232
233abstract class DCacheModule(implicit p: Parameters) extends L1CacheModule
234  with HasDCacheParameters
235
236abstract class DCacheBundle(implicit p: Parameters) extends L1CacheBundle
237  with HasDCacheParameters
238
239class ReplacementAccessBundle(implicit p: Parameters) extends DCacheBundle {
240  val set = UInt(log2Up(nSets).W)
241  val way = UInt(log2Up(nWays).W)
242}
243
244class ReplacementWayReqIO(implicit p: Parameters) extends DCacheBundle {
245  val set = ValidIO(UInt(log2Up(nSets).W))
246  val way = Input(UInt(log2Up(nWays).W))
247}
248
249// memory request in word granularity(load, mmio, lr/sc, atomics)
250class DCacheWordReq(implicit p: Parameters)  extends DCacheBundle
251{
252  val cmd    = UInt(M_SZ.W)
253  val addr   = UInt(PAddrBits.W)
254  val data   = UInt(DataBits.W)
255  val mask   = UInt((DataBits/8).W)
256  val id     = UInt(reqIdWidth.W)
257  val instrtype   = UInt(sourceTypeWidth.W)
258  def dump() = {
259    XSDebug("DCacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
260      cmd, addr, data, mask, id)
261  }
262}
263
264// memory request in word granularity(store)
265class DCacheLineReq(implicit p: Parameters)  extends DCacheBundle
266{
267  val cmd    = UInt(M_SZ.W)
268  val vaddr  = UInt(VAddrBits.W)
269  val addr   = UInt(PAddrBits.W)
270  val data   = UInt((cfg.blockBytes * 8).W)
271  val mask   = UInt(cfg.blockBytes.W)
272  val id     = UInt(reqIdWidth.W)
273  def dump() = {
274    XSDebug("DCacheLineReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
275      cmd, addr, data, mask, id)
276  }
277  def idx: UInt = get_idx(vaddr)
278}
279
280class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq {
281  val vaddr = UInt(VAddrBits.W)
282  val wline = Bool()
283}
284
285class BaseDCacheWordResp(implicit p: Parameters) extends DCacheBundle
286{
287  val data         = UInt(DataBits.W)
288  val id     = UInt(reqIdWidth.W)
289
290  // cache req missed, send it to miss queue
291  val miss   = Bool()
292  // cache miss, and failed to enter the missqueue, replay from RS is needed
293  val replay = Bool()
294  // data has been corrupted
295  val tag_error = Bool() // tag error
296  def dump() = {
297    XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n",
298      data, id, miss, replay)
299  }
300}
301
302class DCacheWordResp(implicit p: Parameters) extends BaseDCacheWordResp
303{
304  // 1 cycle after data resp
305  val error_delayed = Bool() // all kinds of errors, include tag error
306  val data_dup_0 = UInt(DataBits.W)
307}
308
309class DCacheWordRespWithError(implicit p: Parameters) extends BaseDCacheWordResp
310{
311  val error = Bool() // all kinds of errors, include tag error
312}
313
314class DCacheLineResp(implicit p: Parameters) extends DCacheBundle
315{
316  val data   = UInt((cfg.blockBytes * 8).W)
317  // cache req missed, send it to miss queue
318  val miss   = Bool()
319  // cache req nacked, replay it later
320  val replay = Bool()
321  val id     = UInt(reqIdWidth.W)
322  def dump() = {
323    XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n",
324      data, id, miss, replay)
325  }
326}
327
328class Refill(implicit p: Parameters) extends DCacheBundle
329{
330  val addr   = UInt(PAddrBits.W)
331  val data   = UInt(l1BusDataWidth.W)
332  val error  = Bool() // refilled data has been corrupted
333  // for debug usage
334  val data_raw = UInt((cfg.blockBytes * 8).W)
335  val hasdata = Bool()
336  val refill_done = Bool()
337  def dump() = {
338    XSDebug("Refill: addr: %x data: %x\n", addr, data)
339  }
340}
341
342class Release(implicit p: Parameters) extends DCacheBundle
343{
344  val paddr  = UInt(PAddrBits.W)
345  def dump() = {
346    XSDebug("Release: paddr: %x\n", paddr(PAddrBits-1, DCacheTagOffset))
347  }
348}
349
350class DCacheWordIO(implicit p: Parameters) extends DCacheBundle
351{
352  val req  = DecoupledIO(new DCacheWordReq)
353  val resp = Flipped(DecoupledIO(new DCacheWordResp))
354}
355
356class UncacheWordIO(implicit p: Parameters) extends DCacheBundle
357{
358  val req  = DecoupledIO(new DCacheWordReq)
359  val resp = Flipped(DecoupledIO(new DCacheWordRespWithError))
360}
361
362class AtomicsResp(implicit p: Parameters) extends DCacheBundle {
363  val data    = UInt(DataBits.W)
364  val miss    = Bool()
365  val miss_id = UInt(log2Up(cfg.nMissEntries).W)
366  val replay  = Bool()
367  val error   = Bool()
368
369  val ack_miss_queue = Bool()
370
371  val id     = UInt(reqIdWidth.W)
372}
373
374class AtomicWordIO(implicit p: Parameters) extends DCacheBundle
375{
376  val req  = DecoupledIO(new MainPipeReq)
377  val resp = Flipped(ValidIO(new AtomicsResp))
378  val block_lr = Input(Bool())
379}
380
381// used by load unit
382class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO
383{
384  // kill previous cycle's req
385  val s1_kill  = Output(Bool())
386  val s2_kill  = Output(Bool())
387  // cycle 0: virtual address: req.addr
388  // cycle 1: physical address: s1_paddr
389  val s1_paddr_dup_lsu = Output(UInt(PAddrBits.W)) // lsu side paddr
390  val s1_paddr_dup_dcache = Output(UInt(PAddrBits.W)) // dcache side paddr
391  val s1_disable_fast_wakeup = Input(Bool())
392  val s1_bank_conflict = Input(Bool())
393  // cycle 2: hit signal
394  val s2_hit = Input(Bool()) // hit signal for lsu,
395
396  // debug
397  val debug_s1_hit_way = Input(UInt(nWays.W))
398}
399
400class DCacheLineIO(implicit p: Parameters) extends DCacheBundle
401{
402  val req  = DecoupledIO(new DCacheLineReq)
403  val resp = Flipped(DecoupledIO(new DCacheLineResp))
404}
405
406class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle {
407  // sbuffer will directly send request to dcache main pipe
408  val req = Flipped(Decoupled(new DCacheLineReq))
409
410  val main_pipe_hit_resp = ValidIO(new DCacheLineResp)
411  val refill_hit_resp = ValidIO(new DCacheLineResp)
412
413  val replay_resp = ValidIO(new DCacheLineResp)
414
415  def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp)
416}
417
418class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle {
419  val load  = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load
420  val lsq = ValidIO(new Refill)  // refill to load queue, wake up load misses
421  val store = new DCacheToSbufferIO // for sbuffer
422  val atomics  = Flipped(new AtomicWordIO)  // atomics reqs
423  val release = ValidIO(new Release) // cacheline release hint for ld-ld violation check
424}
425
426class DCacheIO(implicit p: Parameters) extends DCacheBundle {
427  val hartId = Input(UInt(8.W))
428  val lsu = new DCacheToLsuIO
429  val csr = new L1CacheToCsrIO
430  val error = new L1CacheErrorInfo
431  val mshrFull = Output(Bool())
432}
433
434
435class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters {
436
437  val clientParameters = TLMasterPortParameters.v1(
438    Seq(TLMasterParameters.v1(
439      name = "dcache",
440      sourceId = IdRange(0, nEntries + 1),
441      supportsProbe = TransferSizes(cfg.blockBytes)
442    )),
443    requestFields = cacheParams.reqFields,
444    echoFields = cacheParams.echoFields
445  )
446
447  val clientNode = TLClientNode(Seq(clientParameters))
448
449  lazy val module = new DCacheImp(this)
450}
451
452
453class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters with HasPerfEvents {
454
455  val io = IO(new DCacheIO)
456
457  val (bus, edge) = outer.clientNode.out.head
458  require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match")
459
460  println("DCache:")
461  println("  DCacheSets: " + DCacheSets)
462  println("  DCacheWays: " + DCacheWays)
463  println("  DCacheBanks: " + DCacheBanks)
464  println("  DCacheSRAMRowBits: " + DCacheSRAMRowBits)
465  println("  DCacheWordOffset: " + DCacheWordOffset)
466  println("  DCacheBankOffset: " + DCacheBankOffset)
467  println("  DCacheSetOffset: " + DCacheSetOffset)
468  println("  DCacheTagOffset: " + DCacheTagOffset)
469  println("  DCacheAboveIndexOffset: " + DCacheAboveIndexOffset)
470
471  //----------------------------------------
472  // core data structures
473  val bankedDataArray = Module(new BankedDataArray)
474  val metaArray = Module(new AsynchronousMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2))
475  val errorArray = Module(new ErrorArray(readPorts = LoadPipelineWidth + 1, writePorts = 2)) // TODO: add it to meta array
476  val tagArray = Module(new DuplicatedTagArray(readPorts = LoadPipelineWidth + 1))
477  bankedDataArray.dump()
478
479  //----------------------------------------
480  // core modules
481  val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))})
482  // val atomicsReplayUnit = Module(new AtomicsReplayEntry)
483  val mainPipe   = Module(new MainPipe)
484  val refillPipe = Module(new RefillPipe)
485  val missQueue  = Module(new MissQueue(edge))
486  val probeQueue = Module(new ProbeQueue(edge))
487  val wb         = Module(new WritebackQueue(edge))
488
489  missQueue.io.hartId := io.hartId
490
491  val errors = ldu.map(_.io.error) ++ // load error
492    Seq(mainPipe.io.error) // store / misc error
493  io.error <> RegNext(Mux1H(errors.map(e => RegNext(e.valid) -> RegNext(e))))
494
495  //----------------------------------------
496  // meta array
497  val meta_read_ports = ldu.map(_.io.meta_read) ++
498    Seq(mainPipe.io.meta_read)
499  val meta_resp_ports = ldu.map(_.io.meta_resp) ++
500    Seq(mainPipe.io.meta_resp)
501  val meta_write_ports = Seq(
502    mainPipe.io.meta_write,
503    refillPipe.io.meta_write
504  )
505  meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p }
506  meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r }
507  meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p }
508
509  val error_flag_resp_ports = ldu.map(_.io.error_flag_resp) ++
510    Seq(mainPipe.io.error_flag_resp)
511  val error_flag_write_ports = Seq(
512    mainPipe.io.error_flag_write,
513    refillPipe.io.error_flag_write
514  )
515  meta_read_ports.zip(errorArray.io.read).foreach { case (p, r) => r <> p }
516  error_flag_resp_ports.zip(errorArray.io.resp).foreach { case (p, r) => p := r }
517  error_flag_write_ports.zip(errorArray.io.write).foreach { case (p, w) => w <> p }
518
519  //----------------------------------------
520  // tag array
521  require(tagArray.io.read.size == (ldu.size + 1))
522  val tag_write_intend = missQueue.io.refill_pipe_req.valid || mainPipe.io.tag_write_intend
523  assert(!RegNext(!tag_write_intend && tagArray.io.write.valid))
524  ldu.zipWithIndex.foreach {
525    case (ld, i) =>
526      tagArray.io.read(i) <> ld.io.tag_read
527      ld.io.tag_resp := tagArray.io.resp(i)
528      ld.io.tag_read.ready := !tag_write_intend
529  }
530  tagArray.io.read.last <> mainPipe.io.tag_read
531  mainPipe.io.tag_resp := tagArray.io.resp.last
532
533  val fake_tag_read_conflict_this_cycle = PopCount(ldu.map(ld=> ld.io.tag_read.valid))
534  XSPerfAccumulate("fake_tag_read_conflict", fake_tag_read_conflict_this_cycle)
535
536  val tag_write_arb = Module(new Arbiter(new TagWriteReq, 2))
537  tag_write_arb.io.in(0) <> refillPipe.io.tag_write
538  tag_write_arb.io.in(1) <> mainPipe.io.tag_write
539  tagArray.io.write <> tag_write_arb.io.out
540
541  //----------------------------------------
542  // data array
543
544  val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 2))
545  dataWriteArb.io.in(0) <> refillPipe.io.data_write
546  dataWriteArb.io.in(1) <> mainPipe.io.data_write
547
548  bankedDataArray.io.write <> dataWriteArb.io.out
549
550  bankedDataArray.io.readline <> mainPipe.io.data_read
551  bankedDataArray.io.readline_intend := mainPipe.io.data_read_intend
552  mainPipe.io.readline_error_delayed := bankedDataArray.io.readline_error_delayed
553  mainPipe.io.data_resp := bankedDataArray.io.resp
554
555  (0 until LoadPipelineWidth).map(i => {
556    bankedDataArray.io.read(i) <> ldu(i).io.banked_data_read
557    bankedDataArray.io.read_error_delayed(i) <> ldu(i).io.read_error_delayed
558
559    ldu(i).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(i)
560    ldu(i).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(i)
561  })
562
563  (0 until (LoadPipelineWidth / 2)).map(i => {
564    ldu(i).io.banked_data_resp := bankedDataArray.io.resp
565  })
566
567  ((LoadPipelineWidth / 2) until LoadPipelineWidth).map(i => {
568    ldu(i).io.banked_data_resp := bankedDataArray.io.resp_dup_0
569  })
570
571  //----------------------------------------
572  // load pipe
573  // the s1 kill signal
574  // only lsu uses this, replay never kills
575  for (w <- 0 until LoadPipelineWidth) {
576    ldu(w).io.lsu <> io.lsu.load(w)
577
578    // replay and nack not needed anymore
579    // TODO: remove replay and nack
580    ldu(w).io.nack := false.B
581
582    ldu(w).io.disable_ld_fast_wakeup :=
583      bankedDataArray.io.disable_ld_fast_wakeup(w) // load pipe fast wake up should be disabled when bank conflict
584  }
585
586  //----------------------------------------
587  // atomics
588  // atomics not finished yet
589  // io.lsu.atomics <> atomicsReplayUnit.io.lsu
590  io.lsu.atomics.resp := RegNext(mainPipe.io.atomic_resp)
591  io.lsu.atomics.block_lr := mainPipe.io.block_lr
592  // atomicsReplayUnit.io.pipe_resp := RegNext(mainPipe.io.atomic_resp)
593  // atomicsReplayUnit.io.block_lr <> mainPipe.io.block_lr
594
595  //----------------------------------------
596  // miss queue
597  val MissReqPortCount = LoadPipelineWidth + 1
598  val MainPipeMissReqPort = 0
599
600  // Request
601  val missReqArb = Module(new Arbiter(new MissReq, MissReqPortCount))
602
603  missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req
604  for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req }
605
606  wb.io.miss_req.valid := missReqArb.io.out.valid
607  wb.io.miss_req.bits  := missReqArb.io.out.bits.addr
608
609  // block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req)
610  missReqArb.io.out <> missQueue.io.req
611  when(wb.io.block_miss_req) {
612    missQueue.io.req.bits.cancel := true.B
613    missReqArb.io.out.ready := false.B
614  }
615
616  // refill to load queue
617  io.lsu.lsq <> missQueue.io.refill_to_ldq
618
619  // tilelink stuff
620  bus.a <> missQueue.io.mem_acquire
621  bus.e <> missQueue.io.mem_finish
622  missQueue.io.probe_addr := bus.b.bits.address
623
624  missQueue.io.main_pipe_resp := RegNext(mainPipe.io.atomic_resp)
625
626  //----------------------------------------
627  // probe
628  // probeQueue.io.mem_probe <> bus.b
629  block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block)
630  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
631  probeQueue.io.update_resv_set <> mainPipe.io.update_resv_set
632
633  //----------------------------------------
634  // mainPipe
635  // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe,
636  // block the req in main pipe
637  block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, missQueue.io.refill_pipe_req.valid)
638  block_decoupled(io.lsu.store.req, mainPipe.io.store_req, refillPipe.io.req.valid)
639
640  io.lsu.store.replay_resp := RegNext(mainPipe.io.store_replay_resp)
641  io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp
642
643  arbiter_with_pipereg(
644    in = Seq(missQueue.io.main_pipe_req, io.lsu.atomics.req),
645    out = mainPipe.io.atomic_req,
646    name = Some("main_pipe_atomic_req")
647  )
648
649  mainPipe.io.invalid_resv_set := RegNext(wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits)
650
651  //----------------------------------------
652  // replace (main pipe)
653  val mpStatus = mainPipe.io.status
654  mainPipe.io.replace_req <> missQueue.io.replace_pipe_req
655  missQueue.io.replace_pipe_resp := mainPipe.io.replace_resp
656
657  //----------------------------------------
658  // refill pipe
659  val refillShouldBeBlocked = (mpStatus.s1.valid && mpStatus.s1.bits.set === missQueue.io.refill_pipe_req.bits.idx) ||
660    Cat(Seq(mpStatus.s2, mpStatus.s3).map(s =>
661      s.valid &&
662        s.bits.set === missQueue.io.refill_pipe_req.bits.idx &&
663        s.bits.way_en === missQueue.io.refill_pipe_req.bits.way_en
664    )).orR
665  block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked)
666
667  val nDupDataWriteReady = 4
668  val nDupTagWriteReady = 4
669  val nDupStatus = nDupDataWriteReady + nDupTagWriteReady
670  val mpStatus_dup = mainPipe.io.status_dup
671  val mq_refill_dup = missQueue.io.refill_pipe_req_dup
672  val refillShouldBeBlocked_dup = VecInit((0 until nDupStatus).map { case i =>
673    mpStatus_dup(i).s1.valid && mpStatus_dup(i).s1.bits.set === mq_refill_dup(i).bits.idx ||
674    Cat(Seq(mpStatus_dup(i).s2, mpStatus_dup(i).s3).map(s =>
675      s.valid &&
676        s.bits.set === mq_refill_dup(i).bits.idx &&
677        s.bits.way_en === mq_refill_dup(i).bits.way_en
678    )).orR
679  })
680  dontTouch(refillShouldBeBlocked_dup)
681
682  refillPipe.io.req_dup_0.bits := mq_refill_dup(0).bits
683  refillPipe.io.req_dup_1.bits := mq_refill_dup(1).bits
684  refillPipe.io.req_dup_2.bits := mq_refill_dup(2).bits
685  refillPipe.io.req_dup_3.bits := mq_refill_dup(3).bits
686  refillPipe.io.req_dup_0.valid := mq_refill_dup(0).valid && !refillShouldBeBlocked_dup(0)
687  refillPipe.io.req_dup_1.valid := mq_refill_dup(1).valid && !refillShouldBeBlocked_dup(1)
688  refillPipe.io.req_dup_2.valid := mq_refill_dup(2).valid && !refillShouldBeBlocked_dup(2)
689  refillPipe.io.req_dup_3.valid := mq_refill_dup(3).valid && !refillShouldBeBlocked_dup(3)
690
691  val refillPipe_io_req_valid_dup = VecInit(mq_refill_dup.zip(refillShouldBeBlocked_dup).map(
692    x => x._1.valid && !x._2
693  ))
694  val refillPipe_io_data_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(0, nDupDataWriteReady))
695  val refillPipe_io_tag_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(nDupDataWriteReady, nDupDataWriteReady + nDupTagWriteReady))
696  dontTouch(refillPipe_io_req_valid_dup)
697  dontTouch(refillPipe_io_data_write_valid_dup)
698  dontTouch(refillPipe_io_tag_write_valid_dup)
699  mainPipe.io.data_write_ready_dup := VecInit(refillPipe_io_data_write_valid_dup.map(v => !v))
700  mainPipe.io.tag_write_ready_dup := VecInit(refillPipe_io_tag_write_valid_dup.map(v => !v))
701  mainPipe.io.wb_ready_dup := wb.io.req_ready_dup
702
703  mq_refill_dup.zip(refillShouldBeBlocked_dup).foreach { case (r, block) =>
704    r.ready := refillPipe.io.req.ready && !block
705  }
706
707  missQueue.io.refill_pipe_resp := refillPipe.io.resp
708  io.lsu.store.refill_hit_resp := RegNext(refillPipe.io.store_resp)
709
710  //----------------------------------------
711  // wb
712  // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy
713
714  wb.io.req <> mainPipe.io.wb
715  bus.c     <> wb.io.mem_release
716  wb.io.release_wakeup := refillPipe.io.release_wakeup
717  wb.io.release_update := mainPipe.io.release_update
718
719  io.lsu.release.valid := RegNext(wb.io.req.fire())
720  io.lsu.release.bits.paddr := RegNext(wb.io.req.bits.addr)
721  // Note: RegNext() is required by:
722  // * load queue released flag update logic
723  // * load / load violation check logic
724  // * and timing requirements
725  // CHANGE IT WITH CARE
726
727  // connect bus d
728  missQueue.io.mem_grant.valid := false.B
729  missQueue.io.mem_grant.bits  := DontCare
730
731  wb.io.mem_grant.valid := false.B
732  wb.io.mem_grant.bits  := DontCare
733
734  // in L1DCache, we ony expect Grant[Data] and ReleaseAck
735  bus.d.ready := false.B
736  when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) {
737    missQueue.io.mem_grant <> bus.d
738  } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) {
739    wb.io.mem_grant <> bus.d
740  } .otherwise {
741    assert (!bus.d.fire())
742  }
743
744  //----------------------------------------
745  // replacement algorithm
746  val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets)
747
748  val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way)
749  replWayReqs.foreach{
750    case req =>
751      req.way := DontCare
752      when (req.set.valid) { req.way := replacer.way(req.set.bits) }
753  }
754
755  val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq(
756    mainPipe.io.replace_access
757  )
758  val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W))))
759  touchWays.zip(replAccessReqs).foreach {
760    case (w, req) =>
761      w.valid := req.valid
762      w.bits := req.bits.way
763  }
764  val touchSets = replAccessReqs.map(_.bits.set)
765  replacer.access(touchSets, touchWays)
766
767  //----------------------------------------
768  // assertions
769  // dcache should only deal with DRAM addresses
770  when (bus.a.fire()) {
771    assert(bus.a.bits.address >= 0x80000000L.U)
772  }
773  when (bus.b.fire()) {
774    assert(bus.b.bits.address >= 0x80000000L.U)
775  }
776  when (bus.c.fire()) {
777    assert(bus.c.bits.address >= 0x80000000L.U)
778  }
779
780  //----------------------------------------
781  // utility functions
782  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
783    sink.valid   := source.valid && !block_signal
784    source.ready := sink.ready   && !block_signal
785    sink.bits    := source.bits
786  }
787
788  //----------------------------------------
789  // Customized csr cache op support
790  val cacheOpDecoder = Module(new CSRCacheOpDecoder("dcache", CacheInstrucion.COP_ID_DCACHE))
791  cacheOpDecoder.io.csr <> io.csr
792  bankedDataArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
793  // dup cacheOp_req_valid
794  bankedDataArray.io.cacheOp_req_dups.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dups(i) }
795  // dup cacheOp_req_bits_opCode
796  bankedDataArray.io.cacheOp_req_bits_opCode_dups.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dups(i) }
797
798  tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
799  // dup cacheOp_req_valid
800  tagArray.io.cacheOp_req_dups.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dups(i) }
801  // dup cacheOp_req_bits_opCode
802  tagArray.io.cacheOp_req_bits_opCode_dups.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dups(i) }
803
804  cacheOpDecoder.io.cache.resp.valid := bankedDataArray.io.cacheOp.resp.valid ||
805    tagArray.io.cacheOp.resp.valid
806  cacheOpDecoder.io.cache.resp.bits := Mux1H(List(
807    bankedDataArray.io.cacheOp.resp.valid -> bankedDataArray.io.cacheOp.resp.bits,
808    tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits,
809  ))
810  cacheOpDecoder.io.error := io.error
811  assert(!((bankedDataArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U))
812
813  //----------------------------------------
814  // performance counters
815  val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire()))
816  XSPerfAccumulate("num_loads", num_loads)
817
818  io.mshrFull := missQueue.io.full
819
820  // performance counter
821  val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType))
822  val st_access = Wire(ld_access.last.cloneType)
823  ld_access.zip(ldu).foreach {
824    case (a, u) =>
825      a.valid := RegNext(u.io.lsu.req.fire()) && !u.io.lsu.s1_kill
826      a.bits.idx := RegNext(get_idx(u.io.lsu.req.bits.addr))
827      a.bits.tag := get_tag(u.io.lsu.s1_paddr_dup_dcache)
828  }
829  st_access.valid := RegNext(mainPipe.io.store_req.fire())
830  st_access.bits.idx := RegNext(get_idx(mainPipe.io.store_req.bits.vaddr))
831  st_access.bits.tag := RegNext(get_tag(mainPipe.io.store_req.bits.addr))
832  val access_info = ld_access.toSeq ++ Seq(st_access)
833  val early_replace = RegNext(missQueue.io.debug_early_replace)
834  val access_early_replace = access_info.map {
835    case acc =>
836      Cat(early_replace.map {
837        case r =>
838          acc.valid && r.valid &&
839            acc.bits.tag === r.bits.tag &&
840            acc.bits.idx === r.bits.idx
841      })
842  }
843  XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace)))
844
845  val perfEvents = (Seq(wb, mainPipe, missQueue, probeQueue) ++ ldu).flatMap(_.getPerfEvents)
846  generatePerfEvent()
847}
848
849class AMOHelper() extends ExtModule {
850  val clock  = IO(Input(Clock()))
851  val enable = IO(Input(Bool()))
852  val cmd    = IO(Input(UInt(5.W)))
853  val addr   = IO(Input(UInt(64.W)))
854  val wdata  = IO(Input(UInt(64.W)))
855  val mask   = IO(Input(UInt(8.W)))
856  val rdata  = IO(Output(UInt(64.W)))
857}
858
859class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
860
861  val useDcache = coreParams.dcacheParametersOpt.nonEmpty
862  val clientNode = if (useDcache) TLIdentityNode() else null
863  val dcache = if (useDcache) LazyModule(new DCache()) else null
864  if (useDcache) {
865    clientNode := dcache.clientNode
866  }
867
868  lazy val module = new LazyModuleImp(this) with HasPerfEvents {
869    val io = IO(new DCacheIO)
870    val perfEvents = if (!useDcache) {
871      // a fake dcache which uses dpi-c to access memory, only for debug usage!
872      val fake_dcache = Module(new FakeDCache())
873      io <> fake_dcache.io
874      Seq()
875    }
876    else {
877      io <> dcache.module.io
878      dcache.module.getPerfEvents
879    }
880    generatePerfEvent()
881  }
882}
883