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