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