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