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