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