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