xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/StoreQueue.scala (revision d57bda64dd69dbc246bd52257ef7392f220149aa)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.mem
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import xiangshan._
24import xiangshan.cache._
25import xiangshan.cache.{DCacheWordIO, DCacheLineIO, MemoryOpConstants}
26import xiangshan.backend.roq.{RoqLsqIO, RoqPtr}
27import difftest._
28import device.RAMHelper
29
30class SqPtr(implicit p: Parameters) extends CircularQueuePtr[SqPtr](
31  p => p(XSCoreParamsKey).StoreQueueSize
32){
33  override def cloneType = (new SqPtr).asInstanceOf[this.type]
34}
35
36object SqPtr {
37  def apply(f: Bool, v: UInt)(implicit p: Parameters): SqPtr = {
38    val ptr = Wire(new SqPtr)
39    ptr.flag := f
40    ptr.value := v
41    ptr
42  }
43}
44
45class SqEnqIO(implicit p: Parameters) extends XSBundle {
46  val canAccept = Output(Bool())
47  val lqCanAccept = Input(Bool())
48  val needAlloc = Vec(RenameWidth, Input(Bool()))
49  val req = Vec(RenameWidth, Flipped(ValidIO(new MicroOp)))
50  val resp = Vec(RenameWidth, Output(new SqPtr))
51}
52
53// Store Queue
54class StoreQueue(implicit p: Parameters) extends XSModule with HasDCacheParameters with HasCircularQueuePtrHelper {
55  val io = IO(new Bundle() {
56    val enq = new SqEnqIO
57    val brqRedirect = Flipped(ValidIO(new Redirect))
58    val flush = Input(Bool())
59    val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle))) // store addr, data is not included
60    val storeDataIn = Vec(StorePipelineWidth, Flipped(Valid(new StoreDataBundle))) // store data, send to sq from rs
61    val sbuffer = Vec(StorePipelineWidth, Decoupled(new DCacheWordReq)) // write commited store to sbuffer
62    val mmioStout = DecoupledIO(new ExuOutput) // writeback uncached store
63    val forward = Vec(LoadPipelineWidth, Flipped(new PipeLoadForwardQueryIO))
64    val roq = Flipped(new RoqLsqIO)
65    val uncache = new DCacheWordIO
66    // val refill = Flipped(Valid(new DCacheLineReq ))
67    val exceptionAddr = new ExceptionAddrIO
68    val sqempty = Output(Bool())
69    val issuePtrExt = Output(new SqPtr) // used to wake up delayed load/store
70    val storeIssue = Vec(StorePipelineWidth, Flipped(Valid(new ExuInput))) // used to update issuePtrExt
71    val sqFull = Output(Bool())
72  })
73
74  println("StoreQueue: size:" + StoreQueueSize)
75
76  // data modules
77  val uop = Reg(Vec(StoreQueueSize, new MicroOp))
78  // val data = Reg(Vec(StoreQueueSize, new LsqEntry))
79  val dataModule = Module(new SQDataModule(StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth, numForward = StorePipelineWidth))
80  dataModule.io := DontCare
81  val paddrModule = Module(new SQPaddrModule(StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth, numForward = StorePipelineWidth))
82  paddrModule.io := DontCare
83  val vaddrModule = Module(new SyncDataModuleTemplate(UInt(VAddrBits.W), StoreQueueSize, numRead = 1, numWrite = StorePipelineWidth))
84  vaddrModule.io := DontCare
85
86  // state & misc
87  val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated
88  val addrvalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio addr is valid
89  val datavalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio data is valid
90  val allvalid  = VecInit((0 until StoreQueueSize).map(i => addrvalid(i) && datavalid(i))) // non-mmio data & addr is valid
91  val issued = Reg(Vec(StoreQueueSize, Bool())) // inst has been issued by rs
92  val commited = Reg(Vec(StoreQueueSize, Bool())) // inst has been commited by roq
93  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
94  val mmio = Reg(Vec(StoreQueueSize, Bool())) // mmio: inst is an mmio inst
95
96  // ptr
97  require(StoreQueueSize > RenameWidth)
98  val enqPtrExt = RegInit(VecInit((0 until RenameWidth).map(_.U.asTypeOf(new SqPtr))))
99  val deqPtrExt = RegInit(VecInit((0 until StorePipelineWidth).map(_.U.asTypeOf(new SqPtr))))
100  val cmtPtrExt = RegInit(VecInit((0 until CommitWidth).map(_.U.asTypeOf(new SqPtr))))
101  val issuePtrExt = RegInit(0.U.asTypeOf(new SqPtr))
102  val validCounter = RegInit(0.U(log2Ceil(LoadQueueSize + 1).W))
103  val allowEnqueue = RegInit(true.B)
104
105  val enqPtr = enqPtrExt(0).value
106  val deqPtr = deqPtrExt(0).value
107  val cmtPtr = cmtPtrExt(0).value
108
109  val deqMask = UIntToMask(deqPtr, StoreQueueSize)
110  val enqMask = UIntToMask(enqPtr, StoreQueueSize)
111
112  val commitCount = RegNext(io.roq.scommit)
113
114  // Read dataModule
115  // deqPtrExtNext and deqPtrExtNext+1 entry will be read from dataModule
116  // if !sbuffer.fire(), read the same ptr
117  // if sbuffer.fire(), read next
118  val deqPtrExtNext = WireInit(Mux(io.sbuffer(1).fire(),
119    VecInit(deqPtrExt.map(_ + 2.U)),
120    Mux(io.sbuffer(0).fire() || io.mmioStout.fire(),
121      VecInit(deqPtrExt.map(_ + 1.U)),
122      deqPtrExt
123    )
124  ))
125  for (i <- 0 until StorePipelineWidth) {
126    dataModule.io.raddr(i) := deqPtrExtNext(i).value
127    paddrModule.io.raddr(i) := deqPtrExtNext(i).value
128  }
129
130  // no inst will be commited 1 cycle before tval update
131  vaddrModule.io.raddr(0) := (cmtPtrExt(0) + commitCount).value
132
133  /**
134    * Enqueue at dispatch
135    *
136    * Currently, StoreQueue only allows enqueue when #emptyEntries > RenameWidth(EnqWidth)
137    */
138  io.enq.canAccept := allowEnqueue
139  for (i <- 0 until RenameWidth) {
140    val offset = if (i == 0) 0.U else PopCount(io.enq.needAlloc.take(i))
141    val sqIdx = enqPtrExt(offset)
142    val index = sqIdx.value
143    when (io.enq.req(i).valid && io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush)) {
144      uop(index) := io.enq.req(i).bits
145      allocated(index) := true.B
146      datavalid(index) := false.B
147      addrvalid(index) := false.B
148      issued(index) := false.B
149      commited(index) := false.B
150      pending(index) := false.B
151    }
152    io.enq.resp(i) := sqIdx
153  }
154  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
155
156  /**
157    * Update issuePtr when issue from rs
158    */
159
160  // update state bit issued
161  for (i <- 0 until StorePipelineWidth) {
162    when (io.storeIssue(i).valid) {
163      issued(io.storeIssue(i).bits.uop.sqIdx.value) := true.B
164    }
165  }
166
167  // update issuePtr
168  val IssuePtrMoveStride = 4
169  require(IssuePtrMoveStride >= 2)
170
171  val issueLookupVec = (0 until IssuePtrMoveStride).map(issuePtrExt + _.U)
172  val issueLookup = issueLookupVec.map(ptr => allocated(ptr.value) && issued(ptr.value) && ptr =/= enqPtrExt(0))
173  val nextIssuePtr = issuePtrExt + PriorityEncoder(VecInit(issueLookup.map(!_) :+ true.B))
174  issuePtrExt := nextIssuePtr
175
176  when (io.brqRedirect.valid || io.flush) {
177    issuePtrExt := Mux(
178      isAfter(cmtPtrExt(0), deqPtrExt(0)),
179      cmtPtrExt(0),
180      deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr
181    )
182  }
183  // send issuePtrExt to rs
184  // io.issuePtrExt := cmtPtrExt(0)
185  io.issuePtrExt := issuePtrExt
186
187  /**
188    * Writeback store from store units
189    *
190    * Most store instructions writeback to regfile in the previous cycle.
191    * However,
192    *   (1) For an mmio instruction with exceptions, we need to mark it as addrvalid
193    * (in this way it will trigger an exception when it reaches ROB's head)
194    * instead of pending to avoid sending them to lower level.
195    *   (2) For an mmio instruction without exceptions, we mark it as pending.
196    * When the instruction reaches ROB's head, StoreQueue sends it to uncache channel.
197    * Upon receiving the response, StoreQueue writes back the instruction
198    * through arbiter with store units. It will later commit as normal.
199    */
200
201  // Write addr to sq
202  for (i <- 0 until StorePipelineWidth) {
203    paddrModule.io.wen(i) := false.B
204    dataModule.io.mask.wen(i) := false.B
205    val stWbIndex = io.storeIn(i).bits.uop.sqIdx.value
206    when (io.storeIn(i).fire()) {
207      addrvalid(stWbIndex) := true.B//!io.storeIn(i).bits.mmio
208      pending(stWbIndex) := io.storeIn(i).bits.mmio
209
210      dataModule.io.mask.waddr(i) := stWbIndex
211      dataModule.io.mask.wdata(i) := io.storeIn(i).bits.mask
212      dataModule.io.mask.wen(i) := true.B
213
214      paddrModule.io.waddr(i) := stWbIndex
215      paddrModule.io.wdata(i) := io.storeIn(i).bits.paddr
216      paddrModule.io.wen(i) := true.B
217
218      mmio(stWbIndex) := io.storeIn(i).bits.mmio
219
220      XSInfo("store addr write to sq idx %d pc 0x%x vaddr %x paddr %x mmio %x\n",
221        io.storeIn(i).bits.uop.sqIdx.value,
222        io.storeIn(i).bits.uop.cf.pc,
223        io.storeIn(i).bits.vaddr,
224        io.storeIn(i).bits.paddr,
225        io.storeIn(i).bits.mmio
226      )
227    }
228    // vaddrModule write is delayed, as vaddrModule will not be read right after write
229    vaddrModule.io.waddr(i) := RegNext(stWbIndex)
230    vaddrModule.io.wdata(i) := RegNext(io.storeIn(i).bits.vaddr)
231    vaddrModule.io.wen(i) := RegNext(io.storeIn(i).fire())
232  }
233
234  // Write data to sq
235  for (i <- 0 until StorePipelineWidth) {
236    dataModule.io.data.wen(i) := false.B
237    io.roq.storeDataRoqWb(i).valid := false.B
238    io.roq.storeDataRoqWb(i).bits := DontCare
239    val stWbIndex = io.storeDataIn(i).bits.uop.sqIdx.value
240    when (io.storeDataIn(i).fire()) {
241      datavalid(stWbIndex) := true.B
242
243      dataModule.io.data.waddr(i) := stWbIndex
244      dataModule.io.data.wdata(i) := genWdata(io.storeDataIn(i).bits.data, io.storeDataIn(i).bits.uop.ctrl.fuOpType(1,0))
245      dataModule.io.data.wen(i) := true.B
246
247      io.roq.storeDataRoqWb(i).valid := true.B
248      io.roq.storeDataRoqWb(i).bits := io.storeDataIn(i).bits.uop.roqIdx
249
250      XSInfo("store data write to sq idx %d pc 0x%x data %x -> %x\n",
251        io.storeDataIn(i).bits.uop.sqIdx.value,
252        io.storeDataIn(i).bits.uop.cf.pc,
253        io.storeDataIn(i).bits.data,
254        dataModule.io.data.wdata(i)
255      )
256    }
257  }
258
259  /**
260    * load forward query
261    *
262    * Check store queue for instructions that is older than the load.
263    * The response will be valid at the next cycle after req.
264    */
265  // check over all lq entries and forward data from the first matched store
266  for (i <- 0 until LoadPipelineWidth) {
267    io.forward(i).forwardMask := 0.U(8.W).asBools
268    io.forward(i).forwardData := DontCare
269
270    // Compare deqPtr (deqPtr) and forward.sqIdx, we have two cases:
271    // (1) if they have the same flag, we need to check range(tail, sqIdx)
272    // (2) if they have different flags, we need to check range(tail, LoadQueueSize) and range(0, sqIdx)
273    // Forward1: Mux(same_flag, range(tail, sqIdx), range(tail, LoadQueueSize))
274    // Forward2: Mux(same_flag, 0.U,                   range(0, sqIdx)    )
275    // i.e. forward1 is the target entries with the same flag bits and forward2 otherwise
276    val differentFlag = deqPtrExt(0).flag =/= io.forward(i).sqIdx.flag
277    val forwardMask = io.forward(i).sqIdxMask
278    // all addrvalid terms need to be checked
279    val addrValidVec = WireInit(VecInit((0 until StoreQueueSize).map(i => addrvalid(i) && allocated(i))))
280    val dataValidVec = WireInit(VecInit((0 until StoreQueueSize).map(i => datavalid(i))))
281    val allValidVec = WireInit(VecInit((0 until StoreQueueSize).map(i => addrvalid(i) && datavalid(i) && allocated(i))))
282    val canForward1 = Mux(differentFlag, ~deqMask, deqMask ^ forwardMask) & allValidVec.asUInt
283    val canForward2 = Mux(differentFlag, forwardMask, 0.U(StoreQueueSize.W)) & allValidVec.asUInt
284    val needForward = Mux(differentFlag, ~deqMask | forwardMask, deqMask ^ forwardMask)
285
286    XSDebug(p"$i f1 ${Binary(canForward1)} f2 ${Binary(canForward2)} " +
287      p"sqIdx ${io.forward(i).sqIdx} pa ${Hexadecimal(io.forward(i).paddr)}\n"
288    )
289
290    // do real fwd query (cam lookup in load_s1)
291    dataModule.io.needForward(i)(0) := canForward1 & paddrModule.io.forwardMmask(i).asUInt
292    dataModule.io.needForward(i)(1) := canForward2 & paddrModule.io.forwardMmask(i).asUInt
293
294    paddrModule.io.forwardMdata(i) := io.forward(i).paddr
295
296    // Forward result will be generated 1 cycle later (load_s2)
297    io.forward(i).forwardMask := dataModule.io.forwardMask(i)
298    io.forward(i).forwardData := dataModule.io.forwardData(i)
299
300    // If addr match, data not ready, mark it as dataInvalid
301    // load_s1: generate dataInvalid in load_s1 to set fastUop to
302    io.forward(i).dataInvalidFast := (addrValidVec.asUInt & ~dataValidVec.asUInt & paddrModule.io.forwardMmask(i).asUInt & needForward).orR
303    // load_s2
304    io.forward(i).dataInvalid := RegNext(io.forward(i).dataInvalidFast)
305  }
306
307  /**
308    * Memory mapped IO / other uncached operations
309    *
310    * States:
311    * (1) writeback from store units: mark as pending
312    * (2) when they reach ROB's head, they can be sent to uncache channel
313    * (3) response from uncache channel: mark as datavalidmask.wen
314    * (4) writeback to ROB (and other units): mark as writebacked
315    * (5) ROB commits the instruction: same as normal instructions
316    */
317  //(2) when they reach ROB's head, they can be sent to uncache channel
318  val s_idle :: s_req :: s_resp :: s_wb :: s_wait :: Nil = Enum(5)
319  val uncacheState = RegInit(s_idle)
320  switch(uncacheState) {
321    is(s_idle) {
322      when(io.roq.pendingst && pending(deqPtr) && allocated(deqPtr) && datavalid(deqPtr) && addrvalid(deqPtr)) {
323        uncacheState := s_req
324      }
325    }
326    is(s_req) {
327      when(io.uncache.req.fire()) {
328        uncacheState := s_resp
329      }
330    }
331    is(s_resp) {
332      when(io.uncache.resp.fire()) {
333        uncacheState := s_wb
334      }
335    }
336    is(s_wb) {
337      when (io.mmioStout.fire()) {
338        uncacheState := s_wait
339      }
340    }
341    is(s_wait) {
342      when(io.roq.commit) {
343        uncacheState := s_idle // ready for next mmio
344      }
345    }
346  }
347  io.uncache.req.valid := uncacheState === s_req
348
349  io.uncache.req.bits.cmd  := MemoryOpConstants.M_XWR
350  io.uncache.req.bits.addr := paddrModule.io.rdata(0) // data(deqPtr) -> rdata(0)
351  io.uncache.req.bits.data := dataModule.io.rdata(0).data
352  io.uncache.req.bits.mask := dataModule.io.rdata(0).mask
353
354  io.uncache.req.bits.id   := DontCare
355
356  when(io.uncache.req.fire()){
357    // mmio store should not be committed until uncache req is sent
358    pending(deqPtr) := false.B
359
360    XSDebug(
361      p"uncache req: pc ${Hexadecimal(uop(deqPtr).cf.pc)} " +
362      p"addr ${Hexadecimal(io.uncache.req.bits.addr)} " +
363      p"data ${Hexadecimal(io.uncache.req.bits.data)} " +
364      p"op ${Hexadecimal(io.uncache.req.bits.cmd)} " +
365      p"mask ${Hexadecimal(io.uncache.req.bits.mask)}\n"
366    )
367  }
368
369  // (3) response from uncache channel: mark as datavalid
370  io.uncache.resp.ready := true.B
371
372  // (4) writeback to ROB (and other units): mark as writebacked
373  io.mmioStout.valid := uncacheState === s_wb
374  io.mmioStout.bits.uop := uop(deqPtr)
375  io.mmioStout.bits.uop.sqIdx := deqPtrExt(0)
376  io.mmioStout.bits.data := dataModule.io.rdata(0).data // dataModule.io.rdata.read(deqPtr)
377  io.mmioStout.bits.redirectValid := false.B
378  io.mmioStout.bits.redirect := DontCare
379  io.mmioStout.bits.debug.isMMIO := true.B
380  io.mmioStout.bits.debug.paddr := DontCare
381  io.mmioStout.bits.debug.isPerfCnt := false.B
382  io.mmioStout.bits.fflags := DontCare
383  // Remove MMIO inst from store queue after MMIO request is being sent
384  // That inst will be traced by uncache state machine
385  when (io.mmioStout.fire()) {
386    allocated(deqPtr) := false.B
387  }
388
389  /**
390    * ROB commits store instructions (mark them as commited)
391    *
392    * (1) When store commits, mark it as commited.
393    * (2) They will not be cancelled and can be sent to lower level.
394    */
395  XSError(uncacheState === s_wait && commitCount > 1.U, "should only commit one instruction when there's an MMIO\n")
396  XSError(uncacheState =/= s_idle && uncacheState =/= s_wait && commitCount > 0.U,
397   "should not commit instruction when MMIO has not been finished\n")
398  for (i <- 0 until CommitWidth) {
399    when (commitCount > i.U && uncacheState === s_idle) { // MMIO inst is not in progress
400      commited(cmtPtrExt(i).value) := true.B
401    }
402  }
403  cmtPtrExt := cmtPtrExt.map(_ + commitCount)
404
405  // Commited stores will not be cancelled and can be sent to lower level.
406  // remove retired insts from sq, add retired store to sbuffer
407  for (i <- 0 until StorePipelineWidth) {
408    // We use RegNext to prepare data for sbuffer
409    val ptr = deqPtrExt(i).value
410    // if !sbuffer.fire(), read the same ptr
411    // if sbuffer.fire(), read next
412    io.sbuffer(i).valid := allocated(ptr) && commited(ptr) && !mmio(ptr)
413    // Note that store data/addr should both be valid after store's commit
414    assert(!io.sbuffer(i).valid || allvalid(ptr))
415    io.sbuffer(i).bits.cmd  := MemoryOpConstants.M_XWR
416    io.sbuffer(i).bits.addr := paddrModule.io.rdata(i)
417    io.sbuffer(i).bits.data := dataModule.io.rdata(i).data
418    io.sbuffer(i).bits.mask := dataModule.io.rdata(i).mask
419    io.sbuffer(i).bits.id   := DontCare
420
421    when (io.sbuffer(i).fire()) {
422      allocated(ptr) := false.B
423      XSDebug("sbuffer "+i+" fire: ptr %d\n", ptr)
424    }
425  }
426  when (io.sbuffer(1).fire()) {
427    assert(io.sbuffer(0).fire())
428  }
429  if (useFakeDCache) {
430    for (i <- 0 until StorePipelineWidth) {
431      val ptr = deqPtrExt(i).value
432      val fakeRAM = Module(new RAMHelper(64L * 1024 * 1024 * 1024))
433      fakeRAM.io.clk   := clock
434      fakeRAM.io.en    := allocated(ptr) && commited(ptr) && !mmio(ptr)
435      fakeRAM.io.rIdx  := 0.U
436      fakeRAM.io.wIdx  := (paddrModule.io.rdata(i) - "h80000000".U) >> 3
437      fakeRAM.io.wdata := dataModule.io.rdata(i).data
438      fakeRAM.io.wmask := MaskExpand(dataModule.io.rdata(i).mask)
439      fakeRAM.io.wen   := allocated(ptr) && commited(ptr) && !mmio(ptr)
440    }
441  }
442
443  if (!env.FPGAPlatform) {
444    for (i <- 0 until StorePipelineWidth) {
445      val storeCommit = io.sbuffer(i).fire()
446      val waddr = SignExt(io.sbuffer(i).bits.addr, 64)
447      val wdata = io.sbuffer(i).bits.data & MaskExpand(io.sbuffer(i).bits.mask)
448      val wmask = io.sbuffer(i).bits.mask
449
450      val difftest = Module(new DifftestStoreEvent)
451      difftest.io.clock       := clock
452      difftest.io.coreid      := hardId.U
453      difftest.io.index       := i.U
454      difftest.io.valid       := storeCommit
455      difftest.io.storeAddr   := waddr
456      difftest.io.storeData   := wdata
457      difftest.io.storeMask   := wmask
458    }
459  }
460
461  // Read vaddr for mem exception
462  io.exceptionAddr.vaddr := vaddrModule.io.rdata(0)
463
464  // misprediction recovery / exception redirect
465  // invalidate sq term using robIdx
466  val needCancel = Wire(Vec(StoreQueueSize, Bool()))
467  for (i <- 0 until StoreQueueSize) {
468    needCancel(i) := uop(i).roqIdx.needFlush(io.brqRedirect, io.flush) && allocated(i) && !commited(i)
469    when (needCancel(i)) {
470        allocated(i) := false.B
471    }
472  }
473
474  /**
475    * update pointers
476    */
477  val lastCycleRedirect = RegNext(io.brqRedirect.valid)
478  val lastCycleFlush = RegNext(io.flush)
479  val lastCycleCancelCount = PopCount(RegNext(needCancel))
480  // when io.brqRedirect.valid, we don't allow eneuque even though it may fire.
481  val enqNumber = Mux(io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush), PopCount(io.enq.req.map(_.valid)), 0.U)
482  when (lastCycleRedirect || lastCycleFlush) {
483    // we recover the pointers in the next cycle after redirect
484    enqPtrExt := VecInit(enqPtrExt.map(_ - lastCycleCancelCount))
485  }.otherwise {
486    enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber))
487  }
488
489  deqPtrExt := deqPtrExtNext
490
491  val dequeueCount = Mux(io.sbuffer(1).fire(), 2.U, Mux(io.sbuffer(0).fire() || io.mmioStout.fire(), 1.U, 0.U))
492  val validCount = distanceBetween(enqPtrExt(0), deqPtrExt(0))
493
494  allowEnqueue := validCount + enqNumber <= (StoreQueueSize - RenameWidth).U
495
496  // io.sqempty will be used by sbuffer
497  // We delay it for 1 cycle for better timing
498  // When sbuffer need to check if it is empty, the pipeline is blocked, which means delay io.sqempty
499  // for 1 cycle will also promise that sq is empty in that cycle
500  io.sqempty := RegNext(enqPtrExt(0).value === deqPtrExt(0).value && enqPtrExt(0).flag === deqPtrExt(0).flag)
501
502  // perf counter
503  QueuePerf(StoreQueueSize, validCount, !allowEnqueue)
504  io.sqFull := !allowEnqueue
505  XSPerfAccumulate("mmioCycle", uncacheState =/= s_idle) // lq is busy dealing with uncache req
506  XSPerfAccumulate("mmioCnt", io.uncache.req.fire())
507  XSPerfAccumulate("mmio_wb_success", io.mmioStout.fire())
508  XSPerfAccumulate("mmio_wb_blocked", io.mmioStout.valid && !io.mmioStout.ready)
509  XSPerfAccumulate("validEntryCnt", distanceBetween(enqPtrExt(0), deqPtrExt(0)))
510  XSPerfAccumulate("cmtEntryCnt", distanceBetween(cmtPtrExt(0), deqPtrExt(0)))
511  XSPerfAccumulate("nCmtEntryCnt", distanceBetween(enqPtrExt(0), cmtPtrExt(0)))
512
513  // debug info
514  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt(0).flag, deqPtr)
515
516  def PrintFlag(flag: Bool, name: String): Unit = {
517    when(flag) {
518      XSDebug(false, true.B, name)
519    }.otherwise {
520      XSDebug(false, true.B, " ")
521    }
522  }
523
524  for (i <- 0 until StoreQueueSize) {
525    if (i % 4 == 0) XSDebug("")
526    XSDebug(false, true.B, "%x ", uop(i).cf.pc)
527    PrintFlag(allocated(i), "a")
528    PrintFlag(allocated(i) && addrvalid(i), "a")
529    PrintFlag(allocated(i) && datavalid(i), "d")
530    PrintFlag(allocated(i) && commited(i), "c")
531    PrintFlag(allocated(i) && pending(i), "p")
532    PrintFlag(allocated(i) && mmio(i), "m")
533    XSDebug(false, true.B, " ")
534    if (i % 4 == 3 || i == StoreQueueSize - 1) XSDebug(false, true.B, "\n")
535  }
536
537}
538