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