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