xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/LoadUnit.scala (revision 3c02ee8f82edea481fa8336c7f54ffc17fafba91)
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 chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import utility._
24import xiangshan.ExceptionNO._
25import xiangshan._
26import xiangshan.backend.fu.PMPRespBundle
27import xiangshan.cache._
28import xiangshan.cache.mmu.{TlbCmd, TlbReq, TlbRequestIO, TlbResp}
29
30class LoadToLsqFastIO(implicit p: Parameters) extends XSBundle {
31  val valid = Output(Bool())
32  val ld_ld_check_ok = Output(Bool())
33  val st_ld_check_ok = Output(Bool())
34  val cache_bank_no_conflict = Output(Bool())
35  val ld_idx = Output(UInt(log2Ceil(LoadQueueSize).W))
36}
37
38class LoadToLsqSlowIO(implicit p: Parameters) extends XSBundle {
39  val valid = Output(Bool())
40  val tlb_hited = Output(Bool())
41  val st_ld_check_ok = Output(Bool())
42  val cache_no_replay = Output(Bool())
43  val forward_data_valid = Output(Bool())
44  val ld_idx = Output(UInt(log2Ceil(LoadQueueSize).W))
45  val data_invalid_sq_idx = Output(UInt(log2Ceil(StoreQueueSize).W))
46}
47
48class LoadToLsqIO(implicit p: Parameters) extends XSBundle {
49  val loadIn = ValidIO(new LqWriteBundle)
50  val loadPaddrIn = ValidIO(new LqPaddrWriteBundle)
51  val loadVaddrIn = ValidIO(new LqVaddrWriteBundle)
52  val ldout = Flipped(DecoupledIO(new ExuOutput))
53  val ldRawData = Input(new LoadDataFromLQBundle)
54  val s2_load_data_forwarded = Output(Bool())
55  val s3_delayed_load_error = Output(Bool())
56  val s2_dcache_require_replay = Output(Bool())
57  val s3_replay_from_fetch = Output(Bool()) // update uop.ctrl.replayInst in load queue in s3
58  val forward = new PipeLoadForwardQueryIO
59  val loadViolationQuery = new LoadViolationQueryIO
60  val trigger = Flipped(new LqTriggerIO)
61
62  // for load replay
63  val replayFast = new LoadToLsqFastIO
64  val replaySlow = new LoadToLsqSlowIO
65}
66
67class LoadToLoadIO(implicit p: Parameters) extends XSBundle {
68  // load to load fast path is limited to ld (64 bit) used as vaddr src1 only
69  val data = UInt(XLEN.W)
70  val valid = Bool()
71}
72
73class LoadUnitTriggerIO(implicit p: Parameters) extends XSBundle {
74  val tdata2 = Input(UInt(64.W))
75  val matchType = Input(UInt(2.W))
76  val tEnable = Input(Bool()) // timing is calculated before this
77  val addrHit = Output(Bool())
78  val lastDataHit = Output(Bool())
79}
80
81// Load Pipeline Stage 0
82// Generate addr, use addr to query DCache and DTLB
83class LoadUnit_S0(implicit p: Parameters) extends XSModule with HasDCacheParameters{
84  val io = IO(new Bundle() {
85    val in = Flipped(Decoupled(new ExuInput))
86    val out = Decoupled(new LsPipelineBundle)
87    val dtlbReq = DecoupledIO(new TlbReq)
88    val dcacheReq = DecoupledIO(new DCacheWordReq)
89    val rsIdx = Input(UInt(log2Up(IssQueSize).W))
90    val isFirstIssue = Input(Bool())
91    val fastpath = Input(new LoadToLoadIO)
92    val s0_kill = Input(Bool())
93    // wire from lq to load pipeline
94    val lsqOut = Flipped(Decoupled(new LsPipelineBundle))
95
96    val s0_sqIdx = Output(new SqPtr)
97  })
98  require(LoadPipelineWidth == exuParameters.LduCnt)
99
100  // there are three sources of load pipeline's input
101  // * 1. load issued by RS  (io.in)
102  // * 2. load replayed by LSQ  (io.lsqOut)
103  // * 3. load try pointchaising when no issued or replayed load  (io.fastpath)
104
105  // the priority is
106  // 1 > 2 > 3
107  // now in S0, choise a load according to priority
108
109  val s0_vaddr = Wire(UInt(VAddrBits.W))
110  val s0_mask = Wire(UInt(8.W))
111  val s0_uop = Wire(new MicroOp)
112  val s0_isFirstIssue = Wire(Bool())
113  val s0_rsIdx = Wire(UInt(log2Up(IssQueSize).W))
114  val s0_sqIdx = Wire(new SqPtr)
115
116  io.s0_sqIdx := s0_sqIdx
117
118  val tryFastpath = WireInit(false.B)
119
120  val s0_valid = Wire(Bool())
121
122  s0_valid := io.in.valid || io.lsqOut.valid || tryFastpath
123
124  // assign default value
125  s0_uop := DontCare
126
127  when(io.in.valid) {
128    val imm12 = io.in.bits.uop.ctrl.imm(11, 0)
129    s0_vaddr := io.in.bits.src(0) + SignExt(imm12, VAddrBits)
130    s0_mask := genWmask(s0_vaddr, io.in.bits.uop.ctrl.fuOpType(1,0))
131    s0_uop := io.in.bits.uop
132    s0_isFirstIssue := io.isFirstIssue
133    s0_rsIdx := io.rsIdx
134    s0_sqIdx := io.in.bits.uop.sqIdx
135
136  }.elsewhen(io.lsqOut.valid) {
137    s0_vaddr := io.lsqOut.bits.vaddr
138    s0_mask := io.lsqOut.bits.mask
139    s0_uop := io.lsqOut.bits.uop
140    s0_isFirstIssue := io.lsqOut.bits.isFirstIssue
141    s0_rsIdx := io.lsqOut.bits.rsIdx
142    s0_sqIdx := io.lsqOut.bits.uop.sqIdx
143
144  }.otherwise {
145    if (EnableLoadToLoadForward) {
146      tryFastpath := io.fastpath.valid
147      // When there's no valid instruction from RS and LSQ, we try the load-to-load forwarding.
148      s0_vaddr := io.fastpath.data
149      // Assume the pointer chasing is always ld.
150      s0_uop.ctrl.fuOpType := LSUOpType.ld
151      s0_mask := genWmask(0.U, LSUOpType.ld)
152      // we dont care s0_isFirstIssue and s0_rsIdx and s0_sqIdx in S0 when trying pointchasing
153      // because these signals will be updated in S1
154      s0_isFirstIssue := DontCare
155      s0_rsIdx := DontCare
156      s0_sqIdx := DontCare
157    }
158  }
159
160  val addrAligned = LookupTree(s0_uop.ctrl.fuOpType(1, 0), List(
161    "b00".U   -> true.B,                   //b
162    "b01".U   -> (s0_vaddr(0)    === 0.U), //h
163    "b10".U   -> (s0_vaddr(1, 0) === 0.U), //w
164    "b11".U   -> (s0_vaddr(2, 0) === 0.U)  //d
165  ))
166
167  // io.in has highest priority
168  io.in.ready := !io.in.valid || (io.out.ready && io.dcacheReq.ready)
169  // io.lsqOut can fire only when there in no RS-issued load
170  io.lsqOut.ready := (io.out.ready && io.dcacheReq.ready && !io.in.valid)
171
172  val isSoftPrefetch = LSUOpType.isPrefetch(s0_uop.ctrl.fuOpType)
173  val isSoftPrefetchRead = s0_uop.ctrl.fuOpType === LSUOpType.prefetch_r
174  val isSoftPrefetchWrite = s0_uop.ctrl.fuOpType === LSUOpType.prefetch_w
175
176  // query DTLB
177  io.dtlbReq.valid := s0_valid
178  io.dtlbReq.bits.vaddr := s0_vaddr
179  io.dtlbReq.bits.cmd := TlbCmd.read
180  io.dtlbReq.bits.size := LSUOpType.size(s0_uop.ctrl.fuOpType)
181  io.dtlbReq.bits.kill := DontCare
182  io.dtlbReq.bits.debug.robIdx := s0_uop.robIdx
183  io.dtlbReq.bits.debug.pc := s0_uop.cf.pc
184  io.dtlbReq.bits.debug.isFirstIssue := s0_isFirstIssue
185
186  // query DCache
187  io.dcacheReq.valid := s0_valid
188  when (isSoftPrefetchRead) {
189    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_PFR
190  }.elsewhen (isSoftPrefetchWrite) {
191    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_PFW
192  }.otherwise {
193    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_XRD
194  }
195  io.dcacheReq.bits.addr := s0_vaddr
196  io.dcacheReq.bits.mask := s0_mask
197  io.dcacheReq.bits.data := DontCare
198  when(isSoftPrefetch) {
199    io.dcacheReq.bits.instrtype := SOFT_PREFETCH.U
200  }.otherwise {
201    io.dcacheReq.bits.instrtype := LOAD_SOURCE.U
202  }
203
204  // TODO: update cache meta
205  io.dcacheReq.bits.id   := DontCare
206
207  io.out.valid := s0_valid && io.dcacheReq.ready && !io.s0_kill
208
209  io.out.bits := DontCare
210  io.out.bits.vaddr := s0_vaddr
211  io.out.bits.mask := s0_mask
212  io.out.bits.uop := s0_uop
213  io.out.bits.uop.cf.exceptionVec(loadAddrMisaligned) := !addrAligned
214  io.out.bits.rsIdx := s0_rsIdx
215  io.out.bits.isFirstIssue := s0_isFirstIssue
216  io.out.bits.isSoftPrefetch := isSoftPrefetch
217  io.out.bits.isLoadReplay := !io.in.valid && io.lsqOut.valid
218
219  XSDebug(io.dcacheReq.fire,
220    p"[DCACHE LOAD REQ] pc ${Hexadecimal(s0_uop.cf.pc)}, vaddr ${Hexadecimal(s0_vaddr)}\n"
221  )
222  XSPerfAccumulate("in_valid", io.in.valid)
223  XSPerfAccumulate("in_fire", io.in.fire)
224  XSPerfAccumulate("in_fire_first_issue", io.in.valid && io.isFirstIssue)
225  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready && io.dcacheReq.ready)
226  XSPerfAccumulate("stall_dcache", io.out.valid && io.out.ready && !io.dcacheReq.ready)
227  XSPerfAccumulate("addr_spec_success", io.out.fire && s0_vaddr(VAddrBits-1, 12) === io.in.bits.src(0)(VAddrBits-1, 12))
228  XSPerfAccumulate("addr_spec_failed", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12))
229  XSPerfAccumulate("addr_spec_success_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) === io.in.bits.src(0)(VAddrBits-1, 12) && io.isFirstIssue)
230  XSPerfAccumulate("addr_spec_failed_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12) && io.isFirstIssue)
231}
232
233
234// Load Pipeline Stage 1
235// TLB resp (send paddr to dcache)
236class LoadUnit_S1(implicit p: Parameters) extends XSModule with HasCircularQueuePtrHelper {
237  val io = IO(new Bundle() {
238    val in = Flipped(Decoupled(new LsPipelineBundle))
239    val s1_kill = Input(Bool())
240    val out = Decoupled(new LsPipelineBundle)
241    val dtlbResp = Flipped(DecoupledIO(new TlbResp(2)))
242    val lsuPAddr = Output(UInt(PAddrBits.W))
243    val dcachePAddr = Output(UInt(PAddrBits.W))
244    val dcacheKill = Output(Bool())
245    val dcacheBankConflict = Input(Bool())
246    val fullForwardFast = Output(Bool())
247    val sbuffer = new LoadForwardQueryIO
248    val lsq = new PipeLoadForwardQueryIO
249    val loadViolationQueryReq = Decoupled(new LoadViolationQueryReq)
250    val reExecuteQuery = Flipped(Vec(StorePipelineWidth, Valid(new LoadReExecuteQueryIO)))
251    val rsFeedback = ValidIO(new RSFeedback)
252    val replayFast = new LoadToLsqFastIO
253    val csrCtrl = Flipped(new CustomCSRCtrlIO)
254    val needLdVioCheckRedo = Output(Bool())
255    val needReExecute = Output(Bool())
256  })
257
258  val s1_uop = io.in.bits.uop
259  val s1_paddr_dup_lsu = io.dtlbResp.bits.paddr(0)
260  val s1_paddr_dup_dcache = io.dtlbResp.bits.paddr(1)
261  // af & pf exception were modified below.
262  val s1_exception = ExceptionNO.selectByFu(io.out.bits.uop.cf.exceptionVec, lduCfg).asUInt.orR
263  val s1_tlb_miss = io.dtlbResp.bits.miss
264  val s1_mask = io.in.bits.mask
265  val s1_bank_conflict = io.dcacheBankConflict
266
267  io.out.bits := io.in.bits // forwardXX field will be updated in s1
268
269  io.dtlbResp.ready := true.B
270
271  io.lsuPAddr := s1_paddr_dup_lsu
272  io.dcachePAddr := s1_paddr_dup_dcache
273  //io.dcacheKill := s1_tlb_miss || s1_exception || s1_mmio
274  io.dcacheKill := s1_tlb_miss || s1_exception || io.s1_kill
275  // load forward query datapath
276  io.sbuffer.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill)
277  io.sbuffer.vaddr := io.in.bits.vaddr
278  io.sbuffer.paddr := s1_paddr_dup_lsu
279  io.sbuffer.uop := s1_uop
280  io.sbuffer.sqIdx := s1_uop.sqIdx
281  io.sbuffer.mask := s1_mask
282  io.sbuffer.pc := s1_uop.cf.pc // FIXME: remove it
283
284  io.lsq.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill)
285  io.lsq.vaddr := io.in.bits.vaddr
286  io.lsq.paddr := s1_paddr_dup_lsu
287  io.lsq.uop := s1_uop
288  io.lsq.sqIdx := s1_uop.sqIdx
289  io.lsq.sqIdxMask := DontCare // will be overwritten by sqIdxMask pre-generated in s0
290  io.lsq.mask := s1_mask
291  io.lsq.pc := s1_uop.cf.pc // FIXME: remove it
292
293  // ld-ld violation query
294  io.loadViolationQueryReq.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill)
295  io.loadViolationQueryReq.bits.paddr := s1_paddr_dup_lsu
296  io.loadViolationQueryReq.bits.uop := s1_uop
297
298  // st-ld violation query
299  val needReExecuteVec = Wire(Vec(StorePipelineWidth, Bool()))
300  val needReExecute = Wire(Bool())
301
302  for (w <- 0 until StorePipelineWidth) {
303    //  needReExecute valid when
304    //  1. ReExecute query request valid.
305    //  2. Load instruction is younger than requestors(store instructions).
306    //  3. Physical address match.
307    //  4. Data contains.
308
309    needReExecuteVec(w) := io.reExecuteQuery(w).valid &&
310                          isAfter(io.in.bits.uop.robIdx, io.reExecuteQuery(w).bits.robIdx) &&
311                          !s1_tlb_miss &&
312                          (s1_paddr_dup_lsu(PAddrBits-1, 3) === io.reExecuteQuery(w).bits.paddr(PAddrBits-1, 3)) &&
313                          (s1_mask & io.reExecuteQuery(w).bits.mask).orR
314  }
315  needReExecute := needReExecuteVec.asUInt.orR
316  io.needReExecute := needReExecute
317
318  // Generate forwardMaskFast to wake up insts earlier
319  val forwardMaskFast = io.lsq.forwardMaskFast.asUInt | io.sbuffer.forwardMaskFast.asUInt
320  io.fullForwardFast := ((~forwardMaskFast).asUInt & s1_mask) === 0.U
321
322  // Generate feedback signal caused by:
323  // * dcache bank conflict
324  // * need redo ld-ld violation check
325  val needLdVioCheckRedo = io.loadViolationQueryReq.valid &&
326    !io.loadViolationQueryReq.ready &&
327    RegNext(io.csrCtrl.ldld_vio_check_enable)
328  io.needLdVioCheckRedo := needLdVioCheckRedo
329  // io.rsFeedback.valid := io.in.valid && (s1_bank_conflict || needLdVioCheckRedo) && !io.s1_kill
330  io.rsFeedback.valid := Mux(io.in.bits.isLoadReplay, false.B, io.in.valid && !io.s1_kill)
331  io.rsFeedback.bits.hit := true.B // we have found s1_bank_conflict / re do ld-ld violation check
332  io.rsFeedback.bits.rsIdx := io.in.bits.rsIdx
333  io.rsFeedback.bits.flushState := io.in.bits.ptwBack
334  io.rsFeedback.bits.sourceType := Mux(s1_bank_conflict, RSFeedbackType.bankConflict, RSFeedbackType.ldVioCheckRedo)
335  io.rsFeedback.bits.dataInvalidSqIdx := DontCare
336
337  io.replayFast.valid := io.in.valid && !io.s1_kill
338  io.replayFast.ld_ld_check_ok := !needLdVioCheckRedo
339  io.replayFast.st_ld_check_ok := !needReExecute
340  io.replayFast.cache_bank_no_conflict := !s1_bank_conflict
341  io.replayFast.ld_idx := io.in.bits.uop.lqIdx.value
342
343  // if replay is detected in load_s1,
344  // load inst will be canceled immediately
345  io.out.valid := io.in.valid && (!needLdVioCheckRedo && !s1_bank_conflict && !needReExecute) && !io.s1_kill
346  io.out.bits.paddr := s1_paddr_dup_lsu
347  io.out.bits.tlbMiss := s1_tlb_miss
348
349  // current ori test will cause the case of ldest == 0, below will be modifeid in the future.
350  // af & pf exception were modified
351  io.out.bits.uop.cf.exceptionVec(loadPageFault) := io.dtlbResp.bits.excp(0).pf.ld
352  io.out.bits.uop.cf.exceptionVec(loadAccessFault) := io.dtlbResp.bits.excp(0).af.ld
353
354  io.out.bits.ptwBack := io.dtlbResp.bits.ptwBack
355  io.out.bits.rsIdx := io.in.bits.rsIdx
356
357  io.out.bits.isSoftPrefetch := io.in.bits.isSoftPrefetch
358
359  io.in.ready := !io.in.valid || io.out.ready
360
361  XSPerfAccumulate("in_valid", io.in.valid)
362  XSPerfAccumulate("in_fire", io.in.fire)
363  XSPerfAccumulate("in_fire_first_issue", io.in.fire && io.in.bits.isFirstIssue)
364  XSPerfAccumulate("tlb_miss", io.in.fire && s1_tlb_miss)
365  XSPerfAccumulate("tlb_miss_first_issue", io.in.fire && s1_tlb_miss && io.in.bits.isFirstIssue)
366  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready)
367}
368
369// Load Pipeline Stage 2
370// DCache resp
371class LoadUnit_S2(implicit p: Parameters) extends XSModule with HasLoadHelper with HasCircularQueuePtrHelper {
372  val io = IO(new Bundle() {
373    val in = Flipped(Decoupled(new LsPipelineBundle))
374    val out = Decoupled(new LsPipelineBundle)
375    val rsFeedback = ValidIO(new RSFeedback)
376    val replaySlow = new LoadToLsqSlowIO
377    val dcacheResp = Flipped(DecoupledIO(new BankedDCacheWordResp))
378    val pmpResp = Flipped(new PMPRespBundle())
379    val lsq = new LoadForwardQueryIO
380    val dataInvalidSqIdx = Input(UInt())
381    val sbuffer = new LoadForwardQueryIO
382    val dataForwarded = Output(Bool())
383    val s2_dcache_require_replay = Output(Bool())
384    val fullForward = Output(Bool())
385    val dcache_kill = Output(Bool())
386    val s3_delayed_load_error = Output(Bool())
387    val loadViolationQueryResp = Flipped(Valid(new LoadViolationQueryResp))
388    val csrCtrl = Flipped(new CustomCSRCtrlIO)
389    val sentFastUop = Input(Bool())
390    val static_pm = Input(Valid(Bool())) // valid for static, bits for mmio
391    val s2_can_replay_from_fetch = Output(Bool()) // dirty code
392    val loadDataFromDcache = Output(new LoadDataFromDcacheBundle)
393    val reExecuteQuery = Flipped(Vec(StorePipelineWidth, Valid(new LoadReExecuteQueryIO)))
394    val needReExecute = Output(Bool())
395    // val write_lq_safe = Output(Bool()) // used by duplicate wen signals
396  })
397
398  val pmp = WireInit(io.pmpResp)
399  when (io.static_pm.valid) {
400    pmp.ld := false.B
401    pmp.st := false.B
402    pmp.instr := false.B
403    pmp.mmio := io.static_pm.bits
404  }
405
406  val s2_is_prefetch = io.in.bits.isSoftPrefetch
407
408  // exception that may cause load addr to be invalid / illegal
409  //
410  // if such exception happen, that inst and its exception info
411  // will be force writebacked to rob
412  val s2_exception_vec = WireInit(io.in.bits.uop.cf.exceptionVec)
413  s2_exception_vec(loadAccessFault) := io.in.bits.uop.cf.exceptionVec(loadAccessFault) || pmp.ld
414  // soft prefetch will not trigger any exception (but ecc error interrupt may be triggered)
415  when (s2_is_prefetch) {
416    s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
417  }
418  val s2_exception = ExceptionNO.selectByFu(s2_exception_vec, lduCfg).asUInt.orR && !io.in.bits.tlbMiss // ????????
419
420  // writeback access fault caused by ecc error / bus error
421  //
422  // * ecc data error is slow to generate, so we will not use it until load stage 3
423  // * in load stage 3, an extra signal io.load_error will be used to
424
425  // now cache ecc error will raise an access fault
426  // at the same time, error info (including error paddr) will be write to
427  // an customized CSR "CACHE_ERROR"
428  if (EnableAccurateLoadError) {
429    io.s3_delayed_load_error := io.dcacheResp.bits.error_delayed &&
430      io.csrCtrl.cache_error_enable &&
431      RegNext(io.out.valid)
432  } else {
433    io.s3_delayed_load_error := false.B
434  }
435
436  val actually_mmio = pmp.mmio
437  val s2_uop = io.in.bits.uop
438  val s2_mask = io.in.bits.mask
439  val s2_paddr = io.in.bits.paddr
440  val s2_tlb_miss = io.in.bits.tlbMiss
441  val s2_mmio = !s2_is_prefetch && actually_mmio && !s2_exception
442  val s2_cache_miss = io.dcacheResp.bits.miss
443  val s2_cache_replay = io.dcacheResp.bits.replay
444  val s2_cache_tag_error = io.dcacheResp.bits.tag_error
445  val s2_forward_fail = io.lsq.matchInvalid || io.sbuffer.matchInvalid
446  val s2_ldld_violation = io.loadViolationQueryResp.valid &&
447    io.loadViolationQueryResp.bits.have_violation &&
448    RegNext(io.csrCtrl.ldld_vio_check_enable)
449  val s2_data_invalid = io.lsq.dataInvalid && !s2_ldld_violation && !s2_exception
450
451  io.dcache_kill := pmp.ld || pmp.mmio // move pmp resp kill to outside
452  io.dcacheResp.ready := true.B
453  val dcacheShouldResp = !(s2_tlb_miss || s2_exception || s2_mmio || s2_is_prefetch)
454  assert(!(io.in.valid && (dcacheShouldResp && !io.dcacheResp.valid)), "DCache response got lost")
455
456  // merge forward result
457  // lsq has higher priority than sbuffer
458  val forwardMask = Wire(Vec(8, Bool()))
459  val forwardData = Wire(Vec(8, UInt(8.W)))
460
461  val fullForward = ((~forwardMask.asUInt).asUInt & s2_mask) === 0.U && !io.lsq.dataInvalid
462  io.lsq := DontCare
463  io.sbuffer := DontCare
464  io.fullForward := fullForward
465
466  // generate XLEN/8 Muxs
467  for (i <- 0 until XLEN / 8) {
468    forwardMask(i) := io.lsq.forwardMask(i) || io.sbuffer.forwardMask(i)
469    forwardData(i) := Mux(io.lsq.forwardMask(i), io.lsq.forwardData(i), io.sbuffer.forwardData(i))
470  }
471
472  XSDebug(io.out.fire, "[FWD LOAD RESP] pc %x fwd %x(%b) + %x(%b)\n",
473    s2_uop.cf.pc,
474    io.lsq.forwardData.asUInt, io.lsq.forwardMask.asUInt,
475    io.in.bits.forwardData.asUInt, io.in.bits.forwardMask.asUInt
476  )
477
478  // data merge
479  // val rdataVec = VecInit((0 until XLEN / 8).map(j =>
480  //   Mux(forwardMask(j), forwardData(j), io.dcacheResp.bits.data(8*(j+1)-1, 8*j))
481  // )) // s2_rdataVec will be write to load queue
482  // val rdata = rdataVec.asUInt
483  // val rdataSel = LookupTree(s2_paddr(2, 0), List(
484  //   "b000".U -> rdata(63, 0),
485  //   "b001".U -> rdata(63, 8),
486  //   "b010".U -> rdata(63, 16),
487  //   "b011".U -> rdata(63, 24),
488  //   "b100".U -> rdata(63, 32),
489  //   "b101".U -> rdata(63, 40),
490  //   "b110".U -> rdata(63, 48),
491  //   "b111".U -> rdata(63, 56)
492  // ))
493  // val rdataPartialLoad = rdataHelper(s2_uop, rdataSel) // s2_rdataPartialLoad is not used
494
495  io.out.valid := io.in.valid && !s2_tlb_miss && !s2_data_invalid && !io.needReExecute
496  // write_lq_safe is needed by dup logic
497  // io.write_lq_safe := !s2_tlb_miss && !s2_data_invalid
498  // Inst will be canceled in store queue / lsq,
499  // so we do not need to care about flush in load / store unit's out.valid
500  io.out.bits := io.in.bits
501  // io.out.bits.data := rdataPartialLoad
502  io.out.bits.data := 0.U // data will be generated in load_s3
503  // when exception occurs, set it to not miss and let it write back to rob (via int port)
504  if (EnableFastForward) {
505    io.out.bits.miss := s2_cache_miss &&
506      !s2_exception &&
507      !fullForward &&
508      !s2_is_prefetch
509  } else {
510    io.out.bits.miss := s2_cache_miss &&
511      !s2_exception &&
512      !s2_is_prefetch
513  }
514  io.out.bits.uop.ctrl.fpWen := io.in.bits.uop.ctrl.fpWen && !s2_exception
515
516  io.loadDataFromDcache.bankedDcacheData := io.dcacheResp.bits.bank_data
517  io.loadDataFromDcache.bank_oh := io.dcacheResp.bits.bank_oh
518  // io.loadDataFromDcache.dcacheData := io.dcacheResp.bits.data
519  io.loadDataFromDcache.forwardMask := forwardMask
520  io.loadDataFromDcache.forwardData := forwardData
521  io.loadDataFromDcache.uop := io.out.bits.uop
522  io.loadDataFromDcache.addrOffset := s2_paddr(2, 0)
523
524  io.s2_can_replay_from_fetch := !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
525  // if forward fail, replay this inst from fetch
526  val debug_forwardFailReplay = s2_forward_fail && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
527  // if ld-ld violation is detected, replay from this inst from fetch
528  val debug_ldldVioReplay = s2_ldld_violation && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
529  // io.out.bits.uop.ctrl.replayInst := false.B
530
531  io.out.bits.mmio := s2_mmio
532  io.out.bits.uop.ctrl.flushPipe := s2_mmio && io.sentFastUop
533  io.out.bits.uop.cf.exceptionVec := s2_exception_vec // cache error not included
534
535  // For timing reasons, sometimes we can not let
536  // io.out.bits.miss := s2_cache_miss && !s2_exception && !fullForward
537  // We use io.dataForwarded instead. It means:
538  // 1. Forward logic have prepared all data needed,
539  //    and dcache query is no longer needed.
540  // 2. ... or data cache tag error is detected, this kind of inst
541  //    will not update miss queue. That is to say, if miss, that inst
542  //    may not be refilled
543  // Such inst will be writebacked from load queue.
544  io.dataForwarded := s2_cache_miss && !s2_exception &&
545    (fullForward || io.csrCtrl.cache_error_enable && s2_cache_tag_error)
546  // io.out.bits.forwardX will be send to lq
547  io.out.bits.forwardMask := forwardMask
548  // data from dcache is not included in io.out.bits.forwardData
549  io.out.bits.forwardData := forwardData
550
551  io.in.ready := io.out.ready || !io.in.valid
552
553
554  // st-ld violation query
555  val needReExecuteVec = Wire(Vec(StorePipelineWidth, Bool()))
556  val needReExecute = Wire(Bool())
557
558  for (i <- 0 until StorePipelineWidth) {
559    //  NeedFastRecovery Valid when
560    //  1. Fast recovery query request Valid.
561    //  2. Load instruction is younger than requestors(store instructions).
562    //  3. Physical address match.
563    //  4. Data contains.
564    needReExecuteVec(i) := io.reExecuteQuery(i).valid &&
565                              isAfter(io.in.bits.uop.robIdx, io.reExecuteQuery(i).bits.robIdx) &&
566                              !s2_tlb_miss &&
567                              (s2_paddr(PAddrBits-1,3) === io.reExecuteQuery(i).bits.paddr(PAddrBits-1, 3)) &&
568                              (s2_mask & io.reExecuteQuery(i).bits.mask).orR
569  }
570  needReExecute := needReExecuteVec.asUInt.orR
571  io.needReExecute := needReExecute
572
573  // feedback tlb result to RS
574  io.rsFeedback.valid := false.B
575  val s2_need_replay_from_rs = Wire(Bool())
576  if (EnableFastForward) {
577    s2_need_replay_from_rs :=
578      needReExecute ||
579      s2_tlb_miss || // replay if dtlb miss
580      s2_cache_replay && !s2_is_prefetch && !s2_mmio && !s2_exception && !fullForward || // replay if dcache miss queue full / busy
581      s2_data_invalid && !s2_is_prefetch // replay if store to load forward data is not ready
582  } else {
583    // Note that if all parts of data are available in sq / sbuffer, replay required by dcache will not be scheduled
584    s2_need_replay_from_rs :=
585      needReExecute ||
586      s2_tlb_miss || // replay if dtlb miss
587      s2_cache_replay && !s2_is_prefetch && !s2_mmio && !s2_exception && !io.dataForwarded || // replay if dcache miss queue full / busy
588      s2_data_invalid && !s2_is_prefetch // replay if store to load forward data is not ready
589  }
590  io.rsFeedback.bits.hit := !s2_need_replay_from_rs
591  io.rsFeedback.bits.rsIdx := io.in.bits.rsIdx
592  io.rsFeedback.bits.flushState := io.in.bits.ptwBack
593  // feedback source priority: tlbMiss > dataInvalid > mshrFull
594  // general case priority: tlbMiss > exception (include forward_fail / ldld_violation) > mmio > dataInvalid > mshrFull > normal miss / hit
595  io.rsFeedback.bits.sourceType := Mux(s2_tlb_miss, RSFeedbackType.tlbMiss,
596    Mux(s2_data_invalid,
597      RSFeedbackType.dataInvalid,
598      RSFeedbackType.mshrFull
599    )
600  )
601  io.rsFeedback.bits.dataInvalidSqIdx.value := io.dataInvalidSqIdx
602  io.rsFeedback.bits.dataInvalidSqIdx.flag := DontCare
603
604  io.replaySlow.valid := io.in.valid
605  io.replaySlow.tlb_hited := !s2_tlb_miss
606  io.replaySlow.st_ld_check_ok := !needReExecute
607  if (EnableFastForward) {
608    io.replaySlow.cache_no_replay := !s2_cache_replay || s2_is_prefetch || s2_mmio || s2_exception || fullForward
609  }else {
610    io.replaySlow.cache_no_replay := !s2_cache_replay || s2_is_prefetch || s2_mmio || s2_exception || io.dataForwarded
611  }
612  io.replaySlow.forward_data_valid := !s2_data_invalid || s2_is_prefetch
613  io.replaySlow.ld_idx := io.in.bits.uop.lqIdx.value
614  io.replaySlow.data_invalid_sq_idx := io.dataInvalidSqIdx
615
616  // s2_cache_replay is quite slow to generate, send it separately to LQ
617  if (EnableFastForward) {
618    io.s2_dcache_require_replay := s2_cache_replay && !fullForward
619  } else {
620    io.s2_dcache_require_replay := s2_cache_replay &&
621      s2_need_replay_from_rs &&
622      !io.dataForwarded &&
623      !s2_is_prefetch &&
624      io.out.bits.miss
625  }
626
627  XSPerfAccumulate("in_valid", io.in.valid)
628  XSPerfAccumulate("in_fire", io.in.fire)
629  XSPerfAccumulate("in_fire_first_issue", io.in.fire && io.in.bits.isFirstIssue)
630  XSPerfAccumulate("dcache_miss", io.in.fire && s2_cache_miss)
631  XSPerfAccumulate("dcache_miss_first_issue", io.in.fire && s2_cache_miss && io.in.bits.isFirstIssue)
632  XSPerfAccumulate("full_forward", io.in.valid && fullForward)
633  XSPerfAccumulate("dcache_miss_full_forward", io.in.valid && s2_cache_miss && fullForward)
634  XSPerfAccumulate("replay",  io.rsFeedback.valid && !io.rsFeedback.bits.hit)
635  XSPerfAccumulate("replay_tlb_miss", io.rsFeedback.valid && !io.rsFeedback.bits.hit && s2_tlb_miss)
636  XSPerfAccumulate("replay_cache", io.rsFeedback.valid && !io.rsFeedback.bits.hit && !s2_tlb_miss && s2_cache_replay)
637  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready)
638  XSPerfAccumulate("replay_from_fetch_forward", io.out.valid && debug_forwardFailReplay)
639  XSPerfAccumulate("replay_from_fetch_load_vio", io.out.valid && debug_ldldVioReplay)
640
641  XSPerfAccumulate("replay_lq",  io.replaySlow.valid && (!io.replaySlow.tlb_hited || !io.replaySlow.cache_no_replay || !io.replaySlow.forward_data_valid))
642  XSPerfAccumulate("replay_tlb_miss_lq", io.replaySlow.valid && !io.replaySlow.tlb_hited)
643  XSPerfAccumulate("replay_sl_vio", io.replaySlow.valid && io.replaySlow.tlb_hited && !io.replaySlow.st_ld_check_ok)
644  XSPerfAccumulate("replay_cache_lq", io.replaySlow.valid && io.replaySlow.tlb_hited && io.replaySlow.st_ld_check_ok && !io.replaySlow.cache_no_replay)
645}
646
647class LoadUnit(implicit p: Parameters) extends XSModule
648  with HasLoadHelper
649  with HasPerfEvents
650  with HasDCacheParameters
651{
652  val io = IO(new Bundle() {
653    val ldin = Flipped(Decoupled(new ExuInput))
654    val ldout = Decoupled(new ExuOutput)
655    val redirect = Flipped(ValidIO(new Redirect))
656    val feedbackSlow = ValidIO(new RSFeedback)
657    val feedbackFast = ValidIO(new RSFeedback)
658    val rsIdx = Input(UInt(log2Up(IssQueSize).W))
659    val isFirstIssue = Input(Bool())
660    val dcache = new DCacheLoadIO
661    val sbuffer = new LoadForwardQueryIO
662    val lsq = new LoadToLsqIO
663    val refill = Flipped(ValidIO(new Refill))
664    val fastUop = ValidIO(new MicroOp) // early wakeup signal generated in load_s1, send to RS in load_s2
665    val trigger = Vec(3, new LoadUnitTriggerIO)
666
667    val tlb = new TlbRequestIO(2)
668    val pmp = Flipped(new PMPRespBundle()) // arrive same to tlb now
669
670    val fastpathOut = Output(new LoadToLoadIO)
671    val fastpathIn = Input(new LoadToLoadIO)
672    val loadFastMatch = Input(Bool())
673    val loadFastImm = Input(UInt(12.W))
674
675    val s3_delayed_load_error = Output(Bool()) // load ecc error
676    // Note that io.s3_delayed_load_error and io.lsq.s3_delayed_load_error is different
677
678    val csrCtrl = Flipped(new CustomCSRCtrlIO)
679    val reExecuteQuery = Flipped(Vec(StorePipelineWidth, Valid(new LoadReExecuteQueryIO)))    // load replay
680    val lsqOut = Flipped(Decoupled(new LsPipelineBundle))
681  })
682
683  val load_s0 = Module(new LoadUnit_S0)
684  val load_s1 = Module(new LoadUnit_S1)
685  val load_s2 = Module(new LoadUnit_S2)
686
687  load_s0.io.lsqOut <> io.lsqOut
688
689  // load s0
690  load_s0.io.in <> io.ldin
691  load_s0.io.dtlbReq <> io.tlb.req
692  load_s0.io.dcacheReq <> io.dcache.req
693  load_s0.io.rsIdx := io.rsIdx
694  load_s0.io.isFirstIssue := io.isFirstIssue
695  load_s0.io.s0_kill := false.B
696  // we try pointerchasing when (1. no rs-issued load and 2. no LSQ replayed load)
697  val s0_tryPointerChasing = !io.ldin.valid && !io.lsqOut.valid && io.fastpathIn.valid
698  val s0_pointerChasingVAddr = io.fastpathIn.data(5, 0) +& io.loadFastImm(5, 0)
699  load_s0.io.fastpath.valid := io.fastpathIn.valid
700  load_s0.io.fastpath.data := Cat(io.fastpathIn.data(XLEN-1, 6), s0_pointerChasingVAddr(5,0))
701
702  val s1_data = PipelineConnect(load_s0.io.out, load_s1.io.in, true.B,
703    load_s0.io.out.bits.uop.robIdx.needFlush(io.redirect) && !s0_tryPointerChasing).get
704
705  // load s1
706  // update s1_kill when any source has valid request
707  load_s1.io.s1_kill := RegEnable(load_s0.io.s0_kill, false.B, io.ldin.valid || io.lsqOut.valid || io.fastpathIn.valid)
708  io.tlb.req_kill := load_s1.io.s1_kill
709  load_s1.io.dtlbResp <> io.tlb.resp
710  io.dcache.s1_paddr_dup_lsu <> load_s1.io.lsuPAddr
711  io.dcache.s1_paddr_dup_dcache <> load_s1.io.dcachePAddr
712  io.dcache.s1_kill := load_s1.io.dcacheKill
713  load_s1.io.sbuffer <> io.sbuffer
714  load_s1.io.lsq <> io.lsq.forward
715  load_s1.io.loadViolationQueryReq <> io.lsq.loadViolationQuery.req
716  load_s1.io.dcacheBankConflict <> io.dcache.s1_bank_conflict
717  load_s1.io.csrCtrl <> io.csrCtrl
718  load_s1.io.reExecuteQuery := io.reExecuteQuery
719  // provide paddr and vaddr for lq
720  io.lsq.loadPaddrIn.valid := load_s1.io.out.valid
721  io.lsq.loadPaddrIn.bits.lqIdx := load_s1.io.out.bits.uop.lqIdx
722  io.lsq.loadPaddrIn.bits.paddr := load_s1.io.lsuPAddr
723
724  io.lsq.loadVaddrIn.valid := load_s1.io.in.valid && !load_s1.io.s1_kill
725  io.lsq.loadVaddrIn.bits.lqIdx := load_s1.io.out.bits.uop.lqIdx
726  io.lsq.loadVaddrIn.bits.vaddr := load_s1.io.out.bits.vaddr
727
728  // when S0 has opportunity to try pointerchasing, make sure it truely goes to S1
729  // which is S0's out is ready and dcache is ready
730  val s0_doTryPointerChasing = s0_tryPointerChasing && load_s0.io.out.ready && load_s0.io.dcacheReq.ready
731  val s1_tryPointerChasing = RegNext(s0_doTryPointerChasing, false.B)
732  val s1_pointerChasingVAddr = RegEnable(s0_pointerChasingVAddr, s0_doTryPointerChasing)
733  val cancelPointerChasing = WireInit(false.B)
734  if (EnableLoadToLoadForward) {
735    // Sometimes, we need to cancel the load-load forwarding.
736    // These can be put at S0 if timing is bad at S1.
737    // Case 0: CACHE_SET(base + offset) != CACHE_SET(base) (lowest 6-bit addition has an overflow)
738    val addressMisMatch = s1_pointerChasingVAddr(6) || RegEnable(io.loadFastImm(11, 6).orR, s0_doTryPointerChasing)
739    // Case 1: the address is not 64-bit aligned or the fuOpType is not LD
740    val addressNotAligned = s1_pointerChasingVAddr(2, 0).orR
741    val fuOpTypeIsNotLd = io.ldin.bits.uop.ctrl.fuOpType =/= LSUOpType.ld
742    // Case 2: this is not a valid load-load pair
743    val notFastMatch = RegEnable(!io.loadFastMatch, s0_tryPointerChasing)
744    // Case 3: this load-load uop is cancelled
745    val isCancelled = !io.ldin.valid
746    when (s1_tryPointerChasing) {
747      cancelPointerChasing := addressMisMatch || addressNotAligned || fuOpTypeIsNotLd || notFastMatch || isCancelled
748      load_s1.io.in.bits.uop := io.ldin.bits.uop
749      val spec_vaddr = s1_data.vaddr
750      val vaddr = Cat(spec_vaddr(VAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W))
751      load_s1.io.in.bits.vaddr := vaddr
752      load_s1.io.in.bits.rsIdx := io.rsIdx
753      load_s1.io.in.bits.isFirstIssue := io.isFirstIssue
754      // We need to replace vaddr(5, 3).
755      val spec_paddr = io.tlb.resp.bits.paddr(0)
756      load_s1.io.dtlbResp.bits.paddr.foreach(_ := Cat(spec_paddr(PAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W)))
757    }
758    when (cancelPointerChasing) {
759      load_s1.io.s1_kill := true.B
760    }.otherwise {
761      load_s0.io.s0_kill := s1_tryPointerChasing
762      when (s1_tryPointerChasing) {
763        io.ldin.ready := true.B
764      }
765    }
766
767    XSPerfAccumulate("load_to_load_forward", s1_tryPointerChasing && !cancelPointerChasing)
768    XSPerfAccumulate("load_to_load_forward_try", s1_tryPointerChasing)
769    XSPerfAccumulate("load_to_load_forward_fail", cancelPointerChasing)
770    XSPerfAccumulate("load_to_load_forward_fail_cancelled", cancelPointerChasing && isCancelled)
771    XSPerfAccumulate("load_to_load_forward_fail_wakeup_mismatch", cancelPointerChasing && !isCancelled && notFastMatch)
772    XSPerfAccumulate("load_to_load_forward_fail_op_not_ld",
773      cancelPointerChasing && !isCancelled && !notFastMatch && fuOpTypeIsNotLd)
774    XSPerfAccumulate("load_to_load_forward_fail_addr_align",
775      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && addressNotAligned)
776    XSPerfAccumulate("load_to_load_forward_fail_set_mismatch",
777      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && !addressNotAligned && addressMisMatch)
778  }
779  PipelineConnect(load_s1.io.out, load_s2.io.in, true.B,
780    load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect) || cancelPointerChasing)
781
782
783  // load s2
784  io.dcache.s2_kill := load_s2.io.dcache_kill // to kill mmio resp which are redirected
785  load_s2.io.dcacheResp <> io.dcache.resp
786  load_s2.io.pmpResp <> io.pmp
787  load_s2.io.static_pm := RegNext(io.tlb.resp.bits.static_pm)
788  load_s2.io.lsq.forwardData <> io.lsq.forward.forwardData
789  load_s2.io.lsq.forwardMask <> io.lsq.forward.forwardMask
790  load_s2.io.lsq.forwardMaskFast <> io.lsq.forward.forwardMaskFast // should not be used in load_s2
791  load_s2.io.lsq.dataInvalid <> io.lsq.forward.dataInvalid
792  load_s2.io.lsq.matchInvalid <> io.lsq.forward.matchInvalid
793  load_s2.io.sbuffer.forwardData <> io.sbuffer.forwardData
794  load_s2.io.sbuffer.forwardMask <> io.sbuffer.forwardMask
795  load_s2.io.sbuffer.forwardMaskFast <> io.sbuffer.forwardMaskFast // should not be used in load_s2
796  load_s2.io.sbuffer.dataInvalid <> io.sbuffer.dataInvalid // always false
797  load_s2.io.sbuffer.matchInvalid <> io.sbuffer.matchInvalid
798  load_s2.io.dataForwarded <> io.lsq.s2_load_data_forwarded
799  load_s2.io.dataInvalidSqIdx := io.lsq.forward.dataInvalidSqIdx // provide dataInvalidSqIdx to make wakeup faster
800  load_s2.io.loadViolationQueryResp <> io.lsq.loadViolationQuery.resp
801  load_s2.io.csrCtrl <> io.csrCtrl
802  load_s2.io.sentFastUop := io.fastUop.valid
803  load_s2.io.reExecuteQuery := io.reExecuteQuery
804  // feedback bank conflict / ld-vio check struct hazard to rs
805  io.feedbackFast.bits := RegNext(load_s1.io.rsFeedback.bits)
806  io.feedbackFast.valid := RegNext(load_s1.io.rsFeedback.valid && !load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect))
807
808  // pre-calcuate sqIdx mask in s0, then send it to lsq in s1 for forwarding
809  val sqIdxMaskReg = RegNext(UIntToMask(load_s0.io.s0_sqIdx.value, StoreQueueSize))
810  // to enable load-load, sqIdxMask must be calculated based on ldin.uop
811  // If the timing here is not OK, load-load forwarding has to be disabled.
812  // Or we calculate sqIdxMask at RS??
813  io.lsq.forward.sqIdxMask := sqIdxMaskReg
814  if (EnableLoadToLoadForward) {
815    when (s1_tryPointerChasing) {
816      io.lsq.forward.sqIdxMask := UIntToMask(io.ldin.bits.uop.sqIdx.value, StoreQueueSize)
817    }
818  }
819
820  // // use s2_hit_way to select data received in s1
821  // load_s2.io.dcacheResp.bits.data := Mux1H(RegNext(io.dcache.s1_hit_way), RegNext(io.dcache.s1_data))
822  // assert(load_s2.io.dcacheResp.bits.data === io.dcache.resp.bits.data)
823
824  // now io.fastUop.valid is sent to RS in load_s2
825  val s2_dcache_hit = io.dcache.s2_hit // dcache hit dup in lsu side
826
827  io.fastUop.valid := RegNext(
828      !io.dcache.s1_disable_fast_wakeup &&  // load fast wakeup should be disabled when dcache data read is not ready
829      load_s1.io.in.valid && // valid load request
830      !load_s1.io.s1_kill && // killed by load-load forwarding
831      !load_s1.io.dtlbResp.bits.fast_miss && // not mmio or tlb miss, pf / af not included here
832      !io.lsq.forward.dataInvalidFast // forward failed
833    ) &&
834    !RegNext(load_s1.io.needLdVioCheckRedo) && // load-load violation check: load paddr cam struct hazard
835    !RegNext(load_s1.io.needReExecute) &&
836    !RegNext(load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) &&
837    (load_s2.io.in.valid && !load_s2.io.needReExecute && s2_dcache_hit) // dcache hit in lsu side
838
839  io.fastUop.bits := RegNext(load_s1.io.out.bits.uop)
840
841  XSDebug(load_s0.io.out.valid,
842    p"S0: pc ${Hexadecimal(load_s0.io.out.bits.uop.cf.pc)}, lId ${Hexadecimal(load_s0.io.out.bits.uop.lqIdx.asUInt)}, " +
843    p"vaddr ${Hexadecimal(load_s0.io.out.bits.vaddr)}, mask ${Hexadecimal(load_s0.io.out.bits.mask)}\n")
844  XSDebug(load_s1.io.out.valid,
845    p"S1: pc ${Hexadecimal(load_s1.io.out.bits.uop.cf.pc)}, lId ${Hexadecimal(load_s1.io.out.bits.uop.lqIdx.asUInt)}, tlb_miss ${io.tlb.resp.bits.miss}, " +
846    p"paddr ${Hexadecimal(load_s1.io.out.bits.paddr)}, mmio ${load_s1.io.out.bits.mmio}\n")
847
848  // writeback to LSQ
849  // Current dcache use MSHR
850  // Load queue will be updated at s2 for both hit/miss int/fp load
851  io.lsq.loadIn.valid := load_s2.io.out.valid
852  // generate LqWriteBundle from LsPipelineBundle
853  io.lsq.loadIn.bits.fromLsPipelineBundle(load_s2.io.out.bits)
854
855  io.lsq.replayFast := load_s1.io.replayFast
856  io.lsq.replaySlow := load_s2.io.replaySlow
857  io.lsq.replaySlow.valid := load_s2.io.replaySlow.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)
858
859  // generate duplicated load queue data wen
860  val load_s2_valid_vec = RegInit(0.U(6.W))
861  val load_s2_leftFire = load_s1.io.out.valid && load_s2.io.in.ready
862  // val write_lq_safe = load_s2.io.write_lq_safe
863  load_s2_valid_vec := 0x0.U(6.W)
864  when (load_s2_leftFire) { load_s2_valid_vec := 0x3f.U(6.W)}
865  when (load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) { load_s2_valid_vec := 0x0.U(6.W) }
866  assert(RegNext(load_s2.io.in.valid === load_s2_valid_vec(0)))
867  io.lsq.loadIn.bits.lq_data_wen_dup := load_s2_valid_vec.asBools()
868
869  // s2_dcache_require_replay signal will be RegNexted, then used in s3
870  io.lsq.s2_dcache_require_replay := load_s2.io.s2_dcache_require_replay
871
872  // write to rob and writeback bus
873  val s2_wb_valid = load_s2.io.out.valid && !load_s2.io.out.bits.miss && !load_s2.io.out.bits.mmio
874
875  // Int load, if hit, will be writebacked at s2
876  val hitLoadOut = Wire(Valid(new ExuOutput))
877  hitLoadOut.valid := s2_wb_valid
878  hitLoadOut.bits.uop := load_s2.io.out.bits.uop
879  hitLoadOut.bits.data := load_s2.io.out.bits.data
880  hitLoadOut.bits.redirectValid := false.B
881  hitLoadOut.bits.redirect := DontCare
882  hitLoadOut.bits.debug.isMMIO := load_s2.io.out.bits.mmio
883  hitLoadOut.bits.debug.isPerfCnt := false.B
884  hitLoadOut.bits.debug.paddr := load_s2.io.out.bits.paddr
885  hitLoadOut.bits.debug.vaddr := load_s2.io.out.bits.vaddr
886  hitLoadOut.bits.fflags := DontCare
887
888  load_s2.io.out.ready := true.B
889
890  // load s3
891  val s3_load_wb_meta_reg = RegNext(Mux(hitLoadOut.valid, hitLoadOut.bits, io.lsq.ldout.bits))
892
893  // data from load queue refill
894  val s3_loadDataFromLQ = RegEnable(io.lsq.ldRawData, io.lsq.ldout.valid)
895  val s3_rdataLQ = s3_loadDataFromLQ.mergedData()
896  val s3_rdataSelLQ = LookupTree(s3_loadDataFromLQ.addrOffset, List(
897    "b000".U -> s3_rdataLQ(63, 0),
898    "b001".U -> s3_rdataLQ(63, 8),
899    "b010".U -> s3_rdataLQ(63, 16),
900    "b011".U -> s3_rdataLQ(63, 24),
901    "b100".U -> s3_rdataLQ(63, 32),
902    "b101".U -> s3_rdataLQ(63, 40),
903    "b110".U -> s3_rdataLQ(63, 48),
904    "b111".U -> s3_rdataLQ(63, 56)
905  ))
906  val s3_rdataPartialLoadLQ = rdataHelper(s3_loadDataFromLQ.uop, s3_rdataSelLQ)
907
908  // data from dcache hit
909  val s3_loadDataFromDcache = RegEnable(load_s2.io.loadDataFromDcache, load_s2.io.in.valid)
910  val s3_rdataDcache = s3_loadDataFromDcache.mergedData()
911  val s3_rdataSelDcache = LookupTree(s3_loadDataFromDcache.addrOffset, List(
912    "b000".U -> s3_rdataDcache(63, 0),
913    "b001".U -> s3_rdataDcache(63, 8),
914    "b010".U -> s3_rdataDcache(63, 16),
915    "b011".U -> s3_rdataDcache(63, 24),
916    "b100".U -> s3_rdataDcache(63, 32),
917    "b101".U -> s3_rdataDcache(63, 40),
918    "b110".U -> s3_rdataDcache(63, 48),
919    "b111".U -> s3_rdataDcache(63, 56)
920  ))
921  val s3_rdataPartialLoadDcache = rdataHelper(s3_loadDataFromDcache.uop, s3_rdataSelDcache)
922
923  io.ldout.bits := s3_load_wb_meta_reg
924  io.ldout.bits.data := Mux(RegNext(hitLoadOut.valid), s3_rdataPartialLoadDcache, s3_rdataPartialLoadLQ)
925  io.ldout.valid := RegNext(hitLoadOut.valid) && !RegNext(load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)) ||
926    RegNext(io.lsq.ldout.valid) && !RegNext(io.lsq.ldout.bits.uop.robIdx.needFlush(io.redirect)) && !RegNext(hitLoadOut.valid)
927
928  io.ldout.bits.uop.cf.exceptionVec(loadAccessFault) := s3_load_wb_meta_reg.uop.cf.exceptionVec(loadAccessFault) ||
929    RegNext(hitLoadOut.valid) && load_s2.io.s3_delayed_load_error
930
931  // fast load to load forward
932  io.fastpathOut.valid := RegNext(load_s2.io.out.valid) // for debug only
933  io.fastpathOut.data := s3_loadDataFromDcache.mergedData() // fastpath is for ld only
934
935  // feedback tlb miss / dcache miss queue full
936  io.feedbackSlow.bits := RegNext(load_s2.io.rsFeedback.bits)
937  io.feedbackSlow.valid := RegNext(load_s2.io.rsFeedback.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect))
938  // If replay is reported at load_s1, inst will be canceled (will not enter load_s2),
939  // in that case:
940  // * replay should not be reported twice
941  assert(!(RegNext(io.feedbackFast.valid) && io.feedbackSlow.valid))
942  // * io.fastUop.valid should not be reported
943  assert(!RegNext(io.feedbackFast.valid && !io.feedbackFast.bits.hit && io.fastUop.valid))
944
945  // load forward_fail/ldld_violation check
946  // check for inst in load pipeline
947  val s3_forward_fail = RegNext(io.lsq.forward.matchInvalid || io.sbuffer.matchInvalid)
948  val s3_ldld_violation = RegNext(
949    io.lsq.loadViolationQuery.resp.valid &&
950    io.lsq.loadViolationQuery.resp.bits.have_violation &&
951    RegNext(io.csrCtrl.ldld_vio_check_enable)
952  )
953  val s3_need_replay_from_fetch = s3_forward_fail || s3_ldld_violation
954  val s3_can_replay_from_fetch = RegEnable(load_s2.io.s2_can_replay_from_fetch, load_s2.io.out.valid)
955  // 1) use load pipe check result generated in load_s3 iff load_hit
956  when (RegNext(hitLoadOut.valid)) {
957    io.ldout.bits.uop.ctrl.replayInst := s3_need_replay_from_fetch
958  }
959  // 2) otherwise, write check result to load queue
960  io.lsq.s3_replay_from_fetch := s3_need_replay_from_fetch && s3_can_replay_from_fetch
961
962  // s3_delayed_load_error path is not used for now, as we writeback load result in load_s3
963  // but we keep this path for future use
964  io.s3_delayed_load_error := false.B
965  io.lsq.s3_delayed_load_error := false.B //load_s2.io.s3_delayed_load_error
966
967  io.lsq.ldout.ready := !hitLoadOut.valid
968
969  when(io.feedbackSlow.valid && !io.feedbackSlow.bits.hit){
970    // when need replay from rs, inst should not be writebacked to rob
971    assert(RegNext(!hitLoadOut.valid))
972    assert(RegNext(!io.lsq.loadIn.valid) || RegNext(load_s2.io.s2_dcache_require_replay))
973  }
974
975  val lastValidData = RegEnable(io.ldout.bits.data, io.ldout.fire)
976  val hitLoadAddrTriggerHitVec = Wire(Vec(3, Bool()))
977  val lqLoadAddrTriggerHitVec = io.lsq.trigger.lqLoadAddrTriggerHitVec
978  (0 until 3).map{i => {
979    val tdata2 = io.trigger(i).tdata2
980    val matchType = io.trigger(i).matchType
981    val tEnable = io.trigger(i).tEnable
982
983    hitLoadAddrTriggerHitVec(i) := TriggerCmp(load_s2.io.out.bits.vaddr, tdata2, matchType, tEnable)
984    io.trigger(i).addrHit := Mux(hitLoadOut.valid, hitLoadAddrTriggerHitVec(i), lqLoadAddrTriggerHitVec(i))
985    io.trigger(i).lastDataHit := TriggerCmp(lastValidData, tdata2, matchType, tEnable)
986  }}
987  io.lsq.trigger.hitLoadAddrTriggerHitVec := hitLoadAddrTriggerHitVec
988
989  val perfEvents = Seq(
990    ("load_s0_in_fire         ", load_s0.io.in.fire                                                                                                              ),
991    ("load_to_load_forward    ", load_s1.io.out.valid && s1_tryPointerChasing && !cancelPointerChasing                                                           ),
992    ("stall_dcache            ", load_s0.io.out.valid && load_s0.io.out.ready && !load_s0.io.dcacheReq.ready                                                     ),
993    ("load_s1_in_fire         ", load_s1.io.in.fire                                                                                                              ),
994    ("load_s1_tlb_miss        ", load_s1.io.in.fire && load_s1.io.dtlbResp.bits.miss                                                                             ),
995    ("load_s2_in_fire         ", load_s2.io.in.fire                                                                                                              ),
996    ("load_s2_dcache_miss     ", load_s2.io.in.fire && load_s2.io.dcacheResp.bits.miss                                                                           ),
997    ("load_s2_replay          ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit                                                                  ),
998    ("load_s2_replay_tlb_miss ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit && load_s2.io.in.bits.tlbMiss                                    ),
999    ("load_s2_replay_cache    ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit && !load_s2.io.in.bits.tlbMiss && load_s2.io.dcacheResp.bits.miss),
1000  )
1001  generatePerfEvent()
1002
1003  when(io.ldout.fire){
1004    XSDebug("ldout %x\n", io.ldout.bits.uop.cf.pc)
1005  }
1006}
1007