L1plusCache.scala 25.5 KB
Newer Older
A
Allen 已提交
1 2 3 4
package xiangshan.cache

import chisel3._
import chisel3.util._
5
import utils.{Code, RandomReplacement, HasTLDump, XSDebug, SRAMTemplate}
A
Allen 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19
import xiangshan.{HasXSLog}

import chipsalliance.rocketchip.config.Parameters
import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp, IdRange}
import freechips.rocketchip.tilelink.{TLClientNode, TLClientParameters,
  TLMasterParameters, TLMasterPortParameters, TLArbiter,
  TLEdgeOut, TLBundleA, TLBundleD,
  ClientStates, ClientMetadata
}

import scala.math.max


// L1plusCache specific parameters
20
// L1 L1plusCache is 256 set, 8 way associative, with 64byte block, a total of 128KB
A
Allen 已提交
21 22 23
// It's a virtually indexed, physically tagged cache.
case class L1plusCacheParameters
(
24
    nSets: Int = 256,
A
Allen 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
    nWays: Int = 8,
    rowBits: Int = 64,
    tagECC: Option[String] = None,
    dataECC: Option[String] = None,
    nMissEntries: Int = 1,
    blockBytes: Int = 64
) extends L1CacheParameters {

  def tagCode: Code = Code.fromString(tagECC)
  def dataCode: Code = Code.fromString(dataECC)

  def replacement = new RandomReplacement(nWays)
}

trait HasL1plusCacheParameters extends HasL1CacheParameters {
  val cacheParams = l1plusCacheParameters
J
jinyue110 已提交
41
  val icacheParams = icacheParameters
A
Allen 已提交
42
  val cfg = cacheParams
J
jinyue110 已提交
43
  val icfg = icacheParams
44
  val pcfg = l1plusPrefetcherParameters
A
Allen 已提交
45 46 47 48

  def encRowBits = cacheParams.dataCode.width(rowBits)

  def missQueueEntryIdWidth = log2Up(cfg.nMissEntries)
49 50 51 52 53 54
  // def icacheMissQueueEntryIdWidth = log2Up(icfg.nMissEntries)
  // L1plusCache has 2 clients: ICacheMissQueue and L1plusPrefetcher
  def nClients = 2
  def icacheMissQueueId = 0
  def l1plusPrefetcherId = 1
  def clientIdWidth = log2Up(nClients)
A
Allen 已提交
55
  def icacheMissQueueEntryIdWidth = log2Up(icfg.nMissEntries)
56 57 58
  def l1plusPrefetcherEntryIdWidth = log2Up(pcfg.nEntries)// TODO
  def entryIdWidth = max(icacheMissQueueEntryIdWidth, l1plusPrefetcherEntryIdWidth)
  def idWidth = clientIdWidth + entryIdWidth
59 60
  def clientId(id: UInt) = id(idWidth - 1, entryIdWidth)
  def entryId(id: UInt) = id(entryIdWidth - 1, 0)
A
Allen 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

  require(isPow2(nSets), s"nSets($nSets) must be pow2")
  require(isPow2(nWays), s"nWays($nWays) must be pow2")
  require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)")
}

abstract class L1plusCacheModule extends L1CacheModule
  with HasL1plusCacheParameters

abstract class L1plusCacheBundle extends L1CacheBundle
  with HasL1plusCacheParameters

// basic building blocks for L1plusCache
// MetaArray and DataArray
// TODO: dedup with DCache
class L1plusCacheMetadata extends L1plusCacheBundle {
77
  val valid = Bool()
A
Allen 已提交
78 79 80 81
  val tag = UInt(tagBits.W)
}

object L1plusCacheMetadata {
82
  def apply(tag: Bits, valid: Bool) = {
A
Allen 已提交
83 84
    val meta = Wire(new L1plusCacheMetadata)
    meta.tag := tag
85
    meta.valid := valid
A
Allen 已提交
86 87 88 89 90
    meta
  }
}

class L1plusCacheMetaReadReq extends L1plusCacheBundle {
J
jinyue110 已提交
91 92
  val tagIdx    = UInt(idxBits.W)
  val validIdx  = UInt(idxBits.W)
A
Allen 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
  val way_en = UInt(nWays.W)
  val tag    = UInt(tagBits.W)
}

class L1plusCacheMetaWriteReq extends L1plusCacheMetaReadReq {
  val data = new L1plusCacheMetadata
}

