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