DCacheWrapper.scala 26.3 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._
J
Jiawei Lin 已提交
27
import freechips.rocketchip.util.{BundleFieldBase, UIntToOH1}
28
import device.RAMHelper
J
Jiawei Lin 已提交
29
import huancun.{AliasField, AliasKey, DirtyField, PreferCacheField, PrefetchField}
30
import mem.{AddPipelineReg}
J
Jiawei Lin 已提交
31

Z
zhanglinjuan 已提交
32
import scala.math.max
33 34 35 36 37 38 39 40 41

// DCache specific parameters
case class DCacheParameters
(
  nSets: Int = 256,
  nWays: Int = 8,
  rowBits: Int = 128,
  tagECC: Option[String] = None,
  dataECC: Option[String] = None,
W
William Wang 已提交
42
  replacer: Option[String] = Some("setplru"),
43 44 45 46 47
  nMissEntries: Int = 1,
  nProbeEntries: Int = 1,
  nReleaseEntries: Int = 1,
  nMMIOEntries: Int = 1,
  nMMIOs: Int = 1,
48 49
  blockBytes: Int = 64,
  alwaysReleaseData: Boolean = true
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
) 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 已提交
73
//
74 75 76 77 78
//           Virtual Address
// --------------------------------------
// | Above index  | Set | Bank | Offset |
// --------------------------------------
//                |     |      |        |
79
//                |     |      |        0
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
//                |     |      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

95 96 97
  def encTagBits = cacheParams.tagCode.width(tagBits)
  def eccTagBits = encTagBits - tagBits

98 99 100 101 102 103 104
  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

W
William Wang 已提交
110 111 112 113 114
  require(isPow2(cfg.nMissEntries)) // TODO
  // require(isPow2(cfg.nReleaseEntries))
  require(cfg.nMissEntries < cfg.nReleaseEntries)
  val nEntries = cfg.nMissEntries + cfg.nReleaseEntries
  val releaseIdBase = cfg.nMissEntries
Z
zhanglinjuan 已提交
115

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

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

  val DCacheSameVPAddrLength = 12

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

  val DCacheBankOffset = log2Up(DCacheSRAMRowBytes)
134 135 136
  val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks)
  val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets)
  val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength
137
  val DCacheLineOffset = DCacheSetOffset
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  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)
  }

160 161 162 163
  def refill_addr_hit(a: UInt, b: UInt): Bool = {
    a(PAddrBits-1, DCacheIndexOffset) === b(PAddrBits-1, DCacheIndexOffset)
  }

164 165 166 167 168 169 170 171 172 173 174 175
  def arbiter[T <: Bundle](
    in: Seq[DecoupledIO[T]],
    out: DecoupledIO[T],
    name: Option[String] = None): Unit = {
    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
    for ((a, req) <- arb.io.in.zip(in)) {
      a <> req
    }
    out <> arb.io.out
  }

176 177 178 179 180 181 182 183 184 185 186 187
  def arbiter_with_pipereg[T <: Bundle](
    in: Seq[DecoupledIO[T]],
    out: DecoupledIO[T],
    name: Option[String] = None): Unit = {
    val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size))
    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
    for ((a, req) <- arb.io.in.zip(in)) {
      a <> req
    }
    AddPipelineReg(arb.io.out, out, false.B)
  }

188 189 190 191 192 193 194 195 196 197 198 199
  def rrArbiter[T <: Bundle](
    in: Seq[DecoupledIO[T]],
    out: DecoupledIO[T],
    name: Option[String] = None): Unit = {
    val arb = Module(new RRArbiter[T](chiselTypeOf(out.bits), in.size))
    if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") }
    for ((a, req) <- arb.io.in.zip(in)) {
      a <> req
    }
    out <> arb.io.out
  }

Z
zhanglinjuan 已提交
200 201
  val numReplaceRespPorts = 2

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  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 已提交
218

Z
zhanglinjuan 已提交
219 220 221 222 223
class ReplacementWayReqIO(implicit p: Parameters) extends DCacheBundle {
  val set = ValidIO(UInt(log2Up(nSets).W))
  val way = Input(UInt(log2Up(nWays).W))
}

A
Allen 已提交
224
// memory request in word granularity(load, mmio, lr/sc, atomics)
225
class DCacheWordReq(implicit p: Parameters)  extends DCacheBundle
A
Allen 已提交
226 227 228 229 230 231
{
  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)
232
  val instrtype   = UInt(sourceTypeWidth.W)
