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