xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/StoreQueue.scala (revision b7b0d6c1ab6c9f4501f56975a1b95c01c7ec5983)
1package xiangshan.mem
2
3import chisel3._
4import chisel3.util._
5import utils._
6import xiangshan._
7import xiangshan.cache._
8import xiangshan.cache.{DCacheWordIO, DCacheLineIO, TlbRequestIO, MemoryOpConstants}
9import xiangshan.backend.LSUOpType
10import xiangshan.backend.roq.RoqLsqIO
11
12
13class SqPtr extends CircularQueuePtr[SqPtr](SqPtr.StoreQueueSize)
14
15object SqPtr extends HasXSParameter {
16  def apply(f: Bool, v: UInt): SqPtr = {
17    val ptr = Wire(new SqPtr)
18    ptr.flag := f
19    ptr.value := v
20    ptr
21  }
22}
23
24class SqEnqIO extends XSBundle {
25  val canAccept = Output(Bool())
26  val lqCanAccept = Input(Bool())
27  val needAlloc = Vec(RenameWidth, Input(Bool()))
28  val req = Vec(RenameWidth, Flipped(ValidIO(new MicroOp)))
29  val resp = Vec(RenameWidth, Output(new SqPtr))
30}
31
32// Store Queue
33class StoreQueue extends XSModule with HasDCacheParameters with HasCircularQueuePtrHelper {
34  val io = IO(new Bundle() {
35    val enq = new SqEnqIO
36    val brqRedirect = Flipped(ValidIO(new Redirect))
37    val flush = Input(Bool())
38    val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle)))
39    val sbuffer = Vec(StorePipelineWidth, Decoupled(new DCacheWordReq))
40    val mmioStout = DecoupledIO(new ExuOutput) // writeback uncached store
41    val forward = Vec(LoadPipelineWidth, Flipped(new MaskedLoadForwardQueryIO))
42    val roq = Flipped(new RoqLsqIO)
43    val uncache = new DCacheWordIO
44    // val refill = Flipped(Valid(new DCacheLineReq ))
45    val exceptionAddr = new ExceptionAddrIO
46    val sqempty = Output(Bool())
47    val issuePtrExt = Output(new SqPtr)
48    val storeIssue = Vec(StorePipelineWidth, Flipped(Valid(new ExuInput)))
49    val sqFull = Output(Bool())
50  })
51
52  val difftestIO = IO(new Bundle() {
53    val storeCommit = Output(UInt(2.W))
54    val storeAddr   = Output(Vec(2, UInt(64.W)))
55    val storeData   = Output(Vec(2, UInt(64.W)))
56    val storeMask   = Output(Vec(2, UInt(8.W)))
57  })
58  difftestIO <> DontCare
59
60  // data modules
61  val uop = Reg(Vec(StoreQueueSize, new MicroOp))
62  // val data = Reg(Vec(StoreQueueSize, new LsqEntry))
63  val dataModule = Module(new StoreQueueData(StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth, numForward = StorePipelineWidth))
64  dataModule.io := DontCare
65  val paddrModule = Module(new SQPaddrModule(StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth, numForward = StorePipelineWidth))
66  paddrModule.io := DontCare
67  val vaddrModule = Module(new SyncDataModuleTemplate(UInt(VAddrBits.W), StoreQueueSize, numRead = 1, numWrite = StorePipelineWidth))
68  vaddrModule.io := DontCare
69
70  // state & misc
71  val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated
72  val datavalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio data is valid
73  val writebacked = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // inst has been writebacked to CDB
74  val issued = Reg(Vec(StoreQueueSize, Bool())) // inst has been issued by rs
75  val commited = Reg(Vec(StoreQueueSize, Bool())) // inst has been commited by roq
76  val pending = Reg(Vec(StoreQueueSize, Bool())) // mmio pending: inst is an mmio inst, it will not be executed until it reachs the end of roq
77  val mmio = Reg(Vec(StoreQueueSize, Bool())) // mmio: inst is an mmio inst
78
79  // ptr
80  require(StoreQueueSize > RenameWidth)
81  val enqPtrExt = RegInit(VecInit((0 until RenameWidth).map(_.U.asTypeOf(new SqPtr))))
82  val deqPtrExt = RegInit(VecInit((0 until StorePipelineWidth).map(_.U.asTypeOf(new SqPtr))))
83  val cmtPtrExt = RegInit(VecInit((0 until CommitWidth).map(_.U.asTypeOf(new SqPtr))))
84  val issuePtrExt = RegInit(0.U.asTypeOf(new SqPtr))
85  val validCounter = RegInit(0.U(log2Ceil(LoadQueueSize + 1).W))
86  val allowEnqueue = RegInit(true.B)
87
88  val enqPtr = enqPtrExt(0).value
89  val deqPtr = deqPtrExt(0).value
90  val cmtPtr = cmtPtrExt(0).value
91
92  val deqMask = UIntToMask(deqPtr, StoreQueueSize)
93  val enqMask = UIntToMask(enqPtr, StoreQueueSize)
94
95  val commitCount = RegNext(io.roq.scommit)
96
97  // Read dataModule
98  // deqPtrExtNext and deqPtrExtNext+1 entry will be read from dataModule
99  // if !sbuffer.fire(), read the same ptr
100  // if sbuffer.fire(), read next
101  val deqPtrExtNext = WireInit(Mux(io.sbuffer(1).fire(),
102    VecInit(deqPtrExt.map(_ + 2.U)),
103    Mux(io.sbuffer(0).fire() || io.mmioStout.fire(),
104      VecInit(deqPtrExt.map(_ + 1.U)),
105      deqPtrExt
106    )
107  ))
108  for (i <- 0 until StorePipelineWidth) {
109    dataModule.io.raddr(i) := deqPtrExtNext(i).value
110    paddrModule.io.raddr(i) := deqPtrExtNext(i).value
111  }
112
113  // no inst will be commited 1 cycle before tval update
114  vaddrModule.io.raddr(0) := (cmtPtrExt(0) + commitCount).value
115
116  /**
117    * Enqueue at dispatch
118    *
119    * Currently, StoreQueue only allows enqueue when #emptyEntries > RenameWidth(EnqWidth)
120    */
121  io.enq.canAccept := allowEnqueue
122  for (i <- 0 until RenameWidth) {
123    val offset = if (i == 0) 0.U else PopCount(io.enq.needAlloc.take(i))
124    val sqIdx = enqPtrExt(offset)
125    val index = sqIdx.value
126    when (io.enq.req(i).valid && io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush)) {
127      uop(index) := io.enq.req(i).bits
128      allocated(index) := true.B
129      datavalid(index) := false.B
130      writebacked(index) := false.B
131      issued(index) := false.B
132      commited(index) := false.B
133      pending(index) := false.B
134    }
135    io.enq.resp(i) := sqIdx
136  }
137  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n")
138
139  /**
140    * Update issuePtr when issue from rs
141    */
142
143  // update state bit issued
144  for (i <- 0 until StorePipelineWidth) {
145    when (io.storeIssue(i).valid) {
146      issued(io.storeIssue(i).bits.uop.sqIdx.value) := true.B
147    }
148  }
149
150  // update issuePtr
151  val IssuePtrMoveStride = 4
152  require(IssuePtrMoveStride >= 2)
153
154  val issueLookupVec = (0 until IssuePtrMoveStride).map(issuePtrExt + _.U)
155  val issueLookup = issueLookupVec.map(ptr => allocated(ptr.value) && issued(ptr.value) && ptr =/= enqPtrExt(0))
156  val nextIssuePtr = issuePtrExt + PriorityEncoder(VecInit(issueLookup.map(!_) :+ true.B))
157  issuePtrExt := nextIssuePtr
158
159  when (io.brqRedirect.valid || io.flush) {
160    issuePtrExt := Mux(
161      isAfter(cmtPtrExt(0), deqPtrExt(0)),
162      cmtPtrExt(0),
163      deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr
164    )
165  }
166  // send issuePtrExt to rs
167  // io.issuePtrExt := cmtPtrExt(0)
168  io.issuePtrExt := issuePtrExt
169
170  /**
171    * Writeback store from store units
172    *
173    * Most store instructions writeback to regfile in the previous cycle.
174    * However,
175    *   (1) For an mmio instruction with exceptions, we need to mark it as datavalid
176    * (in this way it will trigger an exception when it reaches ROB's head)
177    * instead of pending to avoid sending them to lower level.
178    *   (2) For an mmio instruction without exceptions, we mark it as pending.
179    * When the instruction reaches ROB's head, StoreQueue sends it to uncache channel.
180    * Upon receiving the response, StoreQueue writes back the instruction
181    * through arbiter with store units. It will later commit as normal.
182    */
183  for (i <- 0 until StorePipelineWidth) {
184    dataModule.io.wen(i) := false.B
185    paddrModule.io.wen(i) := false.B
186    val stWbIndex = io.storeIn(i).bits.uop.sqIdx.value
187    when (io.storeIn(i).fire()) {
188      datavalid(stWbIndex) := !io.storeIn(i).bits.mmio
189      writebacked(stWbIndex) := !io.storeIn(i).bits.mmio
190      pending(stWbIndex) := io.storeIn(i).bits.mmio
191
192      val storeWbData = Wire(new SQDataEntry)
193      storeWbData := DontCare
194      storeWbData.mask := io.storeIn(i).bits.mask
195      storeWbData.data := io.storeIn(i).bits.data
196
197      dataModule.io.waddr(i) := stWbIndex
198      dataModule.io.wdata(i) := storeWbData
199      dataModule.io.wen(i) := true.B
200
201      paddrModule.io.waddr(i) := stWbIndex
202      paddrModule.io.wdata(i) := io.storeIn(i).bits.paddr
203      paddrModule.io.wen(i) := true.B
204
205
206      mmio(stWbIndex) := io.storeIn(i).bits.mmio
207
208      XSInfo("store write to sq idx %d pc 0x%x vaddr %x paddr %x data %x mmio %x\n",
209        io.storeIn(i).bits.uop.sqIdx.value,
210        io.storeIn(i).bits.uop.cf.pc,
211        io.storeIn(i).bits.vaddr,
212        io.storeIn(i).bits.paddr,
213        io.storeIn(i).bits.data,
214        io.storeIn(i).bits.mmio
215        )
216    }
217    // vaddrModule write is delayed, as vaddrModule will not be read right after write
218    vaddrModule.io.waddr(i) := RegNext(stWbIndex)
219    vaddrModule.io.wdata(i) := RegNext(io.storeIn(i).bits.vaddr)
220    vaddrModule.io.wen(i) := RegNext(io.storeIn(i).fire())
221  }
222
223  /**
224    * load forward query
225    *
226    * Check store queue for instructions that is older than the load.
227    * The response will be valid at the next cycle after req.
228    */
229  // check over all lq entries and forward data from the first matched store
230  for (i <- 0 until LoadPipelineWidth) {
231    io.forward(i).forwardMask := 0.U(8.W).asBools
232    io.forward(i).forwardData := DontCare
233
234    // Compare deqPtr (deqPtr) and forward.sqIdx, we have two cases:
235    // (1) if they have the same flag, we need to check range(tail, sqIdx)
236    // (2) if they have different flags, we need to check range(tail, LoadQueueSize) and range(0, sqIdx)
237    // Forward1: Mux(same_flag, range(tail, sqIdx), range(tail, LoadQueueSize))
238    // Forward2: Mux(same_flag, 0.U,                   range(0, sqIdx)    )
239    // i.e. forward1 is the target entries with the same flag bits and forward2 otherwise
240    val differentFlag = deqPtrExt(0).flag =/= io.forward(i).sqIdx.flag
241    val forwardMask = io.forward(i).sqIdxMask
242    val storeWritebackedVec = WireInit(VecInit(Seq.fill(StoreQueueSize)(false.B)))
243    for (j <- 0 until StoreQueueSize) {
244      storeWritebackedVec(j) := datavalid(j) && allocated(j) // all datavalid terms need to be checked
245    }
246    val needForward1 = Mux(differentFlag, ~deqMask, deqMask ^ forwardMask) & storeWritebackedVec.asUInt
247    val needForward2 = Mux(differentFlag, forwardMask, 0.U(StoreQueueSize.W)) & storeWritebackedVec.asUInt
248
249    XSDebug(p"$i f1 ${Binary(needForward1)} f2 ${Binary(needForward2)} " +
250      p"sqIdx ${io.forward(i).sqIdx} pa ${Hexadecimal(io.forward(i).paddr)}\n"
251    )
252
253    // do real fwd query
254    dataModule.io.needForward(i)(0) := needForward1 & paddrModule.io.forwardMmask(i).asUInt
255    dataModule.io.needForward(i)(1) := needForward2 & paddrModule.io.forwardMmask(i).asUInt
256
257    paddrModule.io.forwardMdata(i) := io.forward(i).paddr
258
259    io.forward(i).forwardMask := dataModule.io.forwardMask(i)
260    io.forward(i).forwardData := dataModule.io.forwardData(i)
261  }
262
263  /**
264    * Memory mapped IO / other uncached operations
265    *
266    * States:
267    * (1) writeback from store units: mark as pending
268    * (2) when they reach ROB's head, they can be sent to uncache channel
269    * (3) response from uncache channel: mark as datavalid
270    * (4) writeback to ROB (and other units): mark as writebacked
271    * (5) ROB commits the instruction: same as normal instructions
272    */
273  //(2) when they reach ROB's head, they can be sent to uncache channel
274  val s_idle :: s_req :: s_resp :: s_wb :: s_wait :: Nil = Enum(5)
275  val uncacheState = RegInit(s_idle)
276  switch(uncacheState) {
277    is(s_idle) {
278      when(io.roq.pendingst && pending(deqPtr) && allocated(deqPtr)) {
279        uncacheState := s_req
280      }
281    }
282    is(s_req) {
283      when(io.uncache.req.fire()) {
284        uncacheState := s_resp
285      }
286    }
287    is(s_resp) {
288      when(io.uncache.resp.fire()) {
289        uncacheState := s_wb
290      }
291    }
292    is(s_wb) {
293      when (io.mmioStout.fire()) {
294        uncacheState := s_wait
295      }
296    }
297    is(s_wait) {
298      when(io.roq.commit) {
299        uncacheState := s_idle // ready for next mmio
300      }
301    }
302  }
303  io.uncache.req.valid := uncacheState === s_req
304
305  io.uncache.req.bits.cmd  := MemoryOpConstants.M_XWR
306  io.uncache.req.bits.addr := paddrModule.io.rdata(0) // data(deqPtr) -> rdata(0)
307  io.uncache.req.bits.data := dataModule.io.rdata(0).data
308  io.uncache.req.bits.mask := dataModule.io.rdata(0).mask
309
310  io.uncache.req.bits.id   := DontCare
311
312  when(io.uncache.req.fire()){
313    pending(deqPtr) := false.B
314
315    XSDebug(
316      p"uncache req: pc ${Hexadecimal(uop(deqPtr).cf.pc)} " +
317      p"addr ${Hexadecimal(io.uncache.req.bits.addr)} " +
318      p"data ${Hexadecimal(io.uncache.req.bits.data)} " +
319      p"op ${Hexadecimal(io.uncache.req.bits.cmd)} " +
320      p"mask ${Hexadecimal(io.uncache.req.bits.mask)}\n"
321    )
322  }
323
324  // (3) response from uncache channel: mark as datavalid
325  io.uncache.resp.ready := true.B
326  when (io.uncache.resp.fire()) {
327    datavalid(deqPtr) := true.B
328  }
329
330  // (4) writeback to ROB (and other units): mark as writebacked
331  io.mmioStout.valid := uncacheState === s_wb // allocated(deqPtr) && datavalid(deqPtr) && !writebacked(deqPtr)
332  io.mmioStout.bits.uop := uop(deqPtr)
333  io.mmioStout.bits.uop.sqIdx := deqPtrExt(0)
334  io.mmioStout.bits.data := dataModule.io.rdata(0).data // dataModule.io.rdata.read(deqPtr)
335  io.mmioStout.bits.redirectValid := false.B
336  io.mmioStout.bits.redirect := DontCare
337  io.mmioStout.bits.debug.isMMIO := true.B
338  io.mmioStout.bits.debug.paddr := DontCare
339  io.mmioStout.bits.debug.isPerfCnt := false.B
340  io.mmioStout.bits.fflags := DontCare
341  when (io.mmioStout.fire()) {
342    writebacked(deqPtr) := true.B
343    allocated(deqPtr) := false.B
344  }
345
346  /**
347    * ROB commits store instructions (mark them as commited)
348    *
349    * (1) When store commits, mark it as commited.
350    * (2) They will not be cancelled and can be sent to lower level.
351    */
352  for (i <- 0 until CommitWidth) {
353    when (commitCount > i.U) {
354      commited(cmtPtrExt(i).value) := true.B
355    }
356  }
357  cmtPtrExt := cmtPtrExt.map(_ + commitCount)
358
359  // Commited stores will not be cancelled and can be sent to lower level.
360  // remove retired insts from sq, add retired store to sbuffer
361  for (i <- 0 until StorePipelineWidth) {
362    // We use RegNext to prepare data for sbuffer
363    val ptr = deqPtrExt(i).value
364    // if !sbuffer.fire(), read the same ptr
365    // if sbuffer.fire(), read next
366    io.sbuffer(i).valid := allocated(ptr) && commited(ptr) && !mmio(ptr)
367    io.sbuffer(i).bits.cmd  := MemoryOpConstants.M_XWR
368    io.sbuffer(i).bits.addr := paddrModule.io.rdata(i)
369    io.sbuffer(i).bits.data := dataModule.io.rdata(i).data
370    io.sbuffer(i).bits.mask := dataModule.io.rdata(i).mask
371    io.sbuffer(i).bits.id   := DontCare
372
373    when (io.sbuffer(i).fire()) {
374      allocated(ptr) := false.B
375      XSDebug("sbuffer "+i+" fire: ptr %d\n", ptr)
376    }
377  }
378  when (io.sbuffer(1).fire()) {
379    assert(io.sbuffer(0).fire())
380  }
381
382  val storeCommit = PopCount(io.sbuffer.map(_.fire()))
383  val waddr = VecInit(io.sbuffer.map(req => SignExt(req.bits.addr, 64)))
384  val wdata = VecInit(io.sbuffer.map(req => req.bits.data & MaskExpand(req.bits.mask)))
385  val wmask = VecInit(io.sbuffer.map(_.bits.mask))
386
387  if (!env.FPGAPlatform) {
388    difftestIO.storeCommit := RegNext(storeCommit)
389    difftestIO.storeAddr   := RegNext(waddr)
390    difftestIO.storeData   := RegNext(wdata)
391    difftestIO.storeMask   := RegNext(wmask)
392  }
393
394  // Read vaddr for mem exception
395  io.exceptionAddr.vaddr := vaddrModule.io.rdata(0)
396
397  // misprediction recovery / exception redirect
398  // invalidate sq term using robIdx
399  val needCancel = Wire(Vec(StoreQueueSize, Bool()))
400  for (i <- 0 until StoreQueueSize) {
401    needCancel(i) := uop(i).roqIdx.needFlush(io.brqRedirect, io.flush) && allocated(i) && !commited(i)
402    when (needCancel(i)) {
403        allocated(i) := false.B
404    }
405  }
406
407  /**
408    * update pointers
409    */
410  val lastCycleRedirect = RegNext(io.brqRedirect.valid)
411  val lastCycleFlush = RegNext(io.flush)
412  val lastCycleCancelCount = PopCount(RegNext(needCancel))
413  // when io.brqRedirect.valid, we don't allow eneuque even though it may fire.
414  val enqNumber = Mux(io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush), PopCount(io.enq.req.map(_.valid)), 0.U)
415  when (lastCycleRedirect || lastCycleFlush) {
416    // we recover the pointers in the next cycle after redirect
417    enqPtrExt := VecInit(enqPtrExt.map(_ - lastCycleCancelCount))
418  }.otherwise {
419    enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber))
420  }
421
422  deqPtrExt := deqPtrExtNext
423
424  val dequeueCount = Mux(io.sbuffer(1).fire(), 2.U, Mux(io.sbuffer(0).fire() || io.mmioStout.fire(), 1.U, 0.U))
425  val validCount = distanceBetween(enqPtrExt(0), deqPtrExt(0))
426
427  allowEnqueue := validCount + enqNumber <= (StoreQueueSize - RenameWidth).U
428
429  // io.sqempty will be used by sbuffer
430  // We delay it for 1 cycle for better timing
431  // When sbuffer need to check if it is empty, the pipeline is blocked, which means delay io.sqempty
432  // for 1 cycle will also promise that sq is empty in that cycle
433  io.sqempty := RegNext(enqPtrExt(0).value === deqPtrExt(0).value && enqPtrExt(0).flag === deqPtrExt(0).flag)
434
435  // perf counter
436  QueuePerf(StoreQueueSize, validCount, !allowEnqueue)
437  io.sqFull := !allowEnqueue
438  XSPerfAccumulate("mmioCycle", uncacheState =/= s_idle) // lq is busy dealing with uncache req
439  XSPerfAccumulate("mmioCnt", io.uncache.req.fire())
440  XSPerfAccumulate("mmio_wb_success", io.mmioStout.fire())
441  XSPerfAccumulate("mmio_wb_blocked", io.mmioStout.valid && !io.mmioStout.ready)
442  XSPerfAccumulate("validEntryCnt", distanceBetween(enqPtrExt(0), deqPtrExt(0)))
443  XSPerfAccumulate("cmtEntryCnt", distanceBetween(cmtPtrExt(0), deqPtrExt(0)))
444  XSPerfAccumulate("nCmtEntryCnt", distanceBetween(enqPtrExt(0), cmtPtrExt(0)))
445
446  // debug info
447  XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt(0).flag, deqPtr)
448
449  def PrintFlag(flag: Bool, name: String): Unit = {
450    when(flag) {
451      XSDebug(false, true.B, name)
452    }.otherwise {
453      XSDebug(false, true.B, " ")
454    }
455  }
456
457  for (i <- 0 until StoreQueueSize) {
458    if (i % 4 == 0) XSDebug("")
459    XSDebug(false, true.B, "%x ", uop(i).cf.pc)
460    PrintFlag(allocated(i), "a")
461    PrintFlag(allocated(i) && datavalid(i), "v")
462    PrintFlag(allocated(i) && writebacked(i), "w")
463    PrintFlag(allocated(i) && commited(i), "c")
464    PrintFlag(allocated(i) && pending(i), "p")
465    XSDebug(false, true.B, " ")
466    if (i % 4 == 3 || i == StoreQueueSize - 1) XSDebug(false, true.B, "\n")
467  }
468
469}
470