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