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