xref: /XiangShan/src/main/scala/xiangshan/backend/fu/CSR.scala (revision 9473e04d5cab97eaf63add958b2392eec3d876a2)
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 chipsalliance.rocketchip.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(8.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  // from outside cpu,externalInterrupt
122  val externalInterrupt = new ExternalInterruptIO
123  // TLB
124  val tlb = Output(new TlbCsrBundle)
125  // Debug Mode
126  // val singleStep = Output(Bool())
127  val debugMode = Output(Bool())
128  // to Fence to disable sfence
129  val disableSfence = Output(Bool())
130  // Custom microarchiture ctrl signal
131  val customCtrl = Output(new CustomCSRCtrlIO)
132  // distributed csr write
133  val distributedUpdate = Vec(2, Flipped(new DistributedCSRUpdateReq))
134}
135
136class CSR(implicit p: Parameters) extends FunctionUnit with HasCSRConst with PMPMethod with PMAMethod with HasTriggerConst
137{
138  val csrio = IO(new CSRFileIO)
139
140  val cfIn = io.in.bits.uop.cf
141  val cfOut = Wire(new CtrlFlow)
142  cfOut := cfIn
143  val flushPipe = Wire(Bool())
144
145  val (valid, src1, src2, func) = (
146    io.in.valid,
147    io.in.bits.src(0),
148    io.in.bits.uop.ctrl.imm,
149    io.in.bits.uop.ctrl.fuOpType
150  )
151
152  // CSR define
153
154  class Priv extends Bundle {
155    val m = Output(Bool())
156    val h = Output(Bool())
157    val s = Output(Bool())
158    val u = Output(Bool())
159  }
160
161  val csrNotImplemented = RegInit(UInt(XLEN.W), 0.U)
162
163  class DcsrStruct extends Bundle {
164    val xdebugver = Output(UInt(2.W))
165    val zero4 = Output(UInt(2.W))
166    val zero3 = Output(UInt(12.W))
167    val ebreakm = Output(Bool())
168    val ebreakh = Output(Bool())
169    val ebreaks = Output(Bool())
170    val ebreaku = Output(Bool())
171    val stepie = Output(Bool()) // 0
172    val stopcycle = Output(Bool())
173    val stoptime = Output(Bool())
174    val cause = Output(UInt(3.W))
175    val v = Output(Bool()) // 0
176    val mprven = Output(Bool())
177    val nmip = Output(Bool())
178    val step = Output(Bool())
179    val prv = Output(UInt(2.W))
180  }
181
182  class MstatusStruct extends Bundle {
183    val sd = Output(UInt(1.W))
184
185    val pad1 = if (XLEN == 64) Output(UInt(25.W)) else null
186    val mbe  = if (XLEN == 64) Output(UInt(1.W)) else null
187    val sbe  = if (XLEN == 64) Output(UInt(1.W)) else null
188    val sxl  = if (XLEN == 64) Output(UInt(2.W))  else null
189    val uxl  = if (XLEN == 64) Output(UInt(2.W))  else null
190    val pad0 = if (XLEN == 64) Output(UInt(9.W))  else Output(UInt(8.W))
191
192    val tsr = Output(UInt(1.W))
193    val tw = Output(UInt(1.W))
194    val tvm = Output(UInt(1.W))
195    val mxr = Output(UInt(1.W))
196    val sum = Output(UInt(1.W))
197    val mprv = Output(UInt(1.W))
198    val xs = Output(UInt(2.W))
199    val fs = Output(UInt(2.W))
200    val mpp = Output(UInt(2.W))
201    val hpp = Output(UInt(2.W))
202    val spp = Output(UInt(1.W))
203    val pie = new Priv
204    val ie = new Priv
205    assert(this.getWidth == XLEN)
206
207    def ube = pie.h // a little ugly
208    def ube_(r: UInt): Unit = {
209      pie.h := r(0)
210    }
211  }
212
213  class Interrupt extends Bundle {
214//  val d = Output(Bool())    // Debug
215    val e = new Priv
216    val t = new Priv
217    val s = new Priv
218  }
219
220  // Debug CSRs
221  val dcsr = RegInit(UInt(32.W), 0x4000b000.U)
222  val dpc = Reg(UInt(64.W))
223  val dscratch = Reg(UInt(64.W))
224  val dscratch1 = Reg(UInt(64.W))
225  val debugMode = RegInit(false.B)
226  val debugIntrEnable = RegInit(true.B)
227  csrio.debugMode := debugMode
228
229  val dpcPrev = RegNext(dpc)
230  XSDebug(dpcPrev =/= dpc, "Debug Mode: dpc is altered! Current is %x, previous is %x\n", dpc, dpcPrev)
231
232  // dcsr value table
233  // | debugver | 0100
234  // | zero     | 10 bits of 0
235  // | ebreakvs | 0
236  // | ebreakvu | 0
237  // | ebreakm  | 1 if ebreak enters debug
238  // | zero     | 0
239  // | ebreaks  |
240  // | ebreaku  |
241  // | stepie   | disable interrupts in singlestep
242  // | stopcount| stop counter, 0
243  // | stoptime | stop time, 0
244  // | cause    | 3 bits read only
245  // | v        | 0
246  // | mprven   | 1
247  // | nmip     | read only
248  // | step     |
249  // | prv      | 2 bits
250
251  val dcsrData = Wire(new DcsrStruct)
252  dcsrData := dcsr.asTypeOf(new DcsrStruct)
253  val dcsrMask = ZeroExt(GenMask(15) | GenMask(13, 11) | GenMask(4) | GenMask(2, 0), XLEN)// Dcsr write mask
254  def dcsrUpdateSideEffect(dcsr: UInt): UInt = {
255    val dcsrOld = WireInit(dcsr.asTypeOf(new DcsrStruct))
256    val dcsrNew = dcsr | (dcsrOld.prv(0) | dcsrOld.prv(1)).asUInt // turn 10 priv into 11
257    dcsrNew
258  }
259  // csrio.singleStep := dcsrData.step
260  csrio.customCtrl.singlestep := dcsrData.step && !debugMode
261
262  // Trigger CSRs
263
264  val type_config = Array(
265    0.U -> I_Trigger, 1.U -> I_Trigger,
266    2.U -> S_Trigger, 3.U -> S_Trigger,
267    4.U -> L_Trigger, 5.U -> L_Trigger, // No.5 Load Trigger
268    6.U -> I_Trigger, 7.U -> S_Trigger,
269    8.U -> I_Trigger, 9.U -> L_Trigger
270  )
271  def TypeLookup(select: UInt) = MuxLookup(select, I_Trigger, type_config)
272
273  val tdata1Phy = RegInit(VecInit(List.fill(10) {(2L << 60L).U(64.W)})) // init ttype 2
274  val tdata2Phy = Reg(Vec(10, UInt(64.W)))
275  val tselectPhy = RegInit(0.U(4.W))
276  val tinfo = RegInit(2.U(64.W))
277  val tControlPhy = RegInit(0.U(64.W))
278  val triggerAction = RegInit(false.B)
279
280  def ReadTdata1(rdata: UInt) = rdata | Cat(triggerAction, 0.U(12.W)) // fix action
281  def WriteTdata1(wdata: UInt): UInt = {
282    val tdata1 = WireInit(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle))
283    val wdata_wire = WireInit(wdata.asTypeOf(new TdataBundle))
284    val tdata1_new = WireInit(wdata.asTypeOf(new TdataBundle))
285    XSDebug(src2(11, 0) === Tdata1.U && valid && func =/= CSROpType.jmp, p"Debug Mode: tdata1(${tselectPhy})is written, the actual value is ${wdata}\n")
286//    tdata1_new.hit := wdata(20)
287    tdata1_new.ttype := tdata1.ttype
288    tdata1_new.dmode := 0.U // Mux(debugMode, wdata_wire.dmode, tdata1.dmode)
289    tdata1_new.maskmax := 0.U
290    tdata1_new.hit := 0.U
291    tdata1_new.select := (TypeLookup(tselectPhy) === I_Trigger) && wdata_wire.select
292    when(wdata_wire.action <= 1.U){
293      triggerAction := tdata1_new.action(0)
294    } .otherwise{
295      tdata1_new.action := tdata1.action
296    }
297    tdata1_new.timing := false.B // hardwire this because we have singlestep
298    tdata1_new.zero1 := 0.U
299    tdata1_new.zero2 := 0.U
300    tdata1_new.chain := !tselectPhy(0) && wdata_wire.chain
301    when(wdata_wire.matchType =/= 0.U && wdata_wire.matchType =/= 2.U && wdata_wire.matchType =/= 3.U) {
302      tdata1_new.matchType := tdata1.matchType
303    }
304    tdata1_new.sizehi := Mux(wdata_wire.select && TypeLookup(tselectPhy) === I_Trigger, 0.U, 1.U)
305    tdata1_new.sizelo:= Mux(wdata_wire.select && TypeLookup(tselectPhy) === I_Trigger, 3.U, 1.U)
306    tdata1_new.execute := TypeLookup(tselectPhy) === I_Trigger
307    tdata1_new.store := TypeLookup(tselectPhy) === S_Trigger
308    tdata1_new.load := TypeLookup(tselectPhy) === L_Trigger
309    tdata1_new.asUInt
310  }
311
312  def WriteTselect(wdata: UInt) = {
313    Mux(wdata < 10.U, wdata(3, 0), tselectPhy)
314  }
315
316  val tcontrolWriteMask = ZeroExt(GenMask(3) | GenMask(7), XLEN)
317
318
319  def GenTdataDistribute(tdata1: TdataBundle, tdata2: UInt): MatchTriggerIO = {
320    val res = Wire(new MatchTriggerIO)
321    res.matchType := tdata1.matchType
322    res.select := tdata1.select
323    res.timing := tdata1.timing
324    res.action := triggerAction
325    res.chain := tdata1.chain
326    res.tdata2 := tdata2
327    res
328  }
329
330  csrio.customCtrl.frontend_trigger.t.bits.addr := MuxLookup(tselectPhy, 0.U, Seq(
331    0.U -> 0.U,
332    1.U -> 1.U,
333    6.U -> 2.U,
334    8.U -> 3.U
335  ))
336  csrio.customCtrl.mem_trigger.t.bits.addr := MuxLookup(tselectPhy, 0.U, Seq(
337    2.U -> 0.U,
338    3.U -> 1.U,
339    4.U -> 2.U,
340    5.U -> 3.U,
341    7.U -> 4.U,
342    9.U -> 5.U
343  ))
344  csrio.customCtrl.frontend_trigger.t.bits.tdata := GenTdataDistribute(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle), tdata2Phy(tselectPhy))
345  csrio.customCtrl.mem_trigger.t.bits.tdata := GenTdataDistribute(tdata1Phy(tselectPhy).asTypeOf(new TdataBundle), tdata2Phy(tselectPhy))
346
347  // Machine-Level CSRs
348  // mtvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1
349  val mtvecMask = ~(0x2.U(XLEN.W))
350  val mtvec = RegInit(UInt(XLEN.W), 0.U)
351  val mcounteren = RegInit(UInt(XLEN.W), 0.U)
352  val mcause = RegInit(UInt(XLEN.W), 0.U)
353  val mtval = RegInit(UInt(XLEN.W), 0.U)
354  val mepc = Reg(UInt(XLEN.W))
355  // Page 36 in riscv-priv: The low bit of mepc (mepc[0]) is always zero.
356  val mepcMask = ~(0x1.U(XLEN.W))
357
358  val mie = RegInit(0.U(XLEN.W))
359  val mipWire = WireInit(0.U.asTypeOf(new Interrupt))
360  val mipReg  = RegInit(0.U(XLEN.W))
361  val mipFixMask = ZeroExt(GenMask(9) | GenMask(5) | GenMask(1), XLEN)
362  val mip = (mipWire.asUInt | mipReg).asTypeOf(new Interrupt)
363
364  def getMisaMxl(mxl: BigInt): BigInt = mxl << (XLEN - 2)
365  def getMisaExt(ext: Char): Long = 1 << (ext.toInt - 'a'.toInt)
366  var extList = List('a', 's', 'i', 'u')
367  if (HasMExtension) { extList = extList :+ 'm' }
368  if (HasCExtension) { extList = extList :+ 'c' }
369  if (HasFPU) { extList = extList ++ List('f', 'd') }
370  val misaInitVal = getMisaMxl(2) | extList.foldLeft(0L)((sum, i) => sum | getMisaExt(i)) //"h8000000000141105".U
371  val misa = RegInit(UInt(XLEN.W), misaInitVal.U)
372
373  // MXL = 2          | 0 | EXT = b 00 0000 0100 0001 0001 0000 0101
374  // (XLEN-1, XLEN-2) |   |(25, 0)  ZY XWVU TSRQ PONM LKJI HGFE DCBA
375
376  val mvendorid = RegInit(UInt(XLEN.W), 0.U) // this is a non-commercial implementation
377  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
378  val mimpid = RegInit(UInt(XLEN.W), 0.U) // provides a unique encoding of the version of the processor implementation
379  val mhartid = Reg(UInt(XLEN.W)) // the hardware thread running the code
380  when (RegNext(RegNext(reset.asBool) && !reset.asBool)) {
381    mhartid := csrio.hartId
382  }
383  val mconfigptr = RegInit(UInt(XLEN.W), 0.U) // the read-only pointer pointing to the platform config structure, 0 for not supported.
384  val mstatus = RegInit("ha00002000".U(XLEN.W))
385
386  // mstatus Value Table
387  // | sd   |
388  // | pad1 |
389  // | sxl  | hardlinked to 10, use 00 to pass xv6 test
390  // | uxl  | hardlinked to 10
391  // | pad0 |
392  // | tsr  |
393  // | tw   |
394  // | tvm  |
395  // | mxr  |
396  // | sum  |
397  // | mprv |
398  // | xs   | 00 |
399  // | fs   | 01 |
400  // | mpp  | 00 |
401  // | hpp  | 00 |
402  // | spp  | 0 |
403  // | pie  | 0000 | pie.h is used as UBE
404  // | ie   | 0000 | uie hardlinked to 0, as N ext is not implemented
405
406  val mstatusStruct = mstatus.asTypeOf(new MstatusStruct)
407  def mstatusUpdateSideEffect(mstatus: UInt): UInt = {
408    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
409    val mstatusNew = Cat(mstatusOld.xs === "b11".U || mstatusOld.fs === "b11".U, mstatus(XLEN-2, 0))
410    mstatusNew
411  }
412
413  val mstatusWMask = (~ZeroExt((
414    GenMask(XLEN - 2, 36) | // WPRI
415    GenMask(35, 32)       | // SXL and UXL cannot be changed
416    GenMask(31, 23)       | // WPRI
417    GenMask(16, 15)       | // XS is read-only
418    GenMask(10, 9)        | // WPRI
419    GenMask(6)            | // WPRI
420    GenMask(2)              // WPRI
421  ), 64)).asUInt
422  val mstatusMask = (~ZeroExt((
423    GenMask(XLEN - 2, 36) | // WPRI
424    GenMask(31, 23)       | // WPRI
425    GenMask(10, 9)        | // WPRI
426    GenMask(6)            | // WPRI
427    GenMask(2)              // WPRI
428  ), 64)).asUInt
429
430  val medeleg = RegInit(UInt(XLEN.W), 0.U)
431  val mideleg = RegInit(UInt(XLEN.W), 0.U)
432  val mscratch = RegInit(UInt(XLEN.W), 0.U)
433
434  // PMP Mapping
435  val pmp = Wire(Vec(NumPMP, new PMPEntry())) // just used for method parameter
436  val pma = Wire(Vec(NumPMA, new PMPEntry())) // just used for method parameter
437  val pmpMapping = pmp_gen_mapping(pmp_init, NumPMP, PmpcfgBase, PmpaddrBase, pmp)
438  val pmaMapping = pmp_gen_mapping(pma_init, NumPMA, PmacfgBase, PmaaddrBase, pma)
439
440  // Superviser-Level CSRs
441
442  // val sstatus = RegInit(UInt(XLEN.W), "h00000000".U)
443  val sstatusWmask = "hc6122".U(XLEN.W)
444  // Sstatus Write Mask
445  // -------------------------------------------------------
446  //    19           9   5     2
447  // 0  1100 0000 0001 0010 0010
448  // 0  c    0    1    2    2
449  // -------------------------------------------------------
450  val sstatusRmask = sstatusWmask | "h8000000300018000".U
451  // Sstatus Read Mask = (SSTATUS_WMASK | (0xf << 13) | (1ull << 63) | (3ull << 32))
452  // stvec: {BASE (WARL), MODE (WARL)} where mode is 0 or 1
453  val stvecMask = ~(0x2.U(XLEN.W))
454  val stvec = RegInit(UInt(XLEN.W), 0.U)
455  // val sie = RegInit(0.U(XLEN.W))
456  val sieMask = "h222".U & mideleg
457  val sipMask = "h222".U & mideleg
458  val sipWMask = "h2".U(XLEN.W) // ssip is writeable in smode
459  val satp = if(EnbaleTlbDebug) RegInit(UInt(XLEN.W), "h8000000000087fbe".U) else RegInit(0.U(XLEN.W))
460  // val satp = RegInit(UInt(XLEN.W), "h8000000000087fbe".U) // only use for tlb naive debug
461  // val satpMask = "h80000fffffffffff".U(XLEN.W) // disable asid, mode can only be 8 / 0
462  // TODO: use config to control the length of asid
463  // val satpMask = "h8fffffffffffffff".U(XLEN.W) // enable asid, mode can only be 8 / 0
464  val satpMask = Cat("h8".U(Satp_Mode_len.W), satp_part_wmask(Satp_Asid_len, AsidLength), satp_part_wmask(Satp_Addr_len, PAddrBits-12))
465  val sepc = RegInit(UInt(XLEN.W), 0.U)
466  // Page 60 in riscv-priv: The low bit of sepc (sepc[0]) is always zero.
467  val sepcMask = ~(0x1.U(XLEN.W))
468  val scause = RegInit(UInt(XLEN.W), 0.U)
469  val stval = Reg(UInt(XLEN.W))
470  val sscratch = RegInit(UInt(XLEN.W), 0.U)
471  val scounteren = RegInit(UInt(XLEN.W), 0.U)
472
473  // sbpctl
474  // Bits 0-7: {LOOP, RAS, SC, TAGE, BIM, BTB, uBTB}
475  val sbpctl = RegInit(UInt(XLEN.W), "h7f".U)
476  csrio.customCtrl.bp_ctrl.ubtb_enable := sbpctl(0)
477  csrio.customCtrl.bp_ctrl.btb_enable  := sbpctl(1)
478  csrio.customCtrl.bp_ctrl.bim_enable  := sbpctl(2)
479  csrio.customCtrl.bp_ctrl.tage_enable := sbpctl(3)
480  csrio.customCtrl.bp_ctrl.sc_enable   := sbpctl(4)
481  csrio.customCtrl.bp_ctrl.ras_enable  := sbpctl(5)
482  csrio.customCtrl.bp_ctrl.loop_enable := sbpctl(6)
483
484  // spfctl Bit 0: L1I Cache Prefetcher Enable
485  // spfctl Bit 1: L2Cache Prefetcher Enable
486  // spfctl Bit 2: L1D Cache Prefetcher Enable
487  // spfctl Bit 3: L1D train prefetch on hit
488  // spfctl Bit 4: L1D prefetch enable agt
489  // spfctl Bit 5: L1D prefetch enable pht
490  // spfctl Bit [9:6]: L1D prefetch active page threshold
491  // spfctl Bit [15:10]: L1D prefetch active page stride
492  // turn off L2 BOP, turn on L1 SMS by default
493  val spfctl = RegInit(UInt(XLEN.W), Seq(
494    0 << 17,    // L2 pf store only [17] init: false
495    1 << 16,    // L1D pf enable stride [16] init: true
496    30 << 10,   // L1D active page stride [15:10] init: 30
497    12 << 6,    // L1D active page threshold [9:6] init: 12
498    1  << 5,    // L1D enable pht [5] init: true
499    1  << 4,    // L1D enable agt [4] init: true
500    0  << 3,    // L1D train on hit [3] init: false
501    1  << 2,    // L1D pf enable [2] init: true
502    1  << 1,    // L2 pf enable [1] init: true
503    1  << 0,    // L1I pf enable [0] init: true
504  ).reduce(_|_).U(XLEN.W))
505  csrio.customCtrl.l1I_pf_enable := spfctl(0)
506  csrio.customCtrl.l2_pf_enable := spfctl(1)
507  csrio.customCtrl.l1D_pf_enable := spfctl(2)
508  csrio.customCtrl.l1D_pf_train_on_hit := spfctl(3)
509  csrio.customCtrl.l1D_pf_enable_agt := spfctl(4)
510  csrio.customCtrl.l1D_pf_enable_pht := spfctl(5)
511  csrio.customCtrl.l1D_pf_active_threshold := spfctl(9, 6)
512  csrio.customCtrl.l1D_pf_active_stride := spfctl(15, 10)
513  csrio.customCtrl.l1D_pf_enable_stride := spfctl(16)
514  csrio.customCtrl.l2_pf_store_only := spfctl(17)
515
516  // sfetchctl Bit 0: L1I Cache Parity check enable
517  val sfetchctl = RegInit(UInt(XLEN.W), "b0".U)
518  csrio.customCtrl.icache_parity_enable := sfetchctl(0)
519
520  // sdsid: Differentiated Services ID
521  val sdsid = RegInit(UInt(XLEN.W), 0.U)
522  csrio.customCtrl.dsid := sdsid
523
524  // slvpredctl: load violation predict settings
525  // Default reset period: 2^16
526  // Why this number: reset more frequently while keeping the overhead low
527  // Overhead: extra two redirections in every 64K cycles => ~0.1% overhead
528  val slvpredctl = RegInit(UInt(XLEN.W), "h60".U)
529  csrio.customCtrl.lvpred_disable := slvpredctl(0)
530  csrio.customCtrl.no_spec_load := slvpredctl(1)
531  csrio.customCtrl.storeset_wait_store := slvpredctl(2)
532  csrio.customCtrl.storeset_no_fast_wakeup := slvpredctl(3)
533  csrio.customCtrl.lvpred_timeout := slvpredctl(8, 4)
534
535  //  smblockctl: memory block configurations
536  //  +------------------------------+---+----+----+-----+--------+
537  //  |XLEN-1                       8| 7 | 6  | 5  |  4  |3      0|
538  //  +------------------------------+---+----+----+-----+--------+
539  //  |           Reserved           | O | CE | SP | LVC |   Th   |
540  //  +------------------------------+---+----+----+-----+--------+
541  //  Description:
542  //  Bit 3-0   : Store buffer flush threshold (Th).
543  //  Bit 4     : Enable load violation check after reset (LVC).
544  //  Bit 5     : Enable soft-prefetch after reset (SP).
545  //  Bit 6     : Enable cache error after reset (CE).
546  //  Bit 7     : Enable uncache write outstanding (O).
547  //  Others    : Reserved.
548
549  val smblockctl_init_val =
550    (0xf & StoreBufferThreshold) |
551    (EnableLdVioCheckAfterReset.toInt << 4) |
552    (EnableSoftPrefetchAfterReset.toInt << 5) |
553    (EnableCacheErrorAfterReset.toInt << 6)
554    (EnableUncacheWriteOutstanding.toInt << 7)
555  val smblockctl = RegInit(UInt(XLEN.W), smblockctl_init_val.U)
556  csrio.customCtrl.sbuffer_threshold := smblockctl(3, 0)
557  // bits 4: enable load load violation check
558  csrio.customCtrl.ldld_vio_check_enable := smblockctl(4)
559  csrio.customCtrl.soft_prefetch_enable := smblockctl(5)
560  csrio.customCtrl.cache_error_enable := smblockctl(6)
561  csrio.customCtrl.uncache_write_outstanding_enable := smblockctl(7)
562
563  println("CSR smblockctl init value:")
564  println("  Store buffer replace threshold: " + StoreBufferThreshold)
565  println("  Enable ld-ld vio check after reset: " + EnableLdVioCheckAfterReset)
566  println("  Enable soft prefetch after reset: " + EnableSoftPrefetchAfterReset)
567  println("  Enable cache error after reset: " + EnableCacheErrorAfterReset)
568  println("  Enable uncache write outstanding: " + EnableUncacheWriteOutstanding)
569
570  val srnctl = RegInit(UInt(XLEN.W), "h7".U)
571  csrio.customCtrl.fusion_enable := srnctl(0)
572  csrio.customCtrl.svinval_enable := srnctl(1)
573  csrio.customCtrl.wfi_enable := srnctl(2)
574
575  val tlbBundle = Wire(new TlbCsrBundle)
576  tlbBundle.satp.apply(satp)
577
578  csrio.tlb := tlbBundle
579
580  // User-Level CSRs
581  val uepc = Reg(UInt(XLEN.W))
582
583  // fcsr
584  class FcsrStruct extends Bundle {
585    val reserved = UInt((XLEN-3-5).W)
586    val frm = UInt(3.W)
587    val fflags = UInt(5.W)
588    assert(this.getWidth == XLEN)
589  }
590  val fcsr = RegInit(0.U(XLEN.W))
591  // set mstatus->sd and mstatus->fs when true
592  val csrw_dirty_fp_state = WireInit(false.B)
593
594  def frm_wfn(wdata: UInt): UInt = {
595    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
596    csrw_dirty_fp_state := true.B
597    fcsrOld.frm := wdata(2,0)
598    fcsrOld.asUInt
599  }
600  def frm_rfn(rdata: UInt): UInt = rdata(7,5)
601
602  def fflags_wfn(update: Boolean)(wdata: UInt): UInt = {
603    val fcsrOld = fcsr.asTypeOf(new FcsrStruct)
604    val fcsrNew = WireInit(fcsrOld)
605    csrw_dirty_fp_state := true.B
606    if (update) {
607      fcsrNew.fflags := wdata(4,0) | fcsrOld.fflags
608    } else {
609      fcsrNew.fflags := wdata(4,0)
610    }
611    fcsrNew.asUInt
612  }
613  def fflags_rfn(rdata:UInt): UInt = rdata(4,0)
614
615  def fcsr_wfn(wdata: UInt): UInt = {
616    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
617    csrw_dirty_fp_state := true.B
618    Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags)
619  }
620
621  val fcsrMapping = Map(
622    MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn(update = false), rfn = fflags_rfn),
623    MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn),
624    MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn)
625  )
626
627  // Hart Priviledge Mode
628  val priviledgeMode = RegInit(UInt(2.W), ModeM)
629
630  //val perfEventscounten = List.fill(nrPerfCnts)(RegInit(false(Bool())))
631  // Perf Counter
632  val nrPerfCnts = 29  // 3...31
633  val priviledgeModeOH = UIntToOH(priviledgeMode)
634  val perfEventscounten = RegInit(0.U.asTypeOf(Vec(nrPerfCnts, Bool())))
635  val perfCnts   = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W)))
636  val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++
637                   List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++
638                   List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++
639                   List.fill(5)(RegInit("hc0300c0300".U(XLEN.W)))
640  for (i <-0 until nrPerfCnts) {
641    perfEventscounten(i) := (Cat(perfEvents(i)(62),perfEvents(i)(61),(perfEvents(i)(61,60))) & priviledgeModeOH).orR
642  }
643
644  val hpmEvents = Wire(Vec(numPCntHc * coreParams.L2NBanks, new PerfEvent))
645  for (i <- 0 until numPCntHc * coreParams.L2NBanks) {
646    hpmEvents(i) := csrio.perf.perfEventsHc(i)
647  }
648
649  val csrevents = perfEvents.slice(24, 29)
650  val hpm_hc = HPerfMonitor(csrevents, hpmEvents)
651  val mcountinhibit = RegInit(0.U(XLEN.W))
652  val mcycle = RegInit(0.U(XLEN.W))
653  mcycle := mcycle + 1.U
654  val minstret = RegInit(0.U(XLEN.W))
655  val perf_events = csrio.perf.perfEventsFrontend ++
656                    csrio.perf.perfEventsCtrl ++
657                    csrio.perf.perfEventsLsu ++
658                    hpm_hc.getPerf
659  minstret := minstret + RegNext(csrio.perf.retiredInstr)
660  for(i <- 0 until 29){
661    perfCnts(i) := Mux(mcountinhibit(i+3) | !perfEventscounten(i), perfCnts(i), perfCnts(i) + perf_events(i).value)
662  }
663
664  // CSR reg map
665  val basicPrivMapping = Map(
666
667    //--- User Trap Setup ---
668    // MaskedRegMap(Ustatus, ustatus),
669    // MaskedRegMap(Uie, uie, 0.U, MaskedRegMap.Unwritable),
670    // MaskedRegMap(Utvec, utvec),
671
672    //--- User Trap Handling ---
673    // MaskedRegMap(Uscratch, uscratch),
674    // MaskedRegMap(Uepc, uepc),
675    // MaskedRegMap(Ucause, ucause),
676    // MaskedRegMap(Utval, utval),
677    // MaskedRegMap(Uip, uip),
678
679    //--- User Counter/Timers ---
680    // MaskedRegMap(Cycle, cycle),
681    // MaskedRegMap(Time, time),
682    // MaskedRegMap(Instret, instret),
683
684    //--- Supervisor Trap Setup ---
685    MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask),
686    // MaskedRegMap(Sedeleg, Sedeleg),
687    // MaskedRegMap(Sideleg, Sideleg),
688    MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask),
689    MaskedRegMap(Stvec, stvec, stvecMask, MaskedRegMap.NoSideEffect, stvecMask),
690    MaskedRegMap(Scounteren, scounteren),
691
692    //--- Supervisor Trap Handling ---
693    MaskedRegMap(Sscratch, sscratch),
694    MaskedRegMap(Sepc, sepc, sepcMask, MaskedRegMap.NoSideEffect, sepcMask),
695    MaskedRegMap(Scause, scause),
696    MaskedRegMap(Stval, stval),
697    MaskedRegMap(Sip, mip.asUInt, sipWMask, MaskedRegMap.Unwritable, sipMask),
698
699    //--- Supervisor Protection and Translation ---
700    MaskedRegMap(Satp, satp, satpMask, MaskedRegMap.NoSideEffect, satpMask),
701
702    //--- Supervisor Custom Read/Write Registers
703    MaskedRegMap(Sbpctl, sbpctl),
704    MaskedRegMap(Spfctl, spfctl),
705    MaskedRegMap(Sfetchctl, sfetchctl),
706    MaskedRegMap(Sdsid, sdsid),
707    MaskedRegMap(Slvpredctl, slvpredctl),
708    MaskedRegMap(Smblockctl, smblockctl),
709    MaskedRegMap(Srnctl, srnctl),
710
711    //--- Machine Information Registers ---
712    MaskedRegMap(Mvendorid, mvendorid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
713    MaskedRegMap(Marchid, marchid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
714    MaskedRegMap(Mimpid, mimpid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
715    MaskedRegMap(Mhartid, mhartid, 0.U(XLEN.W), MaskedRegMap.Unwritable),
716    MaskedRegMap(Mconfigptr, mconfigptr, 0.U(XLEN.W), MaskedRegMap.Unwritable),
717
718    //--- Machine Trap Setup ---
719    MaskedRegMap(Mstatus, mstatus, mstatusWMask, mstatusUpdateSideEffect, mstatusMask),
720    MaskedRegMap(Misa, misa, 0.U, MaskedRegMap.Unwritable), // now whole misa is unchangeable
721    MaskedRegMap(Medeleg, medeleg, "hb3ff".U(XLEN.W)),
722    MaskedRegMap(Mideleg, mideleg, "h222".U(XLEN.W)),
723    MaskedRegMap(Mie, mie),
724    MaskedRegMap(Mtvec, mtvec, mtvecMask, MaskedRegMap.NoSideEffect, mtvecMask),
725    MaskedRegMap(Mcounteren, mcounteren),
726
727    //--- Machine Trap Handling ---
728    MaskedRegMap(Mscratch, mscratch),
729    MaskedRegMap(Mepc, mepc, mepcMask, MaskedRegMap.NoSideEffect, mepcMask),
730    MaskedRegMap(Mcause, mcause),
731    MaskedRegMap(Mtval, mtval),
732    MaskedRegMap(Mip, mip.asUInt, 0.U(XLEN.W), MaskedRegMap.Unwritable),
733
734    //--- Trigger ---
735    MaskedRegMap(Tselect, tselectPhy, WritableMask, WriteTselect),
736    MaskedRegMap(Tdata1, tdata1Phy(tselectPhy), WritableMask, WriteTdata1, WritableMask, ReadTdata1),
737    MaskedRegMap(Tdata2, tdata2Phy(tselectPhy)),
738    MaskedRegMap(Tinfo, tinfo, 0.U(XLEN.W), MaskedRegMap.Unwritable),
739    MaskedRegMap(Tcontrol, tControlPhy, tcontrolWriteMask),
740
741    //--- Debug Mode ---
742    MaskedRegMap(Dcsr, dcsr, dcsrMask, dcsrUpdateSideEffect),
743    MaskedRegMap(Dpc, dpc),
744    MaskedRegMap(Dscratch, dscratch),
745    MaskedRegMap(Dscratch1, dscratch1),
746    MaskedRegMap(Mcountinhibit, mcountinhibit),
747    MaskedRegMap(Mcycle, mcycle),
748    MaskedRegMap(Minstret, minstret),
749  )
750
751  val perfCntMapping = (0 until 29).map(i => {Map(
752    MaskedRegMap(addr = Mhpmevent3 +i,
753                 reg  = perfEvents(i),
754                 wmask = "hf87fff3fcff3fcff".U(XLEN.W)),
755    MaskedRegMap(addr = Mhpmcounter3 +i,
756                 reg  = perfCnts(i))
757  )}).fold(Map())((a,b) => a ++ b)
758  // TODO: mechanism should be implemented later
759  // val MhpmcounterStart = Mhpmcounter3
760  // val MhpmeventStart   = Mhpmevent3
761  // for (i <- 0 until nrPerfCnts) {
762  //   perfCntMapping += MaskedRegMap(MhpmcounterStart + i, perfCnts(i))
763  //   perfCntMapping += MaskedRegMap(MhpmeventStart + i, perfEvents(i))
764  // }
765
766  val cacheopRegs = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
767    name -> RegInit(0.U(attribute("width").toInt.W))
768  }}
769  val cacheopMapping = CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
770    MaskedRegMap(
771      Scachebase + attribute("offset").toInt,
772      cacheopRegs(name)
773    )
774  }}
775
776  val mapping = basicPrivMapping ++
777                perfCntMapping ++
778                pmpMapping ++
779                pmaMapping ++
780                (if (HasFPU) fcsrMapping else Nil) ++
781                (if (HasCustomCSRCacheOp) cacheopMapping else Nil)
782
783  val addr = src2(11, 0)
784  val csri = ZeroExt(src2(16, 12), XLEN)
785  val rdata = Wire(UInt(XLEN.W))
786  val wdata = LookupTree(func, List(
787    CSROpType.wrt  -> src1,
788    CSROpType.set  -> (rdata | src1),
789    CSROpType.clr  -> (rdata & (~src1).asUInt),
790    CSROpType.wrti -> csri,
791    CSROpType.seti -> (rdata | csri),
792    CSROpType.clri -> (rdata & (~csri).asUInt)
793  ))
794
795  val addrInPerfCnt = (addr >= Mcycle.U) && (addr <= Mhpmcounter31.U) ||
796    (addr >= Mcountinhibit.U) && (addr <= Mhpmevent31.U) ||
797    addr === Mip.U
798  csrio.isPerfCnt := addrInPerfCnt && valid && func =/= CSROpType.jmp
799
800  // satp wen check
801  val satpLegalMode = (wdata.asTypeOf(new SatpStruct).mode===0.U) || (wdata.asTypeOf(new SatpStruct).mode===8.U)
802
803  // csr access check, special case
804  val tvmNotPermit = (priviledgeMode === ModeS && mstatusStruct.tvm.asBool)
805  val accessPermitted = !(addr === Satp.U && tvmNotPermit)
806  csrio.disableSfence := tvmNotPermit
807
808  // general CSR wen check
809  val wen = valid && CSROpType.needAccess(func) && (addr=/=Satp.U || satpLegalMode)
810  val dcsrPermitted = dcsrPermissionCheck(addr, false.B, debugMode)
811  val triggerPermitted = triggerPermissionCheck(addr, true.B, debugMode) // todo dmode
812  val modePermitted = csrAccessPermissionCheck(addr, false.B, priviledgeMode) && dcsrPermitted && triggerPermitted
813  val perfcntPermitted = perfcntPermissionCheck(addr, priviledgeMode, mcounteren, scounteren)
814  val permitted = Mux(addrInPerfCnt, perfcntPermitted, modePermitted) && accessPermitted
815
816  MaskedRegMap.generate(mapping, addr, rdata, wen && permitted, wdata)
817  io.out.bits.data := rdata
818  io.out.bits.uop := io.in.bits.uop
819  io.out.bits.uop.cf := cfOut
820  io.out.bits.uop.ctrl.flushPipe := flushPipe
821
822  // send distribute csr a w signal
823  csrio.customCtrl.distribute_csr.w.valid := wen && permitted
824  csrio.customCtrl.distribute_csr.w.bits.data := wdata
825  csrio.customCtrl.distribute_csr.w.bits.addr := addr
826
827  // Fix Mip/Sip write
828  val fixMapping = Map(
829    MaskedRegMap(Mip, mipReg.asUInt, mipFixMask),
830    MaskedRegMap(Sip, mipReg.asUInt, sipWMask, MaskedRegMap.NoSideEffect, sipMask)
831  )
832  val rdataFix = Wire(UInt(XLEN.W))
833  val wdataFix = LookupTree(func, List(
834    CSROpType.wrt  -> src1,
835    CSROpType.set  -> (rdataFix | src1),
836    CSROpType.clr  -> (rdataFix & (~src1).asUInt),
837    CSROpType.wrti -> csri,
838    CSROpType.seti -> (rdataFix | csri),
839    CSROpType.clri -> (rdataFix & (~csri).asUInt)
840  ))
841  MaskedRegMap.generate(fixMapping, addr, rdataFix, wen && permitted, wdataFix)
842
843  when (RegNext(csrio.fpu.fflags.valid)) {
844    fcsr := fflags_wfn(update = true)(RegNext(csrio.fpu.fflags.bits))
845  }
846  // set fs and sd in mstatus
847  when (csrw_dirty_fp_state || RegNext(csrio.fpu.dirty_fs)) {
848    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
849    mstatusNew.fs := "b11".U
850    mstatusNew.sd := true.B
851    mstatus := mstatusNew.asUInt
852  }
853  csrio.fpu.frm := fcsr.asTypeOf(new FcsrStruct).frm
854
855
856  // Trigger Ctrl
857  csrio.customCtrl.trigger_enable := tdata1Phy.map{t =>
858    def tdata1 = t.asTypeOf(new TdataBundle)
859    tdata1.m && priviledgeMode === ModeM ||
860    tdata1.s && priviledgeMode === ModeS || tdata1.u && priviledgeMode === ModeU
861  }
862  csrio.customCtrl.frontend_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) === I_Trigger)
863  csrio.customCtrl.mem_trigger.t.valid := RegNext(wen && (addr === Tdata1.U || addr === Tdata2.U) && TypeLookup(tselectPhy) =/= I_Trigger)
864  XSDebug(csrio.customCtrl.trigger_enable.asUInt.orR, p"Debug Mode: At least 1 trigger is enabled," +
865    p"trigger enable is ${Binary(csrio.customCtrl.trigger_enable.asUInt)}\n")
866
867  // CSR inst decode
868  val isEbreak = addr === privEbreak && func === CSROpType.jmp
869  val isEcall  = addr === privEcall  && func === CSROpType.jmp
870  val isMret   = addr === privMret   && func === CSROpType.jmp
871  val isSret   = addr === privSret   && func === CSROpType.jmp
872  val isUret   = addr === privUret   && func === CSROpType.jmp
873  val isDret   = addr === privDret   && func === CSROpType.jmp
874  val isWFI    = func === CSROpType.wfi
875
876  XSDebug(wen, "csr write: pc %x addr %x rdata %x wdata %x func %x\n", cfIn.pc, addr, rdata, wdata, func)
877  XSDebug(wen, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", cfIn.pc, mstatus, mideleg , medeleg, priviledgeMode)
878
879  // Illegal priviledged operation list
880  val illegalMret = valid && isMret && priviledgeMode < ModeM
881  val illegalSret = valid && isSret && priviledgeMode < ModeS
882  val illegalSModeSret = valid && isSret && priviledgeMode === ModeS && mstatusStruct.tsr.asBool
883  // When TW=1, then if WFI is executed in any less-privileged mode,
884  // and it does not complete within an implementation-specific, bounded time limit,
885  // the WFI instruction causes an illegal instruction exception.
886  // The time limit may always be 0, in which case WFI always causes
887  // an illegal instruction exception in less-privileged modes when TW=1.
888  val illegalWFI = valid && isWFI && priviledgeMode < ModeM && mstatusStruct.tw === 1.U
889
890  // Illegal priviledged instruction check
891  val isIllegalAddr = valid && CSROpType.needAccess(func) && MaskedRegMap.isIllegalAddr(mapping, addr)
892  val isIllegalAccess = wen && !permitted
893  val isIllegalPrivOp = illegalMret || illegalSret || illegalSModeSret || illegalWFI
894
895  // expose several csr bits for tlb
896  tlbBundle.priv.mxr   := mstatusStruct.mxr.asBool
897  tlbBundle.priv.sum   := mstatusStruct.sum.asBool
898  tlbBundle.priv.imode := priviledgeMode
899  tlbBundle.priv.dmode := Mux(debugMode && dcsr.asTypeOf(new DcsrStruct).mprven, ModeM, Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpp, priviledgeMode))
900
901  // Branch control
902  val retTarget = Wire(UInt(VAddrBits.W))
903  val resetSatp = addr === Satp.U && wen // write to satp will cause the pipeline be flushed
904  flushPipe := resetSatp || (valid && func === CSROpType.jmp && !isEcall && !isEbreak)
905
906  retTarget := DontCare
907  // val illegalEret = TODO
908
909  when (valid && isDret) {
910    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
911    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
912    val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct))
913    val debugModeNew = WireInit(debugMode)
914    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.
915    mstatus := mstatusNew.asUInt
916    priviledgeMode := dcsrNew.prv
917    retTarget := dpc(VAddrBits-1, 0)
918    debugModeNew := false.B
919    debugIntrEnable := true.B
920    debugMode := debugModeNew
921    XSDebug("Debug Mode: Dret executed, returning to %x.", retTarget)
922  }
923
924  when (valid && isMret && !illegalMret) {
925    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
926    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
927    mstatusNew.ie.m := mstatusOld.pie.m
928    priviledgeMode := mstatusOld.mpp
929    mstatusNew.pie.m := true.B
930    mstatusNew.mpp := ModeU
931    when (mstatusOld.mpp =/= ModeM) { mstatusNew.mprv := 0.U }
932    mstatus := mstatusNew.asUInt
933    // lr := false.B
934    retTarget := mepc(VAddrBits-1, 0)
935  }
936
937  when (valid && isSret && !illegalSret && !illegalSModeSret) {
938    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
939    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
940    mstatusNew.ie.s := mstatusOld.pie.s
941    priviledgeMode := Cat(0.U(1.W), mstatusOld.spp)
942    mstatusNew.pie.s := true.B
943    mstatusNew.spp := ModeU
944    mstatus := mstatusNew.asUInt
945    when (mstatusOld.spp =/= ModeM) { mstatusNew.mprv := 0.U }
946    // lr := false.B
947    retTarget := sepc(VAddrBits-1, 0)
948  }
949
950  when (valid && isUret) {
951    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
952    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
953    // mstatusNew.mpp.m := ModeU //TODO: add mode U
954    mstatusNew.ie.u := mstatusOld.pie.u
955    priviledgeMode := ModeU
956    mstatusNew.pie.u := true.B
957    mstatus := mstatusNew.asUInt
958    retTarget := uepc(VAddrBits-1, 0)
959  }
960
961  io.in.ready := true.B
962  io.out.valid := valid
963
964  val ebreakCauseException = (priviledgeMode === ModeM && dcsrData.ebreakm) || (priviledgeMode === ModeS && dcsrData.ebreaks) || (priviledgeMode === ModeU && dcsrData.ebreaku)
965
966  val csrExceptionVec = WireInit(cfIn.exceptionVec)
967  csrExceptionVec(breakPoint) := io.in.valid && isEbreak && (ebreakCauseException || debugMode)
968  csrExceptionVec(ecallM) := priviledgeMode === ModeM && io.in.valid && isEcall
969  csrExceptionVec(ecallS) := priviledgeMode === ModeS && io.in.valid && isEcall
970  csrExceptionVec(ecallU) := priviledgeMode === ModeU && io.in.valid && isEcall
971  // Trigger an illegal instr exception when:
972  // * unimplemented csr is being read/written
973  // * csr access is illegal
974  csrExceptionVec(illegalInstr) := isIllegalAddr || isIllegalAccess || isIllegalPrivOp
975  cfOut.exceptionVec := csrExceptionVec
976
977  XSDebug(io.in.valid && isEbreak, s"Debug Mode: an Ebreak is executed, ebreak cause exception ? ${ebreakCauseException}\n")
978
979  /**
980    * Exception and Intr
981    */
982  val ideleg =  (mideleg & mip.asUInt)
983  def priviledgedEnableDetect(x: Bool): Bool = Mux(x, ((priviledgeMode === ModeS) && mstatusStruct.ie.s) || (priviledgeMode < ModeS),
984    ((priviledgeMode === ModeM) && mstatusStruct.ie.m) || (priviledgeMode < ModeM))
985
986  val debugIntr = csrio.externalInterrupt.debug & debugIntrEnable
987  XSDebug(debugIntr, "Debug Mode: debug interrupt is asserted and valid!")
988  // send interrupt information to ROB
989  val intrVecEnable = Wire(Vec(12, Bool()))
990  val disableInterrupt = debugMode || (dcsrData.step && !dcsrData.stepie)
991  intrVecEnable.zip(ideleg.asBools).map{case(x,y) => x := priviledgedEnableDetect(y) && !disableInterrupt}
992  val intrVec = Cat(debugIntr && !debugMode, (mie(11,0) & mip.asUInt & intrVecEnable.asUInt))
993  val intrBitSet = intrVec.orR
994  csrio.interrupt := intrBitSet
995  // Page 45 in RISC-V Privileged Specification
996  // The WFI instruction can also be executed when interrupts are disabled. The operation of WFI
997  // must be unaffected by the global interrupt bits in mstatus (MIE and SIE) and the delegation
998  // register mideleg, but should honor the individual interrupt enables (e.g, MTIE).
999  csrio.wfi_event := debugIntr || (mie(11, 0) & mip.asUInt).orR
1000  mipWire.t.m := csrio.externalInterrupt.mtip
1001  mipWire.s.m := csrio.externalInterrupt.msip
1002  mipWire.e.m := csrio.externalInterrupt.meip
1003  mipWire.e.s := csrio.externalInterrupt.seip
1004
1005  // interrupts
1006  val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(intrVec(i), i.U, sum))
1007  val raiseIntr = csrio.exception.valid && csrio.exception.bits.isInterrupt
1008  val ivmEnable = tlbBundle.priv.imode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1009  val iexceptionPC = Mux(ivmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc)
1010  val dvmEnable = tlbBundle.priv.dmode < ModeM && satp.asTypeOf(new SatpStruct).mode === 8.U
1011  val dexceptionPC = Mux(dvmEnable, SignExt(csrio.exception.bits.uop.cf.pc, XLEN), csrio.exception.bits.uop.cf.pc)
1012  XSDebug(raiseIntr, "interrupt: pc=0x%x, %d\n", dexceptionPC, intrNO)
1013  val raiseDebugIntr = intrNO === IRQ_DEBUG.U && raiseIntr
1014
1015  // exceptions
1016  val raiseException = csrio.exception.valid && !csrio.exception.bits.isInterrupt
1017  val hasInstrPageFault = csrio.exception.bits.uop.cf.exceptionVec(instrPageFault) && raiseException
1018  val hasLoadPageFault = csrio.exception.bits.uop.cf.exceptionVec(loadPageFault) && raiseException
1019  val hasStorePageFault = csrio.exception.bits.uop.cf.exceptionVec(storePageFault) && raiseException
1020  val hasStoreAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(storeAddrMisaligned) && raiseException
1021  val hasLoadAddrMisaligned = csrio.exception.bits.uop.cf.exceptionVec(loadAddrMisaligned) && raiseException
1022  val hasInstrAccessFault = csrio.exception.bits.uop.cf.exceptionVec(instrAccessFault) && raiseException
1023  val hasLoadAccessFault = csrio.exception.bits.uop.cf.exceptionVec(loadAccessFault) && raiseException
1024  val hasStoreAccessFault = csrio.exception.bits.uop.cf.exceptionVec(storeAccessFault) && raiseException
1025  val hasbreakPoint = csrio.exception.bits.uop.cf.exceptionVec(breakPoint) && raiseException
1026  val hasSingleStep = csrio.exception.bits.uop.ctrl.singleStep && raiseException
1027  val hasTriggerHit = (csrio.exception.bits.uop.cf.trigger.hit) && raiseException
1028
1029  XSDebug(hasSingleStep, "Debug Mode: single step exception\n")
1030  XSDebug(hasTriggerHit, p"Debug Mode: trigger hit, is frontend? ${Binary(csrio.exception.bits.uop.cf.trigger.frontendHit.asUInt)} " +
1031    p"backend hit vec ${Binary(csrio.exception.bits.uop.cf.trigger.backendHit.asUInt)}\n")
1032
1033  val raiseExceptionVec = csrio.exception.bits.uop.cf.exceptionVec
1034  val regularExceptionNO = ExceptionNO.priorities.foldRight(0.U)((i: Int, sum: UInt) => Mux(raiseExceptionVec(i), i.U, sum))
1035  val exceptionNO = Mux(hasSingleStep || hasTriggerHit, 3.U, regularExceptionNO)
1036  val causeNO = (raiseIntr << (XLEN-1)).asUInt | Mux(raiseIntr, intrNO, exceptionNO)
1037
1038  val raiseExceptionIntr = csrio.exception.valid
1039
1040  val raiseDebugExceptionIntr = !debugMode && (hasbreakPoint || raiseDebugIntr || hasSingleStep || hasTriggerHit && triggerAction) // TODO
1041  val ebreakEnterParkLoop = debugMode && raiseExceptionIntr
1042
1043  XSDebug(raiseExceptionIntr, "int/exc: pc %x int (%d):%x exc: (%d):%x\n",
1044    dexceptionPC, intrNO, intrVec, exceptionNO, raiseExceptionVec.asUInt
1045  )
1046  XSDebug(raiseExceptionIntr,
1047    "pc %x mstatus %x mideleg %x medeleg %x mode %x\n",
1048    dexceptionPC,
1049    mstatus,
1050    mideleg,
1051    medeleg,
1052    priviledgeMode
1053  )
1054
1055  // mtval write logic
1056  // Due to timing reasons of memExceptionVAddr, we delay the write of mtval and stval
1057  val memExceptionAddr = SignExt(csrio.memExceptionVAddr, XLEN)
1058  val updateTval = VecInit(Seq(
1059    hasInstrPageFault,
1060    hasLoadPageFault,
1061    hasStorePageFault,
1062    hasInstrAccessFault,
1063    hasLoadAccessFault,
1064    hasStoreAccessFault,
1065    hasLoadAddrMisaligned,
1066    hasStoreAddrMisaligned
1067  )).asUInt.orR
1068  when (RegNext(RegNext(updateTval))) {
1069      val tval = Mux(
1070        RegNext(RegNext(hasInstrPageFault || hasInstrAccessFault)),
1071        RegNext(RegNext(Mux(
1072          csrio.exception.bits.uop.cf.crossPageIPFFix,
1073          SignExt(csrio.exception.bits.uop.cf.pc + 2.U, XLEN),
1074          iexceptionPC
1075        ))),
1076        memExceptionAddr
1077    )
1078    when (RegNext(priviledgeMode === ModeM)) {
1079      mtval := tval
1080    }.otherwise {
1081      stval := tval
1082    }
1083  }
1084
1085  val debugTrapTarget = Mux(!isEbreak && debugMode, 0x38020808.U, 0x38020800.U) // 0x808 is when an exception occurs in debug mode prog buf exec
1086  val deleg = Mux(raiseIntr, mideleg , medeleg)
1087  // val delegS = ((deleg & (1 << (causeNO & 0xf))) != 0) && (priviledgeMode < ModeM);
1088  val delegS = deleg(causeNO(3,0)) && (priviledgeMode < ModeM)
1089  val clearTval = !updateTval || raiseIntr
1090  val isXRet = io.in.valid && func === CSROpType.jmp && !isEcall && !isEbreak
1091
1092  // ctrl block will use theses later for flush
1093  val isXRetFlag = RegInit(false.B)
1094  when (DelayN(io.redirectIn.valid, 5)) {
1095    isXRetFlag := false.B
1096  }.elsewhen (isXRet) {
1097    isXRetFlag := true.B
1098  }
1099  csrio.isXRet := isXRetFlag
1100  val retTargetReg = RegEnable(retTarget, isXRet)
1101
1102  val tvec = Mux(delegS, stvec, mtvec)
1103  val tvecBase = tvec(VAddrBits - 1, 2)
1104  // XRet sends redirect instead of Flush and isXRetFlag is true.B before redirect.valid.
1105  // ROB sends exception at T0 while CSR receives at T2.
1106  // We add a RegNext here and trapTarget is valid at T3.
1107  csrio.trapTarget := RegEnable(Mux(isXRetFlag,
1108    retTargetReg,
1109    Mux(raiseDebugExceptionIntr || ebreakEnterParkLoop, debugTrapTarget,
1110      // When MODE=Vectored, all synchronous exceptions into M/S mode
1111      // cause the pc to be set to the address in the BASE field, whereas
1112      // interrupts cause the pc to be set to the address in the BASE field
1113      // plus four times the interrupt cause number.
1114      Cat(tvecBase + Mux(tvec(0) && raiseIntr, causeNO(3, 0), 0.U), 0.U(2.W))
1115  )), isXRetFlag || csrio.exception.valid)
1116
1117  when (raiseExceptionIntr) {
1118    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
1119    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
1120    val dcsrNew = WireInit(dcsr.asTypeOf(new DcsrStruct))
1121    val debugModeNew = WireInit(debugMode)
1122
1123    when (raiseDebugExceptionIntr) {
1124      when (raiseDebugIntr) {
1125        debugModeNew := true.B
1126        mstatusNew.mprv := false.B
1127        dpc := iexceptionPC
1128        dcsrNew.cause := 3.U
1129        dcsrNew.prv := priviledgeMode
1130        priviledgeMode := ModeM
1131        XSDebug(raiseDebugIntr, "Debug Mode: Trap to %x at pc %x\n", debugTrapTarget, dpc)
1132      }.elsewhen ((hasbreakPoint || hasSingleStep) && !debugMode) {
1133        // ebreak or ss in running hart
1134        debugModeNew := true.B
1135        dpc := iexceptionPC
1136        dcsrNew.cause := Mux(hasTriggerHit, 2.U, Mux(hasbreakPoint, 1.U, 4.U))
1137        dcsrNew.prv := priviledgeMode // TODO
1138        priviledgeMode := ModeM
1139        mstatusNew.mprv := false.B
1140      }
1141      dcsr := dcsrNew.asUInt
1142      debugIntrEnable := false.B
1143    }.elsewhen (debugMode) {
1144      //do nothing
1145    }.elsewhen (delegS) {
1146      scause := causeNO
1147      sepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1148      mstatusNew.spp := priviledgeMode
1149      mstatusNew.pie.s := mstatusOld.ie.s
1150      mstatusNew.ie.s := false.B
1151      priviledgeMode := ModeS
1152      when (clearTval) { stval := 0.U }
1153    }.otherwise {
1154      mcause := causeNO
1155      mepc := Mux(hasInstrPageFault || hasInstrAccessFault, iexceptionPC, dexceptionPC)
1156      mstatusNew.mpp := priviledgeMode
1157      mstatusNew.pie.m := mstatusOld.ie.m
1158      mstatusNew.ie.m := false.B
1159      priviledgeMode := ModeM
1160      when (clearTval) { mtval := 0.U }
1161    }
1162    mstatus := mstatusNew.asUInt
1163    debugMode := debugModeNew
1164  }
1165
1166  XSDebug(raiseExceptionIntr && delegS, "sepc is written!!! pc:%x\n", cfIn.pc)
1167
1168  // Distributed CSR update req
1169  //
1170  // For now we use it to implement customized cache op
1171  // It can be delayed if necessary
1172
1173  val delayedUpdate0 = DelayN(csrio.distributedUpdate(0), 2)
1174  val delayedUpdate1 = DelayN(csrio.distributedUpdate(1), 2)
1175  val distributedUpdateValid = delayedUpdate0.w.valid || delayedUpdate1.w.valid
1176  val distributedUpdateAddr = Mux(delayedUpdate0.w.valid,
1177    delayedUpdate0.w.bits.addr,
1178    delayedUpdate1.w.bits.addr
1179  )
1180  val distributedUpdateData = Mux(delayedUpdate0.w.valid,
1181    delayedUpdate0.w.bits.data,
1182    delayedUpdate1.w.bits.data
1183  )
1184
1185  assert(!(delayedUpdate0.w.valid && delayedUpdate1.w.valid))
1186
1187  when(distributedUpdateValid){
1188    // cacheopRegs can be distributed updated
1189    CacheInstrucion.CacheInsRegisterList.map{case (name, attribute) => {
1190      when((Scachebase + attribute("offset").toInt).U === distributedUpdateAddr){
1191        cacheopRegs(name) := distributedUpdateData
1192      }
1193    }}
1194  }
1195
1196  // Cache error debug support
1197  if(HasCustomCSRCacheOp){
1198    val cache_error_decoder = Module(new CSRCacheErrorDecoder)
1199    cache_error_decoder.io.encoded_cache_error := cacheopRegs("CACHE_ERROR")
1200  }
1201
1202  // Implicit add reset values for mepc[0] and sepc[0]
1203  // TODO: rewrite mepc and sepc using a struct-like style with the LSB always being 0
1204  when (RegNext(RegNext(reset.asBool) && !reset.asBool)) {
1205    mepc := Cat(mepc(XLEN - 1, 1), 0.U(1.W))
1206    sepc := Cat(sepc(XLEN - 1, 1), 0.U(1.W))
1207  }
1208
1209  def readWithScala(addr: Int): UInt = mapping(addr)._1
1210
1211  val difftestIntrNO = Mux(raiseIntr, causeNO, 0.U)
1212
1213  // Always instantiate basic difftest modules.
1214  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1215    val difftest = Module(new DifftestArchEvent)
1216    difftest.io.clock := clock
1217    difftest.io.coreid := csrio.hartId
1218    difftest.io.intrNO := RegNext(RegNext(RegNext(difftestIntrNO)))
1219    difftest.io.cause  := RegNext(RegNext(RegNext(Mux(csrio.exception.valid, causeNO, 0.U))))
1220    difftest.io.exceptionPC := RegNext(RegNext(RegNext(dexceptionPC)))
1221    if (env.EnableDifftest) {
1222      difftest.io.exceptionInst := RegNext(RegNext(RegNext(csrio.exception.bits.uop.cf.instr)))
1223    }
1224  }
1225
1226  // Always instantiate basic difftest modules.
1227  if (env.AlwaysBasicDiff || env.EnableDifftest) {
1228    val difftest = Module(new DifftestCSRState)
1229    difftest.io.clock := clock
1230    difftest.io.coreid := csrio.hartId
1231    difftest.io.priviledgeMode := priviledgeMode
1232    difftest.io.mstatus := mstatus
1233    difftest.io.sstatus := mstatus & sstatusRmask
1234    difftest.io.mepc := mepc
1235    difftest.io.sepc := sepc
1236    difftest.io.mtval:= mtval
1237    difftest.io.stval:= stval
1238    difftest.io.mtvec := mtvec
1239    difftest.io.stvec := stvec
1240    difftest.io.mcause := mcause
1241    difftest.io.scause := scause
1242    difftest.io.satp := satp
1243    difftest.io.mip := mipReg
1244    difftest.io.mie := mie
1245    difftest.io.mscratch := mscratch
1246    difftest.io.sscratch := sscratch
1247    difftest.io.mideleg := mideleg
1248    difftest.io.medeleg := medeleg
1249  }
1250
1251  if(env.AlwaysBasicDiff || env.EnableDifftest) {
1252    val difftest = Module(new DifftestDebugMode)
1253    difftest.io.clock := clock
1254    difftest.io.coreid := csrio.hartId
1255    difftest.io.debugMode := debugMode
1256    difftest.io.dcsr := dcsr
1257    difftest.io.dpc := dpc
1258    difftest.io.dscratch0 := dscratch
1259    difftest.io.dscratch1 := dscratch1
1260  }
1261}
1262
1263class PFEvent(implicit p: Parameters) extends XSModule with HasCSRConst  {
1264  val io = IO(new Bundle {
1265    val distribute_csr = Flipped(new DistributedCSRIO())
1266    val hpmevent = Output(Vec(29, UInt(XLEN.W)))
1267  })
1268
1269  val w = io.distribute_csr.w
1270
1271  val perfEvents = List.fill(8)(RegInit("h0000000000".U(XLEN.W))) ++
1272                   List.fill(8)(RegInit("h4010040100".U(XLEN.W))) ++
1273                   List.fill(8)(RegInit("h8020080200".U(XLEN.W))) ++
1274                   List.fill(5)(RegInit("hc0300c0300".U(XLEN.W)))
1275
1276  val perfEventMapping = (0 until 29).map(i => {Map(
1277    MaskedRegMap(addr = Mhpmevent3 +i,
1278                 reg  = perfEvents(i),
1279                 wmask = "hf87fff3fcff3fcff".U(XLEN.W))
1280  )}).fold(Map())((a,b) => a ++ b)
1281
1282  val rdata = Wire(UInt(XLEN.W))
1283  MaskedRegMap.generate(perfEventMapping, w.bits.addr, rdata, w.valid, w.bits.data)
1284  for(i <- 0 until 29){
1285    io.hpmevent(i) := perfEvents(i)
1286  }
1287}
1288