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