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