xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/mainpipe/MissQueue.scala (revision 9473e04d5cab97eaf63add958b2392eec3d876a2)
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 huancun.{AliasKey, DirtyKey, PreferCacheKey, PrefetchKey}
31import utility.FastArbiter
32import mem.{AddPipelineReg}
33import mem.trace._
34
35class MissReqWoStoreData(implicit p: Parameters) extends DCacheBundle {
36  val source = UInt(sourceTypeWidth.W)
37  val cmd = UInt(M_SZ.W)
38  val addr = UInt(PAddrBits.W)
39  val vaddr = UInt(VAddrBits.W)
40  val way_en = UInt(DCacheWays.W)
41  val pc = UInt(VAddrBits.W)
42
43  // store
44  val full_overwrite = Bool()
45
46  // which word does amo work on?
47  val word_idx = UInt(log2Up(blockWords).W)
48  val amo_data = UInt(DataBits.W)
49  val amo_mask = UInt((DataBits / 8).W)
50
51  val req_coh = new ClientMetadata
52  val replace_coh = new ClientMetadata
53  val replace_tag = UInt(tagBits.W)
54  val id = UInt(reqIdWidth.W)
55
56  // For now, miss queue entry req is actually valid when req.valid && !cancel
57  // * req.valid is fast to generate
58  // * cancel is slow to generate, it will not be used until the last moment
59  //
60  // cancel may come from the following sources:
61  // 1. miss req blocked by writeback queue:
62  //      a writeback req of the same address is in progress
63  // 2. pmp check failed
64  val cancel = Bool() // cancel is slow to generate, it will cancel missreq.valid
65
66  // Req source decode
67  // Note that req source is NOT cmd type
68  // For instance, a req which isFromPrefetch may have R or W cmd
69  def isFromLoad = source === LOAD_SOURCE.U
70  def isFromStore = source === STORE_SOURCE.U
71  def isFromAMO = source === AMO_SOURCE.U
72  def isFromPrefetch = source >= DCACHE_PREFETCH_SOURCE.U
73  def hit = req_coh.isValid()
74}
75
76class MissReqStoreData(implicit p: Parameters) extends DCacheBundle {
77  // store data and store mask will be written to miss queue entry
78  // 1 cycle after req.fire() and meta write
79  val store_data = UInt((cfg.blockBytes * 8).W)
80  val store_mask = UInt(cfg.blockBytes.W)
81}
82
83class MissReq(implicit p: Parameters) extends MissReqWoStoreData {
84  // store data and store mask will be written to miss queue entry
85  // 1 cycle after req.fire() and meta write
86  val store_data = UInt((cfg.blockBytes * 8).W)
87  val store_mask = UInt(cfg.blockBytes.W)
88
89  def toMissReqStoreData(): MissReqStoreData = {
90    val out = Wire(new MissReqStoreData)
91    out.store_data := store_data
92    out.store_mask := store_mask
93    out
94  }
95
96  def toMissReqWoStoreData(): MissReqWoStoreData = {
97    val out = Wire(new MissReqWoStoreData)
98    out.source := source
99    out.cmd := cmd
100    out.addr := addr
101    out.vaddr := vaddr
102    out.way_en := way_en
103    out.full_overwrite := full_overwrite
104    out.word_idx := word_idx
105    out.amo_data := amo_data
106    out.amo_mask := amo_mask
107    out.req_coh := req_coh
108    out.replace_coh := replace_coh
109    out.replace_tag := replace_tag
110    out.id := id
111    out.cancel := cancel
112    out.pc := pc
113    out
114  }
115}
116
117class MissResp(implicit p: Parameters) extends DCacheBundle {
118  val id = UInt(log2Up(cfg.nMissEntries).W)
119}
120
121class MissEntry(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule {
122  val io = IO(new Bundle() {
123    val hartId = Input(UInt(8.W))
124    // MSHR ID
125    val id = Input(UInt(log2Up(cfg.nMissEntries).W))
126    // client requests
127    // MSHR update request, MSHR state and addr will be updated when req.fire()
128    val req = Flipped(ValidIO(new MissReqWoStoreData))
129    // store data and mask will be write to miss queue entry 1 cycle after req.fire()
130    val req_data = Input(new MissReqStoreData)
131    // allocate this entry for new req
132    val primary_valid = Input(Bool())
133    // this entry is free and can be allocated to new reqs
134    val primary_ready = Output(Bool())
135    // this entry is busy, but it can merge the new req
136    val secondary_ready = Output(Bool())
137    // this entry is busy and it can not merge the new req
138    val secondary_reject = Output(Bool())
139
140    val refill_to_ldq = ValidIO(new Refill)
141
142    // bus
143    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
144    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
145    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
146
147    // refill pipe
148    val refill_pipe_req = DecoupledIO(new RefillPipeReq)
149    val refill_pipe_resp = Input(Bool())
150
151    // replace pipe
152    val replace_pipe_req = DecoupledIO(new MainPipeReq)
153    val replace_pipe_resp = Input(Bool())
154
155    // main pipe: amo miss
156    val main_pipe_req = DecoupledIO(new MainPipeReq)
157    val main_pipe_resp = Input(Bool())
158
159    val block_addr = ValidIO(UInt(PAddrBits.W))
160
161    val debug_early_replace = ValidIO(new Bundle() {
162      // info about the block that has been replaced
163      val idx = UInt(idxBits.W) // vaddr
164      val tag = UInt(tagBits.W) // paddr
165    })
166
167    val req_handled_by_this_entry = Output(Bool())
168
169    val forwardInfo = Output(new MissEntryForwardIO)
170    val l2_pf_store_only = Input(Bool())
171  })
172
173  assert(!RegNext(io.primary_valid && !io.primary_ready))
174
175  val req = Reg(new MissReqWoStoreData)
176  val req_store_mask = Reg(UInt(cfg.blockBytes.W))
177  val req_valid = RegInit(false.B)
178  val set = addr_to_dcache_set(req.vaddr)
179
180  val input_req_is_prefetch = isPrefetch(io.req.bits.cmd)
181
182  val s_acquire = RegInit(true.B)
183  val s_grantack = RegInit(true.B)
184  val s_replace_req = RegInit(true.B)
185  val s_refill = RegInit(true.B)
186  val s_mainpipe_req = RegInit(true.B)
187  val s_write_storedata = RegInit(true.B)
188
189  val w_grantfirst = RegInit(true.B)
190  val w_grantlast = RegInit(true.B)
191  val w_replace_resp = RegInit(true.B)
192  val w_refill_resp = RegInit(true.B)
193  val w_mainpipe_resp = RegInit(true.B)
194
195  val release_entry = s_grantack && w_refill_resp && w_mainpipe_resp
196
197  val acquire_not_sent = !s_acquire && !io.mem_acquire.ready
198  val data_not_refilled = !w_grantfirst
199
200  val error = RegInit(false.B)
201  val prefetch = RegInit(false.B)
202  val access = RegInit(false.B)
203
204  val should_refill_data_reg =  Reg(Bool())
205  val should_refill_data = WireInit(should_refill_data_reg)
206
207  // val full_overwrite = req.isFromStore && req_store_mask.andR
208  val full_overwrite = Reg(Bool())
209
210  val (_, _, refill_done, refill_count) = edge.count(io.mem_grant)
211  val grant_param = Reg(UInt(TLPermissions.bdWidth.W))
212
213  // refill data with store data, this reg will be used to store:
214  // 1. store data (if needed), before l2 refill data
215  // 2. store data and l2 refill data merged result (i.e. new cacheline taht will be write to data array)
216  val refill_and_store_data = Reg(Vec(blockRows, UInt(rowBits.W)))
217  // raw data refilled to l1 by l2
218  val refill_data_raw = Reg(Vec(blockBytes/beatBytes, UInt(beatBits.W)))
219
220  // allocate current miss queue entry for a miss req
221  val primary_fire = WireInit(io.req.valid && io.primary_ready && io.primary_valid && !io.req.bits.cancel)
222  // merge miss req to current miss queue entry
223  val secondary_fire = WireInit(io.req.valid && io.secondary_ready && !io.req.bits.cancel)
224
225  val req_handled_by_this_entry = primary_fire || secondary_fire
226
227  io.req_handled_by_this_entry := req_handled_by_this_entry
228
229  when (release_entry && req_valid) {
230    req_valid := false.B
231  }
232
233  when (!s_write_storedata && req_valid) {
234    // store data will be write to miss queue entry 1 cycle after req.fire()
235    s_write_storedata := true.B
236    assert(RegNext(primary_fire || secondary_fire))
237  }
238
239  when (primary_fire) {
240    req_valid := true.B
241    req := io.req.bits
242    req.addr := get_block_addr(io.req.bits.addr)
243
244    s_acquire := false.B
245    s_grantack := false.B
246
247    w_grantfirst := false.B
248    w_grantlast := false.B
249
250    s_write_storedata := !io.req.bits.isFromStore // only store need to wait for data
251    full_overwrite := io.req.bits.isFromStore && io.req.bits.full_overwrite
252
253    when (!io.req.bits.isFromAMO) {
254      s_refill := false.B
255      w_refill_resp := false.B
256    }
257
258    when (!io.req.bits.hit && io.req.bits.replace_coh.isValid() && !io.req.bits.isFromAMO) {
259      s_replace_req := false.B
260      w_replace_resp := false.B
261    }
262
263    when (io.req.bits.isFromAMO) {
264      s_mainpipe_req := false.B
265      w_mainpipe_resp := false.B
266    }
267
268    should_refill_data_reg := io.req.bits.isFromLoad
269    error := false.B
270    prefetch := input_req_is_prefetch
271    access := false.B
272  }
273
274  when (secondary_fire) {
275    assert(io.req.bits.req_coh.state <= req.req_coh.state || (prefetch && !access))
276    assert(!(io.req.bits.isFromAMO || req.isFromAMO))
277    // use the most uptodate meta
278    req.req_coh := io.req.bits.req_coh
279
280    when (io.req.bits.isFromStore) {
281      req := io.req.bits
282      req.addr := get_block_addr(io.req.bits.addr)
283      req.way_en := req.way_en
284      req.replace_coh := req.replace_coh
285      req.replace_tag := req.replace_tag
286      s_write_storedata := false.B // only store need to wait for data
287      full_overwrite := io.req.bits.isFromStore && io.req.bits.full_overwrite
288    }
289
290    should_refill_data := should_refill_data_reg || io.req.bits.isFromLoad
291    should_refill_data_reg := should_refill_data
292    when (!input_req_is_prefetch) {
293      access := true.B // when merge non-prefetch req, set access bit
294    }
295  }
296
297  when (io.mem_acquire.fire()) {
298    s_acquire := true.B
299  }
300
301  // store data and mask write
302  when (!s_write_storedata && req_valid) {
303    req_store_mask := io.req_data.store_mask
304    for (i <- 0 until blockRows) {
305      refill_and_store_data(i) := io.req_data.store_data(rowBits * (i + 1) - 1, rowBits * i)
306    }
307  }
308
309  // merge data refilled by l2 and store data, update miss queue entry, gen refill_req
310  val new_data = Wire(Vec(blockRows, UInt(rowBits.W)))
311  val new_mask = Wire(Vec(blockRows, UInt(rowBytes.W)))
312  // merge refilled data and store data (if needed)
313  def mergePutData(old_data: UInt, new_data: UInt, wmask: UInt): UInt = {
314    val full_wmask = FillInterleaved(8, wmask)
315    (~full_wmask & old_data | full_wmask & new_data)
316  }
317  for (i <- 0 until blockRows) {
318    // new_data(i) := req.store_data(rowBits * (i + 1) - 1, rowBits * i)
319    new_data(i) := refill_and_store_data(i)
320    // we only need to merge data for Store
321    new_mask(i) := Mux(req.isFromStore, req_store_mask(rowBytes * (i + 1) - 1, rowBytes * i), 0.U)
322  }
323
324  val hasData = RegInit(true.B)
325  val isDirty = RegInit(false.B)
326  when (io.mem_grant.fire()) {
327    w_grantfirst := true.B
328    grant_param := io.mem_grant.bits.param
329    when (edge.hasData(io.mem_grant.bits)) {
330      // GrantData
331      for (i <- 0 until beatRows) {
332        val idx = (refill_count << log2Floor(beatRows)) + i.U
333        val grant_row = io.mem_grant.bits.data(rowBits * (i + 1) - 1, rowBits * i)
334        refill_and_store_data(idx) := mergePutData(grant_row, new_data(idx), new_mask(idx))
335      }
336      w_grantlast := w_grantlast || refill_done
337      hasData := true.B
338    }.otherwise {
339      // Grant
340      assert(full_overwrite)
341      for (i <- 0 until blockRows) {
342        refill_and_store_data(i) := new_data(i)
343      }
344      w_grantlast := true.B
345      hasData := false.B
346    }
347
348    error := io.mem_grant.bits.denied || io.mem_grant.bits.corrupt || error
349
350    refill_data_raw(refill_count) := io.mem_grant.bits.data
351    isDirty := io.mem_grant.bits.echo.lift(DirtyKey).getOrElse(false.B)
352  }
353
354  when (io.mem_finish.fire()) {
355    s_grantack := true.B
356  }
357
358  when (io.replace_pipe_req.fire()) {
359    s_replace_req := true.B
360  }
361
362  when (io.replace_pipe_resp) {
363    w_replace_resp := true.B
364  }
365
366  when (io.refill_pipe_req.fire()) {
367    s_refill := true.B
368  }
369
370  when (io.refill_pipe_resp) {
371    w_refill_resp := true.B
372  }
373
374  when (io.main_pipe_req.fire()) {
375    s_mainpipe_req := true.B
376  }
377
378  when (io.main_pipe_resp) {
379    w_mainpipe_resp := true.B
380  }
381
382  def before_req_sent_can_merge(new_req: MissReqWoStoreData): Bool = {
383    acquire_not_sent && (req.isFromLoad || req.isFromPrefetch) && (new_req.isFromLoad || new_req.isFromStore)
384  }
385
386  def before_data_refill_can_merge(new_req: MissReqWoStoreData): Bool = {
387    data_not_refilled && (req.isFromLoad || req.isFromStore || req.isFromPrefetch) && new_req.isFromLoad
388  }
389
390  // Note that late prefetch will be ignored
391
392  def should_merge(new_req: MissReqWoStoreData): Bool = {
393    val block_match = get_block(req.addr) === get_block(new_req.addr)
394    block_match &&
395    (
396      before_req_sent_can_merge(new_req) ||
397      before_data_refill_can_merge(new_req)
398    )
399  }
400
401  // store can be merged before io.mem_acquire.fire()
402  // store can not be merged the cycle that io.mem_acquire.fire()
403  // load can be merged before io.mem_grant.fire()
404  //
405  // TODO: merge store if possible? mem_acquire may need to be re-issued,
406  // but sbuffer entry can be freed
407  def should_reject(new_req: MissReqWoStoreData): Bool = {
408    val block_match = get_block(req.addr) === get_block(new_req.addr)
409    val set_match = set === addr_to_dcache_set(new_req.vaddr)
410
411    req_valid &&
412      Mux(
413        block_match,
414        !before_req_sent_can_merge(new_req) &&
415          !before_data_refill_can_merge(new_req),
416        set_match && new_req.way_en === req.way_en
417      )
418  }
419
420  io.primary_ready := !req_valid
421  io.secondary_ready := should_merge(io.req.bits)
422  io.secondary_reject := should_reject(io.req.bits)
423
424  // should not allocate, merge or reject at the same time
425  assert(RegNext(PopCount(Seq(io.primary_ready, io.secondary_ready, io.secondary_reject)) <= 1.U))
426
427  val refill_data_splited = WireInit(VecInit(Seq.tabulate(cfg.blockBytes * 8 / l1BusDataWidth)(i => {
428    val data = refill_and_store_data.asUInt
429    data((i + 1) * l1BusDataWidth - 1, i * l1BusDataWidth)
430  })))
431  // when granted data is all ready, wakeup lq's miss load
432  io.refill_to_ldq.valid := RegNext(!w_grantlast && io.mem_grant.fire()) && should_refill_data_reg
433  io.refill_to_ldq.bits.addr := RegNext(req.addr + (refill_count << refillOffBits))
434  io.refill_to_ldq.bits.data := refill_data_splited(RegNext(refill_count))
435  io.refill_to_ldq.bits.error := RegNext(io.mem_grant.bits.corrupt || io.mem_grant.bits.denied)
436  io.refill_to_ldq.bits.refill_done := RegNext(refill_done && io.mem_grant.fire())
437  io.refill_to_ldq.bits.hasdata := hasData
438  io.refill_to_ldq.bits.data_raw := refill_data_raw.asUInt
439  io.refill_to_ldq.bits.id := io.id
440
441  io.mem_acquire.valid := !s_acquire
442  val grow_param = req.req_coh.onAccess(req.cmd)._2
443  val acquireBlock = edge.AcquireBlock(
444    fromSource = io.id,
445    toAddress = req.addr,
446    lgSize = (log2Up(cfg.blockBytes)).U,
447    growPermissions = grow_param
448  )._2
449  val acquirePerm = edge.AcquirePerm(
450    fromSource = io.id,
451    toAddress = req.addr,
452    lgSize = (log2Up(cfg.blockBytes)).U,
453    growPermissions = grow_param
454  )._2
455  io.mem_acquire.bits := Mux(full_overwrite, acquirePerm, acquireBlock)
456  // resolve cache alias by L2
457  io.mem_acquire.bits.user.lift(AliasKey).foreach( _ := req.vaddr(13, 12))
458  // trigger prefetch
459  io.mem_acquire.bits.user.lift(PrefetchKey).foreach(_ := Mux(io.l2_pf_store_only, req.isFromStore, true.B))
460  // prefer not to cache data in L2 by default
461  io.mem_acquire.bits.user.lift(PreferCacheKey).foreach(_ := false.B)
462  require(nSets <= 256)
463
464  io.mem_grant.ready := !w_grantlast && s_acquire
465
466  val grantack = RegEnable(edge.GrantAck(io.mem_grant.bits), io.mem_grant.fire())
467  assert(RegNext(!io.mem_grant.fire() || edge.isRequest(io.mem_grant.bits)))
468  io.mem_finish.valid := !s_grantack && w_grantfirst
469  io.mem_finish.bits := grantack
470
471  io.replace_pipe_req.valid := !s_replace_req
472  val replace = io.replace_pipe_req.bits
473  replace := DontCare
474  replace.miss := false.B
475  replace.miss_id := io.id
476  replace.miss_dirty := false.B
477  replace.probe := false.B
478  replace.probe_need_data := false.B
479  replace.source := LOAD_SOURCE.U
480  replace.vaddr := req.vaddr // only untag bits are needed
481  replace.addr := Cat(req.replace_tag, 0.U(pgUntagBits.W)) // only tag bits are needed
482  replace.store_mask := 0.U
483  replace.replace := true.B
484  replace.replace_way_en := req.way_en
485  replace.error := false.B
486
487  io.refill_pipe_req.valid := !s_refill && w_replace_resp && w_grantlast
488  val refill = io.refill_pipe_req.bits
489  refill.source := req.source
490  refill.addr := req.addr
491  refill.way_en := req.way_en
492  refill.wmask := Mux(
493    hasData || req.isFromLoad,
494    ~0.U(DCacheBanks.W),
495    VecInit((0 until DCacheBanks).map(i => get_mask_of_bank(i, req_store_mask).orR)).asUInt
496  )
497  refill.data := refill_and_store_data.asTypeOf((new RefillPipeReq).data)
498  refill.miss_id := io.id
499  refill.id := req.id
500  def missCohGen(cmd: UInt, param: UInt, dirty: Bool) = {
501    val c = categorize(cmd)
502    MuxLookup(Cat(c, param, dirty), Nothing, Seq(
503      //(effect param) -> (next)
504      Cat(rd, toB, false.B)  -> Branch,
505      Cat(rd, toB, true.B)   -> Branch,
506      Cat(rd, toT, false.B)  -> Trunk,
507      Cat(rd, toT, true.B)   -> Dirty,
508      Cat(wi, toT, false.B)  -> Trunk,
509      Cat(wi, toT, true.B)   -> Dirty,
510      Cat(wr, toT, false.B)  -> Dirty,
511      Cat(wr, toT, true.B)   -> Dirty))
512  }
513  refill.meta.coh := ClientMetadata(missCohGen(req.cmd, grant_param, isDirty))
514  refill.error := error
515  refill.prefetch := prefetch
516  refill.access := access
517  refill.alias := req.vaddr(13, 12) // TODO
518
519  io.main_pipe_req.valid := !s_mainpipe_req && w_grantlast
520  io.main_pipe_req.bits := DontCare
521  io.main_pipe_req.bits.miss := true.B
522  io.main_pipe_req.bits.miss_id := io.id
523  io.main_pipe_req.bits.miss_param := grant_param
524  io.main_pipe_req.bits.miss_dirty := isDirty
525  io.main_pipe_req.bits.miss_way_en := req.way_en
526  io.main_pipe_req.bits.probe := false.B
527  io.main_pipe_req.bits.source := req.source
528  io.main_pipe_req.bits.cmd := req.cmd
529  io.main_pipe_req.bits.vaddr := req.vaddr
530  io.main_pipe_req.bits.addr := req.addr
531  io.main_pipe_req.bits.store_data := refill_and_store_data.asUInt
532  io.main_pipe_req.bits.store_mask := ~0.U(blockBytes.W)
533  io.main_pipe_req.bits.word_idx := req.word_idx
534  io.main_pipe_req.bits.amo_data := req.amo_data
535  io.main_pipe_req.bits.amo_mask := req.amo_mask
536  io.main_pipe_req.bits.error := error
537  io.main_pipe_req.bits.id := req.id
538
539  io.block_addr.valid := req_valid && w_grantlast && !w_refill_resp
540  io.block_addr.bits := req.addr
541
542  io.debug_early_replace.valid := BoolStopWatch(io.replace_pipe_resp, io.refill_pipe_req.fire())
543  io.debug_early_replace.bits.idx := addr_to_dcache_set(req.vaddr)
544  io.debug_early_replace.bits.tag := req.replace_tag
545
546  io.forwardInfo.apply(req_valid, req.addr, refill_data_raw, w_grantfirst, w_grantlast)
547
548  XSPerfAccumulate("miss_req_primary", primary_fire)
549  XSPerfAccumulate("miss_req_merged", secondary_fire)
550  XSPerfAccumulate("load_miss_penalty_to_use",
551    should_refill_data &&
552      BoolStopWatch(primary_fire, io.refill_to_ldq.valid, true)
553  )
554  XSPerfAccumulate("main_pipe_penalty", BoolStopWatch(io.main_pipe_req.fire(), io.main_pipe_resp))
555  XSPerfAccumulate("penalty_blocked_by_channel_A", io.mem_acquire.valid && !io.mem_acquire.ready)
556  XSPerfAccumulate("penalty_waiting_for_channel_D", s_acquire && !w_grantlast && !io.mem_grant.valid)
557  XSPerfAccumulate("penalty_waiting_for_channel_E", io.mem_finish.valid && !io.mem_finish.ready)
558  XSPerfAccumulate("penalty_from_grant_to_refill", !w_refill_resp && w_grantlast)
559  XSPerfAccumulate("prefetch_req_primary", primary_fire && io.req.bits.source === DCACHE_PREFETCH_SOURCE.U)
560  XSPerfAccumulate("prefetch_req_merged", secondary_fire && io.req.bits.source === DCACHE_PREFETCH_SOURCE.U)
561
562  val (mshr_penalty_sample, mshr_penalty) = TransactionLatencyCounter(RegNext(primary_fire), release_entry)
563  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 0, 20, 1, true, true)
564  XSPerfHistogram("miss_penalty", mshr_penalty, mshr_penalty_sample, 20, 100, 10, true, false)
565
566  val load_miss_begin = primary_fire && io.req.bits.isFromLoad
567  val refill_finished = RegNext(!w_grantlast && refill_done) && should_refill_data
568  val (load_miss_penalty_sample, load_miss_penalty) = TransactionLatencyCounter(load_miss_begin, refill_finished) // not real refill finish time
569  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 0, 20, 1, true, true)
570  XSPerfHistogram("load_miss_penalty_to_use", load_miss_penalty, load_miss_penalty_sample, 20, 100, 10, true, false)
571
572  val (a_to_d_penalty_sample, a_to_d_penalty) = TransactionLatencyCounter(io.mem_acquire.fire(), io.mem_grant.fire() && refill_done)
573  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 0, 20, 1, true, true)
574  XSPerfHistogram("a_to_d_penalty", a_to_d_penalty, a_to_d_penalty_sample, 20, 100, 10, true, false)
575}
576
577class MissQueue(edge: TLEdgeOut)(implicit p: Parameters) extends DCacheModule with HasPerfEvents {
578  val io = IO(new Bundle {
579    val hartId = Input(UInt(8.W))
580    val req = Flipped(DecoupledIO(new MissReq))
581    val resp = Output(new MissResp)
582    val refill_to_ldq = ValidIO(new Refill)
583
584    val mem_acquire = DecoupledIO(new TLBundleA(edge.bundle))
585    val mem_grant = Flipped(DecoupledIO(new TLBundleD(edge.bundle)))
586    val mem_finish = DecoupledIO(new TLBundleE(edge.bundle))
587
588    val refill_pipe_req = DecoupledIO(new RefillPipeReq)
589    val refill_pipe_req_dup = Vec(nDupStatus, DecoupledIO(new RefillPipeReqCtrl))
590    val refill_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
591
592    val replace_pipe_req = DecoupledIO(new MainPipeReq)
593    val replace_pipe_resp = Flipped(ValidIO(UInt(log2Up(cfg.nMissEntries).W)))
594
595    val main_pipe_req = DecoupledIO(new MainPipeReq)
596    val main_pipe_resp = Flipped(ValidIO(new AtomicsResp))
597
598    // block probe
599    val probe_addr = Input(UInt(PAddrBits.W))
600    val probe_block = Output(Bool())
601
602    val full = Output(Bool())
603
604    // only for performance counter
605    // This is valid when an mshr has finished replacing a block (w_replace_resp),
606    // but hasn't received Grant from L2 (!w_grantlast)
607    val debug_early_replace = Vec(cfg.nMissEntries, ValidIO(new Bundle() {
608      // info about the block that has been replaced
609      val idx = UInt(idxBits.W) // vaddr
610      val tag = UInt(tagBits.W) // paddr
611    }))
612
613    // forward missqueue
614    val forward = Vec(LoadPipelineWidth, new LduToMissqueueForwardIO)
615    val l2_pf_store_only = Input(Bool())
616  })
617
618  // 128KBL1: FIXME: provide vaddr for l2
619
620  val entries = Seq.fill(cfg.nMissEntries)(Module(new MissEntry(edge)))
621
622  val req_data_gen = io.req.bits.toMissReqStoreData()
623  val req_data_buffer = RegEnable(req_data_gen, io.req.valid)
624
625  val primary_ready_vec = entries.map(_.io.primary_ready)
626  val secondary_ready_vec = entries.map(_.io.secondary_ready)
627  val secondary_reject_vec = entries.map(_.io.secondary_reject)
628  val probe_block_vec = entries.map { case e => e.io.block_addr.valid && e.io.block_addr.bits === io.probe_addr }
629
630  val merge = Cat(secondary_ready_vec).orR
631  val reject = Cat(secondary_reject_vec).orR
632  val alloc = !reject && !merge && Cat(primary_ready_vec).orR
633  val accept = alloc || merge
634
635  val req_handled_vec = entries.map(_.io.req_handled_by_this_entry)
636  assert(PopCount(req_handled_vec) <= 1.U, "Only one mshr can handle a req")
637  io.resp.id := OHToUInt(req_handled_vec)
638
639  val forwardInfo_vec = VecInit(entries.map(_.io.forwardInfo))
640  (0 until LoadPipelineWidth).map(i => {
641    val id = io.forward(i).mshrid
642    val req_valid = io.forward(i).valid
643    val paddr = io.forward(i).paddr
644
645    val (forward_mshr, forwardData) = forwardInfo_vec(id).forward(req_valid, paddr)
646    io.forward(i).forward_result_valid := forwardInfo_vec(id).check(req_valid, paddr)
647    io.forward(i).forward_mshr := forward_mshr
648    io.forward(i).forwardData := forwardData
649  })
650
651  assert(RegNext(PopCount(secondary_ready_vec) <= 1.U))
652//  assert(RegNext(PopCount(secondary_reject_vec) <= 1.U))
653  // It is possible that one mshr wants to merge a req, while another mshr wants to reject it.
654  // That is, a coming req has the same paddr as that of mshr_0 (merge),
655  // while it has the same set and the same way as mshr_1 (reject).
656  // In this situation, the coming req should be merged by mshr_0
657//  assert(RegNext(PopCount(Seq(merge, reject)) <= 1.U))
658
659  def select_valid_one[T <: Bundle](
660    in: Seq[DecoupledIO[T]],
661    out: DecoupledIO[T],
662    name: Option[String] = None): Unit = {
663
664    if (name.nonEmpty) { out.suggestName(s"${name.get}_select") }
665    out.valid := Cat(in.map(_.valid)).orR
666    out.bits := ParallelMux(in.map(_.valid) zip in.map(_.bits))
667    in.map(_.ready := out.ready)
668    assert(!RegNext(out.valid && PopCount(Cat(in.map(_.valid))) > 1.U))
669  }
670
671  io.mem_grant.ready := false.B
672
673  entries.zipWithIndex.foreach {
674    case (e, i) =>
675      val former_primary_ready = if(i == 0)
676        false.B
677      else
678        Cat((0 until i).map(j => entries(j).io.primary_ready)).orR
679
680      e.io.hartId := io.hartId
681      e.io.id := i.U
682      e.io.l2_pf_store_only := io.l2_pf_store_only
683      e.io.req.valid := io.req.valid
684      e.io.primary_valid := io.req.valid &&
685        !merge &&
686        !reject &&
687        !former_primary_ready &&
688        e.io.primary_ready
689      e.io.req.bits := io.req.bits.toMissReqWoStoreData()
690      e.io.req_data := req_data_buffer
691
692      e.io.mem_grant.valid := false.B
693      e.io.mem_grant.bits := DontCare
694      when (io.mem_grant.bits.source === i.U) {
695        e.io.mem_grant <> io.mem_grant
696      }
697
698      e.io.refill_pipe_resp := io.refill_pipe_resp.valid && io.refill_pipe_resp.bits === i.U
699      e.io.replace_pipe_resp := io.replace_pipe_resp.valid && io.replace_pipe_resp.bits === i.U
700      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
701
702      io.debug_early_replace(i) := e.io.debug_early_replace
703  }
704
705  io.req.ready := accept
706  io.refill_to_ldq.valid := Cat(entries.map(_.io.refill_to_ldq.valid)).orR
707  io.refill_to_ldq.bits := ParallelMux(entries.map(_.io.refill_to_ldq.valid) zip entries.map(_.io.refill_to_ldq.bits))
708
709  TLArbiter.lowest(edge, io.mem_acquire, entries.map(_.io.mem_acquire):_*)
710  TLArbiter.lowest(edge, io.mem_finish, entries.map(_.io.mem_finish):_*)
711
712  // arbiter_with_pipereg_N_dup(entries.map(_.io.refill_pipe_req), io.refill_pipe_req,
713  // io.refill_pipe_req_dup,
714  // Some("refill_pipe_req"))
715  val out_refill_pipe_req = Wire(Decoupled(new RefillPipeReq))
716  val out_refill_pipe_req_ctrl = Wire(Decoupled(new RefillPipeReqCtrl))
717  out_refill_pipe_req_ctrl.valid := out_refill_pipe_req.valid
718  out_refill_pipe_req_ctrl.bits := out_refill_pipe_req.bits.getCtrl
719  out_refill_pipe_req.ready := out_refill_pipe_req_ctrl.ready
720  arbiter(entries.map(_.io.refill_pipe_req), out_refill_pipe_req, Some("refill_pipe_req"))
721  for (dup <- io.refill_pipe_req_dup) {
722    AddPipelineReg(out_refill_pipe_req_ctrl, dup, false.B)
723  }
724  AddPipelineReg(out_refill_pipe_req, io.refill_pipe_req, false.B)
725
726  arbiter_with_pipereg(entries.map(_.io.replace_pipe_req), io.replace_pipe_req, Some("replace_pipe_req"))
727
728  fastArbiter(entries.map(_.io.main_pipe_req), io.main_pipe_req, Some("main_pipe_req"))
729
730  io.probe_block := Cat(probe_block_vec).orR
731
732  io.full := ~Cat(entries.map(_.io.primary_ready)).andR
733
734  // L1MissTrace Chisel DB
735  val debug_miss_trace = Wire(new L1MissTrace)
736  debug_miss_trace.vaddr := io.req.bits.vaddr
737  debug_miss_trace.paddr := io.req.bits.addr
738  debug_miss_trace.source := io.req.bits.source
739  debug_miss_trace.pc := io.req.bits.pc
740
741  val table = ChiselDB.createTable("L1MissQMissTrace_hart"+ p(XSCoreParamsKey).HartId.toString, new L1MissTrace)
742  table.log(debug_miss_trace, io.req.valid && !io.req.bits.cancel && alloc, "MissQueue", clock, reset)
743
744  // Difftest
745  if (env.EnableDifftest) {
746    val difftest = Module(new DifftestRefillEvent)
747    difftest.io.clock := clock
748    difftest.io.coreid := io.hartId
749    difftest.io.cacheid := 1.U
750    difftest.io.valid := io.refill_to_ldq.valid && io.refill_to_ldq.bits.hasdata && io.refill_to_ldq.bits.refill_done
751    difftest.io.addr := io.refill_to_ldq.bits.addr
752    difftest.io.data := io.refill_to_ldq.bits.data_raw.asTypeOf(difftest.io.data)
753  }
754
755  // Perf count
756  XSPerfAccumulate("miss_req", io.req.fire())
757  XSPerfAccumulate("miss_req_allocate", io.req.fire() && alloc)
758  XSPerfAccumulate("miss_req_merge_load", io.req.fire() && merge && io.req.bits.isFromLoad)
759  XSPerfAccumulate("miss_req_reject_load", io.req.valid && reject && io.req.bits.isFromLoad)
760  XSPerfAccumulate("probe_blocked_by_miss", io.probe_block)
761  XSPerfAccumulate("prefetch_primary_fire", io.req.fire() && alloc && io.req.bits.isFromPrefetch)
762  XSPerfAccumulate("prefetch_secondary_fire", io.req.fire() && merge && io.req.bits.isFromPrefetch)
763  val max_inflight = RegInit(0.U((log2Up(cfg.nMissEntries) + 1).W))
764  val num_valids = PopCount(~Cat(primary_ready_vec).asUInt)
765  when (num_valids > max_inflight) {
766    max_inflight := num_valids
767  }
768  // max inflight (average) = max_inflight_total / cycle cnt
769  XSPerfAccumulate("max_inflight", max_inflight)
770  QueuePerf(cfg.nMissEntries, num_valids, num_valids === cfg.nMissEntries.U)
771  io.full := num_valids === cfg.nMissEntries.U
772  XSPerfHistogram("num_valids", num_valids, true.B, 0, cfg.nMissEntries, 1)
773
774  val perfValidCount = RegNext(PopCount(entries.map(entry => (!entry.io.primary_ready))))
775  val perfEvents = Seq(
776    ("dcache_missq_req      ", io.req.fire()),
777    ("dcache_missq_1_4_valid", (perfValidCount < (cfg.nMissEntries.U/4.U))),
778    ("dcache_missq_2_4_valid", (perfValidCount > (cfg.nMissEntries.U/4.U)) & (perfValidCount <= (cfg.nMissEntries.U/2.U))),
779    ("dcache_missq_3_4_valid", (perfValidCount > (cfg.nMissEntries.U/2.U)) & (perfValidCount <= (cfg.nMissEntries.U*3.U/4.U))),
780    ("dcache_missq_4_4_valid", (perfValidCount > (cfg.nMissEntries.U*3.U/4.U))),
781  )
782  generatePerfEvent()
783}
784