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