xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/DCacheWrapper.scala (revision 068bf978a62360db6c16671704497c3e01d6843f)
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  // cache req missed, send it to miss queue
262  val miss   = Bool()
263  // cache req nacked, replay it later
264  val miss_enter = Bool()
265  // cache miss, and enter the missqueue successfully. just for softprefetch
266  val replay = Bool()
267  val id     = UInt(reqIdWidth.W)
268  def dump() = {
269    XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n",
270      data, id, miss, replay)
271  }
272}
273
274class DCacheLineResp(implicit p: Parameters) extends DCacheBundle
275{
276  val data   = UInt((cfg.blockBytes * 8).W)
277  // cache req missed, send it to miss queue
278  val miss   = Bool()
279  // cache req nacked, replay it later
280  val replay = Bool()
281  val id     = UInt(reqIdWidth.W)
282  def dump() = {
283    XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n",
284      data, id, miss, replay)
285  }
286}
287
288class Refill(implicit p: Parameters) extends DCacheBundle
289{
290  val addr   = UInt(PAddrBits.W)
291  val data   = UInt(l1BusDataWidth.W)
292  // for debug usage
293  val data_raw = UInt((cfg.blockBytes * 8).W)
294  val hasdata = Bool()
295  val refill_done = Bool()
296  def dump() = {
297    XSDebug("Refill: addr: %x data: %x\n", addr, data)
298  }
299}
300
301class Release(implicit p: Parameters) extends DCacheBundle
302{
303  val paddr  = UInt(PAddrBits.W)
304  def dump() = {
305    XSDebug("Release: paddr: %x\n", paddr(PAddrBits-1, DCacheTagOffset))
306  }
307}
308
309class DCacheWordIO(implicit p: Parameters) extends DCacheBundle
310{
311  val req  = DecoupledIO(new DCacheWordReq)
312  val resp = Flipped(DecoupledIO(new DCacheWordResp))
313}
314
315class DCacheWordIOWithVaddr(implicit p: Parameters) extends DCacheBundle
316{
317  val req  = DecoupledIO(new DCacheWordReqWithVaddr)
318  val resp = Flipped(DecoupledIO(new DCacheWordResp))
319}
320
321// used by load unit
322class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO
323{
324  // kill previous cycle's req
325  val s1_kill  = Output(Bool())
326  val s2_kill  = Output(Bool())
327  // cycle 0: virtual address: req.addr
328  // cycle 1: physical address: s1_paddr
329  val s1_paddr = Output(UInt(PAddrBits.W))
330  val s1_hit_way = Input(UInt(nWays.W))
331  val s1_disable_fast_wakeup = Input(Bool())
332  val s1_bank_conflict = Input(Bool())
333}
334
335class DCacheLineIO(implicit p: Parameters) extends DCacheBundle
336{
337  val req  = DecoupledIO(new DCacheLineReq)
338  val resp = Flipped(DecoupledIO(new DCacheLineResp))
339}
340
341class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle {
342  // sbuffer will directly send request to dcache main pipe
343  val req = Flipped(Decoupled(new DCacheLineReq))
344
345  val main_pipe_hit_resp = ValidIO(new DCacheLineResp)
346  val refill_hit_resp = ValidIO(new DCacheLineResp)
347
348  val replay_resp = ValidIO(new DCacheLineResp)
349
350  def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp)
351}
352
353class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle {
354  val load  = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load
355  val lsq = ValidIO(new Refill)  // refill to load queue, wake up load misses
356  val store = new DCacheToSbufferIO // for sbuffer
357  val atomics  = Flipped(new DCacheWordIOWithVaddr)  // atomics reqs
358  val release = ValidIO(new Release) // cacheline release hint for ld-ld violation check
359}
360
361class DCacheIO(implicit p: Parameters) extends DCacheBundle {
362  val hartId = Input(UInt(8.W))
363  val lsu = new DCacheToLsuIO
364  val csr = new L1CacheToCsrIO
365  val error = new L1CacheErrorInfo
366  val mshrFull = Output(Bool())
367}
368
369
370class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters {
371
372  val clientParameters = TLMasterPortParameters.v1(
373    Seq(TLMasterParameters.v1(
374      name = "dcache",
375      sourceId = IdRange(0, nEntries + 1),
376      supportsProbe = TransferSizes(cfg.blockBytes)
377    )),
378    requestFields = cacheParams.reqFields,
379    echoFields = cacheParams.echoFields
380  )
381
382  val clientNode = TLClientNode(Seq(clientParameters))
383
384  lazy val module = new DCacheImp(this)
385}
386
387
388class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters with HasPerfEvents {
389
390  val io = IO(new DCacheIO)
391
392  val (bus, edge) = outer.clientNode.out.head
393  require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match")
394
395  println("DCache:")
396  println("  DCacheSets: " + DCacheSets)
397  println("  DCacheWays: " + DCacheWays)
398  println("  DCacheBanks: " + DCacheBanks)
399  println("  DCacheSRAMRowBits: " + DCacheSRAMRowBits)
400  println("  DCacheWordOffset: " + DCacheWordOffset)
401  println("  DCacheBankOffset: " + DCacheBankOffset)
402  println("  DCacheSetOffset: " + DCacheSetOffset)
403  println("  DCacheTagOffset: " + DCacheTagOffset)
404  println("  DCacheAboveIndexOffset: " + DCacheAboveIndexOffset)
405
406  //----------------------------------------
407  // core data structures
408  val bankedDataArray = Module(new BankedDataArray)
409  val metaArray = Module(new AsynchronousMetaArray(readPorts = 3, writePorts = 2))
410  val tagArray = Module(new DuplicatedTagArray(readPorts = LoadPipelineWidth + 1))
411  bankedDataArray.dump()
412
413  val errors = bankedDataArray.io.errors ++ metaArray.io.errors
414  io.error <> RegNext(Mux1H(errors.map(e => e.ecc_error.valid -> e)))
415  // assert(!io.error.ecc_error.valid)
416
417  //----------------------------------------
418  // core modules
419  val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))})
420  val atomicsReplayUnit = Module(new AtomicsReplayEntry)
421  val mainPipe   = Module(new MainPipe)
422  val refillPipe = Module(new RefillPipe)
423//  val replacePipe = Module(new ReplacePipe)
424  val missQueue  = Module(new MissQueue(edge))
425  val probeQueue = Module(new ProbeQueue(edge))
426  val wb         = Module(new WritebackQueue(edge))
427
428  missQueue.io.hartId := io.hartId
429
430  //----------------------------------------
431  // meta array
432  val meta_read_ports = ldu.map(_.io.meta_read) ++
433    Seq(mainPipe.io.meta_read/*,
434      replacePipe.io.meta_read*/)
435  val meta_resp_ports = ldu.map(_.io.meta_resp) ++
436    Seq(mainPipe.io.meta_resp/*,
437      replacePipe.io.meta_resp*/)
438  val meta_write_ports = Seq(
439    mainPipe.io.meta_write,
440    refillPipe.io.meta_write/*,
441    replacePipe.io.meta_write*/
442  )
443  meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p }
444  meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r }
445  meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p }
446
447  //----------------------------------------
448  // tag array
449  require(tagArray.io.read.size == (ldu.size + 1))
450  ldu.zipWithIndex.foreach {
451    case (ld, i) =>
452      tagArray.io.read(i) <> ld.io.tag_read
453      ld.io.tag_resp := tagArray.io.resp(i)
454  }
455  tagArray.io.read.last <> mainPipe.io.tag_read
456  mainPipe.io.tag_resp := tagArray.io.resp.last
457
458  val tag_write_arb = Module(new Arbiter(new TagWriteReq, 2))
459  tag_write_arb.io.in(0) <> refillPipe.io.tag_write
460  tag_write_arb.io.in(1) <> mainPipe.io.tag_write
461  tagArray.io.write <> tag_write_arb.io.out
462
463  //----------------------------------------
464  // data array
465
466//  val dataReadLineArb = Module(new Arbiter(new L1BankedDataReadLineReq, 2))
467//  dataReadLineArb.io.in(0) <> replacePipe.io.data_read
468//  dataReadLineArb.io.in(1) <> mainPipe.io.data_read
469
470  val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 2))
471  dataWriteArb.io.in(0) <> refillPipe.io.data_write
472  dataWriteArb.io.in(1) <> mainPipe.io.data_write
473
474  bankedDataArray.io.write <> dataWriteArb.io.out
475  bankedDataArray.io.read(0) <> ldu(0).io.banked_data_read
476  bankedDataArray.io.read(1) <> ldu(1).io.banked_data_read
477  bankedDataArray.io.readline <> mainPipe.io.data_read
478
479  ldu(0).io.banked_data_resp := bankedDataArray.io.resp
480  ldu(1).io.banked_data_resp := bankedDataArray.io.resp
481  mainPipe.io.data_resp := bankedDataArray.io.resp
482//  replacePipe.io.data_resp := bankedDataArray.io.resp
483
484  ldu(0).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(0)
485  ldu(1).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(1)
486  ldu(0).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(0)
487  ldu(1).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(1)
488
489  //----------------------------------------
490  // load pipe
491  // the s1 kill signal
492  // only lsu uses this, replay never kills
493  for (w <- 0 until LoadPipelineWidth) {
494    ldu(w).io.lsu <> io.lsu.load(w)
495
496    // replay and nack not needed anymore
497    // TODO: remove replay and nack
498    ldu(w).io.nack := false.B
499
500    ldu(w).io.disable_ld_fast_wakeup :=
501      bankedDataArray.io.bank_conflict_fast(w) // load pipe fast wake up should be disabled when bank conflict
502  }
503
504  //----------------------------------------
505  // atomics
506  // atomics not finished yet
507  io.lsu.atomics <> atomicsReplayUnit.io.lsu
508  atomicsReplayUnit.io.pipe_resp := RegNext(mainPipe.io.atomic_resp)
509
510  //----------------------------------------
511  // miss queue
512  val MissReqPortCount = LoadPipelineWidth + 1
513  val MainPipeMissReqPort = 0
514
515  // Request
516  val missReqArb = Module(new Arbiter(new MissReq, MissReqPortCount))
517
518  missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req
519  for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req }
520
521  wb.io.miss_req.valid := missReqArb.io.out.valid
522  wb.io.miss_req.bits  := missReqArb.io.out.bits.addr
523
524  // block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req)
525  missReqArb.io.out <> missQueue.io.req
526  when(wb.io.block_miss_req) {
527    missQueue.io.req.bits.cancel := true.B
528    missReqArb.io.out.ready := false.B
529  }
530
531  // refill to load queue
532  io.lsu.lsq <> missQueue.io.refill_to_ldq
533
534  // tilelink stuff
535  bus.a <> missQueue.io.mem_acquire
536  bus.e <> missQueue.io.mem_finish
537  missQueue.io.probe_addr := bus.b.bits.address
538
539  missQueue.io.main_pipe_resp := RegNext(mainPipe.io.atomic_resp)
540
541  //----------------------------------------
542  // probe
543  // probeQueue.io.mem_probe <> bus.b
544  block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block)
545  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
546  probeQueue.io.update_resv_set <> mainPipe.io.update_resv_set
547
548  //----------------------------------------
549  // mainPipe
550  // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe,
551  // block the req in main pipe
552  block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, refillPipe.io.req.valid)
553  block_decoupled(io.lsu.store.req, mainPipe.io.store_req, refillPipe.io.req.valid)
554
555  io.lsu.store.replay_resp := RegNext(mainPipe.io.store_replay_resp)
556  io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp
557
558  val mainPipeAtomicReqArb = Module(new Arbiter(new MainPipeReq, 2))
559  mainPipeAtomicReqArb.io.in(0) <> missQueue.io.main_pipe_req
560  mainPipeAtomicReqArb.io.in(1) <> atomicsReplayUnit.io.pipe_req
561  mainPipe.io.atomic_req <> mainPipeAtomicReqArb.io.out
562
563  mainPipe.io.invalid_resv_set := RegNext(wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits)
564
565  //----------------------------------------
566  // replace (main pipe)
567  val mpStatus = mainPipe.io.status
568  mainPipe.io.replace_req <> missQueue.io.replace_pipe_req
569  missQueue.io.replace_pipe_resp := mainPipe.io.replace_resp
570
571  //----------------------------------------
572  // refill pipe
573  val refillShouldBeBlocked = (mpStatus.s1.valid && mpStatus.s1.bits.set === missQueue.io.refill_pipe_req.bits.idx) ||
574    Cat(Seq(mpStatus.s2, mpStatus.s3).map(s =>
575      s.valid &&
576        s.bits.set === missQueue.io.refill_pipe_req.bits.idx &&
577        s.bits.way_en === missQueue.io.refill_pipe_req.bits.way_en
578    )).orR
579  block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked)
580  missQueue.io.refill_pipe_resp := refillPipe.io.resp
581  io.lsu.store.refill_hit_resp := RegNext(refillPipe.io.store_resp)
582
583  //----------------------------------------
584  // wb
585  // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy
586//  val wbArb = Module(new Arbiter(new WritebackReq, 2))
587//  wbArb.io.in.zip(Seq(mainPipe.io.wb, replacePipe.io.wb)).foreach { case (arb, pipe) => arb <> pipe }
588  wb.io.req <> mainPipe.io.wb
589  bus.c     <> wb.io.mem_release
590  wb.io.release_wakeup := refillPipe.io.release_wakeup
591  wb.io.release_update := mainPipe.io.release_update
592  io.lsu.release.valid := RegNext(bus.c.fire())
593  io.lsu.release.bits.paddr := RegNext(bus.c.bits.address)
594
595  // connect bus d
596  missQueue.io.mem_grant.valid := false.B
597  missQueue.io.mem_grant.bits  := DontCare
598
599  wb.io.mem_grant.valid := false.B
600  wb.io.mem_grant.bits  := DontCare
601
602  // in L1DCache, we ony expect Grant[Data] and ReleaseAck
603  bus.d.ready := false.B
604  when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) {
605    missQueue.io.mem_grant <> bus.d
606  } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) {
607    wb.io.mem_grant <> bus.d
608  } .otherwise {
609    assert (!bus.d.fire())
610  }
611
612  //----------------------------------------
613  // replacement algorithm
614  val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets)
615
616  val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way)
617  replWayReqs.foreach{
618    case req =>
619      req.way := DontCare
620      when (req.set.valid) { req.way := replacer.way(req.set.bits) }
621  }
622
623  val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq(
624    mainPipe.io.replace_access,
625    refillPipe.io.replace_access
626  )
627  val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W))))
628  touchWays.zip(replAccessReqs).foreach {
629    case (w, req) =>
630      w.valid := req.valid
631      w.bits := req.bits.way
632  }
633  val touchSets = replAccessReqs.map(_.bits.set)
634  replacer.access(touchSets, touchWays)
635
636  //----------------------------------------
637  // assertions
638  // dcache should only deal with DRAM addresses
639  when (bus.a.fire()) {
640    assert(bus.a.bits.address >= 0x80000000L.U)
641  }
642  when (bus.b.fire()) {
643    assert(bus.b.bits.address >= 0x80000000L.U)
644  }
645  when (bus.c.fire()) {
646    assert(bus.c.bits.address >= 0x80000000L.U)
647  }
648
649  //----------------------------------------
650  // utility functions
651  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
652    sink.valid   := source.valid && !block_signal
653    source.ready := sink.ready   && !block_signal
654    sink.bits    := source.bits
655  }
656
657  //----------------------------------------
658  // Customized csr cache op support
659  val cacheOpDecoder = Module(new CSRCacheOpDecoder("dcache", CacheInstrucion.COP_ID_DCACHE))
660  cacheOpDecoder.io.csr <> io.csr
661  bankedDataArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
662  metaArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
663  tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
664  cacheOpDecoder.io.cache.resp.valid := bankedDataArray.io.cacheOp.resp.valid ||
665    metaArray.io.cacheOp.resp.valid ||
666    tagArray.io.cacheOp.resp.valid
667  cacheOpDecoder.io.cache.resp.bits := Mux1H(List(
668    bankedDataArray.io.cacheOp.resp.valid -> bankedDataArray.io.cacheOp.resp.bits,
669    metaArray.io.cacheOp.resp.valid -> metaArray.io.cacheOp.resp.bits,
670    tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits,
671  ))
672  assert(!((bankedDataArray.io.cacheOp.resp.valid +& metaArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U))
673
674  //----------------------------------------
675  // performance counters
676  val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire()))
677  XSPerfAccumulate("num_loads", num_loads)
678
679  io.mshrFull := missQueue.io.full
680
681  // performance counter
682  val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType))
683  val st_access = Wire(ld_access.last.cloneType)
684  ld_access.zip(ldu).foreach {
685    case (a, u) =>
686      a.valid := RegNext(u.io.lsu.req.fire()) && !u.io.lsu.s1_kill
687      a.bits.idx := RegNext(get_idx(u.io.lsu.req.bits.addr))
688      a.bits.tag := get_tag(u.io.lsu.s1_paddr)
689  }
690  st_access.valid := RegNext(mainPipe.io.store_req.fire())
691  st_access.bits.idx := RegNext(get_idx(mainPipe.io.store_req.bits.vaddr))
692  st_access.bits.tag := RegNext(get_tag(mainPipe.io.store_req.bits.addr))
693  val access_info = ld_access.toSeq ++ Seq(st_access)
694  val early_replace = RegNext(missQueue.io.debug_early_replace)
695  val access_early_replace = access_info.map {
696    case acc =>
697      Cat(early_replace.map {
698        case r =>
699          acc.valid && r.valid &&
700            acc.bits.tag === r.bits.tag &&
701            acc.bits.idx === r.bits.idx
702      })
703  }
704  XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace)))
705
706  val perfEvents = (Seq(wb, mainPipe, missQueue, probeQueue) ++ ldu).flatMap(_.getPerfEvents)
707  generatePerfEvent()
708}
709
710class AMOHelper() extends ExtModule {
711  val clock  = IO(Input(Clock()))
712  val enable = IO(Input(Bool()))
713  val cmd    = IO(Input(UInt(5.W)))
714  val addr   = IO(Input(UInt(64.W)))
715  val wdata  = IO(Input(UInt(64.W)))
716  val mask   = IO(Input(UInt(8.W)))
717  val rdata  = IO(Output(UInt(64.W)))
718}
719
720class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
721
722  val useDcache = coreParams.dcacheParametersOpt.nonEmpty
723  val clientNode = if (useDcache) TLIdentityNode() else null
724  val dcache = if (useDcache) LazyModule(new DCache()) else null
725  if (useDcache) {
726    clientNode := dcache.clientNode
727  }
728
729  lazy val module = new LazyModuleImp(this) with HasPerfEvents {
730    val io = IO(new DCacheIO)
731    val perfEvents = if (!useDcache) {
732      // a fake dcache which uses dpi-c to access memory, only for debug usage!
733      val fake_dcache = Module(new FakeDCache())
734      io <> fake_dcache.io
735      Seq()
736    }
737    else {
738      io <> dcache.module.io
739      dcache.module.getPerfEvents
740    }
741    generatePerfEvent()
742  }
743}
744