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