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