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