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