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