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