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