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