class L1plusCacheDataReadReq extends L1plusCacheBundle {
  // you can choose which bank to read to save power
  val rmask  = Bits(blockRows.W)
  val way_en = Bits(nWays.W)
  val addr   = Bits(untagBits.W)
}

// Now, we can write a cache-block in a single cycle
class L1plusCacheDataWriteReq extends L1plusCacheDataReadReq {
  val wmask  = Bits(blockRows.W)
  val data   = Vec(blockRows, Bits(encRowBits.W))
}

class L1plusCacheDataArray extends L1plusCacheModule {
  val io = IO(new L1plusCacheBundle {
    val read  = Flipped(DecoupledIO(new L1plusCacheDataReadReq))
    val write = Flipped(DecoupledIO(new L1plusCacheDataWriteReq))
    val resp  = Output(Vec(nWays, Vec(blockRows, Bits(encRowBits.W))))
  })

A
Allen 已提交
121 122
  val singlePort = true

A
Allen 已提交
123 124 125 126
  // write is always ready
  io.write.ready := true.B
  val waddr = (io.write.bits.addr >> blockOffBits).asUInt()
  val raddr = (io.read.bits.addr >> blockOffBits).asUInt()
A
Allen 已提交
127 128 129 130 131 132

  // for single port SRAM, do not allow read and write in the same cycle
  // for dual port SRAM, raddr === waddr is undefined behavior
  val rwhazard = if(singlePort) io.write.valid else io.write.valid && waddr === raddr
  io.read.ready := !rwhazard

A
Allen 已提交
133
  for (w <- 0 until nWays) {
134
    val array = Module(new SRAMTemplate(Bits((blockRows * encRowBits).W), set=nSets, way=1,
A
Allen 已提交
135 136 137 138 139 140 141 142 143 144 145
      shouldReset=false, holdRead=false, singlePort=singlePort))
    // data write
    array.io.w.req.valid := io.write.bits.way_en(w) && io.write.valid
    array.io.w.req.bits.apply(
      setIdx=waddr,
      data=io.write.bits.data.asUInt,
      waymask=1.U)

    // data read
    array.io.r.req.valid := io.read.bits.way_en(w) && io.read.valid
    array.io.r.req.bits.apply(setIdx=raddr)
A
Allen 已提交
146
    for (r <- 0 until blockRows) {
A
Allen 已提交
147
      io.resp(w)(r) := RegNext(array.io.r.resp.data(0)((r + 1) * encRowBits - 1, r * encRowBits))
A
Allen 已提交
148 149 150
    }
  }

A
Allen 已提交
151 152 153 154 155 156 157 158 159 160 161 162
  // since we use a RAM of block width
  // we must do full read and write
  when (io.write.valid) {
    assert (io.write.bits.wmask.andR)
  }

  // since we use a RAM of block width
  // we must do full read and write
  when (io.read.valid) {
    assert (io.read.bits.rmask.andR)
  }

A
Allen 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
  // debug output
  def dumpRead() = {
    when (io.read.valid) {
      XSDebug(s"DataArray Read valid way_en: %x addr: %x\n",
        io.read.bits.way_en, io.read.bits.addr)
    }
  }

  def dumpWrite() = {
    when (io.write.valid) {
      XSDebug(s"DataArray Write valid way_en: %x addr: %x\n",
        io.write.bits.way_en, io.write.bits.addr)

      (0 until blockRows) map { r =>
        XSDebug(s"cycle: $r data: %x wmask: %x\n",
          io.write.bits.data(r), io.write.bits.wmask(r))
      }
    }
  }

  def dumpResp() = {
      XSDebug(s"DataArray ReadResp\n")
      (0 until nWays) map { i =>
        (0 until blockRows) map { r =>
          XSDebug(s"way: $i cycle: $r data: %x\n", io.resp(i)(r))
        }
      }
  }

  def dump() = {
    dumpRead
    dumpWrite
    dumpResp
  }
}

