xref: /XiangShan/src/main/scala/xiangshan/frontend/icache/ICacheMainPipe.scala (revision 614d2bc6eead7bc6e6e71c4d6dc850d2d5ad3aef)
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.ClientStates
23import org.chipsalliance.cde.config.Parameters
24import utility._
25import utils._
26import xiangshan._
27import xiangshan.backend.fu.PMPReqBundle
28import xiangshan.backend.fu.PMPRespBundle
29import xiangshan.cache.mmu._
30import xiangshan.frontend.ExceptionType
31import xiangshan.frontend.FtqICacheInfo
32import xiangshan.frontend.FtqToICacheRequestBundle
33
34class ICacheMainPipeReq(implicit p: Parameters) extends ICacheBundle {
35  val vaddr   = UInt(VAddrBits.W)
36  def vSetIdx = get_idx(vaddr)
37}
38
39class ICacheMainPipeResp(implicit p: Parameters) extends ICacheBundle {
40  val vaddr             = UInt(VAddrBits.W)
41  val data              = UInt(blockBits.W)
42  val paddr             = UInt(PAddrBits.W)
43  val gpaddr            = UInt(GPAddrBits.W)
44  val isForVSnonLeafPTE = Bool()
45  val exception         = UInt(ExceptionType.width.W)
46  val pmp_mmio          = Bool()
47  val itlb_pbmt         = UInt(Pbmt.width.W)
48  val backendException  = Bool()
49}
50
51class ICacheMainPipeBundle(implicit p: Parameters) extends ICacheBundle {
52  val req               = Flipped(Decoupled(new FtqToICacheRequestBundle))
53  val resp              = Vec(PortNumber, ValidIO(new ICacheMainPipeResp))
54  val topdownIcacheMiss = Output(Bool())
55  val topdownItlbMiss   = Output(Bool())
56}
57
58class ICacheMetaReqBundle(implicit p: Parameters) extends ICacheBundle {
59  val toIMeta   = DecoupledIO(new ICacheReadBundle)
60  val fromIMeta = Input(new ICacheMetaRespBundle)
61}
62
63class ICacheDataReqBundle(implicit p: Parameters) extends ICacheBundle {
64  val toIData   = Vec(partWayNum, DecoupledIO(new ICacheReadBundle))
65  val fromIData = Input(new ICacheDataRespBundle)
66}
67
68class ICacheMSHRBundle(implicit p: Parameters) extends ICacheBundle {
69  val req  = Decoupled(new ICacheMissReq)
70  val resp = Flipped(ValidIO(new ICacheMissResp))
71}
72
73class ICachePMPBundle(implicit p: Parameters) extends ICacheBundle {
74  val req  = Valid(new PMPReqBundle())
75  val resp = Input(new PMPRespBundle())
76}
77
78class ICachePerfInfo(implicit p: Parameters) extends ICacheBundle {
79  val only_0_hit      = Bool()
80  val only_0_miss     = Bool()
81  val hit_0_hit_1     = Bool()
82  val hit_0_miss_1    = Bool()
83  val miss_0_hit_1    = Bool()
84  val miss_0_miss_1   = Bool()
85  val hit_0_except_1  = Bool()
86  val miss_0_except_1 = Bool()
87  val except_0        = Bool()
88  val bank_hit        = Vec(2, Bool())
89  val hit             = Bool()
90}
91
92class ICacheMainPipeInterface(implicit p: Parameters) extends ICacheBundle {
93  val hartId = Input(UInt(hartIdLen.W))
94
95  /*** internal interface ***/
96  val dataArray = new ICacheDataReqBundle
97
98  /** prefetch io */
99  val touch         = Vec(PortNumber, ValidIO(new ReplacerTouch))
100  val wayLookupRead = Flipped(DecoupledIO(new WayLookupInfo))
101
102  val mshr   = new ICacheMSHRBundle
103  val errors = Output(Vec(PortNumber, ValidIO(new L1CacheErrorInfo)))
104
105  /*** outside interface ***/
106  // val fetch       = Vec(PortNumber, new ICacheMainPipeBundle)
107  /* when ftq.valid is high in T + 1 cycle
108   * the ftq component must be valid in T cycle
109   */
110  val fetch     = new ICacheMainPipeBundle
111  val pmp       = Vec(PortNumber, new ICachePMPBundle)
112  val respStall = Input(Bool())
113
114  val csr_parity_enable = Input(Bool())
115  val flush             = Input(Bool())
116
117  val perfInfo = Output(new ICachePerfInfo)
118}
119
120class ICacheDB(implicit p: Parameters) extends ICacheBundle {
121  val blk_vaddr = UInt((VAddrBits - blockOffBits).W)
122  val blk_paddr = UInt((PAddrBits - blockOffBits).W)
123  val hit       = Bool()
124}
125
126class ICacheMainPipe(implicit p: Parameters) extends ICacheModule {
127  val io = IO(new ICacheMainPipeInterface)
128
129  /** Input/Output port */
130  val (fromFtq, toIFU)   = (io.fetch.req, io.fetch.resp)
131  val (toData, fromData) = (io.dataArray.toIData, io.dataArray.fromIData)
132  val (toMSHR, fromMSHR) = (io.mshr.req, io.mshr.resp)
133  val (toPMP, fromPMP)   = (io.pmp.map(_.req), io.pmp.map(_.resp))
134  val fromWayLookup      = io.wayLookupRead
135
136  // Statistics on the frequency distribution of FTQ fire interval
137  val cntFtqFireInterval = RegInit(0.U(32.W))
138  cntFtqFireInterval := Mux(fromFtq.fire, 1.U, cntFtqFireInterval + 1.U)
139  XSPerfHistogram("ftq2icache_fire", cntFtqFireInterval, fromFtq.fire, 1, 300, 1, right_strict = true)
140
141  /** pipeline control signal */
142  val s1_ready, s2_ready           = Wire(Bool())
143  val s0_fire, s1_fire, s2_fire    = Wire(Bool())
144  val s0_flush, s1_flush, s2_flush = Wire(Bool())
145
146  /**
147    ******************************************************************************
148    * ICache Stage 0
149    * - send req to data SRAM
150    * - get waymask and tlb info from wayLookup
151    ******************************************************************************
152    */
153
154  /** s0 control */
155  // 0,1,2,3 -> dataArray(data); 4 -> mainPipe
156  // Ftq RegNext Register
157  val fromFtqReq       = fromFtq.bits.pcMemRead
158  val s0_valid         = fromFtq.valid
159  val s0_req_valid_all = (0 until partWayNum + 1).map(i => fromFtq.bits.readValid(i))
160  val s0_req_vaddr_all =
161    (0 until partWayNum + 1).map(i => VecInit(Seq(fromFtqReq(i).startAddr, fromFtqReq(i).nextlineStart)))
162  val s0_req_vSetIdx_all = (0 until partWayNum + 1).map(i => VecInit(s0_req_vaddr_all(i).map(get_idx)))
163  val s0_req_offset_all  = (0 until partWayNum + 1).map(i => s0_req_vaddr_all(i)(0)(log2Ceil(blockBytes) - 1, 0))
164  val s0_doubleline_all  = (0 until partWayNum + 1).map(i => fromFtq.bits.readValid(i) && fromFtqReq(i).crossCacheline)
165
166  val s0_req_vaddr   = s0_req_vaddr_all.last
167  val s0_req_vSetIdx = s0_req_vSetIdx_all.last
168  val s0_doubleline  = s0_doubleline_all.last
169
170  val s0_backendException = fromFtq.bits.backendException
171
172  /**
173    ******************************************************************************
174    * get waymask and tlb info from wayLookup
175    ******************************************************************************
176    */
177  fromWayLookup.ready := s0_fire
178  val s0_waymasks              = VecInit(fromWayLookup.bits.waymask.map(_.asTypeOf(Vec(nWays, Bool()))))
179  val s0_req_ptags             = fromWayLookup.bits.ptag
180  val s0_req_gpaddr            = fromWayLookup.bits.gpaddr
181  val s0_req_isForVSnonLeafPTE = fromWayLookup.bits.isForVSnonLeafPTE
182  val s0_itlb_exception        = fromWayLookup.bits.itlb_exception
183  val s0_itlb_pbmt             = fromWayLookup.bits.itlb_pbmt
184  val s0_meta_codes            = fromWayLookup.bits.meta_codes
185  val s0_hits                  = VecInit(fromWayLookup.bits.waymask.map(_.orR))
186
187  when(s0_fire) {
188    assert(
189      (0 until PortNumber).map(i => s0_req_vSetIdx(i) === fromWayLookup.bits.vSetIdx(i)).reduce(_ && _),
190      "vSetIdxs from ftq and wayLookup are different! vaddr0=0x%x ftq: vidx0=0x%x vidx1=0x%x wayLookup: vidx0=0x%x vidx1=0x%x",
191      s0_req_vaddr(0),
192      s0_req_vSetIdx(0),
193      s0_req_vSetIdx(1),
194      fromWayLookup.bits.vSetIdx(0),
195      fromWayLookup.bits.vSetIdx(1)
196    )
197  }
198
199  /**
200    ******************************************************************************
201    * data SRAM request
202    ******************************************************************************
203    */
204  for (i <- 0 until partWayNum) {
205    toData(i).valid             := s0_req_valid_all(i)
206    toData(i).bits.isDoubleLine := s0_doubleline_all(i)
207    toData(i).bits.vSetIdx      := s0_req_vSetIdx_all(i)
208    toData(i).bits.blkOffset    := s0_req_offset_all(i)
209    toData(i).bits.wayMask      := s0_waymasks
210  }
211
212  val s0_can_go = toData.last.ready && fromWayLookup.valid && s1_ready
213  s0_flush := io.flush
214  s0_fire  := s0_valid && s0_can_go && !s0_flush
215
216  fromFtq.ready := s0_can_go
217
218  /**
219    ******************************************************************************
220    * ICache Stage 1
221    * - PMP check
222    * - get Data SRAM read responses (latched for pipeline stop)
223    * - monitor missUint response port
224    ******************************************************************************
225    */
226  val s1_valid = generatePipeControl(lastFire = s0_fire, thisFire = s1_fire, thisFlush = s1_flush, lastFlush = false.B)
227
228  val s1_req_vaddr             = RegEnable(s0_req_vaddr, 0.U.asTypeOf(s0_req_vaddr), s0_fire)
229  val s1_req_ptags             = RegEnable(s0_req_ptags, 0.U.asTypeOf(s0_req_ptags), s0_fire)
230  val s1_req_gpaddr            = RegEnable(s0_req_gpaddr, 0.U.asTypeOf(s0_req_gpaddr), s0_fire)
231  val s1_req_isForVSnonLeafPTE = RegEnable(s0_req_isForVSnonLeafPTE, 0.U.asTypeOf(s0_req_isForVSnonLeafPTE), s0_fire)
232  val s1_doubleline            = RegEnable(s0_doubleline, 0.U.asTypeOf(s0_doubleline), s0_fire)
233  val s1_SRAMhits              = RegEnable(s0_hits, 0.U.asTypeOf(s0_hits), s0_fire)
234  val s1_itlb_exception        = RegEnable(s0_itlb_exception, 0.U.asTypeOf(s0_itlb_exception), s0_fire)
235  val s1_backendException      = RegEnable(s0_backendException, false.B, s0_fire)
236  val s1_itlb_pbmt             = RegEnable(s0_itlb_pbmt, 0.U.asTypeOf(s0_itlb_pbmt), s0_fire)
237  val s1_waymasks              = RegEnable(s0_waymasks, 0.U.asTypeOf(s0_waymasks), s0_fire)
238  val s1_meta_codes            = RegEnable(s0_meta_codes, 0.U.asTypeOf(s0_meta_codes), s0_fire)
239
240  val s1_req_vSetIdx = s1_req_vaddr.map(get_idx)
241  val s1_req_paddr   = s1_req_vaddr.zip(s1_req_ptags).map { case (vaddr, ptag) => get_paddr_from_ptag(vaddr, ptag) }
242  val s1_req_offset  = s1_req_vaddr(0)(log2Ceil(blockBytes) - 1, 0)
243
244  // do metaArray ECC check
245  val s1_meta_corrupt = VecInit((s1_req_ptags zip s1_meta_codes zip s1_waymasks).map { case ((meta, code), waymask) =>
246    val hit_num = PopCount(waymask)
247    // NOTE: if not hit, encodeMetaECC(meta) =/= code can also be true, but we don't care about it
248    (encodeMetaECC(meta) =/= code && hit_num === 1.U) || // hit one way, but parity code does not match, ECC failure
249    hit_num > 1.U                                        // hit multi way, must be a ECC failure
250  })
251
252  /**
253    ******************************************************************************
254    * update replacement status register
255    ******************************************************************************
256    */
257  (0 until PortNumber).foreach { i =>
258    io.touch(i).bits.vSetIdx := s1_req_vSetIdx(i)
259    io.touch(i).bits.way     := OHToUInt(s1_waymasks(i))
260  }
261  io.touch(0).valid := RegNext(s0_fire) && s1_SRAMhits(0)
262  io.touch(1).valid := RegNext(s0_fire) && s1_SRAMhits(1) && s1_doubleline
263
264  /**
265    ******************************************************************************
266    * PMP check
267    ******************************************************************************
268    */
269  toPMP.zipWithIndex.foreach { case (p, i) =>
270    // if itlb has exception, paddr can be invalid, therefore pmp check can be skipped
271    p.valid     := s1_valid // && s1_itlb_exception === ExceptionType.none
272    p.bits.addr := s1_req_paddr(i)
273    p.bits.size := 3.U      // TODO
274    p.bits.cmd  := TlbCmd.exec
275  }
276  val s1_pmp_exception = VecInit(fromPMP.map(ExceptionType.fromPMPResp))
277  val s1_pmp_mmio      = VecInit(fromPMP.map(_.mmio))
278
279  // also raise af when meta array corrupt is detected, to cancel fetch
280  val s1_meta_exception = VecInit(s1_meta_corrupt.map(ExceptionType.fromECC(io.csr_parity_enable, _)))
281
282  // merge s1 itlb/pmp/meta exceptions, itlb has the highest priority, pmp next, meta lowest
283  val s1_exception_out = ExceptionType.merge(
284    s1_itlb_exception,
285    s1_pmp_exception,
286    s1_meta_exception
287  )
288
289  // DO NOT merge pmp mmio and itlb pbmt here, we need them to be passed to IFU separately
290
291  /**
292    ******************************************************************************
293    * select data from MSHR, SRAM
294    ******************************************************************************
295    */
296  val s1_MSHR_match = VecInit((0 until PortNumber).map(i =>
297    (s1_req_vSetIdx(i) === fromMSHR.bits.vSetIdx) &&
298      (s1_req_ptags(i) === getPhyTagFromBlk(fromMSHR.bits.blkPaddr)) &&
299      fromMSHR.valid && !fromMSHR.bits.corrupt
300  ))
301  val s1_MSHR_hits  = Seq(s1_valid && s1_MSHR_match(0), s1_valid && (s1_MSHR_match(1) && s1_doubleline))
302  val s1_MSHR_datas = fromMSHR.bits.data.asTypeOf(Vec(ICacheDataBanks, UInt((blockBits / ICacheDataBanks).W)))
303
304  val s1_hits = (0 until PortNumber).map(i =>
305    ValidHoldBypass(s1_MSHR_hits(i) || (RegNext(s0_fire) && s1_SRAMhits(i)), s1_fire || s1_flush)
306  )
307
308  val s1_bankIdxLow = s1_req_offset >> log2Ceil(blockBytes / ICacheDataBanks)
309  val s1_bankMSHRHit = VecInit((0 until ICacheDataBanks).map(i =>
310    (i.U >= s1_bankIdxLow) && s1_MSHR_hits(0) ||
311      (i.U < s1_bankIdxLow) && s1_MSHR_hits(1)
312  ))
313  val s1_datas = VecInit((0 until ICacheDataBanks).map(i =>
314    DataHoldBypass(Mux(s1_bankMSHRHit(i), s1_MSHR_datas(i), fromData.datas(i)), s1_bankMSHRHit(i) || RegNext(s0_fire))
315  ))
316  val s1_codes = DataHoldBypass(fromData.codes, RegNext(s0_fire))
317
318  s1_flush := io.flush
319  s1_ready := s2_ready || !s1_valid
320  s1_fire  := s1_valid && s2_ready && !s1_flush
321
322  /**
323    ******************************************************************************
324    * ICache Stage 2
325    * - send request to MSHR if ICache miss
326    * - monitor missUint response port
327    * - response to IFU
328    ******************************************************************************
329    */
330
331  val s2_valid = generatePipeControl(lastFire = s1_fire, thisFire = s2_fire, thisFlush = s2_flush, lastFlush = false.B)
332
333  val s2_req_vaddr             = RegEnable(s1_req_vaddr, 0.U.asTypeOf(s1_req_vaddr), s1_fire)
334  val s2_req_ptags             = RegEnable(s1_req_ptags, 0.U.asTypeOf(s1_req_ptags), s1_fire)
335  val s2_req_gpaddr            = RegEnable(s1_req_gpaddr, 0.U.asTypeOf(s1_req_gpaddr), s1_fire)
336  val s2_req_isForVSnonLeafPTE = RegEnable(s1_req_isForVSnonLeafPTE, 0.U.asTypeOf(s1_req_isForVSnonLeafPTE), s1_fire)
337  val s2_doubleline            = RegEnable(s1_doubleline, 0.U.asTypeOf(s1_doubleline), s1_fire)
338  val s2_exception =
339    RegEnable(s1_exception_out, 0.U.asTypeOf(s1_exception_out), s1_fire) // includes itlb/pmp/meta exception
340  val s2_backendException = RegEnable(s1_backendException, false.B, s1_fire)
341  val s2_pmp_mmio         = RegEnable(s1_pmp_mmio, 0.U.asTypeOf(s1_pmp_mmio), s1_fire)
342  val s2_itlb_pbmt        = RegEnable(s1_itlb_pbmt, 0.U.asTypeOf(s1_itlb_pbmt), s1_fire)
343
344  val s2_req_vSetIdx = s2_req_vaddr.map(get_idx)
345  val s2_req_offset  = s2_req_vaddr(0)(log2Ceil(blockBytes) - 1, 0)
346  val s2_req_paddr   = s2_req_vaddr.zip(s2_req_ptags).map { case (vaddr, ptag) => get_paddr_from_ptag(vaddr, ptag) }
347
348  val s2_SRAMhits = RegEnable(s1_SRAMhits, 0.U.asTypeOf(s1_SRAMhits), s1_fire)
349  val s2_codes    = RegEnable(s1_codes, 0.U.asTypeOf(s1_codes), s1_fire)
350  val s2_hits     = RegInit(VecInit(Seq.fill(PortNumber)(false.B)))
351  val s2_datas    = RegInit(VecInit(Seq.fill(ICacheDataBanks)(0.U((blockBits / ICacheDataBanks).W))))
352
353  /**
354    ******************************************************************************
355    * report data parity error
356    ******************************************************************************
357    */
358  // check data error
359  val s2_bankSel      = getBankSel(s2_req_offset, s2_valid)
360  val s2_bank_corrupt = (0 until ICacheDataBanks).map(i => encodeDataECC(s2_datas(i)) =/= s2_codes(i))
361  val s2_data_corrupt = (0 until PortNumber).map(port =>
362    (0 until ICacheDataBanks).map(bank =>
363      s2_bank_corrupt(bank) && s2_bankSel(port)(bank).asBool
364    ).reduce(_ || _) && s2_SRAMhits(port)
365  )
366  // meta error is checked in prefetch pipeline
367  val s2_meta_corrupt = RegEnable(s1_meta_corrupt, 0.U.asTypeOf(s1_meta_corrupt), s1_fire)
368  // send errors to top
369  (0 until PortNumber).map { i =>
370    io.errors(i).valid := io.csr_parity_enable && RegNext(s1_fire) && (s2_meta_corrupt(i) || s2_data_corrupt(i))
371    io.errors(i).bits.report_to_beu := io.csr_parity_enable && RegNext(s1_fire) && (s2_meta_corrupt(
372      i
373    ) || s2_data_corrupt(i))
374    io.errors(i).bits.paddr        := s2_req_paddr(i)
375    io.errors(i).bits.source       := DontCare
376    io.errors(i).bits.source.tag   := s2_meta_corrupt(i)
377    io.errors(i).bits.source.data  := s2_data_corrupt(i)
378    io.errors(i).bits.source.l2    := false.B
379    io.errors(i).bits.opType       := DontCare
380    io.errors(i).bits.opType.fetch := true.B
381  }
382
383  /**
384    ******************************************************************************
385    * monitor missUint response port
386    ******************************************************************************
387    */
388  val s2_MSHR_match = VecInit((0 until PortNumber).map(i =>
389    (s2_req_vSetIdx(i) === fromMSHR.bits.vSetIdx) &&
390      (s2_req_ptags(i) === getPhyTagFromBlk(fromMSHR.bits.blkPaddr)) &&
391      fromMSHR.valid // we don't care about whether it's corrupt here
392  ))
393  val s2_MSHR_hits  = Seq(s2_valid && s2_MSHR_match(0), s2_valid && s2_MSHR_match(1) && s2_doubleline)
394  val s2_MSHR_datas = fromMSHR.bits.data.asTypeOf(Vec(ICacheDataBanks, UInt((blockBits / ICacheDataBanks).W)))
395
396  val s2_bankIdxLow = s2_req_offset >> log2Ceil(blockBytes / ICacheDataBanks)
397  val s2_bankMSHRHit = VecInit((0 until ICacheDataBanks).map(i =>
398    ((i.U >= s2_bankIdxLow) && s2_MSHR_hits(0)) || ((i.U < s2_bankIdxLow) && s2_MSHR_hits(1))
399  ))
400
401  (0 until ICacheDataBanks).foreach { i =>
402    when(s1_fire) {
403      s2_datas := s1_datas
404    }.elsewhen(s2_bankMSHRHit(i) && !fromMSHR.bits.corrupt) {
405      // if corrupt, no need to update s2_datas (it's wrong anyway), to save power
406      s2_datas(i) := s2_MSHR_datas(i)
407    }
408  }
409
410  (0 until PortNumber).foreach { i =>
411    when(s1_fire) {
412      s2_hits := s1_hits
413    }.elsewhen(s2_MSHR_hits(i)) {
414      // update s2_hits even if it's corrupt, to let s2_fire
415      s2_hits(i) := true.B
416    }
417  }
418
419  val s2_l2_corrupt = RegInit(VecInit(Seq.fill(PortNumber)(false.B)))
420  (0 until PortNumber).foreach { i =>
421    when(s1_fire) {
422      s2_l2_corrupt(i) := false.B
423    }.elsewhen(s2_MSHR_hits(i)) {
424      s2_l2_corrupt(i) := fromMSHR.bits.corrupt
425    }
426  }
427
428  /**
429    ******************************************************************************
430    * send request to MSHR if ICache miss
431    ******************************************************************************
432    */
433
434  // merge pmp mmio and itlb pbmt
435  val s2_mmio = VecInit((s2_pmp_mmio zip s2_itlb_pbmt).map { case (mmio, pbmt) =>
436    mmio || Pbmt.isUncache(pbmt)
437  })
438
439  /* s2_exception includes itlb pf/gpf/af, pmp af and meta corruption (af), neither of which should be fetched
440   * mmio should not be fetched, it will be fetched by IFU mmio fsm
441   * also, if previous has exception, latter port should also not be fetched
442   */
443  val s2_miss = VecInit((0 until PortNumber).map { i =>
444    !s2_hits(i) && (if (i == 0) true.B else s2_doubleline) &&
445    s2_exception.take(i + 1).map(_ === ExceptionType.none).reduce(_ && _) &&
446    s2_mmio.take(i + 1).map(!_).reduce(_ && _)
447  })
448
449  val toMSHRArbiter = Module(new Arbiter(new ICacheMissReq, PortNumber))
450
451  // To avoid sending duplicate requests.
452  val has_send = RegInit(VecInit(Seq.fill(PortNumber)(false.B)))
453  (0 until PortNumber).foreach { i =>
454    when(s1_fire) {
455      has_send(i) := false.B
456    }.elsewhen(toMSHRArbiter.io.in(i).fire) {
457      has_send(i) := true.B
458    }
459  }
460
461  (0 until PortNumber).map { i =>
462    toMSHRArbiter.io.in(i).valid         := s2_valid && s2_miss(i) && !has_send(i) && !s2_flush
463    toMSHRArbiter.io.in(i).bits.blkPaddr := getBlkAddr(s2_req_paddr(i))
464    toMSHRArbiter.io.in(i).bits.vSetIdx  := s2_req_vSetIdx(i)
465  }
466  toMSHR <> toMSHRArbiter.io.out
467
468  XSPerfAccumulate("to_missUnit_stall", toMSHR.valid && !toMSHR.ready)
469
470  val s2_fetch_finish = !s2_miss.reduce(_ || _)
471
472  // also raise af if data/l2 corrupt is detected
473  val s2_data_exception = VecInit(s2_data_corrupt.map(ExceptionType.fromECC(io.csr_parity_enable, _)))
474  val s2_l2_exception   = VecInit(s2_l2_corrupt.map(ExceptionType.fromECC(true.B, _)))
475
476  // merge s2 exceptions, itlb has the highest priority, meta next, meta/data/l2 lowest (and we dont care about prioritizing between this three)
477  val s2_exception_out = ExceptionType.merge(
478    s2_exception, // includes itlb/pmp/meta exception
479    s2_data_exception,
480    s2_l2_exception
481  )
482
483  /**
484    ******************************************************************************
485    * response to IFU
486    ******************************************************************************
487    */
488  (0 until PortNumber).foreach { i =>
489    if (i == 0) {
490      toIFU(i).valid          := s2_fire
491      toIFU(i).bits.exception := s2_exception_out(i)
492      toIFU(i).bits.pmp_mmio  := s2_pmp_mmio(i) // pass pmp_mmio instead of merged mmio to IFU
493      toIFU(i).bits.itlb_pbmt := s2_itlb_pbmt(i)
494      toIFU(i).bits.data      := s2_datas.asTypeOf(UInt(blockBits.W))
495    } else {
496      toIFU(i).valid          := s2_fire && s2_doubleline
497      toIFU(i).bits.exception := Mux(s2_doubleline, s2_exception_out(i), ExceptionType.none)
498      toIFU(i).bits.pmp_mmio  := s2_pmp_mmio(i) && s2_doubleline
499      toIFU(i).bits.itlb_pbmt := Mux(s2_doubleline, s2_itlb_pbmt(i), Pbmt.pma)
500      toIFU(i).bits.data      := DontCare
501    }
502    toIFU(i).bits.backendException := s2_backendException
503    toIFU(i).bits.vaddr            := s2_req_vaddr(i)
504    toIFU(i).bits.paddr            := s2_req_paddr(i)
505    toIFU(i).bits.gpaddr           := s2_req_gpaddr // Note: toIFU(1).bits.gpaddr is actually DontCare in current design
506    toIFU(i).bits.isForVSnonLeafPTE := s2_req_isForVSnonLeafPTE
507  }
508
509  s2_flush := io.flush
510  s2_ready := (s2_fetch_finish && !io.respStall) || !s2_valid
511  s2_fire  := s2_valid && s2_fetch_finish && !io.respStall && !s2_flush
512
513  /**
514    ******************************************************************************
515    * report Tilelink corrupt error
516    ******************************************************************************
517    */
518  (0 until PortNumber).map { i =>
519    when(RegNext(s2_fire && s2_l2_corrupt(i))) {
520      io.errors(i).valid              := true.B
521      io.errors(i).bits.report_to_beu := false.B // l2 should have report that to bus error unit, no need to do it again
522      io.errors(i).bits.paddr         := RegNext(s2_req_paddr(i))
523      io.errors(i).bits.source.tag    := false.B
524      io.errors(i).bits.source.data   := false.B
525      io.errors(i).bits.source.l2     := true.B
526    }
527  }
528
529  /**
530    ******************************************************************************
531    * performance info. TODO: need to simplify the logic
532    ***********************************************************s*******************
533    */
534  io.perfInfo.only_0_hit      := s2_hits(0) && !s2_doubleline
535  io.perfInfo.only_0_miss     := !s2_hits(0) && !s2_doubleline
536  io.perfInfo.hit_0_hit_1     := s2_hits(0) && s2_hits(1) && s2_doubleline
537  io.perfInfo.hit_0_miss_1    := s2_hits(0) && !s2_hits(1) && s2_doubleline
538  io.perfInfo.miss_0_hit_1    := !s2_hits(0) && s2_hits(1) && s2_doubleline
539  io.perfInfo.miss_0_miss_1   := !s2_hits(0) && !s2_hits(1) && s2_doubleline
540  io.perfInfo.hit_0_except_1  := s2_hits(0) && (s2_exception(1) =/= ExceptionType.none) && s2_doubleline
541  io.perfInfo.miss_0_except_1 := !s2_hits(0) && (s2_exception(1) =/= ExceptionType.none) && s2_doubleline
542  io.perfInfo.bank_hit(0)     := s2_hits(0)
543  io.perfInfo.bank_hit(1)     := s2_hits(1) && s2_doubleline
544  io.perfInfo.except_0        := s2_exception(0) =/= ExceptionType.none
545  io.perfInfo.hit             := s2_hits(0) && (!s2_doubleline || s2_hits(1))
546
547  /** <PERF> fetch bubble generated by icache miss */
548  XSPerfAccumulate("icache_bubble_s2_miss", s2_valid && !s2_fetch_finish)
549  XSPerfAccumulate("icache_bubble_s0_wayLookup", s0_valid && !fromWayLookup.ready)
550
551  io.fetch.topdownIcacheMiss := !s2_fetch_finish
552  io.fetch.topdownItlbMiss   := s0_valid && !fromWayLookup.ready
553
554  // class ICacheTouchDB(implicit p: Parameters) extends ICacheBundle{
555  //   val blkPaddr  = UInt((PAddrBits - blockOffBits).W)
556  //   val vSetIdx   = UInt(idxBits.W)
557  //   val waymask   = UInt(log2Ceil(nWays).W)
558  // }
559
560  // val isWriteICacheTouchTable = WireInit(Constantin.createRecord("isWriteICacheTouchTable" + p(XSCoreParamsKey).HartId.toString))
561  // val ICacheTouchTable = ChiselDB.createTable("ICacheTouchTable" + p(XSCoreParamsKey).HartId.toString, new ICacheTouchDB)
562
563  // val ICacheTouchDumpData = Wire(Vec(PortNumber, new ICacheTouchDB))
564  // (0 until PortNumber).foreach{ i =>
565  //   ICacheTouchDumpData(i).blkPaddr  := getBlkAddr(s2_req_paddr(i))
566  //   ICacheTouchDumpData(i).vSetIdx   := s2_req_vSetIdx(i)
567  //   ICacheTouchDumpData(i).waymask   := OHToUInt(s2_tag_match_vec(i))
568  //   ICacheTouchTable.log(
569  //     data  = ICacheTouchDumpData(i),
570  //     en    = io.touch(i).valid,
571  //     site  = "req_" + i.toString,
572  //     clock = clock,
573  //     reset = reset
574  //   )
575  // }
576
577  /**
578    ******************************************************************************
579    * difftest refill check
580    ******************************************************************************
581    */
582  if (env.EnableDifftest) {
583    val discards = (0 until PortNumber).map { i =>
584      val discard = toIFU(i).bits.exception =/= ExceptionType.none || toIFU(i).bits.pmp_mmio ||
585        Pbmt.isUncache(toIFU(i).bits.itlb_pbmt)
586      discard
587    }
588    val blkPaddrAll = s2_req_paddr.map(addr => addr(PAddrBits - 1, blockOffBits) << blockOffBits)
589    (0 until ICacheDataBanks).map { i =>
590      val diffMainPipeOut = DifftestModule(new DiffRefillEvent, dontCare = true)
591      diffMainPipeOut.coreid := io.hartId
592      diffMainPipeOut.index  := (3 + i).U
593
594      val bankSel = getBankSel(s2_req_offset, s2_valid).reduce(_ | _)
595      val lineSel = getLineSel(s2_req_offset)
596
597      diffMainPipeOut.valid := s2_fire && bankSel(i).asBool && Mux(lineSel(i), !discards(1), !discards(0))
598      diffMainPipeOut.addr := Mux(
599        lineSel(i),
600        blkPaddrAll(1) + (i.U << (log2Ceil(blockBytes / ICacheDataBanks))),
601        blkPaddrAll(0) + (i.U << (log2Ceil(blockBytes / ICacheDataBanks)))
602      )
603
604      diffMainPipeOut.data  := s2_datas(i).asTypeOf(diffMainPipeOut.data)
605      diffMainPipeOut.idtfr := DontCare
606    }
607  }
608}
609