xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/DCacheWrapper.scala (revision ca18a0b47b0e4089fd0dd1c085091cb90bf98f25)
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 chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.experimental.ExtModule
22import chisel3.util._
23import xiangshan._
24import utils._
25import freechips.rocketchip.diplomacy.{IdRange, LazyModule, LazyModuleImp, TransferSizes}
26import freechips.rocketchip.tilelink._
27import freechips.rocketchip.util.BundleFieldBase
28import device.RAMHelper
29import huancun.{AliasField, AliasKey, PreferCacheField, PrefetchField, DirtyField}
30import scala.math.max
31
32// DCache specific parameters
33case class DCacheParameters
34(
35  nSets: Int = 256,
36  nWays: Int = 8,
37  rowBits: Int = 128,
38  tagECC: Option[String] = None,
39  dataECC: Option[String] = None,
40  replacer: Option[String] = Some("random"),
41  nMissEntries: Int = 1,
42  nProbeEntries: Int = 1,
43  nReleaseEntries: Int = 1,
44  nMMIOEntries: Int = 1,
45  nMMIOs: Int = 1,
46  blockBytes: Int = 64,
47  alwaysReleaseData: Boolean = true
48) extends L1CacheParameters {
49  // if sets * blockBytes > 4KB(page size),
50  // cache alias will happen,
51  // we need to avoid this by recoding additional bits in L2 cache
52  val setBytes = nSets * blockBytes
53  val aliasBitsOpt = if(setBytes > pageSize) Some(log2Ceil(setBytes / pageSize)) else None
54  val reqFields: Seq[BundleFieldBase] = Seq(
55    PrefetchField(),
56    PreferCacheField()
57  ) ++ aliasBitsOpt.map(AliasField)
58  val echoFields: Seq[BundleFieldBase] = Seq(DirtyField())
59
60  def tagCode: Code = Code.fromString(tagECC)
61
62  def dataCode: Code = Code.fromString(dataECC)
63}
64
65//           Physical Address
66// --------------------------------------
67// |   Physical Tag |  PIndex  | Offset |
68// --------------------------------------
69//                  |
70//                  DCacheTagOffset
71//
72//           Virtual Address
73// --------------------------------------
74// | Above index  | Set | Bank | Offset |
75// --------------------------------------
76//                |     |      |        |
77//                |     |      |        0
78//                |     |      DCacheBankOffset
79//                |     DCacheSetOffset
80//                DCacheAboveIndexOffset
81
82// Default DCache size = 64 sets * 8 ways * 8 banks * 8 Byte = 32K Byte
83
84trait HasDCacheParameters extends HasL1CacheParameters {
85  val cacheParams = dcacheParameters
86  val cfg = cacheParams
87
88  def encWordBits = cacheParams.dataCode.width(wordBits)
89
90  def encRowBits = encWordBits * rowWords // for DuplicatedDataArray only
91  def eccBits = encWordBits - wordBits
92
93  def lrscCycles = LRSCCycles // ISA requires 16-insn LRSC sequences to succeed
94  def lrscBackoff = 3 // disallow LRSC reacquisition briefly
95  def blockProbeAfterGrantCycles = 8 // give the processor some time to issue a request after a grant
96
97  def nSourceType = 3
98  def sourceTypeWidth = log2Up(nSourceType)
99  def LOAD_SOURCE = 0
100  def STORE_SOURCE = 1
101  def AMO_SOURCE = 2
102  def SOFT_PREFETCH = 3
103
104  // each source use a id to distinguish its multiple reqs
105  def reqIdWidth = 64
106
107  require(isPow2(cfg.nMissEntries))
108  require(isPow2(cfg.nReleaseEntries))
109  val nEntries = max(cfg.nMissEntries, cfg.nReleaseEntries) << 1
110  val releaseIdBase = max(cfg.nMissEntries, cfg.nReleaseEntries)
111
112  // banked dcache support
113  val DCacheSets = cacheParams.nSets
114  val DCacheWays = cacheParams.nWays
115  val DCacheBanks = 8
116  val DCacheSRAMRowBits = 64 // hardcoded
117  val DCacheWordBits = 64 // hardcoded
118  val DCacheWordBytes = DCacheWordBits / 8
119
120  val DCacheSizeBits = DCacheSRAMRowBits * DCacheBanks * DCacheWays * DCacheSets
121  val DCacheSizeBytes = DCacheSizeBits / 8
122  val DCacheSizeWords = DCacheSizeBits / 64 // TODO
123
124  val DCacheSameVPAddrLength = 12
125
126  val DCacheSRAMRowBytes = DCacheSRAMRowBits / 8
127  val DCacheWordOffset = log2Up(DCacheWordBytes)
128
129  val DCacheBankOffset = log2Up(DCacheSRAMRowBytes)
130  val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks)
131  val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets)
132  val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength
133  val DCacheLineOffset = DCacheSetOffset
134  val DCacheIndexOffset = DCacheBankOffset
135
136  def addr_to_dcache_bank(addr: UInt) = {
137    require(addr.getWidth >= DCacheSetOffset)
138    addr(DCacheSetOffset-1, DCacheBankOffset)
139  }
140
141  def addr_to_dcache_set(addr: UInt) = {
142    require(addr.getWidth >= DCacheAboveIndexOffset)
143    addr(DCacheAboveIndexOffset-1, DCacheSetOffset)
144  }
145
146  def get_data_of_bank(bank: Int, data: UInt) = {
147    require(data.getWidth >= (bank+1)*DCacheSRAMRowBits)
148    data(DCacheSRAMRowBits * (bank + 1) - 1, DCacheSRAMRowBits * bank)
149  }
150
151  def get_mask_of_bank(bank: Int, data: UInt) = {
152    require(data.getWidth >= (bank+1)*DCacheSRAMRowBytes)
153    data(DCacheSRAMRowBytes * (bank + 1) - 1, DCacheSRAMRowBytes * bank)
154  }
155
156  val numReplaceRespPorts = 2
157
158  require(isPow2(nSets), s"nSets($nSets) must be pow2")
159  require(isPow2(nWays), s"nWays($nWays) must be pow2")
160  require(full_divide(rowBits, wordBits), s"rowBits($rowBits) must be multiple of wordBits($wordBits)")
161  require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)")
162}
163
164abstract class DCacheModule(implicit p: Parameters) extends L1CacheModule
165  with HasDCacheParameters
166
167abstract class DCacheBundle(implicit p: Parameters) extends L1CacheBundle
168  with HasDCacheParameters
169
170class ReplacementAccessBundle(implicit p: Parameters) extends DCacheBundle {
171  val set = UInt(log2Up(nSets).W)
172  val way = UInt(log2Up(nWays).W)
173}
174
175class ReplacementWayReqIO(implicit p: Parameters) extends DCacheBundle {
176  val set = ValidIO(UInt(log2Up(nSets).W))
177  val way = Input(UInt(log2Up(nWays).W))
178}
179
180// memory request in word granularity(load, mmio, lr/sc, atomics)
181class DCacheWordReq(implicit p: Parameters)  extends DCacheBundle
182{
183  val cmd    = UInt(M_SZ.W)
184  val addr   = UInt(PAddrBits.W)
185  val data   = UInt(DataBits.W)
186  val mask   = UInt((DataBits/8).W)
187  val id     = UInt(reqIdWidth.W)
188  val instrtype   = UInt(sourceTypeWidth.W)
189  def dump() = {
190    XSDebug("DCacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
191      cmd, addr, data, mask, id)
192  }
193}
194
195// memory request in word granularity(store)
196class DCacheLineReq(implicit p: Parameters)  extends DCacheBundle
197{
198  val cmd    = UInt(M_SZ.W)
199  val vaddr  = UInt(VAddrBits.W)
200  val addr   = UInt(PAddrBits.W)
201  val data   = UInt((cfg.blockBytes * 8).W)
202  val mask   = UInt(cfg.blockBytes.W)
203  val id     = UInt(reqIdWidth.W)
204  def dump() = {
205    XSDebug("DCacheLineReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
206      cmd, addr, data, mask, id)
207  }
208  def idx: UInt = get_idx(vaddr)
209}
210
211class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq {
212  val vaddr = UInt(VAddrBits.W)
213  val wline = Bool()
214}
215
216class DCacheWordResp(implicit p: Parameters) extends DCacheBundle
217{
218  val data         = UInt(DataBits.W)
219  // cache req missed, send it to miss queue
220  val miss   = Bool()
221  // cache req nacked, replay it later
222  val miss_enter = Bool()
223  // cache miss, and enter the missqueue successfully. just for softprefetch
224  val replay = Bool()
225  val id     = UInt(reqIdWidth.W)
226  def dump() = {
227    XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n",
228      data, id, miss, replay)
229  }
230}
231
232class DCacheLineResp(implicit p: Parameters) extends DCacheBundle
233{
234  val data   = UInt((cfg.blockBytes * 8).W)
235  // cache req missed, send it to miss queue
236  val miss   = Bool()
237  // cache req nacked, replay it later
238  val replay = Bool()
239  val id     = UInt(reqIdWidth.W)
240  def dump() = {
241    XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n",
242      data, id, miss, replay)
243  }
244}
245
246class Refill(implicit p: Parameters) extends DCacheBundle
247{
248  val addr   = UInt(PAddrBits.W)
249  val data   = UInt(l1BusDataWidth.W)
250  // for debug usage
251  val data_raw = UInt((cfg.blockBytes * 8).W)
252  val hasdata = Bool()
253  val refill_done = Bool()
254  def dump() = {
255    XSDebug("Refill: addr: %x data: %x\n", addr, data)
256  }
257}
258
259class DCacheWordIO(implicit p: Parameters) extends DCacheBundle
260{
261  val req  = DecoupledIO(new DCacheWordReq)
262  val resp = Flipped(DecoupledIO(new DCacheWordResp))
263}
264
265class DCacheWordIOWithVaddr(implicit p: Parameters) extends DCacheBundle
266{
267  val req  = DecoupledIO(new DCacheWordReqWithVaddr)
268  val resp = Flipped(DecoupledIO(new DCacheWordResp))
269}
270
271// used by load unit
272class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO
273{
274  // kill previous cycle's req
275  val s1_kill  = Output(Bool())
276  val s2_kill  = Output(Bool())
277  // cycle 0: virtual address: req.addr
278  // cycle 1: physical address: s1_paddr
279  val s1_paddr = Output(UInt(PAddrBits.W))
280  val s1_hit_way = Input(UInt(nWays.W))
281  val s1_disable_fast_wakeup = Input(Bool())
282  val s1_bank_conflict = Input(Bool())
283}
284
285class DCacheLineIO(implicit p: Parameters) extends DCacheBundle
286{
287  val req  = DecoupledIO(new DCacheLineReq)
288  val resp = Flipped(DecoupledIO(new DCacheLineResp))
289}
290
291class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle {
292  // sbuffer will directly send request to dcache main pipe
293  val req = Flipped(Decoupled(new DCacheLineReq))
294
295  val main_pipe_hit_resp = ValidIO(new DCacheLineResp)
296  val refill_hit_resp = ValidIO(new DCacheLineResp)
297
298  val replay_resp = ValidIO(new DCacheLineResp)
299
300  def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp)
301}
302
303class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle {
304  val load  = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load
305  val lsq = ValidIO(new Refill)  // refill to load queue, wake up load misses
306  val store = new DCacheToSbufferIO // for sbuffer
307  val atomics  = Flipped(new DCacheWordIOWithVaddr)  // atomics reqs
308}
309
310class DCacheIO(implicit p: Parameters) extends DCacheBundle {
311  val lsu = new DCacheToLsuIO
312  val error = new L1CacheErrorInfo
313  val mshrFull = Output(Bool())
314}
315
316
317class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters {
318
319  val clientParameters = TLMasterPortParameters.v1(
320    Seq(TLMasterParameters.v1(
321      name = "dcache",
322      sourceId = IdRange(0, nEntries + 1),
323      supportsProbe = TransferSizes(cfg.blockBytes)
324    )),
325    requestFields = cacheParams.reqFields,
326    echoFields = cacheParams.echoFields
327  )
328
329  val clientNode = TLClientNode(Seq(clientParameters))
330
331  lazy val module = new DCacheImp(this)
332}
333
334
335class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters {
336
337  val io = IO(new DCacheIO)
338
339  val (bus, edge) = outer.clientNode.out.head
340  require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match")
341
342  println("DCache:")
343  println("  DCacheSets: " + DCacheSets)
344  println("  DCacheWays: " + DCacheWays)
345  println("  DCacheBanks: " + DCacheBanks)
346  println("  DCacheSRAMRowBits: " + DCacheSRAMRowBits)
347  println("  DCacheWordOffset: " + DCacheWordOffset)
348  println("  DCacheBankOffset: " + DCacheBankOffset)
349  println("  DCacheSetOffset: " + DCacheSetOffset)
350  println("  DCacheTagOffset: " + DCacheTagOffset)
351  println("  DCacheAboveIndexOffset: " + DCacheAboveIndexOffset)
352
353  //----------------------------------------
354  // core data structures
355  val bankedDataArray = Module(new BankedDataArray)
356  val metaArray = Module(new AsynchronousMetaArray(readPorts = 4, writePorts = 3))
357  val tagArray = Module(new DuplicatedTagArray(readPorts = LoadPipelineWidth + 1))
358  bankedDataArray.dump()
359
360  val errors = bankedDataArray.io.errors ++ metaArray.io.errors
361  io.error <> RegNext(Mux1H(errors.map(e => e.ecc_error.valid -> e)))
362  // assert(!io.error.ecc_error.valid)
363
364  //----------------------------------------
365  // core modules
366  val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))})
367  val atomicsReplayUnit = Module(new AtomicsReplayEntry)
368  val mainPipe   = Module(new MainPipe)
369  val refillPipe = Module(new RefillPipe)
370  val replacePipe = Module(new ReplacePipe)
371  val missQueue  = Module(new MissQueue(edge))
372  val probeQueue = Module(new ProbeQueue(edge))
373  val wb         = Module(new WritebackQueue(edge))
374
375  //----------------------------------------
376  // meta array
377  val meta_read_ports = ldu.map(_.io.meta_read) ++
378    Seq(mainPipe.io.meta_read,
379      replacePipe.io.meta_read)
380  val meta_resp_ports = ldu.map(_.io.meta_resp) ++
381    Seq(mainPipe.io.meta_resp,
382      replacePipe.io.meta_resp)
383  val meta_write_ports = Seq(
384    mainPipe.io.meta_write,
385    refillPipe.io.meta_write,
386    replacePipe.io.meta_write
387  )
388  meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p }
389  meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r }
390  meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p }
391
392  //----------------------------------------
393  // tag array
394  require(tagArray.io.read.size == (ldu.size + 1))
395  ldu.zipWithIndex.foreach {
396    case (ld, i) =>
397      tagArray.io.read(i) <> ld.io.tag_read
398      ld.io.tag_resp := tagArray.io.resp(i)
399  }
400  tagArray.io.read.last <> mainPipe.io.tag_read
401  mainPipe.io.tag_resp := tagArray.io.resp.last
402
403  val tag_write_arb = Module(new Arbiter(new TagWriteReq, 2))
404  tag_write_arb.io.in(0) <> refillPipe.io.tag_write
405  tag_write_arb.io.in(1) <> mainPipe.io.tag_write
406  tagArray.io.write <> tag_write_arb.io.out
407
408  //----------------------------------------
409  // data array
410
411  val dataReadLineArb = Module(new Arbiter(new L1BankedDataReadLineReq, 2))
412  dataReadLineArb.io.in(0) <> replacePipe.io.data_read
413  dataReadLineArb.io.in(1) <> mainPipe.io.data_read
414
415  val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 2))
416  dataWriteArb.io.in(0) <> refillPipe.io.data_write
417  dataWriteArb.io.in(1) <> mainPipe.io.data_write
418
419  bankedDataArray.io.write <> dataWriteArb.io.out
420  bankedDataArray.io.read(0) <> ldu(0).io.banked_data_read
421  bankedDataArray.io.read(1) <> ldu(1).io.banked_data_read
422  bankedDataArray.io.readline <> dataReadLineArb.io.out
423
424  ldu(0).io.banked_data_resp := bankedDataArray.io.resp
425  ldu(1).io.banked_data_resp := bankedDataArray.io.resp
426  mainPipe.io.data_resp := bankedDataArray.io.resp
427  replacePipe.io.data_resp := bankedDataArray.io.resp
428
429  ldu(0).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(0)
430  ldu(1).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(1)
431  ldu(0).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(0)
432  ldu(1).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(1)
433
434  //----------------------------------------
435  // load pipe
436  // the s1 kill signal
437  // only lsu uses this, replay never kills
438  for (w <- 0 until LoadPipelineWidth) {
439    ldu(w).io.lsu <> io.lsu.load(w)
440
441    // replay and nack not needed anymore
442    // TODO: remove replay and nack
443    ldu(w).io.nack := false.B
444
445    ldu(w).io.disable_ld_fast_wakeup :=
446      bankedDataArray.io.bank_conflict_fast(w) // load pipe fast wake up should be disabled when bank conflict
447  }
448
449  //----------------------------------------
450  // atomics
451  // atomics not finished yet
452  io.lsu.atomics <> atomicsReplayUnit.io.lsu
453  atomicsReplayUnit.io.pipe_resp := mainPipe.io.atomic_resp
454
455  //----------------------------------------
456  // miss queue
457  val MissReqPortCount = LoadPipelineWidth + 1
458  val MainPipeMissReqPort = 0
459
460  // Request
461  val missReqArb = Module(new RRArbiter(new MissReq, MissReqPortCount))
462
463  missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss
464  for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req }
465
466  wb.io.miss_req.valid := missReqArb.io.out.valid
467  wb.io.miss_req.bits  := missReqArb.io.out.bits.addr
468
469  block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req)
470
471  // refill to load queue
472  io.lsu.lsq <> missQueue.io.refill_to_ldq
473
474  // tilelink stuff
475  bus.a <> missQueue.io.mem_acquire
476  bus.e <> missQueue.io.mem_finish
477  missQueue.io.probe_addr := bus.b.bits.address
478
479  missQueue.io.main_pipe_resp := mainPipe.io.atomic_resp
480
481  //----------------------------------------
482  // probe
483  // probeQueue.io.mem_probe <> bus.b
484  block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block)
485  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
486
487  //----------------------------------------
488  // mainPipe
489//  val MainPipeReqPortCount = 4
490//  val MissMainPipeReqPort = 0
491//  val StoreMainPipeReqPort = 1
492//  val AtomicsMainPipeReqPort = 2
493//  val ProbeMainPipeReqPort = 3
494//
495//  val mainPipeReqArb = Module(new RRArbiter(new MainPipeReq, MainPipeReqPortCount))
496//  mainPipeReqArb.io.in(MissMainPipeReqPort)    <> missQueue.io.pipe_req
497//  mainPipeReqArb.io.in(StoreMainPipeReqPort)   <> io.lsu.store.pipe_req
498//  mainPipeReqArb.io.in(AtomicsMainPipeReqPort) <> atomicsReplayUnit.io.pipe_req
499//  mainPipeReqArb.io.in(ProbeMainPipeReqPort)   <> probeQueue.io.pipe_req
500//
501//  // add a stage to break the Arbiter bits.addr to ready path
502//  val mainPipeReq_valid = RegInit(false.B)
503//  val mainPipeReq_fire  = mainPipeReq_valid && mainPipe.io.req.ready
504//  val mainPipeReq_req   = RegEnable(mainPipeReqArb.io.out.bits, mainPipeReqArb.io.out.fire())
505//
506//  mainPipeReqArb.io.out.ready := mainPipeReq_fire || !mainPipeReq_valid
507//  mainPipe.io.req.valid := mainPipeReq_valid
508//  mainPipe.io.req.bits  := mainPipeReq_req
509//
510//  when (mainPipeReqArb.io.out.fire()) { mainPipeReq_valid := true.B }
511//  when (!mainPipeReqArb.io.out.fire() && mainPipeReq_fire) { mainPipeReq_valid := false.B }
512//
513//  missQueue.io.pipe_resp         <> mainPipe.io.miss_resp
514//  io.lsu.store.pipe_resp         <> mainPipe.io.store_resp
515//  atomicsReplayUnit.io.pipe_resp <> mainPipe.io.amo_resp
516//
517//  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
518//
519//  for(i <- 0 until LoadPipelineWidth) {
520//    mainPipe.io.replace_access(i) <> ldu(i).io.replace_access
521//  }
522
523  // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe,
524  // block the req in main pipe
525  val refillPipeStatus = Wire(Valid(UInt(idxBits.W)))
526  refillPipeStatus.valid := refillPipe.io.req.valid
527  refillPipeStatus.bits := refillPipe.io.req.bits.paddrWithVirtualAlias
528  val blockMainPipeReqs = Seq(
529    refillPipeStatus,
530    replacePipe.io.status.s1_set,
531    replacePipe.io.status.s2_set
532  )
533  val storeShouldBeBlocked = Cat(blockMainPipeReqs.map(r => r.valid && r.bits === io.lsu.store.req.bits.idx)).orR
534  val probeShouldBeBlocked = Cat(blockMainPipeReqs.map(r => r.valid && r.bits === get_idx(probeQueue.io.pipe_req.bits.vaddr))).orR
535
536  block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, probeShouldBeBlocked)
537  block_decoupled(io.lsu.store.req, mainPipe.io.store_req, storeShouldBeBlocked)
538
539  io.lsu.store.replay_resp := mainPipe.io.store_replay_resp
540  io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp
541
542  val mainPipeAtomicReqArb = Module(new Arbiter(new MainPipeReq, 2))
543  mainPipeAtomicReqArb.io.in(0) <> missQueue.io.main_pipe_req
544  mainPipeAtomicReqArb.io.in(1) <> atomicsReplayUnit.io.pipe_req
545  mainPipe.io.atomic_req <> mainPipeAtomicReqArb.io.out
546
547  mainPipe.io.invalid_resv_set := wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits
548
549  //----------------------------------------
550  // replace pipe
551  val mpStatus = mainPipe.io.status
552  val replaceSet = addr_to_dcache_set(missQueue.io.replace_pipe_req.bits.vaddr)
553  val replaceWayEn = missQueue.io.replace_pipe_req.bits.way_en
554  val replaceShouldBeBlocked = mpStatus.s0_set.valid && replaceSet === mpStatus.s0_set.bits ||
555    Cat(Seq(mpStatus.s1, mpStatus.s2, mpStatus.s3).map(s =>
556      s.valid && s.bits.set === replaceSet && s.bits.way_en === replaceWayEn
557    )).orR()
558  block_decoupled(missQueue.io.replace_pipe_req, replacePipe.io.req, replaceShouldBeBlocked)
559  missQueue.io.replace_pipe_resp := replacePipe.io.resp
560
561  //----------------------------------------
562  // refill pipe
563  val refillShouldBeBlocked = (mpStatus.s1.valid && mpStatus.s1.bits.set === missQueue.io.refill_pipe_req.bits.idx) ||
564	Cat(Seq(mpStatus.s2, mpStatus.s3).map(s =>
565	  s.valid &&
566        s.bits.set === missQueue.io.refill_pipe_req.bits.idx &&
567        s.bits.way_en === missQueue.io.refill_pipe_req.bits.way_en
568    )).orR
569  block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked)
570  io.lsu.store.refill_hit_resp := refillPipe.io.store_resp
571
572  //----------------------------------------
573  // wb
574  // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy
575  val wbArb = Module(new Arbiter(new WritebackReq, 2))
576  wbArb.io.in.zip(Seq(mainPipe.io.wb, replacePipe.io.wb)).foreach { case (arb, pipe) => arb <> pipe }
577  wb.io.req <> wbArb.io.out
578  bus.c     <> wb.io.mem_release
579  wb.io.release_wakeup := refillPipe.io.release_wakeup
580  wb.io.release_update := mainPipe.io.release_update
581
582  // connect bus d
583  missQueue.io.mem_grant.valid := false.B
584  missQueue.io.mem_grant.bits  := DontCare
585
586  wb.io.mem_grant.valid := false.B
587  wb.io.mem_grant.bits  := DontCare
588
589  // in L1DCache, we ony expect Grant[Data] and ReleaseAck
590  bus.d.ready := false.B
591  when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) {
592    missQueue.io.mem_grant <> bus.d
593  } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) {
594    wb.io.mem_grant <> bus.d
595  } .otherwise {
596    assert (!bus.d.fire())
597  }
598
599  //----------------------------------------
600  // replacement algorithm
601  val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets)
602
603  val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way)
604  replWayReqs.foreach{
605    case req =>
606      req.way := DontCare
607      when (req.set.valid) { req.way := replacer.way(req.set.bits) }
608  }
609
610  val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq(
611    mainPipe.io.replace_access,
612    refillPipe.io.replace_access
613  )
614  val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W))))
615  touchWays.zip(replAccessReqs).foreach {
616    case (w, req) =>
617      w.valid := req.valid
618      w.bits := req.bits.way
619  }
620  val touchSets = replAccessReqs.map(_.bits.set)
621  replacer.access(touchSets, touchWays)
622
623  //----------------------------------------
624  // assertions
625  // dcache should only deal with DRAM addresses
626  when (bus.a.fire()) {
627    assert(bus.a.bits.address >= 0x80000000L.U)
628  }
629  when (bus.b.fire()) {
630    assert(bus.b.bits.address >= 0x80000000L.U)
631  }
632  when (bus.c.fire()) {
633    assert(bus.c.bits.address >= 0x80000000L.U)
634  }
635
636  //----------------------------------------
637  // utility functions
638  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
639    sink.valid   := source.valid && !block_signal
640    source.ready := sink.ready   && !block_signal
641    sink.bits    := source.bits
642  }
643
644  //----------------------------------------
645  // performance counters
646  val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire()))
647  XSPerfAccumulate("num_loads", num_loads)
648
649  io.mshrFull := missQueue.io.full
650
651  // performance counter
652  val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType))
653  val st_access = Wire(ld_access.last.cloneType)
654  ld_access.zip(ldu).foreach {
655    case (a, u) =>
656      a.valid := RegNext(u.io.lsu.req.fire()) && !u.io.lsu.s1_kill
657      a.bits.idx := RegNext(get_idx(u.io.lsu.req.bits.addr))
658      a.bits.tag := get_tag(u.io.lsu.s1_paddr)
659  }
660  st_access.valid := RegNext(mainPipe.io.store_req.fire())
661  st_access.bits.idx := RegNext(get_idx(mainPipe.io.store_req.bits.vaddr))
662  st_access.bits.tag := RegNext(get_tag(mainPipe.io.store_req.bits.addr))
663  val access_info = ld_access.toSeq ++ Seq(st_access)
664  val early_replace = RegNext(missQueue.io.debug_early_replace)
665  val access_early_replace = access_info.map {
666    case acc =>
667      Cat(early_replace.map {
668        case r =>
669          acc.valid && r.valid &&
670            acc.bits.tag === r.bits.tag &&
671            acc.bits.idx === r.bits.idx
672      })
673  }
674  XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace)))
675}
676
677class AMOHelper() extends ExtModule {
678  val clock  = IO(Input(Clock()))
679  val enable = IO(Input(Bool()))
680  val cmd    = IO(Input(UInt(5.W)))
681  val addr   = IO(Input(UInt(64.W)))
682  val wdata  = IO(Input(UInt(64.W)))
683  val mask   = IO(Input(UInt(8.W)))
684  val rdata  = IO(Output(UInt(64.W)))
685}
686
687
688class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
689
690  val useDcache = coreParams.dcacheParametersOpt.nonEmpty
691  val clientNode = if (useDcache) TLIdentityNode() else null
692  val dcache = if (useDcache) LazyModule(new DCache()) else null
693  if (useDcache) {
694    clientNode := dcache.clientNode
695  }
696
697  lazy val module = new LazyModuleImp(this) {
698    val io = IO(new DCacheIO)
699    if (!useDcache) {
700      // a fake dcache which uses dpi-c to access memory, only for debug usage!
701      val fake_dcache = Module(new FakeDCache())
702      io <> fake_dcache.io
703    }
704    else {
705      io <> dcache.module.io
706    }
707  }
708}
709