A
Allen 已提交
233 234 235 236 237 238 239
  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)
240
class DCacheLineReq(implicit p: Parameters)  extends DCacheBundle
A
Allen 已提交
241 242
{
  val cmd    = UInt(M_SZ.W)
243
  val vaddr  = UInt(VAddrBits.W)
A
Allen 已提交
244 245 246 247 248 249 250 251
  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 已提交
252
  def idx: UInt = get_idx(vaddr)
A
Allen 已提交
253 254
}

255 256
class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq {
  val vaddr = UInt(VAddrBits.W)
257
  val wline = Bool()
258 259
}

260
class BaseDCacheWordResp(implicit p: Parameters) extends DCacheBundle
A
Allen 已提交
261 262
{
  val data         = UInt(DataBits.W)
263 264
  val id     = UInt(reqIdWidth.W)

A
Allen 已提交
265 266
  // cache req missed, send it to miss queue
  val miss   = Bool()
267
  // cache miss, and failed to enter the missqueue, replay from RS is needed
A
Allen 已提交
268
  val replay = Bool()
269
  // data has been corrupted
270
  val tag_error = Bool() // tag error
A
Allen 已提交
271 272 273 274 275 276
  def dump() = {
    XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n",
      data, id, miss, replay)
  }
}

277 278 279 280 281 282 283 284 285 286 287
class DCacheWordResp(implicit p: Parameters) extends BaseDCacheWordResp
{
  // 1 cycle after data resp
  val error_delayed = Bool() // all kinds of errors, include tag error
}

class DCacheWordRespWithError(implicit p: Parameters) extends BaseDCacheWordResp
{
  val error = Bool() // all kinds of errors, include tag error
}

288
class DCacheLineResp(implicit p: Parameters) extends DCacheBundle
A
Allen 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301
{
  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)
  }
}

302
class Refill(implicit p: Parameters) extends DCacheBundle
A
Allen 已提交
303 304
{
  val addr   = UInt(PAddrBits.W)
305
  val data   = UInt(l1BusDataWidth.W)
306
  val error  = Bool() // refilled data has been corrupted
307 308 309 310
  // for debug usage
  val data_raw = UInt((cfg.blockBytes * 8).W)
  val hasdata = Bool()
  val refill_done = Bool()
A
Allen 已提交
311 312 313 314 315
  def dump() = {
    XSDebug("Refill: addr: %x data: %x\n", addr, data)
  }
}

W
William Wang 已提交
316 317 318 319 320 321 322 323
class Release(implicit p: Parameters) extends DCacheBundle
{
  val paddr  = UInt(PAddrBits.W)
  def dump() = {
    XSDebug("Release: paddr: %x\n", paddr(PAddrBits-1, DCacheTagOffset))
  }
}

324
class DCacheWordIO(implicit p: Parameters) extends DCacheBundle
A
Allen 已提交
325 326 327 328 329
{
  val req  = DecoupledIO(new DCacheWordReq)
  val resp = Flipped(DecoupledIO(new DCacheWordResp))
}

330 331 332 333 334 335 336
class UncacheWordIO(implicit p: Parameters) extends DCacheBundle
{
  val req  = DecoupledIO(new DCacheWordReq)
  val resp = Flipped(DecoupledIO(new DCacheWordRespWithError))
}

class AtomicWordIO(implicit p: Parameters) extends DCacheBundle
337 338
{
  val req  = DecoupledIO(new DCacheWordReqWithVaddr)
339
  val resp = Flipped(DecoupledIO(new DCacheWordRespWithError))
340 341
}

A
Allen 已提交
342
// used by load unit
343
class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO
344 345 346
{
  // kill previous cycle's req
  val s1_kill  = Output(Bool())
L
Lemover 已提交
347
  val s2_kill  = Output(Bool())
348 349 350
  // cycle 0: virtual address: req.addr
  // cycle 1: physical address: s1_paddr
  val s1_paddr = Output(UInt(PAddrBits.W))
351
  val s1_hit_way = Input(UInt(nWays.W))
352
  val s1_disable_fast_wakeup = Input(Bool())
353
  val s1_bank_conflict = Input(Bool())
354 355
}

356
class DCacheLineIO(implicit p: Parameters) extends DCacheBundle
A
Allen 已提交
357
{
358
  val req  = DecoupledIO(new DCacheLineReq)
A
Allen 已提交
359 360 361
  val resp = Flipped(DecoupledIO(new DCacheLineResp))
}

