MissQueue.scala 26.7 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
package xiangshan.cache

19
import chipsalliance.rocketchip.config.Parameters
A
Allen 已提交
20 21
import chisel3._
import chisel3.util._
Z
zhanglinjuan 已提交
22
import xiangshan._
23
import utils._
24
import utility._
25
import freechips.rocketchip.tilelink._
Z
zhanglinjuan 已提交
26 27 28
import freechips.rocketchip.tilelink.ClientStates._
import freechips.rocketchip.tilelink.MemoryOpCategories._
import freechips.rocketchip.tilelink.TLPermissions._
29
import difftest._
30
import huancun.{AliasKey, DirtyKey, PreferCacheKey, PrefetchKey}
31
import utility.FastArbiter
Z
zhanglinjuan 已提交
32
import mem.{AddPipelineReg}
A
Allen 已提交
33

34
class MissReqWoStoreData(implicit p: Parameters) extends DCacheBundle {
A
Allen 已提交
35
  val source = UInt(sourceTypeWidth.W)
Z
zhanglinjuan 已提交
36 37 38 39
  val cmd = UInt(M_SZ.W)
  val addr = UInt(PAddrBits.W)
  val vaddr = UInt(VAddrBits.W)
  val way_en = UInt(DCacheWays.W)
A
Allen 已提交
40 41

  // store
42
  val full_overwrite = Bool()
A
Allen 已提交
43 44 45 46

  // which word does amo work on?
  val word_idx = UInt(log2Up(blockWords).W)
  val amo_data = UInt(DataBits.W)
Z
zhanglinjuan 已提交
47
  val amo_mask = UInt((DataBits / 8).W)
A
Allen 已提交
48

Z
zhanglinjuan 已提交
49 50 51 52
  val req_coh = new ClientMetadata
  val replace_coh = new ClientMetadata
  val replace_tag = UInt(tagBits.W)
  val id = UInt(reqIdWidth.W)
A
Allen 已提交
53

W
William Wang 已提交
54 55 56 57 58 59 60 61 62 63
  // For now, miss queue entry req is actually valid when req.valid && !cancel
  // * req.valid is fast to generate
  // * cancel is slow to generate, it will not be used until the last moment
  //
  // cancel may come from the following sources:
  // 1. miss req blocked by writeback queue: 
  //      a writeback req of the same address is in progress
  // 2. pmp check failed
  val cancel = Bool() // cancel is slow to generate, it will cancel missreq.valid

Z
zhanglinjuan 已提交
64
  def isLoad = source === LOAD_SOURCE.U
65
  def isStore = source === STORE_SOURCE.U
Z
zhanglinjuan 已提交
66 67
  def isAMO = source === AMO_SOURCE.U
  def hit = req_coh.isValid()
A
Allen 已提交
68 69
}

70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
class MissReqStoreData(implicit p: Parameters) extends DCacheBundle {
  // store data and store mask will be written to miss queue entry 
  // 1 cycle after req.fire() and meta write
  val store_data = UInt((cfg.blockBytes * 8).W)
  val store_mask = UInt(cfg.blockBytes.W)
}

class MissReq(implicit p: Parameters) extends MissReqWoStoreData {
  // store data and store mask will be written to miss queue entry 
  // 1 cycle after req.fire() and meta write
  val store_data = UInt((cfg.blockBytes * 8).W)
  val store_mask = UInt(cfg.blockBytes.W)

  def toMissReqStoreData(): MissReqStoreData = {
    val out = Wire(new MissReqStoreData)
    out.store_data := store_data
    out.store_mask := store_mask
    out
  }
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

  def toMissReqWoStoreData(): MissReqWoStoreData = {
    val out = Wire(new MissReqWoStoreData)
    out.source := source
    out.cmd := cmd
    out.addr := addr
    out.vaddr := vaddr
    out.way_en := way_en
    out.full_overwrite := full_overwrite
    out.word_idx := word_idx
    out.amo_data := amo_data
    out.amo_mask := amo_mask
    out.req_coh := req_coh
    out.replace_coh := replace_coh
    out.replace_tag := replace_tag
    out.id := id
    out.cancel := cancel
    out
  }
108 109
}

