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