199
class L1plusCacheMetadataArray extends L1plusCacheModule {
A
Allen 已提交
200 201 202 203
  val io = IO(new Bundle {
    val read = Flipped(Decoupled(new L1plusCacheMetaReadReq))
    val write = Flipped(Decoupled(new L1plusCacheMetaWriteReq))
    val resp = Output(Vec(nWays, new L1plusCacheMetadata))
A
Allen 已提交
204
    val flush = Input(Bool())
A
Allen 已提交
205
  })
J
jinyue110 已提交
206
  val waddr = io.write.bits.tagIdx
207 208 209 210 211
  val wvalid = io.write.bits.data.valid
  val wtag = io.write.bits.data.tag.asUInt
  val wmask = Mux((nWays == 1).B, (-1).asSInt, io.write.bits.way_en.asSInt).asBools
  val rmask = Mux((nWays == 1).B, (-1).asSInt, io.read.bits.way_en.asSInt).asBools

A
Allen 已提交
212
  def encTagBits = cacheParams.tagCode.width(tagBits)
213
  val tag_array = Module(new SRAMTemplate(UInt(encTagBits.W), set=nSets, way=nWays,
214
    shouldReset=false, holdRead=false, singlePort=true))
A
Allen 已提交
215 216 217 218 219 220
  val valid_array = Reg(Vec(nSets, UInt(nWays.W)))
  when (reset.toBool || io.flush) {
    for (i <- 0 until nSets) {
      valid_array(i) := 0.U
    }
  }
221
  XSDebug("valid_array:%x   flush:%d\n",valid_array.asUInt,io.flush)
222

223
  // tag write
A
Allen 已提交
224
  val wen = io.write.valid && !reset.toBool && !io.flush
225 226 227 228 229 230
  tag_array.io.w.req.valid := wen
  tag_array.io.w.req.bits.apply(
    setIdx=waddr,
    data=cacheParams.tagCode.encode(wtag),
    waymask=VecInit(wmask).asUInt)

A
Allen 已提交
231
  when (wen) {
232 233 234 235 236 237
    when (wvalid) {
      valid_array(waddr) := valid_array(waddr) | io.write.bits.way_en
    } .otherwise {
      valid_array(waddr) := valid_array(waddr) & ~io.write.bits.way_en
    }
  }
238 239 240

  // tag read
  tag_array.io.r.req.valid := io.read.fire()
J
jinyue110 已提交
241
  tag_array.io.r.req.bits.apply(setIdx=io.read.bits.tagIdx)
242
  val rtags = tag_array.io.r.resp.data.map(rdata =>
243
      cacheParams.tagCode.decode(rdata).corrected)
244

245
  for (i <- 0 until nWays) {
J
jinyue110 已提交
246
    io.resp(i).valid := valid_array(io.read.bits.validIdx)(i)
247
    io.resp(i).tag   := rtags(i)
A
Allen 已提交
248 249
  }

A
Allen 已提交
250 251
  // we use single port SRAM
  // do not allow read and write in the same cycle
252 253
  io.read.ready  := !io.write.valid && !reset.toBool && !io.flush && tag_array.io.r.req.ready
  io.write.ready := !reset.toBool && !io.flush && tag_array.io.w.req.ready
A
Allen 已提交
254 255 256

  def dumpRead() = {
    when (io.read.fire()) {
J
jinyue110 已提交
257 258
      XSDebug("MetaArray Read: idx: (t:%d v:%d) way_en: %x tag: %x\n",
        io.read.bits.tagIdx, io.read.bits.validIdx, io.read.bits.way_en, io.read.bits.tag)
A
Allen 已提交
259 260 261 262 263
    }
  }

  def dumpWrite() = {
    when (io.write.fire()) {
264
      XSDebug("MetaArray Write: idx: %d way_en: %x tag: %x new_tag: %x new_valid: %x\n",
J
jinyue110 已提交
265
        io.write.bits.tagIdx, io.write.bits.way_en, io.write.bits.tag, io.write.bits.data.tag, io.write.bits.data.valid)
A
Allen 已提交
266 267 268 269 270
    }
  }

  def dumpResp() = {
    (0 until nWays) map { i =>
271 272
      XSDebug(s"MetaArray Resp: way: $i tag: %x valid: %x\n",
        io.resp(i).tag, io.resp(i).valid)
A
Allen 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286
    }
  }

  def dump() = {
    dumpRead
    dumpWrite
    dumpResp
  }
}

class L1plusCacheReq extends L1plusCacheBundle
{
  val cmd  = UInt(M_SZ.W)
  val addr = UInt(PAddrBits.W)
287
  val id   = UInt(idWidth.W)
Z
zhanglinjuan 已提交
288 289 290 291

  override def toPrintable: Printable = {
    p"cmd=${Binary(cmd)} addr=0x${Hexadecimal(addr)} id=${Binary(id)}"
  }
A
Allen 已提交
292 293 294 295 296
}

