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