xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/mainpipe/MissQueue.scala (revision a4e57ea3a91431261d57a58df4810c0d9f0366ef)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.cache
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import freechips.rocketchip.tilelink._
24import freechips.rocketchip.tilelink.ClientStates._
25import freechips.rocketchip.tilelink.MemoryOpCategories._
26import freechips.rocketchip.tilelink.TLPermissions._
27import difftest._
28import huancun.{AliasKey, DirtyKey, PreferCacheKey, PrefetchKey}
29
30class MissReq(implicit p: Parameters) extends DCacheBundle {
31  val source = UInt(sourceTypeWidth.W)
32  val cmd = UInt(M_SZ.W)
33  val addr = UInt(PAddrBits.W)
34  val vaddr = UInt(VAddrBits.W)
35  val way_en = UInt(DCacheWays.W)
36
37  // store
38  val store_data = UInt((cfg.blockBytes * 8).W)
39  val store_mask = UInt(cfg.blockBytes.W)
40
41  // which word does amo work on?
42  val word_idx = UInt(log2Up(blockWords).W)
43  val amo_data = UInt(DataBits.W)
44  val amo_mask = UInt((DataBits / 8).W)
45
46  val req_coh = new ClientMetadata
47  val replace_coh = new ClientMetadata
48  val replace_tag = UInt(tagBits.W)
49  val id = UInt(reqIdWidth.W)
50
51  // For now, miss queue entry req is actually valid when req.valid && !cancel
52  // * req.valid is fast to generate
53  // * cancel is slow to generate, it will not be used until the last moment
54  //
55  // cancel may come from the following sources:
56  // 1. miss req blocked by writeback queue:
57  //      a writeback req of the same address is in progress
58  // 2. pmp check failed
59  val cancel = Bool() // cancel is slow to generate, it will cancel missreq.valid
60
61  def isLoad = source === LOAD_SOURCE.U
62  def isStore = source === STORE_SOURCE.U
63  def isAMO = source === AMO_SOURCE.U
64  def hit = req_coh.isValid()
65}
66
67class MissEntry(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule {
68  val io = IO(new Bundle() {
69    // MSHR ID
70    val id = Input(UInt(log2Up(cfg.nMissEntries).W))
71    // client requests
72    val req    = Flipped(ValidIO(new MissReq))
73    // allocate this entry for new req
74    val primary_valid = Input(Bool())
75    // this entry is free and can be allocated to new reqs
76    val primary_ready = Output(Bool())
77    // this entry is busy, but it can merge the new req
78    val secondary_ready = Output(Bool())
79    // this entry is busy and it can not merge the new req
80    val secondary_reject = Output(Bool())
81
82    val refill_to_ldq = ValidIO(new Refill)
83
84    // bus
85    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
86    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
87    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
88
89    // refill pipe
90    val refill_pipe_req = DecoupledIO(new RefillPipeReq)
91    val refill_pipe_resp = Input(Bool())
92
93    // replace pipe
94    val replace_pipe_req = DecoupledIO(new MainPipeReq)
95    val replace_pipe_resp = Input(Bool())
96
97    // main pipe: amo miss
98    val main_pipe_req = DecoupledIO(new MainPipeReq)
99    val main_pipe_resp = Input(Bool())
100
101    val block_addr = ValidIO(UInt(PAddrBits.W))
102
103    val debug_early_replace = ValidIO(new Bundle() {
104      // info about the block that has been replaced
105      val idx = UInt(idxBits.W) // vaddr
106      val tag = UInt(tagBits.W) // paddr
107    })
108  })
109
110  assert(!RegNext(io.primary_valid && !io.primary_ready))
111
112  val req = Reg(new MissReq)
113  val req_valid = RegInit(false.B)
114  val set = addr_to_dcache_set(req.vaddr)
115
116  val s_acquire = RegInit(true.B)
117  val s_grantack = RegInit(true.B)
118  val s_replace_req = RegInit(true.B)
119  val s_refill = RegInit(true.B)
120  val s_mainpipe_req = RegInit(true.B)
121
122  val w_grantfirst = RegInit(true.B)
123  val w_grantlast = RegInit(true.B)
124  val w_replace_resp = RegInit(true.B)
125  val w_refill_resp = RegInit(true.B)
126  val w_mainpipe_resp = RegInit(true.B)
127
128  val release_entry = s_grantack && w_refill_resp && w_mainpipe_resp
129
130  val acquire_not_sent = !s_acquire && !io.mem_acquire.ready
131  val data_not_refilled = !w_grantfirst
132
133  val error = RegInit(false.B)
134
135  val should_refill_data_reg =  Reg(Bool())
136  val should_refill_data = WireInit(should_refill_data_reg)
137
138  val full_overwrite = req.isStore && req.store_mask.andR
139
140  val (_, _, refill_done, refill_count) = edge.count(io.mem_grant)
141  val grant_param = Reg(UInt(TLPermissions.bdWidth.W))
142
143  when (release_entry && req_valid) {
144    req_valid := false.B
145  }
146
147  val primary_fire = WireInit(io.req.valid && io.primary_ready && io.primary_valid && !io.req.bits.cancel)
148  when (primary_fire) {
149    req_valid := true.B
150    req := io.req.bits
151    req.addr := get_block_addr(io.req.bits.addr)
152
153    s_acquire := false.B
154    s_grantack := false.B
155
156    w_grantfirst := false.B
157    w_grantlast := false.B
158
159    when (!io.req.bits.isAMO) {
160      s_refill := false.B
161      w_refill_resp := false.B
162    }
163
164    when (!io.req.bits.hit && io.req.bits.replace_coh.isValid() && !io.req.bits.isAMO) {
165      s_replace_req := false.B
166      w_replace_resp := false.B
167    }
168
169    when (io.req.bits.isAMO) {
170      s_mainpipe_req := false.B
171      w_mainpipe_resp := false.B
172    }
173
174    should_refill_data_reg := io.req.bits.isLoad
175    error := false.B
176  }
177
178  val secondary_fire = WireInit(io.req.valid && io.secondary_ready && !io.req.bits.cancel)
179  when (secondary_fire) {
180    assert(io.req.bits.req_coh.state <= req.req_coh.state)
181    assert(!(io.req.bits.isAMO || req.isAMO))
182    // use the most uptodate meta
183    req.req_coh := io.req.bits.req_coh
184
185    when (io.req.bits.isStore) {
186      req := io.req.bits
187      req.addr := get_block_addr(io.req.bits.addr)
188      req.way_en := req.way_en
189      req.replace_coh := req.replace_coh
190      req.replace_tag := req.replace_tag
191    }
192
193    should_refill_data := should_refill_data_reg || io.req.bits.isLoad
194    should_refill_data_reg := should_refill_data
195  }
196
197  when (io.mem_acquire.fire()) {
198    s_acquire := true.B
199  }
200
201  val refill_data = Reg(Vec(blockRows, UInt(rowBits.W)))
202  val refill_data_raw = Reg(Vec(blockBytes/beatBytes, UInt(beatBits.W)))
203  val new_data = Wire(Vec(blockRows, UInt(rowBits.W)))
204  val new_mask = Wire(Vec(blockRows, UInt(rowBytes.W)))
205  def mergePutData(old_data: UInt, new_data: UInt, wmask: UInt): UInt = {
206    val full_wmask = FillInterleaved(8, wmask)
207    (~full_wmask & old_data | full_wmask & new_data)
208  }
209  for (i <- 0 until blockRows) {
210    new_data(i) := req.store_data(rowBits * (i + 1) - 1, rowBits * i)
211    // we only need to merge data for Store
212    new_mask(i) := Mux(req.isStore, req.store_mask(rowBytes * (i + 1) - 1, rowBytes * i), 0.U)
213  }
214  val hasData = RegInit(true.B)
215  val isDirty = RegInit(false.B)
216  when (io.mem_grant.fire()) {
217    w_grantfirst := true.B
218    grant_param := io.mem_grant.bits.param
219    when (edge.hasData(io.mem_grant.bits)) {
220      // GrantData
221      for (i <- 0 until beatRows) {
222        val idx = (refill_count << log2Floor(beatRows)) + i.U
223        val grant_row = io.mem_grant.bits.data(rowBits * (i + 1) - 1, rowBits * i)
224        refill_data(idx) := mergePutData(grant_row, new_data(idx), new_mask(idx))
225      }
226      w_grantlast := w_grantlast || refill_done
227      hasData := true.B
228    }.otherwise {
229      // Grant
230      assert(full_overwrite)
231      for (i <- 0 until blockRows) {
232        refill_data(i) := new_data(i)
233      }
234      w_grantlast := true.B
235      hasData := false.B
236    }
237
238    error := io.mem_grant.bits.denied || io.mem_grant.bits.corrupt || error
239
240    refill_data_raw(refill_count) := io.mem_grant.bits.data
241    isDirty := io.mem_grant.bits.echo.lift(DirtyKey).getOrElse(false.B)
242  }
243
244  when (io.mem_finish.fire()) {
245    s_grantack := true.B
246  }
247
248  when (io.replace_pipe_req.fire()) {
249    s_replace_req := true.B
250  }
251
252  when (io.replace_pipe_resp) {
253    w_replace_resp := true.B
254  }
255
256  when (io.refill_pipe_req.fire()) {
257    s_refill := true.B
258  }
259
260  when (io.refill_pipe_resp) {
261    w_refill_resp := true.B
262  }
263
264  when (io.main_pipe_req.fire()) {
265    s_mainpipe_req := true.B
266  }
267
268  when (io.main_pipe_resp) {
269    w_mainpipe_resp := true.B
270  }
271
272  def before_read_sent_can_merge(new_req: MissReq): Bool = {
273    acquire_not_sent && req.isLoad && (new_req.isLoad || new_req.isStore)
274  }
275
276  def before_data_refill_can_merge(new_req: MissReq): Bool = {
277    data_not_refilled && (req.isLoad || req.isStore) && new_req.isLoad
278  }
279
280  def should_merge(new_req: MissReq): Bool = {
281    val block_match = get_block(req.addr) === get_block(new_req.addr)
282    block_match &&
283    (before_read_sent_can_merge(new_req) ||
284      before_data_refill_can_merge(new_req))
285  }
286
287  def should_reject(new_req: MissReq): Bool = {
288    val block_match = get_block(req.addr) === get_block(new_req.addr)
289    val set_match = set === addr_to_dcache_set(new_req.vaddr)
290
291    req_valid &&
292      Mux(
293        block_match,
294        !before_read_sent_can_merge(new_req) &&
295          !before_data_refill_can_merge(new_req),
296        set_match && new_req.way_en === req.way_en
297      )
298  }
299
300  io.primary_ready := !req_valid
301  io.secondary_ready := should_merge(io.req.bits)
302  io.secondary_reject := should_reject(io.req.bits)
303
304  // should not allocate, merge or reject at the same time
305  assert(RegNext(PopCount(Seq(io.primary_ready, io.secondary_ready, io.secondary_reject)) <= 1.U))
306
307  val refill_data_splited = WireInit(VecInit(Seq.tabulate(cfg.blockBytes * 8 / l1BusDataWidth)(i => {
308    val data = refill_data.asUInt
309    data((i + 1) * l1BusDataWidth - 1, i * l1BusDataWidth)
310  })))
311  io.refill_to_ldq.valid := RegNext(!w_grantlast && io.mem_grant.fire()) && should_refill_data_reg
312  io.refill_to_ldq.bits.addr := RegNext(req.addr + (refill_count << refillOffBits))
313  io.refill_to_ldq.bits.data := refill_data_splited(RegNext(refill_count))
314  io.refill_to_ldq.bits.error := RegNext(io.mem_grant.bits.corrupt || io.mem_grant.bits.denied)
315  io.refill_to_ldq.bits.refill_done := RegNext(refill_done && io.mem_grant.fire())
316  io.refill_to_ldq.bits.hasdata := hasData
317  io.refill_to_ldq.bits.data_raw := refill_data_raw.asUInt
318
319  io.mem_acquire.valid := !s_acquire
320  val grow_param = req.req_coh.onAccess(req.cmd)._2
321  val acquireBlock = edge.AcquireBlock(
322    fromSource = io.id,
323    toAddress = req.addr,
324    lgSize = (log2Up(cfg.blockBytes)).U,
325    growPermissions = grow_param
326  )._2
327  val acquirePerm = edge.AcquirePerm(
328    fromSource = io.id,
329    toAddress = req.addr,
330    lgSize = (log2Up(cfg.blockBytes)).U,
331    growPermissions = grow_param
332  )._2
333  io.mem_acquire.bits := Mux(full_overwrite, acquirePerm, acquireBlock)
334  // resolve cache alias by L2
335  io.mem_acquire.bits.user.lift(AliasKey).foreach( _ := req.vaddr(13, 12))
336  // trigger prefetch
337  io.mem_acquire.bits.user.lift(PrefetchKey).foreach(_ := true.B)
338  // prefer not to cache data in L2 by default
339  io.mem_acquire.bits.user.lift(PreferCacheKey).foreach(_ := false.B)
340  require(nSets <= 256)
341
342  io.mem_grant.ready := !w_grantlast && s_acquire
343
344  val grantack = RegEnable(edge.GrantAck(io.mem_grant.bits), io.mem_grant.fire())
345  assert(RegNext(!io.mem_grant.fire() || edge.isRequest(io.mem_grant.bits)))
346  io.mem_finish.valid := !s_grantack && w_grantfirst
347  io.mem_finish.bits := grantack
348
349  io.replace_pipe_req.valid := !s_replace_req
350  val replace = io.replace_pipe_req.bits
351  replace := DontCare
352  replace.miss := false.B
353  replace.miss_id := io.id
354  replace.miss_dirty := false.B
355  replace.probe := false.B
356  replace.probe_need_data := false.B
357  replace.source := LOAD_SOURCE.U
358  replace.vaddr := req.vaddr // only untag bits are needed
359  replace.addr := Cat(req.replace_tag, 0.U(pgUntagBits.W)) // only tag bits are needed
360  replace.store_mask := 0.U
361  replace.replace := true.B
362  replace.replace_way_en := req.way_en
363
364  io.refill_pipe_req.valid := !s_refill && w_replace_resp && w_grantlast
365  val refill = io.refill_pipe_req.bits
366  refill.source := req.source
367  refill.addr := req.addr
368  refill.way_en := req.way_en
369  refill.wmask := Mux(
370    hasData || req.isLoad,
371    ~0.U(DCacheBanks.W),
372    VecInit((0 until DCacheBanks).map(i => get_mask_of_bank(i, req.store_mask).orR)).asUInt
373  )
374  refill.data := refill_data.asTypeOf((new RefillPipeReq).data)
375  refill.miss_id := io.id
376  refill.id := req.id
377  def missCohGen(cmd: UInt, param: UInt, dirty: Bool) = {
378    val c = categorize(cmd)
379    MuxLookup(Cat(c, param, dirty), Nothing, Seq(
380      //(effect param) -> (next)
381      Cat(rd, toB, false.B)  -> Branch,
382      Cat(rd, toB, true.B)   -> Branch,
383      Cat(rd, toT, false.B)  -> Trunk,
384      Cat(rd, toT, true.B)   -> Dirty,
385      Cat(wi, toT, false.B)  -> Trunk,
386      Cat(wi, toT, true.B)   -> Dirty,
387      Cat(wr, toT, false.B)  -> Dirty,
388      Cat(wr, toT, true.B)   -> Dirty))
389  }
390  refill.meta.coh := ClientMetadata(missCohGen(req.cmd, grant_param, isDirty))
391  refill.error := error
392  refill.alias := req.vaddr(13, 12) // TODO
393
394  io.main_pipe_req.valid := !s_mainpipe_req && w_grantlast
395  io.main_pipe_req.bits := DontCare
396  io.main_pipe_req.bits.miss := true.B
397  io.main_pipe_req.bits.miss_id := io.id
398  io.main_pipe_req.bits.miss_param := grant_param
399  io.main_pipe_req.bits.miss_dirty := isDirty
400  io.main_pipe_req.bits.probe := false.B
401  io.main_pipe_req.bits.source := req.source
402  io.main_pipe_req.bits.cmd := req.cmd
403  io.main_pipe_req.bits.vaddr := req.vaddr
404  io.main_pipe_req.bits.addr := req.addr
405  io.main_pipe_req.bits.store_data := refill_data.asUInt
406  io.main_pipe_req.bits.store_mask := ~0.U(blockBytes.W)
407  io.main_pipe_req.bits.word_idx := req.word_idx
408  io.main_pipe_req.bits.amo_data := req.amo_data
409  io.main_pipe_req.bits.amo_mask := req.amo_mask
410  io.main_pipe_req.bits.id := req.id
411
412  io.block_addr.valid := req_valid && w_grantlast && !w_refill_resp
413  io.block_addr.bits := req.addr
414
415  io.debug_early_replace.valid := BoolStopWatch(io.replace_pipe_resp, io.refill_pipe_req.fire())
416  io.debug_early_replace.bits.idx := addr_to_dcache_set(req.vaddr)
417  io.debug_early_replace.bits.tag := req.replace_tag
418
419  XSPerfAccumulate("miss_req_primary", primary_fire)
420  XSPerfAccumulate("miss_req_merged", secondary_fire)
421  XSPerfAccumulate("load_miss_penalty_to_use",
422    should_refill_data &&
423      BoolStopWatch(primary_fire, io.refill_to_ldq.valid, true)
424  )
425  XSPerfAccumulate("main_pipe_penalty", BoolStopWatch(io.main_pipe_req.fire(), io.main_pipe_resp))
426  XSPerfAccumulate("penalty_blocked_by_channel_A", io.mem_acquire.valid && !io.mem_acquire.ready)
427  XSPerfAccumulate("penalty_waiting_for_channel_D", s_acquire && !w_grantlast && !io.mem_grant.valid)
428  XSPerfAccumulate("penalty_waiting_for_channel_E", io.mem_finish.valid && !io.mem_finish.ready)
429  XSPerfAccumulate("penalty_from_grant_to_refill", !w_refill_resp && w_grantlast)
430  XSPerfAccumulate("soft_prefetch_number", primary_fire && io.req.bits.source === SOFT_PREFETCH.U)
431
432  val (mshr_penalty_sample, mshr_penalty) = TransactionLatencyCounter(RegNext(primary_fire), release_entry)
433  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 0, 20, 1, true, true)
434  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 20, 100, 10, true, false)
435
436  val load_miss_begin = primary_fire && io.req.bits.isLoad
437  val refill_finished = RegNext(!w_grantlast && refill_done) && should_refill_data
438  val (load_miss_penalty_sample, load_miss_penalty) = TransactionLatencyCounter(load_miss_begin, refill_finished) // not real refill finish time
439  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 0, 20, 1, true, true)
440  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 20, 100, 10, true, false)
441
442  val (a_to_d_penalty_sample, a_to_d_penalty) = TransactionLatencyCounter(io.mem_acquire.fire(), io.mem_grant.fire() && refill_done)
443  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 0, 20, 1, true, true)
444  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 20, 100, 10, true, false)
445}
446
447class MissQueue(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule with HasPerfEvents {
448  val io = IO(new Bundle {
449    val hartId = Input(UInt(8.W))
450    val req = Flipped(DecoupledIO(new MissReq))
451    val refill_to_ldq = ValidIO(new Refill)
452
453    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
454    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
455    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
456
457    val refill_pipe_req = DecoupledIO(new RefillPipeReq)
458    val refill_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
459
460    val replace_pipe_req = DecoupledIO(new MainPipeReq)
461    val replace_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
462
463    val main_pipe_req = DecoupledIO(new MainPipeReq)
464    val main_pipe_resp = Flipped(ValidIO(new AtomicsResp))
465
466    // block probe
467    val probe_addr = Input(UInt(PAddrBits.W))
468    val probe_block = Output(Bool())
469
470    val full = Output(Bool())
471
472    // only for performance counter
473    // This is valid when an mshr has finished replacing a block (w_replace_resp),
474    // but hasn't received Grant from L2 (!w_grantlast)
475    val debug_early_replace = Vec(cfg.nMissEntries, ValidIO(new Bundle() {
476      // info about the block that has been replaced
477      val idx = UInt(idxBits.W) // vaddr
478      val tag = UInt(tagBits.W) // paddr
479    }))
480  })
481
482  // 128KBL1: FIXME: provide vaddr for l2
483
484  val entries = Seq.fill(cfg.nMissEntries)(Module(new MissEntry(edge)))
485
486  val primary_ready_vec = entries.map(_.io.primary_ready)
487  val secondary_ready_vec = entries.map(_.io.secondary_ready)
488  val secondary_reject_vec = entries.map(_.io.secondary_reject)
489  val probe_block_vec = entries.map { case e => e.io.block_addr.valid && e.io.block_addr.bits === io.probe_addr }
490
491  val merge = Cat(secondary_ready_vec).orR
492  val reject = Cat(secondary_reject_vec).orR
493  val alloc = !reject && !merge && Cat(primary_ready_vec).orR
494  val accept = alloc || merge
495
496  assert(RegNext(PopCount(secondary_ready_vec) <= 1.U))
497//  assert(RegNext(PopCount(secondary_reject_vec) <= 1.U))
498  // It is possible that one mshr wants to merge a req, while another mshr wants to reject it.
499  // That is, a coming req has the same paddr as that of mshr_0 (merge),
500  // while it has the same set and the same way as mshr_1 (reject).
501  // In this situation, the coming req should be merged by mshr_0
502//  assert(RegNext(PopCount(Seq(merge, reject)) <= 1.U))
503
504  def select_valid_one[T <: Bundle](
505    in: Seq[DecoupledIO[T]],
506    out: DecoupledIO[T],
507    name: Option[String] = None): Unit = {
508
509    if (name.nonEmpty) { out.suggestName(s"${name.get}_select") }
510    out.valid := Cat(in.map(_.valid)).orR
511    out.bits := ParallelMux(in.map(_.valid) zip in.map(_.bits))
512    in.map(_.ready := out.ready)
513    assert(!RegNext(out.valid && PopCount(Cat(in.map(_.valid))) > 1.U))
514  }
515
516  io.mem_grant.ready := false.B
517
518  entries.zipWithIndex.foreach {
519    case (e, i) =>
520      val former_primary_ready = if(i == 0)
521        false.B
522      else
523        Cat((0 until i).map(j => entries(j).io.primary_ready)).orR
524
525      e.io.id := i.U
526      e.io.req.valid := io.req.valid
527      e.io.primary_valid := io.req.valid &&
528        !merge &&
529        !reject &&
530        !former_primary_ready &&
531        e.io.primary_ready
532      e.io.req.bits := io.req.bits
533
534      e.io.mem_grant.valid := false.B
535      e.io.mem_grant.bits := DontCare
536      when (io.mem_grant.bits.source === i.U) {
537        e.io.mem_grant <> io.mem_grant
538      }
539
540      e.io.refill_pipe_resp := io.refill_pipe_resp.valid && io.refill_pipe_resp.bits === i.U
541      e.io.replace_pipe_resp := io.replace_pipe_resp.valid && io.replace_pipe_resp.bits === i.U
542      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
543
544      io.debug_early_replace(i) := e.io.debug_early_replace
545  }
546
547  io.req.ready := accept
548  io.refill_to_ldq.valid := Cat(entries.map(_.io.refill_to_ldq.valid)).orR
549  io.refill_to_ldq.bits := ParallelMux(entries.map(_.io.refill_to_ldq.valid) zip entries.map(_.io.refill_to_ldq.bits))
550
551  TLArbiter.lowest(edge, io.mem_acquire, entries.map(_.io.mem_acquire):_*)
552  TLArbiter.lowest(edge, io.mem_finish, entries.map(_.io.mem_finish):_*)
553
554  arbiter_with_pipereg(entries.map(_.io.refill_pipe_req), io.refill_pipe_req, Some("refill_pipe_req"))
555  arbiter(entries.map(_.io.replace_pipe_req), io.replace_pipe_req, Some("replace_pipe_req"))
556  arbiter(entries.map(_.io.main_pipe_req), io.main_pipe_req, Some("main_pipe_req"))
557
558  io.probe_block := Cat(probe_block_vec).orR
559
560  io.full := ~Cat(entries.map(_.io.primary_ready)).andR
561
562  if (env.EnableDifftest) {
563    val difftest = Module(new DifftestRefillEvent)
564    difftest.io.clock := clock
565    difftest.io.coreid := io.hartId
566    difftest.io.valid := io.refill_to_ldq.valid && io.refill_to_ldq.bits.hasdata && io.refill_to_ldq.bits.refill_done
567    difftest.io.addr := io.refill_to_ldq.bits.addr
568    difftest.io.data := io.refill_to_ldq.bits.data_raw.asTypeOf(difftest.io.data)
569  }
570
571  XSPerfAccumulate("miss_req", io.req.fire())
572  XSPerfAccumulate("miss_req_allocate", io.req.fire() && alloc)
573  XSPerfAccumulate("miss_req_merge_load", io.req.fire() && merge && io.req.bits.isLoad)
574  XSPerfAccumulate("miss_req_reject_load", io.req.valid && reject && io.req.bits.isLoad)
575  XSPerfAccumulate("probe_blocked_by_miss", io.probe_block)
576  val max_inflight = RegInit(0.U((log2Up(cfg.nMissEntries) + 1).W))
577  val num_valids = PopCount(~Cat(primary_ready_vec).asUInt)
578  when (num_valids > max_inflight) {
579    max_inflight := num_valids
580  }
581  // max inflight (average) = max_inflight_total / cycle cnt
582  XSPerfAccumulate("max_inflight", max_inflight)
583  QueuePerf(cfg.nMissEntries, num_valids, num_valids === cfg.nMissEntries.U)
584  io.full := num_valids === cfg.nMissEntries.U
585  XSPerfHistogram("num_valids", num_valids, true.B, 0, cfg.nMissEntries, 1)
586
587  val perfEvents = Seq(
588    ("dcache_missq_req      ", io.req.fire()                                                                                                                                                                       ),
589    ("dcache_missq_1_4_valid", (PopCount(entries.map(entry => (!entry.io.primary_ready))) < (cfg.nMissEntries.U/4.U))                                                                                              ),
590    ("dcache_missq_2_4_valid", (PopCount(entries.map(entry => (!entry.io.primary_ready))) > (cfg.nMissEntries.U/4.U)) & (PopCount(entries.map(entry => (!entry.io.primary_ready))) <= (cfg.nMissEntries.U/2.U))    ),
591    ("dcache_missq_3_4_valid", (PopCount(entries.map(entry => (!entry.io.primary_ready))) > (cfg.nMissEntries.U/2.U)) & (PopCount(entries.map(entry => (!entry.io.primary_ready))) <= (cfg.nMissEntries.U*3.U/4.U))),
592    ("dcache_missq_4_4_valid", (PopCount(entries.map(entry => (!entry.io.primary_ready))) > (cfg.nMissEntries.U*3.U/4.U))                                                                                          ),
593  )
594  generatePerfEvent()
595}
596