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