110
class MissEntry(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule {
Z
zhanglinjuan 已提交
111
  val io = IO(new Bundle() {
A
Allen 已提交
112
    // MSHR ID
Z
zhanglinjuan 已提交
113
    val id = Input(UInt(log2Up(cfg.nMissEntries).W))
A
Allen 已提交
114
    // client requests
115
    // MSHR update request, MSHR state and addr will be updated when req.fire()
116
    val req = Flipped(ValidIO(new MissReqWoStoreData))
117 118
    // store data and mask will be write to miss queue entry 1 cycle after req.fire()
    val req_data = Input(new MissReqStoreData)
W
William Wang 已提交
119 120
    // allocate this entry for new req
    val primary_valid = Input(Bool())
A
Allen 已提交
121 122 123 124 125 126
    // this entry is free and can be allocated to new reqs
    val primary_ready = Output(Bool())
    // this entry is busy, but it can merge the new req
    val secondary_ready = Output(Bool())
    // this entry is busy and it can not merge the new req
    val secondary_reject = Output(Bool())
W
William Wang 已提交
127

Z
zhanglinjuan 已提交
128
    val refill_to_ldq = ValidIO(new Refill)
A
Allen 已提交
129 130 131

    // bus
    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
Z
zhanglinjuan 已提交
132 133
    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
A
Allen 已提交
134

Z
zhanglinjuan 已提交
135 136
    // refill pipe
    val refill_pipe_req = DecoupledIO(new RefillPipeReq)
137
    val refill_pipe_resp = Input(Bool())
Z
zhanglinjuan 已提交
138 139

    // replace pipe
140
    val replace_pipe_req = DecoupledIO(new MainPipeReq)
Z
zhanglinjuan 已提交
141 142 143 144 145
    val replace_pipe_resp = Input(Bool())

    // main pipe: amo miss
    val main_pipe_req = DecoupledIO(new MainPipeReq)
    val main_pipe_resp = Input(Bool())
146 147

    val block_addr = ValidIO(UInt(PAddrBits.W))
Z
zhanglinjuan 已提交
148 149 150 151 152 153

    val debug_early_replace = ValidIO(new Bundle() {
      // info about the block that has been replaced
      val idx = UInt(idxBits.W) // vaddr
      val tag = UInt(tagBits.W) // paddr
    })
154
  })
A
Allen 已提交
155

W
William Wang 已提交
156 157
  assert(!RegNext(io.primary_valid && !io.primary_ready))

158
  val req = Reg(new MissReqWoStoreData)
159
  val req_store_mask = Reg(UInt(cfg.blockBytes.W))
160
  val req_valid = RegInit(false.B)
Z
zhanglinjuan 已提交
161
  val set = addr_to_dcache_set(req.vaddr)
A
Allen 已提交
162

163 164
  val s_acquire = RegInit(true.B)
  val s_grantack = RegInit(true.B)
Z
zhanglinjuan 已提交
165 166 167
  val s_replace_req = RegInit(true.B)
  val s_refill = RegInit(true.B)
  val s_mainpipe_req = RegInit(true.B)
168
  val s_write_storedata = RegInit(true.B)
Z
zhanglinjuan 已提交
169

170 171
  val w_grantfirst = RegInit(true.B)
  val w_grantlast = RegInit(true.B)
Z
zhanglinjuan 已提交
172
  val w_replace_resp = RegInit(true.B)
173
  val w_refill_resp = RegInit(true.B)
Z
zhanglinjuan 已提交
174
  val w_mainpipe_resp = RegInit(true.B)
A
Allen 已提交
175

176
  val release_entry = s_grantack && w_refill_resp && w_mainpipe_resp
177 178

  val acquire_not_sent = !s_acquire && !io.mem_acquire.ready
Z
zhanglinjuan 已提交
179
  val data_not_refilled = !w_grantfirst
A
Allen 已提交
180

181 182
  val error = RegInit(false.B)

Z
zhanglinjuan 已提交
183
  val should_refill_data_reg =  Reg(Bool())
184
  val should_refill_data = WireInit(should_refill_data_reg)
A
Allen 已提交
185

186 187
  // val full_overwrite = req.isStore && req_store_mask.andR
  val full_overwrite = Reg(Bool())
A
Allen 已提交
188

189 190
  val (_, _, refill_done, refill_count) = edge.count(io.mem_grant)
  val grant_param = Reg(UInt(TLPermissions.bdWidth.W))
A
Allen 已提交
191

192 193 194 195 196 197 198 199 200 201 202 203
  // refill data with store data, this reg will be used to store:
  // 1. store data (if needed), before l2 refill data
  // 2. store data and l2 refill data merged result (i.e. new cacheline taht will be write to data array)
  val refill_and_store_data = Reg(Vec(blockRows, UInt(rowBits.W)))
  // raw data refilled to l1 by l2
  val refill_data_raw = Reg(Vec(blockBytes/beatBytes, UInt(beatBits.W)))

  // allocate current miss queue entry for a miss req
  val primary_fire = WireInit(io.req.valid && io.primary_ready && io.primary_valid && !io.req.bits.cancel)
  // merge miss req to current miss queue entry
  val secondary_fire = WireInit(io.req.valid && io.secondary_ready && !io.req.bits.cancel)

W
William Wang 已提交
204 205 206 207
  when (release_entry && req_valid) {
    req_valid := false.B
  }

208 209 210 211 212 213
  when (!s_write_storedata && req_valid) {
    // store data will be write to miss queue entry 1 cycle after req.fire()
    s_write_storedata := true.B
    assert(RegNext(primary_fire || secondary_fire))
  }

W
William Wang 已提交
214
  when (primary_fire) {
215 216
    req_valid := true.B
    req := io.req.bits
217
    req.addr := get_block_addr(io.req.bits.addr)
A
Allen 已提交
218

219 220
    s_acquire := false.B
    s_grantack := false.B
Z
zhanglinjuan 已提交
221

222 223
    w_grantfirst := false.B
    w_grantlast := false.B
A
Allen 已提交
224

225 226 227
    s_write_storedata := !io.req.bits.isStore // only store need to wait for data
    full_overwrite := io.req.bits.isStore && io.req.bits.full_overwrite

Z
zhanglinjuan 已提交
228 229
    when (!io.req.bits.isAMO) {
      s_refill := false.B
230
      w_refill_resp := false.B
Z
zhanglinjuan 已提交
231 232 233 234 235 236
    }

    when (!io.req.bits.hit && io.req.bits.replace_coh.isValid() && !io.req.bits.isAMO) {
      s_replace_req := false.B
      w_replace_resp := false.B
    }
237

Z
zhanglinjuan 已提交
238 239 240 241 242 243
    when (io.req.bits.isAMO) {
      s_mainpipe_req := false.B
      w_mainpipe_resp := false.B
    }

    should_refill_data_reg := io.req.bits.isLoad
244
    error := false.B
A
Allen 已提交
245 246
  }

W
William Wang 已提交
247
  when (secondary_fire) {
Z
zhanglinjuan 已提交
248 249
    assert(io.req.bits.req_coh.state <= req.req_coh.state)
    assert(!(io.req.bits.isAMO || req.isAMO))
A
Allen 已提交
250
    // use the most uptodate meta
Z
zhanglinjuan 已提交
251
    req.req_coh := io.req.bits.req_coh
A
Allen 已提交
252

253 254
    when (io.req.bits.isStore) {
      req := io.req.bits
Z
zhanglinjuan 已提交
255 256 257 258
      req.addr := get_block_addr(io.req.bits.addr)
      req.way_en := req.way_en
      req.replace_coh := req.replace_coh
      req.replace_tag := req.replace_tag
259 260
      s_write_storedata := false.B // only store need to wait for data
      full_overwrite := io.req.bits.isStore && io.req.bits.full_overwrite
A
Allen 已提交
261 262
    }

263
    should_refill_data := should_refill_data_reg || io.req.bits.isLoad
264
    should_refill_data_reg := should_refill_data
A
Allen 已提交
265 266
  }

267 268 269
  when (io.mem_acquire.fire()) {
    s_acquire := true.B
  }
A
Allen 已提交
270

271 272 273 274 275 276 277 278 279
  // store data and mask write
  when (!s_write_storedata && req_valid) {
    req_store_mask := io.req_data.store_mask
    for (i <- 0 until blockRows) {
      refill_and_store_data(i) := io.req_data.store_data(rowBits * (i + 1) - 1, rowBits * i)
    }
  }

  // merge data refilled by l2 and store data, update miss queue entry, gen refill_req
280 281
  val new_data = Wire(Vec(blockRows, UInt(rowBits.W)))
  val new_mask = Wire(Vec(blockRows, UInt(rowBytes.W)))
282
  // merge refilled data and store data (if needed)
283 284 285 286 287
  def mergePutData(old_data: UInt, new_data: UInt, wmask: UInt): UInt = {
    val full_wmask = FillInterleaved(8, wmask)
    (~full_wmask & old_data | full_wmask & new_data)
  }
  for (i <- 0 until blockRows) {
288 289
    // new_data(i) := req.store_data(rowBits * (i + 1) - 1, rowBits * i)
    new_data(i) := refill_and_store_data(i)
290
    // we only need to merge data for Store
291
    new_mask(i) := Mux(req.isStore, req_store_mask(rowBytes * (i + 1) - 1, rowBytes * i), 0.U)
292
  }
293

294
  val hasData = RegInit(true.B)
295
  val isDirty = RegInit(false.B)
296 297 298 299 300 301 302 303
  when (io.mem_grant.fire()) {
    w_grantfirst := true.B
    grant_param := io.mem_grant.bits.param
    when (edge.hasData(io.mem_grant.bits)) {
      // GrantData
      for (i <- 0 until beatRows) {
        val idx = (refill_count << log2Floor(beatRows)) + i.U
        val grant_row = io.mem_grant.bits.data(rowBits * (i + 1) - 1, rowBits * i)
304
        refill_and_store_data(idx) := mergePutData(grant_row, new_data(idx), new_mask(idx))
305 306 307 308 309
      }
      w_grantlast := w_grantlast || refill_done
      hasData := true.B
    }.otherwise {
      // Grant
Z
zhanglinjuan 已提交
310
      assert(full_overwrite)
311
      for (i <- 0 until blockRows) {
312
        refill_and_store_data(i) := new_data(i)
313 314 315
      }
      w_grantlast := true.B
      hasData := false.B
A
Allen 已提交
316 317
    }

318 319
    error := io.mem_grant.bits.denied || io.mem_grant.bits.corrupt || error

320
    refill_data_raw(refill_count) := io.mem_grant.bits.data
321
    isDirty := io.mem_grant.bits.echo.lift(DirtyKey).getOrElse(false.B)
322
  }
A
Allen 已提交
323

324 325 326
  when (io.mem_finish.fire()) {
    s_grantack := true.B
  }
A
Allen 已提交
327

Z
zhanglinjuan 已提交
328 329 330 331 332 333 334 335 336 337
  when (io.replace_pipe_req.fire()) {
    s_replace_req := true.B
  }

  when (io.replace_pipe_resp) {
    w_replace_resp := true.B
  }

  when (io.refill_pipe_req.fire()) {
    s_refill := true.B
A
Allen 已提交
338 339
  }

340 341 342 343
  when (io.refill_pipe_resp) {
    w_refill_resp := true.B
  }

Z
zhanglinjuan 已提交
344 345
  when (io.main_pipe_req.fire()) {
    s_mainpipe_req := true.B
A
Allen 已提交
346 347
  }

Z
zhanglinjuan 已提交
348 349 350
  when (io.main_pipe_resp) {
    w_mainpipe_resp := true.B
  }
351

352
  def before_read_sent_can_merge(new_req: MissReqWoStoreData): Bool = {
Z
zhanglinjuan 已提交
353
    acquire_not_sent && req.isLoad && (new_req.isLoad || new_req.isStore)
354
  }
A
Allen 已提交
355

356
  def before_data_refill_can_merge(new_req: MissReqWoStoreData): Bool = {
Z
zhanglinjuan 已提交
357
    data_not_refilled && (req.isLoad || req.isStore) && new_req.isLoad
358 359
  }

360
  def should_merge(new_req: MissReqWoStoreData): Bool = {
Z
zhanglinjuan 已提交
361
    val block_match = get_block(req.addr) === get_block(new_req.addr)
Z
zhanglinjuan 已提交
362
    block_match &&
363 364 365 366
    (
      before_read_sent_can_merge(new_req) ||
      before_data_refill_can_merge(new_req)
    )
A
Allen 已提交
367 368
  }

369 370 371 372 373 374
  // store can be merged before io.mem_acquire.fire()
  // store can not be merged the cycle that io.mem_acquire.fire()
  // load can be merged before io.mem_grant.fire()
  //
  // TODO: merge store if possible? mem_acquire may need to be re-issued,
  // but sbuffer entry can be freed
375
  def should_reject(new_req: MissReqWoStoreData): Bool = {
Z
zhanglinjuan 已提交
376
    val block_match = get_block(req.addr) === get_block(new_req.addr)
Z
zhanglinjuan 已提交
377 378 379 380 381 382
    val set_match = set === addr_to_dcache_set(new_req.vaddr)

    req_valid &&
      Mux(
        block_match,
        !before_read_sent_can_merge(new_req) &&
Z
zhanglinjuan 已提交
383
          !before_data_refill_can_merge(new_req),
Z
zhanglinjuan 已提交
384 385
        set_match && new_req.way_en === req.way_en
      )
386 387 388 389 390 391 392
  }

  io.primary_ready := !req_valid
  io.secondary_ready := should_merge(io.req.bits)
  io.secondary_reject := should_reject(io.req.bits)

  // should not allocate, merge or reject at the same time
Z
zhanglinjuan 已提交
393 394
  assert(RegNext(PopCount(Seq(io.primary_ready, io.secondary_ready, io.secondary_reject)) <= 1.U))

395
  val refill_data_splited = WireInit(VecInit(Seq.tabulate(cfg.blockBytes * 8 / l1BusDataWidth)(i => {
396
    val data = refill_and_store_data.asUInt
397 398
    data((i + 1) * l1BusDataWidth - 1, i * l1BusDataWidth)
  })))
Z
zhanglinjuan 已提交
399
  io.refill_to_ldq.valid := RegNext(!w_grantlast && io.mem_grant.fire()) && should_refill_data_reg
Z
zhanglinjuan 已提交
400 401
  io.refill_to_ldq.bits.addr := RegNext(req.addr + (refill_count << refillOffBits))
  io.refill_to_ldq.bits.data := refill_data_splited(RegNext(refill_count))
402
  io.refill_to_ldq.bits.error := RegNext(io.mem_grant.bits.corrupt || io.mem_grant.bits.denied)
Z
zhanglinjuan 已提交
403 404 405
  io.refill_to_ldq.bits.refill_done := RegNext(refill_done && io.mem_grant.fire())
  io.refill_to_ldq.bits.hasdata := hasData
  io.refill_to_ldq.bits.data_raw := refill_data_raw.asUInt
406 407

  io.mem_acquire.valid := !s_acquire
Z
zhanglinjuan 已提交
408
  val grow_param = req.req_coh.onAccess(req.cmd)._2
409 410 411 412 413 414 415 416 417 418 419 420 421
  val acquireBlock = edge.AcquireBlock(
    fromSource = io.id,
    toAddress = req.addr,
    lgSize = (log2Up(cfg.blockBytes)).U,
    growPermissions = grow_param
  )._2
  val acquirePerm = edge.AcquirePerm(
    fromSource = io.id,
    toAddress = req.addr,
    lgSize = (log2Up(cfg.blockBytes)).U,
    growPermissions = grow_param
  )._2
  io.mem_acquire.bits := Mux(full_overwrite, acquirePerm, acquireBlock)
422 423 424 425 426 427
  // resolve cache alias by L2
  io.mem_acquire.bits.user.lift(AliasKey).foreach( _ := req.vaddr(13, 12))
  // trigger prefetch
  io.mem_acquire.bits.user.lift(PrefetchKey).foreach(_ := true.B)
  // prefer not to cache data in L2 by default
  io.mem_acquire.bits.user.lift(PreferCacheKey).foreach(_ := false.B)
Z
zhanglinjuan 已提交
428 429
  require(nSets <= 256)

430
  io.mem_grant.ready := !w_grantlast && s_acquire
Z
zhanglinjuan 已提交
431

432
  val grantack = RegEnable(edge.GrantAck(io.mem_grant.bits), io.mem_grant.fire())
Z
zhanglinjuan 已提交
433 434
  assert(RegNext(!io.mem_grant.fire() || edge.isRequest(io.mem_grant.bits)))
  io.mem_finish.valid := !s_grantack && w_grantfirst
435 436
  io.mem_finish.bits := grantack

Z
zhanglinjuan 已提交
437 438
  io.replace_pipe_req.valid := !s_replace_req
  val replace = io.replace_pipe_req.bits
439 440
  replace := DontCare
  replace.miss := false.B
Z
zhanglinjuan 已提交
441
  replace.miss_id := io.id
442 443 444 445 446 447 448 449 450
  replace.miss_dirty := false.B
  replace.probe := false.B
  replace.probe_need_data := false.B
  replace.source := LOAD_SOURCE.U
  replace.vaddr := req.vaddr // only untag bits are needed
  replace.addr := Cat(req.replace_tag, 0.U(pgUntagBits.W)) // only tag bits are needed
  replace.store_mask := 0.U
  replace.replace := true.B
  replace.replace_way_en := req.way_en
451
  replace.error := false.B
Z
zhanglinjuan 已提交
452 453 454 455 456 457 458 459 460

  io.refill_pipe_req.valid := !s_refill && w_replace_resp && w_grantlast
  val refill = io.refill_pipe_req.bits
  refill.source := req.source
  refill.addr := req.addr
  refill.way_en := req.way_en
  refill.wmask := Mux(
    hasData || req.isLoad,
    ~0.U(DCacheBanks.W),
461
    VecInit((0 until DCacheBanks).map(i => get_mask_of_bank(i, req_store_mask).orR)).asUInt
Z
zhanglinjuan 已提交
462
  )
463
  refill.data := refill_and_store_data.asTypeOf((new RefillPipeReq).data)
Z
zhanglinjuan 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
  refill.miss_id := io.id
  refill.id := req.id
  def missCohGen(cmd: UInt, param: UInt, dirty: Bool) = {
    val c = categorize(cmd)
    MuxLookup(Cat(c, param, dirty), Nothing, Seq(
      //(effect param) -> (next)
      Cat(rd, toB, false.B)  -> Branch,
      Cat(rd, toB, true.B)   -> Branch,
      Cat(rd, toT, false.B)  -> Trunk,
      Cat(rd, toT, true.B)   -> Dirty,
      Cat(wi, toT, false.B)  -> Trunk,
      Cat(wi, toT, true.B)   -> Dirty,
      Cat(wr, toT, false.B)  -> Dirty,
      Cat(wr, toT, true.B)   -> Dirty))
  }
  refill.meta.coh := ClientMetadata(missCohGen(req.cmd, grant_param, isDirty))
480
  refill.error := error
Z
zhanglinjuan 已提交
481 482 483 484 485 486 487 488
  refill.alias := req.vaddr(13, 12) // TODO

  io.main_pipe_req.valid := !s_mainpipe_req && w_grantlast
  io.main_pipe_req.bits := DontCare
  io.main_pipe_req.bits.miss := true.B
  io.main_pipe_req.bits.miss_id := io.id
  io.main_pipe_req.bits.miss_param := grant_param
  io.main_pipe_req.bits.miss_dirty := isDirty
489
  io.main_pipe_req.bits.miss_way_en := req.way_en
Z
zhanglinjuan 已提交
490 491 492 493 494
  io.main_pipe_req.bits.probe := false.B
  io.main_pipe_req.bits.source := req.source
  io.main_pipe_req.bits.cmd := req.cmd
  io.main_pipe_req.bits.vaddr := req.vaddr
  io.main_pipe_req.bits.addr := req.addr
495
  io.main_pipe_req.bits.store_data := refill_and_store_data.asUInt
Z
zhanglinjuan 已提交
496 497 498 499
  io.main_pipe_req.bits.store_mask := ~0.U(blockBytes.W)
  io.main_pipe_req.bits.word_idx := req.word_idx
  io.main_pipe_req.bits.amo_data := req.amo_data
  io.main_pipe_req.bits.amo_mask := req.amo_mask
500
  io.main_pipe_req.bits.error := error
Z
zhanglinjuan 已提交
501 502
  io.main_pipe_req.bits.id := req.id

503
  io.block_addr.valid := req_valid && w_grantlast && !w_refill_resp
504
  io.block_addr.bits := req.addr
505

Z
zhanglinjuan 已提交
506 507 508 509
  io.debug_early_replace.valid := BoolStopWatch(io.replace_pipe_resp, io.refill_pipe_req.fire())
  io.debug_early_replace.bits.idx := addr_to_dcache_set(req.vaddr)
  io.debug_early_replace.bits.tag := req.replace_tag

W
William Wang 已提交
510 511
  XSPerfAccumulate("miss_req_primary", primary_fire)
  XSPerfAccumulate("miss_req_merged", secondary_fire)
Z
zhanglinjuan 已提交
512 513
  XSPerfAccumulate("load_miss_penalty_to_use",
    should_refill_data &&
W
William Wang 已提交
514
      BoolStopWatch(primary_fire, io.refill_to_ldq.valid, true)
Z
zhanglinjuan 已提交
515 516
  )
  XSPerfAccumulate("main_pipe_penalty", BoolStopWatch(io.main_pipe_req.fire(), io.main_pipe_resp))
517
  XSPerfAccumulate("penalty_blocked_by_channel_A", io.mem_acquire.valid && !io.mem_acquire.ready)
518
  XSPerfAccumulate("penalty_waiting_for_channel_D", s_acquire && !w_grantlast && !io.mem_grant.valid)
Z
zhanglinjuan 已提交
519
  XSPerfAccumulate("penalty_waiting_for_channel_E", io.mem_finish.valid && !io.mem_finish.ready)
520
  XSPerfAccumulate("penalty_from_grant_to_refill", !w_refill_resp && w_grantlast)
W
William Wang 已提交
521
  XSPerfAccumulate("soft_prefetch_number", primary_fire && io.req.bits.source === SOFT_PREFETCH.U)
522

W
William Wang 已提交
523
  val (mshr_penalty_sample, mshr_penalty) = TransactionLatencyCounter(RegNext(primary_fire), release_entry)
W
William Wang 已提交
524 525
  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 0, 20, 1, true, true)
  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 20, 100, 10, true, false)
