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