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