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