class L1plusCacheResp extends L1plusCacheBundle
{
  val data = UInt((cfg.blockBytes * 8).W)
297
  val id   = UInt(idWidth.W)
Z
zhanglinjuan 已提交
298 299 300 301

  override def toPrintable: Printable = {
    p"id=${Binary(id)} data=${Hexadecimal(data)}"
  }
A
Allen 已提交
302 303 304 305 306 307
}

class L1plusCacheIO extends L1plusCacheBundle
{
  val req  = DecoupledIO(new L1plusCacheReq)
  val resp = Flipped(DecoupledIO(new L1plusCacheResp))
A
Allen 已提交
308 309
  val flush = Output(Bool())
  val empty = Input(Bool())
Z
zhanglinjuan 已提交
310 311 312 313 314

  override def toPrintable: Printable = {
    p"req: v=${req.valid} r=${req.ready} ${req.bits} " +
      p"resp: v=${resp.valid} r=${resp.ready} ${resp.bits}"
  }
A
Allen 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
}

class L1plusCache()(implicit p: Parameters) extends LazyModule with HasL1plusCacheParameters {

  val clientParameters = TLMasterPortParameters.v1(
    Seq(TLMasterParameters.v1(
      name = "l1plusCache",
      sourceId = IdRange(0, cfg.nMissEntries)
    ))
  )

  val clientNode = TLClientNode(Seq(clientParameters))

  lazy val module = new L1plusCacheImp(this)
}


class L1plusCacheImp(outer: L1plusCache) extends LazyModuleImp(outer) with HasL1plusCacheParameters with HasXSLog {

  val io = IO(Flipped(new L1plusCacheIO))

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

  //----------------------------------------
  // core data structures
  val dataArray = Module(new L1plusCacheDataArray)

343
  val metaArray = Module(new L1plusCacheMetadataArray())
A
Allen 已提交
344 345 346 347 348 349 350 351 352
  dataArray.dump()
  metaArray.dump()


  //----------------------------------------
  val pipe = Module(new L1plusCachePipe)
  val missQueue = Module(new L1plusCacheMissQueue(edge))
  val resp_arb = Module(new Arbiter(new L1plusCacheResp, 2))

A
Allen 已提交
353 354
  val flush_block_req = Wire(Bool())
  val req_block = block_req(io.req.bits.addr) || flush_block_req
A
Allen 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
  block_decoupled(io.req, pipe.io.req, req_block)
  XSDebug(req_block, "Request blocked\n")

  pipe.io.data_read <> dataArray.io.read
  pipe.io.data_resp <> dataArray.io.resp
  pipe.io.meta_read <> metaArray.io.read
  pipe.io.meta_resp <> metaArray.io.resp

  missQueue.io.req <> pipe.io.miss_req
  bus.a <> missQueue.io.mem_acquire
  missQueue.io.mem_grant <> bus.d
  metaArray.io.write <> missQueue.io.meta_write
  dataArray.io.write <> missQueue.io.refill

  // response
  io.resp           <> resp_arb.io.out
  resp_arb.io.in(0) <> pipe.io.resp
  resp_arb.io.in(1) <> missQueue.io.resp

  bus.b.ready := false.B
  bus.c.valid := false.B
  bus.c.bits  := DontCare
  bus.e.valid := false.B
  bus.e.bits  := DontCare

A
Allen 已提交
380 381 382 383 384 385 386
  // flush state machine
  val s_invalid :: s_drain_cache :: s_flush_cache :: s_send_resp :: Nil = Enum(4)
  val state = RegInit(s_invalid)

  switch (state) {
    is (s_invalid) {
      when (io.flush) {
387
        state := s_drain_cache
A
Allen 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
      }
    }
    is (s_drain_cache) {
      when (pipe.io.empty && missQueue.io.empty) {
        state := s_flush_cache
      }
    }
    is (s_flush_cache) {
      state := s_send_resp
    }
    is (s_send_resp) {
      state := s_invalid
    }
  }
  metaArray.io.flush := state === s_flush_cache
  io.empty := state === s_send_resp
  flush_block_req := state =/= s_invalid

A
Allen 已提交
406 407 408 409
  when (state =/= s_invalid) {
    XSDebug(s"L1plusCache flush state machine: %d\n", state)
  }

A
Allen 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
  // to simplify synchronization, we do not allow reqs with same indexes
  def block_req(addr: UInt) = {
    val pipe_idx_matches = VecInit(pipe.io.inflight_req_idxes map (entry => entry.valid && entry.bits === get_idx(addr)))
    val pipe_idx_match = pipe_idx_matches.reduce(_||_)

    val miss_idx_matches = VecInit(missQueue.io.inflight_req_idxes map (entry => entry.valid && entry.bits === get_idx(addr)))
    val miss_idx_match = miss_idx_matches.reduce(_||_)

    pipe_idx_match || miss_idx_match
  }

  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
  }
