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