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