xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/LoadUnit.scala (revision ccfddc82986614e4679393c87bca4127b2662b8d)
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 xiangshan.ExceptionNO._
24import xiangshan._
25import xiangshan.backend.fu.PMPRespBundle
26import xiangshan.cache._
27import xiangshan.cache.mmu.{TlbCmd, TlbReq, TlbRequestIO, TlbResp}
28
29class LoadToLsqIO(implicit p: Parameters) extends XSBundle {
30  val loadIn = ValidIO(new LqWriteBundle)
31  val ldout = Flipped(DecoupledIO(new ExuOutput))
32  val s2_load_data_forwarded = Output(Bool())
33  val s3_delayed_load_error = Output(Bool())
34  val s3_dcache_require_replay = Output(Bool())
35  val forward = new PipeLoadForwardQueryIO
36  val loadViolationQuery = new LoadViolationQueryIO
37  val trigger = Flipped(new LqTriggerIO)
38}
39
40class LoadToLoadIO(implicit p: Parameters) extends XSBundle {
41  // load to load fast path is limited to ld (64 bit) used as vaddr src1 only
42  val data = UInt(XLEN.W)
43  val valid = Bool()
44}
45
46class LoadUnitTriggerIO(implicit p: Parameters) extends XSBundle {
47  val tdata2 = Input(UInt(64.W))
48  val matchType = Input(UInt(2.W))
49  val tEnable = Input(Bool()) // timing is calculated before this
50  val addrHit = Output(Bool())
51  val lastDataHit = Output(Bool())
52}
53
54// Load Pipeline Stage 0
55// Generate addr, use addr to query DCache and DTLB
56class LoadUnit_S0(implicit p: Parameters) extends XSModule with HasDCacheParameters{
57  val io = IO(new Bundle() {
58    val in = Flipped(Decoupled(new ExuInput))
59    val out = Decoupled(new LsPipelineBundle)
60    val dtlbReq = DecoupledIO(new TlbReq)
61    val dcacheReq = DecoupledIO(new DCacheWordReq)
62    val rsIdx = Input(UInt(log2Up(IssQueSize).W))
63    val isFirstIssue = Input(Bool())
64    val fastpath = Input(new LoadToLoadIO)
65    val s0_kill = Input(Bool())
66  })
67  require(LoadPipelineWidth == exuParameters.LduCnt)
68
69  val imm12 = io.in.bits.uop.ctrl.imm(11, 0)
70  val s0_vaddr = WireInit(io.in.bits.src(0) + SignExt(imm12, VAddrBits))
71  val s0_mask = WireInit(genWmask(s0_vaddr, io.in.bits.uop.ctrl.fuOpType(1,0)))
72  val s0_uop = WireInit(io.in.bits.uop)
73
74  if (EnableLoadToLoadForward) {
75    // When there's no valid instruction from RS, we try the load-to-load forwarding.
76    when (!io.in.valid) {
77      s0_vaddr := io.fastpath.data
78      // Assume the pointer chasing is always ld.
79      s0_uop.ctrl.fuOpType := LSUOpType.ld
80      s0_mask := genWmask(0.U, LSUOpType.ld)
81    }
82  }
83
84  val isSoftPrefetch = LSUOpType.isPrefetch(s0_uop.ctrl.fuOpType)
85  val isSoftPrefetchRead = s0_uop.ctrl.fuOpType === LSUOpType.prefetch_r
86  val isSoftPrefetchWrite = s0_uop.ctrl.fuOpType === LSUOpType.prefetch_w
87
88  // query DTLB
89  io.dtlbReq.valid := io.in.valid || io.fastpath.valid
90  io.dtlbReq.bits.vaddr := s0_vaddr
91  io.dtlbReq.bits.cmd := TlbCmd.read
92  io.dtlbReq.bits.size := LSUOpType.size(s0_uop.ctrl.fuOpType)
93  io.dtlbReq.bits.kill := DontCare
94  io.dtlbReq.bits.debug.robIdx := s0_uop.robIdx
95  io.dtlbReq.bits.debug.pc := s0_uop.cf.pc
96  io.dtlbReq.bits.debug.isFirstIssue := io.isFirstIssue
97
98  // query DCache
99  io.dcacheReq.valid := io.in.valid || io.fastpath.valid
100  when (isSoftPrefetchRead) {
101    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_PFR
102  }.elsewhen (isSoftPrefetchWrite) {
103    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_PFW
104  }.otherwise {
105    io.dcacheReq.bits.cmd  := MemoryOpConstants.M_XRD
106  }
107  io.dcacheReq.bits.addr := s0_vaddr
108  io.dcacheReq.bits.mask := s0_mask
109  io.dcacheReq.bits.data := DontCare
110  when(isSoftPrefetch) {
111    io.dcacheReq.bits.instrtype := SOFT_PREFETCH.U
112  }.otherwise {
113    io.dcacheReq.bits.instrtype := LOAD_SOURCE.U
114  }
115
116  // TODO: update cache meta
117  io.dcacheReq.bits.id   := DontCare
118
119  val addrAligned = LookupTree(s0_uop.ctrl.fuOpType(1, 0), List(
120    "b00".U   -> true.B,                   //b
121    "b01".U   -> (s0_vaddr(0)    === 0.U), //h
122    "b10".U   -> (s0_vaddr(1, 0) === 0.U), //w
123    "b11".U   -> (s0_vaddr(2, 0) === 0.U)  //d
124  ))
125
126  io.out.valid := (io.in.valid || io.fastpath.valid) && io.dcacheReq.ready && !io.s0_kill
127
128  io.out.bits := DontCare
129  io.out.bits.vaddr := s0_vaddr
130  io.out.bits.mask := s0_mask
131  io.out.bits.uop := s0_uop
132  io.out.bits.uop.cf.exceptionVec(loadAddrMisaligned) := !addrAligned
133  io.out.bits.rsIdx := io.rsIdx
134  io.out.bits.isFirstIssue := io.isFirstIssue
135  io.out.bits.isSoftPrefetch := isSoftPrefetch
136
137  io.in.ready := !io.in.valid || (io.out.ready && io.dcacheReq.ready)
138
139  XSDebug(io.dcacheReq.fire,
140    p"[DCACHE LOAD REQ] pc ${Hexadecimal(s0_uop.cf.pc)}, vaddr ${Hexadecimal(s0_vaddr)}\n"
141  )
142  XSPerfAccumulate("in_valid", io.in.valid)
143  XSPerfAccumulate("in_fire", io.in.fire)
144  XSPerfAccumulate("in_fire_first_issue", io.in.valid && io.isFirstIssue)
145  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready && io.dcacheReq.ready)
146  XSPerfAccumulate("stall_dcache", io.out.valid && io.out.ready && !io.dcacheReq.ready)
147  XSPerfAccumulate("addr_spec_success", io.out.fire && s0_vaddr(VAddrBits-1, 12) === io.in.bits.src(0)(VAddrBits-1, 12))
148  XSPerfAccumulate("addr_spec_failed", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12))
149  XSPerfAccumulate("addr_spec_success_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) === io.in.bits.src(0)(VAddrBits-1, 12) && io.isFirstIssue)
150  XSPerfAccumulate("addr_spec_failed_once", io.out.fire && s0_vaddr(VAddrBits-1, 12) =/= io.in.bits.src(0)(VAddrBits-1, 12) && io.isFirstIssue)
151}
152
153
154// Load Pipeline Stage 1
155// TLB resp (send paddr to dcache)
156class LoadUnit_S1(implicit p: Parameters) extends XSModule {
157  val io = IO(new Bundle() {
158    val in = Flipped(Decoupled(new LsPipelineBundle))
159    val s1_kill = Input(Bool())
160    val out = Decoupled(new LsPipelineBundle)
161    val dtlbResp = Flipped(DecoupledIO(new TlbResp(2)))
162    val lsuPAddr = Output(UInt(PAddrBits.W))
163    val dcachePAddr = Output(UInt(PAddrBits.W))
164    val dcacheKill = Output(Bool())
165    val dcacheBankConflict = Input(Bool())
166    val fullForwardFast = Output(Bool())
167    val sbuffer = new LoadForwardQueryIO
168    val lsq = new PipeLoadForwardQueryIO
169    val loadViolationQueryReq = Decoupled(new LoadViolationQueryReq)
170    val rsFeedback = ValidIO(new RSFeedback)
171    val csrCtrl = Flipped(new CustomCSRCtrlIO)
172    val needLdVioCheckRedo = Output(Bool())
173  })
174
175  val s1_uop = io.in.bits.uop
176  val s1_paddr_dup_lsu = io.dtlbResp.bits.paddr(0)
177  val s1_paddr_dup_dcache = io.dtlbResp.bits.paddr(1)
178  // af & pf exception were modified below.
179  val s1_exception = ExceptionNO.selectByFu(io.out.bits.uop.cf.exceptionVec, lduCfg).asUInt.orR
180  val s1_tlb_miss = io.dtlbResp.bits.miss
181  val s1_mask = io.in.bits.mask
182  val s1_bank_conflict = io.dcacheBankConflict
183
184  io.out.bits := io.in.bits // forwardXX field will be updated in s1
185
186  io.dtlbResp.ready := true.B
187
188  io.lsuPAddr := s1_paddr_dup_lsu
189  io.dcachePAddr := s1_paddr_dup_dcache
190  //io.dcacheKill := s1_tlb_miss || s1_exception || s1_mmio
191  io.dcacheKill := s1_tlb_miss || s1_exception || io.s1_kill
192  // load forward query datapath
193  io.sbuffer.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill)
194  io.sbuffer.vaddr := io.in.bits.vaddr
195  io.sbuffer.paddr := s1_paddr_dup_lsu
196  io.sbuffer.uop := s1_uop
197  io.sbuffer.sqIdx := s1_uop.sqIdx
198  io.sbuffer.mask := s1_mask
199  io.sbuffer.pc := s1_uop.cf.pc // FIXME: remove it
200
201  io.lsq.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill)
202  io.lsq.vaddr := io.in.bits.vaddr
203  io.lsq.paddr := s1_paddr_dup_lsu
204  io.lsq.uop := s1_uop
205  io.lsq.sqIdx := s1_uop.sqIdx
206  io.lsq.sqIdxMask := DontCare // will be overwritten by sqIdxMask pre-generated in s0
207  io.lsq.mask := s1_mask
208  io.lsq.pc := s1_uop.cf.pc // FIXME: remove it
209
210  // ld-ld violation query
211  io.loadViolationQueryReq.valid := io.in.valid && !(s1_exception || s1_tlb_miss || io.s1_kill)
212  io.loadViolationQueryReq.bits.paddr := s1_paddr_dup_lsu
213  io.loadViolationQueryReq.bits.uop := s1_uop
214
215  // Generate forwardMaskFast to wake up insts earlier
216  val forwardMaskFast = io.lsq.forwardMaskFast.asUInt | io.sbuffer.forwardMaskFast.asUInt
217  io.fullForwardFast := ((~forwardMaskFast).asUInt & s1_mask) === 0.U
218
219  // Generate feedback signal caused by:
220  // * dcache bank conflict
221  // * need redo ld-ld violation check
222  val needLdVioCheckRedo = io.loadViolationQueryReq.valid &&
223    !io.loadViolationQueryReq.ready &&
224    RegNext(io.csrCtrl.ldld_vio_check_enable)
225  io.needLdVioCheckRedo := needLdVioCheckRedo
226  io.rsFeedback.valid := io.in.valid && (s1_bank_conflict || needLdVioCheckRedo) && !io.s1_kill
227  io.rsFeedback.bits.hit := false.B // we have found s1_bank_conflict / re do ld-ld violation check
228  io.rsFeedback.bits.rsIdx := io.in.bits.rsIdx
229  io.rsFeedback.bits.flushState := io.in.bits.ptwBack
230  io.rsFeedback.bits.sourceType := Mux(s1_bank_conflict, RSFeedbackType.bankConflict, RSFeedbackType.ldVioCheckRedo)
231  io.rsFeedback.bits.dataInvalidSqIdx := DontCare
232
233  // if replay is detected in load_s1,
234  // load inst will be canceled immediately
235  io.out.valid := io.in.valid && !io.rsFeedback.valid && !io.s1_kill
236  io.out.bits.paddr := s1_paddr_dup_lsu
237  io.out.bits.tlbMiss := s1_tlb_miss
238
239  // current ori test will cause the case of ldest == 0, below will be modifeid in the future.
240  // af & pf exception were modified
241  io.out.bits.uop.cf.exceptionVec(loadPageFault) := io.dtlbResp.bits.excp(0).pf.ld
242  io.out.bits.uop.cf.exceptionVec(loadAccessFault) := io.dtlbResp.bits.excp(0).af.ld
243
244  io.out.bits.ptwBack := io.dtlbResp.bits.ptwBack
245  io.out.bits.rsIdx := io.in.bits.rsIdx
246
247  io.out.bits.isSoftPrefetch := io.in.bits.isSoftPrefetch
248
249  io.in.ready := !io.in.valid || io.out.ready
250
251  XSPerfAccumulate("in_valid", io.in.valid)
252  XSPerfAccumulate("in_fire", io.in.fire)
253  XSPerfAccumulate("in_fire_first_issue", io.in.fire && io.in.bits.isFirstIssue)
254  XSPerfAccumulate("tlb_miss", io.in.fire && s1_tlb_miss)
255  XSPerfAccumulate("tlb_miss_first_issue", io.in.fire && s1_tlb_miss && io.in.bits.isFirstIssue)
256  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready)
257}
258
259// Load Pipeline Stage 2
260// DCache resp
261class LoadUnit_S2(implicit p: Parameters) extends XSModule with HasLoadHelper {
262  val io = IO(new Bundle() {
263    val in = Flipped(Decoupled(new LsPipelineBundle))
264    val out = Decoupled(new LsPipelineBundle)
265    val rsFeedback = ValidIO(new RSFeedback)
266    val dcacheResp = Flipped(DecoupledIO(new DCacheWordResp))
267    val pmpResp = Flipped(new PMPRespBundle())
268    val lsq = new LoadForwardQueryIO
269    val dataInvalidSqIdx = Input(UInt())
270    val sbuffer = new LoadForwardQueryIO
271    val dataForwarded = Output(Bool())
272    val s3_dcache_require_replay = Output(Bool())
273    val fullForward = Output(Bool())
274    val fastpath = Output(new LoadToLoadIO)
275    val dcache_kill = Output(Bool())
276    val s3_delayed_load_error = Output(Bool())
277    val loadViolationQueryResp = Flipped(Valid(new LoadViolationQueryResp))
278    val csrCtrl = Flipped(new CustomCSRCtrlIO)
279    val sentFastUop = Input(Bool())
280    val static_pm = Input(Valid(Bool())) // valid for static, bits for mmio
281  })
282
283  val pmp = WireInit(io.pmpResp)
284  when (io.static_pm.valid) {
285    pmp.ld := false.B
286    pmp.st := false.B
287    pmp.instr := false.B
288    pmp.mmio := io.static_pm.bits
289  }
290
291  val s2_is_prefetch = io.in.bits.isSoftPrefetch
292
293  // exception that may cause load addr to be invalid / illegal
294  //
295  // if such exception happen, that inst and its exception info
296  // will be force writebacked to rob
297  val s2_exception_vec = WireInit(io.in.bits.uop.cf.exceptionVec)
298  s2_exception_vec(loadAccessFault) := io.in.bits.uop.cf.exceptionVec(loadAccessFault) || pmp.ld
299  // soft prefetch will not trigger any exception (but ecc error interrupt may be triggered)
300  when (s2_is_prefetch) {
301    s2_exception_vec := 0.U.asTypeOf(s2_exception_vec.cloneType)
302  }
303  val s2_exception = ExceptionNO.selectByFu(s2_exception_vec, lduCfg).asUInt.orR
304
305  // writeback access fault caused by ecc error / bus error
306  //
307  // * ecc data error is slow to generate, so we will not use it until load stage 3
308  // * in load stage 3, an extra signal io.load_error will be used to
309
310  // now cache ecc error will raise an access fault
311  // at the same time, error info (including error paddr) will be write to
312  // an customized CSR "CACHE_ERROR"
313  if (EnableAccurateLoadError) {
314    io.s3_delayed_load_error := io.dcacheResp.bits.error_delayed &&
315      io.csrCtrl.cache_error_enable &&
316      RegNext(io.out.valid)
317  } else {
318    io.s3_delayed_load_error := false.B
319  }
320
321  val actually_mmio = pmp.mmio
322  val s2_uop = io.in.bits.uop
323  val s2_mask = io.in.bits.mask
324  val s2_paddr = io.in.bits.paddr
325  val s2_tlb_miss = io.in.bits.tlbMiss
326  val s2_mmio = !s2_is_prefetch && actually_mmio && !s2_exception
327  val s2_cache_miss = io.dcacheResp.bits.miss
328  val s2_cache_replay = io.dcacheResp.bits.replay
329  val s2_cache_tag_error = io.dcacheResp.bits.tag_error
330  val s2_forward_fail = io.lsq.matchInvalid || io.sbuffer.matchInvalid
331  val s2_ldld_violation = io.loadViolationQueryResp.valid &&
332    io.loadViolationQueryResp.bits.have_violation &&
333    RegNext(io.csrCtrl.ldld_vio_check_enable)
334  val s2_data_invalid = io.lsq.dataInvalid && !s2_forward_fail && !s2_ldld_violation && !s2_exception
335
336  io.dcache_kill := pmp.ld || pmp.mmio // move pmp resp kill to outside
337  io.dcacheResp.ready := true.B
338  val dcacheShouldResp = !(s2_tlb_miss || s2_exception || s2_mmio || s2_is_prefetch)
339  assert(!(io.in.valid && (dcacheShouldResp && !io.dcacheResp.valid)), "DCache response got lost")
340
341  // merge forward result
342  // lsq has higher priority than sbuffer
343  val forwardMask = Wire(Vec(8, Bool()))
344  val forwardData = Wire(Vec(8, UInt(8.W)))
345
346  val fullForward = ((~forwardMask.asUInt).asUInt & s2_mask) === 0.U && !io.lsq.dataInvalid
347  io.lsq := DontCare
348  io.sbuffer := DontCare
349  io.fullForward := fullForward
350
351  // generate XLEN/8 Muxs
352  for (i <- 0 until XLEN / 8) {
353    forwardMask(i) := io.lsq.forwardMask(i) || io.sbuffer.forwardMask(i)
354    forwardData(i) := Mux(io.lsq.forwardMask(i), io.lsq.forwardData(i), io.sbuffer.forwardData(i))
355  }
356
357  XSDebug(io.out.fire, "[FWD LOAD RESP] pc %x fwd %x(%b) + %x(%b)\n",
358    s2_uop.cf.pc,
359    io.lsq.forwardData.asUInt, io.lsq.forwardMask.asUInt,
360    io.in.bits.forwardData.asUInt, io.in.bits.forwardMask.asUInt
361  )
362
363  // data merge
364  val rdataVec = VecInit((0 until XLEN / 8).map(j =>
365    Mux(forwardMask(j), forwardData(j), io.dcacheResp.bits.data(8*(j+1)-1, 8*j))))
366  val rdata = rdataVec.asUInt
367  val rdataSel = LookupTree(s2_paddr(2, 0), List(
368    "b000".U -> rdata(63, 0),
369    "b001".U -> rdata(63, 8),
370    "b010".U -> rdata(63, 16),
371    "b011".U -> rdata(63, 24),
372    "b100".U -> rdata(63, 32),
373    "b101".U -> rdata(63, 40),
374    "b110".U -> rdata(63, 48),
375    "b111".U -> rdata(63, 56)
376  ))
377  val rdataPartialLoad = rdataHelper(s2_uop, rdataSel)
378
379  io.out.valid := io.in.valid && !s2_tlb_miss && !s2_data_invalid
380  // Inst will be canceled in store queue / lsq,
381  // so we do not need to care about flush in load / store unit's out.valid
382  io.out.bits := io.in.bits
383  io.out.bits.data := rdataPartialLoad
384  // when exception occurs, set it to not miss and let it write back to rob (via int port)
385  if (EnableFastForward) {
386    io.out.bits.miss := s2_cache_miss &&
387      !s2_exception &&
388      !s2_forward_fail &&
389      !s2_ldld_violation &&
390      !fullForward &&
391      !s2_is_prefetch
392  } else {
393    io.out.bits.miss := s2_cache_miss &&
394      !s2_exception &&
395      !s2_forward_fail &&
396      !s2_ldld_violation &&
397      !s2_is_prefetch
398  }
399  io.out.bits.uop.ctrl.fpWen := io.in.bits.uop.ctrl.fpWen && !s2_exception
400  // if forward fail, replay this inst from fetch
401  val forwardFailReplay = s2_forward_fail && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
402  // if ld-ld violation is detected, replay from this inst from fetch
403  val ldldVioReplay = s2_ldld_violation && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
404  val s2_need_replay_from_fetch = (s2_forward_fail || s2_ldld_violation) && !s2_mmio && !s2_is_prefetch && !s2_tlb_miss
405  io.out.bits.uop.ctrl.replayInst := s2_need_replay_from_fetch
406  io.out.bits.mmio := s2_mmio
407  io.out.bits.uop.ctrl.flushPipe := s2_mmio && io.sentFastUop
408  io.out.bits.uop.cf.exceptionVec := s2_exception_vec // cache error not included
409
410  // For timing reasons, sometimes we can not let
411  // io.out.bits.miss := s2_cache_miss && !s2_exception && !fullForward
412  // We use io.dataForwarded instead. It means:
413  // 1. Forward logic have prepared all data needed,
414  //    and dcache query is no longer needed.
415  // 2. ... or data cache tag error is detected, this kind of inst
416  //    will not update miss queue. That is to say, if miss, that inst
417  //    may not be refilled
418  // Such inst will be writebacked from load queue.
419  io.dataForwarded := s2_cache_miss && !s2_exception && !s2_forward_fail &&
420    (fullForward || io.csrCtrl.cache_error_enable && s2_cache_tag_error)
421  // io.out.bits.forwardX will be send to lq
422  io.out.bits.forwardMask := forwardMask
423  // data retbrived from dcache is also included in io.out.bits.forwardData
424  io.out.bits.forwardData := rdataVec
425
426  io.in.ready := io.out.ready || !io.in.valid
427
428  // feedback tlb result to RS
429  io.rsFeedback.valid := io.in.valid
430  val s2_need_replay_from_rs = Wire(Bool())
431  if (EnableFastForward) {
432    s2_need_replay_from_rs :=
433      s2_tlb_miss || // replay if dtlb miss
434      s2_cache_replay && !s2_is_prefetch && !s2_forward_fail && !s2_ldld_violation && !s2_mmio && !s2_exception && !fullForward || // replay if dcache miss queue full / busy
435      s2_data_invalid && !s2_is_prefetch && !s2_forward_fail && !s2_ldld_violation // replay if store to load forward data is not ready
436  } else {
437    // Note that if all parts of data are available in sq / sbuffer, replay required by dcache will not be scheduled
438    s2_need_replay_from_rs :=
439      s2_tlb_miss || // replay if dtlb miss
440      s2_cache_replay && !s2_is_prefetch && !s2_forward_fail && !s2_ldld_violation && !s2_mmio && !s2_exception && !io.dataForwarded || // replay if dcache miss queue full / busy
441      s2_data_invalid && !s2_is_prefetch && !s2_forward_fail && !s2_ldld_violation // replay if store to load forward data is not ready
442  }
443  assert(!RegNext(io.in.valid && s2_need_replay_from_rs && s2_need_replay_from_fetch))
444  io.rsFeedback.bits.hit := !s2_need_replay_from_rs
445  io.rsFeedback.bits.rsIdx := io.in.bits.rsIdx
446  io.rsFeedback.bits.flushState := io.in.bits.ptwBack
447  // feedback source priority: tlbMiss > dataInvalid > mshrFull
448  // general case priority: tlbMiss > exception (include forward_fail / ldld_violation) > mmio > dataInvalid > mshrFull > normal miss / hit
449  io.rsFeedback.bits.sourceType := Mux(s2_tlb_miss, RSFeedbackType.tlbMiss,
450    Mux(s2_data_invalid,
451      RSFeedbackType.dataInvalid,
452      RSFeedbackType.mshrFull
453    )
454  )
455  io.rsFeedback.bits.dataInvalidSqIdx.value := io.dataInvalidSqIdx
456  io.rsFeedback.bits.dataInvalidSqIdx.flag := DontCare
457
458  // s2_cache_replay is quite slow to generate, send it separately to LQ
459  if (EnableFastForward) {
460    io.s3_dcache_require_replay := s2_cache_replay && !fullForward
461  } else {
462    io.s3_dcache_require_replay := s2_cache_replay &&
463      !io.rsFeedback.bits.hit &&
464      !io.dataForwarded &&
465      !s2_is_prefetch &&
466      io.out.bits.miss
467  }
468
469  // fast load to load forward
470  io.fastpath.valid := RegNext(io.out.valid) // for debug only
471  io.fastpath.data := RegNext(io.out.bits.data)
472
473
474  XSDebug(io.out.fire, "[DCACHE LOAD RESP] pc %x rdata %x <- D$ %x + fwd %x(%b)\n",
475    s2_uop.cf.pc, rdataPartialLoad, io.dcacheResp.bits.data,
476    forwardData.asUInt, forwardMask.asUInt
477  )
478
479  XSPerfAccumulate("in_valid", io.in.valid)
480  XSPerfAccumulate("in_fire", io.in.fire)
481  XSPerfAccumulate("in_fire_first_issue", io.in.fire && io.in.bits.isFirstIssue)
482  XSPerfAccumulate("dcache_miss", io.in.fire && s2_cache_miss)
483  XSPerfAccumulate("dcache_miss_first_issue", io.in.fire && s2_cache_miss && io.in.bits.isFirstIssue)
484  XSPerfAccumulate("full_forward", io.in.valid && fullForward)
485  XSPerfAccumulate("dcache_miss_full_forward", io.in.valid && s2_cache_miss && fullForward)
486  XSPerfAccumulate("replay",  io.rsFeedback.valid && !io.rsFeedback.bits.hit)
487  XSPerfAccumulate("replay_tlb_miss", io.rsFeedback.valid && !io.rsFeedback.bits.hit && s2_tlb_miss)
488  XSPerfAccumulate("replay_cache", io.rsFeedback.valid && !io.rsFeedback.bits.hit && !s2_tlb_miss && s2_cache_replay)
489  XSPerfAccumulate("stall_out", io.out.valid && !io.out.ready)
490  XSPerfAccumulate("replay_from_fetch_forward", io.out.valid && forwardFailReplay)
491  XSPerfAccumulate("replay_from_fetch_load_vio", io.out.valid && ldldVioReplay)
492}
493
494class LoadUnit(implicit p: Parameters) extends XSModule
495  with HasLoadHelper
496  with HasPerfEvents
497  with HasDCacheParameters
498{
499  val io = IO(new Bundle() {
500    val ldin = Flipped(Decoupled(new ExuInput))
501    val ldout = Decoupled(new ExuOutput)
502    val redirect = Flipped(ValidIO(new Redirect))
503    val feedbackSlow = ValidIO(new RSFeedback)
504    val feedbackFast = ValidIO(new RSFeedback)
505    val rsIdx = Input(UInt(log2Up(IssQueSize).W))
506    val isFirstIssue = Input(Bool())
507    val dcache = new DCacheLoadIO
508    val sbuffer = new LoadForwardQueryIO
509    val lsq = new LoadToLsqIO
510    val refill = Flipped(ValidIO(new Refill))
511    val fastUop = ValidIO(new MicroOp) // early wakeup signal generated in load_s1, send to RS in load_s2
512    val trigger = Vec(3, new LoadUnitTriggerIO)
513
514    val tlb = new TlbRequestIO(2)
515    val pmp = Flipped(new PMPRespBundle()) // arrive same to tlb now
516
517    val fastpathOut = Output(new LoadToLoadIO)
518    val fastpathIn = Input(new LoadToLoadIO)
519    val loadFastMatch = Input(Bool())
520    val loadFastImm = Input(UInt(12.W))
521
522    val s3_delayed_load_error = Output(Bool()) // load ecc error
523    // Note that io.s3_delayed_load_error and io.lsq.s3_delayed_load_error is different
524
525    val csrCtrl = Flipped(new CustomCSRCtrlIO)
526  })
527
528  val load_s0 = Module(new LoadUnit_S0)
529  val load_s1 = Module(new LoadUnit_S1)
530  val load_s2 = Module(new LoadUnit_S2)
531
532  load_s0.io.in <> io.ldin
533  load_s0.io.dtlbReq <> io.tlb.req
534  load_s0.io.dcacheReq <> io.dcache.req
535  load_s0.io.rsIdx := io.rsIdx
536  load_s0.io.isFirstIssue := io.isFirstIssue
537  load_s0.io.fastpath := io.fastpathIn
538  load_s0.io.s0_kill := false.B
539  val s0_tryPointerChasing = !io.ldin.valid && io.fastpathIn.valid
540  val s0_pointerChasingVAddr = io.fastpathIn.data(5, 0) +& io.loadFastImm(5, 0)
541
542  val s1_data = PipelineConnect(load_s0.io.out, load_s1.io.in, true.B,
543    load_s0.io.out.bits.uop.robIdx.needFlush(io.redirect) && !s0_tryPointerChasing).get
544
545  load_s1.io.s1_kill := RegEnable(load_s0.io.s0_kill, false.B, load_s0.io.in.valid || io.fastpathIn.valid)
546  io.tlb.req_kill := load_s1.io.s1_kill
547  load_s1.io.dtlbResp <> io.tlb.resp
548  io.dcache.s1_paddr_dup_lsu <> load_s1.io.lsuPAddr
549  io.dcache.s1_paddr_dup_dcache <> load_s1.io.dcachePAddr
550  io.dcache.s1_kill := load_s1.io.dcacheKill
551  load_s1.io.sbuffer <> io.sbuffer
552  load_s1.io.lsq <> io.lsq.forward
553  load_s1.io.loadViolationQueryReq <> io.lsq.loadViolationQuery.req
554  load_s1.io.dcacheBankConflict <> io.dcache.s1_bank_conflict
555  load_s1.io.csrCtrl <> io.csrCtrl
556
557  val s0_doTryPointerChasing = s0_tryPointerChasing && load_s0.io.in.ready && load_s0.io.dcacheReq.ready
558  val s1_tryPointerChasing = RegNext(s0_doTryPointerChasing, false.B)
559  val s1_pointerChasingVAddr = RegEnable(s0_pointerChasingVAddr, s0_doTryPointerChasing)
560  val cancelPointerChasing = WireInit(false.B)
561  if (EnableLoadToLoadForward) {
562    // Sometimes, we need to cancel the load-load forwarding.
563    // These can be put at S0 if timing is bad at S1.
564    // Case 0: CACHE_SET(base + offset) != CACHE_SET(base) (lowest 6-bit addition has an overflow)
565    val addressMisMatch = s1_pointerChasingVAddr(6) || RegEnable(io.loadFastImm(11, 6).orR, s0_doTryPointerChasing)
566    // Case 1: the address is not 64-bit aligned or the fuOpType is not LD
567    val addressNotAligned = s1_pointerChasingVAddr(2, 0).orR
568    val fuOpTypeIsNotLd = io.ldin.bits.uop.ctrl.fuOpType =/= LSUOpType.ld
569    // Case 2: this is not a valid load-load pair
570    val notFastMatch = RegEnable(!io.loadFastMatch, s0_tryPointerChasing)
571    // Case 3: this load-load uop is cancelled
572    val isCancelled = !io.ldin.valid
573    when (s1_tryPointerChasing) {
574      cancelPointerChasing := addressMisMatch || addressNotAligned || fuOpTypeIsNotLd || notFastMatch || isCancelled
575      load_s1.io.in.bits.uop := io.ldin.bits.uop
576      val spec_vaddr = s1_data.vaddr
577      val vaddr = Cat(spec_vaddr(VAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W))
578      load_s1.io.in.bits.vaddr := vaddr
579      load_s1.io.in.bits.rsIdx := io.rsIdx
580      load_s1.io.in.bits.isFirstIssue := io.isFirstIssue
581      // We need to replace vaddr(5, 3).
582      for (d <- 0 until 2) {
583        val spec_paddr = io.tlb.resp.bits.paddr(d)
584        load_s1.io.dtlbResp.bits.paddr(d) := Cat(spec_paddr(PAddrBits - 1, 6), s1_pointerChasingVAddr(5, 3), 0.U(3.W))
585      }
586    }
587    when (cancelPointerChasing) {
588      load_s1.io.s1_kill := true.B
589    }.otherwise {
590      load_s0.io.s0_kill := s1_tryPointerChasing
591      when (s1_tryPointerChasing) {
592        io.ldin.ready := true.B
593      }
594    }
595
596    XSPerfAccumulate("load_to_load_forward", s1_tryPointerChasing && !cancelPointerChasing)
597    XSPerfAccumulate("load_to_load_forward_try", s1_tryPointerChasing)
598    XSPerfAccumulate("load_to_load_forward_fail", cancelPointerChasing)
599    XSPerfAccumulate("load_to_load_forward_fail_cancelled", cancelPointerChasing && isCancelled)
600    XSPerfAccumulate("load_to_load_forward_fail_wakeup_mismatch", cancelPointerChasing && !isCancelled && notFastMatch)
601    XSPerfAccumulate("load_to_load_forward_fail_op_not_ld",
602      cancelPointerChasing && !isCancelled && !notFastMatch && fuOpTypeIsNotLd)
603    XSPerfAccumulate("load_to_load_forward_fail_addr_align",
604      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && addressNotAligned)
605    XSPerfAccumulate("load_to_load_forward_fail_set_mismatch",
606      cancelPointerChasing && !isCancelled && !notFastMatch && !fuOpTypeIsNotLd && !addressNotAligned && addressMisMatch)
607  }
608  PipelineConnect(load_s1.io.out, load_s2.io.in, true.B,
609    load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect) || cancelPointerChasing)
610
611  io.dcache.s2_kill := load_s2.io.dcache_kill // to kill mmio resp which are redirected
612  load_s2.io.dcacheResp <> io.dcache.resp
613  load_s2.io.pmpResp <> io.pmp
614  load_s2.io.static_pm := RegNext(io.tlb.resp.bits.static_pm)
615  load_s2.io.lsq.forwardData <> io.lsq.forward.forwardData
616  load_s2.io.lsq.forwardMask <> io.lsq.forward.forwardMask
617  load_s2.io.lsq.forwardMaskFast <> io.lsq.forward.forwardMaskFast // should not be used in load_s2
618  load_s2.io.lsq.dataInvalid <> io.lsq.forward.dataInvalid
619  load_s2.io.lsq.matchInvalid <> io.lsq.forward.matchInvalid
620  load_s2.io.sbuffer.forwardData <> io.sbuffer.forwardData
621  load_s2.io.sbuffer.forwardMask <> io.sbuffer.forwardMask
622  load_s2.io.sbuffer.forwardMaskFast <> io.sbuffer.forwardMaskFast // should not be used in load_s2
623  load_s2.io.sbuffer.dataInvalid <> io.sbuffer.dataInvalid // always false
624  load_s2.io.sbuffer.matchInvalid <> io.sbuffer.matchInvalid
625  load_s2.io.dataForwarded <> io.lsq.s2_load_data_forwarded
626  load_s2.io.fastpath <> io.fastpathOut
627  load_s2.io.dataInvalidSqIdx := io.lsq.forward.dataInvalidSqIdx // provide dataInvalidSqIdx to make wakeup faster
628  load_s2.io.loadViolationQueryResp <> io.lsq.loadViolationQuery.resp
629  load_s2.io.csrCtrl <> io.csrCtrl
630  load_s2.io.sentFastUop := io.fastUop.valid
631
632  // actually load s3
633  io.lsq.s3_dcache_require_replay := load_s2.io.s3_dcache_require_replay
634  io.lsq.s3_delayed_load_error := load_s2.io.s3_delayed_load_error
635
636  // feedback tlb miss / dcache miss queue full
637  io.feedbackSlow.valid := RegNext(load_s2.io.rsFeedback.valid && !load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect))
638  io.feedbackSlow.bits := RegNext(load_s2.io.rsFeedback.bits)
639  val s3_replay_for_mshrfull = RegNext(!load_s2.io.rsFeedback.bits.hit && load_s2.io.rsFeedback.bits.sourceType === RSFeedbackType.mshrFull)
640  val s3_refill_hit_load_paddr = refill_addr_hit(RegNext(load_s2.io.out.bits.paddr), io.refill.bits.addr)
641  // update replay request
642  io.feedbackSlow.bits.hit := RegNext(load_s2.io.rsFeedback.bits).hit ||
643    s3_refill_hit_load_paddr && s3_replay_for_mshrfull
644
645  // feedback bank conflict / ld-vio check struct hazard to rs
646  io.feedbackFast.bits := RegNext(load_s1.io.rsFeedback.bits)
647  io.feedbackFast.valid := RegNext(load_s1.io.rsFeedback.valid && !load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect))
648  // If replay is reported at load_s1, inst will be canceled (will not enter load_s2),
649  // in that case:
650  // * replay should not be reported twice
651  assert(!(RegNext(io.feedbackFast.valid) && io.feedbackSlow.valid))
652  // * io.fastUop.valid should not be reported
653  assert(!RegNext(io.feedbackFast.valid && io.fastUop.valid))
654
655  // pre-calcuate sqIdx mask in s0, then send it to lsq in s1 for forwarding
656  val sqIdxMaskReg = RegNext(UIntToMask(load_s0.io.in.bits.uop.sqIdx.value, StoreQueueSize))
657  // to enable load-load, sqIdxMask must be calculated based on ldin.uop
658  // If the timing here is not OK, load-load forwarding has to be disabled.
659  // Or we calculate sqIdxMask at RS??
660  io.lsq.forward.sqIdxMask := sqIdxMaskReg
661  if (EnableLoadToLoadForward) {
662    when (s1_tryPointerChasing) {
663      io.lsq.forward.sqIdxMask := UIntToMask(io.ldin.bits.uop.sqIdx.value, StoreQueueSize)
664    }
665  }
666
667  // // use s2_hit_way to select data received in s1
668  // load_s2.io.dcacheResp.bits.data := Mux1H(RegNext(io.dcache.s1_hit_way), RegNext(io.dcache.s1_data))
669  // assert(load_s2.io.dcacheResp.bits.data === io.dcache.resp.bits.data)
670
671  // now io.fastUop.valid is sent to RS in load_s2
672  val s2_dcache_hit = io.dcache.s2_hit // dcache hit dup in lsu side
673
674  io.fastUop.valid := RegNext(
675      !io.dcache.s1_disable_fast_wakeup &&  // load fast wakeup should be disabled when dcache data read is not ready
676      load_s1.io.in.valid && // valid load request
677      !load_s1.io.s1_kill && // killed by load-load forwarding
678      !load_s1.io.dtlbResp.bits.fast_miss && // not mmio or tlb miss, pf / af not included here
679      !io.lsq.forward.dataInvalidFast // forward failed
680    ) &&
681    !RegNext(load_s1.io.needLdVioCheckRedo) && // load-load violation check: load paddr cam struct hazard
682    !RegNext(load_s1.io.out.bits.uop.robIdx.needFlush(io.redirect)) &&
683    s2_dcache_hit // dcache hit in lsu side
684
685  io.fastUop.bits := RegNext(load_s1.io.out.bits.uop)
686
687  XSDebug(load_s0.io.out.valid,
688    p"S0: pc ${Hexadecimal(load_s0.io.out.bits.uop.cf.pc)}, lId ${Hexadecimal(load_s0.io.out.bits.uop.lqIdx.asUInt)}, " +
689    p"vaddr ${Hexadecimal(load_s0.io.out.bits.vaddr)}, mask ${Hexadecimal(load_s0.io.out.bits.mask)}\n")
690  XSDebug(load_s1.io.out.valid,
691    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}, " +
692    p"paddr ${Hexadecimal(load_s1.io.out.bits.paddr)}, mmio ${load_s1.io.out.bits.mmio}\n")
693
694  // writeback to LSQ
695  // Current dcache use MSHR
696  // Load queue will be updated at s2 for both hit/miss int/fp load
697  io.lsq.loadIn.valid := load_s2.io.out.valid
698  // generate LqWriteBundle from LsPipelineBundle
699  io.lsq.loadIn.bits.fromLsPipelineBundle(load_s2.io.out.bits)
700  io.lsq.loadIn.bits.writeQueueData := load_s2.io.in.valid
701
702  // write to rob and writeback bus
703  val s2_wb_valid = load_s2.io.out.valid && !load_s2.io.out.bits.miss && !load_s2.io.out.bits.mmio
704
705  // Int load, if hit, will be writebacked at s2
706  val hitLoadOut = Wire(Valid(new ExuOutput))
707  hitLoadOut.valid := s2_wb_valid
708  hitLoadOut.bits.uop := load_s2.io.out.bits.uop
709  hitLoadOut.bits.data := load_s2.io.out.bits.data
710  hitLoadOut.bits.redirectValid := false.B
711  hitLoadOut.bits.redirect := DontCare
712  hitLoadOut.bits.debug.isMMIO := load_s2.io.out.bits.mmio
713  hitLoadOut.bits.debug.isPerfCnt := false.B
714  hitLoadOut.bits.debug.paddr := load_s2.io.out.bits.paddr
715  hitLoadOut.bits.debug.vaddr := load_s2.io.out.bits.vaddr
716  hitLoadOut.bits.fflags := DontCare
717
718  load_s2.io.out.ready := true.B
719
720  val load_wb_reg = RegNext(Mux(hitLoadOut.valid, hitLoadOut.bits, io.lsq.ldout.bits))
721  io.ldout.bits := load_wb_reg
722  io.ldout.valid := RegNext(hitLoadOut.valid) && !RegNext(load_s2.io.out.bits.uop.robIdx.needFlush(io.redirect)) ||
723    RegNext(io.lsq.ldout.valid) && !RegNext(io.lsq.ldout.bits.uop.robIdx.needFlush(io.redirect)) && !RegNext(hitLoadOut.valid)
724
725  // io.ldout.bits.uop.cf.exceptionVec(loadAccessFault) := load_wb_reg.uop.cf.exceptionVec(loadAccessFault) ||
726  //   hitLoadOut.valid && load_s2.io.delayedLoadError
727
728  // io.delayedLoadError := false.B
729
730  io.s3_delayed_load_error := hitLoadOut.valid && load_s2.io.s3_delayed_load_error
731
732  io.lsq.ldout.ready := !hitLoadOut.valid
733
734  when(io.feedbackSlow.valid && !io.feedbackSlow.bits.hit){
735    // when need replay from rs, inst should not be writebacked to rob
736    assert(RegNext(!hitLoadOut.valid))
737    // when need replay from rs
738    // * inst should not be writebacked to lq, or
739    // * lq state will be updated in load_s3 (next cycle)
740    assert(RegNext(!io.lsq.loadIn.valid) || RegNext(load_s2.io.s3_dcache_require_replay))
741  }
742
743  val lastValidData = RegEnable(io.ldout.bits.data, io.ldout.fire)
744  val hitLoadAddrTriggerHitVec = Wire(Vec(3, Bool()))
745  val lqLoadAddrTriggerHitVec = io.lsq.trigger.lqLoadAddrTriggerHitVec
746  (0 until 3).map{i => {
747    val tdata2 = io.trigger(i).tdata2
748    val matchType = io.trigger(i).matchType
749    val tEnable = io.trigger(i).tEnable
750
751    hitLoadAddrTriggerHitVec(i) := TriggerCmp(load_s2.io.out.bits.vaddr, tdata2, matchType, tEnable)
752    io.trigger(i).addrHit := Mux(hitLoadOut.valid, hitLoadAddrTriggerHitVec(i), lqLoadAddrTriggerHitVec(i))
753    io.trigger(i).lastDataHit := TriggerCmp(lastValidData, tdata2, matchType, tEnable)
754  }}
755  io.lsq.trigger.hitLoadAddrTriggerHitVec := hitLoadAddrTriggerHitVec
756
757  val perfEvents = Seq(
758    ("load_s0_in_fire         ", load_s0.io.in.fire                                                                                                              ),
759    ("load_to_load_forward    ", load_s1.io.out.valid && s1_tryPointerChasing && !cancelPointerChasing                                                           ),
760    ("stall_dcache            ", load_s0.io.out.valid && load_s0.io.out.ready && !load_s0.io.dcacheReq.ready                                                     ),
761    ("load_s1_in_fire         ", load_s1.io.in.fire                                                                                                              ),
762    ("load_s1_tlb_miss        ", load_s1.io.in.fire && load_s1.io.dtlbResp.bits.miss                                                                             ),
763    ("load_s2_in_fire         ", load_s2.io.in.fire                                                                                                              ),
764    ("load_s2_dcache_miss     ", load_s2.io.in.fire && load_s2.io.dcacheResp.bits.miss                                                                           ),
765    ("load_s2_replay          ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit                                                                  ),
766    ("load_s2_replay_tlb_miss ", load_s2.io.rsFeedback.valid && !load_s2.io.rsFeedback.bits.hit && load_s2.io.in.bits.tlbMiss                                    ),
767    ("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),
768  )
769  generatePerfEvent()
770
771  when(io.ldout.fire){
772    XSDebug("ldout %x\n", io.ldout.bits.uop.cf.pc)
773  }
774}
775