xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/StoreQueue.scala (revision 5c5bd416ce761d956348a8e2fbbf268922371d8b)
1package xiangshan.mem
2
3import chisel3._
4import chisel3.util._
5import utils._
6import xiangshan._
7import xiangshan.cache._
8import xiangshan.cache.{DCacheWordIO, DCacheLineIO, TlbRequestIO, MemoryOpConstants}
9import xiangshan.backend.LSUOpType
10import xiangshan.backend.roq.RoqLsqIO
11
12
13class SqPtr extends CircularQueuePtr(SqPtr.StoreQueueSize) { }
14
15object SqPtr extends HasXSParameter {
16  def apply(f: Bool, v: UInt): SqPtr = {
17    val ptr = Wire(new SqPtr)
18    ptr.flag := f
19    ptr.value := v
20    ptr
21  }
22}
23
24class SqEnqIO extends XSBundle {
25  val canAccept = Output(Bool())
26  val lqCanAccept = Input(Bool())
27  val needAlloc = Vec(RenameWidth, Input(Bool()))
28  val req = Vec(RenameWidth, Flipped(ValidIO(new MicroOp)))
29  val resp = Vec(RenameWidth, Output(new SqPtr))
30}
31
32// Store Queue
33class StoreQueue extends XSModule with HasDCacheParameters with HasCircularQueuePtrHelper {
34  val io = IO(new Bundle() {
35    val enq = new SqEnqIO
36    val brqRedirect = Flipped(ValidIO(new Redirect))
37    val flush = Input(Bool())
38    val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle)))
39    val sbuffer = Vec(StorePipelineWidth, Decoupled(new DCacheWordReq))
40    val mmioStout = DecoupledIO(new ExuOutput) // writeback uncached store
41    val forward = Vec(LoadPipelineWidth, Flipped(new MaskedLoadForwardQueryIO))
42    val roq = Flipped(new RoqLsqIO)
43    val uncache = new DCacheWordIO
44    // val refill = Flipped(Valid(new DCacheLineReq ))
45    val exceptionAddr = new ExceptionAddrIO
46    val sqempty = Output(Bool())
47    val issuePtrExt = Output(new SqPtr)
48    val storeIssue = Vec(StorePipelineWidth, Flipped(Valid(new ExuInput)))
49  })
50
51  val difftestIO = IO(new Bundle() {
52    val storeCommit = Output(UInt(2.W))
53    val storeAddr   = Output(Vec(2, UInt(64.W)))
54    val storeData   = Output(Vec(2, UInt(64.W)))
55    val storeMask   = Output(Vec(2, UInt(8.W)))
56  })
57  difftestIO <> DontCare
58
59  // data modules
60  val uop = Reg(Vec(StoreQueueSize, new MicroOp))
61  // val data = Reg(Vec(StoreQueueSize, new LsqEntry))
62  val dataModule = Module(new StoreQueueData(StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth, numForward = StorePipelineWidth))
63  dataModule.io := DontCare
64  val paddrModule = Module(new SQPaddrModule(StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth, numForward = StorePipelineWidth))
65  paddrModule.io := DontCare
66  val vaddrModule = Module(new SyncDataModuleTemplate(UInt(VAddrBits.W), StoreQueueSize, numRead = 1, numWrite = StorePipelineWidth))
67  vaddrModule.io := DontCare
68
69  // state & misc
70  val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated
71  val datavalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio data is valid
72  val writebacked = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // inst has been writebacked to CDB
73  val issued = Reg(Vec(StoreQueueSize, Bool())) // inst has been issued by rs
74  val commited = Reg(Vec(StoreQueueSize, Bool())) // inst has been commited by roq
75  val pending = Reg(Vec(StoreQueueSize, Bool())) // mmio pending: inst is an mmio inst, it will not be executed until it reachs the end of roq
76  val mmio = Reg(Vec(StoreQueueSize, Bool())) // mmio: inst is an mmio inst
77
78  // ptr
79  require(StoreQueueSize > RenameWidth)
80  val enqPtrExt = RegInit(VecInit((0 until RenameWidth).map(_.U.asTypeOf(new SqPtr))))
81  val deqPtrExt = RegInit(VecInit((0 until StorePipelineWidth).map(_.U.asTypeOf(new SqPtr))))
82  val cmtPtrExt = RegInit(VecInit((0 until CommitWidth).map(_.U.asTypeOf(new SqPtr))))
83  val issuePtrExt = RegInit(0.U.asTypeOf(new SqPtr))
84  val validCounter = RegInit(0.U(log2Ceil(LoadQueueSize + 1).W))
85  val allowEnqueue = RegInit(true.B)
86
87  val enqPtr = enqPtrExt(0).value
88  val deqPtr = deqPtrExt(0).value
89  val cmtPtr = cmtPtrExt(0).value
90
91  val deqMask = UIntToMask(deqPtr, StoreQueueSize)
92  val enqMask = UIntToMask(enqPtr, StoreQueueSize)
93
94  val commitCount = RegNext(io.roq.scommit)
95
96  // Read dataModule
97  // deqPtrExtNext and deqPtrExtNext+1 entry will be read from dataModule
98  // if !sbuffer.fire(), read the same ptr
99  // if sbuffer.fire(), read next
100  val deqPtrExtNext = WireInit(Mux(io.sbuffer(1).fire(),
101    VecInit(deqPtrExt.map(_ + 2.U)),
102    Mux(io.sbuffer(0).fire() || io.mmioStout.fire(),
103      VecInit(deqPtrExt.map(_ + 1.U)),
104      deqPtrExt
105    )
106  ))
107  for (i <- 0 until StorePipelineWidth) {
108    dataModule.io.raddr(i) := deqPtrExtNext(i).value
109    paddrModule.io.raddr(i) := deqPtrExtNext(i).value
110  }
111
112  // no inst will be commited 1 cycle before tval update
113  vaddrModule.io.raddr(0) := (cmtPtrExt(0) + commitCount).value
114
115  /**
116    * Enqueue at dispatch
117    *
118    * Currently, StoreQueue only allows enqueue when #emptyEntries > RenameWidth(EnqWidth)
119    */
120  io.enq.canAccept := allowEnqueue
121  for (i <- 0 until RenameWidth) {
122    val offset = if (i == 0) 0.U else PopCount(io.enq.needAlloc.take(i))
123    val sqIdx = enqPtrExt(offset)
124    val index = sqIdx.value
125    when (io.enq.req(i).valid && io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush)) {
126      uop(index) := io.enq.req(i).bits
127      allocated(index) := true.B
128      datavalid(index) := false.B
129      writebacked(index) := false.B
130      issued(index) := false.B
131      commited(index) := false.B
132      pending(index) := false.B
133    }
134    io.enq.resp(i) := sqIdx
135  }
136  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
137
138  /**
139    * Update issuePtr when issue from rs
140    */
141
142  // update state bit issued
143  for (i <- 0 until StorePipelineWidth) {
144    when (io.storeIssue(i).valid) {
145      issued(io.storeIssue(i).bits.uop.sqIdx.value) := true.B
146    }
147  }
148
149  // update issuePtr
150  val IssuePtrMoveStride = 4
151  require(IssuePtrMoveStride >= 2)
152
153  val issueLookupVec = (0 until IssuePtrMoveStride).map(issuePtrExt + _.U)
154  val issueLookup = issueLookupVec.map(ptr => allocated(ptr.value) && issued(ptr.value) && ptr =/= enqPtrExt(0))
155  val nextIssuePtr = issuePtrExt + PriorityEncoder(VecInit(issueLookup.map(!_) :+ true.B))
156  issuePtrExt := nextIssuePtr
157
158  when (io.brqRedirect.valid || io.flush) {
159    issuePtrExt := Mux(
160      isAfter(cmtPtrExt(0), deqPtrExt(0)),
161      cmtPtrExt(0),
162      deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr
163    )
164  }
165  // send issuePtrExt to rs
166  // io.issuePtrExt := cmtPtrExt(0)
167  io.issuePtrExt := issuePtrExt
168
169  /**
170    * Writeback store from store units
171    *
172    * Most store instructions writeback to regfile in the previous cycle.
173    * However,
174    *   (1) For an mmio instruction with exceptions, we need to mark it as datavalid
175    * (in this way it will trigger an exception when it reaches ROB's head)
176    * instead of pending to avoid sending them to lower level.
177    *   (2) For an mmio instruction without exceptions, we mark it as pending.
178    * When the instruction reaches ROB's head, StoreQueue sends it to uncache channel.
179    * Upon receiving the response, StoreQueue writes back the instruction
180    * through arbiter with store units. It will later commit as normal.
181    */
182  for (i <- 0 until StorePipelineWidth) {
183    dataModule.io.wen(i) := false.B
184    paddrModule.io.wen(i) := false.B
185    val stWbIndex = io.storeIn(i).bits.uop.sqIdx.value
186    when (io.storeIn(i).fire()) {
187      datavalid(stWbIndex) := !io.storeIn(i).bits.mmio
188      writebacked(stWbIndex) := !io.storeIn(i).bits.mmio
189      pending(stWbIndex) := io.storeIn(i).bits.mmio
190
191      val storeWbData = Wire(new SQDataEntry)
192      storeWbData := DontCare
193      storeWbData.mask := io.storeIn(i).bits.mask
194      storeWbData.data := io.storeIn(i).bits.data
195
196      dataModule.io.waddr(i) := stWbIndex
197      dataModule.io.wdata(i) := storeWbData
198      dataModule.io.wen(i) := true.B
199
200      paddrModule.io.waddr(i) := stWbIndex
201      paddrModule.io.wdata(i) := io.storeIn(i).bits.paddr
202      paddrModule.io.wen(i) := true.B
203
204
205      mmio(stWbIndex) := io.storeIn(i).bits.mmio
206
207      XSInfo("store write to sq idx %d pc 0x%x vaddr %x paddr %x data %x mmio %x\n",
208        io.storeIn(i).bits.uop.sqIdx.value,
209        io.storeIn(i).bits.uop.cf.pc,
210        io.storeIn(i).bits.vaddr,
211        io.storeIn(i).bits.paddr,
212        io.storeIn(i).bits.data,
213        io.storeIn(i).bits.mmio
214        )
215    }
216    // vaddrModule write is delayed, as vaddrModule will not be read right after write
217    vaddrModule.io.waddr(i) := RegNext(stWbIndex)
218    vaddrModule.io.wdata(i) := RegNext(io.storeIn(i).bits.vaddr)
219    vaddrModule.io.wen(i) := RegNext(io.storeIn(i).fire())
220  }
221
222  /**
223    * load forward query
224    *
225    * Check store queue for instructions that is older than the load.
226    * The response will be valid at the next cycle after req.
227    */
228  // check over all lq entries and forward data from the first matched store
229  for (i <- 0 until LoadPipelineWidth) {
230    io.forward(i).forwardMask := 0.U(8.W).asBools
231    io.forward(i).forwardData := DontCare
232
233    // Compare deqPtr (deqPtr) and forward.sqIdx, we have two cases:
234    // (1) if they have the same flag, we need to check range(tail, sqIdx)
235    // (2) if they have different flags, we need to check range(tail, LoadQueueSize) and range(0, sqIdx)
236    // Forward1: Mux(same_flag, range(tail, sqIdx), range(tail, LoadQueueSize))
237    // Forward2: Mux(same_flag, 0.U,                   range(0, sqIdx)    )
238    // i.e. forward1 is the target entries with the same flag bits and forward2 otherwise
239    val differentFlag = deqPtrExt(0).flag =/= io.forward(i).sqIdx.flag
240    val forwardMask = io.forward(i).sqIdxMask
241    val storeWritebackedVec = WireInit(VecInit(Seq.fill(StoreQueueSize)(false.B)))
242    for (j <- 0 until StoreQueueSize) {
243      storeWritebackedVec(j) := datavalid(j) && allocated(j) // all datavalid terms need to be checked
244    }
245    val needForward1 = Mux(differentFlag, ~deqMask, deqMask ^ forwardMask) & storeWritebackedVec.asUInt
246    val needForward2 = Mux(differentFlag, forwardMask, 0.U(StoreQueueSize.W)) & storeWritebackedVec.asUInt
247
248    XSDebug(p"$i f1 ${Binary(needForward1)} f2 ${Binary(needForward2)} " +
249      p"sqIdx ${io.forward(i).sqIdx} pa ${Hexadecimal(io.forward(i).paddr)}\n"
250    )
251
252    // do real fwd query
253    dataModule.io.needForward(i)(0) := needForward1 & paddrModule.io.forwardMmask(i).asUInt
254    dataModule.io.needForward(i)(1) := needForward2 & paddrModule.io.forwardMmask(i).asUInt
255
256    paddrModule.io.forwardMdata(i) := io.forward(i).paddr
257
258    io.forward(i).forwardMask := dataModule.io.forwardMask(i)
259    io.forward(i).forwardData := dataModule.io.forwardData(i)
260  }
261
262  /**
263    * Memory mapped IO / other uncached operations
264    *
265    * States:
266    * (1) writeback from store units: mark as pending
267    * (2) when they reach ROB's head, they can be sent to uncache channel
268    * (3) response from uncache channel: mark as datavalid
269    * (4) writeback to ROB (and other units): mark as writebacked
270    * (5) ROB commits the instruction: same as normal instructions
271    */
272  //(2) when they reach ROB's head, they can be sent to uncache channel
273  val s_idle :: s_req :: s_resp :: s_wb :: s_wait :: Nil = Enum(5)
274  val uncacheState = RegInit(s_idle)
275  switch(uncacheState) {
276    is(s_idle) {
277      when(io.roq.pendingst && pending(deqPtr) && allocated(deqPtr)) {
278        uncacheState := s_req
279      }
280    }
281    is(s_req) {
282      when(io.uncache.req.fire()) {
283        uncacheState := s_resp
284      }
285    }
286    is(s_resp) {
287      when(io.uncache.resp.fire()) {
288        uncacheState := s_wb
289      }
290    }
291    is(s_wb) {
292      when (io.mmioStout.fire()) {
293        uncacheState := s_wait
294      }
295    }
296    is(s_wait) {
297      when(io.roq.commit) {
298        uncacheState := s_idle // ready for next mmio
299      }
300    }
301  }
302  io.uncache.req.valid := uncacheState === s_req
303
304  io.uncache.req.bits.cmd  := MemoryOpConstants.M_XWR
305  io.uncache.req.bits.addr := paddrModule.io.rdata(0) // data(deqPtr) -> rdata(0)
306  io.uncache.req.bits.data := dataModule.io.rdata(0).data
307  io.uncache.req.bits.mask := dataModule.io.rdata(0).mask
308
309  io.uncache.req.bits.id   := DontCare
310
311  when(io.uncache.req.fire()){
312    pending(deqPtr) := false.B
313
314    XSDebug(
315      p"uncache req: pc ${Hexadecimal(uop(deqPtr).cf.pc)} " +
316      p"addr ${Hexadecimal(io.uncache.req.bits.addr)} " +
317      p"data ${Hexadecimal(io.uncache.req.bits.data)} " +
318      p"op ${Hexadecimal(io.uncache.req.bits.cmd)} " +
319      p"mask ${Hexadecimal(io.uncache.req.bits.mask)}\n"
320    )
321  }
322
323  // (3) response from uncache channel: mark as datavalid
324  io.uncache.resp.ready := true.B
325  when (io.uncache.resp.fire()) {
326    datavalid(deqPtr) := true.B
327  }
328
329  // (4) writeback to ROB (and other units): mark as writebacked
330  io.mmioStout.valid := uncacheState === s_wb // allocated(deqPtr) && datavalid(deqPtr) && !writebacked(deqPtr)
331  io.mmioStout.bits.uop := uop(deqPtr)
332  io.mmioStout.bits.uop.sqIdx := deqPtrExt(0)
333  io.mmioStout.bits.data := dataModule.io.rdata(0).data // dataModule.io.rdata.read(deqPtr)
334  io.mmioStout.bits.redirectValid := false.B
335  io.mmioStout.bits.redirect := DontCare
336  io.mmioStout.bits.debug.isMMIO := true.B
337  io.mmioStout.bits.debug.paddr := DontCare
338  io.mmioStout.bits.debug.isPerfCnt := false.B
339  io.mmioStout.bits.fflags := DontCare
340  when (io.mmioStout.fire()) {
341    writebacked(deqPtr) := true.B
342    allocated(deqPtr) := false.B
343  }
344
345  /**
346    * ROB commits store instructions (mark them as commited)
347    *
348    * (1) When store commits, mark it as commited.
349    * (2) They will not be cancelled and can be sent to lower level.
350    */
351  for (i <- 0 until CommitWidth) {
352    when (commitCount > i.U) {
353      commited(cmtPtrExt(i).value) := true.B
354    }
355  }
356  cmtPtrExt := cmtPtrExt.map(_ + commitCount)
357
358  // Commited stores will not be cancelled and can be sent to lower level.
359  // remove retired insts from sq, add retired store to sbuffer
360  for (i <- 0 until StorePipelineWidth) {
361    // We use RegNext to prepare data for sbuffer
362    val ptr = deqPtrExt(i).value
363    // if !sbuffer.fire(), read the same ptr
364    // if sbuffer.fire(), read next
365    io.sbuffer(i).valid := allocated(ptr) && commited(ptr) && !mmio(ptr)
366    io.sbuffer(i).bits.cmd  := MemoryOpConstants.M_XWR
367    io.sbuffer(i).bits.addr := paddrModule.io.rdata(i)
368    io.sbuffer(i).bits.data := dataModule.io.rdata(i).data
369    io.sbuffer(i).bits.mask := dataModule.io.rdata(i).mask
370    io.sbuffer(i).bits.id   := DontCare
371
372    when (io.sbuffer(i).fire()) {
373      allocated(ptr) := false.B
374      XSDebug("sbuffer "+i+" fire: ptr %d\n", ptr)
375    }
376  }
377  when (io.sbuffer(1).fire()) {
378    assert(io.sbuffer(0).fire())
379  }
380
381  val storeCommit = PopCount(io.sbuffer.map(_.fire()))
382  val waddr = VecInit(io.sbuffer.map(req => SignExt(req.bits.addr, 64)))
383  val wdata = VecInit(io.sbuffer.map(req => req.bits.data & MaskExpand(req.bits.mask)))
384  val wmask = VecInit(io.sbuffer.map(_.bits.mask))
385
386  if (!env.FPGAPlatform) {
387    difftestIO.storeCommit := RegNext(storeCommit)
388    difftestIO.storeAddr   := RegNext(waddr)
389    difftestIO.storeData   := RegNext(wdata)
390    difftestIO.storeMask   := RegNext(wmask)
391  }
392
393  // Read vaddr for mem exception
394  io.exceptionAddr.vaddr := vaddrModule.io.rdata(0)
395
396  // misprediction recovery / exception redirect
397  // invalidate sq term using robIdx
398  val needCancel = Wire(Vec(StoreQueueSize, Bool()))
399  for (i <- 0 until StoreQueueSize) {
400    needCancel(i) := uop(i).roqIdx.needFlush(io.brqRedirect, io.flush) && allocated(i) && !commited(i)
401    when (needCancel(i)) {
402        allocated(i) := false.B
403    }
404  }
405
406  /**
407    * update pointers
408    */
409  val lastCycleRedirect = RegNext(io.brqRedirect.valid)
410  val lastCycleFlush = RegNext(io.flush)
411  val lastCycleCancelCount = PopCount(RegNext(needCancel))
412  // when io.brqRedirect.valid, we don't allow eneuque even though it may fire.
413  val enqNumber = Mux(io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush), PopCount(io.enq.req.map(_.valid)), 0.U)
414  when (lastCycleRedirect || lastCycleFlush) {
415    // we recover the pointers in the next cycle after redirect
416    enqPtrExt := VecInit(enqPtrExt.map(_ - lastCycleCancelCount))
417  }.otherwise {
418    enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber))
419  }
420
421  deqPtrExt := deqPtrExtNext
422
423  val dequeueCount = Mux(io.sbuffer(1).fire(), 2.U, Mux(io.sbuffer(0).fire() || io.mmioStout.fire(), 1.U, 0.U))
424  val validCount = distanceBetween(enqPtrExt(0), deqPtrExt(0))
425
426  allowEnqueue := validCount + enqNumber <= (StoreQueueSize - RenameWidth).U
427
428  // io.sqempty will be used by sbuffer
429  // We delay it for 1 cycle for better timing
430  // When sbuffer need to check if it is empty, the pipeline is blocked, which means delay io.sqempty
431  // for 1 cycle will also promise that sq is empty in that cycle
432  io.sqempty := RegNext(enqPtrExt(0).value === deqPtrExt(0).value && enqPtrExt(0).flag === deqPtrExt(0).flag)
433
434  // perf counter
435  QueuePerf(StoreQueueSize, validCount, !allowEnqueue)
436  XSPerfAccumulate("mmioCycle", uncacheState =/= s_idle) // lq is busy dealing with uncache req
437  XSPerfAccumulate("mmioCnt", io.uncache.req.fire())
438  XSPerfAccumulate("mmio_wb_success", io.mmioStout.fire())
439  XSPerfAccumulate("mmio_wb_blocked", io.mmioStout.valid && !io.mmioStout.ready)
440  XSPerfAccumulate("validEntryCnt", distanceBetween(enqPtrExt(0), deqPtrExt(0)))
441  XSPerfAccumulate("cmtEntryCnt", distanceBetween(cmtPtrExt(0), deqPtrExt(0)))
442  XSPerfAccumulate("nCmtEntryCnt", distanceBetween(enqPtrExt(0), cmtPtrExt(0)))
443
444  // debug info
445  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt(0).flag, deqPtr)
446
447  def PrintFlag(flag: Bool, name: String): Unit = {
448    when(flag) {
449      XSDebug(false, true.B, name)
450    }.otherwise {
451      XSDebug(false, true.B, " ")
452    }
453  }
454
455  for (i <- 0 until StoreQueueSize) {
456    if (i % 4 == 0) XSDebug("")
457    XSDebug(false, true.B, "%x ", uop(i).cf.pc)
458    PrintFlag(allocated(i), "a")
459    PrintFlag(allocated(i) && datavalid(i), "v")
460    PrintFlag(allocated(i) && writebacked(i), "w")
461    PrintFlag(allocated(i) && commited(i), "c")
462    PrintFlag(allocated(i) && pending(i), "p")
463    XSDebug(false, true.B, " ")
464    if (i % 4 == 3 || i == StoreQueueSize - 1) XSDebug(false, true.B, "\n")
465  }
466
467}
468