xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/DCacheWrapper.scala (revision 34f38695595bef0ac495f3c1c1f0690fbcffa16b)
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 xiangshan.backend.rob.RobDebugRollingIO
28import freechips.rocketchip.tilelink._
29import freechips.rocketchip.util.{BundleFieldBase, UIntToOH1}
30import device.RAMHelper
31import coupledL2.{AliasField, VaddrField, PrefetchField}
32import utility.ReqSourceField
33import utility.FastArbiter
34import mem.AddPipelineReg
35import xiangshan.cache.wpu._
36import xiangshan.mem.HasL1PrefetchSourceParameter
37import xiangshan.mem.prefetch._
38
39import scala.math.max
40
41// DCache specific parameters
42case class DCacheParameters
43(
44  nSets: Int = 256,
45  nWays: Int = 8,
46  rowBits: Int = 64,
47  tagECC: Option[String] = None,
48  dataECC: Option[String] = None,
49  replacer: Option[String] = Some("setplru"),
50  updateReplaceOn2ndmiss: Boolean = true,
51  nMissEntries: Int = 1,
52  nProbeEntries: Int = 1,
53  nReleaseEntries: Int = 1,
54  nMMIOEntries: Int = 1,
55  nMMIOs: Int = 1,
56  blockBytes: Int = 64,
57  nMaxPrefetchEntry: Int = 1,
58  alwaysReleaseData: Boolean = false
59) extends L1CacheParameters {
60  // if sets * blockBytes > 4KB(page size),
61  // cache alias will happen,
62  // we need to avoid this by recoding additional bits in L2 cache
63  val setBytes = nSets * blockBytes
64  val aliasBitsOpt = if(setBytes > pageSize) Some(log2Ceil(setBytes / pageSize)) else None
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 with HasL1PrefetchSourceParameter{
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  // the following sources are only used inside SMS
114  def HW_PREFETCH_AGT = 5
115  def HW_PREFETCH_PHT_CUR = 6
116  def HW_PREFETCH_PHT_INC = 7
117  def HW_PREFETCH_PHT_DEC = 8
118  def HW_PREFETCH_BOP = 9
119  def HW_PREFETCH_STRIDE = 10
120
121  def BLOOM_FILTER_ENTRY_NUM = 4096
122
123  // each source use a id to distinguish its multiple reqs
124  def reqIdWidth = log2Up(nEntries) max log2Up(StoreBufferSize)
125
126  require(isPow2(cfg.nMissEntries)) // TODO
127  // require(isPow2(cfg.nReleaseEntries))
128  require(cfg.nMissEntries < cfg.nReleaseEntries)
129  val nEntries = cfg.nMissEntries + cfg.nReleaseEntries
130  val releaseIdBase = cfg.nMissEntries
131
132  // banked dcache support
133  val DCacheSetDiv = 1
134  val DCacheSets = cacheParams.nSets
135  val DCacheWays = cacheParams.nWays
136  val DCacheBanks = 8 // hardcoded
137  val DCacheDupNum = 16
138  val DCacheSRAMRowBits = cacheParams.rowBits // hardcoded
139  val DCacheWordBits = 64 // hardcoded
140  val DCacheWordBytes = DCacheWordBits / 8
141  val MaxPrefetchEntry = cacheParams.nMaxPrefetchEntry
142  val DCacheVWordBytes = VLEN / 8
143  require(DCacheSRAMRowBits == 64)
144
145  val DCacheSetDivBits = log2Ceil(DCacheSetDiv)
146  val DCacheSetBits = log2Ceil(DCacheSets)
147  val DCacheSizeBits = DCacheSRAMRowBits * DCacheBanks * DCacheWays * DCacheSets
148  val DCacheSizeBytes = DCacheSizeBits / 8
149  val DCacheSizeWords = DCacheSizeBits / 64 // TODO
150
151  val DCacheSameVPAddrLength = 12
152
153  val DCacheSRAMRowBytes = DCacheSRAMRowBits / 8
154  val DCacheWordOffset = log2Up(DCacheWordBytes)
155  val DCacheVWordOffset = log2Up(DCacheVWordBytes)
156
157  val DCacheBankOffset = log2Up(DCacheSRAMRowBytes)
158  val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks)
159  val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets)
160  val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength
161  val DCacheLineOffset = DCacheSetOffset
162
163  // uncache
164  val uncacheIdxBits = log2Up(StoreQueueSize + 1) max log2Up(VirtualLoadQueueSize + 1)
165  // hardware prefetch parameters
166  // high confidence hardware prefetch port
167  val HighConfHWPFLoadPort = LoadPipelineWidth - 1 // use the last load port by default
168  val IgnorePrefetchConfidence = false
169
170  // parameters about duplicating regs to solve fanout
171  // In Main Pipe:
172    // tag_write.ready -> data_write.valid * 8 banks
173    // tag_write.ready -> meta_write.valid
174    // tag_write.ready -> tag_write.valid
175    // tag_write.ready -> err_write.valid
176    // tag_write.ready -> wb.valid
177  val nDupTagWriteReady = DCacheBanks + 4
178  // In Main Pipe:
179    // data_write.ready -> data_write.valid * 8 banks
180    // data_write.ready -> meta_write.valid
181    // data_write.ready -> tag_write.valid
182    // data_write.ready -> err_write.valid
183    // data_write.ready -> wb.valid
184  val nDupDataWriteReady = DCacheBanks + 4
185  val nDupWbReady = DCacheBanks + 4
186  val nDupStatus = nDupTagWriteReady + nDupDataWriteReady
187  val dataWritePort = 0
188  val metaWritePort = DCacheBanks
189  val tagWritePort = metaWritePort + 1
190  val errWritePort = tagWritePort + 1
191  val wbPort = errWritePort + 1
192
193  def set_to_dcache_div(set: UInt) = {
194    require(set.getWidth >= DCacheSetBits)
195    if (DCacheSetDivBits == 0) 0.U else set(DCacheSetDivBits-1, 0)
196  }
197
198  def set_to_dcache_div_set(set: UInt) = {
199    require(set.getWidth >= DCacheSetBits)
200    set(DCacheSetBits - 1, DCacheSetDivBits)
201  }
202
203  def addr_to_dcache_bank(addr: UInt) = {
204    require(addr.getWidth >= DCacheSetOffset)
205    addr(DCacheSetOffset-1, DCacheBankOffset)
206  }
207
208  def addr_to_dcache_div(addr: UInt) = {
209    require(addr.getWidth >= DCacheAboveIndexOffset)
210    if(DCacheSetDivBits == 0) 0.U else addr(DCacheSetOffset + DCacheSetDivBits - 1, DCacheSetOffset)
211  }
212
213  def addr_to_dcache_div_set(addr: UInt) = {
214    require(addr.getWidth >= DCacheAboveIndexOffset)
215    addr(DCacheAboveIndexOffset - 1, DCacheSetOffset + DCacheSetDivBits)
216  }
217
218  def addr_to_dcache_set(addr: UInt) = {
219    require(addr.getWidth >= DCacheAboveIndexOffset)
220    addr(DCacheAboveIndexOffset-1, DCacheSetOffset)
221  }
222
223  def get_data_of_bank(bank: Int, data: UInt) = {
224    require(data.getWidth >= (bank+1)*DCacheSRAMRowBits)
225    data(DCacheSRAMRowBits * (bank + 1) - 1, DCacheSRAMRowBits * bank)
226  }
227
228  def get_mask_of_bank(bank: Int, data: UInt) = {
229    require(data.getWidth >= (bank+1)*DCacheSRAMRowBytes)
230    data(DCacheSRAMRowBytes * (bank + 1) - 1, DCacheSRAMRowBytes * bank)
231  }
232
233  def is_alias_match(vaddr0: UInt, vaddr1: UInt): Bool = {
234    require(vaddr0.getWidth == VAddrBits && vaddr1.getWidth == VAddrBits)
235    if(blockOffBits + idxBits > pgIdxBits) {
236      vaddr0(blockOffBits + idxBits - 1, pgIdxBits) === vaddr1(blockOffBits + idxBits - 1, pgIdxBits)
237    }else {
238      // no alias problem
239      true.B
240    }
241  }
242
243  def get_direct_map_way(addr:UInt): UInt = {
244    addr(DCacheAboveIndexOffset + log2Up(DCacheWays) - 1, DCacheAboveIndexOffset)
245  }
246
247  def arbiter[T <: Bundle](
248    in: Seq[DecoupledIO[T]],
249    out: DecoupledIO[T],
250    name: Option[String] = None): Unit = {
251    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
252    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
253    for ((a, req) <- arb.io.in.zip(in)) {
254      a <> req
255    }
256    out <> arb.io.out
257  }
258
259  def arbiter_with_pipereg[T <: Bundle](
260    in: Seq[DecoupledIO[T]],
261    out: DecoupledIO[T],
262    name: Option[String] = None): Unit = {
263    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
264    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
265    for ((a, req) <- arb.io.in.zip(in)) {
266      a <> req
267    }
268    AddPipelineReg(arb.io.out, out, false.B)
269  }
270
271  def arbiter_with_pipereg_N_dup[T <: Bundle](
272    in: Seq[DecoupledIO[T]],
273    out: DecoupledIO[T],
274    dups: Seq[DecoupledIO[T]],
275    name: Option[String] = None): Unit = {
276    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
277    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
278    for ((a, req) <- arb.io.in.zip(in)) {
279      a <> req
280    }
281    for (dup <- dups) {
282      AddPipelineReg(arb.io.out, dup, false.B)
283    }
284    AddPipelineReg(arb.io.out, out, false.B)
285  }
286
287  def rrArbiter[T <: Bundle](
288    in: Seq[DecoupledIO[T]],
289    out: DecoupledIO[T],
290    name: Option[String] = None): Unit = {
291    val arb = Module(new RRArbiter[T](chiselTypeOf(out.bits), in.size))
292    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
293    for ((a, req) <- arb.io.in.zip(in)) {
294      a <> req
295    }
296    out <> arb.io.out
297  }
298
299  def fastArbiter[T <: Bundle](
300    in: Seq[DecoupledIO[T]],
301    out: DecoupledIO[T],
302    name: Option[String] = None): Unit = {
303    val arb = Module(new FastArbiter[T](chiselTypeOf(out.bits), in.size))
304    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
305    for ((a, req) <- arb.io.in.zip(in)) {
306      a <> req
307    }
308    out <> arb.io.out
309  }
310
311  val numReplaceRespPorts = 2
312
313  require(isPow2(nSets), s"nSets($nSets) must be pow2")
314  require(isPow2(nWays), s"nWays($nWays) must be pow2")
315  require(full_divide(rowBits, wordBits), s"rowBits($rowBits) must be multiple of wordBits($wordBits)")
316  require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)")
317}
318
319abstract class DCacheModule(implicit p: Parameters) extends L1CacheModule
320  with HasDCacheParameters
321
322abstract class DCacheBundle(implicit p: Parameters) extends L1CacheBundle
323  with HasDCacheParameters
324
325class ReplacementAccessBundle(implicit p: Parameters) extends DCacheBundle {
326  val set = UInt(log2Up(nSets).W)
327  val way = UInt(log2Up(nWays).W)
328}
329
330class ReplacementWayReqIO(implicit p: Parameters) extends DCacheBundle {
331  val set = ValidIO(UInt(log2Up(nSets).W))
332  val dmWay = Output(UInt(log2Up(nWays).W))
333  val way = Input(UInt(log2Up(nWays).W))
334}
335
336class DCacheExtraMeta(implicit p: Parameters) extends DCacheBundle
337{
338  val error = Bool() // cache line has been marked as corrupted by l2 / ecc error detected when store
339  val prefetch = UInt(L1PfSourceBits.W) // cache line is first required by prefetch
340  val access = Bool() // cache line has been accessed by load / store
341
342  // val debug_access_timestamp = UInt(64.W) // last time a load / store / refill access that cacheline
343}
344
345// memory request in word granularity(load, mmio, lr/sc, atomics)
346class DCacheWordReq(implicit p: Parameters) extends DCacheBundle
347{
348  val cmd    = UInt(M_SZ.W)
349  val vaddr  = UInt(VAddrBits.W)
350  val data   = UInt(VLEN.W)
351  val mask   = UInt((VLEN/8).W)
352  val id     = UInt(reqIdWidth.W)
353  val instrtype   = UInt(sourceTypeWidth.W)
354  val isFirstIssue = Bool()
355  val replayCarry = new ReplayCarry(nWays)
356
357  val debug_robIdx = UInt(log2Ceil(RobSize).W)
358  def dump() = {
359    XSDebug("DCacheWordReq: cmd: %x vaddr: %x data: %x mask: %x id: %d\n",
360      cmd, vaddr, data, mask, id)
361  }
362}
363
364// memory request in word granularity(store)
365class DCacheLineReq(implicit p: Parameters) extends DCacheBundle
366{
367  val cmd    = UInt(M_SZ.W)
368  val vaddr  = UInt(VAddrBits.W)
369  val addr   = UInt(PAddrBits.W)
370  val data   = UInt((cfg.blockBytes * 8).W)
371  val mask   = UInt(cfg.blockBytes.W)
372  val id     = UInt(reqIdWidth.W)
373  def dump() = {
374    XSDebug("DCacheLineReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
375      cmd, addr, data, mask, id)
376  }
377  def idx: UInt = get_idx(vaddr)
378}
379
380class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq {
381  val addr = UInt(PAddrBits.W)
382  val wline = Bool()
383}
384
385class DCacheWordReqWithVaddrAndPfFlag(implicit p: Parameters) extends DCacheWordReqWithVaddr {
386  val prefetch = Bool()
387
388  def toDCacheWordReqWithVaddr() = {
389    val res = Wire(new DCacheWordReqWithVaddr)
390    res.vaddr := vaddr
391    res.wline := wline
392    res.cmd := cmd
393    res.addr := addr
394    res.data := data
395    res.mask := mask
396    res.id := id
397    res.instrtype := instrtype
398    res.replayCarry := replayCarry
399    res.isFirstIssue := isFirstIssue
400    res.debug_robIdx := debug_robIdx
401
402    res
403  }
404}
405
406class BaseDCacheWordResp(implicit p: Parameters) extends DCacheBundle
407{
408  // read in s2
409  val data = UInt(VLEN.W)
410  // select in s3
411  val data_delayed = UInt(VLEN.W)
412  val id     = UInt(reqIdWidth.W)
413  // cache req missed, send it to miss queue
414  val miss   = Bool()
415  // cache miss, and failed to enter the missqueue, replay from RS is needed
416  val replay = Bool()
417  val replayCarry = new ReplayCarry(nWays)
418  // data has been corrupted
419  val tag_error = Bool() // tag error
420  val mshr_id = UInt(log2Up(cfg.nMissEntries).W)
421
422  val debug_robIdx = UInt(log2Ceil(RobSize).W)
423  def dump() = {
424    XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n",
425      data, id, miss, replay)
426  }
427}
428
429class DCacheWordResp(implicit p: Parameters) extends BaseDCacheWordResp
430{
431  val meta_prefetch = UInt(L1PfSourceBits.W)
432  val meta_access = Bool()
433  // s2
434  val handled = Bool()
435  val real_miss = Bool()
436  // s3: 1 cycle after data resp
437  val error_delayed = Bool() // all kinds of errors, include tag error
438  val replacementUpdated = Bool()
439}
440
441class BankedDCacheWordResp(implicit p: Parameters) extends DCacheWordResp
442{
443  val bank_data = Vec(DCacheBanks, Bits(DCacheSRAMRowBits.W))
444  val bank_oh = UInt(DCacheBanks.W)
445}
446
447class DCacheWordRespWithError(implicit p: Parameters) extends BaseDCacheWordResp
448{
449  val error = Bool() // all kinds of errors, include tag error
450}
451
452class DCacheLineResp(implicit p: Parameters) extends DCacheBundle
453{
454  val data   = UInt((cfg.blockBytes * 8).W)
455  // cache req missed, send it to miss queue
456  val miss   = Bool()
457  // cache req nacked, replay it later
458  val replay = Bool()
459  val id     = UInt(reqIdWidth.W)
460  def dump() = {
461    XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n",
462      data, id, miss, replay)
463  }
464}
465
466class Refill(implicit p: Parameters) extends DCacheBundle
467{
468  val addr   = UInt(PAddrBits.W)
469  val data   = UInt(l1BusDataWidth.W)
470  val error  = Bool() // refilled data has been corrupted
471  // for debug usage
472  val data_raw = UInt((cfg.blockBytes * 8).W)
473  val hasdata = Bool()
474  val refill_done = Bool()
475  def dump() = {
476    XSDebug("Refill: addr: %x data: %x\n", addr, data)
477  }
478  val id     = UInt(log2Up(cfg.nMissEntries).W)
479}
480
481class Release(implicit p: Parameters) extends DCacheBundle
482{
483  val paddr  = UInt(PAddrBits.W)
484  def dump() = {
485    XSDebug("Release: paddr: %x\n", paddr(PAddrBits-1, DCacheTagOffset))
486  }
487}
488
489class DCacheWordIO(implicit p: Parameters) extends DCacheBundle
490{
491  val req  = DecoupledIO(new DCacheWordReq)
492  val resp = Flipped(DecoupledIO(new DCacheWordResp))
493}
494
495
496class UncacheWordReq(implicit p: Parameters) extends DCacheBundle
497{
498  val cmd  = UInt(M_SZ.W)
499  val addr = UInt(PAddrBits.W)
500  val data = UInt(XLEN.W)
501  val mask = UInt((XLEN/8).W)
502  val id   = UInt(uncacheIdxBits.W)
503  val instrtype = UInt(sourceTypeWidth.W)
504  val atomic = Bool()
505  val isFirstIssue = Bool()
506  val replayCarry = new ReplayCarry(nWays)
507
508  def dump() = {
509    XSDebug("UncacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
510      cmd, addr, data, mask, id)
511  }
512}
513
514class UncacheWordResp(implicit p: Parameters) extends DCacheBundle
515{
516  val data      = UInt(XLEN.W)
517  val data_delayed = UInt(XLEN.W)
518  val id        = UInt(uncacheIdxBits.W)
519  val miss      = Bool()
520  val replay    = Bool()
521  val tag_error = Bool()
522  val error     = Bool()
523  val replayCarry = new ReplayCarry(nWays)
524  val mshr_id = UInt(log2Up(cfg.nMissEntries).W)  // FIXME: why uncacheWordResp is not merged to baseDcacheResp
525
526  val debug_robIdx = UInt(log2Ceil(RobSize).W)
527  def dump() = {
528    XSDebug("UncacheWordResp: data: %x id: %d miss: %b replay: %b, tag_error: %b, error: %b\n",
529      data, id, miss, replay, tag_error, error)
530  }
531}
532
533class UncacheWordIO(implicit p: Parameters) extends DCacheBundle
534{
535  val req  = DecoupledIO(new UncacheWordReq)
536  val resp = Flipped(DecoupledIO(new UncacheWordResp))
537}
538
539class AtomicsResp(implicit p: Parameters) extends DCacheBundle {
540  val data    = UInt(DataBits.W)
541  val miss    = Bool()
542  val miss_id = UInt(log2Up(cfg.nMissEntries).W)
543  val replay  = Bool()
544  val error   = Bool()
545
546  val ack_miss_queue = Bool()
547
548  val id     = UInt(reqIdWidth.W)
549}
550
551class AtomicWordIO(implicit p: Parameters) extends DCacheBundle
552{
553  val req  = DecoupledIO(new MainPipeReq)
554  val resp = Flipped(ValidIO(new AtomicsResp))
555  val block_lr = Input(Bool())
556}
557
558// used by load unit
559class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO
560{
561  // kill previous cycle's req
562  val s1_kill  = Output(Bool())
563  val s2_kill  = Output(Bool())
564  val s0_pc = Output(UInt(VAddrBits.W))
565  val s1_pc = Output(UInt(VAddrBits.W))
566  val s2_pc = Output(UInt(VAddrBits.W))
567  // cycle 0: load has updated replacement before
568  val replacementUpdated = Output(Bool())
569  // cycle 0: prefetch source bits
570  val pf_source = Output(UInt(L1PfSourceBits.W))
571  // cycle 0: virtual address: req.addr
572  // cycle 1: physical address: s1_paddr
573  val s1_paddr_dup_lsu = Output(UInt(PAddrBits.W)) // lsu side paddr
574  val s1_paddr_dup_dcache = Output(UInt(PAddrBits.W)) // dcache side paddr
575  val s1_disable_fast_wakeup = Input(Bool())
576  // cycle 2: hit signal
577  val s2_hit = Input(Bool()) // hit signal for lsu,
578  val s2_first_hit = Input(Bool())
579  val s2_bank_conflict = Input(Bool())
580  val s2_wpu_pred_fail = Input(Bool())
581  val s2_mq_nack = Input(Bool())
582
583  // debug
584  val debug_s1_hit_way = Input(UInt(nWays.W))
585  val debug_s2_pred_way_num = Input(UInt(XLEN.W))
586  val debug_s2_dm_way_num = Input(UInt(XLEN.W))
587  val debug_s2_real_way_num = Input(UInt(XLEN.W))
588}
589
590class DCacheLineIO(implicit p: Parameters) extends DCacheBundle
591{
592  val req  = DecoupledIO(new DCacheLineReq)
593  val resp = Flipped(DecoupledIO(new DCacheLineResp))
594}
595
596class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle {
597  // sbuffer will directly send request to dcache main pipe
598  val req = Flipped(Decoupled(new DCacheLineReq))
599
600  val main_pipe_hit_resp = ValidIO(new DCacheLineResp)
601  val refill_hit_resp = ValidIO(new DCacheLineResp)
602
603  val replay_resp = ValidIO(new DCacheLineResp)
604
605  def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp)
606}
607
608// forward tilelink channel D's data to ldu
609class DcacheToLduForwardIO(implicit p: Parameters) extends DCacheBundle {
610  val valid = Bool()
611  val data = UInt(l1BusDataWidth.W)
612  val mshrid = UInt(log2Up(cfg.nMissEntries).W)
613  val last = Bool()
614
615  def apply(req_valid : Bool, req_data : UInt, req_mshrid : UInt, req_last : Bool) = {
616    valid := req_valid
617    data := req_data
618    mshrid := req_mshrid
619    last := req_last
620  }
621
622  def dontCare() = {
623    valid := false.B
624    data := DontCare
625    mshrid := DontCare
626    last := DontCare
627  }
628
629  def forward(req_valid : Bool, req_mshr_id : UInt, req_paddr : UInt) = {
630    val all_match = req_valid && valid &&
631                req_mshr_id === mshrid &&
632                req_paddr(log2Up(refillBytes)) === last
633
634    val forward_D = RegInit(false.B)
635    val forwardData = RegInit(VecInit(List.fill(VLEN/8)(0.U(8.W))))
636
637    val block_idx = req_paddr(log2Up(refillBytes) - 1, 3)
638    val block_data = Wire(Vec(l1BusDataWidth / 64, UInt(64.W)))
639    (0 until l1BusDataWidth / 64).map(i => {
640      block_data(i) := data(64 * i + 63, 64 * i)
641    })
642    val selected_data = Wire(UInt(128.W))
643    selected_data := Mux(req_paddr(3), Fill(2, block_data(block_idx)), Cat(block_data(block_idx + 1.U), block_data(block_idx)))
644
645    forward_D := all_match
646    for (i <- 0 until VLEN/8) {
647      forwardData(i) := selected_data(8 * i + 7, 8 * i)
648    }
649
650    (forward_D, forwardData)
651  }
652}
653
654class MissEntryForwardIO(implicit p: Parameters) extends DCacheBundle {
655  val inflight = Bool()
656  val paddr = UInt(PAddrBits.W)
657  val raw_data = Vec(blockRows, UInt(rowBits.W))
658  val firstbeat_valid = Bool()
659  val lastbeat_valid = Bool()
660
661  def apply(mshr_valid : Bool, mshr_paddr : UInt, mshr_rawdata : Vec[UInt], mshr_first_valid : Bool, mshr_last_valid : Bool) = {
662    inflight := mshr_valid
663    paddr := mshr_paddr
664    raw_data := mshr_rawdata
665    firstbeat_valid := mshr_first_valid
666    lastbeat_valid := mshr_last_valid
667  }
668
669  // check if we can forward from mshr or D channel
670  def check(req_valid : Bool, req_paddr : UInt) = {
671    RegNext(req_valid && inflight && req_paddr(PAddrBits - 1, blockOffBits) === paddr(PAddrBits - 1, blockOffBits))
672  }
673
674  def forward(req_valid : Bool, req_paddr : UInt) = {
675    val all_match = (req_paddr(log2Up(refillBytes)) === 0.U && firstbeat_valid) ||
676                    (req_paddr(log2Up(refillBytes)) === 1.U && lastbeat_valid)
677
678    val forward_mshr = RegInit(false.B)
679    val forwardData = RegInit(VecInit(List.fill(VLEN/8)(0.U(8.W))))
680
681    val block_idx = req_paddr(log2Up(refillBytes), 3)
682    val block_data = raw_data
683
684    val selected_data = Wire(UInt(128.W))
685    selected_data := Mux(req_paddr(3), Fill(2, block_data(block_idx)), Cat(block_data(block_idx + 1.U), block_data(block_idx)))
686
687    forward_mshr := all_match
688    for (i <- 0 until VLEN/8) {
689      forwardData(i) := selected_data(8 * i + 7, 8 * i)
690    }
691
692    (forward_mshr, forwardData)
693  }
694}
695
696// forward mshr's data to ldu
697class LduToMissqueueForwardIO(implicit p: Parameters) extends DCacheBundle {
698  // req
699  val valid = Input(Bool())
700  val mshrid = Input(UInt(log2Up(cfg.nMissEntries).W))
701  val paddr = Input(UInt(PAddrBits.W))
702  // resp
703  val forward_mshr = Output(Bool())
704  val forwardData = Output(Vec(VLEN/8, UInt(8.W)))
705  val forward_result_valid = Output(Bool())
706
707  def connect(sink: LduToMissqueueForwardIO) = {
708    sink.valid := valid
709    sink.mshrid := mshrid
710    sink.paddr := paddr
711    forward_mshr := sink.forward_mshr
712    forwardData := sink.forwardData
713    forward_result_valid := sink.forward_result_valid
714  }
715
716  def forward() = {
717    (forward_result_valid, forward_mshr, forwardData)
718  }
719}
720
721class StorePrefetchReq(implicit p: Parameters) extends DCacheBundle {
722  val paddr = UInt(PAddrBits.W)
723  val vaddr = UInt(VAddrBits.W)
724}
725
726class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle {
727  val load  = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load
728  val sta   = Vec(StorePipelineWidth, Flipped(new DCacheStoreIO)) // for non-blocking store
729  val lsq = ValidIO(new Refill)  // refill to load queue, wake up load misses
730  val tl_d_channel = Output(new DcacheToLduForwardIO)
731  val store = new DCacheToSbufferIO // for sbuffer
732  val atomics  = Flipped(new AtomicWordIO)  // atomics reqs
733  val release = ValidIO(new Release) // cacheline release hint for ld-ld violation check
734  val forward_D = Output(Vec(LoadPipelineWidth, new DcacheToLduForwardIO))
735  val forward_mshr = Vec(LoadPipelineWidth, new LduToMissqueueForwardIO)
736}
737
738class DCacheTopDownIO(implicit p: Parameters) extends DCacheBundle {
739  val robHeadVaddr = Flipped(Valid(UInt(VAddrBits.W)))
740  val robHeadMissInDCache = Output(Bool())
741  val robHeadOtherReplay = Input(Bool())
742}
743
744class DCacheIO(implicit p: Parameters) extends DCacheBundle {
745  val hartId = Input(UInt(8.W))
746  val l2_pf_store_only = Input(Bool())
747  val lsu = new DCacheToLsuIO
748  val csr = new L1CacheToCsrIO
749  val error = new L1CacheErrorInfo
750  val mshrFull = Output(Bool())
751  val memSetPattenDetected = Output(Bool())
752  val lqEmpty = Input(Bool())
753  val pf_ctrl = Output(new PrefetchControlBundle)
754  val force_write = Input(Bool())
755  val debugTopDown = new DCacheTopDownIO
756  val debugRolling = Flipped(new RobDebugRollingIO)
757}
758
759class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters {
760  override def shouldBeInlined: Boolean = false
761
762  val reqFields: Seq[BundleFieldBase] = Seq(
763    PrefetchField(),
764    ReqSourceField(),
765    VaddrField(VAddrBits - blockOffBits),
766  ) ++ cacheParams.aliasBitsOpt.map(AliasField)
767  val echoFields: Seq[BundleFieldBase] = Nil
768
769  val clientParameters = TLMasterPortParameters.v1(
770    Seq(TLMasterParameters.v1(
771      name = "dcache",
772      sourceId = IdRange(0, nEntries + 1),
773      supportsProbe = TransferSizes(cfg.blockBytes)
774    )),
775    requestFields = reqFields,
776    echoFields = echoFields
777  )
778
779  val clientNode = TLClientNode(Seq(clientParameters))
780
781  lazy val module = new DCacheImp(this)
782}
783
784
785class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters with HasPerfEvents with HasL1PrefetchSourceParameter {
786
787  val io = IO(new DCacheIO)
788
789  val (bus, edge) = outer.clientNode.out.head
790  require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match")
791
792  println("DCache:")
793  println("  DCacheSets: " + DCacheSets)
794  println("  DCacheSetDiv: " + DCacheSetDiv)
795  println("  DCacheWays: " + DCacheWays)
796  println("  DCacheBanks: " + DCacheBanks)
797  println("  DCacheSRAMRowBits: " + DCacheSRAMRowBits)
798  println("  DCacheWordOffset: " + DCacheWordOffset)
799  println("  DCacheBankOffset: " + DCacheBankOffset)
800  println("  DCacheSetOffset: " + DCacheSetOffset)
801  println("  DCacheTagOffset: " + DCacheTagOffset)
802  println("  DCacheAboveIndexOffset: " + DCacheAboveIndexOffset)
803  println("  DcacheMaxPrefetchEntry: " + MaxPrefetchEntry)
804  println("  WPUEnable: " + dwpuParam.enWPU)
805  println("  WPUEnableCfPred: " + dwpuParam.enCfPred)
806  println("  WPUAlgorithm: " + dwpuParam.algoName)
807
808  // Enable L1 Store prefetch
809  val StorePrefetchL1Enabled = EnableStorePrefetchAtCommit || EnableStorePrefetchAtIssue || EnableStorePrefetchSPB
810  val MetaReadPort = if(StorePrefetchL1Enabled) LoadPipelineWidth + 1 + StorePipelineWidth else LoadPipelineWidth + 1
811  val TagReadPort = if(StorePrefetchL1Enabled) LoadPipelineWidth + 1 + StorePipelineWidth else LoadPipelineWidth + 1
812
813  // Enable L1 Load prefetch
814  val LoadPrefetchL1Enabled = true
815  val AccessArrayReadPort = if(LoadPrefetchL1Enabled) LoadPipelineWidth + 1 + 1 else LoadPipelineWidth + 1
816  val PrefetchArrayReadPort = if(LoadPrefetchL1Enabled) LoadPipelineWidth + 1 + 1 else LoadPipelineWidth + 1
817
818  //----------------------------------------
819  // core data structures
820  val bankedDataArray = if(dwpuParam.enWPU) Module(new SramedDataArray) else Module(new BankedDataArray)
821  val metaArray = Module(new L1CohMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2))
822  val errorArray = Module(new L1FlagMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2))
823  val prefetchArray = Module(new L1PrefetchSourceArray(readPorts = PrefetchArrayReadPort, writePorts = 2 + LoadPipelineWidth)) // prefetch flag array
824  val accessArray = Module(new L1FlagMetaArray(readPorts = AccessArrayReadPort, writePorts = LoadPipelineWidth + 2))
825  val tagArray = Module(new DuplicatedTagArray(readPorts = TagReadPort))
826  val prefetcherMonitor = Module(new PrefetcherMonitor)
827  val fdpMonitor =  Module(new FDPrefetcherMonitor)
828  val bloomFilter =  Module(new BloomFilter(BLOOM_FILTER_ENTRY_NUM, true))
829  val counterFilter = Module(new CounterFilter)
830  bankedDataArray.dump()
831
832  //----------------------------------------
833  // core modules
834  val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))})
835  val stu = Seq.tabulate(StorePipelineWidth)({ i => Module(new StorePipe(i))})
836  val mainPipe     = Module(new MainPipe)
837  val refillPipe   = Module(new RefillPipe)
838  val missQueue    = Module(new MissQueue(edge))
839  val probeQueue   = Module(new ProbeQueue(edge))
840  val wb           = Module(new WritebackQueue(edge))
841
842  missQueue.io.lqEmpty := io.lqEmpty
843  missQueue.io.hartId := io.hartId
844  missQueue.io.l2_pf_store_only := RegNext(io.l2_pf_store_only, false.B)
845  missQueue.io.debugTopDown <> io.debugTopDown
846  io.memSetPattenDetected := missQueue.io.memSetPattenDetected
847
848  val errors = ldu.map(_.io.error) ++ // load error
849    Seq(mainPipe.io.error) // store / misc error
850  io.error <> RegNext(Mux1H(errors.map(e => RegNext(e.valid) -> RegNext(e))))
851
852  //----------------------------------------
853  // meta array
854
855  // read / write coh meta
856  val meta_read_ports = ldu.map(_.io.meta_read) ++
857    Seq(mainPipe.io.meta_read) ++
858    stu.map(_.io.meta_read)
859
860  val meta_resp_ports = ldu.map(_.io.meta_resp) ++
861    Seq(mainPipe.io.meta_resp) ++
862    stu.map(_.io.meta_resp)
863
864  val meta_write_ports = Seq(
865    mainPipe.io.meta_write,
866    refillPipe.io.meta_write
867  )
868  if(StorePrefetchL1Enabled) {
869    meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p }
870    meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r }
871  }else {
872    meta_read_ports.take(LoadPipelineWidth + 1).zip(metaArray.io.read).foreach { case (p, r) => r <> p }
873    meta_resp_ports.take(LoadPipelineWidth + 1).zip(metaArray.io.resp).foreach { case (p, r) => p := r }
874
875    meta_read_ports.drop(LoadPipelineWidth + 1).foreach { case p => p.ready := false.B }
876    meta_resp_ports.drop(LoadPipelineWidth + 1).foreach { case p => p := 0.U.asTypeOf(p) }
877  }
878  meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p }
879
880  // read extra meta (exclude stu)
881  meta_read_ports.take(LoadPipelineWidth + 1).zip(errorArray.io.read).foreach { case (p, r) => r <> p }
882  meta_read_ports.take(LoadPipelineWidth + 1).zip(prefetchArray.io.read).foreach { case (p, r) => r <> p }
883  meta_read_ports.take(LoadPipelineWidth + 1).zip(accessArray.io.read).foreach { case (p, r) => r <> p }
884  val extra_meta_resp_ports = ldu.map(_.io.extra_meta_resp) ++
885    Seq(mainPipe.io.extra_meta_resp)
886  extra_meta_resp_ports.zip(errorArray.io.resp).foreach { case (p, r) => {
887    (0 until nWays).map(i => { p(i).error := r(i) })
888  }}
889  extra_meta_resp_ports.zip(prefetchArray.io.resp).foreach { case (p, r) => {
890    (0 until nWays).map(i => { p(i).prefetch := r(i) })
891  }}
892  extra_meta_resp_ports.zip(accessArray.io.resp).foreach { case (p, r) => {
893    (0 until nWays).map(i => { p(i).access := r(i) })
894  }}
895
896  if(LoadPrefetchL1Enabled) {
897    // use last port to read prefetch and access flag
898    prefetchArray.io.read.last.valid := refillPipe.io.prefetch_flag_write.valid
899    prefetchArray.io.read.last.bits.idx := refillPipe.io.prefetch_flag_write.bits.idx
900    prefetchArray.io.read.last.bits.way_en := refillPipe.io.prefetch_flag_write.bits.way_en
901
902    accessArray.io.read.last.valid := refillPipe.io.prefetch_flag_write.valid
903    accessArray.io.read.last.bits.idx := refillPipe.io.prefetch_flag_write.bits.idx
904    accessArray.io.read.last.bits.way_en := refillPipe.io.prefetch_flag_write.bits.way_en
905
906    val extra_flag_valid = RegNext(refillPipe.io.prefetch_flag_write.valid)
907    val extra_flag_way_en = RegEnable(refillPipe.io.prefetch_flag_write.bits.way_en, refillPipe.io.prefetch_flag_write.valid)
908    val extra_flag_prefetch = Mux1H(extra_flag_way_en, prefetchArray.io.resp.last)
909    val extra_flag_access = Mux1H(extra_flag_way_en, accessArray.io.resp.last)
910
911    prefetcherMonitor.io.validity.good_prefetch := extra_flag_valid && isFromL1Prefetch(extra_flag_prefetch) && extra_flag_access
912    prefetcherMonitor.io.validity.bad_prefetch := extra_flag_valid && isFromL1Prefetch(extra_flag_prefetch) && !extra_flag_access
913  }
914
915  // write extra meta
916  val error_flag_write_ports = Seq(
917    mainPipe.io.error_flag_write, // error flag generated by corrupted store
918    refillPipe.io.error_flag_write // corrupted signal from l2
919  )
920  error_flag_write_ports.zip(errorArray.io.write).foreach { case (p, w) => w <> p }
921
922  val prefetch_flag_write_ports = ldu.map(_.io.prefetch_flag_write) ++ Seq(
923    mainPipe.io.prefetch_flag_write, // set prefetch_flag to false if coh is set to Nothing
924    refillPipe.io.prefetch_flag_write // refill required by prefetch will set prefetch_flag
925  )
926  prefetch_flag_write_ports.zip(prefetchArray.io.write).foreach { case (p, w) => w <> p }
927
928  val same_cycle_update_pf_flag = ldu(0).io.prefetch_flag_write.valid && ldu(1).io.prefetch_flag_write.valid && (ldu(0).io.prefetch_flag_write.bits.idx === ldu(1).io.prefetch_flag_write.bits.idx) && (ldu(0).io.prefetch_flag_write.bits.way_en === ldu(1).io.prefetch_flag_write.bits.way_en)
929  XSPerfAccumulate("same_cycle_update_pf_flag", same_cycle_update_pf_flag)
930
931  val access_flag_write_ports = ldu.map(_.io.access_flag_write) ++ Seq(
932    mainPipe.io.access_flag_write,
933    refillPipe.io.access_flag_write
934  )
935  access_flag_write_ports.zip(accessArray.io.write).foreach { case (p, w) => w <> p }
936
937  //----------------------------------------
938  // tag array
939  if(StorePrefetchL1Enabled) {
940    require(tagArray.io.read.size == (ldu.size + stu.size + 1))
941  }else {
942    require(tagArray.io.read.size == (ldu.size + 1))
943  }
944  val tag_write_intend = missQueue.io.refill_pipe_req.valid || mainPipe.io.tag_write_intend
945  assert(!RegNext(!tag_write_intend && tagArray.io.write.valid))
946  ldu.zipWithIndex.foreach {
947    case (ld, i) =>
948      tagArray.io.read(i) <> ld.io.tag_read
949      ld.io.tag_resp := tagArray.io.resp(i)
950      ld.io.tag_read.ready := !tag_write_intend
951  }
952  if(StorePrefetchL1Enabled) {
953    stu.zipWithIndex.foreach {
954      case (st, i) =>
955        tagArray.io.read(ldu.size + i) <> st.io.tag_read
956        st.io.tag_resp := tagArray.io.resp(ldu.size + i)
957        st.io.tag_read.ready := !tag_write_intend
958    }
959  }else {
960    stu.foreach {
961      case st =>
962        st.io.tag_read.ready := false.B
963        st.io.tag_resp := 0.U.asTypeOf(st.io.tag_resp)
964    }
965  }
966  tagArray.io.read.last <> mainPipe.io.tag_read
967  mainPipe.io.tag_resp := tagArray.io.resp.last
968
969  val fake_tag_read_conflict_this_cycle = PopCount(ldu.map(ld=> ld.io.tag_read.valid))
970  XSPerfAccumulate("fake_tag_read_conflict", fake_tag_read_conflict_this_cycle)
971
972  val tag_write_arb = Module(new Arbiter(new TagWriteReq, 2))
973  tag_write_arb.io.in(0) <> refillPipe.io.tag_write
974  tag_write_arb.io.in(1) <> mainPipe.io.tag_write
975  tagArray.io.write <> tag_write_arb.io.out
976
977  ldu.map(m => {
978    m.io.vtag_update.valid := tagArray.io.write.valid
979    m.io.vtag_update.bits := tagArray.io.write.bits
980  })
981
982  //----------------------------------------
983  // data array
984  mainPipe.io.data_read.zip(ldu).map(x => x._1 := x._2.io.lsu.req.valid)
985
986  val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 2))
987  dataWriteArb.io.in(0) <> refillPipe.io.data_write
988  dataWriteArb.io.in(1) <> mainPipe.io.data_write
989
990  bankedDataArray.io.write <> dataWriteArb.io.out
991
992  for (bank <- 0 until DCacheBanks) {
993    val dataWriteArb_dup = Module(new Arbiter(new L1BankedDataWriteReqCtrl, 2))
994    dataWriteArb_dup.io.in(0).valid := refillPipe.io.data_write_dup(bank).valid
995    dataWriteArb_dup.io.in(0).bits := refillPipe.io.data_write_dup(bank).bits
996    dataWriteArb_dup.io.in(1).valid := mainPipe.io.data_write_dup(bank).valid
997    dataWriteArb_dup.io.in(1).bits := mainPipe.io.data_write_dup(bank).bits
998
999    bankedDataArray.io.write_dup(bank) <> dataWriteArb_dup.io.out
1000  }
1001
1002  bankedDataArray.io.readline <> mainPipe.io.data_readline
1003  bankedDataArray.io.readline_intend := mainPipe.io.data_read_intend
1004  mainPipe.io.readline_error_delayed := bankedDataArray.io.readline_error_delayed
1005  mainPipe.io.data_resp := bankedDataArray.io.readline_resp
1006
1007  (0 until LoadPipelineWidth).map(i => {
1008    bankedDataArray.io.read(i) <> ldu(i).io.banked_data_read
1009    bankedDataArray.io.is128Req(i) <> ldu(i).io.is128Req
1010    bankedDataArray.io.read_error_delayed(i) <> ldu(i).io.read_error_delayed
1011
1012    ldu(i).io.banked_data_resp := bankedDataArray.io.read_resp_delayed(i)
1013
1014    ldu(i).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(i)
1015  })
1016
1017  (0 until LoadPipelineWidth).map(i => {
1018    val (_, _, done, _) = edge.count(bus.d)
1019    when(bus.d.bits.opcode === TLMessages.GrantData) {
1020      io.lsu.forward_D(i).apply(bus.d.valid, bus.d.bits.data, bus.d.bits.source, done)
1021    }.otherwise {
1022      io.lsu.forward_D(i).dontCare()
1023    }
1024  })
1025  // tl D channel wakeup
1026  val (_, _, done, _) = edge.count(bus.d)
1027  when (bus.d.bits.opcode === TLMessages.GrantData || bus.d.bits.opcode === TLMessages.Grant) {
1028    io.lsu.tl_d_channel.apply(bus.d.valid, bus.d.bits.data, bus.d.bits.source, done)
1029  } .otherwise {
1030    io.lsu.tl_d_channel.dontCare()
1031  }
1032  mainPipe.io.force_write <> io.force_write
1033
1034  /** dwpu */
1035  val dwpu = Module(new DCacheWpuWrapper(LoadPipelineWidth))
1036  for(i <- 0 until LoadPipelineWidth){
1037    dwpu.io.req(i) <> ldu(i).io.dwpu.req(0)
1038    dwpu.io.resp(i) <> ldu(i).io.dwpu.resp(0)
1039    dwpu.io.lookup_upd(i) <> ldu(i).io.dwpu.lookup_upd(0)
1040    dwpu.io.cfpred(i) <> ldu(i).io.dwpu.cfpred(0)
1041  }
1042  dwpu.io.tagwrite_upd.valid := tagArray.io.write.valid
1043  dwpu.io.tagwrite_upd.bits.vaddr := tagArray.io.write.bits.vaddr
1044  dwpu.io.tagwrite_upd.bits.s1_real_way_en := tagArray.io.write.bits.way_en
1045
1046  //----------------------------------------
1047  // load pipe
1048  // the s1 kill signal
1049  // only lsu uses this, replay never kills
1050  for (w <- 0 until LoadPipelineWidth) {
1051    ldu(w).io.lsu <> io.lsu.load(w)
1052
1053    // TODO:when have load128Req
1054    ldu(w).io.load128Req := false.B
1055
1056    // replay and nack not needed anymore
1057    // TODO: remove replay and nack
1058    ldu(w).io.nack := false.B
1059
1060    ldu(w).io.disable_ld_fast_wakeup :=
1061      bankedDataArray.io.disable_ld_fast_wakeup(w) // load pipe fast wake up should be disabled when bank conflict
1062  }
1063
1064  prefetcherMonitor.io.timely.total_prefetch := ldu.map(_.io.prefetch_info.naive.total_prefetch).reduce(_ || _)
1065  prefetcherMonitor.io.timely.late_hit_prefetch := ldu.map(_.io.prefetch_info.naive.late_hit_prefetch).reduce(_ || _)
1066  prefetcherMonitor.io.timely.late_miss_prefetch := missQueue.io.prefetch_info.naive.late_miss_prefetch
1067  prefetcherMonitor.io.timely.prefetch_hit := PopCount(ldu.map(_.io.prefetch_info.naive.prefetch_hit))
1068  io.pf_ctrl <> prefetcherMonitor.io.pf_ctrl
1069  XSPerfAccumulate("useless_prefetch", ldu.map(_.io.prefetch_info.naive.total_prefetch).reduce(_ || _) && !(ldu.map(_.io.prefetch_info.naive.useful_prefetch).reduce(_ || _)))
1070  XSPerfAccumulate("useful_prefetch", ldu.map(_.io.prefetch_info.naive.useful_prefetch).reduce(_ || _))
1071  XSPerfAccumulate("late_prefetch_hit", ldu.map(_.io.prefetch_info.naive.late_prefetch_hit).reduce(_ || _))
1072  XSPerfAccumulate("late_load_hit", ldu.map(_.io.prefetch_info.naive.late_load_hit).reduce(_ || _))
1073
1074  /** LoadMissDB: record load miss state */
1075  val isWriteLoadMissTable = WireInit(Constantin.createRecord("isWriteLoadMissTable" + p(XSCoreParamsKey).HartId.toString))
1076  val isFirstHitWrite = WireInit(Constantin.createRecord("isFirstHitWrite" + p(XSCoreParamsKey).HartId.toString))
1077  val tableName = "LoadMissDB" + p(XSCoreParamsKey).HartId.toString
1078  val siteName = "DcacheWrapper" + p(XSCoreParamsKey).HartId.toString
1079  val loadMissTable = ChiselDB.createTable(tableName, new LoadMissEntry)
1080  for( i <- 0 until LoadPipelineWidth){
1081    val loadMissEntry = Wire(new LoadMissEntry)
1082    val loadMissWriteEn =
1083      (!ldu(i).io.lsu.resp.bits.replay && ldu(i).io.miss_req.fire) ||
1084      (ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid && isFirstHitWrite.orR)
1085    loadMissEntry.timeCnt := GTimer()
1086    loadMissEntry.robIdx := ldu(i).io.lsu.resp.bits.debug_robIdx
1087    loadMissEntry.paddr := ldu(i).io.miss_req.bits.addr
1088    loadMissEntry.vaddr := ldu(i).io.miss_req.bits.vaddr
1089    loadMissEntry.missState := OHToUInt(Cat(Seq(
1090      ldu(i).io.miss_req.fire & ldu(i).io.miss_resp.merged,
1091      ldu(i).io.miss_req.fire & !ldu(i).io.miss_resp.merged,
1092      ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid
1093    )))
1094    loadMissTable.log(
1095      data = loadMissEntry,
1096      en = isWriteLoadMissTable.orR && loadMissWriteEn,
1097      site = siteName,
1098      clock = clock,
1099      reset = reset
1100    )
1101  }
1102
1103  val isWriteLoadAccessTable = WireInit(Constantin.createRecord("isWriteLoadAccessTable" + p(XSCoreParamsKey).HartId.toString))
1104  val loadAccessTable = ChiselDB.createTable("LoadAccessDB" + p(XSCoreParamsKey).HartId.toString, new LoadAccessEntry)
1105  for (i <- 0 until LoadPipelineWidth) {
1106    val loadAccessEntry = Wire(new LoadAccessEntry)
1107    loadAccessEntry.timeCnt := GTimer()
1108    loadAccessEntry.robIdx := ldu(i).io.lsu.resp.bits.debug_robIdx
1109    loadAccessEntry.paddr := ldu(i).io.miss_req.bits.addr
1110    loadAccessEntry.vaddr := ldu(i).io.miss_req.bits.vaddr
1111    loadAccessEntry.missState := OHToUInt(Cat(Seq(
1112      ldu(i).io.miss_req.fire & ldu(i).io.miss_resp.merged,
1113      ldu(i).io.miss_req.fire & !ldu(i).io.miss_resp.merged,
1114      ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid
1115    )))
1116    loadAccessEntry.pred_way_num := ldu(i).io.lsu.debug_s2_pred_way_num
1117    loadAccessEntry.real_way_num := ldu(i).io.lsu.debug_s2_real_way_num
1118    loadAccessEntry.dm_way_num := ldu(i).io.lsu.debug_s2_dm_way_num
1119    loadAccessTable.log(
1120      data = loadAccessEntry,
1121      en = isWriteLoadAccessTable.orR && ldu(i).io.lsu.resp.valid,
1122      site = siteName + "_loadpipe" + i.toString,
1123      clock = clock,
1124      reset = reset
1125    )
1126  }
1127
1128  //----------------------------------------
1129  // Sta pipe
1130  for (w <- 0 until StorePipelineWidth) {
1131    stu(w).io.lsu <> io.lsu.sta(w)
1132  }
1133
1134  //----------------------------------------
1135  // atomics
1136  // atomics not finished yet
1137  // io.lsu.atomics <> atomicsReplayUnit.io.lsu
1138  io.lsu.atomics.resp := RegNext(mainPipe.io.atomic_resp)
1139  io.lsu.atomics.block_lr := mainPipe.io.block_lr
1140  // atomicsReplayUnit.io.pipe_resp := RegNext(mainPipe.io.atomic_resp)
1141  // atomicsReplayUnit.io.block_lr <> mainPipe.io.block_lr
1142
1143  //----------------------------------------
1144  // miss queue
1145  // missReqArb port:
1146  // enableStorePrefetch: main pipe * 1 + load pipe * 2 + store pipe * 2; disable: main pipe * 1 + load pipe * 2
1147  // higher priority is given to lower indices
1148  val MissReqPortCount = if(StorePrefetchL1Enabled) LoadPipelineWidth + 1 + StorePipelineWidth else LoadPipelineWidth + 1
1149  val MainPipeMissReqPort = 0
1150
1151  // Request
1152  val missReqArb = Module(new ArbiterFilterByCacheLineAddr(new MissReq, MissReqPortCount, blockOffBits, PAddrBits))
1153
1154  missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req
1155  for (w <- 0 until LoadPipelineWidth)  { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req }
1156
1157  for (w <- 0 until LoadPipelineWidth) { ldu(w).io.miss_resp := missQueue.io.resp }
1158  mainPipe.io.miss_resp := missQueue.io.resp
1159
1160  if(StorePrefetchL1Enabled) {
1161    for (w <- 0 until StorePipelineWidth) { missReqArb.io.in(w + 1 + LoadPipelineWidth) <> stu(w).io.miss_req }
1162  }else {
1163    for (w <- 0 until StorePipelineWidth) { stu(w).io.miss_req.ready := false.B }
1164  }
1165
1166  wb.io.miss_req.valid := missReqArb.io.out.valid
1167  wb.io.miss_req.bits  := missReqArb.io.out.bits.addr
1168
1169  // block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req)
1170  missReqArb.io.out <> missQueue.io.req
1171  when(wb.io.block_miss_req) {
1172    missQueue.io.req.bits.cancel := true.B
1173    missReqArb.io.out.ready := false.B
1174  }
1175
1176  for (w <- 0 until LoadPipelineWidth) { ldu(w).io.mq_enq_cancel := missQueue.io.mq_enq_cancel }
1177
1178  XSPerfAccumulate("miss_queue_fire", PopCount(VecInit(missReqArb.io.in.map(_.fire))) >= 1.U)
1179  XSPerfAccumulate("miss_queue_muti_fire", PopCount(VecInit(missReqArb.io.in.map(_.fire))) > 1.U)
1180
1181  XSPerfAccumulate("miss_queue_has_enq_req", PopCount(VecInit(missReqArb.io.in.map(_.valid))) >= 1.U)
1182  XSPerfAccumulate("miss_queue_has_muti_enq_req", PopCount(VecInit(missReqArb.io.in.map(_.valid))) > 1.U)
1183  XSPerfAccumulate("miss_queue_has_muti_enq_but_not_fire", PopCount(VecInit(missReqArb.io.in.map(_.valid))) > 1.U && PopCount(VecInit(missReqArb.io.in.map(_.fire))) === 0.U)
1184
1185  // forward missqueue
1186  (0 until LoadPipelineWidth).map(i => io.lsu.forward_mshr(i).connect(missQueue.io.forward(i)))
1187
1188  // refill to load queue
1189  io.lsu.lsq <> missQueue.io.refill_to_ldq
1190
1191  // tilelink stuff
1192  bus.a <> missQueue.io.mem_acquire
1193  bus.e <> missQueue.io.mem_finish
1194  missQueue.io.probe_addr := bus.b.bits.address
1195
1196  missQueue.io.main_pipe_resp := RegNext(mainPipe.io.atomic_resp)
1197
1198  //----------------------------------------
1199  // probe
1200  // probeQueue.io.mem_probe <> bus.b
1201  block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block)
1202  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
1203  probeQueue.io.update_resv_set <> mainPipe.io.update_resv_set
1204
1205  //----------------------------------------
1206  // mainPipe
1207  // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe,
1208  // block the req in main pipe
1209  block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, missQueue.io.refill_pipe_req.valid)
1210  block_decoupled(io.lsu.store.req, mainPipe.io.store_req, refillPipe.io.req.valid)
1211
1212  io.lsu.store.replay_resp := RegNext(mainPipe.io.store_replay_resp)
1213  io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp
1214
1215  arbiter_with_pipereg(
1216    in = Seq(missQueue.io.main_pipe_req, io.lsu.atomics.req),
1217    out = mainPipe.io.atomic_req,
1218    name = Some("main_pipe_atomic_req")
1219  )
1220
1221  mainPipe.io.invalid_resv_set := RegNext(wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits)
1222
1223  //----------------------------------------
1224  // replace (main pipe)
1225  val mpStatus = mainPipe.io.status
1226  mainPipe.io.replace_req <> missQueue.io.replace_pipe_req
1227  missQueue.io.replace_pipe_resp := mainPipe.io.replace_resp
1228
1229  //----------------------------------------
1230  // refill pipe
1231  val refillShouldBeBlocked = (mpStatus.s1.valid && mpStatus.s1.bits.set === missQueue.io.refill_pipe_req.bits.idx) ||
1232    Cat(Seq(mpStatus.s2, mpStatus.s3).map(s =>
1233      s.valid &&
1234        s.bits.set === missQueue.io.refill_pipe_req.bits.idx &&
1235        s.bits.way_en === missQueue.io.refill_pipe_req.bits.way_en
1236    )).orR
1237  block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked)
1238
1239  val mpStatus_dup = mainPipe.io.status_dup
1240  val mq_refill_dup = missQueue.io.refill_pipe_req_dup
1241  val refillShouldBeBlocked_dup = VecInit((0 until nDupStatus).map { case i =>
1242    mpStatus_dup(i).s1.valid && mpStatus_dup(i).s1.bits.set === mq_refill_dup(i).bits.idx ||
1243    Cat(Seq(mpStatus_dup(i).s2, mpStatus_dup(i).s3).map(s =>
1244      s.valid &&
1245        s.bits.set === mq_refill_dup(i).bits.idx &&
1246        s.bits.way_en === mq_refill_dup(i).bits.way_en
1247    )).orR
1248  })
1249  dontTouch(refillShouldBeBlocked_dup)
1250
1251  refillPipe.io.req_dup_for_data_w.zipWithIndex.foreach { case (r, i) =>
1252    r.bits := (mq_refill_dup.drop(dataWritePort).take(DCacheBanks))(i).bits
1253  }
1254  refillPipe.io.req_dup_for_meta_w.bits := mq_refill_dup(metaWritePort).bits
1255  refillPipe.io.req_dup_for_tag_w.bits := mq_refill_dup(tagWritePort).bits
1256  refillPipe.io.req_dup_for_err_w.bits := mq_refill_dup(errWritePort).bits
1257  refillPipe.io.req_dup_for_data_w.zipWithIndex.foreach { case (r, i) =>
1258    r.valid := (mq_refill_dup.drop(dataWritePort).take(DCacheBanks))(i).valid &&
1259      !(refillShouldBeBlocked_dup.drop(dataWritePort).take(DCacheBanks))(i)
1260  }
1261  refillPipe.io.req_dup_for_meta_w.valid := mq_refill_dup(metaWritePort).valid && !refillShouldBeBlocked_dup(metaWritePort)
1262  refillPipe.io.req_dup_for_tag_w.valid := mq_refill_dup(tagWritePort).valid && !refillShouldBeBlocked_dup(tagWritePort)
1263  refillPipe.io.req_dup_for_err_w.valid := mq_refill_dup(errWritePort).valid && !refillShouldBeBlocked_dup(errWritePort)
1264
1265  val refillPipe_io_req_valid_dup = VecInit(mq_refill_dup.zip(refillShouldBeBlocked_dup).map(
1266    x => x._1.valid && !x._2
1267  ))
1268  val refillPipe_io_data_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(0, nDupDataWriteReady))
1269  val refillPipe_io_tag_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(nDupDataWriteReady, nDupStatus))
1270  dontTouch(refillPipe_io_req_valid_dup)
1271  dontTouch(refillPipe_io_data_write_valid_dup)
1272  dontTouch(refillPipe_io_tag_write_valid_dup)
1273  mainPipe.io.data_write_ready_dup := VecInit(refillPipe_io_data_write_valid_dup.map(v => !v))
1274  mainPipe.io.tag_write_ready_dup := VecInit(refillPipe_io_tag_write_valid_dup.map(v => !v))
1275  mainPipe.io.wb_ready_dup := wb.io.req_ready_dup
1276
1277  mq_refill_dup.zip(refillShouldBeBlocked_dup).foreach { case (r, block) =>
1278    r.ready := refillPipe.io.req.ready && !block
1279  }
1280
1281  missQueue.io.refill_pipe_resp := refillPipe.io.resp
1282  io.lsu.store.refill_hit_resp := RegNext(refillPipe.io.store_resp)
1283
1284  //----------------------------------------
1285  // wb
1286  // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy
1287
1288  wb.io.req <> mainPipe.io.wb
1289  bus.c     <> wb.io.mem_release
1290  wb.io.release_wakeup := refillPipe.io.release_wakeup
1291  wb.io.release_update := mainPipe.io.release_update
1292  wb.io.probe_ttob_check_req <> mainPipe.io.probe_ttob_check_req
1293  wb.io.probe_ttob_check_resp <> mainPipe.io.probe_ttob_check_resp
1294
1295  io.lsu.release.valid := RegNext(wb.io.req.fire)
1296  io.lsu.release.bits.paddr := RegNext(wb.io.req.bits.addr)
1297  // Note: RegNext() is required by:
1298  // * load queue released flag update logic
1299  // * load / load violation check logic
1300  // * and timing requirements
1301  // CHANGE IT WITH CARE
1302
1303  // connect bus d
1304  missQueue.io.mem_grant.valid := false.B
1305  missQueue.io.mem_grant.bits  := DontCare
1306
1307  wb.io.mem_grant.valid := false.B
1308  wb.io.mem_grant.bits  := DontCare
1309
1310  // in L1DCache, we ony expect Grant[Data] and ReleaseAck
1311  bus.d.ready := false.B
1312  when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) {
1313    missQueue.io.mem_grant <> bus.d
1314  } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) {
1315    wb.io.mem_grant <> bus.d
1316  } .otherwise {
1317    assert (!bus.d.fire)
1318  }
1319
1320  //----------------------------------------
1321  // Feedback Direct Prefetch Monitor
1322  fdpMonitor.io.refill := missQueue.io.prefetch_info.fdp.prefetch_monitor_cnt
1323  fdpMonitor.io.timely.late_prefetch := missQueue.io.prefetch_info.fdp.late_miss_prefetch
1324  fdpMonitor.io.accuracy.total_prefetch := missQueue.io.prefetch_info.fdp.total_prefetch
1325  for (w <- 0 until LoadPipelineWidth)  {
1326    if(w == 0) {
1327      fdpMonitor.io.accuracy.useful_prefetch(w) := ldu(w).io.prefetch_info.fdp.useful_prefetch
1328    }else {
1329      fdpMonitor.io.accuracy.useful_prefetch(w) := Mux(same_cycle_update_pf_flag, false.B, ldu(w).io.prefetch_info.fdp.useful_prefetch)
1330    }
1331  }
1332  for (w <- 0 until LoadPipelineWidth)  { fdpMonitor.io.pollution.cache_pollution(w) :=  ldu(w).io.prefetch_info.fdp.pollution }
1333  for (w <- 0 until LoadPipelineWidth)  { fdpMonitor.io.pollution.demand_miss(w) :=  ldu(w).io.prefetch_info.fdp.demand_miss }
1334  fdpMonitor.io.debugRolling := io.debugRolling
1335
1336  //----------------------------------------
1337  // Bloom Filter
1338  bloomFilter.io.set <> missQueue.io.bloom_filter_query.set
1339  bloomFilter.io.clr <> missQueue.io.bloom_filter_query.clr
1340
1341  for (w <- 0 until LoadPipelineWidth)  { bloomFilter.io.query(w) <> ldu(w).io.bloom_filter_query.query }
1342  for (w <- 0 until LoadPipelineWidth)  { bloomFilter.io.resp(w) <> ldu(w).io.bloom_filter_query.resp }
1343
1344  for (w <- 0 until LoadPipelineWidth)  { counterFilter.io.ld_in(w) <> ldu(w).io.counter_filter_enq }
1345  for (w <- 0 until LoadPipelineWidth)  { counterFilter.io.query(w) <> ldu(w).io.counter_filter_query }
1346
1347  //----------------------------------------
1348  // replacement algorithm
1349  val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets)
1350  val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way) ++ stu.map(_.io.replace_way)
1351
1352  val victimList = VictimList(nSets)
1353  if (dwpuParam.enCfPred) {
1354    when(missQueue.io.replace_pipe_req.valid) {
1355      victimList.replace(get_idx(missQueue.io.replace_pipe_req.bits.vaddr))
1356    }
1357    replWayReqs.foreach {
1358      case req =>
1359        req.way := DontCare
1360        when(req.set.valid) {
1361          when(victimList.whether_sa(req.set.bits)) {
1362            req.way := replacer.way(req.set.bits)
1363          }.otherwise {
1364            req.way := req.dmWay
1365          }
1366        }
1367    }
1368  } else {
1369    replWayReqs.foreach {
1370      case req =>
1371        req.way := DontCare
1372        when(req.set.valid) {
1373          req.way := replacer.way(req.set.bits)
1374        }
1375    }
1376  }
1377
1378  val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq(
1379    mainPipe.io.replace_access
1380  ) ++ stu.map(_.io.replace_access)
1381  val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W))))
1382  touchWays.zip(replAccessReqs).foreach {
1383    case (w, req) =>
1384      w.valid := req.valid
1385      w.bits := req.bits.way
1386  }
1387  val touchSets = replAccessReqs.map(_.bits.set)
1388  replacer.access(touchSets, touchWays)
1389
1390  //----------------------------------------
1391  // assertions
1392  // dcache should only deal with DRAM addresses
1393  when (bus.a.fire) {
1394    assert(bus.a.bits.address >= 0x80000000L.U)
1395  }
1396  when (bus.b.fire) {
1397    assert(bus.b.bits.address >= 0x80000000L.U)
1398  }
1399  when (bus.c.fire) {
1400    assert(bus.c.bits.address >= 0x80000000L.U)
1401  }
1402
1403  //----------------------------------------
1404  // utility functions
1405  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
1406    sink.valid   := source.valid && !block_signal
1407    source.ready := sink.ready   && !block_signal
1408    sink.bits    := source.bits
1409  }
1410
1411  //----------------------------------------
1412  // Customized csr cache op support
1413  val cacheOpDecoder = Module(new CSRCacheOpDecoder("dcache", CacheInstrucion.COP_ID_DCACHE))
1414  cacheOpDecoder.io.csr <> io.csr
1415  bankedDataArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
1416  // dup cacheOp_req_valid
1417  bankedDataArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) }
1418  // dup cacheOp_req_bits_opCode
1419  bankedDataArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) }
1420
1421  tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
1422  // dup cacheOp_req_valid
1423  tagArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) }
1424  // dup cacheOp_req_bits_opCode
1425  tagArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) }
1426
1427  cacheOpDecoder.io.cache.resp.valid := bankedDataArray.io.cacheOp.resp.valid ||
1428    tagArray.io.cacheOp.resp.valid
1429  cacheOpDecoder.io.cache.resp.bits := Mux1H(List(
1430    bankedDataArray.io.cacheOp.resp.valid -> bankedDataArray.io.cacheOp.resp.bits,
1431    tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits,
1432  ))
1433  cacheOpDecoder.io.error := io.error
1434  assert(!((bankedDataArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U))
1435
1436  //----------------------------------------
1437  // performance counters
1438  val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire))
1439  XSPerfAccumulate("num_loads", num_loads)
1440
1441  io.mshrFull := missQueue.io.full
1442
1443  // performance counter
1444  val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType))
1445  val st_access = Wire(ld_access.last.cloneType)
1446  ld_access.zip(ldu).foreach {
1447    case (a, u) =>
1448      a.valid := RegNext(u.io.lsu.req.fire) && !u.io.lsu.s1_kill
1449      a.bits.idx := RegNext(get_idx(u.io.lsu.req.bits.vaddr))
1450      a.bits.tag := get_tag(u.io.lsu.s1_paddr_dup_dcache)
1451  }
1452  st_access.valid := RegNext(mainPipe.io.store_req.fire)
1453  st_access.bits.idx := RegNext(get_idx(mainPipe.io.store_req.bits.vaddr))
1454  st_access.bits.tag := RegNext(get_tag(mainPipe.io.store_req.bits.addr))
1455  val access_info = ld_access.toSeq ++ Seq(st_access)
1456  val early_replace = RegNext(missQueue.io.debug_early_replace)
1457  val access_early_replace = access_info.map {
1458    case acc =>
1459      Cat(early_replace.map {
1460        case r =>
1461          acc.valid && r.valid &&
1462            acc.bits.tag === r.bits.tag &&
1463            acc.bits.idx === r.bits.idx
1464      })
1465  }
1466  XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace)))
1467
1468  val perfEvents = (Seq(wb, mainPipe, missQueue, probeQueue) ++ ldu).flatMap(_.getPerfEvents)
1469  generatePerfEvent()
1470}
1471
1472class AMOHelper() extends ExtModule {
1473  val clock  = IO(Input(Clock()))
1474  val enable = IO(Input(Bool()))
1475  val cmd    = IO(Input(UInt(5.W)))
1476  val addr   = IO(Input(UInt(64.W)))
1477  val wdata  = IO(Input(UInt(64.W)))
1478  val mask   = IO(Input(UInt(8.W)))
1479  val rdata  = IO(Output(UInt(64.W)))
1480}
1481
1482class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
1483  override def shouldBeInlined: Boolean = false
1484
1485  val useDcache = coreParams.dcacheParametersOpt.nonEmpty
1486  val clientNode = if (useDcache) TLIdentityNode() else null
1487  val dcache = if (useDcache) LazyModule(new DCache()) else null
1488  if (useDcache) {
1489    clientNode := dcache.clientNode
1490  }
1491
1492  class DCacheWrapperImp(wrapper: LazyModule) extends LazyModuleImp(wrapper) with HasPerfEvents {
1493    val io = IO(new DCacheIO)
1494    val perfEvents = if (!useDcache) {
1495      // a fake dcache which uses dpi-c to access memory, only for debug usage!
1496      val fake_dcache = Module(new FakeDCache())
1497      io <> fake_dcache.io
1498      Seq()
1499    }
1500    else {
1501      io <> dcache.module.io
1502      dcache.module.getPerfEvents
1503    }
1504    generatePerfEvent()
1505  }
1506
1507  lazy val module = new DCacheWrapperImp(this)
1508}
1509