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