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