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