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