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