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