xref: /XiangShan/src/main/scala/xiangshan/backend/fu/CSR.scala (revision d0de7e4a4bcd4633260dda99dfedc2a5e543b8b4)
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_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  val wdata = Mux(is_vsip_ie, ZeroExt(wdata_tmp << 1, XLEN), wdata_tmp)
982
983  val addrInPerfCnt = (addr >= Mcycle.U) && (addr <= Mhpmcounter31.U) ||
984    (addr >= Mcountinhibit.U) && (addr <= Mhpmevent31.U) ||
985    addr === Mip.U
986  csrio.isPerfCnt := addrInPerfCnt && valid && func =/= CSROpType.jmp
987
988  // satp wen check
989  val satpLegalMode = (wdata.asTypeOf(new SatpStruct).mode===0.U) || (wdata.asTypeOf(new SatpStruct).mode===8.U)
990
991  // csr access check, special case
992  val tvmNotPermit = (privilegeMode === ModeS && !virtMode && mstatusStruct.tvm.asBool)
993  val accessPermitted = !(addr === Satp.U && tvmNotPermit)
994  val vtvmNotPermit = (privilegeMode === ModeS && virtMode && hstatusStruct.vtvm.asBool)
995  val vaccessPermitted = !(addr === Vsatp.U && vtvmNotPermit)
996  csrio.disableSfence := (tvmNotPermit || !virtMode && privilegeMode < ModeS) || (vtvmNotPermit || virtMode && privilegeMode < ModeS)
997  csrio.disableHfenceg := !((!virtMode && privilegeMode === ModeS && !mstatusStruct.tvm.asBool) || (privilegeMode === ModeM)) // only valid in HS and mstatus.tvm == 0 or in M
998  csrio.disableHfencev :=  !(privilegeMode === ModeM || (!virtMode && privilegeMode === ModeS))
999
1000  // general CSR wen check
1001  val wen = valid && CSROpType.needAccess(func) && ((addr=/=Satp.U && addr =/= Vsatp.U) || satpLegalMode)
1002  val dcsrPermitted = dcsrPermissionCheck(addr, false.B, debugMode)
1003  val triggerPermitted = triggerPermissionCheck(addr, true.B, debugMode) // todo dmode
1004  val HasH = (HasHExtension == true).asBool()
1005  val csrAccess = csrAccessPermissionCheck(addr, false.B, privilegeMode, virtMode, HasH)
1006  val modePermitted = csrAccess === 0.U && dcsrPermitted && triggerPermitted
1007  val perfcntPermitted = perfcntPermissionCheck(addr, privilegeMode, mcounteren, scounteren)
1008  val permitted = Mux(addrInPerfCnt, perfcntPermitted, modePermitted) && Mux(virtMode, vaccessPermitted, accessPermitted)
1009  MaskedRegMap.generate(mapping, addr, rdata_tmp, wen && permitted, wdata)
1010  rdata := Mux(is_vsip_ie, ZeroExt(rdata_tmp >> 1, XLEN), rdata_tmp)
1011  io.out.bits.data := rdata
1012  io.out.bits.uop := io.in.bits.uop
1013  io.out.bits.uop.cf := cfOut
1014  io.out.bits.uop.ctrl.flushPipe := flushPipe
1015
1016  // send distribute csr a w signal
1017  csrio.customCtrl.distribute_csr.w.valid := wen && permitted
1018  csrio.customCtrl.distribute_csr.w.bits.data := wdata
1019  csrio.customCtrl.distribute_csr.w.bits.addr := addr
1020
1021  when (RegNext(csrio.fpu.fflags.valid)) {
1022    fcsr := fflags_wfn(update = true)(RegNext(csrio.fpu.fflags.bits))
1023  }
1024  // set fs and sd in mstatus
1025  when (csrw_dirty_fp_state || RegNext(csrio.fpu.dirty_fs)) {
1026    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1027    mstatusNew.fs := "b11".U
1028    mstatusNew.sd := true.B
1029    mstatus := mstatusNew.asUInt
1030  }
1031  csrio.fpu.frm := fcsr.asTypeOf(new FcsrStruct).frm
1032
1033
1034  // Trigger Ctrl
1035  csrio.customCtrl.trigger_enable := tdata1Phy.map{t =>
1036    def tdata1 = t.asTypeOf(new TdataBundle)
1037    tdata1.m && privilegeMode === ModeM ||
1038    tdata1.s && privilegeMode === ModeS || tdata1.u && privilegeMode === ModeU
1039  }
1040  csrio.customCtrl.frontend_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) === I_Trigger)
1041  csrio.customCtrl.mem_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) =/= I_Trigger)
1042  XSDebug(csrio.customCtrl.trigger_enable.asUInt.orR, p"Debug Mode: At least 1 trigger is enabled," +
1043    p"trigger enable is ${Binary(csrio.customCtrl.trigger_enable.asUInt)}\n")
1044
1045  // CSR inst decode
1046  val isEbreak = addr === privEbreak && func === CSROpType.jmp
1047  val isEcall  = addr === privEcall  && func === CSROpType.jmp
1048  val isMret   = addr === privMret   && func === CSROpType.jmp
1049  val isSret   = addr === privSret   && func === CSROpType.jmp
1050  val isUret   = addr === privUret   && func === CSROpType.jmp
1051  val isDret   = addr === privDret   && func === CSROpType.jmp
1052  val isWFI    = func === CSROpType.wfi
1053
1054  XSDebug(wen, "csr write: pc %x addr %x rdata %x wdata %x func %x\n", cfIn.pc, addr, rdata, wdata, func)
1055  XSDebug(wen, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", cfIn.pc, mstatus, mideleg , medeleg, privilegeMode)
1056
1057  // Illegal privileged operation list
1058  val illegalMret = valid && isMret && privilegeMode < ModeM
1059  val illegalSret = valid && isSret && privilegeMode < ModeS
1060  val illegalSModeSret = valid && isSret && privilegeMode === ModeS && virtMode === false.B && mstatusStruct.tsr.asBool
1061  // when hstatus.vtsr == 1, if sret is executed in VS-mode, it will cause virtual instruction
1062  val illegalVSModeSret = valid && isSret && privilegeMode === ModeS && virtMode && hstatusStruct.vtsr.asBool
1063  // When TW=1, then if WFI is executed in any less-privileged mode,
1064  // and it does not complete within an implementation-specific, bounded time limit,
1065  // the WFI instruction causes an illegal instruction exception.
1066  // The time limit may always be 0, in which case WFI always causes
1067  // an illegal instruction exception in less-privileged modes when TW=1.
1068  val illegalWFI = valid && isWFI && (privilegeMode < ModeM && mstatusStruct.tw === 1.U ||  privilegeMode === ModeU && !virtMode)
1069  val illegalVWFI = valid && isWFI && ((virtMode && privilegeMode === ModeS && hstatusStruct.vtw === 1.U && mstatusStruct.tw === 0.U)||
1070      (virtMode && privilegeMode === ModeU && mstatusStruct.tw === 0.U))
1071  // Illegal privileged instruction check
1072  val isIllegalAddr = valid && CSROpType.needAccess(func) && MaskedRegMap.isIllegalAddr(mapping, addr)
1073  val isIllegalAccess = !virtMode && wen && !(Mux(addrInPerfCnt, perfcntPermitted, csrAccess === 0.U && dcsrPermitted && triggerPermitted) && accessPermitted)
1074  val isIllegalPrivOp = illegalMret || illegalSret || illegalSModeSret || illegalWFI
1075
1076  val isIllegalVAccess = virtMode && wen && (csrAccess === 2.U || !vaccessPermitted)
1077  val isIllegalVPrivOp = illegalVSModeSret || illegalVWFI
1078  // expose several csr bits for tlb
1079  tlbBundle.priv.mxr   := mstatusStruct.mxr.asBool
1080  tlbBundle.priv.sum   := mstatusStruct.sum.asBool
1081  tlbBundle.priv.vmxr := vsstatusStruct.mxr.asBool
1082  tlbBundle.priv.vsum := vsstatusStruct.sum.asBool
1083  tlbBundle.priv.spvp := hstatusStruct.spvp
1084  tlbBundle.priv.virt  := Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpv & (mstatusStruct.mpp =/= ModeM), virtMode)
1085  tlbBundle.priv.imode := privilegeMode
1086  tlbBundle.priv.dmode := Mux(debugMode && dcsr.asTypeOf(new DcsrStruct).mprven, ModeM, Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpp, privilegeMode))
1087
1088  // Branch control
1089  val retTarget = WireInit(0.U)
1090  val resetSatp = addr === Satp.U && wen // write to satp will cause the pipeline be flushed
1091  flushPipe := resetSatp || (valid && func === CSROpType.jmp && !isEcall && !isEbreak)
1092
1093  private val illegalRetTarget = WireInit(false.B)
1094  when(valid) {
1095    when(isDret) {
1096      retTarget := dpc(VAddrBits - 1, 0)
1097    }.elsewhen(isMret && !illegalMret) {
1098      retTarget := mepc(VAddrBits - 1, 0)
1099    }.elsewhen(isSret && !illegalSret && !illegalSModeSret && !illegalVSModeSret) {
1100      retTarget := Mux(virtMode, vsepc(VAddrBits - 1, 0), sepc(VAddrBits - 1, 0))
1101    }.elsewhen(isUret) {
1102      retTarget := uepc(VAddrBits - 1, 0)
1103    }.otherwise {
1104      illegalRetTarget := true.B
1105    }
1106  }.otherwise {
1107    illegalRetTarget := true.B // when illegalRetTarget setted, retTarget should never be used
1108  }
1109
1110  when (valid && isDret) {
1111    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1112    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1113    val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct))
1114    val debugModeNew = WireInit(debugMode)
1115    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.
1116    mstatus := mstatusNew.asUInt
1117    privilegeMode := dcsrNew.prv
1118    retTarget := dpc(VAddrBits-1, 0)
1119    debugModeNew := false.B
1120    debugIntrEnable := true.B
1121    debugMode := debugModeNew
1122    XSDebug("Debug Mode: Dret executed, returning to %x.", retTarget)
1123  }
1124
1125  when (valid && isMret && !illegalMret) {
1126    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1127    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1128    mstatusNew.ie.m := mstatusOld.pie.m
1129    privilegeMode := mstatusOld.mpp
1130    if(HasHExtension) {
1131      virtMode := mstatusOld.mpv
1132      mstatusNew.mpv := 0.U
1133    }
1134    mstatusNew.pie.m := true.B
1135    mstatusNew.mpp := ModeU
1136    when (mstatusOld.mpp =/= ModeM) { mstatusNew.mprv := 0.U }
1137    mstatus := mstatusNew.asUInt
1138  }
1139
1140  when (valid && isSret && !illegalSret && !illegalSModeSret && !illegalVSModeSret) {
1141    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1142    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1143    val hstatusOld = WireInit(hstatus.asTypeOf(new HstatusStruct))
1144    val hstatusNew = WireInit(hstatus.asTypeOf(new HstatusStruct))
1145    val vsstatusOld = WireInit(vsstatus.asTypeOf(new MstatusStruct))
1146    val vsstatusNew = WireInit(vsstatus.asTypeOf(new MstatusStruct))
1147    when (virtMode === 0.U) {
1148      virtMode := hstatusOld.spv
1149      hstatusNew.spv := 0.U
1150      mstatusNew.ie.s := mstatusOld.pie.s
1151      privilegeMode := Cat(0.U(1.W), mstatusOld.spp)
1152      mstatusNew.pie.s := true.B
1153      mstatusNew.spp := ModeU
1154      when(mstatusOld.spp =/= ModeM) {
1155        mstatusNew.mprv := 0.U
1156      }
1157      mstatus := mstatusNew.asUInt
1158      hstatus := hstatusNew.asUInt
1159    }.otherwise{
1160      privilegeMode := vsstatusOld.spp
1161      vsstatusNew.spp := ModeU
1162      vsstatusNew.ie.s := vsstatusOld.pie.s
1163      vsstatusNew.pie.s := 1.U
1164      vsstatus := vsstatusNew.asUInt
1165    }
1166  }
1167
1168  when (valid && isUret) {
1169    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1170    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1171    // mstatusNew.mpp.m := ModeU //TODO: add mode U
1172    mstatusNew.ie.u := mstatusOld.pie.u
1173    privilegeMode := ModeU
1174    mstatusNew.pie.u := true.B
1175    mstatus := mstatusNew.asUInt
1176  }
1177
1178  io.in.ready := true.B
1179  io.out.valid := valid
1180
1181  // In this situation, hart will enter debug mode instead of handling a breakpoint exception simply.
1182  // Ebreak block instructions backwards, so it's ok to not keep extra info to distinguish between breakpoint
1183  // exception and enter-debug-mode exception.
1184  val ebreakEnterDebugMode =
1185    (privilegeMode === ModeM && dcsrData.ebreakm) ||
1186    (privilegeMode === ModeS && dcsrData.ebreaks) ||
1187    (privilegeMode === ModeU && dcsrData.ebreaku)
1188
1189  // raise a debug exception waiting to enter debug mode, instead of a breakpoint exception
1190  val raiseDebugException = !debugMode && isEbreak && ebreakEnterDebugMode
1191
1192  val csrExceptionVec = WireInit(cfIn.exceptionVec)
1193  csrExceptionVec(breakPoint) := io.in.valid && isEbreak && (ebreakCauseException || debugMode)
1194  csrExceptionVec(ecallM) := privilegeMode === ModeM && io.in.valid && isEcall
1195  csrExceptionVec(ecallVS) := privilegeMode === ModeS && virtMode && io.in.valid && isEcall
1196  csrExceptionVec(ecallS) := privilegeMode === ModeS && !virtMode && io.in.valid && isEcall
1197  csrExceptionVec(ecallU) := privilegeMode === ModeU && io.in.valid && isEcall
1198  // Trigger an illegal instr exception when:
1199  // * unimplemented csr is being read/written
1200  // * csr access is illegal
1201  csrExceptionVec(illegalInstr) := isIllegalAddr || isIllegalAccess || isIllegalPrivOp
1202  csrExceptionVec(virtualInstr) := isIllegalVAccess || isIllegalVPrivOp
1203  cfOut.exceptionVec := csrExceptionVec
1204
1205  XSDebug(io.in.valid, s"Debug Mode: an Ebreak is executed, ebreak cause enter-debug-mode exception ? ${raiseDebugException}\n")
1206
1207  /**
1208    * Exception and Intr
1209    */
1210  val idelegS =  (mideleg & mip.asUInt)
1211  val idelegVS = (hideleg & mideleg & mip.asUInt)
1212  def privilegedEnableDetect(idelegS: Bool, idelegVS: Bool): Bool = Mux(idelegS,
1213    Mux(idelegVS, (virtMode && privilegeMode === ModeS && vsstatusStruct.ie.s) || (virtMode && privilegeMode < ModeS),
1214      ((privilegeMode === ModeS) && mstatusStruct.ie.s) || (privilegeMode < ModeS) || virtMode),
1215    ((privilegeMode === ModeM) && mstatusStruct.ie.m) || (privilegeMode < ModeM))
1216
1217  val debugIntr = csrio.externalInterrupt.debug & debugIntrEnable
1218  XSDebug(debugIntr, "Debug Mode: debug interrupt is asserted and valid!")
1219  // send interrupt information to ROB
1220  val intrVecEnable = Wire(Vec(13, Bool()))
1221  val disableInterrupt = debugMode || (dcsrData.step && !dcsrData.stepie)
1222  intrVecEnable.zip(idelegS.asBools).zip(idelegVS.asBools).map{case((x,y),z) => x := privilegedEnableDetect(y, z) && !disableInterrupt}
1223  val intrVec = Cat(debugIntr && !debugMode, (mie(11,0) & mip.asUInt & intrVecEnable.asUInt))
1224  val intrBitSet = intrVec.orR
1225  csrio.interrupt := intrBitSet
1226  // Page 45 in RISC-V Privileged Specification
1227  // The WFI instruction can also be executed when interrupts are disabled. The operation of WFI
1228  // must be unaffected by the global interrupt bits in mstatus (MIE and SIE) and the delegation
1229  // register mideleg, but should honor the individual interrupt enables (e.g, MTIE).
1230  csrio.wfi_event := debugIntr || (mie(11, 0) & mip.asUInt).orR
1231  mipWire.t.m := csrio.externalInterrupt.mtip
1232  mipWire.s.m := csrio.externalInterrupt.msip
1233  mipWire.e.m := csrio.externalInterrupt.meip
1234  mipWire.e.s := csrio.externalInterrupt.seip
1235
1236  // interrupts
1237  val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(intrVec(i), i.U, sum))
1238  val hasIntr = csrio.exception.valid && csrio.exception.bits.isInterrupt
1239  val ivmEnable = tlbBundle.priv.imode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1240  val iexceptionPC = Mux(ivmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc)
1241  val iexceptionGPAddr = Mux(ivmEnable, SignExt(csrio.exception.bits.uop.cf.gpaddr, XLEN), csrio.exception.bits.uop.cf.gpaddr)
1242  val dvmEnable = tlbBundle.priv.dmode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1243  val dexceptionPC = Mux(dvmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc)
1244  XSDebug(hasIntr, "interrupt: pc=0x%x, %d\n", dexceptionPC, intrNO)
1245  val hasDebugIntr = intrNO === IRQ_DEBUG.U && hasIntr
1246
1247  // exceptions
1248  val raiseException = csrio.exception.valid && !csrio.exception.bits.isInterrupt
1249  val hasInstrPageFault = csrio.exception.bits.uop.cf.exceptionVec(instrPageFault) && raiseException
1250  val hasLoadPageFault = csrio.exception.bits.uop.cf.exceptionVec(loadPageFault) && raiseException
1251  val hasStorePageFault = csrio.exception.bits.uop.cf.exceptionVec(storePageFault) && raiseException
1252  val hasStoreAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(storeAddrMisaligned) && raiseException
1253  val hasLoadAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(loadAddrMisaligned) && raiseException
1254  val hasInstrAccessFault = csrio.exception.bits.uop.cf.exceptionVec(instrAccessFault) && raiseException
1255  val hasLoadAccessFault = csrio.exception.bits.uop.cf.exceptionVec(loadAccessFault) && raiseException
1256  val hasStoreAccessFault = csrio.exception.bits.uop.cf.exceptionVec(storeAccessFault) && raiseException
1257  val hasbreakPoint = csrio.exception.bits.uop.cf.exceptionVec(breakPoint) && raiseException
1258  val hasSingleStep = csrio.exception.bits.uop.ctrl.singleStep && raiseException
1259  val hasTriggerHit = (csrio.exception.bits.uop.cf.trigger.hit) && raiseException
1260  val hasInstGuestPageFault = csrio.exception.bits.uop.cf.exceptionVec(instrGuestPageFault) && raiseException
1261  val hasLoadGuestPageFault = csrio.exception.bits.uop.cf.exceptionVec(loadGuestPageFault) && raiseException
1262  val hasStoreGuestPageFault = csrio.exception.bits.uop.cf.exceptionVec(storeGuestPageFault) && raiseException
1263
1264  XSDebug(hasSingleStep, "Debug Mode: single step exception\n")
1265  XSDebug(hasTriggerHit, p"Debug Mode: trigger hit, is frontend? ${Binary(csrio.exception.bits.uop.cf.trigger.frontendHit.asUInt)} " +
1266    p"backend hit vec ${Binary(csrio.exception.bits.uop.cf.trigger.backendHit.asUInt)}\n")
1267
1268  val hasExceptionVec = csrio.exception.bits.uop.cf.exceptionVec
1269  val regularExceptionNO = ExceptionNO.priorities.foldRight(0.U)((i: Int, sum: UInt) => Mux(hasExceptionVec(i), i.U, sum))
1270  val exceptionNO = Mux(hasSingleStep || hasTriggerHit, 3.U, regularExceptionNO)
1271  val causeNO = (hasIntr << (XLEN-1)).asUInt | Mux(hasIntr, intrNO, exceptionNO)
1272
1273  val hasExceptionIntr = csrio.exception.valid
1274
1275  val hasDebugException = hasBreakPoint && !debugMode && ebreakEnterDebugMode
1276  val hasDebugExceptionIntr = !debugMode && (hasDebugException || hasDebugIntr || hasSingleStep || hasTriggerHit && triggerAction) // TODO
1277  val ebreakEnterParkLoop = debugMode && hasExceptionIntr
1278
1279  XSDebug(hasExceptionIntr, "int/exc: pc %x int (%d):%x exc: (%d):%x\n",
1280    dexceptionPC, intrNO, intrVec, exceptionNO, hasExceptionVec.asUInt
1281  )
1282  XSDebug(hasExceptionIntr,
1283    "pc %x mstatus %x mideleg %x medeleg %x mode %x\n",
1284    dexceptionPC,
1285    mstatus,
1286    mideleg,
1287    medeleg,
1288    privilegeMode
1289  )
1290
1291  // mtval write logic
1292  // Due to timing reasons of memExceptionVAddr, we delay the write of mtval and stval
1293  val memExceptionAddr = SignExt(csrio.memExceptionVAddr, XLEN)
1294  val memExceptionGPAddr = SignExt(csrio.memExceptionGPAddr, XLEN)
1295  val updateTval = VecInit(Seq(
1296    hasInstrPageFault,
1297    hasLoadPageFault,
1298    hasStorePageFault,
1299    hasInstrAccessFault,
1300    hasLoadAccessFault,
1301    hasStoreAccessFault,
1302    hasLoadAddrMisaligned,
1303    hasStoreAddrMisaligned,
1304    hasInstGuestPageFault,
1305    hasLoadGuestPageFault,
1306    hasStoreGuestPageFault
1307  )).asUInt.orR
1308  val updateTval_h = VecInit(Seq(
1309    hasInstGuestPageFault,
1310    hasLoadGuestPageFault,
1311    hasStoreGuestPageFault
1312  )).asUInt.orR
1313  when (RegNext(RegNext(updateTval))) {
1314      val tval = Mux(
1315        RegNext(RegNext(hasInstrPageFault || hasInstrAccessFault || hasInstGuestPageFault)),
1316        RegNext(RegNext(Mux(
1317          csrio.exception.bits.uop.cf.crossPageIPFFix,
1318          SignExt(csrio.exception.bits.uop.cf.pc + 2.U, XLEN),
1319          iexceptionPC
1320        ))),
1321        memExceptionAddr
1322    )
1323    // because we update tval two beats later, we can choose xtval according to the privilegeMode which has been updated
1324    when (RegNext(privilegeMode === ModeM)) {
1325      mtval := tval
1326    }.otherwise {
1327      when (virtMode){
1328        vstval := tval
1329      }.otherwise{
1330        stval := tval
1331      }
1332    }
1333  }
1334
1335  when(RegNext(RegNext(updateTval_h))) {
1336    val tval_tmp = Mux(
1337      RegNext(RegNext(hasInstGuestPageFault)),
1338      RegNext(RegNext(Mux(
1339        csrio.exception.bits.uop.cf.crossPageIPFFix,
1340        SignExt(csrio.exception.bits.uop.cf.gpaddr + 2.U, XLEN),
1341        iexceptionGPAddr
1342      ))),
1343      memExceptionGPAddr
1344    )
1345    val tval = tval_tmp >> 2
1346    when(RegNext(privilegeMode === ModeM)) {
1347      mtval2 := tval
1348    }.otherwise {
1349      htval := tval
1350    }
1351  }
1352
1353  val debugTrapTarget = Mux(!isEbreak && debugMode, 0x38020808.U, 0x38020800.U) // 0x808 is when an exception occurs in debug mode prog buf exec
1354  val deleg = Mux(raiseIntr, mideleg , medeleg)
1355  val hdeleg = Mux(raiseIntr, hideleg, hedeleg)
1356  // val delegS = ((deleg & (1 << (causeNO & 0xf))) != 0) && (privilegeMode < ModeM);
1357  val delegS = deleg(causeNO(7,0)) && (privilegeMode < ModeM)
1358  val delegVS = virtMode && delegS && hdeleg(causeNO(7, 0)) && (privilegeMode < ModeM)
1359  val clearTval = !updateTval || raiseIntr
1360  val clearTval_h = !updateTval_h || raiseIntr
1361  val isXRet = io.in.valid && func === CSROpType.jmp && !isEcall && !isEbreak
1362  val isHyperInst = csrio.exception.bits.uop.ctrl.isHyperInst
1363  // ctrl block will use theses later for flush
1364  val isXRetFlag = RegInit(false.B)
1365  when (DelayN(io.redirectIn.valid, 5)) {
1366    isXRetFlag := false.B
1367  }.elsewhen (isXRet) {
1368    isXRetFlag := true.B
1369  }
1370  csrio.isXRet := isXRetFlag
1371  private val retTargetReg = RegEnable(retTarget, isXRet && !illegalRetTarget)
1372  private val illegalXret = RegEnable(illegalMret || illegalSret || illegalSModeSret || illegalVSModeSret, isXRet)
1373  val xtvec = Mux(delegS, Mux(delegVS, vstvec, stvec), mtvec)
1374  val xtvecBase = xtvec(VAddrBits - 1, 2)
1375  // When MODE=Vectored, all synchronous exceptions into M/S mode
1376  // cause the pc to be set to the address in the BASE field, whereas
1377  // interrupts cause the pc to be set to the address in the BASE field
1378  // plus four times the interrupt cause number.
1379  private val pcFromXtvec = Cat(xtvecBase + Mux(xtvec(0) && raiseIntr, causeNO(3, 0), 0.U), 0.U(2.W))
1380  // XRet sends redirect instead of Flush and isXRetFlag is true.B before redirect.valid.
1381  // ROB sends exception at T0 while CSR receives at T2.
1382  // We add a RegNext here and trapTarget is valid at T3.
1383  csrio.trapTarget := RegEnable(
1384    MuxCase(pcFromXtvec, Seq(
1385      (isXRetFlag && !illegalXret) -> retTargetReg,
1386      (raiseDebugExceptionIntr || ebreakEnterParkLoop) -> debugTrapTarget
1387    )),
1388    isXRetFlag || csrio.exception.valid)
1389
1390  when (hasExceptionIntr) {
1391    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1392    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1393    val hstatusOld = WireInit(hstatus.asTypeOf(new HstatusStruct))
1394    val hstatusNew = WireInit(hstatus.asTypeOf(new HstatusStruct))
1395    val vsstatusOld = WireInit(vsstatus.asTypeOf(new MstatusStruct))
1396    val vsstatusNew = WireInit(vsstatus.asTypeOf(new MstatusStruct))
1397    val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct))
1398    val debugModeNew = WireInit(debugMode)
1399
1400    when (hasDebugExceptionIntr) {
1401      when (hasDebugIntr) {
1402        debugModeNew := true.B
1403        dpc := iexceptionPC
1404        dcsrNew.cause := 3.U
1405        dcsrNew.prv := privilegeMode
1406        privilegeMode := ModeM
1407        XSDebug(hasDebugIntr, "Debug Mode: Trap to %x at pc %x\n", debugTrapTarget, dpc)
1408      }.elsewhen ((hasBreakPoint || hasSingleStep || hasTriggerHit && triggerAction) && !debugMode) {
1409        // ebreak or ss in running hart
1410        debugModeNew := true.B
1411        dpc := iexceptionPC // TODO: check it when hasSingleStep
1412        dcsrNew.cause := Mux(hasTriggerHit, 2.U, Mux(hasBreakPoint, 1.U, 4.U))
1413        dcsrNew.prv := privilegeMode
1414        privilegeMode := ModeM
1415      }
1416      dcsr := dcsrNew.asUInt
1417      debugIntrEnable := false.B
1418    }.elsewhen (debugMode) {
1419      //do nothing
1420    }}.elsewhen (delegVS) {
1421      vscause := (raiseIntr << (XLEN-1)).asUInt | Mux(raiseIntr, intrNO >> 1.U, exceptionNO)
1422      vsepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1423      vsstatusNew.spp := privilegeMode
1424      vsstatusNew.pie.s := vsstatusOld.ie.s
1425      vsstatusNew.ie.s := false.B
1426      when (clearTval) {vstval := 0.U}
1427      virtMode := true.B
1428      privilegeMode := ModeS
1429    }.elsewhen (delegS) {
1430      val virt = Mux(mstatusOld.mprv.asBool(), mstatusOld.mpv, virtMode)
1431      // to do hld st
1432      hstatusNew.gva := (hasInstGuestPageFault || hasLoadGuestPageFault || hasStoreGuestPageFault ||
1433                      ((virt.asBool() || isHyperInst) && ((raiseException && 0.U <= exceptionNO && exceptionNO <= 7.U && exceptionNO =/= 2.U)
1434                      || hasInstrPageFault || hasLoadPageFault || hasStorePageFault)))
1435      hstatusNew.spv := virtMode
1436      when(virtMode){
1437        hstatusNew.spvp := privilegeMode
1438      }
1439      virtMode := false.B
1440      scause := causeNO
1441      sepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1442      mstatusNew.spp := privilegeMode
1443      mstatusNew.pie.s := mstatusOld.ie.s
1444      mstatusNew.ie.s := false.B
1445      privilegeMode := ModeS
1446      when (clearTval) { stval := 0.U }
1447      when (clearTval_h) {htval := 0.U}
1448    }.otherwise {
1449      val virt = Mux(mstatusOld.mprv.asBool(), mstatusOld.mpv, virtMode)
1450      // to do hld st
1451      mstatusNew.gva := (hasInstGuestPageFault || hasLoadGuestPageFault || hasStoreGuestPageFault ||
1452      ((virt.asBool() || isHyperInst) && ((raiseException && 0.U <= exceptionNO && exceptionNO <= 7.U && exceptionNO =/= 2.U)
1453        || hasInstrPageFault || hasLoadPageFault || hasStorePageFault)))
1454      mstatusNew.mpv := virtMode
1455      virtMode := false.B
1456      mcause := causeNO
1457      mepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1458      mstatusNew.mpp := privilegeMode
1459      mstatusNew.pie.m := mstatusOld.ie.m
1460      mstatusNew.ie.m := false.B
1461      privilegeMode := ModeM
1462      when (clearTval) { mtval := 0.U }
1463      when (clearTval_h) {mtval2 := 0.U}
1464    }
1465    mstatus := mstatusNew.asUInt
1466    vsstatus := vsstatusNew.asUInt
1467    hstatus := hstatusNew.asUInt
1468    debugMode := debugModeNew
1469  }
1470
1471  XSDebug(hasExceptionIntr && delegS, "sepc is written!!! pc:%x\n", cfIn.pc)
1472
1473  // Distributed CSR update req
1474  //
1475  // For now we use it to implement customized cache op
1476  // It can be delayed if necessary
1477
1478  val delayedUpdate0 = DelayN(csrio.distributedUpdate(0), 2)
1479  val delayedUpdate1 = DelayN(csrio.distributedUpdate(1), 2)
1480  val distributedUpdateValid = delayedUpdate0.w.valid || delayedUpdate1.w.valid
1481  val distributedUpdateAddr = Mux(delayedUpdate0.w.valid,
1482    delayedUpdate0.w.bits.addr,
1483    delayedUpdate1.w.bits.addr
1484  )
1485  val distributedUpdateData = Mux(delayedUpdate0.w.valid,
1486    delayedUpdate0.w.bits.data,
1487    delayedUpdate1.w.bits.data
1488  )
1489
1490  assert(!(delayedUpdate0.w.valid && delayedUpdate1.w.valid))
1491
1492  when(distributedUpdateValid){
1493    // cacheopRegs can be distributed updated
1494    CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
1495      when((Scachebase + attribute("offset").toInt).U === distributedUpdateAddr){
1496        cacheopRegs(name) := distributedUpdateData
1497      }
1498    }}
1499  }
1500
1501  // Cache error debug support
1502  if(HasCustomCSRCacheOp){
1503    val cache_error_decoder = Module(new CSRCacheErrorDecoder)
1504    cache_error_decoder.io.encoded_cache_error := cacheopRegs("CACHE_ERROR")
1505  }
1506
1507  // Implicit add reset values for mepc[0] and sepc[0]
1508  // TODO: rewrite mepc and sepc using a struct-like style with the LSB always being 0
1509  when (RegNext(RegNext(reset.asBool) && !reset.asBool)) {
1510    mepc := Cat(mepc(XLEN - 1, 1), 0.U(1.W))
1511    sepc := Cat(sepc(XLEN - 1, 1), 0.U(1.W))
1512  }
1513
1514  def readWithScala(addr: Int): UInt = mapping(addr)._1
1515
1516  val difftestIntrNO = Mux(hasIntr, causeNO, 0.U)
1517
1518  // Always instantiate basic difftest modules.
1519  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1520    val difftest = DifftestModule(new DiffArchEvent, delay = 3, dontCare = true)
1521    difftest.coreid      := csrio.hartId
1522    difftest.valid       := csrio.exception.valid
1523    difftest.interrupt   := Mux(hasIntr, causeNO, 0.U)
1524    difftest.exception   := Mux(hasException, causeNO, 0.U)
1525    difftest.exceptionPC := dexceptionPC
1526    if (env.EnableDifftest) {
1527      difftest.exceptionInst := csrio.exception.bits.uop.cf.instr
1528    }
1529  }
1530
1531  // Always instantiate basic difftest modules.
1532  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1533    val difftest = DifftestModule(new DiffCSRState)
1534    difftest.coreid := csrio.hartId
1535    difftest.privilegeMode := privilegeMode
1536    difftest.mstatus := mstatus
1537    difftest.sstatus := mstatus & sstatusRmask
1538    difftest.mepc := mepc
1539    difftest.sepc := sepc
1540    difftest.mtval:= mtval
1541    difftest.stval:= stval
1542    difftest.mtvec := mtvec
1543    difftest.stvec := stvec
1544    difftest.mcause := mcause
1545    difftest.scause := scause
1546    difftest.satp := satp
1547    difftest.mip := mipReg
1548    difftest.mie := mie
1549    difftest.mscratch := mscratch
1550    difftest.sscratch := sscratch
1551    difftest.mideleg := mideleg
1552    difftest.medeleg := medeleg
1553  }
1554
1555  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1556    val difftest = Module(new DifftestHCSRState)
1557    difftest.io.clock := clock
1558    difftest.io.coreid := csrio.hartId
1559    difftest.io.virtMode := virtMode
1560    difftest.io.mtval2 := mtval2
1561    difftest.io.mtinst := mtinst
1562    difftest.io.hstatus := hstatus
1563    difftest.io.hideleg := hideleg
1564    difftest.io.hedeleg := hedeleg
1565    difftest.io.hcounteren := hcounteren
1566    difftest.io.htval := htval
1567    difftest.io.htinst := htinst
1568    difftest.io.hgatp := hgatp
1569    difftest.io.vsstatus := vsstatus
1570    difftest.io.vstvec := vstvec
1571    difftest.io.vsepc := vsepc
1572    difftest.io.vscause := vscause
1573    difftest.io.vstval := vstval
1574    difftest.io.vsatp := vsatp
1575    difftest.io.vsscratch := vsscratch
1576  }
1577
1578  if(env.AlwaysBasicDiff || env.EnableDifftest) {
1579    val difftest = DifftestModule(new DiffDebugMode)
1580    difftest.coreid := csrio.hartId
1581    difftest.debugMode := debugMode
1582    difftest.dcsr := dcsr
1583    difftest.dpc := dpc
1584    difftest.dscratch0 := dscratch0
1585    difftest.dscratch1 := dscratch1
1586  }
1587}
1588
1589class PFEvent(implicit p: Parameters) extends XSModule with HasCSRConst  {
1590  val io = IO(new Bundle {
1591    val distribute_csr = Flipped(new DistributedCSRIO())
1592    val hpmevent = Output(Vec(29, UInt(XLEN.W)))
1593  })
1594
1595  val w = io.distribute_csr.w
1596
1597  val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++
1598                   List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++
1599                   List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++
1600                   List.fill(5)(RegInit("hc0300c0300".U(XLEN.W)))
1601
1602  val perfEventMapping = (0 until 29).map(i => {Map(
1603    MaskedRegMap(addr = Mhpmevent3 +i,
1604                 reg  = perfEvents(i),
1605                 wmask = "hf87fff3fcff3fcff".U(XLEN.W))
1606  )}).fold(Map())((a,b) => a ++ b)
1607
1608  val rdata = Wire(UInt(XLEN.W))
1609  MaskedRegMap.generate(perfEventMapping, w.bits.addr, rdata, w.valid, w.bits.data)
1610  for(i <- 0 until 29){
1611    io.hpmevent(i) := perfEvents(i)
1612  }
1613}
1614