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