xref: /XiangShan/src/main/scala/xiangshan/backend/fu/CSR.scala (revision b6c99e8e0860a7dc7a9395cdfaf7c9ae1796a16e)
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: Int): UInt = {mxl.U << (XLEN-2)}.asUInt
389  def getMisaExt(ext: Char): UInt = {1.U << (ext.toInt - 'a'.toInt)}.asUInt
390  var extList = List('a', 's', 'i', 'u')
391  if (HasMExtension) { extList = extList :+ 'm' }
392  if (HasCExtension) { extList = extList :+ 'c' }
393  if (HasFPU) { extList = extList ++ List('f', 'd') }
394  if (HasVPU) { extList = extList :+ 'v' }
395  val misaInitVal = getMisaMxl(2) | extList.foldLeft(0.U)((sum, i) => sum | getMisaExt(i)) //"h8000000000141105".U
396  val misa = RegInit(UInt(XLEN.W), misaInitVal)
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 = RegInit(UInt(XLEN.W), csrio.hartId) // the hardware thread running the code
405  val mconfigptr = RegInit(UInt(XLEN.W), 0.U) // the read-only pointer pointing to the platform config structure, 0 for not supported.
406  val mstatus = RegInit("ha00002000".U(XLEN.W))
407
408  // mstatus Value Table
409  // | sd   |
410  // | pad1 |
411  // | sxl  | hardlinked to 10, use 00 to pass xv6 test
412  // | uxl  | hardlinked to 10
413  // | pad0 |
414  // | tsr  |
415  // | tw   |
416  // | tvm  |
417  // | mxr  |
418  // | sum  |
419  // | mprv |
420  // | xs   | 00 |
421  // | fs   | 01 |
422  // | mpp  | 00 |
423  // | vs  | 00 |
424  // | spp  | 0 |
425  // | pie  | 0000 | pie.h is used as UBE
426  // | ie   | 0000 | uie hardlinked to 0, as N ext is not implemented
427
428  val mstatusStruct = mstatus.asTypeOf(new MstatusStruct)
429  def mstatusUpdateSideEffect(mstatus: UInt): UInt = {
430    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
431    val mstatusNew = Cat(mstatusOld.xs === "b11".U || mstatusOld.fs === "b11".U, mstatus(XLEN-2, 0))
432    mstatusNew
433  }
434
435  val mstatusWMask = (~ZeroExt((
436    GenMask(XLEN - 2, 36) | // WPRI
437    GenMask(35, 32)       | // SXL and UXL cannot be changed
438    GenMask(31, 23)       | // WPRI
439    GenMask(16, 15)       | // XS is read-only
440    GenMask(10, 9)        | // WPRI
441    GenMask(6)            | // WPRI
442    GenMask(2)              // WPRI
443  ), 64)).asUInt
444  val mstatusMask = (~ZeroExt((
445    GenMask(XLEN - 2, 36) | // WPRI
446    GenMask(31, 23)       | // WPRI
447    GenMask(10, 9)        | // WPRI
448    GenMask(6)            | // WPRI
449    GenMask(2)              // WPRI
450  ), 64)).asUInt
451
452  val medeleg = RegInit(UInt(XLEN.W), 0.U)
453  val mideleg = RegInit(UInt(XLEN.W), 0.U)
454  val mscratch = RegInit(UInt(XLEN.W), 0.U)
455
456  // PMP Mapping
457  val pmp = Wire(Vec(NumPMP, new PMPEntry())) // just used for method parameter
458  val pma = Wire(Vec(NumPMA, new PMPEntry())) // just used for method parameter
459  val pmpMapping = pmp_gen_mapping(pmp_init, NumPMP, PmpcfgBase, PmpaddrBase, pmp)
460  val pmaMapping = pmp_gen_mapping(pma_init, NumPMA, PmacfgBase, PmaaddrBase, pma)
461
462  // Superviser-Level CSRs
463
464  // val sstatus = RegInit(UInt(XLEN.W), "h00000000".U)
465  val sstatusWmask = "hc6122".U(XLEN.W)
466  // Sstatus Write Mask
467  // -------------------------------------------------------
468  //    19           9   5     2
469  // 0  1100 0000 0001 0010 0010
470  // 0  c    0    1    2    2
471  // -------------------------------------------------------
472  val sstatusRmask = sstatusWmask | "h8000000300018000".U
473  // Sstatus Read Mask = (SSTATUS_WMASK | (0xf << 13) | (1ull << 63) | (3ull << 32))
474  // stvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1
475  val stvecMask = ~(0x2.U(XLEN.W))
476  val stvec = RegInit(UInt(XLEN.W), 0.U)
477  // val sie = RegInit(0.U(XLEN.W))
478  val sieMask = "h222".U & mideleg
479  val sipMask = "h222".U & mideleg
480  val sipWMask = "h2".U(XLEN.W) // ssip is writeable in smode
481  val satp = if(EnbaleTlbDebug) RegInit(UInt(XLEN.W), "h8000000000087fbe".U) else RegInit(0.U(XLEN.W))
482  // val satp = RegInit(UInt(XLEN.W), "h8000000000087fbe".U) // only use for tlb naive debug
483  // val satpMask = "h80000fffffffffff".U(XLEN.W) // disable asid, mode can only be 8 / 0
484  // TODO: use config to control the length of asid
485  // val satpMask = "h8fffffffffffffff".U(XLEN.W) // enable asid, mode can only be 8 / 0
486  val satpMask = Cat("h8".U(Satp_Mode_len.W), satp_part_wmask(Satp_Asid_len, AsidLength), satp_part_wmask(Satp_Addr_len, PAddrBits-12))
487  val sepc = RegInit(UInt(XLEN.W), 0.U)
488  // Page 60 in riscv-priv: The low bit of sepc (sepc[0]) is always zero.
489  val sepcMask = ~(0x1.U(XLEN.W))
490  val scause = RegInit(UInt(XLEN.W), 0.U)
491  val stval = Reg(UInt(XLEN.W))
492  val sscratch = RegInit(UInt(XLEN.W), 0.U)
493  val scounteren = RegInit(UInt(XLEN.W), 0.U)
494
495  // sbpctl
496  // Bits 0-7: {LOOP, RAS, SC, TAGE, BIM, BTB, uBTB}
497  val sbpctl = RegInit(UInt(XLEN.W), "h7f".U)
498  csrio.customCtrl.bp_ctrl.ubtb_enable := sbpctl(0)
499  csrio.customCtrl.bp_ctrl.btb_enable  := sbpctl(1)
500  csrio.customCtrl.bp_ctrl.bim_enable  := sbpctl(2)
501  csrio.customCtrl.bp_ctrl.tage_enable := sbpctl(3)
502  csrio.customCtrl.bp_ctrl.sc_enable   := sbpctl(4)
503  csrio.customCtrl.bp_ctrl.ras_enable  := sbpctl(5)
504  csrio.customCtrl.bp_ctrl.loop_enable := sbpctl(6)
505
506  // spfctl Bit 0: L1I Cache Prefetcher Enable
507  // spfctl Bit 1: L2Cache Prefetcher Enable
508  val spfctl = RegInit(UInt(XLEN.W), "b11".U)
509  csrio.customCtrl.l1I_pf_enable := spfctl(0)
510  csrio.customCtrl.l2_pf_enable := spfctl(1)
511
512  // sfetchctl Bit 0: L1I Cache Parity check enable
513  val sfetchctl = RegInit(UInt(XLEN.W), "b0".U)
514  csrio.customCtrl.icache_parity_enable := sfetchctl(0)
515
516  // sdsid: Differentiated Services ID
517  val sdsid = RegInit(UInt(XLEN.W), 0.U)
518  csrio.customCtrl.dsid := sdsid
519
520  // slvpredctl: load violation predict settings
521  // Default reset period: 2^16
522  // Why this number: reset more frequently while keeping the overhead low
523  // Overhead: extra two redirections in every 64K cycles => ~0.1% overhead
524  val slvpredctl = RegInit(UInt(XLEN.W), "h60".U)
525  csrio.customCtrl.lvpred_disable := slvpredctl(0)
526  csrio.customCtrl.no_spec_load := slvpredctl(1)
527  csrio.customCtrl.storeset_wait_store := slvpredctl(2)
528  csrio.customCtrl.storeset_no_fast_wakeup := slvpredctl(3)
529  csrio.customCtrl.lvpred_timeout := slvpredctl(8, 4)
530
531  //  smblockctl: memory block configurations
532  //  +------------------------------+---+----+----+-----+--------+
533  //  |XLEN-1                       8| 7 | 6  | 5  |  4  |3      0|
534  //  +------------------------------+---+----+----+-----+--------+
535  //  |           Reserved           | O | CE | SP | LVC |   Th   |
536  //  +------------------------------+---+----+----+-----+--------+
537  //  Description:
538  //  Bit 3-0   : Store buffer flush threshold (Th).
539  //  Bit 4     : Enable load violation check after reset (LVC).
540  //  Bit 5     : Enable soft-prefetch after reset (SP).
541  //  Bit 6     : Enable cache error after reset (CE).
542  //  Bit 7     : Enable uncache write outstanding (O).
543  //  Others    : Reserved.
544
545  val smblockctl_init_val =
546    ("hf".U & StoreBufferThreshold.U) |
547    (EnableLdVioCheckAfterReset.B.asUInt << 4) |
548    (EnableSoftPrefetchAfterReset.B.asUInt << 5) |
549    (EnableCacheErrorAfterReset.B.asUInt << 6) |
550    (EnableUncacheWriteOutstanding.B.asUInt << 7)
551  val smblockctl = RegInit(UInt(XLEN.W), smblockctl_init_val)
552  csrio.customCtrl.sbuffer_threshold := smblockctl(3, 0)
553  // bits 4: enable load load violation check
554  csrio.customCtrl.ldld_vio_check_enable := smblockctl(4)
555  csrio.customCtrl.soft_prefetch_enable := smblockctl(5)
556  csrio.customCtrl.cache_error_enable := smblockctl(6)
557  csrio.customCtrl.uncache_write_outstanding_enable := smblockctl(7)
558
559  println("CSR smblockctl init value:")
560  println("  Store buffer replace threshold: " + StoreBufferThreshold)
561  println("  Enable ld-ld vio check after reset: " + EnableLdVioCheckAfterReset)
562  println("  Enable soft prefetch after reset: " + EnableSoftPrefetchAfterReset)
563  println("  Enable cache error after reset: " + EnableCacheErrorAfterReset)
564  println("  Enable uncache write outstanding: " + EnableUncacheWriteOutstanding)
565
566  val srnctl = RegInit(UInt(XLEN.W), "h7".U)
567  csrio.customCtrl.fusion_enable := srnctl(0)
568  csrio.customCtrl.svinval_enable := srnctl(1)
569  csrio.customCtrl.wfi_enable := srnctl(2)
570
571  val tlbBundle = Wire(new TlbCsrBundle)
572  tlbBundle.satp.apply(satp)
573
574  csrio.tlb := tlbBundle
575
576  // User-Level CSRs
577  val uepc = Reg(UInt(XLEN.W))
578
579  // fcsr
580  class FcsrStruct extends Bundle {
581    val reserved = UInt((XLEN-3-5).W)
582    val frm = UInt(3.W)
583    val fflags = UInt(5.W)
584    assert(this.getWidth == XLEN)
585  }
586  val fcsr = RegInit(0.U(XLEN.W))
587  // set mstatus->sd and mstatus->fs when true
588  val csrw_dirty_fp_state = WireInit(false.B)
589
590  def frm_wfn(wdata: UInt): UInt = {
591    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
592    csrw_dirty_fp_state := true.B
593    fcsrOld.frm := wdata(2,0)
594    fcsrOld.asUInt
595  }
596  def frm_rfn(rdata: UInt): UInt = rdata(7,5)
597
598  def fflags_wfn(update: Boolean)(wdata: UInt): UInt = {
599    val fcsrOld = fcsr.asTypeOf(new FcsrStruct)
600    val fcsrNew = WireInit(fcsrOld)
601    csrw_dirty_fp_state := true.B
602    if (update) {
603      fcsrNew.fflags := wdata(4,0) | fcsrOld.fflags
604    } else {
605      fcsrNew.fflags := wdata(4,0)
606    }
607    fcsrNew.asUInt
608  }
609  def fflags_rfn(rdata:UInt): UInt = rdata(4,0)
610
611  def fcsr_wfn(wdata: UInt): UInt = {
612    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
613    csrw_dirty_fp_state := true.B
614    Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags)
615  }
616
617  val fcsrMapping = Map(
618    MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn(update = false), rfn = fflags_rfn),
619    MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn),
620    MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn)
621  )
622
623  // Vector extension CSRs
624  val vstart = Reg(UInt(XLEN.W))
625  val vcsr = RegInit(0.U(XLEN.W))
626  val vl = Reg(UInt(XLEN.W))
627  val vtype = Reg(UInt(XLEN.W))
628  val vlenb = RegInit(0.U(XLEN.W))
629
630  // set mstatus->sd and mstatus->vs when true
631  val csrw_dirty_vs_state = WireInit(false.B)
632
633  // vcsr is mapped to vxrm and vxsat
634  class VcsrStruct extends Bundle {
635    val reserved = UInt((XLEN-3).W)
636    val vxrm = UInt(2.W)
637    val vxsat = UInt(1.W)
638    assert(this.getWidth == XLEN)
639  }
640
641  class VtypeStruct extends Bundle {
642    val vill = UInt(1.W)
643    val reserved = UInt((XLEN-9).W)
644    val vma = UInt(1.W)
645    val vta = UInt(1.W)
646    val vsew = UInt(3.W)
647    val vlmul = UInt(3.W)
648  }
649
650  def vxrm_wfn(wdata: UInt): UInt = {
651    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
652    csrw_dirty_vs_state := true.B
653    vcsrOld.vxrm := wdata(1,0)
654    vcsrOld.asUInt
655  }
656  def vxrm_rfn(rdata: UInt): UInt = rdata(2,1)
657
658  def vxsat_wfn(wdata: UInt): UInt = {
659    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
660    csrw_dirty_vs_state := true.B
661    vcsrOld.vxsat := wdata(0)
662    vcsrOld.asUInt
663  }
664  def vxsat_rfn(rdata: UInt): UInt = rdata(0)
665
666  def vcsr_wfn(wdata: UInt): UInt = {
667    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
668    csrw_dirty_vs_state := true.B
669    vcsrOld.vxrm := wdata.asTypeOf(vcsrOld).vxrm
670    vcsrOld.vxsat := wdata.asTypeOf(vcsrOld).vxsat
671    vcsrOld.asUInt
672  }
673
674  val vcsrMapping = Map(
675    MaskedRegMap(Vstart, vstart),
676    MaskedRegMap(Vxrm, vcsr, wfn = vxrm_wfn, rfn = vxrm_rfn),
677    MaskedRegMap(Vxsat, vcsr, wfn = vxsat_wfn, rfn = vxsat_rfn),
678    MaskedRegMap(Vcsr, vcsr, wfn = vcsr_wfn),
679    MaskedRegMap(Vl, vl),
680    MaskedRegMap(Vtype, vtype),
681    MaskedRegMap(Vlenb, vlenb),
682  )
683
684  // Hart Priviledge Mode
685  val priviledgeMode = RegInit(UInt(2.W), ModeM)
686
687  //val perfEventscounten = List.fill(nrPerfCnts)(RegInit(false(Bool())))
688  // Perf Counter
689  val nrPerfCnts = 29  // 3...31
690  val priviledgeModeOH = UIntToOH(priviledgeMode)
691  val perfEventscounten = RegInit(0.U.asTypeOf(Vec(nrPerfCnts, Bool())))
692  val perfCnts   = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W)))
693  val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++
694                   List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++
695                   List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++
696                   List.fill(5)(RegInit("hc0300c0300".U(XLEN.W)))
697  for (i <-0 until nrPerfCnts) {
698    perfEventscounten(i) := (Cat(perfEvents(i)(62),perfEvents(i)(61),(perfEvents(i)(61,60))) & priviledgeModeOH).orR
699  }
700
701  val hpmEvents = Wire(Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent))
702  for (i <- 0 until numPCntHc * coreParams.L2NBanks) {
703    hpmEvents(i) := csrio.perf.perfEventsHc(i)
704  }
705
706  val csrevents = perfEvents.slice(24, 29)
707  val hpm_hc = HPerfMonitor(csrevents, hpmEvents)
708  val mcountinhibit = RegInit(0.U(XLEN.W))
709  val mcycle = RegInit(0.U(XLEN.W))
710  mcycle := mcycle + 1.U
711  val minstret = RegInit(0.U(XLEN.W))
712  val perf_events = csrio.perf.perfEventsFrontend ++
713                    csrio.perf.perfEventsCtrl ++
714                    csrio.perf.perfEventsLsu ++
715                    hpm_hc.getPerf
716  minstret := minstret + RegNext(csrio.perf.retiredInstr)
717  for(i <- 0 until 29){
718    perfCnts(i) := Mux(mcountinhibit(i+3) | !perfEventscounten(i), perfCnts(i), perfCnts(i) + perf_events(i).value)
719  }
720
721  // CSR reg map
722  val basicPrivMapping = Map(
723
724    //--- User Trap Setup ---
725    // MaskedRegMap(Ustatus, ustatus),
726    // MaskedRegMap(Uie, uie, 0.U, MaskedRegMap.Unwritable),
727    // MaskedRegMap(Utvec, utvec),
728
729    //--- User Trap Handling ---
730    // MaskedRegMap(Uscratch, uscratch),
731    // MaskedRegMap(Uepc, uepc),
732    // MaskedRegMap(Ucause, ucause),
733    // MaskedRegMap(Utval, utval),
734    // MaskedRegMap(Uip, uip),
735
736    //--- User Counter/Timers ---
737    // MaskedRegMap(Cycle, cycle),
738    // MaskedRegMap(Time, time),
739    // MaskedRegMap(Instret, instret),
740
741    //--- Supervisor Trap Setup ---
742    MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask),
743    // MaskedRegMap(Sedeleg, Sedeleg),
744    // MaskedRegMap(Sideleg, Sideleg),
745    MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask),
746    MaskedRegMap(Stvec, stvec, stvecMask, MaskedRegMap.NoSideEffect, stvecMask),
747    MaskedRegMap(Scounteren, scounteren),
748
749    //--- Supervisor Trap Handling ---
750    MaskedRegMap(Sscratch, sscratch),
751    MaskedRegMap(Sepc, sepc, sepcMask, MaskedRegMap.NoSideEffect, sepcMask),
752    MaskedRegMap(Scause, scause),
753    MaskedRegMap(Stval, stval),
754    MaskedRegMap(Sip, mip.asUInt, sipWMask, MaskedRegMap.Unwritable, sipMask),
755
756    //--- Supervisor Protection and Translation ---
757    MaskedRegMap(Satp, satp, satpMask, MaskedRegMap.NoSideEffect, satpMask),
758
759    //--- Supervisor Custom Read/Write Registers
760    MaskedRegMap(Sbpctl, sbpctl),
761    MaskedRegMap(Spfctl, spfctl),
762    MaskedRegMap(Sfetchctl, sfetchctl),
763    MaskedRegMap(Sdsid, sdsid),
764    MaskedRegMap(Slvpredctl, slvpredctl),
765    MaskedRegMap(Smblockctl, smblockctl),
766    MaskedRegMap(Srnctl, srnctl),
767
768    //--- Machine Information Registers ---
769    MaskedRegMap(Mvendorid, mvendorid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
770    MaskedRegMap(Marchid, marchid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
771    MaskedRegMap(Mimpid, mimpid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
772    MaskedRegMap(Mhartid, mhartid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
773    MaskedRegMap(Mconfigptr, mconfigptr, 0.U(XLEN.W), MaskedRegMap.Unwritable),
774
775    //--- Machine Trap Setup ---
776    MaskedRegMap(Mstatus, mstatus, mstatusWMask, mstatusUpdateSideEffect, mstatusMask),
777    MaskedRegMap(Misa, misa, 0.U, MaskedRegMap.Unwritable), // now whole misa is unchangeable
778    MaskedRegMap(Medeleg, medeleg, "hb3ff".U(XLEN.W)),
779    MaskedRegMap(Mideleg, mideleg, "h222".U(XLEN.W)),
780    MaskedRegMap(Mie, mie),
781    MaskedRegMap(Mtvec, mtvec, mtvecMask, MaskedRegMap.NoSideEffect, mtvecMask),
782    MaskedRegMap(Mcounteren, mcounteren),
783
784    //--- Machine Trap Handling ---
785    MaskedRegMap(Mscratch, mscratch),
786    MaskedRegMap(Mepc, mepc, mepcMask, MaskedRegMap.NoSideEffect, mepcMask),
787    MaskedRegMap(Mcause, mcause),
788    MaskedRegMap(Mtval, mtval),
789    MaskedRegMap(Mip, mip.asUInt, 0.U(XLEN.W), MaskedRegMap.Unwritable),
790
791    //--- Trigger ---
792    MaskedRegMap(Tselect, tselectPhy, WritableMask, WriteTselect),
793    MaskedRegMap(Tdata1, tdata1Phy(tselectPhy), WritableMask, WriteTdata1, WritableMask, ReadTdata1),
794    MaskedRegMap(Tdata2, tdata2Phy(tselectPhy)),
795    MaskedRegMap(Tinfo, tinfo, 0.U(XLEN.W), MaskedRegMap.Unwritable),
796    MaskedRegMap(Tcontrol, tControlPhy, tcontrolWriteMask),
797
798    //--- Debug Mode ---
799    MaskedRegMap(Dcsr, dcsr, dcsrMask, dcsrUpdateSideEffect),
800    MaskedRegMap(Dpc, dpc),
801    MaskedRegMap(Dscratch, dscratch),
802    MaskedRegMap(Dscratch1, dscratch1),
803    MaskedRegMap(Mcountinhibit, mcountinhibit),
804    MaskedRegMap(Mcycle, mcycle),
805    MaskedRegMap(Minstret, minstret),
806  )
807
808  val perfCntMapping = (0 until 29).map(i => {Map(
809    MaskedRegMap(addr = Mhpmevent3 +i,
810                 reg  = perfEvents(i),
811                 wmask = "hf87fff3fcff3fcff".U(XLEN.W)),
812    MaskedRegMap(addr = Mhpmcounter3 +i,
813                 reg  = perfCnts(i))
814  )}).fold(Map())((a,b) => a ++ b)
815  // TODO: mechanism should be implemented later
816  // val MhpmcounterStart = Mhpmcounter3
817  // val MhpmeventStart   = Mhpmevent3
818  // for (i <- 0 until nrPerfCnts) {
819  //   perfCntMapping += MaskedRegMap(MhpmcounterStart + i, perfCnts(i))
820  //   perfCntMapping += MaskedRegMap(MhpmeventStart + i, perfEvents(i))
821  // }
822
823  val cacheopRegs = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
824    name -> RegInit(0.U(attribute("width").toInt.W))
825  }}
826  val cacheopMapping = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
827    MaskedRegMap(
828      Scachebase + attribute("offset").toInt,
829      cacheopRegs(name)
830    )
831  }}
832
833  val mapping = basicPrivMapping ++
834                perfCntMapping ++
835                pmpMapping ++
836                pmaMapping ++
837                (if (HasFPU) fcsrMapping else Nil) ++
838                (if (HasVPU) vcsrMapping else Nil) ++
839                (if (HasCustomCSRCacheOp) cacheopMapping else Nil)
840
841  val addr = src2(11, 0)
842  val csri = ZeroExt(src2(16, 12), XLEN)
843  val rdata = Wire(UInt(XLEN.W))
844  val wdata = LookupTree(func, List(
845    CSROpType.wrt  -> src1,
846    CSROpType.set  -> (rdata | src1),
847    CSROpType.clr  -> (rdata & (~src1).asUInt),
848    CSROpType.wrti -> csri,
849    CSROpType.seti -> (rdata | csri),
850    CSROpType.clri -> (rdata & (~csri).asUInt)
851  ))
852
853  val addrInPerfCnt = (addr >= Mcycle.U) && (addr <= Mhpmcounter31.U) ||
854    (addr >= Mcountinhibit.U) && (addr <= Mhpmevent31.U) ||
855    addr === Mip.U
856  csrio.isPerfCnt := addrInPerfCnt && valid && func =/= CSROpType.jmp
857
858  // satp wen check
859  val satpLegalMode = (wdata.asTypeOf(new SatpStruct).mode===0.U) || (wdata.asTypeOf(new SatpStruct).mode===8.U)
860
861  // csr access check, special case
862  val tvmNotPermit = (priviledgeMode === ModeS && mstatusStruct.tvm.asBool)
863  val accessPermitted = !(addr === Satp.U && tvmNotPermit)
864  csrio.disableSfence := tvmNotPermit
865
866  // general CSR wen check
867  val wen = valid && func =/= CSROpType.jmp && (addr=/=Satp.U || satpLegalMode)
868  val dcsrPermitted = dcsrPermissionCheck(addr, false.B, debugMode)
869  val triggerPermitted = triggerPermissionCheck(addr, true.B, debugMode) // todo dmode
870  val modePermitted = csrAccessPermissionCheck(addr, false.B, priviledgeMode) && dcsrPermitted && triggerPermitted
871  val perfcntPermitted = perfcntPermissionCheck(addr, priviledgeMode, mcounteren, scounteren)
872  val permitted = Mux(addrInPerfCnt, perfcntPermitted, modePermitted) && accessPermitted
873
874  MaskedRegMap.generate(mapping, addr, rdata, wen && permitted, wdata)
875  io.out.bits.data := rdata
876  io.out.bits.uop := io.in.bits.uop
877  io.out.bits.uop.cf := cfOut
878  io.out.bits.uop.ctrl.flushPipe := flushPipe
879
880  // send distribute csr a w signal
881  csrio.customCtrl.distribute_csr.w.valid := wen && permitted
882  csrio.customCtrl.distribute_csr.w.bits.data := wdata
883  csrio.customCtrl.distribute_csr.w.bits.addr := addr
884
885  // Fix Mip/Sip write
886  val fixMapping = Map(
887    MaskedRegMap(Mip, mipReg.asUInt, mipFixMask),
888    MaskedRegMap(Sip, mipReg.asUInt, sipWMask, MaskedRegMap.NoSideEffect, sipMask)
889  )
890  val rdataFix = Wire(UInt(XLEN.W))
891  val wdataFix = LookupTree(func, List(
892    CSROpType.wrt  -> src1,
893    CSROpType.set  -> (rdataFix | src1),
894    CSROpType.clr  -> (rdataFix & (~src1).asUInt),
895    CSROpType.wrti -> csri,
896    CSROpType.seti -> (rdataFix | csri),
897    CSROpType.clri -> (rdataFix & (~csri).asUInt)
898  ))
899  MaskedRegMap.generate(fixMapping, addr, rdataFix, wen && permitted, wdataFix)
900
901  when (RegNext(csrio.fpu.fflags.valid)) {
902    fcsr := fflags_wfn(update = true)(RegNext(csrio.fpu.fflags.bits))
903  }
904  // set fs and sd in mstatus
905  when (csrw_dirty_fp_state || RegNext(csrio.fpu.dirty_fs)) {
906    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
907    mstatusNew.fs := "b11".U
908    mstatusNew.sd := true.B
909    mstatus := mstatusNew.asUInt
910  }
911  csrio.fpu.frm := fcsr.asTypeOf(new FcsrStruct).frm
912
913  when (RegNext(csrio.vpu.set_vstart.valid)) {
914    vstart := RegNext(csrio.vpu.set_vstart.bits)
915  }
916  when (RegNext(csrio.vpu.set_vtype.valid)) {
917    vtype := RegNext(csrio.vpu.set_vtype.bits)
918  }
919  when (RegNext(csrio.vpu.set_vl.valid)) {
920    vl := RegNext(csrio.vpu.set_vl.bits)
921  }
922  // set vs and sd in mstatus
923  // when (csrw_dirty_vs_state || RegNext(csrio.vpu.dirty_vs)) {
924  //   val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
925  //   mstatusNew.vs := "b11".U
926  //   mstatusNew.sd := true.B
927  //   mstatus := mstatusNew.asUInt
928  // }
929
930  csrio.vpu.vstart := vstart
931  csrio.vpu.vxrm := vcsr.asTypeOf(new VcsrStruct).vxrm
932  csrio.vpu.vxsat := vcsr.asTypeOf(new VcsrStruct).vxsat
933  csrio.vpu.vcsr := vcsr
934  csrio.vpu.vtype := vtype
935  csrio.vpu.vl := vl
936  csrio.vpu.vlenb := vlenb
937  csrio.vpu.vill := vtype.asTypeOf(new VtypeStruct).vill
938  csrio.vpu.vma := vtype.asTypeOf(new VtypeStruct).vma
939  csrio.vpu.vta := vtype.asTypeOf(new VtypeStruct).vta
940  csrio.vpu.vsew := vtype.asTypeOf(new VtypeStruct).vsew
941  csrio.vpu.vlmul := vtype.asTypeOf(new VtypeStruct).vlmul
942
943  // Trigger Ctrl
944  csrio.customCtrl.trigger_enable := tdata1Phy.map{t =>
945    def tdata1 = t.asTypeOf(new TdataBundle)
946    tdata1.m && priviledgeMode === ModeM ||
947    tdata1.s && priviledgeMode === ModeS || tdata1.u && priviledgeMode === ModeU
948  }
949  csrio.customCtrl.frontend_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) === I_Trigger)
950  csrio.customCtrl.mem_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) =/= I_Trigger)
951  XSDebug(csrio.customCtrl.trigger_enable.asUInt.orR, p"Debug Mode: At least 1 trigger is enabled," +
952    p"trigger enable is ${Binary(csrio.customCtrl.trigger_enable.asUInt)}\n")
953
954  // CSR inst decode
955  val isEbreak = addr === privEbreak && func === CSROpType.jmp
956  val isEcall  = addr === privEcall  && func === CSROpType.jmp
957  val isMret   = addr === privMret   && func === CSROpType.jmp
958  val isSret   = addr === privSret   && func === CSROpType.jmp
959  val isUret   = addr === privUret   && func === CSROpType.jmp
960  val isDret   = addr === privDret   && func === CSROpType.jmp
961  val isWFI    = func === CSROpType.wfi
962
963  XSDebug(wen, "csr write: pc %x addr %x rdata %x wdata %x func %x\n", cfIn.pc, addr, rdata, wdata, func)
964  XSDebug(wen, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", cfIn.pc, mstatus, mideleg , medeleg, priviledgeMode)
965
966  // Illegal priviledged operation list
967  val illegalMret = valid && isMret && priviledgeMode < ModeM
968  val illegalSret = valid && isSret && priviledgeMode < ModeS
969  val illegalSModeSret = valid && isSret && priviledgeMode === ModeS && mstatusStruct.tsr.asBool
970  // When TW=1, then if WFI is executed in any less-privileged mode,
971  // and it does not complete within an implementation-specific, bounded time limit,
972  // the WFI instruction causes an illegal instruction exception.
973  // The time limit may always be 0, in which case WFI always causes
974  // an illegal instruction exception in less-privileged modes when TW=1.
975  val illegalWFI = valid && isWFI && priviledgeMode < ModeM && mstatusStruct.tw === 1.U
976
977  // Illegal priviledged instruction check
978  val isIllegalAddr = valid && CSROpType.needAccess(func) && MaskedRegMap.isIllegalAddr(mapping, addr)
979  val isIllegalAccess = wen && !permitted
980  val isIllegalPrivOp = illegalMret || illegalSret || illegalSModeSret || illegalWFI
981
982  // expose several csr bits for tlb
983  tlbBundle.priv.mxr   := mstatusStruct.mxr.asBool
984  tlbBundle.priv.sum   := mstatusStruct.sum.asBool
985  tlbBundle.priv.imode := priviledgeMode
986  tlbBundle.priv.dmode := Mux(debugMode && dcsr.asTypeOf(new DcsrStruct).mprven, ModeM, Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpp, priviledgeMode))
987
988  // Branch control
989  val retTarget = Wire(UInt(VAddrBits.W))
990  val resetSatp = addr === Satp.U && wen // write to satp will cause the pipeline be flushed
991  flushPipe := resetSatp || (valid && func === CSROpType.jmp && !isEcall && !isEbreak)
992
993  retTarget := DontCare
994  // val illegalEret = TODO
995
996  when (valid && isDret) {
997    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
998    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
999    val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct))
1000    val debugModeNew = WireInit(debugMode)
1001    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.
1002    mstatus := mstatusNew.asUInt
1003    priviledgeMode := dcsrNew.prv
1004    retTarget := dpc(VAddrBits-1, 0)
1005    debugModeNew := false.B
1006    debugIntrEnable := true.B
1007    debugMode := debugModeNew
1008    XSDebug("Debug Mode: Dret executed, returning to %x.", retTarget)
1009  }
1010
1011  when (valid && isMret && !illegalMret) {
1012    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1013    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1014    mstatusNew.ie.m := mstatusOld.pie.m
1015    priviledgeMode := mstatusOld.mpp
1016    mstatusNew.pie.m := true.B
1017    mstatusNew.mpp := ModeU
1018    when (mstatusOld.mpp =/= ModeM) { mstatusNew.mprv := 0.U }
1019    mstatus := mstatusNew.asUInt
1020    // lr := false.B
1021    retTarget := mepc(VAddrBits-1, 0)
1022  }
1023
1024  when (valid && isSret && !illegalSret && !illegalSModeSret) {
1025    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1026    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1027    mstatusNew.ie.s := mstatusOld.pie.s
1028    priviledgeMode := Cat(0.U(1.W), mstatusOld.spp)
1029    mstatusNew.pie.s := true.B
1030    mstatusNew.spp := ModeU
1031    mstatus := mstatusNew.asUInt
1032    when (mstatusOld.spp =/= ModeM) { mstatusNew.mprv := 0.U }
1033    // lr := false.B
1034    retTarget := sepc(VAddrBits-1, 0)
1035  }
1036
1037  when (valid && isUret) {
1038    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1039    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1040    // mstatusNew.mpp.m := ModeU //TODO: add mode U
1041    mstatusNew.ie.u := mstatusOld.pie.u
1042    priviledgeMode := ModeU
1043    mstatusNew.pie.u := true.B
1044    mstatus := mstatusNew.asUInt
1045    retTarget := uepc(VAddrBits-1, 0)
1046  }
1047
1048  io.in.ready := true.B
1049  io.out.valid := valid
1050
1051  val ebreakCauseException = (priviledgeMode === ModeM && dcsrData.ebreakm) || (priviledgeMode === ModeS && dcsrData.ebreaks) || (priviledgeMode === ModeU && dcsrData.ebreaku)
1052
1053  val csrExceptionVec = WireInit(cfIn.exceptionVec)
1054  csrExceptionVec(breakPoint) := io.in.valid && isEbreak && (ebreakCauseException || debugMode)
1055  csrExceptionVec(ecallM) := priviledgeMode === ModeM && io.in.valid && isEcall
1056  csrExceptionVec(ecallS) := priviledgeMode === ModeS && io.in.valid && isEcall
1057  csrExceptionVec(ecallU) := priviledgeMode === ModeU && io.in.valid && isEcall
1058  // Trigger an illegal instr exception when:
1059  // * unimplemented csr is being read/written
1060  // * csr access is illegal
1061  csrExceptionVec(illegalInstr) := isIllegalAddr || isIllegalAccess || isIllegalPrivOp
1062  cfOut.exceptionVec := csrExceptionVec
1063
1064  XSDebug(io.in.valid && isEbreak, s"Debug Mode: an Ebreak is executed, ebreak cause exception ? ${ebreakCauseException}\n")
1065
1066  /**
1067    * Exception and Intr
1068    */
1069  val ideleg =  (mideleg & mip.asUInt)
1070  def priviledgedEnableDetect(x: Bool): Bool = Mux(x, ((priviledgeMode === ModeS) && mstatusStruct.ie.s) || (priviledgeMode < ModeS),
1071    ((priviledgeMode === ModeM) && mstatusStruct.ie.m) || (priviledgeMode < ModeM))
1072
1073  val debugIntr = csrio.externalInterrupt.debug & debugIntrEnable
1074  XSDebug(debugIntr, "Debug Mode: debug interrupt is asserted and valid!")
1075  // send interrupt information to ROB
1076  val intrVecEnable = Wire(Vec(12, Bool()))
1077  val disableInterrupt = debugMode || (dcsrData.step && !dcsrData.stepie)
1078  intrVecEnable.zip(ideleg.asBools).map{case(x,y) => x := priviledgedEnableDetect(y) && !disableInterrupt}
1079  val intrVec = Cat(debugIntr && !debugMode, (mie(11,0) & mip.asUInt & intrVecEnable.asUInt))
1080  val intrBitSet = intrVec.orR
1081  csrio.interrupt := intrBitSet
1082  // Page 45 in RISC-V Privileged Specification
1083  // The WFI instruction can also be executed when interrupts are disabled. The operation of WFI
1084  // must be unaffected by the global interrupt bits in mstatus (MIE and SIE) and the delegation
1085  // register mideleg, but should honor the individual interrupt enables (e.g, MTIE).
1086  csrio.wfi_event := debugIntr || (mie(11, 0) & mip.asUInt).orR
1087  mipWire.t.m := csrio.externalInterrupt.mtip
1088  mipWire.s.m := csrio.externalInterrupt.msip
1089  mipWire.e.m := csrio.externalInterrupt.meip
1090  mipWire.e.s := csrio.externalInterrupt.seip
1091
1092  // interrupts
1093  val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(intrVec(i), i.U, sum))
1094  val raiseIntr = csrio.exception.valid && csrio.exception.bits.isInterrupt
1095  val ivmEnable = tlbBundle.priv.imode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1096  val iexceptionPC = Mux(ivmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc)
1097  val dvmEnable = tlbBundle.priv.dmode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1098  val dexceptionPC = Mux(dvmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc)
1099  XSDebug(raiseIntr, "interrupt: pc=0x%x, %d\n", dexceptionPC, intrNO)
1100  val raiseDebugIntr = intrNO === IRQ_DEBUG.U && raiseIntr
1101
1102  // exceptions
1103  val raiseException = csrio.exception.valid && !csrio.exception.bits.isInterrupt
1104  val hasInstrPageFault = csrio.exception.bits.uop.cf.exceptionVec(instrPageFault) && raiseException
1105  val hasLoadPageFault = csrio.exception.bits.uop.cf.exceptionVec(loadPageFault) && raiseException
1106  val hasStorePageFault = csrio.exception.bits.uop.cf.exceptionVec(storePageFault) && raiseException
1107  val hasStoreAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(storeAddrMisaligned) && raiseException
1108  val hasLoadAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(loadAddrMisaligned) && raiseException
1109  val hasInstrAccessFault = csrio.exception.bits.uop.cf.exceptionVec(instrAccessFault) && raiseException
1110  val hasLoadAccessFault = csrio.exception.bits.uop.cf.exceptionVec(loadAccessFault) && raiseException
1111  val hasStoreAccessFault = csrio.exception.bits.uop.cf.exceptionVec(storeAccessFault) && raiseException
1112  val hasbreakPoint = csrio.exception.bits.uop.cf.exceptionVec(breakPoint) && raiseException
1113  val hasSingleStep = csrio.exception.bits.uop.ctrl.singleStep && raiseException
1114  val hasTriggerHit = (csrio.exception.bits.uop.cf.trigger.hit) && raiseException
1115
1116  XSDebug(hasSingleStep, "Debug Mode: single step exception\n")
1117  XSDebug(hasTriggerHit, p"Debug Mode: trigger hit, is frontend? ${Binary(csrio.exception.bits.uop.cf.trigger.frontendHit.asUInt)} " +
1118    p"backend hit vec ${Binary(csrio.exception.bits.uop.cf.trigger.backendHit.asUInt)}\n")
1119
1120  val raiseExceptionVec = csrio.exception.bits.uop.cf.exceptionVec
1121  val regularExceptionNO = ExceptionNO.priorities.foldRight(0.U)((i: Int, sum: UInt) => Mux(raiseExceptionVec(i), i.U, sum))
1122  val exceptionNO = Mux(hasSingleStep || hasTriggerHit, 3.U, regularExceptionNO)
1123  val causeNO = (raiseIntr << (XLEN-1)).asUInt | Mux(raiseIntr, intrNO, exceptionNO)
1124
1125  val raiseExceptionIntr = csrio.exception.valid
1126
1127  val raiseDebugExceptionIntr = !debugMode && (hasbreakPoint || raiseDebugIntr || hasSingleStep || hasTriggerHit && triggerAction) // TODO
1128  val ebreakEnterParkLoop = debugMode && raiseExceptionIntr
1129
1130  XSDebug(raiseExceptionIntr, "int/exc: pc %x int (%d):%x exc: (%d):%x\n",
1131    dexceptionPC, intrNO, intrVec, exceptionNO, raiseExceptionVec.asUInt
1132  )
1133  XSDebug(raiseExceptionIntr,
1134    "pc %x mstatus %x mideleg %x medeleg %x mode %x\n",
1135    dexceptionPC,
1136    mstatus,
1137    mideleg,
1138    medeleg,
1139    priviledgeMode
1140  )
1141
1142  // mtval write logic
1143  // Due to timing reasons of memExceptionVAddr, we delay the write of mtval and stval
1144  val memExceptionAddr = SignExt(csrio.memExceptionVAddr, XLEN)
1145  val updateTval = VecInit(Seq(
1146    hasInstrPageFault,
1147    hasLoadPageFault,
1148    hasStorePageFault,
1149    hasInstrAccessFault,
1150    hasLoadAccessFault,
1151    hasStoreAccessFault,
1152    hasLoadAddrMisaligned,
1153    hasStoreAddrMisaligned
1154  )).asUInt.orR
1155  when (RegNext(RegNext(updateTval))) {
1156      val tval = Mux(
1157        RegNext(RegNext(hasInstrPageFault || hasInstrAccessFault)),
1158        RegNext(RegNext(Mux(
1159          csrio.exception.bits.uop.cf.crossPageIPFFix,
1160          SignExt(csrio.exception.bits.uop.cf.pc + 2.U, XLEN),
1161          iexceptionPC
1162        ))),
1163        memExceptionAddr
1164    )
1165    when (RegNext(priviledgeMode === ModeM)) {
1166      mtval := tval
1167    }.otherwise {
1168      stval := tval
1169    }
1170  }
1171
1172  val debugTrapTarget = Mux(!isEbreak && debugMode, 0x38020808.U, 0x38020800.U) // 0x808 is when an exception occurs in debug mode prog buf exec
1173  val deleg = Mux(raiseIntr, mideleg , medeleg)
1174  // val delegS = ((deleg & (1 << (causeNO & 0xf))) != 0) && (priviledgeMode < ModeM);
1175  val delegS = deleg(causeNO(3,0)) && (priviledgeMode < ModeM)
1176  val clearTval = !updateTval || raiseIntr
1177  val isXRet = io.in.valid && func === CSROpType.jmp && !isEcall && !isEbreak
1178
1179  // ctrl block will use theses later for flush
1180  val isXRetFlag = RegInit(false.B)
1181  when (DelayN(io.redirectIn.valid, 5)) {
1182    isXRetFlag := false.B
1183  }.elsewhen (isXRet) {
1184    isXRetFlag := true.B
1185  }
1186  csrio.isXRet := isXRetFlag
1187  val retTargetReg = RegEnable(retTarget, isXRet)
1188
1189  val tvec = Mux(delegS, stvec, mtvec)
1190  val tvecBase = tvec(VAddrBits - 1, 2)
1191  // XRet sends redirect instead of Flush and isXRetFlag is true.B before redirect.valid.
1192  // ROB sends exception at T0 while CSR receives at T2.
1193  // We add a RegNext here and trapTarget is valid at T3.
1194  csrio.trapTarget := RegEnable(Mux(isXRetFlag,
1195    retTargetReg,
1196    Mux(raiseDebugExceptionIntr || ebreakEnterParkLoop, debugTrapTarget,
1197      // When MODE=Vectored, all synchronous exceptions into M/S mode
1198      // cause the pc to be set to the address in the BASE field, whereas
1199      // interrupts cause the pc to be set to the address in the BASE field
1200      // plus four times the interrupt cause number.
1201      Cat(tvecBase + Mux(tvec(0) && raiseIntr, causeNO(3, 0), 0.U), 0.U(2.W))
1202  )), isXRetFlag || csrio.exception.valid)
1203
1204  when (raiseExceptionIntr) {
1205    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1206    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1207    val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct))
1208    val debugModeNew = WireInit(debugMode)
1209
1210    when (raiseDebugExceptionIntr) {
1211      when (raiseDebugIntr) {
1212        debugModeNew := true.B
1213        mstatusNew.mprv := false.B
1214        dpc := iexceptionPC
1215        dcsrNew.cause := 3.U
1216        dcsrNew.prv := priviledgeMode
1217        priviledgeMode := ModeM
1218        XSDebug(raiseDebugIntr, "Debug Mode: Trap to %x at pc %x\n", debugTrapTarget, dpc)
1219      }.elsewhen ((hasbreakPoint || hasSingleStep) && !debugMode) {
1220        // ebreak or ss in running hart
1221        debugModeNew := true.B
1222        dpc := iexceptionPC
1223        dcsrNew.cause := Mux(hasTriggerHit, 2.U, Mux(hasbreakPoint, 1.U, 4.U))
1224        dcsrNew.prv := priviledgeMode // TODO
1225        priviledgeMode := ModeM
1226        mstatusNew.mprv := false.B
1227      }
1228      dcsr := dcsrNew.asUInt
1229      debugIntrEnable := false.B
1230    }.elsewhen (debugMode) {
1231      //do nothing
1232    }.elsewhen (delegS) {
1233      scause := causeNO
1234      sepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1235      mstatusNew.spp := priviledgeMode
1236      mstatusNew.pie.s := mstatusOld.ie.s
1237      mstatusNew.ie.s := false.B
1238      priviledgeMode := ModeS
1239      when (clearTval) { stval := 0.U }
1240    }.otherwise {
1241      mcause := causeNO
1242      mepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1243      mstatusNew.mpp := priviledgeMode
1244      mstatusNew.pie.m := mstatusOld.ie.m
1245      mstatusNew.ie.m := false.B
1246      priviledgeMode := ModeM
1247      when (clearTval) { mtval := 0.U }
1248    }
1249    mstatus := mstatusNew.asUInt
1250    debugMode := debugModeNew
1251  }
1252
1253  XSDebug(raiseExceptionIntr && delegS, "sepc is written!!! pc:%x\n", cfIn.pc)
1254
1255  // Distributed CSR update req
1256  //
1257  // For now we use it to implement customized cache op
1258  // It can be delayed if necessary
1259
1260  val delayedUpdate0 = DelayN(csrio.distributedUpdate(0), 2)
1261  val delayedUpdate1 = DelayN(csrio.distributedUpdate(1), 2)
1262  val distributedUpdateValid = delayedUpdate0.w.valid || delayedUpdate1.w.valid
1263  val distributedUpdateAddr = Mux(delayedUpdate0.w.valid,
1264    delayedUpdate0.w.bits.addr,
1265    delayedUpdate1.w.bits.addr
1266  )
1267  val distributedUpdateData = Mux(delayedUpdate0.w.valid,
1268    delayedUpdate0.w.bits.data,
1269    delayedUpdate1.w.bits.data
1270  )
1271
1272  assert(!(delayedUpdate0.w.valid && delayedUpdate1.w.valid))
1273
1274  when(distributedUpdateValid){
1275    // cacheopRegs can be distributed updated
1276    CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
1277      when((Scachebase + attribute("offset").toInt).U === distributedUpdateAddr){
1278        cacheopRegs(name) := distributedUpdateData
1279      }
1280    }}
1281  }
1282
1283  // Cache error debug support
1284  if(HasCustomCSRCacheOp){
1285    val cache_error_decoder = Module(new CSRCacheErrorDecoder)
1286    cache_error_decoder.io.encoded_cache_error := cacheopRegs("CACHE_ERROR")
1287  }
1288
1289  // Implicit add reset values for mepc[0] and sepc[0]
1290  // TODO: rewrite mepc and sepc using a struct-like style with the LSB always being 0
1291  when (reset.asBool) {
1292    mepc := Cat(mepc(XLEN - 1, 1), 0.U(1.W))
1293    sepc := Cat(sepc(XLEN - 1, 1), 0.U(1.W))
1294  }
1295
1296  def readWithScala(addr: Int): UInt = mapping(addr)._1
1297
1298  val difftestIntrNO = Mux(raiseIntr, causeNO, 0.U)
1299
1300  // Always instantiate basic difftest modules.
1301  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1302    val difftest = Module(new DifftestArchEvent)
1303    difftest.io.clock := clock
1304    difftest.io.coreid := csrio.hartId
1305    difftest.io.intrNO := RegNext(RegNext(RegNext(difftestIntrNO)))
1306    difftest.io.cause  := RegNext(RegNext(RegNext(Mux(csrio.exception.valid, causeNO, 0.U))))
1307    difftest.io.exceptionPC := RegNext(RegNext(RegNext(dexceptionPC)))
1308    if (env.EnableDifftest) {
1309      difftest.io.exceptionInst := RegNext(RegNext(RegNext(csrio.exception.bits.uop.cf.instr)))
1310    }
1311  }
1312
1313  // Always instantiate basic difftest modules.
1314  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1315    val difftest = Module(new DifftestCSRState)
1316    difftest.io.clock := clock
1317    difftest.io.coreid := csrio.hartId
1318    difftest.io.priviledgeMode := priviledgeMode
1319    difftest.io.mstatus := mstatus
1320    difftest.io.sstatus := mstatus & sstatusRmask
1321    difftest.io.mepc := mepc
1322    difftest.io.sepc := sepc
1323    difftest.io.mtval:= mtval
1324    difftest.io.stval:= stval
1325    difftest.io.mtvec := mtvec
1326    difftest.io.stvec := stvec
1327    difftest.io.mcause := mcause
1328    difftest.io.scause := scause
1329    difftest.io.satp := satp
1330    difftest.io.mip := mipReg
1331    difftest.io.mie := mie
1332    difftest.io.mscratch := mscratch
1333    difftest.io.sscratch := sscratch
1334    difftest.io.mideleg := mideleg
1335    difftest.io.medeleg := medeleg
1336  }
1337
1338  if(env.AlwaysBasicDiff || env.EnableDifftest) {
1339    val difftest = Module(new DifftestDebugMode)
1340    difftest.io.clock := clock
1341    difftest.io.coreid := csrio.hartId
1342    difftest.io.debugMode := debugMode
1343    difftest.io.dcsr := dcsr
1344    difftest.io.dpc := dpc
1345    difftest.io.dscratch0 := dscratch
1346    difftest.io.dscratch1 := dscratch1
1347  }
1348
1349  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1350    val difftest = Module(new DifftestVectorState)
1351    difftest.io.clock := clock
1352    difftest.io.coreid := csrio.hartId
1353    difftest.io.vstart := vstart
1354    difftest.io.vxsat := vcsr.asTypeOf(new VcsrStruct).vxsat
1355    difftest.io.vxrm := vcsr.asTypeOf(new VcsrStruct).vxrm
1356    difftest.io.vcsr := vcsr
1357    difftest.io.vl := vl
1358    difftest.io.vtype := vtype
1359    difftest.io.vlenb := vlenb
1360  }
1361}
1362
1363class PFEvent(implicit p: Parameters) extends XSModule with HasCSRConst  {
1364  val io = IO(new Bundle {
1365    val distribute_csr = Flipped(new DistributedCSRIO())
1366    val hpmevent = Output(Vec(29, UInt(XLEN.W)))
1367  })
1368
1369  val w = io.distribute_csr.w
1370
1371  val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++
1372                   List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++
1373                   List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++
1374                   List.fill(5)(RegInit("hc0300c0300".U(XLEN.W)))
1375
1376  val perfEventMapping = (0 until 29).map(i => {Map(
1377    MaskedRegMap(addr = Mhpmevent3 +i,
1378                 reg  = perfEvents(i),
1379                 wmask = "hf87fff3fcff3fcff".U(XLEN.W))
1380  )}).fold(Map())((a,b) => a ++ b)
1381
1382  val rdata = Wire(UInt(XLEN.W))
1383  MaskedRegMap.generate(perfEventMapping, w.bits.addr, rdata, w.valid, w.bits.data)
1384  for(i <- 0 until 29){
1385    io.hpmevent(i) := perfEvents(i)
1386  }
1387}
1388