xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/StoreQueue.scala (revision 042e89e414f8956a139ecd64336469a6a7b5ff6f)
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.cache.{CMOReq, CMOResp}
31import xiangshan.backend._
32import xiangshan.backend.rob.{RobLsqIO, RobPtr}
33import xiangshan.backend.Bundles.{DynInst, MemExuOutput}
34import xiangshan.backend.decode.isa.bitfield.{Riscv32BitInst, XSInstBitFields}
35import xiangshan.backend.fu.FuConfig._
36import xiangshan.backend.fu.FuType
37import xiangshan.ExceptionNO._
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  val sqNeedDeq = Bool()
71}
72
73class StoreExceptionBuffer(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
74  // The 1st StorePipelineWidth ports: sta exception generated at s1, except for af
75  // The 2nd StorePipelineWidth ports: sta af generated at s2
76  // The following VecStorePipelineWidth ports: vector st exception
77  // The last port: non-data error generated in SoC
78  val enqPortNum = StorePipelineWidth * 2 + VecStorePipelineWidth + 1
79
80  val io = IO(new Bundle() {
81    val redirect = Flipped(ValidIO(new Redirect))
82    val storeAddrIn = Vec(enqPortNum, Flipped(ValidIO(new LsPipelineBundle())))
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 := 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          (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}
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.fullva         := io.vecFeedback(i).bits.vaddr
238    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.vaNeedExt      := io.vecFeedback(i).bits.vaNeedExt
239    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.gpaddr         := io.vecFeedback(i).bits.gpaddr
240    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.uop.uopIdx     := io.vecFeedback(i).bits.uopidx
241    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.uop.robIdx     := io.vecFeedback(i).bits.robidx
242    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.uop.vpu.vstart := io.vecFeedback(i).bits.vstart
243    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.uop.vpu.vl     := io.vecFeedback(i).bits.vl
244    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.isForVSnonLeafPTE := io.vecFeedback(i).bits.isForVSnonLeafPTE
245    exceptionBuffer.io.storeAddrIn(StorePipelineWidth * 2 + i).bits.uop.exceptionVec  := io.vecFeedback(i).bits.exceptionVec
246  }
247
248
249  val debug_paddr = Reg(Vec(StoreQueueSize, UInt((PAddrBits).W)))
250  val debug_vaddr = Reg(Vec(StoreQueueSize, UInt((VAddrBits).W)))
251  val debug_data = Reg(Vec(StoreQueueSize, UInt((XLEN).W)))
252
253  // state & misc
254  val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated
255  val addrvalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B)))
256  val datavalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B)))
257  val allvalid  = VecInit((0 until StoreQueueSize).map(i => addrvalid(i) && datavalid(i)))
258  val committed = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // inst has been committed by rob
259  val unaligned = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // unaligned store
260  val cross16Byte = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // unaligned cross 16Byte boundary
261  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
262  val nc = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // nc: inst is a nc inst
263  val mmio = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // mmio: inst is an mmio inst
264  val atomic = RegInit(VecInit(List.fill(StoreQueueSize)(false.B)))
265  val prefetch = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // need prefetch when committing this store to sbuffer?
266  val isVec = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // vector store instruction
267  val vecLastFlow = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // last uop the last flow of vector store instruction
268  val vecMbCommit = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // vector store committed from merge buffer to rob
269  val hasException = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // store has exception, should deq but not write sbuffer
270  val waitStoreS2 = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // wait for mmio and exception result until store_s2
271  // val vec_robCommit = Reg(Vec(StoreQueueSize, Bool())) // vector store committed by rob
272  // val vec_secondInv = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // Vector unit-stride, second entry is invalid
273  val vecExceptionFlag = RegInit(0.U.asTypeOf(Valid(new DynInst)))
274
275  // ptr
276  val enqPtrExt = RegInit(VecInit((0 until io.enq.req.length).map(_.U.asTypeOf(new SqPtr))))
277  val rdataPtrExt = RegInit(VecInit((0 until EnsbufferWidth).map(_.U.asTypeOf(new SqPtr))))
278  val deqPtrExt = RegInit(VecInit((0 until EnsbufferWidth).map(_.U.asTypeOf(new SqPtr))))
279  val cmtPtrExt = RegInit(VecInit((0 until CommitWidth).map(_.U.asTypeOf(new SqPtr))))
280  val addrReadyPtrExt = RegInit(0.U.asTypeOf(new SqPtr))
281  val dataReadyPtrExt = RegInit(0.U.asTypeOf(new SqPtr))
282
283  val enqPtr = enqPtrExt(0).value
284  val deqPtr = deqPtrExt(0).value
285  val cmtPtr = cmtPtrExt(0).value
286
287  val validCount = distanceBetween(enqPtrExt(0), deqPtrExt(0))
288  val allowEnqueue = validCount <= (StoreQueueSize - LSQStEnqWidth).U
289
290  val deqMask = UIntToMask(deqPtr, StoreQueueSize)
291  val enqMask = UIntToMask(enqPtr, StoreQueueSize)
292
293  val commitCount = WireInit(0.U(log2Ceil(CommitWidth + 1).W))
294  val scommit = GatedRegNext(io.rob.scommit)
295  val mmioReq = Wire(chiselTypeOf(io.uncache.req))
296  val ncReq = Wire(chiselTypeOf(io.uncache.req))
297  val ncResp = Wire(chiselTypeOf(io.uncache.resp))
298  val ncDoReq = Wire(Bool())
299  val ncDoResp = Wire(Bool())
300  val ncReadNextTrigger = Mux(io.uncacheOutstanding, ncDoReq, ncDoResp)
301  // ncDoReq is double RegNexted, as ubuffer data write takes 3 cycles.
302  // TODO lyq: to eliminate coupling by passing signals through ubuffer
303  val ncDeqTrigger = Mux(io.uncacheOutstanding, RegNext(RegNext(ncDoReq)), ncDoResp)
304  val ncPtr = Mux(io.uncacheOutstanding, RegNext(RegNext(io.uncache.req.bits.id)), io.uncache.resp.bits.id)
305
306  // store can be committed by ROB
307  io.rob.mmio := DontCare
308  io.rob.uop := DontCare
309
310  // Read dataModule
311  assert(EnsbufferWidth <= 2)
312  // rdataPtrExtNext and rdataPtrExtNext+1 entry will be read from dataModule
313  val rdataPtrExtNext = Wire(Vec(EnsbufferWidth, new SqPtr))
314  rdataPtrExtNext := rdataPtrExt.map(i => i +
315    PopCount(dataBuffer.io.enq.map(x=> x.fire && x.bits.sqNeedDeq)) +
316    PopCount(ncReadNextTrigger || io.mmioStout.fire || io.vecmmioStout.fire)
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  // Only sqNeedDeq can move the ptr
329  deqPtrExtNext := deqPtrExt.map(i =>  i +
330    RegNext(PopCount(VecInit(io.sbuffer.map(x=> x.fire && x.bits.sqNeedDeq)))) +
331    PopCount(ncDeqTrigger || io.mmioStout.fire || io.vecmmioStout.fire)
332  )
333
334  io.sqDeq := RegNext(
335    RegNext(PopCount(VecInit(io.sbuffer.map(x=> x.fire && x.bits.sqNeedDeq)))) +
336    PopCount(ncDeqTrigger || io.mmioStout.fire || io.vecmmioStout.fire)
337  )
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          vecLastFlow((index + j.U).value) := Mux((j + 1).U === validVStoreOffset(i), io.enq.req(i).bits.lastUop, false.B)
374          allocated((index + j.U).value) := true.B
375          datavalid((index + j.U).value) := false.B
376          addrvalid((index + j.U).value) := false.B
377          unaligned((index + j.U).value) := false.B
378          cross16Byte((index + j.U).value) := false.B
379          committed((index + j.U).value) := false.B
380          pending((index + j.U).value) := false.B
381          prefetch((index + j.U).value) := false.B
382          nc((index + j.U).value) := false.B
383          mmio((index + j.U).value) := false.B
384          isVec((index + j.U).value) :=  FuType.isVStore(io.enq.req(i).bits.fuType)
385          vecMbCommit((index + j.U).value) := false.B
386          hasException((index + j.U).value) := false.B
387          waitStoreS2((index + j.U).value) := true.B
388          XSError(!io.enq.canAccept || !io.enq.lqCanAccept, s"must accept $i\n")
389          XSError(index.value =/= sqIdx.value, s"must be the same entry $i\n")
390        }
391      }
392    }
393    io.enq.resp(i) := sqIdx
394  }
395  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
396
397  /**
398    * Update addr/dataReadyPtr when issue from rs
399    */
400  // update issuePtr
401  val IssuePtrMoveStride = 4
402  require(IssuePtrMoveStride >= 2)
403
404  val addrReadyLookupVec = (0 until IssuePtrMoveStride).map(addrReadyPtrExt + _.U)
405  val addrReadyLookup = addrReadyLookupVec.map(ptr => allocated(ptr.value) &&
406   (mmio(ptr.value) || addrvalid(ptr.value) || vecMbCommit(ptr.value))
407    && ptr =/= enqPtrExt(0))
408  val nextAddrReadyPtr = addrReadyPtrExt + PriorityEncoder(VecInit(addrReadyLookup.map(!_) :+ true.B))
409  addrReadyPtrExt := nextAddrReadyPtr
410
411  val stAddrReadyVecReg = Wire(Vec(StoreQueueSize, Bool()))
412  (0 until StoreQueueSize).map(i => {
413    stAddrReadyVecReg(i) := allocated(i) && (mmio(i) || addrvalid(i) || (isVec(i) && vecMbCommit(i)))
414  })
415  io.stAddrReadyVec := GatedValidRegNext(stAddrReadyVecReg)
416
417  when (io.brqRedirect.valid) {
418    addrReadyPtrExt := Mux(
419      isAfter(cmtPtrExt(0), deqPtrExt(0)),
420      cmtPtrExt(0),
421      deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr
422    )
423  }
424
425  io.stAddrReadySqPtr := addrReadyPtrExt
426
427  // update
428  val dataReadyLookupVec = (0 until IssuePtrMoveStride).map(dataReadyPtrExt + _.U)
429  val dataReadyLookup = dataReadyLookupVec.map(ptr => allocated(ptr.value) &&
430   (mmio(ptr.value) || datavalid(ptr.value) || vecMbCommit(ptr.value))
431    && ptr =/= enqPtrExt(0))
432  val nextDataReadyPtr = dataReadyPtrExt + PriorityEncoder(VecInit(dataReadyLookup.map(!_) :+ true.B))
433  dataReadyPtrExt := nextDataReadyPtr
434
435  val stDataReadyVecReg = Wire(Vec(StoreQueueSize, Bool()))
436  (0 until StoreQueueSize).map(i => {
437    stDataReadyVecReg(i) := allocated(i) && (mmio(i) || datavalid(i) || (isVec(i) && vecMbCommit(i)))
438  })
439  io.stDataReadyVec := GatedValidRegNext(stDataReadyVecReg)
440
441  when (io.brqRedirect.valid) {
442    dataReadyPtrExt := Mux(
443      isAfter(cmtPtrExt(0), deqPtrExt(0)),
444      cmtPtrExt(0),
445      deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr
446    )
447  }
448
449  io.stDataReadySqPtr := dataReadyPtrExt
450  io.stIssuePtr := enqPtrExt(0)
451  io.sqDeqPtr := deqPtrExt(0)
452
453  /**
454    * Writeback store from store units
455    *
456    * Most store instructions writeback to regfile in the previous cycle.
457    * However,
458    *   (1) For an mmio instruction with exceptions, we need to mark it as addrvalid
459    * (in this way it will trigger an exception when it reaches ROB's head)
460    * instead of pending to avoid sending them to lower level.
461    *   (2) For an mmio instruction without exceptions, we mark it as pending.
462    * When the instruction reaches ROB's head, StoreQueue sends it to uncache channel.
463    * Upon receiving the response, StoreQueue writes back the instruction
464    * through arbiter with store units. It will later commit as normal.
465    */
466
467  // Write addr to sq
468  for (i <- 0 until StorePipelineWidth) {
469    paddrModule.io.wen(i) := false.B
470    vaddrModule.io.wen(i) := false.B
471    dataModule.io.mask.wen(i) := false.B
472    val stWbIndex = io.storeAddrIn(i).bits.uop.sqIdx.value
473    exceptionBuffer.io.storeAddrIn(i).valid := io.storeAddrIn(i).fire && !io.storeAddrIn(i).bits.miss && !io.storeAddrIn(i).bits.isvec
474    exceptionBuffer.io.storeAddrIn(i).bits := io.storeAddrIn(i).bits
475    // will re-enter exceptionbuffer at store_s2
476    exceptionBuffer.io.storeAddrIn(StorePipelineWidth + i).valid := false.B
477    exceptionBuffer.io.storeAddrIn(StorePipelineWidth + i).bits := 0.U.asTypeOf(new LsPipelineBundle)
478
479    when (io.storeAddrIn(i).fire && io.storeAddrIn(i).bits.updateAddrValid) {
480      val addr_valid = !io.storeAddrIn(i).bits.miss
481      addrvalid(stWbIndex) := addr_valid //!io.storeAddrIn(i).bits.mmio
482      nc(stWbIndex) := io.storeAddrIn(i).bits.nc
483
484    }
485    when (io.storeAddrIn(i).fire && !io.storeAddrIn(i).bits.isFrmMisAlignBuf) {
486      // pending(stWbIndex) := io.storeAddrIn(i).bits.mmio
487      unaligned(stWbIndex) := io.storeAddrIn(i).bits.isMisalign
488      cross16Byte(stWbIndex) := io.storeAddrIn(i).bits.isMisalign && !io.storeAddrIn(i).bits.misalignWith16Byte
489
490      paddrModule.io.waddr(i) := stWbIndex
491      paddrModule.io.wdata(i) := io.storeAddrIn(i).bits.paddr
492      paddrModule.io.wmask(i) := io.storeAddrIn(i).bits.mask
493      paddrModule.io.wlineflag(i) := io.storeAddrIn(i).bits.wlineflag
494      paddrModule.io.wen(i) := true.B
495
496      vaddrModule.io.waddr(i) := stWbIndex
497      vaddrModule.io.wdata(i) := io.storeAddrIn(i).bits.vaddr
498      vaddrModule.io.wmask(i) := io.storeAddrIn(i).bits.mask
499      vaddrModule.io.wlineflag(i) := io.storeAddrIn(i).bits.wlineflag
500      vaddrModule.io.wen(i) := true.B
501
502      debug_paddr(paddrModule.io.waddr(i)) := paddrModule.io.wdata(i)
503
504      // mmio(stWbIndex) := io.storeAddrIn(i).bits.mmio
505
506      XSInfo("store addr write to sq idx %d pc 0x%x miss:%d vaddr %x paddr %x mmio %x isvec %x\n",
507        io.storeAddrIn(i).bits.uop.sqIdx.value,
508        io.storeAddrIn(i).bits.uop.pc,
509        io.storeAddrIn(i).bits.miss,
510        io.storeAddrIn(i).bits.vaddr,
511        io.storeAddrIn(i).bits.paddr,
512        io.storeAddrIn(i).bits.mmio,
513        io.storeAddrIn(i).bits.isvec
514      )
515    }
516    when (io.storeAddrIn(i).fire) {
517      uop(stWbIndex) := io.storeAddrIn(i).bits.uop
518      uop(stWbIndex).debugInfo := io.storeAddrIn(i).bits.uop.debugInfo
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) && io.storeAddrInRe(i).updateAddrValid
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) := io.storeAddrInRe(i).hasException
530      waitStoreS2(stWbIndexReg) := false.B
531    }
532    // dcache miss info (one cycle later than storeIn)
533    // if dcache report a miss in sta pipeline, this store will trigger a prefetch when committing to sbuffer (if EnableAtCommitMissTrigger)
534    when (storeAddrInFireReg) {
535      prefetch(stWbIndexReg) := io.storeAddrInRe(i).miss
536    }
537    // enter exceptionbuffer again
538    when (storeAddrInFireReg) {
539      exceptionBuffer.io.storeAddrIn(StorePipelineWidth + i).valid := io.storeAddrInRe(i).hasException && !io.storeAddrInRe(i).isvec
540      exceptionBuffer.io.storeAddrIn(StorePipelineWidth + i).bits := io.storeAddrInRe(i)
541      exceptionBuffer.io.storeAddrIn(StorePipelineWidth + i).bits.uop.exceptionVec(storeAccessFault) := io.storeAddrInRe(i).af
542    }
543
544    when(vaddrModule.io.wen(i)){
545      debug_vaddr(vaddrModule.io.waddr(i)) := vaddrModule.io.wdata(i)
546    }
547  }
548
549  // Write data to sq
550  // Now store data pipeline is actually 2 stages
551  for (i <- 0 until StorePipelineWidth) {
552    dataModule.io.data.wen(i) := false.B
553    val stWbIndex = io.storeDataIn(i).bits.uop.sqIdx.value
554    val isVec     = FuType.isVStore(io.storeDataIn(i).bits.uop.fuType)
555    // sq data write takes 2 cycles:
556    // sq data write s0
557    when (io.storeDataIn(i).fire) {
558      // send data write req to data module
559      dataModule.io.data.waddr(i) := stWbIndex
560      dataModule.io.data.wdata(i) := Mux(io.storeDataIn(i).bits.uop.fuOpType === LSUOpType.cbo_zero,
561        0.U,
562        Mux(isVec,
563          io.storeDataIn(i).bits.data,
564          genVWdata(io.storeDataIn(i).bits.data, io.storeDataIn(i).bits.uop.fuOpType(2,0)))
565      )
566      dataModule.io.data.wen(i) := true.B
567
568      debug_data(dataModule.io.data.waddr(i)) := dataModule.io.data.wdata(i)
569
570      XSInfo("store data write to sq idx %d pc 0x%x data %x -> %x\n",
571        io.storeDataIn(i).bits.uop.sqIdx.value,
572        io.storeDataIn(i).bits.uop.pc,
573        io.storeDataIn(i).bits.data,
574        dataModule.io.data.wdata(i)
575      )
576    }
577    // sq data write s1
578    val lastStWbIndex = RegEnable(stWbIndex, io.storeDataIn(i).fire)
579    when (
580      RegNext(io.storeDataIn(i).fire) && allocated(lastStWbIndex)
581      // && !RegNext(io.storeDataIn(i).bits.uop).robIdx.needFlush(io.brqRedirect)
582    ) {
583      datavalid(lastStWbIndex) := 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
674    //TODO If the previous store appears out of alignment, then simply FF, this is a very unreasonable way to do it.
675    //TODO But for the time being, this is the way to ensure correctness. Such a suitable opportunity to support unaligned forward.
676    // If addr match, data not ready, mark it as dataInvalid
677    // load_s1: generate dataInvalid in load_s1 to set fastUop
678    val dataInvalidMask1 = ((addrValidVec.asUInt & ~dataValidVec.asUInt & vaddrModule.io.forwardMmask(i).asUInt) | unaligned.asUInt & allocated.asUInt) & forwardMask1.asUInt
679    val dataInvalidMask2 = ((addrValidVec.asUInt & ~dataValidVec.asUInt & vaddrModule.io.forwardMmask(i).asUInt) | unaligned.asUInt & allocated.asUInt) & forwardMask2.asUInt
680    val dataInvalidMask = dataInvalidMask1 | dataInvalidMask2
681    io.forward(i).dataInvalidFast := dataInvalidMask.orR
682
683    // make chisel happy
684    val dataInvalidMask1Reg = Wire(UInt(StoreQueueSize.W))
685    dataInvalidMask1Reg := RegNext(dataInvalidMask1)
686    // make chisel happy
687    val dataInvalidMask2Reg = Wire(UInt(StoreQueueSize.W))
688    dataInvalidMask2Reg := RegNext(dataInvalidMask2)
689    val dataInvalidMaskReg = dataInvalidMask1Reg | dataInvalidMask2Reg
690
691    // If SSID match, address not ready, mark it as addrInvalid
692    // load_s2: generate addrInvalid
693    val addrInvalidMask1 = (~addrValidVec.asUInt & storeSetHitVec.asUInt & forwardMask1.asUInt)
694    val addrInvalidMask2 = (~addrValidVec.asUInt & storeSetHitVec.asUInt & forwardMask2.asUInt)
695    // make chisel happy
696    val addrInvalidMask1Reg = Wire(UInt(StoreQueueSize.W))
697    addrInvalidMask1Reg := RegNext(addrInvalidMask1)
698    // make chisel happy
699    val addrInvalidMask2Reg = Wire(UInt(StoreQueueSize.W))
700    addrInvalidMask2Reg := RegNext(addrInvalidMask2)
701    val addrInvalidMaskReg = addrInvalidMask1Reg | addrInvalidMask2Reg
702
703    // load_s2
704    io.forward(i).dataInvalid := RegNext(io.forward(i).dataInvalidFast)
705    // check if vaddr forward mismatched
706    io.forward(i).matchInvalid := vaddrMatchFailed
707
708    // data invalid sq index
709    // check whether false fail
710    // check flag
711    val s2_differentFlag = RegNext(differentFlag)
712    val s2_enqPtrExt = RegNext(enqPtrExt(0))
713    val s2_deqPtrExt = RegNext(deqPtrExt(0))
714
715    // addr invalid sq index
716    // make chisel happy
717    val addrInvalidMaskRegWire = Wire(UInt(StoreQueueSize.W))
718    addrInvalidMaskRegWire := addrInvalidMaskReg
719    val addrInvalidFlag = addrInvalidMaskRegWire.orR
720    val hasInvalidAddr = (~addrValidVec.asUInt & needForward).orR
721
722    val addrInvalidSqIdx1 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(addrInvalidMask1Reg))))
723    val addrInvalidSqIdx2 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(addrInvalidMask2Reg))))
724    val addrInvalidSqIdx = Mux(addrInvalidMask2Reg.orR, addrInvalidSqIdx2, addrInvalidSqIdx1)
725
726    // store-set content management
727    //                +-----------------------+
728    //                | Search a SSID for the |
729    //                |    load operation     |
730    //                +-----------------------+
731    //                           |
732    //                           V
733    //                 +-------------------+
734    //                 | load wait strict? |
735    //                 +-------------------+
736    //                           |
737    //                           V
738    //               +----------------------+
739    //            Set|                      |Clean
740    //               V                      V
741    //  +------------------------+   +------------------------------+
742    //  | Waiting for all older  |   | Wait until the corresponding |
743    //  |   stores operations    |   | older store operations       |
744    //  +------------------------+   +------------------------------+
745
746
747
748    when (RegEnable(io.forward(i).uop.loadWaitStrict, io.forward(i).valid)) {
749      io.forward(i).addrInvalidSqIdx := RegEnable((io.forward(i).uop.sqIdx - 1.U), io.forward(i).valid)
750    } .elsewhen (addrInvalidFlag) {
751      io.forward(i).addrInvalidSqIdx.flag := Mux(!s2_differentFlag || addrInvalidSqIdx >= s2_deqPtrExt.value, s2_deqPtrExt.flag, s2_enqPtrExt.flag)
752      io.forward(i).addrInvalidSqIdx.value := addrInvalidSqIdx
753    } .otherwise {
754      // may be store inst has been written to sbuffer already.
755      io.forward(i).addrInvalidSqIdx := RegEnable(io.forward(i).uop.sqIdx, io.forward(i).valid)
756    }
757    io.forward(i).addrInvalid := Mux(RegEnable(io.forward(i).uop.loadWaitStrict, io.forward(i).valid), RegNext(hasInvalidAddr), addrInvalidFlag)
758
759    // data invalid sq index
760    // make chisel happy
761    val dataInvalidMaskRegWire = Wire(UInt(StoreQueueSize.W))
762    dataInvalidMaskRegWire := dataInvalidMaskReg
763    val dataInvalidFlag = dataInvalidMaskRegWire.orR
764
765    val dataInvalidSqIdx1 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(dataInvalidMask1Reg))))
766    val dataInvalidSqIdx2 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(dataInvalidMask2Reg))))
767    val dataInvalidSqIdx = Mux(dataInvalidMask2Reg.orR, dataInvalidSqIdx2, dataInvalidSqIdx1)
768
769    when (dataInvalidFlag) {
770      io.forward(i).dataInvalidSqIdx.flag := Mux(!s2_differentFlag || dataInvalidSqIdx >= s2_deqPtrExt.value, s2_deqPtrExt.flag, s2_enqPtrExt.flag)
771      io.forward(i).dataInvalidSqIdx.value := dataInvalidSqIdx
772    } .otherwise {
773      // may be store inst has been written to sbuffer already.
774      io.forward(i).dataInvalidSqIdx := RegEnable(io.forward(i).uop.sqIdx, io.forward(i).valid)
775    }
776  }
777
778  /**
779    * Memory mapped IO / other uncached operations / CMO
780    *
781    * States:
782    * (1) writeback from store units: mark as pending
783    * (2) when they reach ROB's head, they can be sent to uncache channel
784    * (3) response from uncache channel: mark as datavalidmask.wen
785    * (4) writeback to ROB (and other units): mark as writebacked
786    * (5) ROB commits the instruction: same as normal instructions
787    */
788  //(2) when they reach ROB's head, they can be sent to uncache channel
789  // TODO: CAN NOT deal with vector mmio now!
790  val s_idle :: s_req :: s_resp :: s_wb :: s_wait :: Nil = Enum(5)
791  val mmioState = RegInit(s_idle)
792  val uncacheUop = Reg(new DynInst)
793  val cboFlushedSb = RegInit(false.B)
794  val cmoOpCode = uncacheUop.fuOpType(1, 0)
795  val mmioDoReq = io.uncache.req.fire && !io.uncache.req.bits.nc
796  val cboMmioPAddr = Reg(UInt(PAddrBits.W))
797  switch(mmioState) {
798    is(s_idle) {
799      when(RegNext(io.rob.pendingst && uop(deqPtr).robIdx === io.rob.pendingPtr && pending(deqPtr) && allocated(deqPtr) && datavalid(deqPtr) && addrvalid(deqPtr) && !hasException(deqPtr))) {
800        mmioState := s_req
801        uncacheUop := uop(deqPtr)
802        uncacheUop.exceptionVec := 0.U.asTypeOf(ExceptionVec())
803        cboFlushedSb := false.B
804        cboMmioPAddr := paddrModule.io.rdata(0)
805      }
806    }
807    is(s_req) {
808      when (mmioDoReq) {
809        mmioState := s_resp
810      }
811    }
812    is(s_resp) {
813      when(io.uncache.resp.fire && !io.uncache.resp.bits.nc) {
814        mmioState := s_wb
815
816        when (io.uncache.resp.bits.nderr) {
817          uncacheUop.exceptionVec(storeAccessFault) := true.B
818        }
819      }
820    }
821    is(s_wb) {
822      when (io.mmioStout.fire || io.vecmmioStout.fire) {
823        when (uncacheUop.exceptionVec(storeAccessFault)) {
824          mmioState := s_idle
825        }.otherwise {
826          mmioState := s_wait
827        }
828      }
829    }
830    is(s_wait) {
831      // A MMIO store can always move cmtPtrExt as it must be ROB head
832      when(scommit > 0.U) {
833        mmioState := s_idle // ready for next mmio
834      }
835    }
836  }
837
838  mmioReq.valid := mmioState === s_req
839  mmioReq.bits := DontCare
840  mmioReq.bits.cmd  := MemoryOpConstants.M_XWR
841  mmioReq.bits.addr := paddrModule.io.rdata(0) // data(deqPtr) -> rdata(0)
842  mmioReq.bits.vaddr:= vaddrModule.io.rdata(0)
843  mmioReq.bits.data := shiftDataToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).data)
844  mmioReq.bits.mask := shiftMaskToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).mask)
845  mmioReq.bits.atomic := atomic(GatedRegNext(rdataPtrExtNext(0)).value)
846  mmioReq.bits.nc := false.B
847  mmioReq.bits.id := rdataPtrExt(0).value
848
849  /**
850    * NC Store
851    * (1) req: when it has been commited, it can be sent to lower level.
852    * (2) resp: because SQ data forward is required, it can only be deq when ncResp is received
853    */
854  // TODO: CAN NOT deal with vector nc now!
855  val nc_idle :: nc_req :: nc_resp :: Nil = Enum(3)
856  val ncState = RegInit(nc_idle)
857  val rptr0 = rdataPtrExt(0).value
858  switch(ncState){
859    is(nc_idle) {
860      when(nc(rptr0) && allocated(rptr0) && committed(rptr0) && !mmio(rptr0) && !isVec(rptr0)) {
861        ncState := nc_req
862      }
863    }
864    is(nc_req) {
865      when(ncDoReq) {
866        when(io.uncacheOutstanding) {
867          ncState := nc_idle
868        }.otherwise{
869          ncState := nc_resp
870        }
871      }
872    }
873    is(nc_resp) {
874      when(ncResp.fire) {
875        ncState := nc_idle
876      }
877    }
878  }
879
880  ncDoReq := io.uncache.req.fire && io.uncache.req.bits.nc
881  ncDoResp := ncResp.fire
882
883  ncReq.valid := ncState === nc_req
884  ncReq.bits := DontCare
885  ncReq.bits.cmd  := MemoryOpConstants.M_XWR
886  ncReq.bits.addr := paddrModule.io.rdata(0)
887  ncReq.bits.vaddr:= vaddrModule.io.rdata(0)
888  ncReq.bits.data := shiftDataToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).data)
889  ncReq.bits.mask := shiftMaskToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).mask)
890  ncReq.bits.atomic := atomic(GatedRegNext(rdataPtrExtNext(0)).value)
891  ncReq.bits.nc := true.B
892  ncReq.bits.id := rptr0
893
894  ncResp.ready := io.uncache.resp.ready
895  ncResp.valid := io.uncache.resp.fire && io.uncache.resp.bits.nc
896  ncResp.bits <> io.uncache.resp.bits
897  when (ncDeqTrigger) {
898    allocated(ncPtr) := false.B
899    XSDebug("nc fire: ptr %d\n", ncPtr)
900  }
901
902  mmioReq.ready := io.uncache.req.ready
903  ncReq.ready := io.uncache.req.ready && !mmioReq.valid
904  io.uncache.req.valid := mmioReq.valid || ncReq.valid
905  io.uncache.req.bits := Mux(mmioReq.valid, mmioReq.bits, ncReq.bits)
906
907  // CBO op type check can be delayed for 1 cycle,
908  // as uncache op will not start in s_idle
909  val cboMmioAddr = get_block_addr(cboMmioPAddr)
910  val deqCanDoCbo = GatedRegNext(LSUOpType.isCbo(uop(deqPtr).fuOpType) && allocated(deqPtr) && addrvalid(deqPtr))
911  when (deqCanDoCbo) {
912    // disable uncache channel
913    io.uncache.req.valid := false.B
914
915    when (io.cmoOpReq.fire) {
916      mmioState := s_resp
917    }
918
919    when (mmioState === s_resp) {
920      when (io.cmoOpResp.fire) {
921        mmioState := s_wb
922      }
923    }
924  }
925
926  io.cmoOpReq.valid := deqCanDoCbo && cboFlushedSb && (mmioState === s_req)
927  io.cmoOpReq.bits.opcode  := cmoOpCode
928  io.cmoOpReq.bits.address := cboMmioAddr
929
930  io.cmoOpResp.ready := deqCanDoCbo && (mmioState === s_resp)
931
932  io.flushSbuffer.valid := deqCanDoCbo && !cboFlushedSb && (mmioState === s_req) && !io.flushSbuffer.empty
933
934  when(deqCanDoCbo && !cboFlushedSb && (mmioState === s_req) && io.flushSbuffer.empty) {
935    cboFlushedSb := true.B
936  }
937
938  when(mmioDoReq){
939    // mmio store should not be committed until uncache req is sent
940    pending(deqPtr) := false.B
941
942    XSDebug(
943      p"uncache mmio req: pc ${Hexadecimal(uop(deqPtr).pc)} " +
944      p"addr ${Hexadecimal(io.uncache.req.bits.addr)} " +
945      p"data ${Hexadecimal(io.uncache.req.bits.data)} " +
946      p"op ${Hexadecimal(io.uncache.req.bits.cmd)} " +
947      p"mask ${Hexadecimal(io.uncache.req.bits.mask)}\n"
948    )
949  }
950
951  // (3) response from uncache channel: mark as datavalid
952  io.uncache.resp.ready := true.B
953
954  // (4) scalar store: writeback to ROB (and other units): mark as writebacked
955  io.mmioStout.valid := mmioState === s_wb && !isVec(deqPtr)
956  io.mmioStout.bits.uop := uncacheUop
957  io.mmioStout.bits.uop.exceptionVec := ExceptionNO.selectByFu(uncacheUop.exceptionVec, StaCfg)
958  io.mmioStout.bits.uop.sqIdx := deqPtrExt(0)
959  io.mmioStout.bits.uop.flushPipe := deqCanDoCbo // flush Pipeline to keep order in CMO
960  io.mmioStout.bits.data := shiftDataToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).data) // dataModule.io.rdata.read(deqPtr)
961  io.mmioStout.bits.isFromLoadUnit := DontCare
962  io.mmioStout.bits.debug.isMMIO := true.B
963  io.mmioStout.bits.debug.isNC := false.B
964  io.mmioStout.bits.debug.paddr := DontCare
965  io.mmioStout.bits.debug.isPerfCnt := false.B
966  io.mmioStout.bits.debug.vaddr := DontCare
967  // Remove MMIO inst from store queue after MMIO request is being sent
968  // That inst will be traced by uncache state machine
969  when (io.mmioStout.fire) {
970    allocated(deqPtr) := false.B
971  }
972
973  exceptionBuffer.io.storeAddrIn.last.valid := io.mmioStout.fire
974  exceptionBuffer.io.storeAddrIn.last.bits := DontCare
975  exceptionBuffer.io.storeAddrIn.last.bits.fullva := vaddrModule.io.rdata.head
976  exceptionBuffer.io.storeAddrIn.last.bits.vaNeedExt := true.B
977  exceptionBuffer.io.storeAddrIn.last.bits.uop := uncacheUop
978
979  // (4) or vector store:
980  // TODO: implement it!
981  io.vecmmioStout := DontCare
982  io.vecmmioStout.valid := false.B //mmioState === s_wb && isVec(deqPtr)
983  io.vecmmioStout.bits.uop := uop(deqPtr)
984  io.vecmmioStout.bits.uop.sqIdx := deqPtrExt(0)
985  io.vecmmioStout.bits.data := shiftDataToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).data) // dataModule.io.rdata.read(deqPtr)
986  io.vecmmioStout.bits.debug.isMMIO := true.B
987  io.vecmmioStout.bits.debug.isNC   := false.B
988  io.vecmmioStout.bits.debug.paddr := DontCare
989  io.vecmmioStout.bits.debug.isPerfCnt := false.B
990  io.vecmmioStout.bits.debug.vaddr := DontCare
991  // Remove MMIO inst from store queue after MMIO request is being sent
992  // That inst will be traced by uncache state machine
993  when (io.vecmmioStout.fire) {
994    allocated(deqPtr) := false.B
995  }
996
997  /**
998    * ROB commits store instructions (mark them as committed)
999    *
1000    * (1) When store commits, mark it as committed.
1001    * (2) They will not be cancelled and can be sent to lower level.
1002    */
1003  XSError(mmioState =/= s_idle && mmioState =/= s_wait && commitCount > 0.U,
1004   "should not commit instruction when MMIO has not been finished\n")
1005
1006  val commitVec = WireInit(VecInit(Seq.fill(CommitWidth)(false.B)))
1007  val needCancel = Wire(Vec(StoreQueueSize, Bool())) // Will be assigned later
1008
1009  if (backendParams.debugEn){ dontTouch(commitVec) }
1010
1011  // TODO: Deal with vector store mmio
1012  for (i <- 0 until CommitWidth) {
1013    // don't mark misalign store as committed
1014    when (
1015      allocated(cmtPtrExt(i).value) &&
1016      isNotAfter(uop(cmtPtrExt(i).value).robIdx, GatedRegNext(io.rob.pendingPtr)) &&
1017      !needCancel(cmtPtrExt(i).value) &&
1018      (!waitStoreS2(cmtPtrExt(i).value) || isVec(cmtPtrExt(i).value))) {
1019      if (i == 0){
1020        // TODO: fixme for vector mmio
1021        when ((mmioState === s_idle) || (mmioState === s_wait && scommit > 0.U)){
1022          when ((isVec(cmtPtrExt(i).value) && vecMbCommit(cmtPtrExt(i).value)) || !isVec(cmtPtrExt(i).value)) {
1023            committed(cmtPtrExt(0).value) := true.B
1024            commitVec(0) := true.B
1025          }
1026        }
1027      } else {
1028        when ((isVec(cmtPtrExt(i).value) && vecMbCommit(cmtPtrExt(i).value)) || !isVec(cmtPtrExt(i).value)) {
1029          committed(cmtPtrExt(i).value) := commitVec(i - 1) || committed(cmtPtrExt(i).value)
1030          commitVec(i) := commitVec(i - 1)
1031        }
1032      }
1033    }
1034  }
1035
1036  commitCount := PopCount(commitVec)
1037  cmtPtrExt := cmtPtrExt.map(_ + commitCount)
1038
1039  /**
1040   * committed stores will not be cancelled and can be sent to lower level.
1041   *
1042   * 1. Store NC: Read data to uncache
1043   *    implement as above
1044   *
1045   * 2. Store Cache: Read data from data module
1046   *    remove retired insts from sq, add retired store to sbuffer.
1047   *    as store queue grows larger and larger, time needed to read data from data
1048   *    module keeps growing higher. Now we give data read a whole cycle.
1049   */
1050
1051  //TODO An unaligned command can only be sent out if the databuffer can enter more than two.
1052  //TODO For now, hardcode the number of ENQs for the databuffer.
1053  val canDeqMisaligned = dataBuffer.io.enq(0).ready && dataBuffer.io.enq(1).ready
1054  val firstWithMisalign = unaligned(rdataPtrExt(0).value)
1055  val firstWithCross16Byte = cross16Byte(rdataPtrExt(0).value)
1056
1057  val isCross4KPage = io.maControl.toStoreQueue.crossPageWithHit
1058  val isCross4KPageCanDeq = io.maControl.toStoreQueue.crossPageCanDeq
1059  // When encountering a cross page store, a request needs to be sent to storeMisalignBuffer for the high page table's paddr.
1060  io.maControl.toStoreMisalignBuffer.sqPtr := rdataPtrExt(0)
1061  io.maControl.toStoreMisalignBuffer.doDeq := isCross4KPage && isCross4KPageCanDeq && dataBuffer.io.enq(0).fire
1062  io.maControl.toStoreMisalignBuffer.uop := uop(rdataPtrExt(0).value)
1063  for (i <- 0 until EnsbufferWidth) {
1064    val ptr = rdataPtrExt(i).value
1065    val mmioStall = if(i == 0) mmio(rdataPtrExt(0).value) else (mmio(rdataPtrExt(i).value) || mmio(rdataPtrExt(i-1).value))
1066    val ncStall = if(i == 0) nc(rdataPtrExt(0).value) else (nc(rdataPtrExt(i).value) || nc(rdataPtrExt(i-1).value))
1067    val exceptionValid = if(i == 0) hasException(rdataPtrExt(0).value) else {
1068      hasException(rdataPtrExt(i).value) || (hasException(rdataPtrExt(i-1).value) && uop(rdataPtrExt(i).value).robIdx === uop(rdataPtrExt(i-1).value).robIdx)
1069    }
1070    val vecNotAllMask = dataModule.io.rdata(i).mask.orR
1071    // Vector instructions that prevent triggered exceptions from being written to the 'databuffer'.
1072    val vecHasExceptionFlagValid = vecExceptionFlag.valid && isVec(ptr) && vecExceptionFlag.bits.robIdx === uop(ptr).robIdx
1073
1074    // Only the first interface can write unaligned directives.
1075    // Simplified design, even if the two ports have exceptions, but still only one unaligned dequeue.
1076    val assert_flag = WireInit(false.B)
1077    when(firstWithMisalign && firstWithCross16Byte) {
1078      dataBuffer.io.enq(0).valid := canDeqMisaligned && allocated(rdataPtrExt(0).value) && committed(rdataPtrExt(0).value) &&
1079        ((!isVec(rdataPtrExt(0).value) && allvalid(rdataPtrExt(0).value) || vecMbCommit(rdataPtrExt(0).value)) &&
1080        (!isCross4KPage || isCross4KPageCanDeq) || hasException(rdataPtrExt(0).value)) && !ncStall
1081
1082      dataBuffer.io.enq(1).valid := canDeqMisaligned && allocated(rdataPtrExt(0).value) && committed(rdataPtrExt(0).value) &&
1083        (!isVec(rdataPtrExt(0).value) && allvalid(rdataPtrExt(0).value) || vecMbCommit(rdataPtrExt(0).value)) &&
1084        (!isCross4KPage || isCross4KPageCanDeq) && !hasException(rdataPtrExt(0).value) && !ncStall
1085      assert_flag := dataBuffer.io.enq(1).valid
1086    }.otherwise {
1087      if (i == 0) {
1088        dataBuffer.io.enq(i).valid := (
1089          allocated(ptr) && committed(ptr)
1090            && ((!isVec(ptr) && (allvalid(ptr) || hasException(ptr))) || vecMbCommit(ptr))
1091            && !mmioStall && !ncStall
1092            && (!unaligned(ptr) || !cross16Byte(ptr) && (allvalid(ptr) || hasException(ptr)))
1093          )
1094      }
1095      else {
1096        dataBuffer.io.enq(i).valid := (
1097          allocated(ptr) && committed(ptr)
1098            && ((!isVec(ptr) && (allvalid(ptr) || hasException(ptr))) || vecMbCommit(ptr))
1099            && !mmioStall && !ncStall
1100            && (!unaligned(ptr) || !cross16Byte(ptr) && (allvalid(ptr) || hasException(ptr)))
1101          )
1102      }
1103    }
1104
1105    val misalignAddrLow = vaddrModule.io.rdata(0)(2, 0)
1106    val cross16ByteAddrLow4bit = vaddrModule.io.rdata(0)(3, 0)
1107    val addrLow4bit = vaddrModule.io.rdata(i)(3, 0)
1108
1109    // For unaligned, we need to generate a base-aligned mask in storeunit and then do a shift split in StoreQueue.
1110    val Cross16ByteMask = Wire(UInt(32.W))
1111    val Cross16ByteData = Wire(UInt(256.W))
1112    Cross16ByteMask := dataModule.io.rdata(0).mask << cross16ByteAddrLow4bit
1113    Cross16ByteData := dataModule.io.rdata(0).data << (cross16ByteAddrLow4bit << 3)
1114
1115    val paddrLow  = Cat(paddrModule.io.rdata(0)(paddrModule.io.rdata(0).getWidth - 1, 3), 0.U(3.W))
1116    val paddrHigh = Cat(paddrModule.io.rdata(0)(paddrModule.io.rdata(0).getWidth - 1, 3), 0.U(3.W)) + 8.U
1117
1118    val vaddrLow  = Cat(vaddrModule.io.rdata(0)(vaddrModule.io.rdata(0).getWidth - 1, 3), 0.U(3.W))
1119    val vaddrHigh = Cat(vaddrModule.io.rdata(0)(vaddrModule.io.rdata(0).getWidth - 1, 3), 0.U(3.W)) + 8.U
1120
1121    val maskLow   = Cross16ByteMask(15, 0)
1122    val maskHigh  = Cross16ByteMask(31, 16)
1123
1124    val dataLow   = Cross16ByteData(127, 0)
1125    val dataHigh  = Cross16ByteData(255, 128)
1126
1127    val toSbufferVecValid = (!isVec(ptr) || (vecMbCommit(ptr) && allvalid(ptr) && vecNotAllMask)) && !exceptionValid && !vecHasExceptionFlagValid
1128    when(canDeqMisaligned && firstWithMisalign && firstWithCross16Byte) {
1129      when(isCross4KPage && isCross4KPageCanDeq) {
1130        if (i == 0) {
1131          dataBuffer.io.enq(i).bits.addr      := paddrLow
1132          dataBuffer.io.enq(i).bits.vaddr     := vaddrLow
1133          dataBuffer.io.enq(i).bits.data      := dataLow
1134          dataBuffer.io.enq(i).bits.mask      := maskLow
1135          dataBuffer.io.enq(i).bits.wline     := false.B
1136          dataBuffer.io.enq(i).bits.sqPtr     := rdataPtrExt(0)
1137          dataBuffer.io.enq(i).bits.prefetch  := false.B
1138          dataBuffer.io.enq(i).bits.sqNeedDeq := true.B
1139          dataBuffer.io.enq(i).bits.vecValid  := toSbufferVecValid
1140        }
1141        else {
1142          dataBuffer.io.enq(i).bits.addr      := io.maControl.toStoreQueue.paddr
1143          dataBuffer.io.enq(i).bits.vaddr     := vaddrHigh
1144          dataBuffer.io.enq(i).bits.data      := dataHigh
1145          dataBuffer.io.enq(i).bits.mask      := maskHigh
1146          dataBuffer.io.enq(i).bits.wline     := false.B
1147          dataBuffer.io.enq(i).bits.sqPtr     := rdataPtrExt(0)
1148          dataBuffer.io.enq(i).bits.prefetch  := false.B
1149          dataBuffer.io.enq(i).bits.sqNeedDeq := false.B
1150          dataBuffer.io.enq(i).bits.vecValid  := dataBuffer.io.enq(0).bits.vecValid
1151        }
1152      } .otherwise {
1153        if (i == 0) {
1154          dataBuffer.io.enq(i).bits.addr      := paddrLow
1155          dataBuffer.io.enq(i).bits.vaddr     := vaddrLow
1156          dataBuffer.io.enq(i).bits.data      := dataLow
1157          dataBuffer.io.enq(i).bits.mask      := maskLow
1158          dataBuffer.io.enq(i).bits.wline     := false.B
1159          dataBuffer.io.enq(i).bits.sqPtr     := rdataPtrExt(0)
1160          dataBuffer.io.enq(i).bits.prefetch  := false.B
1161          dataBuffer.io.enq(i).bits.sqNeedDeq  := true.B
1162          dataBuffer.io.enq(i).bits.vecValid  := toSbufferVecValid
1163        }
1164        else {
1165          dataBuffer.io.enq(i).bits.addr      := paddrHigh
1166          dataBuffer.io.enq(i).bits.vaddr     := vaddrHigh
1167          dataBuffer.io.enq(i).bits.data      := dataHigh
1168          dataBuffer.io.enq(i).bits.mask      := maskHigh
1169          dataBuffer.io.enq(i).bits.wline     := false.B
1170          dataBuffer.io.enq(i).bits.sqPtr     := rdataPtrExt(0)
1171          dataBuffer.io.enq(i).bits.prefetch  := false.B
1172          dataBuffer.io.enq(i).bits.sqNeedDeq  := false.B
1173          dataBuffer.io.enq(i).bits.vecValid  := dataBuffer.io.enq(0).bits.vecValid
1174        }
1175      }
1176
1177
1178    }.elsewhen(!cross16Byte(ptr) && unaligned(ptr)) {
1179      dataBuffer.io.enq(i).bits.addr     := Cat(paddrModule.io.rdata(i)(PAddrBits - 1, 4), 0.U(4.W))
1180      dataBuffer.io.enq(i).bits.vaddr    := Cat(vaddrModule.io.rdata(i)(VAddrBits - 1, 4), 0.U(4.W))
1181      dataBuffer.io.enq(i).bits.data     := dataModule.io.rdata(i).data << (addrLow4bit << 3)
1182      dataBuffer.io.enq(i).bits.mask     := dataModule.io.rdata(i).mask
1183      dataBuffer.io.enq(i).bits.wline    := paddrModule.io.rlineflag(i)
1184      dataBuffer.io.enq(i).bits.sqPtr    := rdataPtrExt(i)
1185      dataBuffer.io.enq(i).bits.prefetch := prefetch(ptr)
1186      dataBuffer.io.enq(i).bits.sqNeedDeq := true.B
1187      // when scalar has exception, will also not write into sbuffer
1188      dataBuffer.io.enq(i).bits.vecValid := toSbufferVecValid
1189    }.otherwise {
1190      dataBuffer.io.enq(i).bits.addr     := paddrModule.io.rdata(i)
1191      dataBuffer.io.enq(i).bits.vaddr    := vaddrModule.io.rdata(i)
1192      dataBuffer.io.enq(i).bits.data     := dataModule.io.rdata(i).data
1193      dataBuffer.io.enq(i).bits.mask     := dataModule.io.rdata(i).mask
1194      dataBuffer.io.enq(i).bits.wline    := paddrModule.io.rlineflag(i)
1195      dataBuffer.io.enq(i).bits.sqPtr    := rdataPtrExt(i)
1196      dataBuffer.io.enq(i).bits.prefetch := prefetch(ptr)
1197      dataBuffer.io.enq(i).bits.sqNeedDeq := true.B
1198      // when scalar has exception, will also not write into sbuffer
1199      dataBuffer.io.enq(i).bits.vecValid := toSbufferVecValid
1200
1201    }
1202
1203    // Note that store data/addr should both be valid after store's commit
1204    assert(!dataBuffer.io.enq(i).valid || allvalid(ptr) || hasException(ptr) || (allocated(ptr) && vecMbCommit(ptr)) || assert_flag)
1205  }
1206
1207  // Send data stored in sbufferReqBitsReg to sbuffer
1208  for (i <- 0 until EnsbufferWidth) {
1209    io.sbuffer(i).valid := dataBuffer.io.deq(i).valid
1210    dataBuffer.io.deq(i).ready := io.sbuffer(i).ready
1211    io.sbuffer(i).bits := DontCare
1212    io.sbuffer(i).bits.cmd   := MemoryOpConstants.M_XWR
1213    io.sbuffer(i).bits.addr  := dataBuffer.io.deq(i).bits.addr
1214    io.sbuffer(i).bits.vaddr := dataBuffer.io.deq(i).bits.vaddr
1215    io.sbuffer(i).bits.data  := dataBuffer.io.deq(i).bits.data
1216    io.sbuffer(i).bits.mask  := dataBuffer.io.deq(i).bits.mask
1217    io.sbuffer(i).bits.wline := dataBuffer.io.deq(i).bits.wline && dataBuffer.io.deq(i).bits.vecValid
1218    io.sbuffer(i).bits.prefetch := dataBuffer.io.deq(i).bits.prefetch
1219    io.sbuffer(i).bits.vecValid := dataBuffer.io.deq(i).bits.vecValid
1220    io.sbuffer(i).bits.sqNeedDeq := dataBuffer.io.deq(i).bits.sqNeedDeq
1221    // io.sbuffer(i).fire is RegNexted, as sbuffer data write takes 2 cycles.
1222    // Before data write finish, sbuffer is unable to provide store to load
1223    // forward data. As an workaround, deqPtrExt and allocated flag update
1224    // is delayed so that load can get the right data from store queue.
1225    val ptr = dataBuffer.io.deq(i).bits.sqPtr.value
1226    when (RegNext(io.sbuffer(i).fire && io.sbuffer(i).bits.sqNeedDeq)) {
1227      allocated(RegEnable(ptr, io.sbuffer(i).fire)) := false.B
1228      XSDebug("sbuffer "+i+" fire: ptr %d\n", ptr)
1229    }
1230  }
1231
1232  // All vector instruction uop normally dequeue, but the Uop after the exception is raised does not write to the 'sbuffer'.
1233  // Flags are used to record whether there are any exceptions when the queue is displayed.
1234  // This is determined each time a write is made to the 'databuffer', prevent subsequent uop of the same instruction from writing to the 'dataBuffer'.
1235  val vecCommitHasException = (0 until EnsbufferWidth).map{ i =>
1236    val ptr = rdataPtrExt(i).value
1237    val mmioStall = if(i == 0) mmio(rdataPtrExt(0).value) else (mmio(rdataPtrExt(i).value) || mmio(rdataPtrExt(i-1).value))
1238    val ncStall = if(i == 0) nc(rdataPtrExt(0).value) else (nc(rdataPtrExt(i).value) || nc(rdataPtrExt(i-1).value))
1239    val exceptionVliad      = isVec(ptr) && hasException(ptr) && dataBuffer.io.enq(i).fire
1240    (exceptionVliad, uop(ptr), vecLastFlow(ptr))
1241  }
1242
1243  val vecCommitHasExceptionValid      = vecCommitHasException.map(_._1)
1244  val vecCommitHasExceptionUop        = vecCommitHasException.map(_._2)
1245  val vecCommitHasExceptionLastFlow   = vecCommitHasException.map(_._3)
1246  val vecCommitHasExceptionValidOR    = vecCommitHasExceptionValid.reduce(_ || _)
1247  // Just select the last Uop tah has an exception.
1248  val vecCommitHasExceptionSelectUop  = ParallelPosteriorityMux(vecCommitHasExceptionValid, vecCommitHasExceptionUop)
1249  // If the last flow with an exception is the LastFlow of this instruction, the flag is not set.
1250  // compare robidx to select the last flow
1251  require(EnsbufferWidth == 2, "The vector store exception handle process only support EnsbufferWidth == 2 yet.")
1252  val robidxEQ = dataBuffer.io.enq(0).fire && dataBuffer.io.enq(1).fire &&
1253    uop(rdataPtrExt(0).value).robIdx === uop(rdataPtrExt(1).value).robIdx
1254  val robidxNE = dataBuffer.io.enq(0).fire && dataBuffer.io.enq(1).fire && (
1255    uop(rdataPtrExt(0).value).robIdx =/= uop(rdataPtrExt(1).value).robIdx
1256  )
1257  val onlyCommit0 = dataBuffer.io.enq(0).fire && !dataBuffer.io.enq(1).fire
1258
1259  val vecCommitLastFlow =
1260    // robidx equal => check if 1 is last flow
1261    robidxEQ && vecCommitHasExceptionLastFlow(1) ||
1262    // robidx not equal => 0 must be the last flow, just check if 1 is last flow when 1 has exception
1263    robidxNE && (vecCommitHasExceptionValid(1) && vecCommitHasExceptionLastFlow(1) || !vecCommitHasExceptionValid(1)) ||
1264    onlyCommit0 && vecCommitHasExceptionLastFlow(0)
1265
1266
1267  val vecExceptionFlagCancel  = (0 until EnsbufferWidth).map{ i =>
1268    val ptr = rdataPtrExt(i).value
1269    val vecLastFlowCommit = vecLastFlow(ptr) && (uop(ptr).robIdx === vecExceptionFlag.bits.robIdx) && dataBuffer.io.enq(i).fire
1270    vecLastFlowCommit
1271  }.reduce(_ || _)
1272
1273  // When a LastFlow with an exception instruction is commited, clear the flag.
1274  when(!vecExceptionFlag.valid && vecCommitHasExceptionValidOR && !vecCommitLastFlow) {
1275    vecExceptionFlag.valid  := true.B
1276    vecExceptionFlag.bits   := vecCommitHasExceptionSelectUop
1277  }.elsewhen(vecExceptionFlag.valid && vecExceptionFlagCancel) {
1278    vecExceptionFlag.valid  := false.B
1279    vecExceptionFlag.bits   := 0.U.asTypeOf(new DynInst)
1280  }
1281
1282  // A dumb defensive code. The flag should not be placed for a long period of time.
1283  // A relatively large timeout period, not have any special meaning.
1284  // If an assert appears and you confirm that it is not a Bug: Increase the timeout or remove the assert.
1285  TimeOutAssert(vecExceptionFlag.valid, 3000, "vecExceptionFlag timeout, Plase check for bugs or add timeouts.")
1286
1287  // Initialize when unenabled difftest.
1288  for (i <- 0 until EnsbufferWidth) {
1289    io.sbufferVecDifftestInfo(i) := DontCare
1290  }
1291  // Consistent with the logic above.
1292  // Only the vector store difftest required signal is separated from the rtl code.
1293  if (env.EnableDifftest) {
1294    for (i <- 0 until EnsbufferWidth) {
1295      val ptr = dataBuffer.io.enq(i).bits.sqPtr.value
1296      difftestBuffer.get.io.enq(i).valid := dataBuffer.io.enq(i).valid
1297      difftestBuffer.get.io.enq(i).bits := uop(ptr)
1298    }
1299    for (i <- 0 until EnsbufferWidth) {
1300      io.sbufferVecDifftestInfo(i).valid := difftestBuffer.get.io.deq(i).valid
1301      difftestBuffer.get.io.deq(i).ready := io.sbufferVecDifftestInfo(i).ready
1302
1303      io.sbufferVecDifftestInfo(i).bits := difftestBuffer.get.io.deq(i).bits
1304    }
1305
1306    // commit cbo.inval to difftest
1307    val cmoInvalEvent = DifftestModule(new DiffCMOInvalEvent)
1308    cmoInvalEvent.coreid := io.hartId
1309    cmoInvalEvent.valid  := io.mmioStout.fire && deqCanDoCbo && LSUOpType.isCboInval(uop(deqPtr).fuOpType)
1310    cmoInvalEvent.addr   := cboMmioAddr
1311  }
1312
1313  (1 until EnsbufferWidth).foreach(i => when(io.sbuffer(i).fire) { assert(io.sbuffer(i - 1).fire) })
1314  if (coreParams.dcacheParametersOpt.isEmpty) {
1315    for (i <- 0 until EnsbufferWidth) {
1316      val ptr = deqPtrExt(i).value
1317      val ram = DifftestMem(64L * 1024 * 1024 * 1024, 8)
1318      val wen = allocated(ptr) && committed(ptr) && !mmio(ptr)
1319      val waddr = ((paddrModule.io.rdata(i) - "h80000000".U) >> 3).asUInt
1320      val wdata = Mux(paddrModule.io.rdata(i)(3), dataModule.io.rdata(i).data(127, 64), dataModule.io.rdata(i).data(63, 0))
1321      val wmask = Mux(paddrModule.io.rdata(i)(3), dataModule.io.rdata(i).mask(15, 8), dataModule.io.rdata(i).mask(7, 0))
1322      when (wen) {
1323        ram.write(waddr, wdata.asTypeOf(Vec(8, UInt(8.W))), wmask.asBools)
1324      }
1325    }
1326  }
1327
1328  // Read vaddr for mem exception
1329  io.exceptionAddr.vaddr     := exceptionBuffer.io.exceptionAddr.vaddr
1330  io.exceptionAddr.vaNeedExt := exceptionBuffer.io.exceptionAddr.vaNeedExt
1331  io.exceptionAddr.isHyper   := exceptionBuffer.io.exceptionAddr.isHyper
1332  io.exceptionAddr.gpaddr    := exceptionBuffer.io.exceptionAddr.gpaddr
1333  io.exceptionAddr.vstart    := exceptionBuffer.io.exceptionAddr.vstart
1334  io.exceptionAddr.vl        := exceptionBuffer.io.exceptionAddr.vl
1335  io.exceptionAddr.isForVSnonLeafPTE := exceptionBuffer.io.exceptionAddr.isForVSnonLeafPTE
1336
1337  // vector commit or replay from
1338  val vecCommittmp = Wire(Vec(StoreQueueSize, Vec(VecStorePipelineWidth, Bool())))
1339  val vecCommit = Wire(Vec(StoreQueueSize, Bool()))
1340  for (i <- 0 until StoreQueueSize) {
1341    val fbk = io.vecFeedback
1342    for (j <- 0 until VecStorePipelineWidth) {
1343      vecCommittmp(i)(j) := fbk(j).valid && (fbk(j).bits.isCommit || fbk(j).bits.isFlush) &&
1344        uop(i).robIdx === fbk(j).bits.robidx && uop(i).uopIdx === fbk(j).bits.uopidx && allocated(i)
1345    }
1346    vecCommit(i) := vecCommittmp(i).reduce(_ || _)
1347
1348    when (vecCommit(i)) {
1349      vecMbCommit(i) := true.B
1350    }
1351  }
1352
1353  // For vector, when there is a store across pages with the same uop in storeMisalignBuffer, storequeue needs to mark this item as committed.
1354  // TODO FIXME Can vecMbCommit be removed?
1355  when(io.maControl.toStoreQueue.withSameUop && allvalid(rdataPtrExt(0).value)) {
1356    vecMbCommit(rdataPtrExt(0).value) := true.B
1357  }
1358
1359  // misprediction recovery / exception redirect
1360  // invalidate sq term using robIdx
1361  for (i <- 0 until StoreQueueSize) {
1362    needCancel(i) := uop(i).robIdx.needFlush(io.brqRedirect) && allocated(i) && !committed(i) &&
1363      (!isVec(i) || !(uop(i).robIdx === io.brqRedirect.bits.robIdx))
1364    when (needCancel(i)) {
1365      allocated(i) := false.B
1366    }
1367  }
1368
1369 /**
1370* update pointers
1371**/
1372  val enqCancelValid = canEnqueue.zip(io.enq.req).map{case (v , x) =>
1373    v && x.bits.robIdx.needFlush(io.brqRedirect)
1374  }
1375  val enqCancelNum = enqCancelValid.zip(io.enq.req).map{case (v, req) =>
1376    Mux(v, req.bits.numLsElem, 0.U)
1377  }
1378  val lastEnqCancel = RegEnable(enqCancelNum.reduce(_ + _), io.brqRedirect.valid) // 1 cycle after redirect
1379
1380  val lastCycleCancelCount = PopCount(RegEnable(needCancel, io.brqRedirect.valid)) // 1 cycle after redirect
1381  val lastCycleRedirect = RegNext(io.brqRedirect.valid) // 1 cycle after redirect
1382  val enqNumber = validVStoreFlow.reduce(_ + _)
1383
1384  val lastlastCycleRedirect=RegNext(lastCycleRedirect)// 2 cycle after redirect
1385  val redirectCancelCount = RegEnable(lastCycleCancelCount + lastEnqCancel, 0.U, lastCycleRedirect) // 2 cycle after redirect
1386
1387  when (lastlastCycleRedirect) {
1388    // we recover the pointers in 2 cycle after redirect for better timing
1389    enqPtrExt := VecInit(enqPtrExt.map(_ - redirectCancelCount))
1390  }.otherwise {
1391    // lastCycleRedirect.valid or nornal case
1392    // when lastCycleRedirect.valid, enqNumber === 0.U, enqPtrExt will not change
1393    enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber))
1394  }
1395  assert(!(lastCycleRedirect && enqNumber =/= 0.U))
1396
1397  deqPtrExt := deqPtrExtNext
1398  rdataPtrExt := rdataPtrExtNext
1399
1400  // val dequeueCount = Mux(io.sbuffer(1).fire, 2.U, Mux(io.sbuffer(0).fire || io.mmioStout.fire, 1.U, 0.U))
1401
1402  // If redirect at T0, sqCancelCnt is at T2
1403  io.sqCancelCnt := redirectCancelCount
1404  val ForceWriteUpper = Wire(UInt(log2Up(StoreQueueSize + 1).W))
1405  ForceWriteUpper := Constantin.createRecord(s"ForceWriteUpper_${p(XSCoreParamsKey).HartId}", initValue = 60)
1406  val ForceWriteLower = Wire(UInt(log2Up(StoreQueueSize + 1).W))
1407  ForceWriteLower := Constantin.createRecord(s"ForceWriteLower_${p(XSCoreParamsKey).HartId}", initValue = 55)
1408
1409  val valid_cnt = PopCount(allocated)
1410  io.force_write := RegNext(Mux(valid_cnt >= ForceWriteUpper, true.B, valid_cnt >= ForceWriteLower && io.force_write), init = false.B)
1411
1412  // io.sqempty will be used by sbuffer
1413  // We delay it for 1 cycle for better timing
1414  // When sbuffer need to check if it is empty, the pipeline is blocked, which means delay io.sqempty
1415  // for 1 cycle will also promise that sq is empty in that cycle
1416  io.sqEmpty := RegNext(
1417    enqPtrExt(0).value === deqPtrExt(0).value &&
1418    enqPtrExt(0).flag === deqPtrExt(0).flag
1419  )
1420  // perf counter
1421  QueuePerf(StoreQueueSize, validCount, !allowEnqueue)
1422  val vecValidVec = WireInit(VecInit((0 until StoreQueueSize).map(i => allocated(i) && isVec(i))))
1423  QueuePerf(StoreQueueSize, PopCount(vecValidVec), !allowEnqueue)
1424  io.sqFull := !allowEnqueue
1425  XSPerfAccumulate("mmioCycle", mmioState =/= s_idle) // lq is busy dealing with uncache req
1426  XSPerfAccumulate("mmioCnt", mmioDoReq)
1427  XSPerfAccumulate("mmio_wb_success", io.mmioStout.fire || io.vecmmioStout.fire)
1428  XSPerfAccumulate("mmio_wb_blocked", (io.mmioStout.valid && !io.mmioStout.ready) || (io.vecmmioStout.valid && !io.vecmmioStout.ready))
1429  XSPerfAccumulate("validEntryCnt", distanceBetween(enqPtrExt(0), deqPtrExt(0)))
1430  XSPerfAccumulate("cmtEntryCnt", distanceBetween(cmtPtrExt(0), deqPtrExt(0)))
1431  XSPerfAccumulate("nCmtEntryCnt", distanceBetween(enqPtrExt(0), cmtPtrExt(0)))
1432
1433  val perfValidCount = distanceBetween(enqPtrExt(0), deqPtrExt(0))
1434  val perfEvents = Seq(
1435    ("mmioCycle      ", mmioState =/= s_idle),
1436    ("mmioCnt        ", mmioDoReq),
1437    ("mmio_wb_success", io.mmioStout.fire || io.vecmmioStout.fire),
1438    ("mmio_wb_blocked", (io.mmioStout.valid && !io.mmioStout.ready) || (io.vecmmioStout.valid && !io.vecmmioStout.ready)),
1439    ("stq_1_4_valid  ", (perfValidCount < (StoreQueueSize.U/4.U))),
1440    ("stq_2_4_valid  ", (perfValidCount > (StoreQueueSize.U/4.U)) & (perfValidCount <= (StoreQueueSize.U/2.U))),
1441    ("stq_3_4_valid  ", (perfValidCount > (StoreQueueSize.U/2.U)) & (perfValidCount <= (StoreQueueSize.U*3.U/4.U))),
1442    ("stq_4_4_valid  ", (perfValidCount > (StoreQueueSize.U*3.U/4.U))),
1443  )
1444  generatePerfEvent()
1445
1446  // debug info
1447  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt(0).flag, deqPtr)
1448
1449  def PrintFlag(flag: Bool, name: String): Unit = {
1450    when(flag) {
1451      XSDebug(false, true.B, name)
1452    }.otherwise {
1453      XSDebug(false, true.B, " ")
1454    }
1455  }
1456
1457  for (i <- 0 until StoreQueueSize) {
1458    XSDebug(s"$i: pc %x va %x pa %x data %x ",
1459      uop(i).pc,
1460      debug_vaddr(i),
1461      debug_paddr(i),
1462      debug_data(i)
1463    )
1464    PrintFlag(allocated(i), "a")
1465    PrintFlag(allocated(i) && addrvalid(i), "a")
1466    PrintFlag(allocated(i) && datavalid(i), "d")
1467    PrintFlag(allocated(i) && committed(i), "c")
1468    PrintFlag(allocated(i) && pending(i), "p")
1469    PrintFlag(allocated(i) && mmio(i), "m")
1470    XSDebug(false, true.B, "\n")
1471  }
1472
1473}
1474