Z
zhanglinjuan 已提交
362 363 364 365 366 367 368 369 370 371 372 373
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)
}

374
class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle {
A
Allen 已提交
375 376
  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 已提交
377
  val store = new DCacheToSbufferIO // for sbuffer
378
  val atomics  = Flipped(new AtomicWordIO)  // atomics reqs
W
William Wang 已提交
379
  val release = ValidIO(new Release) // cacheline release hint for ld-ld violation check 
A
Allen 已提交
380 381
}

382
class DCacheIO(implicit p: Parameters) extends DCacheBundle {
J
Jiawei Lin 已提交
383
  val hartId = Input(UInt(8.W))
A
Allen 已提交
384
  val lsu = new DCacheToLsuIO
385
  val csr = new L1CacheToCsrIO
386
  val error = new L1CacheErrorInfo
387
  val mshrFull = Output(Bool())
A
Allen 已提交
388 389 390 391 392 393 394 395
}


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

  val clientParameters = TLMasterPortParameters.v1(
    Seq(TLMasterParameters.v1(
      name = "dcache",
Z
zhanglinjuan 已提交
396
      sourceId = IdRange(0, nEntries + 1),
A
Allen 已提交
397
      supportsProbe = TransferSizes(cfg.blockBytes)
398 399 400
    )),
    requestFields = cacheParams.reqFields,
    echoFields = cacheParams.echoFields
A
Allen 已提交
401 402 403 404 405 406 407 408
  )

  val clientNode = TLClientNode(Seq(clientParameters))

  lazy val module = new DCacheImp(this)
}


409
class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters with HasPerfEvents {
A
Allen 已提交
410 411 412 413 414 415

  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 已提交
416 417 418 419 420 421 422 423 424 425
  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)
426

A
Allen 已提交
427 428
  //----------------------------------------
  // core data structures
429
  val bankedDataArray = Module(new BankedDataArray)
430 431
  val metaArray = Module(new AsynchronousMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2))
  val errorArray = Module(new ErrorArray(readPorts = LoadPipelineWidth + 1, writePorts = 2)) // TODO: add it to meta array
Z
zhanglinjuan 已提交
432
  val tagArray = Module(new DuplicatedTagArray(readPorts = LoadPipelineWidth + 1))
433 434
  bankedDataArray.dump()

A
Allen 已提交
435 436
  //----------------------------------------
  // core modules
437
  val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))})
A
Allen 已提交
438
  val atomicsReplayUnit = Module(new AtomicsReplayEntry)
439
  val mainPipe   = Module(new MainPipe)
Z
zhanglinjuan 已提交
440
  val refillPipe = Module(new RefillPipe)
A
Allen 已提交
441 442
  val missQueue  = Module(new MissQueue(edge))
  val probeQueue = Module(new ProbeQueue(edge))
443
  val wb         = Module(new WritebackQueue(edge))
A
Allen 已提交
444

J
Jiawei Lin 已提交
445 446
  missQueue.io.hartId := io.hartId

447 448
  val errors = ldu.map(_.io.error) ++ // load error
    Seq(mainPipe.io.error) // store / misc error 
449
  io.error <> RegNext(Mux1H(errors.map(e => RegNext(e.valid) -> RegNext(e))))
450

A
Allen 已提交
451 452
  //----------------------------------------
  // meta array
Z
zhanglinjuan 已提交
453
  val meta_read_ports = ldu.map(_.io.meta_read) ++
454
    Seq(mainPipe.io.meta_read)
Z
zhanglinjuan 已提交
455
  val meta_resp_ports = ldu.map(_.io.meta_resp) ++
456
    Seq(mainPipe.io.meta_resp)
Z
zhanglinjuan 已提交
457 458
  val meta_write_ports = Seq(
    mainPipe.io.meta_write,
459
    refillPipe.io.meta_write
Z
zhanglinjuan 已提交
460 461 462 463
  )
  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 已提交
464

465 466 467 468 469 470 471 472 473 474
  val error_flag_resp_ports = ldu.map(_.io.error_flag_resp) ++
    Seq(mainPipe.io.error_flag_resp)
  val error_flag_write_ports = Seq(
    mainPipe.io.error_flag_write,
    refillPipe.io.error_flag_write
  )
  meta_read_ports.zip(errorArray.io.read).foreach { case (p, r) => r <> p }
  error_flag_resp_ports.zip(errorArray.io.resp).foreach { case (p, r) => p := r }
  error_flag_write_ports.zip(errorArray.io.write).foreach { case (p, w) => w <> p }

