xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/LSQWrapper.scala (revision 4aa0028654716f3ef660f985eb6662c6c75b70d0)
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 org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import utility._
24import xiangshan._
25import xiangshan.backend.Bundles.{DynInst, MemExuOutput}
26import xiangshan.cache._
27import xiangshan.cache.{DCacheWordIO, DCacheLineIO, MemoryOpConstants}
28import xiangshan.cache.mmu.{TlbRequestIO, TlbHintIO}
29import xiangshan.mem._
30import xiangshan.backend._
31import xiangshan.backend.rob.RobLsqIO
32
33class ExceptionAddrIO(implicit p: Parameters) extends XSBundle {
34  val isStore = Input(Bool())
35  val vaddr = Output(UInt(VAddrBits.W))
36  val vstart = Output(UInt((log2Up(VLEN) + 1).W))
37  val vl = Output(UInt((log2Up(VLEN) + 1).W))
38}
39
40class FwdEntry extends Bundle {
41  val validFast = Bool() // validFast is generated the same cycle with query
42  val valid = Bool() // valid is generated 1 cycle after query request
43  val data = UInt(8.W) // data is generated 1 cycle after query request
44}
45
46// inflight miss block reqs
47class InflightBlockInfo(implicit p: Parameters) extends XSBundle {
48  val block_addr = UInt(PAddrBits.W)
49  val valid = Bool()
50}
51
52class LsqEnqIO(implicit p: Parameters) extends MemBlockBundle {
53  val canAccept = Output(Bool())
54  val needAlloc = Vec(LSQEnqWidth, Input(UInt(2.W)))
55  val req       = Vec(LSQEnqWidth, Flipped(ValidIO(new DynInst)))
56  val resp      = Vec(LSQEnqWidth, Output(new LSIdx))
57}
58
59// Load / Store Queue Wrapper for XiangShan Out of Order LSU
60class LsqWrapper(implicit p: Parameters) extends XSModule with HasDCacheParameters with HasPerfEvents {
61  val io = IO(new Bundle() {
62    val hartId = Input(UInt(8.W))
63    val brqRedirect = Flipped(ValidIO(new Redirect))
64    val stvecFeedback = Vec(VecStorePipelineWidth, Flipped(ValidIO(new FeedbackToLsqIO)))
65    val ldvecFeedback = Vec(VecLoadPipelineWidth, Flipped(ValidIO(new FeedbackToLsqIO)))
66    val enq = new LsqEnqIO
67    val ldu = new Bundle() {
68        val stld_nuke_query = Vec(LoadPipelineWidth, Flipped(new LoadNukeQueryIO)) // from load_s2
69        val ldld_nuke_query = Vec(LoadPipelineWidth, Flipped(new LoadNukeQueryIO)) // from load_s2
70        val ldin = Vec(LoadPipelineWidth, Flipped(Decoupled(new LqWriteBundle))) // from load_s3
71    }
72    val sta = new Bundle() {
73      val storeMaskIn = Vec(StorePipelineWidth, Flipped(Valid(new StoreMaskBundle))) // from store_s0, store mask, send to sq from rs
74      val storeAddrIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle))) // from store_s1
75      val storeAddrInRe = Vec(StorePipelineWidth, Input(new LsPipelineBundle())) // from store_s2
76    }
77    val std = new Bundle() {
78      val storeDataIn = Vec(StorePipelineWidth, Flipped(Valid(new MemExuOutput(isVector = true)))) // from store_s0, store data, send to sq from rs
79    }
80    val ldout = Vec(LoadPipelineWidth, DecoupledIO(new MemExuOutput))
81    val ld_raw_data = Vec(LoadPipelineWidth, Output(new LoadDataFromLQBundle))
82    val replay = Vec(LoadPipelineWidth, Decoupled(new LsPipelineBundle))
83    val sbuffer = Vec(EnsbufferWidth, Decoupled(new DCacheWordReqWithVaddrAndPfFlag))
84    val sbufferVecDifftestInfo = Vec(EnsbufferWidth, Decoupled(new DynInst)) // The vector store difftest needs is
85    val forward = Vec(LoadPipelineWidth, Flipped(new PipeLoadForwardQueryIO))
86    val rob = Flipped(new RobLsqIO)
87    val nuke_rollback = Output(Valid(new Redirect))
88    val nack_rollback = Output(Valid(new Redirect))
89    val release = Flipped(Valid(new Release))
90    val refill = Flipped(Valid(new Refill))
91    val tl_d_channel  = Input(new DcacheToLduForwardIO)
92    val uncacheOutstanding = Input(Bool())
93    val uncache = new UncacheWordIO
94    val mmioStout = DecoupledIO(new MemExuOutput) // writeback uncached store
95    // TODO: implement vector store
96    val vecmmioStout = DecoupledIO(new MemExuOutput(isVector = true)) // vec writeback uncached store
97    val sqEmpty = Output(Bool())
98    val lq_rep_full = Output(Bool())
99    val sqFull = Output(Bool())
100    val lqFull = Output(Bool())
101    val sqCancelCnt = Output(UInt(log2Up(StoreQueueSize+1).W))
102    val lqCancelCnt = Output(UInt(log2Up(VirtualLoadQueueSize+1).W))
103    val lqDeq = Output(UInt(log2Up(CommitWidth + 1).W))
104    val sqDeq = Output(UInt(log2Ceil(EnsbufferWidth + 1).W))
105    val lqCanAccept = Output(Bool())
106    val sqCanAccept = Output(Bool())
107    val lqDeqPtr = Output(new LqPtr)
108    val sqDeqPtr = Output(new SqPtr)
109    val exceptionAddr = new ExceptionAddrIO
110    val trigger = Vec(LoadPipelineWidth, new LqTriggerIO)
111    val issuePtrExt = Output(new SqPtr)
112    val l2_hint = Input(Valid(new L2ToL1Hint()))
113    val tlb_hint = Flipped(new TlbHintIO)
114    val force_write = Output(Bool())
115    val lqEmpty = Output(Bool())
116
117    // top-down
118    val debugTopDown = new LoadQueueTopDownIO
119  })
120
121  val loadQueue = Module(new LoadQueue)
122  val storeQueue = Module(new StoreQueue)
123
124  storeQueue.io.hartId := io.hartId
125  storeQueue.io.uncacheOutstanding := io.uncacheOutstanding
126
127
128  dontTouch(loadQueue.io.tlbReplayDelayCycleCtrl)
129  // Todo: imm
130  val tlbReplayDelayCycleCtrl = WireInit(VecInit(Seq(14.U(ReSelectLen.W), 0.U(ReSelectLen.W), 125.U(ReSelectLen.W), 0.U(ReSelectLen.W))))
131  loadQueue.io.tlbReplayDelayCycleCtrl := tlbReplayDelayCycleCtrl
132
133  // io.enq logic
134  // LSQ: send out canAccept when both load queue and store queue are ready
135  // Dispatch: send instructions to LSQ only when they are ready
136  io.enq.canAccept := loadQueue.io.enq.canAccept && storeQueue.io.enq.canAccept
137  io.lqCanAccept := loadQueue.io.enq.canAccept
138  io.sqCanAccept := storeQueue.io.enq.canAccept
139  loadQueue.io.enq.sqCanAccept := storeQueue.io.enq.canAccept
140  storeQueue.io.enq.lqCanAccept := loadQueue.io.enq.canAccept
141  io.lqDeqPtr := loadQueue.io.lqDeqPtr
142  io.sqDeqPtr := storeQueue.io.sqDeqPtr
143  for (i <- io.enq.req.indices) {
144    loadQueue.io.enq.needAlloc(i)      := io.enq.needAlloc(i)(0)
145    loadQueue.io.enq.req(i).valid      := io.enq.needAlloc(i)(0) && io.enq.req(i).valid
146    loadQueue.io.enq.req(i).bits       := io.enq.req(i).bits
147    loadQueue.io.enq.req(i).bits.sqIdx := storeQueue.io.enq.resp(i)
148
149    storeQueue.io.enq.needAlloc(i)      := io.enq.needAlloc(i)(1)
150    storeQueue.io.enq.req(i).valid      := io.enq.needAlloc(i)(1) && io.enq.req(i).valid
151    storeQueue.io.enq.req(i).bits       := io.enq.req(i).bits
152    storeQueue.io.enq.req(i).bits.lqIdx := loadQueue.io.enq.resp(i)
153
154    io.enq.resp(i).lqIdx := loadQueue.io.enq.resp(i)
155    io.enq.resp(i).sqIdx := storeQueue.io.enq.resp(i)
156  }
157
158  // store queue wiring
159  storeQueue.io.brqRedirect <> io.brqRedirect
160  storeQueue.io.vecFeedback   <> io.stvecFeedback
161  storeQueue.io.storeAddrIn <> io.sta.storeAddrIn // from store_s1
162  storeQueue.io.storeAddrInRe <> io.sta.storeAddrInRe // from store_s2
163  storeQueue.io.storeDataIn <> io.std.storeDataIn // from store_s0
164  storeQueue.io.storeMaskIn <> io.sta.storeMaskIn // from store_s0
165  storeQueue.io.sbuffer     <> io.sbuffer
166  storeQueue.io.sbufferVecDifftestInfo <> io.sbufferVecDifftestInfo
167  storeQueue.io.mmioStout   <> io.mmioStout
168  storeQueue.io.vecmmioStout <> io.vecmmioStout
169  storeQueue.io.rob         <> io.rob
170  storeQueue.io.exceptionAddr.isStore := DontCare
171  storeQueue.io.sqCancelCnt <> io.sqCancelCnt
172  storeQueue.io.sqDeq       <> io.sqDeq
173  storeQueue.io.sqEmpty     <> io.sqEmpty
174  storeQueue.io.sqFull      <> io.sqFull
175  storeQueue.io.forward     <> io.forward // overlap forwardMask & forwardData, DO NOT CHANGE SEQUENCE
176  storeQueue.io.force_write <> io.force_write
177
178  /* <------- DANGEROUS: Don't change sequence here ! -------> */
179
180  //  load queue wiring
181  loadQueue.io.redirect            <> io.brqRedirect
182  loadQueue.io.vecFeedback           <> io.ldvecFeedback
183  loadQueue.io.ldu                 <> io.ldu
184  loadQueue.io.ldout               <> io.ldout
185  loadQueue.io.ld_raw_data         <> io.ld_raw_data
186  loadQueue.io.rob                 <> io.rob
187  loadQueue.io.nuke_rollback       <> io.nuke_rollback
188  loadQueue.io.nack_rollback       <> io.nack_rollback
189  loadQueue.io.replay              <> io.replay
190  loadQueue.io.refill              <> io.refill
191  loadQueue.io.tl_d_channel        <> io.tl_d_channel
192  loadQueue.io.release             <> io.release
193  loadQueue.io.trigger             <> io.trigger
194  loadQueue.io.exceptionAddr.isStore := DontCare
195  loadQueue.io.lqCancelCnt         <> io.lqCancelCnt
196  loadQueue.io.sq.stAddrReadySqPtr <> storeQueue.io.stAddrReadySqPtr
197  loadQueue.io.sq.stAddrReadyVec   <> storeQueue.io.stAddrReadyVec
198  loadQueue.io.sq.stDataReadySqPtr <> storeQueue.io.stDataReadySqPtr
199  loadQueue.io.sq.stDataReadyVec   <> storeQueue.io.stDataReadyVec
200  loadQueue.io.sq.stIssuePtr       <> storeQueue.io.stIssuePtr
201  loadQueue.io.sq.sqEmpty          <> storeQueue.io.sqEmpty
202  loadQueue.io.sta.storeAddrIn     <> io.sta.storeAddrIn // store_s1
203  loadQueue.io.std.storeDataIn     <> io.std.storeDataIn // store_s0
204  loadQueue.io.lqFull              <> io.lqFull
205  loadQueue.io.lq_rep_full         <> io.lq_rep_full
206  loadQueue.io.lqDeq               <> io.lqDeq
207  loadQueue.io.l2_hint             <> io.l2_hint
208  loadQueue.io.tlb_hint            <> io.tlb_hint
209  loadQueue.io.lqEmpty             <> io.lqEmpty
210
211  // rob commits for lsq is delayed for two cycles, which causes the delayed update for deqPtr in lq/sq
212  // s0: commit
213  // s1:               exception find
214  // s2:               exception triggered
215  // s3: ptr updated & new address
216  // address will be used at the next cycle after exception is triggered
217  io.exceptionAddr.vaddr := Mux(RegNext(io.exceptionAddr.isStore), storeQueue.io.exceptionAddr.vaddr, loadQueue.io.exceptionAddr.vaddr)
218  io.exceptionAddr.vstart := Mux(RegNext(io.exceptionAddr.isStore), storeQueue.io.exceptionAddr.vstart, loadQueue.io.exceptionAddr.vstart)
219  io.exceptionAddr.vl     := Mux(RegNext(io.exceptionAddr.isStore), storeQueue.io.exceptionAddr.vl, loadQueue.io.exceptionAddr.vl)
220  io.issuePtrExt := storeQueue.io.stAddrReadySqPtr
221
222  // naive uncache arbiter
223  val s_idle :: s_load :: s_store :: Nil = Enum(3)
224  val pendingstate = RegInit(s_idle)
225
226  switch(pendingstate){
227    is(s_idle){
228      when(io.uncache.req.fire){
229        pendingstate := Mux(loadQueue.io.uncache.req.valid, s_load,
230                          Mux(io.uncacheOutstanding, s_idle, s_store))
231      }
232    }
233    is(s_load){
234      when(io.uncache.resp.fire){
235        pendingstate := s_idle
236      }
237    }
238    is(s_store){
239      when(io.uncache.resp.fire){
240        pendingstate := s_idle
241      }
242    }
243  }
244
245  loadQueue.io.uncache := DontCare
246  storeQueue.io.uncache := DontCare
247  loadQueue.io.uncache.req.ready := false.B
248  storeQueue.io.uncache.req.ready := false.B
249  loadQueue.io.uncache.resp.valid := false.B
250  storeQueue.io.uncache.resp.valid := false.B
251  when(loadQueue.io.uncache.req.valid){
252    io.uncache.req <> loadQueue.io.uncache.req
253  }.otherwise{
254    io.uncache.req <> storeQueue.io.uncache.req
255  }
256  when (io.uncacheOutstanding) {
257    io.uncache.resp <> loadQueue.io.uncache.resp
258  } .otherwise {
259    when(pendingstate === s_load){
260      io.uncache.resp <> loadQueue.io.uncache.resp
261    }.otherwise{
262      io.uncache.resp <> storeQueue.io.uncache.resp
263    }
264  }
265
266  loadQueue.io.debugTopDown <> io.debugTopDown
267
268  assert(!(loadQueue.io.uncache.req.valid && storeQueue.io.uncache.req.valid))
269  assert(!(loadQueue.io.uncache.resp.valid && storeQueue.io.uncache.resp.valid))
270  when (!io.uncacheOutstanding) {
271    assert(!((loadQueue.io.uncache.resp.valid || storeQueue.io.uncache.resp.valid) && pendingstate === s_idle))
272  }
273
274
275  val perfEvents = Seq(loadQueue, storeQueue).flatMap(_.getPerfEvents)
276  generatePerfEvent()
277}
278
279class LsqEnqCtrl(implicit p: Parameters) extends XSModule
280  with HasVLSUParameters  {
281  val io = IO(new Bundle {
282    val redirect = Flipped(ValidIO(new Redirect))
283    // to dispatch
284    val enq = new LsqEnqIO
285    // from `memBlock.io.lqDeq
286    val lcommit = Input(UInt(log2Up(CommitWidth + 1).W))
287    // from `memBlock.io.sqDeq`
288    val scommit = Input(UInt(log2Ceil(EnsbufferWidth + 1).W))
289    // from/tp lsq
290    val lqCancelCnt = Input(UInt(log2Up(VirtualLoadQueueSize + 1).W))
291    val sqCancelCnt = Input(UInt(log2Up(StoreQueueSize + 1).W))
292    val lqFreeCount = Output(UInt(log2Up(VirtualLoadQueueSize + 1).W))
293    val sqFreeCount = Output(UInt(log2Up(StoreQueueSize + 1).W))
294    val enqLsq = Flipped(new LsqEnqIO)
295  })
296
297  val lqPtr = RegInit(0.U.asTypeOf(new LqPtr))
298  val sqPtr = RegInit(0.U.asTypeOf(new SqPtr))
299  val lqCounter = RegInit(VirtualLoadQueueSize.U(log2Up(VirtualLoadQueueSize + 1).W))
300  val sqCounter = RegInit(StoreQueueSize.U(log2Up(StoreQueueSize + 1).W))
301  val canAccept = RegInit(false.B)
302
303  val loadEnqVec = io.enq.req.zip(io.enq.needAlloc).map(x => x._1.valid && x._2(0))
304  val storeEnqVec = io.enq.req.zip(io.enq.needAlloc).map(x => x._1.valid && x._2(1))
305  val isLastUopVec = io.enq.req.map(_.bits.lastUop)
306  val vLoadFlow = io.enq.req.map(_.bits.numLsElem)
307  val vStoreFlow = io.enq.req.map(_.bits.numLsElem)
308  val validVLoadFlow = vLoadFlow.zipWithIndex.map{case (vLoadFlowNumItem, index) => Mux(loadEnqVec(index), vLoadFlowNumItem, 0.U)}
309  val validVStoreFlow = vStoreFlow.zipWithIndex.map{case (vStoreFlowNumItem, index) => Mux(storeEnqVec(index), vStoreFlowNumItem, 0.U)}
310  val enqVLoadOffsetNumber = validVLoadFlow.reduce(_ + _)
311  val enqVStoreOffsetNumber = validVStoreFlow.reduce(_ + _)
312  val validVLoadOffset = 0.U +: vLoadFlow.zip(io.enq.needAlloc)
313                                .map{case (flow, needAllocItem) => Mux(needAllocItem(0).asBool, flow, 0.U)}
314                                .slice(0, validVLoadFlow.length - 1)
315  val validVStoreOffset = 0.U +: vStoreFlow.zip(io.enq.needAlloc)
316                                .map{case (flow, needAllocItem) => Mux(needAllocItem(1).asBool, flow, 0.U)}
317                                .slice(0, validVStoreFlow.length - 1)
318  val lqAllocNumber = enqVLoadOffsetNumber
319  val sqAllocNumber = enqVStoreOffsetNumber
320
321  io.lqFreeCount  := lqCounter
322  io.sqFreeCount  := sqCounter
323  // How to update ptr and counter:
324  // (1) by default, updated according to enq/commit
325  // (2) when redirect and dispatch queue is empty, update according to lsq
326  val t1_redirect = RegNext(io.redirect.valid)
327  val t2_redirect = RegNext(t1_redirect)
328  val t2_update = t2_redirect && !VecInit(io.enq.needAlloc.map(_.orR)).asUInt.orR
329  val t3_update = RegNext(t2_update)
330  val t3_lqCancelCnt = RegNext(io.lqCancelCnt)
331  val t3_sqCancelCnt = RegNext(io.sqCancelCnt)
332  when (t3_update) {
333    lqPtr := lqPtr - t3_lqCancelCnt
334    lqCounter := lqCounter + io.lcommit + t3_lqCancelCnt
335    sqPtr := sqPtr - t3_sqCancelCnt
336    sqCounter := sqCounter + io.scommit + t3_sqCancelCnt
337  }.elsewhen (!io.redirect.valid && io.enq.canAccept) {
338    lqPtr := lqPtr + lqAllocNumber
339    lqCounter := lqCounter + io.lcommit - lqAllocNumber
340    sqPtr := sqPtr + sqAllocNumber
341    sqCounter := sqCounter + io.scommit - sqAllocNumber
342  }.otherwise {
343    lqCounter := lqCounter + io.lcommit
344    sqCounter := sqCounter + io.scommit
345  }
346
347
348  //TODO MaxAllocate and width of lqOffset/sqOffset needs to be discussed
349  val lqMaxAllocate = LSQLdEnqWidth
350  val sqMaxAllocate = LSQStEnqWidth
351  val maxAllocate = lqMaxAllocate max sqMaxAllocate
352  val ldCanAccept = lqCounter >= lqAllocNumber +& lqMaxAllocate.U
353  val sqCanAccept = sqCounter >= sqAllocNumber +& sqMaxAllocate.U
354  // It is possible that t3_update and enq are true at the same clock cycle.
355  // For example, if redirect.valid lasts more than one clock cycle,
356  // after the last redirect, new instructions may enter but previously redirect has not been resolved (updated according to the cancel count from LSQ).
357  // To solve the issue easily, we block enqueue when t3_update, which is RegNext(t2_update).
358  io.enq.canAccept := RegNext(ldCanAccept && sqCanAccept && !t2_update)
359  val lqOffset = Wire(Vec(io.enq.resp.length, UInt(lqPtr.value.getWidth.W)))
360  val sqOffset = Wire(Vec(io.enq.resp.length, UInt(sqPtr.value.getWidth.W)))
361  for ((resp, i) <- io.enq.resp.zipWithIndex) {
362    lqOffset(i) := validVLoadOffset.take(i + 1).reduce(_ + _)
363    resp.lqIdx := lqPtr + lqOffset(i)
364    sqOffset(i) := validVStoreOffset.take(i + 1).reduce(_ + _)
365    resp.sqIdx := sqPtr + sqOffset(i)
366  }
367
368  io.enqLsq.needAlloc := RegNext(io.enq.needAlloc)
369  io.enqLsq.req.zip(io.enq.req).zip(io.enq.resp).foreach{ case ((toLsq, enq), resp) =>
370    val do_enq = enq.valid && !io.redirect.valid && io.enq.canAccept
371    toLsq.valid := RegNext(do_enq)
372    toLsq.bits := RegEnable(enq.bits, do_enq)
373    toLsq.bits.lqIdx := RegEnable(resp.lqIdx, do_enq)
374    toLsq.bits.sqIdx := RegEnable(resp.sqIdx, do_enq)
375  }
376
377}