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