A
Allen 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444

  // debug output
  when (io.req.valid) {
    XSDebug(s"L1plusCache req cmd: %x addr: %x id: %d\n",
      io.req.bits.cmd, io.req.bits.addr, io.req.bits.id)
  }

  when (io.resp.valid) {
    XSDebug(s"L1plusCache resp data: %x id: %d\n",
      io.resp.bits.data, io.resp.bits.id)
  }

  when (io.flush) {
    XSDebug(s"L1plusCache flush\n")
  }

  when (io.empty) {
    XSDebug(s"L1plusCache empty\n")
  }
A
Allen 已提交
445 446 447 448 449 450 451 452 453 454 455 456 457
}

class L1plusCachePipe extends L1plusCacheModule
{
  val io = IO(new L1plusCacheBundle{
    val req  = Flipped(DecoupledIO(new L1plusCacheReq))
    val resp = DecoupledIO(new L1plusCacheResp)
    val data_read  = DecoupledIO(new L1plusCacheDataReadReq)
    val data_resp  = Input(Vec(nWays, Vec(blockRows, Bits(encRowBits.W))))
    val meta_read  = DecoupledIO(new L1plusCacheMetaReadReq)
    val meta_resp  = Input(Vec(nWays, new L1plusCacheMetadata))
    val miss_req   = DecoupledIO(new L1plusCacheMissReq)
    val inflight_req_idxes = Output(Vec(2, Valid(UInt())))
A
Allen 已提交
458
    val empty = Output(Bool())
A
Allen 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
  })

  val s0_passdown = Wire(Bool())
  val s1_passdown = Wire(Bool())
  val s2_passdown = Wire(Bool())

  val s0_valid = Wire(Bool())
  val s1_valid = Wire(Bool())
  val s2_valid = Wire(Bool())

  // requests
  val can_accept_req = !s1_valid || s1_passdown
  io.req.ready := io.meta_read.ready && io.data_read.ready && can_accept_req
  io.meta_read.valid := io.req.valid && can_accept_req
  io.data_read.valid := io.req.valid && can_accept_req

  val meta_read = io.meta_read.bits
  val data_read = io.data_read.bits

  // Tag read for new requests
J
jinyue110 已提交
479
  meta_read.tagIdx    := get_idx(io.req.bits.addr)
A
Allen 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493
  meta_read.way_en := ~0.U(nWays.W)
  meta_read.tag    := DontCare
  // Data read for new requests
  data_read.addr   := io.req.bits.addr
  data_read.way_en := ~0.U(nWays.W)
  data_read.rmask  := ~0.U(blockRows.W)

  // Pipeline
  // stage 0
  s0_valid := io.req.fire()
  val s0_req = io.req.bits

  s0_passdown := s0_valid

494
  assert(!(s0_valid && s0_req.cmd =/= MemoryOpConstants.M_XRD && s0_req.cmd =/= MemoryOpConstants.M_PFR), "L1plusCachePipe only accepts read req")
A
Allen 已提交
495 496 497 498 499 500 501 502 503 504 505

  dump_pipeline_reqs("L1plusCachePipe s0", s0_valid, s0_req)
// stage 1
  val s1_req = RegEnable(s0_req, s0_passdown)
  val s1_valid_reg = RegEnable(s0_valid, init = false.B, enable = s0_passdown)
  val s1_addr = s1_req.addr
  when (s1_passdown && !s0_passdown) {
    s1_valid_reg := false.B
  }
  s1_valid := s1_valid_reg

J
jinyue110 已提交
506 507 508
  meta_read.validIdx  := get_idx(s1_addr)


A
Allen 已提交
509 510 511 512 513 514
  dump_pipeline_reqs("L1plusCachePipe s1", s1_valid, s1_req)

