xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/StoreQueue.scala (revision 2d7c7105479bec3c329cf213502bd6a01cff7c0a)
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.RoqPtr
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 LoadForwardQueryIO))
42    val commits = Flipped(new RoqCommitIO)
43    val uncache = new DCacheWordIO
44    val roqDeqPtr = Input(new RoqPtr)
45    // val refill = Flipped(Valid(new DCacheLineReq ))
46    val exceptionAddr = new ExceptionAddrIO
47    val sqempty = Output(Bool())
48  })
49
50  // data modules
51  val uop = Reg(Vec(StoreQueueSize, new MicroOp))
52  // val data = Reg(Vec(StoreQueueSize, new LsqEntry))
53  val dataModule = Module(new StoreQueueData(StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth, numForward = StorePipelineWidth))
54  dataModule.io := DontCare
55  val vaddrModule = Module(new AsyncDataModuleTemplate(UInt(VAddrBits.W), StoreQueueSize, numRead = 1, numWrite = StorePipelineWidth))
56  vaddrModule.io := DontCare
57
58  // state & misc
59  val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated
60  val datavalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio data is valid
61  val writebacked = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // inst has been writebacked to CDB
62  val commited = Reg(Vec(StoreQueueSize, Bool())) // inst has been commited by roq
63  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
64  val mmio = Reg(Vec(StoreQueueSize, Bool())) // mmio: inst is an mmio inst
65
66  // ptr
67  require(StoreQueueSize > RenameWidth)
68  val enqPtrExt = RegInit(VecInit((0 until RenameWidth).map(_.U.asTypeOf(new SqPtr))))
69  val deqPtrExt = RegInit(VecInit((0 until StorePipelineWidth).map(_.U.asTypeOf(new SqPtr))))
70  val validCounter = RegInit(0.U(log2Ceil(LoadQueueSize + 1).W))
71  val allowEnqueue = RegInit(true.B)
72
73  val enqPtr = enqPtrExt(0).value
74  val deqPtr = deqPtrExt(0).value
75
76  val tailMask = UIntToMask(deqPtr, StoreQueueSize)
77  val headMask = UIntToMask(enqPtr, StoreQueueSize)
78
79  // Read dataModule
80  // deqPtrExtNext and deqPtrExtNext+1 entry will be read from dataModule
81  // if !sbuffer.fire(), read the same ptr
82  // if sbuffer.fire(), read next
83  val deqPtrExtNext = WireInit(Mux(io.sbuffer(1).fire(),
84    VecInit(deqPtrExt.map(_ + 2.U)),
85    Mux(io.sbuffer(0).fire() || io.mmioStout.fire(),
86      VecInit(deqPtrExt.map(_ + 1.U)),
87      deqPtrExt
88    )
89  ))
90  val dataModuleRead = dataModule.io.rdata
91  for (i <- 0 until StorePipelineWidth) {
92    dataModule.io.raddr(i) := deqPtrExtNext(i).value
93  }
94  vaddrModule.io.raddr(0) := io.exceptionAddr.lsIdx.sqIdx.value
95
96  /**
97    * Enqueue at dispatch
98    *
99    * Currently, StoreQueue only allows enqueue when #emptyEntries > RenameWidth(EnqWidth)
100    */
101  io.enq.canAccept := allowEnqueue
102  for (i <- 0 until RenameWidth) {
103    val offset = if (i == 0) 0.U else PopCount(io.enq.needAlloc.take(i))
104    val sqIdx = enqPtrExt(offset)
105    val index = sqIdx.value
106    when (io.enq.req(i).valid && io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush)) {
107      uop(index) := io.enq.req(i).bits
108      allocated(index) := true.B
109      datavalid(index) := false.B
110      writebacked(index) := false.B
111      commited(index) := false.B
112      pending(index) := false.B
113    }
114    io.enq.resp(i) := sqIdx
115  }
116  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
117
118  /**
119    * Writeback store from store units
120    *
121    * Most store instructions writeback to regfile in the previous cycle.
122    * However,
123    *   (1) For an mmio instruction with exceptions, we need to mark it as datavalid
124    * (in this way it will trigger an exception when it reaches ROB's head)
125    * instead of pending to avoid sending them to lower level.
126    *   (2) For an mmio instruction without exceptions, we mark it as pending.
127    * When the instruction reaches ROB's head, StoreQueue sends it to uncache channel.
128    * Upon receiving the response, StoreQueue writes back the instruction
129    * through arbiter with store units. It will later commit as normal.
130    */
131  for (i <- 0 until StorePipelineWidth) {
132    dataModule.io.wen(i) := false.B
133    vaddrModule.io.wen(i) := false.B
134    when (io.storeIn(i).fire()) {
135      val stWbIndex = io.storeIn(i).bits.uop.sqIdx.value
136      datavalid(stWbIndex) := !io.storeIn(i).bits.mmio
137      writebacked(stWbIndex) := !io.storeIn(i).bits.mmio
138      pending(stWbIndex) := io.storeIn(i).bits.mmio
139
140      val storeWbData = Wire(new SQDataEntry)
141      storeWbData := DontCare
142      storeWbData.paddr := io.storeIn(i).bits.paddr
143      storeWbData.mask := io.storeIn(i).bits.mask
144      storeWbData.data := io.storeIn(i).bits.data
145      dataModule.io.waddr(i) := stWbIndex
146      dataModule.io.wdata(i) := storeWbData
147      dataModule.io.wen(i) := true.B
148
149      vaddrModule.io.waddr(i) := stWbIndex
150      vaddrModule.io.wdata(i) := io.storeIn(i).bits.vaddr
151      vaddrModule.io.wen(i) := true.B
152
153      mmio(stWbIndex) := io.storeIn(i).bits.mmio
154
155      XSInfo("store write to sq idx %d pc 0x%x vaddr %x paddr %x data %x mmio %x\n",
156        io.storeIn(i).bits.uop.sqIdx.value,
157        io.storeIn(i).bits.uop.cf.pc,
158        io.storeIn(i).bits.vaddr,
159        io.storeIn(i).bits.paddr,
160        io.storeIn(i).bits.data,
161        io.storeIn(i).bits.mmio
162        )
163    }
164  }
165
166  /**
167    * load forward query
168    *
169    * Check store queue for instructions that is older than the load.
170    * The response will be valid at the next cycle after req.
171    */
172  // check over all lq entries and forward data from the first matched store
173  for (i <- 0 until LoadPipelineWidth) {
174    io.forward(i).forwardMask := 0.U(8.W).asBools
175    io.forward(i).forwardData := DontCare
176
177    // Compare deqPtr (deqPtr) and forward.sqIdx, we have two cases:
178    // (1) if they have the same flag, we need to check range(tail, sqIdx)
179    // (2) if they have different flags, we need to check range(tail, LoadQueueSize) and range(0, sqIdx)
180    // Forward1: Mux(same_flag, range(tail, sqIdx), range(tail, LoadQueueSize))
181    // Forward2: Mux(same_flag, 0.U,                   range(0, sqIdx)    )
182    // i.e. forward1 is the target entries with the same flag bits and forward2 otherwise
183    val differentFlag = deqPtrExt(0).flag =/= io.forward(i).sqIdx.flag
184    val forwardMask = UIntToMask(io.forward(i).sqIdx.value, StoreQueueSize)
185    val storeWritebackedVec = WireInit(VecInit(Seq.fill(StoreQueueSize)(false.B)))
186    for (j <- 0 until StoreQueueSize) {
187      storeWritebackedVec(j) := datavalid(j) && allocated(j) // all datavalid terms need to be checked
188    }
189    val needForward1 = Mux(differentFlag, ~tailMask, tailMask ^ forwardMask) & storeWritebackedVec.asUInt
190    val needForward2 = Mux(differentFlag, forwardMask, 0.U(StoreQueueSize.W)) & storeWritebackedVec.asUInt
191
192    XSDebug(p"$i f1 ${Binary(needForward1)} f2 ${Binary(needForward2)} " +
193      p"sqIdx ${io.forward(i).sqIdx} pa ${Hexadecimal(io.forward(i).paddr)}\n"
194    )
195
196    // do real fwd query
197    dataModule.io.forwardQuery(
198      numForward = i,
199      paddr = io.forward(i).paddr,
200      needForward1 = needForward1,
201      needForward2 = needForward2
202    )
203
204    io.forward(i).forwardMask := dataModule.io.forward(i).forwardMask
205    io.forward(i).forwardData := dataModule.io.forward(i).forwardData
206  }
207
208  /**
209    * Memory mapped IO / other uncached operations
210    *
211    * States:
212    * (1) writeback from store units: mark as pending
213    * (2) when they reach ROB's head, they can be sent to uncache channel
214    * (3) response from uncache channel: mark as datavalid
215    * (4) writeback to ROB (and other units): mark as writebacked
216    * (5) ROB commits the instruction: same as normal instructions
217    */
218  //(2) when they reach ROB's head, they can be sent to uncache channel
219  io.uncache.req.valid := pending(deqPtr) && allocated(deqPtr) &&
220    io.commits.info(0).commitType === CommitType.STORE &&
221    io.roqDeqPtr === uop(deqPtr).roqIdx &&
222    !io.commits.isWalk
223
224  io.uncache.req.bits.cmd  := MemoryOpConstants.M_XWR
225  io.uncache.req.bits.addr := dataModule.io.rdata(0).paddr // data(deqPtr) -> rdata(0)
226  io.uncache.req.bits.data := dataModule.io.rdata(0).data
227  io.uncache.req.bits.mask := dataModule.io.rdata(0).mask
228
229  io.uncache.req.bits.meta.id       := DontCare
230  io.uncache.req.bits.meta.vaddr    := DontCare
231  io.uncache.req.bits.meta.paddr    := dataModule.io.rdata(0).paddr
232  io.uncache.req.bits.meta.uop      := uop(deqPtr)
233  io.uncache.req.bits.meta.mmio     := true.B
234  io.uncache.req.bits.meta.tlb_miss := false.B
235  io.uncache.req.bits.meta.mask     := dataModule.io.rdata(0).mask
236  io.uncache.req.bits.meta.replay   := false.B
237
238  when(io.uncache.req.fire()){
239    pending(deqPtr) := false.B
240
241    XSDebug(
242      p"uncache req: pc ${Hexadecimal(uop(deqPtr).cf.pc)} " +
243      p"addr ${Hexadecimal(io.uncache.req.bits.addr)} " +
244      p"data ${Hexadecimal(io.uncache.req.bits.data)} " +
245      p"op ${Hexadecimal(io.uncache.req.bits.cmd)} " +
246      p"mask ${Hexadecimal(io.uncache.req.bits.mask)}\n"
247    )
248  }
249
250  // (3) response from uncache channel: mark as datavalid
251  io.uncache.resp.ready := true.B
252  when (io.uncache.resp.fire()) {
253    datavalid(deqPtr) := true.B
254  }
255
256  // (4) writeback to ROB (and other units): mark as writebacked
257  io.mmioStout.valid := allocated(deqPtr) && datavalid(deqPtr) && !writebacked(deqPtr)
258  io.mmioStout.bits.uop := uop(deqPtr)
259  io.mmioStout.bits.uop.sqIdx := deqPtrExt(0)
260  io.mmioStout.bits.data := dataModuleRead(0).data // dataModuleRead.read(deqPtr)
261  io.mmioStout.bits.redirectValid := false.B
262  io.mmioStout.bits.redirect := DontCare
263  io.mmioStout.bits.brUpdate := DontCare
264  io.mmioStout.bits.debug.isMMIO := true.B
265  io.mmioStout.bits.debug.isPerfCnt := false.B
266  io.mmioStout.bits.fflags := DontCare
267  when (io.mmioStout.fire()) {
268    writebacked(deqPtr) := true.B
269    allocated(deqPtr) := false.B
270  }
271
272  /**
273    * ROB commits store instructions (mark them as commited)
274    *
275    * (1) When store commits, mark it as commited.
276    * (2) They will not be cancelled and can be sent to lower level.
277    */
278  for (i <- 0 until CommitWidth) {
279    val storeCommit = !io.commits.isWalk && io.commits.valid(i) && io.commits.info(i).commitType === CommitType.STORE
280    when (storeCommit) {
281      commited(io.commits.info(i).sqIdx.value) := true.B
282      XSDebug("store commit %d: idx %d\n", i.U, io.commits.info(i).sqIdx.value)
283    }
284  }
285
286  // Commited stores will not be cancelled and can be sent to lower level.
287  // remove retired insts from sq, add retired store to sbuffer
288  for (i <- 0 until StorePipelineWidth) {
289    // We use RegNext to prepare data for sbuffer
290    val ptr = deqPtrExt(i).value
291    // if !sbuffer.fire(), read the same ptr
292    // if sbuffer.fire(), read next
293    io.sbuffer(i).valid := allocated(ptr) && commited(ptr) && !mmio(ptr)
294    io.sbuffer(i).bits.cmd  := MemoryOpConstants.M_XWR
295    io.sbuffer(i).bits.addr := dataModuleRead(i).paddr
296    io.sbuffer(i).bits.data := dataModuleRead(i).data
297    io.sbuffer(i).bits.mask := dataModuleRead(i).mask
298    io.sbuffer(i).bits.meta          := DontCare
299    io.sbuffer(i).bits.meta.tlb_miss := false.B
300    io.sbuffer(i).bits.meta.uop      := DontCare
301    io.sbuffer(i).bits.meta.mmio     := false.B
302    io.sbuffer(i).bits.meta.mask     := io.sbuffer(i).bits.mask
303
304    when (io.sbuffer(i).fire()) {
305      allocated(ptr) := false.B
306      XSDebug("sbuffer "+i+" fire: ptr %d\n", ptr)
307    }
308  }
309  when (io.sbuffer(1).fire()) {
310    assert(io.sbuffer(0).fire())
311  }
312
313  if (!env.FPGAPlatform) {
314    val storeCommit = PopCount(io.sbuffer.map(_.fire()))
315    val waddr = VecInit(io.sbuffer.map(req => SignExt(req.bits.addr, 64)))
316    val wdata = VecInit(io.sbuffer.map(req => req.bits.data & MaskExpand(req.bits.mask)))
317    val wmask = VecInit(io.sbuffer.map(_.bits.mask))
318
319    ExcitingUtils.addSource(RegNext(storeCommit), "difftestStoreCommit", ExcitingUtils.Debug)
320    ExcitingUtils.addSource(RegNext(waddr), "difftestStoreAddr", ExcitingUtils.Debug)
321    ExcitingUtils.addSource(RegNext(wdata), "difftestStoreData", ExcitingUtils.Debug)
322    ExcitingUtils.addSource(RegNext(wmask), "difftestStoreMask", ExcitingUtils.Debug)
323  }
324
325  // Read vaddr for mem exception
326  io.exceptionAddr.vaddr := vaddrModule.io.rdata(0)
327
328  // misprediction recovery / exception redirect
329  // invalidate sq term using robIdx
330  val needCancel = Wire(Vec(StoreQueueSize, Bool()))
331  for (i <- 0 until StoreQueueSize) {
332    needCancel(i) := uop(i).roqIdx.needFlush(io.brqRedirect, io.flush) && allocated(i) && !commited(i)
333    when (needCancel(i)) {
334        allocated(i) := false.B
335    }
336  }
337
338  /**
339    * update pointers
340    */
341  val lastCycleRedirect = RegNext(io.brqRedirect.valid)
342  val lastCycleFlush = RegNext(io.flush)
343  val lastCycleCancelCount = PopCount(RegNext(needCancel))
344  // when io.brqRedirect.valid, we don't allow eneuque even though it may fire.
345  val enqNumber = Mux(io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush), PopCount(io.enq.req.map(_.valid)), 0.U)
346  when (lastCycleRedirect || lastCycleFlush) {
347    // we recover the pointers in the next cycle after redirect
348    enqPtrExt := VecInit(enqPtrExt.map(_ - lastCycleCancelCount))
349  }.otherwise {
350    enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber))
351  }
352
353  deqPtrExt := deqPtrExtNext
354
355  val lastLastCycleRedirect = RegNext(lastCycleRedirect)
356  val dequeueCount = Mux(io.sbuffer(1).fire(), 2.U, Mux(io.sbuffer(0).fire() || io.mmioStout.fire(), 1.U, 0.U))
357  val trueValidCounter = distanceBetween(enqPtrExt(0), deqPtrExt(0))
358  validCounter := Mux(lastLastCycleRedirect,
359    trueValidCounter - dequeueCount,
360    validCounter + enqNumber - dequeueCount
361  )
362
363  allowEnqueue := Mux(io.brqRedirect.valid || io.flush,
364    false.B,
365    Mux(lastLastCycleRedirect,
366      trueValidCounter <= (StoreQueueSize - RenameWidth).U,
367      validCounter + enqNumber <= (StoreQueueSize - RenameWidth).U
368    )
369  )
370
371  // io.sqempty will be used by sbuffer
372  // We delay it for 1 cycle for better timing
373  // When sbuffer need to check if it is empty, the pipeline is blocked, which means delay io.sqempty
374  // for 1 cycle will also promise that sq is empty in that cycle
375  io.sqempty := RegNext(enqPtrExt(0).value === deqPtrExt(0).value && enqPtrExt(0).flag === deqPtrExt(0).flag)
376
377  // debug info
378  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt(0).flag, deqPtr)
379
380  def PrintFlag(flag: Bool, name: String): Unit = {
381    when(flag) {
382      XSDebug(false, true.B, name)
383    }.otherwise {
384      XSDebug(false, true.B, " ")
385    }
386  }
387
388  for (i <- 0 until StoreQueueSize) {
389    if (i % 4 == 0) XSDebug("")
390    XSDebug(false, true.B, "%x [%x] ", uop(i).cf.pc, dataModule.io.debug(i).paddr)
391    PrintFlag(allocated(i), "a")
392    PrintFlag(allocated(i) && datavalid(i), "v")
393    PrintFlag(allocated(i) && writebacked(i), "w")
394    PrintFlag(allocated(i) && commited(i), "c")
395    PrintFlag(allocated(i) && pending(i), "p")
396    XSDebug(false, true.B, " ")
397    if (i % 4 == 3 || i == StoreQueueSize - 1) XSDebug(false, true.B, "\n")
398  }
399
400}
401