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