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