xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/DCacheWrapper.scala (revision e04c5f647e1e5251ae701f95f5b9bd4e0172caed)
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 vaddr = UInt(VAddrBits.W) // for uncache buffer forwarding
519  val data = UInt(XLEN.W)
520  val mask = UInt((XLEN/8).W)
521  val id   = UInt(uncacheIdxBits.W)
522  val instrtype = UInt(sourceTypeWidth.W)
523  val atomic = Bool()
524  val nc = Bool()
525  val isFirstIssue = Bool()
526  val replayCarry = new ReplayCarry(nWays)
527
528  def dump() = {
529    XSDebug("UncacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
530      cmd, addr, data, mask, id)
531  }
532}
533
534class UncacheWordResp(implicit p: Parameters) extends DCacheBundle
535{
536  val data      = UInt(XLEN.W)
537  val data_delayed = UInt(XLEN.W)
538  val id        = UInt(uncacheIdxBits.W) // resp identified signals
539  val nc        = Bool() // resp identified signals
540  val is2lq     = Bool() // resp identified signals
541  val miss      = Bool()
542  val replay    = Bool()
543  val tag_error = Bool()
544  val error     = Bool()
545  val nderr     = Bool()
546  val replayCarry = new ReplayCarry(nWays)
547  val mshr_id = UInt(log2Up(cfg.nMissEntries).W)  // FIXME: why uncacheWordResp is not merged to baseDcacheResp
548
549  val debug_robIdx = UInt(log2Ceil(RobSize).W)
550  def dump() = {
551    XSDebug("UncacheWordResp: data: %x id: %d miss: %b replay: %b, tag_error: %b, error: %b\n",
552      data, id, miss, replay, tag_error, error)
553  }
554}
555
556class UncacheWordIO(implicit p: Parameters) extends DCacheBundle
557{
558  val req  = DecoupledIO(new UncacheWordReq)
559  val resp = Flipped(DecoupledIO(new UncacheWordResp))
560}
561
562class MainPipeResp(implicit p: Parameters) extends DCacheBundle {
563  //distinguish amo
564  val source  = UInt(sourceTypeWidth.W)
565  val data    = UInt(DataBits.W)
566  val miss    = Bool()
567  val miss_id = UInt(log2Up(cfg.nMissEntries).W)
568  val replay  = Bool()
569  val error   = Bool()
570
571  val ack_miss_queue = Bool()
572
573  val id     = UInt(reqIdWidth.W)
574
575  def isAMO: Bool = source === AMO_SOURCE.U
576  def isStore: Bool = source === STORE_SOURCE.U
577}
578
579class AtomicWordIO(implicit p: Parameters) extends DCacheBundle
580{
581  val req  = DecoupledIO(new MainPipeReq)
582  val resp = Flipped(ValidIO(new MainPipeResp))
583  val block_lr = Input(Bool())
584}
585
586class CMOReq(implicit p: Parameters) extends Bundle {
587  val opcode = UInt(3.W)   // 0-cbo.clean, 1-cbo.flush, 2-cbo.inval, 3-cbo.zero
588  val address = UInt(64.W)
589}
590
591class CMOResp(implicit p: Parameters) extends Bundle {
592  val address = UInt(64.W)
593}
594
595// used by load unit
596class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO
597{
598  // kill previous cycle's req
599  val s1_kill_data_read = Output(Bool()) // only kill bandedDataRead at s1
600  val s1_kill           = Output(Bool()) // kill loadpipe req at s1
601  val s2_kill           = Output(Bool())
602  val s0_pc             = Output(UInt(VAddrBits.W))
603  val s1_pc             = Output(UInt(VAddrBits.W))
604  val s2_pc             = Output(UInt(VAddrBits.W))
605  // cycle 0: load has updated replacement before
606  val replacementUpdated = Output(Bool())
607  val is128Req = Bool()
608  // cycle 0: prefetch source bits
609  val pf_source = Output(UInt(L1PfSourceBits.W))
610  // cycle0: load microop
611 // val s0_uop = Output(new MicroOp)
612  // cycle 0: virtual address: req.addr
613  // cycle 1: physical address: s1_paddr
614  val s1_paddr_dup_lsu = Output(UInt(PAddrBits.W)) // lsu side paddr
615  val s1_paddr_dup_dcache = Output(UInt(PAddrBits.W)) // dcache side paddr
616  val s1_disable_fast_wakeup = Input(Bool())
617  // cycle 2: hit signal
618  val s2_hit = Input(Bool()) // hit signal for lsu,
619  val s2_first_hit = Input(Bool())
620  val s2_bank_conflict = Input(Bool())
621  val s2_wpu_pred_fail = Input(Bool())
622  val s2_mq_nack = Input(Bool())
623
624  // debug
625  val debug_s1_hit_way = Input(UInt(nWays.W))
626  val debug_s2_pred_way_num = Input(UInt(XLEN.W))
627  val debug_s2_dm_way_num = Input(UInt(XLEN.W))
628  val debug_s2_real_way_num = Input(UInt(XLEN.W))
629}
630
631class DCacheLineIO(implicit p: Parameters) extends DCacheBundle
632{
633  val req  = DecoupledIO(new DCacheLineReq)
634  val resp = Flipped(DecoupledIO(new DCacheLineResp))
635}
636
637class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle {
638  // sbuffer will directly send request to dcache main pipe
639  val req = Flipped(Decoupled(new DCacheLineReq))
640
641  val main_pipe_hit_resp = ValidIO(new DCacheLineResp)
642  //val refill_hit_resp = ValidIO(new DCacheLineResp)
643
644  val replay_resp = ValidIO(new DCacheLineResp)
645
646  //def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp)
647  def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp)
648}
649
650// forward tilelink channel D's data to ldu
651class DcacheToLduForwardIO(implicit p: Parameters) extends DCacheBundle {
652  val valid = Bool()
653  val data = UInt(l1BusDataWidth.W)
654  val mshrid = UInt(log2Up(cfg.nMissEntries).W)
655  val last = Bool()
656
657  def apply(req_valid : Bool, req_data : UInt, req_mshrid : UInt, req_last : Bool) = {
658    valid := req_valid
659    data := req_data
660    mshrid := req_mshrid
661    last := req_last
662  }
663
664  def dontCare() = {
665    valid := false.B
666    data := DontCare
667    mshrid := DontCare
668    last := DontCare
669  }
670
671  def forward(req_valid : Bool, req_mshr_id : UInt, req_paddr : UInt) = {
672    val all_match = req_valid && valid &&
673                req_mshr_id === mshrid &&
674                req_paddr(log2Up(refillBytes)) === last
675    val forward_D = RegInit(false.B)
676    val forwardData = RegInit(VecInit(List.fill(VLEN/8)(0.U(8.W))))
677
678    val block_idx = req_paddr(log2Up(refillBytes) - 1, 3)
679    val block_data = Wire(Vec(l1BusDataWidth / 64, UInt(64.W)))
680    (0 until l1BusDataWidth / 64).map(i => {
681      block_data(i) := data(64 * i + 63, 64 * i)
682    })
683    val selected_data = Wire(UInt(128.W))
684    selected_data := Mux(req_paddr(3), Fill(2, block_data(block_idx)), Cat(block_data(block_idx + 1.U), block_data(block_idx)))
685
686    forward_D := all_match
687    for (i <- 0 until VLEN/8) {
688      when (all_match) {
689        forwardData(i) := selected_data(8 * i + 7, 8 * i)
690      }
691    }
692
693    (forward_D, forwardData)
694  }
695}
696
697class MissEntryForwardIO(implicit p: Parameters) extends DCacheBundle {
698  val inflight = Bool()
699  val paddr = UInt(PAddrBits.W)
700  val raw_data = Vec(blockRows, UInt(rowBits.W))
701  val firstbeat_valid = Bool()
702  val lastbeat_valid = Bool()
703
704  def apply(mshr_valid : Bool, mshr_paddr : UInt, mshr_rawdata : Vec[UInt], mshr_first_valid : Bool, mshr_last_valid : Bool) = {
705    inflight := mshr_valid
706    paddr := mshr_paddr
707    raw_data := mshr_rawdata
708    firstbeat_valid := mshr_first_valid
709    lastbeat_valid := mshr_last_valid
710  }
711
712  // check if we can forward from mshr or D channel
713  def check(req_valid : Bool, req_paddr : UInt) = {
714    RegNext(req_valid && inflight && req_paddr(PAddrBits - 1, blockOffBits) === paddr(PAddrBits - 1, blockOffBits)) // TODO: clock gate(1-bit)
715  }
716
717  def forward(req_valid : Bool, req_paddr : UInt) = {
718    val all_match = (req_paddr(log2Up(refillBytes)) === 0.U && firstbeat_valid) ||
719                    (req_paddr(log2Up(refillBytes)) === 1.U && lastbeat_valid)
720
721    val forward_mshr = RegInit(false.B)
722    val forwardData = RegInit(VecInit(List.fill(VLEN/8)(0.U(8.W))))
723
724    val block_idx = req_paddr(log2Up(refillBytes), 3)
725    val block_data = raw_data
726
727    val selected_data = Wire(UInt(128.W))
728    selected_data := Mux(req_paddr(3), Fill(2, block_data(block_idx)), Cat(block_data(block_idx + 1.U), block_data(block_idx)))
729
730    forward_mshr := all_match
731    for (i <- 0 until VLEN/8) {
732      forwardData(i) := selected_data(8 * i + 7, 8 * i)
733    }
734
735    (forward_mshr, forwardData)
736  }
737}
738
739// forward mshr's data to ldu
740class LduToMissqueueForwardIO(implicit p: Parameters) extends DCacheBundle {
741  // req
742  val valid = Input(Bool())
743  val mshrid = Input(UInt(log2Up(cfg.nMissEntries).W))
744  val paddr = Input(UInt(PAddrBits.W))
745  // resp
746  val forward_mshr = Output(Bool())
747  val forwardData = Output(Vec(VLEN/8, UInt(8.W)))
748  val forward_result_valid = Output(Bool())
749
750  def connect(sink: LduToMissqueueForwardIO) = {
751    sink.valid := valid
752    sink.mshrid := mshrid
753    sink.paddr := paddr
754    forward_mshr := sink.forward_mshr
755    forwardData := sink.forwardData
756    forward_result_valid := sink.forward_result_valid
757  }
758
759  def forward() = {
760    (forward_result_valid, forward_mshr, forwardData)
761  }
762}
763
764class StorePrefetchReq(implicit p: Parameters) extends DCacheBundle {
765  val paddr = UInt(PAddrBits.W)
766  val vaddr = UInt(VAddrBits.W)
767}
768
769class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle {
770  val load  = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load
771  val sta   = Vec(StorePipelineWidth, Flipped(new DCacheStoreIO)) // for non-blocking store
772  //val lsq = ValidIO(new Refill)  // refill to load queue, wake up load misses
773  val tl_d_channel = Output(new DcacheToLduForwardIO)
774  val store = new DCacheToSbufferIO // for sbuffer
775  val atomics  = Flipped(new AtomicWordIO)  // atomics reqs
776  val release = ValidIO(new Release) // cacheline release hint for ld-ld violation check
777  val forward_D = Output(Vec(LoadPipelineWidth, new DcacheToLduForwardIO))
778  val forward_mshr = Vec(LoadPipelineWidth, new LduToMissqueueForwardIO)
779}
780
781class DCacheTopDownIO(implicit p: Parameters) extends DCacheBundle {
782  val robHeadVaddr = Flipped(Valid(UInt(VAddrBits.W)))
783  val robHeadMissInDCache = Output(Bool())
784  val robHeadOtherReplay = Input(Bool())
785}
786
787class DCacheIO(implicit p: Parameters) extends DCacheBundle {
788  val hartId = Input(UInt(hartIdLen.W))
789  val l2_pf_store_only = Input(Bool())
790  val lsu = new DCacheToLsuIO
791  val csr = new L1CacheToCsrIO
792  val error = ValidIO(new L1CacheErrorInfo)
793  val mshrFull = Output(Bool())
794  val memSetPattenDetected = Output(Bool())
795  val lqEmpty = Input(Bool())
796  val pf_ctrl = Output(new PrefetchControlBundle)
797  val force_write = Input(Bool())
798  val sms_agt_evict_req = DecoupledIO(new AGTEvictReq)
799  val debugTopDown = new DCacheTopDownIO
800  val debugRolling = Flipped(new RobDebugRollingIO)
801  val l2_hint = Input(Valid(new L2ToL1Hint()))
802  val cmoOpReq = Flipped(DecoupledIO(new CMOReq))
803  val cmoOpResp = DecoupledIO(new CMOResp)
804}
805
806private object ArbiterCtrl {
807  def apply(request: Seq[Bool]): Seq[Bool] = request.length match {
808    case 0 => Seq()
809    case 1 => Seq(true.B)
810    case _ => true.B +: request.tail.init.scanLeft(request.head)(_ || _).map(!_)
811  }
812}
813
814class TreeArbiter[T <: MissReqWoStoreData](val gen: T, val n: Int) extends Module{
815  val io = IO(new ArbiterIO(gen, n))
816
817  def selectTree(in: Vec[Valid[T]], sIdx: UInt): Tuple2[UInt, T] = {
818    if (in.length == 1) {
819      (sIdx, in(0).bits)
820    } else if (in.length == 2) {
821      (
822        Mux(in(0).valid, sIdx, sIdx + 1.U),
823        Mux(in(0).valid, in(0).bits, in(1).bits)
824      )
825    } else {
826      val half = in.length / 2
827      val leftValid = in.slice(0, half).map(_.valid).reduce(_ || _)
828      val (leftIdx, leftSel) = selectTree(VecInit(in.slice(0, half)), sIdx)
829      val (rightIdx, rightSel) = selectTree(VecInit(in.slice(half, in.length)), sIdx + half.U)
830      (
831        Mux(leftValid, leftIdx, rightIdx),
832        Mux(leftValid, leftSel, rightSel)
833      )
834    }
835  }
836  val ins = Wire(Vec(n, Valid(gen)))
837  for (i <- 0 until n) {
838    ins(i).valid := io.in(i).valid
839    ins(i).bits  := io.in(i).bits
840  }
841  val (idx, sel) = selectTree(ins, 0.U)
842  // NOTE: io.chosen is very slow, dont use it
843  io.chosen := idx
844  io.out.bits := sel
845
846  val grant = ArbiterCtrl(io.in.map(_.valid))
847  for ((in, g) <- io.in.zip(grant))
848    in.ready := g && io.out.ready
849  io.out.valid := !grant.last || io.in.last.valid
850}
851
852class DCacheMEQueryIOBundle(implicit p: Parameters) extends DCacheBundle
853{
854  val req              = ValidIO(new MissReqWoStoreData)
855  val primary_ready    = Input(Bool())
856  val secondary_ready  = Input(Bool())
857  val secondary_reject = Input(Bool())
858}
859
860class DCacheMQQueryIOBundle(implicit p: Parameters) extends DCacheBundle
861{
862  val req    = ValidIO(new MissReq)
863  val ready  = Input(Bool())
864}
865
866class MissReadyGen(val n: Int)(implicit p: Parameters) extends XSModule {
867  val io = IO(new Bundle {
868    val in = Vec(n, Flipped(DecoupledIO(new MissReq)))
869    val queryMQ = Vec(n, new DCacheMQQueryIOBundle)
870  })
871
872  val mqReadyVec = io.queryMQ.map(_.ready)
873
874  io.queryMQ.zipWithIndex.foreach{
875    case (q, idx) => {
876      q.req.valid := io.in(idx).valid
877      q.req.bits  := io.in(idx).bits
878    }
879  }
880  io.in.zipWithIndex.map {
881    case (r, idx) => {
882      if (idx == 0) {
883        r.ready := mqReadyVec(idx)
884      } else {
885        r.ready := mqReadyVec(idx) && !Cat(io.in.slice(0, idx).map(_.valid)).orR
886      }
887    }
888  }
889
890}
891
892class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters {
893  override def shouldBeInlined: Boolean = false
894
895  val reqFields: Seq[BundleFieldBase] = Seq(
896    PrefetchField(),
897    ReqSourceField(),
898    VaddrField(VAddrBits - blockOffBits),
899  //  IsKeywordField()
900  ) ++ cacheParams.aliasBitsOpt.map(AliasField)
901  val echoFields: Seq[BundleFieldBase] = Seq(
902    IsKeywordField()
903  )
904
905  val clientParameters = TLMasterPortParameters.v1(
906    Seq(TLMasterParameters.v1(
907      name = "dcache",
908      sourceId = IdRange(0, nEntries + 1),
909      supportsProbe = TransferSizes(cfg.blockBytes)
910    )),
911    requestFields = reqFields,
912    echoFields = echoFields
913  )
914
915  val clientNode = TLClientNode(Seq(clientParameters))
916
917  lazy val module = new DCacheImp(this)
918}
919
920
921class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters with HasPerfEvents with HasL1PrefetchSourceParameter {
922
923  val io = IO(new DCacheIO)
924
925  val (bus, edge) = outer.clientNode.out.head
926  require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match")
927
928  println("DCache:")
929  println("  DCacheSets: " + DCacheSets)
930  println("  DCacheSetDiv: " + DCacheSetDiv)
931  println("  DCacheWays: " + DCacheWays)
932  println("  DCacheBanks: " + DCacheBanks)
933  println("  DCacheSRAMRowBits: " + DCacheSRAMRowBits)
934  println("  DCacheWordOffset: " + DCacheWordOffset)
935  println("  DCacheBankOffset: " + DCacheBankOffset)
936  println("  DCacheSetOffset: " + DCacheSetOffset)
937  println("  DCacheTagOffset: " + DCacheTagOffset)
938  println("  DCacheAboveIndexOffset: " + DCacheAboveIndexOffset)
939  println("  DcacheMaxPrefetchEntry: " + MaxPrefetchEntry)
940  println("  WPUEnable: " + dwpuParam.enWPU)
941  println("  WPUEnableCfPred: " + dwpuParam.enCfPred)
942  println("  WPUAlgorithm: " + dwpuParam.algoName)
943  println("  HasCMO: " + HasCMO)
944
945  // Enable L1 Store prefetch
946  val StorePrefetchL1Enabled = EnableStorePrefetchAtCommit || EnableStorePrefetchAtIssue || EnableStorePrefetchSPB
947  val MetaReadPort =
948        if (StorePrefetchL1Enabled)
949          1 + backendParams.LduCnt + backendParams.StaCnt + backendParams.HyuCnt
950        else
951          1 + backendParams.LduCnt + backendParams.HyuCnt
952  val TagReadPort =
953        if (StorePrefetchL1Enabled)
954          1 + backendParams.LduCnt + backendParams.StaCnt + backendParams.HyuCnt
955        else
956          1 + backendParams.LduCnt + backendParams.HyuCnt
957
958  // Enable L1 Load prefetch
959  val LoadPrefetchL1Enabled = true
960  val AccessArrayReadPort = if(LoadPrefetchL1Enabled) LoadPipelineWidth + 1 + 1 else LoadPipelineWidth + 1
961  val PrefetchArrayReadPort = if(LoadPrefetchL1Enabled) LoadPipelineWidth + 1 + 1 else LoadPipelineWidth + 1
962
963  //----------------------------------------
964  // core data structures
965  val bankedDataArray = if(dwpuParam.enWPU) Module(new SramedDataArray) else Module(new BankedDataArray)
966  val metaArray = Module(new L1CohMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 1))
967  val errorArray = Module(new L1FlagMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 1))
968  val prefetchArray = Module(new L1PrefetchSourceArray(readPorts = PrefetchArrayReadPort, writePorts = 1 + LoadPipelineWidth)) // prefetch flag array
969  val accessArray = Module(new L1FlagMetaArray(readPorts = AccessArrayReadPort, writePorts = LoadPipelineWidth + 1))
970  val tagArray = Module(new DuplicatedTagArray(readPorts = TagReadPort))
971  val prefetcherMonitor = Module(new PrefetcherMonitor)
972  val fdpMonitor =  Module(new FDPrefetcherMonitor)
973  val bloomFilter =  Module(new BloomFilter(BLOOM_FILTER_ENTRY_NUM, true))
974  val counterFilter = Module(new CounterFilter)
975  bankedDataArray.dump()
976
977  //----------------------------------------
978  // miss queue
979  // missReqArb port:
980  // enableStorePrefetch: main pipe * 1 + load pipe * 2 + store pipe * 1 +
981  // hybrid * 1; disable: main pipe * 1 + load pipe * 2 + hybrid * 1
982  // higher priority is given to lower indices
983  val MissReqPortCount = if(StorePrefetchL1Enabled) 1 + backendParams.LduCnt + backendParams.StaCnt + backendParams.HyuCnt else 1 + backendParams.LduCnt + backendParams.HyuCnt
984  val MainPipeMissReqPort = 0
985  val HybridMissReqBase = MissReqPortCount - backendParams.HyuCnt
986
987  //----------------------------------------
988  // core modules
989  val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))})
990  val stu = Seq.tabulate(StorePipelineWidth)({ i => Module(new StorePipe(i))})
991  val mainPipe     = Module(new MainPipe)
992  // val refillPipe   = Module(new RefillPipe)
993  val missQueue    = Module(new MissQueue(edge, MissReqPortCount))
994  val probeQueue   = Module(new ProbeQueue(edge))
995  val wb           = Module(new WritebackQueue(edge))
996
997  missQueue.io.lqEmpty := io.lqEmpty
998  missQueue.io.hartId := io.hartId
999  missQueue.io.l2_pf_store_only := RegNext(io.l2_pf_store_only, false.B)
1000  missQueue.io.debugTopDown <> io.debugTopDown
1001  missQueue.io.l2_hint <> RegNext(io.l2_hint)
1002  missQueue.io.mainpipe_info := mainPipe.io.mainpipe_info
1003  mainPipe.io.refill_info := missQueue.io.refill_info
1004  mainPipe.io.replace_block := missQueue.io.replace_block
1005  mainPipe.io.sms_agt_evict_req <> io.sms_agt_evict_req
1006  io.memSetPattenDetected := missQueue.io.memSetPattenDetected
1007
1008  val errors = ldu.map(_.io.error) ++ // load error
1009    Seq(mainPipe.io.error) // store / misc error
1010  val error_valid = errors.map(e => e.valid).reduce(_|_)
1011  io.error.bits <> RegEnable(
1012    Mux1H(errors.map(e => RegNext(e.valid) -> RegEnable(e.bits, e.valid))),
1013    RegNext(error_valid))
1014  io.error.valid := RegNext(RegNext(error_valid, init = false.B), init = false.B)
1015
1016  //----------------------------------------
1017  // meta array
1018  val HybridLoadReadBase = LoadPipelineWidth - backendParams.HyuCnt
1019  val HybridStoreReadBase = StorePipelineWidth - backendParams.HyuCnt
1020
1021  val hybrid_meta_read_ports = Wire(Vec(backendParams.HyuCnt, DecoupledIO(new MetaReadReq)))
1022  val hybrid_meta_resp_ports = Wire(Vec(backendParams.HyuCnt, ldu(0).io.meta_resp.cloneType))
1023  for (i <- 0 until backendParams.HyuCnt) {
1024    val HybridLoadMetaReadPort = HybridLoadReadBase + i
1025    val HybridStoreMetaReadPort = HybridStoreReadBase + i
1026
1027    hybrid_meta_read_ports(i).valid := ldu(HybridLoadMetaReadPort).io.meta_read.valid ||
1028                                       (stu(HybridStoreMetaReadPort).io.meta_read.valid && StorePrefetchL1Enabled.B)
1029    hybrid_meta_read_ports(i).bits := Mux(ldu(HybridLoadMetaReadPort).io.meta_read.valid, ldu(HybridLoadMetaReadPort).io.meta_read.bits,
1030                                          stu(HybridStoreMetaReadPort).io.meta_read.bits)
1031
1032    ldu(HybridLoadMetaReadPort).io.meta_read.ready := hybrid_meta_read_ports(i).ready
1033    stu(HybridStoreMetaReadPort).io.meta_read.ready := hybrid_meta_read_ports(i).ready && StorePrefetchL1Enabled.B
1034
1035    ldu(HybridLoadMetaReadPort).io.meta_resp := hybrid_meta_resp_ports(i)
1036    stu(HybridStoreMetaReadPort).io.meta_resp := hybrid_meta_resp_ports(i)
1037  }
1038
1039  // read / write coh meta
1040  val meta_read_ports = ldu.map(_.io.meta_read).take(HybridLoadReadBase) ++
1041    Seq(mainPipe.io.meta_read) ++
1042    stu.map(_.io.meta_read).take(HybridStoreReadBase) ++ hybrid_meta_read_ports
1043
1044  val meta_resp_ports = ldu.map(_.io.meta_resp).take(HybridLoadReadBase) ++
1045    Seq(mainPipe.io.meta_resp) ++
1046    stu.map(_.io.meta_resp).take(HybridStoreReadBase) ++ hybrid_meta_resp_ports
1047
1048  val meta_write_ports = Seq(
1049    mainPipe.io.meta_write
1050    // refillPipe.io.meta_write
1051  )
1052  if(StorePrefetchL1Enabled) {
1053    meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p }
1054    meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r }
1055  } else {
1056    (meta_read_ports.take(HybridLoadReadBase + 1) ++
1057     meta_read_ports.takeRight(backendParams.HyuCnt)).zip(metaArray.io.read).foreach { case (p, r) => r <> p }
1058    (meta_resp_ports.take(HybridLoadReadBase + 1) ++
1059     meta_resp_ports.takeRight(backendParams.HyuCnt)).zip(metaArray.io.resp).foreach { case (p, r) => p := r }
1060
1061    meta_read_ports.drop(HybridLoadReadBase + 1).take(HybridStoreReadBase).foreach { case p => p.ready := false.B }
1062    meta_resp_ports.drop(HybridLoadReadBase + 1).take(HybridStoreReadBase).foreach { case p => p := 0.U.asTypeOf(p) }
1063  }
1064  meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p }
1065
1066  // read extra meta (exclude stu)
1067  (meta_read_ports.take(HybridLoadReadBase + 1) ++
1068   meta_read_ports.takeRight(backendParams.HyuCnt)).zip(errorArray.io.read).foreach { case (p, r) => r <> p }
1069  (meta_read_ports.take(HybridLoadReadBase + 1) ++
1070   meta_read_ports.takeRight(backendParams.HyuCnt)).zip(prefetchArray.io.read).foreach { case (p, r) => r <> p }
1071  (meta_read_ports.take(HybridLoadReadBase + 1) ++
1072   meta_read_ports.takeRight(backendParams.HyuCnt)).zip(accessArray.io.read).foreach { case (p, r) => r <> p }
1073  val extra_meta_resp_ports = ldu.map(_.io.extra_meta_resp).take(HybridLoadReadBase) ++
1074    Seq(mainPipe.io.extra_meta_resp) ++
1075    ldu.map(_.io.extra_meta_resp).takeRight(backendParams.HyuCnt)
1076  extra_meta_resp_ports.zip(errorArray.io.resp).foreach { case (p, r) => {
1077    (0 until nWays).map(i => { p(i).error := r(i) })
1078  }}
1079  extra_meta_resp_ports.zip(prefetchArray.io.resp).foreach { case (p, r) => {
1080    (0 until nWays).map(i => { p(i).prefetch := r(i) })
1081  }}
1082  extra_meta_resp_ports.zip(accessArray.io.resp).foreach { case (p, r) => {
1083    (0 until nWays).map(i => { p(i).access := r(i) })
1084  }}
1085
1086  if(LoadPrefetchL1Enabled) {
1087    // use last port to read prefetch and access flag
1088//    prefetchArray.io.read.last.valid := refillPipe.io.prefetch_flag_write.valid
1089//    prefetchArray.io.read.last.bits.idx := refillPipe.io.prefetch_flag_write.bits.idx
1090//    prefetchArray.io.read.last.bits.way_en := refillPipe.io.prefetch_flag_write.bits.way_en
1091//
1092//    accessArray.io.read.last.valid := refillPipe.io.prefetch_flag_write.valid
1093//    accessArray.io.read.last.bits.idx := refillPipe.io.prefetch_flag_write.bits.idx
1094//    accessArray.io.read.last.bits.way_en := refillPipe.io.prefetch_flag_write.bits.way_en
1095    prefetchArray.io.read.last.valid := mainPipe.io.prefetch_flag_write.valid
1096    prefetchArray.io.read.last.bits.idx := mainPipe.io.prefetch_flag_write.bits.idx
1097    prefetchArray.io.read.last.bits.way_en := mainPipe.io.prefetch_flag_write.bits.way_en
1098
1099    accessArray.io.read.last.valid := mainPipe.io.prefetch_flag_write.valid
1100    accessArray.io.read.last.bits.idx := mainPipe.io.prefetch_flag_write.bits.idx
1101    accessArray.io.read.last.bits.way_en := mainPipe.io.prefetch_flag_write.bits.way_en
1102
1103    val extra_flag_valid = RegNext(mainPipe.io.prefetch_flag_write.valid)
1104    val extra_flag_way_en = RegEnable(mainPipe.io.prefetch_flag_write.bits.way_en, mainPipe.io.prefetch_flag_write.valid)
1105    val extra_flag_prefetch = Mux1H(extra_flag_way_en, prefetchArray.io.resp.last)
1106    val extra_flag_access = Mux1H(extra_flag_way_en, accessArray.io.resp.last)
1107
1108    prefetcherMonitor.io.validity.good_prefetch := extra_flag_valid && isPrefetchRelated(extra_flag_prefetch) && extra_flag_access
1109    prefetcherMonitor.io.validity.bad_prefetch := extra_flag_valid && isPrefetchRelated(extra_flag_prefetch) && !extra_flag_access
1110  }
1111
1112  // write extra meta
1113  val error_flag_write_ports = Seq(
1114    mainPipe.io.error_flag_write // error flag generated by corrupted store
1115    // refillPipe.io.error_flag_write // corrupted signal from l2
1116  )
1117  error_flag_write_ports.zip(errorArray.io.write).foreach { case (p, w) => w <> p }
1118
1119  val prefetch_flag_write_ports = ldu.map(_.io.prefetch_flag_write) ++ Seq(
1120    mainPipe.io.prefetch_flag_write // set prefetch_flag to false if coh is set to Nothing
1121    // refillPipe.io.prefetch_flag_write // refill required by prefetch will set prefetch_flag
1122  )
1123  prefetch_flag_write_ports.zip(prefetchArray.io.write).foreach { case (p, w) => w <> p }
1124
1125  // FIXME: add hybrid unit?
1126  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)
1127  XSPerfAccumulate("same_cycle_update_pf_flag", same_cycle_update_pf_flag)
1128
1129  val access_flag_write_ports = ldu.map(_.io.access_flag_write) ++ Seq(
1130    mainPipe.io.access_flag_write
1131    // refillPipe.io.access_flag_write
1132  )
1133  access_flag_write_ports.zip(accessArray.io.write).foreach { case (p, w) => w <> p }
1134
1135  //----------------------------------------
1136  // tag array
1137  if(StorePrefetchL1Enabled) {
1138    require(tagArray.io.read.size == (LoadPipelineWidth + StorePipelineWidth - backendParams.HyuCnt + 1))
1139  }else {
1140    require(tagArray.io.read.size == (LoadPipelineWidth + 1))
1141  }
1142  // val tag_write_intend = missQueue.io.refill_pipe_req.valid || mainPipe.io.tag_write_intend
1143  val tag_write_intend = mainPipe.io.tag_write_intend
1144  assert(!RegNext(!tag_write_intend && tagArray.io.write.valid))
1145  ldu.take(HybridLoadReadBase).zipWithIndex.foreach {
1146    case (ld, i) =>
1147      tagArray.io.read(i) <> ld.io.tag_read
1148      ld.io.tag_resp := tagArray.io.resp(i)
1149      ld.io.tag_read.ready := !tag_write_intend
1150  }
1151  if(StorePrefetchL1Enabled) {
1152    stu.take(HybridStoreReadBase).zipWithIndex.foreach {
1153      case (st, i) =>
1154        tagArray.io.read(HybridLoadReadBase + i) <> st.io.tag_read
1155        st.io.tag_resp := tagArray.io.resp(HybridLoadReadBase + i)
1156        st.io.tag_read.ready := !tag_write_intend
1157    }
1158  }else {
1159    stu.foreach {
1160      case st =>
1161        st.io.tag_read.ready := false.B
1162        st.io.tag_resp := 0.U.asTypeOf(st.io.tag_resp)
1163    }
1164  }
1165  for (i <- 0 until backendParams.HyuCnt) {
1166    val HybridLoadTagReadPort = HybridLoadReadBase + i
1167    val HybridStoreTagReadPort = HybridStoreReadBase + i
1168    val TagReadPort =
1169      if (EnableStorePrefetchSPB)
1170        HybridLoadReadBase + HybridStoreReadBase + i
1171      else
1172        HybridLoadReadBase + i
1173
1174    // read tag
1175    ldu(HybridLoadTagReadPort).io.tag_read.ready := false.B
1176    stu(HybridStoreTagReadPort).io.tag_read.ready := false.B
1177
1178    if (StorePrefetchL1Enabled) {
1179      when (ldu(HybridLoadTagReadPort).io.tag_read.valid) {
1180        tagArray.io.read(TagReadPort) <> ldu(HybridLoadTagReadPort).io.tag_read
1181        ldu(HybridLoadTagReadPort).io.tag_read.ready := !tag_write_intend
1182      } .otherwise {
1183        tagArray.io.read(TagReadPort) <> stu(HybridStoreTagReadPort).io.tag_read
1184        stu(HybridStoreTagReadPort).io.tag_read.ready := !tag_write_intend
1185      }
1186    } else {
1187      tagArray.io.read(TagReadPort) <> ldu(HybridLoadTagReadPort).io.tag_read
1188      ldu(HybridLoadTagReadPort).io.tag_read.ready := !tag_write_intend
1189    }
1190
1191    // tag resp
1192    ldu(HybridLoadTagReadPort).io.tag_resp := tagArray.io.resp(TagReadPort)
1193    stu(HybridStoreTagReadPort).io.tag_resp := tagArray.io.resp(TagReadPort)
1194  }
1195  tagArray.io.read.last <> mainPipe.io.tag_read
1196  mainPipe.io.tag_resp := tagArray.io.resp.last
1197
1198  val fake_tag_read_conflict_this_cycle = PopCount(ldu.map(ld=> ld.io.tag_read.valid))
1199  XSPerfAccumulate("fake_tag_read_conflict", fake_tag_read_conflict_this_cycle)
1200
1201  val tag_write_arb = Module(new Arbiter(new TagWriteReq, 1))
1202  // tag_write_arb.io.in(0) <> refillPipe.io.tag_write
1203  tag_write_arb.io.in(0) <> mainPipe.io.tag_write
1204  tagArray.io.write <> tag_write_arb.io.out
1205
1206  ldu.map(m => {
1207    m.io.vtag_update.valid := tagArray.io.write.valid
1208    m.io.vtag_update.bits := tagArray.io.write.bits
1209  })
1210
1211  //----------------------------------------
1212  // data array
1213  mainPipe.io.data_read.zip(ldu).map(x => x._1 := x._2.io.lsu.req.valid)
1214
1215  val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 1))
1216  // dataWriteArb.io.in(0) <> refillPipe.io.data_write
1217  dataWriteArb.io.in(0) <> mainPipe.io.data_write
1218
1219  bankedDataArray.io.write <> dataWriteArb.io.out
1220
1221  for (bank <- 0 until DCacheBanks) {
1222    val dataWriteArb_dup = Module(new Arbiter(new L1BankedDataWriteReqCtrl, 1))
1223    // dataWriteArb_dup.io.in(0).valid := refillPipe.io.data_write_dup(bank).valid
1224    // dataWriteArb_dup.io.in(0).bits := refillPipe.io.data_write_dup(bank).bits
1225    dataWriteArb_dup.io.in(0).valid := mainPipe.io.data_write_dup(bank).valid
1226    dataWriteArb_dup.io.in(0).bits := mainPipe.io.data_write_dup(bank).bits
1227
1228    bankedDataArray.io.write_dup(bank) <> dataWriteArb_dup.io.out
1229  }
1230
1231  bankedDataArray.io.readline <> mainPipe.io.data_readline
1232  bankedDataArray.io.readline_intend := mainPipe.io.data_read_intend
1233  mainPipe.io.readline_error_delayed := bankedDataArray.io.readline_error_delayed
1234  mainPipe.io.data_resp := bankedDataArray.io.readline_resp
1235
1236  (0 until LoadPipelineWidth).map(i => {
1237    bankedDataArray.io.read(i) <> ldu(i).io.banked_data_read
1238    bankedDataArray.io.is128Req(i) <> ldu(i).io.is128Req
1239    bankedDataArray.io.read_error_delayed(i) <> ldu(i).io.read_error_delayed
1240
1241    ldu(i).io.banked_data_resp := bankedDataArray.io.read_resp(i)
1242
1243    ldu(i).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(i)
1244  })
1245 val isKeyword = bus.d.bits.echo.lift(IsKeywordKey).getOrElse(false.B)
1246  (0 until LoadPipelineWidth).map(i => {
1247    val (_, _, done, _) = edge.count(bus.d)
1248    when(bus.d.bits.opcode === TLMessages.GrantData) {
1249      io.lsu.forward_D(i).apply(bus.d.valid, bus.d.bits.data, bus.d.bits.source, isKeyword ^ done)
1250   //   io.lsu.forward_D(i).apply(bus.d.valid, bus.d.bits.data, bus.d.bits.source,done)
1251    }.otherwise {
1252      io.lsu.forward_D(i).dontCare()
1253    }
1254  })
1255  // tl D channel wakeup
1256  val (_, _, done, _) = edge.count(bus.d)
1257  when (bus.d.bits.opcode === TLMessages.GrantData || bus.d.bits.opcode === TLMessages.Grant) {
1258    io.lsu.tl_d_channel.apply(bus.d.valid, bus.d.bits.data, bus.d.bits.source, done)
1259  } .otherwise {
1260    io.lsu.tl_d_channel.dontCare()
1261  }
1262  mainPipe.io.force_write <> io.force_write
1263
1264  /** dwpu */
1265  if (dwpuParam.enWPU) {
1266    val dwpu = Module(new DCacheWpuWrapper(LoadPipelineWidth))
1267    for(i <- 0 until LoadPipelineWidth){
1268      dwpu.io.req(i) <> ldu(i).io.dwpu.req(0)
1269      dwpu.io.resp(i) <> ldu(i).io.dwpu.resp(0)
1270      dwpu.io.lookup_upd(i) <> ldu(i).io.dwpu.lookup_upd(0)
1271      dwpu.io.cfpred(i) <> ldu(i).io.dwpu.cfpred(0)
1272    }
1273    dwpu.io.tagwrite_upd.valid := tagArray.io.write.valid
1274    dwpu.io.tagwrite_upd.bits.vaddr := tagArray.io.write.bits.vaddr
1275    dwpu.io.tagwrite_upd.bits.s1_real_way_en := tagArray.io.write.bits.way_en
1276  } else {
1277    for(i <- 0 until LoadPipelineWidth){
1278      ldu(i).io.dwpu.req(0).ready := true.B
1279      ldu(i).io.dwpu.resp(0).valid := false.B
1280      ldu(i).io.dwpu.resp(0).bits := DontCare
1281    }
1282  }
1283
1284  //----------------------------------------
1285  // load pipe
1286  // the s1 kill signal
1287  // only lsu uses this, replay never kills
1288  for (w <- 0 until LoadPipelineWidth) {
1289    ldu(w).io.lsu <> io.lsu.load(w)
1290
1291    // TODO:when have load128Req
1292    ldu(w).io.load128Req := io.lsu.load(w).is128Req
1293
1294    // replay and nack not needed anymore
1295    // TODO: remove replay and nack
1296    ldu(w).io.nack := false.B
1297
1298    ldu(w).io.disable_ld_fast_wakeup :=
1299      bankedDataArray.io.disable_ld_fast_wakeup(w) // load pipe fast wake up should be disabled when bank conflict
1300  }
1301
1302  prefetcherMonitor.io.timely.total_prefetch := ldu.map(_.io.prefetch_info.naive.total_prefetch).reduce(_ || _)
1303  prefetcherMonitor.io.timely.late_hit_prefetch := ldu.map(_.io.prefetch_info.naive.late_hit_prefetch).reduce(_ || _)
1304  prefetcherMonitor.io.timely.late_miss_prefetch := missQueue.io.prefetch_info.naive.late_miss_prefetch
1305  prefetcherMonitor.io.timely.prefetch_hit := PopCount(ldu.map(_.io.prefetch_info.naive.prefetch_hit))
1306  io.pf_ctrl <> prefetcherMonitor.io.pf_ctrl
1307  XSPerfAccumulate("useless_prefetch", ldu.map(_.io.prefetch_info.naive.total_prefetch).reduce(_ || _) && !(ldu.map(_.io.prefetch_info.naive.useful_prefetch).reduce(_ || _)))
1308  XSPerfAccumulate("useful_prefetch", ldu.map(_.io.prefetch_info.naive.useful_prefetch).reduce(_ || _))
1309  XSPerfAccumulate("late_prefetch_hit", ldu.map(_.io.prefetch_info.naive.late_prefetch_hit).reduce(_ || _))
1310  XSPerfAccumulate("late_load_hit", ldu.map(_.io.prefetch_info.naive.late_load_hit).reduce(_ || _))
1311
1312  /** LoadMissDB: record load miss state */
1313  val hartId = p(XSCoreParamsKey).HartId
1314  val isWriteLoadMissTable = Constantin.createRecord(s"isWriteLoadMissTable$hartId")
1315  val isFirstHitWrite = Constantin.createRecord(s"isFirstHitWrite$hartId")
1316  val tableName = s"LoadMissDB$hartId"
1317  val siteName = s"DcacheWrapper$hartId"
1318  val loadMissTable = ChiselDB.createTable(tableName, new LoadMissEntry)
1319  for( i <- 0 until LoadPipelineWidth){
1320    val loadMissEntry = Wire(new LoadMissEntry)
1321    val loadMissWriteEn =
1322      (!ldu(i).io.lsu.resp.bits.replay && ldu(i).io.miss_req.fire) ||
1323      (ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid && isFirstHitWrite.orR)
1324    loadMissEntry.timeCnt := GTimer()
1325    loadMissEntry.robIdx := ldu(i).io.lsu.resp.bits.debug_robIdx
1326    loadMissEntry.paddr := ldu(i).io.miss_req.bits.addr
1327    loadMissEntry.vaddr := ldu(i).io.miss_req.bits.vaddr
1328    loadMissEntry.missState := OHToUInt(Cat(Seq(
1329      ldu(i).io.miss_req.fire & ldu(i).io.miss_resp.merged,
1330      ldu(i).io.miss_req.fire & !ldu(i).io.miss_resp.merged,
1331      ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid
1332    )))
1333    loadMissTable.log(
1334      data = loadMissEntry,
1335      en = isWriteLoadMissTable.orR && loadMissWriteEn,
1336      site = siteName,
1337      clock = clock,
1338      reset = reset
1339    )
1340  }
1341
1342  val isWriteLoadAccessTable = Constantin.createRecord(s"isWriteLoadAccessTable$hartId")
1343  val loadAccessTable = ChiselDB.createTable(s"LoadAccessDB$hartId", new LoadAccessEntry)
1344  for (i <- 0 until LoadPipelineWidth) {
1345    val loadAccessEntry = Wire(new LoadAccessEntry)
1346    loadAccessEntry.timeCnt := GTimer()
1347    loadAccessEntry.robIdx := ldu(i).io.lsu.resp.bits.debug_robIdx
1348    loadAccessEntry.paddr := ldu(i).io.miss_req.bits.addr
1349    loadAccessEntry.vaddr := ldu(i).io.miss_req.bits.vaddr
1350    loadAccessEntry.missState := OHToUInt(Cat(Seq(
1351      ldu(i).io.miss_req.fire & ldu(i).io.miss_resp.merged,
1352      ldu(i).io.miss_req.fire & !ldu(i).io.miss_resp.merged,
1353      ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid
1354    )))
1355    loadAccessEntry.pred_way_num := ldu(i).io.lsu.debug_s2_pred_way_num
1356    loadAccessEntry.real_way_num := ldu(i).io.lsu.debug_s2_real_way_num
1357    loadAccessEntry.dm_way_num := ldu(i).io.lsu.debug_s2_dm_way_num
1358    loadAccessTable.log(
1359      data = loadAccessEntry,
1360      en = isWriteLoadAccessTable.orR && ldu(i).io.lsu.resp.valid,
1361      site = siteName + "_loadpipe" + i.toString,
1362      clock = clock,
1363      reset = reset
1364    )
1365  }
1366
1367  //----------------------------------------
1368  // Sta pipe
1369  for (w <- 0 until StorePipelineWidth) {
1370    stu(w).io.lsu <> io.lsu.sta(w)
1371  }
1372
1373  //----------------------------------------
1374  // atomics
1375  // atomics not finished yet
1376  val atomic_resp_valid = mainPipe.io.atomic_resp.valid && mainPipe.io.atomic_resp.bits.isAMO
1377  io.lsu.atomics.resp.valid := RegNext(atomic_resp_valid)
1378  io.lsu.atomics.resp.bits := RegEnable(mainPipe.io.atomic_resp.bits, atomic_resp_valid)
1379  io.lsu.atomics.block_lr := mainPipe.io.block_lr
1380  // atomicsReplayUnit.io.pipe_resp := RegNext(mainPipe.io.atomic_resp)
1381  // atomicsReplayUnit.io.block_lr <> mainPipe.io.block_lr
1382
1383  // Request
1384  val missReqArb = Module(new TreeArbiter(new MissReq, MissReqPortCount))
1385  // seperately generating miss queue enq ready for better timeing
1386  val missReadyGen = Module(new MissReadyGen(MissReqPortCount))
1387
1388  missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req
1389  missReadyGen.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req
1390  for (w <- 0 until backendParams.LduCnt) {
1391    missReqArb.io.in(w + 1) <> ldu(w).io.miss_req
1392    missReadyGen.io.in(w + 1) <> ldu(w).io.miss_req
1393  }
1394
1395  for (w <- 0 until LoadPipelineWidth) { ldu(w).io.miss_resp := missQueue.io.resp }
1396  mainPipe.io.miss_resp := missQueue.io.resp
1397
1398  if(StorePrefetchL1Enabled) {
1399    for (w <- 0 until backendParams.StaCnt) {
1400      missReqArb.io.in(1 + backendParams.LduCnt + w) <> stu(w).io.miss_req
1401      missReadyGen.io.in(1 + backendParams.LduCnt + w) <> stu(w).io.miss_req
1402    }
1403  }else {
1404    for (w <- 0 until backendParams.StaCnt) { stu(w).io.miss_req.ready := false.B }
1405  }
1406
1407  for (i <- 0 until backendParams.HyuCnt) {
1408    val HybridLoadReqPort = HybridLoadReadBase + i
1409    val HybridStoreReqPort = HybridStoreReadBase + i
1410    val HybridMissReqPort = HybridMissReqBase + i
1411
1412    ldu(HybridLoadReqPort).io.miss_req.ready := false.B
1413    stu(HybridStoreReqPort).io.miss_req.ready := false.B
1414
1415    if (StorePrefetchL1Enabled) {
1416      when (ldu(HybridLoadReqPort).io.miss_req.valid) {
1417        missReqArb.io.in(HybridMissReqPort) <> ldu(HybridLoadReqPort).io.miss_req
1418        missReadyGen.io.in(HybridMissReqPort) <> ldu(HybridLoadReqPort).io.miss_req
1419      } .otherwise {
1420        missReqArb.io.in(HybridMissReqPort) <> stu(HybridStoreReqPort).io.miss_req
1421        missReadyGen.io.in(HybridMissReqPort) <> stu(HybridStoreReqPort).io.miss_req
1422      }
1423    } else {
1424      missReqArb.io.in(HybridMissReqPort) <> ldu(HybridLoadReqPort).io.miss_req
1425      missReadyGen.io.in(HybridMissReqPort) <> ldu(HybridLoadReqPort).io.miss_req
1426    }
1427  }
1428
1429  for(w <- 0 until LoadPipelineWidth) {
1430    wb.io.miss_req_conflict_check(w) := ldu(w).io.wbq_conflict_check
1431    ldu(w).io.wbq_block_miss_req     := wb.io.block_miss_req(w)
1432  }
1433
1434  wb.io.miss_req_conflict_check(3) := mainPipe.io.wbq_conflict_check
1435  mainPipe.io.wbq_block_miss_req   := wb.io.block_miss_req(3)
1436
1437  wb.io.miss_req_conflict_check(4).valid := missReqArb.io.out.valid
1438  wb.io.miss_req_conflict_check(4).bits  := missReqArb.io.out.bits.addr
1439  missQueue.io.wbq_block_miss_req := wb.io.block_miss_req(4)
1440
1441  missReqArb.io.out <> missQueue.io.req
1442  missReadyGen.io.queryMQ <> missQueue.io.queryMQ
1443  io.cmoOpReq <> missQueue.io.cmo_req
1444  io.cmoOpResp <> missQueue.io.cmo_resp
1445
1446  for (w <- 0 until LoadPipelineWidth) { ldu(w).io.mq_enq_cancel := missQueue.io.mq_enq_cancel }
1447
1448  XSPerfAccumulate("miss_queue_fire", PopCount(VecInit(missReqArb.io.in.map(_.fire))) >= 1.U)
1449  XSPerfAccumulate("miss_queue_muti_fire", PopCount(VecInit(missReqArb.io.in.map(_.fire))) > 1.U)
1450
1451  XSPerfAccumulate("miss_queue_has_enq_req", PopCount(VecInit(missReqArb.io.in.map(_.valid))) >= 1.U)
1452  XSPerfAccumulate("miss_queue_has_muti_enq_req", PopCount(VecInit(missReqArb.io.in.map(_.valid))) > 1.U)
1453  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)
1454
1455  // forward missqueue
1456  (0 until LoadPipelineWidth).map(i => io.lsu.forward_mshr(i).connect(missQueue.io.forward(i)))
1457
1458  // refill to load queue
1459 // io.lsu.lsq <> missQueue.io.refill_to_ldq
1460
1461  // tilelink stuff
1462  bus.a <> missQueue.io.mem_acquire
1463  bus.e <> missQueue.io.mem_finish
1464  missQueue.io.probe_addr := bus.b.bits.address
1465  missQueue.io.replace_addr := mainPipe.io.replace_addr
1466
1467  missQueue.io.main_pipe_resp.valid := RegNext(mainPipe.io.atomic_resp.valid)
1468  missQueue.io.main_pipe_resp.bits := RegEnable(mainPipe.io.atomic_resp.bits, mainPipe.io.atomic_resp.valid)
1469
1470  //----------------------------------------
1471  // probe
1472  // probeQueue.io.mem_probe <> bus.b
1473  block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block)
1474  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
1475  probeQueue.io.update_resv_set <> mainPipe.io.update_resv_set
1476
1477  val refill_req = RegNext(missQueue.io.main_pipe_req.valid && ((missQueue.io.main_pipe_req.bits.isLoad) | (missQueue.io.main_pipe_req.bits.isStore)))
1478  //----------------------------------------
1479  // mainPipe
1480  // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe,
1481  // block the req in main pipe
1482  probeQueue.io.pipe_req <> mainPipe.io.probe_req
1483  io.lsu.store.req <> mainPipe.io.store_req
1484
1485  io.lsu.store.replay_resp.valid := RegNext(mainPipe.io.store_replay_resp.valid)
1486  io.lsu.store.replay_resp.bits := RegEnable(mainPipe.io.store_replay_resp.bits, mainPipe.io.store_replay_resp.valid)
1487  io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp
1488
1489  mainPipe.io.atomic_req <> io.lsu.atomics.req
1490
1491  mainPipe.io.invalid_resv_set := RegNext(
1492    wb.io.req.fire &&
1493    wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits &&
1494    mainPipe.io.lrsc_locked_block.valid
1495  )
1496
1497  //----------------------------------------
1498  // replace (main pipe)
1499  val mpStatus = mainPipe.io.status
1500  mainPipe.io.refill_req <> missQueue.io.main_pipe_req
1501
1502  mainPipe.io.data_write_ready_dup := VecInit(Seq.fill(nDupDataWriteReady)(true.B))
1503  mainPipe.io.tag_write_ready_dup := VecInit(Seq.fill(nDupDataWriteReady)(true.B))
1504  mainPipe.io.wb_ready_dup := wb.io.req_ready_dup
1505
1506  //----------------------------------------
1507  // wb
1508  // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy
1509
1510  wb.io.req <> mainPipe.io.wb
1511  bus.c     <> wb.io.mem_release
1512  // wb.io.release_wakeup := refillPipe.io.release_wakeup
1513  // wb.io.release_update := mainPipe.io.release_update
1514  //wb.io.probe_ttob_check_req <> mainPipe.io.probe_ttob_check_req
1515  //wb.io.probe_ttob_check_resp <> mainPipe.io.probe_ttob_check_resp
1516
1517  io.lsu.release.valid := RegNext(wb.io.req.fire)
1518  io.lsu.release.bits.paddr := RegEnable(wb.io.req.bits.addr, wb.io.req.fire)
1519  // Note: RegNext() is required by:
1520  // * load queue released flag update logic
1521  // * load / load violation check logic
1522  // * and timing requirements
1523  // CHANGE IT WITH CARE
1524
1525  // connect bus d
1526  missQueue.io.mem_grant.valid := false.B
1527  missQueue.io.mem_grant.bits  := DontCare
1528
1529  wb.io.mem_grant.valid := false.B
1530  wb.io.mem_grant.bits  := DontCare
1531
1532  // in L1DCache, we ony expect Grant[Data] and ReleaseAck
1533  bus.d.ready := false.B
1534  when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData || bus.d.bits.opcode === TLMessages.CBOAck) {
1535    missQueue.io.mem_grant <> bus.d
1536  } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) {
1537    wb.io.mem_grant <> bus.d
1538  } .otherwise {
1539    assert (!bus.d.fire)
1540  }
1541
1542  //----------------------------------------
1543  // Feedback Direct Prefetch Monitor
1544  fdpMonitor.io.refill := missQueue.io.prefetch_info.fdp.prefetch_monitor_cnt
1545  fdpMonitor.io.timely.late_prefetch := missQueue.io.prefetch_info.fdp.late_miss_prefetch
1546  fdpMonitor.io.accuracy.total_prefetch := missQueue.io.prefetch_info.fdp.total_prefetch
1547  for (w <- 0 until LoadPipelineWidth)  {
1548    if(w == 0) {
1549      fdpMonitor.io.accuracy.useful_prefetch(w) := ldu(w).io.prefetch_info.fdp.useful_prefetch
1550    }else {
1551      fdpMonitor.io.accuracy.useful_prefetch(w) := Mux(same_cycle_update_pf_flag, false.B, ldu(w).io.prefetch_info.fdp.useful_prefetch)
1552    }
1553  }
1554  for (w <- 0 until LoadPipelineWidth)  { fdpMonitor.io.pollution.cache_pollution(w) :=  ldu(w).io.prefetch_info.fdp.pollution }
1555  for (w <- 0 until LoadPipelineWidth)  { fdpMonitor.io.pollution.demand_miss(w) :=  ldu(w).io.prefetch_info.fdp.demand_miss }
1556  fdpMonitor.io.debugRolling := io.debugRolling
1557
1558  //----------------------------------------
1559  // Bloom Filter
1560  // bloomFilter.io.set <> missQueue.io.bloom_filter_query.set
1561  // bloomFilter.io.clr <> missQueue.io.bloom_filter_query.clr
1562  bloomFilter.io.set <> mainPipe.io.bloom_filter_query.set
1563  bloomFilter.io.clr <> mainPipe.io.bloom_filter_query.clr
1564
1565  for (w <- 0 until LoadPipelineWidth)  { bloomFilter.io.query(w) <> ldu(w).io.bloom_filter_query.query }
1566  for (w <- 0 until LoadPipelineWidth)  { bloomFilter.io.resp(w) <> ldu(w).io.bloom_filter_query.resp }
1567
1568  for (w <- 0 until LoadPipelineWidth)  { counterFilter.io.ld_in(w) <> ldu(w).io.counter_filter_enq }
1569  for (w <- 0 until LoadPipelineWidth)  { counterFilter.io.query(w) <> ldu(w).io.counter_filter_query }
1570
1571  //----------------------------------------
1572  // replacement algorithm
1573  val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets)
1574  val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way) ++ stu.map(_.io.replace_way)
1575
1576  if (dwpuParam.enCfPred) {
1577    val victimList = VictimList(nSets)
1578    replWayReqs.foreach {
1579      case req =>
1580        req.way := DontCare
1581        when(req.set.valid) {
1582          when(victimList.whether_sa(req.set.bits)) {
1583            req.way := replacer.way(req.set.bits)
1584          }.otherwise {
1585            req.way := req.dmWay
1586          }
1587        }
1588    }
1589  } else {
1590    replWayReqs.foreach {
1591      case req =>
1592        req.way := DontCare
1593        when(req.set.valid) {
1594          req.way := replacer.way(req.set.bits)
1595        }
1596    }
1597  }
1598
1599  val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq(
1600    mainPipe.io.replace_access
1601  ) ++ stu.map(_.io.replace_access)
1602  val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W))))
1603  touchWays.zip(replAccessReqs).foreach {
1604    case (w, req) =>
1605      w.valid := req.valid
1606      w.bits := req.bits.way
1607  }
1608  val touchSets = replAccessReqs.map(_.bits.set)
1609  replacer.access(touchSets, touchWays)
1610
1611  //----------------------------------------
1612  // assertions
1613  // dcache should only deal with DRAM addresses
1614  import freechips.rocketchip.util._
1615  when (bus.a.fire) {
1616    assert(PmemRanges.map(range => bus.a.bits.address.inRange(range._1.U, range._2.U)).reduce(_ || _))
1617  }
1618  when (bus.b.fire) {
1619    assert(PmemRanges.map(range => bus.b.bits.address.inRange(range._1.U, range._2.U)).reduce(_ || _))
1620  }
1621  when (bus.c.fire) {
1622    assert(PmemRanges.map(range => bus.c.bits.address.inRange(range._1.U, range._2.U)).reduce(_ || _))
1623  }
1624
1625  //----------------------------------------
1626  // utility functions
1627  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
1628    sink.valid   := source.valid && !block_signal
1629    source.ready := sink.ready   && !block_signal
1630    sink.bits    := source.bits
1631  }
1632
1633
1634  //----------------------------------------
1635  // Customized csr cache op support
1636  val cacheOpDecoder = Module(new CSRCacheOpDecoder("dcache", CacheInstrucion.COP_ID_DCACHE))
1637  cacheOpDecoder.io.csr <> io.csr
1638  bankedDataArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
1639  // dup cacheOp_req_valid
1640  bankedDataArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) }
1641  // dup cacheOp_req_bits_opCode
1642  bankedDataArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) }
1643
1644  tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
1645  // dup cacheOp_req_valid
1646  tagArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) }
1647  // dup cacheOp_req_bits_opCode
1648  tagArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) }
1649
1650  cacheOpDecoder.io.cache.resp.valid := bankedDataArray.io.cacheOp.resp.valid ||
1651    tagArray.io.cacheOp.resp.valid
1652  cacheOpDecoder.io.cache.resp.bits := Mux1H(List(
1653    bankedDataArray.io.cacheOp.resp.valid -> bankedDataArray.io.cacheOp.resp.bits,
1654    tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits,
1655  ))
1656  cacheOpDecoder.io.error := io.error
1657  assert(!((bankedDataArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U))
1658
1659  //----------------------------------------
1660  // performance counters
1661  val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire))
1662  XSPerfAccumulate("num_loads", num_loads)
1663
1664  io.mshrFull := missQueue.io.full
1665
1666  // performance counter
1667  // val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType))
1668  // val st_access = Wire(ld_access.last.cloneType)
1669  // ld_access.zip(ldu).foreach {
1670  //   case (a, u) =>
1671  //     a.valid := RegNext(u.io.lsu.req.fire) && !u.io.lsu.s1_kill
1672  //     a.bits.idx := RegEnable(get_idx(u.io.lsu.req.bits.vaddr), u.io.lsu.req.fire)
1673  //     a.bits.tag := get_tag(u.io.lsu.s1_paddr_dup_dcache)
1674  // }
1675  // st_access.valid := RegNext(mainPipe.io.store_req.fire)
1676  // st_access.bits.idx := RegEnable(get_idx(mainPipe.io.store_req.bits.vaddr), mainPipe.io.store_req.fire)
1677  // st_access.bits.tag := RegEnable(get_tag(mainPipe.io.store_req.bits.addr), mainPipe.io.store_req.fire)
1678  // val access_info = ld_access.toSeq ++ Seq(st_access)
1679  // val early_replace = RegNext(missQueue.io.debug_early_replace) // TODO: clock gate
1680  // val access_early_replace = access_info.map {
1681  //   case acc =>
1682  //     Cat(early_replace.map {
1683  //       case r =>
1684  //         acc.valid && r.valid &&
1685  //           acc.bits.tag === r.bits.tag &&
1686  //           acc.bits.idx === r.bits.idx
1687  //     })
1688  // }
1689  // XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace)))
1690
1691  val perfEvents = (Seq(wb, mainPipe, missQueue, probeQueue) ++ ldu).flatMap(_.getPerfEvents)
1692  generatePerfEvent()
1693}
1694
1695class AMOHelper() extends ExtModule {
1696  val clock  = IO(Input(Clock()))
1697  val enable = IO(Input(Bool()))
1698  val cmd    = IO(Input(UInt(5.W)))
1699  val addr   = IO(Input(UInt(64.W)))
1700  val wdata  = IO(Input(UInt(64.W)))
1701  val mask   = IO(Input(UInt(8.W)))
1702  val rdata  = IO(Output(UInt(64.W)))
1703}
1704
1705class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
1706  override def shouldBeInlined: Boolean = false
1707
1708  val useDcache = coreParams.dcacheParametersOpt.nonEmpty
1709  val clientNode = if (useDcache) TLIdentityNode() else null
1710  val dcache = if (useDcache) LazyModule(new DCache()) else null
1711  if (useDcache) {
1712    clientNode := dcache.clientNode
1713  }
1714
1715  class DCacheWrapperImp(wrapper: LazyModule) extends LazyModuleImp(wrapper) with HasPerfEvents {
1716    val io = IO(new DCacheIO)
1717    val perfEvents = if (!useDcache) {
1718      // a fake dcache which uses dpi-c to access memory, only for debug usage!
1719      val fake_dcache = Module(new FakeDCache())
1720      io <> fake_dcache.io
1721      Seq()
1722    }
1723    else {
1724      io <> dcache.module.io
1725      dcache.module.getPerfEvents
1726    }
1727    generatePerfEvent()
1728  }
1729
1730  lazy val module = new DCacheWrapperImp(this)
1731}