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