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 // from outside cpu,externalInterrupt 122 val externalInterrupt = new ExternalInterruptIO 123 // TLB 124 val tlb = Output(new TlbCsrBundle) 125 // Debug Mode 126 // val singleStep = Output(Bool()) 127 val debugMode = Output(Bool()) 128 // to Fence to disable sfence 129 val disableSfence = Output(Bool()) 130 // Custom microarchiture ctrl signal 131 val customCtrl = Output(new CustomCSRCtrlIO) 132 // distributed csr write 133 val distributedUpdate = Vec(2, Flipped(new DistributedCSRUpdateReq)) 134} 135 136class CSR(implicit p: Parameters) extends FunctionUnit with HasCSRConst with PMPMethod with PMAMethod with HasTriggerConst 137{ 138 val csrio = IO(new CSRFileIO) 139 140 val cfIn = io.in.bits.uop.cf 141 val cfOut = Wire(new CtrlFlow) 142 cfOut := cfIn 143 val flushPipe = Wire(Bool()) 144 145 val (valid, src1, src2, func) = ( 146 io.in.valid, 147 io.in.bits.src(0), 148 io.in.bits.uop.ctrl.imm, 149 io.in.bits.uop.ctrl.fuOpType 150 ) 151 152 // CSR define 153 154 class Priv extends Bundle { 155 val m = Output(Bool()) 156 val h = Output(Bool()) 157 val s = Output(Bool()) 158 val u = Output(Bool()) 159 } 160 161 val csrNotImplemented = RegInit(UInt(XLEN.W), 0.U) 162 163 class DcsrStruct extends Bundle { 164 val debugver = Output(UInt(4.W)) // 28 165 val pad1 = Output(UInt(10.W))// 18 166 val ebreakvs = Output(Bool()) // 17 reserved for Hypervisor debug 167 val ebreakvu = Output(Bool()) // 16 reserved for Hypervisor debug 168 val ebreakm = Output(Bool()) // 15 169 val pad0 = Output(Bool()) // 14 ebreakh has been removed 170 val ebreaks = Output(Bool()) // 13 171 val ebreaku = Output(Bool()) // 12 172 val stepie = Output(Bool()) // 11 173 val stopcount = Output(Bool()) // 10 174 val stoptime = Output(Bool()) // 9 175 val cause = Output(UInt(3.W)) // 6 176 val v = Output(Bool()) // 5 177 val mprven = Output(Bool()) // 4 178 val nmip = Output(Bool()) // 3 179 val step = Output(Bool()) // 2 180 val prv = Output(UInt(2.W)) // 0 181 } 182 183 object DcsrStruct extends DcsrStruct { 184 private def debugver_offset = 28 185 private def stopcount_offset = 10 186 private def stoptime_offset = 9 187 private def mprven_offset = 5 188 private def prv_offset = 0 189 def init: UInt = ( 190 (4L << debugver_offset) | /* Debug implementation as it described in 0.13 draft */ 191 (0L << stopcount_offset) | /* Stop count updating has not been supported */ 192 (0L << stoptime_offset) | /* Stop time updating has not been supported */ 193 (0L << mprven_offset) | /* Whether use mstatus.perven mprven */ 194 (3L << prv_offset) /* Hart was operating in Privilege M when Debug Mode was entered */ 195 ).U 196 } 197 require(new DcsrStruct().getWidth == 32) 198 199 class MstatusStruct extends Bundle { 200 val sd = Output(UInt(1.W)) 201 202 val pad1 = if (XLEN == 64) Output(UInt(25.W)) else null 203 val mbe = if (XLEN == 64) Output(UInt(1.W)) else null 204 val sbe = if (XLEN == 64) Output(UInt(1.W)) else null 205 val sxl = if (XLEN == 64) Output(UInt(2.W)) else null 206 val uxl = if (XLEN == 64) Output(UInt(2.W)) else null 207 val pad0 = if (XLEN == 64) Output(UInt(9.W)) else Output(UInt(8.W)) 208 209 val tsr = Output(UInt(1.W)) 210 val tw = Output(UInt(1.W)) 211 val tvm = Output(UInt(1.W)) 212 val mxr = Output(UInt(1.W)) 213 val sum = Output(UInt(1.W)) 214 val mprv = Output(UInt(1.W)) 215 val xs = Output(UInt(2.W)) 216 val fs = Output(UInt(2.W)) 217 val mpp = Output(UInt(2.W)) 218 val hpp = Output(UInt(2.W)) 219 val spp = Output(UInt(1.W)) 220 val pie = new Priv 221 val ie = new Priv 222 assert(this.getWidth == XLEN) 223 224 def ube = pie.h // a little ugly 225 def ube_(r: UInt): Unit = { 226 pie.h := r(0) 227 } 228 } 229 230 class Interrupt extends Bundle { 231// val d = Output(Bool()) // Debug 232 val e = new Priv 233 val t = new Priv 234 val s = new Priv 235 } 236 237 // Debug CSRs 238 val dcsr = RegInit(UInt(32.W), DcsrStruct.init) 239 val dpc = Reg(UInt(64.W)) 240 val dscratch0 = Reg(UInt(64.W)) 241 val dscratch1 = Reg(UInt(64.W)) 242 val debugMode = RegInit(false.B) 243 val debugIntrEnable = RegInit(true.B) // debug interrupt will be handle only when debugIntrEnable 244 csrio.debugMode := debugMode 245 246 val dpcPrev = RegNext(dpc) 247 XSDebug(dpcPrev =/= dpc, "Debug Mode: dpc is altered! Current is %x, previous is %x\n", dpc, dpcPrev) 248 249 // dcsr value table 250 // | debugver | 0100 251 // | zero | 10 bits of 0 252 // | ebreakvs | 0 253 // | ebreakvu | 0 254 // | ebreakm | 1 if ebreak enters debug 255 // | zero | 0 256 // | ebreaks | 257 // | ebreaku | 258 // | stepie | disable interrupts in singlestep 259 // | stopcount| stop counter, 0 260 // | stoptime | stop time, 0 261 // | cause | 3 bits read only 262 // | v | 0 263 // | mprven | 1 264 // | nmip | read only 265 // | step | 266 // | prv | 2 bits 267 268 val dcsrData = Wire(new DcsrStruct) 269 dcsrData := dcsr.asTypeOf(new DcsrStruct) 270 val dcsrMask = ZeroExt(GenMask(15) | GenMask(13, 11) | GenMask(4) | GenMask(2, 0), XLEN)// Dcsr write mask 271 def dcsrUpdateSideEffect(dcsr: UInt): UInt = { 272 val dcsrOld = WireInit(dcsr.asTypeOf(new DcsrStruct)) 273 val dcsrNew = dcsr | (dcsrOld.prv(0) | dcsrOld.prv(1)).asUInt // turn 10 priv into 11 274 dcsrNew 275 } 276 // csrio.singleStep := dcsrData.step 277 csrio.customCtrl.singlestep := dcsrData.step && !debugMode 278 279 // Trigger CSRs 280 281 val type_config = Array( 282 0.U -> I_Trigger, 1.U -> I_Trigger, 283 2.U -> S_Trigger, 3.U -> S_Trigger, 284 4.U -> L_Trigger, 5.U -> L_Trigger, // No.5 Load Trigger 285 6.U -> I_Trigger, 7.U -> S_Trigger, 286 8.U -> I_Trigger, 9.U -> L_Trigger 287 ) 288 def TypeLookup(select: UInt) = MuxLookup(select, I_Trigger)(type_config) 289 290 val tdata1Phy = RegInit(VecInit(List.fill(10) {(2L << 60L).U(64.W)})) // init ttype 2 291 val tdata2Phy = Reg(Vec(10, UInt(64.W))) 292 val tselectPhy = RegInit(0.U(4.W)) 293 val tinfo = RegInit(2.U(64.W)) 294 val tControlPhy = RegInit(0.U(64.W)) 295 val triggerAction = RegInit(false.B) 296 297 def ReadTdata1(rdata: UInt) = rdata | Cat(triggerAction, 0.U(12.W)) // fix action 298 def WriteTdata1(wdata: UInt): UInt = { 299 val tdata1 = WireInit(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle)) 300 val wdata_wire = WireInit(wdata.asTypeOf(new TdataBundle)) 301 val tdata1_new = WireInit(wdata.asTypeOf(new TdataBundle)) 302 XSDebug(src2(11, 0) === Tdata1.U && valid && func =/= CSROpType.jmp, p"Debug Mode: tdata1(${tselectPhy})is written, the actual value is ${wdata}\n") 303// tdata1_new.hit := wdata(20) 304 tdata1_new.ttype := tdata1.ttype 305 tdata1_new.dmode := 0.U // Mux(debugMode, wdata_wire.dmode, tdata1.dmode) 306 tdata1_new.maskmax := 0.U 307 tdata1_new.hit := 0.U 308 tdata1_new.select := (TypeLookup(tselectPhy) === I_Trigger) && wdata_wire.select 309 when(wdata_wire.action <= 1.U){ 310 triggerAction := tdata1_new.action(0) 311 } .otherwise{ 312 tdata1_new.action := tdata1.action 313 } 314 tdata1_new.timing := false.B // hardwire this because we have singlestep 315 tdata1_new.zero1 := 0.U 316 tdata1_new.zero2 := 0.U 317 tdata1_new.chain := !tselectPhy(0) && wdata_wire.chain 318 when(wdata_wire.matchType =/= 0.U && wdata_wire.matchType =/= 2.U && wdata_wire.matchType =/= 3.U) { 319 tdata1_new.matchType := tdata1.matchType 320 } 321 tdata1_new.sizehi := Mux(wdata_wire.select && TypeLookup(tselectPhy) === I_Trigger, 0.U, 1.U) 322 tdata1_new.sizelo:= Mux(wdata_wire.select && TypeLookup(tselectPhy) === I_Trigger, 3.U, 1.U) 323 tdata1_new.execute := TypeLookup(tselectPhy) === I_Trigger 324 tdata1_new.store := TypeLookup(tselectPhy) === S_Trigger 325 tdata1_new.load := TypeLookup(tselectPhy) === L_Trigger 326 tdata1_new.asUInt 327 } 328 329 def WriteTselect(wdata: UInt) = { 330 Mux(wdata < 10.U, wdata(3, 0), tselectPhy) 331 } 332 333 val tcontrolWriteMask = ZeroExt(GenMask(3) | GenMask(7), XLEN) 334 335 336 def GenTdataDistribute(tdata1: TdataBundle, tdata2: UInt): MatchTriggerIO = { 337 val res = Wire(new MatchTriggerIO) 338 res.matchType := tdata1.matchType 339 res.select := tdata1.select 340 res.timing := tdata1.timing 341 res.action := triggerAction 342 res.chain := tdata1.chain 343 res.tdata2 := tdata2 344 res 345 } 346 347 csrio.customCtrl.frontend_trigger.t.bits.addr := MuxLookup(tselectPhy, 0.U)(Seq( 348 0.U -> 0.U, 349 1.U -> 1.U, 350 6.U -> 2.U, 351 8.U -> 3.U 352 )) 353 csrio.customCtrl.mem_trigger.t.bits.addr := MuxLookup(tselectPhy, 0.U)(Seq( 354 2.U -> 0.U, 355 3.U -> 1.U, 356 4.U -> 2.U, 357 5.U -> 3.U, 358 7.U -> 4.U, 359 9.U -> 5.U 360 )) 361 csrio.customCtrl.frontend_trigger.t.bits.tdata := GenTdataDistribute(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle), tdata2Phy(tselectPhy)) 362 csrio.customCtrl.mem_trigger.t.bits.tdata := GenTdataDistribute(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle), tdata2Phy(tselectPhy)) 363 364 // Machine-Level CSRs 365 // mtvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1 366 val mtvecMask = ~(0x2.U(XLEN.W)) 367 val mtvec = RegInit(UInt(XLEN.W), 0.U) 368 val mcounteren = RegInit(UInt(XLEN.W), 0.U) 369 val mcause = RegInit(UInt(XLEN.W), 0.U) 370 val mtval = RegInit(UInt(XLEN.W), 0.U) 371 val mepc = Reg(UInt(XLEN.W)) 372 // Page 36 in riscv-priv: The low bit of mepc (mepc[0]) is always zero. 373 val mepcMask = ~(0x1.U(XLEN.W)) 374 375 val mie = RegInit(0.U(XLEN.W)) 376 val mipWire = WireInit(0.U.asTypeOf(new Interrupt)) 377 val mipReg = RegInit(0.U(XLEN.W)) 378 val mipFixMask = ZeroExt(GenMask(9) | GenMask(5) | GenMask(1), XLEN) 379 val mip = (mipWire.asUInt | mipReg).asTypeOf(new Interrupt) 380 381 def getMisaMxl(mxl: BigInt): BigInt = mxl << (XLEN - 2) 382 def getMisaExt(ext: Char): Long = 1 << (ext.toInt - 'a'.toInt) 383 var extList = List('a', 's', 'i', 'u') 384 if (HasMExtension) { extList = extList :+ 'm' } 385 if (HasCExtension) { extList = extList :+ 'c' } 386 if (HasFPU) { extList = extList ++ List('f', 'd') } 387 val misaInitVal = getMisaMxl(2) | extList.foldLeft(0L)((sum, i) => sum | getMisaExt(i)) //"h8000000000141105".U 388 val misa = RegInit(UInt(XLEN.W), misaInitVal.U) 389 390 // MXL = 2 | 0 | EXT = b 00 0000 0100 0001 0001 0000 0101 391 // (XLEN-1, XLEN-2) | |(25, 0) ZY XWVU TSRQ PONM LKJI HGFE DCBA 392 393 val mvendorid = RegInit(UInt(XLEN.W), 0.U) // this is a non-commercial implementation 394 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 395 val mimpid = RegInit(UInt(XLEN.W), 0.U) // provides a unique encoding of the version of the processor implementation 396 val mhartid = Reg(UInt(XLEN.W)) // the hardware thread running the code 397 when (RegNext(RegNext(reset.asBool) && !reset.asBool)) { 398 mhartid := csrio.hartId 399 } 400 val mconfigptr = RegInit(UInt(XLEN.W), 0.U) // the read-only pointer pointing to the platform config structure, 0 for not supported. 401 val mstatus = RegInit("ha00002000".U(XLEN.W)) 402 403 // mstatus Value Table 404 // | sd | 405 // | pad1 | 406 // | sxl | hardlinked to 10, use 00 to pass xv6 test 407 // | uxl | hardlinked to 10 408 // | pad0 | 409 // | tsr | 410 // | tw | 411 // | tvm | 412 // | mxr | 413 // | sum | 414 // | mprv | 415 // | xs | 00 | 416 // | fs | 01 | 417 // | mpp | 00 | 418 // | hpp | 00 | 419 // | spp | 0 | 420 // | pie | 0000 | pie.h is used as UBE 421 // | ie | 0000 | uie hardlinked to 0, as N ext is not implemented 422 423 val mstatusStruct = mstatus.asTypeOf(new MstatusStruct) 424 def mstatusUpdateSideEffect(mstatus: UInt): UInt = { 425 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 426 val mstatusNew = Cat(mstatusOld.xs === "b11".U || mstatusOld.fs === "b11".U, mstatus(XLEN-2, 0)) 427 mstatusNew 428 } 429 430 val mstatusWMask = (~ZeroExt(( 431 GenMask(XLEN - 2, 36) | // WPRI 432 GenMask(35, 32) | // SXL and UXL cannot be changed 433 GenMask(31, 23) | // WPRI 434 GenMask(16, 15) | // XS is read-only 435 GenMask(10, 9) | // VS, not supported yet 436 GenMask(6) | // UBE, always little-endian (0) 437 GenMask(4) | // WPRI 438 GenMask(2) | // WPRI 439 GenMask(0) // WPRI 440 ), 64)).asUInt 441 442 val medeleg = RegInit(UInt(XLEN.W), 0.U) 443 val mideleg = RegInit(UInt(XLEN.W), 0.U) 444 val mscratch = RegInit(UInt(XLEN.W), 0.U) 445 446 val menvcfg = RegInit(UInt(XLEN.W), 0.U) // !WARNING: there is no logic about this CSR. 447 448 // PMP Mapping 449 val pmp = Wire(Vec(NumPMP, new PMPEntry())) // just used for method parameter 450 val pma = Wire(Vec(NumPMA, new PMPEntry())) // just used for method parameter 451 val pmpMapping = pmp_gen_mapping(pmp_init, NumPMP, PmpcfgBase, PmpaddrBase, pmp) 452 val pmaMapping = pmp_gen_mapping(pma_init, NumPMA, PmacfgBase, PmaaddrBase, pma) 453 // !WARNNING: pmp and pma CSRs are not checked in difftest. 454 455 // Superviser-Level CSRs 456 457 // val sstatus = RegInit(UInt(XLEN.W), "h00000000".U) 458 val sstatusWmask = "hc6122".U(XLEN.W) 459 // Sstatus Write Mask 460 // ------------------------------------------------------- 461 // 19 9 5 2 462 // 0 1100 0000 0001 0010 0010 463 // 0 c 0 1 2 2 464 // ------------------------------------------------------- 465 val sstatusRmask = sstatusWmask | "h8000000300018000".U 466 // Sstatus Read Mask = (SSTATUS_WMASK | (0xf << 13) | (1ull << 63) | (3ull << 32)) 467 // stvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1 468 val stvecMask = ~(0x2.U(XLEN.W)) 469 val stvec = RegInit(UInt(XLEN.W), 0.U) 470 // val sie = RegInit(0.U(XLEN.W)) 471 val sieMask = "h222".U & mideleg 472 val sipMask = "h222".U & mideleg 473 val sipWMask = "h2".U(XLEN.W) // ssip is writeable in smode 474 val satp = if(EnbaleTlbDebug) RegInit(UInt(XLEN.W), "h8000000000087fbe".U) else RegInit(0.U(XLEN.W)) 475 // val satp = RegInit(UInt(XLEN.W), "h8000000000087fbe".U) // only use for tlb naive debug 476 // val satpMask = "h80000fffffffffff".U(XLEN.W) // disable asid, mode can only be 8 / 0 477 // TODO: use config to control the length of asid 478 // val satpMask = "h8fffffffffffffff".U(XLEN.W) // enable asid, mode can only be 8 / 0 479 val satpMask = Cat("h8".U(Satp_Mode_len.W), satp_part_wmask(Satp_Asid_len, AsidLength), satp_part_wmask(Satp_Addr_len, PAddrBits-12)) 480 val sepc = RegInit(UInt(XLEN.W), 0.U) 481 // Page 60 in riscv-priv: The low bit of sepc (sepc[0]) is always zero. 482 val sepcMask = ~(0x1.U(XLEN.W)) 483 val scause = RegInit(UInt(XLEN.W), 0.U) 484 val stval = Reg(UInt(XLEN.W)) 485 val sscratch = RegInit(UInt(XLEN.W), 0.U) 486 val scounteren = RegInit(UInt(XLEN.W), 0.U) 487 val senvcfg = RegInit(UInt(XLEN.W), 0.U) // !WARNING: there is no logic about this CSR. 488 489 // sbpctl 490 // Bits 0-7: {LOOP, RAS, SC, TAGE, BIM, BTB, uBTB} 491 val sbpctl = RegInit(UInt(XLEN.W), "h7f".U) 492 csrio.customCtrl.bp_ctrl.ubtb_enable := sbpctl(0) 493 csrio.customCtrl.bp_ctrl.btb_enable := sbpctl(1) 494 csrio.customCtrl.bp_ctrl.bim_enable := sbpctl(2) 495 csrio.customCtrl.bp_ctrl.tage_enable := sbpctl(3) 496 csrio.customCtrl.bp_ctrl.sc_enable := sbpctl(4) 497 csrio.customCtrl.bp_ctrl.ras_enable := sbpctl(5) 498 csrio.customCtrl.bp_ctrl.loop_enable := sbpctl(6) 499 500 // spfctl Bit 0: L1I Cache Prefetcher Enable 501 // spfctl Bit 1: L2Cache Prefetcher Enable 502 // spfctl Bit 2: L1D Cache Prefetcher Enable 503 // spfctl Bit 3: L1D train prefetch on hit 504 // spfctl Bit 4: L1D prefetch enable agt 505 // spfctl Bit 5: L1D prefetch enable pht 506 // spfctl Bit [9:6]: L1D prefetch active page threshold 507 // spfctl Bit [15:10]: L1D prefetch active page stride 508 // turn off L2 BOP, turn on L1 SMS by default 509 val spfctl = RegInit(UInt(XLEN.W), Seq( 510 0 << 17, // L2 pf store only [17] init: false 511 1 << 16, // L1D pf enable stride [16] init: true 512 30 << 10, // L1D active page stride [15:10] init: 30 513 12 << 6, // L1D active page threshold [9:6] init: 12 514 1 << 5, // L1D enable pht [5] init: true 515 1 << 4, // L1D enable agt [4] init: true 516 0 << 3, // L1D train on hit [3] init: false 517 1 << 2, // L1D pf enable [2] init: true 518 1 << 1, // L2 pf enable [1] init: true 519 1 << 0, // L1I pf enable [0] init: true 520 ).reduce(_|_).U(XLEN.W)) 521 csrio.customCtrl.l1I_pf_enable := spfctl(0) 522 csrio.customCtrl.l2_pf_enable := spfctl(1) 523 csrio.customCtrl.l1D_pf_enable := spfctl(2) 524 csrio.customCtrl.l1D_pf_train_on_hit := spfctl(3) 525 csrio.customCtrl.l1D_pf_enable_agt := spfctl(4) 526 csrio.customCtrl.l1D_pf_enable_pht := spfctl(5) 527 csrio.customCtrl.l1D_pf_active_threshold := spfctl(9, 6) 528 csrio.customCtrl.l1D_pf_active_stride := spfctl(15, 10) 529 csrio.customCtrl.l1D_pf_enable_stride := spfctl(16) 530 csrio.customCtrl.l2_pf_store_only := spfctl(17) 531 532 // sfetchctl Bit 0: L1I Cache Parity check enable 533 val sfetchctl = RegInit(UInt(XLEN.W), "b0".U) 534 csrio.customCtrl.icache_parity_enable := sfetchctl(0) 535 536 // sdsid: Differentiated Services ID 537 val sdsid = RegInit(UInt(XLEN.W), 0.U) 538 csrio.customCtrl.dsid := sdsid 539 540 // slvpredctl: load violation predict settings 541 // Default reset period: 2^16 542 // Why this number: reset more frequently while keeping the overhead low 543 // Overhead: extra two redirections in every 64K cycles => ~0.1% overhead 544 val slvpredctl = RegInit(UInt(XLEN.W), "h60".U) 545 csrio.customCtrl.lvpred_disable := slvpredctl(0) 546 csrio.customCtrl.no_spec_load := slvpredctl(1) 547 csrio.customCtrl.storeset_wait_store := slvpredctl(2) 548 csrio.customCtrl.storeset_no_fast_wakeup := slvpredctl(3) 549 csrio.customCtrl.lvpred_timeout := slvpredctl(8, 4) 550 551 // smblockctl: memory block configurations 552 // +------------------------------+---+----+----+-----+--------+ 553 // |XLEN-1 8| 7 | 6 | 5 | 4 |3 0| 554 // +------------------------------+---+----+----+-----+--------+ 555 // | Reserved | O | CE | SP | LVC | Th | 556 // +------------------------------+---+----+----+-----+--------+ 557 // Description: 558 // Bit 3-0 : Store buffer flush threshold (Th). 559 // Bit 4 : Enable load violation check after reset (LVC). 560 // Bit 5 : Enable soft-prefetch after reset (SP). 561 // Bit 6 : Enable cache error after reset (CE). 562 // Bit 7 : Enable uncache write outstanding (O). 563 // Others : Reserved. 564 565 val smblockctl_init_val = 566 (0xf & StoreBufferThreshold) | 567 (EnableLdVioCheckAfterReset.toInt << 4) | 568 (EnableSoftPrefetchAfterReset.toInt << 5) | 569 (EnableCacheErrorAfterReset.toInt << 6) 570 (EnableUncacheWriteOutstanding.toInt << 7) 571 val smblockctl = RegInit(UInt(XLEN.W), smblockctl_init_val.U) 572 csrio.customCtrl.sbuffer_threshold := smblockctl(3, 0) 573 // bits 4: enable load load violation check 574 csrio.customCtrl.ldld_vio_check_enable := smblockctl(4) 575 csrio.customCtrl.soft_prefetch_enable := smblockctl(5) 576 csrio.customCtrl.cache_error_enable := smblockctl(6) 577 csrio.customCtrl.uncache_write_outstanding_enable := smblockctl(7) 578 579 println("CSR smblockctl init value:") 580 println(" Store buffer replace threshold: " + StoreBufferThreshold) 581 println(" Enable ld-ld vio check after reset: " + EnableLdVioCheckAfterReset) 582 println(" Enable soft prefetch after reset: " + EnableSoftPrefetchAfterReset) 583 println(" Enable cache error after reset: " + EnableCacheErrorAfterReset) 584 println(" Enable uncache write outstanding: " + EnableUncacheWriteOutstanding) 585 586 val srnctl = RegInit(UInt(XLEN.W), "h7".U) 587 csrio.customCtrl.fusion_enable := srnctl(0) 588 csrio.customCtrl.svinval_enable := srnctl(1) 589 csrio.customCtrl.wfi_enable := srnctl(2) 590 591 val tlbBundle = Wire(new TlbCsrBundle) 592 tlbBundle.satp.apply(satp) 593 594 csrio.tlb := tlbBundle 595 596 // User-Level CSRs 597 val uepc = Reg(UInt(XLEN.W)) 598 599 // fcsr 600 class FcsrStruct extends Bundle { 601 val reserved = UInt((XLEN-3-5).W) 602 val frm = UInt(3.W) 603 val fflags = UInt(5.W) 604 assert(this.getWidth == XLEN) 605 } 606 val fcsr = RegInit(0.U(XLEN.W)) 607 // set mstatus->sd and mstatus->fs when true 608 val csrw_dirty_fp_state = WireInit(false.B) 609 610 def frm_wfn(wdata: UInt): UInt = { 611 val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct)) 612 csrw_dirty_fp_state := true.B 613 fcsrOld.frm := wdata(2,0) 614 fcsrOld.asUInt 615 } 616 def frm_rfn(rdata: UInt): UInt = rdata(7,5) 617 618 def fflags_wfn(update: Boolean)(wdata: UInt): UInt = { 619 val fcsrOld = fcsr.asTypeOf(new FcsrStruct) 620 val fcsrNew = WireInit(fcsrOld) 621 csrw_dirty_fp_state := true.B 622 if (update) { 623 fcsrNew.fflags := wdata(4,0) | fcsrOld.fflags 624 } else { 625 fcsrNew.fflags := wdata(4,0) 626 } 627 fcsrNew.asUInt 628 } 629 def fflags_rfn(rdata:UInt): UInt = rdata(4,0) 630 631 def fcsr_wfn(wdata: UInt): UInt = { 632 val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct)) 633 csrw_dirty_fp_state := true.B 634 Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags) 635 } 636 637 val fcsrMapping = Map( 638 MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn(update = false), rfn = fflags_rfn), 639 MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn), 640 MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn) 641 ) 642 643 // Hart Privilege Mode 644 val privilegeMode = RegInit(UInt(2.W), ModeM) 645 646 //val perfEventscounten = List.fill(nrPerfCnts)(RegInit(false(Bool()))) 647 // Perf Counter 648 val nrPerfCnts = 29 // 3...31 649 val privilegeModeOH = UIntToOH(privilegeMode) 650 val perfEventscounten = RegInit(0.U.asTypeOf(Vec(nrPerfCnts, Bool()))) 651 val perfCnts = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W))) 652 val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++ 653 List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++ 654 List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++ 655 List.fill(5)(RegInit("hc0300c0300".U(XLEN.W))) 656 for (i <-0 until nrPerfCnts) { 657 perfEventscounten(i) := (perfEvents(i)(63,60) & privilegeModeOH).orR 658 } 659 660 val hpmEvents = Wire(Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent)) 661 for (i <- 0 until numPCntHc * coreParams.L2NBanks) { 662 hpmEvents(i) := csrio.perf.perfEventsHc(i) 663 } 664 665 // print perfEvents 666 val allPerfEvents = hpmEvents.map(x => (s"Hc", x.value)) 667 if (printEventCoding) { 668 for (((name, inc), i) <- allPerfEvents.zipWithIndex) { 669 println("CSR perfEvents Set", name, inc, i) 670 } 671 } 672 673 val csrevents = perfEvents.slice(24, 29) 674 val hpm_hc = HPerfMonitor(csrevents, hpmEvents) 675 val mcountinhibit = RegInit(0.U(XLEN.W)) 676 val mcycle = RegInit(0.U(XLEN.W)) 677 mcycle := mcycle + 1.U 678 val minstret = RegInit(0.U(XLEN.W)) 679 val perf_events = csrio.perf.perfEventsFrontend ++ 680 csrio.perf.perfEventsCtrl ++ 681 csrio.perf.perfEventsLsu ++ 682 hpm_hc.getPerf 683 minstret := minstret + RegNext(csrio.perf.retiredInstr) 684 for(i <- 0 until 29){ 685 perfCnts(i) := Mux(mcountinhibit(i+3) | !perfEventscounten(i), perfCnts(i), perfCnts(i) + perf_events(i).value) 686 } 687 688 // CSR reg map 689 val basicPrivMapping = Map( 690 691 //--- User Trap Setup --- 692 // MaskedRegMap(Ustatus, ustatus), 693 // MaskedRegMap(Uie, uie, 0.U, MaskedRegMap.Unwritable), 694 // MaskedRegMap(Utvec, utvec), 695 696 //--- User Trap Handling --- 697 // MaskedRegMap(Uscratch, uscratch), 698 // MaskedRegMap(Uepc, uepc), 699 // MaskedRegMap(Ucause, ucause), 700 // MaskedRegMap(Utval, utval), 701 // MaskedRegMap(Uip, uip), 702 703 //--- User Counter/Timers --- 704 // MaskedRegMap(Cycle, cycle), 705 // MaskedRegMap(Time, time), 706 // MaskedRegMap(Instret, instret), 707 708 //--- Supervisor Trap Setup --- 709 MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask), 710 // MaskedRegMap(Sedeleg, Sedeleg), 711 // MaskedRegMap(Sideleg, Sideleg), 712 MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask), 713 MaskedRegMap(Stvec, stvec, stvecMask, MaskedRegMap.NoSideEffect, stvecMask), 714 MaskedRegMap(Scounteren, scounteren), 715 716 //--- Supervisor Configuration --- 717 MaskedRegMap(Senvcfg, senvcfg), 718 719 //--- Supervisor Trap Handling --- 720 MaskedRegMap(Sscratch, sscratch), 721 MaskedRegMap(Sepc, sepc, sepcMask, MaskedRegMap.NoSideEffect, sepcMask), 722 MaskedRegMap(Scause, scause), 723 MaskedRegMap(Stval, stval), 724 MaskedRegMap(Sip, mip.asUInt, sipWMask, MaskedRegMap.Unwritable, sipMask), 725 726 //--- Supervisor Protection and Translation --- 727 MaskedRegMap(Satp, satp, satpMask, MaskedRegMap.NoSideEffect, satpMask), 728 729 //--- Supervisor Custom Read/Write Registers 730 MaskedRegMap(Sbpctl, sbpctl), 731 MaskedRegMap(Spfctl, spfctl), 732 MaskedRegMap(Sfetchctl, sfetchctl), 733 MaskedRegMap(Sdsid, sdsid), 734 MaskedRegMap(Slvpredctl, slvpredctl), 735 MaskedRegMap(Smblockctl, smblockctl), 736 MaskedRegMap(Srnctl, srnctl), 737 738 //--- Machine Information Registers --- 739 MaskedRegMap(Mvendorid, mvendorid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 740 MaskedRegMap(Marchid, marchid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 741 MaskedRegMap(Mimpid, mimpid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 742 MaskedRegMap(Mhartid, mhartid, 0.U(XLEN.W), MaskedRegMap.Unwritable), 743 MaskedRegMap(Mconfigptr, mconfigptr, 0.U(XLEN.W), MaskedRegMap.Unwritable), 744 745 //--- Machine Trap Setup --- 746 MaskedRegMap(Mstatus, mstatus, mstatusWMask, mstatusUpdateSideEffect), 747 MaskedRegMap(Misa, misa, 0.U, MaskedRegMap.Unwritable), // now whole misa is unchangeable 748 MaskedRegMap(Medeleg, medeleg, "hb3ff".U(XLEN.W)), 749 MaskedRegMap(Mideleg, mideleg, "h222".U(XLEN.W)), 750 MaskedRegMap(Mie, mie, "haaa".U(XLEN.W)), 751 MaskedRegMap(Mtvec, mtvec, mtvecMask, MaskedRegMap.NoSideEffect, mtvecMask), 752 MaskedRegMap(Mcounteren, mcounteren), 753 754 //--- Machine Trap Handling --- 755 MaskedRegMap(Mscratch, mscratch), 756 MaskedRegMap(Mepc, mepc, mepcMask, MaskedRegMap.NoSideEffect, mepcMask), 757 MaskedRegMap(Mcause, mcause), 758 MaskedRegMap(Mtval, mtval), 759 MaskedRegMap(Mip, mip.asUInt, 0.U(XLEN.W), MaskedRegMap.Unwritable), 760 761 //--- Machine Configuration --- 762 MaskedRegMap(Menvcfg, menvcfg), 763 764 //--- Trigger --- 765 MaskedRegMap(Tselect, tselectPhy, WritableMask, WriteTselect), 766 MaskedRegMap(Tdata1, tdata1Phy(tselectPhy), WritableMask, WriteTdata1, WritableMask, ReadTdata1), 767 MaskedRegMap(Tdata2, tdata2Phy(tselectPhy)), 768 MaskedRegMap(Tinfo, tinfo, 0.U(XLEN.W), MaskedRegMap.Unwritable), 769 MaskedRegMap(Tcontrol, tControlPhy, tcontrolWriteMask), 770 771 //--- Debug Mode --- 772 MaskedRegMap(Dcsr, dcsr, dcsrMask, dcsrUpdateSideEffect), 773 MaskedRegMap(Dpc, dpc), 774 MaskedRegMap(Dscratch0, dscratch0), 775 MaskedRegMap(Dscratch1, dscratch1), 776 MaskedRegMap(Mcountinhibit, mcountinhibit), 777 MaskedRegMap(Mcycle, mcycle), 778 MaskedRegMap(Minstret, minstret), 779 ) 780 781 val perfCntMapping = (0 until 29).map(i => {Map( 782 MaskedRegMap(addr = Mhpmevent3 +i, 783 reg = perfEvents(i), 784 wmask = "hf87fff3fcff3fcff".U(XLEN.W)), 785 MaskedRegMap(addr = Mhpmcounter3 +i, 786 reg = perfCnts(i)) 787 )}).fold(Map())((a,b) => a ++ b) 788 // TODO: mechanism should be implemented later 789 // val MhpmcounterStart = Mhpmcounter3 790 // val MhpmeventStart = Mhpmevent3 791 // for (i <- 0 until nrPerfCnts) { 792 // perfCntMapping += MaskedRegMap(MhpmcounterStart + i, perfCnts(i)) 793 // perfCntMapping += MaskedRegMap(MhpmeventStart + i, perfEvents(i)) 794 // } 795 796 val cacheopRegs = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => { 797 name -> RegInit(0.U(attribute("width").toInt.W)) 798 }} 799 val cacheopMapping = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => { 800 MaskedRegMap( 801 Scachebase + attribute("offset").toInt, 802 cacheopRegs(name) 803 ) 804 }} 805 806 val mapping = basicPrivMapping ++ 807 perfCntMapping ++ 808 pmpMapping ++ 809 pmaMapping ++ 810 (if (HasFPU) fcsrMapping else Nil) ++ 811 (if (HasCustomCSRCacheOp) cacheopMapping else Nil) 812 813 val addr = src2(11, 0) 814 val csri = ZeroExt(src2(16, 12), XLEN) 815 val rdata = Wire(UInt(XLEN.W)) 816 val wdata = LookupTree(func, List( 817 CSROpType.wrt -> src1, 818 CSROpType.set -> (rdata | src1), 819 CSROpType.clr -> (rdata & (~src1).asUInt), 820 CSROpType.wrti -> csri, 821 CSROpType.seti -> (rdata | csri), 822 CSROpType.clri -> (rdata & (~csri).asUInt) 823 )) 824 825 val addrInPerfCnt = (addr >= Mcycle.U) && (addr <= Mhpmcounter31.U) || 826 (addr >= Mcountinhibit.U) && (addr <= Mhpmevent31.U) || 827 addr === Mip.U 828 csrio.isPerfCnt := addrInPerfCnt && valid && func =/= CSROpType.jmp 829 830 // satp wen check 831 val satpLegalMode = (wdata.asTypeOf(new SatpStruct).mode===0.U) || (wdata.asTypeOf(new SatpStruct).mode===8.U) 832 833 // csr access check, special case 834 val tvmNotPermit = (privilegeMode === ModeS && mstatusStruct.tvm.asBool) 835 val accessPermitted = !(addr === Satp.U && tvmNotPermit) 836 csrio.disableSfence := tvmNotPermit || privilegeMode === ModeU 837 838 // general CSR wen check 839 val wen = valid && CSROpType.needAccess(func) && (addr=/=Satp.U || satpLegalMode) 840 val dcsrPermitted = dcsrPermissionCheck(addr, false.B, debugMode) 841 val triggerPermitted = triggerPermissionCheck(addr, true.B, debugMode) // todo dmode 842 val modePermitted = csrAccessPermissionCheck(addr, false.B, privilegeMode) && dcsrPermitted && triggerPermitted 843 val perfcntPermitted = perfcntPermissionCheck(addr, privilegeMode, mcounteren, scounteren) 844 val permitted = Mux(addrInPerfCnt, perfcntPermitted, modePermitted) && accessPermitted 845 846 MaskedRegMap.generate(mapping, addr, rdata, wen && permitted, wdata) 847 io.out.bits.data := rdata 848 io.out.bits.uop := io.in.bits.uop 849 io.out.bits.uop.cf := cfOut 850 io.out.bits.uop.ctrl.flushPipe := flushPipe 851 852 // send distribute csr a w signal 853 csrio.customCtrl.distribute_csr.w.valid := wen && permitted 854 csrio.customCtrl.distribute_csr.w.bits.data := wdata 855 csrio.customCtrl.distribute_csr.w.bits.addr := addr 856 857 // Fix Mip/Sip write 858 val fixMapping = Map( 859 MaskedRegMap(Mip, mipReg.asUInt, mipFixMask), 860 MaskedRegMap(Sip, mipReg.asUInt, sipWMask, MaskedRegMap.NoSideEffect, sipMask) 861 ) 862 val rdataFix = Wire(UInt(XLEN.W)) 863 val wdataFix = LookupTree(func, List( 864 CSROpType.wrt -> src1, 865 CSROpType.set -> (rdataFix | src1), 866 CSROpType.clr -> (rdataFix & (~src1).asUInt), 867 CSROpType.wrti -> csri, 868 CSROpType.seti -> (rdataFix | csri), 869 CSROpType.clri -> (rdataFix & (~csri).asUInt) 870 )) 871 MaskedRegMap.generate(fixMapping, addr, rdataFix, wen && permitted, wdataFix) 872 873 when (RegNext(csrio.fpu.fflags.valid)) { 874 fcsr := fflags_wfn(update = true)(RegNext(csrio.fpu.fflags.bits)) 875 } 876 // set fs and sd in mstatus 877 when (csrw_dirty_fp_state || RegNext(csrio.fpu.dirty_fs)) { 878 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 879 mstatusNew.fs := "b11".U 880 mstatusNew.sd := true.B 881 mstatus := mstatusNew.asUInt 882 } 883 csrio.fpu.frm := fcsr.asTypeOf(new FcsrStruct).frm 884 885 886 // Trigger Ctrl 887 csrio.customCtrl.trigger_enable := tdata1Phy.map{t => 888 def tdata1 = t.asTypeOf(new TdataBundle) 889 tdata1.m && privilegeMode === ModeM || 890 tdata1.s && privilegeMode === ModeS || tdata1.u && privilegeMode === ModeU 891 } 892 csrio.customCtrl.frontend_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) === I_Trigger) 893 csrio.customCtrl.mem_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) =/= I_Trigger) 894 XSDebug(csrio.customCtrl.trigger_enable.asUInt.orR, p"Debug Mode: At least 1 trigger is enabled," + 895 p"trigger enable is ${Binary(csrio.customCtrl.trigger_enable.asUInt)}\n") 896 897 // CSR inst decode 898 val isEbreak = addr === privEbreak && func === CSROpType.jmp 899 val isEcall = addr === privEcall && func === CSROpType.jmp 900 val isMret = addr === privMret && func === CSROpType.jmp 901 val isSret = addr === privSret && func === CSROpType.jmp 902 val isUret = addr === privUret && func === CSROpType.jmp 903 val isDret = addr === privDret && func === CSROpType.jmp 904 val isWFI = func === CSROpType.wfi 905 906 XSDebug(wen, "csr write: pc %x addr %x rdata %x wdata %x func %x\n", cfIn.pc, addr, rdata, wdata, func) 907 XSDebug(wen, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", cfIn.pc, mstatus, mideleg , medeleg, privilegeMode) 908 909 // Illegal privileged operation list 910 val illegalMret = valid && isMret && privilegeMode < ModeM 911 val illegalSret = valid && isSret && privilegeMode < ModeS 912 val illegalSModeSret = valid && isSret && privilegeMode === ModeS && mstatusStruct.tsr.asBool 913 // When TW=1, then if WFI is executed in any less-privileged mode, 914 // and it does not complete within an implementation-specific, bounded time limit, 915 // the WFI instruction causes an illegal instruction exception. 916 // The time limit may always be 0, in which case WFI always causes 917 // an illegal instruction exception in less-privileged modes when TW=1. 918 val illegalWFI = valid && isWFI && privilegeMode < ModeM && mstatusStruct.tw === 1.U 919 920 // Illegal privileged instruction check 921 val isIllegalAddr = valid && CSROpType.needAccess(func) && MaskedRegMap.isIllegalAddr(mapping, addr) 922 val isIllegalAccess = wen && !permitted 923 val isIllegalPrivOp = illegalMret || illegalSret || illegalSModeSret || illegalWFI 924 925 // expose several csr bits for tlb 926 tlbBundle.priv.mxr := mstatusStruct.mxr.asBool 927 tlbBundle.priv.sum := mstatusStruct.sum.asBool 928 tlbBundle.priv.imode := privilegeMode 929 tlbBundle.priv.dmode := Mux(debugMode && dcsr.asTypeOf(new DcsrStruct).mprven, ModeM, Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpp, privilegeMode)) 930 931 // Branch control 932 val retTarget = WireInit(0.U) 933 val resetSatp = addr === Satp.U && wen // write to satp will cause the pipeline be flushed 934 flushPipe := resetSatp || (valid && func === CSROpType.jmp && !isEcall && !isEbreak) 935 936 private val illegalRetTarget = WireInit(false.B) 937 when(valid) { 938 when(isDret) { 939 retTarget := dpc(VAddrBits - 1, 0) 940 }.elsewhen(isMret && !illegalMret) { 941 retTarget := mepc(VAddrBits - 1, 0) 942 }.elsewhen(isSret && !illegalSret && !illegalSModeSret) { 943 retTarget := sepc(VAddrBits - 1, 0) 944 }.elsewhen(isUret) { 945 retTarget := uepc(VAddrBits - 1, 0) 946 }.otherwise { 947 illegalRetTarget := true.B 948 } 949 }.otherwise { 950 illegalRetTarget := true.B // when illegalRetTarget setted, retTarget should never be used 951 } 952 953 when (valid && isDret) { 954 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 955 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 956 val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct)) 957 val debugModeNew = WireInit(debugMode) 958 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. 959 mstatus := mstatusNew.asUInt 960 privilegeMode := dcsrNew.prv 961 retTarget := dpc(VAddrBits-1, 0) 962 debugModeNew := false.B 963 debugIntrEnable := true.B 964 debugMode := debugModeNew 965 XSDebug("Debug Mode: Dret executed, returning to %x.", retTarget) 966 } 967 968 when (valid && isMret && !illegalMret) { 969 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 970 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 971 mstatusNew.ie.m := mstatusOld.pie.m 972 privilegeMode := mstatusOld.mpp 973 mstatusNew.pie.m := true.B 974 mstatusNew.mpp := ModeU 975 when (mstatusOld.mpp =/= ModeM) { mstatusNew.mprv := 0.U } 976 mstatus := mstatusNew.asUInt 977 // lr := false.B 978 retTarget := mepc(VAddrBits-1, 0) 979 } 980 981 when (valid && isSret && !illegalSret && !illegalSModeSret) { 982 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 983 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 984 mstatusNew.ie.s := mstatusOld.pie.s 985 privilegeMode := Cat(0.U(1.W), mstatusOld.spp) 986 mstatusNew.pie.s := true.B 987 mstatusNew.spp := ModeU 988 mstatus := mstatusNew.asUInt 989 when (mstatusOld.spp =/= ModeM) { mstatusNew.mprv := 0.U } 990 // lr := false.B 991 retTarget := sepc(VAddrBits-1, 0) 992 } 993 994 when (valid && isUret) { 995 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 996 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 997 // mstatusNew.mpp.m := ModeU //TODO: add mode U 998 mstatusNew.ie.u := mstatusOld.pie.u 999 privilegeMode := ModeU 1000 mstatusNew.pie.u := true.B 1001 mstatus := mstatusNew.asUInt 1002 retTarget := uepc(VAddrBits-1, 0) 1003 } 1004 1005 io.in.ready := true.B 1006 io.out.valid := valid 1007 1008 // In this situation, hart will enter debug mode instead of handling a breakpoint exception simply. 1009 // Ebreak block instructions backwards, so it's ok to not keep extra info to distinguish between breakpoint 1010 // exception and enter-debug-mode exception. 1011 val ebreakEnterDebugMode = 1012 (privilegeMode === ModeM && dcsrData.ebreakm) || 1013 (privilegeMode === ModeS && dcsrData.ebreaks) || 1014 (privilegeMode === ModeU && dcsrData.ebreaku) 1015 1016 // raise a debug exception waiting to enter debug mode, instead of a breakpoint exception 1017 val raiseDebugException = !debugMode && isEbreak && ebreakEnterDebugMode 1018 1019 val csrExceptionVec = WireInit(cfIn.exceptionVec) 1020 csrExceptionVec(breakPoint) := io.in.valid && isEbreak 1021 csrExceptionVec(ecallM) := privilegeMode === ModeM && io.in.valid && isEcall 1022 csrExceptionVec(ecallS) := privilegeMode === ModeS && io.in.valid && isEcall 1023 csrExceptionVec(ecallU) := privilegeMode === ModeU && io.in.valid && isEcall 1024 // Trigger an illegal instr exception when: 1025 // * unimplemented csr is being read/written 1026 // * csr access is illegal 1027 csrExceptionVec(illegalInstr) := isIllegalAddr || isIllegalAccess || isIllegalPrivOp 1028 cfOut.exceptionVec := csrExceptionVec 1029 1030 XSDebug(io.in.valid, s"Debug Mode: an Ebreak is executed, ebreak cause enter-debug-mode exception ? ${raiseDebugException}\n") 1031 1032 /** 1033 * Exception and Intr 1034 */ 1035 val ideleg = (mideleg & mip.asUInt) 1036 def privilegedEnableDetect(x: Bool): Bool = Mux(x, ((privilegeMode === ModeS) && mstatusStruct.ie.s) || (privilegeMode < ModeS), 1037 ((privilegeMode === ModeM) && mstatusStruct.ie.m) || (privilegeMode < ModeM)) 1038 1039 val debugIntr = csrio.externalInterrupt.debug & debugIntrEnable 1040 XSDebug(debugIntr, "Debug Mode: debug interrupt is asserted and valid!") 1041 // send interrupt information to ROB 1042 val intrVecEnable = Wire(Vec(12, Bool())) 1043 val disableInterrupt = debugMode || (dcsrData.step && !dcsrData.stepie) 1044 intrVecEnable.zip(ideleg.asBools).map{case(x,y) => x := privilegedEnableDetect(y) && !disableInterrupt} 1045 val intrVec = Cat(debugIntr && !debugMode, (mie(11,0) & mip.asUInt & intrVecEnable.asUInt)) 1046 val intrBitSet = intrVec.orR 1047 csrio.interrupt := intrBitSet 1048 // Page 45 in RISC-V Privileged Specification 1049 // The WFI instruction can also be executed when interrupts are disabled. The operation of WFI 1050 // must be unaffected by the global interrupt bits in mstatus (MIE and SIE) and the delegation 1051 // register mideleg, but should honor the individual interrupt enables (e.g, MTIE). 1052 csrio.wfi_event := debugIntr || (mie(11, 0) & mip.asUInt).orR 1053 mipWire.t.m := csrio.externalInterrupt.mtip 1054 mipWire.s.m := csrio.externalInterrupt.msip 1055 mipWire.e.m := csrio.externalInterrupt.meip 1056 mipWire.e.s := csrio.externalInterrupt.seip 1057 1058 // interrupts 1059 val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(intrVec(i), i.U, sum)) 1060 val hasIntr = csrio.exception.valid && csrio.exception.bits.isInterrupt 1061 val ivmEnable = tlbBundle.priv.imode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U 1062 val iexceptionPC = Mux(ivmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc) 1063 val dvmEnable = tlbBundle.priv.dmode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U 1064 val dexceptionPC = Mux(dvmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc) 1065 XSDebug(hasIntr, "interrupt: pc=0x%x, %d\n", dexceptionPC, intrNO) 1066 val hasDebugIntr = intrNO === IRQ_DEBUG.U && hasIntr 1067 1068 // exceptions from rob need to handle 1069 val exceptionVecFromRob = csrio.exception.bits.uop.cf.exceptionVec 1070 val hasException = csrio.exception.valid && !csrio.exception.bits.isInterrupt 1071 val hasInstrPageFault = hasException && exceptionVecFromRob(instrPageFault) 1072 val hasLoadPageFault = hasException && exceptionVecFromRob(loadPageFault) 1073 val hasStorePageFault = hasException && exceptionVecFromRob(storePageFault) 1074 val hasStoreAddrMisalign = hasException && exceptionVecFromRob(storeAddrMisaligned) 1075 val hasLoadAddrMisalign = hasException && exceptionVecFromRob(loadAddrMisaligned) 1076 val hasInstrAccessFault = hasException && exceptionVecFromRob(instrAccessFault) 1077 val hasLoadAccessFault = hasException && exceptionVecFromRob(loadAccessFault) 1078 val hasStoreAccessFault = hasException && exceptionVecFromRob(storeAccessFault) 1079 val hasBreakPoint = hasException && exceptionVecFromRob(breakPoint) 1080 val hasSingleStep = hasException && csrio.exception.bits.uop.ctrl.singleStep 1081 val hasTriggerHit = hasException && csrio.exception.bits.uop.cf.trigger.hit 1082 1083 XSDebug(hasSingleStep, "Debug Mode: single step exception\n") 1084 XSDebug(hasTriggerHit, p"Debug Mode: trigger hit, is frontend? ${Binary(csrio.exception.bits.uop.cf.trigger.frontendHit.asUInt)} " + 1085 p"backend hit vec ${Binary(csrio.exception.bits.uop.cf.trigger.backendHit.asUInt)}\n") 1086 1087 val hasExceptionVec = csrio.exception.bits.uop.cf.exceptionVec 1088 val regularExceptionNO = ExceptionNO.priorities.foldRight(0.U)((i: Int, sum: UInt) => Mux(hasExceptionVec(i), i.U, sum)) 1089 val exceptionNO = Mux(hasSingleStep || hasTriggerHit, 3.U, regularExceptionNO) 1090 val causeNO = (hasIntr << (XLEN-1)).asUInt | Mux(hasIntr, intrNO, exceptionNO) 1091 1092 val hasExceptionIntr = csrio.exception.valid 1093 1094 val hasDebugException = hasBreakPoint && !debugMode && ebreakEnterDebugMode 1095 val hasDebugExceptionIntr = !debugMode && (hasDebugException || hasDebugIntr || hasSingleStep || hasTriggerHit && triggerAction) // TODO 1096 val ebreakEnterParkLoop = debugMode && hasExceptionIntr 1097 1098 XSDebug(hasExceptionIntr, "int/exc: pc %x int (%d):%x exc: (%d):%x\n", 1099 dexceptionPC, intrNO, intrVec, exceptionNO, hasExceptionVec.asUInt 1100 ) 1101 XSDebug(hasExceptionIntr, 1102 "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", 1103 dexceptionPC, 1104 mstatus, 1105 mideleg, 1106 medeleg, 1107 privilegeMode 1108 ) 1109 1110 // mtval write logic 1111 // Due to timing reasons of memExceptionVAddr, we delay the write of mtval and stval 1112 val memExceptionAddr = SignExt(csrio.memExceptionVAddr, XLEN) 1113 val updateTval = VecInit(Seq( 1114 hasInstrPageFault, 1115 hasLoadPageFault, 1116 hasStorePageFault, 1117 hasInstrAccessFault, 1118 hasLoadAccessFault, 1119 hasStoreAccessFault, 1120 hasLoadAddrMisalign, 1121 hasStoreAddrMisalign, 1122 )).asUInt.orR 1123 when (RegNext(RegNext(updateTval))) { 1124 val tval = Mux( 1125 RegNext(RegNext(hasInstrPageFault || hasInstrAccessFault)), 1126 RegNext(RegNext(Mux( 1127 csrio.exception.bits.uop.cf.crossPageIPFFix, 1128 SignExt(csrio.exception.bits.uop.cf.pc + 2.U, XLEN), 1129 iexceptionPC 1130 ))), 1131 memExceptionAddr 1132 ) 1133 when (RegNext(privilegeMode === ModeM)) { 1134 mtval := tval 1135 }.otherwise { 1136 stval := tval 1137 } 1138 } 1139 1140 val debugTrapTarget = Mux(!isEbreak && debugMode, 0x38020808.U, 0x38020800.U) // 0x808 is when an exception occurs in debug mode prog buf exec 1141 val deleg = Mux(hasIntr, mideleg, medeleg) 1142 // val delegS = ((deleg & (1 << (causeNO & 0xf))) != 0) && (privilegeMode < ModeM); 1143 val delegS = deleg(causeNO(7,0)) && (privilegeMode < ModeM) 1144 val clearTval = !updateTval || hasIntr 1145 val isXRet = io.in.valid && func === CSROpType.jmp && !isEcall && !isEbreak 1146 1147 // ctrl block will use theses later for flush 1148 val isXRetFlag = RegInit(false.B) 1149 when (DelayN(io.redirectIn.valid, 5)) { 1150 isXRetFlag := false.B 1151 }.elsewhen (isXRet) { 1152 isXRetFlag := true.B 1153 } 1154 csrio.isXRet := isXRetFlag 1155 private val retTargetReg = RegEnable(retTarget, isXRet && !illegalRetTarget) 1156 private val illegalXret = RegEnable(illegalMret || illegalSret || illegalSModeSret, isXRet) 1157 val xtvec = Mux(delegS, stvec, mtvec) 1158 val xtvecBase = xtvec(VAddrBits - 1, 2) 1159 // When MODE=Vectored, all synchronous exceptions into M/S mode 1160 // cause the pc to be set to the address in the BASE field, whereas 1161 // interrupts cause the pc to be set to the address in the BASE field 1162 // plus four times the interrupt cause number. 1163 private val pcFromXtvec = Cat(xtvecBase + Mux(xtvec(0) && hasIntr, causeNO(3, 0), 0.U), 0.U(2.W)) 1164 // XRet sends redirect instead of Flush and isXRetFlag is true.B before redirect.valid. 1165 // ROB sends exception at T0 while CSR receives at T2. 1166 // We add a RegNext here and trapTarget is valid at T3. 1167 csrio.trapTarget := RegEnable( 1168 MuxCase(pcFromXtvec, Seq( 1169 (isXRetFlag && !illegalXret) -> retTargetReg, 1170 (hasDebugExceptionIntr || ebreakEnterParkLoop) -> debugTrapTarget 1171 )), 1172 isXRetFlag || csrio.exception.valid) 1173 1174 when (hasExceptionIntr) { 1175 val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1176 val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct)) 1177 val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct)) 1178 val debugModeNew = WireInit(debugMode) 1179 1180 when (hasDebugExceptionIntr) { 1181 when (hasDebugIntr) { 1182 debugModeNew := true.B 1183 dpc := iexceptionPC 1184 dcsrNew.cause := 3.U 1185 dcsrNew.prv := privilegeMode 1186 privilegeMode := ModeM 1187 XSDebug(hasDebugIntr, "Debug Mode: Trap to %x at pc %x\n", debugTrapTarget, dpc) 1188 }.elsewhen ((hasBreakPoint || hasSingleStep || hasTriggerHit && triggerAction) && !debugMode) { 1189 // ebreak or ss in running hart 1190 debugModeNew := true.B 1191 dpc := iexceptionPC // TODO: check it when hasSingleStep 1192 dcsrNew.cause := Mux(hasTriggerHit, 2.U, Mux(hasBreakPoint, 1.U, 4.U)) 1193 dcsrNew.prv := privilegeMode 1194 privilegeMode := ModeM 1195 } 1196 dcsr := dcsrNew.asUInt 1197 debugIntrEnable := false.B 1198 }.elsewhen (debugMode) { 1199 //do nothing 1200 }.elsewhen (delegS) { 1201 scause := causeNO 1202 sepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC) 1203 mstatusNew.spp := privilegeMode 1204 mstatusNew.pie.s := mstatusOld.ie.s 1205 mstatusNew.ie.s := false.B 1206 privilegeMode := ModeS 1207 when (clearTval) { stval := 0.U } 1208 }.otherwise { 1209 mcause := causeNO 1210 mepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC) 1211 mstatusNew.mpp := privilegeMode 1212 mstatusNew.pie.m := mstatusOld.ie.m 1213 mstatusNew.ie.m := false.B 1214 privilegeMode := ModeM 1215 when (clearTval) { mtval := 0.U } 1216 } 1217 mstatus := mstatusNew.asUInt 1218 debugMode := debugModeNew 1219 } 1220 1221 XSDebug(hasExceptionIntr && delegS, "sepc is written!!! pc:%x\n", cfIn.pc) 1222 1223 // Distributed CSR update req 1224 // 1225 // For now we use it to implement customized cache op 1226 // It can be delayed if necessary 1227 1228 val delayedUpdate0 = DelayN(csrio.distributedUpdate(0), 2) 1229 val delayedUpdate1 = DelayN(csrio.distributedUpdate(1), 2) 1230 val distributedUpdateValid = delayedUpdate0.w.valid || delayedUpdate1.w.valid 1231 val distributedUpdateAddr = Mux(delayedUpdate0.w.valid, 1232 delayedUpdate0.w.bits.addr, 1233 delayedUpdate1.w.bits.addr 1234 ) 1235 val distributedUpdateData = Mux(delayedUpdate0.w.valid, 1236 delayedUpdate0.w.bits.data, 1237 delayedUpdate1.w.bits.data 1238 ) 1239 1240 assert(!(delayedUpdate0.w.valid && delayedUpdate1.w.valid)) 1241 1242 when(distributedUpdateValid){ 1243 // cacheopRegs can be distributed updated 1244 CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => { 1245 when((Scachebase + attribute("offset").toInt).U === distributedUpdateAddr){ 1246 cacheopRegs(name) := distributedUpdateData 1247 } 1248 }} 1249 } 1250 1251 // Cache error debug support 1252 if(HasCustomCSRCacheOp){ 1253 val cache_error_decoder = Module(new CSRCacheErrorDecoder) 1254 cache_error_decoder.io.encoded_cache_error := cacheopRegs("CACHE_ERROR") 1255 } 1256 1257 // Implicit add reset values for mepc[0] and sepc[0] 1258 // TODO: rewrite mepc and sepc using a struct-like style with the LSB always being 0 1259 when (RegNext(RegNext(reset.asBool) && !reset.asBool)) { 1260 mepc := Cat(mepc(XLEN - 1, 1), 0.U(1.W)) 1261 sepc := Cat(sepc(XLEN - 1, 1), 0.U(1.W)) 1262 } 1263 1264 def readWithScala(addr: Int): UInt = mapping(addr)._1 1265 1266 val difftestIntrNO = Mux(hasIntr, causeNO, 0.U) 1267 1268 // Always instantiate basic difftest modules. 1269 if (env.AlwaysBasicDiff || env.EnableDifftest) { 1270 val difftest = DifftestModule(new DiffArchEvent, delay = 3, dontCare = true) 1271 difftest.coreid := csrio.hartId 1272 difftest.valid := csrio.exception.valid 1273 difftest.interrupt := Mux(hasIntr, causeNO, 0.U) 1274 difftest.exception := Mux(hasException, causeNO, 0.U) 1275 difftest.exceptionPC := dexceptionPC 1276 if (env.EnableDifftest) { 1277 difftest.exceptionInst := csrio.exception.bits.uop.cf.instr 1278 } 1279 } 1280 1281 // Always instantiate basic difftest modules. 1282 if (env.AlwaysBasicDiff || env.EnableDifftest) { 1283 val difftest = DifftestModule(new DiffCSRState) 1284 difftest.coreid := csrio.hartId 1285 difftest.privilegeMode := privilegeMode 1286 difftest.mstatus := mstatus 1287 difftest.sstatus := mstatus & sstatusRmask 1288 difftest.mepc := mepc 1289 difftest.sepc := sepc 1290 difftest.mtval:= mtval 1291 difftest.stval:= stval 1292 difftest.mtvec := mtvec 1293 difftest.stvec := stvec 1294 difftest.mcause := mcause 1295 difftest.scause := scause 1296 difftest.satp := satp 1297 difftest.mip := mipReg 1298 difftest.mie := mie 1299 difftest.mscratch := mscratch 1300 difftest.sscratch := sscratch 1301 difftest.mideleg := mideleg 1302 difftest.medeleg := medeleg 1303 } 1304 1305 if(env.AlwaysBasicDiff || env.EnableDifftest) { 1306 val difftest = DifftestModule(new DiffDebugMode) 1307 difftest.coreid := csrio.hartId 1308 difftest.debugMode := debugMode 1309 difftest.dcsr := dcsr 1310 difftest.dpc := dpc 1311 difftest.dscratch0 := dscratch0 1312 difftest.dscratch1 := dscratch1 1313 } 1314} 1315 1316class PFEvent(implicit p: Parameters) extends XSModule with HasCSRConst { 1317 val io = IO(new Bundle { 1318 val distribute_csr = Flipped(new DistributedCSRIO()) 1319 val hpmevent = Output(Vec(29, UInt(XLEN.W))) 1320 }) 1321 1322 val w = io.distribute_csr.w 1323 1324 val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++ 1325 List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++ 1326 List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++ 1327 List.fill(5)(RegInit("hc0300c0300".U(XLEN.W))) 1328 1329 val perfEventMapping = (0 until 29).map(i => {Map( 1330 MaskedRegMap(addr = Mhpmevent3 +i, 1331 reg = perfEvents(i), 1332 wmask = "hf87fff3fcff3fcff".U(XLEN.W)) 1333 )}).fold(Map())((a,b) => a ++ b) 1334 1335 val rdata = Wire(UInt(XLEN.W)) 1336 MaskedRegMap.generate(perfEventMapping, w.bits.addr, rdata, w.valid, w.bits.data) 1337 for(i <- 0 until 29){ 1338 io.hpmevent(i) := perfEvents(i) 1339 } 1340} 1341