Z
zhanglinjuan 已提交
475 476 477 478 479 480 481
  //----------------------------------------
  // 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 已提交
482
  }
Z
zhanglinjuan 已提交
483 484 485 486 487 488 489
  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 已提交
490 491 492 493

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

Z
zhanglinjuan 已提交
494 495 496 497 498
  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
A
Allen 已提交
499

500
  bankedDataArray.io.readline <> mainPipe.io.data_read
501
  bankedDataArray.io.readline_intend := mainPipe.io.data_read_intend
502
  mainPipe.io.readline_error_delayed := bankedDataArray.io.readline_error_delayed
Z
zhanglinjuan 已提交
503
  mainPipe.io.data_resp := bankedDataArray.io.resp
A
Allen 已提交
504

505 506
  (0 until LoadPipelineWidth).map(i => {
    bankedDataArray.io.read(i) <> ldu(i).io.banked_data_read
507
    bankedDataArray.io.read_error_delayed(i) <> ldu(i).io.read_error_delayed
508 509 510 511 512 513

    ldu(i).io.banked_data_resp := bankedDataArray.io.resp

    ldu(i).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(i)
    ldu(i).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(i)
  })
A
Allen 已提交
514 515 516 517 518 519

  //----------------------------------------
  // load pipe
  // the s1 kill signal
  // only lsu uses this, replay never kills
  for (w <- 0 until LoadPipelineWidth) {
520
    ldu(w).io.lsu <> io.lsu.load(w)
A
Allen 已提交
521 522 523 524

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

Y
Yinan Xu 已提交
526
    ldu(w).io.disable_ld_fast_wakeup :=
527
      bankedDataArray.io.disable_ld_fast_wakeup(w) // load pipe fast wake up should be disabled when bank conflict
A
Allen 已提交
528 529 530 531 532
  }

  //----------------------------------------
  // atomics
  // atomics not finished yet
A
Allen 已提交
533
  io.lsu.atomics <> atomicsReplayUnit.io.lsu
W
William Wang 已提交
534
  atomicsReplayUnit.io.pipe_resp := RegNext(mainPipe.io.atomic_resp)
535
  atomicsReplayUnit.io.block_lr <> mainPipe.io.block_lr
A
Allen 已提交
536 537 538 539 540 541 542

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

  // Request
W
William Wang 已提交
543
  val missReqArb = Module(new Arbiter(new MissReq, MissReqPortCount))
A
Allen 已提交
544

W
William Wang 已提交
545
  missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req
A
Allen 已提交
546 547
  for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req }

548 549 550
  wb.io.miss_req.valid := missReqArb.io.out.valid
  wb.io.miss_req.bits  := missReqArb.io.out.bits.addr

W
William Wang 已提交
551 552 553 554 555 556
  // block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req)
  missReqArb.io.out <> missQueue.io.req
  when(wb.io.block_miss_req) {
    missQueue.io.req.bits.cancel := true.B
    missReqArb.io.out.ready := false.B
  }
A
Allen 已提交
557 558

  // refill to load queue
Z
zhanglinjuan 已提交
559
  io.lsu.lsq <> missQueue.io.refill_to_ldq
A
Allen 已提交
560 561 562 563

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

W
William Wang 已提交
566
  missQueue.io.main_pipe_resp := RegNext(mainPipe.io.atomic_resp)
A
Allen 已提交
567 568 569

  //----------------------------------------
  // probe
570 571
  // probeQueue.io.mem_probe <> bus.b
  block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block)
Z
zhanglinjuan 已提交
572
  probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block
W
William Wang 已提交
573
  probeQueue.io.update_resv_set <> mainPipe.io.update_resv_set
A
Allen 已提交
574 575 576

  //----------------------------------------
  // mainPipe
Z
zhanglinjuan 已提交
577 578
  // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe,
  // block the req in main pipe
579 580
  block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, refillPipe.io.req.valid)
  block_decoupled(io.lsu.store.req, mainPipe.io.store_req, refillPipe.io.req.valid)
A
Allen 已提交
581

W
William Wang 已提交
582
  io.lsu.store.replay_resp := RegNext(mainPipe.io.store_replay_resp)
Z
zhanglinjuan 已提交
583 584
  io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp

Z
zhanglinjuan 已提交
585 586 587 588 589
  arbiter_with_pipereg(
    in = Seq(missQueue.io.main_pipe_req, atomicsReplayUnit.io.pipe_req),
    out = mainPipe.io.atomic_req,
    name = Some("main_pipe_atomic_req")
  )
