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