xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/LoadQueue.scala (revision 779faf1201ad09c3e3f0faef77ebebb4ddd3522f)
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.mem
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import xiangshan._
24import xiangshan.backend.fu.fpu.FPU
25import xiangshan.backend.rob.RobLsqIO
26import xiangshan.cache._
27import xiangshan.frontend.FtqPtr
28import xiangshan.ExceptionNO._
29
30class LqPtr(implicit p: Parameters) extends CircularQueuePtr[LqPtr](
31  p => p(XSCoreParamsKey).LoadQueueSize
32){
33}
34
35object LqPtr {
36  def apply(f: Bool, v: UInt)(implicit p: Parameters): LqPtr = {
37    val ptr = Wire(new LqPtr)
38    ptr.flag := f
39    ptr.value := v
40    ptr
41  }
42}
43
44trait HasLoadHelper { this: XSModule =>
45  def rdataHelper(uop: MicroOp, rdata: UInt): UInt = {
46    val fpWen = uop.ctrl.fpWen
47    LookupTree(uop.ctrl.fuOpType, List(
48      LSUOpType.lb   -> SignExt(rdata(7, 0) , XLEN),
49      LSUOpType.lh   -> SignExt(rdata(15, 0), XLEN),
50      /*
51          riscv-spec-20191213: 12.2 NaN Boxing of Narrower Values
52          Any operation that writes a narrower result to an f register must write
53          all 1s to the uppermost FLEN−n bits to yield a legal NaN-boxed value.
54      */
55      LSUOpType.lw   -> Mux(fpWen, FPU.box(rdata, FPU.S), SignExt(rdata(31, 0), XLEN)),
56      LSUOpType.ld   -> Mux(fpWen, FPU.box(rdata, FPU.D), SignExt(rdata(63, 0), XLEN)),
57      LSUOpType.lbu  -> ZeroExt(rdata(7, 0) , XLEN),
58      LSUOpType.lhu  -> ZeroExt(rdata(15, 0), XLEN),
59      LSUOpType.lwu  -> ZeroExt(rdata(31, 0), XLEN),
60    ))
61  }
62}
63
64class LqEnqIO(implicit p: Parameters) extends XSBundle {
65  val canAccept = Output(Bool())
66  val sqCanAccept = Input(Bool())
67  val needAlloc = Vec(exuParameters.LsExuCnt, Input(Bool()))
68  val req = Vec(exuParameters.LsExuCnt, Flipped(ValidIO(new MicroOp)))
69  val resp = Vec(exuParameters.LsExuCnt, Output(new LqPtr))
70}
71
72class LqTriggerIO(implicit p: Parameters) extends XSBundle {
73  val hitLoadAddrTriggerHitVec = Input(Vec(3, Bool()))
74  val lqLoadAddrTriggerHitVec = Output(Vec(3, Bool()))
75}
76
77// Load Queue
78class LoadQueue(implicit p: Parameters) extends XSModule
79  with HasDCacheParameters
80  with HasCircularQueuePtrHelper
81  with HasLoadHelper
82  with HasPerfEvents
83{
84  val io = IO(new Bundle() {
85    val enq = new LqEnqIO
86    val brqRedirect = Flipped(ValidIO(new Redirect))
87    val loadIn = Vec(LoadPipelineWidth, Flipped(Valid(new LqWriteBundle)))
88    val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle)))
89    val s2_load_data_forwarded = Vec(LoadPipelineWidth, Input(Bool()))
90    val s3_delayed_load_error = Vec(LoadPipelineWidth, Input(Bool()))
91    val s2_dcache_require_replay = Vec(LoadPipelineWidth, Input(Bool()))
92    val s3_replay_from_fetch = Vec(LoadPipelineWidth, Input(Bool()))
93    val ldout = Vec(LoadPipelineWidth, DecoupledIO(new ExuOutput)) // writeback int load
94    val load_s1 = Vec(LoadPipelineWidth, Flipped(new PipeLoadForwardQueryIO)) // TODO: to be renamed
95    val loadViolationQuery = Vec(LoadPipelineWidth, Flipped(new LoadViolationQueryIO))
96    val rob = Flipped(new RobLsqIO)
97    val rollback = Output(Valid(new Redirect)) // replay now starts from load instead of store
98    val refill = Flipped(ValidIO(new Refill))
99    val release = Flipped(ValidIO(new Release))
100    val uncache = new UncacheWordIO
101    val exceptionAddr = new ExceptionAddrIO
102    val lqFull = Output(Bool())
103    val lqCancelCnt = Output(UInt(log2Up(LoadQueueSize + 1).W))
104    val trigger = Vec(LoadPipelineWidth, new LqTriggerIO)
105  })
106
107  println("LoadQueue: size:" + LoadQueueSize)
108
109  val uop = Reg(Vec(LoadQueueSize, new MicroOp))
110  // val data = Reg(Vec(LoadQueueSize, new LsRobEntry))
111  val dataModule = Module(new LoadQueueDataWrapper(LoadQueueSize, wbNumRead = LoadPipelineWidth, wbNumWrite = LoadPipelineWidth))
112  dataModule.io := DontCare
113  val vaddrModule = Module(new SyncDataModuleTemplate(UInt(VAddrBits.W), LoadQueueSize, numRead = LoadPipelineWidth + 1, numWrite = LoadPipelineWidth))
114  vaddrModule.io := DontCare
115  val vaddrTriggerResultModule = Module(new SyncDataModuleTemplate(Vec(3, Bool()), LoadQueueSize, numRead = LoadPipelineWidth, numWrite = LoadPipelineWidth))
116  vaddrTriggerResultModule.io := DontCare
117  val allocated = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // lq entry has been allocated
118  val datavalid = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // data is valid
119  val writebacked = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // inst has been writebacked to CDB
120  val released = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // load data has been released by dcache
121  val error = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // load data has been corrupted
122  val miss = Reg(Vec(LoadQueueSize, Bool())) // load inst missed, waiting for miss queue to accept miss request
123  // val listening = Reg(Vec(LoadQueueSize, Bool())) // waiting for refill result
124  val pending = Reg(Vec(LoadQueueSize, Bool())) // mmio pending: inst is an mmio inst, it will not be executed until it reachs the end of rob
125  val refilling = WireInit(VecInit(List.fill(LoadQueueSize)(false.B))) // inst has been writebacked to CDB
126
127  val debug_mmio = Reg(Vec(LoadQueueSize, Bool())) // mmio: inst is an mmio inst
128  val debug_paddr = Reg(Vec(LoadQueueSize, UInt(PAddrBits.W))) // mmio: inst is an mmio inst
129
130  val enqPtrExt = RegInit(VecInit((0 until io.enq.req.length).map(_.U.asTypeOf(new LqPtr))))
131  val deqPtrExt = RegInit(0.U.asTypeOf(new LqPtr))
132  val deqPtrExtNext = Wire(new LqPtr)
133
134  val enqPtr = enqPtrExt(0).value
135  val deqPtr = deqPtrExt.value
136
137  val validCount = distanceBetween(enqPtrExt(0), deqPtrExt)
138  val allowEnqueue = validCount <= (LoadQueueSize - LoadPipelineWidth).U
139
140  val deqMask = UIntToMask(deqPtr, LoadQueueSize)
141  val enqMask = UIntToMask(enqPtr, LoadQueueSize)
142
143  val commitCount = RegNext(io.rob.lcommit)
144
145  val release1cycle = io.release
146  val release2cycle = RegNext(io.release)
147  val release2cycle_dup_lsu = RegNext(io.release)
148
149  /**
150    * Enqueue at dispatch
151    *
152    * Currently, LoadQueue only allows enqueue when #emptyEntries > EnqWidth
153    */
154  io.enq.canAccept := allowEnqueue
155
156  val canEnqueue = io.enq.req.map(_.valid)
157  val enqCancel = io.enq.req.map(_.bits.robIdx.needFlush(io.brqRedirect))
158  for (i <- 0 until io.enq.req.length) {
159    val offset = if (i == 0) 0.U else PopCount(io.enq.needAlloc.take(i))
160    val lqIdx = enqPtrExt(offset)
161    val index = io.enq.req(i).bits.lqIdx.value
162    when (canEnqueue(i) && !enqCancel(i)) {
163      uop(index).robIdx := io.enq.req(i).bits.robIdx
164      allocated(index) := true.B
165      datavalid(index) := false.B
166      writebacked(index) := false.B
167      released(index) := false.B
168      miss(index) := false.B
169      pending(index) := false.B
170      error(index) := false.B
171      XSError(!io.enq.canAccept || !io.enq.sqCanAccept, s"must accept $i\n")
172      XSError(index =/= lqIdx.value, s"must be the same entry $i\n")
173    }
174    io.enq.resp(i) := lqIdx
175  }
176  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
177
178  /**
179    * Writeback load from load units
180    *
181    * Most load instructions writeback to regfile at the same time.
182    * However,
183    *   (1) For an mmio instruction with exceptions, it writes back to ROB immediately.
184    *   (2) For an mmio instruction without exceptions, it does not write back.
185    * The mmio instruction will be sent to lower level when it reaches ROB's head.
186    * After uncache response, it will write back through arbiter with loadUnit.
187    *   (3) For cache misses, it is marked miss and sent to dcache later.
188    * After cache refills, it will write back through arbiter with loadUnit.
189    */
190  for (i <- 0 until LoadPipelineWidth) {
191    dataModule.io.wb.wen(i) := false.B
192    vaddrTriggerResultModule.io.wen(i) := false.B
193    val loadWbIndex = io.loadIn(i).bits.uop.lqIdx.value
194
195    // most lq status need to be updated immediately after load writeback to lq
196    // flag bits in lq needs to be updated accurately
197    when(io.loadIn(i).fire()) {
198      when(io.loadIn(i).bits.miss) {
199        XSInfo(io.loadIn(i).valid, "load miss write to lq idx %d pc 0x%x vaddr %x paddr %x data %x mask %x forwardData %x forwardMask: %x mmio %x\n",
200          io.loadIn(i).bits.uop.lqIdx.asUInt,
201          io.loadIn(i).bits.uop.cf.pc,
202          io.loadIn(i).bits.vaddr,
203          io.loadIn(i).bits.paddr,
204          io.loadIn(i).bits.data,
205          io.loadIn(i).bits.mask,
206          io.loadIn(i).bits.forwardData.asUInt,
207          io.loadIn(i).bits.forwardMask.asUInt,
208          io.loadIn(i).bits.mmio
209        )
210      }.otherwise {
211        XSInfo(io.loadIn(i).valid, "load hit write to cbd lqidx %d pc 0x%x vaddr %x paddr %x data %x mask %x forwardData %x forwardMask: %x mmio %x\n",
212        io.loadIn(i).bits.uop.lqIdx.asUInt,
213        io.loadIn(i).bits.uop.cf.pc,
214        io.loadIn(i).bits.vaddr,
215        io.loadIn(i).bits.paddr,
216        io.loadIn(i).bits.data,
217        io.loadIn(i).bits.mask,
218        io.loadIn(i).bits.forwardData.asUInt,
219        io.loadIn(i).bits.forwardMask.asUInt,
220        io.loadIn(i).bits.mmio
221      )}
222      if(EnableFastForward){
223        datavalid(loadWbIndex) := (!io.loadIn(i).bits.miss || io.s2_load_data_forwarded(i)) &&
224          !io.loadIn(i).bits.mmio && // mmio data is not valid until we finished uncache access
225          !io.s2_dcache_require_replay(i) // do not writeback if that inst will be resend from rs
226      } else {
227        datavalid(loadWbIndex) := (!io.loadIn(i).bits.miss || io.s2_load_data_forwarded(i)) &&
228          !io.loadIn(i).bits.mmio // mmio data is not valid until we finished uncache access
229      }
230      writebacked(loadWbIndex) := !io.loadIn(i).bits.miss && !io.loadIn(i).bits.mmio
231
232      debug_mmio(loadWbIndex) := io.loadIn(i).bits.mmio
233      debug_paddr(loadWbIndex) := io.loadIn(i).bits.paddr
234
235      val dcacheMissed = io.loadIn(i).bits.miss && !io.loadIn(i).bits.mmio
236      if(EnableFastForward){
237        miss(loadWbIndex) := dcacheMissed && !io.s2_load_data_forwarded(i) && !io.s2_dcache_require_replay(i)
238      } else {
239        miss(loadWbIndex) := dcacheMissed && !io.s2_load_data_forwarded(i)
240      }
241      pending(loadWbIndex) := io.loadIn(i).bits.mmio
242      released(loadWbIndex) := release2cycle.valid &&
243        io.loadIn(i).bits.paddr(PAddrBits-1, DCacheLineOffset) === release2cycle.bits.paddr(PAddrBits-1, DCacheLineOffset) ||
244        release1cycle.valid &&
245        io.loadIn(i).bits.paddr(PAddrBits-1, DCacheLineOffset) === release1cycle.bits.paddr(PAddrBits-1, DCacheLineOffset)
246    }
247
248    // data bit in lq can be updated when load_s2 valid
249    // when(io.loadIn(i).bits.lq_data_wen){
250    //   val loadWbData = Wire(new LQDataEntry)
251    //   loadWbData.paddr := io.loadIn(i).bits.paddr
252    //   loadWbData.mask := io.loadIn(i).bits.mask
253    //   loadWbData.data := io.loadIn(i).bits.forwardData.asUInt // fwd data
254    //   loadWbData.fwdMask := io.loadIn(i).bits.forwardMask
255    //   dataModule.io.wbWrite(i, loadWbIndex, loadWbData)
256    //   dataModule.io.wb.wen(i) := true.B
257
258    //   // dirty code for load instr
259    //   uop(loadWbIndex).pdest := io.loadIn(i).bits.uop.pdest
260    //   uop(loadWbIndex).cf := io.loadIn(i).bits.uop.cf
261    //   uop(loadWbIndex).ctrl := io.loadIn(i).bits.uop.ctrl
262    //   uop(loadWbIndex).debugInfo := io.loadIn(i).bits.uop.debugInfo
263
264    //   vaddrTriggerResultModule.io.waddr(i) := loadWbIndex
265    //   vaddrTriggerResultModule.io.wdata(i) := io.trigger(i).hitLoadAddrTriggerHitVec
266
267    //   vaddrTriggerResultModule.io.wen(i) := true.B
268    // }
269
270    // dirty code to reduce load_s2.valid fanout
271    when(io.loadIn(i).bits.lq_data_wen_dup(0)){
272      val loadWbData = Wire(new LQDataEntry)
273      loadWbData.paddr := io.loadIn(i).bits.paddr
274      loadWbData.mask := io.loadIn(i).bits.mask
275      loadWbData.data := io.loadIn(i).bits.forwardData.asUInt // fwd data
276      loadWbData.fwdMask := io.loadIn(i).bits.forwardMask
277      dataModule.io.wbWrite(i, loadWbIndex, loadWbData)
278      dataModule.io.wb.wen(i) := true.B
279    }
280    // dirty code for load instr
281    when(io.loadIn(i).bits.lq_data_wen_dup(1)){
282      uop(loadWbIndex).pdest := io.loadIn(i).bits.uop.pdest
283    }
284    when(io.loadIn(i).bits.lq_data_wen_dup(2)){
285      uop(loadWbIndex).cf := io.loadIn(i).bits.uop.cf
286    }
287    when(io.loadIn(i).bits.lq_data_wen_dup(3)){
288      uop(loadWbIndex).ctrl := io.loadIn(i).bits.uop.ctrl
289    }
290    when(io.loadIn(i).bits.lq_data_wen_dup(4)){
291      uop(loadWbIndex).debugInfo := io.loadIn(i).bits.uop.debugInfo
292    }
293    when(io.loadIn(i).bits.lq_data_wen_dup(5)){
294      vaddrTriggerResultModule.io.waddr(i) := loadWbIndex
295      vaddrTriggerResultModule.io.wdata(i) := io.trigger(i).hitLoadAddrTriggerHitVec
296      vaddrTriggerResultModule.io.wen(i) := true.B
297    }
298
299    // vaddrModule write is delayed, as vaddrModule will not be read right after write
300    vaddrModule.io.waddr(i) := RegNext(loadWbIndex)
301    vaddrModule.io.wdata(i) := RegNext(io.loadIn(i).bits.vaddr)
302    vaddrModule.io.wen(i) := RegNext(io.loadIn(i).fire())
303  }
304
305  when(io.refill.valid) {
306    XSDebug("miss resp: paddr:0x%x data %x\n", io.refill.bits.addr, io.refill.bits.data)
307  }
308
309  // Refill 64 bit in a cycle
310  // Refill data comes back from io.dcache.resp
311  dataModule.io.refill.valid := io.refill.valid
312  dataModule.io.refill.paddr := io.refill.bits.addr
313  dataModule.io.refill.data := io.refill.bits.data
314
315  val s2_dcache_require_replay = WireInit(VecInit((0 until LoadPipelineWidth).map(i =>{
316    RegNext(io.loadIn(i).fire()) && RegNext(io.s2_dcache_require_replay(i))
317  })))
318  dontTouch(s2_dcache_require_replay)
319
320  (0 until LoadQueueSize).map(i => {
321    dataModule.io.refill.refillMask(i) := allocated(i) && miss(i)
322    when(dataModule.io.refill.valid && dataModule.io.refill.refillMask(i) && dataModule.io.refill.matchMask(i)) {
323      datavalid(i) := true.B
324      miss(i) := false.B
325      when(!s2_dcache_require_replay.asUInt.orR){
326        refilling(i) := true.B
327      }
328      when(io.refill.bits.error) {
329        error(i) := true.B
330      }
331    }
332  })
333
334  for (i <- 0 until LoadPipelineWidth) {
335    val loadWbIndex = io.loadIn(i).bits.uop.lqIdx.value
336    val lastCycleLoadWbIndex = RegNext(loadWbIndex)
337    // update miss state in load s3
338    if(!EnableFastForward){
339      // s2_dcache_require_replay will be used to update lq flag 1 cycle after for better timing
340      //
341      // io.s2_dcache_require_replay comes from dcache miss req reject, which is quite slow to generate
342      when(s2_dcache_require_replay(i)) {
343        // do not writeback if that inst will be resend from rs
344        // rob writeback will not be triggered by a refill before inst replay
345        miss(lastCycleLoadWbIndex) := false.B // disable refill listening
346        datavalid(lastCycleLoadWbIndex) := false.B // disable refill listening
347        assert(!datavalid(lastCycleLoadWbIndex))
348      }
349    }
350    // update load error state in load s3
351    when(RegNext(io.loadIn(i).fire()) && io.s3_delayed_load_error(i)){
352      uop(lastCycleLoadWbIndex).cf.exceptionVec(loadAccessFault) := true.B
353    }
354    // update inst replay from fetch flag in s3
355    when(RegNext(io.loadIn(i).fire()) && io.s3_replay_from_fetch(i)){
356      uop(lastCycleLoadWbIndex).ctrl.replayInst := true.B
357    }
358  }
359
360
361  // Writeback up to 2 missed load insts to CDB
362  //
363  // Pick 2 missed load (data refilled), write them back to cdb
364  // 2 refilled load will be selected from even/odd entry, separately
365
366  // Stage 0
367  // Generate writeback indexes
368
369  def getRemBits(input: UInt)(rem: Int): UInt = {
370    VecInit((0 until LoadQueueSize / LoadPipelineWidth).map(i => { input(LoadPipelineWidth * i + rem) })).asUInt
371  }
372
373  val loadWbSel = Wire(Vec(LoadPipelineWidth, UInt(log2Up(LoadQueueSize).W))) // index selected last cycle
374  val loadWbSelV = Wire(Vec(LoadPipelineWidth, Bool())) // index selected in last cycle is valid
375
376  val loadWbSelVec = VecInit((0 until LoadQueueSize).map(i => {
377    // allocated(i) && !writebacked(i) && (datavalid(i) || refilling(i))
378    allocated(i) && !writebacked(i) && datavalid(i) // query refilling will cause bad timing
379  })).asUInt() // use uint instead vec to reduce verilog lines
380  val remDeqMask = Seq.tabulate(LoadPipelineWidth)(getRemBits(deqMask)(_))
381  // generate lastCycleSelect mask
382  val remFireMask = Seq.tabulate(LoadPipelineWidth)(rem => getRemBits(UIntToOH(loadWbSel(rem)))(rem))
383  // generate real select vec
384  def toVec(a: UInt): Vec[Bool] = {
385    VecInit(a.asBools)
386  }
387  val loadRemSelVecFire = Seq.tabulate(LoadPipelineWidth)(rem => getRemBits(loadWbSelVec)(rem) & ~remFireMask(rem))
388  val loadRemSelVecNotFire = Seq.tabulate(LoadPipelineWidth)(getRemBits(loadWbSelVec)(_))
389  val loadRemSel = Seq.tabulate(LoadPipelineWidth)(rem => Mux(
390    io.ldout(rem).fire(),
391    getFirstOne(toVec(loadRemSelVecFire(rem)), remDeqMask(rem)),
392    getFirstOne(toVec(loadRemSelVecNotFire(rem)), remDeqMask(rem))
393  ))
394
395
396  val loadWbSelGen = Wire(Vec(LoadPipelineWidth, UInt(log2Up(LoadQueueSize).W)))
397  val loadWbSelVGen = Wire(Vec(LoadPipelineWidth, Bool()))
398  (0 until LoadPipelineWidth).foreach(index => {
399    loadWbSelGen(index) := (
400      if (LoadPipelineWidth > 1) Cat(loadRemSel(index), index.U(log2Ceil(LoadPipelineWidth).W))
401      else loadRemSel(index)
402    )
403    loadWbSelVGen(index) := Mux(io.ldout(index).fire, loadRemSelVecFire(index).asUInt.orR, loadRemSelVecNotFire(index).asUInt.orR)
404  })
405
406  (0 until LoadPipelineWidth).map(i => {
407    loadWbSel(i) := RegNext(loadWbSelGen(i))
408    loadWbSelV(i) := RegNext(loadWbSelVGen(i), init = false.B)
409    when(io.ldout(i).fire()){
410      // Mark them as writebacked, so they will not be selected in the next cycle
411      writebacked(loadWbSel(i)) := true.B
412    }
413  })
414
415  // Stage 1
416  // Use indexes generated in cycle 0 to read data
417  // writeback data to cdb
418  (0 until LoadPipelineWidth).map(i => {
419    // data select
420    dataModule.io.wb.raddr(i) := loadWbSelGen(i)
421    val rdata = dataModule.io.wb.rdata(i).data
422    val seluop = uop(loadWbSel(i))
423    val func = seluop.ctrl.fuOpType
424    val raddr = dataModule.io.wb.rdata(i).paddr
425    val rdataSel = LookupTree(raddr(2, 0), List(
426      "b000".U -> rdata(63, 0),
427      "b001".U -> rdata(63, 8),
428      "b010".U -> rdata(63, 16),
429      "b011".U -> rdata(63, 24),
430      "b100".U -> rdata(63, 32),
431      "b101".U -> rdata(63, 40),
432      "b110".U -> rdata(63, 48),
433      "b111".U -> rdata(63, 56)
434    ))
435    val rdataPartialLoad = rdataHelper(seluop, rdataSel)
436
437    // writeback missed int/fp load
438    //
439    // Int load writeback will finish (if not blocked) in one cycle
440    io.ldout(i).bits.uop := seluop
441    io.ldout(i).bits.uop.lqIdx := loadWbSel(i).asTypeOf(new LqPtr)
442    io.ldout(i).bits.data := rdataPartialLoad
443    io.ldout(i).bits.redirectValid := false.B
444    io.ldout(i).bits.redirect := DontCare
445    io.ldout(i).bits.debug.isMMIO := debug_mmio(loadWbSel(i))
446    io.ldout(i).bits.debug.isPerfCnt := false.B
447    io.ldout(i).bits.debug.paddr := debug_paddr(loadWbSel(i))
448    io.ldout(i).bits.debug.vaddr := vaddrModule.io.rdata(i+1)
449    io.ldout(i).bits.fflags := DontCare
450    io.ldout(i).valid := loadWbSelV(i)
451
452    when(io.ldout(i).fire()) {
453      XSInfo("int load miss write to cbd robidx %d lqidx %d pc 0x%x mmio %x\n",
454        io.ldout(i).bits.uop.robIdx.asUInt,
455        io.ldout(i).bits.uop.lqIdx.asUInt,
456        io.ldout(i).bits.uop.cf.pc,
457        debug_mmio(loadWbSel(i))
458      )
459    }
460
461  })
462
463  /**
464    * Load commits
465    *
466    * When load commited, mark it as !allocated and move deqPtrExt forward.
467    */
468  (0 until CommitWidth).map(i => {
469    when(commitCount > i.U){
470      allocated((deqPtrExt+i.U).value) := false.B
471      XSError(!allocated((deqPtrExt+i.U).value), s"why commit invalid entry $i?\n")
472    }
473  })
474
475  def getFirstOne(mask: Vec[Bool], startMask: UInt) = {
476    val length = mask.length
477    val highBits = (0 until length).map(i => mask(i) & ~startMask(i))
478    val highBitsUint = Cat(highBits.reverse)
479    PriorityEncoder(Mux(highBitsUint.orR(), highBitsUint, mask.asUInt))
480  }
481
482  def getOldest[T <: XSBundleWithMicroOp](valid: Seq[Bool], bits: Seq[T]): (Seq[Bool], Seq[T]) = {
483    assert(valid.length == bits.length)
484    assert(isPow2(valid.length))
485    if (valid.length == 1) {
486      (valid, bits)
487    } else if (valid.length == 2) {
488      val res = Seq.fill(2)(Wire(ValidIO(chiselTypeOf(bits(0)))))
489      for (i <- res.indices) {
490        res(i).valid := valid(i)
491        res(i).bits := bits(i)
492      }
493      val oldest = Mux(valid(0) && valid(1), Mux(isAfter(bits(0).uop.robIdx, bits(1).uop.robIdx), res(1), res(0)), Mux(valid(0) && !valid(1), res(0), res(1)))
494      (Seq(oldest.valid), Seq(oldest.bits))
495    } else {
496      val left = getOldest(valid.take(valid.length / 2), bits.take(valid.length / 2))
497      val right = getOldest(valid.takeRight(valid.length / 2), bits.takeRight(valid.length / 2))
498      getOldest(left._1 ++ right._1, left._2 ++ right._2)
499    }
500  }
501
502  def getAfterMask(valid: Seq[Bool], uop: Seq[MicroOp]) = {
503    assert(valid.length == uop.length)
504    val length = valid.length
505    (0 until length).map(i => {
506      (0 until length).map(j => {
507        Mux(valid(i) && valid(j),
508          isAfter(uop(i).robIdx, uop(j).robIdx),
509          Mux(!valid(i), true.B, false.B))
510      })
511    })
512  }
513
514  /**
515    * Store-Load Memory violation detection
516    *
517    * When store writes back, it searches LoadQueue for younger load instructions
518    * with the same load physical address. They loaded wrong data and need re-execution.
519    *
520    * Cycle 0: Store Writeback
521    *   Generate match vector for store address with rangeMask(stPtr, enqPtr).
522    *   Besides, load instructions in LoadUnit_S1 and S2 are also checked.
523    * Cycle 1: Redirect Generation
524    *   There're three possible types of violations, up to 6 possible redirect requests.
525    *   Choose the oldest load (part 1). (4 + 2) -> (1 + 2)
526    * Cycle 2: Redirect Fire
527    *   Choose the oldest load (part 2). (3 -> 1)
528    *   Prepare redirect request according to the detected violation.
529    *   Fire redirect request (if valid)
530    */
531
532  // stage 0:        lq l1 wb     l1 wb lq
533  //                 |  |  |      |  |  |  (paddr match)
534  // stage 1:        lq l1 wb     l1 wb lq
535  //                 |  |  |      |  |  |
536  //                 |  |------------|  |
537  //                 |        |         |
538  // stage 2:        lq      l1wb       lq
539  //                 |        |         |
540  //                 --------------------
541  //                          |
542  //                      rollback req
543  io.load_s1 := DontCare
544  def detectRollback(i: Int) = {
545    val startIndex = io.storeIn(i).bits.uop.lqIdx.value
546    val lqIdxMask = UIntToMask(startIndex, LoadQueueSize)
547    val xorMask = lqIdxMask ^ enqMask
548    val sameFlag = io.storeIn(i).bits.uop.lqIdx.flag === enqPtrExt(0).flag
549    val stToEnqPtrMask = Mux(sameFlag, xorMask, ~xorMask)
550
551    // check if load already in lq needs to be rolledback
552    dataModule.io.violation(i).paddr := io.storeIn(i).bits.paddr
553    dataModule.io.violation(i).mask := io.storeIn(i).bits.mask
554    val addrMaskMatch = RegNext(dataModule.io.violation(i).violationMask)
555    val entryNeedCheck = RegNext(VecInit((0 until LoadQueueSize).map(j => {
556      allocated(j) && stToEnqPtrMask(j) && (datavalid(j) || miss(j))
557    })))
558    val lqViolationVec = VecInit((0 until LoadQueueSize).map(j => {
559      addrMaskMatch(j) && entryNeedCheck(j)
560    }))
561    val lqViolation = lqViolationVec.asUInt().orR()
562    val lqViolationIndex = getFirstOne(lqViolationVec, RegNext(lqIdxMask))
563    val lqViolationUop = uop(lqViolationIndex)
564    // lqViolationUop.lqIdx.flag := deqMask(lqViolationIndex) ^ deqPtrExt.flag
565    // lqViolationUop.lqIdx.value := lqViolationIndex
566    XSDebug(lqViolation, p"${Binary(Cat(lqViolationVec))}, $startIndex, $lqViolationIndex\n")
567
568    // when l/s writeback to rob together, check if rollback is needed
569    val wbViolationVec = RegNext(VecInit((0 until LoadPipelineWidth).map(j => {
570      io.loadIn(j).valid &&
571      isAfter(io.loadIn(j).bits.uop.robIdx, io.storeIn(i).bits.uop.robIdx) &&
572      io.storeIn(i).bits.paddr(PAddrBits - 1, 3) === io.loadIn(j).bits.paddr(PAddrBits - 1, 3) &&
573      (io.storeIn(i).bits.mask & io.loadIn(j).bits.mask).orR
574    })))
575    val wbViolation = wbViolationVec.asUInt().orR() && RegNext(io.storeIn(i).valid && !io.storeIn(i).bits.miss)
576    val wbViolationUop = getOldest(wbViolationVec, RegNext(VecInit(io.loadIn.map(_.bits))))._2(0).uop
577    XSDebug(wbViolation, p"${Binary(Cat(wbViolationVec))}, $wbViolationUop\n")
578
579    // check if rollback is needed for load in l1
580    val l1ViolationVec = RegNext(VecInit((0 until LoadPipelineWidth).map(j => {
581      io.load_s1(j).valid && // L1 valid
582      isAfter(io.load_s1(j).uop.robIdx, io.storeIn(i).bits.uop.robIdx) &&
583      io.storeIn(i).bits.paddr(PAddrBits - 1, 3) === io.load_s1(j).paddr(PAddrBits - 1, 3) &&
584      (io.storeIn(i).bits.mask & io.load_s1(j).mask).orR
585    })))
586    val l1Violation = l1ViolationVec.asUInt().orR() && RegNext(io.storeIn(i).valid && !io.storeIn(i).bits.miss)
587    val load_s1 = Wire(Vec(LoadPipelineWidth, new XSBundleWithMicroOp))
588    (0 until LoadPipelineWidth).foreach(i => load_s1(i).uop := io.load_s1(i).uop)
589    val l1ViolationUop = getOldest(l1ViolationVec, RegNext(load_s1))._2(0).uop
590    XSDebug(l1Violation, p"${Binary(Cat(l1ViolationVec))}, $l1ViolationUop\n")
591
592    XSDebug(
593      l1Violation,
594      "need rollback (l1 load) pc %x robidx %d target %x\n",
595      io.storeIn(i).bits.uop.cf.pc, io.storeIn(i).bits.uop.robIdx.asUInt, l1ViolationUop.robIdx.asUInt
596    )
597    XSDebug(
598      lqViolation,
599      "need rollback (ld wb before store) pc %x robidx %d target %x\n",
600      io.storeIn(i).bits.uop.cf.pc, io.storeIn(i).bits.uop.robIdx.asUInt, lqViolationUop.robIdx.asUInt
601    )
602    XSDebug(
603      wbViolation,
604      "need rollback (ld/st wb together) pc %x robidx %d target %x\n",
605      io.storeIn(i).bits.uop.cf.pc, io.storeIn(i).bits.uop.robIdx.asUInt, wbViolationUop.robIdx.asUInt
606    )
607
608    ((lqViolation, lqViolationUop), (wbViolation, wbViolationUop), (l1Violation, l1ViolationUop))
609  }
610
611  def rollbackSel(a: Valid[MicroOpRbExt], b: Valid[MicroOpRbExt]): ValidIO[MicroOpRbExt] = {
612    Mux(
613      a.valid,
614      Mux(
615        b.valid,
616        Mux(isAfter(a.bits.uop.robIdx, b.bits.uop.robIdx), b, a), // a,b both valid, sel oldest
617        a // sel a
618      ),
619      b // sel b
620    )
621  }
622  val lastCycleRedirect = RegNext(io.brqRedirect)
623  val lastlastCycleRedirect = RegNext(lastCycleRedirect)
624
625  // S2: select rollback (part1) and generate rollback request
626  // rollback check
627  // Wb/L1 rollback seq check is done in s2
628  val rollbackWb = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt)))
629  val rollbackL1 = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt)))
630  val rollbackL1Wb = Wire(Vec(StorePipelineWidth*2, Valid(new MicroOpRbExt)))
631  // Lq rollback seq check is done in s3 (next stage), as getting rollbackLq MicroOp is slow
632  val rollbackLq = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt)))
633  // store ftq index for store set update
634  val stFtqIdxS2 = Wire(Vec(StorePipelineWidth, new FtqPtr))
635  val stFtqOffsetS2 = Wire(Vec(StorePipelineWidth, UInt(log2Up(PredictWidth).W)))
636  for (i <- 0 until StorePipelineWidth) {
637    val detectedRollback = detectRollback(i)
638    rollbackLq(i).valid := detectedRollback._1._1 && RegNext(io.storeIn(i).valid)
639    rollbackLq(i).bits.uop := detectedRollback._1._2
640    rollbackLq(i).bits.flag := i.U
641    rollbackWb(i).valid := detectedRollback._2._1 && RegNext(io.storeIn(i).valid)
642    rollbackWb(i).bits.uop := detectedRollback._2._2
643    rollbackWb(i).bits.flag := i.U
644    rollbackL1(i).valid := detectedRollback._3._1 && RegNext(io.storeIn(i).valid)
645    rollbackL1(i).bits.uop := detectedRollback._3._2
646    rollbackL1(i).bits.flag := i.U
647    rollbackL1Wb(2*i) := rollbackL1(i)
648    rollbackL1Wb(2*i+1) := rollbackWb(i)
649    stFtqIdxS2(i) := RegNext(io.storeIn(i).bits.uop.cf.ftqPtr)
650    stFtqOffsetS2(i) := RegNext(io.storeIn(i).bits.uop.cf.ftqOffset)
651  }
652
653  val rollbackL1WbSelected = ParallelOperation(rollbackL1Wb, rollbackSel)
654  val rollbackL1WbVReg = RegNext(rollbackL1WbSelected.valid)
655  val rollbackL1WbReg = RegEnable(rollbackL1WbSelected.bits, rollbackL1WbSelected.valid)
656  val rollbackLqVReg = rollbackLq.map(x => RegNext(x.valid))
657  val rollbackLqReg = rollbackLq.map(x => RegEnable(x.bits, x.valid))
658
659  // S3: select rollback (part2), generate rollback request, then fire rollback request
660  // Note that we use robIdx - 1.U to flush the load instruction itself.
661  // Thus, here if last cycle's robIdx equals to this cycle's robIdx, it still triggers the redirect.
662
663  val rollbackValidVec = rollbackL1WbVReg +: rollbackLqVReg
664  val rollbackUopExtVec = rollbackL1WbReg +: rollbackLqReg
665
666  // select uop in parallel
667  val mask = getAfterMask(rollbackValidVec, rollbackUopExtVec.map(i => i.uop))
668  val lqs = getOldest(rollbackLqVReg, rollbackLqReg)
669  val rollbackUopExt = getOldest(lqs._1 :+ rollbackL1WbVReg, lqs._2 :+ rollbackL1WbReg)._2(0)
670  val stFtqIdxS3 = RegNext(stFtqIdxS2)
671  val stFtqOffsetS3 = RegNext(stFtqOffsetS2)
672  val rollbackUop = rollbackUopExt.uop
673  val rollbackStFtqIdx = stFtqIdxS3(rollbackUopExt.flag)
674  val rollbackStFtqOffset = stFtqOffsetS3(rollbackUopExt.flag)
675
676  // check if rollback request is still valid in parallel
677  val rollbackValidVecChecked = Wire(Vec(LoadPipelineWidth + 1, Bool()))
678  for(((v, uop), idx) <- rollbackValidVec.zip(rollbackUopExtVec.map(i => i.uop)).zipWithIndex) {
679    rollbackValidVecChecked(idx) := v &&
680      (!lastCycleRedirect.valid || isBefore(uop.robIdx, lastCycleRedirect.bits.robIdx)) &&
681      (!lastlastCycleRedirect.valid || isBefore(uop.robIdx, lastlastCycleRedirect.bits.robIdx))
682  }
683
684  io.rollback.bits.robIdx := rollbackUop.robIdx
685  io.rollback.bits.ftqIdx := rollbackUop.cf.ftqPtr
686  io.rollback.bits.stFtqIdx := rollbackStFtqIdx
687  io.rollback.bits.ftqOffset := rollbackUop.cf.ftqOffset
688  io.rollback.bits.stFtqOffset := rollbackStFtqOffset
689  io.rollback.bits.level := RedirectLevel.flush
690  io.rollback.bits.interrupt := DontCare
691  io.rollback.bits.cfiUpdate := DontCare
692  io.rollback.bits.cfiUpdate.target := rollbackUop.cf.pc
693  io.rollback.bits.debug_runahead_checkpoint_id := rollbackUop.debugInfo.runahead_checkpoint_id
694  // io.rollback.bits.pc := DontCare
695
696  io.rollback.valid := rollbackValidVecChecked.asUInt.orR
697
698  when(io.rollback.valid) {
699    // XSDebug("Mem rollback: pc %x robidx %d\n", io.rollback.bits.cfi, io.rollback.bits.robIdx.asUInt)
700  }
701
702  /**
703  * Load-Load Memory violation detection
704  *
705  * When load arrives load_s1, it searches LoadQueue for younger load instructions
706  * with the same load physical address. If younger load has been released (or observed),
707  * the younger load needs to be re-execed.
708  *
709  * For now, if re-exec it found to be needed in load_s1, we mark the older load as replayInst,
710  * the two loads will be replayed if the older load becomes the head of rob.
711  *
712  * When dcache releases a line, mark all writebacked entrys in load queue with
713  * the same line paddr as released.
714  */
715
716  // Load-Load Memory violation query
717  val deqRightMask = UIntToMask.rightmask(deqPtr, LoadQueueSize)
718  (0 until LoadPipelineWidth).map(i => {
719    dataModule.io.release_violation(i).paddr := io.loadViolationQuery(i).req.bits.paddr
720    io.loadViolationQuery(i).req.ready := true.B
721    io.loadViolationQuery(i).resp.valid := RegNext(io.loadViolationQuery(i).req.fire())
722    // Generate real violation mask
723    // Note that we use UIntToMask.rightmask here
724    val startIndex = io.loadViolationQuery(i).req.bits.uop.lqIdx.value
725    val lqIdxMask = UIntToMask(startIndex, LoadQueueSize)
726    val xorMask = lqIdxMask ^ enqMask
727    val sameFlag = io.loadViolationQuery(i).req.bits.uop.lqIdx.flag === enqPtrExt(0).flag
728    val ldToEnqPtrMask = Mux(sameFlag, xorMask, ~xorMask)
729    val ldld_violation_mask_gen_1 = WireInit(VecInit((0 until LoadQueueSize).map(j => {
730      ldToEnqPtrMask(j) && // the load is younger than current load
731      allocated(j) && // entry is valid
732      released(j) && // cacheline is released
733      (datavalid(j) || miss(j)) // paddr is valid
734    })))
735    val ldld_violation_mask_gen_2 = WireInit(VecInit((0 until LoadQueueSize).map(j => {
736      dataModule.io.release_violation(i).match_mask(j)// addr match
737      // addr match result is slow to generate, we RegNext() it
738    })))
739    val ldld_violation_mask = RegNext(ldld_violation_mask_gen_1).asUInt & RegNext(ldld_violation_mask_gen_2).asUInt
740    dontTouch(ldld_violation_mask)
741    ldld_violation_mask.suggestName("ldldViolationMask_" + i)
742    io.loadViolationQuery(i).resp.bits.have_violation := ldld_violation_mask.orR
743  })
744
745  // "released" flag update
746  //
747  // When io.release.valid (release1cycle.valid), it uses the last ld-ld paddr cam port to
748  // update release flag in 1 cycle
749
750  when(release1cycle.valid){
751    // Take over ld-ld paddr cam port
752    dataModule.io.release_violation.takeRight(1)(0).paddr := release1cycle.bits.paddr
753    io.loadViolationQuery.takeRight(1)(0).req.ready := false.B
754  }
755
756  when(release2cycle.valid){
757    // If a load comes in that cycle, we can not judge if it has ld-ld violation
758    // We replay that load inst from RS
759    io.loadViolationQuery.map(i => i.req.ready :=
760      // use lsu side release2cycle_dup_lsu paddr for better timing
761      !i.req.bits.paddr(PAddrBits-1, DCacheLineOffset) === release2cycle_dup_lsu.bits.paddr(PAddrBits-1, DCacheLineOffset)
762    )
763    // io.loadViolationQuery.map(i => i.req.ready := false.B) // For better timing
764  }
765
766  (0 until LoadQueueSize).map(i => {
767    when(RegNext(dataModule.io.release_violation.takeRight(1)(0).match_mask(i) &&
768      allocated(i) &&
769      datavalid(i) &&
770      release1cycle.valid
771    )){
772      // Note: if a load has missed in dcache and is waiting for refill in load queue,
773      // its released flag still needs to be set as true if addr matches.
774      released(i) := true.B
775    }
776  })
777
778  /**
779    * Memory mapped IO / other uncached operations
780    *
781    * States:
782    * (1) writeback from store units: mark as pending
783    * (2) when they reach ROB's head, they can be sent to uncache channel
784    * (3) response from uncache channel: mark as datavalid
785    * (4) writeback to ROB (and other units): mark as writebacked
786    * (5) ROB commits the instruction: same as normal instructions
787    */
788  //(2) when they reach ROB's head, they can be sent to uncache channel
789  val lqTailMmioPending = WireInit(pending(deqPtr))
790  val lqTailAllocated = WireInit(allocated(deqPtr))
791  val s_idle :: s_req :: s_resp :: s_wait :: Nil = Enum(4)
792  val uncacheState = RegInit(s_idle)
793  switch(uncacheState) {
794    is(s_idle) {
795      when(RegNext(io.rob.pendingld && lqTailMmioPending && lqTailAllocated)) {
796        uncacheState := s_req
797      }
798    }
799    is(s_req) {
800      when(io.uncache.req.fire()) {
801        uncacheState := s_resp
802      }
803    }
804    is(s_resp) {
805      when(io.uncache.resp.fire()) {
806        uncacheState := s_wait
807      }
808    }
809    is(s_wait) {
810      when(RegNext(io.rob.commit)) {
811        uncacheState := s_idle // ready for next mmio
812      }
813    }
814  }
815  io.uncache.req.valid := uncacheState === s_req
816
817  dataModule.io.uncache.raddr := deqPtrExtNext.value
818
819  io.uncache.req.bits.cmd  := MemoryOpConstants.M_XRD
820  io.uncache.req.bits.addr := dataModule.io.uncache.rdata.paddr
821  io.uncache.req.bits.data := dataModule.io.uncache.rdata.data
822  io.uncache.req.bits.mask := dataModule.io.uncache.rdata.mask
823
824  io.uncache.req.bits.id   := DontCare
825  io.uncache.req.bits.instrtype := DontCare
826
827  io.uncache.resp.ready := true.B
828
829  when (io.uncache.req.fire()) {
830    pending(deqPtr) := false.B
831
832    XSDebug("uncache req: pc %x addr %x data %x op %x mask %x\n",
833      uop(deqPtr).cf.pc,
834      io.uncache.req.bits.addr,
835      io.uncache.req.bits.data,
836      io.uncache.req.bits.cmd,
837      io.uncache.req.bits.mask
838    )
839  }
840
841  // (3) response from uncache channel: mark as datavalid
842  dataModule.io.uncache.wen := false.B
843  when(io.uncache.resp.fire()){
844    datavalid(deqPtr) := true.B
845    dataModule.io.uncacheWrite(deqPtr, io.uncache.resp.bits.data(XLEN-1, 0))
846    dataModule.io.uncache.wen := true.B
847
848    XSDebug("uncache resp: data %x\n", io.refill.bits.data)
849  }
850
851  // Read vaddr for mem exception
852  // no inst will be commited 1 cycle before tval update
853  vaddrModule.io.raddr(0) := (deqPtrExt + commitCount).value
854  io.exceptionAddr.vaddr := vaddrModule.io.rdata(0)
855
856  // Read vaddr for debug
857  (0 until LoadPipelineWidth).map(i => {
858    vaddrModule.io.raddr(i+1) := loadWbSel(i)
859  })
860
861  (0 until LoadPipelineWidth).map(i => {
862    vaddrTriggerResultModule.io.raddr(i) := loadWbSelGen(i)
863    io.trigger(i).lqLoadAddrTriggerHitVec := Mux(
864      loadWbSelV(i),
865      vaddrTriggerResultModule.io.rdata(i),
866      VecInit(Seq.fill(3)(false.B))
867    )
868  })
869
870  // misprediction recovery / exception redirect
871  // invalidate lq term using robIdx
872  val needCancel = Wire(Vec(LoadQueueSize, Bool()))
873  for (i <- 0 until LoadQueueSize) {
874    needCancel(i) := uop(i).robIdx.needFlush(io.brqRedirect) && allocated(i)
875    when (needCancel(i)) {
876      allocated(i) := false.B
877    }
878  }
879
880  /**
881    * update pointers
882    */
883  val lastEnqCancel = PopCount(RegNext(VecInit(canEnqueue.zip(enqCancel).map(x => x._1 && x._2))))
884  val lastCycleCancelCount = PopCount(RegNext(needCancel))
885  val enqNumber = Mux(io.enq.canAccept && io.enq.sqCanAccept, PopCount(io.enq.req.map(_.valid)), 0.U)
886  when (lastCycleRedirect.valid) {
887    // we recover the pointers in the next cycle after redirect
888    enqPtrExt := VecInit(enqPtrExt.map(_ - (lastCycleCancelCount + lastEnqCancel)))
889  }.otherwise {
890    enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber))
891  }
892
893  deqPtrExtNext := deqPtrExt + commitCount
894  deqPtrExt := deqPtrExtNext
895
896  io.lqCancelCnt := RegNext(lastCycleCancelCount + lastEnqCancel)
897
898  /**
899    * misc
900    */
901  // perf counter
902  QueuePerf(LoadQueueSize, validCount, !allowEnqueue)
903  io.lqFull := !allowEnqueue
904  XSPerfAccumulate("rollback", io.rollback.valid) // rollback redirect generated
905  XSPerfAccumulate("mmioCycle", uncacheState =/= s_idle) // lq is busy dealing with uncache req
906  XSPerfAccumulate("mmioCnt", io.uncache.req.fire())
907  XSPerfAccumulate("refill", io.refill.valid)
908  XSPerfAccumulate("writeback_success", PopCount(VecInit(io.ldout.map(i => i.fire()))))
909  XSPerfAccumulate("writeback_blocked", PopCount(VecInit(io.ldout.map(i => i.valid && !i.ready))))
910  XSPerfAccumulate("utilization_miss", PopCount((0 until LoadQueueSize).map(i => allocated(i) && miss(i))))
911
912  val perfValidCount = RegNext(validCount)
913
914  val perfEvents = Seq(
915    ("rollback         ", io.rollback.valid),
916    ("mmioCycle        ", uncacheState =/= s_idle),
917    ("mmio_Cnt         ", io.uncache.req.fire()),
918    ("refill           ", io.refill.valid),
919    ("writeback_success", PopCount(VecInit(io.ldout.map(i => i.fire())))),
920    ("writeback_blocked", PopCount(VecInit(io.ldout.map(i => i.valid && !i.ready)))),
921    ("ltq_1_4_valid    ", (perfValidCount < (LoadQueueSize.U/4.U))),
922    ("ltq_2_4_valid    ", (perfValidCount > (LoadQueueSize.U/4.U)) & (perfValidCount <= (LoadQueueSize.U/2.U))),
923    ("ltq_3_4_valid    ", (perfValidCount > (LoadQueueSize.U/2.U)) & (perfValidCount <= (LoadQueueSize.U*3.U/4.U))),
924    ("ltq_4_4_valid    ", (perfValidCount > (LoadQueueSize.U*3.U/4.U)))
925  )
926  generatePerfEvent()
927
928  // debug info
929  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt.flag, deqPtr)
930
931  def PrintFlag(flag: Bool, name: String): Unit = {
932    when(flag) {
933      XSDebug(false, true.B, name)
934    }.otherwise {
935      XSDebug(false, true.B, " ")
936    }
937  }
938
939  for (i <- 0 until LoadQueueSize) {
940    XSDebug(i + " pc %x pa %x ", uop(i).cf.pc, debug_paddr(i))
941    PrintFlag(allocated(i), "a")
942    PrintFlag(allocated(i) && datavalid(i), "v")
943    PrintFlag(allocated(i) && writebacked(i), "w")
944    PrintFlag(allocated(i) && miss(i), "m")
945    PrintFlag(allocated(i) && pending(i), "p")
946    XSDebug(false, true.B, "\n")
947  }
948
949}
950