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