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