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 org.chipsalliance.cde.config.Parameters 20import chisel3._ 21import chisel3.util._ 22import difftest._ 23import freechips.rocketchip.util._ 24import utility.MaskedRegMap.WritableMask 25import utils._ 26import utility._ 27import xiangshan.ExceptionNO._ 28import xiangshan._ 29import xiangshan.backend.fu.util._ 30import xiangshan.cache._ 31import xiangshan.backend.Bundles.ExceptionInfo 32import xiangshan.backend.fu.NewCSR.CSRNamedConstant.ContextStatus 33import utils.MathUtils.{BigIntGenMask, BigIntNot} 34 35class FpuCsrIO extends Bundle { 36 val fflags = Output(Valid(UInt(5.W))) 37 val isIllegal = Output(Bool()) 38 val dirty_fs = Output(Bool()) 39 val frm = Input(UInt(3.W)) 40} 41 42class VpuCsrIO(implicit p: Parameters) extends XSBundle { 43 val vstart = Input(UInt(XLEN.W)) 44 val vxrm = Input(UInt(2.W)) 45 46 val vl = Output(UInt(XLEN.W)) 47 48 val set_vstart = Output(Valid(UInt(XLEN.W))) 49 val set_vtype = Output(Valid(UInt(XLEN.W))) 50 val set_vxsat = Output(Valid(UInt(1.W))) 51 52 val dirty_vs = Output(Bool()) 53} 54 55 56class PerfCounterIO(implicit p: Parameters) extends XSBundle { 57 val perfEventsFrontend = Vec(numCSRPCntFrontend, new PerfEvent) 58 val perfEventsBackend = Vec(numCSRPCntCtrl, new PerfEvent) 59 val perfEventsLsu = Vec(numCSRPCntLsu, new PerfEvent) 60 val perfEventsHc = Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent) 61 val retiredInstr = UInt(7.W) 62 val frontendInfo = new Bundle { 63 val ibufFull = Bool() 64 val bpuInfo = new Bundle { 65 val bpRight = UInt(XLEN.W) 66 val bpWrong = UInt(XLEN.W) 67 } 68 } 69 val ctrlInfo = new Bundle { 70 val robFull = Bool() 71 val intdqFull = Bool() 72 val fpdqFull = Bool() 73 val lsdqFull = Bool() 74 } 75 val memInfo = new Bundle { 76 val sqFull = Bool() 77 val lqFull = Bool() 78 val dcacheMSHRFull = Bool() 79 } 80} 81 82class CSRFileIO(implicit p: Parameters) extends XSBundle { 83 val hartId = Input(UInt(hartIdLen.W)) 84 // output (for func === CSROpType.jmp) 85 val perf = Input(new PerfCounterIO) 86 val isPerfCnt = Output(Bool()) 87 // to FPU 88 val fpu = Flipped(new FpuCsrIO) 89 // to VPU 90 val vpu = Flipped(new VpuCsrIO) 91 // from rob 92 val exception = Flipped(ValidIO(new ExceptionInfo)) 93 // to ROB 94 val isXRet = Output(Bool()) 95 val trapTarget = Output(UInt(VAddrBits.W)) 96 val interrupt = Output(Bool()) 97 val wfi_event = Output(Bool()) 98 // from LSQ 99 val memExceptionVAddr = Input(UInt(VAddrBits.W)) 100 val memExceptionGPAddr = Input(UInt(GPAddrBits.W)) 101 // from outside cpu,externalInterrupt 102 val externalInterrupt = Input(new ExternalInterruptIO) 103 // TLB 104 val tlb = Output(new TlbCsrBundle) 105 // Debug Mode 106 // val singleStep = Output(Bool()) 107 val debugMode = Output(Bool()) 108 // Custom microarchiture ctrl signal 109 val customCtrl = Output(new CustomCSRCtrlIO) 110} 111 112class VtypeStruct(implicit p: Parameters) extends XSBundle { 113 val vill = UInt(1.W) 114 val reserved = UInt((XLEN - 9).W) 115 val vma = UInt(1.W) 116 val vta = UInt(1.W) 117 val vsew = UInt(3.W) 118 val vlmul = UInt(3.W) 119} 120 121class CSR(cfg: FuConfig)(implicit p: Parameters) extends FuncUnit(cfg) 122 with HasCSRConst 123 with PMPMethod 124 with PMAMethod 125 with HasXSParameter 126 with SdtrigExt 127 with DebugCSR 128{ 129 val csrio = io.csrio.get 130 131 val flushPipe = Wire(Bool()) 132 133 val (valid, src1, src2, func) = ( 134 io.in.valid, 135 io.in.bits.data.src(0), 136 io.in.bits.data.imm, 137 io.in.bits.ctrl.fuOpType 138 ) 139 140 // CSR define 141 val virtMode = RegInit(false.B) 142 csrio.customCtrl.virtMode := virtMode 143 144 class Priv extends Bundle { 145 val m = Output(Bool()) 146 val h = Output(Bool()) // unused 147 val s = Output(Bool()) 148 val u = Output(Bool()) 149 } 150 151 class MstatusStruct extends Bundle { 152 val sd = Output(UInt(1.W)) 153 154 val pad1 = if (XLEN == 64 && HasHExtension) Output(UInt(23.W)) else if (XLEN == 64) Output(UInt(25.W)) else null 155 val mpv = if (XLEN == 64 && HasHExtension) Output(UInt(1.W)) else null 156 val gva = if (XLEN == 64 && HasHExtension) Output(UInt(1.W)) else null 157 val mbe = if (XLEN == 64) Output(UInt(1.W)) else null 158 val sbe = if (XLEN == 64) Output(UInt(1.W)) else null 159 val sxl = if (XLEN == 64) Output(UInt(2.W)) else null 160 val uxl = if (XLEN == 64) Output(UInt(2.W)) else null 161 val pad0 = if (XLEN == 64) Output(UInt(9.W)) else Output(UInt(8.W)) 162 163 val tsr = Output(UInt(1.W)) 164 val tw = Output(UInt(1.W)) 165 val tvm = Output(UInt(1.W)) 166 val mxr = Output(UInt(1.W)) 167 val sum = Output(UInt(1.W)) 168 val mprv = Output(UInt(1.W)) 169 val xs = Output(UInt(2.W)) 170 val fs = Output(UInt(2.W)) 171 val mpp = Output(UInt(2.W)) 172 val vs = Output(UInt(2.W)) 173 val spp = Output(UInt(1.W)) 174 val pie = new Priv 175 val ie = new Priv 176 assert(this.getWidth == XLEN) 177 178 def ube = pie.h // a little ugly 179 def ube_(r: UInt): Unit = { 180 pie.h := r(0) 181 } 182 } 183 184 class HstatusStruct extends Bundle { 185 val pad4 = if (HSXLEN == 64) Output(UInt(30.W)) else null 186 val vsxl = if (HSXLEN == 64) Output(UInt(2.W)) else null 187 val pad3 = Output(UInt(9.W)) 188 val vtsr = Output(UInt(1.W)) 189 val vtw = Output(UInt(1.W)) 190 val vtvm = Output(UInt(1.W)) 191 val pad2 = Output(UInt(2.W)) 192 val vgein = Output(UInt(6.W)) 193 val pad1 = Output(UInt(2.W)) 194 val hu = Output(UInt(1.W)) 195 val spvp = Output(UInt(1.W)) 196 val spv = Output(UInt(1.W)) 197 val gva = Output(UInt(1.W)) 198 val vsbe = Output(UInt(1.W)) 199 val pad0 = Output(UInt(5.W)) 200 assert(this.getWidth == XLEN) 201 } 202 203 class Interrupt extends Bundle { 204// val d = Output(Bool()) // Debug 205 val e = new Priv 206 val t = new Priv 207 val s = new Priv 208 } 209 210 // Debug CSRs 211 val dcsr = RegInit(UInt(32.W), DcsrStruct.init) 212 val dpc = Reg(UInt(64.W)) 213 val dscratch0 = Reg(UInt(64.W)) 214 val dscratch1 = Reg(UInt(64.W)) 215 val debugMode = RegInit(false.B) 216 val debugIntrEnable = RegInit(true.B) // debug interrupt will be handle only when debugIntrEnable 217 csrio.debugMode := debugMode 218 219 val dpcPrev = RegNext(dpc) 220 XSDebug(dpcPrev =/= dpc, "Debug Mode: dpc is altered! Current is %x, previous is %x\n", dpc, dpcPrev) 221 222 val dcsrData = Wire(new DcsrStruct) 223 dcsrData := dcsr.asTypeOf(new DcsrStruct) 224 val dcsrMask = ZeroExt(GenMask(15) | GenMask(13, 11) | GenMask(4) | GenMask(2, 0), XLEN)// Dcsr write mask 225 def dcsrUpdateSideEffect(dcsr: UInt): UInt = { 226 val dcsrOld = WireInit(dcsr.asTypeOf(new DcsrStruct)) 227 val dcsrNew = dcsr | (dcsrOld.prv(0) | dcsrOld.prv(1)).asUInt // turn 10 priv into 11 228 dcsrNew 229 } 230 // csrio.singleStep := dcsrData.step 231 csrio.customCtrl.singlestep := dcsrData.step && !debugMode 232 233 // Trigger CSRs 234 private val tselectPhy = RegInit(0.U(log2Up(TriggerNum).W)) 235 236 private val tdata1RegVec = RegInit(VecInit(Seq.fill(TriggerNum)(Tdata1Bundle.default))) 237 private val tdata2RegVec = RegInit(VecInit(Seq.fill(TriggerNum)(0.U(64.W)))) 238 private val tdata1WireVec = tdata1RegVec.map(_.asTypeOf(new Tdata1Bundle)) 239 private val tdata2WireVec = tdata2RegVec 240 private val tdata1Selected = tdata1RegVec(tselectPhy).asTypeOf(new Tdata1Bundle) 241 private val tdata2Selected = tdata2RegVec(tselectPhy) 242 private val newTriggerChainVec = UIntToOH(tselectPhy, TriggerNum).asBools | tdata1WireVec.map(_.data.asTypeOf(new MControlData).chain) 243 private val newTriggerChainIsLegal = TriggerCheckChainLegal(newTriggerChainVec, TriggerChainMaxLength) 244 val tinfo = RegInit((BigInt(1) << TrigTypeEnum.MCONTROL.litValue.toInt).U(XLEN.W)) // This value should be 4.U 245 246 247 def WriteTselect(wdata: UInt) = { 248 Mux(wdata < TriggerNum.U, wdata(log2Up(TriggerNum) - 1, 0), tselectPhy) 249 } 250 251 def GenTdataDistribute(tdata1: Tdata1Bundle, tdata2: UInt): MatchTriggerIO = { 252 val res = Wire(new MatchTriggerIO) 253 val mcontrol: MControlData = WireInit(tdata1.data.asTypeOf(new MControlData)) 254 res.matchType := mcontrol.match_.asUInt 255 res.select := mcontrol.select 256 res.timing := mcontrol.timing 257 res.action := mcontrol.action.asUInt 258 res.chain := mcontrol.chain 259 res.execute := mcontrol.execute 260 res.load := mcontrol.load 261 res.store := mcontrol.store 262 res.tdata2 := tdata2 263 res 264 } 265 266 csrio.customCtrl.frontend_trigger.tUpdate.bits.addr := tselectPhy 267 csrio.customCtrl.mem_trigger.tUpdate.bits.addr := tselectPhy 268 csrio.customCtrl.frontend_trigger.tUpdate.bits.tdata := GenTdataDistribute(tdata1Selected, tdata2Selected) 269 csrio.customCtrl.mem_trigger.tUpdate.bits.tdata := GenTdataDistribute(tdata1Selected, tdata2Selected) 270 271 // Machine-Level CSRs 272 // mtvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1 273 val mtvecMask = ~(0x2.U(XLEN.W)) 274 val mtvec = RegInit(UInt(XLEN.W), 0.U) 275 val mcounteren = RegInit(UInt(XLEN.W), 0.U) 276 // Currently, XiangShan don't support Unprivileged Counter/Timers CSRs ("Zicntr" and "Zihpm") 277 val mcounterenMask = 0.U(XLEN.W) 278 val mcause = RegInit(UInt(XLEN.W), 0.U) 279 val mtval = RegInit(UInt(XLEN.W), 0.U) 280 val mtval2 = RegInit(UInt(XLEN.W), 0.U) 281 val mtinst = RegInit(UInt(XLEN.W), 0.U) 282 val mepc = RegInit(UInt(XLEN.W), 0.U) 283 // Page 36 in riscv-priv: The low bit of mepc (mepc[0]) is always zero. 284 val mepcMask = ~(0x1.U(XLEN.W)) 285 286 val mie = RegInit(0.U(XLEN.W)) 287 val mipWire = WireInit(0.U.asTypeOf(new Interrupt)) 288 val mipReg = RegInit(0.U(XLEN.W)) 289 val mipMask = ZeroExt(Array( 290 1, // SSIP 291 2, // VSSIP 292 3, // MSIP 293 5, // STIP 294 6, // VSTIP 295 7, // MTIP 296 9, // SEIP 297 10, // VSEIP 298 11, // MEIP 299 12, // SGEIP 300 ).map(GenMask(_)).reduce(_ | _), XLEN) 301 val mip = (mipWire.asUInt | mipReg).asTypeOf(new Interrupt) 302 303 val mip_mie_WMask_H = if(HasHExtension){((1 << 2) | (1 << 6) | (1 << 10) | (1 << 12)).U(XLEN.W)}else{0.U(XLEN.W)} 304 val vssip_Mask = (1 << 2).U(XLEN.W) 305 306 val mipWMask = vssip_Mask | ((1 << 9) | (1 << 5) | (1 << 1)).U(XLEN.W) 307 val mieWMask = mip_mie_WMask_H | "haaa".U(XLEN.W) 308 309 def getMisaMxl(mxl: BigInt): BigInt = mxl << (XLEN - 2) 310 def getMisaExt(ext: Char): Long = 1 << (ext.toInt - 'a'.toInt) 311 var extList = List('a', 's', 'i', 'u') 312 if (HasMExtension) { extList = extList :+ 'm' } 313 if (HasCExtension) { extList = extList :+ 'c' } 314 if (HasHExtension) { extList = extList :+ 'h' } 315 if (HasFPU) { extList = extList ++ List('f', 'd') } 316 if (HasVPU) { extList = extList :+ 'v' } 317 val misaInitVal = getMisaMxl(2) | extList.foldLeft(0L)((sum, i) => sum | getMisaExt(i)) //"h8000000000141185".U 318 val misa = RegInit(UInt(XLEN.W), misaInitVal.U) 319 println(s"[CSR] supported isa ext: $extList") 320 321 // MXL = 2 | 0 | EXT = b 00 0000 0100 0001 0001 0000 0101 322 // (XLEN-1, XLEN-2) | |(25, 0) ZY XWVU TSRQ PONM LKJI HGFE DCBA 323 324 // Machine Configuration 325 val menvcfg = RegInit(UInt(XLEN.W), 0.U) 326 327 val mvendorid = RegInit(UInt(XLEN.W), 0.U) // this is a non-commercial implementation 328 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 329 val mimpid = RegInit(UInt(XLEN.W), 0.U) // provides a unique encoding of the version of the processor implementation 330 val mhartid = Reg(UInt(XLEN.W)) // the hardware thread running the code 331 when (RegNext(RegNext(reset.asBool) && !reset.asBool)) { 332 mhartid := csrio.hartId 333 } 334 val mconfigptr = RegInit(UInt(XLEN.W), 0.U) // the read-only pointer pointing to the platform config structure, 0 for not supported. 335 val mstatus = RegInit("ha00002200".U(XLEN.W)) 336 337 // mstatus Value Table 338 // | sd | Read Only 339 // | pad1 | WPRI 340 // | sxl | hardlinked to 10, use 00 to pass xv6 test 341 // | uxl | hardlinked to 10 342 // | pad0 | 343 // | tsr | 344 // | tw | 345 // | tvm | 346 // | mxr | 347 // | sum | 348 // | mprv | 349 // | xs | 00 | 350 // | fs | 01 | 351 // | mpp | 00 | 352 // | vs | 01 | 353 // | spp | 0 | 354 // | pie | 0000 | pie.h is used as UBE 355 // | ie | 0000 | uie hardlinked to 0, as N ext is not implemented 356 357 val mstatusStruct = mstatus.asTypeOf(new MstatusStruct) 358 def mstatusUpdateSideEffect(mstatus: UInt): UInt = { 359 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 360 // Cat(sd, other) 361 val mstatusNew = Cat( 362 mstatusOld.xs === ContextStatus.dirty || mstatusOld.fs === ContextStatus.dirty || mstatusOld.vs === ContextStatus.dirty, 363 mstatus(XLEN-2, 0) 364 ) 365 mstatusNew 366 } 367 def vsstatusUpdateSideEffect(vsstatus: UInt): UInt = { 368 val vsstatusOld = WireInit(vsstatus.asTypeOf(new MstatusStruct)) 369 val vsstatusNew = Cat(vsstatusOld.xs === "b11".U || vsstatusOld.fs === "b11".U, vsstatus(XLEN-2, 0)) 370 vsstatusNew 371 } 372 val mstatusWMask = (~ZeroExt(( 373 GenMask(63) | // SD is read-only 374 (if(HasHExtension) 375 GenMask(62, 40) // WPRI 376 else 377 GenMask(62, 38) )| // WPRI 378 GenMask(35, 32) | // SXL and UXL cannot be changed 379 GenMask(31, 23) | // WPRI 380 GenMask(16, 15) | // XS is read-only 381 GenMask(6) | // UBE, always little-endian (0) 382 GenMask(4) | // WPRI 383 GenMask(2) | // WPRI 384 GenMask(0) // WPRI 385 ), 64)).asUInt 386 387 val medeleg = RegInit(UInt(XLEN.W), 0.U) 388 val midelegInit = if(HasHExtension){((1 << 12) | (1 << 10) | (1 << 6) | (1 << 2)).U}else{0.U} 389 val medelegWMask = if(HasHExtension) { 390 "hf0b7ff".U(XLEN.W) 391 }else { 392 "hb3ff".U(XLEN.W) 393 } 394 395 396 val mideleg = RegInit(UInt(XLEN.W), midelegInit) 397 val mscratch = RegInit(UInt(XLEN.W), 0.U) 398 399 val midelegWMask = "h222".U(XLEN.W) 400 // PMP Mapping 401 val pmp = Wire(Vec(NumPMP, new PMPEntry())) // just used for method parameter 402 val pma = Wire(Vec(NumPMA, new PMPEntry())) // just used for method parameter 403 val pmpMapping = pmp_gen_mapping(pmp_init, NumPMP, PmpcfgBase, PmpaddrBase, pmp) 404 val pmaMapping = pmp_gen_mapping(pma_init, NumPMA, PmacfgBase, PmaaddrBase, pma) 405 // !WARNNING: pmp and pma CSRs are not checked in difftest. 406 407 // Supervisor-Level CSRs 408 409 val sstatusWNmask: BigInt = ( 410 BigIntGenMask(63) | // SD is read-only 411 BigIntGenMask(62, 34) | // WPRI 412 BigIntGenMask(33, 32) | // UXL is hard-wired to 64(b10) 413 BigIntGenMask(31, 20) | // WPRI 414 BigIntGenMask(17) | // WPRI 415 BigIntGenMask(16, 15) | // XS is read-only to zero 416 BigIntGenMask(12, 11) | // WPRI 417 BigIntGenMask(7) | // WPRI 418 BigIntGenMask(6) | // UBE is always little-endian (0) 419 BigIntGenMask(4, 2) | // WPRI 420 BigIntGenMask(0) // WPRI 421 ) 422 423 val sstatusWmask = BigIntNot(sstatusWNmask).U(XLEN.W) 424 val sstatusRmask = ( 425 BigIntGenMask(63) | // SD 426 BigIntGenMask(33, 32) | // UXL 427 BigIntGenMask(19) | // MXR 428 BigIntGenMask(18) | // SUM 429 BigIntGenMask(16, 15) | // XS 430 BigIntGenMask(14, 13) | // FS 431 BigIntGenMask(10, 9 ) | // VS 432 BigIntGenMask(8) | // SPP 433 BigIntGenMask(6) | // UBE: hard wired to 0 434 BigIntGenMask(5) | // SPIE 435 BigIntGenMask(1) 436 ).U(XLEN.W) 437 438 println(s"sstatusWNmask: 0x${sstatusWNmask.toString(16)}") 439 println(s"sstatusWmask: 0x${sstatusWmask.litValue.toString(16)}") 440 println(s"sstatusRmask: 0x${sstatusRmask.litValue.toString(16)}") 441 442 // stvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1 443 val stvecMask = ~(0x2.U(XLEN.W)) 444 val stvec = RegInit(UInt(XLEN.W), 0.U) 445 // val sie = RegInit(0.U(XLEN.W)) 446 val sieMask = "h222".U & mideleg 447 val sipMask = "h222".U & mideleg 448 val sipWMask = "h2".U(XLEN.W) // ssip is writeable in smode 449 val satp = if(EnbaleTlbDebug) RegInit(UInt(XLEN.W), "h8000000000087fbe".U) else RegInit(0.U(XLEN.W)) 450 // val satp = RegInit(UInt(XLEN.W), "h8000000000087fbe".U) // only use for tlb naive debug 451 // val satpMask = "h80000fffffffffff".U(XLEN.W) // disable asid, mode can only be 8 / 0 452 // TODO: use config to control the length of asid 453 // val satpMask = "h8fffffffffffffff".U(XLEN.W) // enable asid, mode can only be 8 / 0 454 val satpMask = Cat("h8".U(Satp_Mode_len.W), satp_part_wmask(Satp_Asid_len, AsidLength), satp_part_wmask(Satp_Addr_len, PAddrBits-12)) 455 val sepc = RegInit(UInt(XLEN.W), 0.U) 456 // Page 60 in riscv-priv: The low bit of sepc (sepc[0]) is always zero. 457 val sepcMask = ~(0x1.U(XLEN.W)) 458 val scause = RegInit(UInt(XLEN.W), 0.U) 459 val stval = RegInit(UInt(XLEN.W), 0.U) 460 val sscratch = RegInit(UInt(XLEN.W), 0.U) 461 val scounteren = RegInit(UInt(XLEN.W), 0.U) 462 val senvcfg = RegInit(UInt(XLEN.W), 0.U) // !WARNING: there is no logic about this CSR. 463 // Currently, XiangShan don't support Unprivileged Counter/Timers CSRs ("Zicntr" and "Zihpm") 464 val scounterenMask = 0.U(XLEN.W) 465 466 // sbpctl 467 // Bits 0-7: {LOOP, RAS, SC, TAGE, BIM, BTB, uBTB} 468 val sbpctl = RegInit(UInt(XLEN.W), "h7f".U) 469 csrio.customCtrl.bp_ctrl.ubtb_enable := sbpctl(0) 470 csrio.customCtrl.bp_ctrl.btb_enable := sbpctl(1) 471 csrio.customCtrl.bp_ctrl.bim_enable := sbpctl(2) 472 csrio.customCtrl.bp_ctrl.tage_enable := sbpctl(3) 473 csrio.customCtrl.bp_ctrl.sc_enable := sbpctl(4) 474 csrio.customCtrl.bp_ctrl.ras_enable := sbpctl(5) 475 csrio.customCtrl.bp_ctrl.loop_enable := sbpctl(6) 476 477 // spfctl Bit 0: L1I Cache Prefetcher Enable 478 // spfctl Bit 1: L2Cache Prefetcher Enable 479 // spfctl Bit 2: L1D Cache Prefetcher Enable 480 // spfctl Bit 3: L1D train prefetch on hit 481 // spfctl Bit 4: L1D prefetch enable agt 482 // spfctl Bit 5: L1D prefetch enable pht 483 // spfctl Bit [9:6]: L1D prefetch active page threshold 484 // spfctl Bit [15:10]: L1D prefetch active page stride 485 // turn off L2 BOP, turn on L1 SMS by default 486 val spfctl = RegInit(UInt(XLEN.W), Seq( 487 0 << 17, // L2 pf store only [17] init: false 488 1 << 16, // L1D pf enable stride [16] init: true 489 30 << 10, // L1D active page stride [15:10] init: 30 490 12 << 6, // L1D active page threshold [9:6] init: 12 491 1 << 5, // L1D enable pht [5] init: true 492 1 << 4, // L1D enable agt [4] init: true 493 0 << 3, // L1D train on hit [3] init: false 494 1 << 2, // L1D pf enable [2] init: true 495 1 << 1, // L2 pf enable [1] init: true 496 1 << 0, // L1I pf enable [0] init: true 497 ).reduce(_|_).U(XLEN.W)) 498 csrio.customCtrl.l1I_pf_enable := spfctl(0) 499 csrio.customCtrl.l2_pf_enable := spfctl(1) 500 csrio.customCtrl.l1D_pf_enable := spfctl(2) 501 csrio.customCtrl.l1D_pf_train_on_hit := spfctl(3) 502 csrio.customCtrl.l1D_pf_enable_agt := spfctl(4) 503 csrio.customCtrl.l1D_pf_enable_pht := spfctl(5) 504 csrio.customCtrl.l1D_pf_active_threshold := spfctl(9, 6) 505 csrio.customCtrl.l1D_pf_active_stride := spfctl(15, 10) 506 csrio.customCtrl.l1D_pf_enable_stride := spfctl(16) 507 csrio.customCtrl.l2_pf_store_only := spfctl(17) 508 509 // sfetchctl Bit 0: L1I Cache Parity check enable 510 val sfetchctl = RegInit(UInt(XLEN.W), "b0".U) 511 csrio.customCtrl.icache_parity_enable := sfetchctl(0) 512 513 // slvpredctl: load violation predict settings 514 // Default reset period: 2^16 515 // Why this number: reset more frequently while keeping the overhead low 516 // Overhead: extra two redirections in every 64K cycles => ~0.1% overhead 517 val slvpredctl = Reg(UInt(XLEN.W)) 518 when(reset.asBool) { 519 slvpredctl := Constantin.createRecord("slvpredctl", 0x60) 520 } 521 csrio.customCtrl.lvpred_disable := slvpredctl(0) 522 csrio.customCtrl.no_spec_load := slvpredctl(1) 523 csrio.customCtrl.storeset_wait_store := slvpredctl(2) 524 csrio.customCtrl.storeset_no_fast_wakeup := slvpredctl(3) 525 csrio.customCtrl.lvpred_timeout := slvpredctl(8, 4) 526 527 // smblockctl: memory block configurations 528 // +------------------------------+---+----+----+-----+--------+ 529 // |XLEN-1 8| 7 | 6 | 5 | 4 |3 0| 530 // +------------------------------+---+----+----+-----+--------+ 531 // | Reserved | O | CE | SP | LVC | Th | 532 // +------------------------------+---+----+----+-----+--------+ 533 // Description: 534 // Bit 3-0 : Store buffer flush threshold (Th). 535 // Bit 4 : Enable load violation check after reset (LVC). 536 // Bit 5 : Enable soft-prefetch after reset (SP). 537 // Bit 6 : Enable cache error after reset (CE). 538 // Bit 7 : Enable uncache write outstanding (O). 539 // Others : Reserved. 540 541 val smblockctl_init_val = 542 (0xf & StoreBufferThreshold) | 543 (EnableLdVioCheckAfterReset.toInt << 4) | 544 (EnableSoftPrefetchAfterReset.toInt << 5) | 545 (EnableCacheErrorAfterReset.toInt << 6) | 546 (EnableUncacheWriteOutstanding.toInt << 7) 547 val smblockctl = RegInit(UInt(XLEN.W), smblockctl_init_val.U) 548 csrio.customCtrl.sbuffer_threshold := smblockctl(3, 0) 549 // bits 4: enable load load violation check 550 csrio.customCtrl.ldld_vio_check_enable := smblockctl(4) 551 csrio.customCtrl.soft_prefetch_enable := smblockctl(5) 552 csrio.customCtrl.cache_error_enable := smblockctl(6) 553 csrio.customCtrl.uncache_write_outstanding_enable := smblockctl(7) 554 555 println("CSR smblockctl init value:") 556 println(" Store buffer replace threshold: " + StoreBufferThreshold) 557 println(" Enable ld-ld vio check after reset: " + EnableLdVioCheckAfterReset) 558 println(" Enable soft prefetch after reset: " + EnableSoftPrefetchAfterReset) 559 println(" Enable cache error after reset: " + EnableCacheErrorAfterReset) 560 println(" Enable uncache write outstanding: " + EnableUncacheWriteOutstanding) 561 562 val srnctl = RegInit(UInt(XLEN.W), "h7".U) 563 csrio.customCtrl.fusion_enable := srnctl(0) 564 csrio.customCtrl.wfi_enable := srnctl(2) 565 566 // Hypervisor CSRs 567 val hstatusWMask = "h7003c0".U(XLEN.W) 568 // hstatus: vtsr, vtw, vtvm, hu, spvp, spv, gva, 569 val hstatus = RegInit("h200000000".U(XLEN.W)) 570 val hstatusStruct = hstatus.asTypeOf(new HstatusStruct) 571 val hedeleg = RegInit(UInt(XLEN.W), 0.U) 572 val hideleg = RegInit(UInt(XLEN.W), 0.U) 573 val hidelegRMask = mideleg 574 val hidelegWMask = ((1 << 10) | (1 << 6) | (1 << 2)).U(XLEN.W) 575 val hgeie = RegInit(UInt(XLEN.W), 0.U) 576 val htval = RegInit(UInt(XLEN.W), 0.U) 577 // hvip hip hie is part of mip or mie 578 val hvipMask = ((1 << 10) | (1 << 6) | (1 << 2)).U(XLEN.W) 579 val hipRMask = (((1 << 12).U | hvipMask) & mideleg) 580 val hipWMask = ((1 << 2).U & mideleg)// vssip 581 val hieMask = hipRMask 582 val htinst = RegInit(UInt(XLEN.W), 0.U) 583 val hgeip = RegInit(UInt(XLEN.W), 0.U) 584 val henvcfg = RegInit(UInt(XLEN.W), 0.U) 585 val hgatp = RegInit(UInt(XLEN.W), 0.U) 586 val hgatpMask = Cat("h8".U(Hgatp_Mode_len.W), satp_part_wmask(Hgatp_Vmid_len, VmidLength), satp_part_wmask(Hgatp_Addr_len, PAddrBits-12)) 587 // val htimedelta = RegInit(UInt(XLEN.W), 0.U) 588 val hcounteren = RegInit(UInt(XLEN.W), 0.U) 589 // Currently, XiangShan don't support Unprivileged Counter/Timers CSRs ("Zicntr" and "Zihpm") 590 val hcounterenMask = 0.U(XLEN.W) 591 592 val vsstatus = RegInit("h200002000".U(XLEN.W)) 593 val vsstatusStruct = vsstatus.asTypeOf(new MstatusStruct) 594 //vsie vsip 595 val vsMask = ((1 << 10) | (1 << 6) | (1 << 2)).U(XLEN.W) 596 val vsip_ie_Mask = ZeroExt((hideleg & mideleg & vsMask), XLEN) 597 val vsip_WMask = ZeroExt((hideleg & mideleg & vssip_Mask), XLEN) 598 val vstvec = RegInit(UInt(XLEN.W), 0.U) 599 val vsscratch = RegInit(UInt(XLEN.W), 0.U) 600 val vsepc = RegInit(UInt(XLEN.W), 0.U) 601 val vscause = RegInit(UInt(XLEN.W), 0.U) 602 val vstval = RegInit(UInt(XLEN.W), 0.U) 603 val vsatp = RegInit(UInt(XLEN.W), 0.U) 604 val tlbBundle = Wire(new TlbCsrBundle) 605 tlbBundle.satp.apply(satp) 606 tlbBundle.vsatp.apply(vsatp) 607 tlbBundle.hgatp.apply(hgatp) 608 csrio.tlb := tlbBundle 609 610 // User-Level CSRs 611 val uepc = Reg(UInt(XLEN.W)) 612 613 // fcsr 614 class FcsrStruct extends Bundle { 615 val reserved = UInt((XLEN-3-5).W) 616 val frm = UInt(3.W) 617 val fflags = UInt(5.W) 618 assert(this.getWidth == XLEN) 619 } 620 val fcsr = RegInit(0.U(XLEN.W)) 621 // set mstatus->sd and mstatus->fs when true 622 val csrw_dirty_fp_state = WireInit(false.B) 623 624 def frm_wfn(wdata: UInt): UInt = { 625 val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct)) 626 csrw_dirty_fp_state := true.B 627 fcsrOld.frm := wdata(2,0) 628 fcsrOld.asUInt 629 } 630 def frm_rfn(rdata: UInt): UInt = rdata(7,5) 631 632 def fflags_wfn(update: Boolean)(wdata: UInt): UInt = { 633 val fcsrOld = fcsr.asTypeOf(new FcsrStruct) 634 val fcsrNew = WireInit(fcsrOld) 635 if (update) { 636 fcsrNew.fflags := wdata(4,0) | fcsrOld.fflags 637 } else { 638 fcsrNew.fflags := wdata(4,0) 639 } 640 fcsrNew.asUInt 641 } 642 def fflags_rfn(rdata:UInt): UInt = rdata(4,0) 643 644 def fcsr_wfn(wdata: UInt): UInt = { 645 val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct)) 646 csrw_dirty_fp_state := true.B 647 Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags) 648 } 649 650 val fcsrMapping = Map( 651 MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn(update = false), rfn = fflags_rfn), 652 MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn), 653 MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn) 654 ) 655 656 // Vector extension CSRs 657 val vstart = RegInit(0.U(XLEN.W)) 658 val vcsr = RegInit(0.U(XLEN.W)) 659 val vl = Reg(UInt(XLEN.W)) 660 val vtype = Reg(UInt(XLEN.W)) 661 val vlenb = RegInit(VDataBytes.U(XLEN.W)) 662 663 // set mstatus->sd and mstatus->vs when true 664 val csrw_dirty_vs_state = WireInit(false.B) 665 666 // vcsr is mapped to vxrm and vxsat 667 class VcsrStruct extends Bundle { 668 val reserved = UInt((XLEN-3).W) 669 val vxrm = UInt(2.W) 670 val vxsat = UInt(1.W) 671 assert(this.getWidth == XLEN) 672 } 673 674 def vxrm_wfn(wdata: UInt): UInt = { 675 val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct)) 676 csrw_dirty_vs_state := true.B 677 vcsrOld.vxrm := wdata(1,0) 678 vcsrOld.asUInt 679 } 680 def vxrm_rfn(rdata: UInt): UInt = rdata(2,1) 681 682 def vxsat_wfn(update: Boolean)(wdata: UInt): UInt = { 683 val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct)) 684 val vcsrNew = WireInit(vcsrOld) 685 csrw_dirty_vs_state := true.B 686 if (update) { 687 vcsrNew.vxsat := wdata(0) | vcsrOld.vxsat 688 } else { 689 vcsrNew.vxsat := wdata(0) 690 } 691 vcsrNew.asUInt 692 } 693 def vxsat_rfn(rdata: UInt): UInt = rdata(0) 694 695 def vcsr_wfn(wdata: UInt): UInt = { 696 val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct)) 697 csrw_dirty_vs_state := true.B 698 vcsrOld.vxrm := wdata.asTypeOf(vcsrOld).vxrm 699 vcsrOld.vxsat := wdata.asTypeOf(vcsrOld).vxsat 700 vcsrOld.asUInt 701 } 702 703 val vcsrMapping = Map( 704 MaskedRegMap(Vstart, vstart), 705 MaskedRegMap(Vxrm, vcsr, wfn = vxrm_wfn, rfn = vxrm_rfn), 706 MaskedRegMap(Vxsat, vcsr, wfn = vxsat_wfn(false), rfn = vxsat_rfn), 707 MaskedRegMap(Vcsr, vcsr, wfn = vcsr_wfn), 708 MaskedRegMap(Vl, vl), 709 MaskedRegMap(Vtype, vtype), 710 MaskedRegMap(Vlenb, vlenb), 711 ) 712 713 // Hart Privilege Mode 714 val privilegeMode = RegInit(UInt(2.W), ModeM) 715 716 //val perfEventscounten = List.fill(nrPerfCnts)(RegInit(false(Bool()))) 717 // Perf Counter 718 val nrPerfCnts = 29 // 3...31 719 val privilegeModeOH = UIntToOH(privilegeMode) 720 val perfEventscounten = RegInit(0.U.asTypeOf(Vec(nrPerfCnts, Bool()))) 721 val perfCnts = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W))) 722 val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++ 723 List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++ 724 List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++ 725 List.fill(5)(RegInit("hc0300c0300".U(XLEN.W))) 726 for (i <-0 until nrPerfCnts) { 727 perfEventscounten(i) := (perfEvents(i)(63,60) & privilegeModeOH).orR 728 } 729 730 val hpmEvents = Wire(Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent)) 731 for (i <- 0 until numPCntHc * coreParams.L2NBanks) { 732 hpmEvents(i) := csrio.perf.perfEventsHc(i) 733 } 734 735 // print perfEvents 736 val allPerfEvents = hpmEvents.map(x => (s"Hc", x.value)) 737 if (printEventCoding) { 738 for (((name, inc), i) <- allPerfEvents.zipWithIndex) { 739 println("CSR perfEvents Set", name, inc, i) 740 } 741 } 742 743 val csrevents = perfEvents.slice(24, 29) 744 val hpm_hc = HPerfMonitor(csrevents, hpmEvents) 745 val mcountinhibit = RegInit(0.U(XLEN.W)) 746 val mcycle = RegInit(0.U(XLEN.W)) 747 mcycle := mcycle + 1.U 748 val minstret = RegInit(0.U(XLEN.W)) 749 val perf_events = csrio.perf.perfEventsFrontend ++ 750 csrio.perf.perfEventsBackend ++ 751 csrio.perf.perfEventsLsu ++ 752 hpm_hc.getPerf 753 minstret := minstret + RegNext(csrio.perf.retiredInstr) 754 for(i <- 0 until 29){ 755 perfCnts(i) := Mux(mcountinhibit(i+3) | !perfEventscounten(i), perfCnts(i), perfCnts(i) + perf_events(i).value) 756 } 757 758 // CSR reg map 759 val basicPrivMapping = Map( 760 761 // Unprivileged Floating-Point CSRs 762 // Has been mapped above 763 764 // TODO: support Unprivileged Counter/Timers CSRs ("Zicntr" and "Zihpm") 765 // Unprivileged Counter/Timers 766 MaskedRegMap(Cycle, mcycle), 767 // We don't support read time CSR. 768 // MaskedRegMap(Time, mtime), 769 MaskedRegMap(Instret, minstret), 770 771 //--- Supervisor Trap Setup --- 772 MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask), 773 // MaskedRegMap(Sedeleg, Sedeleg), 774 // MaskedRegMap(Sideleg, Sideleg), 775 MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask), 776 MaskedRegMap(Stvec, stvec, stvecMask, MaskedRegMap.NoSideEffect, stvecMask), 777 MaskedRegMap(Scounteren, scounteren, scounterenMask), 778 779 //--- Supervisor Configuration --- 780 MaskedRegMap(Senvcfg, senvcfg), 781 782 //--- Supervisor Trap Handling --- 783 MaskedRegMap(Sscratch, sscratch), 784 MaskedRegMap(Sepc, sepc, sepcMask, MaskedRegMap.NoSideEffect, sepcMask), 785 MaskedRegMap(Scause, scause), 786 MaskedRegMap(Stval, stval), 787 MaskedRegMap(Sip, mipReg.asUInt, sipWMask, MaskedRegMap.NoSideEffect, sipMask, x => (mipWire.asUInt | x) & sipMask), 788 789 //--- Supervisor Protection and Translation --- 790 MaskedRegMap(Satp, satp, satpMask, MaskedRegMap.NoSideEffect, satpMask), 791 792 //--- Supervisor Custom Read/Write Registers 793 MaskedRegMap(Sbpctl, sbpctl), 794 MaskedRegMap(Spfctl, spfctl), 795 MaskedRegMap(Sfetchctl, sfetchctl), 796 MaskedRegMap(Slvpredctl, slvpredctl), 797 MaskedRegMap(Smblockctl, smblockctl), 798 MaskedRegMap(Srnctl, srnctl), 799 800 //--- Machine Information Registers --- 801 MaskedRegMap(Mvendorid, mvendorid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 802 MaskedRegMap(Marchid, marchid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 803 MaskedRegMap(Mimpid, mimpid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 804 MaskedRegMap(Mhartid, mhartid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 805 MaskedRegMap(Mconfigptr, mconfigptr, 0.U(XLEN.W), MaskedRegMap.Unwritable), 806 807 //--- Machine Configuration Registers --- 808 MaskedRegMap(Menvcfg, menvcfg), 809 810 //--- Machine Trap Setup --- 811 MaskedRegMap(Mstatus, mstatus, mstatusWMask, mstatusUpdateSideEffect), 812 MaskedRegMap(Misa, misa, 0.U, MaskedRegMap.Unwritable), // now whole misa is unchangeable 813 MaskedRegMap(Medeleg, medeleg, medelegWMask), 814 MaskedRegMap(Mideleg, mideleg, midelegWMask), 815 MaskedRegMap(Mie, mie, mieWMask), 816 MaskedRegMap(Mtvec, mtvec, mtvecMask, MaskedRegMap.NoSideEffect, mtvecMask), 817 MaskedRegMap(Mcounteren, mcounteren, mcounterenMask), 818 819 //--- Machine Trap Handling --- 820 MaskedRegMap(Mscratch, mscratch), 821 MaskedRegMap(Mepc, mepc, mepcMask, MaskedRegMap.NoSideEffect, mepcMask), 822 MaskedRegMap(Mcause, mcause), 823 MaskedRegMap(Mtval, mtval), 824 MaskedRegMap(Mip, mipReg.asUInt, mipWMask, MaskedRegMap.NoSideEffect, mipMask, x => (mipWire.asUInt | x) & mipMask), 825 826 //--- Trigger --- 827 MaskedRegMap(Tselect, tselectPhy, WritableMask, WriteTselect), 828 // Todo: support chain length = 2 829 MaskedRegMap(Tdata1, tdata1RegVec(tselectPhy), 830 WritableMask, 831 x => Tdata1Bundle.Write(x, tdata1RegVec(tselectPhy), newTriggerChainIsLegal, debug_mode = debugMode), 832 WritableMask, 833 x => Tdata1Bundle.Read(x)), 834 MaskedRegMap(Tdata2, tdata2RegVec(tselectPhy)), 835 MaskedRegMap(Tinfo, tinfo, 0.U(XLEN.W), MaskedRegMap.Unwritable), 836 837 //--- Debug Mode --- 838 MaskedRegMap(Dcsr, dcsr, dcsrMask, dcsrUpdateSideEffect), 839 MaskedRegMap(Dpc, dpc), 840 MaskedRegMap(Dscratch0, dscratch0), 841 MaskedRegMap(Dscratch1, dscratch1), 842 MaskedRegMap(Mcountinhibit, mcountinhibit), 843 MaskedRegMap(Mcycle, mcycle), 844 MaskedRegMap(Minstret, minstret), 845 ) 846 847 // hypervisor csr map 848 val hcsrMapping = Map( 849 //--- Hypervisor Trap Setup --- 850 MaskedRegMap(Hstatus, hstatus, hstatusWMask), 851 MaskedRegMap(Hedeleg, hedeleg), 852 MaskedRegMap(Hideleg, hideleg, hidelegWMask, MaskedRegMap.NoSideEffect, hidelegRMask), 853 MaskedRegMap(Hie, mie, hieMask, MaskedRegMap.NoSideEffect, hieMask), 854 MaskedRegMap(Hcounteren, hcounteren, hcounterenMask), 855 MaskedRegMap(Hgeie, hgeie), 856 857 //--- Hypervisor Trap Handling --- 858 MaskedRegMap(Htval, htval), 859 MaskedRegMap(Hip, mipReg.asUInt, hipWMask, MaskedRegMap.NoSideEffect, hipRMask, x => (mipWire.asUInt | x) & hipRMask), 860 MaskedRegMap(Hvip, mipReg.asUInt, hvipMask, MaskedRegMap.NoSideEffect, hvipMask, x => (mipWire.asUInt | x) & hvipMask), 861 MaskedRegMap(Htinst, htinst), 862 MaskedRegMap(Hgeip, hgeip), 863 864 //--- Hypervisor Configuration --- 865 MaskedRegMap(Henvcfg, henvcfg), 866 867 //--- Hypervisor Protection and Translation --- 868 MaskedRegMap(Hgatp, hgatp, hgatpMask, MaskedRegMap.NoSideEffect, hgatpMask), 869 870 //--- Hypervisor Counter/Timer Virtualization Registers --- 871 // MaskedRegMap(Htimedelta, htimedelta), 872 873 //--- Virtual Supervisor Registers --- 874 MaskedRegMap(Vsstatus, vsstatus, rmask = sstatusRmask, wmask = sstatusWmask, wfn = vsstatusUpdateSideEffect), 875 MaskedRegMap(Vsie, mie, rmask = vsip_ie_Mask, wmask = vsip_ie_Mask), 876 MaskedRegMap(Vstvec, vstvec), 877 MaskedRegMap(Vsscratch, vsscratch), 878 MaskedRegMap(Vsepc, vsepc), 879 MaskedRegMap(Vscause, vscause), 880 MaskedRegMap(Vstval, vstval), 881 MaskedRegMap(Vsip, mipReg.asUInt, vsip_WMask, MaskedRegMap.NoSideEffect, vsip_ie_Mask, x => mipWire.asUInt | x), 882 MaskedRegMap(Vsatp, vsatp, satpMask, MaskedRegMap.NoSideEffect, satpMask), 883 884 //--- Machine Registers --- 885 MaskedRegMap(Mtval2, mtval2), 886 MaskedRegMap(Mtinst, mtinst), 887 ) 888 889 val perfCntMapping = (0 until 29).map(i => {Map( 890 MaskedRegMap(addr = Mhpmevent3 +i, 891 reg = perfEvents(i), 892 wmask = "hf87fff3fcff3fcff".U(XLEN.W)), 893 MaskedRegMap(addr = Mhpmcounter3 +i, 894 reg = perfCnts(i)), 895 MaskedRegMap(addr = Hpmcounter3 + i, 896 reg = perfCnts(i)) 897 )}).fold(Map())((a,b) => a ++ b) 898 // TODO: mechanism should be implemented later 899 // val MhpmcounterStart = Mhpmcounter3 900 // val MhpmeventStart = Mhpmevent3 901 // for (i <- 0 until nrPerfCnts) { 902 // perfCntMapping += MaskedRegMap(MhpmcounterStart + i, perfCnts(i)) 903 // perfCntMapping += MaskedRegMap(MhpmeventStart + i, perfEvents(i)) 904 // } 905 906 val cacheopRegs = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => { 907 name -> RegInit(0.U(attribute("width").toInt.W)) 908 }} 909 val cacheopMapping = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => { 910 MaskedRegMap( 911 Scachebase + attribute("offset").toInt, 912 cacheopRegs(name) 913 ) 914 }} 915 916 val mapping = basicPrivMapping ++ 917 perfCntMapping ++ 918 pmpMapping ++ 919 pmaMapping ++ 920 (if (HasFPU) fcsrMapping else Nil) ++ 921 (if (HasVPU) vcsrMapping else Nil) ++ 922 (if (HasCustomCSRCacheOp) cacheopMapping else Nil) ++ 923 (if (HasHExtension) hcsrMapping else Nil) 924 925 926 println("XiangShan CSR Lists") 927 928 for (addr <- mapping.keys.toSeq.sorted) { 929 println(f"$addr%#03x ${mapping(addr)._1}") 930 } 931 932 val vs_s_csr_map = List( 933 Sstatus.U -> Vsstatus.U, 934 Sie.U -> Vsie.U, 935 Stvec.U -> Vstvec.U, 936 Sscratch.U -> Vsscratch.U, 937 Sepc.U -> Vsepc.U, 938 Scause.U -> Vscause.U, 939 Stval.U -> Vstval.U, 940 Sip.U -> Vsip.U, 941 Satp.U -> Vsatp.U 942 ) 943 val addr = Wire(UInt(12.W)) 944 val vscsr_addr = LookupTreeDefault(src2(11, 0), src2(11, 0), vs_s_csr_map) 945 when(virtMode){ 946 addr := vscsr_addr 947 }.otherwise{ 948 addr := src2(11, 0) 949 } 950 val csri = ZeroExt(src2(16, 12), XLEN) 951 val rdata = Wire(UInt(XLEN.W)) 952 val rdata_tmp = Wire(UInt(XLEN.W)) 953 val wdata_tmp = LookupTree(func, List( 954 CSROpType.wrt -> src1, 955 CSROpType.set -> (rdata | src1), 956 CSROpType.clr -> (rdata & (~src1).asUInt), 957 CSROpType.wrti -> csri, 958 CSROpType.seti -> (rdata | csri), 959 CSROpType.clri -> (rdata & (~csri).asUInt) 960 )) 961 val is_vsip_ie = addr === Vsip.U || addr === Vsie.U 962 // for the difftest with NEMU(stay consistent with Spike) 963 val is_satp = addr === Satp.U 964 val is_vsatp = addr === Vsatp.U 965 val is_hgatp = addr === Hgatp.U 966 val check_apt_mode = wdata_tmp(wdata_tmp.getWidth-1, 64-Satp_Mode_len) === 8.U || wdata_tmp(wdata_tmp.getWidth-1, 64-Satp_Mode_len) === 0.U 967 val wdata = MuxCase(wdata_tmp, Seq( 968 is_vsip_ie -> ZeroExt(wdata_tmp << 1, XLEN), 969 (is_satp && !check_apt_mode) -> satp, 970 (is_vsatp && !check_apt_mode) -> vsatp, 971 (is_hgatp && !check_apt_mode) -> hgatp 972 )) 973 val addrInPerfCnt = (addr >= Mcycle.U) && (addr <= Mhpmcounter31.U) || 974 (addr >= Mcountinhibit.U) && (addr <= Mhpmevent31.U) || 975 (addr >= Cycle.U) && (addr <= Hpmcounter31.U) || 976 addr === Mip.U 977 csrio.isPerfCnt := addrInPerfCnt && valid && func =/= CSROpType.jmp 978 979 // satp wen check 980 val satpLegalMode = (wdata.asTypeOf(new SatpStruct).mode===0.U) || (wdata.asTypeOf(new SatpStruct).mode===8.U) 981 982 // csr access check, special case 983 val tvmNotPermit = (privilegeMode === ModeS && !virtMode && mstatusStruct.tvm.asBool) 984 val accessPermitted = !(addr === Satp.U && tvmNotPermit) 985 val vtvmNotPermit = (privilegeMode === ModeS && virtMode && hstatusStruct.vtvm.asBool) 986 val vaccessPermitted = !(addr === Vsatp.U && vtvmNotPermit) 987// csrio.disableSfence := (tvmNotPermit || !virtMode && privilegeMode < ModeS) || (vtvmNotPermit || virtMode && privilegeMode < ModeS) 988// csrio.disableHfenceg := !((!virtMode && privilegeMode === ModeS && !mstatusStruct.tvm.asBool) || (privilegeMode === ModeM)) // only valid in HS and mstatus.tvm == 0 or in M 989// csrio.disableHfencev := !(privilegeMode === ModeM || (!virtMode && privilegeMode === ModeS)) 990 991 // general CSR wen check 992 val wen = valid && CSROpType.isCsrAccess(func) && ((addr=/=Satp.U && addr =/= Vsatp.U) || satpLegalMode) 993 val dcsrPermitted = dcsrPermissionCheck(addr, false.B, debugMode) 994 val triggerPermitted = triggerPermissionCheck(addr, true.B, debugMode) // todo dmode 995 val HasH = (HasHExtension == true).asBool 996 val csrAccess = csrAccessPermissionCheck(addr, false.B, privilegeMode, virtMode, HasH) 997 val modePermitted = csrAccess === 0.U && dcsrPermitted && triggerPermitted 998 val perfcntPermitted = perfcntPermissionCheck(addr, privilegeMode, mcounteren, scounteren) 999 val permitted = Mux(addrInPerfCnt, perfcntPermitted, modePermitted) && Mux(virtMode, vaccessPermitted, accessPermitted) 1000 MaskedRegMap.generate(mapping, addr, rdata_tmp, wen && permitted, wdata) 1001 rdata := Mux(is_vsip_ie, ZeroExt(rdata_tmp >> 1, XLEN), rdata_tmp) 1002 io.out.bits.res.data := rdata 1003 io.out.bits.ctrl.flushPipe.get := flushPipe 1004 connect0LatencyCtrlSingal 1005 1006 // send distribute csr a w signal 1007 csrio.customCtrl.distribute_csr.w.valid := wen && permitted 1008 csrio.customCtrl.distribute_csr.w.bits.data := wdata 1009 csrio.customCtrl.distribute_csr.w.bits.addr := addr 1010 1011 when (RegNext(csrio.fpu.fflags.valid)) { 1012 fcsr := fflags_wfn(update = true)(RegEnable(csrio.fpu.fflags.bits, csrio.fpu.fflags.valid)) 1013 } 1014 when(RegNext(csrio.vpu.set_vxsat.valid)) { 1015 vcsr := vxsat_wfn(update = true)(RegEnable(csrio.vpu.set_vxsat.bits, csrio.vpu.set_vxsat.valid)) 1016 } 1017 1018 // set fs and sd in mstatus 1019 when (csrw_dirty_fp_state || RegNext(csrio.fpu.dirty_fs)) { 1020 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1021 mstatusNew.fs := "b11".U 1022 mstatusNew.sd := true.B 1023 mstatus := mstatusNew.asUInt 1024 when(virtMode){ 1025 val vsstatusNew = WireInit(vsstatus.asTypeOf(new MstatusStruct)) 1026 vsstatusNew.fs := "b11".U 1027 vsstatusNew.sd := true.B 1028 vsstatus := vsstatusNew.asUInt 1029 } 1030 } 1031 csrio.fpu.frm := fcsr.asTypeOf(new FcsrStruct).frm 1032 1033 when (RegNext(csrio.vpu.set_vstart.valid)) { 1034 vstart := RegEnable(csrio.vpu.set_vstart.bits, csrio.vpu.set_vstart.valid) 1035 } 1036 when (RegNext(csrio.vpu.set_vtype.valid)) { 1037 vtype := RegEnable(csrio.vpu.set_vtype.bits, csrio.vpu.set_vtype.valid) 1038 } 1039 vl := csrio.vpu.vl 1040 // set vs and sd in mstatus 1041 when(csrw_dirty_vs_state || RegNext(csrio.vpu.dirty_vs)) { 1042 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1043 mstatusNew.vs := ContextStatus.dirty 1044 mstatusNew.sd := true.B 1045 mstatus := mstatusNew.asUInt 1046 } 1047 1048 csrio.vpu.vstart := vstart 1049 csrio.vpu.vxrm := vcsr.asTypeOf(new VcsrStruct).vxrm 1050 1051 // Trigger Ctrl 1052 val triggerEnableVec = tdata1RegVec.map { tdata1 => 1053 val mcontrolData = tdata1.asTypeOf(new Tdata1Bundle).data.asTypeOf(new MControlData) 1054 tdata1.asTypeOf(new Tdata1Bundle).type_.asUInt === TrigTypeEnum.MCONTROL && ( 1055 mcontrolData.m && privilegeMode === ModeM || 1056 mcontrolData.s && privilegeMode === ModeS || 1057 mcontrolData.u && privilegeMode === ModeU) 1058 } 1059 val fetchTriggerEnableVec = triggerEnableVec.zip(tdata1WireVec).map { 1060 case (tEnable, tdata1) => tEnable && tdata1.asTypeOf(new Tdata1Bundle).data.asTypeOf(new MControlData).isFetchTrigger 1061 } 1062 val memAccTriggerEnableVec = triggerEnableVec.zip(tdata1WireVec).map { 1063 case (tEnable, tdata1) => tEnable && tdata1.asTypeOf(new Tdata1Bundle).data.asTypeOf(new MControlData).isMemAccTrigger 1064 } 1065 csrio.customCtrl.frontend_trigger.tEnableVec := fetchTriggerEnableVec 1066 csrio.customCtrl.mem_trigger.tEnableVec := memAccTriggerEnableVec 1067 1068 val tdata1Update = wen && (addr === Tdata1.U) 1069 val tdata2Update = wen && (addr === Tdata2.U) 1070 val triggerUpdate = wen && (addr === Tdata1.U || addr === Tdata2.U) 1071 val frontendTriggerUpdate = 1072 tdata1Update && wdata.asTypeOf(new Tdata1Bundle).type_.asUInt === TrigTypeEnum.MCONTROL && 1073 wdata.asTypeOf(new Tdata1Bundle).data.asTypeOf(new MControlData).isFetchTrigger || 1074 tdata1Selected.data.asTypeOf(new MControlData).isFetchTrigger && triggerUpdate 1075 val memTriggerUpdate = 1076 tdata1Update && wdata.asTypeOf(new Tdata1Bundle).type_.asUInt === TrigTypeEnum.MCONTROL && 1077 wdata.asTypeOf(new Tdata1Bundle).data.asTypeOf(new MControlData).isMemAccTrigger || 1078 tdata1Selected.data.asTypeOf(new MControlData).isMemAccTrigger && triggerUpdate 1079 1080 csrio.customCtrl.frontend_trigger.tUpdate.valid := RegNext(RegNext(frontendTriggerUpdate)) 1081 csrio.customCtrl.mem_trigger.tUpdate.valid := RegNext(RegNext(memTriggerUpdate)) 1082 XSDebug(triggerEnableVec.reduce(_ || _), p"Debug Mode: At least 1 trigger is enabled," + 1083 p"trigger enable is ${Binary(triggerEnableVec.asUInt)}\n") 1084 1085 // CSR inst decode 1086 val isEbreak = addr === privEbreak && func === CSROpType.jmp 1087 val isEcall = addr === privEcall && func === CSROpType.jmp 1088 val isMret = addr === privMret && func === CSROpType.jmp 1089 val isSret = addr === privSret && func === CSROpType.jmp 1090 val isUret = addr === privUret && func === CSROpType.jmp 1091 val isDret = addr === privDret && func === CSROpType.jmp 1092 val isWFI = func === CSROpType.wfi 1093 1094 // Illegal privileged operation list 1095 val illegalMret = valid && isMret && privilegeMode < ModeM 1096 val illegalSret = valid && isSret && privilegeMode < ModeS 1097 val illegalSModeSret = valid && isSret && privilegeMode === ModeS && virtMode === false.B && mstatusStruct.tsr.asBool 1098 // when hstatus.vtsr == 1, if sret is executed in VS-mode, it will cause virtual instruction 1099 val illegalVSModeSret = valid && isSret && privilegeMode === ModeS && virtMode && hstatusStruct.vtsr.asBool 1100 // When TW=1, then if WFI is executed in any less-privileged mode, 1101 // and it does not complete within an implementation-specific, bounded time limit, 1102 // the WFI instruction causes an illegal instruction exception. 1103 // The time limit may always be 0, in which case WFI always causes 1104 // an illegal instruction exception in less-privileged modes when TW=1. 1105 val illegalWFI = valid && isWFI && (privilegeMode < ModeM && mstatusStruct.tw === 1.U || privilegeMode === ModeU && !virtMode) 1106 val illegalVWFI = valid && isWFI && ((virtMode && privilegeMode === ModeS && hstatusStruct.vtw === 1.U && mstatusStruct.tw === 0.U)|| 1107 (virtMode && privilegeMode === ModeU && mstatusStruct.tw === 0.U)) 1108 // Illegal privileged instruction check 1109 val isIllegalAddr = valid && CSROpType.isCsrAccess(func) && MaskedRegMap.isIllegalAddr(mapping, addr) 1110 val isIllegalAccess = !virtMode && wen && !(Mux(addrInPerfCnt, perfcntPermitted, csrAccess === 0.U && dcsrPermitted && triggerPermitted) && accessPermitted) 1111 val isIllegalPrivOp = illegalMret || illegalSret || illegalSModeSret || illegalWFI 1112 1113 val isIllegalVAccess = virtMode && wen && (csrAccess === 2.U || !vaccessPermitted) 1114 val isIllegalVPrivOp = illegalVSModeSret || illegalVWFI 1115 // expose several csr bits for tlb 1116 tlbBundle.priv.mxr := mstatusStruct.mxr.asBool 1117 tlbBundle.priv.sum := mstatusStruct.sum.asBool 1118 tlbBundle.priv.vmxr := vsstatusStruct.mxr.asBool 1119 tlbBundle.priv.vsum := vsstatusStruct.sum.asBool 1120 tlbBundle.priv.spvp := hstatusStruct.spvp 1121 tlbBundle.priv.virt := Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpv & (mstatusStruct.mpp =/= ModeM), virtMode) 1122 tlbBundle.priv.imode := privilegeMode 1123 tlbBundle.priv.dmode := Mux((debugMode && dcsr.asTypeOf(new DcsrStruct).mprven || !debugMode) && mstatusStruct.mprv.asBool, mstatusStruct.mpp, privilegeMode) 1124 1125 // Branch control 1126 val retTarget = WireInit(0.U) 1127 val resetSatp = (addr === Satp.U || addr === Hgatp.U || addr === Vsatp.U) && wen // write to satp will cause the pipeline be flushed 1128 val writeVstart = addr === Vstart.U && wen // write to vstart will cause the pipeline be flushed 1129 dontTouch(writeVstart) 1130 1131 val w_fcsr_change_rm = wen && addr === Fcsr.U && wdata(7, 5) =/= fcsr(7, 5) 1132 val w_frm_change_rm = wen && addr === Frm.U && wdata(2, 0) =/= fcsr(7, 5) 1133 val frm_change = w_fcsr_change_rm || w_frm_change_rm 1134 val isXRet = valid && func === CSROpType.jmp && !isEcall && !isEbreak 1135 flushPipe := resetSatp || frm_change || isXRet || frontendTriggerUpdate || writeVstart 1136 1137 private val illegalRetTarget = WireInit(false.B) 1138 when(valid) { 1139 when(isDret) { 1140 retTarget := dpc(VAddrBits - 1, 0) 1141 }.elsewhen(isMret && !illegalMret) { 1142 retTarget := mepc(VAddrBits - 1, 0) 1143 }.elsewhen(isSret && !illegalSret && !illegalSModeSret && !illegalVSModeSret) { 1144 retTarget := Mux(virtMode, vsepc(VAddrBits - 1, 0), sepc(VAddrBits - 1, 0)) 1145 }.elsewhen(isUret) { 1146 retTarget := uepc(VAddrBits - 1, 0) 1147 }.otherwise { 1148 illegalRetTarget := true.B 1149 } 1150 }.otherwise { 1151 illegalRetTarget := true.B // when illegalRetTarget setted, retTarget should never be used 1152 } 1153 1154 // Mux tree for regs 1155 when(valid) { 1156 when(isDret) { 1157 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1158 val debugModeNew = WireInit(debugMode) 1159 when(dcsr.asTypeOf(new DcsrStruct).prv =/= ModeM) { 1160 mstatusNew.mprv := 0.U 1161 } //If the new privilege mode is less privileged than M-mode, MPRV in mstatus is cleared. 1162 mstatus := mstatusNew.asUInt 1163 privilegeMode := dcsr.asTypeOf(new DcsrStruct).prv 1164 debugModeNew := false.B 1165 debugIntrEnable := true.B 1166 debugMode := debugModeNew 1167 XSDebug("Debug Mode: Dret executed, returning to %x.", retTarget) 1168 }.elsewhen(isMret && !illegalMret) { 1169 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1170 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1171 mstatusNew.ie.m := mstatusOld.pie.m 1172 privilegeMode := mstatusOld.mpp 1173 if (HasHExtension) { 1174 virtMode := mstatusOld.mpv 1175 mstatusNew.mpv := 0.U 1176 } 1177 mstatusNew.pie.m := true.B 1178 mstatusNew.mpp := ModeU 1179 when(mstatusOld.mpp =/= ModeM) { 1180 mstatusNew.mprv := 0.U 1181 } 1182 mstatus := mstatusNew.asUInt 1183 }.elsewhen(isSret && !illegalSret && !illegalSModeSret && !illegalVSModeSret) { 1184 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1185 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1186 val hstatusOld = WireInit(hstatus.asTypeOf(new HstatusStruct)) 1187 val hstatusNew = WireInit(hstatus.asTypeOf(new HstatusStruct)) 1188 val vsstatusOld = WireInit(vsstatus.asTypeOf(new MstatusStruct)) 1189 val vsstatusNew = WireInit(vsstatus.asTypeOf(new MstatusStruct)) 1190 when(virtMode === 0.U) { 1191 virtMode := hstatusOld.spv 1192 hstatusNew.spv := 0.U 1193 mstatusNew.ie.s := mstatusOld.pie.s 1194 privilegeMode := Cat(0.U(1.W), mstatusOld.spp) 1195 mstatusNew.pie.s := true.B 1196 mstatusNew.spp := ModeU 1197 when(mstatusOld.spp =/= ModeM) { 1198 mstatusNew.mprv := 0.U 1199 } 1200 mstatus := mstatusNew.asUInt 1201 hstatus := hstatusNew.asUInt 1202 }.otherwise { 1203 privilegeMode := vsstatusOld.spp 1204 vsstatusNew.spp := ModeU 1205 vsstatusNew.ie.s := vsstatusOld.pie.s 1206 vsstatusNew.pie.s := 1.U 1207 vsstatus := vsstatusNew.asUInt 1208 } 1209 }.elsewhen(isUret) { 1210 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1211 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1212 // mstatusNew.mpp.m := ModeU //TODO: add mode U 1213 mstatusNew.ie.u := mstatusOld.pie.u 1214 privilegeMode := ModeU 1215 mstatusNew.pie.u := true.B 1216 mstatus := mstatusNew.asUInt 1217 } 1218 } 1219 1220 io.in.ready := true.B 1221 io.out.valid := valid 1222 1223 // In this situation, hart will enter debug mode instead of handling a breakpoint exception simply. 1224 // Ebreak block instructions backwards, so it's ok to not keep extra info to distinguish between breakpoint 1225 // exception and enter-debug-mode exception. 1226 val ebreakEnterDebugMode = 1227 (privilegeMode === ModeM && dcsrData.ebreakm) || 1228 (privilegeMode === ModeS && dcsrData.ebreaks) || 1229 (privilegeMode === ModeU && dcsrData.ebreaku) 1230 1231 // raise a debug exception waiting to enter debug mode, instead of a breakpoint exception 1232 val raiseDebugException = !debugMode && isEbreak && ebreakEnterDebugMode 1233 1234 val csrExceptionVec = WireInit(0.U.asTypeOf(ExceptionVec())) 1235 csrExceptionVec(breakPoint) := io.in.valid && isEbreak 1236 csrExceptionVec(ecallM) := privilegeMode === ModeM && io.in.valid && isEcall 1237 csrExceptionVec(ecallVS) := privilegeMode === ModeS && virtMode && io.in.valid && isEcall 1238 csrExceptionVec(ecallS) := privilegeMode === ModeS && !virtMode && io.in.valid && isEcall 1239 csrExceptionVec(ecallU) := privilegeMode === ModeU && io.in.valid && isEcall 1240 // Trigger an illegal instr exception when: 1241 // * unimplemented csr is being read/written 1242 // * csr access is illegal 1243 csrExceptionVec(illegalInstr) := isIllegalAddr || isIllegalAccess || isIllegalPrivOp 1244 csrExceptionVec(virtualInstr) := isIllegalVAccess || isIllegalVPrivOp 1245 io.out.bits.ctrl.exceptionVec.get := csrExceptionVec 1246 1247 XSDebug(io.in.valid, s"Debug Mode: an Ebreak is executed, ebreak cause enter-debug-mode exception ? ${raiseDebugException}\n") 1248 1249 /** 1250 * Exception and Intr 1251 */ 1252 val idelegS = (mideleg & mip.asUInt) 1253 val idelegVS = (hideleg & mideleg & mip.asUInt) 1254 def privilegedEnableDetect(idelegS: Bool, idelegVS: Bool): Bool = Mux(idelegS, 1255 Mux(idelegVS, (virtMode && privilegeMode === ModeS && vsstatusStruct.ie.s) || (virtMode && privilegeMode < ModeS), 1256 ((privilegeMode === ModeS) && mstatusStruct.ie.s) || (privilegeMode < ModeS) || virtMode), 1257 ((privilegeMode === ModeM) && mstatusStruct.ie.m) || (privilegeMode < ModeM)) 1258 1259 val debugIntr = csrio.externalInterrupt.debug & debugIntrEnable 1260 XSDebug(debugIntr, "Debug Mode: debug interrupt is asserted and valid!") 1261 // send interrupt information to ROB 1262 val intrVecEnable = Wire(Vec(13, Bool())) 1263 val disableInterrupt = debugMode || (dcsrData.step && !dcsrData.stepie) 1264 intrVecEnable.zip(idelegS.asBools).zip(idelegVS.asBools).map{case((x,y),z) => x := privilegedEnableDetect(y, z) && !disableInterrupt} 1265 val intrVec = Cat(debugIntr && !debugMode, (mie(11,0) & mip.asUInt & intrVecEnable.asUInt)) 1266 val intrBitSet = intrVec.orR 1267 csrio.interrupt := intrBitSet 1268 // Page 45 in RISC-V Privileged Specification 1269 // The WFI instruction can also be executed when interrupts are disabled. The operation of WFI 1270 // must be unaffected by the global interrupt bits in mstatus (MIE and SIE) and the delegation 1271 // register mideleg, but should honor the individual interrupt enables (e.g, MTIE). 1272 csrio.wfi_event := debugIntr || (mie(11, 0) & mip.asUInt).orR 1273 mipWire.t.m := csrio.externalInterrupt.mtip 1274 mipWire.s.m := csrio.externalInterrupt.msip 1275 mipWire.e.m := csrio.externalInterrupt.meip 1276 mipWire.e.s := csrio.externalInterrupt.seip 1277 1278 // interrupts 1279 val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(intrVec(i), i.U, sum)) 1280 val hasIntr = csrio.exception.valid && csrio.exception.bits.isInterrupt 1281 val ivmEnable = tlbBundle.priv.imode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U 1282 val iexceptionPC = Mux(ivmEnable, SignExt(csrio.exception.bits.pc, XLEN), csrio.exception.bits.pc) 1283 val iexceptionGPAddr = Mux(ivmEnable, SignExt(csrio.exception.bits.gpaddr, XLEN), csrio.exception.bits.gpaddr) 1284 val dvmEnable = tlbBundle.priv.dmode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U 1285 val dexceptionPC = Mux(dvmEnable, SignExt(csrio.exception.bits.pc, XLEN), csrio.exception.bits.pc) 1286 XSDebug(hasIntr, "interrupt: pc=0x%x, %d\n", dexceptionPC, intrNO) 1287 val hasDebugIntr = intrNO === IRQ_DEBUG.U && hasIntr 1288 1289 // exceptions from rob need to handle 1290 val exceptionVecFromRob = csrio.exception.bits.exceptionVec 1291 val hasException = csrio.exception.valid && !csrio.exception.bits.isInterrupt 1292 val hasInstrPageFault = hasException && exceptionVecFromRob(instrPageFault) 1293 val hasLoadPageFault = hasException && exceptionVecFromRob(loadPageFault) 1294 val hasStorePageFault = hasException && exceptionVecFromRob(storePageFault) 1295 val hasStoreAddrMisalign = hasException && exceptionVecFromRob(storeAddrMisaligned) 1296 val hasLoadAddrMisalign = hasException && exceptionVecFromRob(loadAddrMisaligned) 1297 val hasInstrAccessFault = hasException && exceptionVecFromRob(instrAccessFault) 1298 val hasLoadAccessFault = hasException && exceptionVecFromRob(loadAccessFault) 1299 val hasStoreAccessFault = hasException && exceptionVecFromRob(storeAccessFault) 1300 val hasBreakPoint = hasException && exceptionVecFromRob(breakPoint) 1301 val hasInstGuestPageFault = hasException && exceptionVecFromRob(instrGuestPageFault) 1302 val hasLoadGuestPageFault = hasException && exceptionVecFromRob(loadGuestPageFault) 1303 val hasStoreGuestPageFault = hasException && exceptionVecFromRob(storeGuestPageFault) 1304 val hasSingleStep = hasException && csrio.exception.bits.singleStep 1305 val hasTriggerFire = hasException && csrio.exception.bits.trigger.canFire 1306 val triggerFrontendHitVec = csrio.exception.bits.trigger.frontendHit 1307 val triggerMemHitVec = csrio.exception.bits.trigger.backendHit 1308 val triggerHitVec = triggerFrontendHitVec | triggerMemHitVec // Todo: update mcontrol.hit 1309 val triggerCanFireVec = csrio.exception.bits.trigger.frontendCanFire | csrio.exception.bits.trigger.backendCanFire 1310 // More than one triggers can hit at the same time, but only fire one 1311 // We select the first hit trigger to fire 1312 val triggerFireOH = PriorityEncoderOH(triggerCanFireVec) 1313 val triggerFireAction = PriorityMux(triggerFireOH, tdata1WireVec.map(_.getTriggerAction)).asUInt 1314 1315 1316 XSDebug(hasSingleStep, "Debug Mode: single step exception\n") 1317 XSDebug(hasTriggerFire, p"Debug Mode: trigger fire, frontend hit vec ${Binary(csrio.exception.bits.trigger.frontendHit.asUInt)} " + 1318 p"backend hit vec ${Binary(csrio.exception.bits.trigger.backendHit.asUInt)}\n") 1319 1320 val hasExceptionVec = csrio.exception.bits.exceptionVec 1321 val regularExceptionNO = ExceptionNO.priorities.foldRight(0.U)((i: Int, sum: UInt) => Mux(hasExceptionVec(i), i.U, sum)) 1322 val exceptionNO = Mux(hasSingleStep || hasTriggerFire, 3.U, regularExceptionNO) 1323 val causeNO = (hasIntr << (XLEN - 1)).asUInt | Mux(hasIntr, intrNO, exceptionNO) 1324 1325 val hasExceptionIntr = csrio.exception.valid 1326 1327 val hasDebugEbreakException = hasBreakPoint && ebreakEnterDebugMode 1328 val hasDebugTriggerException = hasTriggerFire && triggerFireAction === TrigActionEnum.DEBUG_MODE 1329 val hasDebugException = hasDebugEbreakException || hasDebugTriggerException || hasSingleStep 1330 val hasDebugTrap = hasDebugException || hasDebugIntr 1331 val ebreakEnterParkLoop = debugMode && hasExceptionIntr 1332 1333 XSDebug(hasExceptionIntr, "int/exc: pc %x int (%d):%x exc: (%d):%x\n", 1334 dexceptionPC, intrNO, intrVec, exceptionNO, hasExceptionVec.asUInt 1335 ) 1336 XSDebug(hasExceptionIntr, 1337 "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", 1338 dexceptionPC, 1339 mstatus, 1340 mideleg, 1341 medeleg, 1342 privilegeMode 1343 ) 1344 1345 // mtval write logic 1346 // Due to timing reasons of memExceptionVAddr, we delay the write of mtval and stval 1347 val memExceptionAddr = SignExt(csrio.memExceptionVAddr, XLEN) 1348 val memExceptionGPAddr = SignExt(csrio.memExceptionGPAddr, XLEN) 1349 val updateTval = VecInit(Seq( 1350 hasInstrPageFault, 1351 hasLoadPageFault, 1352 hasStorePageFault, 1353 hasInstrAccessFault, 1354 hasLoadAccessFault, 1355 hasStoreAccessFault, 1356 hasLoadAddrMisalign, 1357 hasStoreAddrMisalign, 1358 hasInstGuestPageFault, 1359 hasLoadGuestPageFault, 1360 hasStoreGuestPageFault, 1361 hasBreakPoint, 1362 )).asUInt.orR 1363 val updateTval_h = VecInit(Seq( 1364 hasInstGuestPageFault, 1365 hasLoadGuestPageFault, 1366 hasStoreGuestPageFault 1367 )).asUInt.orR 1368 when (RegNext(RegNext(updateTval))) { 1369 val tval = Mux( 1370 RegNext(RegNext(hasInstrPageFault || hasInstrAccessFault || hasInstGuestPageFault || hasBreakPoint)), 1371 RegNext(RegNext(Mux( 1372 csrio.exception.bits.crossPageIPFFix, 1373 SignExt(csrio.exception.bits.pc + 2.U, XLEN), 1374 iexceptionPC 1375 ))), 1376 memExceptionAddr 1377 ) 1378 // because we update tval two beats later, we can choose xtval according to the privilegeMode which has been updated 1379 when (RegNext(privilegeMode === ModeM)) { 1380 mtval := tval 1381 }.otherwise { 1382 when (virtMode){ 1383 vstval := tval 1384 }.otherwise{ 1385 stval := tval 1386 } 1387 } 1388 } 1389 1390 when(RegNext(RegNext(updateTval_h))) { 1391 val tval_tmp = Mux( 1392 RegNext(RegNext(hasInstGuestPageFault)), 1393 RegNext(RegNext(Mux( 1394 csrio.exception.bits.crossPageIPFFix, 1395 SignExt(csrio.exception.bits.gpaddr + 2.U, XLEN), 1396 iexceptionGPAddr 1397 ))), 1398 memExceptionGPAddr 1399 ) 1400 val tval = tval_tmp >> 2 1401 when(RegNext(privilegeMode === ModeM)) { 1402 mtval2 := tval 1403 }.otherwise { 1404 htval := tval 1405 } 1406 } 1407 1408 val debugTrapTarget = Mux(!isEbreak && debugMode, 0x38020808.U, 0x38020800.U) // 0x808 is when an exception occurs in debug mode prog buf exec 1409 val deleg = Mux(hasIntr, mideleg , medeleg) 1410 val hdeleg = Mux(hasIntr, hideleg, hedeleg) 1411 // val delegS = ((deleg & (1 << (causeNO & 0xf))) != 0) && (privilegeMode < ModeM); 1412 val delegS = deleg(causeNO(7,0)) && (privilegeMode < ModeM) 1413 val delegVS = virtMode && delegS && hdeleg(causeNO(7, 0)) && (privilegeMode < ModeM) 1414 val clearTval = !updateTval || hasIntr 1415 1416 val clearTval_h = !updateTval_h || hasIntr 1417 val isHyperInst = csrio.exception.bits.isHls 1418 // ctrl block will use theses later for flush 1419 val isXRetFlag = RegInit(false.B) 1420 when (DelayN(io.flush.valid, 5)) { 1421 isXRetFlag := false.B 1422 }.elsewhen (isXRet) { 1423 isXRetFlag := true.B 1424 } 1425 csrio.isXRet := isXRetFlag 1426 private val retTargetReg = RegEnable(retTarget, isXRet && !illegalRetTarget) 1427 private val illegalXret = RegEnable(illegalMret || illegalSret || illegalSModeSret || illegalVSModeSret, isXRet) 1428 1429 private val xtvec = Mux(delegS, Mux(delegVS, vstvec, stvec), mtvec) 1430 private val xtvecBase = xtvec(VAddrBits - 1, 2) 1431 // When MODE=Vectored, all synchronous exceptions into M/S mode 1432 // cause the pc to be set to the address in the BASE field, whereas 1433 // interrupts cause the pc to be set to the address in the BASE field 1434 // plus four times the interrupt cause number. 1435 private val pcFromXtvec = Cat(xtvecBase + Mux(xtvec(0) && hasIntr, causeNO(3, 0), 0.U), 0.U(2.W)) 1436 1437 // XRet sends redirect instead of Flush and isXRetFlag is true.B before redirect.valid. 1438 // ROB sends exception at T0 while CSR receives at T2. 1439 // We add a RegNext here and trapTarget is valid at T3. 1440 csrio.trapTarget := RegEnable( 1441 MuxCase(pcFromXtvec, Seq( 1442 (isXRetFlag && !illegalXret) -> retTargetReg, 1443 ((hasDebugTrap && !debugMode) || ebreakEnterParkLoop) -> debugTrapTarget 1444 )), 1445 isXRetFlag || csrio.exception.valid) 1446 1447 when(hasExceptionIntr) { 1448 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1449 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1450 val hstatusOld = WireInit(hstatus.asTypeOf(new HstatusStruct)) 1451 val hstatusNew = WireInit(hstatus.asTypeOf(new HstatusStruct)) 1452 val vsstatusOld = WireInit(vsstatus.asTypeOf(new MstatusStruct)) 1453 val vsstatusNew = WireInit(vsstatus.asTypeOf(new MstatusStruct)) 1454 val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct)) 1455 val debugModeNew = WireInit(debugMode) 1456 when(hasDebugTrap && !debugMode) { 1457 import DcsrStruct._ 1458 debugModeNew := true.B 1459 dcsrNew.prv := privilegeMode 1460 privilegeMode := ModeM 1461 when(hasDebugIntr) { 1462 dpc := iexceptionPC 1463 dcsrNew.cause := CAUSE_HALTREQ 1464 XSDebug(hasDebugIntr, "Debug Mode: Trap to %x at pc %x\n", debugTrapTarget, dpc) 1465 }.otherwise { // hasDebugException 1466 dpc := iexceptionPC // TODO: check it when hasSingleStep 1467 dcsrNew.cause := MuxCase(0.U, Seq( 1468 hasTriggerFire -> CAUSE_TRIGGER, 1469 raiseDebugException -> CAUSE_EBREAK, 1470 hasBreakPoint -> CAUSE_HALTREQ, 1471 hasSingleStep -> CAUSE_STEP 1472 )) 1473 } 1474 dcsr := dcsrNew.asUInt 1475 debugIntrEnable := false.B 1476 }.elsewhen (debugMode) { 1477 //do nothing 1478 }.elsewhen (delegVS) { 1479 vscause := (hasIntr << (XLEN-1)).asUInt | Mux(hasIntr, intrNO - 1.U, exceptionNO) 1480 vsepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC) 1481 vsstatusNew.spp := privilegeMode 1482 vsstatusNew.pie.s := vsstatusOld.ie.s 1483 vsstatusNew.ie.s := false.B 1484 when (clearTval) {vstval := 0.U} 1485 virtMode := true.B 1486 privilegeMode := ModeS 1487 }.elsewhen (delegS) { 1488 val virt = Mux(mstatusOld.mprv.asBool, mstatusOld.mpv, virtMode) 1489 // to do hld st 1490 hstatusNew.gva := (hasInstGuestPageFault || hasLoadGuestPageFault || hasStoreGuestPageFault || 1491 ((virt.asBool || isHyperInst) && ((hasException && 0.U <= exceptionNO && exceptionNO <= 7.U && exceptionNO =/= 2.U) 1492 || hasInstrPageFault || hasLoadPageFault || hasStorePageFault))) 1493 hstatusNew.spv := virtMode 1494 when(virtMode){ 1495 hstatusNew.spvp := privilegeMode 1496 } 1497 virtMode := false.B 1498 scause := causeNO 1499 sepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC) 1500 mstatusNew.spp := privilegeMode 1501 mstatusNew.pie.s := mstatusOld.ie.s 1502 mstatusNew.ie.s := false.B 1503 privilegeMode := ModeS 1504 when (clearTval) { stval := 0.U } 1505 when (clearTval_h) {htval := 0.U} 1506 }.otherwise { 1507 val virt = Mux(mstatusOld.mprv.asBool, mstatusOld.mpv, virtMode) 1508 // to do hld st 1509 mstatusNew.gva := (hasInstGuestPageFault || hasLoadGuestPageFault || hasStoreGuestPageFault || 1510 ((virt.asBool || isHyperInst) && ((hasException && 0.U <= exceptionNO && exceptionNO <= 7.U && exceptionNO =/= 2.U) 1511 || hasInstrPageFault || hasLoadPageFault || hasStorePageFault))) 1512 mstatusNew.mpv := virtMode 1513 virtMode := false.B 1514 mcause := causeNO 1515 mepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC) 1516 mstatusNew.mpp := privilegeMode 1517 mstatusNew.pie.m := mstatusOld.ie.m 1518 mstatusNew.ie.m := false.B 1519 privilegeMode := ModeM 1520 when (clearTval) { mtval := 0.U } 1521 when (clearTval_h) {mtval2 := 0.U} 1522 } 1523 mstatus := mstatusNew.asUInt 1524 vsstatus := vsstatusNew.asUInt 1525 hstatus := hstatusNew.asUInt 1526 debugMode := debugModeNew 1527 } 1528 1529 // Cache error debug support 1530 if(HasCustomCSRCacheOp){ 1531 val cache_error_decoder = Module(new CSRCacheErrorDecoder) 1532 cache_error_decoder.io.encoded_cache_error := cacheopRegs("CACHE_ERROR") 1533 } 1534 1535 // Implicit add reset values for mepc[0] and sepc[0] 1536 // TODO: rewrite mepc and sepc using a struct-like style with the LSB always being 0 1537 when (RegNext(RegNext(reset.asBool) && !reset.asBool)) { 1538 mepc := Cat(mepc(XLEN - 1, 1), 0.U(1.W)) 1539 sepc := Cat(sepc(XLEN - 1, 1), 0.U(1.W)) 1540 vsepc := Cat(vsepc(XLEN - 1, 1), 0.U(1.W)) 1541 } 1542 1543 def readWithScala(addr: Int): UInt = mapping(addr)._1 1544 1545 val difftestIntrNO = Mux(hasIntr, causeNO, 0.U) 1546 1547 // Always instantiate basic difftest modules. 1548 if (env.AlwaysBasicDiff || env.EnableDifftest) { 1549 val difftest = DifftestModule(new DiffArchEvent, delay = 3, dontCare = true) 1550 difftest.coreid := csrio.hartId 1551 difftest.valid := csrio.exception.valid 1552 difftest.interrupt := Mux(hasIntr, causeNO, 0.U) 1553 difftest.exception := Mux(hasException, causeNO, 0.U) 1554 difftest.exceptionPC := dexceptionPC 1555 if (env.EnableDifftest) { 1556 difftest.exceptionInst := csrio.exception.bits.instr 1557 } 1558 } 1559 1560 // Always instantiate basic difftest modules. 1561 if (env.AlwaysBasicDiff || env.EnableDifftest) { 1562 val difftest = DifftestModule(new DiffCSRState) 1563 difftest.coreid := csrio.hartId 1564 difftest.privilegeMode := privilegeMode 1565 difftest.mstatus := mstatus 1566 difftest.sstatus := mstatus & sstatusRmask 1567 difftest.mepc := mepc 1568 difftest.sepc := sepc 1569 difftest.mtval:= mtval 1570 difftest.stval:= stval 1571 difftest.mtvec := mtvec 1572 difftest.stvec := stvec 1573 difftest.mcause := mcause 1574 difftest.scause := scause 1575 difftest.satp := satp 1576 difftest.mip := mipReg 1577 difftest.mie := mie 1578 difftest.mscratch := mscratch 1579 difftest.sscratch := sscratch 1580 difftest.mideleg := mideleg 1581 difftest.medeleg := medeleg 1582 } 1583 1584 if (env.AlwaysBasicDiff || env.EnableDifftest) { 1585 val difftest = DifftestModule(new DiffHCSRState) 1586 difftest.coreid := csrio.hartId 1587 difftest.virtMode := virtMode 1588 difftest.mtval2 := mtval2 1589 difftest.mtinst := mtinst 1590 difftest.hstatus := hstatus 1591 difftest.hideleg := hideleg 1592 difftest.hedeleg := hedeleg 1593 difftest.hcounteren := hcounteren 1594 difftest.htval := htval 1595 difftest.htinst := htinst 1596 difftest.hgatp := hgatp 1597 difftest.vsstatus := vsstatus 1598 difftest.vstvec := vstvec 1599 difftest.vsepc := vsepc 1600 difftest.vscause := vscause 1601 difftest.vstval := vstval 1602 difftest.vsatp := vsatp 1603 difftest.vsscratch := vsscratch 1604 } 1605 1606 if(env.AlwaysBasicDiff || env.EnableDifftest) { 1607 val difftest = DifftestModule(new DiffDebugMode) 1608 difftest.coreid := csrio.hartId 1609 difftest.debugMode := debugMode 1610 difftest.dcsr := dcsr 1611 difftest.dpc := dpc 1612 difftest.dscratch0 := dscratch0 1613 difftest.dscratch1 := dscratch1 1614 } 1615 1616 if (env.AlwaysBasicDiff || env.EnableDifftest) { 1617 val difftest = DifftestModule(new DiffVecCSRState) 1618 difftest.coreid := csrio.hartId 1619 difftest.vstart := vstart 1620 difftest.vxsat := vcsr.asTypeOf(new VcsrStruct).vxsat 1621 difftest.vxrm := vcsr.asTypeOf(new VcsrStruct).vxrm 1622 difftest.vcsr := vcsr 1623 difftest.vl := vl 1624 difftest.vtype := vtype 1625 difftest.vlenb := vlenb 1626 } 1627} 1628 1629class PFEvent(implicit p: Parameters) extends XSModule with HasCSRConst { 1630 val io = IO(new Bundle { 1631 val distribute_csr = Flipped(new DistributedCSRIO()) 1632 val hpmevent = Output(Vec(29, UInt(XLEN.W))) 1633 }) 1634 1635 val w = io.distribute_csr.w 1636 1637 val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++ 1638 List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++ 1639 List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++ 1640 List.fill(5)(RegInit("hc0300c0300".U(XLEN.W))) 1641 1642 val perfEventMapping = (0 until 29).map(i => {Map( 1643 MaskedRegMap(addr = Mhpmevent3 +i, 1644 reg = perfEvents(i), 1645 wmask = "hf87fff3fcff3fcff".U(XLEN.W)) 1646 )}).fold(Map())((a,b) => a ++ b) 1647 1648 val rdata = Wire(UInt(XLEN.W)) 1649 MaskedRegMap.generate(perfEventMapping, w.bits.addr, rdata, w.valid, w.bits.data) 1650 for(i <- 0 until 29){ 1651 io.hpmevent(i) := perfEvents(i) 1652 } 1653} 1654