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