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