xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/mainpipe/MissQueue.scala (revision ffc9de54938a9574f465b83a71d5252cfd37cf30)
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 xiangshan._
23import utils._
24import utility._
25import freechips.rocketchip.tilelink._
26import freechips.rocketchip.tilelink.ClientStates._
27import freechips.rocketchip.tilelink.MemoryOpCategories._
28import freechips.rocketchip.tilelink.TLPermissions._
29import difftest._
30import coupledL2.{AliasKey, VaddrKey, DirtyKey, PrefetchKey}
31import mem.AddPipelineReg
32import mem.trace._
33
34class MissReqWoStoreData(implicit p: Parameters) extends DCacheBundle {
35  val source = UInt(sourceTypeWidth.W)
36  val cmd = UInt(M_SZ.W)
37  val addr = UInt(PAddrBits.W)
38  val vaddr = UInt(VAddrBits.W)
39  val way_en = UInt(DCacheWays.W)
40  val pc = UInt(VAddrBits.W)
41
42  // store
43  val full_overwrite = Bool()
44
45  // which word does amo work on?
46  val word_idx = UInt(log2Up(blockWords).W)
47  val amo_data = UInt(DataBits.W)
48  val amo_mask = UInt((DataBits / 8).W)
49
50  val req_coh = new ClientMetadata
51  val replace_coh = new ClientMetadata
52  val replace_tag = UInt(tagBits.W)
53  val id = UInt(reqIdWidth.W)
54
55  // For now, miss queue entry req is actually valid when req.valid && !cancel
56  // * req.valid is fast to generate
57  // * cancel is slow to generate, it will not be used until the last moment
58  //
59  // cancel may come from the following sources:
60  // 1. miss req blocked by writeback queue:
61  //      a writeback req of the same address is in progress
62  // 2. pmp check failed
63  val cancel = Bool() // cancel is slow to generate, it will cancel missreq.valid
64
65  // Req source decode
66  // Note that req source is NOT cmd type
67  // For instance, a req which isFromPrefetch may have R or W cmd
68  def isFromLoad = source === LOAD_SOURCE.U
69  def isFromStore = source === STORE_SOURCE.U
70  def isFromAMO = source === AMO_SOURCE.U
71  def isFromPrefetch = source >= DCACHE_PREFETCH_SOURCE.U
72  def hit = req_coh.isValid()
73}
74
75class MissReqStoreData(implicit p: Parameters) extends DCacheBundle {
76  // store data and store mask will be written to miss queue entry
77  // 1 cycle after req.fire() and meta write
78  val store_data = UInt((cfg.blockBytes * 8).W)
79  val store_mask = UInt(cfg.blockBytes.W)
80}
81
82class MissReq(implicit p: Parameters) extends MissReqWoStoreData {
83  // store data and store mask will be written to miss queue entry
84  // 1 cycle after req.fire() and meta write
85  val store_data = UInt((cfg.blockBytes * 8).W)
86  val store_mask = UInt(cfg.blockBytes.W)
87
88  def toMissReqStoreData(): MissReqStoreData = {
89    val out = Wire(new MissReqStoreData)
90    out.store_data := store_data
91    out.store_mask := store_mask
92    out
93  }
94
95  def toMissReqWoStoreData(): MissReqWoStoreData = {
96    val out = Wire(new MissReqWoStoreData)
97    out.source := source
98    out.cmd := cmd
99    out.addr := addr
100    out.vaddr := vaddr
101    out.way_en := way_en
102    out.full_overwrite := full_overwrite
103    out.word_idx := word_idx
104    out.amo_data := amo_data
105    out.amo_mask := amo_mask
106    out.req_coh := req_coh
107    out.replace_coh := replace_coh
108    out.replace_tag := replace_tag
109    out.id := id
110    out.cancel := cancel
111    out.pc := pc
112    out
113  }
114}
115
116class MissResp(implicit p: Parameters) extends DCacheBundle {
117  val id = UInt(log2Up(cfg.nMissEntries).W)
118  // cache miss request is handled by miss queue, either merged or newly allocated
119  val handled = Bool()
120  // cache req missed, merged into one of miss queue entries
121  // i.e. !miss_merged means this access is the first miss for this cacheline
122  val merged = Bool()
123  val repl_way_en = UInt(DCacheWays.W)
124}
125
126
127/**
128  * miss queue enq logic: enq is now splited into 2 cycles
129  *  +---------------------------------------------------------------------+    pipeline reg  +-------------------------+
130  *  +         s0: enq source arbiter, judge mshr alloc or merge           +     +-------+    + s1: real alloc or merge +
131  *  +                      +-----+          primary_fire?       ->        +     | alloc |    +                         +
132  *  + mainpipe  -> req0 -> |     |          secondary_fire?     ->        +     | merge |    +                         +
133  *  + loadpipe0 -> req1 -> | arb | -> req                       ->        +  -> | req   | -> +                         +
134  *  + loadpipe1 -> req2 -> |     |          mshr id             ->        +     | id    |    +                         +
135  *  +                      +-----+                                        +     +-------+    +                         +
136  *  +---------------------------------------------------------------------+                  +-------------------------+
137  */
138
139// a pipeline reg between MissReq and MissEntry
140class MissReqPipeRegBundle(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheBundle {
141  val req           = new MissReq
142  // this request is about to merge to an existing mshr
143  val merge         = Bool()
144  // this request is about to allocate a new mshr
145  val alloc         = Bool()
146  val mshr_id       = UInt(log2Up(cfg.nMissEntries).W)
147
148  def reg_valid(): Bool = {
149    (merge || alloc)
150  }
151
152  def reject_req(new_req: MissReq): Bool = {
153    val set_match = addr_to_dcache_set(req.vaddr) === addr_to_dcache_set(new_req.vaddr)
154    val way_match = req.way_en === new_req.way_en
155    reg_valid() && set_match && way_match
156  }
157
158  def merge_req(new_req: MissReq): Bool = {
159    val block_match = get_block(req.addr) === get_block(new_req.addr)
160    val merge_load = (req.isFromLoad || req.isFromStore || req.isFromPrefetch) && new_req.isFromLoad
161    // store merge to a store is disabled, sbuffer should avoid this situation, as store to same address should preserver their program order to match memory model
162    val merge_store = (req.isFromLoad || req.isFromPrefetch) && new_req.isFromStore
163    Mux(alloc, block_match && (merge_load || merge_store), false.B)
164  }
165
166  // send out acquire as soon as possible
167  // if a new store miss req is about to merge into this pipe reg, don't send acquire now
168  def can_send_acquire(valid: Bool, new_req: MissReq): Bool = {
169    alloc && (!valid || !merge_req(new_req) || !new_req.isFromStore)
170  }
171
172  def get_acquire(l2_pf_store_only: Bool): TLBundleA = {
173    val acquire = Wire(new TLBundleA(edge.bundle))
174    val grow_param = req.req_coh.onAccess(req.cmd)._2
175    val acquireBlock = edge.AcquireBlock(
176      fromSource = mshr_id,
177      toAddress = get_block_addr(req.addr),
178      lgSize = (log2Up(cfg.blockBytes)).U,
179      growPermissions = grow_param
180    )._2
181    val acquirePerm = edge.AcquirePerm(
182      fromSource = mshr_id,
183      toAddress = get_block_addr(req.addr),
184      lgSize = (log2Up(cfg.blockBytes)).U,
185      growPermissions = grow_param
186    )._2
187    acquire := Mux(req.full_overwrite, acquirePerm, acquireBlock)
188    // resolve cache alias by L2
189    acquire.user.lift(AliasKey).foreach( _ := req.vaddr(13, 12))
190    // pass vaddr to l2
191    acquire.user.lift(VaddrKey).foreach(_ := req.vaddr(VAddrBits - 1, blockOffBits))
192    // trigger prefetch
193    acquire.user.lift(PrefetchKey).foreach(_ := Mux(l2_pf_store_only, req.isFromStore, true.B))
194    // req source
195    when(req.isFromLoad) {
196      acquire.user.lift(ReqSourceKey).foreach(_ := MemReqSource.CPULoadData.id.U)
197    }.elsewhen(req.isFromStore) {
198      acquire.user.lift(ReqSourceKey).foreach(_ := MemReqSource.CPUStoreData.id.U)
199    }.elsewhen(req.isFromAMO) {
200      acquire.user.lift(ReqSourceKey).foreach(_ := MemReqSource.CPUAtomicData.id.U)
201    }.otherwise {
202      acquire.user.lift(ReqSourceKey).foreach(_ := MemReqSource.L1DataPrefetch.id.U)
203    }
204
205    acquire
206  }
207}
208
209class MissEntry(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule {
210  val io = IO(new Bundle() {
211    val hartId = Input(UInt(8.W))
212    // MSHR ID
213    val id = Input(UInt(log2Up(cfg.nMissEntries).W))
214    // client requests
215    // MSHR update request, MSHR state and addr will be updated when req.fire()
216    val req = Flipped(ValidIO(new MissReqWoStoreData))
217    // pipeline reg
218    val miss_req_pipe_reg = Input(new MissReqPipeRegBundle(edge))
219    // allocate this entry for new req
220    val primary_valid = Input(Bool())
221    // this entry is free and can be allocated to new reqs
222    val primary_ready = Output(Bool())
223    // this entry is busy, but it can merge the new req
224    val secondary_ready = Output(Bool())
225    // this entry is busy and it can not merge the new req
226    val secondary_reject = Output(Bool())
227    // way selected for replacing, used to support plru update
228    val repl_way_en = Output(UInt(DCacheWays.W))
229
230    // bus
231    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
232    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
233    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
234
235    // send refill info to load queue
236    val refill_to_ldq = ValidIO(new Refill)
237
238    // refill pipe
239    val refill_pipe_req = DecoupledIO(new RefillPipeReq)
240    val refill_pipe_resp = Input(Bool())
241
242    // replace pipe
243    val replace_pipe_req = DecoupledIO(new MainPipeReq)
244    val replace_pipe_resp = Input(Bool())
245
246    // main pipe: amo miss
247    val main_pipe_req = DecoupledIO(new MainPipeReq)
248    val main_pipe_resp = Input(Bool())
249
250    val block_addr = ValidIO(UInt(PAddrBits.W))
251
252    val debug_early_replace = ValidIO(new Bundle() {
253      // info about the block that has been replaced
254      val idx = UInt(idxBits.W) // vaddr
255      val tag = UInt(tagBits.W) // paddr
256    })
257
258    val req_handled_by_this_entry = Output(Bool())
259
260    val forwardInfo = Output(new MissEntryForwardIO)
261    val l2_pf_store_only = Input(Bool())
262
263    // whether the pipeline reg has send out an acquire
264    val acquire_fired_by_pipe_reg = Input(Bool())
265
266    val perf_pending_prefetch = Output(Bool())
267    val perf_pending_normal   = Output(Bool())
268
269    val rob_head_query = new DCacheBundle {
270      val vaddr = Input(UInt(VAddrBits.W))
271      val query_valid = Input(Bool())
272
273      val resp = Output(Bool())
274
275      def hit(e_vaddr: UInt): Bool = {
276        require(e_vaddr.getWidth == VAddrBits)
277        query_valid && vaddr(VAddrBits - 1, DCacheLineOffset) === e_vaddr(VAddrBits - 1, DCacheLineOffset)
278      }
279    }
280
281    val latency_monitor = new DCacheBundle {
282      val load_miss_refilling  = Output(Bool())
283      val store_miss_refilling = Output(Bool())
284      val amo_miss_refilling   = Output(Bool())
285      val pf_miss_refilling    = Output(Bool())
286    }
287  })
288
289  assert(!RegNext(io.primary_valid && !io.primary_ready))
290
291  val req = Reg(new MissReqWoStoreData)
292  val req_primary_fire = Reg(new MissReqWoStoreData) // for perf use
293  val req_store_mask = Reg(UInt(cfg.blockBytes.W))
294  val req_valid = RegInit(false.B)
295  val set = addr_to_dcache_set(req.vaddr)
296
297  val miss_req_pipe_reg_bits = io.miss_req_pipe_reg.req
298
299  val input_req_is_prefetch = isPrefetch(miss_req_pipe_reg_bits.cmd)
300
301  val s_acquire = RegInit(true.B)
302  val s_grantack = RegInit(true.B)
303  val s_replace_req = RegInit(true.B)
304  val s_refill = RegInit(true.B)
305  val s_mainpipe_req = RegInit(true.B)
306
307  val w_grantfirst = RegInit(true.B)
308  val w_grantlast = RegInit(true.B)
309  val w_replace_resp = RegInit(true.B)
310  val w_refill_resp = RegInit(true.B)
311  val w_mainpipe_resp = RegInit(true.B)
312
313  val release_entry = s_grantack && w_refill_resp && w_mainpipe_resp
314
315  val acquire_not_sent = !s_acquire && !io.mem_acquire.ready
316  val data_not_refilled = !w_grantfirst
317
318  val error = RegInit(false.B)
319  val prefetch = RegInit(false.B)
320  val access = RegInit(false.B)
321
322  val should_refill_data_reg =  Reg(Bool())
323  val should_refill_data = WireInit(should_refill_data_reg)
324
325  // val full_overwrite = req.isFromStore && req_store_mask.andR
326  val full_overwrite = Reg(Bool())
327
328  val (_, _, refill_done, refill_count) = edge.count(io.mem_grant)
329  val grant_param = Reg(UInt(TLPermissions.bdWidth.W))
330
331  // refill data with store data, this reg will be used to store:
332  // 1. store data (if needed), before l2 refill data
333  // 2. store data and l2 refill data merged result (i.e. new cacheline taht will be write to data array)
334  val refill_and_store_data = Reg(Vec(blockRows, UInt(rowBits.W)))
335  // raw data refilled to l1 by l2
336  val refill_data_raw = Reg(Vec(blockBytes/beatBytes, UInt(beatBits.W)))
337
338  // allocate current miss queue entry for a miss req
339  val primary_fire = WireInit(io.req.valid && io.primary_ready && io.primary_valid && !io.req.bits.cancel)
340  // merge miss req to current miss queue entry
341  val secondary_fire = WireInit(io.req.valid && io.secondary_ready && !io.req.bits.cancel)
342
343  val req_handled_by_this_entry = primary_fire || secondary_fire
344
345  // for perf use
346  val secondary_fired = RegInit(false.B)
347
348  io.perf_pending_prefetch := req_valid && prefetch && !secondary_fired
349  io.perf_pending_normal   := req_valid && (!prefetch || secondary_fired)
350
351  io.rob_head_query.resp   := io.rob_head_query.hit(req.vaddr) && req_valid
352
353  io.req_handled_by_this_entry := req_handled_by_this_entry
354
355  when (release_entry && req_valid) {
356    req_valid := false.B
357  }
358
359  when (io.miss_req_pipe_reg.alloc) {
360    assert(RegNext(primary_fire), "after 1 cycle of primary_fire, entry will be allocated")
361    req_valid := true.B
362
363    req := miss_req_pipe_reg_bits.toMissReqWoStoreData()
364    req_primary_fire := miss_req_pipe_reg_bits.toMissReqWoStoreData()
365    req.addr := get_block_addr(miss_req_pipe_reg_bits.addr)
366
367    s_acquire := io.acquire_fired_by_pipe_reg
368    s_grantack := false.B
369
370    w_grantfirst := false.B
371    w_grantlast := false.B
372
373    when(miss_req_pipe_reg_bits.isFromStore) {
374      req_store_mask := miss_req_pipe_reg_bits.store_mask
375      for (i <- 0 until blockRows) {
376        refill_and_store_data(i) := miss_req_pipe_reg_bits.store_data(rowBits * (i + 1) - 1, rowBits * i)
377      }
378    }
379    full_overwrite := miss_req_pipe_reg_bits.isFromStore && miss_req_pipe_reg_bits.full_overwrite
380
381    when (!miss_req_pipe_reg_bits.isFromAMO) {
382      s_refill := false.B
383      w_refill_resp := false.B
384    }
385
386    when (!miss_req_pipe_reg_bits.hit && miss_req_pipe_reg_bits.replace_coh.isValid() && !miss_req_pipe_reg_bits.isFromAMO) {
387      s_replace_req := false.B
388      w_replace_resp := false.B
389    }
390
391    when (miss_req_pipe_reg_bits.isFromAMO) {
392      s_mainpipe_req := false.B
393      w_mainpipe_resp := false.B
394    }
395
396    should_refill_data_reg := miss_req_pipe_reg_bits.isFromLoad
397    error := false.B
398    prefetch := input_req_is_prefetch
399    access := false.B
400    secondary_fired := false.B
401  }
402
403  when (io.miss_req_pipe_reg.merge) {
404    assert(RegNext(secondary_fire) || RegNext(RegNext(primary_fire)), "after 1 cycle of secondary_fire or 2 cycle of primary_fire, entry will be merged")
405    assert(miss_req_pipe_reg_bits.req_coh.state <= req.req_coh.state || (prefetch && !access))
406    assert(!(miss_req_pipe_reg_bits.isFromAMO || req.isFromAMO))
407    // use the most uptodate meta
408    req.req_coh := miss_req_pipe_reg_bits.req_coh
409
410    when (miss_req_pipe_reg_bits.isFromStore) {
411      req := miss_req_pipe_reg_bits
412      req.addr := get_block_addr(miss_req_pipe_reg_bits.addr)
413      // vaddr??
414      req.vaddr := req.vaddr
415      req.way_en := req.way_en
416      req.replace_coh := req.replace_coh
417      req.replace_tag := req.replace_tag
418      req_store_mask := miss_req_pipe_reg_bits.store_mask
419      for (i <- 0 until blockRows) {
420        refill_and_store_data(i) := miss_req_pipe_reg_bits.store_data(rowBits * (i + 1) - 1, rowBits * i)
421      }
422      full_overwrite := miss_req_pipe_reg_bits.isFromStore && miss_req_pipe_reg_bits.full_overwrite
423    }
424
425    should_refill_data := should_refill_data_reg || miss_req_pipe_reg_bits.isFromLoad
426    should_refill_data_reg := should_refill_data
427    when (!input_req_is_prefetch) {
428      access := true.B // when merge non-prefetch req, set access bit
429    }
430    secondary_fired := true.B
431  }
432
433  when (io.mem_acquire.fire()) {
434    s_acquire := true.B
435  }
436
437  // merge data refilled by l2 and store data, update miss queue entry, gen refill_req
438  val new_data = Wire(Vec(blockRows, UInt(rowBits.W)))
439  val new_mask = Wire(Vec(blockRows, UInt(rowBytes.W)))
440  // merge refilled data and store data (if needed)
441  def mergePutData(old_data: UInt, new_data: UInt, wmask: UInt): UInt = {
442    val full_wmask = FillInterleaved(8, wmask)
443    (~full_wmask & old_data | full_wmask & new_data)
444  }
445  for (i <- 0 until blockRows) {
446    // new_data(i) := req.store_data(rowBits * (i + 1) - 1, rowBits * i)
447    new_data(i) := refill_and_store_data(i)
448    // we only need to merge data for Store
449    new_mask(i) := Mux(req.isFromStore, req_store_mask(rowBytes * (i + 1) - 1, rowBytes * i), 0.U)
450  }
451
452  val hasData = RegInit(true.B)
453  val isDirty = RegInit(false.B)
454  when (io.mem_grant.fire()) {
455    w_grantfirst := true.B
456    grant_param := io.mem_grant.bits.param
457    when (edge.hasData(io.mem_grant.bits)) {
458      // GrantData
459      for (i <- 0 until beatRows) {
460        val idx = (refill_count << log2Floor(beatRows)) + i.U
461        val grant_row = io.mem_grant.bits.data(rowBits * (i + 1) - 1, rowBits * i)
462        refill_and_store_data(idx) := mergePutData(grant_row, new_data(idx), new_mask(idx))
463      }
464      w_grantlast := w_grantlast || refill_done
465      hasData := true.B
466    }.otherwise {
467      // Grant
468      assert(full_overwrite)
469      for (i <- 0 until blockRows) {
470        refill_and_store_data(i) := new_data(i)
471      }
472      w_grantlast := true.B
473      hasData := false.B
474    }
475
476    error := io.mem_grant.bits.denied || io.mem_grant.bits.corrupt || error
477
478    refill_data_raw(refill_count) := io.mem_grant.bits.data
479    isDirty := io.mem_grant.bits.echo.lift(DirtyKey).getOrElse(false.B)
480  }
481
482  when (io.mem_finish.fire()) {
483    s_grantack := true.B
484  }
485
486  when (io.replace_pipe_req.fire()) {
487    s_replace_req := true.B
488  }
489
490  when (io.replace_pipe_resp) {
491    w_replace_resp := true.B
492  }
493
494  when (io.refill_pipe_req.fire()) {
495    s_refill := true.B
496  }
497
498  when (io.refill_pipe_resp) {
499    w_refill_resp := true.B
500  }
501
502  when (io.main_pipe_req.fire()) {
503    s_mainpipe_req := true.B
504  }
505
506  when (io.main_pipe_resp) {
507    w_mainpipe_resp := true.B
508  }
509
510  def before_req_sent_can_merge(new_req: MissReqWoStoreData): Bool = {
511    acquire_not_sent && (req.isFromLoad || req.isFromPrefetch) && (new_req.isFromLoad || new_req.isFromStore)
512  }
513
514  def before_data_refill_can_merge(new_req: MissReqWoStoreData): Bool = {
515    data_not_refilled && (req.isFromLoad || req.isFromStore || req.isFromPrefetch) && new_req.isFromLoad
516  }
517
518  // Note that late prefetch will be ignored
519
520  def should_merge(new_req: MissReqWoStoreData): Bool = {
521    val block_match = get_block(req.addr) === get_block(new_req.addr)
522    block_match &&
523    (
524      before_req_sent_can_merge(new_req) ||
525      before_data_refill_can_merge(new_req)
526    )
527  }
528
529  // store can be merged before io.mem_acquire.fire()
530  // store can not be merged the cycle that io.mem_acquire.fire()
531  // load can be merged before io.mem_grant.fire()
532  //
533  // TODO: merge store if possible? mem_acquire may need to be re-issued,
534  // but sbuffer entry can be freed
535  def should_reject(new_req: MissReqWoStoreData): Bool = {
536    val block_match = get_block(req.addr) === get_block(new_req.addr)
537    val set_match = set === addr_to_dcache_set(new_req.vaddr)
538
539    req_valid &&
540      Mux(
541        block_match,
542        !before_req_sent_can_merge(new_req) &&
543          !before_data_refill_can_merge(new_req),
544        set_match && new_req.way_en === req.way_en
545      )
546  }
547
548  // req_valid will be updated 1 cycle after primary_fire, so next cycle, this entry cannot accept a new req
549  io.primary_ready := !req_valid && !RegNext(primary_fire)
550  io.secondary_ready := should_merge(io.req.bits)
551  io.secondary_reject := should_reject(io.req.bits)
552  io.repl_way_en := req.way_en
553
554  // should not allocate, merge or reject at the same time
555  assert(RegNext(PopCount(Seq(io.primary_ready, io.secondary_ready, io.secondary_reject)) <= 1.U))
556
557  val refill_data_splited = WireInit(VecInit(Seq.tabulate(cfg.blockBytes * 8 / l1BusDataWidth)(i => {
558    val data = refill_and_store_data.asUInt
559    data((i + 1) * l1BusDataWidth - 1, i * l1BusDataWidth)
560  })))
561  // when granted data is all ready, wakeup lq's miss load
562  io.refill_to_ldq.valid := RegNext(!w_grantlast && io.mem_grant.fire())
563  io.refill_to_ldq.bits.addr := RegNext(req.addr + (refill_count << refillOffBits))
564  io.refill_to_ldq.bits.data := refill_data_splited(RegNext(refill_count))
565  io.refill_to_ldq.bits.error := RegNext(io.mem_grant.bits.corrupt || io.mem_grant.bits.denied)
566  io.refill_to_ldq.bits.refill_done := RegNext(refill_done && io.mem_grant.fire())
567  io.refill_to_ldq.bits.hasdata := hasData
568  io.refill_to_ldq.bits.data_raw := refill_data_raw.asUInt
569  io.refill_to_ldq.bits.id := io.id
570
571  // if the entry has a pending merge req, wait for it
572  // Note: now, only wait for store, because store may acquire T
573  // TODO: support prefetch
574  io.mem_acquire.valid := !s_acquire && !(io.miss_req_pipe_reg.merge && miss_req_pipe_reg_bits.isFromStore)
575  val grow_param = req.req_coh.onAccess(req.cmd)._2
576  val acquireBlock = edge.AcquireBlock(
577    fromSource = io.id,
578    toAddress = req.addr,
579    lgSize = (log2Up(cfg.blockBytes)).U,
580    growPermissions = grow_param
581  )._2
582  val acquirePerm = edge.AcquirePerm(
583    fromSource = io.id,
584    toAddress = req.addr,
585    lgSize = (log2Up(cfg.blockBytes)).U,
586    growPermissions = grow_param
587  )._2
588  io.mem_acquire.bits := Mux(full_overwrite, acquirePerm, acquireBlock)
589  // resolve cache alias by L2
590  io.mem_acquire.bits.user.lift(AliasKey).foreach( _ := req.vaddr(13, 12))
591  // pass vaddr to l2
592  io.mem_acquire.bits.user.lift(VaddrKey).foreach( _ := req.vaddr(VAddrBits-1, blockOffBits))
593  // trigger prefetch
594  io.mem_acquire.bits.user.lift(PrefetchKey).foreach(_ := Mux(io.l2_pf_store_only, req.isFromStore, true.B))
595  // req source
596  when(prefetch && !secondary_fired) {
597    io.mem_acquire.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.L1DataPrefetch.id.U)
598  }.otherwise {
599    when(req.isFromStore) {
600      io.mem_acquire.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.CPUStoreData.id.U)
601    }.elsewhen(req.isFromLoad) {
602      io.mem_acquire.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.CPULoadData.id.U)
603    }.elsewhen(req.isFromAMO) {
604      io.mem_acquire.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.CPUAtomicData.id.U)
605    }.otherwise {
606      io.mem_acquire.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.L1DataPrefetch.id.U)
607    }
608  }
609  require(nSets <= 256)
610
611  io.mem_grant.ready := !w_grantlast && s_acquire
612
613  val grantack = RegEnable(edge.GrantAck(io.mem_grant.bits), io.mem_grant.fire())
614  assert(RegNext(!io.mem_grant.fire() || edge.isRequest(io.mem_grant.bits)))
615  io.mem_finish.valid := !s_grantack && w_grantfirst
616  io.mem_finish.bits := grantack
617
618  io.replace_pipe_req.valid := !s_replace_req
619  val replace = io.replace_pipe_req.bits
620  replace := DontCare
621  replace.miss := false.B
622  replace.miss_id := io.id
623  replace.miss_dirty := false.B
624  replace.probe := false.B
625  replace.probe_need_data := false.B
626  replace.source := LOAD_SOURCE.U
627  replace.vaddr := req.vaddr // only untag bits are needed
628  replace.addr := Cat(req.replace_tag, 0.U(pgUntagBits.W)) // only tag bits are needed
629  replace.store_mask := 0.U
630  replace.replace := true.B
631  replace.replace_way_en := req.way_en
632  replace.error := false.B
633
634  io.refill_pipe_req.valid := !s_refill && w_replace_resp && w_grantlast
635  val refill = io.refill_pipe_req.bits
636  refill.source := req.source
637  refill.vaddr := req.vaddr
638  refill.addr := req.addr
639  refill.way_en := req.way_en
640  refill.wmask := Mux(
641    hasData || req.isFromLoad,
642    ~0.U(DCacheBanks.W),
643    VecInit((0 until DCacheBanks).map(i => get_mask_of_bank(i, req_store_mask).orR)).asUInt
644  )
645  refill.data := refill_and_store_data.asTypeOf((new RefillPipeReq).data)
646  refill.miss_id := io.id
647  refill.id := req.id
648  def missCohGen(cmd: UInt, param: UInt, dirty: Bool) = {
649    val c = categorize(cmd)
650    MuxLookup(Cat(c, param, dirty), Nothing, Seq(
651      //(effect param) -> (next)
652      Cat(rd, toB, false.B)  -> Branch,
653      Cat(rd, toB, true.B)   -> Branch,
654      Cat(rd, toT, false.B)  -> Trunk,
655      Cat(rd, toT, true.B)   -> Dirty,
656      Cat(wi, toT, false.B)  -> Trunk,
657      Cat(wi, toT, true.B)   -> Dirty,
658      Cat(wr, toT, false.B)  -> Dirty,
659      Cat(wr, toT, true.B)   -> Dirty))
660  }
661  refill.meta.coh := ClientMetadata(missCohGen(req.cmd, grant_param, isDirty))
662  refill.error := error
663  refill.prefetch := prefetch
664  refill.access := access
665  refill.alias := req.vaddr(13, 12) // TODO
666
667  io.main_pipe_req.valid := !s_mainpipe_req && w_grantlast
668  io.main_pipe_req.bits := DontCare
669  io.main_pipe_req.bits.miss := true.B
670  io.main_pipe_req.bits.miss_id := io.id
671  io.main_pipe_req.bits.miss_param := grant_param
672  io.main_pipe_req.bits.miss_dirty := isDirty
673  io.main_pipe_req.bits.miss_way_en := req.way_en
674  io.main_pipe_req.bits.probe := false.B
675  io.main_pipe_req.bits.source := req.source
676  io.main_pipe_req.bits.cmd := req.cmd
677  io.main_pipe_req.bits.vaddr := req.vaddr
678  io.main_pipe_req.bits.addr := req.addr
679  io.main_pipe_req.bits.store_data := refill_and_store_data.asUInt
680  io.main_pipe_req.bits.store_mask := ~0.U(blockBytes.W)
681  io.main_pipe_req.bits.word_idx := req.word_idx
682  io.main_pipe_req.bits.amo_data := req.amo_data
683  io.main_pipe_req.bits.amo_mask := req.amo_mask
684  io.main_pipe_req.bits.error := error
685  io.main_pipe_req.bits.id := req.id
686
687  io.block_addr.valid := req_valid && w_grantlast && !w_refill_resp
688  io.block_addr.bits := req.addr
689
690  io.debug_early_replace.valid := BoolStopWatch(io.replace_pipe_resp, io.refill_pipe_req.fire())
691  io.debug_early_replace.bits.idx := addr_to_dcache_set(req.vaddr)
692  io.debug_early_replace.bits.tag := req.replace_tag
693
694  io.forwardInfo.apply(req_valid, req.addr, refill_and_store_data, w_grantfirst, w_grantlast)
695
696  // refill latency monitor
697  io.latency_monitor.load_miss_refilling  := req_valid && req_primary_fire.isFromLoad     && BoolStopWatch(io.mem_acquire.fire, io.mem_grant.fire && !refill_done, true)
698  io.latency_monitor.store_miss_refilling := req_valid && req_primary_fire.isFromStore    && BoolStopWatch(io.mem_acquire.fire, io.mem_grant.fire && !refill_done, true)
699  io.latency_monitor.amo_miss_refilling   := req_valid && req_primary_fire.isFromAMO      && BoolStopWatch(io.mem_acquire.fire, io.mem_grant.fire && !refill_done, true)
700  io.latency_monitor.pf_miss_refilling    := req_valid && req_primary_fire.isFromPrefetch && BoolStopWatch(io.mem_acquire.fire, io.mem_grant.fire && !refill_done, true)
701
702  XSPerfAccumulate("miss_req_primary", primary_fire)
703  XSPerfAccumulate("miss_req_merged", secondary_fire)
704  XSPerfAccumulate("load_miss_penalty_to_use",
705    should_refill_data &&
706      BoolStopWatch(primary_fire, io.refill_to_ldq.valid, true)
707  )
708  XSPerfAccumulate("main_pipe_penalty", BoolStopWatch(io.main_pipe_req.fire(), io.main_pipe_resp))
709  XSPerfAccumulate("penalty_blocked_by_channel_A", io.mem_acquire.valid && !io.mem_acquire.ready)
710  XSPerfAccumulate("penalty_waiting_for_channel_D", s_acquire && !w_grantlast && !io.mem_grant.valid)
711  XSPerfAccumulate("penalty_waiting_for_channel_E", io.mem_finish.valid && !io.mem_finish.ready)
712  XSPerfAccumulate("penalty_from_grant_to_refill", !w_refill_resp && w_grantlast)
713  XSPerfAccumulate("prefetch_req_primary", primary_fire && io.req.bits.source === DCACHE_PREFETCH_SOURCE.U)
714  XSPerfAccumulate("prefetch_req_merged", secondary_fire && io.req.bits.source === DCACHE_PREFETCH_SOURCE.U)
715
716  val (mshr_penalty_sample, mshr_penalty) = TransactionLatencyCounter(RegNext(RegNext(primary_fire)), release_entry)
717  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 0, 20, 1, true, true)
718  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 20, 100, 10, true, false)
719
720  val load_miss_begin = primary_fire && io.req.bits.isFromLoad
721  val refill_finished = RegNext(!w_grantlast && refill_done) && should_refill_data
722  val (load_miss_penalty_sample, load_miss_penalty) = TransactionLatencyCounter(load_miss_begin, refill_finished) // not real refill finish time
723  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 0, 20, 1, true, true)
724  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 20, 100, 10, true, false)
725
726  val (a_to_d_penalty_sample, a_to_d_penalty) = TransactionLatencyCounter(io.mem_acquire.fire(), io.mem_grant.fire() && refill_done)
727  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 0, 20, 1, true, true)
728  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 20, 100, 10, true, false)
729}
730
731class MissQueue(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule with HasPerfEvents {
732  val io = IO(new Bundle {
733    val hartId = Input(UInt(8.W))
734    val req = Flipped(DecoupledIO(new MissReq))
735    val resp = Output(new MissResp)
736    val refill_to_ldq = ValidIO(new Refill)
737
738    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
739    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
740    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
741
742    val refill_pipe_req = DecoupledIO(new RefillPipeReq)
743    val refill_pipe_req_dup = Vec(nDupStatus, DecoupledIO(new RefillPipeReqCtrl))
744    val refill_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
745
746    val replace_pipe_req = DecoupledIO(new MainPipeReq)
747    val replace_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
748
749    val main_pipe_req = DecoupledIO(new MainPipeReq)
750    val main_pipe_resp = Flipped(ValidIO(new AtomicsResp))
751
752    // block probe
753    val probe_addr = Input(UInt(PAddrBits.W))
754    val probe_block = Output(Bool())
755
756    val full = Output(Bool())
757
758    // only for performance counter
759    // This is valid when an mshr has finished replacing a block (w_replace_resp),
760    // but hasn't received Grant from L2 (!w_grantlast)
761    val debug_early_replace = Vec(cfg.nMissEntries, ValidIO(new Bundle() {
762      // info about the block that has been replaced
763      val idx = UInt(idxBits.W) // vaddr
764      val tag = UInt(tagBits.W) // paddr
765    }))
766
767    // forward missqueue
768    val forward = Vec(LoadPipelineWidth, new LduToMissqueueForwardIO)
769    val l2_pf_store_only = Input(Bool())
770
771    val mq_enq_cancel = Output(Bool())
772  })
773
774  // 128KBL1: FIXME: provide vaddr for l2
775
776  val entries = Seq.fill(cfg.nMissEntries)(Module(new MissEntry(edge)))
777
778  val miss_req_pipe_reg = RegInit(0.U.asTypeOf(new MissReqPipeRegBundle(edge)))
779  val acquire_from_pipereg = Wire(chiselTypeOf(io.mem_acquire))
780
781  val primary_ready_vec = entries.map(_.io.primary_ready)
782  val secondary_ready_vec = entries.map(_.io.secondary_ready)
783  val secondary_reject_vec = entries.map(_.io.secondary_reject)
784  val probe_block_vec = entries.map { case e => e.io.block_addr.valid && e.io.block_addr.bits === io.probe_addr }
785
786  val merge = Cat(secondary_ready_vec ++ Seq(miss_req_pipe_reg.merge_req(io.req.bits))).orR
787  val reject = Cat(secondary_reject_vec ++ Seq(miss_req_pipe_reg.reject_req(io.req.bits))).orR
788  val alloc = !reject && !merge && Cat(primary_ready_vec).orR
789  val accept = alloc || merge
790
791  val req_mshr_handled_vec = entries.map(_.io.req_handled_by_this_entry)
792  // merged to pipeline reg
793  val req_pipeline_reg_handled = miss_req_pipe_reg.merge_req(io.req.bits)
794  assert(PopCount(Seq(req_pipeline_reg_handled, VecInit(req_mshr_handled_vec).asUInt.orR)) <= 1.U, "miss req will either go to mshr or pipeline reg")
795  assert(PopCount(req_mshr_handled_vec) <= 1.U, "Only one mshr can handle a req")
796  io.resp.id := Mux(!req_pipeline_reg_handled, OHToUInt(req_mshr_handled_vec), miss_req_pipe_reg.mshr_id)
797  io.resp.handled := Cat(req_mshr_handled_vec).orR || req_pipeline_reg_handled
798  io.resp.merged := merge
799  io.resp.repl_way_en := Mux(!req_pipeline_reg_handled, Mux1H(secondary_ready_vec, entries.map(_.io.repl_way_en)), miss_req_pipe_reg.req.way_en)
800
801  /*  MissQueue enq logic is now splitted into 2 cycles
802   *
803   */
804  miss_req_pipe_reg.req     := io.req.bits
805  miss_req_pipe_reg.alloc   := alloc && io.req.valid && !io.req.bits.cancel
806  miss_req_pipe_reg.merge   := merge && io.req.valid && !io.req.bits.cancel
807  miss_req_pipe_reg.mshr_id := io.resp.id
808
809  assert(PopCount(Seq(alloc && io.req.valid, merge && io.req.valid)) <= 1.U, "allocate and merge a mshr in same cycle!")
810
811  val forwardInfo_vec = VecInit(entries.map(_.io.forwardInfo))
812  (0 until LoadPipelineWidth).map(i => {
813    val id = io.forward(i).mshrid
814    val req_valid = io.forward(i).valid
815    val paddr = io.forward(i).paddr
816
817    val (forward_mshr, forwardData) = forwardInfo_vec(id).forward(req_valid, paddr)
818    io.forward(i).forward_result_valid := forwardInfo_vec(id).check(req_valid, paddr)
819    io.forward(i).forward_mshr := forward_mshr
820    io.forward(i).forwardData := forwardData
821  })
822
823  assert(RegNext(PopCount(secondary_ready_vec) <= 1.U))
824//  assert(RegNext(PopCount(secondary_reject_vec) <= 1.U))
825  // It is possible that one mshr wants to merge a req, while another mshr wants to reject it.
826  // That is, a coming req has the same paddr as that of mshr_0 (merge),
827  // while it has the same set and the same way as mshr_1 (reject).
828  // In this situation, the coming req should be merged by mshr_0
829//  assert(RegNext(PopCount(Seq(merge, reject)) <= 1.U))
830
831  def select_valid_one[T <: Bundle](
832    in: Seq[DecoupledIO[T]],
833    out: DecoupledIO[T],
834    name: Option[String] = None): Unit = {
835
836    if (name.nonEmpty) { out.suggestName(s"${name.get}_select") }
837    out.valid := Cat(in.map(_.valid)).orR
838    out.bits := ParallelMux(in.map(_.valid) zip in.map(_.bits))
839    in.map(_.ready := out.ready)
840    assert(!RegNext(out.valid && PopCount(Cat(in.map(_.valid))) > 1.U))
841  }
842
843  io.mem_grant.ready := false.B
844
845  entries.zipWithIndex.foreach {
846    case (e, i) =>
847      val former_primary_ready = if(i == 0)
848        false.B
849      else
850        Cat((0 until i).map(j => entries(j).io.primary_ready)).orR
851
852      e.io.hartId := io.hartId
853      e.io.id := i.U
854      e.io.l2_pf_store_only := io.l2_pf_store_only
855      e.io.req.valid := io.req.valid
856      e.io.primary_valid := io.req.valid &&
857        !merge &&
858        !reject &&
859        !former_primary_ready &&
860        e.io.primary_ready
861      e.io.req.bits := io.req.bits.toMissReqWoStoreData()
862
863      e.io.mem_grant.valid := false.B
864      e.io.mem_grant.bits := DontCare
865      when (io.mem_grant.bits.source === i.U) {
866        e.io.mem_grant <> io.mem_grant
867      }
868
869      when(miss_req_pipe_reg.reg_valid() && miss_req_pipe_reg.mshr_id === i.U) {
870        e.io.miss_req_pipe_reg := miss_req_pipe_reg
871      }.otherwise {
872        e.io.miss_req_pipe_reg       := DontCare
873        e.io.miss_req_pipe_reg.merge := false.B
874        e.io.miss_req_pipe_reg.alloc := false.B
875      }
876
877      e.io.acquire_fired_by_pipe_reg := acquire_from_pipereg.fire
878
879      e.io.refill_pipe_resp := io.refill_pipe_resp.valid && io.refill_pipe_resp.bits === i.U
880      e.io.replace_pipe_resp := io.replace_pipe_resp.valid && io.replace_pipe_resp.bits === i.U
881      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
882
883      io.debug_early_replace(i) := e.io.debug_early_replace
884      e.io.main_pipe_req.ready := io.main_pipe_req.ready
885  }
886
887  io.req.ready := accept
888  io.mq_enq_cancel := io.req.bits.cancel
889  io.refill_to_ldq.valid := Cat(entries.map(_.io.refill_to_ldq.valid)).orR
890  io.refill_to_ldq.bits := ParallelMux(entries.map(_.io.refill_to_ldq.valid) zip entries.map(_.io.refill_to_ldq.bits))
891
892  acquire_from_pipereg.valid := miss_req_pipe_reg.can_send_acquire(io.req.valid, io.req.bits)
893  acquire_from_pipereg.bits := miss_req_pipe_reg.get_acquire(io.l2_pf_store_only)
894
895  XSPerfAccumulate("acquire_fire_from_pipereg", acquire_from_pipereg.fire)
896  XSPerfAccumulate("pipereg_valid", miss_req_pipe_reg.reg_valid())
897
898  val acquire_sources = Seq(acquire_from_pipereg) ++ entries.map(_.io.mem_acquire)
899  TLArbiter.lowest(edge, io.mem_acquire, acquire_sources:_*)
900  TLArbiter.lowest(edge, io.mem_finish, entries.map(_.io.mem_finish):_*)
901
902  // arbiter_with_pipereg_N_dup(entries.map(_.io.refill_pipe_req), io.refill_pipe_req,
903  // io.refill_pipe_req_dup,
904  // Some("refill_pipe_req"))
905  val out_refill_pipe_req = Wire(Decoupled(new RefillPipeReq))
906  val out_refill_pipe_req_ctrl = Wire(Decoupled(new RefillPipeReqCtrl))
907  out_refill_pipe_req_ctrl.valid := out_refill_pipe_req.valid
908  out_refill_pipe_req_ctrl.bits := out_refill_pipe_req.bits.getCtrl
909  out_refill_pipe_req.ready := out_refill_pipe_req_ctrl.ready
910  arbiter(entries.map(_.io.refill_pipe_req), out_refill_pipe_req, Some("refill_pipe_req"))
911  for (dup <- io.refill_pipe_req_dup) {
912    AddPipelineReg(out_refill_pipe_req_ctrl, dup, false.B)
913  }
914  AddPipelineReg(out_refill_pipe_req, io.refill_pipe_req, false.B)
915
916  arbiter_with_pipereg(entries.map(_.io.replace_pipe_req), io.replace_pipe_req, Some("replace_pipe_req"))
917
918  // amo's main pipe req out
919  val main_pipe_req_vec = entries.map(_.io.main_pipe_req)
920  io.main_pipe_req.valid := VecInit(main_pipe_req_vec.map(_.valid)).asUInt.orR
921  io.main_pipe_req.bits := Mux1H(main_pipe_req_vec.map(_.valid), main_pipe_req_vec.map(_.bits))
922  assert(PopCount(VecInit(main_pipe_req_vec.map(_.valid))) <= 1.U, "multi main pipe req")
923
924  io.probe_block := Cat(probe_block_vec).orR
925
926  io.full := ~Cat(entries.map(_.io.primary_ready)).andR
927
928  // L1MissTrace Chisel DB
929  val debug_miss_trace = Wire(new L1MissTrace)
930  debug_miss_trace.vaddr := io.req.bits.vaddr
931  debug_miss_trace.paddr := io.req.bits.addr
932  debug_miss_trace.source := io.req.bits.source
933  debug_miss_trace.pc := io.req.bits.pc
934
935  val isWriteL1MissQMissTable = WireInit(Constantin.createRecord("isWriteL1MissQMissTable" + p(XSCoreParamsKey).HartId.toString))
936  val table = ChiselDB.createTable("L1MissQMissTrace_hart"+ p(XSCoreParamsKey).HartId.toString, new L1MissTrace)
937  table.log(debug_miss_trace, isWriteL1MissQMissTable.orR && io.req.valid && !io.req.bits.cancel && alloc, "MissQueue", clock, reset)
938
939  // Difftest
940  if (env.EnableDifftest) {
941    val difftest = Module(new DifftestRefillEvent)
942    difftest.io.clock := clock
943    difftest.io.coreid := io.hartId
944    difftest.io.cacheid := 1.U
945    difftest.io.valid := io.refill_to_ldq.valid && io.refill_to_ldq.bits.hasdata && io.refill_to_ldq.bits.refill_done
946    difftest.io.addr := io.refill_to_ldq.bits.addr
947    difftest.io.data := io.refill_to_ldq.bits.data_raw.asTypeOf(difftest.io.data)
948  }
949
950  // Perf count
951  XSPerfAccumulate("miss_req", io.req.fire() && !io.req.bits.cancel)
952  XSPerfAccumulate("miss_req_allocate", io.req.fire() && !io.req.bits.cancel && alloc)
953  XSPerfAccumulate("miss_req_load_allocate", io.req.fire() && !io.req.bits.cancel && alloc && io.req.bits.isFromLoad)
954  XSPerfAccumulate("miss_req_store_allocate", io.req.fire() && !io.req.bits.cancel && alloc && io.req.bits.isFromStore)
955  XSPerfAccumulate("miss_req_amo_allocate", io.req.fire() && !io.req.bits.cancel && alloc && io.req.bits.isFromAMO)
956  XSPerfAccumulate("miss_req_merge_load", io.req.fire() && !io.req.bits.cancel && merge && io.req.bits.isFromLoad)
957  XSPerfAccumulate("miss_req_reject_load", io.req.valid && !io.req.bits.cancel && reject && io.req.bits.isFromLoad)
958  XSPerfAccumulate("probe_blocked_by_miss", io.probe_block)
959  XSPerfAccumulate("prefetch_primary_fire", io.req.fire() && !io.req.bits.cancel && alloc && io.req.bits.isFromPrefetch)
960  XSPerfAccumulate("prefetch_secondary_fire", io.req.fire() && !io.req.bits.cancel && merge && io.req.bits.isFromPrefetch)
961  val max_inflight = RegInit(0.U((log2Up(cfg.nMissEntries) + 1).W))
962  val num_valids = PopCount(~Cat(primary_ready_vec).asUInt)
963  when (num_valids > max_inflight) {
964    max_inflight := num_valids
965  }
966  // max inflight (average) = max_inflight_total / cycle cnt
967  XSPerfAccumulate("max_inflight", max_inflight)
968  QueuePerf(cfg.nMissEntries, num_valids, num_valids === cfg.nMissEntries.U)
969  io.full := num_valids === cfg.nMissEntries.U
970  XSPerfHistogram("num_valids", num_valids, true.B, 0, cfg.nMissEntries, 1)
971
972  XSPerfHistogram("L1DMLP_CPUData", PopCount(VecInit(entries.map(_.io.perf_pending_normal)).asUInt), true.B, 0, cfg.nMissEntries, 1)
973  XSPerfHistogram("L1DMLP_Prefetch", PopCount(VecInit(entries.map(_.io.perf_pending_prefetch)).asUInt), true.B, 0, cfg.nMissEntries, 1)
974  XSPerfHistogram("L1DMLP_Total", num_valids, true.B, 0, cfg.nMissEntries, 1)
975
976  XSPerfAccumulate("miss_load_refill_latency", PopCount(entries.map(_.io.latency_monitor.load_miss_refilling)))
977  XSPerfAccumulate("miss_store_refill_latency", PopCount(entries.map(_.io.latency_monitor.store_miss_refilling)))
978  XSPerfAccumulate("miss_amo_refill_latency", PopCount(entries.map(_.io.latency_monitor.amo_miss_refilling)))
979  XSPerfAccumulate("miss_pf_refill_latency", PopCount(entries.map(_.io.latency_monitor.pf_miss_refilling)))
980
981  val rob_head_miss_in_dcache = VecInit(entries.map(_.io.rob_head_query.resp)).asUInt.orR
982  val sourceVaddr = WireInit(0.U.asTypeOf(new Valid(UInt(VAddrBits.W))))
983  val lq_doing_other_replay = WireInit(false.B)
984
985  ExcitingUtils.addSink(sourceVaddr, s"rob_head_vaddr_${coreParams.HartId}", ExcitingUtils.Perf)
986  ExcitingUtils.addSink(lq_doing_other_replay, s"rob_head_other_replay_${coreParams.HartId}", ExcitingUtils.Perf)
987
988  entries.foreach {
989    case e => {
990      e.io.rob_head_query.query_valid := sourceVaddr.valid
991      e.io.rob_head_query.vaddr := sourceVaddr.bits
992    }
993  }
994
995  // ExcitingUtils.addSource(!rob_head_miss_in_dcache && !lq_doing_other_replay, s"load_l1_cache_stall_without_bank_conflict_${coreParams.HartId}", ExcitingUtils.Perf, true)
996  ExcitingUtils.addSource(rob_head_miss_in_dcache, s"load_l1_miss_${coreParams.HartId}", ExcitingUtils.Perf, true)
997
998  val perfValidCount = RegNext(PopCount(entries.map(entry => (!entry.io.primary_ready))))
999  val perfEvents = Seq(
1000    ("dcache_missq_req      ", io.req.fire()),
1001    ("dcache_missq_1_4_valid", (perfValidCount < (cfg.nMissEntries.U/4.U))),
1002    ("dcache_missq_2_4_valid", (perfValidCount > (cfg.nMissEntries.U/4.U)) & (perfValidCount <= (cfg.nMissEntries.U/2.U))),
1003    ("dcache_missq_3_4_valid", (perfValidCount > (cfg.nMissEntries.U/2.U)) & (perfValidCount <= (cfg.nMissEntries.U*3.U/4.U))),
1004    ("dcache_missq_4_4_valid", (perfValidCount > (cfg.nMissEntries.U*3.U/4.U))),
1005  )
1006  generatePerfEvent()
1007}
1008