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