  val meta_resp = io.meta_resp
  // tag check
  def wayMap[T <: Data](f: Int => T) = VecInit((0 until nWays).map(f))
  val s1_tag_eq_way = wayMap((w: Int) => meta_resp(w).tag === (get_tag(s1_addr))).asUInt
515
  val s1_tag_match_way = wayMap((w: Int) => s1_tag_eq_way(w) && meta_resp(w).valid).asUInt
A
Allen 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529

  s1_passdown := s1_valid && (!s2_valid || s2_passdown)

  // stage 2
  val s2_req   = RegEnable(s1_req, s1_passdown)
  val s2_valid_reg = RegEnable(s1_valid, init=false.B, enable=s1_passdown)
  when (s2_passdown && !s1_passdown) {
    s2_valid_reg := false.B
  }
  s2_valid := s2_valid_reg

  dump_pipeline_reqs("L1plusCachePipe s2", s2_valid, s2_req)

  val s2_tag_match_way = RegEnable(s1_tag_match_way, s1_passdown)
530
  val s2_hit           = s2_tag_match_way.orR
A
Allen 已提交
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
  val s2_hit_way       = OHToUInt(s2_tag_match_way, nWays)

  val data_resp = io.data_resp
  val s2_data = data_resp(s2_hit_way)
  val s2_data_decoded = Cat((0 until blockRows).reverse map { r =>
      val data = s2_data(r)
      val decoded = cacheParams.dataCode.decode(data)
      assert(!(s2_valid && s2_hit && decoded.uncorrectable))
      decoded.corrected
    })

  io.resp.valid     := s2_valid && s2_hit
  io.resp.bits.data := s2_data_decoded
  io.resp.bits.id   := s2_req.id

  // replacement policy
  val replacer = cacheParams.replacement
  val replaced_way_en = UIntToOH(replacer.way)

  io.miss_req.valid       := s2_valid && !s2_hit
  io.miss_req.bits.id     := s2_req.id
  io.miss_req.bits.cmd    := M_XRD
  io.miss_req.bits.addr   := s2_req.addr
  io.miss_req.bits.way_en := replaced_way_en

  s2_passdown := s2_valid && ((s2_hit && io.resp.ready) || (!s2_hit && io.miss_req.ready))

  when (io.miss_req.fire()) {
    replacer.miss
  }

  val resp = io.resp
  when (resp.valid) {
    XSDebug(s"L1plusCachePipe resp: data: %x id: %d\n",
      resp.bits.data, resp.bits.id)
  }

  io.inflight_req_idxes(0).valid := s1_valid
  io.inflight_req_idxes(0).bits := get_idx(s1_req.addr)
  io.inflight_req_idxes(1).valid := s2_valid
  io.inflight_req_idxes(1).bits := get_idx(s2_req.addr)

A
Allen 已提交
573 574
  io.empty := !s0_valid && !s1_valid && !s2_valid

A
Allen 已提交
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
  // -------
  // Debug logging functions
  def dump_pipeline_reqs(pipeline_stage_name: String, valid: Bool, req: L1plusCacheReq) = {
      when (valid) {
        XSDebug(
          s"$pipeline_stage_name cmd: %x addr: %x id: %d\n",
          req.cmd, req.addr, req.id
        )
      }
  }
}

class L1plusCacheMissReq extends L1plusCacheBundle
{
  // transaction id
590
  val id     = UInt(idWidth.W)
A
Allen 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 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 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
  val cmd    = UInt(M_SZ.W)
  val addr   = UInt(PAddrBits.W)
  val way_en = UInt(nWays.W)
}

class L1plusCacheMissEntry(edge: TLEdgeOut) extends L1plusCacheModule
{
  val io = IO(new Bundle {
    val id          = Input(UInt())
    val req         = Flipped(DecoupledIO(new L1plusCacheMissReq))
    val resp        = DecoupledIO(new L1plusCacheResp)

    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
    val mem_grant   = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))

    val meta_write  = DecoupledIO(new L1plusCacheMetaWriteReq)
    val refill      = DecoupledIO(new L1plusCacheDataWriteReq)

