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