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