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