    val idx = Output(Valid(UInt()))
    val tag = Output(Valid(UInt()))
  })

  val s_invalid :: s_refill_req :: s_refill_resp :: s_send_resp :: s_data_write_req :: s_meta_write_req :: Nil = Enum(6)

  val state = RegInit(s_invalid)

  val req     = Reg(new L1plusCacheMissReq)
  val req_idx = get_idx(req.addr)
  val req_tag = get_tag(req.addr)

  val (_, _, refill_done, refill_address_inc) = edge.addr_inc(io.mem_grant)

  val refill_ctr  = Reg(UInt(log2Up(refillCycles).W))

  io.idx.valid := state =/= s_invalid
  io.tag.valid := state =/= s_invalid
  io.idx.bits  := req_idx
  io.tag.bits  := req_tag

  // assign default values to output signals
  io.req.ready           := false.B
  io.resp.valid          := false.B
  io.resp.bits           := DontCare

  io.mem_acquire.valid   := false.B
  io.mem_acquire.bits    := DontCare

  io.mem_grant.ready     := false.B

  io.meta_write.valid    := false.B
  io.meta_write.bits     := DontCare

  io.refill.valid        := false.B
  io.refill.bits         := DontCare

  when (state =/= s_invalid) {
    XSDebug("entry: %d state: %d\n", io.id, state)
    XSDebug("entry: %d idx_valid: %b idx: %x tag_valid: %b tag: %x\n",
      io.id, io.idx.valid, io.idx.bits, io.tag.valid, io.tag.bits)
  }


  // --------------------------------------------
  // s_invalid: receive requests
  when (state === s_invalid) {
    io.req.ready := true.B

    when (io.req.fire()) {
      refill_ctr := 0.U
      req := io.req.bits
      state := s_refill_req
    }
  }

  // --------------------------------------------
  // refill
  when (state === s_refill_req) {
    io.mem_acquire.valid := true.B
    io.mem_acquire.bits  := edge.Get(
      fromSource      = io.id,
      toAddress       = req.addr,
      lgSize          = (log2Up(cfg.blockBytes)).U)._2
    when (io.mem_acquire.fire()) {
      state := s_refill_resp
    }
  }

  val refill_data = Reg(Vec(blockRows, UInt(encRowBits.W)))
  // not encoded data
  val refill_data_raw = Reg(Vec(blockRows, UInt(rowBits.W)))
  when (state === s_refill_resp) {
    io.mem_grant.ready := true.B

    when (edge.hasData(io.mem_grant.bits)) {
      when (io.mem_grant.fire()) {
        refill_ctr := refill_ctr + 1.U
        for (i <- 0 until beatRows) {
          val row = io.mem_grant.bits.data(rowBits * (i + 1) - 1, rowBits * i)
          refill_data((refill_ctr << log2Floor(beatRows)) + i.U) := cacheParams.dataCode.encode(row)
          refill_data_raw((refill_ctr << log2Floor(beatRows)) + i.U) := row
        }

        when (refill_ctr === (refillCycles - 1).U) {
          assert(refill_done, "refill not done!")
          state := s_send_resp
        }
      }
    }
  }

  // --------------------------------------------
  when (state === s_send_resp) {

    val resp_data = Cat((0 until blockRows).reverse map { r => refill_data_raw(r) })
    io.resp.valid     := true.B
    io.resp.bits.data := resp_data
    io.resp.bits.id   := req.id

    when (io.resp.fire()) {
      state := s_data_write_req
    }
  }

  // --------------------------------------------
  // data write
  when (state === s_data_write_req) {
    io.refill.valid        := true.B
    io.refill.bits.addr    := req.addr
    io.refill.bits.way_en  := req.way_en
    io.refill.bits.wmask   := ~0.U(blockRows.W)
    io.refill.bits.rmask   := DontCare
    io.refill.bits.data    := refill_data

    when (io.refill.fire()) {
      state := s_meta_write_req
    }
  }

  // --------------------------------------------
  // meta write
  when (state === s_meta_write_req) {
732
    io.meta_write.valid           := true.B
J
jinyue110 已提交
733 734
    io.meta_write.bits.tagIdx        := req_idx
    io.meta_write.bits.validIdx  := req_idx
735 736 737
    io.meta_write.bits.data.valid := true.B
    io.meta_write.bits.data.tag   := req_tag
    io.meta_write.bits.way_en     := req.way_en
A
Allen 已提交
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756

    when (io.meta_write.fire()) {
      state := s_invalid
    }
  }
}

class L1plusCacheMissQueue(edge: TLEdgeOut) extends L1plusCacheModule with HasTLDump
{
  val io = IO(new Bundle {
    val req         = Flipped(DecoupledIO(new L1plusCacheMissReq))
    val resp        = DecoupledIO(new L1plusCacheResp)

    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
    val mem_grant   = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))

