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