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