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