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