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