xref: /XiangShan/src/main/scala/xiangshan/backend/fu/CSR.scala (revision 4bc8d97793ef704b2b59dfd69ed1c1a16796b1a6)
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
68class VpuCsrIO(implicit p: Parameters) extends XSBundle {
69  val vstart = Input(UInt(XLEN.W))
70  val vxsat = Input(UInt(1.W))
71  val vxrm = Input(UInt(2.W))
72  val vcsr = Input(UInt(XLEN.W))
73  val vl = Input(UInt(XLEN.W))
74  val vtype = Input(UInt(XLEN.W))
75  val vlenb = Input(UInt(XLEN.W))
76
77  val vill = Input(UInt(1.W))
78  val vma = Input(UInt(1.W))
79  val vta = Input(UInt(1.W))
80  val vsew = Input(UInt(3.W))
81  val vlmul = Input(UInt(3.W))
82
83  val set_vstart = Output(Valid(UInt(XLEN.W)))
84  val set_vl = Output(Valid(UInt(XLEN.W)))
85  val set_vtype = Output(Valid(UInt(XLEN.W)))
86
87  val dirty_vs = Output(Bool())
88}
89
90
91class PerfCounterIO(implicit p: Parameters) extends XSBundle {
92  val perfEventsFrontend  = Vec(numCSRPCntFrontend, new PerfEvent)
93  val perfEventsCtrl      = Vec(numCSRPCntCtrl, new PerfEvent)
94  val perfEventsLsu       = Vec(numCSRPCntLsu, new PerfEvent)
95  val perfEventsHc        = Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent)
96  val retiredInstr = UInt(3.W)
97  val frontendInfo = new Bundle {
98    val ibufFull  = Bool()
99    val bpuInfo = new Bundle {
100      val bpRight = UInt(XLEN.W)
101      val bpWrong = UInt(XLEN.W)
102    }
103  }
104  val ctrlInfo = new Bundle {
105    val robFull   = Bool()
106    val intdqFull = Bool()
107    val fpdqFull  = Bool()
108    val lsdqFull  = Bool()
109  }
110  val memInfo = new Bundle {
111    val sqFull = Bool()
112    val lqFull = Bool()
113    val dcacheMSHRFull = Bool()
114  }
115
116  val cacheInfo = new Bundle {
117    val l2MSHRFull = Bool()
118    val l3MSHRFull = Bool()
119    val l2nAcquire = UInt(XLEN.W)
120    val l2nAcquireMiss = UInt(XLEN.W)
121    val l3nAcquire = UInt(XLEN.W)
122    val l3nAcquireMiss = UInt(XLEN.W)
123  }
124}
125
126class CSRFileIO(implicit p: Parameters) extends XSBundle {
127  val hartId = Input(UInt(8.W))
128  // output (for func === CSROpType.jmp)
129  val perf = Input(new PerfCounterIO)
130  val isPerfCnt = Output(Bool())
131  // to FPU
132  val fpu = Flipped(new FpuCsrIO)
133  // to VPU
134  val vpu = Flipped(new VpuCsrIO)
135  // from rob
136  val exception = Flipped(ValidIO(new ExceptionInfo))
137  // to ROB
138  val isXRet = Output(Bool())
139  val trapTarget = Output(UInt(VAddrBits.W))
140  val interrupt = Output(Bool())
141  val wfi_event = Output(Bool())
142  // from LSQ
143  val memExceptionVAddr = Input(UInt(VAddrBits.W))
144  // from outside cpu,externalInterrupt
145  val externalInterrupt = new ExternalInterruptIO
146  // TLB
147  val tlb = Output(new TlbCsrBundle)
148  // Debug Mode
149  // val singleStep = Output(Bool())
150  val debugMode = Output(Bool())
151  // to Fence to disable sfence
152  val disableSfence = Output(Bool())
153  // Custom microarchiture ctrl signal
154  val customCtrl = Output(new CustomCSRCtrlIO)
155  // distributed csr write
156  val distributedUpdate = Vec(2, Flipped(new DistributedCSRUpdateReq))
157}
158
159class CSR(implicit p: Parameters) extends FunctionUnit with HasCSRConst with PMPMethod with PMAMethod with HasTriggerConst
160{
161  val csrio = IO(new CSRFileIO)
162
163  val cfIn = io.in.bits.uop.cf
164  val cfOut = Wire(new CtrlFlow)
165  cfOut := cfIn
166  val flushPipe = Wire(Bool())
167
168  val (valid, src1, src2, func) = (
169    io.in.valid,
170    io.in.bits.src(0),
171    io.in.bits.uop.ctrl.imm,
172    io.in.bits.uop.ctrl.fuOpType
173  )
174
175  // CSR define
176
177  class Priv extends Bundle {
178    val m = Output(Bool())
179    val h = Output(Bool())
180    val s = Output(Bool())
181    val u = Output(Bool())
182  }
183
184  val csrNotImplemented = RegInit(UInt(XLEN.W), 0.U)
185
186  class DcsrStruct extends Bundle {
187    val xdebugver = Output(UInt(2.W))
188    val zero4 = Output(UInt(2.W))
189    val zero3 = Output(UInt(12.W))
190    val ebreakm = Output(Bool())
191    val ebreakh = Output(Bool())
192    val ebreaks = Output(Bool())
193    val ebreaku = Output(Bool())
194    val stepie = Output(Bool()) // 0
195    val stopcycle = Output(Bool())
196    val stoptime = Output(Bool())
197    val cause = Output(UInt(3.W))
198    val v = Output(Bool()) // 0
199    val mprven = Output(Bool())
200    val nmip = Output(Bool())
201    val step = Output(Bool())
202    val prv = Output(UInt(2.W))
203  }
204
205  class MstatusStruct extends Bundle {
206    val sd = Output(UInt(1.W))
207
208    val pad1 = if (XLEN == 64) Output(UInt(25.W)) else null
209    val mbe  = if (XLEN == 64) Output(UInt(1.W)) else null
210    val sbe  = if (XLEN == 64) Output(UInt(1.W)) else null
211    val sxl  = if (XLEN == 64) Output(UInt(2.W))  else null
212    val uxl  = if (XLEN == 64) Output(UInt(2.W))  else null
213    val pad0 = if (XLEN == 64) Output(UInt(9.W))  else Output(UInt(8.W))
214
215    val tsr = Output(UInt(1.W))
216    val tw = Output(UInt(1.W))
217    val tvm = Output(UInt(1.W))
218    val mxr = Output(UInt(1.W))
219    val sum = Output(UInt(1.W))
220    val mprv = Output(UInt(1.W))
221    val xs = Output(UInt(2.W))
222    val fs = Output(UInt(2.W))
223    val mpp = Output(UInt(2.W))
224    val vs = Output(UInt(2.W))
225    val spp = Output(UInt(1.W))
226    val pie = new Priv
227    val ie = new Priv
228    assert(this.getWidth == XLEN)
229
230    def ube = pie.h // a little ugly
231    def ube_(r: UInt): Unit = {
232      pie.h := r(0)
233    }
234  }
235
236  class Interrupt extends Bundle {
237//  val d = Output(Bool())    // Debug
238    val e = new Priv
239    val t = new Priv
240    val s = new Priv
241  }
242
243  // Debug CSRs
244  val dcsr = RegInit(UInt(32.W), 0x4000b000.U)
245  val dpc = Reg(UInt(64.W))
246  val dscratch = Reg(UInt(64.W))
247  val dscratch1 = Reg(UInt(64.W))
248  val debugMode = RegInit(false.B)
249  val debugIntrEnable = RegInit(true.B)
250  csrio.debugMode := debugMode
251
252  val dpcPrev = RegNext(dpc)
253  XSDebug(dpcPrev =/= dpc, "Debug Mode: dpc is altered! Current is %x, previous is %x\n", dpc, dpcPrev)
254
255  // dcsr value table
256  // | debugver | 0100
257  // | zero     | 10 bits of 0
258  // | ebreakvs | 0
259  // | ebreakvu | 0
260  // | ebreakm  | 1 if ebreak enters debug
261  // | zero     | 0
262  // | ebreaks  |
263  // | ebreaku  |
264  // | stepie   | disable interrupts in singlestep
265  // | stopcount| stop counter, 0
266  // | stoptime | stop time, 0
267  // | cause    | 3 bits read only
268  // | v        | 0
269  // | mprven   | 1
270  // | nmip     | read only
271  // | step     |
272  // | prv      | 2 bits
273
274  val dcsrData = Wire(new DcsrStruct)
275  dcsrData := dcsr.asTypeOf(new DcsrStruct)
276  val dcsrMask = ZeroExt(GenMask(15) | GenMask(13, 11) | GenMask(4) | GenMask(2, 0), XLEN)// Dcsr write mask
277  def dcsrUpdateSideEffect(dcsr: UInt): UInt = {
278    val dcsrOld = WireInit(dcsr.asTypeOf(new DcsrStruct))
279    val dcsrNew = dcsr | (dcsrOld.prv(0) | dcsrOld.prv(1)).asUInt // turn 10 priv into 11
280    dcsrNew
281  }
282  // csrio.singleStep := dcsrData.step
283  csrio.customCtrl.singlestep := dcsrData.step && !debugMode
284
285  // Trigger CSRs
286
287  val type_config = Array(
288    0.U -> I_Trigger, 1.U -> I_Trigger,
289    2.U -> S_Trigger, 3.U -> S_Trigger,
290    4.U -> L_Trigger, 5.U -> L_Trigger, // No.5 Load Trigger
291    6.U -> I_Trigger, 7.U -> S_Trigger,
292    8.U -> I_Trigger, 9.U -> L_Trigger
293  )
294  def TypeLookup(select: UInt) = MuxLookup(select, I_Trigger, type_config)
295
296  val tdata1Phy = RegInit(VecInit(List.fill(10) {(2L << 60L).U(64.W)})) // init ttype 2
297  val tdata2Phy = Reg(Vec(10, UInt(64.W)))
298  val tselectPhy = RegInit(0.U(4.W))
299  val tinfo = RegInit(2.U(64.W))
300  val tControlPhy = RegInit(0.U(64.W))
301  val triggerAction = RegInit(false.B)
302
303  def ReadTdata1(rdata: UInt) = rdata | Cat(triggerAction, 0.U(12.W)) // fix action
304  def WriteTdata1(wdata: UInt): UInt = {
305    val tdata1 = WireInit(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle))
306    val wdata_wire = WireInit(wdata.asTypeOf(new TdataBundle))
307    val tdata1_new = WireInit(wdata.asTypeOf(new TdataBundle))
308    XSDebug(src2(11, 0) === Tdata1.U && valid && func =/= CSROpType.jmp, p"Debug Mode: tdata1(${tselectPhy})is written, the actual value is ${wdata}\n")
309//    tdata1_new.hit := wdata(20)
310    tdata1_new.ttype := tdata1.ttype
311    tdata1_new.dmode := 0.U // Mux(debugMode, wdata_wire.dmode, tdata1.dmode)
312    tdata1_new.maskmax := 0.U
313    tdata1_new.hit := 0.U
314    tdata1_new.select := (TypeLookup(tselectPhy) === I_Trigger) && wdata_wire.select
315    when(wdata_wire.action <= 1.U){
316      triggerAction := tdata1_new.action(0)
317    } .otherwise{
318      tdata1_new.action := tdata1.action
319    }
320    tdata1_new.timing := false.B // hardwire this because we have singlestep
321    tdata1_new.zero1 := 0.U
322    tdata1_new.zero2 := 0.U
323    tdata1_new.chain := !tselectPhy(0) && wdata_wire.chain
324    when(wdata_wire.matchType =/= 0.U && wdata_wire.matchType =/= 2.U && wdata_wire.matchType =/= 3.U) {
325      tdata1_new.matchType := tdata1.matchType
326    }
327    tdata1_new.sizehi := Mux(wdata_wire.select && TypeLookup(tselectPhy) === I_Trigger, 0.U, 1.U)
328    tdata1_new.sizelo:= Mux(wdata_wire.select && TypeLookup(tselectPhy) === I_Trigger, 3.U, 1.U)
329    tdata1_new.execute := TypeLookup(tselectPhy) === I_Trigger
330    tdata1_new.store := TypeLookup(tselectPhy) === S_Trigger
331    tdata1_new.load := TypeLookup(tselectPhy) === L_Trigger
332    tdata1_new.asUInt
333  }
334
335  def WriteTselect(wdata: UInt) = {
336    Mux(wdata < 10.U, wdata(3, 0), tselectPhy)
337  }
338
339  val tcontrolWriteMask = ZeroExt(GenMask(3) | GenMask(7), XLEN)
340
341
342  def GenTdataDistribute(tdata1: TdataBundle, tdata2: UInt): MatchTriggerIO = {
343    val res = Wire(new MatchTriggerIO)
344    res.matchType := tdata1.matchType
345    res.select := tdata1.select
346    res.timing := tdata1.timing
347    res.action := triggerAction
348    res.chain := tdata1.chain
349    res.tdata2 := tdata2
350    res
351  }
352
353  csrio.customCtrl.frontend_trigger.t.bits.addr := MuxLookup(tselectPhy, 0.U, Seq(
354    0.U -> 0.U,
355    1.U -> 1.U,
356    6.U -> 2.U,
357    8.U -> 3.U
358  ))
359  csrio.customCtrl.mem_trigger.t.bits.addr := MuxLookup(tselectPhy, 0.U, Seq(
360    2.U -> 0.U,
361    3.U -> 1.U,
362    4.U -> 2.U,
363    5.U -> 3.U,
364    7.U -> 4.U,
365    9.U -> 5.U
366  ))
367  csrio.customCtrl.frontend_trigger.t.bits.tdata := GenTdataDistribute(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle), tdata2Phy(tselectPhy))
368  csrio.customCtrl.mem_trigger.t.bits.tdata := GenTdataDistribute(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle), tdata2Phy(tselectPhy))
369
370  // Machine-Level CSRs
371  // mtvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1
372  val mtvecMask = ~(0x2.U(XLEN.W))
373  val mtvec = RegInit(UInt(XLEN.W), 0.U)
374  val mcounteren = RegInit(UInt(XLEN.W), 0.U)
375  val mcause = RegInit(UInt(XLEN.W), 0.U)
376  val mtval = RegInit(UInt(XLEN.W), 0.U)
377  val mepc = Reg(UInt(XLEN.W))
378  // Page 36 in riscv-priv: The low bit of mepc (mepc[0]) is always zero.
379  val mepcMask = ~(0x1.U(XLEN.W))
380
381  val mie = RegInit(0.U(XLEN.W))
382  val mipWire = WireInit(0.U.asTypeOf(new Interrupt))
383  val mipReg  = RegInit(0.U(XLEN.W))
384  val mipFixMask = ZeroExt(GenMask(9) | GenMask(5) | GenMask(1), XLEN)
385  val mip = (mipWire.asUInt | mipReg).asTypeOf(new Interrupt)
386
387  def getMisaMxl(mxl: Int): UInt = {mxl.U << (XLEN-2)}.asUInt
388  def getMisaExt(ext: Char): UInt = {1.U << (ext.toInt - 'a'.toInt)}.asUInt
389  var extList = List('a', 's', 'i', 'u')
390  if (HasMExtension) { extList = extList :+ 'm' }
391  if (HasCExtension) { extList = extList :+ 'c' }
392  if (HasFPU) { extList = extList ++ List('f', 'd') }
393  if (HasVPU) { extList = extList :+ 'v' }
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  // | vs  | 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  //  +------------------------------+---+----+----+-----+--------+
532  //  |XLEN-1                       8| 7 | 6  | 5  |  4  |3      0|
533  //  +------------------------------+---+----+----+-----+--------+
534  //  |           Reserved           | O | CE | SP | LVC |   Th   |
535  //  +------------------------------+---+----+----+-----+--------+
536  //  Description:
537  //  Bit 3-0   : Store buffer flush threshold (Th).
538  //  Bit 4     : Enable load violation check after reset (LVC).
539  //  Bit 5     : Enable soft-prefetch after reset (SP).
540  //  Bit 6     : Enable cache error after reset (CE).
541  //  Bit 7     : Enable uncache write outstanding (O).
542  //  Others    : Reserved.
543
544  val smblockctl_init_val =
545    ("hf".U & StoreBufferThreshold.U) |
546    (EnableLdVioCheckAfterReset.B.asUInt << 4) |
547    (EnableSoftPrefetchAfterReset.B.asUInt << 5) |
548    (EnableCacheErrorAfterReset.B.asUInt << 6) |
549    (EnableUncacheWriteOutstanding.B.asUInt << 7)
550  val smblockctl = RegInit(UInt(XLEN.W), smblockctl_init_val)
551  csrio.customCtrl.sbuffer_threshold := smblockctl(3, 0)
552  // bits 4: enable load load violation check
553  csrio.customCtrl.ldld_vio_check_enable := smblockctl(4)
554  csrio.customCtrl.soft_prefetch_enable := smblockctl(5)
555  csrio.customCtrl.cache_error_enable := smblockctl(6)
556  csrio.customCtrl.uncache_write_outstanding_enable := smblockctl(7)
557
558  println("CSR smblockctl init value:")
559  println("  Store buffer replace threshold: " + StoreBufferThreshold)
560  println("  Enable ld-ld vio check after reset: " + EnableLdVioCheckAfterReset)
561  println("  Enable soft prefetch after reset: " + EnableSoftPrefetchAfterReset)
562  println("  Enable cache error after reset: " + EnableCacheErrorAfterReset)
563  println("  Enable uncache write outstanding: " + EnableUncacheWriteOutstanding)
564
565  val srnctl = RegInit(UInt(XLEN.W), "h7".U)
566  csrio.customCtrl.fusion_enable := srnctl(0)
567  csrio.customCtrl.svinval_enable := srnctl(1)
568  csrio.customCtrl.wfi_enable := srnctl(2)
569
570  val tlbBundle = Wire(new TlbCsrBundle)
571  tlbBundle.satp.apply(satp)
572
573  csrio.tlb := tlbBundle
574
575  // User-Level CSRs
576  val uepc = Reg(UInt(XLEN.W))
577
578  // fcsr
579  class FcsrStruct extends Bundle {
580    val reserved = UInt((XLEN-3-5).W)
581    val frm = UInt(3.W)
582    val fflags = UInt(5.W)
583    assert(this.getWidth == XLEN)
584  }
585  val fcsr = RegInit(0.U(XLEN.W))
586  // set mstatus->sd and mstatus->fs when true
587  val csrw_dirty_fp_state = WireInit(false.B)
588
589  def frm_wfn(wdata: UInt): UInt = {
590    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
591    csrw_dirty_fp_state := true.B
592    fcsrOld.frm := wdata(2,0)
593    fcsrOld.asUInt
594  }
595  def frm_rfn(rdata: UInt): UInt = rdata(7,5)
596
597  def fflags_wfn(update: Boolean)(wdata: UInt): UInt = {
598    val fcsrOld = fcsr.asTypeOf(new FcsrStruct)
599    val fcsrNew = WireInit(fcsrOld)
600    csrw_dirty_fp_state := true.B
601    if (update) {
602      fcsrNew.fflags := wdata(4,0) | fcsrOld.fflags
603    } else {
604      fcsrNew.fflags := wdata(4,0)
605    }
606    fcsrNew.asUInt
607  }
608  def fflags_rfn(rdata:UInt): UInt = rdata(4,0)
609
610  def fcsr_wfn(wdata: UInt): UInt = {
611    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
612    csrw_dirty_fp_state := true.B
613    Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags)
614  }
615
616  val fcsrMapping = Map(
617    MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn(update = false), rfn = fflags_rfn),
618    MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn),
619    MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn)
620  )
621
622  // Vector extension CSRs
623  val vstart = Reg(UInt(XLEN.W))
624  val vcsr = RegInit(0.U(XLEN.W))
625  val vl = Reg(UInt(XLEN.W))
626  val vtype = Reg(UInt(XLEN.W))
627  val vlenb = RegInit(0.U(XLEN.W))
628
629  // set mstatus->sd and mstatus->vs when true
630  val csrw_dirty_vs_state = WireInit(false.B)
631
632  // vcsr is mapped to vxrm and vxsat
633  class VcsrStruct extends Bundle {
634    val reserved = UInt((XLEN-3).W)
635    val vxrm = UInt(2.W)
636    val vxsat = UInt(1.W)
637    assert(this.getWidth == XLEN)
638  }
639
640  class VtypeStruct extends Bundle {
641    val vill = UInt(1.W)
642    val reserved = UInt((XLEN-9).W)
643    val vma = UInt(1.W)
644    val vta = UInt(1.W)
645    val vsew = UInt(3.W)
646    val vlmul = UInt(3.W)
647  }
648
649  def vxrm_wfn(wdata: UInt): UInt = {
650    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
651    csrw_dirty_vs_state := true.B
652    vcsrOld.vxrm := wdata(1,0)
653    vcsrOld.asUInt
654  }
655  def vxrm_rfn(rdata: UInt): UInt = rdata(2,1)
656
657  def vxsat_wfn(wdata: UInt): UInt = {
658    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
659    csrw_dirty_vs_state := true.B
660    vcsrOld.vxsat := wdata(0)
661    vcsrOld.asUInt
662  }
663  def vxsat_rfn(rdata: UInt): UInt = rdata(0)
664
665  def vcsr_wfn(wdata: UInt): UInt = {
666    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
667    csrw_dirty_vs_state := true.B
668    vcsrOld.vxrm := wdata.asTypeOf(vcsrOld).vxrm
669    vcsrOld.vxsat := wdata.asTypeOf(vcsrOld).vxsat
670    vcsrOld.asUInt
671  }
672
673  val vcsrMapping = Map(
674    MaskedRegMap(Vstart, vstart),
675    MaskedRegMap(Vxrm, vcsr, wfn = vxrm_wfn, rfn = vxrm_rfn),
676    MaskedRegMap(Vxsat, vcsr, wfn = vxsat_wfn, rfn = vxsat_rfn),
677    MaskedRegMap(Vcsr, vcsr, wfn = vcsr_wfn),
678    MaskedRegMap(Vl, vl),
679    MaskedRegMap(Vtype, vtype),
680    MaskedRegMap(Vlenb, vlenb),
681  )
682
683  // Hart Priviledge Mode
684  val priviledgeMode = RegInit(UInt(2.W), ModeM)
685
686  //val perfEventscounten = List.fill(nrPerfCnts)(RegInit(false(Bool())))
687  // Perf Counter
688  val nrPerfCnts = 29  // 3...31
689  val priviledgeModeOH = UIntToOH(priviledgeMode)
690  val perfEventscounten = RegInit(0.U.asTypeOf(Vec(nrPerfCnts, Bool())))
691  val perfCnts   = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W)))
692  val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++
693                   List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++
694                   List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++
695                   List.fill(5)(RegInit("hc0300c0300".U(XLEN.W)))
696  for (i <-0 until nrPerfCnts) {
697    perfEventscounten(i) := (Cat(perfEvents(i)(62),perfEvents(i)(61),(perfEvents(i)(61,60))) & priviledgeModeOH).orR
698  }
699
700  val hpmEvents = Wire(Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent))
701  for (i <- 0 until numPCntHc * coreParams.L2NBanks) {
702    hpmEvents(i) := csrio.perf.perfEventsHc(i)
703  }
704
705  val csrevents = perfEvents.slice(24, 29)
706  val hpm_hc = HPerfMonitor(csrevents, hpmEvents)
707  val mcountinhibit = RegInit(0.U(XLEN.W))
708  val mcycle = RegInit(0.U(XLEN.W))
709  mcycle := mcycle + 1.U
710  val minstret = RegInit(0.U(XLEN.W))
711  val perf_events = csrio.perf.perfEventsFrontend ++
712                    csrio.perf.perfEventsCtrl ++
713                    csrio.perf.perfEventsLsu ++
714                    hpm_hc.getPerf
715  minstret := minstret + RegNext(csrio.perf.retiredInstr)
716  for(i <- 0 until 29){
717    perfCnts(i) := Mux(mcountinhibit(i+3) | !perfEventscounten(i), perfCnts(i), perfCnts(i) + perf_events(i).value)
718  }
719
720  // CSR reg map
721  val basicPrivMapping = Map(
722
723    //--- User Trap Setup ---
724    // MaskedRegMap(Ustatus, ustatus),
725    // MaskedRegMap(Uie, uie, 0.U, MaskedRegMap.Unwritable),
726    // MaskedRegMap(Utvec, utvec),
727
728    //--- User Trap Handling ---
729    // MaskedRegMap(Uscratch, uscratch),
730    // MaskedRegMap(Uepc, uepc),
731    // MaskedRegMap(Ucause, ucause),
732    // MaskedRegMap(Utval, utval),
733    // MaskedRegMap(Uip, uip),
734
735    //--- User Counter/Timers ---
736    // MaskedRegMap(Cycle, cycle),
737    // MaskedRegMap(Time, time),
738    // MaskedRegMap(Instret, instret),
739
740    //--- Supervisor Trap Setup ---
741    MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask),
742    // MaskedRegMap(Sedeleg, Sedeleg),
743    // MaskedRegMap(Sideleg, Sideleg),
744    MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask),
745    MaskedRegMap(Stvec, stvec, stvecMask, MaskedRegMap.NoSideEffect, stvecMask),
746    MaskedRegMap(Scounteren, scounteren),
747
748    //--- Supervisor Trap Handling ---
749    MaskedRegMap(Sscratch, sscratch),
750    MaskedRegMap(Sepc, sepc, sepcMask, MaskedRegMap.NoSideEffect, sepcMask),
751    MaskedRegMap(Scause, scause),
752    MaskedRegMap(Stval, stval),
753    MaskedRegMap(Sip, mip.asUInt, sipWMask, MaskedRegMap.Unwritable, sipMask),
754
755    //--- Supervisor Protection and Translation ---
756    MaskedRegMap(Satp, satp, satpMask, MaskedRegMap.NoSideEffect, satpMask),
757
758    //--- Supervisor Custom Read/Write Registers
759    MaskedRegMap(Sbpctl, sbpctl),
760    MaskedRegMap(Spfctl, spfctl),
761    MaskedRegMap(Sfetchctl, sfetchctl),
762    MaskedRegMap(Sdsid, sdsid),
763    MaskedRegMap(Slvpredctl, slvpredctl),
764    MaskedRegMap(Smblockctl, smblockctl),
765    MaskedRegMap(Srnctl, srnctl),
766
767    //--- Machine Information Registers ---
768    MaskedRegMap(Mvendorid, mvendorid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
769    MaskedRegMap(Marchid, marchid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
770    MaskedRegMap(Mimpid, mimpid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
771    MaskedRegMap(Mhartid, mhartid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
772    MaskedRegMap(Mconfigptr, mconfigptr, 0.U(XLEN.W), MaskedRegMap.Unwritable),
773
774    //--- Machine Trap Setup ---
775    MaskedRegMap(Mstatus, mstatus, mstatusWMask, mstatusUpdateSideEffect, mstatusMask),
776    MaskedRegMap(Misa, misa, 0.U, MaskedRegMap.Unwritable), // now whole misa is unchangeable
777    MaskedRegMap(Medeleg, medeleg, "hb3ff".U(XLEN.W)),
778    MaskedRegMap(Mideleg, mideleg, "h222".U(XLEN.W)),
779    MaskedRegMap(Mie, mie),
780    MaskedRegMap(Mtvec, mtvec, mtvecMask, MaskedRegMap.NoSideEffect, mtvecMask),
781    MaskedRegMap(Mcounteren, mcounteren),
782
783    //--- Machine Trap Handling ---
784    MaskedRegMap(Mscratch, mscratch),
785    MaskedRegMap(Mepc, mepc, mepcMask, MaskedRegMap.NoSideEffect, mepcMask),
786    MaskedRegMap(Mcause, mcause),
787    MaskedRegMap(Mtval, mtval),
788    MaskedRegMap(Mip, mip.asUInt, 0.U(XLEN.W), MaskedRegMap.Unwritable),
789
790    //--- Trigger ---
791    MaskedRegMap(Tselect, tselectPhy, WritableMask, WriteTselect),
792    MaskedRegMap(Tdata1, tdata1Phy(tselectPhy), WritableMask, WriteTdata1, WritableMask, ReadTdata1),
793    MaskedRegMap(Tdata2, tdata2Phy(tselectPhy)),
794    MaskedRegMap(Tinfo, tinfo, 0.U(XLEN.W), MaskedRegMap.Unwritable),
795    MaskedRegMap(Tcontrol, tControlPhy, tcontrolWriteMask),
796
797    //--- Debug Mode ---
798    MaskedRegMap(Dcsr, dcsr, dcsrMask, dcsrUpdateSideEffect),
799    MaskedRegMap(Dpc, dpc),
800    MaskedRegMap(Dscratch, dscratch),
801    MaskedRegMap(Dscratch1, dscratch1),
802    MaskedRegMap(Mcountinhibit, mcountinhibit),
803    MaskedRegMap(Mcycle, mcycle),
804    MaskedRegMap(Minstret, minstret),
805  )
806
807  val perfCntMapping = (0 until 29).map(i => {Map(
808    MaskedRegMap(addr = Mhpmevent3 +i,
809                 reg  = perfEvents(i),
810                 wmask = "hf87fff3fcff3fcff".U(XLEN.W)),
811    MaskedRegMap(addr = Mhpmcounter3 +i,
812                 reg  = perfCnts(i))
813  )}).fold(Map())((a,b) => a ++ b)
814  // TODO: mechanism should be implemented later
815  // val MhpmcounterStart = Mhpmcounter3
816  // val MhpmeventStart   = Mhpmevent3
817  // for (i <- 0 until nrPerfCnts) {
818  //   perfCntMapping += MaskedRegMap(MhpmcounterStart + i, perfCnts(i))
819  //   perfCntMapping += MaskedRegMap(MhpmeventStart + i, perfEvents(i))
820  // }
821
822  val cacheopRegs = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
823    name -> RegInit(0.U(attribute("width").toInt.W))
824  }}
825  val cacheopMapping = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
826    MaskedRegMap(
827      Scachebase + attribute("offset").toInt,
828      cacheopRegs(name)
829    )
830  }}
831
832  val mapping = basicPrivMapping ++
833                perfCntMapping ++
834                pmpMapping ++
835                pmaMapping ++
836                (if (HasFPU) fcsrMapping else Nil) ++
837                (if (HasVPU) vcsrMapping else Nil) ++
838                (if (HasCustomCSRCacheOp) cacheopMapping else Nil)
839
840  val addr = src2(11, 0)
841  val csri = ZeroExt(src2(16, 12), XLEN)
842  val rdata = Wire(UInt(XLEN.W))
843  val wdata = LookupTree(func, List(
844    CSROpType.wrt  -> src1,
845    CSROpType.set  -> (rdata | src1),
846    CSROpType.clr  -> (rdata & (~src1).asUInt),
847    CSROpType.wrti -> csri,
848    CSROpType.seti -> (rdata | csri),
849    CSROpType.clri -> (rdata & (~csri).asUInt)
850  ))
851
852  val addrInPerfCnt = (addr >= Mcycle.U) && (addr <= Mhpmcounter31.U) ||
853    (addr >= Mcountinhibit.U) && (addr <= Mhpmevent31.U) ||
854    addr === Mip.U
855  csrio.isPerfCnt := addrInPerfCnt && valid && func =/= CSROpType.jmp
856
857  // satp wen check
858  val satpLegalMode = (wdata.asTypeOf(new SatpStruct).mode===0.U) || (wdata.asTypeOf(new SatpStruct).mode===8.U)
859
860  // csr access check, special case
861  val tvmNotPermit = (priviledgeMode === ModeS && mstatusStruct.tvm.asBool)
862  val accessPermitted = !(addr === Satp.U && tvmNotPermit)
863  csrio.disableSfence := tvmNotPermit
864
865  // general CSR wen check
866  val wen = valid && func =/= CSROpType.jmp && (addr=/=Satp.U || satpLegalMode)
867  val dcsrPermitted = dcsrPermissionCheck(addr, false.B, debugMode)
868  val triggerPermitted = triggerPermissionCheck(addr, true.B, debugMode) // todo dmode
869  val modePermitted = csrAccessPermissionCheck(addr, false.B, priviledgeMode) && dcsrPermitted && triggerPermitted
870  val perfcntPermitted = perfcntPermissionCheck(addr, priviledgeMode, mcounteren, scounteren)
871  val permitted = Mux(addrInPerfCnt, perfcntPermitted, modePermitted) && accessPermitted
872
873  MaskedRegMap.generate(mapping, addr, rdata, wen && permitted, wdata)
874  io.out.bits.data := rdata
875  io.out.bits.uop := io.in.bits.uop
876  io.out.bits.uop.cf := cfOut
877  io.out.bits.uop.ctrl.flushPipe := flushPipe
878
879  // send distribute csr a w signal
880  csrio.customCtrl.distribute_csr.w.valid := wen && permitted
881  csrio.customCtrl.distribute_csr.w.bits.data := wdata
882  csrio.customCtrl.distribute_csr.w.bits.addr := addr
883
884  // Fix Mip/Sip write
885  val fixMapping = Map(
886    MaskedRegMap(Mip, mipReg.asUInt, mipFixMask),
887    MaskedRegMap(Sip, mipReg.asUInt, sipWMask, MaskedRegMap.NoSideEffect, sipMask)
888  )
889  val rdataFix = Wire(UInt(XLEN.W))
890  val wdataFix = LookupTree(func, List(
891    CSROpType.wrt  -> src1,
892    CSROpType.set  -> (rdataFix | src1),
893    CSROpType.clr  -> (rdataFix & (~src1).asUInt),
894    CSROpType.wrti -> csri,
895    CSROpType.seti -> (rdataFix | csri),
896    CSROpType.clri -> (rdataFix & (~csri).asUInt)
897  ))
898  MaskedRegMap.generate(fixMapping, addr, rdataFix, wen && permitted, wdataFix)
899
900  when (RegNext(csrio.fpu.fflags.valid)) {
901    fcsr := fflags_wfn(update = true)(RegNext(csrio.fpu.fflags.bits))
902  }
903  // set fs and sd in mstatus
904  when (csrw_dirty_fp_state || RegNext(csrio.fpu.dirty_fs)) {
905    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
906    mstatusNew.fs := "b11".U
907    mstatusNew.sd := true.B
908    mstatus := mstatusNew.asUInt
909  }
910  csrio.fpu.frm := fcsr.asTypeOf(new FcsrStruct).frm
911
912  when (RegNext(csrio.vpu.set_vstart.valid)) {
913    vstart := RegNext(csrio.vpu.set_vstart.bits)
914  }
915  when (RegNext(csrio.vpu.set_vtype.valid)) {
916    vtype := RegNext(csrio.vpu.set_vtype.bits)
917  }
918  when (RegNext(csrio.vpu.set_vl.valid)) {
919    vl := RegNext(csrio.vpu.set_vl.bits)
920  }
921  // set vs and sd in mstatus
922  // when (csrw_dirty_vs_state || RegNext(csrio.vpu.dirty_vs)) {
923  //   val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
924  //   mstatusNew.vs := "b11".U
925  //   mstatusNew.sd := true.B
926  //   mstatus := mstatusNew.asUInt
927  // }
928
929  csrio.vpu.vstart := vstart
930  csrio.vpu.vxrm := vcsr.asTypeOf(new VcsrStruct).vxrm
931  csrio.vpu.vxsat := vcsr.asTypeOf(new VcsrStruct).vxsat
932  csrio.vpu.vcsr := vcsr
933  csrio.vpu.vtype := vtype
934  csrio.vpu.vl := vl
935  csrio.vpu.vlenb := vlenb
936  csrio.vpu.vill := vtype.asTypeOf(new VtypeStruct).vill
937  csrio.vpu.vma := vtype.asTypeOf(new VtypeStruct).vma
938  csrio.vpu.vta := vtype.asTypeOf(new VtypeStruct).vta
939  csrio.vpu.vsew := vtype.asTypeOf(new VtypeStruct).vsew
940  csrio.vpu.vlmul := vtype.asTypeOf(new VtypeStruct).vlmul
941
942  // Trigger Ctrl
943  csrio.customCtrl.trigger_enable := tdata1Phy.map{t =>
944    def tdata1 = t.asTypeOf(new TdataBundle)
945    tdata1.m && priviledgeMode === ModeM ||
946    tdata1.s && priviledgeMode === ModeS || tdata1.u && priviledgeMode === ModeU
947  }
948  csrio.customCtrl.frontend_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) === I_Trigger)
949  csrio.customCtrl.mem_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) =/= I_Trigger)
950  XSDebug(csrio.customCtrl.trigger_enable.asUInt.orR, p"Debug Mode: At least 1 trigger is enabled," +
951    p"trigger enable is ${Binary(csrio.customCtrl.trigger_enable.asUInt)}\n")
952
953  // CSR inst decode
954  val isEbreak = addr === privEbreak && func === CSROpType.jmp
955  val isEcall  = addr === privEcall  && func === CSROpType.jmp
956  val isMret   = addr === privMret   && func === CSROpType.jmp
957  val isSret   = addr === privSret   && func === CSROpType.jmp
958  val isUret   = addr === privUret   && func === CSROpType.jmp
959  val isDret   = addr === privDret   && func === CSROpType.jmp
960  val isWFI    = func === CSROpType.wfi
961
962  XSDebug(wen, "csr write: pc %x addr %x rdata %x wdata %x func %x\n", cfIn.pc, addr, rdata, wdata, func)
963  XSDebug(wen, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", cfIn.pc, mstatus, mideleg , medeleg, priviledgeMode)
964
965  // Illegal priviledged operation list
966  val illegalMret = valid && isMret && priviledgeMode < ModeM
967  val illegalSret = valid && isSret && priviledgeMode < ModeS
968  val illegalSModeSret = valid && isSret && priviledgeMode === ModeS && mstatusStruct.tsr.asBool
969  // When TW=1, then if WFI is executed in any less-privileged mode,
970  // and it does not complete within an implementation-specific, bounded time limit,
971  // the WFI instruction causes an illegal instruction exception.
972  // The time limit may always be 0, in which case WFI always causes
973  // an illegal instruction exception in less-privileged modes when TW=1.
974  val illegalWFI = valid && isWFI && priviledgeMode < ModeM && mstatusStruct.tw === 1.U
975
976  // Illegal priviledged instruction check
977  val isIllegalAddr = valid && CSROpType.needAccess(func) && MaskedRegMap.isIllegalAddr(mapping, addr)
978  val isIllegalAccess = wen && !permitted
979  val isIllegalPrivOp = illegalMret || illegalSret || illegalSModeSret || illegalWFI
980
981  // expose several csr bits for tlb
982  tlbBundle.priv.mxr   := mstatusStruct.mxr.asBool
983  tlbBundle.priv.sum   := mstatusStruct.sum.asBool
984  tlbBundle.priv.imode := priviledgeMode
985  tlbBundle.priv.dmode := Mux(debugMode && dcsr.asTypeOf(new DcsrStruct).mprven, ModeM, Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpp, priviledgeMode))
986
987  // Branch control
988  val retTarget = Wire(UInt(VAddrBits.W))
989  val resetSatp = addr === Satp.U && wen // write to satp will cause the pipeline be flushed
990  flushPipe := resetSatp || (valid && func === CSROpType.jmp && !isEcall && !isEbreak)
991
992  retTarget := DontCare
993  // val illegalEret = TODO
994
995  when (valid && isDret) {
996    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
997    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
998    val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct))
999    val debugModeNew = WireInit(debugMode)
1000    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.
1001    mstatus := mstatusNew.asUInt
1002    priviledgeMode := dcsrNew.prv
1003    retTarget := dpc(VAddrBits-1, 0)
1004    debugModeNew := false.B
1005    debugIntrEnable := true.B
1006    debugMode := debugModeNew
1007    XSDebug("Debug Mode: Dret executed, returning to %x.", retTarget)
1008  }
1009
1010  when (valid && isMret && !illegalMret) {
1011    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1012    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1013    mstatusNew.ie.m := mstatusOld.pie.m
1014    priviledgeMode := mstatusOld.mpp
1015    mstatusNew.pie.m := true.B
1016    mstatusNew.mpp := ModeU
1017    when (mstatusOld.mpp =/= ModeM) { mstatusNew.mprv := 0.U }
1018    mstatus := mstatusNew.asUInt
1019    // lr := false.B
1020    retTarget := mepc(VAddrBits-1, 0)
1021  }
1022
1023  when (valid && isSret && !illegalSret && !illegalSModeSret) {
1024    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1025    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1026    mstatusNew.ie.s := mstatusOld.pie.s
1027    priviledgeMode := Cat(0.U(1.W), mstatusOld.spp)
1028    mstatusNew.pie.s := true.B
1029    mstatusNew.spp := ModeU
1030    mstatus := mstatusNew.asUInt
1031    when (mstatusOld.spp =/= ModeM) { mstatusNew.mprv := 0.U }
1032    // lr := false.B
1033    retTarget := sepc(VAddrBits-1, 0)
1034  }
1035
1036  when (valid && isUret) {
1037    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1038    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1039    // mstatusNew.mpp.m := ModeU //TODO: add mode U
1040    mstatusNew.ie.u := mstatusOld.pie.u
1041    priviledgeMode := ModeU
1042    mstatusNew.pie.u := true.B
1043    mstatus := mstatusNew.asUInt
1044    retTarget := uepc(VAddrBits-1, 0)
1045  }
1046
1047  io.in.ready := true.B
1048  io.out.valid := valid
1049
1050  val ebreakCauseException = (priviledgeMode === ModeM && dcsrData.ebreakm) || (priviledgeMode === ModeS && dcsrData.ebreaks) || (priviledgeMode === ModeU && dcsrData.ebreaku)
1051
1052  val csrExceptionVec = WireInit(cfIn.exceptionVec)
1053  csrExceptionVec(breakPoint) := io.in.valid && isEbreak && (ebreakCauseException || debugMode)
1054  csrExceptionVec(ecallM) := priviledgeMode === ModeM && io.in.valid && isEcall
1055  csrExceptionVec(ecallS) := priviledgeMode === ModeS && io.in.valid && isEcall
1056  csrExceptionVec(ecallU) := priviledgeMode === ModeU && io.in.valid && isEcall
1057  // Trigger an illegal instr exception when:
1058  // * unimplemented csr is being read/written
1059  // * csr access is illegal
1060  csrExceptionVec(illegalInstr) := isIllegalAddr || isIllegalAccess || isIllegalPrivOp
1061  cfOut.exceptionVec := csrExceptionVec
1062
1063  XSDebug(io.in.valid && isEbreak, s"Debug Mode: an Ebreak is executed, ebreak cause exception ? ${ebreakCauseException}\n")
1064
1065  /**
1066    * Exception and Intr
1067    */
1068  val ideleg =  (mideleg & mip.asUInt)
1069  def priviledgedEnableDetect(x: Bool): Bool = Mux(x, ((priviledgeMode === ModeS) && mstatusStruct.ie.s) || (priviledgeMode < ModeS),
1070    ((priviledgeMode === ModeM) && mstatusStruct.ie.m) || (priviledgeMode < ModeM))
1071
1072  val debugIntr = csrio.externalInterrupt.debug & debugIntrEnable
1073  XSDebug(debugIntr, "Debug Mode: debug interrupt is asserted and valid!")
1074  // send interrupt information to ROB
1075  val intrVecEnable = Wire(Vec(12, Bool()))
1076  val disableInterrupt = debugMode || (dcsrData.step && !dcsrData.stepie)
1077  intrVecEnable.zip(ideleg.asBools).map{case(x,y) => x := priviledgedEnableDetect(y) && !disableInterrupt}
1078  val intrVec = Cat(debugIntr && !debugMode, (mie(11,0) & mip.asUInt & intrVecEnable.asUInt))
1079  val intrBitSet = intrVec.orR
1080  csrio.interrupt := intrBitSet
1081  // Page 45 in RISC-V Privileged Specification
1082  // The WFI instruction can also be executed when interrupts are disabled. The operation of WFI
1083  // must be unaffected by the global interrupt bits in mstatus (MIE and SIE) and the delegation
1084  // register mideleg, but should honor the individual interrupt enables (e.g, MTIE).
1085  csrio.wfi_event := debugIntr || (mie(11, 0) & mip.asUInt).orR
1086  mipWire.t.m := csrio.externalInterrupt.mtip
1087  mipWire.s.m := csrio.externalInterrupt.msip
1088  mipWire.e.m := csrio.externalInterrupt.meip
1089  mipWire.e.s := csrio.externalInterrupt.seip
1090
1091  // interrupts
1092  val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(intrVec(i), i.U, sum))
1093  val raiseIntr = csrio.exception.valid && csrio.exception.bits.isInterrupt
1094  val ivmEnable = tlbBundle.priv.imode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1095  val iexceptionPC = Mux(ivmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc)
1096  val dvmEnable = tlbBundle.priv.dmode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1097  val dexceptionPC = Mux(dvmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc)
1098  XSDebug(raiseIntr, "interrupt: pc=0x%x, %d\n", dexceptionPC, intrNO)
1099  val raiseDebugIntr = intrNO === IRQ_DEBUG.U && raiseIntr
1100
1101  // exceptions
1102  val raiseException = csrio.exception.valid && !csrio.exception.bits.isInterrupt
1103  val hasInstrPageFault = csrio.exception.bits.uop.cf.exceptionVec(instrPageFault) && raiseException
1104  val hasLoadPageFault = csrio.exception.bits.uop.cf.exceptionVec(loadPageFault) && raiseException
1105  val hasStorePageFault = csrio.exception.bits.uop.cf.exceptionVec(storePageFault) && raiseException
1106  val hasStoreAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(storeAddrMisaligned) && raiseException
1107  val hasLoadAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(loadAddrMisaligned) && raiseException
1108  val hasInstrAccessFault = csrio.exception.bits.uop.cf.exceptionVec(instrAccessFault) && raiseException
1109  val hasLoadAccessFault = csrio.exception.bits.uop.cf.exceptionVec(loadAccessFault) && raiseException
1110  val hasStoreAccessFault = csrio.exception.bits.uop.cf.exceptionVec(storeAccessFault) && raiseException
1111  val hasbreakPoint = csrio.exception.bits.uop.cf.exceptionVec(breakPoint) && raiseException
1112  val hasSingleStep = csrio.exception.bits.uop.ctrl.singleStep && raiseException
1113  val hasTriggerHit = (csrio.exception.bits.uop.cf.trigger.hit) && raiseException
1114
1115  XSDebug(hasSingleStep, "Debug Mode: single step exception\n")
1116  XSDebug(hasTriggerHit, p"Debug Mode: trigger hit, is frontend? ${Binary(csrio.exception.bits.uop.cf.trigger.frontendHit.asUInt)} " +
1117    p"backend hit vec ${Binary(csrio.exception.bits.uop.cf.trigger.backendHit.asUInt)}\n")
1118
1119  val raiseExceptionVec = csrio.exception.bits.uop.cf.exceptionVec
1120  val regularExceptionNO = ExceptionNO.priorities.foldRight(0.U)((i: Int, sum: UInt) => Mux(raiseExceptionVec(i), i.U, sum))
1121  val exceptionNO = Mux(hasSingleStep || hasTriggerHit, 3.U, regularExceptionNO)
1122  val causeNO = (raiseIntr << (XLEN-1)).asUInt | Mux(raiseIntr, intrNO, exceptionNO)
1123
1124  val raiseExceptionIntr = csrio.exception.valid
1125
1126  val raiseDebugExceptionIntr = !debugMode && (hasbreakPoint || raiseDebugIntr || hasSingleStep || hasTriggerHit && triggerAction) // TODO
1127  val ebreakEnterParkLoop = debugMode && raiseExceptionIntr
1128
1129  XSDebug(raiseExceptionIntr, "int/exc: pc %x int (%d):%x exc: (%d):%x\n",
1130    dexceptionPC, intrNO, intrVec, exceptionNO, raiseExceptionVec.asUInt
1131  )
1132  XSDebug(raiseExceptionIntr,
1133    "pc %x mstatus %x mideleg %x medeleg %x mode %x\n",
1134    dexceptionPC,
1135    mstatus,
1136    mideleg,
1137    medeleg,
1138    priviledgeMode
1139  )
1140
1141  // mtval write logic
1142  // Due to timing reasons of memExceptionVAddr, we delay the write of mtval and stval
1143  val memExceptionAddr = SignExt(csrio.memExceptionVAddr, XLEN)
1144  val updateTval = VecInit(Seq(
1145    hasInstrPageFault,
1146    hasLoadPageFault,
1147    hasStorePageFault,
1148    hasInstrAccessFault,
1149    hasLoadAccessFault,
1150    hasStoreAccessFault,
1151    hasLoadAddrMisaligned,
1152    hasStoreAddrMisaligned
1153  )).asUInt.orR
1154  when (RegNext(RegNext(updateTval))) {
1155      val tval = Mux(
1156        RegNext(RegNext(hasInstrPageFault || hasInstrAccessFault)),
1157        RegNext(RegNext(Mux(
1158          csrio.exception.bits.uop.cf.crossPageIPFFix,
1159          SignExt(csrio.exception.bits.uop.cf.pc + 2.U, XLEN),
1160          iexceptionPC
1161        ))),
1162        memExceptionAddr
1163    )
1164    when (RegNext(priviledgeMode === ModeM)) {
1165      mtval := tval
1166    }.otherwise {
1167      stval := tval
1168    }
1169  }
1170
1171  val debugTrapTarget = Mux(!isEbreak && debugMode, 0x38020808.U, 0x38020800.U) // 0x808 is when an exception occurs in debug mode prog buf exec
1172  val deleg = Mux(raiseIntr, mideleg , medeleg)
1173  // val delegS = ((deleg & (1 << (causeNO & 0xf))) != 0) && (priviledgeMode < ModeM);
1174  val delegS = deleg(causeNO(3,0)) && (priviledgeMode < ModeM)
1175  val clearTval = !updateTval || raiseIntr
1176  val isXRet = io.in.valid && func === CSROpType.jmp && !isEcall && !isEbreak
1177
1178  // ctrl block will use theses later for flush
1179  val isXRetFlag = RegInit(false.B)
1180  when (DelayN(io.redirectIn.valid, 5)) {
1181    isXRetFlag := false.B
1182  }.elsewhen (isXRet) {
1183    isXRetFlag := true.B
1184  }
1185  csrio.isXRet := isXRetFlag
1186  val retTargetReg = RegEnable(retTarget, isXRet)
1187
1188  val tvec = Mux(delegS, stvec, mtvec)
1189  val tvecBase = tvec(VAddrBits - 1, 2)
1190  // XRet sends redirect instead of Flush and isXRetFlag is true.B before redirect.valid.
1191  // ROB sends exception at T0 while CSR receives at T2.
1192  // We add a RegNext here and trapTarget is valid at T3.
1193  csrio.trapTarget := RegEnable(Mux(isXRetFlag,
1194    retTargetReg,
1195    Mux(raiseDebugExceptionIntr || ebreakEnterParkLoop, debugTrapTarget,
1196      // When MODE=Vectored, all synchronous exceptions into M/S mode
1197      // cause the pc to be set to the address in the BASE field, whereas
1198      // interrupts cause the pc to be set to the address in the BASE field
1199      // plus four times the interrupt cause number.
1200      Cat(tvecBase + Mux(tvec(0) && raiseIntr, causeNO(3, 0), 0.U), 0.U(2.W))
1201  )), isXRetFlag || csrio.exception.valid)
1202
1203  when (raiseExceptionIntr) {
1204    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1205    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1206    val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct))
1207    val debugModeNew = WireInit(debugMode)
1208
1209    when (raiseDebugExceptionIntr) {
1210      when (raiseDebugIntr) {
1211        debugModeNew := true.B
1212        mstatusNew.mprv := false.B
1213        dpc := iexceptionPC
1214        dcsrNew.cause := 3.U
1215        dcsrNew.prv := priviledgeMode
1216        priviledgeMode := ModeM
1217        XSDebug(raiseDebugIntr, "Debug Mode: Trap to %x at pc %x\n", debugTrapTarget, dpc)
1218      }.elsewhen ((hasbreakPoint || hasSingleStep) && !debugMode) {
1219        // ebreak or ss in running hart
1220        debugModeNew := true.B
1221        dpc := iexceptionPC
1222        dcsrNew.cause := Mux(hasTriggerHit, 2.U, Mux(hasbreakPoint, 1.U, 4.U))
1223        dcsrNew.prv := priviledgeMode // TODO
1224        priviledgeMode := ModeM
1225        mstatusNew.mprv := false.B
1226      }
1227      dcsr := dcsrNew.asUInt
1228      debugIntrEnable := false.B
1229    }.elsewhen (debugMode) {
1230      //do nothing
1231    }.elsewhen (delegS) {
1232      scause := causeNO
1233      sepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1234      mstatusNew.spp := priviledgeMode
1235      mstatusNew.pie.s := mstatusOld.ie.s
1236      mstatusNew.ie.s := false.B
1237      priviledgeMode := ModeS
1238      when (clearTval) { stval := 0.U }
1239    }.otherwise {
1240      mcause := causeNO
1241      mepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1242      mstatusNew.mpp := priviledgeMode
1243      mstatusNew.pie.m := mstatusOld.ie.m
1244      mstatusNew.ie.m := false.B
1245      priviledgeMode := ModeM
1246      when (clearTval) { mtval := 0.U }
1247    }
1248    mstatus := mstatusNew.asUInt
1249    debugMode := debugModeNew
1250  }
1251
1252  XSDebug(raiseExceptionIntr && delegS, "sepc is written!!! pc:%x\n", cfIn.pc)
1253
1254  // Distributed CSR update req
1255  //
1256  // For now we use it to implement customized cache op
1257  // It can be delayed if necessary
1258
1259  val delayedUpdate0 = DelayN(csrio.distributedUpdate(0), 2)
1260  val delayedUpdate1 = DelayN(csrio.distributedUpdate(1), 2)
1261  val distributedUpdateValid = delayedUpdate0.w.valid || delayedUpdate1.w.valid
1262  val distributedUpdateAddr = Mux(delayedUpdate0.w.valid,
1263    delayedUpdate0.w.bits.addr,
1264    delayedUpdate1.w.bits.addr
1265  )
1266  val distributedUpdateData = Mux(delayedUpdate0.w.valid,
1267    delayedUpdate0.w.bits.data,
1268    delayedUpdate1.w.bits.data
1269  )
1270
1271  assert(!(delayedUpdate0.w.valid && delayedUpdate1.w.valid))
1272
1273  when(distributedUpdateValid){
1274    // cacheopRegs can be distributed updated
1275    CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
1276      when((Scachebase + attribute("offset").toInt).U === distributedUpdateAddr){
1277        cacheopRegs(name) := distributedUpdateData
1278      }
1279    }}
1280  }
1281
1282  // Cache error debug support
1283  if(HasCustomCSRCacheOp){
1284    val cache_error_decoder = Module(new CSRCacheErrorDecoder)
1285    cache_error_decoder.io.encoded_cache_error := cacheopRegs("CACHE_ERROR")
1286  }
1287
1288  // Implicit add reset values for mepc[0] and sepc[0]
1289  // TODO: rewrite mepc and sepc using a struct-like style with the LSB always being 0
1290  when (reset.asBool) {
1291    mepc := Cat(mepc(XLEN - 1, 1), 0.U(1.W))
1292    sepc := Cat(sepc(XLEN - 1, 1), 0.U(1.W))
1293  }
1294
1295  def readWithScala(addr: Int): UInt = mapping(addr)._1
1296
1297  val difftestIntrNO = Mux(raiseIntr, causeNO, 0.U)
1298
1299  // Always instantiate basic difftest modules.
1300  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1301    val difftest = Module(new DifftestArchEvent)
1302    difftest.io.clock := clock
1303    difftest.io.coreid := csrio.hartId
1304    difftest.io.intrNO := RegNext(RegNext(RegNext(difftestIntrNO)))
1305    difftest.io.cause  := RegNext(RegNext(RegNext(Mux(csrio.exception.valid, causeNO, 0.U))))
1306    difftest.io.exceptionPC := RegNext(RegNext(RegNext(dexceptionPC)))
1307    if (env.EnableDifftest) {
1308      difftest.io.exceptionInst := RegNext(RegNext(RegNext(csrio.exception.bits.uop.cf.instr)))
1309    }
1310  }
1311
1312  // Always instantiate basic difftest modules.
1313  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1314    val difftest = Module(new DifftestCSRState)
1315    difftest.io.clock := clock
1316    difftest.io.coreid := csrio.hartId
1317    difftest.io.priviledgeMode := priviledgeMode
1318    difftest.io.mstatus := mstatus
1319    difftest.io.sstatus := mstatus & sstatusRmask
1320    difftest.io.mepc := mepc
1321    difftest.io.sepc := sepc
1322    difftest.io.mtval:= mtval
1323    difftest.io.stval:= stval
1324    difftest.io.mtvec := mtvec
1325    difftest.io.stvec := stvec
1326    difftest.io.mcause := mcause
1327    difftest.io.scause := scause
1328    difftest.io.satp := satp
1329    difftest.io.mip := mipReg
1330    difftest.io.mie := mie
1331    difftest.io.mscratch := mscratch
1332    difftest.io.sscratch := sscratch
1333    difftest.io.mideleg := mideleg
1334    difftest.io.medeleg := medeleg
1335  }
1336
1337  if(env.AlwaysBasicDiff || env.EnableDifftest) {
1338    val difftest = Module(new DifftestDebugMode)
1339    difftest.io.clock := clock
1340    difftest.io.coreid := csrio.hartId
1341    difftest.io.debugMode := debugMode
1342    difftest.io.dcsr := dcsr
1343    difftest.io.dpc := dpc
1344    difftest.io.dscratch0 := dscratch
1345    difftest.io.dscratch1 := dscratch1
1346  }
1347
1348  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1349    val difftest = Module(new DifftestVectorState)
1350    difftest.io.clock := clock
1351    difftest.io.coreid := csrio.hartId
1352    difftest.io.vstart := vstart
1353    difftest.io.vxsat := vcsr.asTypeOf(new VcsrStruct).vxsat
1354    difftest.io.vxrm := vcsr.asTypeOf(new VcsrStruct).vxrm
1355    difftest.io.vcsr := vcsr
1356    difftest.io.vl := vl
1357    difftest.io.vtype := vtype
1358    difftest.io.vlenb := vlenb
1359  }
1360}
1361
1362class PFEvent(implicit p: Parameters) extends XSModule with HasCSRConst  {
1363  val io = IO(new Bundle {
1364    val distribute_csr = Flipped(new DistributedCSRIO())
1365    val hpmevent = Output(Vec(29, UInt(XLEN.W)))
1366  })
1367
1368  val w = io.distribute_csr.w
1369
1370  val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++
1371                   List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++
1372                   List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++
1373                   List.fill(5)(RegInit("hc0300c0300".U(XLEN.W)))
1374
1375  val perfEventMapping = (0 until 29).map(i => {Map(
1376    MaskedRegMap(addr = Mhpmevent3 +i,
1377                 reg  = perfEvents(i),
1378                 wmask = "hf87fff3fcff3fcff".U(XLEN.W))
1379  )}).fold(Map())((a,b) => a ++ b)
1380
1381  val rdata = Wire(UInt(XLEN.W))
1382  MaskedRegMap.generate(perfEventMapping, w.bits.addr, rdata, w.valid, w.bits.data)
1383  for(i <- 0 until 29){
1384    io.hpmevent(i) := perfEvents(i)
1385  }
1386}
1387