xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/DCacheWrapper.scala (revision b9e121dff513e733e443a16e49648e82b9583af6)
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, AliasKey, DirtyField, PrefetchField}
31import utility.FastArbiter
32import mem.{AddPipelineReg}
33import xiangshan.cache.dcache.ReplayCarry
34
35import scala.math.max
36
37// DCache specific parameters
38case class DCacheParameters
39(
40  nSets: Int = 256,
41  nWays: Int = 8,
42  rowBits: Int = 64,
43  tagECC: Option[String] = None,
44  dataECC: Option[String] = None,
45  replacer: Option[String] = Some("setplru"),
46  updateReplaceOn2ndmiss: Boolean = true,
47  nMissEntries: Int = 1,
48  nProbeEntries: Int = 1,
49  nReleaseEntries: Int = 1,
50  nMMIOEntries: Int = 1,
51  nMMIOs: Int = 1,
52  blockBytes: Int = 64,
53  alwaysReleaseData: Boolean = false
54) extends L1CacheParameters {
55  // if sets * blockBytes > 4KB(page size),
56  // cache alias will happen,
57  // we need to avoid this by recoding additional bits in L2 cache
58  val setBytes = nSets * blockBytes
59  val aliasBitsOpt = if(setBytes > pageSize) Some(log2Ceil(setBytes / pageSize)) else None
60  val reqFields: Seq[BundleFieldBase] = Seq(
61    PrefetchField()
62  ) ++ aliasBitsOpt.map(AliasField)
63  val echoFields: Seq[BundleFieldBase] = Nil
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 {
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  def HW_PREFETCH_AGT = 5
113  def HW_PREFETCH_PHT_CUR = 6
114  def HW_PREFETCH_PHT_INC = 7
115  def HW_PREFETCH_PHT_DEC = 8
116  def HW_PREFETCH_BOP = 9
117  def HW_PREFETCH_STRIDE = 10
118
119  // each source use a id to distinguish its multiple reqs
120  def reqIdWidth = log2Up(nEntries) max log2Up(StoreBufferSize)
121
122  require(isPow2(cfg.nMissEntries)) // TODO
123  // require(isPow2(cfg.nReleaseEntries))
124  require(cfg.nMissEntries < cfg.nReleaseEntries)
125  val nEntries = cfg.nMissEntries + cfg.nReleaseEntries
126  val releaseIdBase = cfg.nMissEntries
127
128  // banked dcache support
129  val DCacheSets = cacheParams.nSets
130  val DCacheWays = cacheParams.nWays
131  val DCacheBanks = 8 // hardcoded
132  val DCacheDupNum = 16
133  val DCacheSRAMRowBits = cacheParams.rowBits // hardcoded
134  val DCacheWordBits = 64 // hardcoded
135  val DCacheWordBytes = DCacheWordBits / 8
136  require(DCacheSRAMRowBits == 64)
137
138  val DCacheSizeBits = DCacheSRAMRowBits * DCacheBanks * DCacheWays * DCacheSets
139  val DCacheSizeBytes = DCacheSizeBits / 8
140  val DCacheSizeWords = DCacheSizeBits / 64 // TODO
141
142  val DCacheSameVPAddrLength = 12
143
144  val DCacheSRAMRowBytes = DCacheSRAMRowBits / 8
145  val DCacheWordOffset = log2Up(DCacheWordBytes)
146
147  val DCacheBankOffset = log2Up(DCacheSRAMRowBytes)
148  val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks)
149  val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets)
150  val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength
151  val DCacheLineOffset = DCacheSetOffset
152
153  // uncache
154  val uncacheIdxBits = log2Up(StoreQueueSize + 1) max log2Up(VirtualLoadQueueSize + 1)
155  // hardware prefetch parameters
156  // high confidence hardware prefetch port
157  val HighConfHWPFLoadPort = LoadPipelineWidth - 1 // use the last load port by default
158  val IgnorePrefetchConfidence = false
159
160  // parameters about duplicating regs to solve fanout
161  // In Main Pipe:
162    // tag_write.ready -> data_write.valid * 8 banks
163    // tag_write.ready -> meta_write.valid
164    // tag_write.ready -> tag_write.valid
165    // tag_write.ready -> err_write.valid
166    // tag_write.ready -> wb.valid
167  val nDupTagWriteReady = DCacheBanks + 4
168  // In Main Pipe:
169    // data_write.ready -> data_write.valid * 8 banks
170    // data_write.ready -> meta_write.valid
171    // data_write.ready -> tag_write.valid
172    // data_write.ready -> err_write.valid
173    // data_write.ready -> wb.valid
174  val nDupDataWriteReady = DCacheBanks + 4
175  val nDupWbReady = DCacheBanks + 4
176  val nDupStatus = nDupTagWriteReady + nDupDataWriteReady
177  val dataWritePort = 0
178  val metaWritePort = DCacheBanks
179  val tagWritePort = metaWritePort + 1
180  val errWritePort = tagWritePort + 1
181  val wbPort = errWritePort + 1
182
183  def addr_to_dcache_bank(addr: UInt) = {
184    require(addr.getWidth >= DCacheSetOffset)
185    addr(DCacheSetOffset-1, DCacheBankOffset)
186  }
187
188  def addr_to_dcache_set(addr: UInt) = {
189    require(addr.getWidth >= DCacheAboveIndexOffset)
190    addr(DCacheAboveIndexOffset-1, DCacheSetOffset)
191  }
192
193  def get_data_of_bank(bank: Int, data: UInt) = {
194    require(data.getWidth >= (bank+1)*DCacheSRAMRowBits)
195    data(DCacheSRAMRowBits * (bank + 1) - 1, DCacheSRAMRowBits * bank)
196  }
197
198  def get_mask_of_bank(bank: Int, data: UInt) = {
199    require(data.getWidth >= (bank+1)*DCacheSRAMRowBytes)
200    data(DCacheSRAMRowBytes * (bank + 1) - 1, DCacheSRAMRowBytes * bank)
201  }
202
203  def arbiter[T <: Bundle](
204    in: Seq[DecoupledIO[T]],
205    out: DecoupledIO[T],
206    name: Option[String] = None): Unit = {
207    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
208    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
209    for ((a, req) <- arb.io.in.zip(in)) {
210      a <> req
211    }
212    out <> arb.io.out
213  }
214
215  def arbiter_with_pipereg[T <: Bundle](
216    in: Seq[DecoupledIO[T]],
217    out: DecoupledIO[T],
218    name: Option[String] = None): Unit = {
219    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
220    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
221    for ((a, req) <- arb.io.in.zip(in)) {
222      a <> req
223    }
224    AddPipelineReg(arb.io.out, out, false.B)
225  }
226
227  def arbiter_with_pipereg_N_dup[T <: Bundle](
228    in: Seq[DecoupledIO[T]],
229    out: DecoupledIO[T],
230    dups: Seq[DecoupledIO[T]],
231    name: Option[String] = None): Unit = {
232    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
233    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
234    for ((a, req) <- arb.io.in.zip(in)) {
235      a <> req
236    }
237    for (dup <- dups) {
238      AddPipelineReg(arb.io.out, dup, false.B)
239    }
240    AddPipelineReg(arb.io.out, out, false.B)
241  }
242
243  def rrArbiter[T <: Bundle](
244    in: Seq[DecoupledIO[T]],
245    out: DecoupledIO[T],
246    name: Option[String] = None): Unit = {
247    val arb = Module(new RRArbiter[T](chiselTypeOf(out.bits), in.size))
248    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
249    for ((a, req) <- arb.io.in.zip(in)) {
250      a <> req
251    }
252    out <> arb.io.out
253  }
254
255  def fastArbiter[T <: Bundle](
256    in: Seq[DecoupledIO[T]],
257    out: DecoupledIO[T],
258    name: Option[String] = None): Unit = {
259    val arb = Module(new FastArbiter[T](chiselTypeOf(out.bits), in.size))
260    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
261    for ((a, req) <- arb.io.in.zip(in)) {
262      a <> req
263    }
264    out <> arb.io.out
265  }
266
267  val numReplaceRespPorts = 2
268
269  require(isPow2(nSets), s"nSets($nSets) must be pow2")
270  require(isPow2(nWays), s"nWays($nWays) must be pow2")
271  require(full_divide(rowBits, wordBits), s"rowBits($rowBits) must be multiple of wordBits($wordBits)")
272  require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)")
273}
274
275abstract class DCacheModule(implicit p: Parameters) extends L1CacheModule
276  with HasDCacheParameters
277
278abstract class DCacheBundle(implicit p: Parameters) extends L1CacheBundle
279  with HasDCacheParameters
280
281class ReplacementAccessBundle(implicit p: Parameters) extends DCacheBundle {
282  val set = UInt(log2Up(nSets).W)
283  val way = UInt(log2Up(nWays).W)
284}
285
286class ReplacementWayReqIO(implicit p: Parameters) extends DCacheBundle {
287  val set = ValidIO(UInt(log2Up(nSets).W))
288  val way = Input(UInt(log2Up(nWays).W))
289}
290
291class DCacheExtraMeta(implicit p: Parameters) extends DCacheBundle
292{
293  val error = Bool() // cache line has been marked as corrupted by l2 / ecc error detected when store
294  val prefetch = Bool() // cache line is first required by prefetch
295  val access = Bool() // cache line has been accessed by load / store
296
297  // val debug_access_timestamp = UInt(64.W) // last time a load / store / refill access that cacheline
298}
299
300// memory request in word granularity(load, mmio, lr/sc, atomics)
301class DCacheWordReq(implicit p: Parameters)  extends DCacheBundle
302{
303  val cmd    = UInt(M_SZ.W)
304  val addr   = UInt(PAddrBits.W)
305  val data   = UInt(DataBits.W)
306  val mask   = UInt((DataBits/8).W)
307  val id     = UInt(reqIdWidth.W)
308  val instrtype   = UInt(sourceTypeWidth.W)
309  val isFirstIssue = Bool()
310  val replayCarry = new ReplayCarry
311
312  val debug_robIdx = UInt(log2Ceil(RobSize).W)
313  def dump() = {
314    XSDebug("DCacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
315      cmd, addr, data, mask, id)
316  }
317}
318
319// memory request in word granularity(store)
320class DCacheLineReq(implicit p: Parameters)  extends DCacheBundle
321{
322  val cmd    = UInt(M_SZ.W)
323  val vaddr  = UInt(VAddrBits.W)
324  val addr   = UInt(PAddrBits.W)
325  val data   = UInt((cfg.blockBytes * 8).W)
326  val mask   = UInt(cfg.blockBytes.W)
327  val id     = UInt(reqIdWidth.W)
328  def dump() = {
329    XSDebug("DCacheLineReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
330      cmd, addr, data, mask, id)
331  }
332  def idx: UInt = get_idx(vaddr)
333}
334
335class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq {
336  val vaddr = UInt(VAddrBits.W)
337  val wline = Bool()
338}
339
340class BaseDCacheWordResp(implicit p: Parameters) extends DCacheBundle
341{
342  // read in s2
343  val data = UInt(DataBits.W)
344  // select in s3
345  val data_delayed = UInt(DataBits.W)
346  val id     = UInt(reqIdWidth.W)
347  // cache req missed, send it to miss queue
348  val miss   = Bool()
349  // cache miss, and failed to enter the missqueue, replay from RS is needed
350  val replay = Bool()
351  val replayCarry = new ReplayCarry
352  // data has been corrupted
353  val tag_error = Bool() // tag error
354  val mshr_id = UInt(log2Up(cfg.nMissEntries).W)
355
356  val debug_robIdx = UInt(log2Ceil(RobSize).W)
357  def dump() = {
358    XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n",
359      data, id, miss, replay)
360  }
361}
362
363class DCacheWordResp(implicit p: Parameters) extends BaseDCacheWordResp
364{
365  val meta_prefetch = Bool()
366  val meta_access = Bool()
367  // s2
368  val handled = Bool()
369  // s3: 1 cycle after data resp
370  val error_delayed = Bool() // all kinds of errors, include tag error
371  val replacementUpdated = Bool()
372}
373
374class BankedDCacheWordResp(implicit p: Parameters) extends DCacheWordResp
375{
376  val bank_data = Vec(DCacheBanks, Bits(DCacheSRAMRowBits.W))
377  val bank_oh = UInt(DCacheBanks.W)
378}
379
380class DCacheWordRespWithError(implicit p: Parameters) extends BaseDCacheWordResp
381{
382  val error = Bool() // all kinds of errors, include tag error
383}
384
385class DCacheLineResp(implicit p: Parameters) extends DCacheBundle
386{
387  val data   = UInt((cfg.blockBytes * 8).W)
388  // cache req missed, send it to miss queue
389  val miss   = Bool()
390  // cache req nacked, replay it later
391  val replay = Bool()
392  val id     = UInt(reqIdWidth.W)
393  def dump() = {
394    XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n",
395      data, id, miss, replay)
396  }
397}
398
399class Refill(implicit p: Parameters) extends DCacheBundle
400{
401  val addr   = UInt(PAddrBits.W)
402  val data   = UInt(l1BusDataWidth.W)
403  val error  = Bool() // refilled data has been corrupted
404  // for debug usage
405  val data_raw = UInt((cfg.blockBytes * 8).W)
406  val hasdata = Bool()
407  val refill_done = Bool()
408  def dump() = {
409    XSDebug("Refill: addr: %x data: %x\n", addr, data)
410  }
411  val id     = UInt(log2Up(cfg.nMissEntries).W)
412}
413
414class Release(implicit p: Parameters) extends DCacheBundle
415{
416  val paddr  = UInt(PAddrBits.W)
417  def dump() = {
418    XSDebug("Release: paddr: %x\n", paddr(PAddrBits-1, DCacheTagOffset))
419  }
420}
421
422class DCacheWordIO(implicit p: Parameters) extends DCacheBundle
423{
424  val req  = DecoupledIO(new DCacheWordReq)
425  val resp = Flipped(DecoupledIO(new DCacheWordResp))
426}
427
428
429class UncacheWordReq(implicit p: Parameters) extends DCacheBundle
430{
431  val cmd  = UInt(M_SZ.W)
432  val addr = UInt(PAddrBits.W)
433  val data = UInt(DataBits.W)
434  val mask = UInt((DataBits/8).W)
435  val id   = UInt(uncacheIdxBits.W)
436  val instrtype = UInt(sourceTypeWidth.W)
437  val atomic = Bool()
438  val isFirstIssue = Bool()
439  val replayCarry = new ReplayCarry
440
441  def dump() = {
442    XSDebug("UncacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
443      cmd, addr, data, mask, id)
444  }
445}
446
447class UncacheWorResp(implicit p: Parameters) extends DCacheBundle
448{
449  val data      = UInt(DataBits.W)
450  val data_delayed = UInt(DataBits.W)
451  val id        = UInt(uncacheIdxBits.W)
452  val miss      = Bool()
453  val replay    = Bool()
454  val tag_error = Bool()
455  val error     = Bool()
456  val replayCarry = new ReplayCarry
457  val mshr_id = UInt(log2Up(cfg.nMissEntries).W)  // FIXME: why uncacheWordResp is not merged to baseDcacheResp
458
459  val debug_robIdx = UInt(log2Ceil(RobSize).W)
460  def dump() = {
461    XSDebug("UncacheWordResp: data: %x id: %d miss: %b replay: %b, tag_error: %b, error: %b\n",
462      data, id, miss, replay, tag_error, error)
463  }
464}
465
466class UncacheWordIO(implicit p: Parameters) extends DCacheBundle
467{
468  val req  = DecoupledIO(new UncacheWordReq)
469  val resp = Flipped(DecoupledIO(new UncacheWorResp))
470}
471
472class AtomicsResp(implicit p: Parameters) extends DCacheBundle {
473  val data    = UInt(DataBits.W)
474  val miss    = Bool()
475  val miss_id = UInt(log2Up(cfg.nMissEntries).W)
476  val replay  = Bool()
477  val error   = Bool()
478
479  val ack_miss_queue = Bool()
480
481  val id     = UInt(reqIdWidth.W)
482}
483
484class AtomicWordIO(implicit p: Parameters) extends DCacheBundle
485{
486  val req  = DecoupledIO(new MainPipeReq)
487  val resp = Flipped(ValidIO(new AtomicsResp))
488  val block_lr = Input(Bool())
489}
490
491// used by load unit
492class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO
493{
494  // kill previous cycle's req
495  val s1_kill  = Output(Bool())
496  val s2_kill  = Output(Bool())
497  val s2_pc = Output(UInt(VAddrBits.W))
498  // cycle 0: load has updated replacement before
499  val replacementUpdated = Output(Bool())
500  // cycle 0: virtual address: req.addr
501  // cycle 1: physical address: s1_paddr
502  val s1_paddr_dup_lsu = Output(UInt(PAddrBits.W)) // lsu side paddr
503  val s1_paddr_dup_dcache = Output(UInt(PAddrBits.W)) // dcache side paddr
504  val s1_disable_fast_wakeup = Input(Bool())
505  // cycle 2: hit signal
506  val s2_hit = Input(Bool()) // hit signal for lsu,
507  val s2_first_hit = Input(Bool())
508  val s2_bank_conflict = Input(Bool())
509
510  // debug
511  val debug_s1_hit_way = Input(UInt(nWays.W))
512}
513
514class DCacheLineIO(implicit p: Parameters) extends DCacheBundle
515{
516  val req  = DecoupledIO(new DCacheLineReq)
517  val resp = Flipped(DecoupledIO(new DCacheLineResp))
518}
519
520class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle {
521  // sbuffer will directly send request to dcache main pipe
522  val req = Flipped(Decoupled(new DCacheLineReq))
523
524  val main_pipe_hit_resp = ValidIO(new DCacheLineResp)
525  val refill_hit_resp = ValidIO(new DCacheLineResp)
526
527  val replay_resp = ValidIO(new DCacheLineResp)
528
529  def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp)
530}
531
532// forward tilelink channel D's data to ldu
533class DcacheToLduForwardIO(implicit p: Parameters) extends DCacheBundle {
534  val valid = Bool()
535  val data = UInt(l1BusDataWidth.W)
536  val mshrid = UInt(log2Up(cfg.nMissEntries).W)
537  val last = Bool()
538
539  def apply(req_valid : Bool, req_data : UInt, req_mshrid : UInt, req_last : Bool) = {
540    valid := req_valid
541    data := req_data
542    mshrid := req_mshrid
543    last := req_last
544  }
545
546  def dontCare() = {
547    valid := false.B
548    data := DontCare
549    mshrid := DontCare
550    last := DontCare
551  }
552
553  def forward(req_valid : Bool, req_mshr_id : UInt, req_paddr : UInt) = {
554    val all_match = req_valid && valid &&
555                req_mshr_id === mshrid &&
556                req_paddr(log2Up(refillBytes)) === last
557
558    val forward_D = RegInit(false.B)
559    val forwardData = RegInit(VecInit(List.fill(8)(0.U(8.W))))
560
561    val block_idx = req_paddr(log2Up(refillBytes) - 1, 3)
562    val block_data = Wire(Vec(l1BusDataWidth / 64, UInt(64.W)))
563    (0 until l1BusDataWidth / 64).map(i => {
564      block_data(i) := data(64 * i + 63, 64 * i)
565    })
566    val selected_data = block_data(block_idx)
567
568    forward_D := all_match
569    for (i <- 0 until 8) {
570      forwardData(i) := selected_data(8 * i + 7, 8 * i)
571    }
572
573    (forward_D, forwardData)
574  }
575}
576
577class MissEntryForwardIO(implicit p: Parameters) extends DCacheBundle {
578  val inflight = Bool()
579  val paddr = UInt(PAddrBits.W)
580  val raw_data = Vec(blockBytes/beatBytes, UInt(beatBits.W))
581  val firstbeat_valid = Bool()
582  val lastbeat_valid = Bool()
583
584  def apply(mshr_valid : Bool, mshr_paddr : UInt, mshr_rawdata : Vec[UInt], mshr_first_valid : Bool, mshr_last_valid : Bool) = {
585    inflight := mshr_valid
586    paddr := mshr_paddr
587    raw_data := mshr_rawdata
588    firstbeat_valid := mshr_first_valid
589    lastbeat_valid := mshr_last_valid
590  }
591
592  // check if we can forward from mshr or D channel
593  def check(req_valid : Bool, req_paddr : UInt) = {
594    RegNext(req_valid && inflight && req_paddr(PAddrBits - 1, blockOffBits) === paddr(PAddrBits - 1, blockOffBits))
595  }
596
597  def forward(req_valid : Bool, req_paddr : UInt) = {
598    val all_match = (req_paddr(log2Up(refillBytes)) === 0.U && firstbeat_valid) ||
599                    (req_paddr(log2Up(refillBytes)) === 1.U && lastbeat_valid)
600
601    val forward_mshr = RegInit(false.B)
602    val forwardData = RegInit(VecInit(List.fill(8)(0.U(8.W))))
603
604    val beat_data = raw_data(req_paddr(log2Up(refillBytes)))
605    val block_idx = req_paddr(log2Up(refillBytes) - 1, 3)
606    val block_data = Wire(Vec(l1BusDataWidth / 64, UInt(64.W)))
607    (0 until l1BusDataWidth / 64).map(i => {
608      block_data(i) := beat_data(64 * i + 63, 64 * i)
609    })
610    val selected_data = block_data(block_idx)
611
612    forward_mshr := all_match
613    for (i <- 0 until 8) {
614      forwardData(i) := selected_data(8 * i + 7, 8 * i)
615    }
616
617    (forward_mshr, forwardData)
618  }
619}
620
621// forward mshr's data to ldu
622class LduToMissqueueForwardIO(implicit p: Parameters) extends DCacheBundle {
623  // req
624  val valid = Input(Bool())
625  val mshrid = Input(UInt(log2Up(cfg.nMissEntries).W))
626  val paddr = Input(UInt(PAddrBits.W))
627  // resp
628  val forward_mshr = Output(Bool())
629  val forwardData = Output(Vec(8, UInt(8.W)))
630  val forward_result_valid = Output(Bool())
631
632  def connect(sink: LduToMissqueueForwardIO) = {
633    sink.valid := valid
634    sink.mshrid := mshrid
635    sink.paddr := paddr
636    forward_mshr := sink.forward_mshr
637    forwardData := sink.forwardData
638    forward_result_valid := sink.forward_result_valid
639  }
640
641  def forward() = {
642    (forward_result_valid, forward_mshr, forwardData)
643  }
644}
645
646class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle {
647  val load  = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load
648  val lsq = ValidIO(new Refill)  // refill to load queue, wake up load misses
649  val store = new DCacheToSbufferIO // for sbuffer
650  val atomics  = Flipped(new AtomicWordIO)  // atomics reqs
651  val release = ValidIO(new Release) // cacheline release hint for ld-ld violation check
652  val forward_D = Output(Vec(LoadPipelineWidth, new DcacheToLduForwardIO))
653  val forward_mshr = Vec(LoadPipelineWidth, new LduToMissqueueForwardIO)
654}
655
656class DCacheIO(implicit p: Parameters) extends DCacheBundle {
657  val hartId = Input(UInt(8.W))
658  val l2_pf_store_only = Input(Bool())
659  val lsu = new DCacheToLsuIO
660  val csr = new L1CacheToCsrIO
661  val error = new L1CacheErrorInfo
662  val mshrFull = Output(Bool())
663}
664
665
666class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters {
667
668  val clientParameters = TLMasterPortParameters.v1(
669    Seq(TLMasterParameters.v1(
670      name = "dcache",
671      sourceId = IdRange(0, nEntries + 1),
672      supportsProbe = TransferSizes(cfg.blockBytes)
673    )),
674    requestFields = cacheParams.reqFields,
675    echoFields = cacheParams.echoFields
676  )
677
678  val clientNode = TLClientNode(Seq(clientParameters))
679
680  lazy val module = new DCacheImp(this)
681}
682
683
684class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters with HasPerfEvents {
685
686  val io = IO(new DCacheIO)
687
688  val (bus, edge) = outer.clientNode.out.head
689  require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match")
690
691  println("DCache:")
692  println("  DCacheSets: " + DCacheSets)
693  println("  DCacheWays: " + DCacheWays)
694  println("  DCacheBanks: " + DCacheBanks)
695  println("  DCacheSRAMRowBits: " + DCacheSRAMRowBits)
696  println("  DCacheWordOffset: " + DCacheWordOffset)
697  println("  DCacheBankOffset: " + DCacheBankOffset)
698  println("  DCacheSetOffset: " + DCacheSetOffset)
699  println("  DCacheTagOffset: " + DCacheTagOffset)
700  println("  DCacheAboveIndexOffset: " + DCacheAboveIndexOffset)
701
702  //----------------------------------------
703  // core data structures
704  val bankedDataArray = if(EnableDCacheWPU) Module(new SramedDataArray) else Module(new BankedDataArray)
705  val metaArray = Module(new L1CohMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2))
706  val errorArray = Module(new L1FlagMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2))
707  val prefetchArray = Module(new L1FlagMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2)) // prefetch flag array
708  val accessArray = Module(new L1FlagMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = LoadPipelineWidth + 2))
709  val tagArray = Module(new DuplicatedTagArray(readPorts = LoadPipelineWidth + 1))
710  bankedDataArray.dump()
711
712  //----------------------------------------
713  // core modules
714  val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))})
715  // val atomicsReplayUnit = Module(new AtomicsReplayEntry)
716  val mainPipe   = Module(new MainPipe)
717  val refillPipe = Module(new RefillPipe)
718  val missQueue  = Module(new MissQueue(edge))
719  val probeQueue = Module(new ProbeQueue(edge))
720  val wb         = Module(new WritebackQueue(edge))
721
722  missQueue.io.hartId := io.hartId
723  missQueue.io.l2_pf_store_only := RegNext(io.l2_pf_store_only, false.B)
724
725  val errors = ldu.map(_.io.error) ++ // load error
726    Seq(mainPipe.io.error) // store / misc error
727  io.error <> RegNext(Mux1H(errors.map(e => RegNext(e.valid) -> RegNext(e))))
728
729  //----------------------------------------
730  // meta array
731
732  // read / write coh meta
733  val meta_read_ports = ldu.map(_.io.meta_read) ++
734    Seq(mainPipe.io.meta_read)
735  val meta_resp_ports = ldu.map(_.io.meta_resp) ++
736    Seq(mainPipe.io.meta_resp)
737  val meta_write_ports = Seq(
738    mainPipe.io.meta_write,
739    refillPipe.io.meta_write
740  )
741  meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p }
742  meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r }
743  meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p }
744
745  // read extra meta
746  meta_read_ports.zip(errorArray.io.read).foreach { case (p, r) => r <> p }
747  meta_read_ports.zip(prefetchArray.io.read).foreach { case (p, r) => r <> p }
748  meta_read_ports.zip(accessArray.io.read).foreach { case (p, r) => r <> p }
749  val extra_meta_resp_ports = ldu.map(_.io.extra_meta_resp) ++
750    Seq(mainPipe.io.extra_meta_resp)
751  extra_meta_resp_ports.zip(errorArray.io.resp).foreach { case (p, r) => {
752    (0 until nWays).map(i => { p(i).error := r(i) })
753  }}
754  extra_meta_resp_ports.zip(prefetchArray.io.resp).foreach { case (p, r) => {
755    (0 until nWays).map(i => { p(i).prefetch := r(i) })
756  }}
757  extra_meta_resp_ports.zip(accessArray.io.resp).foreach { case (p, r) => {
758    (0 until nWays).map(i => { p(i).access := r(i) })
759  }}
760
761  // write extra meta
762  val error_flag_write_ports = Seq(
763    mainPipe.io.error_flag_write, // error flag generated by corrupted store
764    refillPipe.io.error_flag_write // corrupted signal from l2
765  )
766  error_flag_write_ports.zip(errorArray.io.write).foreach { case (p, w) => w <> p }
767
768  val prefetch_flag_write_ports = Seq(
769    mainPipe.io.prefetch_flag_write, // set prefetch_flag to false if coh is set to Nothing
770    refillPipe.io.prefetch_flag_write // refill required by prefetch will set prefetch_flag
771  )
772  prefetch_flag_write_ports.zip(prefetchArray.io.write).foreach { case (p, w) => w <> p }
773
774  val access_flag_write_ports = ldu.map(_.io.access_flag_write) ++ Seq(
775    mainPipe.io.access_flag_write,
776    refillPipe.io.access_flag_write
777  )
778  access_flag_write_ports.zip(accessArray.io.write).foreach { case (p, w) => w <> p }
779
780  //----------------------------------------
781  // tag array
782  require(tagArray.io.read.size == (ldu.size + 1))
783  val tag_write_intend = missQueue.io.refill_pipe_req.valid || mainPipe.io.tag_write_intend
784  assert(!RegNext(!tag_write_intend && tagArray.io.write.valid))
785  ldu.zipWithIndex.foreach {
786    case (ld, i) =>
787      tagArray.io.read(i) <> ld.io.tag_read
788      ld.io.tag_resp := tagArray.io.resp(i)
789      ld.io.tag_read.ready := !tag_write_intend
790  }
791  tagArray.io.read.last <> mainPipe.io.tag_read
792  mainPipe.io.tag_resp := tagArray.io.resp.last
793
794  val fake_tag_read_conflict_this_cycle = PopCount(ldu.map(ld=> ld.io.tag_read.valid))
795  XSPerfAccumulate("fake_tag_read_conflict", fake_tag_read_conflict_this_cycle)
796
797  val tag_write_arb = Module(new Arbiter(new TagWriteReq, 2))
798  tag_write_arb.io.in(0) <> refillPipe.io.tag_write
799  tag_write_arb.io.in(1) <> mainPipe.io.tag_write
800  tagArray.io.write <> tag_write_arb.io.out
801
802  //----------------------------------------
803  // data array
804
805  val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 2))
806  dataWriteArb.io.in(0) <> refillPipe.io.data_write
807  dataWriteArb.io.in(1) <> mainPipe.io.data_write
808
809  bankedDataArray.io.write <> dataWriteArb.io.out
810
811  for (bank <- 0 until DCacheBanks) {
812    val dataWriteArb_dup = Module(new Arbiter(new L1BankedDataWriteReqCtrl, 2))
813    dataWriteArb_dup.io.in(0).valid := refillPipe.io.data_write_dup(bank).valid
814    dataWriteArb_dup.io.in(0).bits := refillPipe.io.data_write_dup(bank).bits
815    dataWriteArb_dup.io.in(1).valid := mainPipe.io.data_write_dup(bank).valid
816    dataWriteArb_dup.io.in(1).bits := mainPipe.io.data_write_dup(bank).bits
817
818    bankedDataArray.io.write_dup(bank) <> dataWriteArb_dup.io.out
819  }
820
821  bankedDataArray.io.readline <> mainPipe.io.data_read
822  bankedDataArray.io.readline_intend := mainPipe.io.data_read_intend
823  mainPipe.io.readline_error_delayed := bankedDataArray.io.readline_error_delayed
824  mainPipe.io.data_resp := bankedDataArray.io.readline_resp
825
826  (0 until LoadPipelineWidth).map(i => {
827    bankedDataArray.io.read(i) <> ldu(i).io.banked_data_read
828    bankedDataArray.io.read_error_delayed(i) <> ldu(i).io.read_error_delayed
829
830    ldu(i).io.banked_data_resp := bankedDataArray.io.read_resp_delayed(i)
831
832    ldu(i).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(i)
833    ldu(i).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(i)
834  })
835
836  (0 until LoadPipelineWidth).map(i => {
837    val (_, _, done, _) = edge.count(bus.d)
838    when(bus.d.bits.opcode === TLMessages.GrantData) {
839      io.lsu.forward_D(i).apply(bus.d.valid, bus.d.bits.data, bus.d.bits.source, done)
840    }.otherwise {
841      io.lsu.forward_D(i).dontCare()
842    }
843  })
844
845  //----------------------------------------
846  // load pipe
847  // the s1 kill signal
848  // only lsu uses this, replay never kills
849  for (w <- 0 until LoadPipelineWidth) {
850    ldu(w).io.lsu <> io.lsu.load(w)
851
852    // replay and nack not needed anymore
853    // TODO: remove replay and nack
854    ldu(w).io.nack := false.B
855
856    ldu(w).io.disable_ld_fast_wakeup :=
857      bankedDataArray.io.disable_ld_fast_wakeup(w) // load pipe fast wake up should be disabled when bank conflict
858  }
859
860  /** LoadMissDB: record load miss state */
861  val isWriteLoadMissTable = WireInit(Constantin.createRecord("isWriteLoadMissTable" + p(XSCoreParamsKey).HartId.toString))
862  val isFirstHitWrite = WireInit(Constantin.createRecord("isFirstHitWrite" + p(XSCoreParamsKey).HartId.toString))
863  val tableName = "LoadMissDB" + p(XSCoreParamsKey).HartId.toString
864  val siteName = "DcacheWrapper" + p(XSCoreParamsKey).HartId.toString
865  val loadMissTable = ChiselDB.createTable(tableName, new LoadMissEntry)
866  for( i <- 0 until LoadPipelineWidth){
867    val loadMissEntry = Wire(new LoadMissEntry)
868    val loadMissWriteEn =
869      (!ldu(i).io.lsu.resp.bits.replay && ldu(i).io.miss_req.fire) ||
870      (ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid && isFirstHitWrite.orR)
871    loadMissEntry.timeCnt := GTimer()
872    loadMissEntry.robIdx := ldu(i).io.lsu.resp.bits.debug_robIdx
873    loadMissEntry.paddr := ldu(i).io.miss_req.bits.addr
874    loadMissEntry.vaddr := ldu(i).io.miss_req.bits.vaddr
875    loadMissEntry.missState := OHToUInt(Cat(Seq(
876      ldu(i).io.miss_req.fire & ldu(i).io.miss_resp.merged,
877      ldu(i).io.miss_req.fire & !ldu(i).io.miss_resp.merged,
878      ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid
879    )))
880    loadMissTable.log(
881      data = loadMissEntry,
882      en = isWriteLoadMissTable.orR && loadMissWriteEn,
883      site = siteName,
884      clock = clock,
885      reset = reset
886    )
887  }
888
889  //----------------------------------------
890  // atomics
891  // atomics not finished yet
892  // io.lsu.atomics <> atomicsReplayUnit.io.lsu
893  io.lsu.atomics.resp := RegNext(mainPipe.io.atomic_resp)
894  io.lsu.atomics.block_lr := mainPipe.io.block_lr
895  // atomicsReplayUnit.io.pipe_resp := RegNext(mainPipe.io.atomic_resp)
896  // atomicsReplayUnit.io.block_lr <> mainPipe.io.block_lr
897
898  //----------------------------------------
899  // miss queue
900  val MissReqPortCount = LoadPipelineWidth + 1
901  val MainPipeMissReqPort = 0
902
903  // Request
904  val missReqArb = Module(new ArbiterFilterByCacheLineAddr(new MissReq, MissReqPortCount, blockOffBits, PAddrBits))
905
906  missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req
907  for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req }
908
909  for (w <- 0 until LoadPipelineWidth) { ldu(w).io.miss_resp := missQueue.io.resp }
910  mainPipe.io.miss_resp := missQueue.io.resp
911
912  wb.io.miss_req.valid := missReqArb.io.out.valid
913  wb.io.miss_req.bits  := missReqArb.io.out.bits.addr
914
915  // block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req)
916  missReqArb.io.out <> missQueue.io.req
917  when(wb.io.block_miss_req) {
918    missQueue.io.req.bits.cancel := true.B
919    missReqArb.io.out.ready := false.B
920  }
921
922  XSPerfAccumulate("miss_queue_fire", PopCount(VecInit(missReqArb.io.in.map(_.fire))) >= 1.U)
923  XSPerfAccumulate("miss_queue_muti_fire", PopCount(VecInit(missReqArb.io.in.map(_.fire))) > 1.U)
924
925  // forward missqueue
926  (0 until LoadPipelineWidth).map(i => io.lsu.forward_mshr(i).connect(missQueue.io.forward(i)))
927
928  // refill to load queue
929  io.lsu.lsq <> missQueue.io.refill_to_ldq
930
931  // tilelink stuff
932  bus.a <> missQueue.io.mem_acquire
933  bus.e <> missQueue.io.mem_finish
934  missQueue.io.probe_addr := bus.b.bits.address
935
936  missQueue.io.main_pipe_resp := RegNext(mainPipe.io.atomic_resp)
937
938  //----------------------------------------
939  // probe
940  // probeQueue.io.mem_probe <> bus.b
941  block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block)
942  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
943  probeQueue.io.update_resv_set <> mainPipe.io.update_resv_set
944
945  //----------------------------------------
946  // mainPipe
947  // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe,
948  // block the req in main pipe
949  block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, missQueue.io.refill_pipe_req.valid)
950  block_decoupled(io.lsu.store.req, mainPipe.io.store_req, refillPipe.io.req.valid)
951
952  io.lsu.store.replay_resp := RegNext(mainPipe.io.store_replay_resp)
953  io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp
954
955  arbiter_with_pipereg(
956    in = Seq(missQueue.io.main_pipe_req, io.lsu.atomics.req),
957    out = mainPipe.io.atomic_req,
958    name = Some("main_pipe_atomic_req")
959  )
960
961  mainPipe.io.invalid_resv_set := RegNext(wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits)
962
963  //----------------------------------------
964  // replace (main pipe)
965  val mpStatus = mainPipe.io.status
966  mainPipe.io.replace_req <> missQueue.io.replace_pipe_req
967  missQueue.io.replace_pipe_resp := mainPipe.io.replace_resp
968
969  //----------------------------------------
970  // refill pipe
971  val refillShouldBeBlocked = (mpStatus.s1.valid && mpStatus.s1.bits.set === missQueue.io.refill_pipe_req.bits.idx) ||
972    Cat(Seq(mpStatus.s2, mpStatus.s3).map(s =>
973      s.valid &&
974        s.bits.set === missQueue.io.refill_pipe_req.bits.idx &&
975        s.bits.way_en === missQueue.io.refill_pipe_req.bits.way_en
976    )).orR
977  block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked)
978
979  val mpStatus_dup = mainPipe.io.status_dup
980  val mq_refill_dup = missQueue.io.refill_pipe_req_dup
981  val refillShouldBeBlocked_dup = VecInit((0 until nDupStatus).map { case i =>
982    mpStatus_dup(i).s1.valid && mpStatus_dup(i).s1.bits.set === mq_refill_dup(i).bits.idx ||
983    Cat(Seq(mpStatus_dup(i).s2, mpStatus_dup(i).s3).map(s =>
984      s.valid &&
985        s.bits.set === mq_refill_dup(i).bits.idx &&
986        s.bits.way_en === mq_refill_dup(i).bits.way_en
987    )).orR
988  })
989  dontTouch(refillShouldBeBlocked_dup)
990
991  refillPipe.io.req_dup_for_data_w.zipWithIndex.foreach { case (r, i) =>
992    r.bits := (mq_refill_dup.drop(dataWritePort).take(DCacheBanks))(i).bits
993  }
994  refillPipe.io.req_dup_for_meta_w.bits := mq_refill_dup(metaWritePort).bits
995  refillPipe.io.req_dup_for_tag_w.bits := mq_refill_dup(tagWritePort).bits
996  refillPipe.io.req_dup_for_err_w.bits := mq_refill_dup(errWritePort).bits
997  refillPipe.io.req_dup_for_data_w.zipWithIndex.foreach { case (r, i) =>
998    r.valid := (mq_refill_dup.drop(dataWritePort).take(DCacheBanks))(i).valid &&
999      !(refillShouldBeBlocked_dup.drop(dataWritePort).take(DCacheBanks))(i)
1000  }
1001  refillPipe.io.req_dup_for_meta_w.valid := mq_refill_dup(metaWritePort).valid && !refillShouldBeBlocked_dup(metaWritePort)
1002  refillPipe.io.req_dup_for_tag_w.valid := mq_refill_dup(tagWritePort).valid && !refillShouldBeBlocked_dup(tagWritePort)
1003  refillPipe.io.req_dup_for_err_w.valid := mq_refill_dup(errWritePort).valid && !refillShouldBeBlocked_dup(errWritePort)
1004
1005  val refillPipe_io_req_valid_dup = VecInit(mq_refill_dup.zip(refillShouldBeBlocked_dup).map(
1006    x => x._1.valid && !x._2
1007  ))
1008  val refillPipe_io_data_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(0, nDupDataWriteReady))
1009  val refillPipe_io_tag_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(nDupDataWriteReady, nDupStatus))
1010  dontTouch(refillPipe_io_req_valid_dup)
1011  dontTouch(refillPipe_io_data_write_valid_dup)
1012  dontTouch(refillPipe_io_tag_write_valid_dup)
1013  mainPipe.io.data_write_ready_dup := VecInit(refillPipe_io_data_write_valid_dup.map(v => !v))
1014  mainPipe.io.tag_write_ready_dup := VecInit(refillPipe_io_tag_write_valid_dup.map(v => !v))
1015  mainPipe.io.wb_ready_dup := wb.io.req_ready_dup
1016
1017  mq_refill_dup.zip(refillShouldBeBlocked_dup).foreach { case (r, block) =>
1018    r.ready := refillPipe.io.req.ready && !block
1019  }
1020
1021  missQueue.io.refill_pipe_resp := refillPipe.io.resp
1022  io.lsu.store.refill_hit_resp := RegNext(refillPipe.io.store_resp)
1023
1024  //----------------------------------------
1025  // wb
1026  // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy
1027
1028  wb.io.req <> mainPipe.io.wb
1029  bus.c     <> wb.io.mem_release
1030  wb.io.release_wakeup := refillPipe.io.release_wakeup
1031  wb.io.release_update := mainPipe.io.release_update
1032  wb.io.probe_ttob_check_req <> mainPipe.io.probe_ttob_check_req
1033  wb.io.probe_ttob_check_resp <> mainPipe.io.probe_ttob_check_resp
1034
1035  io.lsu.release.valid := RegNext(wb.io.req.fire())
1036  io.lsu.release.bits.paddr := RegNext(wb.io.req.bits.addr)
1037  // Note: RegNext() is required by:
1038  // * load queue released flag update logic
1039  // * load / load violation check logic
1040  // * and timing requirements
1041  // CHANGE IT WITH CARE
1042
1043  // connect bus d
1044  missQueue.io.mem_grant.valid := false.B
1045  missQueue.io.mem_grant.bits  := DontCare
1046
1047  wb.io.mem_grant.valid := false.B
1048  wb.io.mem_grant.bits  := DontCare
1049
1050  // in L1DCache, we ony expect Grant[Data] and ReleaseAck
1051  bus.d.ready := false.B
1052  when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) {
1053    missQueue.io.mem_grant <> bus.d
1054  } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) {
1055    wb.io.mem_grant <> bus.d
1056  } .otherwise {
1057    assert (!bus.d.fire())
1058  }
1059
1060  //----------------------------------------
1061  // replacement algorithm
1062  val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets)
1063
1064  val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way)
1065  replWayReqs.foreach{
1066    case req =>
1067      req.way := DontCare
1068      when (req.set.valid) { req.way := replacer.way(req.set.bits) }
1069  }
1070
1071  val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq(
1072    mainPipe.io.replace_access
1073  )
1074  val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W))))
1075  touchWays.zip(replAccessReqs).foreach {
1076    case (w, req) =>
1077      w.valid := req.valid
1078      w.bits := req.bits.way
1079  }
1080  val touchSets = replAccessReqs.map(_.bits.set)
1081  replacer.access(touchSets, touchWays)
1082
1083  //----------------------------------------
1084  // assertions
1085  // dcache should only deal with DRAM addresses
1086  when (bus.a.fire()) {
1087    assert(bus.a.bits.address >= 0x80000000L.U)
1088  }
1089  when (bus.b.fire()) {
1090    assert(bus.b.bits.address >= 0x80000000L.U)
1091  }
1092  when (bus.c.fire()) {
1093    assert(bus.c.bits.address >= 0x80000000L.U)
1094  }
1095
1096  //----------------------------------------
1097  // utility functions
1098  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
1099    sink.valid   := source.valid && !block_signal
1100    source.ready := sink.ready   && !block_signal
1101    sink.bits    := source.bits
1102  }
1103
1104  //----------------------------------------
1105  // Customized csr cache op support
1106  val cacheOpDecoder = Module(new CSRCacheOpDecoder("dcache", CacheInstrucion.COP_ID_DCACHE))
1107  cacheOpDecoder.io.csr <> io.csr
1108  bankedDataArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
1109  // dup cacheOp_req_valid
1110  bankedDataArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) }
1111  // dup cacheOp_req_bits_opCode
1112  bankedDataArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) }
1113
1114  tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
1115  // dup cacheOp_req_valid
1116  tagArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) }
1117  // dup cacheOp_req_bits_opCode
1118  tagArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) }
1119
1120  cacheOpDecoder.io.cache.resp.valid := bankedDataArray.io.cacheOp.resp.valid ||
1121    tagArray.io.cacheOp.resp.valid
1122  cacheOpDecoder.io.cache.resp.bits := Mux1H(List(
1123    bankedDataArray.io.cacheOp.resp.valid -> bankedDataArray.io.cacheOp.resp.bits,
1124    tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits,
1125  ))
1126  cacheOpDecoder.io.error := io.error
1127  assert(!((bankedDataArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U))
1128
1129  //----------------------------------------
1130  // performance counters
1131  val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire()))
1132  XSPerfAccumulate("num_loads", num_loads)
1133
1134  io.mshrFull := missQueue.io.full
1135
1136  // performance counter
1137  val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType))
1138  val st_access = Wire(ld_access.last.cloneType)
1139  ld_access.zip(ldu).foreach {
1140    case (a, u) =>
1141      a.valid := RegNext(u.io.lsu.req.fire()) && !u.io.lsu.s1_kill
1142      a.bits.idx := RegNext(get_idx(u.io.lsu.req.bits.addr))
1143      a.bits.tag := get_tag(u.io.lsu.s1_paddr_dup_dcache)
1144  }
1145  st_access.valid := RegNext(mainPipe.io.store_req.fire())
1146  st_access.bits.idx := RegNext(get_idx(mainPipe.io.store_req.bits.vaddr))
1147  st_access.bits.tag := RegNext(get_tag(mainPipe.io.store_req.bits.addr))
1148  val access_info = ld_access.toSeq ++ Seq(st_access)
1149  val early_replace = RegNext(missQueue.io.debug_early_replace)
1150  val access_early_replace = access_info.map {
1151    case acc =>
1152      Cat(early_replace.map {
1153        case r =>
1154          acc.valid && r.valid &&
1155            acc.bits.tag === r.bits.tag &&
1156            acc.bits.idx === r.bits.idx
1157      })
1158  }
1159  XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace)))
1160
1161  val perfEvents = (Seq(wb, mainPipe, missQueue, probeQueue) ++ ldu).flatMap(_.getPerfEvents)
1162  generatePerfEvent()
1163}
1164
1165class AMOHelper() extends ExtModule {
1166  val clock  = IO(Input(Clock()))
1167  val enable = IO(Input(Bool()))
1168  val cmd    = IO(Input(UInt(5.W)))
1169  val addr   = IO(Input(UInt(64.W)))
1170  val wdata  = IO(Input(UInt(64.W)))
1171  val mask   = IO(Input(UInt(8.W)))
1172  val rdata  = IO(Output(UInt(64.W)))
1173}
1174
1175class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
1176
1177  val useDcache = coreParams.dcacheParametersOpt.nonEmpty
1178  val clientNode = if (useDcache) TLIdentityNode() else null
1179  val dcache = if (useDcache) LazyModule(new DCache()) else null
1180  if (useDcache) {
1181    clientNode := dcache.clientNode
1182  }
1183
1184  lazy val module = new LazyModuleImp(this) with HasPerfEvents {
1185    val io = IO(new DCacheIO)
1186    val perfEvents = if (!useDcache) {
1187      // a fake dcache which uses dpi-c to access memory, only for debug usage!
1188      val fake_dcache = Module(new FakeDCache())
1189      io <> fake_dcache.io
1190      Seq()
1191    }
1192    else {
1193      io <> dcache.module.io
1194      dcache.module.getPerfEvents
1195    }
1196    generatePerfEvent()
1197  }
1198}
1199