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