DCacheWrapper.scala 24.6 KB
Newer Older
L
Lemover 已提交
1 2
/***************************************************************************************
* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
Y
Yinan Xu 已提交
3
* Copyright (c) 2020-2021 Peng Cheng Laboratory
L
Lemover 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16
*
* XiangShan is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*          http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/

A
Allen 已提交
17 18 19 20
package xiangshan.cache

import chipsalliance.rocketchip.config.Parameters
import chisel3._
21
import chisel3.experimental.ExtModule
A
Allen 已提交
22 23 24 25
import chisel3.util._
import xiangshan._
import utils._
import freechips.rocketchip.diplomacy.{IdRange, LazyModule, LazyModuleImp, TransferSizes}
26
import freechips.rocketchip.tilelink._
27
import freechips.rocketchip.util.BundleFieldBase
28
import device.RAMHelper
29
import huancun.{AliasField, AliasKey, PreferCacheField, PrefetchField, DirtyField}
Z
zhanglinjuan 已提交
30
import scala.math.max
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

// DCache specific parameters
case class DCacheParameters
(
  nSets: Int = 256,
  nWays: Int = 8,
  rowBits: Int = 128,
  tagECC: Option[String] = None,
  dataECC: Option[String] = None,
  replacer: Option[String] = Some("random"),
  nMissEntries: Int = 1,
  nProbeEntries: Int = 1,
  nReleaseEntries: Int = 1,
  nMMIOEntries: Int = 1,
  nMMIOs: Int = 1,
46 47
  blockBytes: Int = 64,
  alwaysReleaseData: Boolean = true
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
) extends L1CacheParameters {
  // if sets * blockBytes > 4KB(page size),
  // cache alias will happen,
  // we need to avoid this by recoding additional bits in L2 cache
  val setBytes = nSets * blockBytes
  val aliasBitsOpt = if(setBytes > pageSize) Some(log2Ceil(setBytes / pageSize)) else None
  val reqFields: Seq[BundleFieldBase] = Seq(
    PrefetchField(),
    PreferCacheField()
  ) ++ aliasBitsOpt.map(AliasField)
  val echoFields: Seq[BundleFieldBase] = Seq(DirtyField())

  def tagCode: Code = Code.fromString(tagECC)

  def dataCode: Code = Code.fromString(dataECC)
}

//           Physical Address
// --------------------------------------
// |   Physical Tag |  PIndex  | Offset |
// --------------------------------------
//                  |
//                  DCacheTagOffset
Y
Yinan Xu 已提交
71
//
72 73 74 75 76
//           Virtual Address
// --------------------------------------
// | Above index  | Set | Bank | Offset |
// --------------------------------------
//                |     |      |        |
77
//                |     |      |        0
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
//                |     |      DCacheBankOffset
//                |     DCacheSetOffset
//                DCacheAboveIndexOffset

// Default DCache size = 64 sets * 8 ways * 8 banks * 8 Byte = 32K Byte

trait HasDCacheParameters extends HasL1CacheParameters {
  val cacheParams = dcacheParameters
  val cfg = cacheParams

  def encWordBits = cacheParams.dataCode.width(wordBits)

  def encRowBits = encWordBits * rowWords // for DuplicatedDataArray only
  def eccBits = encWordBits - wordBits

93 94 95
  def encTagBits = cacheParams.tagCode.width(tagBits)
  def eccTagBits = encTagBits - tagBits

96 97 98 99 100 101 102 103 104
  def lrscCycles = LRSCCycles // ISA requires 16-insn LRSC sequences to succeed
  def lrscBackoff = 3 // disallow LRSC reacquisition briefly
  def blockProbeAfterGrantCycles = 8 // give the processor some time to issue a request after a grant

  def nSourceType = 3
  def sourceTypeWidth = log2Up(nSourceType)
  def LOAD_SOURCE = 0
  def STORE_SOURCE = 1
  def AMO_SOURCE = 2
105
  def SOFT_PREFETCH = 3
106 107 108 109

  // each source use a id to distinguish its multiple reqs
  def reqIdWidth = 64

Z
zhanglinjuan 已提交
110 111 112 113 114
  require(isPow2(cfg.nMissEntries))
  require(isPow2(cfg.nReleaseEntries))
  val nEntries = max(cfg.nMissEntries, cfg.nReleaseEntries) << 1
  val releaseIdBase = max(cfg.nMissEntries, cfg.nReleaseEntries)

115 116 117 118 119
  // banked dcache support
  val DCacheSets = cacheParams.nSets
  val DCacheWays = cacheParams.nWays
  val DCacheBanks = 8
  val DCacheSRAMRowBits = 64 // hardcoded
120 121
  val DCacheWordBits = 64 // hardcoded
  val DCacheWordBytes = DCacheWordBits / 8
122

123 124 125
  val DCacheSizeBits = DCacheSRAMRowBits * DCacheBanks * DCacheWays * DCacheSets
  val DCacheSizeBytes = DCacheSizeBits / 8
  val DCacheSizeWords = DCacheSizeBits / 64 // TODO
126 127 128 129

  val DCacheSameVPAddrLength = 12

  val DCacheSRAMRowBytes = DCacheSRAMRowBits / 8
130 131 132
  val DCacheWordOffset = log2Up(DCacheWordBytes)

  val DCacheBankOffset = log2Up(DCacheSRAMRowBytes)
133 134 135
  val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks)
  val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets)
  val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength
136
  val DCacheLineOffset = DCacheSetOffset
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
  val DCacheIndexOffset = DCacheBankOffset

  def addr_to_dcache_bank(addr: UInt) = {
    require(addr.getWidth >= DCacheSetOffset)
    addr(DCacheSetOffset-1, DCacheBankOffset)
  }

  def addr_to_dcache_set(addr: UInt) = {
    require(addr.getWidth >= DCacheAboveIndexOffset)
    addr(DCacheAboveIndexOffset-1, DCacheSetOffset)
  }

  def get_data_of_bank(bank: Int, data: UInt) = {
    require(data.getWidth >= (bank+1)*DCacheSRAMRowBits)
    data(DCacheSRAMRowBits * (bank + 1) - 1, DCacheSRAMRowBits * bank)
  }

  def get_mask_of_bank(bank: Int, data: UInt) = {
    require(data.getWidth >= (bank+1)*DCacheSRAMRowBytes)
    data(DCacheSRAMRowBytes * (bank + 1) - 1, DCacheSRAMRowBytes * bank)
  }

Z
zhanglinjuan 已提交
159 160
  val numReplaceRespPorts = 2

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
  require(isPow2(nSets), s"nSets($nSets) must be pow2")
  require(isPow2(nWays), s"nWays($nWays) must be pow2")
  require(full_divide(rowBits, wordBits), s"rowBits($rowBits) must be multiple of wordBits($wordBits)")
  require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)")
}

abstract class DCacheModule(implicit p: Parameters) extends L1CacheModule
  with HasDCacheParameters

abstract class DCacheBundle(implicit p: Parameters) extends L1CacheBundle
  with HasDCacheParameters

class ReplacementAccessBundle(implicit p: Parameters) extends DCacheBundle {
  val set = UInt(log2Up(nSets).W)
  val way = UInt(log2Up(nWays).W)
}
A
Allen 已提交
177

Z
zhanglinjuan 已提交
178 179 180 181 182
class ReplacementWayReqIO(implicit p: Parameters) extends DCacheBundle {
  val set = ValidIO(UInt(log2Up(nSets).W))
  val way = Input(UInt(log2Up(nWays).W))
}

A
Allen 已提交
183
// memory request in word granularity(load, mmio, lr/sc, atomics)
184
class DCacheWordReq(implicit p: Parameters)  extends DCacheBundle
A
Allen 已提交
185 186 187 188 189 190
{
  val cmd    = UInt(M_SZ.W)
  val addr   = UInt(PAddrBits.W)
  val data   = UInt(DataBits.W)
  val mask   = UInt((DataBits/8).W)
  val id     = UInt(reqIdWidth.W)
191
  val instrtype   = UInt(sourceTypeWidth.W)
A
Allen 已提交
192 193 194 195 196 197 198
  def dump() = {
    XSDebug("DCacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
      cmd, addr, data, mask, id)
  }
}

// memory request in word granularity(store)
199
class DCacheLineReq(implicit p: Parameters)  extends DCacheBundle
A
Allen 已提交
200 201
{
  val cmd    = UInt(M_SZ.W)
202
  val vaddr  = UInt(VAddrBits.W)
A
Allen 已提交
203 204 205 206 207 208 209 210
  val addr   = UInt(PAddrBits.W)
  val data   = UInt((cfg.blockBytes * 8).W)
  val mask   = UInt(cfg.blockBytes.W)
  val id     = UInt(reqIdWidth.W)
  def dump() = {
    XSDebug("DCacheLineReq: cmd: %x addr: %x data: %x mask: %x id: %d\n",
      cmd, addr, data, mask, id)
  }
Z
zhanglinjuan 已提交
211
  def idx: UInt = get_idx(vaddr)
A
Allen 已提交
212 213
}

214 215
class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq {
  val vaddr = UInt(VAddrBits.W)
216
  val wline = Bool()
217 218
}

219
class DCacheWordResp(implicit p: Parameters) extends DCacheBundle
A
Allen 已提交
220 221 222 223 224
{
  val data         = UInt(DataBits.W)
  // cache req missed, send it to miss queue
  val miss   = Bool()
  // cache req nacked, replay it later
225 226
  val miss_enter = Bool()
  // cache miss, and enter the missqueue successfully. just for softprefetch
A
Allen 已提交
227 228 229 230 231 232 233 234
  val replay = Bool()
  val id     = UInt(reqIdWidth.W)
  def dump() = {
    XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n",
      data, id, miss, replay)
  }
}

235
class DCacheLineResp(implicit p: Parameters) extends DCacheBundle
A
Allen 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248
{
  val data   = UInt((cfg.blockBytes * 8).W)
  // cache req missed, send it to miss queue
  val miss   = Bool()
  // cache req nacked, replay it later
  val replay = Bool()
  val id     = UInt(reqIdWidth.W)
  def dump() = {
    XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n",
      data, id, miss, replay)
  }
}

249
class Refill(implicit p: Parameters) extends DCacheBundle
A
Allen 已提交
250 251
{
  val addr   = UInt(PAddrBits.W)
252
  val data   = UInt(l1BusDataWidth.W)
253 254 255 256
  // for debug usage
  val data_raw = UInt((cfg.blockBytes * 8).W)
  val hasdata = Bool()
  val refill_done = Bool()
A
Allen 已提交
257 258 259 260 261
  def dump() = {
    XSDebug("Refill: addr: %x data: %x\n", addr, data)
  }
}

262
class DCacheWordIO(implicit p: Parameters) extends DCacheBundle
A
Allen 已提交
263 264 265 266 267
{
  val req  = DecoupledIO(new DCacheWordReq)
  val resp = Flipped(DecoupledIO(new DCacheWordResp))
}

268 269 270 271 272 273
class DCacheWordIOWithVaddr(implicit p: Parameters) extends DCacheBundle
{
  val req  = DecoupledIO(new DCacheWordReqWithVaddr)
  val resp = Flipped(DecoupledIO(new DCacheWordResp))
}

A
Allen 已提交
274
// used by load unit
275
class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO
276 277 278
{
  // kill previous cycle's req
  val s1_kill  = Output(Bool())
L
Lemover 已提交
279
  val s2_kill  = Output(Bool())
280 281 282
  // cycle 0: virtual address: req.addr
  // cycle 1: physical address: s1_paddr
  val s1_paddr = Output(UInt(PAddrBits.W))
283
  val s1_hit_way = Input(UInt(nWays.W))
284
  val s1_disable_fast_wakeup = Input(Bool())
285
  val s1_bank_conflict = Input(Bool())
286 287
}

288
class DCacheLineIO(implicit p: Parameters) extends DCacheBundle
A
Allen 已提交
289
{
290
  val req  = DecoupledIO(new DCacheLineReq)
A
Allen 已提交
291 292 293
  val resp = Flipped(DecoupledIO(new DCacheLineResp))
}

Z
zhanglinjuan 已提交
294 295 296 297 298 299 300 301 302 303 304 305
class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle { 
  // sbuffer will directly send request to dcache main pipe
  val req = Flipped(Decoupled(new DCacheLineReq))

  val main_pipe_hit_resp = ValidIO(new DCacheLineResp)
  val refill_hit_resp = ValidIO(new DCacheLineResp)

  val replay_resp = ValidIO(new DCacheLineResp)

  def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp)
}

306
class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle {
A
Allen 已提交
307 308
  val load  = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load
  val lsq = ValidIO(new Refill)  // refill to load queue, wake up load misses
Z
zhanglinjuan 已提交
309
  val store = new DCacheToSbufferIO // for sbuffer
310
  val atomics  = Flipped(new DCacheWordIOWithVaddr)  // atomics reqs
A
Allen 已提交
311 312
}

313
class DCacheIO(implicit p: Parameters) extends DCacheBundle {
A
Allen 已提交
314
  val lsu = new DCacheToLsuIO
315
  val csr = new L1CacheToCsrIO
316
  val error = new L1CacheErrorInfo
317
  val mshrFull = Output(Bool())
A
Allen 已提交
318 319 320 321 322 323 324 325
}


class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters {

  val clientParameters = TLMasterPortParameters.v1(
    Seq(TLMasterParameters.v1(
      name = "dcache",
Z
zhanglinjuan 已提交
326
      sourceId = IdRange(0, nEntries + 1),
A
Allen 已提交
327
      supportsProbe = TransferSizes(cfg.blockBytes)
328 329 330
    )),
    requestFields = cacheParams.reqFields,
    echoFields = cacheParams.echoFields
A
Allen 已提交
331 332 333 334 335 336 337 338
  )

  val clientNode = TLClientNode(Seq(clientParameters))

  lazy val module = new DCacheImp(this)
}


L
ljw 已提交
339
class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters {
A
Allen 已提交
340 341 342 343 344 345

  val io = IO(new DCacheIO)

  val (bus, edge) = outer.clientNode.out.head
  require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match")

Y
Yinan Xu 已提交
346 347 348 349 350 351 352 353 354 355
  println("DCache:")
  println("  DCacheSets: " + DCacheSets)
  println("  DCacheWays: " + DCacheWays)
  println("  DCacheBanks: " + DCacheBanks)
  println("  DCacheSRAMRowBits: " + DCacheSRAMRowBits)
  println("  DCacheWordOffset: " + DCacheWordOffset)
  println("  DCacheBankOffset: " + DCacheBankOffset)
  println("  DCacheSetOffset: " + DCacheSetOffset)
  println("  DCacheTagOffset: " + DCacheTagOffset)
  println("  DCacheAboveIndexOffset: " + DCacheAboveIndexOffset)
356

A
Allen 已提交
357 358
  //----------------------------------------
  // core data structures
359
  val bankedDataArray = Module(new BankedDataArray)
Z
zhanglinjuan 已提交
360 361
  val metaArray = Module(new AsynchronousMetaArray(readPorts = 4, writePorts = 3))
  val tagArray = Module(new DuplicatedTagArray(readPorts = LoadPipelineWidth + 1))
362 363 364
  bankedDataArray.dump()

  val errors = bankedDataArray.io.errors ++ metaArray.io.errors
365
  io.error <> RegNext(Mux1H(errors.map(e => e.ecc_error.valid -> e)))
366
  // assert(!io.error.ecc_error.valid)
A
Allen 已提交
367 368 369

  //----------------------------------------
  // core modules
370
  val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))})
A
Allen 已提交
371
  val atomicsReplayUnit = Module(new AtomicsReplayEntry)
372
  val mainPipe   = Module(new MainPipe)
Z
zhanglinjuan 已提交
373 374
  val refillPipe = Module(new RefillPipe)
  val replacePipe = Module(new ReplacePipe)
A
Allen 已提交
375 376
  val missQueue  = Module(new MissQueue(edge))
  val probeQueue = Module(new ProbeQueue(edge))
377
  val wb         = Module(new WritebackQueue(edge))
A
Allen 已提交
378 379 380

  //----------------------------------------
  // meta array
Z
zhanglinjuan 已提交
381 382 383 384 385 386 387 388 389 390 391 392 393 394
  val meta_read_ports = ldu.map(_.io.meta_read) ++
    Seq(mainPipe.io.meta_read,
      replacePipe.io.meta_read)
  val meta_resp_ports = ldu.map(_.io.meta_resp) ++
    Seq(mainPipe.io.meta_resp,
      replacePipe.io.meta_resp)
  val meta_write_ports = Seq(
    mainPipe.io.meta_write,
    refillPipe.io.meta_write,
    replacePipe.io.meta_write
  )
  meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p }
  meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r }
  meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p }
A
Allen 已提交
395

Z
zhanglinjuan 已提交
396 397 398 399 400 401 402
  //----------------------------------------
  // tag array
  require(tagArray.io.read.size == (ldu.size + 1))
  ldu.zipWithIndex.foreach {
    case (ld, i) =>
      tagArray.io.read(i) <> ld.io.tag_read
      ld.io.tag_resp := tagArray.io.resp(i)
A
Allen 已提交
403
  }
Z
zhanglinjuan 已提交
404 405 406 407 408 409 410
  tagArray.io.read.last <> mainPipe.io.tag_read
  mainPipe.io.tag_resp := tagArray.io.resp.last

  val tag_write_arb = Module(new Arbiter(new TagWriteReq, 2))
  tag_write_arb.io.in(0) <> refillPipe.io.tag_write
  tag_write_arb.io.in(1) <> mainPipe.io.tag_write
  tagArray.io.write <> tag_write_arb.io.out
A
Allen 已提交
411 412 413 414

  //----------------------------------------
  // data array

Z
zhanglinjuan 已提交
415 416 417 418 419 420 421 422 423
  val dataReadLineArb = Module(new Arbiter(new L1BankedDataReadLineReq, 2))
  dataReadLineArb.io.in(0) <> replacePipe.io.data_read
  dataReadLineArb.io.in(1) <> mainPipe.io.data_read

  val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 2))
  dataWriteArb.io.in(0) <> refillPipe.io.data_write
  dataWriteArb.io.in(1) <> mainPipe.io.data_write

  bankedDataArray.io.write <> dataWriteArb.io.out
424 425
  bankedDataArray.io.read(0) <> ldu(0).io.banked_data_read
  bankedDataArray.io.read(1) <> ldu(1).io.banked_data_read
Z
zhanglinjuan 已提交
426
  bankedDataArray.io.readline <> dataReadLineArb.io.out
A
Allen 已提交
427

428 429
  ldu(0).io.banked_data_resp := bankedDataArray.io.resp
  ldu(1).io.banked_data_resp := bankedDataArray.io.resp
Z
zhanglinjuan 已提交
430 431
  mainPipe.io.data_resp := bankedDataArray.io.resp
  replacePipe.io.data_resp := bankedDataArray.io.resp
A
Allen 已提交
432

433 434 435 436
  ldu(0).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(0)
  ldu(1).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(1)
  ldu(0).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(0)
  ldu(1).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(1)
A
Allen 已提交
437 438 439 440 441 442

  //----------------------------------------
  // load pipe
  // the s1 kill signal
  // only lsu uses this, replay never kills
  for (w <- 0 until LoadPipelineWidth) {
443
    ldu(w).io.lsu <> io.lsu.load(w)
A
Allen 已提交
444 445 446 447

    // replay and nack not needed anymore
    // TODO: remove replay and nack
    ldu(w).io.nack := false.B
448

Y
Yinan Xu 已提交
449
    ldu(w).io.disable_ld_fast_wakeup :=
450
      bankedDataArray.io.bank_conflict_fast(w) // load pipe fast wake up should be disabled when bank conflict
A
Allen 已提交
451 452 453 454 455
  }

  //----------------------------------------
  // atomics
  // atomics not finished yet
A
Allen 已提交
456
  io.lsu.atomics <> atomicsReplayUnit.io.lsu
Z
zhanglinjuan 已提交
457
  atomicsReplayUnit.io.pipe_resp := mainPipe.io.atomic_resp
A
Allen 已提交
458 459 460 461 462 463 464

  //----------------------------------------
  // miss queue
  val MissReqPortCount = LoadPipelineWidth + 1
  val MainPipeMissReqPort = 0

  // Request
465
  val missReqArb = Module(new RRArbiter(new MissReq, MissReqPortCount))
A
Allen 已提交
466

Z
zhanglinjuan 已提交
467
  missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss
A
Allen 已提交
468 469
  for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req }

470 471 472 473
  wb.io.miss_req.valid := missReqArb.io.out.valid
  wb.io.miss_req.bits  := missReqArb.io.out.bits.addr

  block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req)
A
Allen 已提交
474 475

  // refill to load queue
Z
zhanglinjuan 已提交
476
  io.lsu.lsq <> missQueue.io.refill_to_ldq
A
Allen 已提交
477 478 479 480

  // tilelink stuff
  bus.a <> missQueue.io.mem_acquire
  bus.e <> missQueue.io.mem_finish
Z
zhanglinjuan 已提交
481 482 483
  missQueue.io.probe_addr := bus.b.bits.address

  missQueue.io.main_pipe_resp := mainPipe.io.atomic_resp
A
Allen 已提交
484 485 486

  //----------------------------------------
  // probe
487 488
  // probeQueue.io.mem_probe <> bus.b
  block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block)
Z
zhanglinjuan 已提交
489
  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
A
Allen 已提交
490 491 492

  //----------------------------------------
  // mainPipe
Z
zhanglinjuan 已提交
493 494
  // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe,
  // block the req in main pipe
495
  val refillPipeStatus, replacePipeStatusS0 = Wire(Valid(UInt(idxBits.W)))
Z
zhanglinjuan 已提交
496
  refillPipeStatus.valid := refillPipe.io.req.valid
497 498 499
  refillPipeStatus.bits := get_idx(refillPipe.io.req.bits.paddrWithVirtualAlias)
  replacePipeStatusS0.valid := replacePipe.io.req.valid
  replacePipeStatusS0.bits := get_idx(replacePipe.io.req.bits.vaddr)
Z
zhanglinjuan 已提交
500 501
  val blockMainPipeReqs = Seq(
    refillPipeStatus,
502
	replacePipeStatusS0,
Z
zhanglinjuan 已提交
503 504 505 506 507
    replacePipe.io.status.s1_set,
    replacePipe.io.status.s2_set
  )
  val storeShouldBeBlocked = Cat(blockMainPipeReqs.map(r => r.valid && r.bits === io.lsu.store.req.bits.idx)).orR
  val probeShouldBeBlocked = Cat(blockMainPipeReqs.map(r => r.valid && r.bits === get_idx(probeQueue.io.pipe_req.bits.vaddr))).orR
A
Allen 已提交
508

Z
zhanglinjuan 已提交
509 510
  block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, probeShouldBeBlocked)
  block_decoupled(io.lsu.store.req, mainPipe.io.store_req, storeShouldBeBlocked)
A
Allen 已提交
511

Z
zhanglinjuan 已提交
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
  io.lsu.store.replay_resp := mainPipe.io.store_replay_resp
  io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp

  val mainPipeAtomicReqArb = Module(new Arbiter(new MainPipeReq, 2))
  mainPipeAtomicReqArb.io.in(0) <> missQueue.io.main_pipe_req
  mainPipeAtomicReqArb.io.in(1) <> atomicsReplayUnit.io.pipe_req
  mainPipe.io.atomic_req <> mainPipeAtomicReqArb.io.out

  mainPipe.io.invalid_resv_set := wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits

  //----------------------------------------
  // replace pipe
  val mpStatus = mainPipe.io.status
  val replaceSet = addr_to_dcache_set(missQueue.io.replace_pipe_req.bits.vaddr)
  val replaceWayEn = missQueue.io.replace_pipe_req.bits.way_en
527
  val replaceShouldBeBlocked = // mpStatus.s0_set.valid && replaceSet === mpStatus.s0_set.bits ||
Z
zhanglinjuan 已提交
528 529 530 531 532 533 534 535
    Cat(Seq(mpStatus.s1, mpStatus.s2, mpStatus.s3).map(s =>
      s.valid && s.bits.set === replaceSet && s.bits.way_en === replaceWayEn
    )).orR()
  block_decoupled(missQueue.io.replace_pipe_req, replacePipe.io.req, replaceShouldBeBlocked)
  missQueue.io.replace_pipe_resp := replacePipe.io.resp

  //----------------------------------------
  // refill pipe
536 537 538 539 540
  val refillShouldBeBlocked = Cat(Seq(mpStatus.s1, mpStatus.s2, mpStatus.s3).map(s =>
    s.valid &&
      s.bits.set === missQueue.io.refill_pipe_req.bits.idx &&
      s.bits.way_en === missQueue.io.refill_pipe_req.bits.way_en
  )).orR
Z
zhanglinjuan 已提交
541 542
  block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked)
  io.lsu.store.refill_hit_resp := refillPipe.io.store_resp
543

A
Allen 已提交
544 545 546
  //----------------------------------------
  // wb
  // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy
Z
zhanglinjuan 已提交
547 548 549
  val wbArb = Module(new Arbiter(new WritebackReq, 2))
  wbArb.io.in.zip(Seq(mainPipe.io.wb, replacePipe.io.wb)).foreach { case (arb, pipe) => arb <> pipe }
  wb.io.req <> wbArb.io.out
A
Allen 已提交
550
  bus.c     <> wb.io.mem_release
Z
zhanglinjuan 已提交
551 552
  wb.io.release_wakeup := refillPipe.io.release_wakeup
  wb.io.release_update := mainPipe.io.release_update
A
Allen 已提交
553

554
  // connect bus d
A
Allen 已提交
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
  missQueue.io.mem_grant.valid := false.B
  missQueue.io.mem_grant.bits  := DontCare

  wb.io.mem_grant.valid := false.B
  wb.io.mem_grant.bits  := DontCare

  // in L1DCache, we ony expect Grant[Data] and ReleaseAck
  bus.d.ready := false.B
  when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) {
    missQueue.io.mem_grant <> bus.d
  } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) {
    wb.io.mem_grant <> bus.d
  } .otherwise {
    assert (!bus.d.fire())
  }

Z
zhanglinjuan 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
  //----------------------------------------
  // replacement algorithm
  val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets)

  val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way)
  replWayReqs.foreach{
    case req =>
      req.way := DontCare
      when (req.set.valid) { req.way := replacer.way(req.set.bits) }
  }

  val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq(
    mainPipe.io.replace_access,
    refillPipe.io.replace_access
  )
  val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W))))
  touchWays.zip(replAccessReqs).foreach {
    case (w, req) =>
      w.valid := req.valid
      w.bits := req.bits.way
  }
  val touchSets = replAccessReqs.map(_.bits.set)
  replacer.access(touchSets, touchWays)

595 596
  //----------------------------------------
  // assertions
A
Allen 已提交
597 598 599 600 601 602 603 604 605 606 607
  // dcache should only deal with DRAM addresses
  when (bus.a.fire()) {
    assert(bus.a.bits.address >= 0x80000000L.U)
  }
  when (bus.b.fire()) {
    assert(bus.b.bits.address >= 0x80000000L.U)
  }
  when (bus.c.fire()) {
    assert(bus.c.bits.address >= 0x80000000L.U)
  }

608 609
  //----------------------------------------
  // utility functions
610 611 612 613 614
  def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = {
    sink.valid   := source.valid && !block_signal
    source.ready := sink.ready   && !block_signal
    sink.bits    := source.bits
  }
615

616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
  //----------------------------------------
  // Customized csr cache op support
  val cacheOpDecoder = Module(new CSRCacheOpDecoder("dcache", CacheInstrucion.COP_ID_DCACHE))
  cacheOpDecoder.io.csr <> io.csr
  bankedDataArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
  metaArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
  tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
  cacheOpDecoder.io.cache.resp.valid := bankedDataArray.io.cacheOp.resp.valid ||
    metaArray.io.cacheOp.resp.valid ||
    tagArray.io.cacheOp.resp.valid
  cacheOpDecoder.io.cache.resp.bits := Mux1H(List(
    bankedDataArray.io.cacheOp.resp.valid -> bankedDataArray.io.cacheOp.resp.bits,
    metaArray.io.cacheOp.resp.valid -> metaArray.io.cacheOp.resp.bits,
    tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits,
  ))
  assert(!((bankedDataArray.io.cacheOp.resp.valid +& metaArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U))

633 634 635
  //----------------------------------------
  // performance counters
  val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire()))
636
  XSPerfAccumulate("num_loads", num_loads)
637 638

  io.mshrFull := missQueue.io.full
Z
zhanglinjuan 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663

  // performance counter
  val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType))
  val st_access = Wire(ld_access.last.cloneType)
  ld_access.zip(ldu).foreach {
    case (a, u) =>
      a.valid := RegNext(u.io.lsu.req.fire()) && !u.io.lsu.s1_kill
      a.bits.idx := RegNext(get_idx(u.io.lsu.req.bits.addr))
      a.bits.tag := get_tag(u.io.lsu.s1_paddr)
  }
  st_access.valid := RegNext(mainPipe.io.store_req.fire())
  st_access.bits.idx := RegNext(get_idx(mainPipe.io.store_req.bits.vaddr))
  st_access.bits.tag := RegNext(get_tag(mainPipe.io.store_req.bits.addr))
  val access_info = ld_access.toSeq ++ Seq(st_access)
  val early_replace = RegNext(missQueue.io.debug_early_replace)
  val access_early_replace = access_info.map {
    case acc =>
      Cat(early_replace.map {
        case r =>
          acc.valid && r.valid &&
            acc.bits.tag === r.bits.tag &&
            acc.bits.idx === r.bits.idx
      })
  }
  XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace)))
A
Allen 已提交
664
}
665

666
class AMOHelper() extends ExtModule {
J
Jiawei Lin 已提交
667 668 669 670 671 672 673
  val clock  = IO(Input(Clock()))
  val enable = IO(Input(Bool()))
  val cmd    = IO(Input(UInt(5.W)))
  val addr   = IO(Input(UInt(64.W)))
  val wdata  = IO(Input(UInt(64.W)))
  val mask   = IO(Input(UInt(8.W)))
  val rdata  = IO(Output(UInt(64.W)))
674 675 676
}


J
Jiawei Lin 已提交
677
class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter {
678

J
Jiawei Lin 已提交
679 680 681 682
  val useDcache = coreParams.dcacheParametersOpt.nonEmpty
  val clientNode = if (useDcache) TLIdentityNode() else null
  val dcache = if (useDcache) LazyModule(new DCache()) else null
  if (useDcache) {
683 684 685 686 687
    clientNode := dcache.clientNode
  }

  lazy val module = new LazyModuleImp(this) {
    val io = IO(new DCacheIO)
J
Jiawei Lin 已提交
688 689
    if (!useDcache) {
      // a fake dcache which uses dpi-c to access memory, only for debug usage!
690 691 692 693 694 695 696 697
      val fake_dcache = Module(new FakeDCache())
      io <> fake_dcache.io
    }
    else {
      io <> dcache.module.io
    }
  }
}