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