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