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