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