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