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