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