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