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