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