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