xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/DCacheWrapper.scala (revision 3f4ec46f46b3a5024eb568d3ccfcddaba3befd49)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.cache
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.experimental.ExtModule
22import chisel3.util._
23import xiangshan._
24import utils._
25import freechips.rocketchip.diplomacy.{IdRange, LazyModule, LazyModuleImp, TransferSizes}
26import freechips.rocketchip.tilelink._
27import freechips.rocketchip.util.BundleFieldBase
28import system.L1CacheErrorInfo
29import device.RAMHelper
30import huancun.{AliasField, AliasKey, PreferCacheField, PrefetchField, DirtyField}
31
32// DCache specific parameters
33case class DCacheParameters
34(
35  nSets: Int = 256,
36  nWays: Int = 8,
37  rowBits: Int = 128,
38  tagECC: Option[String] = None,
39  dataECC: Option[String] = None,
40  replacer: Option[String] = Some("random"),
41  nMissEntries: Int = 1,
42  nProbeEntries: Int = 1,
43  nReleaseEntries: Int = 1,
44  nStoreReplayEntries: 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//                |     |      |        DCacheWordOffset
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 lrscCycles = LRSCCycles // ISA requires 16-insn LRSC sequences to succeed
95  def lrscBackoff = 3 // disallow LRSC reacquisition briefly
96  def blockProbeAfterGrantCycles = 8 // give the processor some time to issue a request after a grant
97
98  def nSourceType = 3
99  def sourceTypeWidth = log2Up(nSourceType)
100  def LOAD_SOURCE = 0
101  def STORE_SOURCE = 1
102  def AMO_SOURCE = 2
103  def SOFT_PREFETCH = 3
104
105  // each source use a id to distinguish its multiple reqs
106  def reqIdWidth = 64
107
108  // banked dcache support
109  val DCacheSets = cacheParams.nSets
110  val DCacheWays = cacheParams.nWays
111  val DCacheBanks = 8
112  val DCacheSRAMRowBits = 64 // hardcoded
113
114  val DCacheLineBits = DCacheSRAMRowBits * DCacheBanks * DCacheWays * DCacheSets
115  val DCacheLineBytes = DCacheLineBits / 8
116  val DCacheLineWords = DCacheLineBits / 64 // TODO
117
118  val DCacheSameVPAddrLength = 12
119
120  val DCacheSRAMRowBytes = DCacheSRAMRowBits / 8
121  val DCacheWordOffset = 0
122  val DCacheBankOffset = DCacheWordOffset + log2Up(DCacheSRAMRowBytes)
123  val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks)
124  val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets)
125  val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength
126  val DCacheIndexOffset = DCacheBankOffset
127
128  def addr_to_dcache_bank(addr: UInt) = {
129    require(addr.getWidth >= DCacheSetOffset)
130    addr(DCacheSetOffset-1, DCacheBankOffset)
131  }
132
133  def addr_to_dcache_set(addr: UInt) = {
134    require(addr.getWidth >= DCacheAboveIndexOffset)
135    addr(DCacheAboveIndexOffset-1, DCacheSetOffset)
136  }
137
138  def get_data_of_bank(bank: Int, data: UInt) = {
139    require(data.getWidth >= (bank+1)*DCacheSRAMRowBits)
140    data(DCacheSRAMRowBits * (bank + 1) - 1, DCacheSRAMRowBits * bank)
141  }
142
143  def get_mask_of_bank(bank: Int, data: UInt) = {
144    require(data.getWidth >= (bank+1)*DCacheSRAMRowBytes)
145    data(DCacheSRAMRowBytes * (bank + 1) - 1, DCacheSRAMRowBytes * bank)
146  }
147
148  require(isPow2(nSets), s"nSets($nSets) must be pow2")
149  require(isPow2(nWays), s"nWays($nWays) must be pow2")
150  require(full_divide(rowBits, wordBits), s"rowBits($rowBits) must be multiple of wordBits($wordBits)")
151  require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)")
152}
153
154abstract class DCacheModule(implicit p: Parameters) extends L1CacheModule
155  with HasDCacheParameters
156
157abstract class DCacheBundle(implicit p: Parameters) extends L1CacheBundle
158  with HasDCacheParameters
159
160class ReplacementAccessBundle(implicit p: Parameters) extends DCacheBundle {
161  val set = UInt(log2Up(nSets).W)
162  val way = UInt(log2Up(nWays).W)
163}
164
165// memory request in word granularity(load, mmio, lr/sc, atomics)
166class DCacheWordReq(implicit p: Parameters)  extends DCacheBundle
167{
168  val cmd    = UInt(M_SZ.W)
169  val addr   = UInt(PAddrBits.W)
170  val data   = UInt(DataBits.W)
171  val mask   = UInt((DataBits/8).W)
172  val id     = UInt(reqIdWidth.W)
173  val instrtype   = UInt(sourceTypeWidth.W)
174  def dump() = {
175    XSDebug("DCacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
176      cmd, addr, data, mask, id)
177  }
178}
179
180// memory request in word granularity(store)
181class DCacheLineReq(implicit p: Parameters)  extends DCacheBundle
182{
183  val cmd    = UInt(M_SZ.W)
184  val vaddr  = UInt(VAddrBits.W)
185  val addr   = UInt(PAddrBits.W)
186  val data   = UInt((cfg.blockBytes * 8).W)
187  val mask   = UInt(cfg.blockBytes.W)
188  val id     = UInt(reqIdWidth.W)
189  def dump() = {
190    XSDebug("DCacheLineReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
191      cmd, addr, data, mask, id)
192  }
193}
194
195class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq {
196  val vaddr = UInt(VAddrBits.W)
197}
198
199class DCacheWordResp(implicit p: Parameters) extends DCacheBundle
200{
201  val data         = UInt(DataBits.W)
202  // cache req missed, send it to miss queue
203  val miss   = Bool()
204  // cache req nacked, replay it later
205  val miss_enter = Bool()
206  // cache miss, and enter the missqueue successfully. just for softprefetch
207  val replay = Bool()
208  val id     = UInt(reqIdWidth.W)
209  def dump() = {
210    XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n",
211      data, id, miss, replay)
212  }
213}
214
215class DCacheLineResp(implicit p: Parameters) extends DCacheBundle
216{
217  val data   = UInt((cfg.blockBytes * 8).W)
218  // cache req missed, send it to miss queue
219  val miss   = Bool()
220  // cache req nacked, replay it later
221  val replay = Bool()
222  val id     = UInt(reqIdWidth.W)
223  def dump() = {
224    XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n",
225      data, id, miss, replay)
226  }
227}
228
229class Refill(implicit p: Parameters) extends DCacheBundle
230{
231  val addr   = UInt(PAddrBits.W)
232  val data   = UInt(l1BusDataWidth.W)
233  // for debug usage
234  val data_raw = UInt((cfg.blockBytes * 8).W)
235  val hasdata = Bool()
236  val refill_done = Bool()
237  def dump() = {
238    XSDebug("Refill: addr: %x data: %x\n", addr, data)
239  }
240}
241
242class DCacheWordIO(implicit p: Parameters) extends DCacheBundle
243{
244  val req  = DecoupledIO(new DCacheWordReq)
245  val resp = Flipped(DecoupledIO(new DCacheWordResp))
246}
247
248class DCacheWordIOWithVaddr(implicit p: Parameters) extends DCacheBundle
249{
250  val req  = DecoupledIO(new DCacheWordReqWithVaddr)
251  val resp = Flipped(DecoupledIO(new DCacheWordResp))
252}
253
254// used by load unit
255class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO
256{
257  // kill previous cycle's req
258  val s1_kill  = Output(Bool())
259  // cycle 0: virtual address: req.addr
260  // cycle 1: physical address: s1_paddr
261  val s1_paddr = Output(UInt(PAddrBits.W))
262  val s1_hit_way = Input(UInt(nWays.W))
263  val s1_disable_fast_wakeup = Input(Bool())
264}
265
266class DCacheLineIO(implicit p: Parameters) extends DCacheBundle
267{
268  val req  = DecoupledIO(new DCacheLineReq)
269  val resp = Flipped(DecoupledIO(new DCacheLineResp))
270}
271
272class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle {
273  val load  = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load
274  val lsq = ValidIO(new Refill)  // refill to load queue, wake up load misses
275  val store = Flipped(new DCacheLineIO) // for sbuffer
276  val atomics  = Flipped(new DCacheWordIOWithVaddr)  // atomics reqs
277}
278
279class DCacheIO(implicit p: Parameters) extends DCacheBundle {
280  val lsu = new DCacheToLsuIO
281  val error = new L1CacheErrorInfo
282  val mshrFull = Output(Bool())
283}
284
285
286class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters {
287
288  val clientParameters = TLMasterPortParameters.v1(
289    Seq(TLMasterParameters.v1(
290      name = "dcache",
291      sourceId = IdRange(0, cfg.nMissEntries+1),
292      supportsProbe = TransferSizes(cfg.blockBytes)
293    )),
294    requestFields = cacheParams.reqFields,
295    echoFields = cacheParams.echoFields
296  )
297
298  val clientNode = TLClientNode(Seq(clientParameters))
299
300  lazy val module = new DCacheImp(this)
301}
302
303
304class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters {
305
306  val io = IO(new DCacheIO)
307
308  val (bus, edge) = outer.clientNode.out.head
309  require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match")
310
311  println("DCache:")
312  println("  DCacheSets: " + DCacheSets)
313  println("  DCacheWays: " + DCacheWays)
314  println("  DCacheBanks: " + DCacheBanks)
315  println("  DCacheSRAMRowBits: " + DCacheSRAMRowBits)
316  println("  DCacheWordOffset: " + DCacheWordOffset)
317  println("  DCacheBankOffset: " + DCacheBankOffset)
318  println("  DCacheSetOffset: " + DCacheSetOffset)
319  println("  DCacheTagOffset: " + DCacheTagOffset)
320  println("  DCacheAboveIndexOffset: " + DCacheAboveIndexOffset)
321
322  //----------------------------------------
323  // core data structures
324  val bankedDataArray = Module(new BankedDataArray)
325  val metaArray = Module(new DuplicatedMetaArray(numReadPorts = 3))
326  bankedDataArray.dump()
327
328  val errors = bankedDataArray.io.errors ++ metaArray.io.errors
329  io.error <> RegNext(Mux1H(errors.map(e => e.ecc_error.valid -> e)))
330  // assert(!io.error.ecc_error.valid)
331
332  //----------------------------------------
333  // core modules
334  val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))})
335  val storeReplayUnit = Module(new StoreReplayQueue)
336  val atomicsReplayUnit = Module(new AtomicsReplayEntry)
337
338  val mainPipe   = Module(new MainPipe)
339  val missQueue  = Module(new MissQueue(edge))
340  val probeQueue = Module(new ProbeQueue(edge))
341  val wb         = Module(new WritebackQueue(edge))
342
343
344  //----------------------------------------
345  // meta array
346  val MetaWritePortCount = 1
347  val MainPipeMetaWritePort = 0
348  metaArray.io.write <> mainPipe.io.meta_write
349
350  // MainPipe contend MetaRead with Load 0
351  // give priority to MainPipe
352  val MetaReadPortCount = 2
353  val MainPipeMetaReadPort = 0
354  val LoadPipeMetaReadPort = 1
355
356  metaArray.io.read(LoadPipelineWidth) <> mainPipe.io.meta_read
357  mainPipe.io.meta_resp <> metaArray.io.resp(LoadPipelineWidth)
358
359  for (w <- 0 until LoadPipelineWidth) {
360    metaArray.io.read(w) <> ldu(w).io.meta_read
361    ldu(w).io.meta_resp <> metaArray.io.resp(w)
362  }
363
364  //----------------------------------------
365  // data array
366
367  bankedDataArray.io.write <> mainPipe.io.banked_data_write
368  bankedDataArray.io.read(0) <> ldu(0).io.banked_data_read
369  bankedDataArray.io.read(1) <> ldu(1).io.banked_data_read
370  bankedDataArray.io.readline <> mainPipe.io.banked_data_read
371
372  ldu(0).io.banked_data_resp := bankedDataArray.io.resp
373  ldu(1).io.banked_data_resp := bankedDataArray.io.resp
374  mainPipe.io.banked_data_resp := bankedDataArray.io.resp
375
376  ldu(0).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(0)
377  ldu(1).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(1)
378  ldu(0).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(0)
379  ldu(1).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(1)
380
381  //----------------------------------------
382  // load pipe
383  // the s1 kill signal
384  // only lsu uses this, replay never kills
385  for (w <- 0 until LoadPipelineWidth) {
386    ldu(w).io.lsu <> io.lsu.load(w)
387
388    // replay and nack not needed anymore
389    // TODO: remove replay and nack
390    ldu(w).io.nack := false.B
391
392    ldu(w).io.disable_ld_fast_wakeup :=
393      mainPipe.io.disable_ld_fast_wakeup(w) ||
394      bankedDataArray.io.bank_conflict_fast(w) // load pipe fast wake up should be disabled when bank conflict
395  }
396
397  //----------------------------------------
398  // store pipe and store miss queue
399  storeReplayUnit.io.lsu    <> io.lsu.store
400
401  //----------------------------------------
402  // atomics
403  // atomics not finished yet
404  io.lsu.atomics <> atomicsReplayUnit.io.lsu
405
406  //----------------------------------------
407  // miss queue
408  val MissReqPortCount = LoadPipelineWidth + 1
409  val MainPipeMissReqPort = 0
410
411  // Request
412  val missReqArb = Module(new RRArbiter(new MissReq, MissReqPortCount))
413
414  missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req
415  for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req }
416
417  wb.io.miss_req.valid := missReqArb.io.out.valid
418  wb.io.miss_req.bits  := missReqArb.io.out.bits.addr
419
420  block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req)
421
422  // refill to load queue
423  io.lsu.lsq <> missQueue.io.refill
424
425  // tilelink stuff
426  bus.a <> missQueue.io.mem_acquire
427  bus.e <> missQueue.io.mem_finish
428  missQueue.io.probe_req := bus.b.bits.address
429
430  //----------------------------------------
431  // probe
432  // probeQueue.io.mem_probe <> bus.b
433  block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block)
434
435  //----------------------------------------
436  // mainPipe
437  val MainPipeReqPortCount = 4
438  val MissMainPipeReqPort = 0
439  val StoreMainPipeReqPort = 1
440  val AtomicsMainPipeReqPort = 2
441  val ProbeMainPipeReqPort = 3
442
443  val mainPipeReqArb = Module(new RRArbiter(new MainPipeReq, MainPipeReqPortCount))
444  mainPipeReqArb.io.in(MissMainPipeReqPort)    <> missQueue.io.pipe_req
445  mainPipeReqArb.io.in(StoreMainPipeReqPort)   <> storeReplayUnit.io.pipe_req
446  mainPipeReqArb.io.in(AtomicsMainPipeReqPort) <> atomicsReplayUnit.io.pipe_req
447  mainPipeReqArb.io.in(ProbeMainPipeReqPort)   <> probeQueue.io.pipe_req
448
449  // add a stage to break the Arbiter bits.addr to ready path
450  val mainPipeReq_valid = RegInit(false.B)
451  val mainPipeReq_fire  = mainPipeReq_valid && mainPipe.io.req.ready
452  val mainPipeReq_req   = RegEnable(mainPipeReqArb.io.out.bits, mainPipeReqArb.io.out.fire())
453
454  mainPipeReqArb.io.out.ready := mainPipeReq_fire || !mainPipeReq_valid
455  mainPipe.io.req.valid := mainPipeReq_valid
456  mainPipe.io.req.bits  := mainPipeReq_req
457
458  when (mainPipeReqArb.io.out.fire()) { mainPipeReq_valid := true.B }
459  when (!mainPipeReqArb.io.out.fire() && mainPipeReq_fire) { mainPipeReq_valid := false.B }
460
461  missQueue.io.pipe_resp         <> mainPipe.io.miss_resp
462  storeReplayUnit.io.pipe_resp   <> mainPipe.io.store_resp
463  atomicsReplayUnit.io.pipe_resp <> mainPipe.io.amo_resp
464
465  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
466
467  for(i <- 0 until LoadPipelineWidth) {
468    mainPipe.io.replace_access(i) <> ldu(i).io.replace_access
469  }
470
471  //----------------------------------------
472  // wb
473  // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy
474  wb.io.req <> mainPipe.io.wb_req
475  bus.c     <> wb.io.mem_release
476
477  // connect bus d
478  missQueue.io.mem_grant.valid := false.B
479  missQueue.io.mem_grant.bits  := DontCare
480
481  wb.io.mem_grant.valid := false.B
482  wb.io.mem_grant.bits  := DontCare
483
484  // in L1DCache, we ony expect Grant[Data] and ReleaseAck
485  bus.d.ready := false.B
486  when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) {
487    missQueue.io.mem_grant <> bus.d
488  } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) {
489    wb.io.mem_grant <> bus.d
490  } .otherwise {
491    assert (!bus.d.fire())
492  }
493
494  //----------------------------------------
495  // assertions
496  // dcache should only deal with DRAM addresses
497  when (bus.a.fire()) {
498    assert(bus.a.bits.address >= 0x80000000L.U)
499  }
500  when (bus.b.fire()) {
501    assert(bus.b.bits.address >= 0x80000000L.U)
502  }
503  when (bus.c.fire()) {
504    assert(bus.c.bits.address >= 0x80000000L.U)
505  }
506
507  //----------------------------------------
508  // utility functions
509  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
510    sink.valid   := source.valid && !block_signal
511    source.ready := sink.ready   && !block_signal
512    sink.bits    := source.bits
513  }
514
515  //----------------------------------------
516  // performance counters
517  val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire()))
518  XSPerfAccumulate("num_loads", num_loads)
519
520  io.mshrFull := missQueue.io.full
521}
522
523class AMOHelper() extends ExtModule {
524  val clock  = IO(Input(Clock()))
525  val enable = IO(Input(Bool()))
526  val cmd    = IO(Input(UInt(5.W)))
527  val addr   = IO(Input(UInt(64.W)))
528  val wdata  = IO(Input(UInt(64.W)))
529  val mask   = IO(Input(UInt(8.W)))
530  val rdata  = IO(Output(UInt(64.W)))
531}
532
533
534class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
535
536  val useDcache = coreParams.dcacheParametersOpt.nonEmpty
537  val clientNode = if (useDcache) TLIdentityNode() else null
538  val dcache = if (useDcache) LazyModule(new DCache()) else null
539  if (useDcache) {
540    clientNode := dcache.clientNode
541  }
542
543  lazy val module = new LazyModuleImp(this) {
544    val io = IO(new DCacheIO)
545    if (!useDcache) {
546      // a fake dcache which uses dpi-c to access memory, only for debug usage!
547      val fake_dcache = Module(new FakeDCache())
548      io <> fake_dcache.io
549    }
550    else {
551      io <> dcache.module.io
552    }
553  }
554}
555