xref: /XiangShan/src/main/scala/xiangshan/frontend/icache/ICacheMainPipe.scala (revision 382a2ebdf328e8147e67aad81c929b5587bdfda4)
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}
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 registerData = UInt(blockBits.W)
41  // val sramData = UInt(blockBits.W)
42  // val select   = Bool()
43  val data = UInt((blockBits/2).W)
44  val paddr    = UInt(PAddrBits.W)
45  val gpaddr    = UInt(GPAddrBits.W)
46  val tlbExcp  = new Bundle{
47    val pageFault = Bool()
48    val guestPageFault = Bool()
49    val accessFault = Bool()
50    val mmio = Bool()
51  }
52}
53
54class ICacheMainPipeBundle(implicit p: Parameters) extends ICacheBundle
55{
56  val req  = Flipped(Decoupled(new FtqToICacheRequestBundle))
57  val resp = Vec(PortNumber, ValidIO(new ICacheMainPipeResp))
58  val topdownIcacheMiss = Output(Bool())
59  val topdownItlbMiss = Output(Bool())
60}
61
62class ICacheMetaReqBundle(implicit p: Parameters) extends ICacheBundle{
63  val toIMeta       = DecoupledIO(new ICacheReadBundle)
64  val fromIMeta     = Input(new ICacheMetaRespBundle)
65}
66
67class ICacheDataReqBundle(implicit p: Parameters) extends ICacheBundle{
68  val toIData       = DecoupledIO(Vec(partWayNum, new ICacheReadBundle))
69  val fromIData     = Input(new ICacheDataRespBundle)
70}
71
72class ICacheMSHRBundle(implicit p: Parameters) extends ICacheBundle{
73  val toMSHR        = Decoupled(new ICacheMissReq)
74  val fromMSHR      = Flipped(ValidIO(new ICacheMissResp))
75}
76
77class ICachePMPBundle(implicit p: Parameters) extends ICacheBundle{
78  val req  = Valid(new PMPReqBundle())
79  val resp = Input(new PMPRespBundle())
80}
81
82class ICachePerfInfo(implicit p: Parameters) extends ICacheBundle{
83  val only_0_hit     = Bool()
84  val only_0_miss    = Bool()
85  val hit_0_hit_1    = Bool()
86  val hit_0_miss_1   = Bool()
87  val miss_0_hit_1   = Bool()
88  val miss_0_miss_1  = Bool()
89  val hit_0_except_1 = Bool()
90  val miss_0_except_1 = Bool()
91  val except_0       = Bool()
92  val bank_hit       = Vec(2,Bool())
93  val hit            = Bool()
94}
95
96class ICacheMainPipeInterface(implicit p: Parameters) extends ICacheBundle {
97  val hartId = Input(UInt(hartIdLen.W))
98  /*** internal interface ***/
99  val metaArray   = new ICacheMetaReqBundle
100  val dataArray   = new ICacheDataReqBundle
101  /** prefetch io */
102  val IPFBufferRead = Flipped(new IPFBufferRead)
103  val PIQRead       = Flipped(new PIQRead)
104
105  val IPFReplacer         = Flipped(new IPFReplacer)
106  val ICacheMainPipeInfo  = new ICacheMainPipeInfo
107
108  val mshr        = Vec(PortNumber, new ICacheMSHRBundle)
109  val errors      = Output(Vec(PortNumber, new L1CacheErrorInfo))
110  /*** outside interface ***/
111  //val fetch       = Vec(PortNumber, new ICacheMainPipeBundle)
112  /* when ftq.valid is high in T + 1 cycle
113   * the ftq component must be valid in T cycle
114   */
115  val fetch       = new ICacheMainPipeBundle
116  val pmp         = Vec(PortNumber, new ICachePMPBundle)
117  val itlb        = Vec(PortNumber, new TlbRequestIO)
118  val respStall   = Input(Bool())
119  val perfInfo = Output(new ICachePerfInfo)
120
121  val csr_parity_enable = Input(Bool())
122}
123
124class ICacheDB(implicit p: Parameters) extends ICacheBundle {
125  val blk_vaddr   = UInt((VAddrBits - blockOffBits).W)
126  val blk_paddr   = UInt((PAddrBits - blockOffBits).W)
127  val hit         = Bool()
128}
129
130class ICacheMainPipe(implicit p: Parameters) extends ICacheModule
131{
132  val io = IO(new ICacheMainPipeInterface)
133
134  /** Input/Output port */
135  val (fromFtq, toIFU)    = (io.fetch.req,          io.fetch.resp)
136  val (toMeta, metaResp)  = (io.metaArray.toIMeta,  io.metaArray.fromIMeta)
137  val (toData, dataResp)  = (io.dataArray.toIData,  io.dataArray.fromIData)
138  val (toIPF,  fromIPF)   = (io.IPFBufferRead.req,  io.IPFBufferRead.resp)
139  val (toPIQ,  fromPIQ)   = (io.PIQRead.req,        io.PIQRead.resp)
140  val (toMSHR, fromMSHR)  = (io.mshr.map(_.toMSHR), io.mshr.map(_.fromMSHR))
141  val (toITLB, fromITLB)  = (io.itlb.map(_.req),    io.itlb.map(_.resp))
142  val (toPMP,  fromPMP)   = (io.pmp.map(_.req),     io.pmp.map(_.resp))
143
144  val IPFReplacer         = io.IPFReplacer
145  val toIPrefetch         = io.ICacheMainPipeInfo
146
147
148  // Statistics on the frequency distribution of FTQ fire interval
149  val cntFtqFireInterval = RegInit(0.U(32.W))
150  cntFtqFireInterval := Mux(fromFtq.fire, 1.U, cntFtqFireInterval + 1.U)
151  XSPerfHistogram("ftq2icache_fire_" + p(XSCoreParamsKey).HartId.toString,
152                  cntFtqFireInterval, fromFtq.fire,
153                  1, 300, 1, right_strict = true)
154
155  // Ftq RegNext Register
156  val fromFtqReq = fromFtq.bits.pcMemRead
157
158  /** pipeline control signal */
159  val s1_ready, s2_ready = Wire(Bool())
160  val s0_fire,  s1_fire , s2_fire  = Wire(Bool())
161
162  /**
163    ******************************************************************************
164    * ICache Stage 0
165    * - send req to ITLB and wait for tlb miss fixing
166    * - send req to Meta/Data SRAM
167    ******************************************************************************
168    */
169
170  /** s0 control */
171  val s0_valid       = fromFtq.valid
172  val s0_req_vaddr   = (0 until partWayNum + 1).map(i => VecInit(Seq(fromFtqReq(i).startAddr, fromFtqReq(i).nextlineStart)))
173  val s0_req_vsetIdx = (0 until partWayNum + 1).map(i => VecInit(s0_req_vaddr(i).map(get_idx(_))))
174  val s0_only_first  = (0 until partWayNum + 1).map(i => fromFtq.bits.readValid(i) && !fromFtqReq(i).crossCacheline)
175  val s0_double_line = (0 until partWayNum + 1).map(i => fromFtq.bits.readValid(i) && fromFtqReq(i).crossCacheline)
176
177  val s0_final_valid        = s0_valid
178  val s0_final_vaddr        = s0_req_vaddr.head
179  val s0_final_vsetIdx      = s0_req_vsetIdx.head
180  val s0_final_only_first   = s0_only_first.head
181  val s0_final_double_line  = s0_double_line.head
182
183  /** SRAM request */
184  // 0,1,2,3 -> dataArray(data); 3 -> dataArray(code); 0 -> metaArray; 4 -> itlb
185  val ftq_req_to_data_doubleline  = s0_double_line.init
186  val ftq_req_to_data_vset_idx    = s0_req_vsetIdx.init
187  val ftq_req_to_data_valid       = fromFtq.bits.readValid.init
188
189  val ftq_req_to_meta_doubleline  = s0_double_line.head
190  val ftq_req_to_meta_vset_idx    = s0_req_vsetIdx.head
191  val ftq_req_to_meta_valid       = fromFtq.bits.readValid.head
192
193  val ftq_req_to_itlb_only_first  = s0_only_first.last
194  val ftq_req_to_itlb_doubleline  = s0_double_line.last
195  val ftq_req_to_itlb_vaddr       = s0_req_vaddr.last
196  val ftq_req_to_itlb_vset_idx    = s0_req_vsetIdx.last
197
198  /** Data request */
199  for(i <- 0 until partWayNum) {
200    toData.valid                  := ftq_req_to_data_valid(i)
201    toData.bits(i).isDoubleLine   := ftq_req_to_data_doubleline(i)
202    toData.bits(i).vSetIdx        := ftq_req_to_data_vset_idx(i)
203  }
204
205  /** Meta request */
206  toMeta.valid               := ftq_req_to_meta_valid
207  toMeta.bits.isDoubleLine   := ftq_req_to_meta_doubleline
208  toMeta.bits.vSetIdx        := ftq_req_to_meta_vset_idx
209
210  val toITLB_s0_valid    = VecInit(Seq(s0_valid, s0_valid && ftq_req_to_itlb_doubleline))
211  val toITLB_s0_size     = VecInit(Seq(3.U, 3.U)) // TODO: fix the size
212  val toITLB_s0_vaddr    = ftq_req_to_itlb_vaddr
213  val toITLB_s0_debug_pc = ftq_req_to_itlb_vaddr
214
215  val itlb_can_go    = toITLB(0).ready && toITLB(1).ready
216  val icache_can_go  = toData.ready && toMeta.ready
217  val pipe_can_go    = s1_ready
218  val s0_can_go      = itlb_can_go && icache_can_go && pipe_can_go
219  s0_fire  := s0_valid && s0_can_go
220
221  //TODO: fix GTimer() condition
222  fromFtq.ready := s0_can_go
223
224  /**
225    ******************************************************************************
226    * ICache Stage 1
227    * - get tlb resp data (exceptiong info and physical addresses)
228    * - get Meta/Data SRAM read responses (latched for pipeline stop)
229    * - tag compare/hit check
230    * - check ipf and piq
231    ******************************************************************************
232    */
233
234  /** s1 control */
235  val s1_valid = generatePipeControl(lastFire = s0_fire, thisFire = s1_fire, thisFlush = false.B, lastFlush = false.B)
236
237  val s1_req_vaddr   = RegEnable(s0_final_vaddr, s0_fire)
238  val s1_req_vsetIdx = RegEnable(s0_final_vsetIdx, s0_fire)
239  val s1_double_line = RegEnable(s0_final_double_line, s0_fire)
240
241  /** tlb request and response */
242  fromITLB.foreach(_.ready := true.B)
243  val s1_wait_itlb  = RegInit(VecInit(Seq.fill(PortNumber)(false.B)))
244
245  (0 until PortNumber).foreach { i =>
246    when(RegNext(s0_fire) && fromITLB(i).bits.miss) {
247      s1_wait_itlb(i) := true.B
248    }.elsewhen(s1_wait_itlb(i) && !fromITLB(i).bits.miss) {
249      s1_wait_itlb(i) := false.B
250    }
251  }
252
253  val s1_need_itlb = Seq((RegNext(s0_fire) || s1_wait_itlb(0)) && fromITLB(0).bits.miss,
254                         (RegNext(s0_fire) || s1_wait_itlb(1)) && fromITLB(1).bits.miss && s1_double_line)
255  val toITLB_s1_valid    = s1_need_itlb
256  val toITLB_s1_size     = VecInit(Seq(3.U, 3.U)) // TODO: fix the size
257  val toITLB_s1_vaddr    = s1_req_vaddr
258  val toITLB_s1_debug_pc = s1_req_vaddr
259
260  // chose tlb req between s0 and s1
261  for (i <- 0 until PortNumber) {
262    toITLB(i).valid         := Mux(s1_need_itlb(i), toITLB_s1_valid(i), toITLB_s0_valid(i))
263    toITLB(i).bits.size     := Mux(s1_need_itlb(i), toITLB_s1_size(i), toITLB_s0_size(i))
264    toITLB(i).bits.vaddr    := Mux(s1_need_itlb(i), toITLB_s1_vaddr(i), toITLB_s0_vaddr(i))
265    toITLB(i).bits.debug.pc := Mux(s1_need_itlb(i), toITLB_s1_debug_pc(i), toITLB_s0_debug_pc(i))
266  }
267  toITLB.map{port =>
268    port.bits.cmd                 := TlbCmd.exec
269    port.bits.memidx              := DontCare
270    port.bits.debug.robIdx        := DontCare
271    port.bits.no_translate        := false.B
272    port.bits.debug.isFirstIssue  := DontCare
273    port.bits.kill                := DontCare
274    port.bits.hlvx                := DontCare
275    port.bits.hyperinst           := DontCare
276  }
277  io.itlb.foreach(_.req_kill := false.B)
278
279  /** tlb response latch for pipeline stop */
280  // val tlb_valid_tmp = VecInit((0 until PortNumber).map(i =>
281  //                       (RegNext(s0_fire) || s1_wait_itlb(i)) && !fromITLB(i).bits.miss))
282  val tlb_valid_tmp = VecInit(Seq((RegNext(s0_fire) || s1_wait_itlb(0)) && !fromITLB(0).bits.miss,
283                                  (RegNext(s0_fire) || s1_wait_itlb(1)) && !fromITLB(1).bits.miss && s1_double_line))
284  val tlbRespPAddr  = VecInit((0 until PortNumber).map(i =>
285                        ResultHoldBypass(valid = tlb_valid_tmp(i), data = fromITLB(i).bits.paddr(0))))
286  val tlbRespGPAddr = VecInit((0 until PortNumber).map(i => ResultHoldBypass(valid = tlb_back(i), data = fromITLB(i).bits.gpaddr(0))))
287  val tlbExcpGPF = VecInit((0 until PortNumber).map(i => ResultHoldBypass(valid = tlb_back(i), data = fromITLB(i).bits.excp(0).gpf.instr) && tlb_need_back(i)))
288  val tlbExcpPF     = VecInit((0 until PortNumber).map(i =>
289                        ResultHoldBypass(valid = tlb_valid_tmp(i), data = fromITLB(i).bits.excp(0).pf.instr)))
290  val tlbExcpAF     = VecInit((0 until PortNumber).map(i =>
291                        ResultHoldBypass(valid = tlb_valid_tmp(i), data = fromITLB(i).bits.excp(0).af.instr)))
292  val tlbExcp       = VecInit((0 until PortNumber).map(i => tlbExcpAF(i) || tlbExcpAF(i) || tlbExcpGPF(i)))
293
294  val s1_tlb_valid = VecInit((0 until PortNumber).map(i => ValidHoldBypass(tlb_valid_tmp(i), s1_fire)))
295  val tlbRespAllValid = s1_tlb_valid(0) && (!s1_double_line || s1_double_line && s1_tlb_valid(1))
296
297
298  def numOfStage = 3
299  val itlbMissStage = RegInit(VecInit(Seq.fill(numOfStage - 1)(0.B)))
300  itlbMissStage(0) := !tlbRespAllValid
301  for (i <- 1 until numOfStage - 1) {
302    itlbMissStage(i) := itlbMissStage(i - 1)
303  }
304
305  /** s1 hit check/tag compare */
306  val s1_req_paddr              = tlbRespPAddr
307  val s1_req_gpaddr             = tlbRespGPAddr
308  val s1_req_ptags              = VecInit(s1_req_paddr.map(get_phy_tag(_)))
309
310  val s1_meta_ptags              = ResultHoldBypass(data = metaResp.tags, valid = RegNext(s0_fire))
311  val s1_meta_valids             = ResultHoldBypass(data = metaResp.entryValid, valid = RegNext(s0_fire))
312  val s1_meta_errors             = ResultHoldBypass(data = metaResp.errors, valid = RegNext(s0_fire))
313
314  val s1_data_cacheline          = ResultHoldBypass(data = dataResp.datas, valid = RegNext(s0_fire))
315  val s1_data_errorBits          = ResultHoldBypass(data = dataResp.codes, valid = RegNext(s0_fire))
316
317  val s1_tag_eq_vec        = VecInit((0 until PortNumber).map( p => VecInit((0 until nWays).map( w =>  s1_meta_ptags(p)(w) ===  s1_req_ptags(p)))))
318  val s1_tag_match_vec     = VecInit((0 until PortNumber).map( k => VecInit(s1_tag_eq_vec(k).zipWithIndex.map{ case(way_tag_eq, w) => way_tag_eq && s1_meta_valids(k)(w)})))
319  val s1_tag_match         = VecInit(s1_tag_match_vec.map(vector => ParallelOR(vector)))
320
321  val s1_port_hit          = VecInit(Seq(s1_tag_match(0) && s1_valid, s1_tag_match(1) && s1_valid && s1_double_line))
322
323  /** choose victim cacheline */
324  val bank_vsetIdx    = VecInit((0 until PortNumber).map( i => Mux(s1_req_vsetIdx(i)(0), s1_req_vsetIdx(1)(highestIdxBit, 1), s1_req_vsetIdx(0)(highestIdxBit, 1))))
325  val replacers       = Seq.fill(PortNumber)(ReplacementPolicy.fromString(cacheParams.replacer,nWays,nSets/PortNumber))
326  val bank_victim_oh  = ResultHoldBypass(data = VecInit(replacers.zipWithIndex.map{case (replacer, i) => UIntToOH(replacer.way(bank_vsetIdx(i)))}), valid = RegNext(s0_fire))
327  val s1_victim_oh    = VecInit((0 until PortNumber).map( i => Mux(s1_req_vsetIdx(i)(0), bank_victim_oh(1), bank_victim_oh(0))))
328
329  when(s1_fire){
330    assert(PopCount(s1_tag_match_vec(0)) <= 1.U && (PopCount(s1_tag_match_vec(1)) <= 1.U || !s1_double_line),
331      "Multiple hit in main pipe, port0:is=%d,ptag=0x%x,vidx=0x%x,vaddr=0x%x port1:is=%d,ptag=0x%x,vidx=0x%x,vaddr=0x%x ",
332      PopCount(s1_tag_match_vec(0)) > 1.U,s1_req_ptags(0), get_idx(s1_req_vaddr(0)), s1_req_vaddr(0),
333      PopCount(s1_tag_match_vec(1)) > 1.U && s1_double_line, s1_req_ptags(1), get_idx(s1_req_vaddr(1)), s1_req_vaddr(1))
334  }
335
336  /** check ipf, get result at the same cycle */
337  (0 until PortNumber).foreach { i =>
338    toIPF(i).valid      := tlb_valid_tmp(i)
339    toIPF(i).bits.paddr := s1_req_paddr(i)
340  }
341  val s1_ipf_hit        = VecInit((0 until PortNumber).map(i => toIPF(i).valid && fromIPF(i).ipf_hit))
342  val s1_ipf_hit_latch  = VecInit((0 until PortNumber).map(i => holdReleaseLatch(valid = s1_ipf_hit(i), release = s1_fire, flush = false.B)))
343  val s1_ipf_data       = VecInit((0 until PortNumber).map(i => ResultHoldBypass(data = fromIPF(i).cacheline, valid = s1_ipf_hit(i))))
344
345  /** check in PIQ, if hit, wait until prefetch port hit */
346  (0 until PortNumber).foreach { i =>
347    toPIQ(i).valid      := tlb_valid_tmp(i)
348    toPIQ(i).bits.paddr := s1_req_paddr(i)
349  }
350  val s1_piq_hit        = VecInit((0 until PortNumber).map(i => toIPF(i).valid && fromPIQ(i).piq_hit))
351  val s1_piq_hit_latch  = VecInit((0 until PortNumber).map(i => holdReleaseLatch(valid = s1_piq_hit(i), release = s1_fire, flush = false.B)))
352  val wait_piq          = VecInit((0 until PortNumber).map(i => toIPF(i).valid && fromPIQ(i).piq_hit && !fromPIQ(i).data_valid))
353  val wait_piq_latch    = VecInit((0 until PortNumber).map(i => holdReleaseLatch(valid = wait_piq(i), release = s1_fire || fromPIQ(i).data_valid, flush = false.B)))
354  val s1_piq_data       = VecInit((0 until PortNumber).map(i => ResultHoldBypass(data = fromPIQ(i).cacheline, valid = (s1_piq_hit(i) || wait_piq_latch(i)) && fromPIQ(i).data_valid)))
355
356  val s1_wait           = (0 until PortNumber).map(i => wait_piq_latch(i) && !fromPIQ(i).data_valid).reduce(_||_)
357
358  val s1_prefetch_hit = VecInit((0 until PortNumber).map(i => s1_ipf_hit_latch(i) || s1_piq_hit_latch(i)))
359  val s1_prefetch_hit_data = VecInit((0 until PortNumber).map(i => Mux(s1_ipf_hit_latch(i), s1_ipf_data(i), s1_piq_data(i))))
360
361  s1_ready := s2_ready && tlbRespAllValid && !s1_wait || !s1_valid
362  s1_fire  := s1_valid && tlbRespAllValid && s2_ready && !s1_wait
363
364  // record cacheline log
365  val isWriteICacheTable = WireInit(Constantin.createRecord("isWriteICacheTable" + p(XSCoreParamsKey).HartId.toString))
366  val ICacheTable = ChiselDB.createTable("ICacheTable" + p(XSCoreParamsKey).HartId.toString, new ICacheDB)
367
368  val ICacheDumpData_req0 = Wire(new ICacheDB)
369  ICacheDumpData_req0.blk_paddr := getBlkAddr(s1_req_paddr(0))
370  ICacheDumpData_req0.blk_vaddr := getBlkAddr(s1_req_vaddr(0))
371  ICacheDumpData_req0.hit       := s1_port_hit(0) || s1_prefetch_hit(0)
372  ICacheTable.log(
373    data = ICacheDumpData_req0,
374    en = isWriteICacheTable.orR && s1_fire,
375    clock = clock,
376    reset = reset
377  )
378
379  val ICacheDumpData_req1 = Wire(new ICacheDB)
380  ICacheDumpData_req1.blk_paddr := getBlkAddr(s1_req_paddr(1))
381  ICacheDumpData_req1.blk_vaddr := getBlkAddr(s1_req_vaddr(1))
382  ICacheDumpData_req1.hit       := s1_port_hit(1) || s1_prefetch_hit(1)
383  ICacheTable.log(
384    data = ICacheDumpData_req1,
385    en = isWriteICacheTable.orR && s1_fire && s1_double_line,
386    clock = clock,
387    reset = reset
388  )
389
390  /** <PERF> replace victim way number */
391
392  (0 until nWays).map{ w =>
393    XSPerfAccumulate("line_0_hit_way_" + Integer.toString(w, 10),  s1_fire && s1_port_hit(0) && OHToUInt(s1_tag_match_vec(0))  === w.U)
394  }
395
396  (0 until nWays).map{ w =>
397    XSPerfAccumulate("line_0_victim_way_" + Integer.toString(w, 10),  s1_fire && !s1_port_hit(0) && OHToUInt(s1_victim_oh(0))  === w.U)
398  }
399
400  (0 until nWays).map{ w =>
401    XSPerfAccumulate("line_1_hit_way_" + Integer.toString(w, 10),  s1_fire && s1_double_line && s1_port_hit(1) && OHToUInt(s1_tag_match_vec(1))  === w.U)
402  }
403
404  (0 until nWays).map{ w =>
405    XSPerfAccumulate("line_1_victim_way_" + Integer.toString(w, 10),  s1_fire && s1_double_line && !s1_port_hit(1) && OHToUInt(s1_victim_oh(1))  === w.U)
406  }
407
408  XSPerfAccumulate("mainPipe_stage1_block_by_piq_cycles", s1_valid && s1_wait)
409
410  /**
411    ******************************************************************************
412    * ICache Stage 2
413    * - send request to MSHR if ICache miss
414    * - generate secondary miss status/data registers
415    * - response to IFU
416    ******************************************************************************
417    */
418
419  /** s2 control */
420  val s2_fetch_finish = Wire(Bool())
421
422  val s2_valid          = generatePipeControl(lastFire = s1_fire, thisFire = s2_fire, thisFlush = false.B, lastFlush = false.B)
423
424  s2_ready      := (s2_valid && s2_fetch_finish && !io.respStall) || !s2_valid
425  s2_fire       := s2_valid && s2_fetch_finish && !io.respStall
426
427  /** s2 data */
428  // val mmio = fromPMP.map(port => port.mmio) // TODO: handle it
429  val (s2_req_paddr , s2_req_vaddr) = (RegEnable(s1_req_paddr, s1_fire), RegEnable(s1_req_vaddr, s1_fire))
430  val s2_req_gpaddr   = RegEnable(s1_req_gpaddr, s1_fire)
431  val s2_req_vsetIdx          = RegEnable(s1_req_vsetIdx,       s1_fire)
432  val s2_req_ptags            = RegEnable(s1_req_ptags,         s1_fire)
433  val s2_double_line          = RegEnable(s1_double_line,       s1_fire)
434  val s2_port_hit             = RegEnable(s1_port_hit,          s1_fire)
435  val s2_waymask              = RegEnable(s1_victim_oh,         s1_fire)
436  val s2_tag_match_vec        = RegEnable(s1_tag_match_vec,     s1_fire)
437
438  val s2_meta_errors          = RegEnable(s1_meta_errors,    s1_fire)
439  val s2_data_errorBits       = RegEnable(s1_data_errorBits, s1_fire)
440  val s2_data_cacheline       = RegEnable(s1_data_cacheline, s1_fire)
441
442  /** send req info of s1 and s2 to IPrefetchPipe for filter request */
443  toIPrefetch.s1Info(0).paddr  := s1_req_paddr(0)
444  toIPrefetch.s1Info(0).valid  := s1_valid
445  toIPrefetch.s1Info(1).paddr  := s1_req_paddr(1)
446  toIPrefetch.s1Info(1).valid  := s1_valid && s1_double_line
447  toIPrefetch.s2Info(0).paddr  := s2_req_paddr(0)
448  toIPrefetch.s2Info(0).valid  := s2_valid
449  toIPrefetch.s2Info(1).paddr  := s2_req_paddr(1)
450  toIPrefetch.s2Info(1).valid  := s2_valid && s2_double_line
451
452  assert(RegNext(!s2_valid || s2_req_paddr(0)(11,0) === s2_req_vaddr(0)(11,0), true.B))
453
454  /**
455    ******************************************************************************
456    * tlb exception and pmp logic
457    ******************************************************************************
458    */
459  // short delay exception signal
460  val s2_except_tlb_pf  = RegEnable(tlbExcpPF, s1_fire)
461  val s2_except_tlb_af  = RegEnable(tlbExcpAF, s1_fire)
462  val s2_except_tlb     = VecInit(Seq(s2_except_tlb_pf(0) || s2_except_tlb_af(0), s2_double_line && (s2_except_tlb_pf(1) || s2_except_tlb_af(1))))
463  val s2_has_except_tlb = s2_valid && s2_except_tlb.reduce(_||_)
464  // long delay exception signal
465  // exception information and mmio
466  val pmpExcpAF = VecInit(Seq(fromPMP(0).instr, fromPMP(1).instr && s2_double_line))
467  val s2_except_pmp_af = DataHoldBypass(pmpExcpAF, RegNext(s1_fire))
468  val s2_mmio = s2_valid && DataHoldBypass(fromPMP(0).mmio && !s2_except_tlb(0) && !s2_except_pmp_af(0), RegNext(s1_fire)).asBool
469  // pmp port
470  toPMP.zipWithIndex.map { case (p, i) =>
471    p.valid     := s2_valid
472    p.bits.addr := s2_req_paddr(i)
473    p.bits.size := 3.U // TODO
474    p.bits.cmd  := TlbCmd.exec
475  }
476
477  /**
478    ******************************************************************************
479    * look last miss data
480    ******************************************************************************
481    */
482  class MissSlot(implicit p: Parameters) extends ICacheBundle {
483    val paddr     = RegInit(0.U(PAddrBits.W))
484    val vSetIdx   = RegInit(0.U(idxBits.W))
485    val waymask   = RegInit(0.U(nWays.W))
486    val data      = RegInit(0.U(blockBits.W))
487    val corrupt   = RegInit(false.B)
488    val finish    = RegInit(true.B)
489    val valid     = RegInit(false.B)
490    def data_vec  = data.asTypeOf(Vec(2, UInt((blockBits/2).W)))
491    def pTag      = get_phy_tag(paddr)
492  }
493  val missSlot    = Seq.fill(2)(new MissSlot)
494
495  // whether hit in last miss req
496  def getMissSituat(missNum : Int, slotNum : Int ) :Bool =  {
497    (missSlot(slotNum).vSetIdx === s1_req_vsetIdx(missNum)) &&
498    (missSlot(slotNum).pTag === s1_req_ptags(missNum)) &&
499    !missSlot(slotNum).corrupt && missSlot(slotNum).finish &&
500    missSlot(slotNum).valid
501  }
502
503  // s2_hit_slot(0)(1): port 0 hit slot 1
504  // Use the signal of S1 to make a judgment for timing, the value of missSlot has benn set when s1 fire
505  val s1_hit_slot_vec = VecInit((0 until PortNumber).map(port => VecInit((0 until PortNumber).map(getMissSituat(port, _)))))
506  val s2_hit_slot_vec = RegEnable(s1_hit_slot_vec, s1_fire)
507
508  // select one from two missSlots to handle miss for every port
509  // slot(0) hit  && slot(1) hit : don't case
510  // slot(0) hit  && slot(1) miss: (a) missed port(0) -> slot(1); (b) missed port(1) -> slot(1)
511  // slot(0) miss && slot(1) hit : (a) missed port(0) -> slot(0); (b) missed port(1) -> slot(0)
512  // slot(0) miss && slot(1) miss: missed port(0) -> slot(0)  missed port(1) -> slot(1)
513  val s1_curr_slot_id = Wire(Vec(2, Bool()))
514  s1_curr_slot_id(0) := s1_hit_slot_vec(0)(0) || s1_hit_slot_vec(1)(0)
515  s1_curr_slot_id(1) := !(s1_hit_slot_vec(0)(1) || s1_hit_slot_vec(1)(1))
516  val s2_curr_slot_id = RegEnable(s1_curr_slot_id, s1_fire)
517
518  /**
519    ******************************************************************************
520    * miss handle
521    ******************************************************************************
522    */
523  val s2_hit_slot = VecInit(s2_hit_slot_vec.map(_.asUInt.orR))
524  val s2_fixed_port_hit = VecInit((0 until PortNumber).map(port => s2_port_hit(port) || s2_hit_slot(port)))
525
526  // only handle port0 miss when port1 have tlb except or pmp except
527  val s2_port_miss = Wire(Vec(PortNumber, Bool()))
528
529  s2_port_miss(0) := !s2_fixed_port_hit(0) && !s2_except_tlb(0) && !s2_except_pmp_af(0) && !s2_mmio
530  s2_port_miss(1) := !s2_fixed_port_hit(1) && s2_double_line && !s2_except_tlb(0) && !s2_except_tlb(1) &&
531                     !s2_except_pmp_af(0) && !s2_except_pmp_af(1) && !s2_mmio
532
533  (0 until PortNumber).map{ i =>
534    when(s2_port_miss(i) && RegNext(s1_fire)) {
535      when(s2_curr_slot_id(i)) {
536        missSlot(1).vSetIdx := s2_req_vsetIdx(i)
537        missSlot(1).paddr   := s2_req_paddr(i)
538        missSlot(1).waymask := s2_waymask(i)
539        missSlot(1).finish  := false.B
540        missSlot(1).valid   := true.B
541      }.otherwise {
542        missSlot(0).vSetIdx := s2_req_vsetIdx(i)
543        missSlot(0).paddr   := s2_req_paddr(i)
544        missSlot(0).waymask := s2_waymask(i)
545        missSlot(0).finish  := false.B
546        missSlot(0).valid   := true.B
547      }
548    }
549  }
550
551  // which missSlot need to be issued
552  val s2_missSlot_issue = Wire(Vec(2, Bool()))
553  s2_missSlot_issue(0) := (s2_port_miss(0) && !s2_curr_slot_id(0)) || (s2_port_miss(1) && !s2_curr_slot_id(1))
554  s2_missSlot_issue(1) := (s2_port_miss(0) && s2_curr_slot_id(0)) || (s2_port_miss(1) && s2_curr_slot_id(1))
555
556  // state machine
557  val m_idle ::m_send_req :: m_wait_resp :: Nil = Enum(3)
558  val missStateQueue = RegInit(VecInit(Seq.fill(2)(m_idle)))
559
560  (0 until PortNumber).map{ i =>
561    switch(missStateQueue(i)){
562      is(m_idle) {
563        missStateQueue(i) := Mux(RegNext(s1_fire) && s2_missSlot_issue(i), m_send_req, m_idle)
564      }
565      is(m_send_req) {
566        missStateQueue(i) := Mux(toMSHR(i).fire, m_wait_resp, m_send_req)
567      }
568      is(m_wait_resp) {
569        missStateQueue(i) := Mux(fromMSHR(i).fire, m_idle, m_wait_resp)
570      }
571    }
572  }
573
574  // send req to MSHR
575  (0 until PortNumber).map{i =>
576    toMSHR(i).valid         := missStateQueue(i) === m_send_req
577    toMSHR(i).bits.paddr    := missSlot(i).paddr
578    toMSHR(i).bits.vSetIdx  := missSlot(i).vSetIdx
579    toMSHR(i).bits.waymask  := missSlot(i).waymask
580  }
581
582  // recrive resp from MSHR to update missSlot
583  (0 until PortNumber).map{ i =>
584    when((missStateQueue(i) === m_wait_resp) && fromMSHR(i).fire) {
585      missSlot(i).finish  := true.B
586      missSlot(i).data    := fromMSHR(i).bits.data
587      missSlot(i).corrupt := fromMSHR(i).bits.corrupt
588    }
589  }
590
591  // handle miss finish
592  s2_fetch_finish := (!s2_port_miss(0) && !s2_port_miss(1)) || (missSlot(0).finish && missSlot(1).finish && !RegNext(s1_fire))
593
594  /**
595    ******************************************************************************
596    * select data from hitted sram data, last missSlot and current missSlot
597    ******************************************************************************
598    */
599  val s2_hit_datas = Wire(Vec(2, UInt((blockBits/2).W)))
600  s2_hit_datas(0) := Mux1H(s2_tag_match_vec(0).asUInt, s2_data_cacheline(0))
601  s2_hit_datas(1) := Mux1H(Mux(s2_double_line, s2_tag_match_vec(1).asUInt, s2_tag_match_vec(0).asUInt), s2_data_cacheline(1))
602
603  // get cacheline from last slot
604  val s2_last_slot_cacheline = (0 until PortNumber).map(port => Mux1H(s2_hit_slot_vec(port).asUInt, missSlot.map(_.data_vec)))
605  // get cacheline from curr slot
606  val s2_curr_slot_cacheline = (0 until PortNumber).map(port => Mux(s2_curr_slot_id(port), missSlot(1).data_vec, missSlot(0).data_vec))
607  val s2_slot_cacheline = (0 until PortNumber).map(port => Mux(s2_hit_slot(port), s2_last_slot_cacheline(port), s2_curr_slot_cacheline(port)))
608  val s2_slot_data = Wire(Vec(PortNumber, UInt((blockBits/2).W)))
609  s2_slot_data(0) := Mux(s2_double_line, s2_slot_cacheline(0)(1), s2_slot_cacheline(0)(0))
610  s2_slot_data(1) := Mux(s2_double_line, s2_slot_cacheline(1)(0), s2_slot_cacheline(0)(1))
611
612  val s2_fetch_data = Wire(Vec(2, UInt((blockBits/2).W)))
613  s2_fetch_data(0) := Mux(s2_port_hit(0), s2_hit_datas(0), s2_slot_data(0))
614  s2_fetch_data(1) := Mux(s2_port_hit(1) || (s2_port_hit(0) && !s2_double_line), s2_hit_datas(1), s2_slot_data(1))
615
616  val s2_corrupt = (0 until PortNumber).map(port => s2_port_miss(port) && Mux(s2_curr_slot_id(port), missSlot(1).corrupt, missSlot(0).corrupt))
617
618  /**
619    ******************************************************************************
620    * IFU data resp
621    ******************************************************************************
622    */
623  (0 until PortNumber).map{ i =>
624    if(i ==0) toIFU(i).valid          := s2_fire
625      else   toIFU(i).valid           := s2_fire && s2_double_line
626    toIFU(i).bits.paddr               := s2_req_paddr(i)
627    toIFU(i).bits.vaddr               := s2_req_vaddr(i)
628    toIFU(i).bits.data                := s2_fetch_data(i)
629    toIFU(i).bits.tlbExcp.pageFault   := s2_except_tlb_pf(i)
630    toIFU(i).bits.tlbExcp.accessFault := s2_except_tlb_af(i) || s2_corrupt(i) || s2_except_pmp_af(i)
631    toIFU(i).bits.tlbExcp.mmio        := s2_mmio
632  }
633
634  /**
635    ******************************************************************************
636    * error resp: MSHR error
637    ******************************************************************************
638    */
639  // data/meta parity error
640  val s2_data_errors = Wire(Vec(PortNumber,Vec(nWays, Bool())))
641  (0 until PortNumber).map{ i =>
642    val read_datas = s2_data_cacheline(i).asTypeOf(Vec(nWays,Vec(dataCodeUnitNum, UInt(dataCodeUnit.W))))
643    val read_codes = s2_data_errorBits(i).asTypeOf(Vec(nWays,Vec(dataCodeUnitNum, UInt(dataCodeBits.W))))
644    val data_full_wayBits = VecInit((0 until nWays).map( w =>
645                                  VecInit((0 until dataCodeUnitNum).map( u =>
646                                        Cat(read_codes(w)(u), read_datas(w)(u))))))
647    val data_error_wayBits = VecInit((0 until nWays).map( w =>
648                                  VecInit((0 until dataCodeUnitNum).map( u =>
649                                       cacheParams.dataCode.decode(data_full_wayBits(w)(u)).error))))
650    // register for timing
651    if(i == 0){
652      (0 until nWays).map{ w =>
653        s2_data_errors(i)(w) := RegNext(RegNext(s1_fire)) && RegNext(data_error_wayBits(w)).reduce(_||_)
654      }
655    } else {
656      (0 until nWays).map{ w =>
657        s2_data_errors(i)(w) := RegNext(RegNext(s1_fire)) && RegNext(RegNext(s1_double_line)) && RegNext(data_error_wayBits(w)).reduce(_||_)
658      }
659    }
660  }
661
662  val s2_parity_meta_error  = VecInit((0 until PortNumber).map(i => s2_meta_errors(i).reduce(_||_) && io.csr_parity_enable))
663  val s2_parity_data_error  = VecInit((0 until PortNumber).map(i => s2_data_errors(i).reduce(_||_) && io.csr_parity_enable))
664  val s2_parity_error       = VecInit((0 until PortNumber).map(i => RegNext(s2_parity_meta_error(i)) || s2_parity_data_error(i)))
665
666  for(i <- 0 until PortNumber){
667    io.errors(i).valid            := RegNext(s2_parity_error(i) && RegNext(RegNext(s1_fire)))
668    io.errors(i).report_to_beu    := RegNext(s2_parity_error(i) && RegNext(RegNext(s1_fire)))
669    io.errors(i).paddr            := RegNext(RegNext(s2_req_paddr(i)))
670    io.errors(i).source           := DontCare
671    io.errors(i).source.tag       := RegNext(RegNext(s2_parity_meta_error(i)))
672    io.errors(i).source.data      := RegNext(s2_parity_data_error(i))
673    io.errors(i).source.l2        := false.B
674    io.errors(i).opType           := DontCare
675    io.errors(i).opType.fetch     := true.B
676  }
677
678  // MSHR error
679  (0 until PortNumber).map{ i =>
680    when(RegNext(s2_fire && s2_corrupt(i))){
681      io.errors(i).valid            := true.B
682      io.errors(i).report_to_beu    := false.B // l2 should have report that to bus error unit, no need to do it again
683      io.errors(i).paddr            := RegNext(s2_req_paddr(i))
684      io.errors(i).source.tag       := false.B
685      io.errors(i).source.data      := false.B
686      io.errors(i).source.l2        := true.B
687    }
688  }
689
690  /**
691    ******************************************************************************
692    * s2 prefetch port
693    ******************************************************************************
694    */
695  (0 until PortNumber).foreach{ i =>
696    // TODO: consider corrupt of missSlot
697    toIPrefetch.missSlot(i).valid   := missSlot(i).valid
698    toIPrefetch.missSlot(i).vSetIdx := missSlot(i).vSetIdx
699    toIPrefetch.missSlot(i).ptag    := missSlot(i).pTag
700  }
701
702  /**
703    ******************************************************************************
704    * update replacement status register
705    ******************************************************************************
706    */
707  /** replacement status register */
708  val port_touch_sets = Seq.fill(PortNumber)(Wire(Vec(2, UInt(log2Ceil(nSets/2).W))))
709  val port_touch_ways = Seq.fill(PortNumber)(Wire(Vec(2, Valid(UInt(log2Ceil(nWays).W)))))
710  (port_touch_ways zip port_touch_sets).zipWithIndex.map{ case((t_w,t_s), i) =>
711    /** update replacement status register: 0 is hit access/ 1 is miss access */
712    t_s(0)         := s2_req_vsetIdx(i)(highestIdxBit, 1)
713    // hit in slot will be ignored, which generate a repeated access
714    t_w(0).valid   := s2_valid && s2_port_hit(i)
715    t_w(0).bits    := OHToUInt(s2_tag_match_vec(i))
716
717    t_s(1)         := s2_req_vsetIdx(i)(highestIdxBit, 1)
718    t_w(1).valid   := s2_valid && s2_port_miss(i)
719    t_w(1).bits    := OHToUInt(s2_waymask(i))
720  }
721
722  val touch_ways = VecInit((0 until PortNumber).map( i => Mux(s2_req_vsetIdx(i)(0), port_touch_ways(1), port_touch_ways(0))))
723  val touch_sets = VecInit((0 until PortNumber).map( i => Mux(s2_req_vsetIdx(i)(0), port_touch_sets(1), port_touch_sets(0))))
724  ((replacers zip touch_sets) zip touch_ways).map{case ((r, s),w) => r.access(s,w)}
725  // TODO: need choose one replacer according to the bankid
726  IPFReplacer.waymask := UIntToOH(replacers(0).way(IPFReplacer.vsetIdx))
727
728  /**
729    ******************************************************************************
730    * performance info. TODO: need to simplify the logic
731    ***********************************************************s*******************
732    */
733  io.fetch.topdownIcacheMiss := s2_port_miss(0) || s2_port_miss(1)
734  io.fetch.topdownItlbMiss := itlbMissStage(0)
735
736  io.perfInfo.only_0_hit      :=  s2_fixed_port_hit(0) && !s2_double_line
737  io.perfInfo.only_0_miss     := !s2_fixed_port_hit(0) && !s2_double_line
738  io.perfInfo.hit_0_hit_1     :=  s2_fixed_port_hit(0) &&  s2_fixed_port_hit(1) && s2_double_line
739  io.perfInfo.hit_0_miss_1    :=  s2_fixed_port_hit(0) && !s2_fixed_port_hit(1) && s2_double_line
740  io.perfInfo.miss_0_hit_1    := !s2_fixed_port_hit(0) &&  s2_fixed_port_hit(1) && s2_double_line
741  io.perfInfo.miss_0_miss_1   := !s2_fixed_port_hit(0) && !s2_fixed_port_hit(1) && s2_double_line
742  io.perfInfo.hit_0_except_1  :=  s2_fixed_port_hit(0) && (s2_except_tlb(1) || s2_except_pmp_af(1)) && s2_double_line
743  io.perfInfo.miss_0_except_1 := !s2_fixed_port_hit(0) && (s2_except_tlb(1) || s2_except_pmp_af(1)) && s2_double_line
744  io.perfInfo.bank_hit(0)     :=  s2_fixed_port_hit(0)
745  io.perfInfo.bank_hit(1)     :=  s2_fixed_port_hit(1) && s2_double_line
746  io.perfInfo.except_0        := s2_except_tlb(0) || s2_except_pmp_af(0)
747  io.perfInfo.hit             := !s2_port_miss(0) && !s2_port_miss(1)
748
749  /** <PERF> fetch bubble generated by icache miss*/
750  XSPerfAccumulate("icache_bubble_s2_miss", s2_valid && !s2_fetch_finish )
751  XSPerfAccumulate("icache_bubble_s0_tlb_miss", s1_valid && !tlbRespAllValid)
752
753  /**
754    ******************************************************************************
755    * difftest refill check
756    ******************************************************************************
757    */
758  if (env.EnableDifftest) {
759    val discards = (0 until PortNumber).map { i =>
760      val discard = toIFU(i).bits.tlbExcp.pageFault || toIFU(i).bits.tlbExcp.accessFault || toIFU(i).bits.tlbExcp.mmio
761      discard
762    }
763    (0 until PortNumber).map { i =>
764      val diffMainPipeOut = DifftestModule(new DiffRefillEvent, dontCare = true)
765      diffMainPipeOut.coreid := io.hartId
766      diffMainPipeOut.index := (4 + i).U
767      if (i == 0) {
768        diffMainPipeOut.valid := s2_fire && !discards(0)
769        diffMainPipeOut.addr  := s2_req_paddr(0)
770      } else {
771        diffMainPipeOut.valid := s2_fire && !discards(0) && (!s2_double_line || (s2_double_line && !discards(1)))
772        diffMainPipeOut.addr  := s2_req_paddr(0) + (blockBits/2).U
773      }
774      diffMainPipeOut.data := Cat(0.U((blockBits/2).W), toIFU(i).bits.data).asTypeOf(diffMainPipeOut.data)
775      // idtfr: 0 -> data from icache 1 -> reversedData 2 -> data from missUnit
776      diffMainPipeOut.idtfr := Mux(s2_port_hit(i), 0.U, Mux(s2_fixed_port_hit(i), 1.U, 2.U))
777      diffMainPipeOut
778    }
779  }
780}
781