xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/LoadQueue.scala (revision a1ea7f76add43b40af78084f7f646a0010120cd7)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.mem
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import xiangshan._
24import xiangshan.cache._
25import xiangshan.cache.{DCacheLineIO, DCacheWordIO, MemoryOpConstants}
26import xiangshan.cache.mmu.TlbRequestIO
27import xiangshan.mem._
28import xiangshan.backend.roq.RoqLsqIO
29import xiangshan.backend.fu.HasExceptionNO
30import xiangshan.frontend.FtqPtr
31import xiangshan.backend.fu.fpu.FPU
32
33
34class LqPtr(implicit p: Parameters) extends CircularQueuePtr[LqPtr](
35  p => p(XSCoreParamsKey).LoadQueueSize
36){
37  override def cloneType = (new LqPtr).asInstanceOf[this.type]
38}
39
40object LqPtr {
41  def apply(f: Bool, v: UInt)(implicit p: Parameters): LqPtr = {
42    val ptr = Wire(new LqPtr)
43    ptr.flag := f
44    ptr.value := v
45    ptr
46  }
47}
48
49trait HasLoadHelper { this: XSModule =>
50  def rdataHelper(uop: MicroOp, rdata: UInt): UInt = {
51    val fpWen = uop.ctrl.fpWen
52    LookupTree(uop.ctrl.fuOpType, List(
53      LSUOpType.lb   -> SignExt(rdata(7, 0) , XLEN),
54      LSUOpType.lh   -> SignExt(rdata(15, 0), XLEN),
55      /*
56          riscv-spec-20191213: 12.2 NaN Boxing of Narrower Values
57          Any operation that writes a narrower result to an f register must write
58          all 1s to the uppermost FLEN−n bits to yield a legal NaN-boxed value.
59      */
60      LSUOpType.lw   -> Mux(fpWen, FPU.box(rdata, FPU.S), SignExt(rdata(31, 0), XLEN)),
61      LSUOpType.ld   -> Mux(fpWen, FPU.box(rdata, FPU.D), SignExt(rdata(63, 0), XLEN)),
62      LSUOpType.lbu  -> ZeroExt(rdata(7, 0) , XLEN),
63      LSUOpType.lhu  -> ZeroExt(rdata(15, 0), XLEN),
64      LSUOpType.lwu  -> ZeroExt(rdata(31, 0), XLEN),
65    ))
66  }
67}
68
69class LqEnqIO(implicit p: Parameters) extends XSBundle {
70  val canAccept = Output(Bool())
71  val sqCanAccept = Input(Bool())
72  val needAlloc = Vec(RenameWidth, Input(Bool()))
73  val req = Vec(RenameWidth, Flipped(ValidIO(new MicroOp)))
74  val resp = Vec(RenameWidth, Output(new LqPtr))
75}
76
77// Load Queue
78class LoadQueue(implicit p: Parameters) extends XSModule
79  with HasDCacheParameters
80  with HasCircularQueuePtrHelper
81  with HasLoadHelper
82  with HasExceptionNO
83{
84  val io = IO(new Bundle() {
85    val enq = new LqEnqIO
86    val brqRedirect = Flipped(ValidIO(new Redirect))
87    val flush = Input(Bool())
88    val loadIn = Vec(LoadPipelineWidth, Flipped(Valid(new LsPipelineBundle)))
89    val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle)))
90    val loadDataForwarded = Vec(LoadPipelineWidth, Input(Bool()))
91    val needReplayFromRS = Vec(LoadPipelineWidth, Input(Bool()))
92    val ldout = Vec(2, DecoupledIO(new ExuOutput)) // writeback int load
93    val load_s1 = Vec(LoadPipelineWidth, Flipped(new PipeLoadForwardQueryIO))
94    val roq = Flipped(new RoqLsqIO)
95    val rollback = Output(Valid(new Redirect)) // replay now starts from load instead of store
96    val dcache = Flipped(ValidIO(new Refill))
97    val uncache = new DCacheWordIO
98    val exceptionAddr = new ExceptionAddrIO
99    val lqFull = Output(Bool())
100  })
101
102  println("LoadQueue: size:" + LoadQueueSize)
103
104  val uop = Reg(Vec(LoadQueueSize, new MicroOp))
105  // val data = Reg(Vec(LoadQueueSize, new LsRoqEntry))
106  val dataModule = Module(new LoadQueueData(LoadQueueSize, wbNumRead = LoadPipelineWidth, wbNumWrite = LoadPipelineWidth))
107  dataModule.io := DontCare
108  val vaddrModule = Module(new SyncDataModuleTemplate(UInt(VAddrBits.W), LoadQueueSize, numRead = 1, numWrite = LoadPipelineWidth))
109  vaddrModule.io := DontCare
110  val allocated = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // lq entry has been allocated
111  val datavalid = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // data is valid
112  val writebacked = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // inst has been writebacked to CDB
113  val miss = Reg(Vec(LoadQueueSize, Bool())) // load inst missed, waiting for miss queue to accept miss request
114  // val listening = Reg(Vec(LoadQueueSize, Bool())) // waiting for refill result
115  val pending = Reg(Vec(LoadQueueSize, Bool())) // mmio pending: inst is an mmio inst, it will not be executed until it reachs the end of roq
116  val refilling = WireInit(VecInit(List.fill(LoadQueueSize)(false.B))) // inst has been writebacked to CDB
117
118  val debug_mmio = Reg(Vec(LoadQueueSize, Bool())) // mmio: inst is an mmio inst
119  val debug_paddr = Reg(Vec(LoadQueueSize, UInt(PAddrBits.W))) // mmio: inst is an mmio inst
120
121  val enqPtrExt = RegInit(VecInit((0 until RenameWidth).map(_.U.asTypeOf(new LqPtr))))
122  val deqPtrExt = RegInit(0.U.asTypeOf(new LqPtr))
123  val deqPtrExtNext = Wire(new LqPtr)
124  val allowEnqueue = RegInit(true.B)
125
126  val enqPtr = enqPtrExt(0).value
127  val deqPtr = deqPtrExt.value
128
129  val deqMask = UIntToMask(deqPtr, LoadQueueSize)
130  val enqMask = UIntToMask(enqPtr, LoadQueueSize)
131
132  val commitCount = RegNext(io.roq.lcommit)
133
134  /**
135    * Enqueue at dispatch
136    *
137    * Currently, LoadQueue only allows enqueue when #emptyEntries > RenameWidth(EnqWidth)
138    */
139  io.enq.canAccept := allowEnqueue
140
141  for (i <- 0 until RenameWidth) {
142    val offset = if (i == 0) 0.U else PopCount(io.enq.needAlloc.take(i))
143    val lqIdx = enqPtrExt(offset)
144    val index = lqIdx.value
145    when (io.enq.req(i).valid && io.enq.canAccept && io.enq.sqCanAccept && !(io.brqRedirect.valid || io.flush)) {
146      uop(index) := io.enq.req(i).bits
147      allocated(index) := true.B
148      datavalid(index) := false.B
149      writebacked(index) := false.B
150      miss(index) := false.B
151      // listening(index) := false.B
152      pending(index) := false.B
153    }
154    io.enq.resp(i) := lqIdx
155  }
156  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
157
158  /**
159    * Writeback load from load units
160    *
161    * Most load instructions writeback to regfile at the same time.
162    * However,
163    *   (1) For an mmio instruction with exceptions, it writes back to ROB immediately.
164    *   (2) For an mmio instruction without exceptions, it does not write back.
165    * The mmio instruction will be sent to lower level when it reaches ROB's head.
166    * After uncache response, it will write back through arbiter with loadUnit.
167    *   (3) For cache misses, it is marked miss and sent to dcache later.
168    * After cache refills, it will write back through arbiter with loadUnit.
169    */
170  for (i <- 0 until LoadPipelineWidth) {
171    dataModule.io.wb.wen(i) := false.B
172    val loadWbIndex = io.loadIn(i).bits.uop.lqIdx.value
173    when(io.loadIn(i).fire()) {
174      when(io.loadIn(i).bits.miss) {
175        XSInfo(io.loadIn(i).valid, "load miss write to lq idx %d pc 0x%x vaddr %x paddr %x data %x mask %x forwardData %x forwardMask: %x mmio %x\n",
176          io.loadIn(i).bits.uop.lqIdx.asUInt,
177          io.loadIn(i).bits.uop.cf.pc,
178          io.loadIn(i).bits.vaddr,
179          io.loadIn(i).bits.paddr,
180          io.loadIn(i).bits.data,
181          io.loadIn(i).bits.mask,
182          io.loadIn(i).bits.forwardData.asUInt,
183          io.loadIn(i).bits.forwardMask.asUInt,
184          io.loadIn(i).bits.mmio
185        )
186      }.otherwise {
187        XSInfo(io.loadIn(i).valid, "load hit write to cbd lqidx %d pc 0x%x vaddr %x paddr %x data %x mask %x forwardData %x forwardMask: %x mmio %x\n",
188        io.loadIn(i).bits.uop.lqIdx.asUInt,
189        io.loadIn(i).bits.uop.cf.pc,
190        io.loadIn(i).bits.vaddr,
191        io.loadIn(i).bits.paddr,
192        io.loadIn(i).bits.data,
193        io.loadIn(i).bits.mask,
194        io.loadIn(i).bits.forwardData.asUInt,
195        io.loadIn(i).bits.forwardMask.asUInt,
196        io.loadIn(i).bits.mmio
197      )}
198      datavalid(loadWbIndex) := (!io.loadIn(i).bits.miss || io.loadDataForwarded(i)) &&
199        !io.loadIn(i).bits.mmio && // mmio data is not valid until we finished uncache access
200        !io.needReplayFromRS(i) // do not writeback if that inst will be resend from rs
201      writebacked(loadWbIndex) := !io.loadIn(i).bits.miss && !io.loadIn(i).bits.mmio
202
203      val loadWbData = Wire(new LQDataEntry)
204      loadWbData.paddr := io.loadIn(i).bits.paddr
205      loadWbData.mask := io.loadIn(i).bits.mask
206      loadWbData.data := io.loadIn(i).bits.forwardData.asUInt // fwd data
207      loadWbData.fwdMask := io.loadIn(i).bits.forwardMask
208      dataModule.io.wbWrite(i, loadWbIndex, loadWbData)
209      dataModule.io.wb.wen(i) := true.B
210
211
212      debug_mmio(loadWbIndex) := io.loadIn(i).bits.mmio
213      debug_paddr(loadWbIndex) := io.loadIn(i).bits.paddr
214
215      val dcacheMissed = io.loadIn(i).bits.miss && !io.loadIn(i).bits.mmio
216      miss(loadWbIndex) := dcacheMissed && !io.loadDataForwarded(i) && !io.needReplayFromRS(i)
217      pending(loadWbIndex) := io.loadIn(i).bits.mmio
218      uop(loadWbIndex).debugInfo.issueTime := io.loadIn(i).bits.uop.debugInfo.issueTime
219    }
220    // vaddrModule write is delayed, as vaddrModule will not be read right after write
221    vaddrModule.io.waddr(i) := RegNext(loadWbIndex)
222    vaddrModule.io.wdata(i) := RegNext(io.loadIn(i).bits.vaddr)
223    vaddrModule.io.wen(i) := RegNext(io.loadIn(i).fire())
224  }
225
226  when(io.dcache.valid) {
227    XSDebug("miss resp: paddr:0x%x data %x\n", io.dcache.bits.addr, io.dcache.bits.data)
228  }
229
230  // Refill 64 bit in a cycle
231  // Refill data comes back from io.dcache.resp
232  dataModule.io.refill.valid := io.dcache.valid
233  dataModule.io.refill.paddr := io.dcache.bits.addr
234  dataModule.io.refill.data := io.dcache.bits.data
235
236  (0 until LoadQueueSize).map(i => {
237    dataModule.io.refill.refillMask(i) := allocated(i) && miss(i)
238    when(dataModule.io.refill.valid && dataModule.io.refill.refillMask(i) && dataModule.io.refill.matchMask(i)) {
239      datavalid(i) := true.B
240      miss(i) := false.B
241      refilling(i) := true.B
242    }
243  })
244
245  // Writeback up to 2 missed load insts to CDB
246  //
247  // Pick 2 missed load (data refilled), write them back to cdb
248  // 2 refilled load will be selected from even/odd entry, separately
249
250  // Stage 0
251  // Generate writeback indexes
252
253  def getEvenBits(input: UInt): UInt = {
254    VecInit((0 until LoadQueueSize/2).map(i => {input(2*i)})).asUInt
255  }
256  def getOddBits(input: UInt): UInt = {
257    VecInit((0 until LoadQueueSize/2).map(i => {input(2*i+1)})).asUInt
258  }
259
260  val loadWbSel = Wire(Vec(LoadPipelineWidth, UInt(log2Up(LoadQueueSize).W))) // index selected last cycle
261  val loadWbSelV = Wire(Vec(LoadPipelineWidth, Bool())) // index selected in last cycle is valid
262
263  val loadWbSelVec = VecInit((0 until LoadQueueSize).map(i => {
264    allocated(i) && !writebacked(i) && (datavalid(i) || refilling(i))
265  })).asUInt() // use uint instead vec to reduce verilog lines
266  val evenDeqMask = getEvenBits(deqMask)
267  val oddDeqMask = getOddBits(deqMask)
268  // generate lastCycleSelect mask
269  val evenSelectMask = Mux(io.ldout(0).fire(), getEvenBits(UIntToOH(loadWbSel(0))), 0.U)
270  val oddSelectMask = Mux(io.ldout(1).fire(), getOddBits(UIntToOH(loadWbSel(1))), 0.U)
271  // generate real select vec
272  val loadEvenSelVec = getEvenBits(loadWbSelVec) & ~evenSelectMask
273  val loadOddSelVec = getOddBits(loadWbSelVec) & ~oddSelectMask
274
275  def toVec(a: UInt): Vec[Bool] = {
276    VecInit(a.asBools)
277  }
278
279  val loadWbSelGen = Wire(Vec(LoadPipelineWidth, UInt(log2Up(LoadQueueSize).W)))
280  val loadWbSelVGen = Wire(Vec(LoadPipelineWidth, Bool()))
281  loadWbSelGen(0) := Cat(getFirstOne(toVec(loadEvenSelVec), evenDeqMask), 0.U(1.W))
282  loadWbSelVGen(0):= loadEvenSelVec.asUInt.orR
283  loadWbSelGen(1) := Cat(getFirstOne(toVec(loadOddSelVec), oddDeqMask), 1.U(1.W))
284  loadWbSelVGen(1) := loadOddSelVec.asUInt.orR
285
286  (0 until LoadPipelineWidth).map(i => {
287    loadWbSel(i) := RegNext(loadWbSelGen(i))
288    loadWbSelV(i) := RegNext(loadWbSelVGen(i), init = false.B)
289    when(io.ldout(i).fire()){
290      // Mark them as writebacked, so they will not be selected in the next cycle
291      writebacked(loadWbSel(i)) := true.B
292    }
293  })
294
295  // Stage 1
296  // Use indexes generated in cycle 0 to read data
297  // writeback data to cdb
298  (0 until LoadPipelineWidth).map(i => {
299    // data select
300    dataModule.io.wb.raddr(i) := loadWbSelGen(i)
301    val rdata = dataModule.io.wb.rdata(i).data
302    val seluop = uop(loadWbSel(i))
303    val func = seluop.ctrl.fuOpType
304    val raddr = dataModule.io.wb.rdata(i).paddr
305    val rdataSel = LookupTree(raddr(2, 0), List(
306      "b000".U -> rdata(63, 0),
307      "b001".U -> rdata(63, 8),
308      "b010".U -> rdata(63, 16),
309      "b011".U -> rdata(63, 24),
310      "b100".U -> rdata(63, 32),
311      "b101".U -> rdata(63, 40),
312      "b110".U -> rdata(63, 48),
313      "b111".U -> rdata(63, 56)
314    ))
315    val rdataPartialLoad = rdataHelper(seluop, rdataSel)
316
317    // writeback missed int/fp load
318    //
319    // Int load writeback will finish (if not blocked) in one cycle
320    io.ldout(i).bits.uop := seluop
321    io.ldout(i).bits.uop.lqIdx := loadWbSel(i).asTypeOf(new LqPtr)
322    io.ldout(i).bits.data := rdataPartialLoad
323    io.ldout(i).bits.redirectValid := false.B
324    io.ldout(i).bits.redirect := DontCare
325    io.ldout(i).bits.debug.isMMIO := debug_mmio(loadWbSel(i))
326    io.ldout(i).bits.debug.isPerfCnt := false.B
327    io.ldout(i).bits.debug.paddr := debug_paddr(loadWbSel(i))
328    io.ldout(i).bits.fflags := DontCare
329    io.ldout(i).valid := loadWbSelV(i)
330
331    when(io.ldout(i).fire()) {
332      XSInfo("int load miss write to cbd roqidx %d lqidx %d pc 0x%x mmio %x\n",
333        io.ldout(i).bits.uop.roqIdx.asUInt,
334        io.ldout(i).bits.uop.lqIdx.asUInt,
335        io.ldout(i).bits.uop.cf.pc,
336        debug_mmio(loadWbSel(i))
337      )
338    }
339
340  })
341
342  /**
343    * Load commits
344    *
345    * When load commited, mark it as !allocated and move deqPtrExt forward.
346    */
347  (0 until CommitWidth).map(i => {
348    when(commitCount > i.U){
349      allocated((deqPtrExt+i.U).value) := false.B
350    }
351  })
352
353  def getFirstOne(mask: Vec[Bool], startMask: UInt) = {
354    val length = mask.length
355    val highBits = (0 until length).map(i => mask(i) & ~startMask(i))
356    val highBitsUint = Cat(highBits.reverse)
357    PriorityEncoder(Mux(highBitsUint.orR(), highBitsUint, mask.asUInt))
358  }
359
360  def getOldestInTwo(valid: Seq[Bool], uop: Seq[MicroOp]) = {
361    assert(valid.length == uop.length)
362    assert(valid.length == 2)
363    Mux(valid(0) && valid(1),
364      Mux(isAfter(uop(0).roqIdx, uop(1).roqIdx), uop(1), uop(0)),
365      Mux(valid(0) && !valid(1), uop(0), uop(1)))
366  }
367
368  def getAfterMask(valid: Seq[Bool], uop: Seq[MicroOp]) = {
369    assert(valid.length == uop.length)
370    val length = valid.length
371    (0 until length).map(i => {
372      (0 until length).map(j => {
373        Mux(valid(i) && valid(j),
374          isAfter(uop(i).roqIdx, uop(j).roqIdx),
375          Mux(!valid(i), true.B, false.B))
376      })
377    })
378  }
379
380  /**
381    * Memory violation detection
382    *
383    * When store writes back, it searches LoadQueue for younger load instructions
384    * with the same load physical address. They loaded wrong data and need re-execution.
385    *
386    * Cycle 0: Store Writeback
387    *   Generate match vector for store address with rangeMask(stPtr, enqPtr).
388    *   Besides, load instructions in LoadUnit_S1 and S2 are also checked.
389    * Cycle 1: Redirect Generation
390    *   There're three possible types of violations, up to 6 possible redirect requests.
391    *   Choose the oldest load (part 1). (4 + 2) -> (1 + 2)
392    * Cycle 2: Redirect Fire
393    *   Choose the oldest load (part 2). (3 -> 1)
394    *   Prepare redirect request according to the detected violation.
395    *   Fire redirect request (if valid)
396    */
397
398  // stage 0:        lq l1 wb     l1 wb lq
399  //                 |  |  |      |  |  |  (paddr match)
400  // stage 1:        lq l1 wb     l1 wb lq
401  //                 |  |  |      |  |  |
402  //                 |  |------------|  |
403  //                 |        |         |
404  // stage 2:        lq      l1wb       lq
405  //                 |        |         |
406  //                 --------------------
407  //                          |
408  //                      rollback req
409  io.load_s1 := DontCare
410  def detectRollback(i: Int) = {
411    val startIndex = io.storeIn(i).bits.uop.lqIdx.value
412    val lqIdxMask = UIntToMask(startIndex, LoadQueueSize)
413    val xorMask = lqIdxMask ^ enqMask
414    val sameFlag = io.storeIn(i).bits.uop.lqIdx.flag === enqPtrExt(0).flag
415    val toEnqPtrMask = Mux(sameFlag, xorMask, ~xorMask)
416
417    // check if load already in lq needs to be rolledback
418    dataModule.io.violation(i).paddr := io.storeIn(i).bits.paddr
419    dataModule.io.violation(i).mask := io.storeIn(i).bits.mask
420    val addrMaskMatch = RegNext(dataModule.io.violation(i).violationMask)
421    val entryNeedCheck = RegNext(VecInit((0 until LoadQueueSize).map(j => {
422      allocated(j) && toEnqPtrMask(j) && (datavalid(j) || miss(j))
423    })))
424    val lqViolationVec = VecInit((0 until LoadQueueSize).map(j => {
425      addrMaskMatch(j) && entryNeedCheck(j)
426    }))
427    val lqViolation = lqViolationVec.asUInt().orR()
428    val lqViolationIndex = getFirstOne(lqViolationVec, RegNext(lqIdxMask))
429    val lqViolationUop = uop(lqViolationIndex)
430    // lqViolationUop.lqIdx.flag := deqMask(lqViolationIndex) ^ deqPtrExt.flag
431    // lqViolationUop.lqIdx.value := lqViolationIndex
432    XSDebug(lqViolation, p"${Binary(Cat(lqViolationVec))}, $startIndex, $lqViolationIndex\n")
433
434    // when l/s writeback to roq together, check if rollback is needed
435    val wbViolationVec = RegNext(VecInit((0 until LoadPipelineWidth).map(j => {
436      io.loadIn(j).valid &&
437        isAfter(io.loadIn(j).bits.uop.roqIdx, io.storeIn(i).bits.uop.roqIdx) &&
438        io.storeIn(i).bits.paddr(PAddrBits - 1, 3) === io.loadIn(j).bits.paddr(PAddrBits - 1, 3) &&
439        (io.storeIn(i).bits.mask & io.loadIn(j).bits.mask).orR
440    })))
441    val wbViolation = wbViolationVec.asUInt().orR()
442    val wbViolationUop = getOldestInTwo(wbViolationVec, RegNext(VecInit(io.loadIn.map(_.bits.uop))))
443    XSDebug(wbViolation, p"${Binary(Cat(wbViolationVec))}, $wbViolationUop\n")
444
445    // check if rollback is needed for load in l1
446    val l1ViolationVec = RegNext(VecInit((0 until LoadPipelineWidth).map(j => {
447      io.load_s1(j).valid && // L1 valid
448        isAfter(io.load_s1(j).uop.roqIdx, io.storeIn(i).bits.uop.roqIdx) &&
449        io.storeIn(i).bits.paddr(PAddrBits - 1, 3) === io.load_s1(j).paddr(PAddrBits - 1, 3) &&
450        (io.storeIn(i).bits.mask & io.load_s1(j).mask).orR
451    })))
452    val l1Violation = l1ViolationVec.asUInt().orR()
453    val l1ViolationUop = getOldestInTwo(l1ViolationVec, RegNext(VecInit(io.load_s1.map(_.uop))))
454    XSDebug(l1Violation, p"${Binary(Cat(l1ViolationVec))}, $l1ViolationUop\n")
455
456    XSDebug(
457      l1Violation,
458      "need rollback (l1 load) pc %x roqidx %d target %x\n",
459      io.storeIn(i).bits.uop.cf.pc, io.storeIn(i).bits.uop.roqIdx.asUInt, l1ViolationUop.roqIdx.asUInt
460    )
461    XSDebug(
462      lqViolation,
463      "need rollback (ld wb before store) pc %x roqidx %d target %x\n",
464      io.storeIn(i).bits.uop.cf.pc, io.storeIn(i).bits.uop.roqIdx.asUInt, lqViolationUop.roqIdx.asUInt
465    )
466    XSDebug(
467      wbViolation,
468      "need rollback (ld/st wb together) pc %x roqidx %d target %x\n",
469      io.storeIn(i).bits.uop.cf.pc, io.storeIn(i).bits.uop.roqIdx.asUInt, wbViolationUop.roqIdx.asUInt
470    )
471
472    ((lqViolation, lqViolationUop), (wbViolation, wbViolationUop), (l1Violation, l1ViolationUop))
473  }
474
475  def rollbackSel(a: Valid[MicroOpRbExt], b: Valid[MicroOpRbExt]): ValidIO[MicroOpRbExt] = {
476    Mux(
477      a.valid,
478      Mux(
479        b.valid,
480        Mux(isAfter(a.bits.uop.roqIdx, b.bits.uop.roqIdx), b, a), // a,b both valid, sel oldest
481        a // sel a
482      ),
483      b // sel b
484    )
485  }
486  val lastCycleRedirect = RegNext(io.brqRedirect)
487  val lastlastCycleRedirect = RegNext(lastCycleRedirect)
488  val lastCycleFlush = RegNext(io.flush)
489  val lastlastCycleFlush = RegNext(lastCycleFlush)
490
491  // S2: select rollback (part1) and generate rollback request
492  // rollback check
493  // Wb/L1 rollback seq check is done in s2
494  val rollbackWb = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt)))
495  val rollbackL1 = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt)))
496  val rollbackL1Wb = Wire(Vec(StorePipelineWidth*2, Valid(new MicroOpRbExt)))
497  // Lq rollback seq check is done in s3 (next stage), as getting rollbackLq MicroOp is slow
498  val rollbackLq = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt)))
499  // store ftq index for store set update
500  val stFtqIdxS2 = Wire(Vec(StorePipelineWidth, new FtqPtr))
501  val stFtqOffsetS2 = Wire(Vec(StorePipelineWidth, UInt(log2Up(PredictWidth).W)))
502  for (i <- 0 until StorePipelineWidth) {
503    val detectedRollback = detectRollback(i)
504    rollbackLq(i).valid := detectedRollback._1._1 && RegNext(io.storeIn(i).valid)
505    rollbackLq(i).bits.uop := detectedRollback._1._2
506    rollbackLq(i).bits.flag := i.U
507    rollbackWb(i).valid := detectedRollback._2._1 && RegNext(io.storeIn(i).valid)
508    rollbackWb(i).bits.uop := detectedRollback._2._2
509    rollbackWb(i).bits.flag := i.U
510    rollbackL1(i).valid := detectedRollback._3._1 && RegNext(io.storeIn(i).valid)
511    rollbackL1(i).bits.uop := detectedRollback._3._2
512    rollbackL1(i).bits.flag := i.U
513    rollbackL1Wb(2*i) := rollbackL1(i)
514    rollbackL1Wb(2*i+1) := rollbackWb(i)
515    stFtqIdxS2(i) := RegNext(io.storeIn(i).bits.uop.cf.ftqPtr)
516    stFtqOffsetS2(i) := RegNext(io.storeIn(i).bits.uop.cf.ftqOffset)
517  }
518
519  val rollbackL1WbSelected = ParallelOperation(rollbackL1Wb, rollbackSel)
520  val rollbackL1WbVReg = RegNext(rollbackL1WbSelected.valid)
521  val rollbackL1WbReg = RegEnable(rollbackL1WbSelected.bits, rollbackL1WbSelected.valid)
522  val rollbackLq0VReg = RegNext(rollbackLq(0).valid)
523  val rollbackLq0Reg = RegEnable(rollbackLq(0).bits, rollbackLq(0).valid)
524  val rollbackLq1VReg = RegNext(rollbackLq(1).valid)
525  val rollbackLq1Reg = RegEnable(rollbackLq(1).bits, rollbackLq(1).valid)
526
527  // S3: select rollback (part2), generate rollback request, then fire rollback request
528  // Note that we use roqIdx - 1.U to flush the load instruction itself.
529  // Thus, here if last cycle's roqIdx equals to this cycle's roqIdx, it still triggers the redirect.
530
531  // FIXME: this is ugly
532  val rollbackValidVec = Seq(rollbackL1WbVReg, rollbackLq0VReg, rollbackLq1VReg)
533  val rollbackUopExtVec = Seq(rollbackL1WbReg, rollbackLq0Reg, rollbackLq1Reg)
534
535  // select uop in parallel
536  val mask = getAfterMask(rollbackValidVec, rollbackUopExtVec.map(i => i.uop))
537  val oneAfterZero = mask(1)(0)
538  val rollbackUopExt = Mux(oneAfterZero && mask(2)(0),
539    rollbackUopExtVec(0),
540    Mux(!oneAfterZero && mask(2)(1), rollbackUopExtVec(1), rollbackUopExtVec(2)))
541  val stFtqIdxS3 = RegNext(stFtqIdxS2)
542  val stFtqOffsetS3 = RegNext(stFtqOffsetS2)
543  val rollbackUop = rollbackUopExt.uop
544  val rollbackStFtqIdx = stFtqIdxS3(rollbackUopExt.flag)
545  val rollbackStFtqOffset = stFtqOffsetS3(rollbackUopExt.flag)
546
547  // check if rollback request is still valid in parallel
548  val rollbackValidVecChecked = Wire(Vec(3, Bool()))
549  for(((v, uop), idx) <- rollbackValidVec.zip(rollbackUopExtVec.map(i => i.uop)).zipWithIndex) {
550    rollbackValidVecChecked(idx) := v &&
551      (!lastCycleRedirect.valid || isBefore(uop.roqIdx, lastCycleRedirect.bits.roqIdx)) &&
552      (!lastlastCycleRedirect.valid || isBefore(uop.roqIdx, lastlastCycleRedirect.bits.roqIdx))
553  }
554
555  io.rollback.bits.roqIdx := rollbackUop.roqIdx
556  io.rollback.bits.ftqIdx := rollbackUop.cf.ftqPtr
557  io.rollback.bits.stFtqIdx := rollbackStFtqIdx
558  io.rollback.bits.ftqOffset := rollbackUop.cf.ftqOffset
559  io.rollback.bits.stFtqOffset := rollbackStFtqOffset
560  io.rollback.bits.level := RedirectLevel.flush
561  io.rollback.bits.interrupt := DontCare
562  io.rollback.bits.cfiUpdate := DontCare
563  io.rollback.bits.cfiUpdate.target := rollbackUop.cf.pc
564  // io.rollback.bits.pc := DontCare
565
566  io.rollback.valid := rollbackValidVecChecked.asUInt.orR && !lastCycleFlush && !lastlastCycleFlush
567
568  when(io.rollback.valid) {
569    // XSDebug("Mem rollback: pc %x roqidx %d\n", io.rollback.bits.cfi, io.rollback.bits.roqIdx.asUInt)
570  }
571
572  /**
573    * Memory mapped IO / other uncached operations
574    *
575    * States:
576    * (1) writeback from store units: mark as pending
577    * (2) when they reach ROB's head, they can be sent to uncache channel
578    * (3) response from uncache channel: mark as datavalid
579    * (4) writeback to ROB (and other units): mark as writebacked
580    * (5) ROB commits the instruction: same as normal instructions
581    */
582  //(2) when they reach ROB's head, they can be sent to uncache channel
583  val lqTailMmioPending = WireInit(pending(deqPtr))
584  val lqTailAllocated = WireInit(allocated(deqPtr))
585  val s_idle :: s_req :: s_resp :: s_wait :: Nil = Enum(4)
586  val uncacheState = RegInit(s_idle)
587  switch(uncacheState) {
588    is(s_idle) {
589      when(io.roq.pendingld && lqTailMmioPending && lqTailAllocated) {
590        uncacheState := s_req
591      }
592    }
593    is(s_req) {
594      when(io.uncache.req.fire()) {
595        uncacheState := s_resp
596      }
597    }
598    is(s_resp) {
599      when(io.uncache.resp.fire()) {
600        uncacheState := s_wait
601      }
602    }
603    is(s_wait) {
604      when(io.roq.commit) {
605        uncacheState := s_idle // ready for next mmio
606      }
607    }
608  }
609  io.uncache.req.valid := uncacheState === s_req
610
611  dataModule.io.uncache.raddr := deqPtrExtNext.value
612
613  io.uncache.req.bits.cmd  := MemoryOpConstants.M_XRD
614  io.uncache.req.bits.addr := dataModule.io.uncache.rdata.paddr
615  io.uncache.req.bits.data := dataModule.io.uncache.rdata.data
616  io.uncache.req.bits.mask := dataModule.io.uncache.rdata.mask
617
618  io.uncache.req.bits.id   := DontCare
619
620  io.uncache.resp.ready := true.B
621
622  when (io.uncache.req.fire()) {
623    pending(deqPtr) := false.B
624
625    XSDebug("uncache req: pc %x addr %x data %x op %x mask %x\n",
626      uop(deqPtr).cf.pc,
627      io.uncache.req.bits.addr,
628      io.uncache.req.bits.data,
629      io.uncache.req.bits.cmd,
630      io.uncache.req.bits.mask
631    )
632  }
633
634  // (3) response from uncache channel: mark as datavalid
635  dataModule.io.uncache.wen := false.B
636  when(io.uncache.resp.fire()){
637    datavalid(deqPtr) := true.B
638    dataModule.io.uncacheWrite(deqPtr, io.uncache.resp.bits.data(XLEN-1, 0))
639    dataModule.io.uncache.wen := true.B
640
641    XSDebug("uncache resp: data %x\n", io.dcache.bits.data)
642  }
643
644  // Read vaddr for mem exception
645  // no inst will be commited 1 cycle before tval update
646  vaddrModule.io.raddr(0) := (deqPtrExt + commitCount).value
647  io.exceptionAddr.vaddr := vaddrModule.io.rdata(0)
648
649  // misprediction recovery / exception redirect
650  // invalidate lq term using robIdx
651  val needCancel = Wire(Vec(LoadQueueSize, Bool()))
652  for (i <- 0 until LoadQueueSize) {
653    needCancel(i) := uop(i).roqIdx.needFlush(io.brqRedirect, io.flush) && allocated(i)
654    when (needCancel(i)) {
655        allocated(i) := false.B
656    }
657  }
658
659  /**
660    * update pointers
661    */
662  val lastCycleCancelCount = PopCount(RegNext(needCancel))
663  // when io.brqRedirect.valid, we don't allow eneuque even though it may fire.
664  val enqNumber = Mux(io.enq.canAccept && io.enq.sqCanAccept && !(io.brqRedirect.valid || io.flush), PopCount(io.enq.req.map(_.valid)), 0.U)
665  when (lastCycleRedirect.valid || lastCycleFlush) {
666    // we recover the pointers in the next cycle after redirect
667    enqPtrExt := VecInit(enqPtrExt.map(_ - lastCycleCancelCount))
668  }.otherwise {
669    enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber))
670  }
671
672  deqPtrExtNext := deqPtrExt + commitCount
673  deqPtrExt := deqPtrExtNext
674
675  val validCount = distanceBetween(enqPtrExt(0), deqPtrExt)
676
677  allowEnqueue := validCount + enqNumber <= (LoadQueueSize - RenameWidth).U
678
679  /**
680    * misc
681    */
682  io.roq.storeDataRoqWb := DontCare // will be overwriten by store queue's result
683
684  // perf counter
685  QueuePerf(LoadQueueSize, validCount, !allowEnqueue)
686  io.lqFull := !allowEnqueue
687  XSPerfAccumulate("rollback", io.rollback.valid) // rollback redirect generated
688  XSPerfAccumulate("mmioCycle", uncacheState =/= s_idle) // lq is busy dealing with uncache req
689  XSPerfAccumulate("mmioCnt", io.uncache.req.fire())
690  XSPerfAccumulate("refill", io.dcache.valid)
691  XSPerfAccumulate("writeback_success", PopCount(VecInit(io.ldout.map(i => i.fire()))))
692  XSPerfAccumulate("writeback_blocked", PopCount(VecInit(io.ldout.map(i => i.valid && !i.ready))))
693  XSPerfAccumulate("utilization_miss", PopCount((0 until LoadQueueSize).map(i => allocated(i) && miss(i))))
694
695  // debug info
696  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt.flag, deqPtr)
697
698  def PrintFlag(flag: Bool, name: String): Unit = {
699    when(flag) {
700      XSDebug(false, true.B, name)
701    }.otherwise {
702      XSDebug(false, true.B, " ")
703    }
704  }
705
706  for (i <- 0 until LoadQueueSize) {
707    if (i % 4 == 0) XSDebug("")
708    XSDebug(false, true.B, "%x [%x] ", uop(i).cf.pc, debug_paddr(i))
709    PrintFlag(allocated(i), "a")
710    PrintFlag(allocated(i) && datavalid(i), "v")
711    PrintFlag(allocated(i) && writebacked(i), "w")
712    PrintFlag(allocated(i) && miss(i), "m")
713    // PrintFlag(allocated(i) && listening(i), "l")
714    PrintFlag(allocated(i) && pending(i), "p")
715    XSDebug(false, true.B, " ")
716    if (i % 4 == 3 || i == LoadQueueSize - 1) XSDebug(false, true.B, "\n")
717  }
718
719}
720