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