xref: /XiangShan/src/main/scala/xiangshan/frontend/icache/IPrefetch.scala (revision 83a0a891f99b684cf22ff3f84a3839d25cc89465)
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  ***************************************************************************************/
16
17package xiangshan.frontend.icache
18
19import chisel3._
20import chisel3.util._
21import org.chipsalliance.cde.config.Parameters
22import utility._
23import xiangshan.SoftIfetchPrefetchBundle
24import xiangshan.cache.mmu._
25import xiangshan.frontend._
26
27abstract class IPrefetchBundle(implicit p: Parameters) extends ICacheBundle
28abstract class IPrefetchModule(implicit p: Parameters) extends ICacheModule
29
30class IPrefetchReq(implicit p: Parameters) extends IPrefetchBundle {
31  val startAddr:        UInt   = UInt(VAddrBits.W)
32  val nextlineStart:    UInt   = UInt(VAddrBits.W)
33  val ftqIdx:           FtqPtr = new FtqPtr
34  val isSoftPrefetch:   Bool   = Bool()
35  val backendException: UInt   = UInt(ExceptionType.width.W)
36  def crossCacheline:   Bool   = startAddr(blockOffBits - 1) === 1.U
37
38  def fromFtqICacheInfo(info: FtqICacheInfo): IPrefetchReq = {
39    this.startAddr      := info.startAddr
40    this.nextlineStart  := info.nextlineStart
41    this.ftqIdx         := info.ftqIdx
42    this.isSoftPrefetch := false.B
43    this
44  }
45
46  def fromSoftPrefetch(req: SoftIfetchPrefetchBundle): IPrefetchReq = {
47    this.startAddr      := req.vaddr
48    this.nextlineStart  := req.vaddr + (1 << blockOffBits).U
49    this.ftqIdx         := DontCare
50    this.isSoftPrefetch := true.B
51    this
52  }
53}
54
55class IPrefetchIO(implicit p: Parameters) extends IPrefetchBundle {
56  // control
57  val csr_pf_enable:     Bool = Input(Bool())
58  val csr_parity_enable: Bool = Input(Bool())
59  val flush:             Bool = Input(Bool())
60
61  val req:            DecoupledIO[IPrefetchReq]  = Flipped(Decoupled(new IPrefetchReq))
62  val flushFromBpu:   BpuFlushInfo               = Flipped(new BpuFlushInfo)
63  val itlb:           Vec[TlbRequestIO]          = Vec(PortNumber, new TlbRequestIO)
64  val itlbFlushPipe:  Bool                       = Bool()
65  val pmp:            Vec[ICachePMPBundle]       = Vec(PortNumber, new ICachePMPBundle)
66  val metaRead:       ICacheMetaReqBundle        = new ICacheMetaReqBundle
67  val MSHRReq:        DecoupledIO[ICacheMissReq] = DecoupledIO(new ICacheMissReq)
68  val MSHRResp:       Valid[ICacheMissResp]      = Flipped(ValidIO(new ICacheMissResp))
69  val wayLookupWrite: DecoupledIO[WayLookupInfo] = DecoupledIO(new WayLookupInfo)
70}
71
72class IPrefetchPipe(implicit p: Parameters) extends IPrefetchModule {
73  val io: IPrefetchIO = IO(new IPrefetchIO)
74
75  private val (toITLB, fromITLB) = (io.itlb.map(_.req), io.itlb.map(_.resp))
76  private val (toPMP, fromPMP)   = (io.pmp.map(_.req), io.pmp.map(_.resp))
77  private val (toMeta, fromMeta) = (io.metaRead.toIMeta, io.metaRead.fromIMeta)
78  private val (toMSHR, fromMSHR) = (io.MSHRReq, io.MSHRResp)
79  private val toWayLookup        = io.wayLookupWrite
80
81  private val s0_fire, s1_fire, s2_fire            = WireInit(false.B)
82  private val s1_ready, s2_ready                   = WireInit(false.B)
83  private val s0_flush, s1_flush, s2_flush         = WireInit(false.B)
84  private val from_bpu_s0_flush, from_bpu_s1_flush = WireInit(false.B)
85
86  /**
87    ******************************************************************************
88    * IPrefetch Stage 0
89    * - 1. receive ftq req
90    * - 2. send req to ITLB
91    * - 3. send req to Meta SRAM
92    ******************************************************************************
93    */
94  private val s0_valid = io.req.valid
95
96  /**
97    ******************************************************************************
98    * receive ftq req
99    ******************************************************************************
100    */
101  private val s0_req_vaddr        = VecInit(Seq(io.req.bits.startAddr, io.req.bits.nextlineStart))
102  private val s0_req_ftqIdx       = io.req.bits.ftqIdx
103  private val s0_isSoftPrefetch   = io.req.bits.isSoftPrefetch
104  private val s0_doubleline       = io.req.bits.crossCacheline
105  private val s0_req_vSetIdx      = s0_req_vaddr.map(get_idx)
106  private val s0_backendException = VecInit(Seq.fill(PortNumber)(io.req.bits.backendException))
107
108  from_bpu_s0_flush := !s0_isSoftPrefetch && (io.flushFromBpu.shouldFlushByStage2(s0_req_ftqIdx) ||
109    io.flushFromBpu.shouldFlushByStage3(s0_req_ftqIdx))
110  s0_flush := io.flush || from_bpu_s0_flush || s1_flush
111
112  private val s0_can_go = s1_ready && toITLB(0).ready && toITLB(1).ready && toMeta.ready
113  io.req.ready := s0_can_go
114
115  s0_fire := s0_valid && s0_can_go && !s0_flush
116
117  /**
118    ******************************************************************************
119    * IPrefetch Stage 1
120    * - 1. Receive resp from ITLB
121    * - 2. Receive resp from IMeta and check
122    * - 3. Monitor the requests from missUnit to write to SRAM.
123    * - 4. Write wayLookup
124    ******************************************************************************
125    */
126  private val s1_valid =
127    generatePipeControl(lastFire = s0_fire, thisFire = s1_fire, thisFlush = s1_flush, lastFlush = false.B)
128
129  private val s1_req_vaddr        = RegEnable(s0_req_vaddr, 0.U.asTypeOf(s0_req_vaddr), s0_fire)
130  private val s1_isSoftPrefetch   = RegEnable(s0_isSoftPrefetch, 0.U.asTypeOf(s0_isSoftPrefetch), s0_fire)
131  private val s1_doubleline       = RegEnable(s0_doubleline, 0.U.asTypeOf(s0_doubleline), s0_fire)
132  private val s1_req_ftqIdx       = RegEnable(s0_req_ftqIdx, 0.U.asTypeOf(s0_req_ftqIdx), s0_fire)
133  private val s1_req_vSetIdx      = VecInit(s1_req_vaddr.map(get_idx))
134  private val s1_backendException = RegEnable(s0_backendException, 0.U.asTypeOf(s0_backendException), s0_fire)
135
136  private val m_idle :: m_itlbResend :: m_metaResend :: m_enqWay :: m_enterS2 :: Nil = Enum(5)
137
138  private val state      = RegInit(m_idle)
139  private val next_state = WireDefault(state)
140  private val s0_fire_r  = RegNext(s0_fire)
141  dontTouch(state)
142  dontTouch(next_state)
143  state := next_state
144
145  /**
146    ******************************************************************************
147    * resend itlb req if miss
148    ******************************************************************************
149    */
150  private val s1_wait_itlb = RegInit(VecInit(Seq.fill(PortNumber)(false.B)))
151  (0 until PortNumber).foreach { i =>
152    when(s1_flush) {
153      s1_wait_itlb(i) := false.B
154    }.elsewhen(RegNext(s0_fire) && fromITLB(i).bits.miss) {
155      s1_wait_itlb(i) := true.B
156    }.elsewhen(s1_wait_itlb(i) && !fromITLB(i).bits.miss) {
157      s1_wait_itlb(i) := false.B
158    }
159  }
160  private val s1_need_itlb = VecInit(Seq(
161    (RegNext(s0_fire) || s1_wait_itlb(0)) && fromITLB(0).bits.miss,
162    (RegNext(s0_fire) || s1_wait_itlb(1)) && fromITLB(1).bits.miss && s1_doubleline
163  ))
164  private val tlb_valid_pulse = VecInit(Seq(
165    (RegNext(s0_fire) || s1_wait_itlb(0)) && !fromITLB(0).bits.miss,
166    (RegNext(s0_fire) || s1_wait_itlb(1)) && !fromITLB(1).bits.miss && s1_doubleline
167  ))
168  private val tlb_valid_latch =
169    VecInit((0 until PortNumber).map(i => ValidHoldBypass(tlb_valid_pulse(i), s1_fire, flush = s1_flush)))
170  private val itlb_finish = tlb_valid_latch(0) && (!s1_doubleline || tlb_valid_latch(1))
171
172  (0 until PortNumber).foreach { i =>
173    toITLB(i).valid             := s1_need_itlb(i) || (s0_valid && (if (i == 0) true.B else s0_doubleline))
174    toITLB(i).bits              := DontCare
175    toITLB(i).bits.size         := 3.U
176    toITLB(i).bits.vaddr        := Mux(s1_need_itlb(i), s1_req_vaddr(i), s0_req_vaddr(i))
177    toITLB(i).bits.debug.pc     := Mux(s1_need_itlb(i), s1_req_vaddr(i), s0_req_vaddr(i))
178    toITLB(i).bits.cmd          := TlbCmd.exec
179    toITLB(i).bits.no_translate := false.B
180  }
181  fromITLB.foreach(_.ready := true.B)
182  io.itlb.foreach(_.req_kill := false.B)
183
184  /**
185    ******************************************************************************
186    * Receive resp from ITLB
187    ******************************************************************************
188    */
189  private val s1_req_paddr_wire = VecInit(fromITLB.map(_.bits.paddr(0)))
190  private val s1_req_paddr_reg = VecInit((0 until PortNumber).map { i =>
191    RegEnable(s1_req_paddr_wire(i), 0.U(PAddrBits.W), tlb_valid_pulse(i))
192  })
193  private val s1_req_paddr = VecInit((0 until PortNumber).map { i =>
194    Mux(tlb_valid_pulse(i), s1_req_paddr_wire(i), s1_req_paddr_reg(i))
195  })
196  private val s1_req_gpaddr_tmp = VecInit((0 until PortNumber).map { i =>
197    ResultHoldBypass(
198      valid = tlb_valid_pulse(i),
199      // NOTE: we dont use GPAddrBits or XLEN here, refer to ICacheMainPipe.scala L43-48 and PR#3795
200      init = 0.U(PAddrBitsMax.W),
201      data = fromITLB(i).bits.gpaddr(0)
202    )
203  })
204  private val s1_req_isForVSnonLeafPTE_tmp = VecInit((0 until PortNumber).map { i =>
205    ResultHoldBypass(
206      valid = tlb_valid_pulse(i),
207      init = 0.U.asTypeOf(fromITLB(i).bits.isForVSnonLeafPTE),
208      data = fromITLB(i).bits.isForVSnonLeafPTE
209    )
210  })
211  private val s1_itlb_exception = VecInit((0 until PortNumber).map { i =>
212    ResultHoldBypass(
213      valid = tlb_valid_pulse(i),
214      init = 0.U(ExceptionType.width.W),
215      data = ExceptionType.fromTlbResp(fromITLB(i).bits)
216    )
217  })
218  private val s1_itlb_pbmt = VecInit((0 until PortNumber).map { i =>
219    ResultHoldBypass(
220      valid = tlb_valid_pulse(i),
221      init = 0.U.asTypeOf(fromITLB(i).bits.pbmt(0)),
222      data = fromITLB(i).bits.pbmt(0)
223    )
224  })
225  private val s1_itlb_exception_gpf = VecInit(s1_itlb_exception.map(_ === ExceptionType.gpf))
226
227  /* Select gpaddr with the first gpf
228   * Note: the backend wants the base guest physical address of a fetch block
229   *       for port(i), its base gpaddr is actually (gpaddr - i * blocksize)
230   *       see GPAMem: https://github.com/OpenXiangShan/XiangShan/blob/344cf5d55568dd40cd658a9ee66047a505eeb504/src/main/scala/xiangshan/backend/GPAMem.scala#L33-L34
231   *       see also: https://github.com/OpenXiangShan/XiangShan/blob/344cf5d55568dd40cd658a9ee66047a505eeb504/src/main/scala/xiangshan/frontend/IFU.scala#L374-L375
232   */
233  private val s1_req_gpaddr = PriorityMuxDefault(
234    s1_itlb_exception_gpf zip (0 until PortNumber).map(i => s1_req_gpaddr_tmp(i) - (i << blockOffBits).U),
235    0.U.asTypeOf(s1_req_gpaddr_tmp(0))
236  )
237
238  private val s1_req_isForVSnonLeafPTE = PriorityMuxDefault(
239    s1_itlb_exception_gpf zip s1_req_isForVSnonLeafPTE_tmp,
240    0.U.asTypeOf(s1_req_isForVSnonLeafPTE_tmp(0))
241  )
242
243  /**
244    ******************************************************************************
245    * resend metaArray read req when itlb miss finish
246    ******************************************************************************
247    */
248  private val s1_need_meta = ((state === m_itlbResend) && itlb_finish) || (state === m_metaResend)
249  toMeta.valid             := s1_need_meta || s0_valid
250  toMeta.bits              := DontCare
251  toMeta.bits.isDoubleLine := Mux(s1_need_meta, s1_doubleline, s0_doubleline)
252
253  (0 until PortNumber).foreach { i =>
254    toMeta.bits.vSetIdx(i) := Mux(s1_need_meta, s1_req_vSetIdx(i), s0_req_vSetIdx(i))
255  }
256
257  /**
258    ******************************************************************************
259    * Receive resp from IMeta and check
260    ******************************************************************************
261    */
262  private val s1_req_ptags = VecInit(s1_req_paddr.map(get_phy_tag))
263
264  private val s1_meta_ptags  = fromMeta.tags
265  private val s1_meta_valids = fromMeta.entryValid
266
267  private def getWaymask(paddrs: Vec[UInt]): Vec[UInt] = {
268    val ptags = paddrs.map(get_phy_tag)
269    val tag_eq_vec =
270      VecInit((0 until PortNumber).map(p => VecInit((0 until nWays).map(w => s1_meta_ptags(p)(w) === ptags(p)))))
271    val tag_match_vec = VecInit((0 until PortNumber).map { k =>
272      VecInit(tag_eq_vec(k).zipWithIndex.map { case (way_tag_eq, w) => way_tag_eq && s1_meta_valids(k)(w) })
273    })
274    val waymasks = VecInit(tag_match_vec.map(_.asUInt))
275    waymasks
276  }
277
278  private val s1_SRAM_waymasks = VecInit((0 until PortNumber).map { port =>
279    Mux(tlb_valid_pulse(port), getWaymask(s1_req_paddr_wire)(port), getWaymask(s1_req_paddr_reg)(port))
280  })
281
282  // select ecc code
283  /* NOTE:
284   * When ECC check fails, s1_waymasks may be corrupted, so this selected meta_codes may be wrong.
285   * However, we can guarantee that the request sent to the l2 cache and the response to the IFU are both correct,
286   * considering the probability of bit flipping abnormally is very small, consider there's up to 1 bit being wrong:
287   * 1. miss -> fake hit: The wrong bit in s1_waymasks was set to true.B, thus selects the wrong meta_codes,
288   *                      but we can detect this by checking whether `encodeMetaECC(req_ptags) === meta_codes`.
289   * 2. hit -> fake multi-hit: In normal situation, multi-hit never happens, so multi-hit indicates ECC failure,
290   *                           we can detect this by checking whether `PopCount(waymasks) <= 1.U`,
291   *                           and meta_codes is not important in this situation.
292   * 3. hit -> fake miss: We can't detect this, but we can (pre)fetch the correct data from L2 cache, so it's not a problem.
293   * 4. hit -> hit / miss -> miss: ECC failure happens in an irrelevant way, so we don't care about it this time.
294   */
295  private val s1_SRAM_meta_codes = VecInit((0 until PortNumber).map { port =>
296    Mux1H(s1_SRAM_waymasks(port), fromMeta.codes(port))
297  })
298
299  /**
300    ******************************************************************************
301    * update waymasks and meta_codes according to MSHR update data
302    ******************************************************************************
303    */
304  private def updateMetaInfo(mask: UInt, vSetIdx: UInt, ptag: UInt, code: UInt): (UInt, UInt) = {
305    require(mask.getWidth == nWays)
306    val new_mask  = WireInit(mask)
307    val new_code  = WireInit(code)
308    val valid     = fromMSHR.valid && !fromMSHR.bits.corrupt
309    val vset_same = fromMSHR.bits.vSetIdx === vSetIdx
310    val ptag_same = getPhyTagFromBlk(fromMSHR.bits.blkPaddr) === ptag
311    val way_same  = fromMSHR.bits.waymask === mask
312    when(valid && vset_same) {
313      when(ptag_same) {
314        new_mask := fromMSHR.bits.waymask
315        // also update meta_codes
316        // we have getPhyTagFromBlk(fromMSHR.bits.blkPaddr) === ptag, so we can use ptag directly for better timing
317        new_code := encodeMetaECC(ptag)
318      }.elsewhen(way_same) {
319        new_mask := 0.U
320        // we don't care about new_code, since it's not used for a missed request
321      }
322    }
323    (new_mask, new_code)
324  }
325
326  private val s1_SRAM_valid   = s0_fire_r || RegNext(s1_need_meta && toMeta.ready)
327  private val s1_MSHR_valid   = fromMSHR.valid && !fromMSHR.bits.corrupt
328  private val s1_waymasks     = WireInit(VecInit(Seq.fill(PortNumber)(0.U(nWays.W))))
329  private val s1_waymasks_r   = RegEnable(s1_waymasks, 0.U.asTypeOf(s1_waymasks), s1_SRAM_valid || s1_MSHR_valid)
330  private val s1_meta_codes   = WireInit(VecInit(Seq.fill(PortNumber)(0.U(ICacheMetaCodeBits.W))))
331  private val s1_meta_codes_r = RegEnable(s1_meta_codes, 0.U.asTypeOf(s1_meta_codes), s1_SRAM_valid || s1_MSHR_valid)
332
333  // update waymasks and meta_codes
334  (0 until PortNumber).foreach { i =>
335    val old_waymask    = Mux(s1_SRAM_valid, s1_SRAM_waymasks(i), s1_waymasks_r(i))
336    val old_meta_codes = Mux(s1_SRAM_valid, s1_SRAM_meta_codes(i), s1_meta_codes_r(i))
337    val new_info       = updateMetaInfo(old_waymask, s1_req_vSetIdx(i), s1_req_ptags(i), old_meta_codes)
338    s1_waymasks(i)   := new_info._1
339    s1_meta_codes(i) := new_info._2
340  }
341
342  /**
343    ******************************************************************************
344    * send enqueue req to WayLookup
345    ******** **********************************************************************
346    */
347  // Disallow enqueuing wayLookup when SRAM write occurs.
348  toWayLookup.valid := ((state === m_enqWay) || ((state === m_idle) && itlb_finish)) &&
349    !s1_flush && !fromMSHR.valid && !s1_isSoftPrefetch // do not enqueue soft prefetch
350  toWayLookup.bits.vSetIdx           := s1_req_vSetIdx
351  toWayLookup.bits.waymask           := s1_waymasks
352  toWayLookup.bits.ptag              := s1_req_ptags
353  toWayLookup.bits.gpaddr            := s1_req_gpaddr
354  toWayLookup.bits.isForVSnonLeafPTE := s1_req_isForVSnonLeafPTE
355  toWayLookup.bits.meta_codes        := s1_meta_codes
356  (0 until PortNumber).foreach { i =>
357    // exception in first line is always valid, in second line is valid iff is doubleline request
358    val excpValid = if (i == 0) true.B else s1_doubleline
359    // Send s1_itlb_exception to WayLookup (instead of s1_exception_out) for better timing.
360    // Will check pmp again in mainPipe
361    toWayLookup.bits.itlb_exception(i) := Mux(excpValid, s1_itlb_exception(i), ExceptionType.none)
362    toWayLookup.bits.itlb_pbmt(i)      := Mux(excpValid, s1_itlb_pbmt(i), Pbmt.pma)
363  }
364
365  private val s1_waymasks_vec = s1_waymasks.map(_.asTypeOf(Vec(nWays, Bool())))
366  when(toWayLookup.fire) {
367    assert(
368      PopCount(s1_waymasks_vec(0)) <= 1.U && (PopCount(s1_waymasks_vec(1)) <= 1.U || !s1_doubleline),
369      "Multi-hit:\nport0: count=%d ptag=0x%x vSet=0x%x vaddr=0x%x\nport1: count=%d ptag=0x%x vSet=0x%x vaddr=0x%x",
370      PopCount(s1_waymasks_vec(0)) > 1.U,
371      s1_req_ptags(0),
372      get_idx(s1_req_vaddr(0)),
373      s1_req_vaddr(0),
374      PopCount(s1_waymasks_vec(1)) > 1.U && s1_doubleline,
375      s1_req_ptags(1),
376      get_idx(s1_req_vaddr(1)),
377      s1_req_vaddr(1)
378    )
379  }
380
381  /**
382    ******************************************************************************
383    * PMP check
384    ******************************************************************************
385    */
386  toPMP.zipWithIndex.foreach { case (p, i) =>
387    // if itlb has exception, paddr can be invalid, therefore pmp check can be skipped
388    p.valid     := s1_valid // !ExceptionType.hasException(s1_itlb_exception(i))
389    p.bits.addr := s1_req_paddr(i)
390    p.bits.size := 3.U
391    p.bits.cmd  := TlbCmd.exec
392  }
393  private val s1_pmp_exception = VecInit(fromPMP.map(ExceptionType.fromPMPResp))
394  private val s1_pmp_mmio      = VecInit(fromPMP.map(_.mmio))
395
396  // merge s1 itlb/pmp exceptions, itlb has the highest priority, pmp next
397  // for timing consideration, meta_corrupt is not merged, and it will NOT cancel prefetch
398  private val s1_exception_out = ExceptionType.merge(
399    s1_backendException,
400    s1_itlb_exception,
401    s1_pmp_exception
402  )
403
404  // merge pmp mmio and itlb pbmt
405  private val s1_mmio = VecInit((s1_pmp_mmio zip s1_itlb_pbmt).map { case (mmio, pbmt) =>
406    mmio || Pbmt.isUncache(pbmt)
407  })
408
409  /**
410    ******************************************************************************
411    * state machine
412    ******** **********************************************************************
413    */
414
415  switch(state) {
416    is(m_idle) {
417      when(s1_valid) {
418        when(!itlb_finish) {
419          next_state := m_itlbResend
420        }.elsewhen(!toWayLookup.fire) { // itlb_finish
421          next_state := m_enqWay
422        }.elsewhen(!s2_ready) { // itlb_finish && toWayLookup.fire
423          next_state := m_enterS2
424        } // .otherwise { next_state := m_idle }
425      }   // .otherwise { next_state := m_idle }  // !s1_valid
426    }
427    is(m_itlbResend) {
428      when(itlb_finish) {
429        when(!toMeta.ready) {
430          next_state := m_metaResend
431        }.otherwise { // toMeta.ready
432          next_state := m_enqWay
433        }
434      } // .otherwise { next_state := m_itlbResend }  // !itlb_finish
435    }
436    is(m_metaResend) {
437      when(toMeta.ready) {
438        next_state := m_enqWay
439      } // .otherwise { next_state := m_metaResend }  // !toMeta.ready
440    }
441    is(m_enqWay) {
442      when(toWayLookup.fire || s1_isSoftPrefetch) {
443        when(!s2_ready) {
444          next_state := m_enterS2
445        }.otherwise { // s2_ready
446          next_state := m_idle
447        }
448      } // .otherwise { next_state := m_enqWay }
449    }
450    is(m_enterS2) {
451      when(s2_ready) {
452        next_state := m_idle
453      }
454    }
455  }
456
457  when(s1_flush) {
458    next_state := m_idle
459  }
460
461  /** Stage 1 control */
462  from_bpu_s1_flush := s1_valid && !s1_isSoftPrefetch && io.flushFromBpu.shouldFlushByStage3(s1_req_ftqIdx)
463  s1_flush          := io.flush || from_bpu_s1_flush
464  // when s1 is flushed, itlb pipeline should also be flushed
465  io.itlbFlushPipe := s1_flush
466
467  s1_ready := next_state === m_idle
468  s1_fire  := (next_state === m_idle) && s1_valid && !s1_flush // used to clear s1_valid & itlb_valid_latch
469  private val s1_real_fire = s1_fire && io.csr_pf_enable // real "s1 fire" that s1 enters s2
470
471  /**
472    ******************************************************************************
473    * IPrefetch Stage 2
474    * - 1. Monitor the requests from missUnit to write to SRAM.
475    * - 2. send req to missUnit
476    ******************************************************************************
477    */
478  private val s2_valid =
479    generatePipeControl(lastFire = s1_real_fire, thisFire = s2_fire, thisFlush = s2_flush, lastFlush = false.B)
480
481  private val s2_req_vaddr      = RegEnable(s1_req_vaddr, 0.U.asTypeOf(s1_req_vaddr), s1_real_fire)
482  private val s2_isSoftPrefetch = RegEnable(s1_isSoftPrefetch, 0.U.asTypeOf(s1_isSoftPrefetch), s1_real_fire)
483  private val s2_doubleline     = RegEnable(s1_doubleline, 0.U.asTypeOf(s1_doubleline), s1_real_fire)
484  private val s2_req_paddr      = RegEnable(s1_req_paddr, 0.U.asTypeOf(s1_req_paddr), s1_real_fire)
485  private val s2_exception =
486    RegEnable(s1_exception_out, 0.U.asTypeOf(s1_exception_out), s1_real_fire) // includes itlb/pmp exception
487  // disabled for timing consideration
488// private val s2_exception_in =
489//   RegEnable(s1_exception_out, 0.U.asTypeOf(s1_exception_out), s1_real_fire)
490  private val s2_mmio     = RegEnable(s1_mmio, 0.U.asTypeOf(s1_mmio), s1_real_fire)
491  private val s2_waymasks = RegEnable(s1_waymasks, 0.U.asTypeOf(s1_waymasks), s1_real_fire)
492  // disabled for timing consideration
493// private val s2_meta_codes   = RegEnable(s1_meta_codes, 0.U.asTypeOf(s1_meta_codes), s1_real_fire)
494
495  private val s2_req_vSetIdx = s2_req_vaddr.map(get_idx)
496  private val s2_req_ptags   = s2_req_paddr.map(get_phy_tag)
497
498  // disabled for timing consideration
499//  // do metaArray ECC check
500//  val s2_meta_corrupt = VecInit((s2_req_ptags zip s2_meta_codes zip s2_waymasks).map{ case ((meta, code), waymask) =>
501//    val hit_num = PopCount(waymask)
502//    // NOTE: if not hit, encodeMetaECC(meta) =/= code can also be true, but we don't care about it
503//    (encodeMetaECC(meta) =/= code && hit_num === 1.U) ||  // hit one way, but parity code does not match, ECC failure
504//      hit_num > 1.U                                       // hit multi-way, must be an ECC failure
505//  })
506//
507//  // generate exception
508//  val s2_meta_exception = VecInit(s2_meta_corrupt.map(ExceptionType.fromECC(io.csr_parity_enable, _)))
509//
510//  // merge meta exception and itlb/pmp exception
511//  val s2_exception = ExceptionType.merge(s2_exception_in, s2_meta_exception)
512
513  /**
514    ******************************************************************************
515    * Monitor the requests from missUnit to write to SRAM
516    ******************************************************************************
517    */
518
519  /* NOTE: If fromMSHR.bits.corrupt, we should set s2_MSHR_hits to false.B, and send prefetch requests again.
520   * This is the opposite of how mainPipe handles fromMSHR.bits.corrupt,
521   *   in which we should set s2_MSHR_hits to true.B, and send error to ifu.
522   */
523  private val s2_MSHR_match = VecInit((0 until PortNumber).map { i =>
524    (s2_req_vSetIdx(i) === fromMSHR.bits.vSetIdx) &&
525    (s2_req_ptags(i) === getPhyTagFromBlk(fromMSHR.bits.blkPaddr)) &&
526    s2_valid && fromMSHR.valid && !fromMSHR.bits.corrupt
527  })
528  private val s2_MSHR_hits = (0 until PortNumber).map(i => ValidHoldBypass(s2_MSHR_match(i), s2_fire || s2_flush))
529
530  private val s2_SRAM_hits = s2_waymasks.map(_.orR)
531  private val s2_hits      = VecInit((0 until PortNumber).map(i => s2_MSHR_hits(i) || s2_SRAM_hits(i)))
532
533  /* s2_exception includes itlb pf/gpf/af, pmp af and meta corruption (af), neither of which should be prefetched
534   * mmio should not be prefetched
535   * also, if previous has exception, latter port should also not be prefetched
536   */
537  private val s2_miss = VecInit((0 until PortNumber).map { i =>
538    !s2_hits(i) && (if (i == 0) true.B else s2_doubleline) &&
539    !ExceptionType.hasException(s2_exception.take(i + 1)) &&
540    s2_mmio.take(i + 1).map(!_).reduce(_ && _)
541  })
542
543  /**
544    ******************************************************************************
545    * send req to missUnit
546    ******************************************************************************
547    */
548  private val toMSHRArbiter = Module(new Arbiter(new ICacheMissReq, PortNumber))
549
550  // To avoid sending duplicate requests.
551  private val has_send = RegInit(VecInit(Seq.fill(PortNumber)(false.B)))
552  (0 until PortNumber).foreach { i =>
553    when(s1_real_fire) {
554      has_send(i) := false.B
555    }.elsewhen(toMSHRArbiter.io.in(i).fire) {
556      has_send(i) := true.B
557    }
558  }
559
560  (0 until PortNumber).foreach { i =>
561    toMSHRArbiter.io.in(i).valid         := s2_valid && s2_miss(i) && !has_send(i)
562    toMSHRArbiter.io.in(i).bits.blkPaddr := getBlkAddr(s2_req_paddr(i))
563    toMSHRArbiter.io.in(i).bits.vSetIdx  := s2_req_vSetIdx(i)
564  }
565
566  toMSHR <> toMSHRArbiter.io.out
567
568  s2_flush := io.flush
569
570  // toMSHRArbiter.io.in(i).fire is not used here for timing consideration
571// private val s2_finish =
572//   (0 until PortNumber).map(i => has_send(i) || !s2_miss(i) || toMSHRArbiter.io.in(i).fire).reduce(_ && _)
573  private val s2_finish = (0 until PortNumber).map(i => has_send(i) || !s2_miss(i)).reduce(_ && _)
574  s2_ready := s2_finish || !s2_valid
575  s2_fire  := s2_valid && s2_finish && !s2_flush
576
577  /** PerfAccumulate */
578  // the number of bpu flush
579  XSPerfAccumulate("bpu_s0_flush", from_bpu_s0_flush)
580  XSPerfAccumulate("bpu_s1_flush", from_bpu_s1_flush)
581  // the number of prefetch request received from ftq or backend (software prefetch)
582//  XSPerfAccumulate("prefetch_req_receive", io.req.fire)
583  XSPerfAccumulate("prefetch_req_receive_hw", io.req.fire && !io.req.bits.isSoftPrefetch)
584  XSPerfAccumulate("prefetch_req_receive_sw", io.req.fire && io.req.bits.isSoftPrefetch)
585  // the number of prefetch request sent to missUnit
586//  XSPerfAccumulate("prefetch_req_send", toMSHR.fire)
587  XSPerfAccumulate("prefetch_req_send_hw", toMSHR.fire && !s2_isSoftPrefetch)
588  XSPerfAccumulate("prefetch_req_send_sw", toMSHR.fire && s2_isSoftPrefetch)
589  XSPerfAccumulate("to_missUnit_stall", toMSHR.valid && !toMSHR.ready)
590
591  /**
592    * Count the number of requests that are filtered for various reasons.
593    * The number of prefetch discard in Performance Accumulator may be
594    * a little larger the number of really discarded. Because there can
595    * be multiple reasons for a canceled request at the same time.
596    */
597  // discard prefetch request by flush
598  // XSPerfAccumulate("fdip_prefetch_discard_by_tlb_except",  p1_discard && p1_tlb_except)
599  // // discard prefetch request by hit icache SRAM
600  // XSPerfAccumulate("fdip_prefetch_discard_by_hit_cache",   p2_discard && p1_meta_hit)
601  // // discard prefetch request by hit write SRAM
602  // XSPerfAccumulate("fdip_prefetch_discard_by_p1_monitor",  p1_discard && p1_monitor_hit)
603  // // discard prefetch request by pmp except or mmio
604  // XSPerfAccumulate("fdip_prefetch_discard_by_pmp",         p2_discard && p2_pmp_except)
605  // // discard prefetch request by hit mainPipe info
606  // // XSPerfAccumulate("fdip_prefetch_discard_by_mainPipe",    p2_discard && p2_mainPipe_hit)
607}
608