xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/StoreQueue.scala (revision 3db2cf7579cc9b3c36124096d12f797410f73430)
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 SBufferWordReq)) // 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(
80    numEntries = StoreQueueSize,
81    numRead = StorePipelineWidth,
82    numWrite = StorePipelineWidth,
83    numForward = StorePipelineWidth
84  ))
85  dataModule.io := DontCare
86  val paddrModule = Module(new SQAddrModule(
87    dataWidth = PAddrBits,
88    numEntries = StoreQueueSize,
89    numRead = StorePipelineWidth,
90    numWrite = StorePipelineWidth,
91    numForward = StorePipelineWidth
92  ))
93  paddrModule.io := DontCare
94  val vaddrModule = Module(new SQAddrModule(
95    dataWidth = VAddrBits,
96    numEntries = StoreQueueSize,
97    numRead = StorePipelineWidth + 1, // sbuffer 2 + badvaddr 1 (TODO)
98    numWrite = StorePipelineWidth,
99    numForward = StorePipelineWidth
100  ))
101  vaddrModule.io := DontCare
102
103  // state & misc
104  val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated
105  val addrvalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio addr is valid
106  val datavalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio data is valid
107  val allvalid  = VecInit((0 until StoreQueueSize).map(i => addrvalid(i) && datavalid(i))) // non-mmio data & addr is valid
108  val issued = Reg(Vec(StoreQueueSize, Bool())) // inst has been issued by rs
109  val commited = Reg(Vec(StoreQueueSize, Bool())) // inst has been commited by roq
110  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
111  val mmio = Reg(Vec(StoreQueueSize, Bool())) // mmio: inst is an mmio inst
112
113  // ptr
114  require(StoreQueueSize > RenameWidth)
115  val enqPtrExt = RegInit(VecInit((0 until RenameWidth).map(_.U.asTypeOf(new SqPtr))))
116  val deqPtrExt = RegInit(VecInit((0 until StorePipelineWidth).map(_.U.asTypeOf(new SqPtr))))
117  val cmtPtrExt = RegInit(VecInit((0 until CommitWidth).map(_.U.asTypeOf(new SqPtr))))
118  val issuePtrExt = RegInit(0.U.asTypeOf(new SqPtr))
119  val validCounter = RegInit(0.U(log2Ceil(LoadQueueSize + 1).W))
120  val allowEnqueue = RegInit(true.B)
121
122  val enqPtr = enqPtrExt(0).value
123  val deqPtr = deqPtrExt(0).value
124  val cmtPtr = cmtPtrExt(0).value
125
126  val deqMask = UIntToMask(deqPtr, StoreQueueSize)
127  val enqMask = UIntToMask(enqPtr, StoreQueueSize)
128
129  val commitCount = RegNext(io.roq.scommit)
130
131  // Read dataModule
132  // deqPtrExtNext and deqPtrExtNext+1 entry will be read from dataModule
133  // if !sbuffer.fire(), read the same ptr
134  // if sbuffer.fire(), read next
135  val deqPtrExtNext = WireInit(Mux(io.sbuffer(1).fire(),
136    VecInit(deqPtrExt.map(_ + 2.U)),
137    Mux(io.sbuffer(0).fire() || io.mmioStout.fire(),
138      VecInit(deqPtrExt.map(_ + 1.U)),
139      deqPtrExt
140    )
141  ))
142  for (i <- 0 until StorePipelineWidth) {
143    dataModule.io.raddr(i) := deqPtrExtNext(i).value
144    paddrModule.io.raddr(i) := deqPtrExtNext(i).value
145    vaddrModule.io.raddr(i) := deqPtrExtNext(i).value
146  }
147
148  // no inst will be commited 1 cycle before tval update
149  vaddrModule.io.raddr(StorePipelineWidth) := (cmtPtrExt(0) + commitCount).value
150
151  /**
152    * Enqueue at dispatch
153    *
154    * Currently, StoreQueue only allows enqueue when #emptyEntries > RenameWidth(EnqWidth)
155    */
156  io.enq.canAccept := allowEnqueue
157  for (i <- 0 until RenameWidth) {
158    val offset = if (i == 0) 0.U else PopCount(io.enq.needAlloc.take(i))
159    val sqIdx = enqPtrExt(offset)
160    val index = sqIdx.value
161    when (io.enq.req(i).valid && io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush)) {
162      uop(index) := io.enq.req(i).bits
163      allocated(index) := true.B
164      datavalid(index) := false.B
165      addrvalid(index) := false.B
166      issued(index) := false.B
167      commited(index) := false.B
168      pending(index) := false.B
169    }
170    io.enq.resp(i) := sqIdx
171  }
172  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
173
174  /**
175    * Update issuePtr when issue from rs
176    */
177
178  // update state bit issued
179  for (i <- 0 until StorePipelineWidth) {
180    when (io.storeIssue(i).valid) {
181      issued(io.storeIssue(i).bits.uop.sqIdx.value) := true.B
182    }
183  }
184
185  // update issuePtr
186  val IssuePtrMoveStride = 4
187  require(IssuePtrMoveStride >= 2)
188
189  val issueLookupVec = (0 until IssuePtrMoveStride).map(issuePtrExt + _.U)
190  val issueLookup = issueLookupVec.map(ptr => allocated(ptr.value) && issued(ptr.value) && ptr =/= enqPtrExt(0))
191  val nextIssuePtr = issuePtrExt + PriorityEncoder(VecInit(issueLookup.map(!_) :+ true.B))
192  issuePtrExt := nextIssuePtr
193
194  when (io.brqRedirect.valid || io.flush) {
195    issuePtrExt := Mux(
196      isAfter(cmtPtrExt(0), deqPtrExt(0)),
197      cmtPtrExt(0),
198      deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr
199    )
200  }
201  // send issuePtrExt to rs
202  // io.issuePtrExt := cmtPtrExt(0)
203  io.issuePtrExt := issuePtrExt
204
205  /**
206    * Writeback store from store units
207    *
208    * Most store instructions writeback to regfile in the previous cycle.
209    * However,
210    *   (1) For an mmio instruction with exceptions, we need to mark it as addrvalid
211    * (in this way it will trigger an exception when it reaches ROB's head)
212    * instead of pending to avoid sending them to lower level.
213    *   (2) For an mmio instruction without exceptions, we mark it as pending.
214    * When the instruction reaches ROB's head, StoreQueue sends it to uncache channel.
215    * Upon receiving the response, StoreQueue writes back the instruction
216    * through arbiter with store units. It will later commit as normal.
217    */
218
219  // Write addr to sq
220  for (i <- 0 until StorePipelineWidth) {
221    paddrModule.io.wen(i) := false.B
222    vaddrModule.io.wen(i) := false.B
223    dataModule.io.mask.wen(i) := false.B
224    val stWbIndex = io.storeIn(i).bits.uop.sqIdx.value
225    when (io.storeIn(i).fire()) {
226      addrvalid(stWbIndex) := true.B//!io.storeIn(i).bits.mmio
227      pending(stWbIndex) := io.storeIn(i).bits.mmio
228
229      dataModule.io.mask.waddr(i) := stWbIndex
230      dataModule.io.mask.wdata(i) := io.storeIn(i).bits.mask
231      dataModule.io.mask.wen(i) := true.B
232
233      paddrModule.io.waddr(i) := stWbIndex
234      paddrModule.io.wdata(i) := io.storeIn(i).bits.paddr
235      paddrModule.io.wen(i) := true.B
236
237      vaddrModule.io.waddr(i) := stWbIndex
238      vaddrModule.io.wdata(i) := io.storeIn(i).bits.vaddr
239      vaddrModule.io.wen(i) := true.B
240
241      mmio(stWbIndex) := io.storeIn(i).bits.mmio
242
243      XSInfo("store addr write to sq idx %d pc 0x%x vaddr %x paddr %x mmio %x\n",
244        io.storeIn(i).bits.uop.sqIdx.value,
245        io.storeIn(i).bits.uop.cf.pc,
246        io.storeIn(i).bits.vaddr,
247        io.storeIn(i).bits.paddr,
248        io.storeIn(i).bits.mmio
249      )
250    }
251  }
252
253  // Write data to sq
254  for (i <- 0 until StorePipelineWidth) {
255    dataModule.io.data.wen(i) := false.B
256    io.roq.storeDataRoqWb(i).valid := false.B
257    io.roq.storeDataRoqWb(i).bits := DontCare
258    val stWbIndex = io.storeDataIn(i).bits.uop.sqIdx.value
259    when (io.storeDataIn(i).fire()) {
260      datavalid(stWbIndex) := true.B
261
262      dataModule.io.data.waddr(i) := stWbIndex
263      dataModule.io.data.wdata(i) := genWdata(io.storeDataIn(i).bits.data, io.storeDataIn(i).bits.uop.ctrl.fuOpType(1,0))
264      dataModule.io.data.wen(i) := true.B
265
266      io.roq.storeDataRoqWb(i).valid := true.B
267      io.roq.storeDataRoqWb(i).bits := io.storeDataIn(i).bits.uop.roqIdx
268
269      XSInfo("store data write to sq idx %d pc 0x%x data %x -> %x\n",
270        io.storeDataIn(i).bits.uop.sqIdx.value,
271        io.storeDataIn(i).bits.uop.cf.pc,
272        io.storeDataIn(i).bits.data,
273        dataModule.io.data.wdata(i)
274      )
275    }
276  }
277
278  /**
279    * load forward query
280    *
281    * Check store queue for instructions that is older than the load.
282    * The response will be valid at the next cycle after req.
283    */
284  // check over all lq entries and forward data from the first matched store
285  for (i <- 0 until LoadPipelineWidth) {
286    // Compare deqPtr (deqPtr) and forward.sqIdx, we have two cases:
287    // (1) if they have the same flag, we need to check range(tail, sqIdx)
288    // (2) if they have different flags, we need to check range(tail, LoadQueueSize) and range(0, sqIdx)
289    // Forward1: Mux(same_flag, range(tail, sqIdx), range(tail, LoadQueueSize))
290    // Forward2: Mux(same_flag, 0.U,                   range(0, sqIdx)    )
291    // i.e. forward1 is the target entries with the same flag bits and forward2 otherwise
292    val differentFlag = deqPtrExt(0).flag =/= io.forward(i).sqIdx.flag
293    val forwardMask = io.forward(i).sqIdxMask
294    // all addrvalid terms need to be checked
295    val addrValidVec = WireInit(VecInit((0 until StoreQueueSize).map(i => addrvalid(i) && allocated(i))))
296    val dataValidVec = WireInit(VecInit((0 until StoreQueueSize).map(i => datavalid(i))))
297    val allValidVec = WireInit(VecInit((0 until StoreQueueSize).map(i => addrvalid(i) && datavalid(i) && allocated(i))))
298    val canForward1 = Mux(differentFlag, ~deqMask, deqMask ^ forwardMask) & allValidVec.asUInt
299    val canForward2 = Mux(differentFlag, forwardMask, 0.U(StoreQueueSize.W)) & allValidVec.asUInt
300    val needForward = Mux(differentFlag, ~deqMask | forwardMask, deqMask ^ forwardMask)
301
302    XSDebug(p"$i f1 ${Binary(canForward1)} f2 ${Binary(canForward2)} " +
303      p"sqIdx ${io.forward(i).sqIdx} pa ${Hexadecimal(io.forward(i).paddr)}\n"
304    )
305
306    // do real fwd query (cam lookup in load_s1)
307    dataModule.io.needForward(i)(0) := canForward1 & vaddrModule.io.forwardMmask(i).asUInt
308    dataModule.io.needForward(i)(1) := canForward2 & vaddrModule.io.forwardMmask(i).asUInt
309
310    vaddrModule.io.forwardMdata(i) := io.forward(i).vaddr
311    paddrModule.io.forwardMdata(i) := io.forward(i).paddr
312
313    // vaddr cam result does not equal to paddr cam result
314    // replay needed
315    // val vpmaskNotEqual = ((paddrModule.io.forwardMmask(i).asUInt ^ vaddrModule.io.forwardMmask(i).asUInt) & needForward) =/= 0.U
316    // val vaddrMatchFailed = vpmaskNotEqual && io.forward(i).valid
317    val vpmaskNotEqual = ((RegNext(paddrModule.io.forwardMmask(i).asUInt) ^ RegNext(vaddrModule.io.forwardMmask(i).asUInt)) & RegNext(needForward)) =/= 0.U
318    val vaddrMatchFailed = vpmaskNotEqual && RegNext(io.forward(i).valid)
319    when (vaddrMatchFailed) {
320      XSInfo("vaddrMatchFailed: pc %x pmask %x vmask %x\n",
321        RegNext(io.forward(i).uop.cf.pc),
322        RegNext(needForward & paddrModule.io.forwardMmask(i).asUInt),
323        RegNext(needForward & vaddrModule.io.forwardMmask(i).asUInt)
324      );
325    }
326    XSPerfAccumulate("vaddr_match_failed", vpmaskNotEqual)
327    XSPerfAccumulate("vaddr_match_really_failed", vaddrMatchFailed)
328
329    // Fast forward mask will be generated immediately (load_s1)
330    io.forward(i).forwardMaskFast := dataModule.io.forwardMaskFast(i)
331
332    // Forward result will be generated 1 cycle later (load_s2)
333    io.forward(i).forwardMask := dataModule.io.forwardMask(i)
334    io.forward(i).forwardData := dataModule.io.forwardData(i)
335
336    // If addr match, data not ready, mark it as dataInvalid
337    // load_s1: generate dataInvalid in load_s1 to set fastUop to
338    io.forward(i).dataInvalidFast := (addrValidVec.asUInt & ~dataValidVec.asUInt & vaddrModule.io.forwardMmask(i).asUInt & needForward).orR
339    // load_s2
340    io.forward(i).dataInvalid := RegNext(io.forward(i).dataInvalidFast)
341
342    // load_s2
343    // check if vaddr forward mismatched
344    io.forward(i).matchInvalid := vaddrMatchFailed
345  }
346
347  /**
348    * Memory mapped IO / other uncached operations
349    *
350    * States:
351    * (1) writeback from store units: mark as pending
352    * (2) when they reach ROB's head, they can be sent to uncache channel
353    * (3) response from uncache channel: mark as datavalidmask.wen
354    * (4) writeback to ROB (and other units): mark as writebacked
355    * (5) ROB commits the instruction: same as normal instructions
356    */
357  //(2) when they reach ROB's head, they can be sent to uncache channel
358  val s_idle :: s_req :: s_resp :: s_wb :: s_wait :: Nil = Enum(5)
359  val uncacheState = RegInit(s_idle)
360  switch(uncacheState) {
361    is(s_idle) {
362      when(io.roq.pendingst && pending(deqPtr) && allocated(deqPtr) && datavalid(deqPtr) && addrvalid(deqPtr)) {
363        uncacheState := s_req
364      }
365    }
366    is(s_req) {
367      when(io.uncache.req.fire()) {
368        uncacheState := s_resp
369      }
370    }
371    is(s_resp) {
372      when(io.uncache.resp.fire()) {
373        uncacheState := s_wb
374      }
375    }
376    is(s_wb) {
377      when (io.mmioStout.fire()) {
378        uncacheState := s_wait
379      }
380    }
381    is(s_wait) {
382      when(io.roq.commit) {
383        uncacheState := s_idle // ready for next mmio
384      }
385    }
386  }
387  io.uncache.req.valid := uncacheState === s_req
388
389  io.uncache.req.bits.cmd  := MemoryOpConstants.M_XWR
390  io.uncache.req.bits.addr := paddrModule.io.rdata(0) // data(deqPtr) -> rdata(0)
391  io.uncache.req.bits.data := dataModule.io.rdata(0).data
392  io.uncache.req.bits.mask := dataModule.io.rdata(0).mask
393
394  io.uncache.req.bits.id   := DontCare
395
396  when(io.uncache.req.fire()){
397    // mmio store should not be committed until uncache req is sent
398    pending(deqPtr) := false.B
399
400    XSDebug(
401      p"uncache req: pc ${Hexadecimal(uop(deqPtr).cf.pc)} " +
402      p"addr ${Hexadecimal(io.uncache.req.bits.addr)} " +
403      p"data ${Hexadecimal(io.uncache.req.bits.data)} " +
404      p"op ${Hexadecimal(io.uncache.req.bits.cmd)} " +
405      p"mask ${Hexadecimal(io.uncache.req.bits.mask)}\n"
406    )
407  }
408
409  // (3) response from uncache channel: mark as datavalid
410  io.uncache.resp.ready := true.B
411
412  // (4) writeback to ROB (and other units): mark as writebacked
413  io.mmioStout.valid := uncacheState === s_wb
414  io.mmioStout.bits.uop := uop(deqPtr)
415  io.mmioStout.bits.uop.sqIdx := deqPtrExt(0)
416  io.mmioStout.bits.data := dataModule.io.rdata(0).data // dataModule.io.rdata.read(deqPtr)
417  io.mmioStout.bits.redirectValid := false.B
418  io.mmioStout.bits.redirect := DontCare
419  io.mmioStout.bits.debug.isMMIO := true.B
420  io.mmioStout.bits.debug.paddr := DontCare
421  io.mmioStout.bits.debug.isPerfCnt := false.B
422  io.mmioStout.bits.fflags := DontCare
423  // Remove MMIO inst from store queue after MMIO request is being sent
424  // That inst will be traced by uncache state machine
425  when (io.mmioStout.fire()) {
426    allocated(deqPtr) := false.B
427  }
428
429  /**
430    * ROB commits store instructions (mark them as commited)
431    *
432    * (1) When store commits, mark it as commited.
433    * (2) They will not be cancelled and can be sent to lower level.
434    */
435  XSError(uncacheState === s_wait && commitCount > 1.U, "should only commit one instruction when there's an MMIO\n")
436  XSError(uncacheState =/= s_idle && uncacheState =/= s_wait && commitCount > 0.U,
437   "should not commit instruction when MMIO has not been finished\n")
438  for (i <- 0 until CommitWidth) {
439    when (commitCount > i.U && uncacheState === s_idle) { // MMIO inst is not in progress
440      commited(cmtPtrExt(i).value) := true.B
441    }
442  }
443  cmtPtrExt := cmtPtrExt.map(_ + commitCount)
444
445  // Commited stores will not be cancelled and can be sent to lower level.
446  // remove retired insts from sq, add retired store to sbuffer
447  for (i <- 0 until StorePipelineWidth) {
448    // We use RegNext to prepare data for sbuffer
449    val ptr = deqPtrExt(i).value
450    // if !sbuffer.fire(), read the same ptr
451    // if sbuffer.fire(), read next
452    io.sbuffer(i).valid := allocated(ptr) && commited(ptr) && !mmio(ptr)
453    // Note that store data/addr should both be valid after store's commit
454    assert(!io.sbuffer(i).valid || allvalid(ptr))
455    io.sbuffer(i).bits.cmd   := MemoryOpConstants.M_XWR
456    io.sbuffer(i).bits.addr  := paddrModule.io.rdata(i)
457    io.sbuffer(i).bits.vaddr := vaddrModule.io.rdata(i)
458    io.sbuffer(i).bits.data  := dataModule.io.rdata(i).data
459    io.sbuffer(i).bits.mask  := dataModule.io.rdata(i).mask
460    io.sbuffer(i).bits.id    := DontCare
461
462    when (io.sbuffer(i).fire()) {
463      allocated(ptr) := false.B
464      XSDebug("sbuffer "+i+" fire: ptr %d\n", ptr)
465    }
466  }
467  when (io.sbuffer(1).fire()) {
468    assert(io.sbuffer(0).fire())
469  }
470  if (useFakeDCache) {
471    for (i <- 0 until StorePipelineWidth) {
472      val ptr = deqPtrExt(i).value
473      val fakeRAM = Module(new RAMHelper(64L * 1024 * 1024 * 1024))
474      fakeRAM.io.clk   := clock
475      fakeRAM.io.en    := allocated(ptr) && commited(ptr) && !mmio(ptr)
476      fakeRAM.io.rIdx  := 0.U
477      fakeRAM.io.wIdx  := (paddrModule.io.rdata(i) - "h80000000".U) >> 3
478      fakeRAM.io.wdata := dataModule.io.rdata(i).data
479      fakeRAM.io.wmask := MaskExpand(dataModule.io.rdata(i).mask)
480      fakeRAM.io.wen   := allocated(ptr) && commited(ptr) && !mmio(ptr)
481    }
482  }
483
484  if (!env.FPGAPlatform) {
485    for (i <- 0 until StorePipelineWidth) {
486      val storeCommit = io.sbuffer(i).fire()
487      val waddr = SignExt(io.sbuffer(i).bits.addr, 64)
488      val wdata = io.sbuffer(i).bits.data & MaskExpand(io.sbuffer(i).bits.mask)
489      val wmask = io.sbuffer(i).bits.mask
490
491      val difftest = Module(new DifftestStoreEvent)
492      difftest.io.clock       := clock
493      difftest.io.coreid      := hardId.U
494      difftest.io.index       := i.U
495      difftest.io.valid       := storeCommit
496      difftest.io.storeAddr   := waddr
497      difftest.io.storeData   := wdata
498      difftest.io.storeMask   := wmask
499    }
500  }
501
502  // Read vaddr for mem exception
503  io.exceptionAddr.vaddr := vaddrModule.io.rdata(StorePipelineWidth)
504
505  // misprediction recovery / exception redirect
506  // invalidate sq term using robIdx
507  val needCancel = Wire(Vec(StoreQueueSize, Bool()))
508  for (i <- 0 until StoreQueueSize) {
509    needCancel(i) := uop(i).roqIdx.needFlush(io.brqRedirect, io.flush) && allocated(i) && !commited(i)
510    when (needCancel(i)) {
511        allocated(i) := false.B
512    }
513  }
514
515  /**
516    * update pointers
517    */
518  val lastCycleRedirect = RegNext(io.brqRedirect.valid)
519  val lastCycleFlush = RegNext(io.flush)
520  val lastCycleCancelCount = PopCount(RegNext(needCancel))
521  // when io.brqRedirect.valid, we don't allow eneuque even though it may fire.
522  val enqNumber = Mux(io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush), PopCount(io.enq.req.map(_.valid)), 0.U)
523  when (lastCycleRedirect || lastCycleFlush) {
524    // we recover the pointers in the next cycle after redirect
525    enqPtrExt := VecInit(enqPtrExt.map(_ - lastCycleCancelCount))
526  }.otherwise {
527    enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber))
528  }
529
530  deqPtrExt := deqPtrExtNext
531
532  val dequeueCount = Mux(io.sbuffer(1).fire(), 2.U, Mux(io.sbuffer(0).fire() || io.mmioStout.fire(), 1.U, 0.U))
533  val validCount = distanceBetween(enqPtrExt(0), deqPtrExt(0))
534
535  allowEnqueue := validCount + enqNumber <= (StoreQueueSize - RenameWidth).U
536
537  // io.sqempty will be used by sbuffer
538  // We delay it for 1 cycle for better timing
539  // When sbuffer need to check if it is empty, the pipeline is blocked, which means delay io.sqempty
540  // for 1 cycle will also promise that sq is empty in that cycle
541  io.sqempty := RegNext(enqPtrExt(0).value === deqPtrExt(0).value && enqPtrExt(0).flag === deqPtrExt(0).flag)
542
543  // perf counter
544  QueuePerf(StoreQueueSize, validCount, !allowEnqueue)
545  io.sqFull := !allowEnqueue
546  XSPerfAccumulate("mmioCycle", uncacheState =/= s_idle) // lq is busy dealing with uncache req
547  XSPerfAccumulate("mmioCnt", io.uncache.req.fire())
548  XSPerfAccumulate("mmio_wb_success", io.mmioStout.fire())
549  XSPerfAccumulate("mmio_wb_blocked", io.mmioStout.valid && !io.mmioStout.ready)
550  XSPerfAccumulate("validEntryCnt", distanceBetween(enqPtrExt(0), deqPtrExt(0)))
551  XSPerfAccumulate("cmtEntryCnt", distanceBetween(cmtPtrExt(0), deqPtrExt(0)))
552  XSPerfAccumulate("nCmtEntryCnt", distanceBetween(enqPtrExt(0), cmtPtrExt(0)))
553
554  // debug info
555  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt(0).flag, deqPtr)
556
557  def PrintFlag(flag: Bool, name: String): Unit = {
558    when(flag) {
559      XSDebug(false, true.B, name)
560    }.otherwise {
561      XSDebug(false, true.B, " ")
562    }
563  }
564
565  for (i <- 0 until StoreQueueSize) {
566    if (i % 4 == 0) XSDebug("")
567    XSDebug(false, true.B, "%x v[%x] p[%x]",
568      uop(i).cf.pc,
569      vaddrModule.io.debug_data(i),
570      paddrModule.io.debug_data(i),
571    )
572    PrintFlag(allocated(i), "a")
573    PrintFlag(allocated(i) && addrvalid(i), "a")
574    PrintFlag(allocated(i) && datavalid(i), "d")
575    PrintFlag(allocated(i) && commited(i), "c")
576    PrintFlag(allocated(i) && pending(i), "p")
577    PrintFlag(allocated(i) && mmio(i), "m")
578    XSDebug(false, true.B, " ")
579    if (i % 4 == 3 || i == StoreQueueSize - 1) XSDebug(false, true.B, "\n")
580  }
581
582}
583