xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/mainpipe/MissQueue.scala (revision d6477c69bc3348d63058f8f4cebbf80cad7ca1e0)
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_grantlast
132
133  val should_refill_data_reg =  Reg(Bool())
134  val should_refill_data = WireInit(should_refill_data_reg)
135
136  val full_overwrite = req.isStore && req.store_mask.andR
137
138  val (_, _, refill_done, refill_count) = edge.count(io.mem_grant)
139  val grant_param = Reg(UInt(TLPermissions.bdWidth.W))
140
141  val grant_beats = RegInit(0.U(beatBits.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    grant_beats := 0.U
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      grant_beats := grant_beats + 1.U
229    }.otherwise {
230      // Grant
231      assert(full_overwrite)
232      for (i <- 0 until blockRows) {
233        refill_data(i) := new_data(i)
234      }
235      w_grantlast := true.B
236      hasData := false.B
237    }
238
239    refill_data_raw(refill_count) := io.mem_grant.bits.data
240    isDirty := io.mem_grant.bits.echo.lift(DirtyKey).getOrElse(false.B)
241  }
242
243  when (io.mem_finish.fire()) {
244    s_grantack := true.B
245  }
246
247  when (io.replace_pipe_req.fire()) {
248    s_replace_req := true.B
249  }
250
251  when (io.replace_pipe_resp) {
252    w_replace_resp := true.B
253  }
254
255  when (io.refill_pipe_req.fire()) {
256    s_refill := true.B
257  }
258
259  when (io.refill_pipe_resp) {
260    w_refill_resp := true.B
261  }
262
263  when (io.main_pipe_req.fire()) {
264    s_mainpipe_req := true.B
265  }
266
267  when (io.main_pipe_resp) {
268    w_mainpipe_resp := true.B
269  }
270
271  def before_read_sent_can_merge(new_req: MissReq): Bool = {
272    acquire_not_sent && req.isLoad && (new_req.isLoad || new_req.isStore)
273  }
274
275  def before_data_refill_can_merge(new_req: MissReq): Bool = {
276    data_not_refilled && (req.isLoad || req.isStore) && new_req.isLoad
277  }
278
279  def should_merge(new_req: MissReq): Bool = {
280    val block_match = req.addr === get_block_addr(new_req.addr)
281    val beat_match = new_req.addr(blockOffBits - 1, beatOffBits) >= grant_beats
282    block_match &&
283    (before_read_sent_can_merge(new_req) ||
284      beat_match && before_data_refill_can_merge(new_req))
285  }
286
287  def should_reject(new_req: MissReq): Bool = {
288    val block_match = req.addr === get_block_addr(new_req.addr)
289    val beat_match = new_req.addr(blockOffBits - 1, beatOffBits) >= grant_beats
290    val set_match = set === addr_to_dcache_set(new_req.vaddr)
291
292    req_valid &&
293      Mux(
294        block_match,
295        !before_read_sent_can_merge(new_req) &&
296          !(beat_match && before_data_refill_can_merge(new_req)),
297        set_match && new_req.way_en === req.way_en
298      )
299  }
300
301  io.primary_ready := !req_valid
302  io.secondary_ready := should_merge(io.req.bits)
303  io.secondary_reject := should_reject(io.req.bits)
304
305  // should not allocate, merge or reject at the same time
306  assert(RegNext(PopCount(Seq(io.primary_ready, io.secondary_ready, io.secondary_reject)) <= 1.U))
307
308  val refill_data_splited = WireInit(VecInit(Seq.tabulate(cfg.blockBytes * 8 / l1BusDataWidth)(i => {
309    val data = refill_data.asUInt
310    data((i + 1) * l1BusDataWidth - 1, i * l1BusDataWidth)
311  })))
312  io.refill_to_ldq.valid := RegNext(!w_grantlast && io.mem_grant.fire()) && should_refill_data
313  io.refill_to_ldq.bits.addr := RegNext(req.addr + (refill_count << refillOffBits))
314  io.refill_to_ldq.bits.data := refill_data_splited(RegNext(refill_count))
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.alias := req.vaddr(13, 12) // TODO
392
393  io.main_pipe_req.valid := !s_mainpipe_req && w_grantlast
394  io.main_pipe_req.bits := DontCare
395  io.main_pipe_req.bits.miss := true.B
396  io.main_pipe_req.bits.miss_id := io.id
397  io.main_pipe_req.bits.miss_param := grant_param
398  io.main_pipe_req.bits.miss_dirty := isDirty
399  io.main_pipe_req.bits.probe := false.B
400  io.main_pipe_req.bits.source := req.source
401  io.main_pipe_req.bits.cmd := req.cmd
402  io.main_pipe_req.bits.vaddr := req.vaddr
403  io.main_pipe_req.bits.addr := req.addr
404  io.main_pipe_req.bits.store_data := refill_data.asUInt
405  io.main_pipe_req.bits.store_mask := ~0.U(blockBytes.W)
406  io.main_pipe_req.bits.word_idx := req.word_idx
407  io.main_pipe_req.bits.amo_data := req.amo_data
408  io.main_pipe_req.bits.amo_mask := req.amo_mask
409  io.main_pipe_req.bits.id := req.id
410
411  io.block_addr.valid := req_valid && w_grantlast && !w_refill_resp
412  io.block_addr.bits := req.addr
413
414  io.debug_early_replace.valid := BoolStopWatch(io.replace_pipe_resp, io.refill_pipe_req.fire())
415  io.debug_early_replace.bits.idx := addr_to_dcache_set(req.vaddr)
416  io.debug_early_replace.bits.tag := req.replace_tag
417
418  XSPerfAccumulate("miss_req_primary", primary_fire)
419  XSPerfAccumulate("miss_req_merged", secondary_fire)
420  XSPerfAccumulate("load_miss_penalty_to_use",
421    should_refill_data &&
422      BoolStopWatch(primary_fire, io.refill_to_ldq.valid, true)
423  )
424  XSPerfAccumulate("main_pipe_penalty", BoolStopWatch(io.main_pipe_req.fire(), io.main_pipe_resp))
425  XSPerfAccumulate("penalty_blocked_by_channel_A", io.mem_acquire.valid && !io.mem_acquire.ready)
426  XSPerfAccumulate("penalty_waiting_for_channel_D", s_acquire && !w_grantlast && !io.mem_grant.valid)
427  XSPerfAccumulate("penalty_waiting_for_channel_E", io.mem_finish.valid && !io.mem_finish.ready)
428  XSPerfAccumulate("penalty_from_grant_to_refill", !w_refill_resp && w_grantlast)
429  XSPerfAccumulate("soft_prefetch_number", primary_fire && io.req.bits.source === SOFT_PREFETCH.U)
430
431  val (mshr_penalty_sample, mshr_penalty) = TransactionLatencyCounter(RegNext(primary_fire), release_entry)
432  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 0, 20, 1, true, true)
433  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 20, 100, 10, true, false)
434
435  val load_miss_begin = primary_fire && io.req.bits.isLoad
436  val refill_finished = RegNext(!w_grantlast && refill_done) && should_refill_data
437  val (load_miss_penalty_sample, load_miss_penalty) = TransactionLatencyCounter(load_miss_begin, refill_finished) // not real refill finish time
438  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 0, 20, 1, true, true)
439  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 20, 100, 10, true, false)
440
441  val (a_to_d_penalty_sample, a_to_d_penalty) = TransactionLatencyCounter(io.mem_acquire.fire(), io.mem_grant.fire() && refill_done)
442  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 0, 20, 1, true, true)
443  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 20, 100, 10, true, false)
444}
445
446class MissQueue(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule {
447  val io = IO(new Bundle {
448    val hartId = Input(UInt(8.W))
449    val req = Flipped(DecoupledIO(new MissReq))
450    val refill_to_ldq = ValidIO(new Refill)
451
452    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
453    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
454    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
455
456    val refill_pipe_req = DecoupledIO(new RefillPipeReq)
457    val refill_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
458
459    val replace_pipe_req = DecoupledIO(new MainPipeReq)
460    val replace_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
461
462    val main_pipe_req = DecoupledIO(new MainPipeReq)
463    val main_pipe_resp = Flipped(ValidIO(new AtomicsResp))
464
465    // block probe
466    val probe_addr = Input(UInt(PAddrBits.W))
467    val probe_block = Output(Bool())
468
469    val full = Output(Bool())
470
471    // only for performance counter
472    // This is valid when an mshr has finished replacing a block (w_replace_resp),
473    // but hasn't received Grant from L2 (!w_grantlast)
474    val debug_early_replace = Vec(cfg.nMissEntries, ValidIO(new Bundle() {
475      // info about the block that has been replaced
476      val idx = UInt(idxBits.W) // vaddr
477      val tag = UInt(tagBits.W) // paddr
478    }))
479  })
480
481  // 128KBL1: FIXME: provide vaddr for l2
482
483  val entries = Seq.fill(cfg.nMissEntries)(Module(new MissEntry(edge)))
484
485  val primary_ready_vec = entries.map(_.io.primary_ready)
486  val secondary_ready_vec = entries.map(_.io.secondary_ready)
487  val secondary_reject_vec = entries.map(_.io.secondary_reject)
488  val probe_block_vec = entries.map { case e => e.io.block_addr.valid && e.io.block_addr.bits === io.probe_addr }
489
490  val merge = Cat(secondary_ready_vec).orR
491  val reject = Cat(secondary_reject_vec).orR
492  val alloc = !reject && !merge && Cat(primary_ready_vec).orR
493  val accept = alloc || merge
494
495  assert(RegNext(PopCount(secondary_ready_vec) <= 1.U))
496//  assert(RegNext(PopCount(secondary_reject_vec) <= 1.U))
497  // It is possible that one mshr wants to merge a req, while another mshr wants to reject it.
498  // That is, a coming req has the same paddr as that of mshr_0 (merge),
499  // while it has the same set and the same way as mshr_1 (reject).
500  // In this situation, the coming req should be merged by mshr_0
501//  assert(RegNext(PopCount(Seq(merge, reject)) <= 1.U))
502
503  def select_valid_one[T <: Bundle](
504    in: Seq[DecoupledIO[T]],
505    out: DecoupledIO[T],
506    name: Option[String] = None): Unit = {
507
508    if (name.nonEmpty) { out.suggestName(s"${name.get}_select") }
509    out.valid := Cat(in.map(_.valid)).orR
510    out.bits := ParallelMux(in.map(_.valid) zip in.map(_.bits))
511    in.map(_.ready := out.ready)
512    assert(!RegNext(out.valid && PopCount(Cat(in.map(_.valid))) > 1.U))
513  }
514
515  io.mem_grant.ready := false.B
516
517  entries.zipWithIndex.foreach {
518    case (e, i) =>
519      val former_primary_ready = if(i == 0)
520        false.B
521      else
522        Cat((0 until i).map(j => entries(j).io.primary_ready)).orR
523
524      e.io.id := i.U
525      e.io.req.valid := io.req.valid
526      e.io.primary_valid := io.req.valid &&
527        !merge &&
528        !reject &&
529        !former_primary_ready &&
530        e.io.primary_ready
531      e.io.req.bits := io.req.bits
532
533      e.io.mem_grant.valid := false.B
534      e.io.mem_grant.bits := DontCare
535      when (io.mem_grant.bits.source === i.U) {
536        e.io.mem_grant <> io.mem_grant
537      }
538
539      e.io.refill_pipe_resp := io.refill_pipe_resp.valid && io.refill_pipe_resp.bits === i.U
540      e.io.replace_pipe_resp := io.replace_pipe_resp.valid && io.replace_pipe_resp.bits === i.U
541      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
542
543      io.debug_early_replace(i) := e.io.debug_early_replace
544  }
545
546  io.req.ready := accept
547  io.refill_to_ldq.valid := Cat(entries.map(_.io.refill_to_ldq.valid)).orR
548  io.refill_to_ldq.bits := ParallelMux(entries.map(_.io.refill_to_ldq.valid) zip entries.map(_.io.refill_to_ldq.bits))
549
550  TLArbiter.lowest(edge, io.mem_acquire, entries.map(_.io.mem_acquire):_*)
551  TLArbiter.lowest(edge, io.mem_finish, entries.map(_.io.mem_finish):_*)
552
553  arbiter(entries.map(_.io.refill_pipe_req), io.refill_pipe_req, Some("refill_pipe_req"))
554  arbiter(entries.map(_.io.replace_pipe_req), io.replace_pipe_req, Some("replace_pipe_req"))
555  arbiter(entries.map(_.io.main_pipe_req), io.main_pipe_req, Some("main_pipe_req"))
556
557  io.probe_block := Cat(probe_block_vec).orR
558
559  io.full := ~Cat(entries.map(_.io.primary_ready)).andR
560
561  if (env.EnableDifftest) {
562    val difftest = Module(new DifftestRefillEvent)
563    difftest.io.clock := clock
564    difftest.io.coreid := io.hartId
565    difftest.io.valid := io.refill_to_ldq.valid && io.refill_to_ldq.bits.hasdata && io.refill_to_ldq.bits.refill_done
566    difftest.io.addr := io.refill_to_ldq.bits.addr
567    difftest.io.data := io.refill_to_ldq.bits.data_raw.asTypeOf(difftest.io.data)
568  }
569
570  XSPerfAccumulate("miss_req", io.req.fire())
571  XSPerfAccumulate("miss_req_allocate", io.req.fire() && alloc)
572  XSPerfAccumulate("miss_req_merge_load", io.req.fire() && merge && io.req.bits.isLoad)
573  XSPerfAccumulate("miss_req_reject_load", io.req.valid && reject && io.req.bits.isLoad)
574  XSPerfAccumulate("probe_blocked_by_miss", io.probe_block)
575  val max_inflight = RegInit(0.U((log2Up(cfg.nMissEntries) + 1).W))
576  val num_valids = PopCount(~Cat(primary_ready_vec).asUInt)
577  when (num_valids > max_inflight) {
578    max_inflight := num_valids
579  }
580  // max inflight (average) = max_inflight_total / cycle cnt
581  XSPerfAccumulate("max_inflight", max_inflight)
582  QueuePerf(cfg.nMissEntries, num_valids, num_valids === cfg.nMissEntries.U)
583  io.full := num_valids === cfg.nMissEntries.U
584  XSPerfHistogram("num_valids", num_valids, true.B, 0, cfg.nMissEntries, 1)
585  val perfinfo = IO(new Bundle(){
586    val perfEvents = Output(new PerfEventsBundle(5))
587  })
588  val perfEvents = Seq(
589    ("dcache_missq_req          ", io.req.fire()                                                                                                                                                                       ),
590    ("dcache_missq_1/4_valid    ", (PopCount(entries.map(entry => (!entry.io.primary_ready))) < (cfg.nMissEntries.U/4.U))                                                                                              ),
591    ("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))    ),
592    ("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))),
593    ("dcache_missq_4/4_valid    ", (PopCount(entries.map(entry => (!entry.io.primary_ready))) > (cfg.nMissEntries.U*3.U/4.U))                                                                                          ),
594  )
595
596  for (((perf_out,(perf_name,perf)),i) <- perfinfo.perfEvents.perf_events.zip(perfEvents).zipWithIndex) {
597    perf_out.incr_step := RegNext(perf)
598  }
599}
600