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