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