xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/mainpipe/MissQueue.scala (revision 7a2fc509e2d355879c4db3dc3f17a6ccacd3d09e)
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  replace.error := false.B
364
365  io.refill_pipe_req.valid := !s_refill && w_replace_resp && w_grantlast
366  val refill = io.refill_pipe_req.bits
367  refill.source := req.source
368  refill.addr := req.addr
369  refill.way_en := req.way_en
370  refill.wmask := Mux(
371    hasData || req.isLoad,
372    ~0.U(DCacheBanks.W),
373    VecInit((0 until DCacheBanks).map(i => get_mask_of_bank(i, req.store_mask).orR)).asUInt
374  )
375  refill.data := refill_data.asTypeOf((new RefillPipeReq).data)
376  refill.miss_id := io.id
377  refill.id := req.id
378  def missCohGen(cmd: UInt, param: UInt, dirty: Bool) = {
379    val c = categorize(cmd)
380    MuxLookup(Cat(c, param, dirty), Nothing, Seq(
381      //(effect param) -> (next)
382      Cat(rd, toB, false.B)  -> Branch,
383      Cat(rd, toB, true.B)   -> Branch,
384      Cat(rd, toT, false.B)  -> Trunk,
385      Cat(rd, toT, true.B)   -> Dirty,
386      Cat(wi, toT, false.B)  -> Trunk,
387      Cat(wi, toT, true.B)   -> Dirty,
388      Cat(wr, toT, false.B)  -> Dirty,
389      Cat(wr, toT, true.B)   -> Dirty))
390  }
391  refill.meta.coh := ClientMetadata(missCohGen(req.cmd, grant_param, isDirty))
392  refill.error := error
393  refill.alias := req.vaddr(13, 12) // TODO
394
395  io.main_pipe_req.valid := !s_mainpipe_req && w_grantlast
396  io.main_pipe_req.bits := DontCare
397  io.main_pipe_req.bits.miss := true.B
398  io.main_pipe_req.bits.miss_id := io.id
399  io.main_pipe_req.bits.miss_param := grant_param
400  io.main_pipe_req.bits.miss_dirty := isDirty
401  io.main_pipe_req.bits.miss_way_en := req.way_en
402  io.main_pipe_req.bits.probe := false.B
403  io.main_pipe_req.bits.source := req.source
404  io.main_pipe_req.bits.cmd := req.cmd
405  io.main_pipe_req.bits.vaddr := req.vaddr
406  io.main_pipe_req.bits.addr := req.addr
407  io.main_pipe_req.bits.store_data := refill_data.asUInt
408  io.main_pipe_req.bits.store_mask := ~0.U(blockBytes.W)
409  io.main_pipe_req.bits.word_idx := req.word_idx
410  io.main_pipe_req.bits.amo_data := req.amo_data
411  io.main_pipe_req.bits.amo_mask := req.amo_mask
412  io.main_pipe_req.bits.error := error
413  io.main_pipe_req.bits.id := req.id
414
415  io.block_addr.valid := req_valid && w_grantlast && !w_refill_resp
416  io.block_addr.bits := req.addr
417
418  io.debug_early_replace.valid := BoolStopWatch(io.replace_pipe_resp, io.refill_pipe_req.fire())
419  io.debug_early_replace.bits.idx := addr_to_dcache_set(req.vaddr)
420  io.debug_early_replace.bits.tag := req.replace_tag
421
422  XSPerfAccumulate("miss_req_primary", primary_fire)
423  XSPerfAccumulate("miss_req_merged", secondary_fire)
424  XSPerfAccumulate("load_miss_penalty_to_use",
425    should_refill_data &&
426      BoolStopWatch(primary_fire, io.refill_to_ldq.valid, true)
427  )
428  XSPerfAccumulate("main_pipe_penalty", BoolStopWatch(io.main_pipe_req.fire(), io.main_pipe_resp))
429  XSPerfAccumulate("penalty_blocked_by_channel_A", io.mem_acquire.valid && !io.mem_acquire.ready)
430  XSPerfAccumulate("penalty_waiting_for_channel_D", s_acquire && !w_grantlast && !io.mem_grant.valid)
431  XSPerfAccumulate("penalty_waiting_for_channel_E", io.mem_finish.valid && !io.mem_finish.ready)
432  XSPerfAccumulate("penalty_from_grant_to_refill", !w_refill_resp && w_grantlast)
433  XSPerfAccumulate("soft_prefetch_number", primary_fire && io.req.bits.source === SOFT_PREFETCH.U)
434
435  val (mshr_penalty_sample, mshr_penalty) = TransactionLatencyCounter(RegNext(primary_fire), release_entry)
436  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 0, 20, 1, true, true)
437  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 20, 100, 10, true, false)
438
439  val load_miss_begin = primary_fire && io.req.bits.isLoad
440  val refill_finished = RegNext(!w_grantlast && refill_done) && should_refill_data
441  val (load_miss_penalty_sample, load_miss_penalty) = TransactionLatencyCounter(load_miss_begin, refill_finished) // not real refill finish time
442  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 0, 20, 1, true, true)
443  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 20, 100, 10, true, false)
444
445  val (a_to_d_penalty_sample, a_to_d_penalty) = TransactionLatencyCounter(io.mem_acquire.fire(), io.mem_grant.fire() && refill_done)
446  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 0, 20, 1, true, true)
447  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 20, 100, 10, true, false)
448}
449
450class MissQueue(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule with HasPerfEvents {
451  val io = IO(new Bundle {
452    val hartId = Input(UInt(8.W))
453    val req = Flipped(DecoupledIO(new MissReq))
454    val refill_to_ldq = ValidIO(new Refill)
455
456    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
457    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
458    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
459
460    val refill_pipe_req = DecoupledIO(new RefillPipeReq)
461    val refill_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
462
463    val replace_pipe_req = DecoupledIO(new MainPipeReq)
464    val replace_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
465
466    val main_pipe_req = DecoupledIO(new MainPipeReq)
467    val main_pipe_resp = Flipped(ValidIO(new AtomicsResp))
468
469    // block probe
470    val probe_addr = Input(UInt(PAddrBits.W))
471    val probe_block = Output(Bool())
472
473    val full = Output(Bool())
474
475    // only for performance counter
476    // This is valid when an mshr has finished replacing a block (w_replace_resp),
477    // but hasn't received Grant from L2 (!w_grantlast)
478    val debug_early_replace = Vec(cfg.nMissEntries, ValidIO(new Bundle() {
479      // info about the block that has been replaced
480      val idx = UInt(idxBits.W) // vaddr
481      val tag = UInt(tagBits.W) // paddr
482    }))
483  })
484
485  // 128KBL1: FIXME: provide vaddr for l2
486
487  val entries = Seq.fill(cfg.nMissEntries)(Module(new MissEntry(edge)))
488
489  val primary_ready_vec = entries.map(_.io.primary_ready)
490  val secondary_ready_vec = entries.map(_.io.secondary_ready)
491  val secondary_reject_vec = entries.map(_.io.secondary_reject)
492  val probe_block_vec = entries.map { case e => e.io.block_addr.valid && e.io.block_addr.bits === io.probe_addr }
493
494  val merge = Cat(secondary_ready_vec).orR
495  val reject = Cat(secondary_reject_vec).orR
496  val alloc = !reject && !merge && Cat(primary_ready_vec).orR
497  val accept = alloc || merge
498
499  assert(RegNext(PopCount(secondary_ready_vec) <= 1.U))
500//  assert(RegNext(PopCount(secondary_reject_vec) <= 1.U))
501  // It is possible that one mshr wants to merge a req, while another mshr wants to reject it.
502  // That is, a coming req has the same paddr as that of mshr_0 (merge),
503  // while it has the same set and the same way as mshr_1 (reject).
504  // In this situation, the coming req should be merged by mshr_0
505//  assert(RegNext(PopCount(Seq(merge, reject)) <= 1.U))
506
507  def select_valid_one[T <: Bundle](
508    in: Seq[DecoupledIO[T]],
509    out: DecoupledIO[T],
510    name: Option[String] = None): Unit = {
511
512    if (name.nonEmpty) { out.suggestName(s"${name.get}_select") }
513    out.valid := Cat(in.map(_.valid)).orR
514    out.bits := ParallelMux(in.map(_.valid) zip in.map(_.bits))
515    in.map(_.ready := out.ready)
516    assert(!RegNext(out.valid && PopCount(Cat(in.map(_.valid))) > 1.U))
517  }
518
519  io.mem_grant.ready := false.B
520
521  entries.zipWithIndex.foreach {
522    case (e, i) =>
523      val former_primary_ready = if(i == 0)
524        false.B
525      else
526        Cat((0 until i).map(j => entries(j).io.primary_ready)).orR
527
528      e.io.id := i.U
529      e.io.req.valid := io.req.valid
530      e.io.primary_valid := io.req.valid &&
531        !merge &&
532        !reject &&
533        !former_primary_ready &&
534        e.io.primary_ready
535      e.io.req.bits := io.req.bits
536
537      e.io.mem_grant.valid := false.B
538      e.io.mem_grant.bits := DontCare
539      when (io.mem_grant.bits.source === i.U) {
540        e.io.mem_grant <> io.mem_grant
541      }
542
543      e.io.refill_pipe_resp := io.refill_pipe_resp.valid && io.refill_pipe_resp.bits === i.U
544      e.io.replace_pipe_resp := io.replace_pipe_resp.valid && io.replace_pipe_resp.bits === i.U
545      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
546
547      io.debug_early_replace(i) := e.io.debug_early_replace
548  }
549
550  io.req.ready := accept
551  io.refill_to_ldq.valid := Cat(entries.map(_.io.refill_to_ldq.valid)).orR
552  io.refill_to_ldq.bits := ParallelMux(entries.map(_.io.refill_to_ldq.valid) zip entries.map(_.io.refill_to_ldq.bits))
553
554  TLArbiter.lowest(edge, io.mem_acquire, entries.map(_.io.mem_acquire):_*)
555  TLArbiter.lowest(edge, io.mem_finish, entries.map(_.io.mem_finish):_*)
556
557  arbiter_with_pipereg(entries.map(_.io.refill_pipe_req), io.refill_pipe_req, Some("refill_pipe_req"))
558  arbiter(entries.map(_.io.replace_pipe_req), io.replace_pipe_req, Some("replace_pipe_req"))
559  arbiter(entries.map(_.io.main_pipe_req), io.main_pipe_req, Some("main_pipe_req"))
560
561  io.probe_block := Cat(probe_block_vec).orR
562
563  io.full := ~Cat(entries.map(_.io.primary_ready)).andR
564
565  if (env.EnableDifftest) {
566    val difftest = Module(new DifftestRefillEvent)
567    difftest.io.clock := clock
568    difftest.io.coreid := io.hartId
569    difftest.io.cacheid := 1.U
570    difftest.io.valid := io.refill_to_ldq.valid && io.refill_to_ldq.bits.hasdata && io.refill_to_ldq.bits.refill_done
571    difftest.io.addr := io.refill_to_ldq.bits.addr
572    difftest.io.data := io.refill_to_ldq.bits.data_raw.asTypeOf(difftest.io.data)
573  }
574
575  XSPerfAccumulate("miss_req", io.req.fire())
576  XSPerfAccumulate("miss_req_allocate", io.req.fire() && alloc)
577  XSPerfAccumulate("miss_req_merge_load", io.req.fire() && merge && io.req.bits.isLoad)
578  XSPerfAccumulate("miss_req_reject_load", io.req.valid && reject && io.req.bits.isLoad)
579  XSPerfAccumulate("probe_blocked_by_miss", io.probe_block)
580  val max_inflight = RegInit(0.U((log2Up(cfg.nMissEntries) + 1).W))
581  val num_valids = PopCount(~Cat(primary_ready_vec).asUInt)
582  when (num_valids > max_inflight) {
583    max_inflight := num_valids
584  }
585  // max inflight (average) = max_inflight_total / cycle cnt
586  XSPerfAccumulate("max_inflight", max_inflight)
587  QueuePerf(cfg.nMissEntries, num_valids, num_valids === cfg.nMissEntries.U)
588  io.full := num_valids === cfg.nMissEntries.U
589  XSPerfHistogram("num_valids", num_valids, true.B, 0, cfg.nMissEntries, 1)
590
591  val perfEvents = Seq(
592    ("dcache_missq_req      ", io.req.fire()                                                                                                                                                                       ),
593    ("dcache_missq_1_4_valid", (PopCount(entries.map(entry => (!entry.io.primary_ready))) < (cfg.nMissEntries.U/4.U))                                                                                              ),
594    ("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))    ),
595    ("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))),
596    ("dcache_missq_4_4_valid", (PopCount(entries.map(entry => (!entry.io.primary_ready))) > (cfg.nMissEntries.U*3.U/4.U))                                                                                          ),
597  )
598  generatePerfEvent()
599}
600