Z
zhanglinjuan 已提交
590

W
William Wang 已提交
591
  mainPipe.io.invalid_resv_set := RegNext(wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits)
Z
zhanglinjuan 已提交
592 593

  //----------------------------------------
594
  // replace (main pipe)
Z
zhanglinjuan 已提交
595
  val mpStatus = mainPipe.io.status
596 597
  mainPipe.io.replace_req <> missQueue.io.replace_pipe_req
  missQueue.io.replace_pipe_resp := mainPipe.io.replace_resp
Z
zhanglinjuan 已提交
598 599 600

  //----------------------------------------
  // refill pipe
601 602 603 604 605 606
  val refillShouldBeBlocked = (mpStatus.s1.valid && mpStatus.s1.bits.set === missQueue.io.refill_pipe_req.bits.idx) ||
    Cat(Seq(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 已提交
607
  block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked)
608
  missQueue.io.refill_pipe_resp := refillPipe.io.resp
W
William Wang 已提交
609
  io.lsu.store.refill_hit_resp := RegNext(refillPipe.io.store_resp)
610

A
Allen 已提交
611 612 613
  //----------------------------------------
  // wb
  // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy
614

615
  wb.io.req <> mainPipe.io.wb
A
Allen 已提交
616
  bus.c     <> wb.io.mem_release
Z
zhanglinjuan 已提交
617 618
  wb.io.release_wakeup := refillPipe.io.release_wakeup
  wb.io.release_update := mainPipe.io.release_update
619 620 621 622 623 624 625 626

  io.lsu.release.valid := RegNext(wb.io.req.fire())
  io.lsu.release.bits.paddr := RegNext(wb.io.req.bits.addr)
  // Note: RegNext() is required by:
  // * load queue released flag update logic
  // * load / load violation check logic
  // * and timing requirements
  // CHANGE IT WITH CARE
A
Allen 已提交
627

628
  // connect bus d
A
Allen 已提交
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
  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 已提交
645 646 647 648 649 650 651 652 653 654 655 656
  //----------------------------------------
  // 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(
657
    mainPipe.io.replace_access
Z
zhanglinjuan 已提交
658 659 660 661 662 663 664 665 666 667
  )
  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)

668 669
  //----------------------------------------
  // assertions
A
Allen 已提交
670 671 672 673 674 675 676 677 678 679 680
  // 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)
  }

681 682
  //----------------------------------------
  // utility functions
683 684 685 686 687
  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
  }
688

689 690 691 692 693 694 695 696 697 698 699 700
  //----------------------------------------
  // 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
  tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req
  cacheOpDecoder.io.cache.resp.valid := bankedDataArray.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,
    tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits,
  ))
701
  cacheOpDecoder.io.error := io.error
702
  assert(!((bankedDataArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U))
703

704 705 706
  //----------------------------------------
  // performance counters
  val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire()))
707
  XSPerfAccumulate("num_loads", num_loads)
708 709

  io.mshrFull := missQueue.io.full
Z
zhanglinjuan 已提交
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734

  // 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)))
735

736 737
  val perfEvents = (Seq(wb, mainPipe, missQueue, probeQueue) ++ ldu).flatMap(_.getPerfEvents)
  generatePerfEvent()
A
Allen 已提交
738
}
739

740
class AMOHelper() extends ExtModule {
J
Jiawei Lin 已提交
741 742 743 744 745 746 747
  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)))
748 749
}

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

J
Jiawei Lin 已提交
752 753 754 755
  val useDcache = coreParams.dcacheParametersOpt.nonEmpty
  val clientNode = if (useDcache) TLIdentityNode() else null
  val dcache = if (useDcache) LazyModule(new DCache()) else null
  if (useDcache) {
756 757 758
    clientNode := dcache.clientNode
  }

759
  lazy val module = new LazyModuleImp(this) with HasPerfEvents {
760
    val io = IO(new DCacheIO)
761
    val perfEvents = if (!useDcache) {
J
Jiawei Lin 已提交
762
      // a fake dcache which uses dpi-c to access memory, only for debug usage!
763 764
      val fake_dcache = Module(new FakeDCache())
      io <> fake_dcache.io
765
      Seq()
766 767 768
    }
    else {
      io <> dcache.module.io
769
      dcache.module.getPerfEvents
770
    }
771
    generatePerfEvent()
772 773
  }
}