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