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