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