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.backend.fu 18 19import chipsalliance.rocketchip.config.Parameters 20import chisel3._ 21import chisel3.util._ 22import difftest._ 23import freechips.rocketchip.util._ 24import utils.MaskedRegMap.WritableMask 25import utils._ 26import xiangshan.ExceptionNO._ 27import xiangshan._ 28import xiangshan.backend.fu.util._ 29import xiangshan.cache._ 30 31// Trigger Tdata1 bundles 32trait HasTriggerConst { 33 def I_Trigger = 0.U 34 def S_Trigger = 1.U 35 def L_Trigger = 2.U 36 def GenESL(triggerType: UInt) = Cat((triggerType === I_Trigger), (triggerType === S_Trigger), (triggerType === L_Trigger)) 37} 38 39class TdataBundle extends Bundle { 40 val ttype = UInt(4.W) 41 val dmode = Bool() 42 val maskmax = UInt(6.W) 43 val zero1 = UInt(30.W) 44 val sizehi = UInt(2.W) 45 val hit = Bool() 46 val select = Bool() 47 val timing = Bool() 48 val sizelo = UInt(2.W) 49 val action = UInt(4.W) 50 val chain = Bool() 51 val matchType = UInt(4.W) 52 val m = Bool() 53 val zero2 = Bool() 54 val s = Bool() 55 val u = Bool() 56 val execute = Bool() 57 val store = Bool() 58 val load = Bool() 59} 60 61class FpuCsrIO extends Bundle { 62 val fflags = Output(Valid(UInt(5.W))) 63 val isIllegal = Output(Bool()) 64 val dirty_fs = Output(Bool()) 65 val frm = Input(UInt(3.W)) 66} 67 68 69class PerfCounterIO(implicit p: Parameters) extends XSBundle { 70 val perfEventsFrontend = Vec(numCSRPCntFrontend, new PerfEvent) 71 val perfEventsCtrl = Vec(numCSRPCntCtrl, new PerfEvent) 72 val perfEventsLsu = Vec(numCSRPCntLsu, new PerfEvent) 73 val perfEventsHc = Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent) 74 val retiredInstr = UInt(3.W) 75 val frontendInfo = new Bundle { 76 val ibufFull = Bool() 77 val bpuInfo = new Bundle { 78 val bpRight = UInt(XLEN.W) 79 val bpWrong = UInt(XLEN.W) 80 } 81 } 82 val ctrlInfo = new Bundle { 83 val robFull = Bool() 84 val intdqFull = Bool() 85 val fpdqFull = Bool() 86 val lsdqFull = Bool() 87 } 88 val memInfo = new Bundle { 89 val sqFull = Bool() 90 val lqFull = Bool() 91 val dcacheMSHRFull = Bool() 92 } 93 94 val cacheInfo = new Bundle { 95 val l2MSHRFull = Bool() 96 val l3MSHRFull = Bool() 97 val l2nAcquire = UInt(XLEN.W) 98 val l2nAcquireMiss = UInt(XLEN.W) 99 val l3nAcquire = UInt(XLEN.W) 100 val l3nAcquireMiss = UInt(XLEN.W) 101 } 102} 103 104class CSRFileIO(implicit p: Parameters) extends XSBundle { 105 val hartId = Input(UInt(8.W)) 106 // output (for func === CSROpType.jmp) 107 val perf = Input(new PerfCounterIO) 108 val isPerfCnt = Output(Bool()) 109 // to FPU 110 val fpu = Flipped(new FpuCsrIO) 111 // from rob 112 val exception = Flipped(ValidIO(new ExceptionInfo)) 113 // to ROB 114 val isXRet = Output(Bool()) 115 val trapTarget = Output(UInt(VAddrBits.W)) 116 val interrupt = Output(Bool()) 117 val wfi_event = Output(Bool()) 118 // from LSQ 119 val memExceptionVAddr = Input(UInt(VAddrBits.W)) 120 // from outside cpu,externalInterrupt 121 val externalInterrupt = new ExternalInterruptIO 122 // TLB 123 val tlb = Output(new TlbCsrBundle) 124 // Debug Mode 125 // val singleStep = Output(Bool()) 126 val debugMode = Output(Bool()) 127 // to Fence to disable sfence 128 val disableSfence = Output(Bool()) 129 // Custom microarchiture ctrl signal 130 val customCtrl = Output(new CustomCSRCtrlIO) 131 // distributed csr write 132 val distributedUpdate = Vec(2, Flipped(new DistributedCSRUpdateReq)) 133} 134 135class CSR(implicit p: Parameters) extends FunctionUnit with HasCSRConst with PMPMethod with PMAMethod with HasTriggerConst 136{ 137 val csrio = IO(new CSRFileIO) 138 139 val cfIn = io.in.bits.uop.cf 140 val cfOut = Wire(new CtrlFlow) 141 cfOut := cfIn 142 val flushPipe = Wire(Bool()) 143 144 val (valid, src1, src2, func) = ( 145 io.in.valid, 146 io.in.bits.src(0), 147 io.in.bits.uop.ctrl.imm, 148 io.in.bits.uop.ctrl.fuOpType 149 ) 150 151 // CSR define 152 153 class Priv extends Bundle { 154 val m = Output(Bool()) 155 val h = Output(Bool()) 156 val s = Output(Bool()) 157 val u = Output(Bool()) 158 } 159 160 val csrNotImplemented = RegInit(UInt(XLEN.W), 0.U) 161 162 class DcsrStruct extends Bundle { 163 val xdebugver = Output(UInt(2.W)) 164 val zero4 = Output(UInt(2.W)) 165 val zero3 = Output(UInt(12.W)) 166 val ebreakm = Output(Bool()) 167 val ebreakh = Output(Bool()) 168 val ebreaks = Output(Bool()) 169 val ebreaku = Output(Bool()) 170 val stepie = Output(Bool()) // 0 171 val stopcycle = Output(Bool()) 172 val stoptime = Output(Bool()) 173 val cause = Output(UInt(3.W)) 174 val v = Output(Bool()) // 0 175 val mprven = Output(Bool()) 176 val nmip = Output(Bool()) 177 val step = Output(Bool()) 178 val prv = Output(UInt(2.W)) 179 } 180 181 class MstatusStruct extends Bundle { 182 val sd = Output(UInt(1.W)) 183 184 val pad1 = if (XLEN == 64) Output(UInt(25.W)) else null 185 val mbe = if (XLEN == 64) Output(UInt(1.W)) else null 186 val sbe = if (XLEN == 64) Output(UInt(1.W)) else null 187 val sxl = if (XLEN == 64) Output(UInt(2.W)) else null 188 val uxl = if (XLEN == 64) Output(UInt(2.W)) else null 189 val pad0 = if (XLEN == 64) Output(UInt(9.W)) else Output(UInt(8.W)) 190 191 val tsr = Output(UInt(1.W)) 192 val tw = Output(UInt(1.W)) 193 val tvm = Output(UInt(1.W)) 194 val mxr = Output(UInt(1.W)) 195 val sum = Output(UInt(1.W)) 196 val mprv = Output(UInt(1.W)) 197 val xs = Output(UInt(2.W)) 198 val fs = Output(UInt(2.W)) 199 val mpp = Output(UInt(2.W)) 200 val hpp = Output(UInt(2.W)) 201 val spp = Output(UInt(1.W)) 202 val pie = new Priv 203 val ie = new Priv 204 assert(this.getWidth == XLEN) 205 206 def ube = pie.h // a little ugly 207 def ube_(r: UInt): Unit = { 208 pie.h := r(0) 209 } 210 } 211 212 class Interrupt extends Bundle { 213// val d = Output(Bool()) // Debug 214 val e = new Priv 215 val t = new Priv 216 val s = new Priv 217 } 218 219 // Debug CSRs 220 val dcsr = RegInit(UInt(32.W), 0x4000b000.U) 221 val dpc = Reg(UInt(64.W)) 222 val dscratch = Reg(UInt(64.W)) 223 val dscratch1 = Reg(UInt(64.W)) 224 val debugMode = RegInit(false.B) 225 val debugIntrEnable = RegInit(true.B) 226 csrio.debugMode := debugMode 227 228 val dpcPrev = RegNext(dpc) 229 XSDebug(dpcPrev =/= dpc, "Debug Mode: dpc is altered! Current is %x, previous is %x\n", dpc, dpcPrev) 230 231 // dcsr value table 232 // | debugver | 0100 233 // | zero | 10 bits of 0 234 // | ebreakvs | 0 235 // | ebreakvu | 0 236 // | ebreakm | 1 if ebreak enters debug 237 // | zero | 0 238 // | ebreaks | 239 // | ebreaku | 240 // | stepie | disable interrupts in singlestep 241 // | stopcount| stop counter, 0 242 // | stoptime | stop time, 0 243 // | cause | 3 bits read only 244 // | v | 0 245 // | mprven | 1 246 // | nmip | read only 247 // | step | 248 // | prv | 2 bits 249 250 val dcsrData = Wire(new DcsrStruct) 251 dcsrData := dcsr.asTypeOf(new DcsrStruct) 252 val dcsrMask = ZeroExt(GenMask(15) | GenMask(13, 11) | GenMask(4) | GenMask(2, 0), XLEN)// Dcsr write mask 253 def dcsrUpdateSideEffect(dcsr: UInt): UInt = { 254 val dcsrOld = WireInit(dcsr.asTypeOf(new DcsrStruct)) 255 val dcsrNew = dcsr | (dcsrOld.prv(0) | dcsrOld.prv(1)).asUInt // turn 10 priv into 11 256 dcsrNew 257 } 258 // csrio.singleStep := dcsrData.step 259 csrio.customCtrl.singlestep := dcsrData.step && !debugMode 260 261 // Trigger CSRs 262 263 val type_config = Array( 264 0.U -> I_Trigger, 1.U -> I_Trigger, 265 2.U -> S_Trigger, 3.U -> S_Trigger, 266 4.U -> L_Trigger, 5.U -> L_Trigger, // No.5 Load Trigger 267 6.U -> I_Trigger, 7.U -> S_Trigger, 268 8.U -> I_Trigger, 9.U -> L_Trigger 269 ) 270 def TypeLookup(select: UInt) = MuxLookup(select, I_Trigger, type_config) 271 272 val tdata1Phy = RegInit(VecInit(List.fill(10) {(2L << 60L).U(64.W)})) // init ttype 2 273 val tdata2Phy = Reg(Vec(10, UInt(64.W))) 274 val tselectPhy = RegInit(0.U(4.W)) 275 val tinfo = RegInit(2.U(64.W)) 276 val tControlPhy = RegInit(0.U(64.W)) 277 val triggerAction = RegInit(false.B) 278 279 def ReadTdata1(rdata: UInt) = rdata | Cat(triggerAction, 0.U(12.W)) // fix action 280 def WriteTdata1(wdata: UInt): UInt = { 281 val tdata1 = WireInit(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle)) 282 val wdata_wire = WireInit(wdata.asTypeOf(new TdataBundle)) 283 val tdata1_new = WireInit(wdata.asTypeOf(new TdataBundle)) 284 XSDebug(src2(11, 0) === Tdata1.U && valid && func =/= CSROpType.jmp, p"Debug Mode: tdata1(${tselectPhy})is written, the actual value is ${wdata}\n") 285// tdata1_new.hit := wdata(20) 286 tdata1_new.ttype := tdata1.ttype 287 tdata1_new.dmode := 0.U // Mux(debugMode, wdata_wire.dmode, tdata1.dmode) 288 tdata1_new.maskmax := 0.U 289 tdata1_new.hit := 0.U 290 tdata1_new.select := (TypeLookup(tselectPhy) === I_Trigger) && wdata_wire.select 291 when(wdata_wire.action <= 1.U){ 292 triggerAction := tdata1_new.action(0) 293 } .otherwise{ 294 tdata1_new.action := tdata1.action 295 } 296 tdata1_new.timing := false.B // hardwire this because we have singlestep 297 tdata1_new.zero1 := 0.U 298 tdata1_new.zero2 := 0.U 299 tdata1_new.chain := !tselectPhy(0) && wdata_wire.chain 300 when(wdata_wire.matchType =/= 0.U && wdata_wire.matchType =/= 2.U && wdata_wire.matchType =/= 3.U) { 301 tdata1_new.matchType := tdata1.matchType 302 } 303 tdata1_new.sizehi := Mux(wdata_wire.select && TypeLookup(tselectPhy) === I_Trigger, 0.U, 1.U) 304 tdata1_new.sizelo:= Mux(wdata_wire.select && TypeLookup(tselectPhy) === I_Trigger, 3.U, 1.U) 305 tdata1_new.execute := TypeLookup(tselectPhy) === I_Trigger 306 tdata1_new.store := TypeLookup(tselectPhy) === S_Trigger 307 tdata1_new.load := TypeLookup(tselectPhy) === L_Trigger 308 tdata1_new.asUInt 309 } 310 311 def WriteTselect(wdata: UInt) = { 312 Mux(wdata < 10.U, wdata(3, 0), tselectPhy) 313 } 314 315 val tcontrolWriteMask = ZeroExt(GenMask(3) | GenMask(7), XLEN) 316 317 318 def GenTdataDistribute(tdata1: TdataBundle, tdata2: UInt): MatchTriggerIO = { 319 val res = Wire(new MatchTriggerIO) 320 res.matchType := tdata1.matchType 321 res.select := tdata1.select 322 res.timing := tdata1.timing 323 res.action := triggerAction 324 res.chain := tdata1.chain 325 res.tdata2 := tdata2 326 res 327 } 328 329 csrio.customCtrl.frontend_trigger.t.bits.addr := MuxLookup(tselectPhy, 0.U, Seq( 330 0.U -> 0.U, 331 1.U -> 1.U, 332 6.U -> 2.U, 333 8.U -> 3.U 334 )) 335 csrio.customCtrl.mem_trigger.t.bits.addr := MuxLookup(tselectPhy, 0.U, Seq( 336 2.U -> 0.U, 337 3.U -> 1.U, 338 4.U -> 2.U, 339 5.U -> 3.U, 340 7.U -> 4.U, 341 9.U -> 5.U 342 )) 343 csrio.customCtrl.frontend_trigger.t.bits.tdata := GenTdataDistribute(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle), tdata2Phy(tselectPhy)) 344 csrio.customCtrl.mem_trigger.t.bits.tdata := GenTdataDistribute(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle), tdata2Phy(tselectPhy)) 345 346 // Machine-Level CSRs 347 // mtvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1 348 val mtvecMask = ~(0x2.U(XLEN.W)) 349 val mtvec = RegInit(UInt(XLEN.W), 0.U) 350 val mcounteren = RegInit(UInt(XLEN.W), 0.U) 351 val mcause = RegInit(UInt(XLEN.W), 0.U) 352 val mtval = RegInit(UInt(XLEN.W), 0.U) 353 val mepc = Reg(UInt(XLEN.W)) 354 // Page 36 in riscv-priv: The low bit of mepc (mepc[0]) is always zero. 355 val mepcMask = ~(0x1.U(XLEN.W)) 356 357 val mie = RegInit(0.U(XLEN.W)) 358 val mipWire = WireInit(0.U.asTypeOf(new Interrupt)) 359 val mipReg = RegInit(0.U(XLEN.W)) 360 val mipFixMask = ZeroExt(GenMask(9) | GenMask(5) | GenMask(1), XLEN) 361 val mip = (mipWire.asUInt | mipReg).asTypeOf(new Interrupt) 362 363 def getMisaMxl(mxl: Int): UInt = {mxl.U << (XLEN-2)}.asUInt 364 def getMisaExt(ext: Char): UInt = {1.U << (ext.toInt - 'a'.toInt)}.asUInt 365 var extList = List('a', 's', 'i', 'u') 366 if (HasMExtension) { extList = extList :+ 'm' } 367 if (HasCExtension) { extList = extList :+ 'c' } 368 if (HasFPU) { extList = extList ++ List('f', 'd') } 369 val misaInitVal = getMisaMxl(2) | extList.foldLeft(0.U)((sum, i) => sum | getMisaExt(i)) //"h8000000000141105".U 370 val misa = RegInit(UInt(XLEN.W), misaInitVal) 371 372 // MXL = 2 | 0 | EXT = b 00 0000 0100 0001 0001 0000 0101 373 // (XLEN-1, XLEN-2) | |(25, 0) ZY XWVU TSRQ PONM LKJI HGFE DCBA 374 375 val mvendorid = RegInit(UInt(XLEN.W), 0.U) // this is a non-commercial implementation 376 val marchid = RegInit(UInt(XLEN.W), 25.U) // architecture id for XiangShan is 25; see https://github.com/riscv/riscv-isa-manual/blob/master/marchid.md 377 val mimpid = RegInit(UInt(XLEN.W), 0.U) // provides a unique encoding of the version of the processor implementation 378 val mhartid = RegInit(UInt(XLEN.W), csrio.hartId) // the hardware thread running the code 379 val mconfigptr = RegInit(UInt(XLEN.W), 0.U) // the read-only pointer pointing to the platform config structure, 0 for not supported. 380 val mstatus = RegInit("ha00002000".U(XLEN.W)) 381 382 // mstatus Value Table 383 // | sd | 384 // | pad1 | 385 // | sxl | hardlinked to 10, use 00 to pass xv6 test 386 // | uxl | hardlinked to 10 387 // | pad0 | 388 // | tsr | 389 // | tw | 390 // | tvm | 391 // | mxr | 392 // | sum | 393 // | mprv | 394 // | xs | 00 | 395 // | fs | 01 | 396 // | mpp | 00 | 397 // | hpp | 00 | 398 // | spp | 0 | 399 // | pie | 0000 | pie.h is used as UBE 400 // | ie | 0000 | uie hardlinked to 0, as N ext is not implemented 401 402 val mstatusStruct = mstatus.asTypeOf(new MstatusStruct) 403 def mstatusUpdateSideEffect(mstatus: UInt): UInt = { 404 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 405 val mstatusNew = Cat(mstatusOld.xs === "b11".U || mstatusOld.fs === "b11".U, mstatus(XLEN-2, 0)) 406 mstatusNew 407 } 408 409 val mstatusWMask = (~ZeroExt(( 410 GenMask(XLEN - 2, 36) | // WPRI 411 GenMask(35, 32) | // SXL and UXL cannot be changed 412 GenMask(31, 23) | // WPRI 413 GenMask(16, 15) | // XS is read-only 414 GenMask(10, 9) | // WPRI 415 GenMask(6) | // WPRI 416 GenMask(2) // WPRI 417 ), 64)).asUInt 418 val mstatusMask = (~ZeroExt(( 419 GenMask(XLEN - 2, 36) | // WPRI 420 GenMask(31, 23) | // WPRI 421 GenMask(10, 9) | // WPRI 422 GenMask(6) | // WPRI 423 GenMask(2) // WPRI 424 ), 64)).asUInt 425 426 val medeleg = RegInit(UInt(XLEN.W), 0.U) 427 val mideleg = RegInit(UInt(XLEN.W), 0.U) 428 val mscratch = RegInit(UInt(XLEN.W), 0.U) 429 430 // PMP Mapping 431 val pmp = Wire(Vec(NumPMP, new PMPEntry())) // just used for method parameter 432 val pma = Wire(Vec(NumPMA, new PMPEntry())) // just used for method parameter 433 val pmpMapping = pmp_gen_mapping(pmp_init, NumPMP, PmpcfgBase, PmpaddrBase, pmp) 434 val pmaMapping = pmp_gen_mapping(pma_init, NumPMA, PmacfgBase, PmaaddrBase, pma) 435 436 // Superviser-Level CSRs 437 438 // val sstatus = RegInit(UInt(XLEN.W), "h00000000".U) 439 val sstatusWmask = "hc6122".U(XLEN.W) 440 // Sstatus Write Mask 441 // ------------------------------------------------------- 442 // 19 9 5 2 443 // 0 1100 0000 0001 0010 0010 444 // 0 c 0 1 2 2 445 // ------------------------------------------------------- 446 val sstatusRmask = sstatusWmask | "h8000000300018000".U 447 // Sstatus Read Mask = (SSTATUS_WMASK | (0xf << 13) | (1ull << 63) | (3ull << 32)) 448 // stvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1 449 val stvecMask = ~(0x2.U(XLEN.W)) 450 val stvec = RegInit(UInt(XLEN.W), 0.U) 451 // val sie = RegInit(0.U(XLEN.W)) 452 val sieMask = "h222".U & mideleg 453 val sipMask = "h222".U & mideleg 454 val sipWMask = "h2".U(XLEN.W) // ssip is writeable in smode 455 val satp = if(EnbaleTlbDebug) RegInit(UInt(XLEN.W), "h8000000000087fbe".U) else RegInit(0.U(XLEN.W)) 456 // val satp = RegInit(UInt(XLEN.W), "h8000000000087fbe".U) // only use for tlb naive debug 457 // val satpMask = "h80000fffffffffff".U(XLEN.W) // disable asid, mode can only be 8 / 0 458 // TODO: use config to control the length of asid 459 // val satpMask = "h8fffffffffffffff".U(XLEN.W) // enable asid, mode can only be 8 / 0 460 val satpMask = Cat("h8".U(Satp_Mode_len.W), satp_part_wmask(Satp_Asid_len, AsidLength), satp_part_wmask(Satp_Addr_len, PAddrBits-12)) 461 val sepc = RegInit(UInt(XLEN.W), 0.U) 462 // Page 60 in riscv-priv: The low bit of sepc (sepc[0]) is always zero. 463 val sepcMask = ~(0x1.U(XLEN.W)) 464 val scause = RegInit(UInt(XLEN.W), 0.U) 465 val stval = Reg(UInt(XLEN.W)) 466 val sscratch = RegInit(UInt(XLEN.W), 0.U) 467 val scounteren = RegInit(UInt(XLEN.W), 0.U) 468 469 // sbpctl 470 // Bits 0-7: {LOOP, RAS, SC, TAGE, BIM, BTB, uBTB} 471 val sbpctl = RegInit(UInt(XLEN.W), "h7f".U) 472 csrio.customCtrl.bp_ctrl.ubtb_enable := sbpctl(0) 473 csrio.customCtrl.bp_ctrl.btb_enable := sbpctl(1) 474 csrio.customCtrl.bp_ctrl.bim_enable := sbpctl(2) 475 csrio.customCtrl.bp_ctrl.tage_enable := sbpctl(3) 476 csrio.customCtrl.bp_ctrl.sc_enable := sbpctl(4) 477 csrio.customCtrl.bp_ctrl.ras_enable := sbpctl(5) 478 csrio.customCtrl.bp_ctrl.loop_enable := sbpctl(6) 479 480 // spfctl Bit 0: L1I Cache Prefetcher Enable 481 // spfctl Bit 1: L2Cache Prefetcher Enable 482 val spfctl = RegInit(UInt(XLEN.W), "b11".U) 483 csrio.customCtrl.l1I_pf_enable := spfctl(0) 484 csrio.customCtrl.l2_pf_enable := spfctl(1) 485 486 // sfetchctl Bit 0: L1I Cache Parity check enable 487 val sfetchctl = RegInit(UInt(XLEN.W), "b0".U) 488 csrio.customCtrl.icache_parity_enable := sfetchctl(0) 489 490 // sdsid: Differentiated Services ID 491 val sdsid = RegInit(UInt(XLEN.W), 0.U) 492 csrio.customCtrl.dsid := sdsid 493 494 // slvpredctl: load violation predict settings 495 // Default reset period: 2^16 496 // Why this number: reset more frequently while keeping the overhead low 497 // Overhead: extra two redirections in every 64K cycles => ~0.1% overhead 498 val slvpredctl = RegInit(UInt(XLEN.W), "h60".U) 499 csrio.customCtrl.lvpred_disable := slvpredctl(0) 500 csrio.customCtrl.no_spec_load := slvpredctl(1) 501 csrio.customCtrl.storeset_wait_store := slvpredctl(2) 502 csrio.customCtrl.storeset_no_fast_wakeup := slvpredctl(3) 503 csrio.customCtrl.lvpred_timeout := slvpredctl(8, 4) 504 505 // smblockctl: memory block configurations 506 // +------------------------------+---+----+----+-----+--------+ 507 // |XLEN-1 8| 7 | 6 | 5 | 4 |3 0| 508 // +------------------------------+---+----+----+-----+--------+ 509 // | Reserved | O | CE | SP | LVC | Th | 510 // +------------------------------+---+----+----+-----+--------+ 511 // Description: 512 // Bit 3-0 : Store buffer flush threshold (Th). 513 // Bit 4 : Enable load violation check after reset (LVC). 514 // Bit 5 : Enable soft-prefetch after reset (SP). 515 // Bit 6 : Enable cache error after reset (CE). 516 // Bit 7 : Enable uncache write outstanding (O). 517 // Others : Reserved. 518 519 val smblockctl_init_val = 520 ("hf".U & StoreBufferThreshold.U) | 521 (EnableLdVioCheckAfterReset.B.asUInt << 4) | 522 (EnableSoftPrefetchAfterReset.B.asUInt << 5) | 523 (EnableCacheErrorAfterReset.B.asUInt << 6) | 524 (EnableUncacheWriteOutstanding.B.asUInt << 7) 525 val smblockctl = RegInit(UInt(XLEN.W), smblockctl_init_val) 526 csrio.customCtrl.sbuffer_threshold := smblockctl(3, 0) 527 // bits 4: enable load load violation check 528 csrio.customCtrl.ldld_vio_check_enable := smblockctl(4) 529 csrio.customCtrl.soft_prefetch_enable := smblockctl(5) 530 csrio.customCtrl.cache_error_enable := smblockctl(6) 531 csrio.customCtrl.uncache_write_outstanding_enable := smblockctl(7) 532 533 println("CSR smblockctl init value:") 534 println(" Store buffer replace threshold: " + StoreBufferThreshold) 535 println(" Enable ld-ld vio check after reset: " + EnableLdVioCheckAfterReset) 536 println(" Enable soft prefetch after reset: " + EnableSoftPrefetchAfterReset) 537 println(" Enable cache error after reset: " + EnableCacheErrorAfterReset) 538 println(" Enable uncache write outstanding: " + EnableUncacheWriteOutstanding) 539 540 val srnctl = RegInit(UInt(XLEN.W), "h7".U) 541 csrio.customCtrl.fusion_enable := srnctl(0) 542 csrio.customCtrl.svinval_enable := srnctl(1) 543 csrio.customCtrl.wfi_enable := srnctl(2) 544 545 val tlbBundle = Wire(new TlbCsrBundle) 546 tlbBundle.satp.apply(satp) 547 548 csrio.tlb := tlbBundle 549 550 // User-Level CSRs 551 val uepc = Reg(UInt(XLEN.W)) 552 553 // fcsr 554 class FcsrStruct extends Bundle { 555 val reserved = UInt((XLEN-3-5).W) 556 val frm = UInt(3.W) 557 val fflags = UInt(5.W) 558 assert(this.getWidth == XLEN) 559 } 560 val fcsr = RegInit(0.U(XLEN.W)) 561 // set mstatus->sd and mstatus->fs when true 562 val csrw_dirty_fp_state = WireInit(false.B) 563 564 def frm_wfn(wdata: UInt): UInt = { 565 val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct)) 566 csrw_dirty_fp_state := true.B 567 fcsrOld.frm := wdata(2,0) 568 fcsrOld.asUInt 569 } 570 def frm_rfn(rdata: UInt): UInt = rdata(7,5) 571 572 def fflags_wfn(update: Boolean)(wdata: UInt): UInt = { 573 val fcsrOld = fcsr.asTypeOf(new FcsrStruct) 574 val fcsrNew = WireInit(fcsrOld) 575 csrw_dirty_fp_state := true.B 576 if (update) { 577 fcsrNew.fflags := wdata(4,0) | fcsrOld.fflags 578 } else { 579 fcsrNew.fflags := wdata(4,0) 580 } 581 fcsrNew.asUInt 582 } 583 def fflags_rfn(rdata:UInt): UInt = rdata(4,0) 584 585 def fcsr_wfn(wdata: UInt): UInt = { 586 val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct)) 587 csrw_dirty_fp_state := true.B 588 Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags) 589 } 590 591 val fcsrMapping = Map( 592 MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn(update = false), rfn = fflags_rfn), 593 MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn), 594 MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn) 595 ) 596 597 // Hart Priviledge Mode 598 val priviledgeMode = RegInit(UInt(2.W), ModeM) 599 600 //val perfEventscounten = List.fill(nrPerfCnts)(RegInit(false(Bool()))) 601 // Perf Counter 602 val nrPerfCnts = 29 // 3...31 603 val priviledgeModeOH = UIntToOH(priviledgeMode) 604 val perfEventscounten = RegInit(0.U.asTypeOf(Vec(nrPerfCnts, Bool()))) 605 val perfCnts = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W))) 606 val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++ 607 List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++ 608 List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++ 609 List.fill(5)(RegInit("hc0300c0300".U(XLEN.W))) 610 for (i <-0 until nrPerfCnts) { 611 perfEventscounten(i) := (Cat(perfEvents(i)(62),perfEvents(i)(61),(perfEvents(i)(61,60))) & priviledgeModeOH).orR 612 } 613 614 val hpmEvents = Wire(Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent)) 615 for (i <- 0 until numPCntHc * coreParams.L2NBanks) { 616 hpmEvents(i) := csrio.perf.perfEventsHc(i) 617 } 618 619 val csrevents = perfEvents.slice(24, 29) 620 val hpm_hc = HPerfMonitor(csrevents, hpmEvents) 621 val mcountinhibit = RegInit(0.U(XLEN.W)) 622 val mcycle = RegInit(0.U(XLEN.W)) 623 mcycle := mcycle + 1.U 624 val minstret = RegInit(0.U(XLEN.W)) 625 val perf_events = csrio.perf.perfEventsFrontend ++ 626 csrio.perf.perfEventsCtrl ++ 627 csrio.perf.perfEventsLsu ++ 628 hpm_hc.getPerf 629 minstret := minstret + RegNext(csrio.perf.retiredInstr) 630 for(i <- 0 until 29){ 631 perfCnts(i) := Mux(mcountinhibit(i+3) | !perfEventscounten(i), perfCnts(i), perfCnts(i) + perf_events(i).value) 632 } 633 634 // CSR reg map 635 val basicPrivMapping = Map( 636 637 //--- User Trap Setup --- 638 // MaskedRegMap(Ustatus, ustatus), 639 // MaskedRegMap(Uie, uie, 0.U, MaskedRegMap.Unwritable), 640 // MaskedRegMap(Utvec, utvec), 641 642 //--- User Trap Handling --- 643 // MaskedRegMap(Uscratch, uscratch), 644 // MaskedRegMap(Uepc, uepc), 645 // MaskedRegMap(Ucause, ucause), 646 // MaskedRegMap(Utval, utval), 647 // MaskedRegMap(Uip, uip), 648 649 //--- User Counter/Timers --- 650 // MaskedRegMap(Cycle, cycle), 651 // MaskedRegMap(Time, time), 652 // MaskedRegMap(Instret, instret), 653 654 //--- Supervisor Trap Setup --- 655 MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask), 656 // MaskedRegMap(Sedeleg, Sedeleg), 657 // MaskedRegMap(Sideleg, Sideleg), 658 MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask), 659 MaskedRegMap(Stvec, stvec, stvecMask, MaskedRegMap.NoSideEffect, stvecMask), 660 MaskedRegMap(Scounteren, scounteren), 661 662 //--- Supervisor Trap Handling --- 663 MaskedRegMap(Sscratch, sscratch), 664 MaskedRegMap(Sepc, sepc, sepcMask, MaskedRegMap.NoSideEffect, sepcMask), 665 MaskedRegMap(Scause, scause), 666 MaskedRegMap(Stval, stval), 667 MaskedRegMap(Sip, mip.asUInt, sipWMask, MaskedRegMap.Unwritable, sipMask), 668 669 //--- Supervisor Protection and Translation --- 670 MaskedRegMap(Satp, satp, satpMask, MaskedRegMap.NoSideEffect, satpMask), 671 672 //--- Supervisor Custom Read/Write Registers 673 MaskedRegMap(Sbpctl, sbpctl), 674 MaskedRegMap(Spfctl, spfctl), 675 MaskedRegMap(Sfetchctl, sfetchctl), 676 MaskedRegMap(Sdsid, sdsid), 677 MaskedRegMap(Slvpredctl, slvpredctl), 678 MaskedRegMap(Smblockctl, smblockctl), 679 MaskedRegMap(Srnctl, srnctl), 680 681 //--- Machine Information Registers --- 682 MaskedRegMap(Mvendorid, mvendorid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 683 MaskedRegMap(Marchid, marchid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 684 MaskedRegMap(Mimpid, mimpid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 685 MaskedRegMap(Mhartid, mhartid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 686 MaskedRegMap(Mconfigptr, mconfigptr, 0.U(XLEN.W), MaskedRegMap.Unwritable), 687 688 //--- Machine Trap Setup --- 689 MaskedRegMap(Mstatus, mstatus, mstatusWMask, mstatusUpdateSideEffect, mstatusMask), 690 MaskedRegMap(Misa, misa, 0.U, MaskedRegMap.Unwritable), // now whole misa is unchangeable 691 MaskedRegMap(Medeleg, medeleg, "hb3ff".U(XLEN.W)), 692 MaskedRegMap(Mideleg, mideleg, "h222".U(XLEN.W)), 693 MaskedRegMap(Mie, mie), 694 MaskedRegMap(Mtvec, mtvec, mtvecMask, MaskedRegMap.NoSideEffect, mtvecMask), 695 MaskedRegMap(Mcounteren, mcounteren), 696 697 //--- Machine Trap Handling --- 698 MaskedRegMap(Mscratch, mscratch), 699 MaskedRegMap(Mepc, mepc, mepcMask, MaskedRegMap.NoSideEffect, mepcMask), 700 MaskedRegMap(Mcause, mcause), 701 MaskedRegMap(Mtval, mtval), 702 MaskedRegMap(Mip, mip.asUInt, 0.U(XLEN.W), MaskedRegMap.Unwritable), 703 704 //--- Trigger --- 705 MaskedRegMap(Tselect, tselectPhy, WritableMask, WriteTselect), 706 MaskedRegMap(Tdata1, tdata1Phy(tselectPhy), WritableMask, WriteTdata1, WritableMask, ReadTdata1), 707 MaskedRegMap(Tdata2, tdata2Phy(tselectPhy)), 708 MaskedRegMap(Tinfo, tinfo, 0.U(XLEN.W), MaskedRegMap.Unwritable), 709 MaskedRegMap(Tcontrol, tControlPhy, tcontrolWriteMask), 710 711 //--- Debug Mode --- 712 MaskedRegMap(Dcsr, dcsr, dcsrMask, dcsrUpdateSideEffect), 713 MaskedRegMap(Dpc, dpc), 714 MaskedRegMap(Dscratch, dscratch), 715 MaskedRegMap(Dscratch1, dscratch1), 716 MaskedRegMap(Mcountinhibit, mcountinhibit), 717 MaskedRegMap(Mcycle, mcycle), 718 MaskedRegMap(Minstret, minstret), 719 ) 720 721 val perfCntMapping = (0 until 29).map(i => {Map( 722 MaskedRegMap(addr = Mhpmevent3 +i, 723 reg = perfEvents(i), 724 wmask = "hf87fff3fcff3fcff".U(XLEN.W)), 725 MaskedRegMap(addr = Mhpmcounter3 +i, 726 reg = perfCnts(i)) 727 )}).fold(Map())((a,b) => a ++ b) 728 // TODO: mechanism should be implemented later 729 // val MhpmcounterStart = Mhpmcounter3 730 // val MhpmeventStart = Mhpmevent3 731 // for (i <- 0 until nrPerfCnts) { 732 // perfCntMapping += MaskedRegMap(MhpmcounterStart + i, perfCnts(i)) 733 // perfCntMapping += MaskedRegMap(MhpmeventStart + i, perfEvents(i)) 734 // } 735 736 val cacheopRegs = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => { 737 name -> RegInit(0.U(attribute("width").toInt.W)) 738 }} 739 val cacheopMapping = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => { 740 MaskedRegMap( 741 Scachebase + attribute("offset").toInt, 742 cacheopRegs(name) 743 ) 744 }} 745 746 val mapping = basicPrivMapping ++ 747 perfCntMapping ++ 748 pmpMapping ++ 749 pmaMapping ++ 750 (if (HasFPU) fcsrMapping else Nil) ++ 751 (if (HasCustomCSRCacheOp) cacheopMapping else Nil) 752 753 val addr = src2(11, 0) 754 val csri = ZeroExt(src2(16, 12), XLEN) 755 val rdata = Wire(UInt(XLEN.W)) 756 val wdata = LookupTree(func, List( 757 CSROpType.wrt -> src1, 758 CSROpType.set -> (rdata | src1), 759 CSROpType.clr -> (rdata & (~src1).asUInt), 760 CSROpType.wrti -> csri, 761 CSROpType.seti -> (rdata | csri), 762 CSROpType.clri -> (rdata & (~csri).asUInt) 763 )) 764 765 val addrInPerfCnt = (addr >= Mcycle.U) && (addr <= Mhpmcounter31.U) || 766 (addr >= Mcountinhibit.U) && (addr <= Mhpmevent31.U) || 767 addr === Mip.U 768 csrio.isPerfCnt := addrInPerfCnt && valid && func =/= CSROpType.jmp 769 770 // satp wen check 771 val satpLegalMode = (wdata.asTypeOf(new SatpStruct).mode===0.U) || (wdata.asTypeOf(new SatpStruct).mode===8.U) 772 773 // csr access check, special case 774 val tvmNotPermit = (priviledgeMode === ModeS && mstatusStruct.tvm.asBool) 775 val accessPermitted = !(addr === Satp.U && tvmNotPermit) 776 csrio.disableSfence := tvmNotPermit 777 778 // general CSR wen check 779 val wen = valid && func =/= CSROpType.jmp && (addr=/=Satp.U || satpLegalMode) 780 val dcsrPermitted = dcsrPermissionCheck(addr, false.B, debugMode) 781 val triggerPermitted = triggerPermissionCheck(addr, true.B, debugMode) // todo dmode 782 val modePermitted = csrAccessPermissionCheck(addr, false.B, priviledgeMode) && dcsrPermitted && triggerPermitted 783 val perfcntPermitted = perfcntPermissionCheck(addr, priviledgeMode, mcounteren, scounteren) 784 val permitted = Mux(addrInPerfCnt, perfcntPermitted, modePermitted) && accessPermitted 785 786 MaskedRegMap.generate(mapping, addr, rdata, wen && permitted, wdata) 787 io.out.bits.data := rdata 788 io.out.bits.uop := io.in.bits.uop 789 io.out.bits.uop.cf := cfOut 790 io.out.bits.uop.ctrl.flushPipe := flushPipe 791 792 // send distribute csr a w signal 793 csrio.customCtrl.distribute_csr.w.valid := wen && permitted 794 csrio.customCtrl.distribute_csr.w.bits.data := wdata 795 csrio.customCtrl.distribute_csr.w.bits.addr := addr 796 797 // Fix Mip/Sip write 798 val fixMapping = Map( 799 MaskedRegMap(Mip, mipReg.asUInt, mipFixMask), 800 MaskedRegMap(Sip, mipReg.asUInt, sipWMask, MaskedRegMap.NoSideEffect, sipMask) 801 ) 802 val rdataFix = Wire(UInt(XLEN.W)) 803 val wdataFix = LookupTree(func, List( 804 CSROpType.wrt -> src1, 805 CSROpType.set -> (rdataFix | src1), 806 CSROpType.clr -> (rdataFix & (~src1).asUInt), 807 CSROpType.wrti -> csri, 808 CSROpType.seti -> (rdataFix | csri), 809 CSROpType.clri -> (rdataFix & (~csri).asUInt) 810 )) 811 MaskedRegMap.generate(fixMapping, addr, rdataFix, wen && permitted, wdataFix) 812 813 when (RegNext(csrio.fpu.fflags.valid)) { 814 fcsr := fflags_wfn(update = true)(RegNext(csrio.fpu.fflags.bits)) 815 } 816 // set fs and sd in mstatus 817 when (csrw_dirty_fp_state || RegNext(csrio.fpu.dirty_fs)) { 818 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 819 mstatusNew.fs := "b11".U 820 mstatusNew.sd := true.B 821 mstatus := mstatusNew.asUInt 822 } 823 csrio.fpu.frm := fcsr.asTypeOf(new FcsrStruct).frm 824 825 826 // Trigger Ctrl 827 csrio.customCtrl.trigger_enable := tdata1Phy.map{t => 828 def tdata1 = t.asTypeOf(new TdataBundle) 829 tdata1.m && priviledgeMode === ModeM || 830 tdata1.s && priviledgeMode === ModeS || tdata1.u && priviledgeMode === ModeU 831 } 832 csrio.customCtrl.frontend_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) === I_Trigger) 833 csrio.customCtrl.mem_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) =/= I_Trigger) 834 XSDebug(csrio.customCtrl.trigger_enable.asUInt.orR, p"Debug Mode: At least 1 trigger is enabled," + 835 p"trigger enable is ${Binary(csrio.customCtrl.trigger_enable.asUInt)}\n") 836 837 // CSR inst decode 838 val isEbreak = addr === privEbreak && func === CSROpType.jmp 839 val isEcall = addr === privEcall && func === CSROpType.jmp 840 val isMret = addr === privMret && func === CSROpType.jmp 841 val isSret = addr === privSret && func === CSROpType.jmp 842 val isUret = addr === privUret && func === CSROpType.jmp 843 val isDret = addr === privDret && func === CSROpType.jmp 844 val isWFI = func === CSROpType.wfi 845 846 XSDebug(wen, "csr write: pc %x addr %x rdata %x wdata %x func %x\n", cfIn.pc, addr, rdata, wdata, func) 847 XSDebug(wen, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", cfIn.pc, mstatus, mideleg , medeleg, priviledgeMode) 848 849 // Illegal priviledged operation list 850 val illegalMret = valid && isMret && priviledgeMode < ModeM 851 val illegalSret = valid && isSret && priviledgeMode < ModeS 852 val illegalSModeSret = valid && isSret && priviledgeMode === ModeS && mstatusStruct.tsr.asBool 853 // When TW=1, then if WFI is executed in any less-privileged mode, 854 // and it does not complete within an implementation-specific, bounded time limit, 855 // the WFI instruction causes an illegal instruction exception. 856 // The time limit may always be 0, in which case WFI always causes 857 // an illegal instruction exception in less-privileged modes when TW=1. 858 val illegalWFI = valid && isWFI && priviledgeMode < ModeM && mstatusStruct.tw === 1.U 859 860 // Illegal priviledged instruction check 861 val isIllegalAddr = valid && CSROpType.needAccess(func) && MaskedRegMap.isIllegalAddr(mapping, addr) 862 val isIllegalAccess = wen && !permitted 863 val isIllegalPrivOp = illegalMret || illegalSret || illegalSModeSret || illegalWFI 864 865 // expose several csr bits for tlb 866 tlbBundle.priv.mxr := mstatusStruct.mxr.asBool 867 tlbBundle.priv.sum := mstatusStruct.sum.asBool 868 tlbBundle.priv.imode := priviledgeMode 869 tlbBundle.priv.dmode := Mux(debugMode && dcsr.asTypeOf(new DcsrStruct).mprven, ModeM, Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpp, priviledgeMode)) 870 871 // Branch control 872 val retTarget = Wire(UInt(VAddrBits.W)) 873 val resetSatp = addr === Satp.U && wen // write to satp will cause the pipeline be flushed 874 flushPipe := resetSatp || (valid && func === CSROpType.jmp && !isEcall && !isEbreak) 875 876 retTarget := DontCare 877 // val illegalEret = TODO 878 879 when (valid && isDret) { 880 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 881 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 882 val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct)) 883 val debugModeNew = WireInit(debugMode) 884 when (dcsr.asTypeOf(new DcsrStruct).prv =/= ModeM) {mstatusNew.mprv := 0.U} //If the new privilege mode is less privileged than M-mode, MPRV in mstatus is cleared. 885 mstatus := mstatusNew.asUInt 886 priviledgeMode := dcsrNew.prv 887 retTarget := dpc(VAddrBits-1, 0) 888 debugModeNew := false.B 889 debugIntrEnable := true.B 890 debugMode := debugModeNew 891 XSDebug("Debug Mode: Dret executed, returning to %x.", retTarget) 892 } 893 894 when (valid && isMret && !illegalMret) { 895 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 896 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 897 mstatusNew.ie.m := mstatusOld.pie.m 898 priviledgeMode := mstatusOld.mpp 899 mstatusNew.pie.m := true.B 900 mstatusNew.mpp := ModeU 901 when (mstatusOld.mpp =/= ModeM) { mstatusNew.mprv := 0.U } 902 mstatus := mstatusNew.asUInt 903 // lr := false.B 904 retTarget := mepc(VAddrBits-1, 0) 905 } 906 907 when (valid && isSret && !illegalSret && !illegalSModeSret) { 908 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 909 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 910 mstatusNew.ie.s := mstatusOld.pie.s 911 priviledgeMode := Cat(0.U(1.W), mstatusOld.spp) 912 mstatusNew.pie.s := true.B 913 mstatusNew.spp := ModeU 914 mstatus := mstatusNew.asUInt 915 when (mstatusOld.spp =/= ModeM) { mstatusNew.mprv := 0.U } 916 // lr := false.B 917 retTarget := sepc(VAddrBits-1, 0) 918 } 919 920 when (valid && isUret) { 921 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 922 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 923 // mstatusNew.mpp.m := ModeU //TODO: add mode U 924 mstatusNew.ie.u := mstatusOld.pie.u 925 priviledgeMode := ModeU 926 mstatusNew.pie.u := true.B 927 mstatus := mstatusNew.asUInt 928 retTarget := uepc(VAddrBits-1, 0) 929 } 930 931 io.in.ready := true.B 932 io.out.valid := valid 933 934 val ebreakCauseException = (priviledgeMode === ModeM && dcsrData.ebreakm) || (priviledgeMode === ModeS && dcsrData.ebreaks) || (priviledgeMode === ModeU && dcsrData.ebreaku) 935 936 val csrExceptionVec = WireInit(cfIn.exceptionVec) 937 csrExceptionVec(breakPoint) := io.in.valid && isEbreak && (ebreakCauseException || debugMode) 938 csrExceptionVec(ecallM) := priviledgeMode === ModeM && io.in.valid && isEcall 939 csrExceptionVec(ecallS) := priviledgeMode === ModeS && io.in.valid && isEcall 940 csrExceptionVec(ecallU) := priviledgeMode === ModeU && io.in.valid && isEcall 941 // Trigger an illegal instr exception when: 942 // * unimplemented csr is being read/written 943 // * csr access is illegal 944 csrExceptionVec(illegalInstr) := isIllegalAddr || isIllegalAccess || isIllegalPrivOp 945 cfOut.exceptionVec := csrExceptionVec 946 947 XSDebug(io.in.valid && isEbreak, s"Debug Mode: an Ebreak is executed, ebreak cause exception ? ${ebreakCauseException}\n") 948 949 /** 950 * Exception and Intr 951 */ 952 val ideleg = (mideleg & mip.asUInt) 953 def priviledgedEnableDetect(x: Bool): Bool = Mux(x, ((priviledgeMode === ModeS) && mstatusStruct.ie.s) || (priviledgeMode < ModeS), 954 ((priviledgeMode === ModeM) && mstatusStruct.ie.m) || (priviledgeMode < ModeM)) 955 956 val debugIntr = csrio.externalInterrupt.debug & debugIntrEnable 957 XSDebug(debugIntr, "Debug Mode: debug interrupt is asserted and valid!") 958 // send interrupt information to ROB 959 val intrVecEnable = Wire(Vec(12, Bool())) 960 val disableInterrupt = debugMode || (dcsrData.step && !dcsrData.stepie) 961 intrVecEnable.zip(ideleg.asBools).map{case(x,y) => x := priviledgedEnableDetect(y) && !disableInterrupt} 962 val intrVec = Cat(debugIntr && !debugMode, (mie(11,0) & mip.asUInt & intrVecEnable.asUInt)) 963 val intrBitSet = intrVec.orR 964 csrio.interrupt := intrBitSet 965 // Page 45 in RISC-V Privileged Specification 966 // The WFI instruction can also be executed when interrupts are disabled. The operation of WFI 967 // must be unaffected by the global interrupt bits in mstatus (MIE and SIE) and the delegation 968 // register mideleg, but should honor the individual interrupt enables (e.g, MTIE). 969 csrio.wfi_event := debugIntr || (mie(11, 0) & mip.asUInt).orR 970 mipWire.t.m := csrio.externalInterrupt.mtip 971 mipWire.s.m := csrio.externalInterrupt.msip 972 mipWire.e.m := csrio.externalInterrupt.meip 973 mipWire.e.s := csrio.externalInterrupt.seip 974 975 // interrupts 976 val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(intrVec(i), i.U, sum)) 977 val raiseIntr = csrio.exception.valid && csrio.exception.bits.isInterrupt 978 val ivmEnable = tlbBundle.priv.imode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U 979 val iexceptionPC = Mux(ivmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc) 980 val dvmEnable = tlbBundle.priv.dmode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U 981 val dexceptionPC = Mux(dvmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc) 982 XSDebug(raiseIntr, "interrupt: pc=0x%x, %d\n", dexceptionPC, intrNO) 983 val raiseDebugIntr = intrNO === IRQ_DEBUG.U && raiseIntr 984 985 // exceptions 986 val raiseException = csrio.exception.valid && !csrio.exception.bits.isInterrupt 987 val hasInstrPageFault = csrio.exception.bits.uop.cf.exceptionVec(instrPageFault) && raiseException 988 val hasLoadPageFault = csrio.exception.bits.uop.cf.exceptionVec(loadPageFault) && raiseException 989 val hasStorePageFault = csrio.exception.bits.uop.cf.exceptionVec(storePageFault) && raiseException 990 val hasStoreAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(storeAddrMisaligned) && raiseException 991 val hasLoadAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(loadAddrMisaligned) && raiseException 992 val hasInstrAccessFault = csrio.exception.bits.uop.cf.exceptionVec(instrAccessFault) && raiseException 993 val hasLoadAccessFault = csrio.exception.bits.uop.cf.exceptionVec(loadAccessFault) && raiseException 994 val hasStoreAccessFault = csrio.exception.bits.uop.cf.exceptionVec(storeAccessFault) && raiseException 995 val hasbreakPoint = csrio.exception.bits.uop.cf.exceptionVec(breakPoint) && raiseException 996 val hasSingleStep = csrio.exception.bits.uop.ctrl.singleStep && raiseException 997 val hasTriggerHit = (csrio.exception.bits.uop.cf.trigger.hit) && raiseException 998 999 XSDebug(hasSingleStep, "Debug Mode: single step exception\n") 1000 XSDebug(hasTriggerHit, p"Debug Mode: trigger hit, is frontend? ${Binary(csrio.exception.bits.uop.cf.trigger.frontendHit.asUInt)} " + 1001 p"backend hit vec ${Binary(csrio.exception.bits.uop.cf.trigger.backendHit.asUInt)}\n") 1002 1003 val raiseExceptionVec = csrio.exception.bits.uop.cf.exceptionVec 1004 val regularExceptionNO = ExceptionNO.priorities.foldRight(0.U)((i: Int, sum: UInt) => Mux(raiseExceptionVec(i), i.U, sum)) 1005 val exceptionNO = Mux(hasSingleStep || hasTriggerHit, 3.U, regularExceptionNO) 1006 val causeNO = (raiseIntr << (XLEN-1)).asUInt | Mux(raiseIntr, intrNO, exceptionNO) 1007 1008 val raiseExceptionIntr = csrio.exception.valid 1009 1010 val raiseDebugExceptionIntr = !debugMode && (hasbreakPoint || raiseDebugIntr || hasSingleStep || hasTriggerHit && triggerAction) // TODO 1011 val ebreakEnterParkLoop = debugMode && raiseExceptionIntr 1012 1013 XSDebug(raiseExceptionIntr, "int/exc: pc %x int (%d):%x exc: (%d):%x\n", 1014 dexceptionPC, intrNO, intrVec, exceptionNO, raiseExceptionVec.asUInt 1015 ) 1016 XSDebug(raiseExceptionIntr, 1017 "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", 1018 dexceptionPC, 1019 mstatus, 1020 mideleg, 1021 medeleg, 1022 priviledgeMode 1023 ) 1024 1025 // mtval write logic 1026 // Due to timing reasons of memExceptionVAddr, we delay the write of mtval and stval 1027 val memExceptionAddr = SignExt(csrio.memExceptionVAddr, XLEN) 1028 val updateTval = VecInit(Seq( 1029 hasInstrPageFault, 1030 hasLoadPageFault, 1031 hasStorePageFault, 1032 hasInstrAccessFault, 1033 hasLoadAccessFault, 1034 hasStoreAccessFault, 1035 hasLoadAddrMisaligned, 1036 hasStoreAddrMisaligned 1037 )).asUInt.orR 1038 when (RegNext(RegNext(updateTval))) { 1039 val tval = Mux( 1040 RegNext(RegNext(hasInstrPageFault || hasInstrAccessFault)), 1041 RegNext(RegNext(Mux( 1042 csrio.exception.bits.uop.cf.crossPageIPFFix, 1043 SignExt(csrio.exception.bits.uop.cf.pc + 2.U, XLEN), 1044 iexceptionPC 1045 ))), 1046 memExceptionAddr 1047 ) 1048 when (RegNext(priviledgeMode === ModeM)) { 1049 mtval := tval 1050 }.otherwise { 1051 stval := tval 1052 } 1053 } 1054 1055 val debugTrapTarget = Mux(!isEbreak && debugMode, 0x38020808.U, 0x38020800.U) // 0x808 is when an exception occurs in debug mode prog buf exec 1056 val deleg = Mux(raiseIntr, mideleg , medeleg) 1057 // val delegS = ((deleg & (1 << (causeNO & 0xf))) != 0) && (priviledgeMode < ModeM); 1058 val delegS = deleg(causeNO(3,0)) && (priviledgeMode < ModeM) 1059 val clearTval = !updateTval || raiseIntr 1060 val isXRet = io.in.valid && func === CSROpType.jmp && !isEcall && !isEbreak 1061 1062 // ctrl block will use theses later for flush 1063 val isXRetFlag = RegInit(false.B) 1064 when (DelayN(io.redirectIn.valid, 5)) { 1065 isXRetFlag := false.B 1066 }.elsewhen (isXRet) { 1067 isXRetFlag := true.B 1068 } 1069 csrio.isXRet := isXRetFlag 1070 val retTargetReg = RegEnable(retTarget, isXRet) 1071 1072 val tvec = Mux(delegS, stvec, mtvec) 1073 val tvecBase = tvec(VAddrBits - 1, 2) 1074 // XRet sends redirect instead of Flush and isXRetFlag is true.B before redirect.valid. 1075 // ROB sends exception at T0 while CSR receives at T2. 1076 // We add a RegNext here and trapTarget is valid at T3. 1077 csrio.trapTarget := RegEnable(Mux(isXRetFlag, 1078 retTargetReg, 1079 Mux(raiseDebugExceptionIntr || ebreakEnterParkLoop, debugTrapTarget, 1080 // When MODE=Vectored, all synchronous exceptions into M/S mode 1081 // cause the pc to be set to the address in the BASE field, whereas 1082 // interrupts cause the pc to be set to the address in the BASE field 1083 // plus four times the interrupt cause number. 1084 Cat(tvecBase + Mux(tvec(0) && raiseIntr, causeNO(3, 0), 0.U), 0.U(2.W)) 1085 )), isXRetFlag || csrio.exception.valid) 1086 1087 when (raiseExceptionIntr) { 1088 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1089 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1090 val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct)) 1091 val debugModeNew = WireInit(debugMode) 1092 1093 when (raiseDebugExceptionIntr) { 1094 when (raiseDebugIntr) { 1095 debugModeNew := true.B 1096 mstatusNew.mprv := false.B 1097 dpc := iexceptionPC 1098 dcsrNew.cause := 3.U 1099 dcsrNew.prv := priviledgeMode 1100 priviledgeMode := ModeM 1101 XSDebug(raiseDebugIntr, "Debug Mode: Trap to %x at pc %x\n", debugTrapTarget, dpc) 1102 }.elsewhen ((hasbreakPoint || hasSingleStep) && !debugMode) { 1103 // ebreak or ss in running hart 1104 debugModeNew := true.B 1105 dpc := iexceptionPC 1106 dcsrNew.cause := Mux(hasTriggerHit, 2.U, Mux(hasbreakPoint, 1.U, 4.U)) 1107 dcsrNew.prv := priviledgeMode // TODO 1108 priviledgeMode := ModeM 1109 mstatusNew.mprv := false.B 1110 } 1111 dcsr := dcsrNew.asUInt 1112 debugIntrEnable := false.B 1113 }.elsewhen (debugMode) { 1114 //do nothing 1115 }.elsewhen (delegS) { 1116 scause := causeNO 1117 sepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC) 1118 mstatusNew.spp := priviledgeMode 1119 mstatusNew.pie.s := mstatusOld.ie.s 1120 mstatusNew.ie.s := false.B 1121 priviledgeMode := ModeS 1122 when (clearTval) { stval := 0.U } 1123 }.otherwise { 1124 mcause := causeNO 1125 mepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC) 1126 mstatusNew.mpp := priviledgeMode 1127 mstatusNew.pie.m := mstatusOld.ie.m 1128 mstatusNew.ie.m := false.B 1129 priviledgeMode := ModeM 1130 when (clearTval) { mtval := 0.U } 1131 } 1132 mstatus := mstatusNew.asUInt 1133 debugMode := debugModeNew 1134 } 1135 1136 XSDebug(raiseExceptionIntr && delegS, "sepc is written!!! pc:%x\n", cfIn.pc) 1137 1138 // Distributed CSR update req 1139 // 1140 // For now we use it to implement customized cache op 1141 // It can be delayed if necessary 1142 1143 val delayedUpdate0 = DelayN(csrio.distributedUpdate(0), 2) 1144 val delayedUpdate1 = DelayN(csrio.distributedUpdate(1), 2) 1145 val distributedUpdateValid = delayedUpdate0.w.valid || delayedUpdate1.w.valid 1146 val distributedUpdateAddr = Mux(delayedUpdate0.w.valid, 1147 delayedUpdate0.w.bits.addr, 1148 delayedUpdate1.w.bits.addr 1149 ) 1150 val distributedUpdateData = Mux(delayedUpdate0.w.valid, 1151 delayedUpdate0.w.bits.data, 1152 delayedUpdate1.w.bits.data 1153 ) 1154 1155 assert(!(delayedUpdate0.w.valid && delayedUpdate1.w.valid)) 1156 1157 when(distributedUpdateValid){ 1158 // cacheopRegs can be distributed updated 1159 CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => { 1160 when((Scachebase + attribute("offset").toInt).U === distributedUpdateAddr){ 1161 cacheopRegs(name) := distributedUpdateData 1162 } 1163 }} 1164 } 1165 1166 // Cache error debug support 1167 if(HasCustomCSRCacheOp){ 1168 val cache_error_decoder = Module(new CSRCacheErrorDecoder) 1169 cache_error_decoder.io.encoded_cache_error := cacheopRegs("CACHE_ERROR") 1170 } 1171 1172 // Implicit add reset values for mepc[0] and sepc[0] 1173 // TODO: rewrite mepc and sepc using a struct-like style with the LSB always being 0 1174 when (reset.asBool) { 1175 mepc := Cat(mepc(XLEN - 1, 1), 0.U(1.W)) 1176 sepc := Cat(sepc(XLEN - 1, 1), 0.U(1.W)) 1177 } 1178 1179 def readWithScala(addr: Int): UInt = mapping(addr)._1 1180 1181 val difftestIntrNO = Mux(raiseIntr, causeNO, 0.U) 1182 1183 // Always instantiate basic difftest modules. 1184 if (env.AlwaysBasicDiff || env.EnableDifftest) { 1185 val difftest = Module(new DifftestArchEvent) 1186 difftest.io.clock := clock 1187 difftest.io.coreid := csrio.hartId 1188 difftest.io.intrNO := RegNext(RegNext(RegNext(difftestIntrNO))) 1189 difftest.io.cause := RegNext(RegNext(RegNext(Mux(csrio.exception.valid, causeNO, 0.U)))) 1190 difftest.io.exceptionPC := RegNext(RegNext(RegNext(dexceptionPC))) 1191 if (env.EnableDifftest) { 1192 difftest.io.exceptionInst := RegNext(RegNext(RegNext(csrio.exception.bits.uop.cf.instr))) 1193 } 1194 } 1195 1196 // Always instantiate basic difftest modules. 1197 if (env.AlwaysBasicDiff || env.EnableDifftest) { 1198 val difftest = Module(new DifftestCSRState) 1199 difftest.io.clock := clock 1200 difftest.io.coreid := csrio.hartId 1201 difftest.io.priviledgeMode := priviledgeMode 1202 difftest.io.mstatus := mstatus 1203 difftest.io.sstatus := mstatus & sstatusRmask 1204 difftest.io.mepc := mepc 1205 difftest.io.sepc := sepc 1206 difftest.io.mtval:= mtval 1207 difftest.io.stval:= stval 1208 difftest.io.mtvec := mtvec 1209 difftest.io.stvec := stvec 1210 difftest.io.mcause := mcause 1211 difftest.io.scause := scause 1212 difftest.io.satp := satp 1213 difftest.io.mip := mipReg 1214 difftest.io.mie := mie 1215 difftest.io.mscratch := mscratch 1216 difftest.io.sscratch := sscratch 1217 difftest.io.mideleg := mideleg 1218 difftest.io.medeleg := medeleg 1219 } 1220 1221 if(env.AlwaysBasicDiff || env.EnableDifftest) { 1222 val difftest = Module(new DifftestDebugMode) 1223 difftest.io.clock := clock 1224 difftest.io.coreid := csrio.hartId 1225 difftest.io.debugMode := debugMode 1226 difftest.io.dcsr := dcsr 1227 difftest.io.dpc := dpc 1228 difftest.io.dscratch0 := dscratch 1229 difftest.io.dscratch1 := dscratch1 1230 } 1231} 1232 1233class PFEvent(implicit p: Parameters) extends XSModule with HasCSRConst { 1234 val io = IO(new Bundle { 1235 val distribute_csr = Flipped(new DistributedCSRIO()) 1236 val hpmevent = Output(Vec(29, UInt(XLEN.W))) 1237 }) 1238 1239 val w = io.distribute_csr.w 1240 1241 val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++ 1242 List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++ 1243 List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++ 1244 List.fill(5)(RegInit("hc0300c0300".U(XLEN.W))) 1245 1246 val perfEventMapping = (0 until 29).map(i => {Map( 1247 MaskedRegMap(addr = Mhpmevent3 +i, 1248 reg = perfEvents(i), 1249 wmask = "hf87fff3fcff3fcff".U(XLEN.W)) 1250 )}).fold(Map())((a,b) => a ++ b) 1251 1252 val rdata = Wire(UInt(XLEN.W)) 1253 MaskedRegMap.generate(perfEventMapping, w.bits.addr, rdata, w.valid, w.bits.data) 1254 for(i <- 0 until 29){ 1255 io.hpmevent(i) := perfEvents(i) 1256 } 1257} 1258