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