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