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