xref: /XiangShan/src/main/scala/xiangshan/backend/fu/CSR.scala (revision 9ab1568e215c540ca0554308577ff4d1813bfa8c)
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._
31
32// Trigger Tdata1 bundles
33trait HasTriggerConst {
34  def I_Trigger = 0.U
35  def S_Trigger = 1.U
36  def L_Trigger = 2.U
37  def GenESL(triggerType: UInt) = Cat((triggerType === I_Trigger), (triggerType === S_Trigger), (triggerType === L_Trigger))
38}
39
40class TdataBundle extends Bundle {
41  val ttype = UInt(4.W)
42  val dmode = Bool()
43  val maskmax = UInt(6.W)
44  val zero1 = UInt(30.W)
45  val sizehi = UInt(2.W)
46  val hit = Bool()
47  val select = Bool()
48  val timing = Bool()
49  val sizelo = UInt(2.W)
50  val action = UInt(4.W)
51  val chain = Bool()
52  val matchType = UInt(4.W)
53  val m = Bool()
54  val zero2 = Bool()
55  val s = Bool()
56  val u = Bool()
57  val execute = Bool()
58  val store = Bool()
59  val load = Bool()
60}
61
62class FpuCsrIO extends Bundle {
63  val fflags = Output(Valid(UInt(5.W)))
64  val isIllegal = Output(Bool())
65  val dirty_fs = Output(Bool())
66  val frm = Input(UInt(3.W))
67}
68
69class VpuCsrIO(implicit p: Parameters) extends XSBundle {
70  val vstart = Input(UInt(XLEN.W))
71  val vxsat = Input(UInt(1.W))
72  val vxrm = Input(UInt(2.W))
73  val vcsr = Input(UInt(XLEN.W))
74  val vl = Input(UInt(XLEN.W))
75  val vtype = Input(UInt(XLEN.W))
76  val vlenb = Input(UInt(XLEN.W))
77
78  val vill = Input(UInt(1.W))
79  val vma = Input(UInt(1.W))
80  val vta = Input(UInt(1.W))
81  val vsew = Input(UInt(3.W))
82  val vlmul = Input(UInt(3.W))
83
84  val set_vstart = Output(Valid(UInt(XLEN.W)))
85  val set_vl = Output(Valid(UInt(XLEN.W)))
86  val set_vtype = Output(Valid(UInt(XLEN.W)))
87
88  val dirty_vs = Output(Bool())
89}
90
91
92class PerfCounterIO(implicit p: Parameters) extends XSBundle {
93  val perfEventsFrontend  = Vec(numCSRPCntFrontend, new PerfEvent)
94  val perfEventsCtrl      = Vec(numCSRPCntCtrl, new PerfEvent)
95  val perfEventsLsu       = Vec(numCSRPCntLsu, new PerfEvent)
96  val perfEventsHc        = Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent)
97  val retiredInstr = UInt(3.W)
98  val frontendInfo = new Bundle {
99    val ibufFull  = Bool()
100    val bpuInfo = new Bundle {
101      val bpRight = UInt(XLEN.W)
102      val bpWrong = UInt(XLEN.W)
103    }
104  }
105  val ctrlInfo = new Bundle {
106    val robFull   = Bool()
107    val intdqFull = Bool()
108    val fpdqFull  = Bool()
109    val lsdqFull  = Bool()
110  }
111  val memInfo = new Bundle {
112    val sqFull = Bool()
113    val lqFull = Bool()
114    val dcacheMSHRFull = Bool()
115  }
116
117  val cacheInfo = new Bundle {
118    val l2MSHRFull = Bool()
119    val l3MSHRFull = Bool()
120    val l2nAcquire = UInt(XLEN.W)
121    val l2nAcquireMiss = UInt(XLEN.W)
122    val l3nAcquire = UInt(XLEN.W)
123    val l3nAcquireMiss = UInt(XLEN.W)
124  }
125}
126
127class CSRFileIO(implicit p: Parameters) extends XSBundle {
128  val hartId = Input(UInt(8.W))
129  // output (for func === CSROpType.jmp)
130  val perf = Input(new PerfCounterIO)
131  val isPerfCnt = Output(Bool())
132  // to FPU
133  val fpu = Flipped(new FpuCsrIO)
134  // to VPU
135  val vpu = Flipped(new VpuCsrIO)
136  // from rob
137  val exception = Flipped(ValidIO(new ExceptionInfo))
138  // to ROB
139  val isXRet = Output(Bool())
140  val trapTarget = Output(UInt(VAddrBits.W))
141  val interrupt = Output(Bool())
142  val wfi_event = Output(Bool())
143  // from LSQ
144  val memExceptionVAddr = Input(UInt(VAddrBits.W))
145  // from outside cpu,externalInterrupt
146  val externalInterrupt = new ExternalInterruptIO
147  // TLB
148  val tlb = Output(new TlbCsrBundle)
149  // Debug Mode
150  // val singleStep = Output(Bool())
151  val debugMode = Output(Bool())
152  // to Fence to disable sfence
153  val disableSfence = Output(Bool())
154  // Custom microarchiture ctrl signal
155  val customCtrl = Output(new CustomCSRCtrlIO)
156  // distributed csr write
157  val distributedUpdate = Vec(2, Flipped(new DistributedCSRUpdateReq))
158}
159
160class CSR(implicit p: Parameters) extends FunctionUnit with HasCSRConst with PMPMethod with PMAMethod with HasTriggerConst
161{
162  val csrio = IO(new CSRFileIO)
163
164  val cfIn = io.in.bits.uop.cf
165  val cfOut = Wire(new CtrlFlow)
166  cfOut := cfIn
167  val flushPipe = Wire(Bool())
168
169  val (valid, src1, src2, func) = (
170    io.in.valid,
171    io.in.bits.src(0),
172    io.in.bits.uop.ctrl.imm,
173    io.in.bits.uop.ctrl.fuOpType
174  )
175
176  // CSR define
177
178  class Priv extends Bundle {
179    val m = Output(Bool())
180    val h = Output(Bool())
181    val s = Output(Bool())
182    val u = Output(Bool())
183  }
184
185  val csrNotImplemented = RegInit(UInt(XLEN.W), 0.U)
186
187  class DcsrStruct extends Bundle {
188    val xdebugver = Output(UInt(2.W))
189    val zero4 = Output(UInt(2.W))
190    val zero3 = Output(UInt(12.W))
191    val ebreakm = Output(Bool())
192    val ebreakh = Output(Bool())
193    val ebreaks = Output(Bool())
194    val ebreaku = Output(Bool())
195    val stepie = Output(Bool()) // 0
196    val stopcycle = Output(Bool())
197    val stoptime = Output(Bool())
198    val cause = Output(UInt(3.W))
199    val v = Output(Bool()) // 0
200    val mprven = Output(Bool())
201    val nmip = Output(Bool())
202    val step = Output(Bool())
203    val prv = Output(UInt(2.W))
204  }
205
206  class MstatusStruct extends Bundle {
207    val sd = Output(UInt(1.W))
208
209    val pad1 = if (XLEN == 64) Output(UInt(25.W)) else null
210    val mbe  = if (XLEN == 64) Output(UInt(1.W)) else null
211    val sbe  = if (XLEN == 64) Output(UInt(1.W)) else null
212    val sxl  = if (XLEN == 64) Output(UInt(2.W))  else null
213    val uxl  = if (XLEN == 64) Output(UInt(2.W))  else null
214    val pad0 = if (XLEN == 64) Output(UInt(9.W))  else Output(UInt(8.W))
215
216    val tsr = Output(UInt(1.W))
217    val tw = Output(UInt(1.W))
218    val tvm = Output(UInt(1.W))
219    val mxr = Output(UInt(1.W))
220    val sum = Output(UInt(1.W))
221    val mprv = Output(UInt(1.W))
222    val xs = Output(UInt(2.W))
223    val fs = Output(UInt(2.W))
224    val mpp = Output(UInt(2.W))
225    val vs = Output(UInt(2.W))
226    val spp = Output(UInt(1.W))
227    val pie = new Priv
228    val ie = new Priv
229    assert(this.getWidth == XLEN)
230
231    def ube = pie.h // a little ugly
232    def ube_(r: UInt): Unit = {
233      pie.h := r(0)
234    }
235  }
236
237  class Interrupt extends Bundle {
238//  val d = Output(Bool())    // Debug
239    val e = new Priv
240    val t = new Priv
241    val s = new Priv
242  }
243
244  // Debug CSRs
245  val dcsr = RegInit(UInt(32.W), 0x4000b000.U)
246  val dpc = Reg(UInt(64.W))
247  val dscratch = Reg(UInt(64.W))
248  val dscratch1 = Reg(UInt(64.W))
249  val debugMode = RegInit(false.B)
250  val debugIntrEnable = RegInit(true.B)
251  csrio.debugMode := debugMode
252
253  val dpcPrev = RegNext(dpc)
254  XSDebug(dpcPrev =/= dpc, "Debug Mode: dpc is altered! Current is %x, previous is %x\n", dpc, dpcPrev)
255
256  // dcsr value table
257  // | debugver | 0100
258  // | zero     | 10 bits of 0
259  // | ebreakvs | 0
260  // | ebreakvu | 0
261  // | ebreakm  | 1 if ebreak enters debug
262  // | zero     | 0
263  // | ebreaks  |
264  // | ebreaku  |
265  // | stepie   | disable interrupts in singlestep
266  // | stopcount| stop counter, 0
267  // | stoptime | stop time, 0
268  // | cause    | 3 bits read only
269  // | v        | 0
270  // | mprven   | 1
271  // | nmip     | read only
272  // | step     |
273  // | prv      | 2 bits
274
275  val dcsrData = Wire(new DcsrStruct)
276  dcsrData := dcsr.asTypeOf(new DcsrStruct)
277  val dcsrMask = ZeroExt(GenMask(15) | GenMask(13, 11) | GenMask(4) | GenMask(2, 0), XLEN)// Dcsr write mask
278  def dcsrUpdateSideEffect(dcsr: UInt): UInt = {
279    val dcsrOld = WireInit(dcsr.asTypeOf(new DcsrStruct))
280    val dcsrNew = dcsr | (dcsrOld.prv(0) | dcsrOld.prv(1)).asUInt // turn 10 priv into 11
281    dcsrNew
282  }
283  // csrio.singleStep := dcsrData.step
284  csrio.customCtrl.singlestep := dcsrData.step && !debugMode
285
286  // Trigger CSRs
287
288  val type_config = Array(
289    0.U -> I_Trigger, 1.U -> I_Trigger,
290    2.U -> S_Trigger, 3.U -> S_Trigger,
291    4.U -> L_Trigger, 5.U -> L_Trigger, // No.5 Load Trigger
292    6.U -> I_Trigger, 7.U -> S_Trigger,
293    8.U -> I_Trigger, 9.U -> L_Trigger
294  )
295  def TypeLookup(select: UInt) = MuxLookup(select, I_Trigger, type_config)
296
297  val tdata1Phy = RegInit(VecInit(List.fill(10) {(2L << 60L).U(64.W)})) // init ttype 2
298  val tdata2Phy = Reg(Vec(10, UInt(64.W)))
299  val tselectPhy = RegInit(0.U(4.W))
300  val tinfo = RegInit(2.U(64.W))
301  val tControlPhy = RegInit(0.U(64.W))
302  val triggerAction = RegInit(false.B)
303
304  def ReadTdata1(rdata: UInt) = rdata | Cat(triggerAction, 0.U(12.W)) // fix action
305  def WriteTdata1(wdata: UInt): UInt = {
306    val tdata1 = WireInit(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle))
307    val wdata_wire = WireInit(wdata.asTypeOf(new TdataBundle))
308    val tdata1_new = WireInit(wdata.asTypeOf(new TdataBundle))
309    XSDebug(src2(11, 0) === Tdata1.U && valid && func =/= CSROpType.jmp, p"Debug Mode: tdata1(${tselectPhy})is written, the actual value is ${wdata}\n")
310//    tdata1_new.hit := wdata(20)
311    tdata1_new.ttype := tdata1.ttype
312    tdata1_new.dmode := 0.U // Mux(debugMode, wdata_wire.dmode, tdata1.dmode)
313    tdata1_new.maskmax := 0.U
314    tdata1_new.hit := 0.U
315    tdata1_new.select := (TypeLookup(tselectPhy) === I_Trigger) && wdata_wire.select
316    when(wdata_wire.action <= 1.U){
317      triggerAction := tdata1_new.action(0)
318    } .otherwise{
319      tdata1_new.action := tdata1.action
320    }
321    tdata1_new.timing := false.B // hardwire this because we have singlestep
322    tdata1_new.zero1 := 0.U
323    tdata1_new.zero2 := 0.U
324    tdata1_new.chain := !tselectPhy(0) && wdata_wire.chain
325    when(wdata_wire.matchType =/= 0.U && wdata_wire.matchType =/= 2.U && wdata_wire.matchType =/= 3.U) {
326      tdata1_new.matchType := tdata1.matchType
327    }
328    tdata1_new.sizehi := Mux(wdata_wire.select && TypeLookup(tselectPhy) === I_Trigger, 0.U, 1.U)
329    tdata1_new.sizelo:= Mux(wdata_wire.select && TypeLookup(tselectPhy) === I_Trigger, 3.U, 1.U)
330    tdata1_new.execute := TypeLookup(tselectPhy) === I_Trigger
331    tdata1_new.store := TypeLookup(tselectPhy) === S_Trigger
332    tdata1_new.load := TypeLookup(tselectPhy) === L_Trigger
333    tdata1_new.asUInt
334  }
335
336  def WriteTselect(wdata: UInt) = {
337    Mux(wdata < 10.U, wdata(3, 0), tselectPhy)
338  }
339
340  val tcontrolWriteMask = ZeroExt(GenMask(3) | GenMask(7), XLEN)
341
342
343  def GenTdataDistribute(tdata1: TdataBundle, tdata2: UInt): MatchTriggerIO = {
344    val res = Wire(new MatchTriggerIO)
345    res.matchType := tdata1.matchType
346    res.select := tdata1.select
347    res.timing := tdata1.timing
348    res.action := triggerAction
349    res.chain := tdata1.chain
350    res.tdata2 := tdata2
351    res
352  }
353
354  csrio.customCtrl.frontend_trigger.t.bits.addr := MuxLookup(tselectPhy, 0.U, Seq(
355    0.U -> 0.U,
356    1.U -> 1.U,
357    6.U -> 2.U,
358    8.U -> 3.U
359  ))
360  csrio.customCtrl.mem_trigger.t.bits.addr := MuxLookup(tselectPhy, 0.U, Seq(
361    2.U -> 0.U,
362    3.U -> 1.U,
363    4.U -> 2.U,
364    5.U -> 3.U,
365    7.U -> 4.U,
366    9.U -> 5.U
367  ))
368  csrio.customCtrl.frontend_trigger.t.bits.tdata := GenTdataDistribute(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle), tdata2Phy(tselectPhy))
369  csrio.customCtrl.mem_trigger.t.bits.tdata := GenTdataDistribute(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle), tdata2Phy(tselectPhy))
370
371  // Machine-Level CSRs
372  // mtvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1
373  val mtvecMask = ~(0x2.U(XLEN.W))
374  val mtvec = RegInit(UInt(XLEN.W), 0.U)
375  val mcounteren = RegInit(UInt(XLEN.W), 0.U)
376  val mcause = RegInit(UInt(XLEN.W), 0.U)
377  val mtval = RegInit(UInt(XLEN.W), 0.U)
378  val mepc = Reg(UInt(XLEN.W))
379  // Page 36 in riscv-priv: The low bit of mepc (mepc[0]) is always zero.
380  val mepcMask = ~(0x1.U(XLEN.W))
381
382  val mie = RegInit(0.U(XLEN.W))
383  val mipWire = WireInit(0.U.asTypeOf(new Interrupt))
384  val mipReg  = RegInit(0.U(XLEN.W))
385  val mipFixMask = ZeroExt(GenMask(9) | GenMask(5) | GenMask(1), XLEN)
386  val mip = (mipWire.asUInt | mipReg).asTypeOf(new Interrupt)
387
388  def getMisaMxl(mxl: BigInt): BigInt = mxl << (XLEN - 2)
389  def getMisaExt(ext: Char): Long = 1 << (ext.toInt - 'a'.toInt)
390  var extList = List('a', 's', 'i', 'u')
391  if (HasMExtension) { extList = extList :+ 'm' }
392  if (HasCExtension) { extList = extList :+ 'c' }
393  if (HasFPU) { extList = extList ++ List('f', 'd') }
394  if (HasVPU) { extList = extList :+ 'v' }
395  val misaInitVal = getMisaMxl(2) | extList.foldLeft(0L)((sum, i) => sum | getMisaExt(i)) //"h8000000000141105".U
396  val misa = RegInit(UInt(XLEN.W), misaInitVal.U)
397
398  // MXL = 2          | 0 | EXT = b 00 0000 0100 0001 0001 0000 0101
399  // (XLEN-1, XLEN-2) |   |(25, 0)  ZY XWVU TSRQ PONM LKJI HGFE DCBA
400
401  val mvendorid = RegInit(UInt(XLEN.W), 0.U) // this is a non-commercial implementation
402  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
403  val mimpid = RegInit(UInt(XLEN.W), 0.U) // provides a unique encoding of the version of the processor implementation
404  val mhartid = Reg(UInt(XLEN.W)) // the hardware thread running the code
405  when (RegNext(RegNext(reset.asBool) && !reset.asBool)) {
406    mhartid := csrio.hartId
407  }
408  val mconfigptr = RegInit(UInt(XLEN.W), 0.U) // the read-only pointer pointing to the platform config structure, 0 for not supported.
409  val mstatus = RegInit("ha00002000".U(XLEN.W))
410
411  // mstatus Value Table
412  // | sd   |
413  // | pad1 |
414  // | sxl  | hardlinked to 10, use 00 to pass xv6 test
415  // | uxl  | hardlinked to 10
416  // | pad0 |
417  // | tsr  |
418  // | tw   |
419  // | tvm  |
420  // | mxr  |
421  // | sum  |
422  // | mprv |
423  // | xs   | 00 |
424  // | fs   | 01 |
425  // | mpp  | 00 |
426  // | vs  | 00 |
427  // | spp  | 0 |
428  // | pie  | 0000 | pie.h is used as UBE
429  // | ie   | 0000 | uie hardlinked to 0, as N ext is not implemented
430
431  val mstatusStruct = mstatus.asTypeOf(new MstatusStruct)
432  def mstatusUpdateSideEffect(mstatus: UInt): UInt = {
433    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
434    val mstatusNew = Cat(mstatusOld.xs === "b11".U || mstatusOld.fs === "b11".U, mstatus(XLEN-2, 0))
435    mstatusNew
436  }
437
438  val mstatusWMask = (~ZeroExt((
439    GenMask(XLEN - 2, 36) | // WPRI
440    GenMask(35, 32)       | // SXL and UXL cannot be changed
441    GenMask(31, 23)       | // WPRI
442    GenMask(16, 15)       | // XS is read-only
443    GenMask(10, 9)        | // WPRI
444    GenMask(6)            | // WPRI
445    GenMask(2)              // WPRI
446  ), 64)).asUInt
447  val mstatusMask = (~ZeroExt((
448    GenMask(XLEN - 2, 36) | // WPRI
449    GenMask(31, 23)       | // WPRI
450    GenMask(10, 9)        | // WPRI
451    GenMask(6)            | // WPRI
452    GenMask(2)              // WPRI
453  ), 64)).asUInt
454
455  val medeleg = RegInit(UInt(XLEN.W), 0.U)
456  val mideleg = RegInit(UInt(XLEN.W), 0.U)
457  val mscratch = RegInit(UInt(XLEN.W), 0.U)
458
459  // PMP Mapping
460  val pmp = Wire(Vec(NumPMP, new PMPEntry())) // just used for method parameter
461  val pma = Wire(Vec(NumPMA, new PMPEntry())) // just used for method parameter
462  val pmpMapping = pmp_gen_mapping(pmp_init, NumPMP, PmpcfgBase, PmpaddrBase, pmp)
463  val pmaMapping = pmp_gen_mapping(pma_init, NumPMA, PmacfgBase, PmaaddrBase, pma)
464
465  // Superviser-Level CSRs
466
467  // val sstatus = RegInit(UInt(XLEN.W), "h00000000".U)
468  val sstatusWmask = "hc6122".U(XLEN.W)
469  // Sstatus Write Mask
470  // -------------------------------------------------------
471  //    19           9   5     2
472  // 0  1100 0000 0001 0010 0010
473  // 0  c    0    1    2    2
474  // -------------------------------------------------------
475  val sstatusRmask = sstatusWmask | "h8000000300018000".U
476  // Sstatus Read Mask = (SSTATUS_WMASK | (0xf << 13) | (1ull << 63) | (3ull << 32))
477  // stvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1
478  val stvecMask = ~(0x2.U(XLEN.W))
479  val stvec = RegInit(UInt(XLEN.W), 0.U)
480  // val sie = RegInit(0.U(XLEN.W))
481  val sieMask = "h222".U & mideleg
482  val sipMask = "h222".U & mideleg
483  val sipWMask = "h2".U(XLEN.W) // ssip is writeable in smode
484  val satp = if(EnbaleTlbDebug) RegInit(UInt(XLEN.W), "h8000000000087fbe".U) else RegInit(0.U(XLEN.W))
485  // val satp = RegInit(UInt(XLEN.W), "h8000000000087fbe".U) // only use for tlb naive debug
486  // val satpMask = "h80000fffffffffff".U(XLEN.W) // disable asid, mode can only be 8 / 0
487  // TODO: use config to control the length of asid
488  // val satpMask = "h8fffffffffffffff".U(XLEN.W) // enable asid, mode can only be 8 / 0
489  val satpMask = Cat("h8".U(Satp_Mode_len.W), satp_part_wmask(Satp_Asid_len, AsidLength), satp_part_wmask(Satp_Addr_len, PAddrBits-12))
490  val sepc = RegInit(UInt(XLEN.W), 0.U)
491  // Page 60 in riscv-priv: The low bit of sepc (sepc[0]) is always zero.
492  val sepcMask = ~(0x1.U(XLEN.W))
493  val scause = RegInit(UInt(XLEN.W), 0.U)
494  val stval = Reg(UInt(XLEN.W))
495  val sscratch = RegInit(UInt(XLEN.W), 0.U)
496  val scounteren = RegInit(UInt(XLEN.W), 0.U)
497
498  // sbpctl
499  // Bits 0-7: {LOOP, RAS, SC, TAGE, BIM, BTB, uBTB}
500  val sbpctl = RegInit(UInt(XLEN.W), "h7f".U)
501  csrio.customCtrl.bp_ctrl.ubtb_enable := sbpctl(0)
502  csrio.customCtrl.bp_ctrl.btb_enable  := sbpctl(1)
503  csrio.customCtrl.bp_ctrl.bim_enable  := sbpctl(2)
504  csrio.customCtrl.bp_ctrl.tage_enable := sbpctl(3)
505  csrio.customCtrl.bp_ctrl.sc_enable   := sbpctl(4)
506  csrio.customCtrl.bp_ctrl.ras_enable  := sbpctl(5)
507  csrio.customCtrl.bp_ctrl.loop_enable := sbpctl(6)
508
509  // spfctl Bit 0: L1I Cache Prefetcher Enable
510  // spfctl Bit 1: L2Cache Prefetcher Enable
511  val spfctl = RegInit(UInt(XLEN.W), "b11".U)
512  csrio.customCtrl.l1I_pf_enable := spfctl(0)
513  csrio.customCtrl.l2_pf_enable := spfctl(1)
514
515  // sfetchctl Bit 0: L1I Cache Parity check enable
516  val sfetchctl = RegInit(UInt(XLEN.W), "b0".U)
517  csrio.customCtrl.icache_parity_enable := sfetchctl(0)
518
519  // sdsid: Differentiated Services ID
520  val sdsid = RegInit(UInt(XLEN.W), 0.U)
521  csrio.customCtrl.dsid := sdsid
522
523  // slvpredctl: load violation predict settings
524  // Default reset period: 2^16
525  // Why this number: reset more frequently while keeping the overhead low
526  // Overhead: extra two redirections in every 64K cycles => ~0.1% overhead
527  val slvpredctl = RegInit(UInt(XLEN.W), "h60".U)
528  csrio.customCtrl.lvpred_disable := slvpredctl(0)
529  csrio.customCtrl.no_spec_load := slvpredctl(1)
530  csrio.customCtrl.storeset_wait_store := slvpredctl(2)
531  csrio.customCtrl.storeset_no_fast_wakeup := slvpredctl(3)
532  csrio.customCtrl.lvpred_timeout := slvpredctl(8, 4)
533
534  //  smblockctl: memory block configurations
535  //  +------------------------------+---+----+----+-----+--------+
536  //  |XLEN-1                       8| 7 | 6  | 5  |  4  |3      0|
537  //  +------------------------------+---+----+----+-----+--------+
538  //  |           Reserved           | O | CE | SP | LVC |   Th   |
539  //  +------------------------------+---+----+----+-----+--------+
540  //  Description:
541  //  Bit 3-0   : Store buffer flush threshold (Th).
542  //  Bit 4     : Enable load violation check after reset (LVC).
543  //  Bit 5     : Enable soft-prefetch after reset (SP).
544  //  Bit 6     : Enable cache error after reset (CE).
545  //  Bit 7     : Enable uncache write outstanding (O).
546  //  Others    : Reserved.
547
548  val smblockctl_init_val =
549    (0xf & StoreBufferThreshold) |
550    (EnableLdVioCheckAfterReset.toInt << 4) |
551    (EnableSoftPrefetchAfterReset.toInt << 5) |
552    (EnableCacheErrorAfterReset.toInt << 6)
553    (EnableUncacheWriteOutstanding.toInt << 7)
554  val smblockctl = RegInit(UInt(XLEN.W), smblockctl_init_val.U)
555  csrio.customCtrl.sbuffer_threshold := smblockctl(3, 0)
556  // bits 4: enable load load violation check
557  csrio.customCtrl.ldld_vio_check_enable := smblockctl(4)
558  csrio.customCtrl.soft_prefetch_enable := smblockctl(5)
559  csrio.customCtrl.cache_error_enable := smblockctl(6)
560  csrio.customCtrl.uncache_write_outstanding_enable := smblockctl(7)
561
562  println("CSR smblockctl init value:")
563  println("  Store buffer replace threshold: " + StoreBufferThreshold)
564  println("  Enable ld-ld vio check after reset: " + EnableLdVioCheckAfterReset)
565  println("  Enable soft prefetch after reset: " + EnableSoftPrefetchAfterReset)
566  println("  Enable cache error after reset: " + EnableCacheErrorAfterReset)
567  println("  Enable uncache write outstanding: " + EnableUncacheWriteOutstanding)
568
569  val srnctl = RegInit(UInt(XLEN.W), "h7".U)
570  csrio.customCtrl.fusion_enable := srnctl(0)
571  csrio.customCtrl.svinval_enable := srnctl(1)
572  csrio.customCtrl.wfi_enable := srnctl(2)
573
574  val tlbBundle = Wire(new TlbCsrBundle)
575  tlbBundle.satp.apply(satp)
576
577  csrio.tlb := tlbBundle
578
579  // User-Level CSRs
580  val uepc = Reg(UInt(XLEN.W))
581
582  // fcsr
583  class FcsrStruct extends Bundle {
584    val reserved = UInt((XLEN-3-5).W)
585    val frm = UInt(3.W)
586    val fflags = UInt(5.W)
587    assert(this.getWidth == XLEN)
588  }
589  val fcsr = RegInit(0.U(XLEN.W))
590  // set mstatus->sd and mstatus->fs when true
591  val csrw_dirty_fp_state = WireInit(false.B)
592
593  def frm_wfn(wdata: UInt): UInt = {
594    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
595    csrw_dirty_fp_state := true.B
596    fcsrOld.frm := wdata(2,0)
597    fcsrOld.asUInt
598  }
599  def frm_rfn(rdata: UInt): UInt = rdata(7,5)
600
601  def fflags_wfn(update: Boolean)(wdata: UInt): UInt = {
602    val fcsrOld = fcsr.asTypeOf(new FcsrStruct)
603    val fcsrNew = WireInit(fcsrOld)
604    csrw_dirty_fp_state := true.B
605    if (update) {
606      fcsrNew.fflags := wdata(4,0) | fcsrOld.fflags
607    } else {
608      fcsrNew.fflags := wdata(4,0)
609    }
610    fcsrNew.asUInt
611  }
612  def fflags_rfn(rdata:UInt): UInt = rdata(4,0)
613
614  def fcsr_wfn(wdata: UInt): UInt = {
615    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
616    csrw_dirty_fp_state := true.B
617    Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags)
618  }
619
620  val fcsrMapping = Map(
621    MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn(update = false), rfn = fflags_rfn),
622    MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn),
623    MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn)
624  )
625
626  // Vector extension CSRs
627  val vstart = Reg(UInt(XLEN.W))
628  val vcsr = RegInit(0.U(XLEN.W))
629  val vl = Reg(UInt(XLEN.W))
630  val vtype = Reg(UInt(XLEN.W))
631  val vlenb = RegInit(0.U(XLEN.W))
632
633  // set mstatus->sd and mstatus->vs when true
634  val csrw_dirty_vs_state = WireInit(false.B)
635
636  // vcsr is mapped to vxrm and vxsat
637  class VcsrStruct extends Bundle {
638    val reserved = UInt((XLEN-3).W)
639    val vxrm = UInt(2.W)
640    val vxsat = UInt(1.W)
641    assert(this.getWidth == XLEN)
642  }
643
644  class VtypeStruct extends Bundle {
645    val vill = UInt(1.W)
646    val reserved = UInt((XLEN-9).W)
647    val vma = UInt(1.W)
648    val vta = UInt(1.W)
649    val vsew = UInt(3.W)
650    val vlmul = UInt(3.W)
651  }
652
653  def vxrm_wfn(wdata: UInt): UInt = {
654    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
655    csrw_dirty_vs_state := true.B
656    vcsrOld.vxrm := wdata(1,0)
657    vcsrOld.asUInt
658  }
659  def vxrm_rfn(rdata: UInt): UInt = rdata(2,1)
660
661  def vxsat_wfn(wdata: UInt): UInt = {
662    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
663    csrw_dirty_vs_state := true.B
664    vcsrOld.vxsat := wdata(0)
665    vcsrOld.asUInt
666  }
667  def vxsat_rfn(rdata: UInt): UInt = rdata(0)
668
669  def vcsr_wfn(wdata: UInt): UInt = {
670    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
671    csrw_dirty_vs_state := true.B
672    vcsrOld.vxrm := wdata.asTypeOf(vcsrOld).vxrm
673    vcsrOld.vxsat := wdata.asTypeOf(vcsrOld).vxsat
674    vcsrOld.asUInt
675  }
676
677  val vcsrMapping = Map(
678    MaskedRegMap(Vstart, vstart),
679    MaskedRegMap(Vxrm, vcsr, wfn = vxrm_wfn, rfn = vxrm_rfn),
680    MaskedRegMap(Vxsat, vcsr, wfn = vxsat_wfn, rfn = vxsat_rfn),
681    MaskedRegMap(Vcsr, vcsr, wfn = vcsr_wfn),
682    MaskedRegMap(Vl, vl),
683    MaskedRegMap(Vtype, vtype),
684    MaskedRegMap(Vlenb, vlenb),
685  )
686
687  // Hart Priviledge Mode
688  val priviledgeMode = RegInit(UInt(2.W), ModeM)
689
690  //val perfEventscounten = List.fill(nrPerfCnts)(RegInit(false(Bool())))
691  // Perf Counter
692  val nrPerfCnts = 29  // 3...31
693  val priviledgeModeOH = UIntToOH(priviledgeMode)
694  val perfEventscounten = RegInit(0.U.asTypeOf(Vec(nrPerfCnts, Bool())))
695  val perfCnts   = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W)))
696  val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++
697                   List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++
698                   List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++
699                   List.fill(5)(RegInit("hc0300c0300".U(XLEN.W)))
700  for (i <-0 until nrPerfCnts) {
701    perfEventscounten(i) := (Cat(perfEvents(i)(62),perfEvents(i)(61),(perfEvents(i)(61,60))) & priviledgeModeOH).orR
702  }
703
704  val hpmEvents = Wire(Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent))
705  for (i <- 0 until numPCntHc * coreParams.L2NBanks) {
706    hpmEvents(i) := csrio.perf.perfEventsHc(i)
707  }
708
709  val csrevents = perfEvents.slice(24, 29)
710  val hpm_hc = HPerfMonitor(csrevents, hpmEvents)
711  val mcountinhibit = RegInit(0.U(XLEN.W))
712  val mcycle = RegInit(0.U(XLEN.W))
713  mcycle := mcycle + 1.U
714  val minstret = RegInit(0.U(XLEN.W))
715  val perf_events = csrio.perf.perfEventsFrontend ++
716                    csrio.perf.perfEventsCtrl ++
717                    csrio.perf.perfEventsLsu ++
718                    hpm_hc.getPerf
719  minstret := minstret + RegNext(csrio.perf.retiredInstr)
720  for(i <- 0 until 29){
721    perfCnts(i) := Mux(mcountinhibit(i+3) | !perfEventscounten(i), perfCnts(i), perfCnts(i) + perf_events(i).value)
722  }
723
724  // CSR reg map
725  val basicPrivMapping = Map(
726
727    //--- User Trap Setup ---
728    // MaskedRegMap(Ustatus, ustatus),
729    // MaskedRegMap(Uie, uie, 0.U, MaskedRegMap.Unwritable),
730    // MaskedRegMap(Utvec, utvec),
731
732    //--- User Trap Handling ---
733    // MaskedRegMap(Uscratch, uscratch),
734    // MaskedRegMap(Uepc, uepc),
735    // MaskedRegMap(Ucause, ucause),
736    // MaskedRegMap(Utval, utval),
737    // MaskedRegMap(Uip, uip),
738
739    //--- User Counter/Timers ---
740    // MaskedRegMap(Cycle, cycle),
741    // MaskedRegMap(Time, time),
742    // MaskedRegMap(Instret, instret),
743
744    //--- Supervisor Trap Setup ---
745    MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask),
746    // MaskedRegMap(Sedeleg, Sedeleg),
747    // MaskedRegMap(Sideleg, Sideleg),
748    MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask),
749    MaskedRegMap(Stvec, stvec, stvecMask, MaskedRegMap.NoSideEffect, stvecMask),
750    MaskedRegMap(Scounteren, scounteren),
751
752    //--- Supervisor Trap Handling ---
753    MaskedRegMap(Sscratch, sscratch),
754    MaskedRegMap(Sepc, sepc, sepcMask, MaskedRegMap.NoSideEffect, sepcMask),
755    MaskedRegMap(Scause, scause),
756    MaskedRegMap(Stval, stval),
757    MaskedRegMap(Sip, mip.asUInt, sipWMask, MaskedRegMap.Unwritable, sipMask),
758
759    //--- Supervisor Protection and Translation ---
760    MaskedRegMap(Satp, satp, satpMask, MaskedRegMap.NoSideEffect, satpMask),
761
762    //--- Supervisor Custom Read/Write Registers
763    MaskedRegMap(Sbpctl, sbpctl),
764    MaskedRegMap(Spfctl, spfctl),
765    MaskedRegMap(Sfetchctl, sfetchctl),
766    MaskedRegMap(Sdsid, sdsid),
767    MaskedRegMap(Slvpredctl, slvpredctl),
768    MaskedRegMap(Smblockctl, smblockctl),
769    MaskedRegMap(Srnctl, srnctl),
770
771    //--- Machine Information Registers ---
772    MaskedRegMap(Mvendorid, mvendorid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
773    MaskedRegMap(Marchid, marchid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
774    MaskedRegMap(Mimpid, mimpid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
775    MaskedRegMap(Mhartid, mhartid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
776    MaskedRegMap(Mconfigptr, mconfigptr, 0.U(XLEN.W), MaskedRegMap.Unwritable),
777
778    //--- Machine Trap Setup ---
779    MaskedRegMap(Mstatus, mstatus, mstatusWMask, mstatusUpdateSideEffect, mstatusMask),
780    MaskedRegMap(Misa, misa, 0.U, MaskedRegMap.Unwritable), // now whole misa is unchangeable
781    MaskedRegMap(Medeleg, medeleg, "hb3ff".U(XLEN.W)),
782    MaskedRegMap(Mideleg, mideleg, "h222".U(XLEN.W)),
783    MaskedRegMap(Mie, mie),
784    MaskedRegMap(Mtvec, mtvec, mtvecMask, MaskedRegMap.NoSideEffect, mtvecMask),
785    MaskedRegMap(Mcounteren, mcounteren),
786
787    //--- Machine Trap Handling ---
788    MaskedRegMap(Mscratch, mscratch),
789    MaskedRegMap(Mepc, mepc, mepcMask, MaskedRegMap.NoSideEffect, mepcMask),
790    MaskedRegMap(Mcause, mcause),
791    MaskedRegMap(Mtval, mtval),
792    MaskedRegMap(Mip, mip.asUInt, 0.U(XLEN.W), MaskedRegMap.Unwritable),
793
794    //--- Trigger ---
795    MaskedRegMap(Tselect, tselectPhy, WritableMask, WriteTselect),
796    MaskedRegMap(Tdata1, tdata1Phy(tselectPhy), WritableMask, WriteTdata1, WritableMask, ReadTdata1),
797    MaskedRegMap(Tdata2, tdata2Phy(tselectPhy)),
798    MaskedRegMap(Tinfo, tinfo, 0.U(XLEN.W), MaskedRegMap.Unwritable),
799    MaskedRegMap(Tcontrol, tControlPhy, tcontrolWriteMask),
800
801    //--- Debug Mode ---
802    MaskedRegMap(Dcsr, dcsr, dcsrMask, dcsrUpdateSideEffect),
803    MaskedRegMap(Dpc, dpc),
804    MaskedRegMap(Dscratch, dscratch),
805    MaskedRegMap(Dscratch1, dscratch1),
806    MaskedRegMap(Mcountinhibit, mcountinhibit),
807    MaskedRegMap(Mcycle, mcycle),
808    MaskedRegMap(Minstret, minstret),
809  )
810
811  val perfCntMapping = (0 until 29).map(i => {Map(
812    MaskedRegMap(addr = Mhpmevent3 +i,
813                 reg  = perfEvents(i),
814                 wmask = "hf87fff3fcff3fcff".U(XLEN.W)),
815    MaskedRegMap(addr = Mhpmcounter3 +i,
816                 reg  = perfCnts(i))
817  )}).fold(Map())((a,b) => a ++ b)
818  // TODO: mechanism should be implemented later
819  // val MhpmcounterStart = Mhpmcounter3
820  // val MhpmeventStart   = Mhpmevent3
821  // for (i <- 0 until nrPerfCnts) {
822  //   perfCntMapping += MaskedRegMap(MhpmcounterStart + i, perfCnts(i))
823  //   perfCntMapping += MaskedRegMap(MhpmeventStart + i, perfEvents(i))
824  // }
825
826  val cacheopRegs = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
827    name -> RegInit(0.U(attribute("width").toInt.W))
828  }}
829  val cacheopMapping = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
830    MaskedRegMap(
831      Scachebase + attribute("offset").toInt,
832      cacheopRegs(name)
833    )
834  }}
835
836  val mapping = basicPrivMapping ++
837                perfCntMapping ++
838                pmpMapping ++
839                pmaMapping ++
840                (if (HasFPU) fcsrMapping else Nil) ++
841                (if (HasVPU) vcsrMapping else Nil) ++
842                (if (HasCustomCSRCacheOp) cacheopMapping else Nil)
843
844  val addr = src2(11, 0)
845  val csri = ZeroExt(src2(16, 12), XLEN)
846  val rdata = Wire(UInt(XLEN.W))
847  val wdata = LookupTree(func, List(
848    CSROpType.wrt  -> src1,
849    CSROpType.set  -> (rdata | src1),
850    CSROpType.clr  -> (rdata & (~src1).asUInt),
851    CSROpType.wrti -> csri,
852    CSROpType.seti -> (rdata | csri),
853    CSROpType.clri -> (rdata & (~csri).asUInt)
854  ))
855
856  val addrInPerfCnt = (addr >= Mcycle.U) && (addr <= Mhpmcounter31.U) ||
857    (addr >= Mcountinhibit.U) && (addr <= Mhpmevent31.U) ||
858    addr === Mip.U
859  csrio.isPerfCnt := addrInPerfCnt && valid && func =/= CSROpType.jmp
860
861  // satp wen check
862  val satpLegalMode = (wdata.asTypeOf(new SatpStruct).mode===0.U) || (wdata.asTypeOf(new SatpStruct).mode===8.U)
863
864  // csr access check, special case
865  val tvmNotPermit = (priviledgeMode === ModeS && mstatusStruct.tvm.asBool)
866  val accessPermitted = !(addr === Satp.U && tvmNotPermit)
867  csrio.disableSfence := tvmNotPermit
868
869  // general CSR wen check
870  val wen = valid && func =/= CSROpType.jmp && (addr=/=Satp.U || satpLegalMode)
871  val dcsrPermitted = dcsrPermissionCheck(addr, false.B, debugMode)
872  val triggerPermitted = triggerPermissionCheck(addr, true.B, debugMode) // todo dmode
873  val modePermitted = csrAccessPermissionCheck(addr, false.B, priviledgeMode) && dcsrPermitted && triggerPermitted
874  val perfcntPermitted = perfcntPermissionCheck(addr, priviledgeMode, mcounteren, scounteren)
875  val permitted = Mux(addrInPerfCnt, perfcntPermitted, modePermitted) && accessPermitted
876
877  MaskedRegMap.generate(mapping, addr, rdata, wen && permitted, wdata)
878  io.out.bits.data := rdata
879  io.out.bits.uop := io.in.bits.uop
880  io.out.bits.uop.cf := cfOut
881  io.out.bits.uop.ctrl.flushPipe := flushPipe
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", cfIn.pc, addr, rdata, wdata, func)
967  XSDebug(wen, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", cfIn.pc, 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(cfIn.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  cfOut.exceptionVec := 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.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc)
1100  val dvmEnable = tlbBundle.priv.dmode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1101  val dexceptionPC = Mux(dvmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.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.uop.cf.exceptionVec(instrPageFault) && raiseException
1108  val hasLoadPageFault = csrio.exception.bits.uop.cf.exceptionVec(loadPageFault) && raiseException
1109  val hasStorePageFault = csrio.exception.bits.uop.cf.exceptionVec(storePageFault) && raiseException
1110  val hasStoreAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(storeAddrMisaligned) && raiseException
1111  val hasLoadAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(loadAddrMisaligned) && raiseException
1112  val hasInstrAccessFault = csrio.exception.bits.uop.cf.exceptionVec(instrAccessFault) && raiseException
1113  val hasLoadAccessFault = csrio.exception.bits.uop.cf.exceptionVec(loadAccessFault) && raiseException
1114  val hasStoreAccessFault = csrio.exception.bits.uop.cf.exceptionVec(storeAccessFault) && raiseException
1115  val hasbreakPoint = csrio.exception.bits.uop.cf.exceptionVec(breakPoint) && raiseException
1116  val hasSingleStep = csrio.exception.bits.uop.ctrl.singleStep && raiseException
1117  val hasTriggerHit = (csrio.exception.bits.uop.cf.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.uop.cf.trigger.frontendHit.asUInt)} " +
1121    p"backend hit vec ${Binary(csrio.exception.bits.uop.cf.trigger.backendHit.asUInt)}\n")
1122
1123  val raiseExceptionVec = csrio.exception.bits.uop.cf.exceptionVec
1124  val regularExceptionNO = ExceptionNO.priorities.foldRight(0.U)((i: Int, sum: UInt) => Mux(raiseExceptionVec(i), i.U, sum))
1125  val exceptionNO = Mux(hasSingleStep || hasTriggerHit, 3.U, regularExceptionNO)
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 || hasTriggerHit && triggerAction) // 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.uop.cf.crossPageIPFFix,
1163          SignExt(csrio.exception.bits.uop.cf.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.redirectIn.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 := Mux(hasTriggerHit, 2.U, Mux(hasbreakPoint, 1.U, 4.U))
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", cfIn.pc)
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.uop.cf.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