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