526

W
William Wang 已提交
527
  val load_miss_begin = primary_fire && io.req.bits.isLoad
528
  val refill_finished = RegNext(!w_grantlast && refill_done) && should_refill_data
529
  val (load_miss_penalty_sample, load_miss_penalty) = TransactionLatencyCounter(load_miss_begin, refill_finished) // not real refill finish time
W
William Wang 已提交
530 531
  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 0, 20, 1, true, true)
  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 20, 100, 10, true, false)
532 533

  val (a_to_d_penalty_sample, a_to_d_penalty) = TransactionLatencyCounter(io.mem_acquire.fire(), io.mem_grant.fire() && refill_done)
W
William Wang 已提交
534 535
  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 0, 20, 1, true, true)
  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 20, 100, 10, true, false)
A
Allen 已提交
536 537
}

538
class MissQueue(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule with HasPerfEvents {
A
Allen 已提交
539
  val io = IO(new Bundle {
J
Jiawei Lin 已提交
540
    val hartId = Input(UInt(8.W))
Z
zhanglinjuan 已提交
541 542 543 544 545 546
    val req = Flipped(DecoupledIO(new MissReq))
    val refill_to_ldq = ValidIO(new Refill)

    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
A
Allen 已提交
547

Z
zhanglinjuan 已提交
548
    val refill_pipe_req = DecoupledIO(new RefillPipeReq)
Z
zhanglinjuan 已提交
549
    val refill_pipe_req_dup = Vec(nDupStatus, DecoupledIO(new RefillPipeReqCtrl))
550
    val refill_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
A
Allen 已提交
551

552 553
    val replace_pipe_req = DecoupledIO(new MainPipeReq)
    val replace_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
Z
zhanglinjuan 已提交
554 555 556

    val main_pipe_req = DecoupledIO(new MainPipeReq)
    val main_pipe_resp = Flipped(ValidIO(new AtomicsResp))
557 558

    // block probe
Z
zhanglinjuan 已提交
559
    val probe_addr = Input(UInt(PAddrBits.W))
560
    val probe_block = Output(Bool())
561 562

    val full = Output(Bool())
A
Allen 已提交
563

Z
zhanglinjuan 已提交
564 565 566 567 568 569 570 571 572 573
    // only for performance counter
    // This is valid when an mshr has finished replacing a block (w_replace_resp),
    // but hasn't received Grant from L2 (!w_grantlast)
    val debug_early_replace = Vec(cfg.nMissEntries, ValidIO(new Bundle() {
      // info about the block that has been replaced
      val idx = UInt(idxBits.W) // vaddr
      val tag = UInt(tagBits.W) // paddr
    }))
  })
  
574 575
  // 128KBL1: FIXME: provide vaddr for l2

Z
zhanglinjuan 已提交
576
  val entries = Seq.fill(cfg.nMissEntries)(Module(new MissEntry(edge)))
A
Allen 已提交
577

578 579 580
  val req_data_gen = io.req.bits.toMissReqStoreData()
  val req_data_buffer = RegEnable(req_data_gen, io.req.valid)

Z
zhanglinjuan 已提交
581 582 583 584
  val primary_ready_vec = entries.map(_.io.primary_ready)
  val secondary_ready_vec = entries.map(_.io.secondary_ready)
  val secondary_reject_vec = entries.map(_.io.secondary_reject)
  val probe_block_vec = entries.map { case e => e.io.block_addr.valid && e.io.block_addr.bits === io.probe_addr }
A
Allen 已提交
585

Z
zhanglinjuan 已提交
586
  val merge = Cat(secondary_ready_vec).orR
587
  val reject = Cat(secondary_reject_vec).orR
Z
zhanglinjuan 已提交
588 589
  val alloc = !reject && !merge && Cat(primary_ready_vec).orR
  val accept = alloc || merge
A
Allen 已提交
590

Z
zhanglinjuan 已提交
591 592 593 594 595 596 597
  assert(RegNext(PopCount(secondary_ready_vec) <= 1.U))
//  assert(RegNext(PopCount(secondary_reject_vec) <= 1.U))
  // It is possible that one mshr wants to merge a req, while another mshr wants to reject it.
  // That is, a coming req has the same paddr as that of mshr_0 (merge),
  // while it has the same set and the same way as mshr_1 (reject).
  // In this situation, the coming req should be merged by mshr_0
//  assert(RegNext(PopCount(Seq(merge, reject)) <= 1.U))
A
Allen 已提交
598

W
William Wang 已提交
599 600 601 602 603 604 605 606 607 608 609 610
  def select_valid_one[T <: Bundle](
    in: Seq[DecoupledIO[T]],
    out: DecoupledIO[T],
    name: Option[String] = None): Unit = {

    if (name.nonEmpty) { out.suggestName(s"${name.get}_select") }
    out.valid := Cat(in.map(_.valid)).orR
    out.bits := ParallelMux(in.map(_.valid) zip in.map(_.bits))
    in.map(_.ready := out.ready) 
    assert(!RegNext(out.valid && PopCount(Cat(in.map(_.valid))) > 1.U))
  }

Z
zhanglinjuan 已提交
611
  io.mem_grant.ready := false.B
A
Allen 已提交
612

Z
zhanglinjuan 已提交
613 614
  entries.zipWithIndex.foreach {
    case (e, i) =>
W
William Wang 已提交
615 616 617 618 619
      val former_primary_ready = if(i == 0)
        false.B 
      else
        Cat((0 until i).map(j => entries(j).io.primary_ready)).orR
      
Z
zhanglinjuan 已提交
620
      e.io.id := i.U
W
William Wang 已提交
621 622 623 624 625 626
      e.io.req.valid := io.req.valid
      e.io.primary_valid := io.req.valid && 
        !merge && 
        !reject && 
        !former_primary_ready &&
        e.io.primary_ready
627
      e.io.req.bits := io.req.bits.toMissReqWoStoreData()
628
      e.io.req_data := req_data_buffer
A
Allen 已提交
629

Z
zhanglinjuan 已提交
630 631 632 633 634
      e.io.mem_grant.valid := false.B
      e.io.mem_grant.bits := DontCare
      when (io.mem_grant.bits.source === i.U) {
        e.io.mem_grant <> io.mem_grant
      }
635

636
      e.io.refill_pipe_resp := io.refill_pipe_resp.valid && io.refill_pipe_resp.bits === i.U
637
      e.io.replace_pipe_resp := io.replace_pipe_resp.valid && io.replace_pipe_resp.bits === i.U
Z
zhanglinjuan 已提交
638
      e.io.main_pipe_resp := io.main_pipe_resp.valid && io.main_pipe_resp.bits.ack_miss_queue && io.main_pipe_resp.bits.miss_id === i.U
A
Allen 已提交
639

Z
zhanglinjuan 已提交
640
      io.debug_early_replace(i) := e.io.debug_early_replace
641 642
  }

Z
zhanglinjuan 已提交
643 644 645
  io.req.ready := accept
  io.refill_to_ldq.valid := Cat(entries.map(_.io.refill_to_ldq.valid)).orR
  io.refill_to_ldq.bits := ParallelMux(entries.map(_.io.refill_to_ldq.valid) zip entries.map(_.io.refill_to_ldq.bits))
A
Allen 已提交
646

647
  TLArbiter.lowest(edge, io.mem_acquire, entries.map(_.io.mem_acquire):_*)
Z
zhanglinjuan 已提交
648
  TLArbiter.lowest(edge, io.mem_finish, entries.map(_.io.mem_finish):_*)
A
Allen 已提交
649

Z
zhanglinjuan 已提交
650 651 652 653 654 655 656 657 658 659 660 661 662
  // arbiter_with_pipereg_N_dup(entries.map(_.io.refill_pipe_req), io.refill_pipe_req,
  // io.refill_pipe_req_dup,
  // Some("refill_pipe_req"))
  val out_refill_pipe_req = Wire(Decoupled(new RefillPipeReq))
  val out_refill_pipe_req_ctrl = Wire(Decoupled(new RefillPipeReqCtrl))
  out_refill_pipe_req_ctrl.valid := out_refill_pipe_req.valid
  out_refill_pipe_req_ctrl.bits := out_refill_pipe_req.bits.getCtrl
  out_refill_pipe_req.ready := out_refill_pipe_req_ctrl.ready
  arbiter(entries.map(_.io.refill_pipe_req), out_refill_pipe_req, Some("refill_pipe_req"))
  for (dup <- io.refill_pipe_req_dup) {
    AddPipelineReg(out_refill_pipe_req_ctrl, dup, false.B)
  }
  AddPipelineReg(out_refill_pipe_req, io.refill_pipe_req, false.B)
663

664
  arbiter_with_pipereg(entries.map(_.io.replace_pipe_req), io.replace_pipe_req, Some("replace_pipe_req"))
665 666

  fastArbiter(entries.map(_.io.main_pipe_req), io.main_pipe_req, Some("main_pipe_req"))
A
Allen 已提交
667

Z
zhanglinjuan 已提交
668
  io.probe_block := Cat(probe_block_vec).orR
A
Allen 已提交
669

Z
zhanglinjuan 已提交
670
  io.full := ~Cat(entries.map(_.io.primary_ready)).andR
A
Allen 已提交
671

672
  if (env.EnableDifftest) {
Z
zhanglinjuan 已提交
673 674
    val difftest = Module(new DifftestRefillEvent)
    difftest.io.clock := clock
J
Jiawei Lin 已提交
675
    difftest.io.coreid := io.hartId
676
    difftest.io.cacheid := 1.U
Z
zhanglinjuan 已提交
677 678 679
    difftest.io.valid := io.refill_to_ldq.valid && io.refill_to_ldq.bits.hasdata && io.refill_to_ldq.bits.refill_done
    difftest.io.addr := io.refill_to_ldq.bits.addr
    difftest.io.data := io.refill_to_ldq.bits.data_raw.asTypeOf(difftest.io.data)
680 681
  }

682
  XSPerfAccumulate("miss_req", io.req.fire())
Z
zhanglinjuan 已提交
683 684
  XSPerfAccumulate("miss_req_allocate", io.req.fire() && alloc)
  XSPerfAccumulate("miss_req_merge_load", io.req.fire() && merge && io.req.bits.isLoad)
685
  XSPerfAccumulate("miss_req_reject_load", io.req.valid && reject && io.req.bits.isLoad)
686
  XSPerfAccumulate("probe_blocked_by_miss", io.probe_block)
687
  val max_inflight = RegInit(0.U((log2Up(cfg.nMissEntries) + 1).W))
Z
zhanglinjuan 已提交
688
  val num_valids = PopCount(~Cat(primary_ready_vec).asUInt)
689 690 691 692
  when (num_valids > max_inflight) {
    max_inflight := num_valids
  }
  // max inflight (average) = max_inflight_total / cycle cnt
693
  XSPerfAccumulate("max_inflight", max_inflight)
694
  QueuePerf(cfg.nMissEntries, num_valids, num_valids === cfg.nMissEntries.U)
695
  io.full := num_valids === cfg.nMissEntries.U
696
  XSPerfHistogram("num_valids", num_valids, true.B, 0, cfg.nMissEntries, 1)
697

698
  val perfValidCount = RegNext(PopCount(entries.map(entry => (!entry.io.primary_ready))))
699
  val perfEvents = Seq(
700 701 702 703 704
    ("dcache_missq_req      ", io.req.fire()),
    ("dcache_missq_1_4_valid", (perfValidCount < (cfg.nMissEntries.U/4.U))),
    ("dcache_missq_2_4_valid", (perfValidCount > (cfg.nMissEntries.U/4.U)) & (perfValidCount <= (cfg.nMissEntries.U/2.U))),
    ("dcache_missq_3_4_valid", (perfValidCount > (cfg.nMissEntries.U/2.U)) & (perfValidCount <= (cfg.nMissEntries.U*3.U/4.U))),
    ("dcache_missq_4_4_valid", (perfValidCount > (cfg.nMissEntries.U*3.U/4.U))),
705
  )
706
  generatePerfEvent()
A
Allen 已提交
707
}