IFU.scala 28.6 KB
Newer Older
L
Lingrui98 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/***************************************************************************************
* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
* Copyright (c) 2020-2021 Peng Cheng Laboratory
*
* XiangShan is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*          http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/

J
JinYue 已提交
17 18 19 20 21 22
package xiangshan.frontend

import chipsalliance.rocketchip.config.Parameters
import chisel3._
import chisel3.util._
import xiangshan._
J
jinyue110 已提交
23
import xiangshan.cache._
J
JinYue 已提交
24
import xiangshan.cache.mmu._
J
JinYue 已提交
25
import chisel3.experimental.verification
J
JinYue 已提交
26
import utils._
L
Lemover 已提交
27
import xiangshan.backend.fu.{PMPReqBundle, PMPRespBundle}
J
JinYue 已提交
28

29 30 31
trait HasInstrMMIOConst extends HasXSParameter with HasIFUConst{
  def mmioBusWidth = 64
  def mmioBusBytes = mmioBusWidth /8
32
  def maxInstrLen = 32
33 34 35 36
}

trait HasIFUConst extends HasXSParameter {
  def align(pc: UInt, bytes: Int): UInt = Cat(pc(VAddrBits-1, log2Ceil(bytes)), 0.U(log2Ceil(bytes).W))
37 38
  // def groupAligned(pc: UInt)  = align(pc, groupBytes)
  // def packetAligned(pc: UInt) = align(pc, packetBytes)
39
}
40

41 42 43 44
class IfuToFtqIO(implicit p:Parameters) extends XSBundle {
  val pdWb = Valid(new PredecodeWritebackBundle)
}

J
JinYue 已提交
45
class FtqInterface(implicit p: Parameters) extends XSBundle {
Z
zoujr 已提交
46
  val fromFtq = Flipped(new FtqToIfuIO)
Y
Yinan Xu 已提交
47
  val toFtq   = new IfuToFtqIO
48 49
}

50 51 52 53 54
class UncacheInterface(implicit p: Parameters) extends XSBundle {
  val fromUncache = Flipped(DecoupledIO(new InsUncacheResp))
  val toUncache   = DecoupledIO( new InsUncacheReq )
}

55 56 57 58 59 60
class ICacheInterface(implicit p: Parameters) extends XSBundle {
  val toIMeta       = Decoupled(new ICacheReadBundle)
  val toIData       = Decoupled(new ICacheReadBundle)
  val toMissQueue   = Vec(2,Decoupled(new ICacheMissReq))
  val fromIMeta     = Input(new ICacheMetaRespBundle)
  val fromIData     = Input(new ICacheDataRespBundle)
61
  val fromMissQueue = Vec(2,Flipped(Decoupled(new ICacheMissResp)))
J
JinYue 已提交
62 63
}

64
class NewIFUIO(implicit p: Parameters) extends XSBundle {
Y
Yinan Xu 已提交
65 66
  val ftqInter        = new FtqInterface
  val icacheInter     = new ICacheInterface
67
  val toIbuffer       = Decoupled(new FetchToIBuffer)
Y
Yinan Xu 已提交
68
  val iTLBInter       = Vec(2, new BlockTlbRequestIO)
69
  val uncacheInter   =  new UncacheInterface
L
Lemover 已提交
70 71 72 73
  val pmp             = Vec(2, new Bundle {
    val req = Valid(new PMPReqBundle())
    val resp = Input(new PMPRespBundle())
  })
J
JinYue 已提交
74 75
}

76 77 78 79 80 81 82 83
// record the situation in which fallThruAddr falls into
// the middle of an RVI inst
class LastHalfInfo(implicit p: Parameters) extends XSBundle {
  val valid = Bool()
  val middlePC = UInt(VAddrBits.W)
  def matchThisBlock(startAddr: UInt) = valid && middlePC === startAddr
}

84
class IfuToPreDecode(implicit p: Parameters) extends XSBundle {
Y
Yinan Xu 已提交
85
  val data          = if(HasCExtension) Vec(PredictWidth + 1, UInt(16.W)) else Vec(PredictWidth, UInt(32.W))
86
  val startAddr     = UInt(VAddrBits.W)
87
  val fallThruAddr  = UInt(VAddrBits.W)
J
JinYue 已提交
88
  val fallThruError = Bool()
J
JinYue 已提交
89
  val isDoubleLine  = Bool()
90
  val ftqOffset     = Valid(UInt(log2Ceil(PredictWidth).W))
J
jinyue110 已提交
91
  val target        = UInt(VAddrBits.W)
J
JinYue 已提交
92 93
  val pageFault     = Vec(2, Bool())
  val accessFault   = Vec(2, Bool())
Y
Yinan Xu 已提交
94
  val instValid     = Bool()
95
  val lastHalfMatch = Bool()
96
  val oversize      = Bool()
97
  val mmio = Bool()
98 99
}

100
class NewIFU(implicit p: Parameters) extends XSModule with HasICacheParameters
J
JinYue 已提交
101
{
102
  println(s"icache ways: ${nWays} sets:${nSets}")
J
JinYue 已提交
103
  val io = IO(new NewIFUIO)
104 105 106
  val (toFtq, fromFtq)    = (io.ftqInter.toFtq, io.ftqInter.fromFtq)
  val (toMeta, toData, meta_resp, data_resp) =  (io.icacheInter.toIMeta, io.icacheInter.toIData, io.icacheInter.fromIMeta, io.icacheInter.fromIData)
  val (toMissQueue, fromMissQueue) = (io.icacheInter.toMissQueue, io.icacheInter.fromMissQueue)
107
  val (toUncache, fromUncache) = (io.uncacheInter.toUncache , io.uncacheInter.fromUncache)
J
JinYue 已提交
108
  val (toITLB, fromITLB) = (VecInit(io.iTLBInter.map(_.req)), VecInit(io.iTLBInter.map(_.resp)))
L
Lemover 已提交
109
  val fromPMP = io.pmp.map(_.resp)
Y
Yinan Xu 已提交
110

111
  def isCrossLineReq(start: UInt, end: UInt): Bool = start(blockOffBits) ^ end(blockOffBits)
112

113
  def isLastInCacheline(fallThruAddr: UInt): Bool = fallThruAddr(blockOffBits - 1, 1) === 0.U
114

J
JinYue 已提交
115

J
jinyue110 已提交
116 117 118 119 120
  //---------------------------------------------
  //  Fetch Stage 1 :
  //  * Send req to ICache Meta/Data
  //  * Check whether need 2 line fetch
  //---------------------------------------------
Y
Yinan Xu 已提交
121

J
JinYue 已提交
122
  val f0_valid                             = fromFtq.req.valid
Z
zoujr 已提交
123
  val f0_ftq_req                           = fromFtq.req.bits
J
jinyue110 已提交
124 125
  val f0_situation                         = VecInit(Seq(isCrossLineReq(f0_ftq_req.startAddr, f0_ftq_req.fallThruAddr), isLastInCacheline(f0_ftq_req.fallThruAddr)))
  val f0_doubleLine                        = f0_situation(0) || f0_situation(1)
J
JinYue 已提交
126
  val f0_vSetIdx                           = VecInit(get_idx((f0_ftq_req.startAddr)), get_idx(f0_ftq_req.fallThruAddr))
Z
zoujr 已提交
127
  val f0_fire                              = fromFtq.req.fire()
J
JinYue 已提交
128

J
JinYue 已提交
129
  val f0_flush, f1_flush, f2_flush, f3_flush = WireInit(false.B)
130
  val from_bpu_f0_flush, from_bpu_f1_flush, from_bpu_f2_flush, from_bpu_f3_flush = WireInit(false.B)
Y
Yinan Xu 已提交
131

132 133 134
  from_bpu_f0_flush := fromFtq.flushFromBpu.shouldFlushByStage2(f0_ftq_req.ftqIdx) ||
                       fromFtq.flushFromBpu.shouldFlushByStage3(f0_ftq_req.ftqIdx)

J
JinYue 已提交
135 136 137
  val f3_redirect = WireInit(false.B)
  f3_flush := fromFtq.redirect.valid
  f2_flush := f3_flush || f3_redirect
138 139
  f1_flush := f2_flush || from_bpu_f1_flush
  f0_flush := f1_flush || from_bpu_f0_flush
J
JinYue 已提交
140

J
JinYue 已提交
141 142
  val f1_ready, f2_ready, f3_ready         = WireInit(false.B)

143
  //fetch: send addr to Meta/TLB and Data simultaneously
J
jinyue110 已提交
144
  val fetch_req = List(toMeta, toData)
145
  for(i <- 0 until 2) {
146
    fetch_req(i).valid := f0_fire
147 148 149
    fetch_req(i).bits.isDoubleLine := f0_doubleLine
    fetch_req(i).bits.vSetIdx := f0_vSetIdx
  }
150

J
JinYue 已提交
151
  fromFtq.req.ready := fetch_req(0).ready && fetch_req(1).ready && f1_ready && GTimer() > 500.U
J
jinyue110 已提交
152

J
JinYue 已提交
153 154 155 156 157
  XSPerfAccumulate("ifu_bubble_ftq_not_valid",   !f0_valid )
  XSPerfAccumulate("ifu_bubble_pipe_stall",    f0_valid && fetch_req(0).ready && fetch_req(1).ready && !f1_ready )
  XSPerfAccumulate("ifu_bubble_sram_0_busy",   f0_valid && !fetch_req(0).ready  )
  XSPerfAccumulate("ifu_bubble_sram_1_busy",   f0_valid && !fetch_req(1).ready  )

J
jinyue110 已提交
158 159
  //---------------------------------------------
  //  Fetch Stage 2 :
J
JinYue 已提交
160
  //  * Send req to ITLB and TLB Response (Get Paddr)
J
jinyue110 已提交
161 162 163 164
  //  * ICache Response (Get Meta and Data)
  //  * Hit Check (Generate hit signal and hit vector)
  //  * Get victim way
  //---------------------------------------------
J
JinYue 已提交
165

J
jinyue110 已提交
166 167
  //TODO: handle fetch exceptions

J
JinYue 已提交
168
  val tlbRespAllValid = WireInit(false.B)
J
jinyue110 已提交
169

J
JinYue 已提交
170
  val f1_valid      = RegInit(false.B)
J
jinyue110 已提交
171 172 173 174
  val f1_ftq_req    = RegEnable(next = f0_ftq_req,    enable=f0_fire)
  val f1_situation  = RegEnable(next = f0_situation,  enable=f0_fire)
  val f1_doubleLine = RegEnable(next = f0_doubleLine, enable=f0_fire)
  val f1_vSetIdx    = RegEnable(next = f0_vSetIdx,    enable=f0_fire)
J
JinYue 已提交
175 176 177
  val f1_fire       = f1_valid && tlbRespAllValid && f2_ready

  f1_ready := f2_ready && tlbRespAllValid || !f1_valid
Z
zoujr 已提交
178

179 180
  from_bpu_f1_flush := fromFtq.flushFromBpu.shouldFlushByStage3(f1_ftq_req.ftqIdx)

Z
zoujr 已提交
181 182 183 184
  val preDecoder      = Module(new PreDecode)
  val (preDecoderIn, preDecoderOut)   = (preDecoder.io.in, preDecoder.io.out)

  //flush generate and to Ftq
J
JinYue 已提交
185
  val predecodeOutValid = WireInit(false.B)
J
jinyue110 已提交
186

L
Lingrui98 已提交
187 188 189
  when(f1_flush)                  {f1_valid  := false.B}
  .elsewhen(f0_fire && !f0_flush) {f1_valid  := true.B}
  .elsewhen(f1_fire)              {f1_valid  := false.B}
J
JinYue 已提交
190

J
JinYue 已提交
191
  toITLB(0).valid         := f1_valid
L
Lemover 已提交
192
  toITLB(0).bits.size     := 3.U // TODO: fix the size
J
JinYue 已提交
193 194
  toITLB(0).bits.vaddr    := align(f1_ftq_req.startAddr, blockBytes)
  toITLB(0).bits.debug.pc := align(f1_ftq_req.startAddr, blockBytes)
Y
Yinan Xu 已提交
195

J
JinYue 已提交
196
  toITLB(1).valid         := f1_valid && f1_doubleLine
L
Lemover 已提交
197
  toITLB(1).bits.size     := 3.U // TODO: fix the size
J
JinYue 已提交
198 199 200 201 202
  toITLB(1).bits.vaddr    := align(f1_ftq_req.fallThruAddr, blockBytes)
  toITLB(1).bits.debug.pc := align(f1_ftq_req.fallThruAddr, blockBytes)

  toITLB.map{port =>
    port.bits.cmd                 := TlbCmd.exec
Y
Yinan Xu 已提交
203
    port.bits.robIdx              := DontCare
J
JinYue 已提交
204 205 206 207 208 209 210
    port.bits.debug.isFirstIssue  := DontCare
  }

  fromITLB.map(_.ready := true.B)

  val (tlbRespValid, tlbRespPAddr) = (fromITLB.map(_.valid), VecInit(fromITLB.map(_.bits.paddr)))
  val (tlbRespMiss,  tlbRespMMIO)  = (fromITLB.map(port => port.bits.miss && port.valid), fromITLB.map(port => port.bits.mmio && port.valid))
L
Lemover 已提交
211 212 213
  val (tlbExcpPF,    tlbExcpAF)    = (fromITLB.map(port => port.bits.excp.pf.instr && port.valid),
    fromITLB.map(port => (port.bits.excp.af.instr) && port.valid)) //TODO: Temp treat mmio req as access fault

J
JinYue 已提交
214 215 216 217

  tlbRespAllValid := tlbRespValid(0)  && (tlbRespValid(1) || !f1_doubleLine)

  val f1_pAddrs             = tlbRespPAddr   //TODO: Temporary assignment
J
JinYue 已提交
218
  val f1_pTags              = VecInit(f1_pAddrs.map(get_phy_tag(_)))
J
JinYue 已提交
219
  val (f1_tags, f1_cacheline_valid, f1_datas)   = (meta_resp.tags, meta_resp.valid, data_resp.datas)
220 221
  val bank0_hit_vec         = VecInit(f1_tags(0).zipWithIndex.map{ case(way_tag,i) => f1_cacheline_valid(0)(i) && way_tag ===  f1_pTags(0) })
  val bank1_hit_vec         = VecInit(f1_tags(1).zipWithIndex.map{ case(way_tag,i) => f1_cacheline_valid(1)(i) && way_tag ===  f1_pTags(1) })
Y
Yinan Xu 已提交
222 223
  val (bank0_hit,bank1_hit) = (ParallelOR(bank0_hit_vec) && !tlbExcpPF(0) && !tlbExcpAF(0), ParallelOR(bank1_hit_vec) && !tlbExcpPF(1) && !tlbExcpAF(1))
  val f1_hit                = (bank0_hit && bank1_hit && f1_valid && f1_doubleLine) || (f1_valid && !f1_doubleLine && bank0_hit)
J
JinYue 已提交
224 225
  val f1_bank_hit_vec       = VecInit(Seq(bank0_hit_vec, bank1_hit_vec))
  val f1_bank_hit           = VecInit(Seq(bank0_hit, bank1_hit))
J
JinYue 已提交
226

227 228 229 230 231
  //MMIO
  //MMIO only need 1 instruction
  val f1_mmio = tlbRespMMIO(0) && f1_valid


232
  val replacers       = Seq.fill(2)(ReplacementPolicy.fromString(Some("random"),nWays,nSets/2))
233
  val f1_victim_masks = VecInit(replacers.zipWithIndex.map{case (replacer, i) => UIntToOH(replacer.way(f1_vSetIdx(i)))})
J
JinYue 已提交
234

235 236
  val touch_sets = Seq.fill(2)(Wire(Vec(2, UInt(log2Ceil(nSets/2).W))))
  val touch_ways = Seq.fill(2)(Wire(Vec(2, Valid(UInt(log2Ceil(nWays).W)))) )
Y
Yinan Xu 已提交
237

J
jinyue110 已提交
238
  ((replacers zip touch_sets) zip touch_ways).map{case ((r, s),w) => r.access(s,w)}
Y
Yinan Xu 已提交
239

J
jinyue110 已提交
240
  val f1_hit_data      =  VecInit(f1_datas.zipWithIndex.map { case(bank, i) =>
241 242
    val bank_hit_data = Mux1H(f1_bank_hit_vec(i).asUInt, bank)
    bank_hit_data
J
jinyue110 已提交
243 244
  })

J
JinYue 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  (0 until nWays).map{ w =>
    XSPerfAccumulate("line_0_hit_way_" + Integer.toString(w, 10),  f1_fire && f1_bank_hit(0) && OHToUInt(f1_bank_hit_vec(0))  === w.U)
  }

  (0 until nWays).map{ w =>
    XSPerfAccumulate("line_0_victim_way_" + Integer.toString(w, 10),  f1_fire && !f1_bank_hit(0) && OHToUInt(f1_victim_masks(0))  === w.U)
  }

  (0 until nWays).map{ w =>
    XSPerfAccumulate("line_1_hit_way_" + Integer.toString(w, 10),  f1_fire && f1_doubleLine && f1_bank_hit(1) && OHToUInt(f1_bank_hit_vec(1))  === w.U)
  }

  (0 until nWays).map{ w =>
    XSPerfAccumulate("line_1_victim_way_" + Integer.toString(w, 10),  f1_fire && f1_doubleLine && !f1_bank_hit(1) && OHToUInt(f1_victim_masks(1))  === w.U)
  }

  XSPerfAccumulate("ifu_bubble_f1_tlb_miss",    f1_valid && !tlbRespAllValid )
262

J
jinyue110 已提交
263 264 265
  //---------------------------------------------
  //  Fetch Stage 3 :
  //  * get data from last stage (hit from f1_hit_data/miss from missQueue response)
J
JinYue 已提交
266
  //  * if at least one needed cacheline miss, wait for miss queue response (a wait_state machine) THIS IS TOO UGLY!!!
J
jinyue110 已提交
267 268 269
  //  * cut cacheline(s) and send to PreDecode
  //  * check if prediction is right (branch target and type, jump direction and type , jal target )
  //---------------------------------------------
J
JinYue 已提交
270 271
  val f2_fetchFinish = Wire(Bool())

J
JinYue 已提交
272
  val f2_valid        = RegInit(false.B)
J
JinYue 已提交
273 274
  val f2_ftq_req      = RegEnable(next = f1_ftq_req,    enable = f1_fire)
  val f2_situation    = RegEnable(next = f1_situation,  enable=f1_fire)
J
JinYue 已提交
275
  val f2_doubleLine   = RegEnable(next = f1_doubleLine, enable=f1_fire)
J
JinYue 已提交
276 277 278
  val f2_fire         = f2_valid && f2_fetchFinish && f3_ready

  f2_ready := (f3_ready && f2_fetchFinish) || !f2_valid
J
jinyue110 已提交
279

L
Lingrui98 已提交
280 281
  when(f2_flush)                  {f2_valid := false.B}
  .elsewhen(f1_fire && !f1_flush) {f2_valid := true.B }
J
JinYue 已提交
282 283
  .elsewhen(f2_fire)              {f2_valid := false.B}

L
Lemover 已提交
284
  val pmpExcpAF = fromPMP.map(port => port.instr)
285

286

287 288
  val f2_pAddrs   = RegEnable(next = f1_pAddrs, enable = f1_fire)
  val f2_hit      = RegEnable(next = f1_hit   , enable = f1_fire)
J
JinYue 已提交
289
  val f2_bank_hit = RegEnable(next = f1_bank_hit, enable = f1_fire)
Y
Yinan Xu 已提交
290
  val f2_miss     = f2_valid && !f2_hit
291 292
  val (f2_vSetIdx, f2_pTags) = (RegEnable(next = f1_vSetIdx, enable = f1_fire), RegEnable(next = f1_pTags, enable = f1_fire))
  val f2_waymask  = RegEnable(next = f1_victim_masks, enable = f1_fire)
J
JinYue 已提交
293 294
  //exception information
  val f2_except_pf = RegEnable(next = VecInit(tlbExcpPF), enable = f1_fire)
L
Lemover 已提交
295
  val f2_except_af = VecInit(RegEnable(next = VecInit(tlbExcpAF), enable = f1_fire).zip(pmpExcpAF).map(a => a._1 || DataHoldBypass(a._2, RegNext(f1_fire)).asBool))
J
JinYue 已提交
296 297
  val f2_except    = VecInit((0 until 2).map{i => f2_except_pf(i) || f2_except_af(i)})
  val f2_has_except = f2_valid && (f2_except_af.reduce(_||_) || f2_except_pf.reduce(_||_))
298 299 300 301 302 303
  //MMIO
  val f2_mmio      = RegInit(false.B)

  when(f2_flush)                             {f2_mmio := false.B}
  .elsewhen(f1_fire && f1_mmio && !f1_flush) {f2_mmio := true.B }
  .elsewhen(f2_fire)                         {f2_mmio := false.B}
L
Lemover 已提交
304 305 306 307 308 309 310
  //
  io.pmp.zipWithIndex.map { case (p, i) =>
    p.req.valid := f2_fire
    p.req.bits.addr := f2_pAddrs(i)
    p.req.bits.size := 3.U // TODO
    p.req.bits.cmd := TlbCmd.exec
  }
311

Y
Yinan Xu 已提交
312
  //instruction
313
  val wait_idle :: wait_queue_ready :: wait_send_req  :: wait_two_resp :: wait_0_resp :: wait_1_resp :: wait_one_resp ::wait_finish :: wait_send_mmio :: wait_mmio_resp ::Nil = Enum(10)
J
JinYue 已提交
314
  val wait_state = RegInit(wait_idle)
J
jinyue110 已提交
315 316 317 318 319 320

  fromMissQueue.map{port => port.ready := true.B}

  val (miss0_resp, miss1_resp) = (fromMissQueue(0).fire(), fromMissQueue(1).fire())
  val (bank0_fix, bank1_fix)   = (miss0_resp  && !f2_bank_hit(0), miss1_resp && f2_doubleLine && !f2_bank_hit(1))

321 322 323 324 325 326
  val  only_0_miss = f2_valid && !f2_hit && !f2_doubleLine && !f2_has_except && !f2_mmio
  val  only_0_hit  = f2_valid && f2_hit && !f2_doubleLine  && !f2_mmio
  val  hit_0_hit_1  = f2_valid && f2_hit && f2_doubleLine  && !f2_mmio
  val (hit_0_miss_1 ,  miss_0_hit_1,  miss_0_miss_1) = (  (f2_valid && !f2_bank_hit(1) && f2_bank_hit(0) && f2_doubleLine  && !f2_has_except  && !f2_mmio),
                                                          (f2_valid && !f2_bank_hit(0) && f2_bank_hit(1) && f2_doubleLine  && !f2_has_except  && !f2_mmio),
                                                          (f2_valid && !f2_bank_hit(0) && !f2_bank_hit(1) && f2_doubleLine && !f2_has_except  && !f2_mmio),
J
JinYue 已提交
327 328
                                                       )

Y
Yinan Xu 已提交
329 330
  val  hit_0_except_1  = f2_valid && f2_doubleLine &&  !f2_except(0) && f2_except(1)  &&  f2_bank_hit(0)
  val  miss_0_except_1 = f2_valid && f2_doubleLine &&  !f2_except(0) && f2_except(1)  && !f2_bank_hit(0)
J
JinYue 已提交
331
  //val  fetch0_except_1 = hit_0_except_1 || miss_0_except_1
Y
Yinan Xu 已提交
332
  val  except_0        = f2_valid && f2_except(0)
J
JinYue 已提交
333

Y
Yinan Xu 已提交
334
  val f2_mq_datas     = Reg(Vec(2, UInt(blockBits.W)))
335
  val f2_mmio_data    = Reg(UInt(maxInstrLen.W))
336 337 338

  when(fromMissQueue(0).fire) {f2_mq_datas(0) :=  fromMissQueue(0).bits.data}
  when(fromMissQueue(1).fire) {f2_mq_datas(1) :=  fromMissQueue(1).bits.data}
339
  when(fromUncache.fire())    {f2_mmio_data   :=  fromUncache.bits.data}
340

J
JinYue 已提交
341 342
  switch(wait_state){
    is(wait_idle){
343 344 345
      when(f2_mmio && !f2_except_af(0) && !f2_except_pf(0)){
        wait_state :=  wait_send_mmio
      }.elsewhen(miss_0_except_1){
J
JinYue 已提交
346 347
        wait_state :=  Mux(toMissQueue(0).ready, wait_queue_ready ,wait_idle )
      }.elsewhen( only_0_miss  || miss_0_hit_1){
J
JinYue 已提交
348
        wait_state :=  Mux(toMissQueue(0).ready, wait_queue_ready ,wait_idle )
J
JinYue 已提交
349
      }.elsewhen(hit_0_miss_1){
J
JinYue 已提交
350
        wait_state :=  Mux(toMissQueue(1).ready, wait_queue_ready ,wait_idle )
J
JinYue 已提交
351
      }.elsewhen( miss_0_miss_1 ){
J
JinYue 已提交
352
        wait_state := Mux(toMissQueue(0).ready && toMissQueue(1).ready, wait_queue_ready ,wait_idle)
J
jinyue110 已提交
353
      }
J
JinYue 已提交
354
    }
J
jinyue110 已提交
355

356 357 358 359 360 361 362 363
    is(wait_send_mmio){
      wait_state := Mux(toUncache.fire(), wait_mmio_resp,wait_send_mmio )
    }

    is(wait_mmio_resp){
      wait_state :=  Mux(fromUncache.fire(), wait_finish, wait_mmio_resp)
    }

J
JinYue 已提交
364
    //TODO: naive logic for wait icache response
J
JinYue 已提交
365 366 367
    is(wait_queue_ready){
      wait_state := wait_send_req
    }
J
JinYue 已提交
368

J
JinYue 已提交
369
    is(wait_send_req) {
J
JinYue 已提交
370
      when(miss_0_except_1 || only_0_miss || hit_0_miss_1 || miss_0_hit_1){
J
JinYue 已提交
371 372 373 374 375 376 377
        wait_state :=  wait_one_resp
      }.elsewhen( miss_0_miss_1 ){
        wait_state := wait_two_resp
      }
    }

    is(wait_one_resp) {
J
JinYue 已提交
378
      when( (miss_0_except_1 ||only_0_miss || miss_0_hit_1) && fromMissQueue(0).fire()){
J
JinYue 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
        wait_state := wait_finish
      }.elsewhen( hit_0_miss_1 && fromMissQueue(1).fire()){
        wait_state := wait_finish
      }
    }

    is(wait_two_resp) {
      when(fromMissQueue(0).fire() && fromMissQueue(1).fire()){
        wait_state := wait_finish
      }.elsewhen( !fromMissQueue(0).fire() && fromMissQueue(1).fire() ){
        wait_state := wait_0_resp
      }.elsewhen(fromMissQueue(0).fire() && !fromMissQueue(1).fire()){
        wait_state := wait_1_resp
      }
    }

    is(wait_0_resp) {
      when(fromMissQueue(0).fire()){
        wait_state := wait_finish
J
jinyue110 已提交
398 399 400
      }
    }

J
JinYue 已提交
401 402 403 404 405
    is(wait_1_resp) {
      when(fromMissQueue(1).fire()){
        wait_state := wait_finish
      }
    }
J
jinyue110 已提交
406

J
JinYue 已提交
407
    is(wait_finish) {
J
JinYue 已提交
408
      when(f2_fire) {wait_state := wait_idle }
J
JinYue 已提交
409 410
    }
  }
J
jinyue110 已提交
411

J
JinYue 已提交
412
  when(f2_flush) { wait_state := wait_idle }
413

J
JinYue 已提交
414
  (0 until 2).map { i =>
J
JinYue 已提交
415
    if(i == 1) toMissQueue(i).valid := (hit_0_miss_1 || miss_0_miss_1) && wait_state === wait_queue_ready
416
      else     toMissQueue(i).valid := (only_0_miss || miss_0_hit_1 || miss_0_miss_1 || miss_0_except_1) && wait_state === wait_queue_ready
J
JinYue 已提交
417 418 419 420 421 422
    toMissQueue(i).bits.addr    := f2_pAddrs(i)
    toMissQueue(i).bits.vSetIdx := f2_vSetIdx(i)
    toMissQueue(i).bits.waymask := f2_waymask(i)
    toMissQueue(i).bits.clientID :=0.U
  }

423 424 425 426 427 428
  toUncache.valid :=  (wait_state === wait_send_mmio) && !f2_except_af(0)
  //assert( (GTimer() < 5000.U && toUncache.fire()) || !toUncache.fire() ) 
  toUncache.bits.addr := f2_ftq_req.startAddr

  fromUncache.ready := true.B

J
JinYue 已提交
429
  val miss_all_fix       = (wait_state === wait_finish)
Y
Yinan Xu 已提交
430

J
JinYue 已提交
431
  f2_fetchFinish         := ((f2_valid && f2_hit) || miss_all_fix || hit_0_except_1 || except_0)
J
JinYue 已提交
432

J
JinYue 已提交
433
  XSPerfAccumulate("ifu_bubble_f2_miss",    f2_valid && !f2_fetchFinish )
J
JinYue 已提交
434 435

  (touch_ways zip touch_sets).zipWithIndex.map{ case((t_w,t_s), i) =>
J
jinyue110 已提交
436 437 438 439
    t_s(0)         := f1_vSetIdx(i)
    t_w(0).valid   := f1_bank_hit(i)
    t_w(0).bits    := OHToUInt(f1_bank_hit_vec(i))

J
JinYue 已提交
440 441 442
    t_s(1)         := f2_vSetIdx(i)
    t_w(1).valid   := f2_valid && !f2_bank_hit(i)
    t_w(1).bits    := OHToUInt(f2_waymask(i))
443
  }
Y
Yinan Xu 已提交
444

J
JinYue 已提交
445 446
  val sec_miss_reg   = RegInit(0.U.asTypeOf(Vec(4, Bool())))
  val reservedRefillData = Reg(Vec(2, UInt(blockBits.W)))
Y
Yinan Xu 已提交
447
  val f2_hit_datas    = RegEnable(next = f1_hit_data, enable = f1_fire)
J
JinYue 已提交
448
  val f2_datas        = Wire(Vec(2, UInt(blockBits.W)))
J
JinYue 已提交
449

Y
Yinan Xu 已提交
450
  f2_datas.zipWithIndex.map{case(bank,i) =>
451 452
    if(i == 0) bank := Mux(f2_bank_hit(i), f2_hit_datas(i),Mux(sec_miss_reg(2),reservedRefillData(1),Mux(sec_miss_reg(0),reservedRefillData(0), f2_mq_datas(i))))
    else bank := Mux(f2_bank_hit(i), f2_hit_datas(i),Mux(sec_miss_reg(3),reservedRefillData(1),Mux(sec_miss_reg(1),reservedRefillData(0), f2_mq_datas(i))))
J
JinYue 已提交
453
  }
J
JinYue 已提交
454

455
  val f2_jump_valids          = Fill(PredictWidth, !preDecoderOut.cfiOffset.valid)   | Fill(PredictWidth, 1.U(1.W)) >> (~preDecoderOut.cfiOffset.bits)
456
  val f2_predecode_valids     = VecInit(preDecoderOut.pd.map(instr => instr.valid)).asUInt & f2_jump_valids
J
JinYue 已提交
457

J
JinYue 已提交
458
  def cut(cacheline: UInt, start: UInt) : Vec[UInt] ={
459 460 461 462 463 464 465
    if(HasCExtension){
      val result   = Wire(Vec(PredictWidth + 1, UInt(16.W)))
      val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 2, UInt(16.W)))
      val startPtr = Cat(0.U(1.W), start(blockOffBits-1, 1))
      (0 until PredictWidth + 1).foreach( i =>
        result(i) := dataVec(startPtr + i.U)
      )
Y
Yinan Xu 已提交
466
      result
467 468 469 470 471 472 473
    } else {
      val result   = Wire(Vec(PredictWidth, UInt(32.W)) )
      val dataVec  = cacheline.asTypeOf(Vec(blockBytes * 2/ 4, UInt(32.W)))
      val startPtr = Cat(0.U(1.W), start(blockOffBits-1, 2))
      (0 until PredictWidth).foreach( i =>
        result(i) := dataVec(startPtr + i.U)
      )
Y
Yinan Xu 已提交
474
      result
475
    }
476 477
  }

J
JinYue 已提交
478
  val f2_cut_data = cut( Cat(f2_datas.map(cacheline => cacheline.asUInt ).reverse).asUInt, f2_ftq_req.startAddr )
479 480 481 482
  when(f2_mmio){
    f2_cut_data(0) := f2_mmio_data(15, 0)
    f2_cut_data(1) := f2_mmio_data(31, 16)
  }
Y
Yinan Xu 已提交
483 484

  // deal with secondary miss in f1
J
JinYue 已提交
485 486 487 488 489
  val f2_0_f1_0 =   ((f2_valid && !f2_bank_hit(0)) && f1_valid && (get_block_addr(f2_ftq_req.startAddr) === get_block_addr(f1_ftq_req.startAddr)))
  val f2_0_f1_1 =   ((f2_valid && !f2_bank_hit(0)) && f1_valid && f1_doubleLine && (get_block_addr(f2_ftq_req.startAddr) === get_block_addr(f1_ftq_req.startAddr + blockBytes.U)))
  val f2_1_f1_0 =   ((f2_valid && !f2_bank_hit(1) && f2_doubleLine) && f1_valid && (get_block_addr(f2_ftq_req.startAddr+ blockBytes.U) === get_block_addr(f1_ftq_req.startAddr) ))
  val f2_1_f1_1 =   ((f2_valid && !f2_bank_hit(1) && f2_doubleLine) && f1_valid && f1_doubleLine && (get_block_addr(f2_ftq_req.startAddr+ blockBytes.U) === get_block_addr(f1_ftq_req.startAddr + blockBytes.U) ))

Y
Yinan Xu 已提交
490
  val isSameLine = f2_0_f1_0 || f2_0_f1_1 || f2_1_f1_0 || f2_1_f1_1
J
JinYue 已提交
491 492 493 494 495 496
  val sec_miss_sit   = VecInit(Seq(f2_0_f1_0, f2_0_f1_1, f2_1_f1_0, f2_1_f1_1))
  val hasSecMiss     = RegInit(false.B)

  when(f2_flush){
    sec_miss_reg.map(sig => sig := false.B)
    hasSecMiss := false.B
J
JinYue 已提交
497
  }.elsewhen(isSameLine && !f1_flush && f2_fire){
J
JinYue 已提交
498 499
    sec_miss_reg.zipWithIndex.map{case(sig, i) => sig := sec_miss_sit(i)}
    hasSecMiss := true.B
J
JinYue 已提交
500
  }.elsewhen((!isSameLine || f1_flush) && hasSecMiss && f2_fire){
J
JinYue 已提交
501 502 503 504
    sec_miss_reg.map(sig => sig := false.B)
    hasSecMiss := false.B
  }

J
JinYue 已提交
505
  when((f2_0_f1_0 || f2_0_f1_1) && f2_fire){
J
JinYue 已提交
506 507
    reservedRefillData(0) := f2_mq_datas(0)
  }
J
JinYue 已提交
508

J
JinYue 已提交
509
  when((f2_1_f1_0 || f2_1_f1_1) && f2_fire){
J
JinYue 已提交
510 511
    reservedRefillData(1) := f2_mq_datas(1)
  }
J
JinYue 已提交
512 513


J
JinYue 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
  //---------------------------------------------
  //  Fetch Stage 4 :
  //  * get data from last stage (hit from f1_hit_data/miss from missQueue response)
  //  * if at least one needed cacheline miss, wait for miss queue response (a wait_state machine) THIS IS TOO UGLY!!!
  //  * cut cacheline(s) and send to PreDecode
  //  * check if prediction is right (branch target and type, jump direction and type , jal target )
  //---------------------------------------------
  val f3_valid          = RegInit(false.B)
  val f3_ftq_req        = RegEnable(next = f2_ftq_req,    enable=f2_fire)
  val f3_situation      = RegEnable(next = f2_situation,  enable=f2_fire)
  val f3_doubleLine     = RegEnable(next = f2_doubleLine, enable=f2_fire)
  val f3_fire           = io.toIbuffer.fire()

  when(f3_flush)                  {f3_valid := false.B}
  .elsewhen(f2_fire && !f2_flush) {f3_valid := true.B }
  .elsewhen(io.toIbuffer.fire())  {f3_valid := false.B}

  f3_ready := io.toIbuffer.ready || !f2_valid

  val f3_cut_data       = RegEnable(next = f2_cut_data, enable=f2_fire)
  val f3_except_pf      = RegEnable(next = f2_except_pf, enable = f2_fire)
  val f3_except_af      = RegEnable(next = f2_except_af, enable = f2_fire)
  val f3_hit            = RegEnable(next = f2_hit   , enable = f2_fire)
537
  val f3_mmio           = RegEnable(next = f2_mmio   , enable = f2_fire)
J
JinYue 已提交
538 539 540 541 542 543

  val f3_lastHalf       = RegInit(0.U.asTypeOf(new LastHalfInfo))
  val f3_lastHalfMatch  = f3_lastHalf.matchThisBlock(f3_ftq_req.startAddr)
  val f3_except         = VecInit((0 until 2).map{i => f3_except_pf(i) || f3_except_af(i)})
  val f3_has_except     = f3_valid && (f3_except_af.reduce(_||_) || f3_except_pf.reduce(_||_))

J
JinYue 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557
  //performance counter
  val f3_only_0_hit     = RegEnable(next = only_0_hit, enable = f2_fire)
  val f3_only_0_miss    = RegEnable(next = only_0_miss, enable = f2_fire)
  val f3_hit_0_hit_1    = RegEnable(next = hit_0_hit_1, enable = f2_fire)
  val f3_hit_0_miss_1   = RegEnable(next = hit_0_miss_1, enable = f2_fire)
  val f3_miss_0_hit_1   = RegEnable(next = miss_0_hit_1, enable = f2_fire)
  val f3_miss_0_miss_1  = RegEnable(next = miss_0_miss_1, enable = f2_fire)

  val f3_bank_hit = RegEnable(next = f2_bank_hit, enable = f2_fire)
  val f3_req_0 = io.toIbuffer.fire()
  val f3_req_1 = io.toIbuffer.fire() && f3_doubleLine
  val f3_hit_0 = io.toIbuffer.fire() & f3_bank_hit(0)
  val f3_hit_1 = io.toIbuffer.fire() && f3_doubleLine & f3_bank_hit(1)

J
JinYue 已提交
558 559 560 561 562 563 564 565 566 567
  preDecoderIn.instValid     :=  f3_valid && !f3_has_except
  preDecoderIn.data          :=  f3_cut_data
  preDecoderIn.startAddr     :=  f3_ftq_req.startAddr
  preDecoderIn.fallThruAddr  :=  f3_ftq_req.fallThruAddr
  preDecoderIn.fallThruError :=  f3_ftq_req.fallThruError
  preDecoderIn.isDoubleLine  :=  f3_doubleLine
  preDecoderIn.ftqOffset     :=  f3_ftq_req.ftqOffset
  preDecoderIn.target        :=  f3_ftq_req.target
  preDecoderIn.oversize      :=  f3_ftq_req.oversize
  preDecoderIn.lastHalfMatch :=  f3_lastHalfMatch
Y
Yinan Xu 已提交
568
  preDecoderIn.pageFault     :=  f3_except_pf
J
JinYue 已提交
569
  preDecoderIn.accessFault   :=  f3_except_af
570
  preDecoderIn.mmio          :=  f3_mmio
J
JinYue 已提交
571 572


573
  // TODO: What if next packet does not match?
J
JinYue 已提交
574 575
  when (f3_flush) {
    f3_lastHalf.valid := false.B
576
  }.elsewhen (io.toIbuffer.fire()) {
J
JinYue 已提交
577 578
    f3_lastHalf.valid := preDecoderOut.hasLastHalf
    f3_lastHalf.middlePC := preDecoderOut.realEndPC
579 580
  }

J
JinYue 已提交
581
  val f3_predecode_range = VecInit(preDecoderOut.pd.map(inst => inst.valid)).asUInt
582
  val f3_mmio_range      = VecInit((0 until PredictWidth).map(i => if(i ==0) true.B else false.B))
583

Y
Yinan Xu 已提交
584
  io.toIbuffer.valid          := f3_valid
J
jinyue110 已提交
585
  io.toIbuffer.bits.instrs    := preDecoderOut.instrs
586
  io.toIbuffer.bits.valid     := Mux(f3_mmio, f3_mmio_range.asUInt, f3_predecode_range & preDecoderOut.instrRange.asUInt)
J
jinyue110 已提交
587
  io.toIbuffer.bits.pd        := preDecoderOut.pd
J
JinYue 已提交
588
  io.toIbuffer.bits.ftqPtr    := f3_ftq_req.ftqIdx
589
  io.toIbuffer.bits.pc        := preDecoderOut.pc
590
  io.toIbuffer.bits.ftqOffset.zipWithIndex.map{case(a, i) => a.bits := i.U; a.valid := preDecoderOut.takens(i) && !f3_mmio}
591
  io.toIbuffer.bits.foldpc    := preDecoderOut.pc.map(i => XORFold(i(VAddrBits-1,1), MemPredPCWidth))
J
JinYue 已提交
592 593 594
  io.toIbuffer.bits.ipf       := preDecoderOut.pageFault
  io.toIbuffer.bits.acf       := preDecoderOut.accessFault
  io.toIbuffer.bits.crossPageIPFFix := preDecoderOut.crossPageIPF
J
JinYue 已提交
595

J
JinYue 已提交
596
  //Write back to Ftq
J
JinYue 已提交
597
  val finishFetchMaskReg = RegNext(f3_valid && !(f2_fire && !f2_flush))
J
JinYue 已提交
598

599 600 601 602
  val f3_mmio_missOffset = Wire(ValidUndirectioned(UInt(log2Ceil(PredictWidth).W)))
  f3_mmio_missOffset.valid := f3_mmio
  f3_mmio_missOffset.bits  := 0.U

J
JinYue 已提交
603
  toFtq.pdWb.valid           := !finishFetchMaskReg && f3_valid
J
jinyue110 已提交
604
  toFtq.pdWb.bits.pc         := preDecoderOut.pc
Y
Yinan Xu 已提交
605
  toFtq.pdWb.bits.pd         := preDecoderOut.pd
606
  toFtq.pdWb.bits.pd.zipWithIndex.map{case(instr,i) => instr.valid :=  Mux(f3_mmio, f3_mmio_range(i), f3_predecode_range(i))}
J
JinYue 已提交
607
  toFtq.pdWb.bits.ftqIdx     := f3_ftq_req.ftqIdx
Y
Yinan Xu 已提交
608
  toFtq.pdWb.bits.ftqOffset  := f3_ftq_req.ftqOffset.bits
609
  toFtq.pdWb.bits.misOffset  := Mux(f3_mmio, f3_mmio_missOffset, preDecoderOut.misOffset)
610
  toFtq.pdWb.bits.cfiOffset  := preDecoderOut.cfiOffset
611
  toFtq.pdWb.bits.target     :=  Mux(f3_mmio,Mux(toFtq.pdWb.bits.pd(0).isRVC, toFtq.pdWb.bits.pc(0) + 2.U , toFtq.pdWb.bits.pc(0)+4.U) ,preDecoderOut.target)
612
  toFtq.pdWb.bits.jalTarget  := preDecoderOut.jalTarget
613
  toFtq.pdWb.bits.instrRange := Mux(f3_mmio, f3_mmio_range, preDecoderOut.instrRange)
614

615
  val predecodeFlush     = ((preDecoderOut.misOffset.valid || f3_mmio) && f3_valid) 
J
JinYue 已提交
616
  val predecodeFlushReg  = RegNext(predecodeFlush && !(f2_fire && !f2_flush))
617

J
JinYue 已提交
618

J
JinYue 已提交
619
  f3_redirect := !predecodeFlushReg && predecodeFlush
J
JinYue 已提交
620

J
JinYue 已提交
621 622 623 624 625 626
  XSPerfAccumulate("ifu_req",   io.toIbuffer.fire() )
  XSPerfAccumulate("ifu_miss",  io.toIbuffer.fire() && !f3_hit )
  XSPerfAccumulate("ifu_req_cacheline_0", f3_req_0  )
  XSPerfAccumulate("ifu_req_cacheline_1", f3_req_1  )
  XSPerfAccumulate("ifu_req_cacheline_0_hit",   f3_hit_0 )
  XSPerfAccumulate("ifu_req_cacheline_1_hit",   f3_hit_1 )
L
Lingrui98 已提交
627
  XSPerfAccumulate("frontendFlush",  f3_redirect )
J
JinYue 已提交
628 629 630 631 632 633 634 635
  XSPerfAccumulate("only_0_hit",      f3_only_0_hit   && io.toIbuffer.fire()  )
  XSPerfAccumulate("only_0_miss",     f3_only_0_miss  && io.toIbuffer.fire()  )
  XSPerfAccumulate("hit_0_hit_1",     f3_hit_0_hit_1  && io.toIbuffer.fire()  )
  XSPerfAccumulate("hit_0_miss_1",    f3_hit_0_miss_1 && io.toIbuffer.fire()  )
  XSPerfAccumulate("miss_0_hit_1",    f3_miss_0_hit_1  && io.toIbuffer.fire() )
  XSPerfAccumulate("miss_0_miss_1",   f3_miss_0_miss_1 && io.toIbuffer.fire() )
  XSPerfAccumulate("cross_line_block", io.toIbuffer.fire() && f3_situation(0) )
  XSPerfAccumulate("fall_through_is_cacheline_end", io.toIbuffer.fire() && f3_situation(1) )
636
}