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