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