xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/LoadQueueReplay.scala (revision 26af847e669bb208507278eafc6ebe52f03b0d19)
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***************************************************************************************/
16package xiangshan.mem
17
18import chisel3._
19import chisel3.util._
20import org.chipsalliance.cde.config._
21import xiangshan._
22import xiangshan.backend.rob.{RobLsqIO, RobPtr}
23import xiangshan.cache._
24import xiangshan.backend.fu.fpu.FPU
25import xiangshan.backend.fu.FuConfig._
26import xiangshan.cache._
27import xiangshan.cache.mmu._
28import xiangshan.frontend.FtqPtr
29import xiangshan.ExceptionNO._
30import xiangshan.cache.wpu.ReplayCarry
31import xiangshan.mem.mdp._
32import utils._
33import utility._
34import xiangshan.backend.Bundles.{DynInst, MemExuOutput}
35
36object LoadReplayCauses {
37  // these causes have priority, lower coding has higher priority.
38  // when load replay happens, load unit will select highest priority
39  // from replay causes vector
40
41  /*
42   * Warning:
43   * ************************************************************
44   * * Don't change the priority. If the priority is changed,   *
45   * * deadlock may occur. If you really need to change or      *
46   * * add priority, please ensure that no deadlock will occur. *
47   * ************************************************************
48   *
49   */
50  // st-ld violation re-execute check
51  val C_MA  = 0
52  // tlb miss check
53  val C_TM  = 1
54  // store-to-load-forwarding check
55  val C_FF  = 2
56  // dcache replay check
57  val C_DR  = 3
58  // dcache miss check
59  val C_DM  = 4
60  // wpu predict fail
61  val C_WF  = 5
62  // dcache bank conflict check
63  val C_BC  = 6
64  // RAR queue accept check
65  val C_RAR = 7
66  // RAW queue accept check
67  val C_RAW = 8
68  // st-ld violation
69  val C_NK  = 9
70  // total causes
71  val allCauses = 10
72}
73
74class AgeDetector(numEntries: Int, numEnq: Int, regOut: Boolean = true)(implicit p: Parameters) extends XSModule {
75  val io = IO(new Bundle {
76    // NOTE: deq and enq may come at the same cycle.
77    val enq = Vec(numEnq, Input(UInt(numEntries.W)))
78    val deq = Input(UInt(numEntries.W))
79    val ready = Input(UInt(numEntries.W))
80    val out = Output(UInt(numEntries.W))
81  })
82
83  // age(i)(j): entry i enters queue before entry j
84  val age = Seq.fill(numEntries)(Seq.fill(numEntries)(RegInit(false.B)))
85  val nextAge = Seq.fill(numEntries)(Seq.fill(numEntries)(Wire(Bool())))
86
87  // to reduce reg usage, only use upper matrix
88  def get_age(row: Int, col: Int): Bool = if (row <= col) age(row)(col) else !age(col)(row)
89  def get_next_age(row: Int, col: Int): Bool = if (row <= col) nextAge(row)(col) else !nextAge(col)(row)
90  def isFlushed(i: Int): Bool = io.deq(i)
91  def isEnqueued(i: Int, numPorts: Int = -1): Bool = {
92    val takePorts = if (numPorts == -1) io.enq.length else numPorts
93    takePorts match {
94      case 0 => false.B
95      case 1 => io.enq.head(i) && !isFlushed(i)
96      case n => VecInit(io.enq.take(n).map(_(i))).asUInt.orR && !isFlushed(i)
97    }
98  }
99
100  for ((row, i) <- nextAge.zipWithIndex) {
101    val thisValid = get_age(i, i) || isEnqueued(i)
102    for ((elem, j) <- row.zipWithIndex) {
103      when (isFlushed(i)) {
104        // (1) when entry i is flushed or dequeues, set row(i) to false.B
105        elem := false.B
106      }.elsewhen (isFlushed(j)) {
107        // (2) when entry j is flushed or dequeues, set column(j) to validVec
108        elem := thisValid
109      }.elsewhen (isEnqueued(i)) {
110        // (3) when entry i enqueues from port k,
111        // (3.1) if entry j enqueues from previous ports, set to false
112        // (3.2) otherwise, set to true if and only of entry j is invalid
113        // overall: !jEnqFromPreviousPorts && !jIsValid
114        val sel = io.enq.map(_(i))
115        val result = (0 until numEnq).map(k => isEnqueued(j, k))
116        // why ParallelMux: sel must be one-hot since enq is one-hot
117        elem := !get_age(j, j) && !ParallelMux(sel, result)
118      }.otherwise {
119        // default: unchanged
120        elem := get_age(i, j)
121      }
122      age(i)(j) := elem
123    }
124  }
125
126  def getOldest(get: (Int, Int) => Bool): UInt = {
127    VecInit((0 until numEntries).map(i => {
128      io.ready(i) & VecInit((0 until numEntries).map(j => if (i != j) !io.ready(j) || get(i, j) else true.B)).asUInt.andR
129    })).asUInt
130  }
131  val best = getOldest(get_age)
132  val nextBest = getOldest(get_next_age)
133
134  io.out := (if (regOut) best else nextBest)
135}
136
137object AgeDetector {
138  def apply(numEntries: Int, enq: Vec[UInt], deq: UInt, ready: UInt)(implicit p: Parameters): Valid[UInt] = {
139    val age = Module(new AgeDetector(numEntries, enq.length, regOut = true))
140    age.io.enq := enq
141    age.io.deq := deq
142    age.io.ready:= ready
143    val out = Wire(Valid(UInt(deq.getWidth.W)))
144    out.valid := age.io.out.orR
145    out.bits := age.io.out
146    out
147  }
148}
149
150
151class LoadQueueReplay(implicit p: Parameters) extends XSModule
152  with HasDCacheParameters
153  with HasCircularQueuePtrHelper
154  with HasLoadHelper
155  with HasTlbConst
156  with HasPerfEvents
157{
158  val io = IO(new Bundle() {
159    // control
160    val redirect = Flipped(ValidIO(new Redirect))
161    val vecFeedback = Flipped(ValidIO(new FeedbackToLsqIO))
162
163    // from load unit s3
164    val enq = Vec(LoadPipelineWidth, Flipped(Decoupled(new LqWriteBundle)))
165
166    // from sta s1
167    val storeAddrIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle)))
168
169    // from std s1
170    val storeDataIn = Vec(StorePipelineWidth, Flipped(Valid(new MemExuOutput(isVector = true))))
171
172    // queue-based replay
173    val replay = Vec(LoadPipelineWidth, Decoupled(new LsPipelineBundle))
174    val refill = Flipped(ValidIO(new Refill))
175    val tl_d_channel = Input(new DcacheToLduForwardIO)
176
177    // from StoreQueue
178    val stAddrReadySqPtr = Input(new SqPtr)
179    val stAddrReadyVec   = Input(Vec(StoreQueueSize, Bool()))
180    val stDataReadySqPtr = Input(new SqPtr)
181    val stDataReadyVec   = Input(Vec(StoreQueueSize, Bool()))
182
183    //
184    val sqEmpty = Input(Bool())
185    val lqFull  = Output(Bool())
186    val ldWbPtr = Input(new LqPtr)
187    val rarFull = Input(Bool())
188    val rawFull = Input(Bool())
189    val l2_hint  = Input(Valid(new L2ToL1Hint()))
190    val tlb_hint = Flipped(new TlbHintIO)
191    val tlbReplayDelayCycleCtrl = Vec(4, Input(UInt(ReSelectLen.W)))
192
193    val debugTopDown = new LoadQueueTopDownIO
194  })
195
196  println("LoadQueueReplay size: " + LoadQueueReplaySize)
197  //  LoadQueueReplay field:
198  //  +-----------+---------+-------+-------------+--------+
199  //  | Allocated | MicroOp | VAddr |    Cause    |  Flags |
200  //  +-----------+---------+-------+-------------+--------+
201  //  Allocated   : entry has been allocated already
202  //  MicroOp     : inst's microOp
203  //  VAddr       : virtual address
204  //  Cause       : replay cause
205  //  Flags       : rar/raw queue allocate flags
206  val allocated = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B))) // The control signals need to explicitly indicate the initial value
207  val scheduled = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
208  val uop = Reg(Vec(LoadQueueReplaySize, new DynInst))
209  val vaddrModule = Module(new LqVAddrModule(
210    gen = UInt(VAddrBits.W),
211    numEntries = LoadQueueReplaySize,
212    numRead = LoadPipelineWidth,
213    numWrite = LoadPipelineWidth,
214    numWBank = LoadQueueNWriteBanks,
215    numWDelay = 2,
216    numCamPort = 0))
217  vaddrModule.io := DontCare
218  val debug_vaddr = RegInit(VecInit(List.fill(LoadQueueReplaySize)(0.U(VAddrBits.W))))
219  val cause = RegInit(VecInit(List.fill(LoadQueueReplaySize)(0.U(LoadReplayCauses.allCauses.W))))
220  val blocking = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
221  val strict = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
222
223  // freeliset: store valid entries index.
224  // +---+---+--------------+-----+-----+
225  // | 0 | 1 |      ......  | n-2 | n-1 |
226  // +---+---+--------------+-----+-----+
227  val freeList = Module(new FreeList(
228    size = LoadQueueReplaySize,
229    allocWidth = LoadPipelineWidth,
230    freeWidth = 4,
231    enablePreAlloc = true,
232    moduleName = "LoadQueueReplay freelist"
233  ))
234  freeList.io := DontCare
235  /**
236   * used for re-select control
237   */
238  val blockSqIdx = Reg(Vec(LoadQueueReplaySize, new SqPtr))
239  // DCache miss block
240  val missMSHRId = RegInit(VecInit(List.fill(LoadQueueReplaySize)(0.U((log2Up(cfg.nMissEntries+1).W)))))
241  val tlbHintId = RegInit(VecInit(List.fill(LoadQueueReplaySize)(0.U((log2Up(loadfiltersize+1).W)))))
242  // Has this load already updated dcache replacement?
243  val replacementUpdated = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
244  val missDbUpdated = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
245  val trueCacheMissReplay = WireInit(VecInit(cause.map(_(LoadReplayCauses.C_DM))))
246  val replayCarryReg = RegInit(VecInit(List.fill(LoadQueueReplaySize)(ReplayCarry(nWays, 0.U, false.B))))
247  val dataInLastBeatReg = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
248
249  /**
250   * Enqueue
251   */
252  val canEnqueue = io.enq.map(_.valid)
253  val cancelEnq = io.enq.map(enq => enq.bits.uop.robIdx.needFlush(io.redirect))
254  val needReplay = io.enq.map(enq => enq.bits.rep_info.need_rep)
255  val hasExceptions = io.enq.map(enq => ExceptionNO.selectByFu(enq.bits.uop.exceptionVec, LduCfg).asUInt.orR && !enq.bits.tlbMiss)
256  val loadReplay = io.enq.map(enq => enq.bits.isLoadReplay)
257  val needEnqueue = VecInit((0 until LoadPipelineWidth).map(w => {
258    canEnqueue(w) && !cancelEnq(w) && needReplay(w) && !hasExceptions(w)
259  }))
260  val canFreeVec = VecInit((0 until LoadPipelineWidth).map(w => {
261    canEnqueue(w) && loadReplay(w) && (!needReplay(w) || hasExceptions(w))
262  }))
263
264  // select LoadPipelineWidth valid index.
265  val lqFull = freeList.io.empty
266  val lqFreeNums = freeList.io.validCount
267
268  // replay logic
269  // release logic generation
270  val storeAddrInSameCycleVec = Wire(Vec(LoadQueueReplaySize, Bool()))
271  val storeDataInSameCycleVec = Wire(Vec(LoadQueueReplaySize, Bool()))
272  val addrNotBlockVec = Wire(Vec(LoadQueueReplaySize, Bool()))
273  val dataNotBlockVec = Wire(Vec(LoadQueueReplaySize, Bool()))
274  val storeAddrValidVec = addrNotBlockVec.asUInt | storeAddrInSameCycleVec.asUInt
275  val storeDataValidVec = dataNotBlockVec.asUInt | storeDataInSameCycleVec.asUInt
276
277  // store data valid check
278  val stAddrReadyVec = io.stAddrReadyVec
279  val stDataReadyVec = io.stDataReadyVec
280
281  for (i <- 0 until LoadQueueReplaySize) {
282    // dequeue
283    //  FIXME: store*Ptr is not accurate
284    dataNotBlockVec(i) := isAfter(io.stDataReadySqPtr, blockSqIdx(i)) || stDataReadyVec(blockSqIdx(i).value) || io.sqEmpty // for better timing
285    addrNotBlockVec(i) := Mux(strict(i), isAfter(io.stAddrReadySqPtr, blockSqIdx(i)), stAddrReadyVec(blockSqIdx(i).value)) || io.sqEmpty // for better timing
286
287    // store address execute
288    storeAddrInSameCycleVec(i) := VecInit((0 until StorePipelineWidth).map(w => {
289      io.storeAddrIn(w).valid &&
290      !io.storeAddrIn(w).bits.miss &&
291      blockSqIdx(i) === io.storeAddrIn(w).bits.uop.sqIdx
292    })).asUInt.orR // for better timing
293
294    // store data execute
295    storeDataInSameCycleVec(i) := VecInit((0 until StorePipelineWidth).map(w => {
296      io.storeDataIn(w).valid &&
297      blockSqIdx(i) === io.storeDataIn(w).bits.uop.sqIdx
298    })).asUInt.orR // for better timing
299
300  }
301
302  // store addr issue check
303  val stAddrDeqVec = Wire(Vec(LoadQueueReplaySize, Bool()))
304  (0 until LoadQueueReplaySize).map(i => {
305    stAddrDeqVec(i) := allocated(i) && storeAddrValidVec(i)
306  })
307
308  // store data issue check
309  val stDataDeqVec = Wire(Vec(LoadQueueReplaySize, Bool()))
310  (0 until LoadQueueReplaySize).map(i => {
311    stDataDeqVec(i) := allocated(i) && storeDataValidVec(i)
312  })
313
314  // update blocking condition
315  (0 until LoadQueueReplaySize).map(i => {
316    // case C_MA
317    when (cause(i)(LoadReplayCauses.C_MA)) {
318      blocking(i) := Mux(stAddrDeqVec(i), false.B, blocking(i))
319    }
320    // case C_TM
321    when (cause(i)(LoadReplayCauses.C_TM)) {
322      blocking(i) := Mux(io.tlb_hint.resp.valid &&
323                     (io.tlb_hint.resp.bits.replay_all ||
324                     io.tlb_hint.resp.bits.id === tlbHintId(i)), false.B, blocking(i))
325    }
326    // case C_FF
327    when (cause(i)(LoadReplayCauses.C_FF)) {
328      blocking(i) := Mux(stDataDeqVec(i), false.B, blocking(i))
329    }
330    // case C_DM
331    when (cause(i)(LoadReplayCauses.C_DM)) {
332      blocking(i) := Mux(io.tl_d_channel.valid && io.tl_d_channel.mshrid === missMSHRId(i), false.B, blocking(i))
333    }
334    // case C_RAR
335    when (cause(i)(LoadReplayCauses.C_RAR)) {
336      blocking(i) := Mux((!io.rarFull || !isAfter(uop(i).lqIdx, io.ldWbPtr)), false.B, blocking(i))
337    }
338    // case C_RAW
339    when (cause(i)(LoadReplayCauses.C_RAW)) {
340      blocking(i) := Mux((!io.rawFull || !isAfter(uop(i).sqIdx, io.stAddrReadySqPtr)), false.B, blocking(i))
341    }
342  })
343
344  //  Replay is splitted into 3 stages
345  require((LoadQueueReplaySize % LoadPipelineWidth) == 0)
346  def getRemBits(input: UInt)(rem: Int): UInt = {
347    VecInit((0 until LoadQueueReplaySize / LoadPipelineWidth).map(i => { input(LoadPipelineWidth * i + rem) })).asUInt
348  }
349
350  def getRemSeq(input: Seq[Seq[Bool]])(rem: Int) = {
351    (0 until LoadQueueReplaySize / LoadPipelineWidth).map(i => { input(LoadPipelineWidth * i + rem) })
352  }
353
354  // stage1: select 2 entries and read their vaddr
355  val s0_oldestSel = Wire(Vec(LoadPipelineWidth, Valid(UInt(LoadQueueReplaySize.W))))
356  val s1_can_go = Wire(Vec(LoadPipelineWidth, Bool()))
357  val s1_oldestSel = Wire(Vec(LoadPipelineWidth, Valid(UInt(log2Up(LoadQueueReplaySize + 1).W))))
358  val s2_can_go = Wire(Vec(LoadPipelineWidth, Bool()))
359  val s2_oldestSel = Wire(Vec(LoadPipelineWidth, Valid(UInt(log2Up(LoadQueueReplaySize + 1).W))))
360
361  // generate mask
362  val needCancel = Wire(Vec(LoadQueueReplaySize, Bool()))
363  // generate enq mask
364  val enqIndexOH = Wire(Vec(LoadPipelineWidth, UInt(LoadQueueReplaySize.W)))
365  val s0_loadEnqFireMask = io.enq.map(x => x.fire && !x.bits.isLoadReplay).zip(enqIndexOH).map(x => Mux(x._1, x._2, 0.U))
366  val s0_remLoadEnqFireVec = s0_loadEnqFireMask.map(x => VecInit((0 until LoadPipelineWidth).map(rem => getRemBits(x)(rem))))
367  val s0_remEnqSelVec = Seq.tabulate(LoadPipelineWidth)(w => VecInit(s0_remLoadEnqFireVec.map(x => x(w))))
368
369  // generate free mask
370  val s0_loadFreeSelMask = RegNext(needCancel.asUInt)
371  val s0_remFreeSelVec = VecInit(Seq.tabulate(LoadPipelineWidth)(rem => getRemBits(s0_loadFreeSelMask)(rem)))
372
373  // l2 hint wakes up cache missed load
374  // l2 will send GrantData in next 2/3 cycle, wake up the missed load early and sent them to load pipe, so them will hit the data in D channel or mshr in load S1
375  val s0_loadHintWakeMask = VecInit((0 until LoadQueueReplaySize).map(i => {
376    allocated(i) && !scheduled(i) && cause(i)(LoadReplayCauses.C_DM) && blocking(i) && missMSHRId(i) === io.l2_hint.bits.sourceId && io.l2_hint.valid
377  })).asUInt
378  // l2 will send 2 beats data in 2 cycles, so if data needed by this load is in first beat, select it this cycle, otherwise next cycle
379  val s0_loadHintSelMask = s0_loadHintWakeMask & VecInit(dataInLastBeatReg.map(!_)).asUInt
380  val s0_remLoadHintSelMask = VecInit((0 until LoadPipelineWidth).map(rem => getRemBits(s0_loadHintSelMask)(rem)))
381  val s0_remHintSelValidVec = VecInit((0 until LoadPipelineWidth).map(rem => ParallelORR(s0_remLoadHintSelMask(rem))))
382  val s0_hintSelValid = ParallelORR(s0_loadHintSelMask)
383
384  // wake up cache missed load
385  (0 until LoadQueueReplaySize).foreach(i => {
386    when(s0_loadHintWakeMask(i)) {
387      blocking(i) := false.B
388    }
389  })
390
391  // generate replay mask
392  // replay select priority is given as follow
393  // 1. hint wake up load
394  // 2. higher priority load
395  // 3. lower priority load
396  val s0_loadHigherPriorityReplaySelMask = VecInit((0 until LoadQueueReplaySize).map(i => {
397    val hasHigherPriority = cause(i)(LoadReplayCauses.C_DM) || cause(i)(LoadReplayCauses.C_FF)
398    allocated(i) && !scheduled(i) && !blocking(i) && hasHigherPriority
399  })).asUInt // use uint instead vec to reduce verilog lines
400  val s0_remLoadHigherPriorityReplaySelMask = VecInit((0 until LoadPipelineWidth).map(rem => getRemBits(s0_loadHigherPriorityReplaySelMask)(rem)))
401  val s0_loadLowerPriorityReplaySelMask = VecInit((0 until LoadQueueReplaySize).map(i => {
402    val hasLowerPriority = !cause(i)(LoadReplayCauses.C_DM) && !cause(i)(LoadReplayCauses.C_FF)
403    allocated(i) && !scheduled(i) && !blocking(i) && hasLowerPriority
404  })).asUInt // use uint instead vec to reduce verilog lines
405  val s0_remLoadLowerPriorityReplaySelMask = VecInit((0 until LoadPipelineWidth).map(rem => getRemBits(s0_loadLowerPriorityReplaySelMask)(rem)))
406  val s0_loadNormalReplaySelMask = s0_loadLowerPriorityReplaySelMask | s0_loadHigherPriorityReplaySelMask | s0_loadHintSelMask
407  val s0_remNormalReplaySelVec = VecInit((0 until LoadPipelineWidth).map(rem => s0_remLoadLowerPriorityReplaySelMask(rem) | s0_remLoadHigherPriorityReplaySelMask(rem) | s0_remLoadHintSelMask(rem)))
408  val s0_remPriorityReplaySelVec = VecInit((0 until LoadPipelineWidth).map(rem => {
409        Mux(s0_remHintSelValidVec(rem), s0_remLoadHintSelMask(rem),
410          Mux(ParallelORR(s0_remLoadHigherPriorityReplaySelMask(rem)), s0_remLoadHigherPriorityReplaySelMask(rem), s0_remLoadLowerPriorityReplaySelMask(rem)))
411      }))
412  /******************************************************************************************************
413   * WARNING: Make sure that OldestSelectStride must less than or equal stages of load pipeline.        *
414   ******************************************************************************************************
415   */
416  val OldestSelectStride = 4
417  val oldestPtrExt = (0 until OldestSelectStride).map(i => io.ldWbPtr + i.U)
418  val s0_oldestMatchMaskVec = (0 until LoadQueueReplaySize).map(i => (0 until OldestSelectStride).map(j => s0_loadNormalReplaySelMask(i) && uop(i).lqIdx === oldestPtrExt(j)))
419  val s0_remOldsetMatchMaskVec = (0 until LoadPipelineWidth).map(rem => getRemSeq(s0_oldestMatchMaskVec.map(_.take(1)))(rem))
420  val s0_remOlderMatchMaskVec = (0 until LoadPipelineWidth).map(rem => getRemSeq(s0_oldestMatchMaskVec.map(_.drop(1)))(rem))
421  val s0_remOldestSelVec = VecInit(Seq.tabulate(LoadPipelineWidth)(rem => {
422    VecInit((0 until LoadQueueReplaySize / LoadPipelineWidth).map(i => {
423      Mux(ParallelORR(s0_remOldsetMatchMaskVec(rem).map(_(0))), s0_remOldsetMatchMaskVec(rem)(i)(0), s0_remOlderMatchMaskVec(rem)(i).reduce(_|_))
424    })).asUInt
425  }))
426  val s0_remOldestHintSelVec = s0_remOldestSelVec.zip(s0_remLoadHintSelMask).map {
427    case(oldestVec, hintVec) => oldestVec & hintVec
428  }
429
430  // select oldest logic
431  s0_oldestSel := VecInit((0 until LoadPipelineWidth).map(rport => {
432    // select enqueue earlest inst
433    val ageOldest = AgeDetector(LoadQueueReplaySize / LoadPipelineWidth, s0_remEnqSelVec(rport), s0_remFreeSelVec(rport), s0_remPriorityReplaySelVec(rport))
434    assert(!(ageOldest.valid && PopCount(ageOldest.bits) > 1.U), "oldest index must be one-hot!")
435    val ageOldestValid = ageOldest.valid
436    val ageOldestIndexOH = ageOldest.bits
437
438    // select program order oldest
439    val l2HintFirst = io.l2_hint.valid && ParallelORR(s0_remOldestHintSelVec(rport))
440    val issOldestValid = l2HintFirst || ParallelORR(s0_remOldestSelVec(rport))
441    val issOldestIndexOH = Mux(l2HintFirst, PriorityEncoderOH(s0_remOldestHintSelVec(rport)), PriorityEncoderOH(s0_remOldestSelVec(rport)))
442
443    val oldest = Wire(Valid(UInt()))
444    val oldestSel = Mux(issOldestValid, issOldestIndexOH, ageOldestIndexOH)
445    val oldestBitsVec = Wire(Vec(LoadQueueReplaySize, Bool()))
446
447    require((LoadQueueReplaySize % LoadPipelineWidth) == 0)
448    oldestBitsVec.foreach(e => e := false.B)
449    for (i <- 0 until LoadQueueReplaySize / LoadPipelineWidth) {
450      oldestBitsVec(i * LoadPipelineWidth + rport) := oldestSel(i)
451    }
452
453    oldest.valid := ageOldest.valid || issOldestValid
454    oldest.bits := oldestBitsVec.asUInt
455    oldest
456  }))
457
458  // stage2: send replay request to load unit
459  // replay cold down
460  val ColdDownCycles = 16
461  val coldCounter = RegInit(VecInit(List.fill(LoadPipelineWidth)(0.U(log2Up(ColdDownCycles).W))))
462  val ColdDownThreshold = Wire(UInt(log2Up(ColdDownCycles).W))
463  ColdDownThreshold := Constantin.createRecord("ColdDownThreshold_"+p(XSCoreParamsKey).HartId.toString(), initValue = 12.U)
464  assert(ColdDownCycles.U > ColdDownThreshold, "ColdDownCycles must great than ColdDownThreshold!")
465
466  def replayCanFire(i: Int) = coldCounter(i) >= 0.U && coldCounter(i) < ColdDownThreshold
467  def coldDownNow(i: Int) = coldCounter(i) >= ColdDownThreshold
468
469  val replay_req = Wire(Vec(LoadPipelineWidth, DecoupledIO(new LsPipelineBundle)))
470
471  for (i <- 0 until LoadPipelineWidth) {
472    val s0_can_go = s1_can_go(i) ||
473                    uop(s1_oldestSel(i).bits).robIdx.needFlush(io.redirect) ||
474                    uop(s1_oldestSel(i).bits).robIdx.needFlush(RegNext(io.redirect))
475    val s0_oldestSelIndexOH = s0_oldestSel(i).bits // one-hot
476    s1_oldestSel(i).valid := RegEnable(s0_oldestSel(i).valid, s0_can_go)
477    s1_oldestSel(i).bits := RegEnable(OHToUInt(s0_oldestSel(i).bits), s0_can_go)
478
479    for (j <- 0 until LoadQueueReplaySize) {
480      when (s0_can_go && s0_oldestSel(i).valid && s0_oldestSelIndexOH(j)) {
481        scheduled(j) := true.B
482      }
483    }
484  }
485  val s2_cancelReplay = Wire(Vec(LoadPipelineWidth, Bool()))
486  for (i <- 0 until LoadPipelineWidth) {
487    val s1_cancel = uop(s1_oldestSel(i).bits).robIdx.needFlush(io.redirect) ||
488                    uop(s1_oldestSel(i).bits).robIdx.needFlush(RegNext(io.redirect))
489    val s1_oldestSelV = s1_oldestSel(i).valid && !s1_cancel
490    s1_can_go(i)          := replayCanFire(i) && (!s2_oldestSel(i).valid || replay_req(i).fire) || s2_cancelReplay(i)
491    s2_oldestSel(i).valid := RegEnable(Mux(s1_can_go(i), s1_oldestSelV, false.B), (s1_can_go(i) || replay_req(i).fire))
492    s2_oldestSel(i).bits  := RegEnable(s1_oldestSel(i).bits, s1_can_go(i))
493
494    vaddrModule.io.ren(i) := s1_oldestSel(i).valid && s1_can_go(i)
495    vaddrModule.io.raddr(i) := s1_oldestSel(i).bits
496  }
497
498  for (i <- 0 until LoadPipelineWidth) {
499    val s1_replayIdx = s1_oldestSel(i).bits
500    val s2_replayUop = RegEnable(uop(s1_replayIdx), s1_can_go(i))
501    val s2_replayMSHRId = RegEnable(missMSHRId(s1_replayIdx), s1_can_go(i))
502    val s2_replacementUpdated = RegEnable(replacementUpdated(s1_replayIdx), s1_can_go(i))
503    val s2_missDbUpdated = RegEnable(missDbUpdated(s1_replayIdx), s1_can_go(i))
504    val s2_replayCauses = RegEnable(cause(s1_replayIdx), s1_can_go(i))
505    val s2_replayCarry = RegEnable(replayCarryReg(s1_replayIdx), s1_can_go(i))
506    val s2_replayCacheMissReplay = RegEnable(trueCacheMissReplay(s1_replayIdx), s1_can_go(i))
507    s2_cancelReplay(i) := s2_replayUop.robIdx.needFlush(io.redirect)
508
509    s2_can_go(i) := DontCare
510    replay_req(i).valid             := s2_oldestSel(i).valid
511    replay_req(i).bits              := DontCare
512    replay_req(i).bits.uop          := s2_replayUop
513    replay_req(i).bits.vaddr        := vaddrModule.io.rdata(i)
514    replay_req(i).bits.isFirstIssue := false.B
515    replay_req(i).bits.isLoadReplay := true.B
516    replay_req(i).bits.replayCarry  := s2_replayCarry
517    replay_req(i).bits.mshrid       := s2_replayMSHRId
518    replay_req(i).bits.replacementUpdated := s2_replacementUpdated
519    replay_req(i).bits.missDbUpdated := s2_missDbUpdated
520    replay_req(i).bits.forward_tlDchannel := s2_replayCauses(LoadReplayCauses.C_DM)
521    replay_req(i).bits.schedIndex   := s2_oldestSel(i).bits
522    replay_req(i).bits.uop.loadWaitStrict := false.B
523
524    when (replay_req(i).fire) {
525      XSError(!allocated(s2_oldestSel(i).bits), p"LoadQueueReplay: why replay an invalid entry ${s2_oldestSel(i).bits} ?")
526    }
527  }
528
529  val EnableHybridUnitReplay = Constantin.createRecord("EnableHybridUnitReplay", true.B)(0)
530  when(EnableHybridUnitReplay) {
531    for (i <- 0 until LoadPipelineWidth)
532      io.replay(i) <> replay_req(i)
533  }.otherwise {
534    io.replay(0) <> replay_req(0)
535    io.replay(2).valid := false.B
536    io.replay(2).bits := DontCare
537
538    val arbiter = Module(new RRArbiter(new LsPipelineBundle, 2))
539    arbiter.io.in(0) <> replay_req(1)
540    arbiter.io.in(1) <> replay_req(2)
541    io.replay(1) <> arbiter.io.out
542  }
543  // update cold counter
544  val lastReplay = RegNext(VecInit(io.replay.map(_.fire)))
545  for (i <- 0 until LoadPipelineWidth) {
546    when (lastReplay(i) && io.replay(i).fire) {
547      coldCounter(i) := coldCounter(i) + 1.U
548    } .elsewhen (coldDownNow(i)) {
549      coldCounter(i) := coldCounter(i) + 1.U
550    } .otherwise {
551      coldCounter(i) := 0.U
552    }
553  }
554
555  when(io.refill.valid) {
556    XSDebug("miss resp: paddr:0x%x data %x\n", io.refill.bits.addr, io.refill.bits.data)
557  }
558
559  //  LoadQueueReplay deallocate
560  val freeMaskVec = Wire(Vec(LoadQueueReplaySize, Bool()))
561
562  // init
563  freeMaskVec.map(e => e := false.B)
564
565  // Allocate logic
566  val newEnqueue = (0 until LoadPipelineWidth).map(i => {
567    needEnqueue(i) && !io.enq(i).bits.isLoadReplay
568  })
569
570  for ((enq, w) <- io.enq.zipWithIndex) {
571    vaddrModule.io.wen(w) := false.B
572    freeList.io.doAllocate(w) := false.B
573
574    freeList.io.allocateReq(w) := true.B
575
576    //  Allocated ready
577    val offset = PopCount(newEnqueue.take(w))
578    val canAccept = freeList.io.canAllocate(offset)
579    val enqIndex = Mux(enq.bits.isLoadReplay, enq.bits.schedIndex, freeList.io.allocateSlot(offset))
580    enqIndexOH(w) := UIntToOH(enqIndex)
581    enq.ready := Mux(enq.bits.isLoadReplay, true.B, canAccept)
582
583    when (needEnqueue(w) && enq.ready) {
584
585      val debug_robIdx = enq.bits.uop.robIdx.asUInt
586      XSError(allocated(enqIndex) && !enq.bits.isLoadReplay, p"LoadQueueReplay: can not accept more load, check: ldu $w, robIdx $debug_robIdx!")
587      XSError(hasExceptions(w), p"LoadQueueReplay: The instruction has exception, it can not be replay, check: ldu $w, robIdx $debug_robIdx!")
588
589      freeList.io.doAllocate(w) := !enq.bits.isLoadReplay
590
591      //  Allocate new entry
592      allocated(enqIndex) := true.B
593      scheduled(enqIndex) := false.B
594      uop(enqIndex)       := enq.bits.uop
595
596      vaddrModule.io.wen(w)   := true.B
597      vaddrModule.io.waddr(w) := enqIndex
598      vaddrModule.io.wdata(w) := enq.bits.vaddr
599      debug_vaddr(enqIndex)   := enq.bits.vaddr
600
601      /**
602       * used for feedback and replay
603       */
604      // set flags
605      val replayInfo = enq.bits.rep_info
606      val dataInLastBeat = replayInfo.last_beat
607      cause(enqIndex) := replayInfo.cause.asUInt
608
609
610      // init
611      blocking(enqIndex)     := true.B
612      strict(enqIndex)       := false.B
613
614      // update blocking pointer
615      when (replayInfo.cause(LoadReplayCauses.C_BC) ||
616            replayInfo.cause(LoadReplayCauses.C_NK) ||
617            replayInfo.cause(LoadReplayCauses.C_DR) ||
618            replayInfo.cause(LoadReplayCauses.C_WF)) {
619        // normal case: bank conflict or schedule error or dcache replay
620        // can replay next cycle
621        blocking(enqIndex) := false.B
622      }
623
624      // special case: tlb miss
625      when (replayInfo.cause(LoadReplayCauses.C_TM)) {
626        blocking(enqIndex) := !replayInfo.tlb_full &&
627          !(io.tlb_hint.resp.valid && (io.tlb_hint.resp.bits.id === replayInfo.tlb_id || io.tlb_hint.resp.bits.replay_all))
628        tlbHintId(enqIndex) := replayInfo.tlb_id
629      }
630
631      // special case: dcache miss
632      when (replayInfo.cause(LoadReplayCauses.C_DM) && enq.bits.handledByMSHR) {
633        blocking(enqIndex) := !replayInfo.full_fwd && //  dcache miss
634                              !(io.tl_d_channel.valid && io.tl_d_channel.mshrid === replayInfo.mshr_id) // no refill in this cycle
635      }
636
637      // special case: st-ld violation
638      when (replayInfo.cause(LoadReplayCauses.C_MA)) {
639        blockSqIdx(enqIndex) := replayInfo.addr_inv_sq_idx
640        strict(enqIndex) := enq.bits.uop.loadWaitStrict
641      }
642
643      // special case: data forward fail
644      when (replayInfo.cause(LoadReplayCauses.C_FF)) {
645        blockSqIdx(enqIndex) := replayInfo.data_inv_sq_idx
646      }
647      // extra info
648      replayCarryReg(enqIndex) := replayInfo.rep_carry
649      replacementUpdated(enqIndex) := enq.bits.replacementUpdated
650      missDbUpdated(enqIndex) := enq.bits.missDbUpdated
651      // update mshr_id only when the load has already been handled by mshr
652      when(enq.bits.handledByMSHR) {
653        missMSHRId(enqIndex) := replayInfo.mshr_id
654      }
655      dataInLastBeatReg(enqIndex) := dataInLastBeat
656    }
657
658    //
659    val schedIndex = enq.bits.schedIndex
660    when (enq.valid && enq.bits.isLoadReplay) {
661      when (!needReplay(w) || hasExceptions(w)) {
662        allocated(schedIndex) := false.B
663        freeMaskVec(schedIndex) := true.B
664      } .otherwise {
665        scheduled(schedIndex) := false.B
666      }
667    }
668  }
669
670  // vector load, all replay entries of same robidx and uopidx
671  // should be released when vlmergebuffer commit or flush
672  val vecLdCancel = Wire(Vec(LoadQueueReplaySize, Bool()))
673  val vecLdCommit = Wire(Vec(LoadQueueReplaySize, Bool()))
674  for (i <- 0 until LoadQueueReplaySize) {
675    vecLdCancel(i) := io.vecFeedback.valid && io.vecFeedback.bits.isFlush && uop(i).robIdx === io.vecFeedback.bits.robidx && uop(i).uopIdx === io.vecFeedback.bits.uopidx
676    vecLdCommit(i) := io.vecFeedback.valid && io.vecFeedback.bits.isCommit && uop(i).robIdx === io.vecFeedback.bits.robidx && uop(i).uopIdx === io.vecFeedback.bits.uopidx
677    XSError(vecLdCancel(i) || vecLdCommit(i), s"vector load, should not have replay entry $i when commit or flush.\n")
678  }
679
680  // misprediction recovery / exception redirect
681  for (i <- 0 until LoadQueueReplaySize) {
682    needCancel(i) := uop(i).robIdx.needFlush(io.redirect) && allocated(i)
683    when (needCancel(i)) {
684      allocated(i) := false.B
685      freeMaskVec(i) := true.B
686    }
687  }
688
689  freeList.io.free := freeMaskVec.asUInt
690
691  io.lqFull := lqFull
692
693  // Topdown
694  val robHeadVaddr = io.debugTopDown.robHeadVaddr
695
696  val uop_wrapper = Wire(Vec(LoadQueueReplaySize, new XSBundleWithMicroOp))
697  (uop_wrapper.zipWithIndex).foreach {
698    case (u, i) => {
699      u.uop := uop(i)
700    }
701  }
702  val lq_match_vec = (debug_vaddr.zip(allocated)).map{case(va, alloc) => alloc && (va === robHeadVaddr.bits)}
703  val rob_head_lq_match = ParallelOperation(lq_match_vec.zip(uop_wrapper), (a: Tuple2[Bool, XSBundleWithMicroOp], b: Tuple2[Bool, XSBundleWithMicroOp]) => {
704    val (a_v, a_uop) = (a._1, a._2)
705    val (b_v, b_uop) = (b._1, b._2)
706
707    val res = Mux(a_v && b_v, Mux(isAfter(a_uop.uop.robIdx, b_uop.uop.robIdx), b_uop, a_uop),
708                  Mux(a_v, a_uop,
709                      Mux(b_v, b_uop,
710                                a_uop)))
711    (a_v || b_v, res)
712  })
713
714  val lq_match_bits = rob_head_lq_match._2.uop
715  val lq_match      = rob_head_lq_match._1 && robHeadVaddr.valid
716  val lq_match_idx  = lq_match_bits.lqIdx.value
717
718  val rob_head_tlb_miss        = lq_match && cause(lq_match_idx)(LoadReplayCauses.C_TM)
719  val rob_head_nuke            = lq_match && cause(lq_match_idx)(LoadReplayCauses.C_NK)
720  val rob_head_mem_amb         = lq_match && cause(lq_match_idx)(LoadReplayCauses.C_MA)
721  val rob_head_confilct_replay = lq_match && cause(lq_match_idx)(LoadReplayCauses.C_BC)
722  val rob_head_forward_fail    = lq_match && cause(lq_match_idx)(LoadReplayCauses.C_FF)
723  val rob_head_mshrfull_replay = lq_match && cause(lq_match_idx)(LoadReplayCauses.C_DR)
724  val rob_head_dcache_miss     = lq_match && cause(lq_match_idx)(LoadReplayCauses.C_DM)
725  val rob_head_rar_nack        = lq_match && cause(lq_match_idx)(LoadReplayCauses.C_RAR)
726  val rob_head_raw_nack        = lq_match && cause(lq_match_idx)(LoadReplayCauses.C_RAW)
727  val rob_head_other_replay    = lq_match && (rob_head_rar_nack || rob_head_raw_nack || rob_head_forward_fail)
728
729  val rob_head_vio_replay = rob_head_nuke || rob_head_mem_amb
730
731  val rob_head_miss_in_dtlb = io.debugTopDown.robHeadMissInDTlb
732  io.debugTopDown.robHeadTlbReplay := rob_head_tlb_miss && !rob_head_miss_in_dtlb
733  io.debugTopDown.robHeadTlbMiss := rob_head_tlb_miss && rob_head_miss_in_dtlb
734  io.debugTopDown.robHeadLoadVio := rob_head_vio_replay
735  io.debugTopDown.robHeadLoadMSHR := rob_head_mshrfull_replay
736  io.debugTopDown.robHeadOtherReplay := rob_head_other_replay
737  val perfValidCount = RegNext(PopCount(allocated))
738
739  //  perf cnt
740  val enqNumber               = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay))
741  val deqNumber               = PopCount(io.replay.map(_.fire))
742  val deqBlockCount           = PopCount(io.replay.map(r => r.valid && !r.ready))
743  val replayTlbMissCount      = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.rep_info.cause(LoadReplayCauses.C_TM)))
744  val replayMemAmbCount       = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.rep_info.cause(LoadReplayCauses.C_MA)))
745  val replayNukeCount         = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.rep_info.cause(LoadReplayCauses.C_NK)))
746  val replayRARRejectCount    = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.rep_info.cause(LoadReplayCauses.C_RAR)))
747  val replayRAWRejectCount    = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.rep_info.cause(LoadReplayCauses.C_RAW)))
748  val replayBankConflictCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.rep_info.cause(LoadReplayCauses.C_BC)))
749  val replayDCacheReplayCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.rep_info.cause(LoadReplayCauses.C_DR)))
750  val replayForwardFailCount  = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.rep_info.cause(LoadReplayCauses.C_FF)))
751  val replayDCacheMissCount   = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.rep_info.cause(LoadReplayCauses.C_DM)))
752  XSPerfAccumulate("enq", enqNumber)
753  XSPerfAccumulate("deq", deqNumber)
754  XSPerfAccumulate("deq_block", deqBlockCount)
755  XSPerfAccumulate("replay_full", io.lqFull)
756  XSPerfAccumulate("replay_rar_nack", replayRARRejectCount)
757  XSPerfAccumulate("replay_raw_nack", replayRAWRejectCount)
758  XSPerfAccumulate("replay_nuke", replayNukeCount)
759  XSPerfAccumulate("replay_mem_amb", replayMemAmbCount)
760  XSPerfAccumulate("replay_tlb_miss", replayTlbMissCount)
761  XSPerfAccumulate("replay_bank_conflict", replayBankConflictCount)
762  XSPerfAccumulate("replay_dcache_replay", replayDCacheReplayCount)
763  XSPerfAccumulate("replay_forward_fail", replayForwardFailCount)
764  XSPerfAccumulate("replay_dcache_miss", replayDCacheMissCount)
765  XSPerfAccumulate("replay_hint_wakeup", s0_hintSelValid)
766
767  val perfEvents: Seq[(String, UInt)] = Seq(
768    ("enq", enqNumber),
769    ("deq", deqNumber),
770    ("deq_block", deqBlockCount),
771    ("replay_full", io.lqFull),
772    ("replay_rar_nack", replayRARRejectCount),
773    ("replay_raw_nack", replayRAWRejectCount),
774    ("replay_nuke", replayNukeCount),
775    ("replay_mem_amb", replayMemAmbCount),
776    ("replay_tlb_miss", replayTlbMissCount),
777    ("replay_bank_conflict", replayBankConflictCount),
778    ("replay_dcache_replay", replayDCacheReplayCount),
779    ("replay_forward_fail", replayForwardFailCount),
780    ("replay_dcache_miss", replayDCacheMissCount),
781  )
782  generatePerfEvent()
783  // end
784}
785