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