xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/LoadQueueRAW.scala (revision bd65812fbfc0ffd0a5356b14ef4986190c31b999)
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 chisel3._
20import chisel3.util._
21import chipsalliance.rocketchip.config._
22import xiangshan._
23import xiangshan.backend.rob.RobPtr
24import xiangshan.cache._
25import xiangshan.frontend.FtqPtr
26import xiangshan.mem.mdp._
27import utils._
28import utility._
29
30class LoadQueueRAW(implicit p: Parameters) extends XSModule
31  with HasDCacheParameters
32  with HasCircularQueuePtrHelper
33  with HasLoadHelper
34  with HasPerfEvents
35{
36  val io = IO(new Bundle() {
37    val redirect = Flipped(ValidIO(new Redirect))
38    val query = Vec(LoadPipelineWidth, Flipped(new LoadViolationQueryIO))
39    val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle)))
40    val rollback = Output(Valid(new Redirect))
41    val stAddrReadySqPtr = Input(new SqPtr)
42    val stIssuePtr = Input(new SqPtr)
43    val lqFull = Output(Bool())
44  })
45
46  println("LoadQueueRAW: size " + LoadQueueRAWSize)
47  //  LoadQueueRAW field
48  //  +-------+--------+-------+-------+-----------+
49  //  | Valid |  uop   |PAddr  | Mask  | Datavalid |
50  //  +-------+--------+-------+-------+-----------+
51  //
52  //  Field descriptions:
53  //  Allocated   : entry has been allocated already
54  //  MicroOp     : inst's microOp
55  //  PAddr       : physical address.
56  //  Mask        : data mask
57  //  Datavalid   : data valid
58  //
59  val allocated = RegInit(VecInit(List.fill(LoadQueueRAWSize)(false.B))) // The control signals need to explicitly indicate the initial value
60  val uop = Reg(Vec(LoadQueueRAWSize, new MicroOp))
61  val paddrModule = Module(new LqPAddrModule(
62    gen = UInt(PAddrBits.W),
63    numEntries = LoadQueueRAWSize,
64    numRead = LoadPipelineWidth,
65    numWrite = LoadPipelineWidth,
66    numWBank = LoadQueueNWriteBanks,
67    numWDelay = 2,
68    numCamPort = StorePipelineWidth
69  ))
70  paddrModule.io := DontCare
71  val maskModule = Module(new LqMaskModule(
72    gen = UInt(8.W),
73    numEntries = LoadQueueRAWSize,
74    numRead = LoadPipelineWidth,
75    numWrite = LoadPipelineWidth,
76    numWBank = LoadQueueNWriteBanks,
77    numWDelay = 2,
78    numCamPort = StorePipelineWidth
79  ))
80  maskModule.io := DontCare
81  val datavalid = RegInit(VecInit(List.fill(LoadQueueRAWSize)(false.B)))
82
83  // freeliset: store valid entries index.
84  // +---+---+--------------+-----+-----+
85  // | 0 | 1 |      ......  | n-2 | n-1 |
86  // +---+---+--------------+-----+-----+
87  val freeList = Module(new FreeList(
88    size = LoadQueueRAWSize,
89    allocWidth = LoadPipelineWidth,
90    freeWidth = 4,
91    moduleName = "LoadQueueRAW freelist"
92  ))
93  freeList.io := DontCare
94
95  //  LoadQueueRAW enqueue
96  val canEnqueue = io.query.map(_.req.valid)
97  val cancelEnqueue = io.query.map(_.req.bits.uop.robIdx.needFlush(io.redirect))
98  val allAddrCheck = io.stIssuePtr === io.stAddrReadySqPtr
99  val hasAddrInvalidStore = io.query.map(_.req.bits.uop.sqIdx).map(sqIdx => {
100    Mux(!allAddrCheck, isBefore(io.stAddrReadySqPtr, sqIdx), false.B)
101  })
102  val needEnqueue = canEnqueue.zip(hasAddrInvalidStore).zip(cancelEnqueue).map { case ((v, r), c) => v && r && !c }
103  val bypassPAddr = Reg(Vec(LoadPipelineWidth, UInt(PAddrBits.W)))
104  val bypassMask = Reg(Vec(LoadPipelineWidth, UInt(8.W)))
105
106  // Allocate logic
107  val enqValidVec = Wire(Vec(LoadPipelineWidth, Bool()))
108  val enqIndexVec = Wire(Vec(LoadPipelineWidth, UInt()))
109
110  // Enqueue
111  for ((enq, w) <- io.query.map(_.req).zipWithIndex) {
112    paddrModule.io.wen(w) := false.B
113    maskModule.io.wen(w) := false.B
114    freeList.io.doAllocate(w) := false.B
115
116    freeList.io.allocateReq(w) := needEnqueue(w)
117
118    //  Allocate ready
119    enqValidVec(w) := freeList.io.canAllocate(w)
120    enqIndexVec(w) := freeList.io.allocateSlot(w)
121    enq.ready := Mux(needEnqueue(w), enqValidVec(w), true.B)
122
123    val enqIndex = enqIndexVec(w)
124    when (needEnqueue(w) && enq.ready) {
125      val debug_robIdx = enq.bits.uop.robIdx.asUInt
126      XSError(allocated(enqIndex), p"LoadQueueRAW: You can not write an valid entry! check: ldu $w, robIdx $debug_robIdx")
127
128      freeList.io.doAllocate(w) := true.B
129
130      //  Allocate new entry
131      allocated(enqIndex) := true.B
132
133      //  Write paddr
134      paddrModule.io.wen(w) := true.B
135      paddrModule.io.waddr(w) := enqIndex
136      paddrModule.io.wdata(w) := enq.bits.paddr
137      bypassPAddr(w) := enq.bits.paddr
138
139      //  Write mask
140      maskModule.io.wen(w) := true.B
141      maskModule.io.waddr(w) := enqIndex
142      maskModule.io.wdata(w) := enq.bits.mask
143      bypassMask(w) := enq.bits.mask
144
145      //  Fill info
146      uop(enqIndex) := enq.bits.uop
147      datavalid(enqIndex) := enq.bits.datavalid
148    }
149  }
150
151  for ((query, w) <- io.query.map(_.resp).zipWithIndex) {
152    query.valid := RegNext(io.query(w).req.valid)
153    query.bits.replayFromFetch := RegNext(false.B)
154  }
155
156  //  LoadQueueRAW deallocate
157  val freeMaskVec = Wire(Vec(LoadQueueRAWSize, Bool()))
158
159  // init
160  freeMaskVec.map(e => e := false.B)
161
162  // when the stores that "older than" current load address were ready.
163  // current load will be released.
164  for (i <- 0 until LoadQueueRAWSize) {
165    val deqNotBlock = Mux(!allAddrCheck, !isBefore(io.stAddrReadySqPtr, uop(i).sqIdx), true.B)
166    val needCancel = uop(i).robIdx.needFlush(io.redirect)
167
168    when (allocated(i) && (deqNotBlock || needCancel)) {
169      allocated(i) := false.B
170      freeMaskVec(i) := true.B
171    }
172  }
173
174  // if need replay deallocate entry
175  val lastCanAccept = RegNext(VecInit(needEnqueue.zip(enqValidVec).map(x => x._1 && x._2)))
176  val lastAllocIndex = RegNext(enqIndexVec)
177
178  for ((release, w) <- io.query.map(_.release).zipWithIndex) {
179    val releaseValid = release && lastCanAccept(w)
180    val releaseIndex = lastAllocIndex(w)
181
182    when (allocated(releaseIndex) && releaseValid) {
183      allocated(releaseIndex) := false.B
184      freeMaskVec(releaseIndex) := true.B
185    }
186  }
187  freeList.io.free := freeMaskVec.asUInt
188
189  io.lqFull := freeList.io.empty
190
191  /**
192    * Store-Load Memory violation detection
193    * Scheme 1(Current scheme): flush the pipeline then re-fetch from the load instruction (like old load queue).
194    * Scheme 2                : re-fetch instructions from the first instruction after the store instruction.
195    *
196    * When store writes back, it searches LoadQueue for younger load instructions
197    * with the same load physical address. They loaded wrong data and need re-execution.
198    *
199    * Cycle 0: Store Writeback
200    *   Generate match vector for store address with rangeMask(stPtr, enqPtr).
201    * Cycle 1: Select oldest load from select group.
202    * Cycle x: Redirect Fire
203    *   Choose the oldest load from LoadPipelineWidth oldest loads.
204    *   Prepare redirect request according to the detected violation.
205    *   Fire redirect request (if valid)
206    */
207  //              SelectGroup 0         SelectGroup 1          SelectGroup y
208  // stage 0:       lq  lq  lq  ......    lq  lq  lq  .......    lq  lq  lq
209  //                |   |   |             |   |   |              |   |   |
210  // stage 1:       lq  lq  lq  ......    lq  lq  lq  .......    lq  lq  lq
211  //                 \  |  /    ......     \  |  /    .......     \  |  /
212  // stage 2:           lq                    lq                     lq
213  //                     \  |  /  .......  \  |  /   ........  \  |  /
214  // stage 3:               lq                lq                  lq
215  //                                          ...
216  //                                          ...
217  //                                           |
218  // stage x:                                  lq
219  //                                           |
220  //                                       rollback req
221
222  // select logic
223  val SelectGroupSize = RollbackGroupSize
224  val lgSelectGroupSize = log2Ceil(SelectGroupSize)
225  val TotalSelectCycles = scala.math.ceil(log2Ceil(LoadQueueRAWSize).toFloat / lgSelectGroupSize).toInt + 1
226
227  def selectPartialOldest[T <: XSBundleWithMicroOp](valid: Seq[Bool], bits: Seq[T]): (Seq[Bool], Seq[T]) = {
228    assert(valid.length == bits.length)
229    if (valid.length == 0 || valid.length == 1) {
230      (valid, bits)
231    } else if (valid.length == 2) {
232      val res = Seq.fill(2)(Wire(ValidIO(chiselTypeOf(bits(0)))))
233      for (i <- res.indices) {
234        res(i).valid := valid(i)
235        res(i).bits := bits(i)
236      }
237      val oldest = Mux(valid(0) && valid(1), Mux(isAfter(bits(0).uop.robIdx, bits(1).uop.robIdx), res(1), res(0)), Mux(valid(0) && !valid(1), res(0), res(1)))
238      (Seq(oldest.valid), Seq(oldest.bits))
239    } else {
240      val left = selectPartialOldest(valid.take(valid.length / 2), bits.take(bits.length / 2))
241      val right = selectPartialOldest(valid.takeRight(valid.length - (valid.length / 2)), bits.takeRight(bits.length - (bits.length / 2)))
242      selectPartialOldest(left._1 ++ right._1, left._2 ++ right._2)
243    }
244  }
245
246  def selectOldest[T <: XSBundleWithMicroOp](valid: Seq[Bool], bits: Seq[T]): (Seq[Bool], Seq[T]) = {
247    assert(valid.length == bits.length)
248    val numSelectGroups = scala.math.ceil(valid.length.toFloat / SelectGroupSize).toInt
249
250    // group info
251    val selectValidGroups =
252      if (valid.length <= SelectGroupSize) {
253        Seq(valid)
254      } else {
255        (0 until numSelectGroups).map(g => {
256          if (valid.length < (g + 1) * SelectGroupSize) {
257            valid.takeRight(valid.length - g * SelectGroupSize)
258          } else {
259            (0 until SelectGroupSize).map(j => valid(g * SelectGroupSize + j))
260          }
261        })
262      }
263    val selectBitsGroups =
264      if (bits.length <= SelectGroupSize) {
265        Seq(bits)
266      } else {
267        (0 until numSelectGroups).map(g => {
268          if (bits.length < (g + 1) * SelectGroupSize) {
269            bits.takeRight(bits.length - g * SelectGroupSize)
270          } else {
271            (0 until SelectGroupSize).map(j => bits(g * SelectGroupSize + j))
272          }
273        })
274      }
275
276    // select logic
277    if (valid.length <= SelectGroupSize) {
278      val (selValid, selBits) = selectPartialOldest(valid, bits)
279      (Seq(RegNext(selValid(0) && !selBits(0).uop.robIdx.needFlush(io.redirect))), Seq(RegNext(selBits(0))))
280    } else {
281      val select = (0 until numSelectGroups).map(g => {
282        val (selValid, selBits) = selectPartialOldest(selectValidGroups(g), selectBitsGroups(g))
283        (RegNext(selValid(0) && !selBits(0).uop.robIdx.needFlush(io.redirect)), RegNext(selBits(0)))
284      })
285      selectOldest(select.map(_._1), select.map(_._2))
286    }
287  }
288
289  def detectRollback(i: Int) = {
290    paddrModule.io.violationMdata(i) := io.storeIn(i).bits.paddr
291    maskModule.io.violationMdata(i) := io.storeIn(i).bits.mask
292
293    val bypassPaddrMask = RegNext(VecInit((0 until LoadPipelineWidth).map(j => bypassPAddr(j)(PAddrBits-1, 3) === io.storeIn(i).bits.paddr(PAddrBits-1, 3))))
294    val bypassMMask = RegNext(VecInit((0 until LoadPipelineWidth).map(j => (bypassMask(j) & io.storeIn(i).bits.mask).orR)))
295    val bypassMaskUInt = (0 until LoadPipelineWidth).map(j =>
296      Fill(LoadQueueRAWSize, RegNext(RegNext(io.query(j).req.fire))) & Mux(bypassPaddrMask(j) && bypassMMask(j), UIntToOH(RegNext(RegNext(enqIndexVec(j)))), 0.U(LoadQueueRAWSize))
297    ).reduce(_|_)
298
299    val addrMaskMatch = RegNext(paddrModule.io.violationMmask(i).asUInt & maskModule.io.violationMmask(i).asUInt) | bypassMaskUInt
300    val entryNeedCheck = RegNext(VecInit((0 until LoadQueueRAWSize).map(j => {
301      allocated(j) && isAfter(uop(j).robIdx, io.storeIn(i).bits.uop.robIdx) && datavalid(j) && !uop(j).robIdx.needFlush(io.redirect)
302    })))
303    val lqViolationSelVec = VecInit((0 until LoadQueueRAWSize).map(j => {
304      addrMaskMatch(j) && entryNeedCheck(j)
305    }))
306
307    val lqViolationSelUopExts = uop.map(uop => {
308      val wrapper = Wire(new XSBundleWithMicroOp)
309      wrapper.uop := uop
310      wrapper
311    })
312
313    // select logic
314    val lqSelect = selectOldest(lqViolationSelVec, lqViolationSelUopExts)
315
316    // select one inst
317    val lqViolation = lqSelect._1(0)
318    val lqViolationUop = lqSelect._2(0).uop
319
320    XSDebug(
321      lqViolation,
322      "need rollback (ld wb before store) pc %x robidx %d target %x\n",
323      io.storeIn(i).bits.uop.cf.pc, io.storeIn(i).bits.uop.robIdx.asUInt, lqViolationUop.robIdx.asUInt
324    )
325
326    (lqViolation, lqViolationUop)
327  }
328
329  // select rollback (part1) and generate rollback request
330  // rollback check
331  // Lq rollback seq check is done in s3 (next stage), as getting rollbackLq MicroOp is slow
332  val rollbackLqWb = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt)))
333  val stFtqIdx = Wire(Vec(StorePipelineWidth, new FtqPtr))
334  val stFtqOffset = Wire(Vec(StorePipelineWidth, UInt(log2Up(PredictWidth).W)))
335  for (w <- 0 until StorePipelineWidth) {
336    val detectedRollback = detectRollback(w)
337    rollbackLqWb(w).valid := detectedRollback._1 && DelayN(io.storeIn(w).valid && !io.storeIn(w).bits.miss, TotalSelectCycles)
338    rollbackLqWb(w).bits.uop := detectedRollback._2
339    rollbackLqWb(w).bits.flag := w.U
340    stFtqIdx(w) := DelayN(io.storeIn(w).bits.uop.cf.ftqPtr, TotalSelectCycles)
341    stFtqOffset(w) := DelayN(io.storeIn(w).bits.uop.cf.ftqOffset, TotalSelectCycles)
342  }
343
344  val rollbackLqWbValid = rollbackLqWb.map(x => x.valid && !x.bits.uop.robIdx.needFlush(io.redirect))
345  val rollbackLqWbBits = rollbackLqWb.map(x => x.bits)
346
347  // select rollback (part2), generate rollback request, then fire rollback request
348  // Note that we use robIdx - 1.U to flush the load instruction itself.
349  // Thus, here if last cycle's robIdx equals to this cycle's robIdx, it still triggers the redirect.
350
351  // select uop in parallel
352  val lqs = selectPartialOldest(rollbackLqWbValid, rollbackLqWbBits)
353  val rollbackUopExt = lqs._2(0)
354  val rollbackUop = rollbackUopExt.uop
355  val rollbackStFtqIdx = stFtqIdx(rollbackUopExt.flag)
356  val rollbackStFtqOffset = stFtqOffset(rollbackUopExt.flag)
357
358  // check if rollback request is still valid in parallel
359  io.rollback.bits := DontCare
360  io.rollback.bits.robIdx := rollbackUop.robIdx
361  io.rollback.bits.ftqIdx := rollbackUop.cf.ftqPtr
362  io.rollback.bits.stFtqIdx := rollbackStFtqIdx
363  io.rollback.bits.ftqOffset := rollbackUop.cf.ftqOffset
364  io.rollback.bits.stFtqOffset := rollbackStFtqOffset
365  io.rollback.bits.level := RedirectLevel.flush
366  io.rollback.bits.interrupt := DontCare
367  io.rollback.bits.cfiUpdate := DontCare
368  io.rollback.bits.cfiUpdate.target := rollbackUop.cf.pc
369  io.rollback.bits.debug_runahead_checkpoint_id := rollbackUop.debugInfo.runahead_checkpoint_id
370  // io.rollback.bits.pc := DontCare
371
372  io.rollback.valid := VecInit(rollbackLqWbValid).asUInt.orR
373
374  // perf cnt
375  val canEnqCount = PopCount(io.query.map(_.req.fire))
376  val validCount = freeList.io.validCount
377  val allowEnqueue = validCount <= (LoadQueueRAWSize - LoadPipelineWidth).U
378
379  QueuePerf(LoadQueueRAWSize, validCount, !allowEnqueue)
380  XSPerfAccumulate("enqs", canEnqCount)
381  XSPerfAccumulate("stld_rollback", io.rollback.valid)
382  val perfEvents: Seq[(String, UInt)] = Seq(
383    ("enq ", canEnqCount),
384    ("stld_rollback", io.rollback.valid),
385  )
386  generatePerfEvent()
387  // end
388}