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