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