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