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