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