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