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