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