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