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