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