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