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