xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/StoreQueue.scala (revision ebb914e7007fa76b83a869685cc5c3efe1f867e9)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3* Copyright (c) 2020-2021 Peng Cheng Laboratory
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package xiangshan.mem
18
19import chisel3._
20import chisel3.util._
21import difftest._
22import difftest.common.DifftestMem
23import org.chipsalliance.cde.config.Parameters
24import utility._
25import utils._
26import xiangshan._
27import xiangshan.cache._
28import xiangshan.cache.{DCacheLineIO, DCacheWordIO, MemoryOpConstants}
29import xiangshan.backend._
30import xiangshan.backend.rob.{RobLsqIO, RobPtr}
31import xiangshan.backend.Bundles.{DynInst, MemExuOutput}
32import xiangshan.backend.decode.isa.bitfield.{Riscv32BitInst, XSInstBitFields}
33import xiangshan.backend.fu.FuConfig._
34
35class SqPtr(implicit p: Parameters) extends CircularQueuePtr[SqPtr](
36  p => p(XSCoreParamsKey).StoreQueueSize
37){
38}
39
40object SqPtr {
41  def apply(f: Bool, v: UInt)(implicit p: Parameters): SqPtr = {
42    val ptr = Wire(new SqPtr)
43    ptr.flag := f
44    ptr.value := v
45    ptr
46  }
47}
48
49class SqEnqIO(implicit p: Parameters) extends MemBlockBundle {
50  val canAccept = Output(Bool())
51  val lqCanAccept = Input(Bool())
52  val needAlloc = Vec(LSQEnqWidth, Input(Bool()))
53  val req = Vec(LSQEnqWidth, Flipped(ValidIO(new DynInst)))
54  val resp = Vec(LSQEnqWidth, Output(new SqPtr))
55}
56
57class DataBufferEntry (implicit p: Parameters)  extends DCacheBundle {
58  val addr   = UInt(PAddrBits.W)
59  val vaddr  = UInt(VAddrBits.W)
60  val data   = UInt(VLEN.W)
61  val mask   = UInt((VLEN/8).W)
62  val wline = Bool()
63  val sqPtr  = new SqPtr
64  val prefetch = Bool()
65  val vec_mbCommit = Bool()
66}
67
68class StoreExceptionBuffer(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
69  val io = IO(new Bundle() {
70    val redirect = Flipped(ValidIO(new Redirect))
71    val storeAddrIn = Vec(StorePipelineWidth + 1, Flipped(ValidIO(new LsPipelineBundle())))
72    val exceptionAddr = new ExceptionAddrIO
73  })
74
75  val req_valid = RegInit(false.B)
76  val req = Reg(new LsPipelineBundle())
77
78  // enqueue
79  // S1:
80  val s1_req = VecInit(io.storeAddrIn.map(_.bits))
81  val s1_valid = VecInit(io.storeAddrIn.map(_.valid))
82
83  // S2: delay 1 cycle
84  val s2_req = RegNext(s1_req)
85  val s2_valid = (0 until StorePipelineWidth + 1).map(i =>
86    RegNext(s1_valid(i)) &&
87      !s2_req(i).uop.robIdx.needFlush(RegNext(io.redirect)) &&
88      !s2_req(i).uop.robIdx.needFlush(io.redirect)
89  )
90  val s2_has_exception = s2_req.map(x => ExceptionNO.selectByFu(x.uop.exceptionVec, StaCfg).asUInt.orR)
91
92  val s2_enqueue = Wire(Vec(StorePipelineWidth + 1, Bool()))
93  for (w <- 0 until StorePipelineWidth + 1) {
94    s2_enqueue(w) := s2_valid(w) && s2_has_exception(w)
95  }
96
97  when (req_valid && req.uop.robIdx.needFlush(io.redirect)) {
98    req_valid := s2_enqueue.asUInt.orR
99  }.elsewhen (s2_enqueue.asUInt.orR) {
100    req_valid := req_valid || true.B
101  }
102
103  def selectOldest[T <: LsPipelineBundle](valid: Seq[Bool], bits: Seq[T]): (Seq[Bool], Seq[T]) = {
104    assert(valid.length == bits.length)
105    if (valid.length == 0 || valid.length == 1) {
106      (valid, bits)
107    } else if (valid.length == 2) {
108      val res = Seq.fill(2)(Wire(Valid(chiselTypeOf(bits(0)))))
109      for (i <- res.indices) {
110        res(i).valid := valid(i)
111        res(i).bits := bits(i)
112      }
113      val oldest = Mux(valid(0) && valid(1),
114        Mux(isAfter(bits(0).uop.robIdx, bits(1).uop.robIdx) ||
115          (isNotBefore(bits(0).uop.robIdx, bits(1).uop.robIdx) && bits(0).uop.uopIdx > bits(1).uop.uopIdx), res(1), res(0)),
116        Mux(valid(0) && !valid(1), res(0), res(1)))
117      (Seq(oldest.valid), Seq(oldest.bits))
118    } else {
119      val left = selectOldest(valid.take(valid.length / 2), bits.take(bits.length / 2))
120      val right = selectOldest(valid.takeRight(valid.length - (valid.length / 2)), bits.takeRight(bits.length - (bits.length / 2)))
121      selectOldest(left._1 ++ right._1, left._2 ++ right._2)
122    }
123  }
124
125  val reqSel = selectOldest(s2_enqueue, s2_req)
126
127  when (req_valid) {
128    req := Mux(reqSel._1(0) && isAfter(req.uop.robIdx, reqSel._2(0).uop.robIdx) ||
129      (isNotBefore(req.uop.robIdx, reqSel._2(0).uop.robIdx) && req.uop.uopIdx > reqSel._2(0).uop.uopIdx), reqSel._2(0), req)
130  } .elsewhen (s2_enqueue.asUInt.orR) {
131    req := reqSel._2(0)
132  }
133
134  io.exceptionAddr.vaddr := req.vaddr
135}
136
137// Store Queue
138class StoreQueue(implicit p: Parameters) extends XSModule
139  with HasDCacheParameters
140  with HasCircularQueuePtrHelper
141  with HasPerfEvents
142  with HasVLSUParameters {
143  val io = IO(new Bundle() {
144    val hartId = Input(UInt(8.W))
145    val enq = new SqEnqIO
146    val brqRedirect = Flipped(ValidIO(new Redirect))
147    val vecFeedback = Flipped(ValidIO(new FeedbackToLsqIO))
148    val storeAddrIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle))) // store addr, data is not included
149    val storeAddrInRe = Vec(StorePipelineWidth, Input(new LsPipelineBundle())) // store more mmio and exception
150    val storeDataIn = Vec(StorePipelineWidth, Flipped(Valid(new MemExuOutput(isVector = true)))) // store data, send to sq from rs
151    val storeMaskIn = Vec(StorePipelineWidth, Flipped(Valid(new StoreMaskBundle))) // store mask, send to sq from rs
152    val sbuffer = Vec(EnsbufferWidth, Decoupled(new DCacheWordReqWithVaddrAndPfFlag)) // write committed store to sbuffer
153    val uncacheOutstanding = Input(Bool())
154    val mmioStout = DecoupledIO(new MemExuOutput) // writeback uncached store
155    val vecmmioStout = DecoupledIO(new MemExuOutput(isVector = true))
156    val forward = Vec(LoadPipelineWidth, Flipped(new PipeLoadForwardQueryIO))
157    // TODO: scommit is only for scalar store
158    val rob = Flipped(new RobLsqIO)
159    val uncache = new UncacheWordIO
160    // val refill = Flipped(Valid(new DCacheLineReq ))
161    val exceptionAddr = new ExceptionAddrIO
162    val sqEmpty = Output(Bool())
163    val stAddrReadySqPtr = Output(new SqPtr)
164    val stAddrReadyVec = Output(Vec(StoreQueueSize, Bool()))
165    val stDataReadySqPtr = Output(new SqPtr)
166    val stDataReadyVec = Output(Vec(StoreQueueSize, Bool()))
167    val stIssuePtr = Output(new SqPtr)
168    val sqDeqPtr = Output(new SqPtr)
169    val sqFull = Output(Bool())
170    val sqCancelCnt = Output(UInt(log2Up(StoreQueueSize + 1).W))
171    val sqDeq = Output(UInt(log2Ceil(EnsbufferWidth + 1).W))
172    val force_write = Output(Bool())
173  })
174
175  println("StoreQueue: size:" + StoreQueueSize)
176
177  // data modules
178  val uop = Reg(Vec(StoreQueueSize, new DynInst))
179  // val data = Reg(Vec(StoreQueueSize, new LsqEntry))
180  val dataModule = Module(new SQDataModule(
181    numEntries = StoreQueueSize,
182    numRead = EnsbufferWidth,
183    numWrite = StorePipelineWidth,
184    numForward = LoadPipelineWidth
185  ))
186  dataModule.io := DontCare
187  val paddrModule = Module(new SQAddrModule(
188    dataWidth = PAddrBits,
189    numEntries = StoreQueueSize,
190    numRead = EnsbufferWidth,
191    numWrite = StorePipelineWidth,
192    numForward = LoadPipelineWidth
193  ))
194  paddrModule.io := DontCare
195  val vaddrModule = Module(new SQAddrModule(
196    dataWidth = VAddrBits,
197    numEntries = StoreQueueSize,
198    numRead = EnsbufferWidth, // sbuffer; badvaddr will be sent from exceptionBuffer
199    numWrite = StorePipelineWidth,
200    numForward = LoadPipelineWidth
201  ))
202  vaddrModule.io := DontCare
203  val dataBuffer = Module(new DatamoduleResultBuffer(new DataBufferEntry))
204  val exceptionBuffer = Module(new StoreExceptionBuffer)
205  exceptionBuffer.io.redirect := io.brqRedirect
206  exceptionBuffer.io.exceptionAddr.isStore := DontCare
207  // TODO: implement it!
208  exceptionBuffer.io.storeAddrIn(StorePipelineWidth) := DontCare
209
210  val debug_paddr = Reg(Vec(StoreQueueSize, UInt((PAddrBits).W)))
211  val debug_vaddr = Reg(Vec(StoreQueueSize, UInt((VAddrBits).W)))
212  val debug_data = Reg(Vec(StoreQueueSize, UInt((XLEN).W)))
213
214  // state & misc
215  val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated
216  val addrvalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio addr is valid
217  val datavalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio data is valid
218  val allvalid  = VecInit((0 until StoreQueueSize).map(i => addrvalid(i) && datavalid(i))) // non-mmio data & addr is valid
219  val committed = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // inst has been committed by rob
220  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
221  val mmio = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // mmio: inst is an mmio inst
222  val atomic = RegInit(VecInit(List.fill(StoreQueueSize)(false.B)))
223  val prefetch = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // need prefetch when committing this store to sbuffer?
224  val is_vec = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // vector store instruction
225  //val vec_lastuop = Reg(Vec(StoreQueueSize, Bool())) // last uop of vector store instruction
226  val vec_mbCommit = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // vector store committed from merge buffer to rob
227  // val vec_robCommit = Reg(Vec(StoreQueueSize, Bool())) // vector store committed by rob
228  val vec_secondInv = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // Vector unit-stride, second entry is invalid
229
230  // ptr
231  val enqPtrExt = RegInit(VecInit((0 until io.enq.req.length).map(_.U.asTypeOf(new SqPtr))))
232  val rdataPtrExt = RegInit(VecInit((0 until EnsbufferWidth).map(_.U.asTypeOf(new SqPtr))))
233  val deqPtrExt = RegInit(VecInit((0 until EnsbufferWidth).map(_.U.asTypeOf(new SqPtr))))
234  val cmtPtrExt = RegInit(VecInit((0 until CommitWidth).map(_.U.asTypeOf(new SqPtr))))
235  val addrReadyPtrExt = RegInit(0.U.asTypeOf(new SqPtr))
236  val dataReadyPtrExt = RegInit(0.U.asTypeOf(new SqPtr))
237
238  val enqPtr = enqPtrExt(0).value
239  val deqPtr = deqPtrExt(0).value
240  val cmtPtr = cmtPtrExt(0).value
241
242  val validCount = distanceBetween(enqPtrExt(0), deqPtrExt(0))
243  val allowEnqueue = validCount <= (StoreQueueSize - LSQStEnqWidth).U
244
245  val deqMask = UIntToMask(deqPtr, StoreQueueSize)
246  val enqMask = UIntToMask(enqPtr, StoreQueueSize)
247
248  // TODO: count commit numbers for scalar / vector store separately
249  val scalarCommitCount = RegInit(0.U(log2Ceil(StoreQueueSize + 1).W))
250  val scalarCommitted = WireInit(0.U(log2Ceil(CommitWidth + 1).W))
251  val vecCommitted = WireInit(0.U(log2Ceil(CommitWidth + 1).W))
252  val commitCount = WireInit(0.U(log2Ceil(CommitWidth + 1).W))
253
254  scalarCommitCount := scalarCommitCount + RegNext(io.rob.scommit) - scalarCommitted
255
256  // store can be committed by ROB
257  io.rob.mmio := DontCare
258  io.rob.uop := DontCare
259
260  // Read dataModule
261  assert(EnsbufferWidth <= 2)
262  // rdataPtrExtNext and rdataPtrExtNext+1 entry will be read from dataModule
263  val rdataPtrExtNext = WireInit(Mux(dataBuffer.io.enq(1).fire,
264    VecInit(rdataPtrExt.map(_ + 2.U)),
265    Mux(dataBuffer.io.enq(0).fire || io.mmioStout.fire || io.vecmmioStout.fire,
266      VecInit(rdataPtrExt.map(_ + 1.U)),
267      rdataPtrExt
268    )
269  ))
270
271  // deqPtrExtNext traces which inst is about to leave store queue
272  //
273  // io.sbuffer(i).fire is RegNexted, as sbuffer data write takes 2 cycles.
274  // Before data write finish, sbuffer is unable to provide store to load
275  // forward data. As an workaround, deqPtrExt and allocated flag update
276  // is delayed so that load can get the right data from store queue.
277  //
278  // Modify deqPtrExtNext and io.sqDeq with care!
279  val sbuffer_Inv = RegInit(VecInit(List.fill(EnsbufferWidth)(false.B)))
280  val deqPtrExtNext = Mux(RegNext(io.sbuffer(1).fire || sbuffer_Inv(1)),
281    VecInit(deqPtrExt.map(_ + 2.U)),
282    Mux((RegNext(io.sbuffer(0).fire) || sbuffer_Inv(0)) || io.mmioStout.fire || io.vecmmioStout.fire,
283      VecInit(deqPtrExt.map(_ + 1.U)),
284      deqPtrExt
285    )
286  )
287  io.sqDeq := RegNext(Mux(RegNext(io.sbuffer(1).fire) || sbuffer_Inv(1), 2.U,
288    Mux((RegNext(io.sbuffer(0).fire) || sbuffer_Inv(0)) || io.mmioStout.fire || io.vecmmioStout.fire, 1.U, 0.U)
289  ))
290  assert(!RegNext(RegNext(io.sbuffer(0).fire) && (io.mmioStout.fire || io.vecmmioStout.fire)))
291
292  for (i <- 0 until EnsbufferWidth) {
293    dataModule.io.raddr(i) := rdataPtrExtNext(i).value
294    paddrModule.io.raddr(i) := rdataPtrExtNext(i).value
295    vaddrModule.io.raddr(i) := rdataPtrExtNext(i).value
296  }
297
298  /**
299    * Enqueue at dispatch
300    *
301    * Currently, StoreQueue only allows enqueue when #emptyEntries > EnqWidth
302    */
303  io.enq.canAccept := allowEnqueue
304  val canEnqueue = io.enq.req.map(_.valid)
305  val enqCancel = io.enq.req.map(_.bits.robIdx.needFlush(io.brqRedirect))
306  val vStoreFlow = io.enq.req.map(_.bits.numLsElem)
307  val validVStoreFlow = vStoreFlow.zipWithIndex.map{case (vLoadFlowNum_Item, index) => Mux(!RegNext(io.brqRedirect.valid) && io.enq.canAccept && io.enq.lqCanAccept && canEnqueue(index), vLoadFlowNum_Item, 0.U)}
308  val validVStoreOffset = 0.U +: vStoreFlow.zip(io.enq.needAlloc).map{case (flow, needAlloc_Item) => Mux(needAlloc_Item, flow, 0.U)}
309  val validVStoreOffsetRShift = 0.U +: validVStoreOffset.take(vStoreFlow.length - 1)
310
311  for (i <- 0 until io.enq.req.length) {
312    val sqIdx = enqPtrExt(0) + validVStoreOffsetRShift.take(i + 1).reduce(_ + _)
313    val index = io.enq.req(i).bits.sqIdx.value
314    val enqInstr = io.enq.req(i).bits.instr.asTypeOf(new XSInstBitFields)
315    when (canEnqueue(i) && !enqCancel(i)) {
316      for (j <- 0 until VecMemDispatchMaxNumber) {
317        when (j.U < validVStoreOffset(i)) {
318          uop(index + j.U) := io.enq.req(i).bits
319          // NOTE: the index will be used when replay
320          uop(index + j.U).sqIdx := sqIdx + j.U
321          allocated(index + j.U) := true.B
322          datavalid(index + j.U) := false.B
323          addrvalid(index + j.U) := false.B
324          committed(index + j.U) := false.B
325          pending(index + j.U) := false.B
326          prefetch(index + j.U) := false.B
327          mmio(index + j.U) := false.B
328          is_vec(index + j.U) := enqInstr.isVecStore // check vector store by the encoding of inst
329          XSError(!io.enq.canAccept || !io.enq.lqCanAccept, s"must accept $i\n")
330          XSError(index =/= sqIdx.value, s"must be the same entry $i\n")
331        }
332      }
333    }
334    io.enq.resp(i) := sqIdx
335  }
336  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
337
338  /**
339    * Update addr/dataReadyPtr when issue from rs
340    */
341  // update issuePtr
342  val IssuePtrMoveStride = 4
343  require(IssuePtrMoveStride >= 2)
344
345  val addrReadyLookupVec = (0 until IssuePtrMoveStride).map(addrReadyPtrExt + _.U)
346  val addrReadyLookup = addrReadyLookupVec.map(ptr => allocated(ptr.value) && (mmio(ptr.value) || addrvalid(ptr.value) || vec_secondInv(ptr.value))
347    && ptr =/= enqPtrExt(0))
348  val nextAddrReadyPtr = addrReadyPtrExt + PriorityEncoder(VecInit(addrReadyLookup.map(!_) :+ true.B))
349  addrReadyPtrExt := nextAddrReadyPtr
350
351  (0 until StoreQueueSize).map(i => {
352    io.stAddrReadyVec(i) := RegNext(allocated(i) && (mmio(i) || addrvalid(i) || vec_secondInv(i)))
353  })
354
355  when (io.brqRedirect.valid) {
356    addrReadyPtrExt := Mux(
357      isAfter(cmtPtrExt(0), deqPtrExt(0)),
358      cmtPtrExt(0),
359      deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr
360    )
361  }
362
363  io.stAddrReadySqPtr := addrReadyPtrExt
364
365  // update
366  val dataReadyLookupVec = (0 until IssuePtrMoveStride).map(dataReadyPtrExt + _.U)
367  val dataReadyLookup = dataReadyLookupVec.map(ptr => allocated(ptr.value) && (mmio(ptr.value) || datavalid(ptr.value) || vec_secondInv(ptr.value))
368    && ptr =/= enqPtrExt(0))
369  val nextDataReadyPtr = dataReadyPtrExt + PriorityEncoder(VecInit(dataReadyLookup.map(!_) :+ true.B))
370  dataReadyPtrExt := nextDataReadyPtr
371
372  (0 until StoreQueueSize).map(i => {
373    io.stDataReadyVec(i) := RegNext(allocated(i) && (mmio(i) || datavalid(i) || vec_secondInv(i)))
374  })
375
376  when (io.brqRedirect.valid) {
377    dataReadyPtrExt := Mux(
378      isAfter(cmtPtrExt(0), deqPtrExt(0)),
379      cmtPtrExt(0),
380      deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr
381    )
382  }
383
384  io.stDataReadySqPtr := dataReadyPtrExt
385  io.stIssuePtr := enqPtrExt(0)
386  io.sqDeqPtr := deqPtrExt(0)
387
388  /**
389    * Writeback store from store units
390    *
391    * Most store instructions writeback to regfile in the previous cycle.
392    * However,
393    *   (1) For an mmio instruction with exceptions, we need to mark it as addrvalid
394    * (in this way it will trigger an exception when it reaches ROB's head)
395    * instead of pending to avoid sending them to lower level.
396    *   (2) For an mmio instruction without exceptions, we mark it as pending.
397    * When the instruction reaches ROB's head, StoreQueue sends it to uncache channel.
398    * Upon receiving the response, StoreQueue writes back the instruction
399    * through arbiter with store units. It will later commit as normal.
400    */
401
402  // Write addr to sq
403  for (i <- 0 until StorePipelineWidth) {
404    paddrModule.io.wen(i) := false.B
405    vaddrModule.io.wen(i) := false.B
406    dataModule.io.mask.wen(i) := false.B
407    val stWbIndex = io.storeAddrIn(i).bits.uop.sqIdx.value
408    exceptionBuffer.io.storeAddrIn(i).valid := io.storeAddrIn(i).fire && !io.storeAddrIn(i).bits.isvec
409    exceptionBuffer.io.storeAddrIn(i).bits := io.storeAddrIn(i).bits
410
411    when (io.storeAddrIn(i).fire) {
412      val addr_valid = !io.storeAddrIn(i).bits.miss
413      addrvalid(stWbIndex) := addr_valid //!io.storeAddrIn(i).bits.mmio
414      // pending(stWbIndex) := io.storeAddrIn(i).bits.mmio
415
416      paddrModule.io.waddr(i) := stWbIndex
417      paddrModule.io.wdata(i) := io.storeAddrIn(i).bits.paddr
418      paddrModule.io.wmask(i) := io.storeAddrIn(i).bits.mask
419      paddrModule.io.wlineflag(i) := io.storeAddrIn(i).bits.wlineflag
420      paddrModule.io.wen(i) := true.B
421
422      vaddrModule.io.waddr(i) := stWbIndex
423      vaddrModule.io.wdata(i) := io.storeAddrIn(i).bits.vaddr
424      vaddrModule.io.wmask(i) := io.storeAddrIn(i).bits.mask
425      vaddrModule.io.wlineflag(i) := io.storeAddrIn(i).bits.wlineflag
426      vaddrModule.io.wen(i) := true.B
427
428      debug_paddr(paddrModule.io.waddr(i)) := paddrModule.io.wdata(i)
429
430      // mmio(stWbIndex) := io.storeAddrIn(i).bits.mmio
431
432      uop(stWbIndex) := io.storeAddrIn(i).bits.uop
433      uop(stWbIndex).debugInfo := io.storeAddrIn(i).bits.uop.debugInfo
434
435      when (io.storeAddrIn(i).bits.usSecondInv) {
436        vec_secondInv(stWbIndex + 1.U) := true.B
437        // For vec commit or flush
438        uop(stWbIndex + 1.U).robIdx := uop(stWbIndex).robIdx
439        uop(stWbIndex + 1.U).uopIdx := uop(stWbIndex).uopIdx
440      }
441
442      XSInfo("store addr write to sq idx %d pc 0x%x miss:%d vaddr %x paddr %x mmio %x isvec %x vec_secondInv %x\n",
443        io.storeAddrIn(i).bits.uop.sqIdx.value,
444        io.storeAddrIn(i).bits.uop.pc,
445        io.storeAddrIn(i).bits.miss,
446        io.storeAddrIn(i).bits.vaddr,
447        io.storeAddrIn(i).bits.paddr,
448        io.storeAddrIn(i).bits.mmio,
449        io.storeAddrIn(i).bits.isvec,
450        io.storeAddrIn(i).bits.usSecondInv
451      )
452    }
453
454    // re-replinish mmio, for pma/pmp will get mmio one cycle later
455    val storeAddrInFireReg = RegNext(io.storeAddrIn(i).fire && !io.storeAddrIn(i).bits.miss)
456    val stWbIndexReg = RegNext(stWbIndex)
457    when (storeAddrInFireReg) {
458      pending(stWbIndexReg) := io.storeAddrInRe(i).mmio
459      mmio(stWbIndexReg) := io.storeAddrInRe(i).mmio
460      atomic(stWbIndexReg) := io.storeAddrInRe(i).atomic
461    }
462    // dcache miss info (one cycle later than storeIn)
463    // if dcache report a miss in sta pipeline, this store will trigger a prefetch when committing to sbuffer (if EnableAtCommitMissTrigger)
464    when (storeAddrInFireReg) {
465      prefetch(stWbIndexReg) := io.storeAddrInRe(i).miss
466    }
467
468    when(vaddrModule.io.wen(i)){
469      debug_vaddr(vaddrModule.io.waddr(i)) := vaddrModule.io.wdata(i)
470    }
471  }
472
473  // Write data to sq
474  // Now store data pipeline is actually 2 stages
475  for (i <- 0 until StorePipelineWidth) {
476    dataModule.io.data.wen(i) := false.B
477    val stWbIndex = io.storeDataIn(i).bits.uop.sqIdx.value
478    // sq data write takes 2 cycles:
479    // sq data write s0
480    when (io.storeDataIn(i).fire) {
481      // send data write req to data module
482      dataModule.io.data.waddr(i) := stWbIndex
483      dataModule.io.data.wdata(i) := Mux(io.storeDataIn(i).bits.uop.fuOpType === LSUOpType.cbo_zero,
484        0.U,
485        genVWdata(io.storeDataIn(i).bits.data, io.storeDataIn(i).bits.uop.fuOpType(2,0))
486      )
487      dataModule.io.data.wen(i) := true.B
488
489      debug_data(dataModule.io.data.waddr(i)) := dataModule.io.data.wdata(i)
490
491      XSInfo("store data write to sq idx %d pc 0x%x data %x -> %x\n",
492        io.storeDataIn(i).bits.uop.sqIdx.value,
493        io.storeDataIn(i).bits.uop.pc,
494        io.storeDataIn(i).bits.data,
495        dataModule.io.data.wdata(i)
496      )
497    }
498    // sq data write s1
499    when (
500      RegNext(io.storeDataIn(i).fire)
501      // && !RegNext(io.storeDataIn(i).bits.uop).robIdx.needFlush(io.brqRedirect)
502    ) {
503      datavalid(RegNext(stWbIndex)) := true.B
504    }
505  }
506
507  // Write mask to sq
508  for (i <- 0 until StorePipelineWidth) {
509    // sq mask write s0
510    when (io.storeMaskIn(i).fire) {
511      // send data write req to data module
512      dataModule.io.mask.waddr(i) := io.storeMaskIn(i).bits.sqIdx.value
513      dataModule.io.mask.wdata(i) := io.storeMaskIn(i).bits.mask
514      dataModule.io.mask.wen(i) := true.B
515    }
516  }
517
518  /**
519    * load forward query
520    *
521    * Check store queue for instructions that is older than the load.
522    * The response will be valid at the next cycle after req.
523    */
524  // check over all lq entries and forward data from the first matched store
525  for (i <- 0 until LoadPipelineWidth) {
526    // Compare deqPtr (deqPtr) and forward.sqIdx, we have two cases:
527    // (1) if they have the same flag, we need to check range(tail, sqIdx)
528    // (2) if they have different flags, we need to check range(tail, VirtualLoadQueueSize) and range(0, sqIdx)
529    // Forward1: Mux(same_flag, range(tail, sqIdx), range(tail, VirtualLoadQueueSize))
530    // Forward2: Mux(same_flag, 0.U,                   range(0, sqIdx)    )
531    // i.e. forward1 is the target entries with the same flag bits and forward2 otherwise
532    val differentFlag = deqPtrExt(0).flag =/= io.forward(i).sqIdx.flag
533    val forwardMask = io.forward(i).sqIdxMask
534    // all addrvalid terms need to be checked
535    // Real Vaild: all scalar stores, and vector store with (!inactive && !secondInvalid)
536    val addrRealValidVec = WireInit(VecInit((0 until StoreQueueSize).map(j => addrvalid(j) && allocated(j))))
537    // vector store will consider all inactive || secondInvalid flows as valid
538    val addrValidVec = WireInit(VecInit((0 until StoreQueueSize).map(j => (addrvalid(j) || vec_secondInv(j) || vec_mbCommit(j)) && allocated(j))))
539    val dataValidVec = WireInit(VecInit((0 until StoreQueueSize).map(j => datavalid(j) || vec_secondInv(j) || vec_mbCommit(j))))
540    val allValidVec  = WireInit(VecInit((0 until StoreQueueSize).map(j => ((addrvalid(j) && datavalid(j)) || vec_secondInv(j) || vec_mbCommit(j)) && allocated(j))))
541
542    val lfstEnable = Constantin.createRecord("LFSTEnable", LFSTEnable.B).orR
543    val storeSetHitVec = Mux(lfstEnable,
544      WireInit(VecInit((0 until StoreQueueSize).map(j => io.forward(i).uop.loadWaitBit && uop(j).robIdx === io.forward(i).uop.waitForRobIdx))),
545      WireInit(VecInit((0 until StoreQueueSize).map(j => uop(j).storeSetHit && uop(j).ssid === io.forward(i).uop.ssid)))
546    )
547
548    val forwardMask1 = Mux(differentFlag, ~deqMask, deqMask ^ forwardMask)
549    val forwardMask2 = Mux(differentFlag, forwardMask, 0.U(StoreQueueSize.W))
550    val canForward1 = forwardMask1 & allValidVec.asUInt
551    val canForward2 = forwardMask2 & allValidVec.asUInt
552    val needForward = Mux(differentFlag, ~deqMask | forwardMask, deqMask ^ forwardMask)
553
554    XSDebug(p"$i f1 ${Binary(canForward1)} f2 ${Binary(canForward2)} " +
555      p"sqIdx ${io.forward(i).sqIdx} pa ${Hexadecimal(io.forward(i).paddr)}\n"
556    )
557
558    // do real fwd query (cam lookup in load_s1)
559    dataModule.io.needForward(i)(0) := canForward1 & vaddrModule.io.forwardMmask(i).asUInt
560    dataModule.io.needForward(i)(1) := canForward2 & vaddrModule.io.forwardMmask(i).asUInt
561
562    vaddrModule.io.forwardMdata(i) := io.forward(i).vaddr
563    vaddrModule.io.forwardDataMask(i) := io.forward(i).mask
564    paddrModule.io.forwardMdata(i) := io.forward(i).paddr
565    paddrModule.io.forwardDataMask(i) := io.forward(i).mask
566
567
568    // vaddr cam result does not equal to paddr cam result
569    // replay needed
570    // val vpmaskNotEqual = ((paddrModule.io.forwardMmask(i).asUInt ^ vaddrModule.io.forwardMmask(i).asUInt) & needForward) =/= 0.U
571    // val vaddrMatchFailed = vpmaskNotEqual && io.forward(i).valid
572    val vpmaskNotEqual = (
573      (RegNext(paddrModule.io.forwardMmask(i).asUInt) ^ RegNext(vaddrModule.io.forwardMmask(i).asUInt)) &
574      RegNext(needForward) &
575      RegNext(addrRealValidVec.asUInt)
576    ) =/= 0.U
577    val vaddrMatchFailed = vpmaskNotEqual && RegNext(io.forward(i).valid)
578    when (vaddrMatchFailed) {
579      XSInfo("vaddrMatchFailed: pc %x pmask %x vmask %x\n",
580        RegNext(io.forward(i).uop.pc),
581        RegNext(needForward & paddrModule.io.forwardMmask(i).asUInt),
582        RegNext(needForward & vaddrModule.io.forwardMmask(i).asUInt)
583      );
584    }
585    XSPerfAccumulate("vaddr_match_failed", vpmaskNotEqual)
586    XSPerfAccumulate("vaddr_match_really_failed", vaddrMatchFailed)
587
588    // Fast forward mask will be generated immediately (load_s1)
589    io.forward(i).forwardMaskFast := dataModule.io.forwardMaskFast(i)
590
591    // Forward result will be generated 1 cycle later (load_s2)
592    io.forward(i).forwardMask := dataModule.io.forwardMask(i)
593    io.forward(i).forwardData := dataModule.io.forwardData(i)
594    // If addr match, data not ready, mark it as dataInvalid
595    // load_s1: generate dataInvalid in load_s1 to set fastUop
596    val dataInvalidMask1 = (addrValidVec.asUInt & ~dataValidVec.asUInt & vaddrModule.io.forwardMmask(i).asUInt & forwardMask1.asUInt)
597    val dataInvalidMask2 = (addrValidVec.asUInt & ~dataValidVec.asUInt & vaddrModule.io.forwardMmask(i).asUInt & forwardMask2.asUInt)
598    val dataInvalidMask = dataInvalidMask1 | dataInvalidMask2
599    io.forward(i).dataInvalidFast := dataInvalidMask.orR
600
601    // make chisel happy
602    val dataInvalidMask1Reg = Wire(UInt(StoreQueueSize.W))
603    dataInvalidMask1Reg := RegNext(dataInvalidMask1)
604    // make chisel happy
605    val dataInvalidMask2Reg = Wire(UInt(StoreQueueSize.W))
606    dataInvalidMask2Reg := RegNext(dataInvalidMask2)
607    val dataInvalidMaskReg = dataInvalidMask1Reg | dataInvalidMask2Reg
608
609    // If SSID match, address not ready, mark it as addrInvalid
610    // load_s2: generate addrInvalid
611    val addrInvalidMask1 = (~addrValidVec.asUInt & storeSetHitVec.asUInt & forwardMask1.asUInt)
612    val addrInvalidMask2 = (~addrValidVec.asUInt & storeSetHitVec.asUInt & forwardMask2.asUInt)
613    // make chisel happy
614    val addrInvalidMask1Reg = Wire(UInt(StoreQueueSize.W))
615    addrInvalidMask1Reg := RegNext(addrInvalidMask1)
616    // make chisel happy
617    val addrInvalidMask2Reg = Wire(UInt(StoreQueueSize.W))
618    addrInvalidMask2Reg := RegNext(addrInvalidMask2)
619    val addrInvalidMaskReg = addrInvalidMask1Reg | addrInvalidMask2Reg
620
621    // load_s2
622    io.forward(i).dataInvalid := RegNext(io.forward(i).dataInvalidFast)
623    // check if vaddr forward mismatched
624    io.forward(i).matchInvalid := vaddrMatchFailed
625
626    // data invalid sq index
627    // check whether false fail
628    // check flag
629    val s2_differentFlag = RegNext(differentFlag)
630    val s2_enqPtrExt = RegNext(enqPtrExt(0))
631    val s2_deqPtrExt = RegNext(deqPtrExt(0))
632
633    // addr invalid sq index
634    // make chisel happy
635    val addrInvalidMaskRegWire = Wire(UInt(StoreQueueSize.W))
636    addrInvalidMaskRegWire := addrInvalidMaskReg
637    val addrInvalidFlag = addrInvalidMaskRegWire.orR
638    val hasInvalidAddr = (~addrValidVec.asUInt & needForward).orR
639
640    val addrInvalidSqIdx1 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(addrInvalidMask1Reg))))
641    val addrInvalidSqIdx2 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(addrInvalidMask2Reg))))
642    val addrInvalidSqIdx = Mux(addrInvalidMask2Reg.orR, addrInvalidSqIdx2, addrInvalidSqIdx1)
643
644    // store-set content management
645    //                +-----------------------+
646    //                | Search a SSID for the |
647    //                |    load operation     |
648    //                +-----------------------+
649    //                           |
650    //                           V
651    //                 +-------------------+
652    //                 | load wait strict? |
653    //                 +-------------------+
654    //                           |
655    //                           V
656    //               +----------------------+
657    //            Set|                      |Clean
658    //               V                      V
659    //  +------------------------+   +------------------------------+
660    //  | Waiting for all older  |   | Wait until the corresponding |
661    //  |   stores operations    |   | older store operations       |
662    //  +------------------------+   +------------------------------+
663
664
665
666    when (RegNext(io.forward(i).uop.loadWaitStrict)) {
667      io.forward(i).addrInvalidSqIdx := RegNext(io.forward(i).uop.sqIdx - 1.U)
668    } .elsewhen (addrInvalidFlag) {
669      io.forward(i).addrInvalidSqIdx.flag := Mux(!s2_differentFlag || addrInvalidSqIdx >= s2_deqPtrExt.value, s2_deqPtrExt.flag, s2_enqPtrExt.flag)
670      io.forward(i).addrInvalidSqIdx.value := addrInvalidSqIdx
671    } .otherwise {
672      // may be store inst has been written to sbuffer already.
673      io.forward(i).addrInvalidSqIdx := RegNext(io.forward(i).uop.sqIdx)
674    }
675    io.forward(i).addrInvalid := Mux(RegNext(io.forward(i).uop.loadWaitStrict), RegNext(hasInvalidAddr), addrInvalidFlag)
676
677    // data invalid sq index
678    // make chisel happy
679    val dataInvalidMaskRegWire = Wire(UInt(StoreQueueSize.W))
680    dataInvalidMaskRegWire := dataInvalidMaskReg
681    val dataInvalidFlag = dataInvalidMaskRegWire.orR
682
683    val dataInvalidSqIdx1 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(dataInvalidMask1Reg))))
684    val dataInvalidSqIdx2 = OHToUInt(Reverse(PriorityEncoderOH(Reverse(dataInvalidMask2Reg))))
685    val dataInvalidSqIdx = Mux(dataInvalidMask2Reg.orR, dataInvalidSqIdx2, dataInvalidSqIdx1)
686
687    when (dataInvalidFlag) {
688      io.forward(i).dataInvalidSqIdx.flag := Mux(!s2_differentFlag || dataInvalidSqIdx >= s2_deqPtrExt.value, s2_deqPtrExt.flag, s2_enqPtrExt.flag)
689      io.forward(i).dataInvalidSqIdx.value := dataInvalidSqIdx
690    } .otherwise {
691      // may be store inst has been written to sbuffer already.
692      io.forward(i).dataInvalidSqIdx := RegNext(io.forward(i).uop.sqIdx)
693    }
694  }
695
696  /**
697    * Memory mapped IO / other uncached operations
698    *
699    * States:
700    * (1) writeback from store units: mark as pending
701    * (2) when they reach ROB's head, they can be sent to uncache channel
702    * (3) response from uncache channel: mark as datavalidmask.wen
703    * (4) writeback to ROB (and other units): mark as writebacked
704    * (5) ROB commits the instruction: same as normal instructions
705    */
706  //(2) when they reach ROB's head, they can be sent to uncache channel
707  // TODO: How to deal with vector store unit-stride 128 bits mmio reqs?
708  val s_idle :: s_req :: s_resp :: s_wb :: s_wait :: Nil = Enum(5)
709  val uncacheState = RegInit(s_idle)
710  switch(uncacheState) {
711    is(s_idle) {
712      when(RegNext(io.rob.pendingst && pending(deqPtr) && allocated(deqPtr) && datavalid(deqPtr) && addrvalid(deqPtr))) {
713        uncacheState := s_req
714      }
715    }
716    is(s_req) {
717      when (io.uncache.req.fire) {
718        when (io.uncacheOutstanding) {
719          uncacheState := s_wb
720        } .otherwise {
721          uncacheState := s_resp
722        }
723      }
724    }
725    is(s_resp) {
726      when(io.uncache.resp.fire) {
727        uncacheState := s_wb
728      }
729    }
730    is(s_wb) {
731      when (io.mmioStout.fire || io.vecmmioStout.fire) {
732        uncacheState := s_wait
733      }
734    }
735    is(s_wait) {
736      when(commitCount > 0.U) {
737        uncacheState := s_idle // ready for next mmio
738      }
739    }
740  }
741  io.uncache.req.valid := uncacheState === s_req
742
743  io.uncache.req.bits := DontCare
744  io.uncache.req.bits.cmd  := MemoryOpConstants.M_XWR
745  io.uncache.req.bits.addr := paddrModule.io.rdata(0) // data(deqPtr) -> rdata(0)
746  io.uncache.req.bits.data := shiftDataToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).data)
747  io.uncache.req.bits.mask := shiftMaskToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).mask)
748
749  // CBO op type check can be delayed for 1 cycle,
750  // as uncache op will not start in s_idle
751  val cbo_mmio_addr = paddrModule.io.rdata(0) >> 2 << 2 // clear lowest 2 bits for op
752  val cbo_mmio_op = 0.U //TODO
753  val cbo_mmio_data = cbo_mmio_addr | cbo_mmio_op
754  when(RegNext(LSUOpType.isCbo(uop(deqPtr).fuOpType))){
755    io.uncache.req.bits.addr := DontCare // TODO
756    io.uncache.req.bits.data := paddrModule.io.rdata(0)
757    io.uncache.req.bits.mask := DontCare // TODO
758  }
759
760  io.uncache.req.bits.atomic := atomic(RegNext(rdataPtrExtNext(0)).value)
761
762  when(io.uncache.req.fire){
763    // mmio store should not be committed until uncache req is sent
764    pending(deqPtr) := false.B
765
766    XSDebug(
767      p"uncache req: pc ${Hexadecimal(uop(deqPtr).pc)} " +
768      p"addr ${Hexadecimal(io.uncache.req.bits.addr)} " +
769      p"data ${Hexadecimal(io.uncache.req.bits.data)} " +
770      p"op ${Hexadecimal(io.uncache.req.bits.cmd)} " +
771      p"mask ${Hexadecimal(io.uncache.req.bits.mask)}\n"
772    )
773  }
774
775  // (3) response from uncache channel: mark as datavalid
776  io.uncache.resp.ready := true.B
777
778  // (4) scalar store: writeback to ROB (and other units): mark as writebacked
779  io.mmioStout.valid := uncacheState === s_wb && !is_vec(deqPtr)
780  io.mmioStout.bits.uop := uop(deqPtr)
781  io.mmioStout.bits.uop.sqIdx := deqPtrExt(0)
782  io.mmioStout.bits.data := shiftDataToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).data) // dataModule.io.rdata.read(deqPtr)
783  io.mmioStout.bits.debug.isMMIO := true.B
784  io.mmioStout.bits.debug.paddr := DontCare
785  io.mmioStout.bits.debug.isPerfCnt := false.B
786  io.mmioStout.bits.debug.vaddr := DontCare
787  // Remove MMIO inst from store queue after MMIO request is being sent
788  // That inst will be traced by uncache state machine
789  when (io.mmioStout.fire) {
790    allocated(deqPtr) := false.B
791  }
792
793  // (4) or vector store:
794  // TODO: implement it!
795  io.vecmmioStout := DontCare
796  io.vecmmioStout.valid := uncacheState === s_wb && is_vec(deqPtr)
797  io.vecmmioStout.bits.uop := uop(deqPtr)
798  io.vecmmioStout.bits.uop.sqIdx := deqPtrExt(0)
799  io.vecmmioStout.bits.data := shiftDataToLow(paddrModule.io.rdata(0), dataModule.io.rdata(0).data) // dataModule.io.rdata.read(deqPtr)
800  io.vecmmioStout.bits.debug.isMMIO := true.B
801  io.vecmmioStout.bits.debug.paddr := DontCare
802  io.vecmmioStout.bits.debug.isPerfCnt := false.B
803  io.vecmmioStout.bits.debug.vaddr := DontCare
804  // Remove MMIO inst from store queue after MMIO request is being sent
805  // That inst will be traced by uncache state machine
806  when (io.vecmmioStout.fire) {
807    allocated(deqPtr) := false.B
808  }
809
810  /**
811    * ROB commits store instructions (mark them as committed)
812    *
813    * (1) When store commits, mark it as committed.
814    * (2) They will not be cancelled and can be sent to lower level.
815    */
816  XSError(uncacheState =/= s_idle && uncacheState =/= s_wait && commitCount > 0.U,
817   "should not commit instruction when MMIO has not been finished\n")
818
819  val scalarcommitVec = WireInit(VecInit(Seq.fill(CommitWidth)(false.B)))
820  val veccommitVec = WireInit(VecInit(Seq.fill(CommitWidth)(false.B)))
821  // TODO: Deal with vector store mmio
822  for (i <- 0 until CommitWidth) {
823    val veccount = PopCount(veccommitVec.take(i))
824    when (is_vec(cmtPtrExt(i).value) && isNotAfter(uop(cmtPtrExt(i).value).robIdx, io.rob.pendingPtr) && vec_mbCommit(cmtPtrExt(i).value)) {
825      if (i == 0){
826        // TODO: fixme for mmio
827        when (uncacheState === s_idle){
828          committed(cmtPtrExt(0).value) := true.B
829          veccommitVec(i) := true.B
830        }
831      } else {
832        committed(cmtPtrExt(i).value) := true.B
833        veccommitVec(i) := true.B
834      }
835    } .elsewhen (scalarCommitCount > i.U - veccount) {
836      if (i == 0){
837        when (uncacheState === s_idle){
838          committed(cmtPtrExt(0).value) := true.B
839          scalarcommitVec(i) := true.B
840        }
841      } else {
842        committed(cmtPtrExt(i).value) := true.B
843        scalarcommitVec(i) := true.B
844      }
845    }
846  }
847
848  scalarCommitted := PopCount(scalarcommitVec)
849  vecCommitted := PopCount(veccommitVec)
850  commitCount := scalarCommitted + vecCommitted
851
852  cmtPtrExt := cmtPtrExt.map(_ + RegNext(PopCount(veccommitVec)) + RegNext(scalarCommitted))
853
854  // committed stores will not be cancelled and can be sent to lower level.
855  // remove retired insts from sq, add retired store to sbuffer
856
857  // Read data from data module
858  // As store queue grows larger and larger, time needed to read data from data
859  // module keeps growing higher. Now we give data read a whole cycle.
860  val mmioStall = mmio(rdataPtrExt(0).value)
861  for (i <- 0 until EnsbufferWidth) {
862    val ptr = rdataPtrExt(i).value
863    dataBuffer.io.enq(i).valid := allocated(ptr) && committed(ptr) && !mmioStall
864    // Note that store data/addr should both be valid after store's commit
865    assert(!dataBuffer.io.enq(i).valid || allvalid(ptr) || (allocated(ptr) && vec_mbCommit(ptr)))
866    dataBuffer.io.enq(i).bits.addr     := paddrModule.io.rdata(i)
867    dataBuffer.io.enq(i).bits.vaddr    := vaddrModule.io.rdata(i)
868    dataBuffer.io.enq(i).bits.data     := dataModule.io.rdata(i).data
869    dataBuffer.io.enq(i).bits.mask     := dataModule.io.rdata(i).mask
870    dataBuffer.io.enq(i).bits.wline    := paddrModule.io.rlineflag(i)
871    dataBuffer.io.enq(i).bits.sqPtr    := rdataPtrExt(i)
872    dataBuffer.io.enq(i).bits.prefetch := prefetch(ptr)
873    dataBuffer.io.enq(i).bits.vec_mbCommit := vec_mbCommit(ptr)
874  }
875
876  // Send data stored in sbufferReqBitsReg to sbuffer
877  for (i <- 0 until EnsbufferWidth) {
878    io.sbuffer(i).valid := dataBuffer.io.deq(i).valid && !dataBuffer.io.deq(i).bits.vec_mbCommit
879    dataBuffer.io.deq(i).ready := io.sbuffer(i).ready
880    // Write line request should have all 1 mask
881    assert(!(io.sbuffer(i).valid && io.sbuffer(i).bits.wline && !io.sbuffer(i).bits.mask.andR))
882    io.sbuffer(i).bits := DontCare
883    io.sbuffer(i).bits.cmd   := MemoryOpConstants.M_XWR
884    io.sbuffer(i).bits.addr  := dataBuffer.io.deq(i).bits.addr
885    io.sbuffer(i).bits.vaddr := dataBuffer.io.deq(i).bits.vaddr
886    io.sbuffer(i).bits.data  := dataBuffer.io.deq(i).bits.data
887    io.sbuffer(i).bits.mask  := dataBuffer.io.deq(i).bits.mask
888    io.sbuffer(i).bits.wline := dataBuffer.io.deq(i).bits.wline
889    io.sbuffer(i).bits.prefetch := dataBuffer.io.deq(i).bits.prefetch
890    sbuffer_Inv(i) := dataBuffer.io.deq(i).valid && dataBuffer.io.deq(i).bits.vec_mbCommit
891
892    // io.sbuffer(i).fire is RegNexted, as sbuffer data write takes 2 cycles.
893    // Before data write finish, sbuffer is unable to provide store to load
894    // forward data. As an workaround, deqPtrExt and allocated flag update
895    // is delayed so that load can get the right data from store queue.
896    val ptr = dataBuffer.io.deq(i).bits.sqPtr.value
897    when (RegNext(io.sbuffer(i).fire) || sbuffer_Inv(i)) {
898      allocated(RegEnable(ptr, io.sbuffer(i).fire)) := false.B
899      XSDebug("sbuffer "+i+" fire: ptr %d\n", ptr)
900    }
901  }
902  (1 until EnsbufferWidth).foreach(i => when(io.sbuffer(i).fire) { assert(io.sbuffer(i - 1).fire) })
903  if (coreParams.dcacheParametersOpt.isEmpty) {
904    for (i <- 0 until EnsbufferWidth) {
905      val ptr = deqPtrExt(i).value
906      val ram = DifftestMem(64L * 1024 * 1024 * 1024, 8)
907      val wen = allocated(ptr) && committed(ptr) && !mmio(ptr)
908      val waddr = ((paddrModule.io.rdata(i) - "h80000000".U) >> 3).asUInt
909      val wdata = Mux(paddrModule.io.rdata(i)(3), dataModule.io.rdata(i).data(127, 64), dataModule.io.rdata(i).data(63, 0))
910      val wmask = Mux(paddrModule.io.rdata(i)(3), dataModule.io.rdata(i).mask(15, 8), dataModule.io.rdata(i).mask(7, 0))
911      when (wen) {
912        ram.write(waddr, wdata.asTypeOf(Vec(8, UInt(8.W))), wmask.asBools)
913      }
914    }
915  }
916
917  // Read vaddr for mem exception
918  io.exceptionAddr.vaddr := exceptionBuffer.io.exceptionAddr.vaddr
919
920  // vector commit or replay from
921  val vecCommit = Wire(Vec(StoreQueueSize, Bool()))
922  for (i <- 0 until StoreQueueSize) {
923    val fbk = io.vecFeedback
924    vecCommit(i) := fbk.valid && fbk.bits.isCommit && uop(i).robIdx === fbk.bits.robidx && uop(i).uopIdx === fbk.bits.uopidx
925    when (vecCommit(i)) {
926      vec_mbCommit(i) := true.B
927    }
928  }
929
930  // misprediction recovery / exception redirect
931  // invalidate sq term using robIdx
932  val needCancel = Wire(Vec(StoreQueueSize, Bool()))
933  for (i <- 0 until StoreQueueSize) {
934    needCancel(i) := uop(i).robIdx.needFlush(io.brqRedirect) && allocated(i) && !committed(i)
935    when (needCancel(i)) {
936      allocated(i) := false.B
937    }
938  }
939
940 /**
941* update pointers
942**/
943  val lastEnqCancel = PopCount(RegNext(VecInit(canEnqueue.zip(enqCancel).map(x => x._1 && x._2)))) // 1 cycle after redirect
944  val lastCycleCancelCount = PopCount(RegNext(needCancel)) // 1 cycle after redirect
945  val lastCycleRedirect = RegNext(io.brqRedirect.valid) // 1 cycle after redirect
946  val enqNumber = validVStoreFlow.reduce(_ + _)
947
948  val lastlastCycleRedirect=RegNext(lastCycleRedirect)// 2 cycle after redirect
949  val redirectCancelCount = RegEnable(lastCycleCancelCount + lastEnqCancel, lastCycleRedirect) // 2 cycle after redirect
950
951  when (lastlastCycleRedirect) {
952    // we recover the pointers in 2 cycle after redirect for better timing
953    enqPtrExt := VecInit(enqPtrExt.map(_ - redirectCancelCount))
954  }.otherwise {
955    // lastCycleRedirect.valid or nornal case
956    // when lastCycleRedirect.valid, enqNumber === 0.U, enqPtrExt will not change
957    enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber))
958  }
959  assert(!(lastCycleRedirect && enqNumber =/= 0.U))
960
961  deqPtrExt := deqPtrExtNext
962  rdataPtrExt := rdataPtrExtNext
963
964  // val dequeueCount = Mux(io.sbuffer(1).fire, 2.U, Mux(io.sbuffer(0).fire || io.mmioStout.fire, 1.U, 0.U))
965
966  // If redirect at T0, sqCancelCnt is at T2
967  io.sqCancelCnt := redirectCancelCount
968  val ForceWriteUpper = Wire(UInt(log2Up(StoreQueueSize + 1).W))
969  ForceWriteUpper := Constantin.createRecord("ForceWriteUpper_"+p(XSCoreParamsKey).HartId.toString(), initValue = 60.U)
970  val ForceWriteLower = Wire(UInt(log2Up(StoreQueueSize + 1).W))
971  ForceWriteLower := Constantin.createRecord("ForceWriteLower_"+p(XSCoreParamsKey).HartId.toString(), initValue = 55.U)
972
973  val valid_cnt = PopCount(allocated)
974  io.force_write := RegNext(Mux(valid_cnt >= ForceWriteUpper, true.B, valid_cnt >= ForceWriteLower && io.force_write), init = false.B)
975
976  // io.sqempty will be used by sbuffer
977  // We delay it for 1 cycle for better timing
978  // When sbuffer need to check if it is empty, the pipeline is blocked, which means delay io.sqempty
979  // for 1 cycle will also promise that sq is empty in that cycle
980  io.sqEmpty := RegNext(
981    enqPtrExt(0).value === deqPtrExt(0).value &&
982    enqPtrExt(0).flag === deqPtrExt(0).flag
983  )
984  // perf counter
985  QueuePerf(StoreQueueSize, validCount, !allowEnqueue)
986  io.sqFull := !allowEnqueue
987  XSPerfAccumulate("mmioCycle", uncacheState =/= s_idle) // lq is busy dealing with uncache req
988  XSPerfAccumulate("mmioCnt", io.uncache.req.fire)
989  XSPerfAccumulate("mmio_wb_success", io.mmioStout.fire || io.vecmmioStout.fire)
990  XSPerfAccumulate("mmio_wb_blocked", (io.mmioStout.valid && !io.mmioStout.ready) || (io.vecmmioStout.valid && !io.vecmmioStout.ready))
991  XSPerfAccumulate("validEntryCnt", distanceBetween(enqPtrExt(0), deqPtrExt(0)))
992  XSPerfAccumulate("cmtEntryCnt", distanceBetween(cmtPtrExt(0), deqPtrExt(0)))
993  XSPerfAccumulate("nCmtEntryCnt", distanceBetween(enqPtrExt(0), cmtPtrExt(0)))
994
995  val perfValidCount = distanceBetween(enqPtrExt(0), deqPtrExt(0))
996  val perfEvents = Seq(
997    ("mmioCycle      ", uncacheState =/= s_idle),
998    ("mmioCnt        ", io.uncache.req.fire),
999    ("mmio_wb_success", io.mmioStout.fire || io.vecmmioStout.fire),
1000    ("mmio_wb_blocked", (io.mmioStout.valid && !io.mmioStout.ready) || (io.vecmmioStout.valid && !io.vecmmioStout.ready)),
1001    ("stq_1_4_valid  ", (perfValidCount < (StoreQueueSize.U/4.U))),
1002    ("stq_2_4_valid  ", (perfValidCount > (StoreQueueSize.U/4.U)) & (perfValidCount <= (StoreQueueSize.U/2.U))),
1003    ("stq_3_4_valid  ", (perfValidCount > (StoreQueueSize.U/2.U)) & (perfValidCount <= (StoreQueueSize.U*3.U/4.U))),
1004    ("stq_4_4_valid  ", (perfValidCount > (StoreQueueSize.U*3.U/4.U))),
1005  )
1006  generatePerfEvent()
1007
1008  // debug info
1009  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt(0).flag, deqPtr)
1010
1011  def PrintFlag(flag: Bool, name: String): Unit = {
1012    when(flag) {
1013      XSDebug(false, true.B, name)
1014    }.otherwise {
1015      XSDebug(false, true.B, " ")
1016    }
1017  }
1018
1019  for (i <- 0 until StoreQueueSize) {
1020    XSDebug(i + ": pc %x va %x pa %x data %x ",
1021      uop(i).pc,
1022      debug_vaddr(i),
1023      debug_paddr(i),
1024      debug_data(i)
1025    )
1026    PrintFlag(allocated(i), "a")
1027    PrintFlag(allocated(i) && addrvalid(i), "a")
1028    PrintFlag(allocated(i) && datavalid(i), "d")
1029    PrintFlag(allocated(i) && committed(i), "c")
1030    PrintFlag(allocated(i) && pending(i), "p")
1031    PrintFlag(allocated(i) && mmio(i), "m")
1032    PrintFlag(allocated(i) && vec_secondInv(i), "s")
1033    XSDebug(false, true.B, "\n")
1034  }
1035
1036}
1037