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