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