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