xref: /XiangShan/src/main/scala/xiangshan/backend/fu/CSR.scala (revision 6c106319588f5988a282dc2e7c687a9d44e9c209)
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  // slvpredctl: load violation predict settings
520  // Default reset period: 2^16
521  // Why this number: reset more frequently while keeping the overhead low
522  // Overhead: extra two redirections in every 64K cycles => ~0.1% overhead
523  val slvpredctl = Reg(UInt(XLEN.W))
524  when(reset.asBool) {
525    slvpredctl := Constantin.createRecord("slvpredctl", 0x60)
526  }
527  csrio.customCtrl.lvpred_disable := slvpredctl(0)
528  csrio.customCtrl.no_spec_load := slvpredctl(1)
529  csrio.customCtrl.storeset_wait_store := slvpredctl(2)
530  csrio.customCtrl.storeset_no_fast_wakeup := slvpredctl(3)
531  csrio.customCtrl.lvpred_timeout := slvpredctl(8, 4)
532
533  //  smblockctl: memory block configurations
534  //  +------------------------+---+---+---+----+----+-----+--------+
535  //  |XLEN-1                10| 9 | 8 | 7 | 6  | 5  |  4  |3      0|
536  //  +------------------------+---+---+---+----+----+-----+--------+
537  //  |           Reserved     | L | S | O | CE | SP | LVC |   Th   |
538  //  +------------------------+---+---+---+----+----+-----+--------+
539  //  Description:
540  //  Bit 3-0   : Store buffer flush threshold (Th).
541  //  Bit 4     : Enable load violation check after reset (LVC).
542  //  Bit 5     : Enable soft-prefetch after reset (SP).
543  //  Bit 6     : Enable cache error after reset (CE).
544  //  Bit 7     : Enable uncache write outstanding (O).
545  //  Bit 8     : Enable unaligned store (S).
546  //  Bit 9     : Enable unaligned load (L).
547  //  Others    : Reserved.
548
549  val smblockctl_init_val =
550    (0xf & StoreBufferThreshold) |
551    (EnableLdVioCheckAfterReset.toInt << 4) |
552    (EnableSoftPrefetchAfterReset.toInt << 5) |
553    (EnableCacheErrorAfterReset.toInt << 6) |
554    (EnableUncacheWriteOutstanding.toInt << 7) |
555    (EnableHardwareStoreMisalign.toInt << 8) |
556    (EnableHardwareLoadMisalign.toInt << 9)
557  val smblockctl = RegInit(UInt(XLEN.W), smblockctl_init_val.U)
558  csrio.customCtrl.sbuffer_threshold := smblockctl(3, 0)
559  // bits 4: enable load load violation check
560  csrio.customCtrl.ldld_vio_check_enable := smblockctl(4)
561  csrio.customCtrl.soft_prefetch_enable := smblockctl(5)
562  csrio.customCtrl.cache_error_enable := smblockctl(6)
563  csrio.customCtrl.uncache_write_outstanding_enable := smblockctl(7)
564  csrio.customCtrl.hd_misalign_st_enable := smblockctl(8)
565  csrio.customCtrl.hd_misalign_ld_enable := smblockctl(9)
566
567  println("CSR smblockctl init value:")
568  println("  Store buffer replace threshold: " + StoreBufferThreshold)
569  println("  Enable ld-ld vio check after reset: " + EnableLdVioCheckAfterReset)
570  println("  Enable soft prefetch after reset: " + EnableSoftPrefetchAfterReset)
571  println("  Enable cache error after reset: " + EnableCacheErrorAfterReset)
572  println("  Enable uncache write outstanding: " + EnableUncacheWriteOutstanding)
573  println("  Enable unaligned store: " + EnableHardwareStoreMisalign)
574  println("  Enable unaligned load: " + EnableHardwareLoadMisalign)
575
576  val srnctl = RegInit(UInt(XLEN.W), "h7".U)
577  csrio.customCtrl.fusion_enable := srnctl(0)
578  csrio.customCtrl.wfi_enable := srnctl(2)
579
580  // Hypervisor CSRs
581  val hstatusWMask = "h7003c0".U(XLEN.W)
582  // hstatus: vtsr, vtw, vtvm, hu, spvp, spv, gva,
583  val hstatus = RegInit("h200000000".U(XLEN.W))
584  val hstatusStruct = hstatus.asTypeOf(new HstatusStruct)
585  val hedeleg = RegInit(UInt(XLEN.W), 0.U)
586  val hideleg = RegInit(UInt(XLEN.W), 0.U)
587  val hidelegRMask = mideleg
588  val hidelegWMask = ((1 << 10) | (1 << 6) | (1 << 2)).U(XLEN.W)
589  val hgeie   = RegInit(UInt(XLEN.W), 0.U)
590  val htval = RegInit(UInt(XLEN.W), 0.U)
591  // hvip hip hie is part of mip or mie
592  val hvipMask = ((1 << 10) | (1 << 6) | (1 << 2)).U(XLEN.W)
593  val hipRMask = (((1 << 12).U | hvipMask) & mideleg)
594  val hipWMask = ((1 << 2).U & mideleg)// vssip
595  val hieMask = hipRMask
596  val htinst = RegInit(UInt(XLEN.W), 0.U)
597  val hgeip = RegInit(UInt(XLEN.W), 0.U)
598  val henvcfg = RegInit(UInt(XLEN.W), 0.U)
599  val hgatp = RegInit(UInt(XLEN.W), 0.U)
600  val hgatpMask = Cat("h8".U(Hgatp_Mode_len.W), satp_part_wmask(Hgatp_Vmid_len, VmidLength), satp_part_wmask(Hgatp_Addr_len, PAddrBits-12))
601  // val htimedelta = RegInit(UInt(XLEN.W), 0.U)
602  val hcounteren = RegInit(UInt(XLEN.W), 0.U)
603  // Currently, XiangShan don't support Unprivileged Counter/Timers CSRs ("Zicntr" and "Zihpm")
604  val hcounterenMask = 0.U(XLEN.W)
605
606  val vsstatus = RegInit("h200002000".U(XLEN.W))
607  val vsstatusStruct = vsstatus.asTypeOf(new MstatusStruct)
608  //vsie vsip
609  val vsMask = ((1 << 10) | (1 << 6) | (1 << 2)).U(XLEN.W)
610  val vsip_ie_Mask = ZeroExt((hideleg & mideleg & vsMask), XLEN)
611  val vsip_WMask = ZeroExt((hideleg & mideleg & vssip_Mask), XLEN)
612  val vstvec = RegInit(UInt(XLEN.W), 0.U)
613  val vsscratch = RegInit(UInt(XLEN.W), 0.U)
614  val vsepc = RegInit(UInt(XLEN.W), 0.U)
615  val vscause = RegInit(UInt(XLEN.W), 0.U)
616  val vstval = RegInit(UInt(XLEN.W), 0.U)
617  val vsatp = RegInit(UInt(XLEN.W), 0.U)
618  val tlbBundle = Wire(new TlbCsrBundle)
619  tlbBundle.satp.apply(satp)
620  tlbBundle.vsatp.apply(vsatp)
621  tlbBundle.hgatp.apply(hgatp)
622  csrio.tlb := tlbBundle
623
624  // User-Level CSRs
625  val uepc = Reg(UInt(XLEN.W))
626
627  // fcsr
628  class FcsrStruct extends Bundle {
629    val reserved = UInt((XLEN-3-5).W)
630    val frm = UInt(3.W)
631    val fflags = UInt(5.W)
632    assert(this.getWidth == XLEN)
633  }
634  val fcsr = RegInit(0.U(XLEN.W))
635  // set mstatus->sd and mstatus->fs when true
636  val csrw_dirty_fp_state = WireInit(false.B)
637
638  def frm_wfn(wdata: UInt): UInt = {
639    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
640    csrw_dirty_fp_state := true.B
641    fcsrOld.frm := wdata(2,0)
642    fcsrOld.asUInt
643  }
644  def frm_rfn(rdata: UInt): UInt = rdata(7,5)
645
646  def fflags_wfn(update: Boolean)(wdata: UInt): UInt = {
647    val fcsrOld = fcsr.asTypeOf(new FcsrStruct)
648    val fcsrNew = WireInit(fcsrOld)
649    if (update) {
650      fcsrNew.fflags := wdata(4,0) | fcsrOld.fflags
651    } else {
652      fcsrNew.fflags := wdata(4,0)
653    }
654    fcsrNew.asUInt
655  }
656  def fflags_rfn(rdata:UInt): UInt = rdata(4,0)
657
658  def fcsr_wfn(wdata: UInt): UInt = {
659    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
660    csrw_dirty_fp_state := true.B
661    Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags)
662  }
663
664  val fcsrMapping = Map(
665    MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn(update = false), rfn = fflags_rfn),
666    MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn),
667    MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn)
668  )
669
670  // Vector extension CSRs
671  val vstart = RegInit(0.U(XLEN.W))
672  val vcsr = RegInit(0.U(XLEN.W))
673  val vl = Reg(UInt(XLEN.W))
674  val vtype = Reg(UInt(XLEN.W))
675  val vlenb = RegInit(VDataBytes.U(XLEN.W))
676
677  // set mstatus->sd and mstatus->vs when true
678  val csrw_dirty_vs_state = WireInit(false.B)
679
680  // vcsr is mapped to vxrm and vxsat
681  class VcsrStruct extends Bundle {
682    val reserved = UInt((XLEN-3).W)
683    val vxrm = UInt(2.W)
684    val vxsat = UInt(1.W)
685    assert(this.getWidth == XLEN)
686  }
687
688  def vxrm_wfn(wdata: UInt): UInt = {
689    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
690    csrw_dirty_vs_state := true.B
691    vcsrOld.vxrm := wdata(1,0)
692    vcsrOld.asUInt
693  }
694  def vxrm_rfn(rdata: UInt): UInt = rdata(2,1)
695
696  def vxsat_wfn(update: Boolean)(wdata: UInt): UInt = {
697    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
698    val vcsrNew = WireInit(vcsrOld)
699    csrw_dirty_vs_state := true.B
700    if (update) {
701      vcsrNew.vxsat := wdata(0) | vcsrOld.vxsat
702    } else {
703      vcsrNew.vxsat := wdata(0)
704    }
705    vcsrNew.asUInt
706  }
707  def vxsat_rfn(rdata: UInt): UInt = rdata(0)
708
709  def vcsr_wfn(wdata: UInt): UInt = {
710    val vcsrOld = WireInit(vcsr.asTypeOf(new VcsrStruct))
711    csrw_dirty_vs_state := true.B
712    vcsrOld.vxrm := wdata.asTypeOf(vcsrOld).vxrm
713    vcsrOld.vxsat := wdata.asTypeOf(vcsrOld).vxsat
714    vcsrOld.asUInt
715  }
716
717  val vcsrMapping = Map(
718    MaskedRegMap(Vstart, vstart),
719    MaskedRegMap(Vxrm, vcsr, wfn = vxrm_wfn, rfn = vxrm_rfn),
720    MaskedRegMap(Vxsat, vcsr, wfn = vxsat_wfn(false), rfn = vxsat_rfn),
721    MaskedRegMap(Vcsr, vcsr, wfn = vcsr_wfn),
722    MaskedRegMap(Vl, vl),
723    MaskedRegMap(Vtype, vtype),
724    MaskedRegMap(Vlenb, vlenb),
725  )
726
727  // Hart Privilege Mode
728  val privilegeMode = RegInit(UInt(2.W), ModeM)
729
730  //val perfEventscounten = List.fill(nrPerfCnts)(RegInit(false(Bool())))
731  // Perf Counter
732  val nrPerfCnts = 29  // 3...31
733  val privilegeModeOH = UIntToOH(privilegeMode)
734  val perfEventscounten = RegInit(0.U.asTypeOf(Vec(nrPerfCnts, Bool())))
735  val perfCnts   = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W)))
736  val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++
737                   List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++
738                   List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++
739                   List.fill(5)(RegInit("hc0300c0300".U(XLEN.W)))
740  for (i <-0 until nrPerfCnts) {
741    perfEventscounten(i) := (perfEvents(i)(63,60) & privilegeModeOH).orR
742  }
743
744  val hpmEvents = Wire(Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent))
745  for (i <- 0 until numPCntHc * coreParams.L2NBanks) {
746    hpmEvents(i) := csrio.perf.perfEventsHc(i)
747  }
748
749  // print perfEvents
750  val allPerfEvents = hpmEvents.map(x => (s"Hc", x.value))
751  if (printEventCoding) {
752    for (((name, inc), i) <- allPerfEvents.zipWithIndex) {
753      println("CSR perfEvents Set", name, inc, i)
754    }
755  }
756
757  val csrevents = perfEvents.slice(24, 29)
758  val hpm_hc = HPerfMonitor(csrevents, hpmEvents)
759  val mcountinhibit = RegInit(0.U(XLEN.W))
760  val mcycle = RegInit(0.U(XLEN.W))
761  mcycle := mcycle + 1.U
762  val minstret = RegInit(0.U(XLEN.W))
763  val perf_events = csrio.perf.perfEventsFrontend ++
764                    csrio.perf.perfEventsBackend ++
765                    csrio.perf.perfEventsLsu ++
766                    hpm_hc.getPerf
767  minstret := minstret + RegNext(csrio.perf.retiredInstr)
768  for(i <- 0 until 29){
769    perfCnts(i) := Mux(mcountinhibit(i+3) | !perfEventscounten(i), perfCnts(i), perfCnts(i) + perf_events(i).value)
770  }
771
772  // CSR reg map
773  val basicPrivMapping = Map(
774
775    // Unprivileged Floating-Point CSRs
776    // Has been mapped above
777
778    // TODO: support Unprivileged Counter/Timers CSRs ("Zicntr" and "Zihpm")
779    // Unprivileged Counter/Timers
780    MaskedRegMap(Cycle, mcycle),
781    // We don't support read time CSR.
782    // MaskedRegMap(Time, mtime),
783    MaskedRegMap(Instret, minstret),
784
785    //--- Supervisor Trap Setup ---
786    MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask),
787    // MaskedRegMap(Sedeleg, Sedeleg),
788    // MaskedRegMap(Sideleg, Sideleg),
789    MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask),
790    MaskedRegMap(Stvec, stvec, stvecMask, MaskedRegMap.NoSideEffect, stvecMask),
791    MaskedRegMap(Scounteren, scounteren, scounterenMask),
792
793    //--- Supervisor Configuration ---
794    MaskedRegMap(Senvcfg, senvcfg),
795
796    //--- Supervisor Trap Handling ---
797    MaskedRegMap(Sscratch, sscratch),
798    MaskedRegMap(Sepc, sepc, sepcMask, MaskedRegMap.NoSideEffect, sepcMask),
799    MaskedRegMap(Scause, scause),
800    MaskedRegMap(Stval, stval),
801    MaskedRegMap(Sip, mipReg.asUInt, sipWMask, MaskedRegMap.NoSideEffect, sipMask, x => (mipWire.asUInt | x) & sipMask),
802
803    //--- Supervisor Protection and Translation ---
804    MaskedRegMap(Satp, satp, satpMask, MaskedRegMap.NoSideEffect, satpMask),
805
806    //--- Supervisor Custom Read/Write Registers
807    MaskedRegMap(Sbpctl, sbpctl),
808    MaskedRegMap(Spfctl, spfctl),
809    MaskedRegMap(Slvpredctl, slvpredctl),
810    MaskedRegMap(Smblockctl, smblockctl),
811    MaskedRegMap(Srnctl, srnctl),
812
813    //--- Machine Information Registers ---
814    MaskedRegMap(Mvendorid, mvendorid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
815    MaskedRegMap(Marchid, marchid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
816    MaskedRegMap(Mimpid, mimpid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
817    MaskedRegMap(Mhartid, mhartid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
818    MaskedRegMap(Mconfigptr, mconfigptr, 0.U(XLEN.W), MaskedRegMap.Unwritable),
819
820    //--- Machine Configuration Registers ---
821    MaskedRegMap(Menvcfg, menvcfg),
822
823    //--- Machine Trap Setup ---
824    MaskedRegMap(Mstatus, mstatus, mstatusWMask, mstatusUpdateSideEffect),
825    MaskedRegMap(Misa, misa, 0.U, MaskedRegMap.Unwritable), // now whole misa is unchangeable
826    MaskedRegMap(Medeleg, medeleg, medelegWMask),
827    MaskedRegMap(Mideleg, mideleg, midelegWMask),
828    MaskedRegMap(Mie, mie, mieWMask),
829    MaskedRegMap(Mtvec, mtvec, mtvecMask, MaskedRegMap.NoSideEffect, mtvecMask),
830    MaskedRegMap(Mcounteren, mcounteren, mcounterenMask),
831
832    //--- Machine Trap Handling ---
833    MaskedRegMap(Mscratch, mscratch),
834    MaskedRegMap(Mepc, mepc, mepcMask, MaskedRegMap.NoSideEffect, mepcMask),
835    MaskedRegMap(Mcause, mcause),
836    MaskedRegMap(Mtval, mtval),
837    MaskedRegMap(Mip, mipReg.asUInt, mipWMask, MaskedRegMap.NoSideEffect, mipMask, x => (mipWire.asUInt | x) & mipMask),
838
839    //--- Trigger ---
840    MaskedRegMap(Tselect, tselectPhy, WritableMask, WriteTselect),
841    // Todo: support chain length = 2
842    MaskedRegMap(Tdata1, tdata1RegVec(tselectPhy),
843      WritableMask,
844      x => Tdata1Bundle.Write(x, tdata1RegVec(tselectPhy), newTriggerChainIsLegal, debug_mode = debugMode),
845      WritableMask,
846      x => Tdata1Bundle.Read(x)),
847    MaskedRegMap(Tdata2, tdata2RegVec(tselectPhy)),
848    MaskedRegMap(Tinfo, tinfo, 0.U(XLEN.W), MaskedRegMap.Unwritable),
849
850    //--- Debug Mode ---
851    MaskedRegMap(Dcsr, dcsr, dcsrMask, dcsrUpdateSideEffect),
852    MaskedRegMap(Dpc, dpc),
853    MaskedRegMap(Dscratch0, dscratch0),
854    MaskedRegMap(Dscratch1, dscratch1),
855    MaskedRegMap(Mcountinhibit, mcountinhibit),
856    MaskedRegMap(Mcycle, mcycle),
857    MaskedRegMap(Minstret, minstret),
858  )
859
860  // hypervisor csr map
861  val hcsrMapping = Map(
862    //--- Hypervisor Trap Setup ---
863    MaskedRegMap(Hstatus, hstatus, hstatusWMask),
864    MaskedRegMap(Hedeleg, hedeleg),
865    MaskedRegMap(Hideleg, hideleg, hidelegWMask, MaskedRegMap.NoSideEffect, hidelegRMask),
866    MaskedRegMap(Hie, mie, hieMask, MaskedRegMap.NoSideEffect, hieMask),
867    MaskedRegMap(Hcounteren, hcounteren, hcounterenMask),
868    MaskedRegMap(Hgeie, hgeie),
869
870    //--- Hypervisor Trap Handling ---
871    MaskedRegMap(Htval, htval),
872    MaskedRegMap(Hip, mipReg.asUInt, hipWMask, MaskedRegMap.NoSideEffect, hipRMask, x => (mipWire.asUInt | x) & hipRMask),
873    MaskedRegMap(Hvip, mipReg.asUInt, hvipMask, MaskedRegMap.NoSideEffect, hvipMask, x => (mipWire.asUInt | x) & hvipMask),
874    MaskedRegMap(Htinst, htinst),
875    MaskedRegMap(Hgeip, hgeip),
876
877    //--- Hypervisor Configuration ---
878    MaskedRegMap(Henvcfg, henvcfg),
879
880    //--- Hypervisor Protection and Translation ---
881    MaskedRegMap(Hgatp, hgatp, hgatpMask, MaskedRegMap.NoSideEffect, hgatpMask),
882
883    //--- Hypervisor Counter/Timer Virtualization Registers ---
884    // MaskedRegMap(Htimedelta, htimedelta),
885
886    //--- Virtual Supervisor Registers ---
887    MaskedRegMap(Vsstatus, vsstatus, rmask = sstatusRmask, wmask = sstatusWmask, wfn = vsstatusUpdateSideEffect),
888    MaskedRegMap(Vsie, mie, rmask = vsip_ie_Mask, wmask = vsip_ie_Mask),
889    MaskedRegMap(Vstvec, vstvec),
890    MaskedRegMap(Vsscratch, vsscratch),
891    MaskedRegMap(Vsepc, vsepc),
892    MaskedRegMap(Vscause, vscause),
893    MaskedRegMap(Vstval, vstval),
894    MaskedRegMap(Vsip, mipReg.asUInt, vsip_WMask, MaskedRegMap.NoSideEffect, vsip_ie_Mask, x => mipWire.asUInt | x),
895    MaskedRegMap(Vsatp, vsatp, satpMask, MaskedRegMap.NoSideEffect, satpMask),
896
897    //--- Machine Registers ---
898    MaskedRegMap(Mtval2, mtval2),
899    MaskedRegMap(Mtinst, mtinst),
900  )
901
902  val perfCntMapping = (0 until 29).map(i => {Map(
903    MaskedRegMap(addr = Mhpmevent3 +i,
904                 reg  = perfEvents(i),
905                 wmask = "hf87fff3fcff3fcff".U(XLEN.W)),
906    MaskedRegMap(addr = Mhpmcounter3 +i,
907                 reg = perfCnts(i)),
908    MaskedRegMap(addr = Hpmcounter3 + i,
909                 reg  = perfCnts(i))
910  )}).fold(Map())((a,b) => a ++ b)
911  // TODO: mechanism should be implemented later
912  // val MhpmcounterStart = Mhpmcounter3
913  // val MhpmeventStart   = Mhpmevent3
914  // for (i <- 0 until nrPerfCnts) {
915  //   perfCntMapping += MaskedRegMap(MhpmcounterStart + i, perfCnts(i))
916  //   perfCntMapping += MaskedRegMap(MhpmeventStart + i, perfEvents(i))
917  // }
918
919  val cacheopRegs = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
920    name -> RegInit(0.U(attribute("width").toInt.W))
921  }}
922  val cacheopMapping = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
923    MaskedRegMap(
924      Scachebase + attribute("offset").toInt,
925      cacheopRegs(name)
926    )
927  }}
928
929  val mapping = basicPrivMapping ++
930                perfCntMapping ++
931                pmpMapping ++
932                pmaMapping ++
933                (if (HasFPU) fcsrMapping else Nil) ++
934                (if (HasVPU) vcsrMapping else Nil) ++
935                (if (HasCustomCSRCacheOp) cacheopMapping else Nil) ++
936                (if (HasHExtension) hcsrMapping else Nil)
937
938
939  println("XiangShan CSR Lists")
940
941  for (addr <- mapping.keys.toSeq.sorted) {
942    println(f"$addr%#03x ${mapping(addr)._1}")
943  }
944
945  val vs_s_csr_map = List(
946    Sstatus.U  -> Vsstatus.U,
947    Sie.U      -> Vsie.U,
948    Stvec.U    -> Vstvec.U,
949    Sscratch.U -> Vsscratch.U,
950    Sepc.U     -> Vsepc.U,
951    Scause.U   -> Vscause.U,
952    Stval.U    -> Vstval.U,
953    Sip.U      -> Vsip.U,
954    Satp.U     -> Vsatp.U
955  )
956  val addr = Wire(UInt(12.W))
957  val vscsr_addr = LookupTreeDefault(src2(11, 0), src2(11, 0), vs_s_csr_map)
958  when(virtMode){
959    addr := vscsr_addr
960  }.otherwise{
961    addr := src2(11, 0)
962  }
963  val csri = ZeroExt(src2(16, 12), XLEN)
964  val rdata = Wire(UInt(XLEN.W))
965  val rdata_tmp = Wire(UInt(XLEN.W))
966  val wdata_tmp = LookupTree(func, List(
967    CSROpType.wrt  -> src1,
968    CSROpType.set  -> (rdata | src1),
969    CSROpType.clr  -> (rdata & (~src1).asUInt),
970    CSROpType.wrti -> csri,
971    CSROpType.seti -> (rdata | csri),
972    CSROpType.clri -> (rdata & (~csri).asUInt)
973  ))
974  val is_vsip_ie = addr === Vsip.U || addr === Vsie.U
975  // for the difftest with NEMU(stay consistent with Spike)
976  val is_satp  = addr === Satp.U
977  val is_vsatp = addr === Vsatp.U
978  val is_hgatp = addr === Hgatp.U
979  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
980  val wdata = MuxCase(wdata_tmp, Seq(
981    is_vsip_ie -> ZeroExt(wdata_tmp << 1, XLEN),
982    (is_satp && !check_apt_mode) -> satp,
983    (is_vsatp && !check_apt_mode) -> vsatp,
984    (is_hgatp && !check_apt_mode) -> hgatp
985  ))
986  val addrInPerfCnt = (addr >= Mcycle.U) && (addr <= Mhpmcounter31.U) ||
987    (addr >= Mcountinhibit.U) && (addr <= Mhpmevent31.U) ||
988    (addr >= Cycle.U) && (addr <= Hpmcounter31.U) ||
989    addr === Mip.U
990  csrio.isPerfCnt := addrInPerfCnt && valid && func =/= CSROpType.jmp
991
992  // satp wen check
993  val satpLegalMode = (wdata.asTypeOf(new SatpStruct).mode===0.U) || (wdata.asTypeOf(new SatpStruct).mode===8.U)
994
995  // csr access check, special case
996  val tvmNotPermit = (privilegeMode === ModeS && !virtMode && mstatusStruct.tvm.asBool)
997  val accessPermitted = !(addr === Satp.U && tvmNotPermit)
998  val vtvmNotPermit = (privilegeMode === ModeS && virtMode && hstatusStruct.vtvm.asBool)
999  val vaccessPermitted = !(addr === Vsatp.U && vtvmNotPermit)
1000//  csrio.disableSfence := (tvmNotPermit || !virtMode && privilegeMode < ModeS) || (vtvmNotPermit || virtMode && privilegeMode < ModeS)
1001//  csrio.disableHfenceg := !((!virtMode && privilegeMode === ModeS && !mstatusStruct.tvm.asBool) || (privilegeMode === ModeM)) // only valid in HS and mstatus.tvm == 0 or in M
1002//  csrio.disableHfencev :=  !(privilegeMode === ModeM || (!virtMode && privilegeMode === ModeS))
1003
1004  // general CSR wen check
1005  val wen = valid && CSROpType.isCsrAccess(func) && ((addr=/=Satp.U && addr =/= Vsatp.U) || satpLegalMode)
1006  val dcsrPermitted = dcsrPermissionCheck(addr, false.B, debugMode)
1007  val triggerPermitted = triggerPermissionCheck(addr, true.B, debugMode) // todo dmode
1008  val HasH = (HasHExtension == true).asBool
1009  val csrAccess = csrAccessPermissionCheck(addr, false.B, privilegeMode, virtMode, HasH)
1010  val modePermitted = csrAccess === 0.U && dcsrPermitted && triggerPermitted
1011  val perfcntPermitted = perfcntPermissionCheck(addr, privilegeMode, mcounteren, scounteren)
1012  val permitted = Mux(addrInPerfCnt, perfcntPermitted, modePermitted) && Mux(virtMode, vaccessPermitted, accessPermitted)
1013  MaskedRegMap.generate(mapping, addr, rdata_tmp, wen && permitted, wdata)
1014  rdata := Mux(is_vsip_ie, ZeroExt(rdata_tmp >> 1, XLEN), rdata_tmp)
1015  io.out.bits.res.data := rdata
1016  io.out.bits.ctrl.flushPipe.get := flushPipe
1017  connect0LatencyCtrlSingal
1018
1019  // send distribute csr a w signal
1020  csrio.customCtrl.distribute_csr.w.valid := wen && permitted
1021  csrio.customCtrl.distribute_csr.w.bits.data := wdata
1022  csrio.customCtrl.distribute_csr.w.bits.addr := addr
1023
1024  when (RegNext(csrio.fpu.fflags.valid)) {
1025    fcsr := fflags_wfn(update = true)(RegEnable(csrio.fpu.fflags.bits, csrio.fpu.fflags.valid))
1026  }
1027  when(RegNext(csrio.vpu.set_vxsat.valid)) {
1028    vcsr := vxsat_wfn(update = true)(RegEnable(csrio.vpu.set_vxsat.bits, csrio.vpu.set_vxsat.valid))
1029  }
1030
1031  // set fs and sd in mstatus
1032  when (csrw_dirty_fp_state || RegNext(csrio.fpu.dirty_fs)) {
1033    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1034    mstatusNew.fs := "b11".U
1035    mstatusNew.sd := true.B
1036    mstatus := mstatusNew.asUInt
1037    when(virtMode){
1038      val vsstatusNew = WireInit(vsstatus.asTypeOf(new MstatusStruct))
1039      vsstatusNew.fs := "b11".U
1040      vsstatusNew.sd := true.B
1041      vsstatus := vsstatusNew.asUInt
1042    }
1043  }
1044  csrio.fpu.frm := fcsr.asTypeOf(new FcsrStruct).frm
1045
1046  when (RegNext(csrio.vpu.set_vstart.valid)) {
1047    vstart := RegEnable(csrio.vpu.set_vstart.bits, csrio.vpu.set_vstart.valid)
1048  }
1049  when (RegNext(csrio.vpu.set_vtype.valid)) {
1050    vtype := RegEnable(csrio.vpu.set_vtype.bits, csrio.vpu.set_vtype.valid)
1051  }
1052  vl := csrio.vpu.vl
1053  // set vs and sd in mstatus
1054  when(csrw_dirty_vs_state || RegNext(csrio.vpu.dirty_vs)) {
1055    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1056    mstatusNew.vs := ContextStatus.dirty
1057    mstatusNew.sd := true.B
1058    mstatus := mstatusNew.asUInt
1059  }
1060
1061  csrio.vpu.vstart := vstart
1062  csrio.vpu.vxrm := vcsr.asTypeOf(new VcsrStruct).vxrm
1063
1064  // Trigger Ctrl
1065  val triggerEnableVec = tdata1RegVec.map { tdata1 =>
1066    val mcontrolData = tdata1.asTypeOf(new Tdata1Bundle).data.asTypeOf(new MControlData)
1067    tdata1.asTypeOf(new Tdata1Bundle).type_.asUInt === TrigTypeEnum.MCONTROL && (
1068      mcontrolData.m && privilegeMode === ModeM ||
1069        mcontrolData.s && privilegeMode === ModeS ||
1070        mcontrolData.u && privilegeMode === ModeU)
1071  }
1072  val fetchTriggerEnableVec = triggerEnableVec.zip(tdata1WireVec).map {
1073    case (tEnable, tdata1) => tEnable && tdata1.asTypeOf(new Tdata1Bundle).data.asTypeOf(new MControlData).isFetchTrigger
1074  }
1075  val memAccTriggerEnableVec = triggerEnableVec.zip(tdata1WireVec).map {
1076    case (tEnable, tdata1) => tEnable && tdata1.asTypeOf(new Tdata1Bundle).data.asTypeOf(new MControlData).isMemAccTrigger
1077  }
1078  csrio.customCtrl.frontend_trigger.tEnableVec := fetchTriggerEnableVec
1079  csrio.customCtrl.mem_trigger.tEnableVec := memAccTriggerEnableVec
1080
1081  val tdata1Update = wen && (addr === Tdata1.U)
1082  val tdata2Update = wen && (addr === Tdata2.U)
1083  val triggerUpdate = wen && (addr === Tdata1.U || addr === Tdata2.U)
1084  val frontendTriggerUpdate =
1085    tdata1Update && wdata.asTypeOf(new Tdata1Bundle).type_.asUInt === TrigTypeEnum.MCONTROL &&
1086      wdata.asTypeOf(new Tdata1Bundle).data.asTypeOf(new MControlData).isFetchTrigger ||
1087      tdata1Selected.data.asTypeOf(new MControlData).isFetchTrigger && triggerUpdate
1088  val memTriggerUpdate =
1089    tdata1Update && wdata.asTypeOf(new Tdata1Bundle).type_.asUInt === TrigTypeEnum.MCONTROL &&
1090      wdata.asTypeOf(new Tdata1Bundle).data.asTypeOf(new MControlData).isMemAccTrigger ||
1091      tdata1Selected.data.asTypeOf(new MControlData).isMemAccTrigger && triggerUpdate
1092
1093  csrio.customCtrl.frontend_trigger.tUpdate.valid := RegNext(RegNext(frontendTriggerUpdate))
1094  csrio.customCtrl.mem_trigger.tUpdate.valid := RegNext(RegNext(memTriggerUpdate))
1095  XSDebug(triggerEnableVec.reduce(_ || _), p"Debug Mode: At least 1 trigger is enabled," +
1096    p"trigger enable is ${Binary(triggerEnableVec.asUInt)}\n")
1097
1098  // CSR inst decode
1099  val isEbreak = addr === privEbreak && func === CSROpType.jmp
1100  val isEcall  = addr === privEcall  && func === CSROpType.jmp
1101  val isMret   = addr === privMret   && func === CSROpType.jmp
1102  val isSret   = addr === privSret   && func === CSROpType.jmp
1103  val isUret   = addr === privUret   && func === CSROpType.jmp
1104  val isDret   = addr === privDret   && func === CSROpType.jmp
1105  val isWFI    = func === CSROpType.wfi
1106
1107  // Illegal privileged operation list
1108  val illegalMret = valid && isMret && privilegeMode < ModeM
1109  val illegalSret = valid && isSret && privilegeMode < ModeS
1110  val illegalSModeSret = valid && isSret && privilegeMode === ModeS && virtMode === false.B && mstatusStruct.tsr.asBool
1111  // when hstatus.vtsr == 1, if sret is executed in VS-mode, it will cause virtual instruction
1112  val illegalVSModeSret = valid && isSret && privilegeMode === ModeS && virtMode && hstatusStruct.vtsr.asBool
1113  // When TW=1, then if WFI is executed in any less-privileged mode,
1114  // and it does not complete within an implementation-specific, bounded time limit,
1115  // the WFI instruction causes an illegal instruction exception.
1116  // The time limit may always be 0, in which case WFI always causes
1117  // an illegal instruction exception in less-privileged modes when TW=1.
1118  val illegalWFI = valid && isWFI && (privilegeMode < ModeM && mstatusStruct.tw === 1.U ||  privilegeMode === ModeU && !virtMode)
1119  val illegalVWFI = valid && isWFI && ((virtMode && privilegeMode === ModeS && hstatusStruct.vtw === 1.U && mstatusStruct.tw === 0.U)||
1120      (virtMode && privilegeMode === ModeU && mstatusStruct.tw === 0.U))
1121  // Illegal privileged instruction check
1122  val isIllegalAddr = valid && CSROpType.isCsrAccess(func) && MaskedRegMap.isIllegalAddr(mapping, addr)
1123  val isIllegalAccess = !virtMode && wen && !(Mux(addrInPerfCnt, perfcntPermitted, csrAccess === 0.U && dcsrPermitted && triggerPermitted) && accessPermitted)
1124  val isIllegalPrivOp = illegalMret || illegalSret || illegalSModeSret || illegalWFI
1125
1126  val isIllegalVAccess = virtMode && wen && (csrAccess === 2.U || !vaccessPermitted)
1127  val isIllegalVPrivOp = illegalVSModeSret || illegalVWFI
1128  // expose several csr bits for tlb
1129  tlbBundle.priv.mxr   := mstatusStruct.mxr.asBool
1130  tlbBundle.priv.sum   := mstatusStruct.sum.asBool
1131  tlbBundle.priv.vmxr := vsstatusStruct.mxr.asBool
1132  tlbBundle.priv.vsum := vsstatusStruct.sum.asBool
1133  tlbBundle.priv.spvp := hstatusStruct.spvp
1134  tlbBundle.priv.virt  := Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpv & (mstatusStruct.mpp =/= ModeM), virtMode)
1135  tlbBundle.priv.imode := privilegeMode
1136  tlbBundle.priv.dmode := Mux((debugMode && dcsr.asTypeOf(new DcsrStruct).mprven || !debugMode) && mstatusStruct.mprv.asBool, mstatusStruct.mpp, privilegeMode)
1137
1138  // Branch control
1139  val retTarget = WireInit(0.U)
1140  val resetSatp = (addr === Satp.U || addr === Hgatp.U || addr === Vsatp.U) && wen // write to satp will cause the pipeline be flushed
1141  val writeVstart = addr === Vstart.U && wen // write to vstart will cause the pipeline be flushed
1142  dontTouch(writeVstart)
1143
1144  val w_fcsr_change_rm = wen && addr === Fcsr.U && wdata(7, 5) =/= fcsr(7, 5)
1145  val w_frm_change_rm = wen && addr === Frm.U && wdata(2, 0) =/= fcsr(7, 5)
1146  val frm_change = w_fcsr_change_rm || w_frm_change_rm
1147  val isXRet = valid && func === CSROpType.jmp && !isEcall && !isEbreak
1148  flushPipe := resetSatp || frm_change || isXRet || frontendTriggerUpdate || writeVstart
1149
1150  private val illegalRetTarget = WireInit(false.B)
1151  when(valid) {
1152    when(isDret) {
1153      retTarget := dpc(VAddrBits - 1, 0)
1154    }.elsewhen(isMret && !illegalMret) {
1155      retTarget := mepc(VAddrBits - 1, 0)
1156    }.elsewhen(isSret && !illegalSret && !illegalSModeSret && !illegalVSModeSret) {
1157      retTarget := Mux(virtMode, vsepc(VAddrBits - 1, 0), sepc(VAddrBits - 1, 0))
1158    }.elsewhen(isUret) {
1159      retTarget := uepc(VAddrBits - 1, 0)
1160    }.otherwise {
1161      illegalRetTarget := true.B
1162    }
1163  }.otherwise {
1164    illegalRetTarget := true.B // when illegalRetTarget setted, retTarget should never be used
1165  }
1166
1167  // Mux tree for regs
1168  when(valid) {
1169    when(isDret) {
1170      val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1171      val debugModeNew = WireInit(debugMode)
1172      when(dcsr.asTypeOf(new DcsrStruct).prv =/= ModeM) {
1173        mstatusNew.mprv := 0.U
1174      } //If the new privilege mode is less privileged than M-mode, MPRV in mstatus is cleared.
1175      mstatus := mstatusNew.asUInt
1176      privilegeMode := dcsr.asTypeOf(new DcsrStruct).prv
1177      debugModeNew := false.B
1178      debugIntrEnable := true.B
1179      debugMode := debugModeNew
1180      XSDebug("Debug Mode: Dret executed, returning to %x.", retTarget)
1181    }.elsewhen(isMret && !illegalMret) {
1182      val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1183      val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1184      mstatusNew.ie.m := mstatusOld.pie.m
1185      privilegeMode := mstatusOld.mpp
1186      if (HasHExtension) {
1187        virtMode := mstatusOld.mpv
1188        mstatusNew.mpv := 0.U
1189      }
1190      mstatusNew.pie.m := true.B
1191      mstatusNew.mpp := ModeU
1192      when(mstatusOld.mpp =/= ModeM) {
1193        mstatusNew.mprv := 0.U
1194      }
1195      mstatus := mstatusNew.asUInt
1196    }.elsewhen(isSret && !illegalSret && !illegalSModeSret && !illegalVSModeSret) {
1197      val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1198      val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1199      val hstatusOld = WireInit(hstatus.asTypeOf(new HstatusStruct))
1200      val hstatusNew = WireInit(hstatus.asTypeOf(new HstatusStruct))
1201      val vsstatusOld = WireInit(vsstatus.asTypeOf(new MstatusStruct))
1202      val vsstatusNew = WireInit(vsstatus.asTypeOf(new MstatusStruct))
1203      when(virtMode === 0.U) {
1204        virtMode := hstatusOld.spv
1205        hstatusNew.spv := 0.U
1206        mstatusNew.ie.s := mstatusOld.pie.s
1207        privilegeMode := Cat(0.U(1.W), mstatusOld.spp)
1208        mstatusNew.pie.s := true.B
1209        mstatusNew.spp := ModeU
1210        when(mstatusOld.spp =/= ModeM) {
1211          mstatusNew.mprv := 0.U
1212        }
1213        mstatus := mstatusNew.asUInt
1214        hstatus := hstatusNew.asUInt
1215      }.otherwise {
1216        privilegeMode := vsstatusOld.spp
1217        vsstatusNew.spp := ModeU
1218        vsstatusNew.ie.s := vsstatusOld.pie.s
1219        vsstatusNew.pie.s := 1.U
1220        vsstatus := vsstatusNew.asUInt
1221      }
1222    }.elsewhen(isUret) {
1223      val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1224      val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1225      // mstatusNew.mpp.m := ModeU //TODO: add mode U
1226      mstatusNew.ie.u := mstatusOld.pie.u
1227      privilegeMode := ModeU
1228      mstatusNew.pie.u := true.B
1229      mstatus := mstatusNew.asUInt
1230    }
1231  }
1232
1233  io.in.ready := true.B
1234  io.out.valid := valid
1235
1236  // In this situation, hart will enter debug mode instead of handling a breakpoint exception simply.
1237  // Ebreak block instructions backwards, so it's ok to not keep extra info to distinguish between breakpoint
1238  // exception and enter-debug-mode exception.
1239  val ebreakEnterDebugMode =
1240    (privilegeMode === ModeM && dcsrData.ebreakm) ||
1241    (privilegeMode === ModeS && dcsrData.ebreaks) ||
1242    (privilegeMode === ModeU && dcsrData.ebreaku)
1243
1244  // raise a debug exception waiting to enter debug mode, instead of a breakpoint exception
1245  val raiseDebugException = !debugMode && isEbreak && ebreakEnterDebugMode
1246
1247  val csrExceptionVec = WireInit(0.U.asTypeOf(ExceptionVec()))
1248  csrExceptionVec(breakPoint) := io.in.valid && isEbreak
1249  csrExceptionVec(ecallM) := privilegeMode === ModeM && io.in.valid && isEcall
1250  csrExceptionVec(ecallVS) := privilegeMode === ModeS && virtMode && io.in.valid && isEcall
1251  csrExceptionVec(ecallS) := privilegeMode === ModeS && !virtMode && io.in.valid && isEcall
1252  csrExceptionVec(ecallU) := privilegeMode === ModeU && io.in.valid && isEcall
1253  // Trigger an illegal instr exception when:
1254  // * unimplemented csr is being read/written
1255  // * csr access is illegal
1256  csrExceptionVec(illegalInstr) := isIllegalAddr || isIllegalAccess || isIllegalPrivOp
1257  csrExceptionVec(virtualInstr) := isIllegalVAccess || isIllegalVPrivOp
1258  io.out.bits.ctrl.exceptionVec.get := csrExceptionVec
1259
1260  XSDebug(io.in.valid, s"Debug Mode: an Ebreak is executed, ebreak cause enter-debug-mode exception ? ${raiseDebugException}\n")
1261
1262  /**
1263    * Exception and Intr
1264    */
1265  val idelegS =  (mideleg & mip.asUInt)
1266  val idelegVS = (hideleg & mideleg & mip.asUInt)
1267  def privilegedEnableDetect(idelegS: Bool, idelegVS: Bool): Bool = Mux(idelegS,
1268    Mux(idelegVS, (virtMode && privilegeMode === ModeS && vsstatusStruct.ie.s) || (virtMode && privilegeMode < ModeS),
1269      ((privilegeMode === ModeS) && mstatusStruct.ie.s) || (privilegeMode < ModeS) || virtMode),
1270    ((privilegeMode === ModeM) && mstatusStruct.ie.m) || (privilegeMode < ModeM))
1271
1272  val debugIntr = csrio.externalInterrupt.debug & debugIntrEnable
1273  XSDebug(debugIntr, "Debug Mode: debug interrupt is asserted and valid!")
1274  // send interrupt information to ROB
1275  val intrVecEnable = Wire(Vec(13, Bool()))
1276  val disableInterrupt = debugMode || (dcsrData.step && !dcsrData.stepie)
1277  intrVecEnable.zip(idelegS.asBools).zip(idelegVS.asBools).map{case((x,y),z) => x := privilegedEnableDetect(y, z) && !disableInterrupt}
1278  val intrVec = Cat(debugIntr && !debugMode, (mie(11,0) & mip.asUInt & intrVecEnable.asUInt))
1279  val intrBitSet = intrVec.orR
1280  csrio.interrupt := intrBitSet
1281  // Page 45 in RISC-V Privileged Specification
1282  // The WFI instruction can also be executed when interrupts are disabled. The operation of WFI
1283  // must be unaffected by the global interrupt bits in mstatus (MIE and SIE) and the delegation
1284  // register mideleg, but should honor the individual interrupt enables (e.g, MTIE).
1285  csrio.wfi_event := debugIntr || (mie(11, 0) & mip.asUInt).orR
1286  mipWire.t.m := csrio.externalInterrupt.mtip
1287  mipWire.s.m := csrio.externalInterrupt.msip
1288  mipWire.e.m := csrio.externalInterrupt.meip
1289  mipWire.e.s := csrio.externalInterrupt.seip
1290
1291  // interrupts
1292  val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(intrVec(i), i.U, sum))
1293  val hasIntr = csrio.exception.valid && csrio.exception.bits.isInterrupt
1294  val ivmEnable = tlbBundle.priv.imode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1295  val iexceptionPC = Mux(ivmEnable, SignExt(csrio.exception.bits.pc, XLEN), csrio.exception.bits.pc)
1296  val iexceptionGPAddr = Mux(ivmEnable, SignExt(csrio.exception.bits.gpaddr, XLEN), csrio.exception.bits.gpaddr)
1297  val dvmEnable = tlbBundle.priv.dmode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1298  val dexceptionPC = Mux(dvmEnable, SignExt(csrio.exception.bits.pc, XLEN), csrio.exception.bits.pc)
1299  XSDebug(hasIntr, "interrupt: pc=0x%x, %d\n", dexceptionPC, intrNO)
1300  val hasDebugIntr = intrNO === IRQ_DEBUG.U && hasIntr
1301
1302  // exceptions from rob need to handle
1303  val exceptionVecFromRob    = csrio.exception.bits.exceptionVec
1304  val hasException           = csrio.exception.valid && !csrio.exception.bits.isInterrupt
1305  val hasInstrPageFault      = hasException && exceptionVecFromRob(instrPageFault)
1306  val hasLoadPageFault       = hasException && exceptionVecFromRob(loadPageFault)
1307  val hasStorePageFault      = hasException && exceptionVecFromRob(storePageFault)
1308  val hasStoreAddrMisalign   = hasException && exceptionVecFromRob(storeAddrMisaligned)
1309  val hasLoadAddrMisalign    = hasException && exceptionVecFromRob(loadAddrMisaligned)
1310  val hasInstrAccessFault    = hasException && exceptionVecFromRob(instrAccessFault)
1311  val hasLoadAccessFault     = hasException && exceptionVecFromRob(loadAccessFault)
1312  val hasStoreAccessFault    = hasException && exceptionVecFromRob(storeAccessFault)
1313  val hasBreakPoint          = hasException && exceptionVecFromRob(breakPoint)
1314  val hasInstGuestPageFault  = hasException && exceptionVecFromRob(instrGuestPageFault)
1315  val hasLoadGuestPageFault  = hasException && exceptionVecFromRob(loadGuestPageFault)
1316  val hasStoreGuestPageFault = hasException && exceptionVecFromRob(storeGuestPageFault)
1317  val hasSingleStep          = hasException && csrio.exception.bits.singleStep
1318  val hasTriggerFire         = hasException && csrio.exception.bits.trigger.canFire
1319  val triggerFrontendHitVec = csrio.exception.bits.trigger.frontendHit
1320  val triggerMemHitVec = csrio.exception.bits.trigger.backendHit
1321  val triggerHitVec = triggerFrontendHitVec | triggerMemHitVec // Todo: update mcontrol.hit
1322  val triggerCanFireVec = csrio.exception.bits.trigger.frontendCanFire | csrio.exception.bits.trigger.backendCanFire
1323  // More than one triggers can hit at the same time, but only fire one
1324  // We select the first hit trigger to fire
1325  val triggerFireOH = PriorityEncoderOH(triggerCanFireVec)
1326  val triggerFireAction = PriorityMux(triggerFireOH, tdata1WireVec.map(_.getTriggerAction)).asUInt
1327
1328
1329  XSDebug(hasSingleStep, "Debug Mode: single step exception\n")
1330  XSDebug(hasTriggerFire, p"Debug Mode: trigger fire, frontend hit vec ${Binary(csrio.exception.bits.trigger.frontendHit.asUInt)} " +
1331    p"backend hit vec ${Binary(csrio.exception.bits.trigger.backendHit.asUInt)}\n")
1332
1333  val hasExceptionVec = csrio.exception.bits.exceptionVec
1334  val regularExceptionNO = ExceptionNO.priorities.foldRight(0.U)((i: Int, sum: UInt) => Mux(hasExceptionVec(i), i.U, sum))
1335  val exceptionNO = Mux(hasSingleStep || hasTriggerFire, 3.U, regularExceptionNO)
1336  val causeNO = (hasIntr << (XLEN - 1)).asUInt | Mux(hasIntr, intrNO, exceptionNO)
1337
1338  val hasExceptionIntr = csrio.exception.valid
1339
1340  val hasDebugEbreakException = hasBreakPoint && ebreakEnterDebugMode
1341  val hasDebugTriggerException = hasTriggerFire && triggerFireAction === TrigActionEnum.DEBUG_MODE
1342  val hasDebugException = hasDebugEbreakException || hasDebugTriggerException || hasSingleStep
1343  val hasDebugTrap = hasDebugException || hasDebugIntr
1344  val ebreakEnterParkLoop = debugMode && hasExceptionIntr
1345
1346  XSDebug(hasExceptionIntr, "int/exc: pc %x int (%d):%x exc: (%d):%x\n",
1347    dexceptionPC, intrNO, intrVec, exceptionNO, hasExceptionVec.asUInt
1348  )
1349  XSDebug(hasExceptionIntr,
1350    "pc %x mstatus %x mideleg %x medeleg %x mode %x\n",
1351    dexceptionPC,
1352    mstatus,
1353    mideleg,
1354    medeleg,
1355    privilegeMode
1356  )
1357
1358  // mtval write logic
1359  // Due to timing reasons of memExceptionVAddr, we delay the write of mtval and stval
1360  val memExceptionAddr = SignExt(csrio.memExceptionVAddr, XLEN)
1361  val memExceptionGPAddr = SignExt(csrio.memExceptionGPAddr, XLEN)
1362  val updateTval = VecInit(Seq(
1363    hasInstrPageFault,
1364    hasLoadPageFault,
1365    hasStorePageFault,
1366    hasInstrAccessFault,
1367    hasLoadAccessFault,
1368    hasStoreAccessFault,
1369    hasLoadAddrMisalign,
1370    hasStoreAddrMisalign,
1371    hasInstGuestPageFault,
1372    hasLoadGuestPageFault,
1373    hasStoreGuestPageFault,
1374    hasBreakPoint,
1375  )).asUInt.orR
1376  val updateTval_h = VecInit(Seq(
1377    hasInstGuestPageFault,
1378    hasLoadGuestPageFault,
1379    hasStoreGuestPageFault
1380  )).asUInt.orR
1381  when (RegNext(RegNext(updateTval))) {
1382      val tval = Mux(
1383        RegNext(RegNext(hasInstrPageFault || hasInstrAccessFault || hasInstGuestPageFault || hasBreakPoint)),
1384        RegNext(RegNext(Mux(
1385          csrio.exception.bits.crossPageIPFFix,
1386          SignExt(csrio.exception.bits.pc + 2.U, XLEN),
1387          iexceptionPC
1388        ))),
1389        memExceptionAddr
1390    )
1391    // because we update tval two beats later, we can choose xtval according to the privilegeMode which has been updated
1392    when (RegNext(privilegeMode === ModeM)) {
1393      mtval := tval
1394    }.otherwise {
1395      when (virtMode){
1396        vstval := tval
1397      }.otherwise{
1398        stval := tval
1399      }
1400    }
1401  }
1402
1403  when(RegNext(RegNext(updateTval_h))) {
1404    val tval_tmp = Mux(
1405      RegNext(RegNext(hasInstGuestPageFault)),
1406      RegNext(RegNext(Mux(
1407        csrio.exception.bits.crossPageIPFFix,
1408        SignExt(csrio.exception.bits.gpaddr + 2.U, XLEN),
1409        iexceptionGPAddr
1410      ))),
1411      memExceptionGPAddr
1412    )
1413    val tval = tval_tmp >> 2
1414    when(RegNext(privilegeMode === ModeM)) {
1415      mtval2 := tval
1416    }.otherwise {
1417      htval := tval
1418    }
1419  }
1420
1421  val debugTrapTarget = Mux(!isEbreak && debugMode, 0x38020808.U, 0x38020800.U) // 0x808 is when an exception occurs in debug mode prog buf exec
1422  val deleg = Mux(hasIntr, mideleg , medeleg)
1423  val hdeleg = Mux(hasIntr, hideleg, hedeleg)
1424  // val delegS = ((deleg & (1 << (causeNO & 0xf))) != 0) && (privilegeMode < ModeM);
1425  val delegS = deleg(causeNO(7,0)) && (privilegeMode < ModeM)
1426  val delegVS = virtMode && delegS && hdeleg(causeNO(7, 0)) && (privilegeMode < ModeM)
1427  val clearTval = !updateTval || hasIntr
1428
1429  val clearTval_h = !updateTval_h || hasIntr
1430  val isHyperInst = csrio.exception.bits.isHls
1431  // ctrl block will use theses later for flush
1432  val isXRetFlag = RegInit(false.B)
1433  when (DelayN(io.flush.valid, 5)) {
1434    isXRetFlag := false.B
1435  }.elsewhen (isXRet) {
1436    isXRetFlag := true.B
1437  }
1438  csrio.isXRet := isXRetFlag
1439  private val retTargetReg = RegEnable(retTarget, isXRet && !illegalRetTarget)
1440  private val illegalXret = RegEnable(illegalMret || illegalSret || illegalSModeSret || illegalVSModeSret, isXRet)
1441
1442  private val xtvec = Mux(delegS, Mux(delegVS, vstvec, stvec), mtvec)
1443  private val xtvecBase = xtvec(VAddrBits - 1, 2)
1444  // When MODE=Vectored, all synchronous exceptions into M/S mode
1445  // cause the pc to be set to the address in the BASE field, whereas
1446  // interrupts cause the pc to be set to the address in the BASE field
1447  // plus four times the interrupt cause number.
1448  private val pcFromXtvec = Cat(xtvecBase + Mux(xtvec(0) && hasIntr, causeNO(3, 0), 0.U), 0.U(2.W))
1449
1450  // XRet sends redirect instead of Flush and isXRetFlag is true.B before redirect.valid.
1451  // ROB sends exception at T0 while CSR receives at T2.
1452  // We add a RegNext here and trapTarget is valid at T3.
1453  csrio.trapTarget := RegEnable(
1454    MuxCase(pcFromXtvec, Seq(
1455      (isXRetFlag && !illegalXret) -> retTargetReg,
1456      ((hasDebugTrap && !debugMode) || ebreakEnterParkLoop) -> debugTrapTarget
1457    )),
1458    isXRetFlag || csrio.exception.valid)
1459
1460  when(hasExceptionIntr) {
1461    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1462    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1463    val hstatusOld = WireInit(hstatus.asTypeOf(new HstatusStruct))
1464    val hstatusNew = WireInit(hstatus.asTypeOf(new HstatusStruct))
1465    val vsstatusOld = WireInit(vsstatus.asTypeOf(new MstatusStruct))
1466    val vsstatusNew = WireInit(vsstatus.asTypeOf(new MstatusStruct))
1467    val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct))
1468    val debugModeNew = WireInit(debugMode)
1469    when(hasDebugTrap && !debugMode) {
1470      import DcsrStruct._
1471      debugModeNew := true.B
1472      dcsrNew.prv := privilegeMode
1473      privilegeMode := ModeM
1474      when(hasDebugIntr) {
1475        dpc := iexceptionPC
1476        dcsrNew.cause := CAUSE_HALTREQ
1477        XSDebug(hasDebugIntr, "Debug Mode: Trap to %x at pc %x\n", debugTrapTarget, dpc)
1478      }.otherwise { // hasDebugException
1479        dpc := iexceptionPC // TODO: check it when hasSingleStep
1480        dcsrNew.cause := MuxCase(0.U, Seq(
1481          hasTriggerFire -> CAUSE_TRIGGER,
1482          raiseDebugException -> CAUSE_EBREAK,
1483          hasBreakPoint -> CAUSE_HALTREQ,
1484          hasSingleStep -> CAUSE_STEP
1485        ))
1486      }
1487      dcsr := dcsrNew.asUInt
1488      debugIntrEnable := false.B
1489    }.elsewhen (debugMode) {
1490      //do nothing
1491    }.elsewhen (delegVS) {
1492      vscause := (hasIntr << (XLEN-1)).asUInt | Mux(hasIntr, intrNO - 1.U, exceptionNO)
1493      vsepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1494      vsstatusNew.spp := privilegeMode
1495      vsstatusNew.pie.s := vsstatusOld.ie.s
1496      vsstatusNew.ie.s := false.B
1497      when (clearTval) {vstval := 0.U}
1498      virtMode := true.B
1499      privilegeMode := ModeS
1500    }.elsewhen (delegS) {
1501      val virt = Mux(mstatusOld.mprv.asBool, mstatusOld.mpv, virtMode)
1502      // to do hld st
1503      hstatusNew.gva := (hasInstGuestPageFault || hasLoadGuestPageFault || hasStoreGuestPageFault ||
1504                      ((virt.asBool || isHyperInst) && ((hasException && 0.U <= exceptionNO && exceptionNO <= 7.U && exceptionNO =/= 2.U)
1505                      || hasInstrPageFault || hasLoadPageFault || hasStorePageFault)))
1506      hstatusNew.spv := virtMode
1507      when(virtMode){
1508        hstatusNew.spvp := privilegeMode
1509      }
1510      virtMode := false.B
1511      scause := causeNO
1512      sepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1513      mstatusNew.spp := privilegeMode
1514      mstatusNew.pie.s := mstatusOld.ie.s
1515      mstatusNew.ie.s := false.B
1516      privilegeMode := ModeS
1517      when (clearTval) { stval := 0.U }
1518      when (clearTval_h) {htval := 0.U}
1519    }.otherwise {
1520      val virt = Mux(mstatusOld.mprv.asBool, mstatusOld.mpv, virtMode)
1521      // to do hld st
1522      mstatusNew.gva := (hasInstGuestPageFault || hasLoadGuestPageFault || hasStoreGuestPageFault ||
1523      ((virt.asBool || isHyperInst) && ((hasException && 0.U <= exceptionNO && exceptionNO <= 7.U && exceptionNO =/= 2.U)
1524        || hasInstrPageFault || hasLoadPageFault || hasStorePageFault)))
1525      mstatusNew.mpv := virtMode
1526      virtMode := false.B
1527      mcause := causeNO
1528      mepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1529      mstatusNew.mpp := privilegeMode
1530      mstatusNew.pie.m := mstatusOld.ie.m
1531      mstatusNew.ie.m := false.B
1532      privilegeMode := ModeM
1533      when (clearTval) { mtval := 0.U }
1534      when (clearTval_h) {mtval2 := 0.U}
1535    }
1536    mstatus := mstatusNew.asUInt
1537    vsstatus := vsstatusNew.asUInt
1538    hstatus := hstatusNew.asUInt
1539    debugMode := debugModeNew
1540  }
1541
1542  // Cache error debug support
1543  if(HasCustomCSRCacheOp){
1544    val cache_error_decoder = Module(new CSRCacheErrorDecoder)
1545    cache_error_decoder.io.encoded_cache_error := cacheopRegs("CACHE_ERROR")
1546  }
1547
1548  // Implicit add reset values for mepc[0] and sepc[0]
1549  // TODO: rewrite mepc and sepc using a struct-like style with the LSB always being 0
1550  when (RegNext(RegNext(reset.asBool) && !reset.asBool)) {
1551    mepc := Cat(mepc(XLEN - 1, 1), 0.U(1.W))
1552    sepc := Cat(sepc(XLEN - 1, 1), 0.U(1.W))
1553    vsepc := Cat(vsepc(XLEN - 1, 1), 0.U(1.W))
1554  }
1555
1556  def readWithScala(addr: Int): UInt = mapping(addr)._1
1557
1558  val difftestIntrNO = Mux(hasIntr, causeNO, 0.U)
1559
1560  // Always instantiate basic difftest modules.
1561  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1562    val difftest = DifftestModule(new DiffArchEvent, delay = 3, dontCare = true)
1563    difftest.coreid      := csrio.hartId
1564    difftest.valid       := csrio.exception.valid
1565    difftest.interrupt   := Mux(hasIntr, causeNO, 0.U)
1566    difftest.exception   := Mux(hasException, causeNO, 0.U)
1567    difftest.exceptionPC := dexceptionPC
1568    if (env.EnableDifftest) {
1569      difftest.exceptionInst := csrio.exception.bits.instr
1570    }
1571  }
1572
1573  // Always instantiate basic difftest modules.
1574  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1575    val difftest = DifftestModule(new DiffCSRState)
1576    difftest.coreid := csrio.hartId
1577    difftest.privilegeMode := privilegeMode
1578    difftest.mstatus := mstatus
1579    difftest.sstatus := mstatus & sstatusRmask
1580    difftest.mepc := mepc
1581    difftest.sepc := sepc
1582    difftest.mtval:= mtval
1583    difftest.stval:= stval
1584    difftest.mtvec := mtvec
1585    difftest.stvec := stvec
1586    difftest.mcause := mcause
1587    difftest.scause := scause
1588    difftest.satp := satp
1589    difftest.mip := mipReg
1590    difftest.mie := mie
1591    difftest.mscratch := mscratch
1592    difftest.sscratch := sscratch
1593    difftest.mideleg := mideleg
1594    difftest.medeleg := medeleg
1595  }
1596
1597  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1598    val difftest = DifftestModule(new DiffHCSRState)
1599    difftest.coreid := csrio.hartId
1600    difftest.virtMode := virtMode
1601    difftest.mtval2 := mtval2
1602    difftest.mtinst := mtinst
1603    difftest.hstatus := hstatus
1604    difftest.hideleg := hideleg
1605    difftest.hedeleg := hedeleg
1606    difftest.hcounteren := hcounteren
1607    difftest.htval := htval
1608    difftest.htinst := htinst
1609    difftest.hgatp := hgatp
1610    difftest.vsstatus := vsstatus
1611    difftest.vstvec := vstvec
1612    difftest.vsepc := vsepc
1613    difftest.vscause := vscause
1614    difftest.vstval := vstval
1615    difftest.vsatp := vsatp
1616    difftest.vsscratch := vsscratch
1617  }
1618
1619  if(env.AlwaysBasicDiff || env.EnableDifftest) {
1620    val difftest = DifftestModule(new DiffDebugMode)
1621    difftest.coreid := csrio.hartId
1622    difftest.debugMode := debugMode
1623    difftest.dcsr := dcsr
1624    difftest.dpc := dpc
1625    difftest.dscratch0 := dscratch0
1626    difftest.dscratch1 := dscratch1
1627  }
1628
1629  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1630    val difftest = DifftestModule(new DiffVecCSRState)
1631    difftest.coreid := csrio.hartId
1632    difftest.vstart := vstart
1633    difftest.vxsat := vcsr.asTypeOf(new VcsrStruct).vxsat
1634    difftest.vxrm := vcsr.asTypeOf(new VcsrStruct).vxrm
1635    difftest.vcsr := vcsr
1636    difftest.vl := vl
1637    difftest.vtype := vtype
1638    difftest.vlenb := vlenb
1639  }
1640}
1641*/
1642class PFEvent(implicit p: Parameters) extends XSModule with HasCSRConst  {
1643  val io = IO(new Bundle {
1644    val distribute_csr = Flipped(new DistributedCSRIO())
1645    val hpmevent = Output(Vec(29, UInt(XLEN.W)))
1646  })
1647
1648  val w = io.distribute_csr.w
1649
1650  val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++
1651                   List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++
1652                   List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++
1653                   List.fill(5)(RegInit("hc0300c0300".U(XLEN.W)))
1654
1655  val perfEventMapping = (0 until 29).map(i => {Map(
1656    MaskedRegMap(addr = Mhpmevent3 +i,
1657                 reg  = perfEvents(i),
1658                 wmask = "hf87fff3fcff3fcff".U(XLEN.W))
1659  )}).fold(Map())((a,b) => a ++ b)
1660
1661  val rdata = Wire(UInt(XLEN.W))
1662  MaskedRegMap.generate(perfEventMapping, w.bits.addr, rdata, w.valid, w.bits.data)
1663  for(i <- 0 until 29){
1664    io.hpmevent(i) := perfEvents(i)
1665  }
1666}
1667