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