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