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