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