xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/StoreQueue.scala (revision 3088616cbf0793407bb68460b2db89b7de80c12a)
1/***************************************************************************************
2* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
4* Copyright (c) 2020-2021 Peng Cheng Laboratory
5*
6* XiangShan is licensed under Mulan PSL v2.
7* You can use this software according to the terms and conditions of the Mulan PSL v2.
8* You may obtain a copy of Mulan PSL v2 at:
9*          http://license.coscl.org.cn/MulanPSL2
10*
11* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
12* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
13* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
14*
15* See the Mulan PSL v2 for more details.
16***************************************************************************************/
17
18package xiangshan.mem
19
20import chisel3._
21import chisel3.util._
22import difftest._
23import difftest.common.DifftestMem
24import org.chipsalliance.cde.config.Parameters
25import utility._
26import utils._
27import xiangshan._
28import xiangshan.cache._
29import xiangshan.cache.{DCacheLineIO, DCacheWordIO, MemoryOpConstants}
30import xiangshan.backend._
31import xiangshan.backend.rob.{RobLsqIO, RobPtr}
32import xiangshan.backend.Bundles.{DynInst, MemExuOutput}
33import xiangshan.backend.decode.isa.bitfield.{Riscv32BitInst, XSInstBitFields}
34import xiangshan.backend.fu.FuConfig._
35import xiangshan.backend.fu.FuType
36import xiangshan.ExceptionNO._
37import coupledL2.{CMOReq, CMOResp}
38
39class SqPtr(implicit p: Parameters) extends CircularQueuePtr[SqPtr](
40  p => p(XSCoreParamsKey).StoreQueueSize
41){
42}
43
44object SqPtr {
45  def apply(f: Bool, v: UInt)(implicit p: Parameters): SqPtr = {
46    val ptr = Wire(new SqPtr)
47    ptr.flag := f
48    ptr.value := v
49    ptr
50  }
51}
52
53class SqEnqIO(implicit p: Parameters) extends MemBlockBundle {
54  val canAccept = Output(Bool())
55  val lqCanAccept = Input(Bool())
56  val needAlloc = Vec(LSQEnqWidth, Input(Bool()))
57  val req = Vec(LSQEnqWidth, Flipped(ValidIO(new DynInst)))
58  val resp = Vec(LSQEnqWidth, Output(new SqPtr))
59}
60
61class DataBufferEntry (implicit p: Parameters)  extends DCacheBundle {
62  val addr   = UInt(PAddrBits.W)
63  val vaddr  = UInt(VAddrBits.W)
64  val data   = UInt(VLEN.W)
65  val mask   = UInt((VLEN/8).W)
66  val wline = Bool()
67  val sqPtr  = new SqPtr
68  val prefetch = Bool()
69  val vecValid = Bool()
70}
71
72class StoreExceptionBuffer(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
73  val io = IO(new Bundle() {
74    val redirect = Flipped(ValidIO(new Redirect))
75    val storeAddrIn = Vec(StorePipelineWidth * 2 + VecStorePipelineWidth, Flipped(ValidIO(new LsPipelineBundle())))
76    val flushFrmMaBuf = Input(Bool())
77    val exceptionAddr = new ExceptionAddrIO
78  })
79
80  val req_valid = RegInit(false.B)
81  val req = Reg(new LsPipelineBundle())
82
83  // enqueue
84  // S1:
85  val s1_req = VecInit(io.storeAddrIn.map(_.bits))
86  val s1_valid = VecInit(io.storeAddrIn.map(x =>
87      x.valid && !x.bits.uop.robIdx.needFlush(io.redirect) && ExceptionNO.selectByFu(x.bits.uop.exceptionVec, StaCfg).asUInt.orR
88  ))
89
90  // S2: delay 1 cycle
91  val s2_req = (0 until StorePipelineWidth * 2 + VecStorePipelineWidth).map(i =>
92    RegEnable(s1_req(i), s1_valid(i)))
93  val s2_valid = (0 until StorePipelineWidth * 2 + VecStorePipelineWidth).map(i =>
94    RegNext(s1_valid(i)) && !s2_req(i).uop.robIdx.needFlush(io.redirect)
95  )
96
97  val s2_enqueue = Wire(Vec(StorePipelineWidth * 2 + VecStorePipelineWidth, Bool()))
98  for (w <- 0 until StorePipelineWidth * 2 + VecStorePipelineWidth) {
99    s2_enqueue(w) := s2_valid(w)
100  }
101
102  when (req_valid && req.uop.robIdx.needFlush(io.redirect)) {
103    req_valid := s2_enqueue.asUInt.orR
104  }.elsewhen (s2_enqueue.asUInt.orR) {
105    req_valid := req_valid || true.B
106  }
107
108  def selectOldest[T <: LsPipelineBundle](valid: Seq[Bool], bits: Seq[T]): (Seq[Bool], Seq[T]) = {
109    assert(valid.length == bits.length)
110    if (valid.length == 0 || valid.length == 1) {
111      (valid, bits)
112    } else if (valid.length == 2) {
113      val res = Seq.fill(2)(Wire(Valid(chiselTypeOf(bits(0)))))
114      for (i <- res.indices) {
115        res(i).valid := valid(i)
116        res(i).bits := bits(i)
117      }
118      val oldest = Mux(valid(0) && valid(1),
119        Mux(isAfter(bits(0).uop.robIdx, bits(1).uop.robIdx) ||
120          (isNotBefore(bits(0).uop.robIdx, bits(1).uop.robIdx) && bits(0).uop.uopIdx > bits(1).uop.uopIdx), res(1), res(0)),
121        Mux(valid(0) && !valid(1), res(0), res(1)))
122      (Seq(oldest.valid), Seq(oldest.bits))
123    } else {
124      val left = selectOldest(valid.take(valid.length / 2), bits.take(bits.length / 2))
125      val right = selectOldest(valid.takeRight(valid.length - (valid.length / 2)), bits.takeRight(bits.length - (bits.length / 2)))
126      selectOldest(left._1 ++ right._1, left._2 ++ right._2)
127    }
128  }
129
130  val reqSel = selectOldest(s2_enqueue, s2_req)
131
132  when (req_valid) {
133    req := Mux(
134      reqSel._1(0) && (isAfter(req.uop.robIdx, reqSel._2(0).uop.robIdx) || (isNotBefore(req.uop.robIdx, reqSel._2(0).uop.robIdx) && req.uop.uopIdx > reqSel._2(0).uop.uopIdx)),
135      reqSel._2(0),
136      req)
137  } .elsewhen (s2_enqueue.asUInt.orR) {
138    req := reqSel._2(0)
139  }
140
141  io.exceptionAddr.vaddr  := req.vaddr
142  io.exceptionAddr.gpaddr := req.gpaddr
143  io.exceptionAddr.vstart := req.uop.vpu.vstart
144  io.exceptionAddr.vl     := req.uop.vpu.vl
145
146  when(req_valid && io.flushFrmMaBuf) {
147    req_valid := false.B
148  }
149}
150
151// Store Queue
152class StoreQueue(implicit p: Parameters) extends XSModule
153  with HasDCacheParameters
154  with HasCircularQueuePtrHelper
155  with HasPerfEvents
156  with HasVLSUParameters {
157  val io = IO(new Bundle() {
158    val hartId = Input(UInt(hartIdLen.W))
159    val enq = new SqEnqIO
160    val brqRedirect = Flipped(ValidIO(new Redirect))
161    val vecFeedback = Vec(VecLoadPipelineWidth, Flipped(ValidIO(new FeedbackToLsqIO)))
162    val storeAddrIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle))) // store addr, data is not included
163    val storeAddrInRe = Vec(StorePipelineWidth, Input(new LsPipelineBundle())) // store more mmio and exception
164    val storeDataIn = Vec(StorePipelineWidth, Flipped(Valid(new MemExuOutput(isVector = true)))) // store data, send to sq from rs
165    val storeMaskIn = Vec(StorePipelineWidth, Flipped(Valid(new StoreMaskBundle))) // store mask, send to sq from rs
166    val sbuffer = Vec(EnsbufferWidth, Decoupled(new DCacheWordReqWithVaddrAndPfFlag)) // write committed store to sbuffer
167    val sbufferVecDifftestInfo = Vec(EnsbufferWidth, Decoupled(new DynInst)) // The vector store difftest needs is, write committed store to sbuffer
168    val uncacheOutstanding = Input(Bool())
169    val cmoOpReq  = DecoupledIO(new CMOReq)
170    val cmoOpResp = Flipped(DecoupledIO(new CMOResp))
171    val mmioStout = DecoupledIO(new MemExuOutput) // writeback uncached store
172    val vecmmioStout = DecoupledIO(new MemExuOutput(isVector = true))
173    val forward = Vec(LoadPipelineWidth, Flipped(new PipeLoadForwardQueryIO))
174    // TODO: scommit is only for scalar store
175    val rob = Flipped(new RobLsqIO)
176    val uncache = new UncacheWordIO
177    // val refill = Flipped(Valid(new DCacheLineReq ))
178    val exceptionAddr = new ExceptionAddrIO
179    val flushSbuffer = new SbufferFlushBundle
180    val sqEmpty = Output(Bool())
181    val stAddrReadySqPtr = Output(new SqPtr)
182    val stAddrReadyVec = Output(Vec(StoreQueueSize, Bool()))
183    val stDataReadySqPtr = Output(new SqPtr)
184    val stDataReadyVec = Output(Vec(StoreQueueSize, Bool()))
185    val stIssuePtr = Output(new SqPtr)
186    val sqDeqPtr = Output(new SqPtr)
187    val sqFull = Output(Bool())
188    val sqCancelCnt = Output(UInt(log2Up(StoreQueueSize + 1).W))
189    val sqDeq = Output(UInt(log2Ceil(EnsbufferWidth + 1).W))
190    val force_write = Output(Bool())
191    val maControl   = Flipped(new StoreMaBufToSqControlIO)
192  })
193
194  println("StoreQueue: size:" + StoreQueueSize)
195
196  // data modules
197  val uop = Reg(Vec(StoreQueueSize, new DynInst))
198  // val data = Reg(Vec(StoreQueueSize, new LsqEntry))
199  val dataModule = Module(new SQDataModule(
200    numEntries = StoreQueueSize,
201    numRead = EnsbufferWidth,
202    numWrite = StorePipelineWidth,
203    numForward = LoadPipelineWidth
204  ))
205  dataModule.io := DontCare
206  val paddrModule = Module(new SQAddrModule(
207    dataWidth = PAddrBits,
208    numEntries = StoreQueueSize,
209    numRead = EnsbufferWidth,
210    numWrite = StorePipelineWidth,
211    numForward = LoadPipelineWidth
212  ))
213  paddrModule.io := DontCare
214  val vaddrModule = Module(new SQAddrModule(
215    dataWidth = VAddrBits,
216    numEntries = StoreQueueSize,
217    numRead = EnsbufferWidth, // sbuffer; badvaddr will be sent from exceptionBuffer
218    numWrite = StorePipelineWidth,
219    numForward = LoadPipelineWidth
220  ))
221  vaddrModule.io := DontCare
222  val dataBuffer = Module(new DatamoduleResultBuffer(new DataBufferEntry))
223  val difftestBuffer = if (env.EnableDifftest) Some(Module(new DatamoduleResultBuffer(new DynInst))) else None
224  val exceptionBuffer = Module(new StoreExceptionBuffer)
225  exceptionBuffer.io.redirect := io.brqRedirect
226  exceptionBuffer.io.exceptionAddr.isStore := DontCare
227  // vlsu exception!
228  for (i <- 0 until VecStorePipelineWidth) {
229    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).valid               := io.vecFeedback(i).valid && io.vecFeedback(i).bits.feedback(VecFeedbacks.FLUSH) // have exception
230    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits                := DontCare
231    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.vaddr          := io.vecFeedback(i).bits.vaddr
232    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.uop.uopIdx     := io.vecFeedback(i).bits.uopidx
233    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.uop.robIdx     := io.vecFeedback(i).bits.robidx
234    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.uop.vpu.vstart := io.vecFeedback(i).bits.vstart
235    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.uop.vpu.vl     := io.vecFeedback(i).bits.vl
236    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.uop.exceptionVec     := io.vecFeedback(i).bits.exceptionVec
237  }
238
239
240  val debug_paddr = Reg(Vec(StoreQueueSize, UInt((PAddrBits).W)))
241  val debug_vaddr = Reg(Vec(StoreQueueSize, UInt((VAddrBits).W)))
242  val debug_data = Reg(Vec(StoreQueueSize, UInt((XLEN).W)))
243
244  // state & misc
245  val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated
246  val addrvalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio addr is valid
247  val datavalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio data is valid
248  val allvalid  = VecInit((0 until StoreQueueSize).map(i => addrvalid(i) && datavalid(i))) // non-mmio data & addr is valid
249  val committed = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // inst has been committed by rob
250  val unaligned = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // unaligned store
251  val pending = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // mmio pending: inst is an mmio inst, it will not be executed until it reachs the end of rob
252  val mmio = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // mmio: inst is an mmio inst
253  val atomic = RegInit(VecInit(List.fill(StoreQueueSize)(false.B)))
254  val prefetch = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // need prefetch when committing this store to sbuffer?
255  val isVec = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // vector store instruction
256  //val vec_lastuop = Reg(Vec(StoreQueueSize, Bool())) // last uop of vector store instruction
257  val vecMbCommit = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // vector store committed from merge buffer to rob
258  val vecDataValid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // vector store need write to sbuffer
259  val hasException = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // store has exception, should deq but not write sbuffer
260  val waitStoreS2 = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // wait for mmio and exception result until store_s2
261  // val vec_robCommit = Reg(Vec(StoreQueueSize, Bool())) // vector store committed by rob
262  // val vec_secondInv = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // Vector unit-stride, second entry is invalid
263  val vecExceptionFlag = RegInit(0.U.asTypeOf(Valid(new DynInst)))
264
265  // ptr
266  val enqPtrExt = RegInit(VecInit((0 until io.enq.req.length).map(_.U.asTypeOf(new SqPtr))))
267  val rdataPtrExt = RegInit(VecInit((0 until EnsbufferWidth).map(_.U.asTypeOf(new SqPtr))))
268  val deqPtrExt = RegInit(VecInit((0 until EnsbufferWidth).map(_.U.asTypeOf(new SqPtr))))
269  val cmtPtrExt = RegInit(VecInit((0 until CommitWidth).map(_.U.asTypeOf(new SqPtr))))
270  val addrReadyPtrExt = RegInit(0.U.asTypeOf(new SqPtr))
271  val dataReadyPtrExt = RegInit(0.U.asTypeOf(new SqPtr))
272
273  val enqPtr = enqPtrExt(0).value
274  val deqPtr = deqPtrExt(0).value
275  val cmtPtr = cmtPtrExt(0).value
276
277  val validCount = distanceBetween(enqPtrExt(0), deqPtrExt(0))
278  val allowEnqueue = validCount <= (StoreQueueSize - LSQStEnqWidth).U
279
280  val deqMask = UIntToMask(deqPtr, StoreQueueSize)
281  val enqMask = UIntToMask(enqPtr, StoreQueueSize)
282
283  val commitCount = WireInit(0.U(log2Ceil(CommitWidth + 1).W))
284  val scommit = GatedRegNext(io.rob.scommit)
285
286  // RegNext misalign control for better timing
287  val doMisalignSt = GatedValidRegNext((rdataPtrExt(0).value === deqPtr) && (cmtPtr === deqPtr) && allocated(deqPtr) && datavalid(deqPtr) && unaligned(deqPtr) && !isVec(deqPtr))
288  val finishMisalignSt = GatedValidRegNext(doMisalignSt && io.maControl.control.removeSq && !io.maControl.control.hasException)
289  val misalignBlock = doMisalignSt && !finishMisalignSt
290
291  // store miss align info
292  io.maControl.storeInfo.data := dataModule.io.rdata(0).data
293  io.maControl.storeInfo.dataReady := doMisalignSt
294  io.maControl.storeInfo.completeSbTrans := doMisalignSt && dataBuffer.io.enq(0).fire
295
296  // store can be committed by ROB
297  io.rob.mmio := DontCare
298  io.rob.uop := DontCare
299
300  // Read dataModule
301  assert(EnsbufferWidth <= 2)
302  // rdataPtrExtNext and rdataPtrExtNext+1 entry will be read from dataModule
303  val rdataPtrExtNext = Wire(Vec(EnsbufferWidth, new SqPtr))
304  rdataPtrExtNext := WireInit(Mux(dataBuffer.io.enq(1).fire,
305    VecInit(rdataPtrExt.map(_ + 2.U)),
306    Mux(dataBuffer.io.enq(0).fire || io.mmioStout.fire || io.vecmmioStout.fire,
307      VecInit(rdataPtrExt.map(_ + 1.U)),
308      rdataPtrExt
309    )
310  ))
311
312  // deqPtrExtNext traces which inst is about to leave store queue
313  //
314  // io.sbuffer(i).fire is RegNexted, as sbuffer data write takes 2 cycles.
315  // Before data write finish, sbuffer is unable to provide store to load
316  // forward data. As an workaround, deqPtrExt and allocated flag update
317  // is delayed so that load can get the right data from store queue.
318  //
319  // Modify deqPtrExtNext and io.sqDeq with care!
320  val deqPtrExtNext = Wire(Vec(EnsbufferWidth, new SqPtr))
321  deqPtrExtNext := Mux(RegNext(io.sbuffer(1).fire),
322    VecInit(deqPtrExt.map(_ + 2.U)),
323    Mux((RegNext(io.sbuffer(0).fire)) || io.mmioStout.fire || io.vecmmioStout.fire,
324      VecInit(deqPtrExt.map(_ + 1.U)),
325      deqPtrExt
326    )
327  )
328
329  io.sqDeq := RegNext(Mux(RegNext(io.sbuffer(1).fire && !misalignBlock), 2.U,
330    Mux((RegNext(io.sbuffer(0).fire && !misalignBlock)) || io.mmioStout.fire || io.vecmmioStout.fire || finishMisalignSt, 1.U, 0.U)
331  ))
332  assert(!RegNext(RegNext(io.sbuffer(0).fire) && (io.mmioStout.fire || io.vecmmioStout.fire)))
333
334  for (i <- 0 until EnsbufferWidth) {
335    dataModule.io.raddr(i) := rdataPtrExtNext(i).value
336    paddrModule.io.raddr(i) := rdataPtrExtNext(i).value
337    vaddrModule.io.raddr(i) := rdataPtrExtNext(i).value
338  }
339
340  /**
341    * Enqueue at dispatch
342    *
343    * Currently, StoreQueue only allows enqueue when #emptyEntries > EnqWidth
344    */
345  io.enq.canAccept := allowEnqueue
346  val canEnqueue = io.enq.req.map(_.valid)
347  val enqCancel = io.enq.req.map(_.bits.robIdx.needFlush(io.brqRedirect))
348  val vStoreFlow = io.enq.req.map(_.bits.numLsElem)
349  val validVStoreFlow = vStoreFlow.zipWithIndex.map{case (vLoadFlowNumItem, index) => Mux(!RegNext(io.brqRedirect.valid) && canEnqueue(index), vLoadFlowNumItem, 0.U)}
350  val validVStoreOffset = vStoreFlow.zip(io.enq.needAlloc).map{case (flow, needAllocItem) => Mux(needAllocItem, flow, 0.U)}
351  val validVStoreOffsetRShift = 0.U +: validVStoreOffset.take(vStoreFlow.length - 1)
352
353  for (i <- 0 until io.enq.req.length) {
354    val sqIdx = enqPtrExt(0) + validVStoreOffsetRShift.take(i + 1).reduce(_ + _)
355    val index = io.enq.req(i).bits.sqIdx
356    val enqInstr = io.enq.req(i).bits.instr.asTypeOf(new XSInstBitFields)
357    when (canEnqueue(i) && !enqCancel(i)) {
358      // The maximum 'numLsElem' number that can be emitted per dispatch port is:
359      //    16 2 2 2 2 2.
360      // Therefore, VecMemLSQEnqIteratorNumberSeq = Seq(16, 2, 2, 2, 2, 2)
361      for (j <- 0 until VecMemLSQEnqIteratorNumberSeq(i)) {
362        when (j.U < validVStoreOffset(i)) {
363          uop((index + j.U).value) := io.enq.req(i).bits
364          // NOTE: the index will be used when replay
365          uop((index + j.U).value).sqIdx := sqIdx + j.U
366          allocated((index + j.U).value) := true.B
367          datavalid((index + j.U).value) := false.B
368          addrvalid((index + j.U).value) := false.B
369          unaligned((index + j.U).value) := false.B
370          committed((index + j.U).value) := false.B
371          pending((index + j.U).value) := false.B
372          prefetch((index + j.U).value) := false.B
373          mmio((index + j.U).value) := false.B
374          isVec((index + j.U).value) := enqInstr.isVecStore // check vector store by the encoding of inst
375          vecMbCommit((index + j.U).value) := false.B
376          vecDataValid((index + j.U).value) := false.B
377          hasException((index + j.U).value) := false.B
378          waitStoreS2((index + j.U).value) := true.B
379          XSError(!io.enq.canAccept || !io.enq.lqCanAccept, s"must accept $i\n")
380          XSError(index.value =/= sqIdx.value, s"must be the same entry $i\n")
381        }
382      }
383    }
384    io.enq.resp(i) := sqIdx
385  }
386  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
387
388  /**
389    * Update addr/dataReadyPtr when issue from rs
390    */
391  // update issuePtr
392  val IssuePtrMoveStride = 4
393  require(IssuePtrMoveStride >= 2)
394
395  val addrReadyLookupVec = (0 until IssuePtrMoveStride).map(addrReadyPtrExt + _.U)
396  val addrReadyLookup = addrReadyLookupVec.map(ptr => allocated(ptr.value) &&
397   (mmio(ptr.value) || addrvalid(ptr.value) || vecMbCommit(ptr.value))
398    && ptr =/= enqPtrExt(0))
399  val nextAddrReadyPtr = addrReadyPtrExt + PriorityEncoder(VecInit(addrReadyLookup.map(!_) :+ true.B))
400  addrReadyPtrExt := nextAddrReadyPtr
401
402  val stAddrReadyVecReg = Wire(Vec(StoreQueueSize, Bool()))
403  (0 until StoreQueueSize).map(i => {
404    stAddrReadyVecReg(i) := allocated(i) && (mmio(i) || addrvalid(i) || (isVec(i) && vecMbCommit(i)))
405  })
406  io.stAddrReadyVec := GatedValidRegNext(stAddrReadyVecReg)
407
408  when (io.brqRedirect.valid) {
409    addrReadyPtrExt := Mux(
410      isAfter(cmtPtrExt(0), deqPtrExt(0)),
411      cmtPtrExt(0),
412      deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr
413    )
414  }
415
416  io.stAddrReadySqPtr := addrReadyPtrExt
417
418  // update
419  val dataReadyLookupVec = (0 until IssuePtrMoveStride).map(dataReadyPtrExt + _.U)
420  val dataReadyLookup = dataReadyLookupVec.map(ptr => allocated(ptr.value) &&
421   (mmio(ptr.value) || datavalid(ptr.value) || vecMbCommit(ptr.value))
422    && ptr =/= enqPtrExt(0))
423  val nextDataReadyPtr = dataReadyPtrExt + PriorityEncoder(VecInit(dataReadyLookup.map(!_) :+ true.B))
424  dataReadyPtrExt := nextDataReadyPtr
425
426  val stDataReadyVecReg = Wire(Vec(StoreQueueSize, Bool()))
427  (0 until StoreQueueSize).map(i => {
428    stDataReadyVecReg(i) := allocated(i) && (mmio(i) || datavalid(i) || (isVec(i) && vecMbCommit(i)))
429  })
430  io.stDataReadyVec := GatedValidRegNext(stDataReadyVecReg)
431
432  when (io.brqRedirect.valid) {
433    dataReadyPtrExt := Mux(
434      isAfter(cmtPtrExt(0), deqPtrExt(0)),
435      cmtPtrExt(0),
436      deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr
437    )
438  }
439
440  io.stDataReadySqPtr := dataReadyPtrExt
441  io.stIssuePtr := enqPtrExt(0)
442  io.sqDeqPtr := deqPtrExt(0)
443
444  /**
445    * Writeback store from store units
446    *
447    * Most store instructions writeback to regfile in the previous cycle.
448    * However,
449    *   (1) For an mmio instruction with exceptions, we need to mark it as addrvalid
450    * (in this way it will trigger an exception when it reaches ROB's head)
451    * instead of pending to avoid sending them to lower level.
452    *   (2) For an mmio instruction without exceptions, we mark it as pending.
453    * When the instruction reaches ROB's head, StoreQueue sends it to uncache channel.
454    * Upon receiving the response, StoreQueue writes back the instruction
455    * through arbiter with store units. It will later commit as normal.
456    */
457
458  // Write addr to sq
459  for (i <- 0 until StorePipelineWidth) {
460    paddrModule.io.wen(i) := false.B
461    vaddrModule.io.wen(i) := false.B
462    dataModule.io.mask.wen(i) := false.B
463    val stWbIndex = io.storeAddrIn(i).bits.uop.sqIdx.value
464    exceptionBuffer.io.storeAddrIn(i).valid := io.storeAddrIn(i).fire && !io.storeAddrIn(i).bits.miss && !io.storeAddrIn(i).bits.isvec
465    exceptionBuffer.io.storeAddrIn(i).bits := io.storeAddrIn(i).bits
466    // will re-enter exceptionbuffer at store_s2
467    exceptionBuffer.io.storeAddrIn(StorePipelineWidth + i).valid := false.B
468    exceptionBuffer.io.storeAddrIn(StorePipelineWidth + i).bits := 0.U.asTypeOf(new LsPipelineBundle)
469
470    when (io.storeAddrIn(i).fire) {
471      val addr_valid = !io.storeAddrIn(i).bits.miss
472      addrvalid(stWbIndex) := addr_valid //!io.storeAddrIn(i).bits.mmio
473      // pending(stWbIndex) := io.storeAddrIn(i).bits.mmio
474      unaligned(stWbIndex) := io.storeAddrIn(i).bits.uop.exceptionVec(storeAddrMisaligned)
475
476      paddrModule.io.waddr(i) := stWbIndex
477      paddrModule.io.wdata(i) := io.storeAddrIn(i).bits.paddr
478      paddrModule.io.wmask(i) := io.storeAddrIn(i).bits.mask
479      paddrModule.io.wlineflag(i) := io.storeAddrIn(i).bits.wlineflag
480      paddrModule.io.wen(i) := true.B
481
482      vaddrModule.io.waddr(i) := stWbIndex
483      vaddrModule.io.wdata(i) := io.storeAddrIn(i).bits.vaddr
484      vaddrModule.io.wmask(i) := io.storeAddrIn(i).bits.mask
485      vaddrModule.io.wlineflag(i) := io.storeAddrIn(i).bits.wlineflag
486      vaddrModule.io.wen(i) := true.B
487
488      debug_paddr(paddrModule.io.waddr(i)) := paddrModule.io.wdata(i)
489
490      // mmio(stWbIndex) := io.storeAddrIn(i).bits.mmio
491
492      uop(stWbIndex) := io.storeAddrIn(i).bits.uop
493      uop(stWbIndex).debugInfo := io.storeAddrIn(i).bits.uop.debugInfo
494
495      vecDataValid(stWbIndex) := io.storeAddrIn(i).bits.isvec
496
497      XSInfo("store addr write to sq idx %d pc 0x%x miss:%d vaddr %x paddr %x mmio %x isvec %x\n",
498        io.storeAddrIn(i).bits.uop.sqIdx.value,
499        io.storeAddrIn(i).bits.uop.pc,
500        io.storeAddrIn(i).bits.miss,
501        io.storeAddrIn(i).bits.vaddr,
502        io.storeAddrIn(i).bits.paddr,
503        io.storeAddrIn(i).bits.mmio,
504        io.storeAddrIn(i).bits.isvec
505      )
506    }
507
508    // re-replinish mmio, for pma/pmp will get mmio one cycle later
509    val storeAddrInFireReg = RegNext(io.storeAddrIn(i).fire && !io.storeAddrIn(i).bits.miss)
510    //val stWbIndexReg = RegNext(stWbIndex)
511    val stWbIndexReg = RegEnable(stWbIndex, io.storeAddrIn(i).fire)
512    when (storeAddrInFireReg) {
513      pending(stWbIndexReg) := io.storeAddrInRe(i).mmio
514      mmio(stWbIndexReg) := io.storeAddrInRe(i).mmio
515      atomic(stWbIndexReg) := io.storeAddrInRe(i).atomic
516      hasException(stWbIndexReg) := ExceptionNO.selectByFu(uop(stWbIndexReg).exceptionVec, StaCfg).asUInt.orR || io.storeAddrInRe(i).af
517      waitStoreS2(stWbIndexReg) := false.B
518    }
519    // dcache miss info (one cycle later than storeIn)
520    // if dcache report a miss in sta pipeline, this store will trigger a prefetch when committing to sbuffer (if EnableAtCommitMissTrigger)
521    when (storeAddrInFireReg) {
522      prefetch(stWbIndexReg) := io.storeAddrInRe(i).miss
523    }
524    // enter exceptionbuffer again
525    when (storeAddrInFireReg) {
526      exceptionBuffer.io.storeAddrIn(StorePipelineWidth + i).valid := io.storeAddrInRe(i).af
527      exceptionBuffer.io.storeAddrIn(StorePipelineWidth + i).bits := RegEnable(io.storeAddrIn(i).bits, io.storeAddrIn(i).fire && !io.storeAddrIn(i).bits.miss)
528      exceptionBuffer.io.storeAddrIn(StorePipelineWidth + i).bits.uop.exceptionVec(storeAccessFault) := io.storeAddrInRe(i).af
529    }
530
531    when(vaddrModule.io.wen(i)){
532      debug_vaddr(vaddrModule.io.waddr(i)) := vaddrModule.io.wdata(i)
533    }
534  }
535
536  // Write data to sq
537  // Now store data pipeline is actually 2 stages
538  for (i <- 0 until StorePipelineWidth) {
539    dataModule.io.data.wen(i) := false.B
540    val stWbIndex = io.storeDataIn(i).bits.uop.sqIdx.value
541    val isVec     = FuType.isVStore(io.storeDataIn(i).bits.uop.fuType)
542    // sq data write takes 2 cycles:
543    // sq data write s0
544    when (io.storeDataIn(i).fire) {
545      // send data write req to data module
546      dataModule.io.data.waddr(i) := stWbIndex
547      dataModule.io.data.wdata(i) := Mux(io.storeDataIn(i).bits.uop.fuOpType === LSUOpType.cbo_zero,
548        0.U,
549        Mux(isVec,
550          io.storeDataIn(i).bits.data,
551          genVWdata(io.storeDataIn(i).bits.data, io.storeDataIn(i).bits.uop.fuOpType(2,0)))
552      )
553      dataModule.io.data.wen(i) := true.B
554
555      debug_data(dataModule.io.data.waddr(i)) := dataModule.io.data.wdata(i)
556
557      XSInfo("store data write to sq idx %d pc 0x%x data %x -> %x\n",
558        io.storeDataIn(i).bits.uop.sqIdx.value,
559        io.storeDataIn(i).bits.uop.pc,
560        io.storeDataIn(i).bits.data,
561        dataModule.io.data.wdata(i)
562      )
563    }
564    // sq data write s1
565    when (
566      RegNext(io.storeDataIn(i).fire)
567      // && !RegNext(io.storeDataIn(i).bits.uop).robIdx.needFlush(io.brqRedirect)
568    ) {
569      datavalid(RegEnable(stWbIndex, io.storeDataIn(i).fire)) := true.B
570    }
571  }
572
573  // Write mask to sq
574  for (i <- 0 until StorePipelineWidth) {
575    // sq mask write s0
576    when (io.storeMaskIn(i).fire) {
577      // send data write req to data module
578      dataModule.io.mask.waddr(i) := io.storeMaskIn(i).bits.sqIdx.value
579      dataModule.io.mask.wdata(i) := io.storeMaskIn(i).bits.mask
580      dataModule.io.mask.wen(i) := true.B
581    }
582  }
583
584  /**
585    * load forward query
586    *
587    * Check store queue for instructions that is older than the load.
588    * The response will be valid at the next cycle after req.
589    */
590  // check over all lq entries and forward data from the first matched store
591  for (i <- 0 until LoadPipelineWidth) {
592    // Compare deqPtr (deqPtr) and forward.sqIdx, we have two cases:
593    // (1) if they have the same flag, we need to check range(tail, sqIdx)
594    // (2) if they have different flags, we need to check range(tail, VirtualLoadQueueSize) and range(0, sqIdx)
595    // Forward1: Mux(same_flag, range(tail, sqIdx), range(tail, VirtualLoadQueueSize))
596    // Forward2: Mux(same_flag, 0.U,                   range(0, sqIdx)    )
597    // i.e. forward1 is the target entries with the same flag bits and forward2 otherwise
598    val differentFlag = deqPtrExt(0).flag =/= io.forward(i).sqIdx.flag
599    val forwardMask = io.forward(i).sqIdxMask
600    // all addrvalid terms need to be checked
601    // Real Vaild: all scalar stores, and vector store with (!inactive && !secondInvalid)
602    val addrRealValidVec = WireInit(VecInit((0 until StoreQueueSize).map(j => addrvalid(j) && allocated(j))))
603    // vector store will consider all inactive || secondInvalid flows as valid
604    val addrValidVec = WireInit(VecInit((0 until StoreQueueSize).map(j => addrvalid(j) && allocated(j))))
605    val dataValidVec = WireInit(VecInit((0 until StoreQueueSize).map(j => datavalid(j))))
606    val allValidVec  = WireInit(VecInit((0 until StoreQueueSize).map(j => addrvalid(j) && datavalid(j) && allocated(j))))
607
608    val lfstEnable = Constantin.createRecord("LFSTEnable", LFSTEnable)
609    val storeSetHitVec = Mux(lfstEnable,
610      WireInit(VecInit((0 until StoreQueueSize).map(j => io.forward(i).uop.loadWaitBit && uop(j).robIdx === io.forward(i).uop.waitForRobIdx))),
611      WireInit(VecInit((0 until StoreQueueSize).map(j => uop(j).storeSetHit && uop(j).ssid === io.forward(i).uop.ssid)))
612    )
613
614    val forwardMask1 = Mux(differentFlag, ~deqMask, deqMask ^ forwardMask)
615    val forwardMask2 = Mux(differentFlag, forwardMask, 0.U(StoreQueueSize.W))
616    val canForward1 = forwardMask1 & allValidVec.asUInt
617    val canForward2 = forwardMask2 & allValidVec.asUInt
618    val needForward = Mux(differentFlag, ~deqMask | forwardMask, deqMask ^ forwardMask)
619
620    XSDebug(p"$i f1 ${Binary(canForward1)} f2 ${Binary(canForward2)} " +
621      p"sqIdx ${io.forward(i).sqIdx} pa ${Hexadecimal(io.forward(i).paddr)}\n"
622    )
623
624    // do real fwd query (cam lookup in load_s1)
625    dataModule.io.needForward(i)(0) := canForward1 & vaddrModule.io.forwardMmask(i).asUInt
626    dataModule.io.needForward(i)(1) := canForward2 & vaddrModule.io.forwardMmask(i).asUInt
627
628    vaddrModule.io.forwardMdata(i) := io.forward(i).vaddr
629    vaddrModule.io.forwardDataMask(i) := io.forward(i).mask
630    paddrModule.io.forwardMdata(i) := io.forward(i).paddr
631    paddrModule.io.forwardDataMask(i) := io.forward(i).mask
632
633    // vaddr cam result does not equal to paddr cam result
634    // replay needed
635    // val vpmaskNotEqual = ((paddrModule.io.forwardMmask(i).asUInt ^ vaddrModule.io.forwardMmask(i).asUInt) & needForward) =/= 0.U
636    // val vaddrMatchFailed = vpmaskNotEqual && io.forward(i).valid
637    val vpmaskNotEqual = (
638      (RegEnable(paddrModule.io.forwardMmask(i).asUInt, io.forward(i).valid) ^ RegEnable(vaddrModule.io.forwardMmask(i).asUInt, io.forward(i).valid)) &
639      RegNext(needForward) &
640      GatedRegNext(addrRealValidVec.asUInt)
641    ) =/= 0.U
642    val vaddrMatchFailed = vpmaskNotEqual && RegNext(io.forward(i).valid)
643    when (vaddrMatchFailed) {
644      XSInfo("vaddrMatchFailed: pc %x pmask %x vmask %x\n",
645        RegEnable(io.forward(i).uop.pc, io.forward(i).valid),
646        RegEnable(needForward & paddrModule.io.forwardMmask(i).asUInt, io.forward(i).valid),
647        RegEnable(needForward & vaddrModule.io.forwardMmask(i).asUInt, io.forward(i).valid)
648      );
649    }
650    XSPerfAccumulate("vaddr_match_failed", vpmaskNotEqual)
651    XSPerfAccumulate("vaddr_match_really_failed", vaddrMatchFailed)
652
653    // Fast forward mask will be generated immediately (load_s1)
654    io.forward(i).forwardMaskFast := dataModule.io.forwardMaskFast(i)
655
656    // Forward result will be generated 1 cycle later (load_s2)
657    io.forward(i).forwardMask := dataModule.io.forwardMask(i)
658    io.forward(i).forwardData := dataModule.io.forwardData(i)
659    // If addr match, data not ready, mark it as dataInvalid
660    // load_s1: generate dataInvalid in load_s1 to set fastUop
661    val dataInvalidMask1 = (addrValidVec.asUInt & ~dataValidVec.asUInt & vaddrModule.io.forwardMmask(i).asUInt & forwardMask1.asUInt)
662    val dataInvalidMask2 = (addrValidVec.asUInt & ~dataValidVec.asUInt & vaddrModule.io.forwardMmask(i).asUInt & forwardMask2.asUInt)
663    val dataInvalidMask = dataInvalidMask1 | dataInvalidMask2
664    io.forward(i).dataInvalidFast := dataInvalidMask.orR
665
666    // make chisel happy
667    val dataInvalidMask1Reg = Wire(UInt(StoreQueueSize.W))
668    dataInvalidMask1Reg := RegNext(dataInvalidMask1)
669    // make chisel happy
670    val dataInvalidMask2Reg = Wire(UInt(StoreQueueSize.W))
671    dataInvalidMask2Reg := RegNext(dataInvalidMask2)
672    val dataInvalidMaskReg = dataInvalidMask1Reg | dataInvalidMask2Reg
673
674    // If SSID match, address not ready, mark it as addrInvalid
675    // load_s2: generate addrInvalid
676    val addrInvalidMask1 = (~addrValidVec.asUInt & storeSetHitVec.asUInt & forwardMask1.asUInt)
677    val addrInvalidMask2 = (~addrValidVec.asUInt & storeSetHitVec.asUInt & forwardMask2.asUInt)
678    // make chisel happy
679    val addrInvalidMask1Reg = Wire(UInt(StoreQueueSize.W))
680    addrInvalidMask1Reg := RegNext(addrInvalidMask1)
681    // make chisel happy
682    val addrInvalidMask2Reg = Wire(UInt(StoreQueueSize.W))
683    addrInvalidMask2Reg := RegNext(addrInvalidMask2)
684    val addrInvalidMaskReg = addrInvalidMask1Reg | addrInvalidMask2Reg
685
686    // load_s2
687    io.forward(i).dataInvalid := RegNext(io.forward(i).dataInvalidFast)
688    // check if vaddr forward mismatched
689    io.forward(i).matchInvalid := vaddrMatchFailed
690
691    // data invalid sq index
692    // check whether false fail
693    // check flag
694    val s2_differentFlag = RegNext(differentFlag)
695    val s2_enqPtrExt = RegNext(enqPtrExt(0))
696    val s2_deqPtrExt = RegNext(deqPtrExt(0))
697
698    // addr invalid sq index
699    // make chisel happy
700    val addrInvalidMaskRegWire = Wire(UInt(StoreQueueSize.W))
701    addrInvalidMaskRegWire := addrInvalidMaskReg
702    val addrInvalidFlag = addrInvalidMaskRegWire.orR
703    val hasInvalidAddr = (~addrValidVec.asUInt & needForward).orR
704
705    val addrInvalidSqIdx1 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(addrInvalidMask1Reg))))
706    val addrInvalidSqIdx2 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(addrInvalidMask2Reg))))
707    val addrInvalidSqIdx = Mux(addrInvalidMask2Reg.orR, addrInvalidSqIdx2, addrInvalidSqIdx1)
708
709    // store-set content management
710    //                +-----------------------+
711    //                | Search a SSID for the |
712    //                |    load operation     |
713    //                +-----------------------+
714    //                           |
715    //                           V
716    //                 +-------------------+
717    //                 | load wait strict? |
718    //                 +-------------------+
719    //                           |
720    //                           V
721    //               +----------------------+
722    //            Set|                      |Clean
723    //               V                      V
724    //  +------------------------+   +------------------------------+
725    //  | Waiting for all older  |   | Wait until the corresponding |
726    //  |   stores operations    |   | older store operations       |
727    //  +------------------------+   +------------------------------+
728
729
730
731    when (RegEnable(io.forward(i).uop.loadWaitStrict, io.forward(i).valid)) {
732      io.forward(i).addrInvalidSqIdx := RegEnable((io.forward(i).uop.sqIdx - 1.U), io.forward(i).valid)
733    } .elsewhen (addrInvalidFlag) {
734      io.forward(i).addrInvalidSqIdx.flag := Mux(!s2_differentFlag || addrInvalidSqIdx >= s2_deqPtrExt.value, s2_deqPtrExt.flag, s2_enqPtrExt.flag)
735      io.forward(i).addrInvalidSqIdx.value := addrInvalidSqIdx
736    } .otherwise {
737      // may be store inst has been written to sbuffer already.
738      io.forward(i).addrInvalidSqIdx := RegEnable(io.forward(i).uop.sqIdx, io.forward(i).valid)
739    }
740    io.forward(i).addrInvalid := Mux(RegEnable(io.forward(i).uop.loadWaitStrict, io.forward(i).valid), RegNext(hasInvalidAddr), addrInvalidFlag)
741
742    // data invalid sq index
743    // make chisel happy
744    val dataInvalidMaskRegWire = Wire(UInt(StoreQueueSize.W))
745    dataInvalidMaskRegWire := dataInvalidMaskReg
746    val dataInvalidFlag = dataInvalidMaskRegWire.orR
747
748    val dataInvalidSqIdx1 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(dataInvalidMask1Reg))))
749    val dataInvalidSqIdx2 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(dataInvalidMask2Reg))))
750    val dataInvalidSqIdx = Mux(dataInvalidMask2Reg.orR, dataInvalidSqIdx2, dataInvalidSqIdx1)
751
752    when (dataInvalidFlag) {
753      io.forward(i).dataInvalidSqIdx.flag := Mux(!s2_differentFlag || dataInvalidSqIdx >= s2_deqPtrExt.value, s2_deqPtrExt.flag, s2_enqPtrExt.flag)
754      io.forward(i).dataInvalidSqIdx.value := dataInvalidSqIdx
755    } .otherwise {
756      // may be store inst has been written to sbuffer already.
757      io.forward(i).dataInvalidSqIdx := RegEnable(io.forward(i).uop.sqIdx, io.forward(i).valid)
758    }
759  }
760
761  /**
762    * Memory mapped IO / other uncached operations / CMO
763    *
764    * States:
765    * (1) writeback from store units: mark as pending
766    * (2) when they reach ROB's head, they can be sent to uncache channel
767    * (3) response from uncache channel: mark as datavalidmask.wen
768    * (4) writeback to ROB (and other units): mark as writebacked
769    * (5) ROB commits the instruction: same as normal instructions
770    */
771  //(2) when they reach ROB's head, they can be sent to uncache channel
772  // TODO: CAN NOT deal with vector mmio now!
773  val s_idle :: s_req :: s_resp :: s_wb :: s_wait :: Nil = Enum(5)
774  val uncacheState = RegInit(s_idle)
775  val uncacheUop = Reg(new DynInst)
776  val cboFlushedSb = RegInit(false.B)
777  switch(uncacheState) {
778    is(s_idle) {
779      when(RegNext(io.rob.pendingst && uop(deqPtr).robIdx === io.rob.pendingPtr && pending(deqPtr) && allocated(deqPtr) && datavalid(deqPtr) && addrvalid(deqPtr))) {
780        uncacheState := s_req
781        uncacheUop := uop(deqPtr)
782        cboFlushedSb := false.B
783      }
784    }
785    is(s_req) {
786      when (io.uncache.req.fire) {
787        when (io.uncacheOutstanding) {
788          uncacheState := s_wb
789        } .otherwise {
790          uncacheState := s_resp
791        }
792      }
793    }
794    is(s_resp) {
795      when(io.uncache.resp.fire) {
796        uncacheState := s_wb
797
798        when (io.uncache.resp.bits.nderr) {
799          uop(deqPtr).exceptionVec(storeAccessFault) := true.B
800        }
801      }
802    }
803    is(s_wb) {
804      when (io.mmioStout.fire || io.vecmmioStout.fire) {
805        uncacheState := s_wait
806      }
807    }
808    is(s_wait) {
809      // A MMIO store can always move cmtPtrExt as it must be ROB head
810      when(scommit > 0.U) {
811        uncacheState := s_idle // ready for next mmio
812      }
813    }
814  }
815  io.uncache.req.valid := uncacheState === s_req
816
817  io.uncache.req.bits := DontCare
818  io.uncache.req.bits.cmd  := MemoryOpConstants.M_XWR
819  io.uncache.req.bits.addr := paddrModule.io.rdata(0) // data(deqPtr) -> rdata(0)
820  io.uncache.req.bits.data := shiftDataToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).data)
821  io.uncache.req.bits.mask := shiftMaskToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).mask)
822
823  // CBO op type check can be delayed for 1 cycle,
824  // as uncache op will not start in s_idle
825  val cboMmioAddr = get_block_addr(paddrModule.io.rdata(0))
826  val deqCanDoCbo = GatedRegNext(LSUOpType.isCbo(uop(deqPtr).fuOpType) && allocated(deqPtr) && addrvalid(deqPtr))
827  when (deqCanDoCbo) {
828    // disable uncache channel
829    io.uncache.req.valid := false.B
830
831    when (io.cmoOpReq.fire) {
832      uncacheState := s_resp
833    }
834
835    when (uncacheState === s_resp) {
836      when (io.cmoOpResp.fire) {
837        uncacheState := s_wb
838      }
839    }
840  }
841
842  io.cmoOpReq.valid := deqCanDoCbo && cboFlushedSb && (uncacheState === s_req)
843  io.cmoOpReq.bits.opcode  := uop(deqPtr).fuOpType(1, 0)
844  io.cmoOpReq.bits.address := cboMmioAddr
845
846  io.cmoOpResp.ready := deqCanDoCbo && (uncacheState === s_resp)
847
848  io.flushSbuffer.valid := deqCanDoCbo && !cboFlushedSb && (uncacheState === s_req) && !io.flushSbuffer.empty
849
850  when(deqCanDoCbo && !cboFlushedSb && (uncacheState === s_req) && io.flushSbuffer.empty) {
851    cboFlushedSb := true.B
852  }
853
854  io.uncache.req.bits.atomic := atomic(GatedRegNext(rdataPtrExtNext(0)).value)
855
856  when(io.uncache.req.fire){
857    // mmio store should not be committed until uncache req is sent
858    pending(deqPtr) := false.B
859
860    XSDebug(
861      p"uncache req: pc ${Hexadecimal(uop(deqPtr).pc)} " +
862      p"addr ${Hexadecimal(io.uncache.req.bits.addr)} " +
863      p"data ${Hexadecimal(io.uncache.req.bits.data)} " +
864      p"op ${Hexadecimal(io.uncache.req.bits.cmd)} " +
865      p"mask ${Hexadecimal(io.uncache.req.bits.mask)}\n"
866    )
867  }
868
869  // (3) response from uncache channel: mark as datavalid
870  io.uncache.resp.ready := true.B
871
872  // (4) scalar store: writeback to ROB (and other units): mark as writebacked
873  io.mmioStout.valid := uncacheState === s_wb && !isVec(deqPtr)
874  io.mmioStout.bits.uop := uncacheUop
875  io.mmioStout.bits.uop.sqIdx := deqPtrExt(0)
876  io.mmioStout.bits.uop.flushPipe := deqCanDoCbo // flush Pipeline to keep order in CMO
877  io.mmioStout.bits.data := shiftDataToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).data) // dataModule.io.rdata.read(deqPtr)
878  io.mmioStout.bits.debug.isMMIO := true.B
879  io.mmioStout.bits.debug.paddr := DontCare
880  io.mmioStout.bits.debug.isPerfCnt := false.B
881  io.mmioStout.bits.debug.vaddr := DontCare
882  // Remove MMIO inst from store queue after MMIO request is being sent
883  // That inst will be traced by uncache state machine
884  when (io.mmioStout.fire) {
885    allocated(deqPtr) := false.B
886  }
887
888  // (4) or vector store:
889  // TODO: implement it!
890  io.vecmmioStout := DontCare
891  io.vecmmioStout.valid := false.B //uncacheState === s_wb && isVec(deqPtr)
892  io.vecmmioStout.bits.uop := uop(deqPtr)
893  io.vecmmioStout.bits.uop.sqIdx := deqPtrExt(0)
894  io.vecmmioStout.bits.data := shiftDataToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).data) // dataModule.io.rdata.read(deqPtr)
895  io.vecmmioStout.bits.debug.isMMIO := true.B
896  io.vecmmioStout.bits.debug.paddr := DontCare
897  io.vecmmioStout.bits.debug.isPerfCnt := false.B
898  io.vecmmioStout.bits.debug.vaddr := DontCare
899  // Remove MMIO inst from store queue after MMIO request is being sent
900  // That inst will be traced by uncache state machine
901  when (io.vecmmioStout.fire) {
902    allocated(deqPtr) := false.B
903  }
904
905  /**
906    * ROB commits store instructions (mark them as committed)
907    *
908    * (1) When store commits, mark it as committed.
909    * (2) They will not be cancelled and can be sent to lower level.
910    */
911  XSError(uncacheState =/= s_idle && uncacheState =/= s_wait && commitCount > 0.U,
912   "should not commit instruction when MMIO has not been finished\n")
913
914  val commitVec = WireInit(VecInit(Seq.fill(CommitWidth)(false.B)))
915  val needCancel = Wire(Vec(StoreQueueSize, Bool())) // Will be assigned later
916  dontTouch(commitVec)
917  // TODO: Deal with vector store mmio
918  for (i <- 0 until CommitWidth) {
919    when (allocated(cmtPtrExt(i).value) && isNotAfter(uop(cmtPtrExt(i).value).robIdx, GatedRegNext(io.rob.pendingPtr)) && !needCancel(cmtPtrExt(i).value) && (!waitStoreS2(cmtPtrExt(i).value) || isVec(cmtPtrExt(i).value))) {
920      // don't commit while doing misalign
921      if (i == 0){
922        // TODO: fixme for vector mmio
923        when ((uncacheState === s_idle) || (uncacheState === s_wait && scommit > 0.U)){
924          when ((isVec(cmtPtrExt(i).value) && vecMbCommit(cmtPtrExt(i).value)) || !isVec(cmtPtrExt(i).value)) {
925            committed(cmtPtrExt(0).value) := Mux(misalignBlock, false.B, true.B)
926            commitVec(0) := Mux(misalignBlock, false.B, true.B)
927          }
928        }
929      } else {
930        when ((isVec(cmtPtrExt(i).value) && vecMbCommit(cmtPtrExt(i).value)) || !isVec(cmtPtrExt(i).value)) {
931          committed(cmtPtrExt(i).value) := Mux(misalignBlock, false.B, commitVec(i - 1) || committed(cmtPtrExt(i).value))
932          commitVec(i) := Mux(misalignBlock, false.B, commitVec(i - 1))
933        }
934      }
935    }
936  }
937
938  commitCount := PopCount(commitVec)
939  cmtPtrExt := cmtPtrExt.map(_ + commitCount)
940
941  // committed stores will not be cancelled and can be sent to lower level.
942  // remove retired insts from sq, add retired store to sbuffer
943
944  // Read data from data module
945  // As store queue grows larger and larger, time needed to read data from data
946  // module keeps growing higher. Now we give data read a whole cycle.
947  for (i <- 0 until EnsbufferWidth) {
948    val ptr = rdataPtrExt(i).value
949    val mmioStall = if(i == 0) mmio(rdataPtrExt(0).value) else (mmio(rdataPtrExt(i).value) || mmio(rdataPtrExt(i-1).value))
950    val exceptionValid = if(i == 0) hasException(rdataPtrExt(0).value) else {
951      hasException(rdataPtrExt(i).value) || (hasException(rdataPtrExt(i-1).value) && uop(rdataPtrExt(i).value).robIdx === uop(rdataPtrExt(i-1).value).robIdx)
952    }
953    val vecNotAllMask = dataModule.io.rdata(i).mask.orR
954    // Vector instructions that prevent triggered exceptions from being written to the 'databuffer'.
955    val vecHasExceptionFlagValid = vecExceptionFlag.valid && isVec(ptr) && vecExceptionFlag.bits.robIdx === uop(ptr).robIdx
956    if (i == 0) {
957      // use dataBuffer write port 0 to writeback missaligned store out
958      dataBuffer.io.enq(i).valid := Mux(
959        doMisalignSt,
960        io.maControl.control.writeSb,
961        allocated(ptr) && committed(ptr) && ((!isVec(ptr) && (allvalid(ptr) || hasException(ptr))) || vecMbCommit(ptr)) && !mmioStall
962      )
963    } else {
964      dataBuffer.io.enq(i).valid := Mux(
965        doMisalignSt,
966        false.B,
967        allocated(ptr) && committed(ptr) && ((!isVec(ptr) && (allvalid(ptr) || hasException(ptr))) || vecMbCommit(ptr)) && !mmioStall
968      )
969    }
970    // Note that store data/addr should both be valid after store's commit
971    assert(!dataBuffer.io.enq(i).valid || allvalid(ptr) || doMisalignSt || (allocated(ptr) && vecMbCommit(ptr)))
972    dataBuffer.io.enq(i).bits.addr     := Mux(doMisalignSt, io.maControl.control.paddr, paddrModule.io.rdata(i))
973    dataBuffer.io.enq(i).bits.vaddr    := Mux(doMisalignSt, io.maControl.control.vaddr, vaddrModule.io.rdata(i))
974    dataBuffer.io.enq(i).bits.data     := Mux(doMisalignSt, io.maControl.control.wdata, dataModule.io.rdata(i).data)
975    dataBuffer.io.enq(i).bits.mask     := Mux(doMisalignSt, io.maControl.control.wmask, dataModule.io.rdata(i).mask)
976    dataBuffer.io.enq(i).bits.wline    := Mux(doMisalignSt, false.B, paddrModule.io.rlineflag(i))
977    dataBuffer.io.enq(i).bits.sqPtr    := rdataPtrExt(i)
978    dataBuffer.io.enq(i).bits.prefetch := Mux(doMisalignSt, false.B, prefetch(ptr))
979    // when scalar has exception, will also not write into sbuffer
980    dataBuffer.io.enq(i).bits.vecValid := Mux(doMisalignSt, true.B, (!isVec(ptr) || (vecDataValid(ptr) && vecNotAllMask)) && !exceptionValid && !vecHasExceptionFlagValid)
981//    dataBuffer.io.enq(i).bits.vecValid := (!isVec(ptr) || vecDataValid(ptr)) && !hasException(ptr)
982  }
983
984  // Send data stored in sbufferReqBitsReg to sbuffer
985  for (i <- 0 until EnsbufferWidth) {
986    io.sbuffer(i).valid := dataBuffer.io.deq(i).valid
987    dataBuffer.io.deq(i).ready := io.sbuffer(i).ready
988    io.sbuffer(i).bits := DontCare
989    io.sbuffer(i).bits.cmd   := MemoryOpConstants.M_XWR
990    io.sbuffer(i).bits.addr  := dataBuffer.io.deq(i).bits.addr
991    io.sbuffer(i).bits.vaddr := dataBuffer.io.deq(i).bits.vaddr
992    io.sbuffer(i).bits.data  := dataBuffer.io.deq(i).bits.data
993    io.sbuffer(i).bits.mask  := dataBuffer.io.deq(i).bits.mask
994    io.sbuffer(i).bits.wline := dataBuffer.io.deq(i).bits.wline && dataBuffer.io.deq(i).bits.vecValid
995    io.sbuffer(i).bits.prefetch := dataBuffer.io.deq(i).bits.prefetch
996    io.sbuffer(i).bits.vecValid := dataBuffer.io.deq(i).bits.vecValid
997    // io.sbuffer(i).fire is RegNexted, as sbuffer data write takes 2 cycles.
998    // Before data write finish, sbuffer is unable to provide store to load
999    // forward data. As an workaround, deqPtrExt and allocated flag update
1000    // is delayed so that load can get the right data from store queue.
1001    val ptr = dataBuffer.io.deq(i).bits.sqPtr.value
1002    when (RegNext(io.sbuffer(i).fire && !doMisalignSt)) {
1003      allocated(RegEnable(ptr, io.sbuffer(i).fire)) := false.B
1004      XSDebug("sbuffer "+i+" fire: ptr %d\n", ptr)
1005    }
1006  }
1007
1008  // All vector instruction uop normally dequeue, but the Uop after the exception is raised does not write to the 'sbuffer'.
1009  // Flags are used to record whether there are any exceptions when the queue is displayed.
1010  // This is determined each time a write is made to the 'databuffer', prevent subsequent uop of the same instruction from writing to the 'dataBuffer'.
1011  val vecCommitHasException = (0 until EnsbufferWidth).map{ i =>
1012    val ptr                 = rdataPtrExt(i).value
1013    val mmioStall           = if(i == 0) mmio(rdataPtrExt(0).value) else (mmio(rdataPtrExt(i).value) || mmio(rdataPtrExt(i-1).value))
1014    val exceptionVliad      = allocated(ptr) && committed(ptr) && vecMbCommit(ptr) && !mmioStall && isVec(ptr) && vecDataValid(ptr) && hasException(ptr)
1015    (exceptionVliad, uop(ptr))
1016  }
1017
1018  val vecCommitHasExceptionValid      = vecCommitHasException.map(_._1)
1019  val vecCommitHasExceptionUop        = vecCommitHasException.map(_._2)
1020  val vecCommitHasExceptionValidOR    = vecCommitHasExceptionValid.reduce(_ || _)
1021  // Just select the last Uop tah has an exception.
1022  val vecCommitHasExceptionSelectUop  = ParallelPosteriorityMux(vecCommitHasExceptionValid, vecCommitHasExceptionUop)
1023  // If the last Uop with an exception is the LastUop of this instruction, the flag is not set.
1024  val vecCommitLastUop = vecCommitHasExceptionSelectUop.lastUop
1025
1026  val vecExceptionFlagCancel  = (0 until EnsbufferWidth).map{ i =>
1027    val ptr                   = rdataPtrExt(i).value
1028    val mmioStall             = if(i == 0) mmio(rdataPtrExt(0).value) else (mmio(rdataPtrExt(i).value) || mmio(rdataPtrExt(i-1).value))
1029    val vecLastUopCommit      = uop(ptr).lastUop && (uop(ptr).robIdx === vecExceptionFlag.bits.robIdx) &&
1030                                allocated(ptr) && committed(ptr) && vecMbCommit(ptr) && !mmioStall && isVec(ptr) && vecDataValid(ptr)
1031    vecLastUopCommit
1032  }.reduce(_ || _)
1033
1034  // When a LastUop with an exception instruction is commited, clear the flag.
1035  when(!vecExceptionFlag.valid && vecCommitHasExceptionValidOR && !vecCommitLastUop) {
1036    vecExceptionFlag.valid  := true.B
1037    vecExceptionFlag.bits   := vecCommitHasExceptionSelectUop
1038  }.elsewhen(vecExceptionFlag.valid && vecExceptionFlagCancel) {
1039    vecExceptionFlag.valid  := false.B
1040    vecExceptionFlag.bits   := 0.U.asTypeOf(new DynInst)
1041  }
1042
1043  // A dumb defensive code. The flag should not be placed for a long period of time.
1044  // A relatively large timeout period, not have any special meaning.
1045  // If an assert appears and you confirm that it is not a Bug: Increase the timeout or remove the assert.
1046  TimeOutAssert(vecExceptionFlag.valid, 3000, "vecExceptionFlag timeout, Plase check for bugs or add timeouts.")
1047
1048  // Initialize when unenabled difftest.
1049  for (i <- 0 until EnsbufferWidth) {
1050    io.sbufferVecDifftestInfo(i) := DontCare
1051  }
1052  // Consistent with the logic above.
1053  // Only the vector store difftest required signal is separated from the rtl code.
1054  if (env.EnableDifftest) {
1055    for (i <- 0 until EnsbufferWidth) {
1056      val ptr = rdataPtrExt(i).value
1057      val mmioStall = if(i == 0) mmio(rdataPtrExt(0).value) else (mmio(rdataPtrExt(i).value) || mmio(rdataPtrExt(i-1).value))
1058      difftestBuffer.get.io.enq(i).valid := allocated(ptr) && committed(ptr) && (!isVec(ptr) || vecMbCommit(ptr)) && !mmioStall
1059      difftestBuffer.get.io.enq(i).bits := uop(ptr)
1060    }
1061    for (i <- 0 until EnsbufferWidth) {
1062      io.sbufferVecDifftestInfo(i).valid := difftestBuffer.get.io.deq(i).valid
1063      difftestBuffer.get.io.deq(i).ready := io.sbufferVecDifftestInfo(i).ready
1064
1065      io.sbufferVecDifftestInfo(i).bits := difftestBuffer.get.io.deq(i).bits
1066    }
1067  }
1068
1069  (1 until EnsbufferWidth).foreach(i => when(io.sbuffer(i).fire) { assert(io.sbuffer(i - 1).fire) })
1070  if (coreParams.dcacheParametersOpt.isEmpty) {
1071    for (i <- 0 until EnsbufferWidth) {
1072      val ptr = deqPtrExt(i).value
1073      val ram = DifftestMem(64L * 1024 * 1024 * 1024, 8)
1074      val wen = allocated(ptr) && committed(ptr) && !mmio(ptr)
1075      val waddr = ((paddrModule.io.rdata(i) - "h80000000".U) >> 3).asUInt
1076      val wdata = Mux(paddrModule.io.rdata(i)(3), dataModule.io.rdata(i).data(127, 64), dataModule.io.rdata(i).data(63, 0))
1077      val wmask = Mux(paddrModule.io.rdata(i)(3), dataModule.io.rdata(i).mask(15, 8), dataModule.io.rdata(i).mask(7, 0))
1078      when (wen) {
1079        ram.write(waddr, wdata.asTypeOf(Vec(8, UInt(8.W))), wmask.asBools)
1080      }
1081    }
1082  }
1083
1084  // Read vaddr for mem exception
1085  io.exceptionAddr.vaddr  := exceptionBuffer.io.exceptionAddr.vaddr
1086  io.exceptionAddr.gpaddr  := exceptionBuffer.io.exceptionAddr.gpaddr
1087  io.exceptionAddr.vstart := exceptionBuffer.io.exceptionAddr.vstart
1088  io.exceptionAddr.vl     := exceptionBuffer.io.exceptionAddr.vl
1089
1090  // vector commit or replay from
1091  val vecCommittmp = Wire(Vec(StoreQueueSize, Vec(VecStorePipelineWidth, Bool())))
1092  val vecCommit = Wire(Vec(StoreQueueSize, Bool()))
1093  for (i <- 0 until StoreQueueSize) {
1094    val fbk = io.vecFeedback
1095    for (j <- 0 until VecStorePipelineWidth) {
1096      vecCommittmp(i)(j) := fbk(j).valid && (fbk(j).bits.isCommit || fbk(j).bits.isFlush) &&
1097        uop(i).robIdx === fbk(j).bits.robidx && uop(i).uopIdx === fbk(j).bits.uopidx && allocated(i)
1098    }
1099    vecCommit(i) := vecCommittmp(i).reduce(_ || _)
1100
1101    when (vecCommit(i)) {
1102      vecMbCommit(i) := true.B
1103    }
1104  }
1105
1106  // misprediction recovery / exception redirect
1107  // invalidate sq term using robIdx
1108  for (i <- 0 until StoreQueueSize) {
1109    needCancel(i) := uop(i).robIdx.needFlush(io.brqRedirect) && allocated(i) && !committed(i) &&
1110      (!isVec(i) || !(uop(i).robIdx === io.brqRedirect.bits.robIdx))
1111    when (needCancel(i)) {
1112      allocated(i) := false.B
1113    }
1114  }
1115
1116 /**
1117* update pointers
1118**/
1119  val enqCancelValid = canEnqueue.zip(io.enq.req).map{case (v , x) =>
1120    v && x.bits.robIdx.needFlush(io.brqRedirect)
1121  }
1122  val enqCancelNum = enqCancelValid.zip(io.enq.req).map{case (v, req) =>
1123    Mux(v, req.bits.numLsElem, 0.U)
1124  }
1125  val lastEnqCancel = RegEnable(enqCancelNum.reduce(_ + _), io.brqRedirect.valid) // 1 cycle after redirect
1126
1127  val lastCycleCancelCount = PopCount(RegEnable(needCancel, io.brqRedirect.valid)) // 1 cycle after redirect
1128  val lastCycleRedirect = RegNext(io.brqRedirect.valid) // 1 cycle after redirect
1129  val enqNumber = validVStoreFlow.reduce(_ + _)
1130
1131  val lastlastCycleRedirect=RegNext(lastCycleRedirect)// 2 cycle after redirect
1132  val redirectCancelCount = RegEnable(lastCycleCancelCount + lastEnqCancel, 0.U, lastCycleRedirect) // 2 cycle after redirect
1133
1134  when (lastlastCycleRedirect) {
1135    // we recover the pointers in 2 cycle after redirect for better timing
1136    enqPtrExt := VecInit(enqPtrExt.map(_ - redirectCancelCount))
1137  }.otherwise {
1138    // lastCycleRedirect.valid or nornal case
1139    // when lastCycleRedirect.valid, enqNumber === 0.U, enqPtrExt will not change
1140    enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber))
1141  }
1142  assert(!(lastCycleRedirect && enqNumber =/= 0.U))
1143
1144  exceptionBuffer.io.flushFrmMaBuf := finishMisalignSt
1145  // special case (store miss align) in updating ptr
1146  when (doMisalignSt) {
1147    when (!finishMisalignSt) {
1148      // dont move deqPtr and rdataPtr until all split store has been written to sb
1149      deqPtrExtNext := deqPtrExt
1150      rdataPtrExtNext := rdataPtrExt
1151    } .otherwise {
1152      // remove this unaligned store from sq
1153      allocated(deqPtr) := false.B
1154      committed(deqPtr) := true.B
1155      cmtPtrExt := cmtPtrExt.map(_ + 1.U)
1156      deqPtrExtNext := deqPtrExt.map(_ + 1.U)
1157      rdataPtrExtNext := rdataPtrExt.map(_ + 1.U)
1158    }
1159  }
1160
1161  deqPtrExt := deqPtrExtNext
1162  rdataPtrExt := rdataPtrExtNext
1163
1164  // val dequeueCount = Mux(io.sbuffer(1).fire, 2.U, Mux(io.sbuffer(0).fire || io.mmioStout.fire, 1.U, 0.U))
1165
1166  // If redirect at T0, sqCancelCnt is at T2
1167  io.sqCancelCnt := redirectCancelCount
1168  val ForceWriteUpper = Wire(UInt(log2Up(StoreQueueSize + 1).W))
1169  ForceWriteUpper := Constantin.createRecord(s"ForceWriteUpper_${p(XSCoreParamsKey).HartId}", initValue = 60)
1170  val ForceWriteLower = Wire(UInt(log2Up(StoreQueueSize + 1).W))
1171  ForceWriteLower := Constantin.createRecord(s"ForceWriteLower_${p(XSCoreParamsKey).HartId}", initValue = 55)
1172
1173  val valid_cnt = PopCount(allocated)
1174  io.force_write := RegNext(Mux(valid_cnt >= ForceWriteUpper, true.B, valid_cnt >= ForceWriteLower && io.force_write), init = false.B)
1175
1176  // io.sqempty will be used by sbuffer
1177  // We delay it for 1 cycle for better timing
1178  // When sbuffer need to check if it is empty, the pipeline is blocked, which means delay io.sqempty
1179  // for 1 cycle will also promise that sq is empty in that cycle
1180  io.sqEmpty := RegNext(
1181    enqPtrExt(0).value === deqPtrExt(0).value &&
1182    enqPtrExt(0).flag === deqPtrExt(0).flag
1183  )
1184  // perf counter
1185  QueuePerf(StoreQueueSize, validCount, !allowEnqueue)
1186  val vecValidVec = WireInit(VecInit((0 until StoreQueueSize).map(i => allocated(i) && isVec(i))))
1187  QueuePerf(StoreQueueSize, PopCount(vecValidVec), !allowEnqueue)
1188  io.sqFull := !allowEnqueue
1189  XSPerfAccumulate("mmioCycle", uncacheState =/= s_idle) // lq is busy dealing with uncache req
1190  XSPerfAccumulate("mmioCnt", io.uncache.req.fire)
1191  XSPerfAccumulate("mmio_wb_success", io.mmioStout.fire || io.vecmmioStout.fire)
1192  XSPerfAccumulate("mmio_wb_blocked", (io.mmioStout.valid && !io.mmioStout.ready) || (io.vecmmioStout.valid && !io.vecmmioStout.ready))
1193  XSPerfAccumulate("validEntryCnt", distanceBetween(enqPtrExt(0), deqPtrExt(0)))
1194  XSPerfAccumulate("cmtEntryCnt", distanceBetween(cmtPtrExt(0), deqPtrExt(0)))
1195  XSPerfAccumulate("nCmtEntryCnt", distanceBetween(enqPtrExt(0), cmtPtrExt(0)))
1196
1197  val perfValidCount = distanceBetween(enqPtrExt(0), deqPtrExt(0))
1198  val perfEvents = Seq(
1199    ("mmioCycle      ", uncacheState =/= s_idle),
1200    ("mmioCnt        ", io.uncache.req.fire),
1201    ("mmio_wb_success", io.mmioStout.fire || io.vecmmioStout.fire),
1202    ("mmio_wb_blocked", (io.mmioStout.valid && !io.mmioStout.ready) || (io.vecmmioStout.valid && !io.vecmmioStout.ready)),
1203    ("stq_1_4_valid  ", (perfValidCount < (StoreQueueSize.U/4.U))),
1204    ("stq_2_4_valid  ", (perfValidCount > (StoreQueueSize.U/4.U)) & (perfValidCount <= (StoreQueueSize.U/2.U))),
1205    ("stq_3_4_valid  ", (perfValidCount > (StoreQueueSize.U/2.U)) & (perfValidCount <= (StoreQueueSize.U*3.U/4.U))),
1206    ("stq_4_4_valid  ", (perfValidCount > (StoreQueueSize.U*3.U/4.U))),
1207  )
1208  generatePerfEvent()
1209
1210  // debug info
1211  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt(0).flag, deqPtr)
1212
1213  def PrintFlag(flag: Bool, name: String): Unit = {
1214    when(flag) {
1215      XSDebug(false, true.B, name)
1216    }.otherwise {
1217      XSDebug(false, true.B, " ")
1218    }
1219  }
1220
1221  for (i <- 0 until StoreQueueSize) {
1222    XSDebug(s"$i: pc %x va %x pa %x data %x ",
1223      uop(i).pc,
1224      debug_vaddr(i),
1225      debug_paddr(i),
1226      debug_data(i)
1227    )
1228    PrintFlag(allocated(i), "a")
1229    PrintFlag(allocated(i) && addrvalid(i), "a")
1230    PrintFlag(allocated(i) && datavalid(i), "d")
1231    PrintFlag(allocated(i) && committed(i), "c")
1232    PrintFlag(allocated(i) && pending(i), "p")
1233    PrintFlag(allocated(i) && mmio(i), "m")
1234    XSDebug(false, true.B, "\n")
1235  }
1236
1237}
1238