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