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