xref: /XiangShan/src/main/scala/xiangshan/mem/lsqueue/LoadQueueReplay.scala (revision f2e8d4199f739189df4742717c087640527dec93)
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 chipsalliance.rocketchip.config._
21import xiangshan._
22import xiangshan.backend.rob.{RobPtr, RobLsqIO}
23import xiangshan.cache._
24import xiangshan.backend.fu.fpu.FPU
25import xiangshan.cache._
26import xiangshan.frontend.FtqPtr
27import xiangshan.ExceptionNO._
28import xiangshan.cache.dcache.ReplayCarry
29import xiangshan.mem.mdp._
30import utils._
31import utility._
32
33object LoadReplayCauses {
34  // these causes have priority, lower coding has higher priority.
35  // when load replay happens, load unit will select highest priority
36  // from replay causes vector
37
38  /*
39   * Warning:
40   * ************************************************************
41   * * Don't change the priority. If the priority is changed,   *
42   * * deadlock may occur. If you really need to change or      *
43   * * add priority, please ensure that no deadlock will occur. *
44   * ************************************************************
45   *
46   */
47  // st-ld violation
48  val waitStore         = 0
49  // tlb miss check
50  val tlbMiss           = 1
51  // st-ld violation re-execute check
52  val schedError        = 2
53  // dcache bank conflict check
54  val bankConflict      = 3
55  // store-to-load-forwarding check
56  val forwardFail       = 4
57  // dcache replay check
58  val dcacheReplay      = 5
59  // dcache miss check
60  val dcacheMiss        = 6
61  // RAR queue accept check
62  val rarReject         = 7
63  // RAW queue accept check
64  val rawReject         = 8
65  // total causes
66  val allCauses         = 9
67}
68
69class AgeDetector(numEntries: Int, numEnq: Int, regOut: Boolean = true)(implicit p: Parameters) extends XSModule {
70  val io = IO(new Bundle {
71    // NOTE: deq and enq may come at the same cycle.
72    val enq = Vec(numEnq, Input(UInt(numEntries.W)))
73    val deq = Input(UInt(numEntries.W))
74    val ready = Input(UInt(numEntries.W))
75    val out = Output(UInt(numEntries.W))
76  })
77
78  // age(i)(j): entry i enters queue before entry j
79  val age = Seq.fill(numEntries)(Seq.fill(numEntries)(RegInit(false.B)))
80  val nextAge = Seq.fill(numEntries)(Seq.fill(numEntries)(Wire(Bool())))
81
82  // to reduce reg usage, only use upper matrix
83  def get_age(row: Int, col: Int): Bool = if (row <= col) age(row)(col) else !age(col)(row)
84  def get_next_age(row: Int, col: Int): Bool = if (row <= col) nextAge(row)(col) else !nextAge(col)(row)
85  def isFlushed(i: Int): Bool = io.deq(i)
86  def isEnqueued(i: Int, numPorts: Int = -1): Bool = {
87    val takePorts = if (numPorts == -1) io.enq.length else numPorts
88    takePorts match {
89      case 0 => false.B
90      case 1 => io.enq.head(i) && !isFlushed(i)
91      case n => VecInit(io.enq.take(n).map(_(i))).asUInt.orR && !isFlushed(i)
92    }
93  }
94
95  for ((row, i) <- nextAge.zipWithIndex) {
96    val thisValid = get_age(i, i) || isEnqueued(i)
97    for ((elem, j) <- row.zipWithIndex) {
98      when (isFlushed(i)) {
99        // (1) when entry i is flushed or dequeues, set row(i) to false.B
100        elem := false.B
101      }.elsewhen (isFlushed(j)) {
102        // (2) when entry j is flushed or dequeues, set column(j) to validVec
103        elem := thisValid
104      }.elsewhen (isEnqueued(i)) {
105        // (3) when entry i enqueues from port k,
106        // (3.1) if entry j enqueues from previous ports, set to false
107        // (3.2) otherwise, set to true if and only of entry j is invalid
108        // overall: !jEnqFromPreviousPorts && !jIsValid
109        val sel = io.enq.map(_(i))
110        val result = (0 until numEnq).map(k => isEnqueued(j, k))
111        // why ParallelMux: sel must be one-hot since enq is one-hot
112        elem := !get_age(j, j) && !ParallelMux(sel, result)
113      }.otherwise {
114        // default: unchanged
115        elem := get_age(i, j)
116      }
117      age(i)(j) := elem
118    }
119  }
120
121  def getOldest(get: (Int, Int) => Bool): UInt = {
122    VecInit((0 until numEntries).map(i => {
123      io.ready(i) & VecInit((0 until numEntries).map(j => if (i != j) !io.ready(j) || get(i, j) else true.B)).asUInt.andR
124    })).asUInt
125  }
126  val best = getOldest(get_age)
127  val nextBest = getOldest(get_next_age)
128
129  io.out := (if (regOut) best else nextBest)
130}
131
132object AgeDetector {
133  def apply(numEntries: Int, enq: Vec[UInt], deq: UInt, ready: UInt)(implicit p: Parameters): Valid[UInt] = {
134    val age = Module(new AgeDetector(numEntries, enq.length, regOut = true))
135    age.io.enq := enq
136    age.io.deq := deq
137    age.io.ready:= ready
138    val out = Wire(Valid(UInt(deq.getWidth.W)))
139    out.valid := age.io.out.orR
140    out.bits := age.io.out
141    out
142  }
143}
144
145
146class LoadQueueReplay(implicit p: Parameters) extends XSModule
147  with HasDCacheParameters
148  with HasCircularQueuePtrHelper
149  with HasLoadHelper
150  with HasPerfEvents
151{
152  val io = IO(new Bundle() {
153    val redirect = Flipped(ValidIO(new Redirect))
154    val enq = Vec(LoadPipelineWidth, Flipped(Decoupled(new LqWriteBundle)))
155    val storeAddrIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle)))
156    val storeDataIn = Vec(StorePipelineWidth, Flipped(Valid(new ExuOutput)))
157    val replay = Vec(LoadPipelineWidth, Decoupled(new LsPipelineBundle))
158    val refill = Flipped(ValidIO(new Refill))
159    val stAddrReadySqPtr = Input(new SqPtr)
160    val stAddrReadyVec = Input(Vec(StoreQueueSize, Bool()))
161    val stDataReadySqPtr = Input(new SqPtr)
162    val stDataReadyVec = Input(Vec(StoreQueueSize, Bool()))
163    val sqEmpty = Input(Bool())
164    val lqFull = Output(Bool())
165    val ldWbPtr = Input(new LqPtr)
166    val tlbReplayDelayCycleCtrl = Vec(4, Input(UInt(ReSelectLen.W)))
167    val rarFull = Input(Bool())
168    val rawFull = Input(Bool())
169  })
170
171  println("LoadQueueReplay size: " + LoadQueueReplaySize)
172  //  LoadQueueReplay field:
173  //  +-----------+---------+-------+-------------+--------+
174  //  | Allocated | MicroOp | VAddr |    Cause    |  Flags |
175  //  +-----------+---------+-------+-------------+--------+
176  //  Allocated   : entry has been allocated already
177  //  MicroOp     : inst's microOp
178  //  VAddr       : virtual address
179  //  Cause       : replay cause
180  //  Flags       : rar/raw queue allocate flags
181  val allocated = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B))) // The control signals need to explicitly indicate the initial value
182  val sleep = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
183  val uop = Reg(Vec(LoadQueueReplaySize, new MicroOp))
184  val vaddrModule = Module(new LqVAddrModule(
185    gen = UInt(VAddrBits.W),
186    numEntries = LoadQueueReplaySize,
187    numRead = LoadPipelineWidth,
188    numWrite = LoadPipelineWidth,
189    numWBank = LoadQueueNWriteBanks,
190    numWDelay = 2,
191    numCamPort = 0))
192  vaddrModule.io := DontCare
193  val cause = RegInit(VecInit(List.fill(LoadQueueReplaySize)(0.U(LoadReplayCauses.allCauses.W))))
194
195  // freeliset: store valid entries index.
196  // +---+---+--------------+-----+-----+
197  // | 0 | 1 |      ......  | n-2 | n-1 |
198  // +---+---+--------------+-----+-----+
199  val freeList = Module(new FreeList(
200    size = LoadQueueReplaySize,
201    allocWidth = LoadPipelineWidth,
202    freeWidth = 4,
203    moduleName = "LoadQueueReplay freelist"
204  ))
205  freeList.io := DontCare
206  /**
207   * used for re-select control
208   */
209  val credit = RegInit(VecInit(List.fill(LoadQueueReplaySize)(0.U(ReSelectLen.W))))
210  val selBlocked = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
211  //  Ptrs to control which cycle to choose
212  val blockPtrTlb = RegInit(VecInit(List.fill(LoadQueueReplaySize)(0.U(2.W))))
213  val blockPtrCache = RegInit(VecInit(List.fill(LoadQueueReplaySize)(0.U(2.W))))
214  val blockPtrOthers = RegInit(VecInit(List.fill(LoadQueueReplaySize)(0.U(2.W))))
215  //  Specific cycles to block
216  val blockCyclesTlb = Reg(Vec(4, UInt(ReSelectLen.W)))
217  blockCyclesTlb := io.tlbReplayDelayCycleCtrl
218  val blockCyclesCache = RegInit(VecInit(Seq(11.U(ReSelectLen.W), 18.U(ReSelectLen.W), 127.U(ReSelectLen.W), 17.U(ReSelectLen.W))))
219  val blockCyclesOthers = RegInit(VecInit(Seq(0.U(ReSelectLen.W), 0.U(ReSelectLen.W), 0.U(ReSelectLen.W), 0.U(ReSelectLen.W))))
220  val blockSqIdx = Reg(Vec(LoadQueueReplaySize, new SqPtr))
221  // block causes
222  val blockByTlbMiss = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
223  val blockByForwardFail = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
224  val blockByWaitStore = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
225  val blockByCacheMiss = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
226  val blockByRARReject = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
227  val blockByRAWReject = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
228  val blockByOthers = RegInit(VecInit(List.fill(LoadQueueReplaySize)(false.B)))
229  //  DCache miss block
230  val missMSHRId = RegInit(VecInit(List.fill(LoadQueueReplaySize)(0.U((log2Up(cfg.nMissEntries).W)))))
231  val trueCacheMissReplay = WireInit(VecInit(cause.map(_(LoadReplayCauses.dcacheMiss))))
232  val creditUpdate = WireInit(VecInit(List.fill(LoadQueueReplaySize)(0.U(ReSelectLen.W))))
233  (0 until LoadQueueReplaySize).map(i => {
234    creditUpdate(i) := Mux(credit(i) > 0.U(ReSelectLen.W), credit(i)-1.U(ReSelectLen.W), credit(i))
235    selBlocked(i) := creditUpdate(i) =/= 0.U(ReSelectLen.W) || credit(i) =/= 0.U(ReSelectLen.W)
236  })
237  val replayCarryReg = RegInit(VecInit(List.fill(LoadQueueReplaySize)(ReplayCarry(0.U, false.B))))
238
239  /**
240   * Enqueue
241   */
242  val canEnqueue = io.enq.map(_.valid)
243  val cancelEnq = io.enq.map(enq => enq.bits.uop.robIdx.needFlush(io.redirect))
244  val needReplay = io.enq.map(enq => enq.bits.replayInfo.needReplay())
245  val hasExceptions = io.enq.map(enq => ExceptionNO.selectByFu(enq.bits.uop.cf.exceptionVec, lduCfg).asUInt.orR && !enq.bits.tlbMiss)
246  val loadReplay = io.enq.map(enq => enq.bits.isLoadReplay)
247  val needEnqueue = VecInit((0 until LoadPipelineWidth).map(w => {
248    canEnqueue(w) && !cancelEnq(w) && needReplay(w) && !hasExceptions(w)
249  }))
250  val canFreeVec = VecInit((0 until LoadPipelineWidth).map(w => {
251    canEnqueue(w) && loadReplay(w) && (!needReplay(w) || hasExceptions(w))
252  }))
253
254  // select LoadPipelineWidth valid index.
255  val lqFull = freeList.io.empty
256  val lqFreeNums = freeList.io.validCount
257
258  // replay logic
259  // release logic generation
260  val storeAddrInSameCycleVec = Wire(Vec(LoadQueueReplaySize, Bool()))
261  val storeDataInSameCycleVec = Wire(Vec(LoadQueueReplaySize, Bool()))
262  val addrNotBlockVec = Wire(Vec(LoadQueueReplaySize, Bool()))
263  val dataNotBlockVec = Wire(Vec(LoadQueueReplaySize, Bool()))
264  val storeAddrValidVec = addrNotBlockVec.asUInt | storeAddrInSameCycleVec.asUInt
265  val storeDataValidVec = dataNotBlockVec.asUInt | storeDataInSameCycleVec.asUInt
266
267  // store data valid check
268  val stAddrReadyVec = io.stAddrReadyVec
269  val stDataReadyVec = io.stDataReadyVec
270
271  for (i <- 0 until LoadQueueReplaySize) {
272    // dequeue
273    //  FIXME: store*Ptr is not accurate
274    dataNotBlockVec(i) := !isBefore(io.stDataReadySqPtr, blockSqIdx(i)) || stDataReadyVec(blockSqIdx(i).value) || io.sqEmpty // for better timing
275    addrNotBlockVec(i) := !isBefore(io.stAddrReadySqPtr, blockSqIdx(i)) || stAddrReadyVec(blockSqIdx(i).value) || io.sqEmpty // for better timing
276
277    // store address execute
278    storeAddrInSameCycleVec(i) := VecInit((0 until StorePipelineWidth).map(w => {
279      io.storeAddrIn(w).valid &&
280      !io.storeAddrIn(w).bits.miss &&
281      blockSqIdx(i) === io.storeAddrIn(w).bits.uop.sqIdx
282    })).asUInt.orR // for better timing
283
284    // store data execute
285    storeDataInSameCycleVec(i) := VecInit((0 until StorePipelineWidth).map(w => {
286      io.storeDataIn(w).valid &&
287      blockSqIdx(i) === io.storeDataIn(w).bits.uop.sqIdx
288    })).asUInt.orR // for better timing
289
290  }
291
292  // store addr issue check
293  val stAddrDeqVec = Wire(Vec(LoadQueueReplaySize, Bool()))
294  (0 until LoadQueueReplaySize).map(i => {
295    stAddrDeqVec(i) := allocated(i) && storeAddrValidVec(i)
296  })
297
298  // store data issue check
299  val stDataDeqVec = Wire(Vec(LoadQueueReplaySize, Bool()))
300  (0 until LoadQueueReplaySize).map(i => {
301    stDataDeqVec(i) := allocated(i) && storeDataValidVec(i)
302  })
303
304  // update block condition
305  (0 until LoadQueueReplaySize).map(i => {
306    blockByForwardFail(i) := Mux(blockByForwardFail(i) && stDataDeqVec(i), false.B, blockByForwardFail(i))
307    blockByWaitStore(i) := Mux(blockByWaitStore(i) && stAddrDeqVec(i), false.B, blockByWaitStore(i))
308    blockByCacheMiss(i) := Mux(blockByCacheMiss(i) && io.refill.valid && io.refill.bits.id === missMSHRId(i), false.B, blockByCacheMiss(i))
309
310    when (blockByCacheMiss(i) && io.refill.valid && io.refill.bits.id === missMSHRId(i)) { creditUpdate(i) := 0.U }
311    when (blockByCacheMiss(i) && creditUpdate(i) === 0.U) { blockByCacheMiss(i) := false.B }
312    when (blockByRARReject(i) && (!io.rarFull || !isAfter(uop(i).lqIdx, io.ldWbPtr))) { blockByRARReject(i) := false.B }
313    when (blockByRAWReject(i) && (!io.rawFull || !isAfter(uop(i).sqIdx, io.stAddrReadySqPtr))) { blockByRAWReject(i) := false.B }
314    when (blockByTlbMiss(i) && creditUpdate(i) === 0.U) { blockByTlbMiss(i) := false.B }
315    when (blockByOthers(i) && creditUpdate(i) === 0.U) { blockByOthers(i) := false.B }
316  })
317
318  //  Replay is splitted into 3 stages
319  def getRemBits(input: UInt)(rem: Int): UInt = {
320    VecInit((0 until LoadQueueReplaySize / LoadPipelineWidth).map(i => { input(LoadPipelineWidth * i + rem) })).asUInt
321  }
322
323  def getRemSeq(input: Seq[Seq[Bool]])(rem: Int) = {
324    (0 until LoadQueueReplaySize / LoadPipelineWidth).map(i => { input(LoadPipelineWidth * i + rem) })
325  }
326
327  // stage1: select 2 entries and read their vaddr
328  val s1_oldestSel = Wire(Vec(LoadPipelineWidth, Valid(UInt(log2Up(LoadQueueReplaySize).W))))
329  val s2_oldestSel = Wire(Vec(LoadPipelineWidth, Valid(UInt(log2Up(LoadQueueReplaySize).W))))
330
331  // generate mask
332  val needCancel = Wire(Vec(LoadQueueReplaySize, Bool()))
333  // generate enq mask
334  val selectIndexOH = Wire(Vec(LoadPipelineWidth, UInt(LoadQueueReplaySize.W)))
335  val loadEnqFireMask = io.enq.map(x => x.fire && !x.bits.isLoadReplay).zip(selectIndexOH).map(x => Mux(x._1, x._2, 0.U))
336  val remLoadEnqFireVec = loadEnqFireMask.map(x => VecInit((0 until LoadPipelineWidth).map(rem => getRemBits(x)(rem))))
337  val remEnqSelVec = Seq.tabulate(LoadPipelineWidth)(w => VecInit(remLoadEnqFireVec.map(x => x(w))))
338
339  // generate free mask
340  val loadReplayFreeMask = io.enq.map(_.bits).zip(canFreeVec).map(x => Mux(x._2, UIntToOH(x._1.sleepIndex), 0.U)).reduce(_|_)
341  val loadFreeSelMask = VecInit((0 until LoadQueueReplaySize).map(i => {
342    needCancel(i) || loadReplayFreeMask(i)
343  })).asUInt
344  val remFreeSelVec = VecInit(Seq.tabulate(LoadPipelineWidth)(rem => getRemBits(loadFreeSelMask)(rem)))
345
346  // generate cancel mask
347  val loadReplayFireMask = (0 until LoadPipelineWidth).map(w => Mux(io.replay(w).fire, UIntToOH(s2_oldestSel(w).bits), 0.U)).reduce(_|_)
348  val loadCancelSelMask = VecInit((0 until LoadQueueReplaySize).map(i => {
349    needCancel(i) || loadReplayFireMask(i)
350  })).asUInt
351  val remCancelSelVec = VecInit(Seq.tabulate(LoadPipelineWidth)(rem => getRemBits(loadCancelSelMask)(rem)))
352
353  // generate replay mask
354  val loadHigherPriorityReplaySelMask = VecInit((0 until LoadQueueReplaySize).map(i => {
355    val blocked = blockByForwardFail(i) || blockByCacheMiss(i) || blockByTlbMiss(i)
356    allocated(i) && sleep(i) && !blocked && !loadCancelSelMask(i)
357  })).asUInt // use uint instead vec to reduce verilog lines
358  val loadLowerPriorityReplaySelMask = VecInit((0 until LoadQueueReplaySize).map(i => {
359    val blocked = selBlocked(i)  || blockByWaitStore(i) || blockByRARReject(i) || blockByRAWReject(i) || blockByOthers(i)
360    allocated(i) && sleep(i) && !blocked && !loadCancelSelMask(i)
361  })).asUInt // use uint instead vec to reduce verilog lines
362  val loadNormalReplaySelMask = loadLowerPriorityReplaySelMask | loadHigherPriorityReplaySelMask
363  val remNormalReplaySelVec = VecInit((0 until LoadPipelineWidth).map(rem => getRemBits(loadNormalReplaySelMask)(rem)))
364  val loadPriorityReplaySelMask = Mux(loadHigherPriorityReplaySelMask.orR, loadHigherPriorityReplaySelMask, loadLowerPriorityReplaySelMask)
365  val remPriorityReplaySelVec = VecInit((0 until LoadPipelineWidth).map(rem => getRemBits(loadPriorityReplaySelMask)(rem)))
366
367  /******************************************************************************************
368   * WARNING: Make sure that OldestSelectStride must less than or equal stages of load unit.*
369   ******************************************************************************************
370   */
371  val OldestSelectStride = 4
372  val oldestPtrExt = (0 until OldestSelectStride).map(i => io.ldWbPtr + i.U)
373  val oldestMatchMaskVec = (0 until LoadQueueReplaySize).map(i => (0 until OldestSelectStride).map(j => loadNormalReplaySelMask(i) && uop(i).lqIdx === oldestPtrExt(j)))
374  val remOldsetMatchMaskVec = (0 until LoadPipelineWidth).map(rem => getRemSeq(oldestMatchMaskVec.map(_.take(1)))(rem))
375  val remOlderMatchMaskVec = (0 until LoadPipelineWidth).map(rem => getRemSeq(oldestMatchMaskVec.map(_.drop(1)))(rem))
376  val remOldestSelVec = VecInit(Seq.tabulate(LoadPipelineWidth)(rem => {
377    VecInit((0 until LoadQueueReplaySize / LoadPipelineWidth).map(i => {
378      Mux(VecInit(remOldsetMatchMaskVec(rem).map(_(0))).asUInt.orR, remOldsetMatchMaskVec(rem)(i)(0), remOlderMatchMaskVec(rem)(i).reduce(_|_))
379    })).asUInt
380  }))
381
382  // select oldest logic
383  s1_oldestSel := VecInit((0 until LoadPipelineWidth).map(rport => {
384    // select enqueue earlest inst
385    val ageOldest = AgeDetector(LoadQueueReplaySize / LoadPipelineWidth, remEnqSelVec(rport), remFreeSelVec(rport), remPriorityReplaySelVec(rport))
386    assert(!(ageOldest.valid && PopCount(ageOldest.bits) > 1.U), "oldest index must be one-hot!")
387    val ageOldestValid = ageOldest.valid
388    val ageOldestIndex = OHToUInt(ageOldest.bits)
389
390    // select program order oldest
391    val issOldestValid = remOldestSelVec(rport).orR
392    val issOldestIndex = OHToUInt(PriorityEncoderOH(remOldestSelVec(rport)))
393
394    val oldest = Wire(Valid(UInt()))
395    oldest.valid := ageOldest.valid || issOldestValid
396    oldest.bits := Cat(Mux(issOldestValid, issOldestIndex, ageOldestIndex), rport.U(log2Ceil(LoadPipelineWidth).W))
397    oldest
398  }))
399
400
401  // Replay port reorder
402  class BalanceEntry extends XSBundle {
403    val balance = Bool()
404    val index = UInt(log2Up(LoadQueueReplaySize).W)
405    val port = UInt(log2Up(LoadPipelineWidth).W)
406  }
407
408  def balanceReOrder(sel: Seq[ValidIO[BalanceEntry]]): Seq[ValidIO[BalanceEntry]] = {
409    require(sel.length > 0)
410    val balancePick = ParallelPriorityMux(sel.map(x => (x.valid && x.bits.balance) -> x))
411    val reorderSel = Wire(Vec(sel.length, ValidIO(new BalanceEntry)))
412    (0 until sel.length).map(i =>
413      if (i == 0) {
414        when (balancePick.valid && balancePick.bits.balance) {
415          reorderSel(i) := balancePick
416        } .otherwise {
417          reorderSel(i) := sel(i)
418        }
419      } else {
420        when (balancePick.valid && balancePick.bits.balance && i.U === balancePick.bits.port) {
421          reorderSel(i) := sel(0)
422        } .otherwise {
423          reorderSel(i) := sel(i)
424        }
425      }
426    )
427    reorderSel
428  }
429
430  // stage2: send replay request to load unit
431  // replay cold down
432  val ColdDownCycles = 16
433  val coldCounter = RegInit(VecInit(List.fill(LoadPipelineWidth)(0.U(log2Up(ColdDownCycles).W))))
434  val ColdDownThreshold = Wire(UInt(log2Up(ColdDownCycles).W))
435  ColdDownThreshold := Constantin.createRecord("ColdDownThreshold_"+p(XSCoreParamsKey).HartId.toString(), initValue = 12.U)
436  assert(ColdDownCycles.U > ColdDownThreshold, "ColdDownCycles must great than ColdDownThreshold!")
437
438  def replayCanFire(i: Int) = coldCounter(i) >= 0.U && coldCounter(i) < ColdDownThreshold
439  def coldDownNow(i: Int) = coldCounter(i) >= ColdDownThreshold
440
441  val s1_balanceOldestSelExt = (0 until LoadPipelineWidth).map(i => {
442    val wrapper = Wire(Valid(new BalanceEntry))
443    wrapper.valid := s1_oldestSel(i).valid
444    wrapper.bits.balance := cause(s1_oldestSel(i).bits)(LoadReplayCauses.bankConflict)
445    wrapper.bits.index := s1_oldestSel(i).bits
446    wrapper.bits.port := i.U
447    wrapper
448  })
449  val s1_balanceOldestSel = balanceReOrder(s1_balanceOldestSelExt)
450  (0 until LoadPipelineWidth).map(w => {
451    vaddrModule.io.raddr(w) := s1_balanceOldestSel(w).bits.index
452  })
453
454  for (i <- 0 until LoadPipelineWidth) {
455    val s2_replayIdx = RegNext(s1_balanceOldestSel(i).bits.index)
456    val s2_replayUop = uop(s2_replayIdx)
457    val s2_replayMSHRId = missMSHRId(s2_replayIdx)
458    val s2_replayCauses = cause(s2_replayIdx)
459    val s2_replayCarry = replayCarryReg(s2_replayIdx)
460    val s2_replayCacheMissReplay = trueCacheMissReplay(s2_replayIdx)
461    val cancelReplay = s2_replayUop.robIdx.needFlush(io.redirect)
462
463    val s2_loadCancelSelMask = RegNext(loadCancelSelMask)
464    s2_oldestSel(i).valid := RegNext(s1_balanceOldestSel(i).valid) && !s2_loadCancelSelMask(s2_replayIdx)
465    s2_oldestSel(i).bits := s2_replayIdx
466
467    io.replay(i).valid := s2_oldestSel(i).valid && !cancelReplay && replayCanFire(i)
468    io.replay(i).bits := DontCare
469    io.replay(i).bits.uop := s2_replayUop
470    io.replay(i).bits.vaddr := vaddrModule.io.rdata(i)
471    io.replay(i).bits.isFirstIssue := false.B
472    io.replay(i).bits.isLoadReplay := true.B
473    io.replay(i).bits.replayCarry := s2_replayCarry
474    io.replay(i).bits.mshrid := s2_replayMSHRId
475    io.replay(i).bits.forward_tlDchannel := s2_replayCauses(LoadReplayCauses.dcacheMiss)
476    io.replay(i).bits.sleepIndex := s2_oldestSel(i).bits
477
478    when (io.replay(i).fire) {
479      sleep(s2_oldestSel(i).bits) := false.B
480      assert(allocated(s2_oldestSel(i).bits), s"LoadQueueReplay: why replay an invalid entry ${s2_oldestSel(i).bits} ?\n")
481    }
482  }
483
484  // update cold counter
485  val lastReplay = RegNext(VecInit(io.replay.map(_.fire)))
486  for (i <- 0 until LoadPipelineWidth) {
487    when (lastReplay(i) && io.replay(i).fire) {
488      coldCounter(i) := coldCounter(i) + 1.U
489    } .elsewhen (coldDownNow(i)) {
490      coldCounter(i) := coldCounter(i) + 1.U
491    } .otherwise {
492      coldCounter(i) := 0.U
493    }
494  }
495
496  when(io.refill.valid) {
497    XSDebug("miss resp: paddr:0x%x data %x\n", io.refill.bits.addr, io.refill.bits.data)
498  }
499
500  //  LoadQueueReplay deallocate
501  val freeMaskVec = Wire(Vec(LoadQueueReplaySize, Bool()))
502
503  // init
504  freeMaskVec.map(e => e := false.B)
505
506  // Allocate logic
507  val enqValidVec = Wire(Vec(LoadPipelineWidth, Bool()))
508  val enqIndexVec = Wire(Vec(LoadPipelineWidth, UInt()))
509  val enqOffset = Wire(Vec(LoadPipelineWidth, UInt()))
510
511  val newEnqueue = (0 until LoadPipelineWidth).map(i => {
512    needEnqueue(i) && !io.enq(i).bits.isLoadReplay
513  })
514
515  for ((enq, w) <- io.enq.zipWithIndex) {
516    vaddrModule.io.wen(w) := false.B
517    freeList.io.doAllocate(w) := false.B
518
519    enqOffset(w) := PopCount(newEnqueue.take(w))
520    freeList.io.allocateReq(w) := newEnqueue(w)
521
522    //  Allocated ready
523    enqValidVec(w) := freeList.io.canAllocate(enqOffset(w))
524    enqIndexVec(w) := Mux(enq.bits.isLoadReplay, enq.bits.sleepIndex, freeList.io.allocateSlot(enqOffset(w)))
525    selectIndexOH(w) := UIntToOH(enqIndexVec(w))
526    enq.ready := Mux(enq.bits.isLoadReplay, true.B, enqValidVec(w))
527
528    val enqIndex = enqIndexVec(w)
529    when (needEnqueue(w) && enq.ready) {
530
531      val debug_robIdx = enq.bits.uop.robIdx.asUInt
532      XSError(allocated(enqIndex) && !enq.bits.isLoadReplay, p"LoadQueueReplay: can not accept more load, check: ldu $w, robIdx $debug_robIdx!")
533      XSError(hasExceptions(w), p"LoadQueueReplay: The instruction has exception, it can not be replay, check: ldu $w, robIdx $debug_robIdx!")
534
535      freeList.io.doAllocate(w) := !enq.bits.isLoadReplay
536
537      //  Allocate new entry
538      allocated(enqIndex) := true.B
539      sleep(enqIndex) := true.B
540      uop(enqIndex) := enq.bits.uop
541
542      vaddrModule.io.wen(w) := true.B
543      vaddrModule.io.waddr(w) := enqIndex
544      vaddrModule.io.wdata(w) := enq.bits.vaddr
545
546      /**
547       * used for feedback and replay
548       */
549      // set flags
550      val replayInfo = enq.bits.replayInfo
551      val dataInLastBeat = replayInfo.dataInLastBeat
552      cause(enqIndex) := replayInfo.cause.asUInt
553
554      // update credit
555      val blockCyclesTlbPtr = blockPtrTlb(enqIndex)
556      val blockCyclesCachePtr = blockPtrCache(enqIndex)
557      val blockCyclesOtherPtr = blockPtrOthers(enqIndex)
558      creditUpdate(enqIndex) := Mux(replayInfo.cause(LoadReplayCauses.tlbMiss), blockCyclesTlb(blockCyclesTlbPtr),
559                                Mux(replayInfo.cause(LoadReplayCauses.dcacheMiss), blockCyclesCache(blockCyclesCachePtr) + dataInLastBeat, blockCyclesOthers(blockCyclesOtherPtr)))
560
561      // init
562      blockByTlbMiss(enqIndex) := false.B
563      blockByWaitStore(enqIndex) := false.B
564      blockByForwardFail(enqIndex) := false.B
565      blockByCacheMiss(enqIndex) := false.B
566      blockByRARReject(enqIndex) := false.B
567      blockByRAWReject(enqIndex) := false.B
568      blockByOthers(enqIndex) := false.B
569
570      // update block pointer
571      when (replayInfo.cause(LoadReplayCauses.dcacheReplay)) {
572        // normal case: dcache replay
573        blockByOthers(enqIndex) := true.B
574        blockPtrOthers(enqIndex) :=  Mux(blockPtrOthers(enqIndex) === 3.U(2.W), blockPtrOthers(enqIndex), blockPtrOthers(enqIndex) + 1.U(2.W))
575      } .elsewhen (replayInfo.cause(LoadReplayCauses.bankConflict) || replayInfo.cause(LoadReplayCauses.schedError)) {
576        // normal case: bank conflict or schedule error
577        // can replay next cycle
578        creditUpdate(enqIndex) := 0.U
579        blockByOthers(enqIndex) := false.B
580      }
581
582      // special case: tlb miss
583      when (replayInfo.cause(LoadReplayCauses.tlbMiss)) {
584        blockByTlbMiss(enqIndex) := true.B
585        blockPtrTlb(enqIndex) := Mux(blockPtrTlb(enqIndex) === 3.U(2.W), blockPtrTlb(enqIndex), blockPtrTlb(enqIndex) + 1.U(2.W))
586      }
587
588      // special case: dcache miss
589      when (replayInfo.cause(LoadReplayCauses.dcacheMiss)) {
590        blockByCacheMiss(enqIndex) := !replayInfo.canForwardFullData && //  dcache miss
591                                  !(io.refill.valid && io.refill.bits.id === replayInfo.missMSHRId) && // no refill in this cycle
592                                  creditUpdate(enqIndex) =/= 0.U //  credit is not zero
593        blockPtrCache(enqIndex) := Mux(blockPtrCache(enqIndex) === 3.U(2.W), blockPtrCache(enqIndex), blockPtrCache(enqIndex) + 1.U(2.W))
594      }
595
596      // special case: st-ld violation
597      when (replayInfo.cause(LoadReplayCauses.waitStore)) {
598        blockByWaitStore(enqIndex) := true.B
599        blockSqIdx(enqIndex) := replayInfo.addrInvalidSqIdx
600        blockPtrOthers(enqIndex) :=  Mux(blockPtrOthers(enqIndex) === 3.U(2.W), blockPtrOthers(enqIndex), blockPtrOthers(enqIndex) + 1.U(2.W))
601      }
602
603      // special case: data forward fail
604      when (replayInfo.cause(LoadReplayCauses.forwardFail)) {
605        blockByForwardFail(enqIndex) := true.B
606        blockSqIdx(enqIndex) := replayInfo.dataInvalidSqIdx
607        blockPtrOthers(enqIndex) :=  Mux(blockPtrOthers(enqIndex) === 3.U(2.W), blockPtrOthers(enqIndex), blockPtrOthers(enqIndex) + 1.U(2.W))
608      }
609
610      // special case: rar reject
611      when (replayInfo.cause(LoadReplayCauses.rarReject)) {
612        blockByRARReject(enqIndex) := true.B
613        blockPtrOthers(enqIndex) :=  Mux(blockPtrOthers(enqIndex) === 3.U(2.W), blockPtrOthers(enqIndex), blockPtrOthers(enqIndex) + 1.U(2.W))
614      }
615
616      // special case: raw reject
617      when (replayInfo.cause(LoadReplayCauses.rawReject)) {
618        blockByRAWReject(enqIndex) := true.B
619        blockPtrOthers(enqIndex) :=  Mux(blockPtrOthers(enqIndex) === 3.U(2.W), blockPtrOthers(enqIndex), blockPtrOthers(enqIndex) + 1.U(2.W))
620      }
621
622      //
623      replayCarryReg(enqIndex) := replayInfo.replayCarry
624      missMSHRId(enqIndex) := replayInfo.missMSHRId
625    }
626
627    //
628    val sleepIndex = enq.bits.sleepIndex
629    when (enq.valid && enq.bits.isLoadReplay) {
630      when (!needReplay(w) || hasExceptions(w)) {
631        allocated(sleepIndex) := false.B
632        freeMaskVec(sleepIndex) := true.B
633      } .otherwise {
634        sleep(sleepIndex) := true.B
635      }
636    }
637  }
638
639  // misprediction recovery / exception redirect
640  for (i <- 0 until LoadQueueReplaySize) {
641    needCancel(i) := uop(i).robIdx.needFlush(io.redirect) && allocated(i)
642    when (needCancel(i)) {
643      allocated(i) := false.B
644      freeMaskVec(i) := true.B
645    }
646  }
647
648  freeList.io.free := freeMaskVec.asUInt
649
650  io.lqFull := lqFull
651
652  //  perf cnt
653  val enqCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay))
654  val deqCount = PopCount(io.replay.map(_.fire))
655  val deqBlockCount = PopCount(io.replay.map(r => r.valid && !r.ready))
656  val replayTlbMissCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.replayInfo.cause(LoadReplayCauses.tlbMiss)))
657  val replayWaitStoreCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.replayInfo.cause(LoadReplayCauses.waitStore)))
658  val replaySchedErrorCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.replayInfo.cause(LoadReplayCauses.schedError)))
659  val replayRARRejectCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.replayInfo.cause(LoadReplayCauses.rarReject)))
660  val replayRAWRejectCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.replayInfo.cause(LoadReplayCauses.rawReject)))
661  val replayBankConflictCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.replayInfo.cause(LoadReplayCauses.bankConflict)))
662  val replayDCacheReplayCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.replayInfo.cause(LoadReplayCauses.dcacheReplay)))
663  val replayForwardFailCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.replayInfo.cause(LoadReplayCauses.forwardFail)))
664  val replayDCacheMissCount = PopCount(io.enq.map(enq => enq.fire && !enq.bits.isLoadReplay && enq.bits.replayInfo.cause(LoadReplayCauses.dcacheMiss)))
665  XSPerfAccumulate("enq", enqCount)
666  XSPerfAccumulate("deq", deqCount)
667  XSPerfAccumulate("deq_block", deqBlockCount)
668  XSPerfAccumulate("replay_full", io.lqFull)
669  XSPerfAccumulate("replay_rar_reject", replayRARRejectCount)
670  XSPerfAccumulate("replay_raw_reject", replayRAWRejectCount)
671  XSPerfAccumulate("replay_sched_error", replaySchedErrorCount)
672  XSPerfAccumulate("replay_wait_store", replayWaitStoreCount)
673  XSPerfAccumulate("replay_tlb_miss", replayTlbMissCount)
674  XSPerfAccumulate("replay_bank_conflict", replayBankConflictCount)
675  XSPerfAccumulate("replay_dcache_replay", replayDCacheReplayCount)
676  XSPerfAccumulate("replay_forward_fail", replayForwardFailCount)
677  XSPerfAccumulate("replay_dcache_miss", replayDCacheMissCount)
678
679  val perfEvents: Seq[(String, UInt)] = Seq(
680    ("enq", enqCount),
681    ("deq", deqCount),
682    ("deq_block", deqBlockCount),
683    ("replay_full", io.lqFull),
684    ("replay_rar_reject", replayRARRejectCount),
685    ("replay_raw_reject", replayRAWRejectCount),
686    ("replay_advance_sched", replaySchedErrorCount),
687    ("replay_wait_store", replayWaitStoreCount),
688    ("replay_tlb_miss", replayTlbMissCount),
689    ("replay_bank_conflict", replayBankConflictCount),
690    ("replay_dcache_replay", replayDCacheReplayCount),
691    ("replay_forward_fail", replayForwardFailCount),
692    ("replay_dcache_miss", replayDCacheMissCount),
693  )
694  generatePerfEvent()
695  // end
696}
697