xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/StoreQueue.scala (revision 08fafef002735f726c86c655e331cdaf3e70cb17)
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.RoqPtr
11
12
13class SqPtr extends CircularQueuePtr(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
24// Store Queue
25class StoreQueue extends XSModule with HasDCacheParameters with HasCircularQueuePtrHelper {
26  val io = IO(new Bundle() {
27    val enq = new Bundle() {
28      val canAccept = Output(Bool())
29      val req = Vec(RenameWidth, Flipped(ValidIO(new MicroOp)))
30      val resp = Vec(RenameWidth, Output(new SqPtr))
31    }
32    val brqRedirect = Input(Valid(new Redirect))
33    val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle)))
34    val sbuffer = Vec(StorePipelineWidth, Decoupled(new DCacheWordReq))
35    val stout = Vec(2, DecoupledIO(new ExuOutput)) // writeback store
36    val forward = Vec(LoadPipelineWidth, Flipped(new LoadForwardQueryIO))
37    val commits = Flipped(Vec(CommitWidth, Valid(new RoqCommit)))
38    val uncache = new DCacheWordIO
39    val roqDeqPtr = Input(new RoqPtr)
40    // val refill = Flipped(Valid(new DCacheLineReq ))
41    val oldestStore = Output(Valid(new RoqPtr))
42    val exceptionAddr = new ExceptionAddrIO
43  })
44
45  val uop = Reg(Vec(StoreQueueSize, new MicroOp))
46  // val data = Reg(Vec(StoreQueueSize, new LsqEntry))
47  val dataModule = Module(new LSQueueData(StoreQueueSize, StorePipelineWidth))
48  dataModule.io := DontCare
49  val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated
50  val valid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // data is valid
51  val writebacked = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // inst has been writebacked to CDB
52  val commited = Reg(Vec(StoreQueueSize, Bool())) // inst has been writebacked to CDB
53  val miss = Reg(Vec(StoreQueueSize, Bool())) // load inst missed, waiting for miss queue to accept miss request
54  val listening = Reg(Vec(StoreQueueSize, Bool())) // waiting for refill result
55  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
56
57  val ringBufferHeadExtended = RegInit(0.U.asTypeOf(new SqPtr))
58  val ringBufferTailExtended = RegInit(0.U.asTypeOf(new SqPtr))
59  val ringBufferHead = ringBufferHeadExtended.value
60  val ringBufferTail = ringBufferTailExtended.value
61  val ringBufferSameFlag = ringBufferHeadExtended.flag === ringBufferTailExtended.flag
62  val ringBufferEmpty = ringBufferHead === ringBufferTail && ringBufferSameFlag
63  val ringBufferFull = ringBufferHead === ringBufferTail && !ringBufferSameFlag
64  val ringBufferAllowin = !ringBufferFull
65
66  val storeCommit = (0 until CommitWidth).map(i => io.commits(i).valid && !io.commits(i).bits.isWalk && io.commits(i).bits.uop.ctrl.commitType === CommitType.STORE)
67  val mcommitIdx = (0 until CommitWidth).map(i => io.commits(i).bits.uop.sqIdx.value)
68
69  val tailMask = (((1.U((StoreQueueSize + 1).W)) << ringBufferTail).asUInt - 1.U)(StoreQueueSize - 1, 0)
70  val headMask = (((1.U((StoreQueueSize + 1).W)) << ringBufferHead).asUInt - 1.U)(StoreQueueSize - 1, 0)
71  val enqDeqMask1 = tailMask ^ headMask
72  val enqDeqMask = Mux(ringBufferSameFlag, enqDeqMask1, ~enqDeqMask1)
73
74  // TODO: misc arbitor
75
76  // Enqueue at dispatch
77  val validEntries = distanceBetween(ringBufferHeadExtended, ringBufferTailExtended)
78  val firedDispatch = io.enq.req.map(_.valid)
79  io.enq.canAccept := validEntries <= (LoadQueueSize - RenameWidth).U
80  XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(firedDispatch))}")
81  for (i <- 0 until RenameWidth) {
82    val offset = if (i == 0) 0.U else PopCount((0 until i).map(firedDispatch(_)))
83    val sqIdx = ringBufferHeadExtended + offset
84    val index = sqIdx.value
85    when(io.enq.req(i).valid) {
86      uop(index) := io.enq.req(i).bits
87      allocated(index) := true.B
88      valid(index) := false.B
89      writebacked(index) := false.B
90      commited(index) := false.B
91      miss(index) := false.B
92      listening(index) := false.B
93      pending(index) := false.B
94    }
95    io.enq.resp(i) := sqIdx
96
97    XSError(!io.enq.canAccept && io.enq.req(i).valid, "should not valid when not ready")
98  }
99
100  when(Cat(firedDispatch).orR) {
101    ringBufferHeadExtended := ringBufferHeadExtended + PopCount(firedDispatch)
102    XSInfo("dispatched %d insts to sq\n", PopCount(firedDispatch))
103  }
104
105  // writeback store
106  (0 until StorePipelineWidth).map(i => {
107    dataModule.io.wb(i).wen := false.B
108    when(io.storeIn(i).fire()) {
109      val stWbIndex = io.storeIn(i).bits.uop.sqIdx.value
110      valid(stWbIndex) := !io.storeIn(i).bits.mmio
111      miss(stWbIndex) := io.storeIn(i).bits.miss
112      pending(stWbIndex) := io.storeIn(i).bits.mmio
113
114      val storeWbData = Wire(new LsqEntry)
115      storeWbData := DontCare
116      storeWbData.paddr := io.storeIn(i).bits.paddr
117      storeWbData.vaddr := io.storeIn(i).bits.vaddr
118      storeWbData.mask := io.storeIn(i).bits.mask
119      storeWbData.data := io.storeIn(i).bits.data
120      storeWbData.mmio := io.storeIn(i).bits.mmio
121      storeWbData.exception := io.storeIn(i).bits.uop.cf.exceptionVec.asUInt
122
123      dataModule.io.wbWrite(i, stWbIndex, storeWbData)
124      dataModule.io.wb(i).wen := true.B
125
126      XSInfo("store write to sq idx %d pc 0x%x vaddr %x paddr %x data %x miss %x mmio %x roll %x exc %x\n",
127        io.storeIn(i).bits.uop.sqIdx.value,
128        io.storeIn(i).bits.uop.cf.pc,
129        io.storeIn(i).bits.vaddr,
130        io.storeIn(i).bits.paddr,
131        io.storeIn(i).bits.data,
132        io.storeIn(i).bits.miss,
133        io.storeIn(i).bits.mmio,
134        io.storeIn(i).bits.rollback,
135        io.storeIn(i).bits.uop.cf.exceptionVec.asUInt
136        )
137    }
138  })
139
140  def getFirstOne(mask: Vec[Bool], startMask: UInt) = {
141    val length = mask.length
142    val highBits = (0 until length).map(i => mask(i) & ~startMask(i))
143    val highBitsUint = Cat(highBits.reverse)
144    PriorityEncoder(Mux(highBitsUint.orR(), highBitsUint, mask.asUInt))
145  }
146
147  def getFirstOneWithFlag(mask: Vec[Bool], startMask: UInt, startFlag: Bool) = {
148    val length = mask.length
149    val highBits = (0 until length).map(i => mask(i) & ~startMask(i))
150    val highBitsUint = Cat(highBits.reverse)
151    val changeDirection = !highBitsUint.orR()
152    val index = PriorityEncoder(Mux(!changeDirection, highBitsUint, mask.asUInt))
153    SqPtr(startFlag ^ changeDirection, index)
154  }
155
156  def selectFirstTwo(valid: Vec[Bool], startMask: UInt) = {
157    val selVec = Wire(Vec(2, UInt(log2Up(StoreQueueSize).W)))
158    val selValid = Wire(Vec(2, Bool()))
159    selVec(0) := getFirstOne(valid, startMask)
160    val firstSelMask = UIntToOH(selVec(0))
161    val secondSelVec = VecInit((0 until valid.length).map(i => valid(i) && !firstSelMask(i)))
162    selVec(1) := getFirstOne(secondSelVec, startMask)
163    selValid(0) := Cat(valid).orR
164    selValid(1) := Cat(secondSelVec).orR
165    (selValid, selVec)
166  }
167
168  def selectFirstTwoRoughly(valid: Vec[Bool]) = {
169    // TODO: do not select according to seq, just select 2 valid bit randomly
170    val firstSelVec = valid
171    val notFirstVec = Wire(Vec(valid.length, Bool()))
172    (0 until valid.length).map(i =>
173      notFirstVec(i) := (if(i != 0) { valid(i) || !notFirstVec(i) } else { false.B })
174    )
175    val secondSelVec = VecInit((0 until valid.length).map(i => valid(i) && !notFirstVec(i)))
176
177    val selVec = Wire(Vec(2, UInt(log2Up(valid.length).W)))
178    val selValid = Wire(Vec(2, Bool()))
179    selVec(0) := PriorityEncoder(firstSelVec)
180    selVec(1) := PriorityEncoder(secondSelVec)
181    selValid(0) := Cat(firstSelVec).orR
182    selValid(1) := Cat(secondSelVec).orR
183    (selValid, selVec)
184  }
185
186  // select the last writebacked instruction
187  val validStoreVec = VecInit((0 until StoreQueueSize).map(i => !(allocated(i) && valid(i))))
188  val storeNotValid = SqPtr(false.B, getFirstOne(validStoreVec, tailMask))
189  val storeValidIndex = (storeNotValid - 1.U).value
190  io.oldestStore.valid := allocated(ringBufferTailExtended.value) && valid(ringBufferTailExtended.value) && !commited(storeValidIndex)
191  io.oldestStore.bits := uop(storeValidIndex).roqIdx
192
193  // writeback up to 2 store insts to CDB
194  // choose the first two valid store requests from deqPtr
195  val storeWbSelVec = VecInit((0 until StoreQueueSize).map(i => allocated(i) && valid(i) && !writebacked(i)))
196  val (storeWbValid, storeWbSel) = selectFirstTwo(storeWbSelVec, tailMask)
197
198  (0 until StorePipelineWidth).map(i => {
199    io.stout(i).bits.uop := uop(storeWbSel(i))
200    io.stout(i).bits.uop.sqIdx := storeWbSel(i).asTypeOf(new SqPtr)
201    io.stout(i).bits.uop.cf.exceptionVec := dataModule.io.rdata(storeWbSel(i)).exception.asBools
202    io.stout(i).bits.data := dataModule.io.rdata(storeWbSel(i)).data
203    io.stout(i).bits.redirectValid := false.B
204    io.stout(i).bits.redirect := DontCare
205    io.stout(i).bits.brUpdate := DontCare
206    io.stout(i).bits.debug.isMMIO := dataModule.io.rdata(storeWbSel(i)).mmio
207    io.stout(i).valid := storeWbSelVec(storeWbSel(i)) && storeWbValid(i)
208    when(io.stout(i).fire()) {
209      writebacked(storeWbSel(i)) := true.B
210    }
211    io.stout(i).bits.fflags := DontCare
212  })
213
214  // remove retired insts from sq, add retired store to sbuffer
215
216  // move tailPtr
217  // allocatedMask: dequeuePtr can go to the next 1-bit
218  val allocatedMask = VecInit((0 until StoreQueueSize).map(i => allocated(i) || !enqDeqMask(i)))
219  // find the first one from deqPtr (ringBufferTail)
220  val nextTail1 = getFirstOneWithFlag(allocatedMask, tailMask, ringBufferTailExtended.flag)
221  val nextTail = Mux(Cat(allocatedMask).orR, nextTail1, ringBufferHeadExtended)
222  ringBufferTailExtended := nextTail
223
224  // load forward query
225  // check over all lq entries and forward data from the first matched store
226  (0 until LoadPipelineWidth).map(i => {
227    io.forward(i).forwardMask := 0.U(8.W).asBools
228    io.forward(i).forwardData := DontCare
229
230    // Compare ringBufferTail (deqPtr) and forward.sqIdx, we have two cases:
231    // (1) if they have the same flag, we need to check range(tail, sqIdx)
232    // (2) if they have different flags, we need to check range(tail, LoadQueueSize) and range(0, sqIdx)
233    // Forward1: Mux(same_flag, range(tail, sqIdx), range(tail, LoadQueueSize))
234    // Forward2: Mux(same_flag, 0.U,                   range(0, sqIdx)    )
235    // i.e. forward1 is the target entries with the same flag bits and forward2 otherwise
236
237    val differentFlag = ringBufferTailExtended.flag =/= io.forward(i).sqIdx.flag
238    val forwardMask = ((1.U((StoreQueueSize + 1).W)) << io.forward(i).sqIdx.value).asUInt - 1.U
239    val storeWritebackedVec = WireInit(VecInit(Seq.fill(StoreQueueSize)(false.B)))
240    for (j <- 0 until StoreQueueSize) {
241      storeWritebackedVec(j) := valid(j) && allocated(j) // all valid terms need to be checked
242    }
243    val needForward1 = Mux(differentFlag, ~tailMask, tailMask ^ forwardMask) & storeWritebackedVec.asUInt
244    val needForward2 = Mux(differentFlag, forwardMask, 0.U(StoreQueueSize.W)) & storeWritebackedVec.asUInt
245
246    XSDebug("" + i + " f1 %b f2 %b sqIdx %d pa %x\n", needForward1, needForward2, io.forward(i).sqIdx.asUInt, io.forward(i).paddr)
247
248    // do real fwd query
249    dataModule.io.forwardQuery(
250      channel = i,
251      paddr = io.forward(i).paddr,
252      needForward1 = needForward1,
253      needForward2 = needForward2
254    )
255
256    io.forward(i).forwardMask := dataModule.io.forward(i).forwardMask
257    io.forward(i).forwardData := dataModule.io.forward(i).forwardData
258  })
259
260  // CommitedStoreQueue for timing opt
261  // send commited store inst to sbuffer
262  // select up to 2 writebacked store insts
263  val commitedStoreQueue = Module(new MIMOQueue(
264    UInt(log2Up(StoreQueueSize).W),
265    entries = 64, //FIXME
266    inCnt = 6,
267    outCnt = 2,
268    mem = false,
269    perf = true
270  ))
271  commitedStoreQueue.io.flush := false.B
272
273  // When store commited, mark it as commited (will not be influenced by redirect),
274  // then add store's sq ptr into commitedStoreQueue
275  (0 until CommitWidth).map(i => {
276    when(storeCommit(i)) {
277      commited(mcommitIdx(i)) := true.B
278      XSDebug("store commit %d: idx %d %x\n", i.U, mcommitIdx(i), uop(mcommitIdx(i)).cf.pc)
279    }
280    commitedStoreQueue.io.enq(i).valid := storeCommit(i)
281    commitedStoreQueue.io.enq(i).bits := mcommitIdx(i)
282    // We assume commitedStoreQueue.io.enq(i).ready === true.B,
283    // for commitedStoreQueue.size = 64
284  })
285
286  class SbufferCandidateEntry extends XSBundle{
287    val sbuffer = new DCacheWordReq
288    val sqIdx = UInt(log2Up(StoreQueueSize).W)
289  }
290
291  val ensbufferCandidateQueue = Module(new MIMOQueue(
292    new SbufferCandidateEntry,
293    entries = 2,
294    inCnt = 2,
295    outCnt = 2,
296    mem = false,
297    perf = true
298  ))
299  ensbufferCandidateQueue.io.flush := false.B
300
301  val sbufferCandidate = Wire(Vec(2, Decoupled(new SbufferCandidateEntry)))
302  (0 until 2).map(i => {
303    val ptr = commitedStoreQueue.io.deq(i).bits
304    val mmio = dataModule.io.rdata(ptr).mmio
305    sbufferCandidate(i).valid := commitedStoreQueue.io.deq(i).valid && !mmio
306    sbufferCandidate(i).bits.sqIdx := ptr
307    sbufferCandidate(i).bits.sbuffer.cmd  := MemoryOpConstants.M_XWR
308    sbufferCandidate(i).bits.sbuffer.addr := dataModule.io.rdata(ptr).paddr
309    sbufferCandidate(i).bits.sbuffer.data := dataModule.io.rdata(ptr).data
310    sbufferCandidate(i).bits.sbuffer.mask := dataModule.io.rdata(ptr).mask
311    sbufferCandidate(i).bits.sbuffer.meta          := DontCare
312    sbufferCandidate(i).bits.sbuffer.meta.tlb_miss := false.B
313    sbufferCandidate(i).bits.sbuffer.meta.uop      := DontCare
314    sbufferCandidate(i).bits.sbuffer.meta.mmio     := mmio
315    sbufferCandidate(i).bits.sbuffer.meta.mask     := dataModule.io.rdata(ptr).mask
316
317    when(mmio && commitedStoreQueue.io.deq(i).valid) {
318      allocated(ptr) := false.B
319    }
320
321    commitedStoreQueue.io.deq(i).ready := sbufferCandidate(i).fire() || mmio
322    sbufferCandidate(i).ready := ensbufferCandidateQueue.io.enq(i).ready
323    ensbufferCandidateQueue.io.enq(i).valid := sbufferCandidate(i).valid
324    ensbufferCandidateQueue.io.enq(i).bits.sqIdx := sbufferCandidate(i).bits.sqIdx
325    ensbufferCandidateQueue.io.enq(i).bits.sbuffer := sbufferCandidate(i).bits.sbuffer
326
327    ensbufferCandidateQueue.io.deq(i).ready := io.sbuffer(i).fire()
328    io.sbuffer(i).valid := ensbufferCandidateQueue.io.deq(i).valid
329    io.sbuffer(i).bits  := ensbufferCandidateQueue.io.deq(i).bits.sbuffer
330
331    // update sq meta if store inst is send to sbuffer
332    when(ensbufferCandidateQueue.io.deq(i).valid && io.sbuffer(i).ready) {
333      allocated(ensbufferCandidateQueue.io.deq(i).bits.sqIdx) := false.B
334    }
335  })
336
337  // Memory mapped IO / other uncached operations
338
339  // setup misc mem access req
340  // mask / paddr / data can be get from sq.data
341  val commitType = io.commits(0).bits.uop.ctrl.commitType
342  io.uncache.req.valid := pending(ringBufferTail) && allocated(ringBufferTail) &&
343    commitType === CommitType.STORE &&
344    io.roqDeqPtr === uop(ringBufferTail).roqIdx &&
345    !io.commits(0).bits.isWalk
346
347  io.uncache.req.bits.cmd  := MemoryOpConstants.M_XWR
348  io.uncache.req.bits.addr := dataModule.io.rdata(ringBufferTail).paddr
349  io.uncache.req.bits.data := dataModule.io.rdata(ringBufferTail).data
350  io.uncache.req.bits.mask := dataModule.io.rdata(ringBufferTail).mask
351
352  io.uncache.req.bits.meta.id       := DontCare // TODO: // FIXME
353  io.uncache.req.bits.meta.vaddr    := DontCare
354  io.uncache.req.bits.meta.paddr    := dataModule.io.rdata(ringBufferTail).paddr
355  io.uncache.req.bits.meta.uop      := uop(ringBufferTail)
356  io.uncache.req.bits.meta.mmio     := true.B // dataModule.io.rdata(ringBufferTail).mmio
357  io.uncache.req.bits.meta.tlb_miss := false.B
358  io.uncache.req.bits.meta.mask     := dataModule.io.rdata(ringBufferTail).mask
359  io.uncache.req.bits.meta.replay   := false.B
360
361  io.uncache.resp.ready := true.B
362
363  when(io.uncache.req.fire()){
364    pending(ringBufferTail) := false.B
365  }
366
367  when(io.uncache.resp.fire()){
368    valid(ringBufferTail) := true.B
369    // TODO: write back exception info
370  }
371
372  when(io.uncache.req.fire()){
373    XSDebug("uncache req: pc %x addr %x data %x op %x mask %x\n",
374      uop(ringBufferTail).cf.pc,
375      io.uncache.req.bits.addr,
376      io.uncache.req.bits.data,
377      io.uncache.req.bits.cmd,
378      io.uncache.req.bits.mask
379    )
380  }
381
382  // Read vaddr for mem exception
383  io.exceptionAddr.vaddr := dataModule.io.rdata(io.exceptionAddr.lsIdx.sqIdx.value).vaddr
384
385  // misprediction recovery / exception redirect
386  // invalidate sq term using robIdx
387  val needCancel = Wire(Vec(StoreQueueSize, Bool()))
388  for (i <- 0 until StoreQueueSize) {
389    needCancel(i) := uop(i).roqIdx.needFlush(io.brqRedirect) && allocated(i) && !commited(i)
390    when(needCancel(i)) {
391      when(io.brqRedirect.bits.isReplay){
392        valid(i) := false.B
393        writebacked(i) := false.B
394        listening(i) := false.B
395        miss(i) := false.B
396        pending(i) := false.B
397      }.otherwise{
398        allocated(i) := false.B
399      }
400    }
401  }
402  when (io.brqRedirect.valid && io.brqRedirect.bits.isMisPred) {
403    ringBufferHeadExtended := ringBufferHeadExtended - PopCount(needCancel)
404  }
405
406  // debug info
407  XSDebug("head %d:%d tail %d:%d\n", ringBufferHeadExtended.flag, ringBufferHead, ringBufferTailExtended.flag, ringBufferTail)
408
409  def PrintFlag(flag: Bool, name: String): Unit = {
410    when(flag) {
411      XSDebug(false, true.B, name)
412    }.otherwise {
413      XSDebug(false, true.B, " ")
414    }
415  }
416
417  for (i <- 0 until StoreQueueSize) {
418    if (i % 4 == 0) XSDebug("")
419    XSDebug(false, true.B, "%x [%x] ", uop(i).cf.pc, dataModule.io.rdata(i).paddr)
420    PrintFlag(allocated(i), "a")
421    PrintFlag(allocated(i) && valid(i), "v")
422    PrintFlag(allocated(i) && writebacked(i), "w")
423    PrintFlag(allocated(i) && commited(i), "c")
424    PrintFlag(allocated(i) && miss(i), "m")
425    PrintFlag(allocated(i) && listening(i), "l")
426    PrintFlag(allocated(i) && pending(i), "p")
427    XSDebug(false, true.B, " ")
428    if (i % 4 == 3 || i == StoreQueueSize - 1) XSDebug(false, true.B, "\n")
429  }
430
431}
432