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