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