xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/DCacheWrapper.scala (revision c7160cd3e17f1f3c35393bcf4ee63b39665ec264)
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  val s2_kill  = Output(Bool())
260  // cycle 0: virtual address: req.addr
261  // cycle 1: physical address: s1_paddr
262  val s1_paddr = Output(UInt(PAddrBits.W))
263  val s1_hit_way = Input(UInt(nWays.W))
264  val s1_disable_fast_wakeup = Input(Bool())
265  val s1_bank_conflict = Input(Bool())
266}
267
268class DCacheLineIO(implicit p: Parameters) extends DCacheBundle
269{
270  val req  = DecoupledIO(new DCacheLineReq)
271  val resp = Flipped(DecoupledIO(new DCacheLineResp))
272}
273
274class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle {
275  val load  = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load
276  val lsq = ValidIO(new Refill)  // refill to load queue, wake up load misses
277  val store = Flipped(new DCacheLineIO) // for sbuffer
278  val atomics  = Flipped(new DCacheWordIOWithVaddr)  // atomics reqs
279}
280
281class DCacheIO(implicit p: Parameters) extends DCacheBundle {
282  val lsu = new DCacheToLsuIO
283  val error = new L1CacheErrorInfo
284  val mshrFull = Output(Bool())
285}
286
287
288class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters {
289
290  val clientParameters = TLMasterPortParameters.v1(
291    Seq(TLMasterParameters.v1(
292      name = "dcache",
293      sourceId = IdRange(0, cfg.nMissEntries+1),
294      supportsProbe = TransferSizes(cfg.blockBytes)
295    )),
296    requestFields = cacheParams.reqFields,
297    echoFields = cacheParams.echoFields
298  )
299
300  val clientNode = TLClientNode(Seq(clientParameters))
301
302  lazy val module = new DCacheImp(this)
303}
304
305
306class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters {
307
308  val io = IO(new DCacheIO)
309
310  val (bus, edge) = outer.clientNode.out.head
311  require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match")
312
313  println("DCache:")
314  println("  DCacheSets: " + DCacheSets)
315  println("  DCacheWays: " + DCacheWays)
316  println("  DCacheBanks: " + DCacheBanks)
317  println("  DCacheSRAMRowBits: " + DCacheSRAMRowBits)
318  println("  DCacheWordOffset: " + DCacheWordOffset)
319  println("  DCacheBankOffset: " + DCacheBankOffset)
320  println("  DCacheSetOffset: " + DCacheSetOffset)
321  println("  DCacheTagOffset: " + DCacheTagOffset)
322  println("  DCacheAboveIndexOffset: " + DCacheAboveIndexOffset)
323
324  //----------------------------------------
325  // core data structures
326  val bankedDataArray = Module(new BankedDataArray)
327  val metaArray = Module(new DuplicatedMetaArray(numReadPorts = 3))
328  bankedDataArray.dump()
329
330  val errors = bankedDataArray.io.errors ++ metaArray.io.errors
331  io.error <> RegNext(Mux1H(errors.map(e => e.ecc_error.valid -> e)))
332  // assert(!io.error.ecc_error.valid)
333
334  //----------------------------------------
335  // core modules
336  val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))})
337  val storeReplayUnit = Module(new StoreReplayQueue)
338  val atomicsReplayUnit = Module(new AtomicsReplayEntry)
339
340  val mainPipe   = Module(new MainPipe)
341  val missQueue  = Module(new MissQueue(edge))
342  val probeQueue = Module(new ProbeQueue(edge))
343  val wb         = Module(new WritebackQueue(edge))
344
345
346  //----------------------------------------
347  // meta array
348  val MetaWritePortCount = 1
349  val MainPipeMetaWritePort = 0
350  metaArray.io.write <> mainPipe.io.meta_write
351
352  // MainPipe contend MetaRead with Load 0
353  // give priority to MainPipe
354  val MetaReadPortCount = 2
355  val MainPipeMetaReadPort = 0
356  val LoadPipeMetaReadPort = 1
357
358  metaArray.io.read(LoadPipelineWidth) <> mainPipe.io.meta_read
359  mainPipe.io.meta_resp <> metaArray.io.resp(LoadPipelineWidth)
360
361  for (w <- 0 until LoadPipelineWidth) {
362    metaArray.io.read(w) <> ldu(w).io.meta_read
363    ldu(w).io.meta_resp <> metaArray.io.resp(w)
364  }
365
366  //----------------------------------------
367  // data array
368
369  bankedDataArray.io.write <> mainPipe.io.banked_data_write
370  bankedDataArray.io.read(0) <> ldu(0).io.banked_data_read
371  bankedDataArray.io.read(1) <> ldu(1).io.banked_data_read
372  bankedDataArray.io.readline <> mainPipe.io.banked_data_read
373
374  ldu(0).io.banked_data_resp := bankedDataArray.io.resp
375  ldu(1).io.banked_data_resp := bankedDataArray.io.resp
376  mainPipe.io.banked_data_resp := bankedDataArray.io.resp
377
378  ldu(0).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(0)
379  ldu(1).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(1)
380  ldu(0).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(0)
381  ldu(1).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(1)
382
383  //----------------------------------------
384  // load pipe
385  // the s1 kill signal
386  // only lsu uses this, replay never kills
387  for (w <- 0 until LoadPipelineWidth) {
388    ldu(w).io.lsu <> io.lsu.load(w)
389
390    // replay and nack not needed anymore
391    // TODO: remove replay and nack
392    ldu(w).io.nack := false.B
393
394    ldu(w).io.disable_ld_fast_wakeup :=
395      mainPipe.io.disable_ld_fast_wakeup(w) ||
396      bankedDataArray.io.bank_conflict_fast(w) // load pipe fast wake up should be disabled when bank conflict
397  }
398
399  //----------------------------------------
400  // store pipe and store miss queue
401  storeReplayUnit.io.lsu    <> io.lsu.store
402
403  //----------------------------------------
404  // atomics
405  // atomics not finished yet
406  io.lsu.atomics <> atomicsReplayUnit.io.lsu
407
408  //----------------------------------------
409  // miss queue
410  val MissReqPortCount = LoadPipelineWidth + 1
411  val MainPipeMissReqPort = 0
412
413  // Request
414  val missReqArb = Module(new RRArbiter(new MissReq, MissReqPortCount))
415
416  missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req
417  for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req }
418
419  wb.io.miss_req.valid := missReqArb.io.out.valid
420  wb.io.miss_req.bits  := missReqArb.io.out.bits.addr
421
422  block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req)
423
424  // refill to load queue
425  io.lsu.lsq <> missQueue.io.refill
426
427  // tilelink stuff
428  bus.a <> missQueue.io.mem_acquire
429  bus.e <> missQueue.io.mem_finish
430  missQueue.io.probe_req := bus.b.bits.address
431
432  //----------------------------------------
433  // probe
434  // probeQueue.io.mem_probe <> bus.b
435  block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block)
436
437  //----------------------------------------
438  // mainPipe
439  val MainPipeReqPortCount = 4
440  val MissMainPipeReqPort = 0
441  val StoreMainPipeReqPort = 1
442  val AtomicsMainPipeReqPort = 2
443  val ProbeMainPipeReqPort = 3
444
445  val mainPipeReqArb = Module(new RRArbiter(new MainPipeReq, MainPipeReqPortCount))
446  mainPipeReqArb.io.in(MissMainPipeReqPort)    <> missQueue.io.pipe_req
447  mainPipeReqArb.io.in(StoreMainPipeReqPort)   <> storeReplayUnit.io.pipe_req
448  mainPipeReqArb.io.in(AtomicsMainPipeReqPort) <> atomicsReplayUnit.io.pipe_req
449  mainPipeReqArb.io.in(ProbeMainPipeReqPort)   <> probeQueue.io.pipe_req
450
451  // add a stage to break the Arbiter bits.addr to ready path
452  val mainPipeReq_valid = RegInit(false.B)
453  val mainPipeReq_fire  = mainPipeReq_valid && mainPipe.io.req.ready
454  val mainPipeReq_req   = RegEnable(mainPipeReqArb.io.out.bits, mainPipeReqArb.io.out.fire())
455
456  mainPipeReqArb.io.out.ready := mainPipeReq_fire || !mainPipeReq_valid
457  mainPipe.io.req.valid := mainPipeReq_valid
458  mainPipe.io.req.bits  := mainPipeReq_req
459
460  when (mainPipeReqArb.io.out.fire()) { mainPipeReq_valid := true.B }
461  when (!mainPipeReqArb.io.out.fire() && mainPipeReq_fire) { mainPipeReq_valid := false.B }
462
463  missQueue.io.pipe_resp         <> mainPipe.io.miss_resp
464  storeReplayUnit.io.pipe_resp   <> mainPipe.io.store_resp
465  atomicsReplayUnit.io.pipe_resp <> mainPipe.io.amo_resp
466
467  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
468
469  for(i <- 0 until LoadPipelineWidth) {
470    mainPipe.io.replace_access(i) <> ldu(i).io.replace_access
471  }
472
473  //----------------------------------------
474  // wb
475  // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy
476  wb.io.req <> mainPipe.io.wb_req
477  bus.c     <> wb.io.mem_release
478
479  // connect bus d
480  missQueue.io.mem_grant.valid := false.B
481  missQueue.io.mem_grant.bits  := DontCare
482
483  wb.io.mem_grant.valid := false.B
484  wb.io.mem_grant.bits  := DontCare
485
486  // in L1DCache, we ony expect Grant[Data] and ReleaseAck
487  bus.d.ready := false.B
488  when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) {
489    missQueue.io.mem_grant <> bus.d
490  } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) {
491    wb.io.mem_grant <> bus.d
492  } .otherwise {
493    assert (!bus.d.fire())
494  }
495
496  //----------------------------------------
497  // assertions
498  // dcache should only deal with DRAM addresses
499  when (bus.a.fire()) {
500    assert(bus.a.bits.address >= 0x80000000L.U)
501  }
502  when (bus.b.fire()) {
503    assert(bus.b.bits.address >= 0x80000000L.U)
504  }
505  when (bus.c.fire()) {
506    assert(bus.c.bits.address >= 0x80000000L.U)
507  }
508
509  //----------------------------------------
510  // utility functions
511  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
512    sink.valid   := source.valid && !block_signal
513    source.ready := sink.ready   && !block_signal
514    sink.bits    := source.bits
515  }
516
517  //----------------------------------------
518  // performance counters
519  val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire()))
520  XSPerfAccumulate("num_loads", num_loads)
521
522  io.mshrFull := missQueue.io.full
523}
524
525class AMOHelper() extends ExtModule {
526  val clock  = IO(Input(Clock()))
527  val enable = IO(Input(Bool()))
528  val cmd    = IO(Input(UInt(5.W)))
529  val addr   = IO(Input(UInt(64.W)))
530  val wdata  = IO(Input(UInt(64.W)))
531  val mask   = IO(Input(UInt(8.W)))
532  val rdata  = IO(Output(UInt(64.W)))
533}
534
535
536class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
537
538  val useDcache = coreParams.dcacheParametersOpt.nonEmpty
539  val clientNode = if (useDcache) TLIdentityNode() else null
540  val dcache = if (useDcache) LazyModule(new DCache()) else null
541  if (useDcache) {
542    clientNode := dcache.clientNode
543  }
544
545  lazy val module = new LazyModuleImp(this) {
546    val io = IO(new DCacheIO)
547    if (!useDcache) {
548      // a fake dcache which uses dpi-c to access memory, only for debug usage!
549      val fake_dcache = Module(new FakeDCache())
550      io <> fake_dcache.io
551    }
552    else {
553      io <> dcache.module.io
554    }
555  }
556}
557