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