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