    val meta_write  = DecoupledIO(new L1plusCacheMetaWriteReq)
    val refill      = DecoupledIO(new L1plusCacheDataWriteReq)
    val inflight_req_idxes = Output(Vec(cfg.nMissEntries, Valid(UInt())))
A
Allen 已提交
757
    val empty       = Output(Bool())
A
Allen 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
  })

  val resp_arb       = Module(new Arbiter(new L1plusCacheResp,           cfg.nMissEntries))
  val meta_write_arb = Module(new Arbiter(new L1plusCacheMetaWriteReq,   cfg.nMissEntries))
  val refill_arb     = Module(new Arbiter(new L1plusCacheDataWriteReq,   cfg.nMissEntries))

  // assign default values to output signals
  io.mem_grant.ready := false.B

  val idx_matches = Wire(Vec(cfg.nMissEntries, Bool()))
  val tag_matches = Wire(Vec(cfg.nMissEntries, Bool()))

  val tag_match   = Mux1H(idx_matches, tag_matches)
  val idx_match   = idx_matches.reduce(_||_)

  val req             = io.req
  val entry_alloc_idx = Wire(UInt())
  val pri_rdy         = WireInit(false.B)
  val pri_val         = req.valid && !idx_match

  val entries = (0 until cfg.nMissEntries) map { i =>
    val entry = Module(new L1plusCacheMissEntry(edge))

    entry.io.id := i.U(missQueueEntryIdWidth.W)

    idx_matches(i) := entry.io.idx.valid && entry.io.idx.bits === get_idx(req.bits.addr)
    tag_matches(i) := entry.io.tag.valid && entry.io.tag.bits === get_tag(req.bits.addr)
    io.inflight_req_idxes(i) <> entry.io.idx

    // req and resp
    entry.io.req.valid := (i.U === entry_alloc_idx) && pri_val
    when (i.U === entry_alloc_idx) {
      pri_rdy := entry.io.req.ready
    }
    entry.io.req.bits  := req.bits

    resp_arb.io.in(i)  <> entry.io.resp

    // tilelink
    entry.io.mem_grant.valid := false.B
    entry.io.mem_grant.bits  := DontCare
    when (io.mem_grant.bits.source === i.U) {
      entry.io.mem_grant <> io.mem_grant
    }

    // meta and data write
    meta_write_arb.io.in(i) <>  entry.io.meta_write
    refill_arb.io.in(i)     <>  entry.io.refill

    entry
  }

  entry_alloc_idx    := PriorityEncoder(entries.map(m=>m.io.req.ready))

  // whenever index matches, do not let it in
  req.ready     := pri_rdy && !idx_match
  io.resp       <> resp_arb.io.out
  io.meta_write <> meta_write_arb.io.out
  io.refill     <> refill_arb.io.out

  TLArbiter.lowestFromSeq(edge, io.mem_acquire, entries.map(_.io.mem_acquire))

A
Allen 已提交
820 821
  io.empty := VecInit(entries.map(m=>m.io.req.ready)).asUInt.andR

A
Allen 已提交
822 823 824 825 826 827 828 829 830 831 832 833 834
  // print all input/output requests for debug purpose
  // print req
  XSDebug(req.fire(), "req id: %d cmd: %x addr: %x way_en: %x\n",
    req.bits.id, req.bits.cmd, req.bits.addr, req.bits.way_en)

  val resp = io.resp
  XSDebug(resp.fire(), s"resp: data: %x id: %d\n",
    resp.bits.data, resp.bits.id)

  // print refill
  XSDebug(io.refill.fire(), "refill addr %x\n", io.refill.bits.addr)

  // print meta_write
835
  XSDebug(io.meta_write.fire(), "meta_write idx %x way_en: %x old_tag: %x new_valid: %d new_tag: %x\n",
J
jinyue110 已提交
836
    io.meta_write.bits.tagIdx, io.meta_write.bits.way_en, io.meta_write.bits.tag,
837
    io.meta_write.bits.data.valid, io.meta_write.bits.data.tag)
A
Allen 已提交
838 839 840 841 842 843 844 845 846 847 848

  // print tilelink messages
  when (io.mem_acquire.fire()) {
    XSDebug("mem_acquire ")
    io.mem_acquire.bits.dump
  }
  when (io.mem_grant.fire()) {
    XSDebug("mem_grant ")
    io.mem_grant.bits.dump
  }
}