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