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