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