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