xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/mainpipe/MissQueue.scala (revision 1b0de924894d56bdd76d8dabd395d204a6d0af67)
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(RegNext(io.id >= ((cfg.nMissEntries).U - io.nMaxPrefetchEntry))) {
641    // can accept prefetch req
642    io.primary_ready := !req_valid && !RegNext(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) && !RegNext(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  io.refill_to_ldq.valid := RegNext(!w_grantlast && io.mem_grant.fire)
659  io.refill_to_ldq.bits.addr := RegNext(req.addr + ((refill_count ^ isKeyword) << refillOffBits))
660  io.refill_to_ldq.bits.data := refill_data_splited(RegNext(refill_count ^ isKeyword))
661  io.refill_to_ldq.bits.error := RegNext(io.mem_grant.bits.corrupt || io.mem_grant.bits.denied)
662  io.refill_to_ldq.bits.refill_done := RegNext(refill_done && io.mem_grant.fire)
663  io.refill_to_ldq.bits.hasdata := hasData
664  io.refill_to_ldq.bits.data_raw := refill_data_raw.asUInt
665  io.refill_to_ldq.bits.id := io.id
666
667  // if the entry has a pending merge req, wait for it
668  // Note: now, only wait for store, because store may acquire T
669  io.mem_acquire.valid := !s_acquire && !(io.miss_req_pipe_reg.merge && miss_req_pipe_reg_bits.isFromStore)
670  val grow_param = req.req_coh.onAccess(req.cmd)._2
671  val acquireBlock = edge.AcquireBlock(
672    fromSource = io.id,
673    toAddress = req.addr,
674    lgSize = (log2Up(cfg.blockBytes)).U,
675    growPermissions = grow_param
676  )._2
677  val acquirePerm = edge.AcquirePerm(
678    fromSource = io.id,
679    toAddress = req.addr,
680    lgSize = (log2Up(cfg.blockBytes)).U,
681    growPermissions = grow_param
682  )._2
683  io.mem_acquire.bits := Mux(full_overwrite, acquirePerm, acquireBlock)
684  // resolve cache alias by L2
685  io.mem_acquire.bits.user.lift(AliasKey).foreach( _ := req.vaddr(13, 12))
686  // pass vaddr to l2
687  io.mem_acquire.bits.user.lift(VaddrKey).foreach( _ := req.vaddr(VAddrBits-1, blockOffBits))
688  // pass keyword to L2
689  io.mem_acquire.bits.echo.lift(IsKeywordKey).foreach(_ := isKeyword)
690  // trigger prefetch
691  io.mem_acquire.bits.user.lift(PrefetchKey).foreach(_ := Mux(io.l2_pf_store_only, req.isFromStore, true.B))
692  // req source
693  when(prefetch && !secondary_fired) {
694    io.mem_acquire.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.L1DataPrefetch.id.U)
695  }.otherwise {
696    when(req.isFromStore) {
697      io.mem_acquire.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.CPUStoreData.id.U)
698    }.elsewhen(req.isFromLoad) {
699      io.mem_acquire.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.CPULoadData.id.U)
700    }.elsewhen(req.isFromAMO) {
701      io.mem_acquire.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.CPUAtomicData.id.U)
702    }.otherwise {
703      io.mem_acquire.bits.user.lift(ReqSourceKey).foreach(_ := MemReqSource.L1DataPrefetch.id.U)
704    }
705  }
706  require(nSets <= 256)
707
708  // io.mem_grant.ready := !w_grantlast && s_acquire
709  io.mem_grant.ready := true.B
710  assert(!(io.mem_grant.valid && !(!w_grantlast && s_acquire)), "dcache should always be ready for mem_grant now")
711
712  val grantack = RegEnable(edge.GrantAck(io.mem_grant.bits), io.mem_grant.fire)
713  assert(RegNext(!io.mem_grant.fire || edge.isRequest(io.mem_grant.bits)))
714  io.mem_finish.valid := !s_grantack && w_grantfirst
715  io.mem_finish.bits := grantack
716
717  // Send mainpipe_req when receive hint from L2 or receive data without hint
718  io.main_pipe_req.valid := !s_mainpipe_req && (w_l2hint || w_grantlast)
719  io.main_pipe_req.bits := DontCare
720  io.main_pipe_req.bits.miss := true.B
721  io.main_pipe_req.bits.miss_id := io.id
722  io.main_pipe_req.bits.probe := false.B
723  io.main_pipe_req.bits.source := req.source
724  io.main_pipe_req.bits.cmd := req.cmd
725  io.main_pipe_req.bits.vaddr := req.vaddr
726  io.main_pipe_req.bits.addr := req.addr
727  io.main_pipe_req.bits.word_idx := req.word_idx
728  io.main_pipe_req.bits.amo_data := req.amo_data
729  io.main_pipe_req.bits.amo_mask := req.amo_mask
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  io.refill_info.bits.error      := error
743
744  XSPerfAccumulate("miss_refill_mainpipe_req", io.main_pipe_req.fire)
745  XSPerfAccumulate("miss_refill_without_hint", io.main_pipe_req.fire && !mainpipe_req_fired && !w_l2hint)
746  XSPerfAccumulate("miss_refill_replay", io.main_pipe_replay)
747
748  val w_grantfirst_forward_info = Mux(isKeyword, w_grantlast, w_grantfirst)
749  val w_grantlast_forward_info = Mux(isKeyword, w_grantfirst, w_grantlast)
750  io.forwardInfo.apply(req_valid, req.addr, refill_and_store_data, w_grantfirst_forward_info, w_grantlast_forward_info)
751
752  io.matched := req_valid && (get_block(req.addr) === get_block(io.req.bits.addr)) && !prefetch
753  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
754
755  when(io.prefetch_info.late_prefetch) {
756    prefetch := false.B
757  }
758
759  // refill latency monitor
760  val start_counting = RegNext(io.mem_acquire.fire) || (RegNextN(primary_fire, 2) && s_acquire)
761  io.latency_monitor.load_miss_refilling  := req_valid && req_primary_fire.isFromLoad     && BoolStopWatch(start_counting, io.mem_grant.fire && !refill_done, true, true)
762  io.latency_monitor.store_miss_refilling := req_valid && req_primary_fire.isFromStore    && BoolStopWatch(start_counting, io.mem_grant.fire && !refill_done, true, true)
763  io.latency_monitor.amo_miss_refilling   := req_valid && req_primary_fire.isFromAMO      && BoolStopWatch(start_counting, io.mem_grant.fire && !refill_done, true, true)
764  io.latency_monitor.pf_miss_refilling    := req_valid && req_primary_fire.isFromPrefetch && BoolStopWatch(start_counting, io.mem_grant.fire && !refill_done, true, true)
765
766  XSPerfAccumulate("miss_req_primary", primary_fire)
767  XSPerfAccumulate("miss_req_merged", secondary_fire)
768  XSPerfAccumulate("load_miss_penalty_to_use",
769    should_refill_data &&
770      BoolStopWatch(primary_fire, io.refill_to_ldq.valid, true)
771  )
772  XSPerfAccumulate("penalty_between_grantlast_and_release",
773    BoolStopWatch(!RegNext(w_grantlast) && w_grantlast, release_entry, true)
774  )
775  XSPerfAccumulate("main_pipe_penalty", BoolStopWatch(io.main_pipe_req.fire, io.main_pipe_resp))
776  XSPerfAccumulate("penalty_blocked_by_channel_A", io.mem_acquire.valid && !io.mem_acquire.ready)
777  XSPerfAccumulate("penalty_waiting_for_channel_D", s_acquire && !w_grantlast && !io.mem_grant.valid)
778  XSPerfAccumulate("penalty_waiting_for_channel_E", io.mem_finish.valid && !io.mem_finish.ready)
779  XSPerfAccumulate("prefetch_req_primary", primary_fire && io.req.bits.source === DCACHE_PREFETCH_SOURCE.U)
780  XSPerfAccumulate("prefetch_req_merged", secondary_fire && io.req.bits.source === DCACHE_PREFETCH_SOURCE.U)
781  XSPerfAccumulate("can_not_send_acquire_because_of_merging_store", !s_acquire && io.miss_req_pipe_reg.merge && miss_req_pipe_reg_bits.isFromStore)
782
783  val (mshr_penalty_sample, mshr_penalty) = TransactionLatencyCounter(RegNext(RegNext(primary_fire)), release_entry)
784  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 0, 20, 1, true, true)
785  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 20, 100, 10, true, false)
786
787  val load_miss_begin = primary_fire && io.req.bits.isFromLoad
788  val refill_finished = RegNext(!w_grantlast && refill_done) && should_refill_data
789  val (load_miss_penalty_sample, load_miss_penalty) = TransactionLatencyCounter(load_miss_begin, refill_finished) // not real refill finish time
790  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 0, 20, 1, true, true)
791  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 20, 100, 10, true, false)
792
793  val (a_to_d_penalty_sample, a_to_d_penalty) = TransactionLatencyCounter(start_counting, RegNext(io.mem_grant.fire && refill_done))
794  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 0, 20, 1, true, true)
795  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 20, 100, 10, true, false)
796}
797
798class MissQueue(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule
799  with HasPerfEvents
800  {
801  val io = IO(new Bundle {
802    val hartId = Input(UInt(hartIdLen.W))
803    val req = Flipped(DecoupledIO(new MissReq))
804    val resp = Output(new MissResp)
805    val refill_to_ldq = ValidIO(new Refill)
806
807    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
808    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
809    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
810
811    val l2_hint = Input(Valid(new L2ToL1Hint())) // Hint from L2 Cache
812
813    val main_pipe_req = DecoupledIO(new MainPipeReq)
814    val main_pipe_resp = Flipped(ValidIO(new MainPipeResp))
815
816    val mainpipe_info = Input(new MainPipeInfoToMQ)
817    val refill_info = ValidIO(new MissQueueRefillInfo)
818
819    // block probe
820    val probe_addr = Input(UInt(PAddrBits.W))
821    val probe_block = Output(Bool())
822
823    val full = Output(Bool())
824
825    // forward missqueue
826    val forward = Vec(LoadPipelineWidth, new LduToMissqueueForwardIO)
827    val l2_pf_store_only = Input(Bool())
828
829    val memSetPattenDetected = Output(Bool())
830    val lqEmpty = Input(Bool())
831
832    val prefetch_info = new Bundle {
833      val naive = new Bundle {
834        val late_miss_prefetch = Output(Bool())
835      }
836
837      val fdp = new Bundle {
838        val late_miss_prefetch = Output(Bool())
839        val prefetch_monitor_cnt = Output(Bool())
840        val total_prefetch = Output(Bool())
841      }
842    }
843
844    val mq_enq_cancel = Output(Bool())
845
846    val debugTopDown = new DCacheTopDownIO
847  })
848
849  // 128KBL1: FIXME: provide vaddr for l2
850
851  val entries = Seq.fill(cfg.nMissEntries)(Module(new MissEntry(edge)))
852
853  val miss_req_pipe_reg = RegInit(0.U.asTypeOf(new MissReqPipeRegBundle(edge)))
854  val acquire_from_pipereg = Wire(chiselTypeOf(io.mem_acquire))
855
856  val primary_ready_vec = entries.map(_.io.primary_ready)
857  val secondary_ready_vec = entries.map(_.io.secondary_ready)
858  val secondary_reject_vec = entries.map(_.io.secondary_reject)
859  val probe_block_vec = entries.map { case e => e.io.block_addr.valid && e.io.block_addr.bits === io.probe_addr }
860
861  val merge = ParallelORR(Cat(secondary_ready_vec ++ Seq(miss_req_pipe_reg.merge_req(io.req.bits))))
862  val reject = ParallelORR(Cat(secondary_reject_vec ++ Seq(miss_req_pipe_reg.reject_req(io.req.bits))))
863  val alloc = !reject && !merge && ParallelORR(Cat(primary_ready_vec))
864  val accept = alloc || merge
865
866  val req_mshr_handled_vec = entries.map(_.io.req_handled_by_this_entry)
867  // merged to pipeline reg
868  val req_pipeline_reg_handled = miss_req_pipe_reg.merge_req(io.req.bits) && io.req.valid
869  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")
870  assert(PopCount(req_mshr_handled_vec) <= 1.U, "Only one mshr can handle a req")
871  io.resp.id := Mux(!req_pipeline_reg_handled, OHToUInt(req_mshr_handled_vec), miss_req_pipe_reg.mshr_id)
872  io.resp.handled := Cat(req_mshr_handled_vec).orR || req_pipeline_reg_handled
873  io.resp.merged := merge
874
875  /*  MissQueue enq logic is now splitted into 2 cycles
876   *
877   */
878  miss_req_pipe_reg.req     := io.req.bits
879  miss_req_pipe_reg.alloc   := alloc && io.req.valid && !io.req.bits.cancel
880  miss_req_pipe_reg.merge   := merge && io.req.valid && !io.req.bits.cancel
881  miss_req_pipe_reg.mshr_id := io.resp.id
882
883  assert(PopCount(Seq(alloc && io.req.valid, merge && io.req.valid)) <= 1.U, "allocate and merge a mshr in same cycle!")
884
885  val source_except_load_cnt = RegInit(0.U(10.W))
886  when(VecInit(req_mshr_handled_vec).asUInt.orR || req_pipeline_reg_handled) {
887    when(io.req.bits.isFromLoad) {
888      source_except_load_cnt := 0.U
889    }.otherwise {
890      when(io.req.bits.isFromStore) {
891        source_except_load_cnt := source_except_load_cnt + 1.U
892      }
893    }
894  }
895  val Threshold = 8
896  val memSetPattenDetected = RegNext((source_except_load_cnt >= Threshold.U) && io.lqEmpty)
897
898  io.memSetPattenDetected := memSetPattenDetected
899
900  val forwardInfo_vec = VecInit(entries.map(_.io.forwardInfo))
901  (0 until LoadPipelineWidth).map(i => {
902    val id = io.forward(i).mshrid
903    val req_valid = io.forward(i).valid
904    val paddr = io.forward(i).paddr
905
906    val (forward_mshr, forwardData) = forwardInfo_vec(id).forward(req_valid, paddr)
907    io.forward(i).forward_result_valid := forwardInfo_vec(id).check(req_valid, paddr)
908    io.forward(i).forward_mshr := forward_mshr
909    io.forward(i).forwardData := forwardData
910  })
911
912  assert(RegNext(PopCount(secondary_ready_vec) <= 1.U || !io.req.valid))
913//  assert(RegNext(PopCount(secondary_reject_vec) <= 1.U))
914  // It is possible that one mshr wants to merge a req, while another mshr wants to reject it.
915  // That is, a coming req has the same paddr as that of mshr_0 (merge),
916  // while it has the same set and the same way as mshr_1 (reject).
917  // In this situation, the coming req should be merged by mshr_0
918//  assert(RegNext(PopCount(Seq(merge, reject)) <= 1.U))
919
920  def select_valid_one[T <: Bundle](
921    in: Seq[DecoupledIO[T]],
922    out: DecoupledIO[T],
923    name: Option[String] = None): Unit = {
924
925    if (name.nonEmpty) { out.suggestName(s"${name.get}_select") }
926    out.valid := Cat(in.map(_.valid)).orR
927    out.bits := ParallelMux(in.map(_.valid) zip in.map(_.bits))
928    in.map(_.ready := out.ready)
929    assert(!RegNext(out.valid && PopCount(Cat(in.map(_.valid))) > 1.U))
930  }
931
932  io.mem_grant.ready := false.B
933
934  val nMaxPrefetchEntry = Constantin.createRecord(s"nMaxPrefetchEntry${p(XSCoreParamsKey).HartId}", initValue = 14)
935  entries.zipWithIndex.foreach {
936    case (e, i) =>
937      val former_primary_ready = if(i == 0)
938        false.B
939      else
940        Cat((0 until i).map(j => entries(j).io.primary_ready)).orR
941
942      e.io.hartId := io.hartId
943      e.io.id := i.U
944      e.io.l2_pf_store_only := io.l2_pf_store_only
945      e.io.req.valid := io.req.valid
946      e.io.primary_valid := io.req.valid &&
947        !merge &&
948        !reject &&
949        !former_primary_ready &&
950        e.io.primary_ready
951      e.io.req.bits := io.req.bits.toMissReqWoStoreData()
952
953      e.io.mem_grant.valid := false.B
954      e.io.mem_grant.bits := DontCare
955      when (io.mem_grant.bits.source === i.U) {
956        e.io.mem_grant <> io.mem_grant
957      }
958
959      when(miss_req_pipe_reg.reg_valid() && miss_req_pipe_reg.mshr_id === i.U) {
960        e.io.miss_req_pipe_reg := miss_req_pipe_reg
961      }.otherwise {
962        e.io.miss_req_pipe_reg       := DontCare
963        e.io.miss_req_pipe_reg.merge := false.B
964        e.io.miss_req_pipe_reg.alloc := false.B
965      }
966
967      e.io.acquire_fired_by_pipe_reg := acquire_from_pipereg.fire
968
969      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
970      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
971      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
972
973      e.io.memSetPattenDetected := memSetPattenDetected
974      e.io.nMaxPrefetchEntry := nMaxPrefetchEntry
975
976      e.io.main_pipe_req.ready := io.main_pipe_req.ready
977
978      when(io.l2_hint.bits.sourceId === i.U) {
979        e.io.l2_hint <> io.l2_hint
980      } .otherwise {
981        e.io.l2_hint.valid := false.B
982        e.io.l2_hint.bits := DontCare
983      }
984  }
985
986  io.req.ready := accept
987  io.mq_enq_cancel := io.req.bits.cancel
988  io.refill_to_ldq.valid := Cat(entries.map(_.io.refill_to_ldq.valid)).orR
989  io.refill_to_ldq.bits := ParallelMux(entries.map(_.io.refill_to_ldq.valid) zip entries.map(_.io.refill_to_ldq.bits))
990
991  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
992  io.refill_info.bits := Mux1H(entries.zipWithIndex.map{ case(e,i) => (io.mainpipe_info.s2_miss_id === i.U) -> e.io.refill_info.bits })
993
994  acquire_from_pipereg.valid := miss_req_pipe_reg.can_send_acquire(io.req.valid, io.req.bits)
995  acquire_from_pipereg.bits := miss_req_pipe_reg.get_acquire(io.l2_pf_store_only)
996
997  XSPerfAccumulate("acquire_fire_from_pipereg", acquire_from_pipereg.fire)
998  XSPerfAccumulate("pipereg_valid", miss_req_pipe_reg.reg_valid())
999
1000  val acquire_sources = Seq(acquire_from_pipereg) ++ entries.map(_.io.mem_acquire)
1001  TLArbiter.lowest(edge, io.mem_acquire, acquire_sources:_*)
1002  TLArbiter.lowest(edge, io.mem_finish, entries.map(_.io.mem_finish):_*)
1003
1004  // amo's main pipe req out
1005  fastArbiter(entries.map(_.io.main_pipe_req), io.main_pipe_req, Some("main_pipe_req"))
1006
1007  io.probe_block := Cat(probe_block_vec).orR
1008
1009  io.full := ~Cat(entries.map(_.io.primary_ready)).andR
1010
1011  // prefetch related
1012  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)
1013
1014  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)
1015  io.prefetch_info.fdp.prefetch_monitor_cnt := io.main_pipe_req.fire
1016  io.prefetch_info.fdp.total_prefetch := alloc && io.req.valid && !io.req.bits.cancel && isFromL1Prefetch(io.req.bits.pf_source)
1017
1018  // L1MissTrace Chisel DB
1019  val debug_miss_trace = Wire(new L1MissTrace)
1020  debug_miss_trace.vaddr := io.req.bits.vaddr
1021  debug_miss_trace.paddr := io.req.bits.addr
1022  debug_miss_trace.source := io.req.bits.source
1023  debug_miss_trace.pc := io.req.bits.pc
1024
1025  val isWriteL1MissQMissTable = Constantin.createRecord(s"isWriteL1MissQMissTable${p(XSCoreParamsKey).HartId}")
1026  val table = ChiselDB.createTable(s"L1MissQMissTrace_hart${p(XSCoreParamsKey).HartId}", new L1MissTrace)
1027  table.log(debug_miss_trace, isWriteL1MissQMissTable.orR && io.req.valid && !io.req.bits.cancel && alloc, "MissQueue", clock, reset)
1028
1029  // Difftest
1030  if (env.EnableDifftest) {
1031    val difftest = DifftestModule(new DiffRefillEvent, dontCare = true)
1032    difftest.coreid := io.hartId
1033    difftest.index := 1.U
1034    difftest.valid := io.refill_to_ldq.valid && io.refill_to_ldq.bits.hasdata && io.refill_to_ldq.bits.refill_done
1035    difftest.addr := io.refill_to_ldq.bits.addr
1036    difftest.data := io.refill_to_ldq.bits.data_raw.asTypeOf(difftest.data)
1037    difftest.idtfr := DontCare
1038  }
1039
1040  // Perf count
1041  XSPerfAccumulate("miss_req", io.req.fire && !io.req.bits.cancel)
1042  XSPerfAccumulate("miss_req_allocate", io.req.fire && !io.req.bits.cancel && alloc)
1043  XSPerfAccumulate("miss_req_load_allocate", io.req.fire && !io.req.bits.cancel && alloc && io.req.bits.isFromLoad)
1044  XSPerfAccumulate("miss_req_store_allocate", io.req.fire && !io.req.bits.cancel && alloc && io.req.bits.isFromStore)
1045  XSPerfAccumulate("miss_req_amo_allocate", io.req.fire && !io.req.bits.cancel && alloc && io.req.bits.isFromAMO)
1046  XSPerfAccumulate("miss_req_prefetch_allocate", io.req.fire && !io.req.bits.cancel && alloc && io.req.bits.isFromPrefetch)
1047  XSPerfAccumulate("miss_req_merge_load", io.req.fire && !io.req.bits.cancel && merge && io.req.bits.isFromLoad)
1048  XSPerfAccumulate("miss_req_reject_load", io.req.valid && !io.req.bits.cancel && reject && io.req.bits.isFromLoad)
1049  XSPerfAccumulate("probe_blocked_by_miss", io.probe_block)
1050  XSPerfAccumulate("prefetch_primary_fire", io.req.fire && !io.req.bits.cancel && alloc && io.req.bits.isFromPrefetch)
1051  XSPerfAccumulate("prefetch_secondary_fire", io.req.fire && !io.req.bits.cancel && merge && io.req.bits.isFromPrefetch)
1052  XSPerfAccumulate("memSetPattenDetected", memSetPattenDetected)
1053  val max_inflight = RegInit(0.U((log2Up(cfg.nMissEntries) + 1).W))
1054  val num_valids = PopCount(~Cat(primary_ready_vec).asUInt)
1055  when (num_valids > max_inflight) {
1056    max_inflight := num_valids
1057  }
1058  // max inflight (average) = max_inflight_total / cycle cnt
1059  XSPerfAccumulate("max_inflight", max_inflight)
1060  QueuePerf(cfg.nMissEntries, num_valids, num_valids === cfg.nMissEntries.U)
1061  io.full := num_valids === cfg.nMissEntries.U
1062  XSPerfHistogram("num_valids", num_valids, true.B, 0, cfg.nMissEntries, 1)
1063
1064  XSPerfHistogram("L1DMLP_CPUData", PopCount(VecInit(entries.map(_.io.perf_pending_normal)).asUInt), true.B, 0, cfg.nMissEntries, 1)
1065  XSPerfHistogram("L1DMLP_Prefetch", PopCount(VecInit(entries.map(_.io.perf_pending_prefetch)).asUInt), true.B, 0, cfg.nMissEntries, 1)
1066  XSPerfHistogram("L1DMLP_Total", num_valids, true.B, 0, cfg.nMissEntries, 1)
1067
1068  XSPerfAccumulate("miss_load_refill_latency", PopCount(entries.map(_.io.latency_monitor.load_miss_refilling)))
1069  XSPerfAccumulate("miss_store_refill_latency", PopCount(entries.map(_.io.latency_monitor.store_miss_refilling)))
1070  XSPerfAccumulate("miss_amo_refill_latency", PopCount(entries.map(_.io.latency_monitor.amo_miss_refilling)))
1071  XSPerfAccumulate("miss_pf_refill_latency", PopCount(entries.map(_.io.latency_monitor.pf_miss_refilling)))
1072
1073  val rob_head_miss_in_dcache = VecInit(entries.map(_.io.rob_head_query.resp)).asUInt.orR
1074
1075  entries.foreach {
1076    case e => {
1077      e.io.rob_head_query.query_valid := io.debugTopDown.robHeadVaddr.valid
1078      e.io.rob_head_query.vaddr := io.debugTopDown.robHeadVaddr.bits
1079    }
1080  }
1081
1082  io.debugTopDown.robHeadMissInDCache := rob_head_miss_in_dcache
1083
1084  val perfValidCount = RegNext(PopCount(entries.map(entry => (!entry.io.primary_ready))))
1085  val perfEvents = Seq(
1086    ("dcache_missq_req      ", io.req.fire),
1087    ("dcache_missq_1_4_valid", (perfValidCount < (cfg.nMissEntries.U/4.U))),
1088    ("dcache_missq_2_4_valid", (perfValidCount > (cfg.nMissEntries.U/4.U)) & (perfValidCount <= (cfg.nMissEntries.U/2.U))),
1089    ("dcache_missq_3_4_valid", (perfValidCount > (cfg.nMissEntries.U/2.U)) & (perfValidCount <= (cfg.nMissEntries.U*3.U/4.U))),
1090    ("dcache_missq_4_4_valid", (perfValidCount > (cfg.nMissEntries.U*3.U/4.U))),
1091  )
1092  generatePerfEvent()
1093}