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