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