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} 122 123class VtypeStruct(implicit p: Parameters) extends XSBundle { 124 val vill = UInt(1.W) 125 val reserved = UInt((XLEN - 9).W) 126 val vma = UInt(1.W) 127 val vta = UInt(1.W) 128 val vsew = UInt(3.W) 129 val vlmul = UInt(3.W) 130} 131/* 132class CSR(cfg: FuConfig)(implicit p: Parameters) extends FuncUnit(cfg) 133 with HasCSRConst 134 with PMPMethod 135 with PMAMethod 136 with HasXSParameter 137 with SdtrigExt 138 with DebugCSR 139{ 140 val csrio = io.csrio.get 141 142 val flushPipe = Wire(Bool()) 143 144 val (valid, src1, src2, func) = ( 145 io.in.valid, 146 io.in.bits.data.src(0), 147 io.in.bits.data.imm, 148 io.in.bits.ctrl.fuOpType 149 ) 150 151 // CSR define 152 val virtMode = RegInit(false.B) 153 csrio.customCtrl.virtMode := virtMode 154 155 class Priv extends Bundle { 156 val m = Output(Bool()) 157 val h = Output(Bool()) // unused 158 val s = Output(Bool()) 159 val u = Output(Bool()) 160 } 161 162 class MstatusStruct extends Bundle { 163 val sd = Output(UInt(1.W)) 164 165 val pad1 = if (XLEN == 64 && HasHExtension) Output(UInt(23.W)) else if (XLEN == 64) Output(UInt(25.W)) else null 166 val mpv = if (XLEN == 64 && HasHExtension) Output(UInt(1.W)) else null 167 val gva = if (XLEN == 64 && HasHExtension) Output(UInt(1.W)) else null 168 val mbe = if (XLEN == 64) Output(UInt(1.W)) else null 169 val sbe = if (XLEN == 64) Output(UInt(1.W)) else null 170 val sxl = if (XLEN == 64) Output(UInt(2.W)) else null 171 val uxl = if (XLEN == 64) Output(UInt(2.W)) else null 172 val pad0 = if (XLEN == 64) Output(UInt(9.W)) else Output(UInt(8.W)) 173 174 val tsr = Output(UInt(1.W)) 175 val tw = Output(UInt(1.W)) 176 val tvm = Output(UInt(1.W)) 177 val mxr = Output(UInt(1.W)) 178 val sum = Output(UInt(1.W)) 179 val mprv = Output(UInt(1.W)) 180 val xs = Output(UInt(2.W)) 181 val fs = Output(UInt(2.W)) 182 val mpp = Output(UInt(2.W)) 183 val vs = Output(UInt(2.W)) 184 val spp = Output(UInt(1.W)) 185 val pie = new Priv 186 val ie = new Priv 187 assert(this.getWidth == XLEN) 188 189 def ube = pie.h // a little ugly 190 def ube_(r: UInt): Unit = { 191 pie.h := r(0) 192 } 193 } 194 195 class HstatusStruct extends Bundle { 196 val pad4 = if (HSXLEN == 64) Output(UInt(30.W)) else null 197 val vsxl = if (HSXLEN == 64) Output(UInt(2.W)) else null 198 val pad3 = Output(UInt(9.W)) 199 val vtsr = Output(UInt(1.W)) 200 val vtw = Output(UInt(1.W)) 201 val vtvm = Output(UInt(1.W)) 202 val pad2 = Output(UInt(2.W)) 203 val vgein = Output(UInt(6.W)) 204 val pad1 = Output(UInt(2.W)) 205 val hu = Output(UInt(1.W)) 206 val spvp = Output(UInt(1.W)) 207 val spv = Output(UInt(1.W)) 208 val gva = Output(UInt(1.W)) 209 val vsbe = Output(UInt(1.W)) 210 val pad0 = Output(UInt(5.W)) 211 assert(this.getWidth == XLEN) 212 } 213 214 class Interrupt extends Bundle { 215// val d = Output(Bool()) // Debug 216 val e = new Priv 217 val t = new Priv 218 val s = new Priv 219 } 220 221 // Debug CSRs 222 val dcsr = RegInit(UInt(32.W), DcsrStruct.init) 223 val dpc = Reg(UInt(64.W)) 224 val dscratch0 = Reg(UInt(64.W)) 225 val dscratch1 = Reg(UInt(64.W)) 226 val debugMode = RegInit(false.B) 227 val debugIntrEnable = RegInit(true.B) // debug interrupt will be handle only when debugIntrEnable 228 csrio.debugMode := debugMode 229 230 val dpcPrev = RegNext(dpc) 231 XSDebug(dpcPrev =/= dpc, "Debug Mode: dpc is altered! Current is %x, previous is %x\n", dpc, dpcPrev) 232 233 val dcsrData = Wire(new DcsrStruct) 234 dcsrData := dcsr.asTypeOf(new DcsrStruct) 235 val dcsrMask = ZeroExt(GenMask(15) | GenMask(13, 11) | GenMask(4) | GenMask(2, 0), XLEN)// Dcsr write mask 236 def dcsrUpdateSideEffect(dcsr: UInt): UInt = { 237 val dcsrOld = WireInit(dcsr.asTypeOf(new DcsrStruct)) 238 val dcsrNew = dcsr | (dcsrOld.prv(0) | dcsrOld.prv(1)).asUInt // turn 10 priv into 11 239 dcsrNew 240 } 241 // csrio.singleStep := dcsrData.step 242 csrio.customCtrl.singlestep := dcsrData.step && !debugMode 243 244 // Trigger CSRs 245 private val tselectPhy = RegInit(0.U(log2Up(TriggerNum).W)) 246 247 private val tdata1RegVec = RegInit(VecInit(Seq.fill(TriggerNum)(Tdata1Bundle.default))) 248 private val tdata2RegVec = RegInit(VecInit(Seq.fill(TriggerNum)(0.U(64.W)))) 249 private val tdata1WireVec = tdata1RegVec.map(_.asTypeOf(new Tdata1Bundle)) 250 private val tdata2WireVec = tdata2RegVec 251 private val tdata1Selected = tdata1RegVec(tselectPhy).asTypeOf(new Tdata1Bundle) 252 private val tdata2Selected = tdata2RegVec(tselectPhy) 253 private val newTriggerChainVec = UIntToOH(tselectPhy, TriggerNum).asBools | tdata1WireVec.map(_.data.asTypeOf(new MControlData).chain) 254 private val newTriggerChainIsLegal = TriggerCheckChainLegal(newTriggerChainVec, TriggerChainMaxLength) 255 val tinfo = RegInit((BigInt(1) << TrigTypeEnum.MCONTROL.litValue.toInt).U(XLEN.W)) // This value should be 4.U 256 257 258 def WriteTselect(wdata: UInt) = { 259 Mux(wdata < TriggerNum.U, wdata(log2Up(TriggerNum) - 1, 0), tselectPhy) 260 } 261 262 def GenTdataDistribute(tdata1: Tdata1Bundle, tdata2: UInt): MatchTriggerIO = { 263 val res = Wire(new MatchTriggerIO) 264 val mcontrol: MControlData = WireInit(tdata1.data.asTypeOf(new MControlData)) 265 res.matchType := mcontrol.match_.asUInt 266 res.select := mcontrol.select 267 res.timing := mcontrol.timing 268 res.action := mcontrol.action.asUInt 269 res.chain := mcontrol.chain 270 res.execute := mcontrol.execute 271 res.load := mcontrol.load 272 res.store := mcontrol.store 273 res.tdata2 := tdata2 274 res 275 } 276 277 csrio.customCtrl.frontend_trigger.tUpdate.bits.addr := tselectPhy 278 csrio.customCtrl.mem_trigger.tUpdate.bits.addr := tselectPhy 279 csrio.customCtrl.frontend_trigger.tUpdate.bits.tdata := GenTdataDistribute(tdata1Selected, tdata2Selected) 280 csrio.customCtrl.mem_trigger.tUpdate.bits.tdata := GenTdataDistribute(tdata1Selected, tdata2Selected) 281 282 // Machine-Level CSRs 283 // mtvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1 284 val mtvecMask = ~(0x2.U(XLEN.W)) 285 val mtvec = RegInit(UInt(XLEN.W), 0.U) 286 val mcounteren = RegInit(UInt(XLEN.W), 0.U) 287 // Currently, XiangShan don't support Unprivileged Counter/Timers CSRs ("Zicntr" and "Zihpm") 288 val mcounterenMask = 0.U(XLEN.W) 289 val mcause = RegInit(UInt(XLEN.W), 0.U) 290 val mtval = RegInit(UInt(XLEN.W), 0.U) 291 val mtval2 = RegInit(UInt(XLEN.W), 0.U) 292 val mtinst = RegInit(UInt(XLEN.W), 0.U) 293 val mepc = RegInit(UInt(XLEN.W), 0.U) 294 // Page 36 in riscv-priv: The low bit of mepc (mepc[0]) is always zero. 295 val mepcMask = ~(0x1.U(XLEN.W)) 296 297 val mie = RegInit(0.U(XLEN.W)) 298 val mipWire = WireInit(0.U.asTypeOf(new Interrupt)) 299 val mipReg = RegInit(0.U(XLEN.W)) 300 val mipMask = ZeroExt(Array( 301 1, // SSIP 302 2, // VSSIP 303 3, // MSIP 304 5, // STIP 305 6, // VSTIP 306 7, // MTIP 307 9, // SEIP 308 10, // VSEIP 309 11, // MEIP 310 12, // SGEIP 311 ).map(GenMask(_)).reduce(_ | _), XLEN) 312 val mip = (mipWire.asUInt | mipReg).asTypeOf(new Interrupt) 313 314 val mip_mie_WMask_H = if(HasHExtension){((1 << 2) | (1 << 6) | (1 << 10) | (1 << 12)).U(XLEN.W)}else{0.U(XLEN.W)} 315 val vssip_Mask = (1 << 2).U(XLEN.W) 316 317 val mipWMask = vssip_Mask | ((1 << 9) | (1 << 5) | (1 << 1)).U(XLEN.W) 318 val mieWMask = mip_mie_WMask_H | "haaa".U(XLEN.W) 319 320 def getMisaMxl(mxl: BigInt): BigInt = mxl << (XLEN - 2) 321 def getMisaExt(ext: Char): Long = 1 << (ext.toInt - 'a'.toInt) 322 var extList = List('a', 's', 'i', 'u') 323 if (HasMExtension) { extList = extList :+ 'm' } 324 if (HasCExtension) { extList = extList :+ 'c' } 325 if (HasHExtension) { extList = extList :+ 'h' } 326 if (HasFPU) { extList = extList ++ List('f', 'd') } 327 if (HasVPU) { extList = extList :+ 'v' } 328 val misaInitVal = getMisaMxl(2) | extList.foldLeft(0L)((sum, i) => sum | getMisaExt(i)) //"h8000000000141185".U 329 val misa = RegInit(UInt(XLEN.W), misaInitVal.U) 330 println(s"[CSR] supported isa ext: $extList") 331 332 // MXL = 2 | 0 | EXT = b 00 0000 0100 0001 0001 0000 0101 333 // (XLEN-1, XLEN-2) | |(25, 0) ZY XWVU TSRQ PONM LKJI HGFE DCBA 334 335 // Machine Configuration 336 val menvcfg = RegInit(UInt(XLEN.W), 0.U) 337 338 val mvendorid = RegInit(UInt(XLEN.W), 0.U) // this is a non-commercial implementation 339 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 340 val mimpid = RegInit(UInt(XLEN.W), 0.U) // provides a unique encoding of the version of the processor implementation 341 val mhartid = Reg(UInt(XLEN.W)) // the hardware thread running the code 342 when (RegNext(RegNext(reset.asBool) && !reset.asBool)) { 343 mhartid := csrio.hartId 344 } 345 val mconfigptr = RegInit(UInt(XLEN.W), 0.U) // the read-only pointer pointing to the platform config structure, 0 for not supported. 346 val mstatus = RegInit("ha00002200".U(XLEN.W)) 347 348 // mstatus Value Table 349 // | sd | Read Only 350 // | pad1 | WPRI 351 // | sxl | hardlinked to 10, use 00 to pass xv6 test 352 // | uxl | hardlinked to 10 353 // | pad0 | 354 // | tsr | 355 // | tw | 356 // | tvm | 357 // | mxr | 358 // | sum | 359 // | mprv | 360 // | xs | 00 | 361 // | fs | 01 | 362 // | mpp | 00 | 363 // | vs | 01 | 364 // | spp | 0 | 365 // | pie | 0000 | pie.h is used as UBE 366 // | ie | 0000 | uie hardlinked to 0, as N ext is not implemented 367 368 val mstatusStruct = mstatus.asTypeOf(new MstatusStruct) 369 def mstatusUpdateSideEffect(mstatus: UInt): UInt = { 370 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 371 // Cat(sd, other) 372 val mstatusNew = Cat( 373 mstatusOld.xs === ContextStatus.dirty || mstatusOld.fs === ContextStatus.dirty || mstatusOld.vs === ContextStatus.dirty, 374 mstatus(XLEN-2, 0) 375 ) 376 mstatusNew 377 } 378 def vsstatusUpdateSideEffect(vsstatus: UInt): UInt = { 379 val vsstatusOld = WireInit(vsstatus.asTypeOf(new MstatusStruct)) 380 val vsstatusNew = Cat(vsstatusOld.xs === "b11".U || vsstatusOld.fs === "b11".U, vsstatus(XLEN-2, 0)) 381 vsstatusNew 382 } 383 val mstatusWMask = (~ZeroExt(( 384 GenMask(63) | // SD is read-only 385 (if(HasHExtension) 386 GenMask(62, 40) // WPRI 387 else 388 GenMask(62, 38) )| // WPRI 389 GenMask(35, 32) | // SXL and UXL cannot be changed 390 GenMask(31, 23) | // WPRI 391 GenMask(16, 15) | // XS is read-only 392 GenMask(6) | // UBE, always little-endian (0) 393 GenMask(4) | // WPRI 394 GenMask(2) | // WPRI 395 GenMask(0) // WPRI 396 ), 64)).asUInt 397 398 val medeleg = RegInit(UInt(XLEN.W), 0.U) 399 val midelegInit = if(HasHExtension){((1 << 12) | (1 << 10) | (1 << 6) | (1 << 2)).U}else{0.U} 400 val medelegWMask = if(HasHExtension) { 401 "hf0b7ff".U(XLEN.W) 402 }else { 403 "hb3ff".U(XLEN.W) 404 } 405 406 407 val mideleg = RegInit(UInt(XLEN.W), midelegInit) 408 val mscratch = RegInit(UInt(XLEN.W), 0.U) 409 410 val midelegWMask = "h222".U(XLEN.W) 411 // PMP Mapping 412 val pmp = Wire(Vec(NumPMP, new PMPEntry())) // just used for method parameter 413 val pma = Wire(Vec(NumPMA, new PMPEntry())) // just used for method parameter 414 val pmpMapping = pmp_gen_mapping(pmp_init, NumPMP, PmpcfgBase, PmpaddrBase, pmp) 415 val pmaMapping = pmp_gen_mapping(pma_init, NumPMA, PmacfgBase, PmaaddrBase, pma) 416 // !WARNNING: pmp and pma CSRs are not checked in difftest. 417 418 // Supervisor-Level CSRs 419 420 val sstatusWNmask: BigInt = ( 421 BigIntGenMask(63) | // SD is read-only 422 BigIntGenMask(62, 34) | // WPRI 423 BigIntGenMask(33, 32) | // UXL is hard-wired to 64(b10) 424 BigIntGenMask(31, 20) | // WPRI 425 BigIntGenMask(17) | // WPRI 426 BigIntGenMask(16, 15) | // XS is read-only to zero 427 BigIntGenMask(12, 11) | // WPRI 428 BigIntGenMask(7) | // WPRI 429 BigIntGenMask(6) | // UBE is always little-endian (0) 430 BigIntGenMask(4, 2) | // WPRI 431 BigIntGenMask(0) // WPRI 432 ) 433 434 val sstatusWmask = BigIntNot(sstatusWNmask).U(XLEN.W) 435 val sstatusRmask = ( 436 BigIntGenMask(63) | // SD 437 BigIntGenMask(33, 32) | // UXL 438 BigIntGenMask(19) | // MXR 439 BigIntGenMask(18) | // SUM 440 BigIntGenMask(16, 15) | // XS 441 BigIntGenMask(14, 13) | // FS 442 BigIntGenMask(10, 9 ) | // VS 443 BigIntGenMask(8) | // SPP 444 BigIntGenMask(6) | // UBE: hard wired to 0 445 BigIntGenMask(5) | // SPIE 446 BigIntGenMask(1) 447 ).U(XLEN.W) 448 449 println(s"sstatusWNmask: 0x${sstatusWNmask.toString(16)}") 450 println(s"sstatusWmask: 0x${sstatusWmask.litValue.toString(16)}") 451 println(s"sstatusRmask: 0x${sstatusRmask.litValue.toString(16)}") 452 453 // stvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1 454 val stvecMask = ~(0x2.U(XLEN.W)) 455 val stvec = RegInit(UInt(XLEN.W), 0.U) 456 // val sie = RegInit(0.U(XLEN.W)) 457 val sieMask = "h222".U & mideleg 458 val sipMask = "h222".U & mideleg 459 val sipWMask = "h2".U(XLEN.W) // ssip is writeable in smode 460 val satp = if(EnbaleTlbDebug) RegInit(UInt(XLEN.W), "h8000000000087fbe".U) else RegInit(0.U(XLEN.W)) 461 // val satp = RegInit(UInt(XLEN.W), "h8000000000087fbe".U) // only use for tlb naive debug 462 // val satpMask = "h80000fffffffffff".U(XLEN.W) // disable asid, mode can only be 8 / 0 463 // TODO: use config to control the length of asid 464 // val satpMask = "h8fffffffffffffff".U(XLEN.W) // enable asid, mode can only be 8 / 0 465 val satpMask = Cat("h8".U(Satp_Mode_len.W), satp_part_wmask(Satp_Asid_len, AsidLength), satp_part_wmask(Satp_Addr_len, PAddrBits-12)) 466 val sepc = RegInit(UInt(XLEN.W), 0.U) 467 // Page 60 in riscv-priv: The low bit of sepc (sepc[0]) is always zero. 468 val sepcMask = ~(0x1.U(XLEN.W)) 469 val scause = RegInit(UInt(XLEN.W), 0.U) 470 val stval = RegInit(UInt(XLEN.W), 0.U) 471 val sscratch = RegInit(UInt(XLEN.W), 0.U) 472 val scounteren = RegInit(UInt(XLEN.W), 0.U) 473 val senvcfg = RegInit(UInt(XLEN.W), 0.U) // !WARNING: there is no logic about this CSR. 474 // Currently, XiangShan don't support Unprivileged Counter/Timers CSRs ("Zicntr" and "Zihpm") 475 val scounterenMask = 0.U(XLEN.W) 476 477 // sbpctl 478 // Bits 0-7: {LOOP, RAS, SC, TAGE, BIM, BTB, uBTB} 479 val sbpctl = RegInit(UInt(XLEN.W), "h7f".U) 480 csrio.customCtrl.bp_ctrl.ubtb_enable := sbpctl(0) 481 csrio.customCtrl.bp_ctrl.btb_enable := sbpctl(1) 482 csrio.customCtrl.bp_ctrl.bim_enable := sbpctl(2) 483 csrio.customCtrl.bp_ctrl.tage_enable := sbpctl(3) 484 csrio.customCtrl.bp_ctrl.sc_enable := sbpctl(4) 485 csrio.customCtrl.bp_ctrl.ras_enable := sbpctl(5) 486 csrio.customCtrl.bp_ctrl.loop_enable := sbpctl(6) 487 488 // spfctl Bit 0: L1I Cache Prefetcher Enable 489 // spfctl Bit 1: L2Cache Prefetcher Enable 490 // spfctl Bit 2: L1D Cache Prefetcher Enable 491 // spfctl Bit 3: L1D train prefetch on hit 492 // spfctl Bit 4: L1D prefetch enable agt 493 // spfctl Bit 5: L1D prefetch enable pht 494 // spfctl Bit [9:6]: L1D prefetch active page threshold 495 // spfctl Bit [15:10]: L1D prefetch active page stride 496 // turn off L2 BOP, turn on L1 SMS by default 497 val spfctl = RegInit(UInt(XLEN.W), Seq( 498 0 << 17, // L2 pf store only [17] init: false 499 1 << 16, // L1D pf enable stride [16] init: true 500 30 << 10, // L1D active page stride [15:10] init: 30 501 12 << 6, // L1D active page threshold [9:6] init: 12 502 1 << 5, // L1D enable pht [5] init: true 503 1 << 4, // L1D enable agt [4] init: true 504 0 << 3, // L1D train on hit [3] init: false 505 1 << 2, // L1D pf enable [2] init: true 506 1 << 1, // L2 pf enable [1] init: true 507 1 << 0, // L1I pf enable [0] init: true 508 ).reduce(_|_).U(XLEN.W)) 509 csrio.customCtrl.l1I_pf_enable := spfctl(0) 510 csrio.customCtrl.l2_pf_enable := spfctl(1) 511 csrio.customCtrl.l1D_pf_enable := spfctl(2) 512 csrio.customCtrl.l1D_pf_train_on_hit := spfctl(3) 513 csrio.customCtrl.l1D_pf_enable_agt := spfctl(4) 514 csrio.customCtrl.l1D_pf_enable_pht := spfctl(5) 515 csrio.customCtrl.l1D_pf_active_threshold := spfctl(9, 6) 516 csrio.customCtrl.l1D_pf_active_stride := spfctl(15, 10) 517 csrio.customCtrl.l1D_pf_enable_stride := spfctl(16) 518 csrio.customCtrl.l2_pf_store_only := spfctl(17) 519 520 // slvpredctl: load violation predict settings 521 // Default reset period: 2^16 522 // Why this number: reset more frequently while keeping the overhead low 523 // Overhead: extra two redirections in every 64K cycles => ~0.1% overhead 524 val slvpredctl = Reg(UInt(XLEN.W)) 525 when(reset.asBool) { 526 slvpredctl := Constantin.createRecord("slvpredctl", 0x60) 527 } 528 csrio.customCtrl.lvpred_disable := slvpredctl(0) 529 csrio.customCtrl.no_spec_load := slvpredctl(1) 530 csrio.customCtrl.storeset_wait_store := slvpredctl(2) 531 csrio.customCtrl.storeset_no_fast_wakeup := slvpredctl(3) 532 csrio.customCtrl.lvpred_timeout := slvpredctl(8, 4) 533 534 // smblockctl: memory block configurations 535 // +------------------------+---+---+---+----+----+-----+--------+ 536 // |XLEN-1 10| 9 | 8 | 7 | 6 | 5 | 4 |3 0| 537 // +------------------------+---+---+---+----+----+-----+--------+ 538 // | Reserved | L | S | O | CE | SP | LVC | Th | 539 // +------------------------+---+---+---+----+----+-----+--------+ 540 // Description: 541 // Bit 3-0 : Store buffer flush threshold (Th). 542 // Bit 4 : Enable load violation check after reset (LVC). 543 // Bit 5 : Enable soft-prefetch after reset (SP). 544 // Bit 6 : Enable cache error after reset (CE). 545 // Bit 7 : Enable uncache write outstanding (O). 546 // Bit 8 : Enable unaligned store (S). 547 // Bit 9 : Enable unaligned load (L). 548 // Others : Reserved. 549 550 val smblockctl_init_val = 551 (0xf & StoreBufferThreshold) | 552 (EnableLdVioCheckAfterReset.toInt << 4) | 553 (EnableSoftPrefetchAfterReset.toInt << 5) | 554 (EnableCacheErrorAfterReset.toInt << 6) | 555 (EnableUncacheWriteOutstanding.toInt << 7) | 556 (EnableHardwareStoreMisalign.toInt << 8) | 557 (EnableHardwareLoadMisalign.toInt << 9) 558 val smblockctl = RegInit(UInt(XLEN.W), smblockctl_init_val.U) 559 csrio.customCtrl.sbuffer_threshold := smblockctl(3, 0) 560 // bits 4: enable load load violation check 561 csrio.customCtrl.ldld_vio_check_enable := smblockctl(4) 562 csrio.customCtrl.soft_prefetch_enable := smblockctl(5) 563 csrio.customCtrl.cache_error_enable := smblockctl(6) 564 csrio.customCtrl.uncache_write_outstanding_enable := smblockctl(7) 565 csrio.customCtrl.hd_misalign_st_enable := smblockctl(8) 566 csrio.customCtrl.hd_misalign_ld_enable := smblockctl(9) 567 568 println("CSR smblockctl init value:") 569 println(" Store buffer replace threshold: " + StoreBufferThreshold) 570 println(" Enable ld-ld vio check after reset: " + EnableLdVioCheckAfterReset) 571 println(" Enable soft prefetch after reset: " + EnableSoftPrefetchAfterReset) 572 println(" Enable cache error after reset: " + EnableCacheErrorAfterReset) 573 println(" Enable uncache write outstanding: " + EnableUncacheWriteOutstanding) 574 println(" Enable unaligned store: " + EnableHardwareStoreMisalign) 575 println(" Enable unaligned load: " + EnableHardwareLoadMisalign) 576 577 val srnctl = RegInit(UInt(XLEN.W), "h7".U) 578 csrio.customCtrl.fusion_enable := srnctl(0) 579 csrio.customCtrl.wfi_enable := srnctl(2) 580 581 // Hypervisor CSRs 582 val hstatusWMask = "h7003c0".U(XLEN.W) 583 // hstatus: vtsr, vtw, vtvm, hu, spvp, spv, gva, 584 val hstatus = RegInit("h200000000".U(XLEN.W)) 585 val hstatusStruct = hstatus.asTypeOf(new HstatusStruct) 586 val hedeleg = RegInit(UInt(XLEN.W), 0.U) 587 val hideleg = RegInit(UInt(XLEN.W), 0.U) 588 val hidelegRMask = mideleg 589 val hidelegWMask = ((1 << 10) | (1 << 6) | (1 << 2)).U(XLEN.W) 590 val hgeie = RegInit(UInt(XLEN.W), 0.U) 591 val htval = RegInit(UInt(XLEN.W), 0.U) 592 // hvip hip hie is part of mip or mie 593 val hvipMask = ((1 << 10) | (1 << 6) | (1 << 2)).U(XLEN.W) 594 val hipRMask = (((1 << 12).U | hvipMask) & mideleg) 595 val hipWMask = ((1 << 2).U & mideleg)// vssip 596 val hieMask = hipRMask 597 val htinst = RegInit(UInt(XLEN.W), 0.U) 598 val hgeip = RegInit(UInt(XLEN.W), 0.U) 599 val henvcfg = RegInit(UInt(XLEN.W), 0.U) 600 val hgatp = RegInit(UInt(XLEN.W), 0.U) 601 val hgatpMask = Cat("h8".U(Hgatp_Mode_len.W), satp_part_wmask(Hgatp_Vmid_len, VmidLength), satp_part_wmask(Hgatp_Addr_len, PAddrBits-12)) 602 // val htimedelta = RegInit(UInt(XLEN.W), 0.U) 603 val hcounteren = RegInit(UInt(XLEN.W), 0.U) 604 // Currently, XiangShan don't support Unprivileged Counter/Timers CSRs ("Zicntr" and "Zihpm") 605 val hcounterenMask = 0.U(XLEN.W) 606 607 val vsstatus = RegInit("h200002000".U(XLEN.W)) 608 val vsstatusStruct = vsstatus.asTypeOf(new MstatusStruct) 609 //vsie vsip 610 val vsMask = ((1 << 10) | (1 << 6) | (1 << 2)).U(XLEN.W) 611 val vsip_ie_Mask = ZeroExt((hideleg & mideleg & vsMask), XLEN) 612 val vsip_WMask = ZeroExt((hideleg & mideleg & vssip_Mask), XLEN) 613 val vstvec = RegInit(UInt(XLEN.W), 0.U) 614 val vsscratch = RegInit(UInt(XLEN.W), 0.U) 615 val vsepc = RegInit(UInt(XLEN.W), 0.U) 616 val vscause = RegInit(UInt(XLEN.W), 0.U) 617 val vstval = RegInit(UInt(XLEN.W), 0.U) 618 val vsatp = RegInit(UInt(XLEN.W), 0.U) 619 val tlbBundle = Wire(new TlbCsrBundle) 620 tlbBundle.satp.apply(satp) 621 tlbBundle.vsatp.apply(vsatp) 622 tlbBundle.hgatp.apply(hgatp) 623 csrio.tlb := tlbBundle 624 625 // User-Level CSRs 626 val uepc = Reg(UInt(XLEN.W)) 627 628 // fcsr 629 class FcsrStruct extends Bundle { 630 val reserved = UInt((XLEN-3-5).W) 631 val frm = UInt(3.W) 632 val fflags = UInt(5.W) 633 assert(this.getWidth == XLEN) 634 } 635 val fcsr = RegInit(0.U(XLEN.W)) 636 // set mstatus->sd and mstatus->fs when true 637 val csrw_dirty_fp_state = WireInit(false.B) 638 639 def frm_wfn(wdata: UInt): UInt = { 640 val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct)) 641 csrw_dirty_fp_state := true.B 642 fcsrOld.frm := wdata(2,0) 643 fcsrOld.asUInt 644 } 645 def frm_rfn(rdata: UInt): UInt = rdata(7,5) 646 647 def fflags_wfn(update: Boolean)(wdata: UInt): UInt = { 648 val fcsrOld = fcsr.asTypeOf(new FcsrStruct) 649 val fcsrNew = WireInit(fcsrOld) 650 if (update) { 651 fcsrNew.fflags := wdata(4,0) | fcsrOld.fflags 652 } else { 653 fcsrNew.fflags := wdata(4,0) 654 } 655 fcsrNew.asUInt 656 } 657 def fflags_rfn(rdata:UInt): UInt = rdata(4,0) 658 659 def fcsr_wfn(wdata: UInt): UInt = { 660 val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct)) 661 csrw_dirty_fp_state := true.B 662 Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags) 663 } 664 665 val fcsrMapping = Map( 666 MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn(update = false), rfn = fflags_rfn), 667 MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn), 668 MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn) 669 ) 670 671 // Vector extension CSRs 672 val vstart = RegInit(0.U(XLEN.W)) 673 val vcsr = RegInit(0.U(XLEN.W)) 674 val vl = Reg(UInt(XLEN.W)) 675 val vtype = Reg(UInt(XLEN.W)) 676 val vlenb = RegInit(VDataBytes.U(XLEN.W)) 677 678 // set mstatus->sd and mstatus->vs when true 679 val csrw_dirty_vs_state = WireInit(false.B) 680 681 // vcsr is mapped to vxrm and vxsat 682 class VcsrStruct extends Bundle { 683 val reserved = UInt((XLEN-3).W) 684 val vxrm = UInt(2.W) 685 val vxsat = UInt(1.W) 686 assert(this.getWidth == XLEN) 687 } 688 689 def vxrm_wfn(wdata: UInt): UInt = { 690 val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct)) 691 csrw_dirty_vs_state := true.B 692 vcsrOld.vxrm := wdata(1,0) 693 vcsrOld.asUInt 694 } 695 def vxrm_rfn(rdata: UInt): UInt = rdata(2,1) 696 697 def vxsat_wfn(update: Boolean)(wdata: UInt): UInt = { 698 val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct)) 699 val vcsrNew = WireInit(vcsrOld) 700 csrw_dirty_vs_state := true.B 701 if (update) { 702 vcsrNew.vxsat := wdata(0) | vcsrOld.vxsat 703 } else { 704 vcsrNew.vxsat := wdata(0) 705 } 706 vcsrNew.asUInt 707 } 708 def vxsat_rfn(rdata: UInt): UInt = rdata(0) 709 710 def vcsr_wfn(wdata: UInt): UInt = { 711 val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct)) 712 csrw_dirty_vs_state := true.B 713 vcsrOld.vxrm := wdata.asTypeOf(vcsrOld).vxrm 714 vcsrOld.vxsat := wdata.asTypeOf(vcsrOld).vxsat 715 vcsrOld.asUInt 716 } 717 718 val vcsrMapping = Map( 719 MaskedRegMap(Vstart, vstart), 720 MaskedRegMap(Vxrm, vcsr, wfn = vxrm_wfn, rfn = vxrm_rfn), 721 MaskedRegMap(Vxsat, vcsr, wfn = vxsat_wfn(false), rfn = vxsat_rfn), 722 MaskedRegMap(Vcsr, vcsr, wfn = vcsr_wfn), 723 MaskedRegMap(Vl, vl), 724 MaskedRegMap(Vtype, vtype), 725 MaskedRegMap(Vlenb, vlenb), 726 ) 727 728 // Hart Privilege Mode 729 val privilegeMode = RegInit(UInt(2.W), ModeM) 730 731 //val perfEventscounten = List.fill(nrPerfCnts)(RegInit(false(Bool()))) 732 // Perf Counter 733 val nrPerfCnts = 29 // 3...31 734 val privilegeModeOH = UIntToOH(privilegeMode) 735 val perfEventscounten = RegInit(0.U.asTypeOf(Vec(nrPerfCnts, Bool()))) 736 val perfCnts = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W))) 737 val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++ 738 List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++ 739 List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++ 740 List.fill(5)(RegInit("hc0300c0300".U(XLEN.W))) 741 for (i <-0 until nrPerfCnts) { 742 perfEventscounten(i) := (perfEvents(i)(63,60) & privilegeModeOH).orR 743 } 744 745 val hpmEvents = Wire(Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent)) 746 for (i <- 0 until numPCntHc * coreParams.L2NBanks) { 747 hpmEvents(i) := csrio.perf.perfEventsHc(i) 748 } 749 750 // print perfEvents 751 val allPerfEvents = hpmEvents.map(x => (s"Hc", x.value)) 752 if (printEventCoding) { 753 for (((name, inc), i) <- allPerfEvents.zipWithIndex) { 754 println("CSR perfEvents Set", name, inc, i) 755 } 756 } 757 758 val csrevents = perfEvents.slice(24, 29) 759 val hpm_hc = HPerfMonitor(csrevents, hpmEvents) 760 val mcountinhibit = RegInit(0.U(XLEN.W)) 761 val mcycle = RegInit(0.U(XLEN.W)) 762 mcycle := mcycle + 1.U 763 val minstret = RegInit(0.U(XLEN.W)) 764 val perf_events = csrio.perf.perfEventsFrontend ++ 765 csrio.perf.perfEventsBackend ++ 766 csrio.perf.perfEventsLsu ++ 767 hpm_hc.getPerf 768 minstret := minstret + RegNext(csrio.perf.retiredInstr) 769 for(i <- 0 until 29){ 770 perfCnts(i) := Mux(mcountinhibit(i+3) | !perfEventscounten(i), perfCnts(i), perfCnts(i) + perf_events(i).value) 771 } 772 773 // CSR reg map 774 val basicPrivMapping = Map( 775 776 // Unprivileged Floating-Point CSRs 777 // Has been mapped above 778 779 // TODO: support Unprivileged Counter/Timers CSRs ("Zicntr" and "Zihpm") 780 // Unprivileged Counter/Timers 781 MaskedRegMap(Cycle, mcycle), 782 // We don't support read time CSR. 783 // MaskedRegMap(Time, mtime), 784 MaskedRegMap(Instret, minstret), 785 786 //--- Supervisor Trap Setup --- 787 MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask), 788 // MaskedRegMap(Sedeleg, Sedeleg), 789 // MaskedRegMap(Sideleg, Sideleg), 790 MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask), 791 MaskedRegMap(Stvec, stvec, stvecMask, MaskedRegMap.NoSideEffect, stvecMask), 792 MaskedRegMap(Scounteren, scounteren, scounterenMask), 793 794 //--- Supervisor Configuration --- 795 MaskedRegMap(Senvcfg, senvcfg), 796 797 //--- Supervisor Trap Handling --- 798 MaskedRegMap(Sscratch, sscratch), 799 MaskedRegMap(Sepc, sepc, sepcMask, MaskedRegMap.NoSideEffect, sepcMask), 800 MaskedRegMap(Scause, scause), 801 MaskedRegMap(Stval, stval), 802 MaskedRegMap(Sip, mipReg.asUInt, sipWMask, MaskedRegMap.NoSideEffect, sipMask, x => (mipWire.asUInt | x) & sipMask), 803 804 //--- Supervisor Protection and Translation --- 805 MaskedRegMap(Satp, satp, satpMask, MaskedRegMap.NoSideEffect, satpMask), 806 807 //--- Supervisor Custom Read/Write Registers 808 MaskedRegMap(Sbpctl, sbpctl), 809 MaskedRegMap(Spfctl, spfctl), 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} 1642class PFEvent(implicit p: Parameters) extends XSModule { 1643 val io = IO(new Bundle { 1644 val distribute_csr = Flipped(new DistributedCSRIO()) 1645 val hpmevent = Output(Vec(29, UInt(XLEN.W))) 1646 }) 1647 1648 val w = io.distribute_csr.w 1649 1650 val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++ 1651 List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++ 1652 List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++ 1653 List.fill(5)(RegInit("hc0300c0300".U(XLEN.W))) 1654 1655 val perfEventMapping = (0 until 29).map(i => {Map( 1656 MaskedRegMap(addr = CSRs.mhpmevent3 + i, 1657 reg = perfEvents(i), 1658 wmask = "hf87fff3fcff3fcff".U(XLEN.W)) 1659 )}).fold(Map())((a,b) => a ++ b) 1660 1661 val rdata = Wire(UInt(XLEN.W)) 1662 MaskedRegMap.generate(perfEventMapping, w.bits.addr, rdata, w.valid, w.bits.data) 1663 for(i <- 0 until 29){ 1664 io.hpmevent(i) := perfEvents(i) 1665 } 1666} 1667*/ 1668