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