xref: /XiangShan/src/main/scala/xiangshan/backend/fu/CSR.scala (revision 68eeafa8a2229450b289b44a3e3644291d5b8e3e)
1package xiangshan.backend.fu
2
3import chisel3._
4import chisel3.ExcitingUtils.ConnectionType
5import chisel3.util._
6import chisel3.util.experimental.BoringUtils
7import fpu.Fflags
8import noop.MMUIO
9import utils._
10import xiangshan._
11import xiangshan.backend._
12import xiangshan.backend.fu.FunctionUnit._
13import utils.XSDebug
14
15trait HasCSRConst {
16  // User Trap Setup
17  val Ustatus       = 0x000
18  val Uie           = 0x004
19  val Utvec         = 0x005
20
21  // User Trap Handling
22  val Uscratch      = 0x040
23  val Uepc          = 0x041
24  val Ucause        = 0x042
25  val Utval         = 0x043
26  val Uip           = 0x044
27
28  // User Floating-Point CSRs (not implemented)
29  val Fflags        = 0x001
30  val Frm           = 0x002
31  val Fcsr          = 0x003
32
33  // User Counter/Timers
34  val Cycle         = 0xC00
35  val Time          = 0xC01
36  val Instret       = 0xC02
37
38  // Supervisor Trap Setup
39  val Sstatus       = 0x100
40  val Sedeleg       = 0x102
41  val Sideleg       = 0x103
42  val Sie           = 0x104
43  val Stvec         = 0x105
44  val Scounteren    = 0x106
45
46  // Supervisor Trap Handling
47  val Sscratch      = 0x140
48  val Sepc          = 0x141
49  val Scause        = 0x142
50  val Stval         = 0x143
51  val Sip           = 0x144
52
53  // Supervisor Protection and Translation
54  val Satp          = 0x180
55
56  // Machine Information Registers
57  val Mvendorid     = 0xF11
58  val Marchid       = 0xF12
59  val Mimpid        = 0xF13
60  val Mhartid       = 0xF14
61
62  // Machine Trap Setup
63  val Mstatus       = 0x300
64  val Misa          = 0x301
65  val Medeleg       = 0x302
66  val Mideleg       = 0x303
67  val Mie           = 0x304
68  val Mtvec         = 0x305
69  val Mcounteren    = 0x306
70
71  // Machine Trap Handling
72  val Mscratch      = 0x340
73  val Mepc          = 0x341
74  val Mcause        = 0x342
75  val Mtval         = 0x343
76  val Mip           = 0x344
77
78  // Machine Memory Protection
79  // TBD
80  val Pmpcfg0       = 0x3A0
81  val Pmpcfg1       = 0x3A1
82  val Pmpcfg2       = 0x3A2
83  val Pmpcfg3       = 0x3A3
84  val PmpaddrBase   = 0x3B0
85
86  // Machine Counter/Timers
87  // Currently, NOOP uses perfcnt csr set instead of standard Machine Counter/Timers
88  // 0xB80 - 0x89F are also used as perfcnt csr
89
90  // Machine Counter Setup (not implemented)
91  // Debug/Trace Registers (shared with Debug Mode) (not implemented)
92  // Debug Mode Registers (not implemented)
93
94  def privEcall = 0x000.U
95  def privMret  = 0x302.U
96  def privSret  = 0x102.U
97  def privUret  = 0x002.U
98
99  def ModeM     = 0x3.U
100  def ModeH     = 0x2.U
101  def ModeS     = 0x1.U
102  def ModeU     = 0x0.U
103
104  def IRQ_UEIP  = 0
105  def IRQ_SEIP  = 1
106  def IRQ_MEIP  = 3
107
108  def IRQ_UTIP  = 4
109  def IRQ_STIP  = 5
110  def IRQ_MTIP  = 7
111
112  def IRQ_USIP  = 8
113  def IRQ_SSIP  = 9
114  def IRQ_MSIP  = 11
115
116  val IntPriority = Seq(
117    IRQ_MEIP, IRQ_MSIP, IRQ_MTIP,
118    IRQ_SEIP, IRQ_SSIP, IRQ_STIP,
119    IRQ_UEIP, IRQ_USIP, IRQ_UTIP
120  )
121}
122
123trait HasExceptionNO {
124  def instrAddrMisaligned = 0
125  def instrAccessFault    = 1
126  def illegalInstr        = 2
127  def breakPoint          = 3
128  def loadAddrMisaligned  = 4
129  def loadAccessFault     = 5
130  def storeAddrMisaligned = 6
131  def storeAccessFault    = 7
132  def ecallU              = 8
133  def ecallS              = 9
134  def ecallM              = 11
135  def instrPageFault      = 12
136  def loadPageFault       = 13
137  def storePageFault      = 15
138
139  val ExcPriority = Seq(
140    breakPoint, // TODO: different BP has different priority
141    instrPageFault,
142    instrAccessFault,
143    illegalInstr,
144    instrAddrMisaligned,
145    ecallM, ecallS, ecallU,
146    storeAddrMisaligned,
147    loadAddrMisaligned,
148    storePageFault,
149    loadPageFault,
150    storeAccessFault,
151    loadAccessFault
152  )
153}
154
155class FpuCsrIO extends XSBundle {
156  val fflags = Output(new Fflags)
157  val isIllegal = Output(Bool())
158  val dirty_fs = Output(Bool())
159  val frm = Input(UInt(3.W))
160}
161
162class CSRIO extends FunctionUnitIO {
163  val cfIn = Input(new CtrlFlow)
164  val redirect = Output(new Redirect)
165  val redirectValid = Output(Bool())
166  val fpu_csr = Flipped(new FpuCsrIO)
167  val cfOut = Output(new CtrlFlow)
168  // from rob
169  val exception = Flipped(ValidIO(new MicroOp))
170  // for exception check
171  val instrValid = Input(Bool())
172  // for differential testing
173//  val intrNO = Output(UInt(XLEN.W))
174  val imemMMU = Flipped(new MMUIO)
175  val dmemMMU = Flipped(new MMUIO)
176  val wenFix = Output(Bool())
177}
178
179class CSR(implicit val p: XSConfig) extends FunctionUnit(csrCfg) with HasCSRConst{
180  val io = IO(new CSRIO)
181
182  io.cfOut := io.cfIn
183
184  val (valid, src1, src2, func) = (io.in.valid, io.in.bits.src1, io.in.bits.src2, io.in.bits.func)
185  def access(valid: Bool, src1: UInt, src2: UInt, func: UInt): UInt = {
186    this.valid := valid
187    this.src1 := src1
188    this.src2 := src2
189    this.func := func
190    io.out.bits
191  }
192
193  // CSR define
194
195  class Priv extends Bundle {
196    val m = Output(Bool())
197    val h = Output(Bool())
198    val s = Output(Bool())
199    val u = Output(Bool())
200  }
201
202  val csrNotImplemented = RegInit(UInt(XLEN.W), 0.U)
203
204  class MstatusStruct extends Bundle {
205    val sd = Output(UInt(1.W))
206    val pad1 = Output(UInt((XLEN-37).W))
207    val sxl = Output(UInt(2.W))
208    val uxl = Output(UInt(2.W))
209    val pad0 = Output(UInt(9.W))
210    val tsr = Output(UInt(1.W))
211    val tw = Output(UInt(1.W))
212    val tvm = Output(UInt(1.W))
213    val mxr = Output(UInt(1.W))
214    val sum = Output(UInt(1.W))
215    val mprv = Output(UInt(1.W))
216    val xs = Output(UInt(2.W))
217    val fs = Output(UInt(2.W))
218    val mpp = Output(UInt(2.W))
219    val hpp = Output(UInt(2.W))
220    val spp = Output(UInt(1.W))
221    val pie = new Priv
222    val ie = new Priv
223    assert(this.getWidth == XLEN)
224  }
225
226  class Interrupt extends Bundle {
227    val e = new Priv
228    val t = new Priv
229    val s = new Priv
230  }
231
232  // Machine-Level CSRs
233
234  val mtvec = RegInit(UInt(XLEN.W), 0.U)
235  val mcounteren = RegInit(UInt(XLEN.W), 0.U)
236  val mcause = RegInit(UInt(XLEN.W), 0.U)
237  val mtval = RegInit(UInt(XLEN.W), 0.U)
238  val mepc = Reg(UInt(XLEN.W))
239
240  val mie = RegInit(0.U(XLEN.W))
241  val mipWire = WireInit(0.U.asTypeOf(new Interrupt))
242  val mipReg  = RegInit(0.U.asTypeOf(new Interrupt).asUInt)
243  val mipFixMask = "h777".U
244  val mip = (mipWire.asUInt | mipReg).asTypeOf(new Interrupt)
245
246  def getMisaMxl(mxl: Int): UInt = (mxl.U << (XLEN-2)).asUInt()
247  def getMisaExt(ext: Char): UInt = (1.U << (ext.toInt - 'a'.toInt)).asUInt()
248  var extList = List('a', 's', 'i', 'u')
249  if(HasMExtension){ extList = extList :+ 'm'}
250  if(HasCExtension){ extList = extList :+ 'c'}
251  if(HasFPU){ extList = extList ++ List('f', 'd')}
252  val misaInitVal = getMisaMxl(2) | extList.foldLeft(0.U)((sum, i) => sum | getMisaExt(i)) //"h8000000000141105".U
253  val misa = RegInit(UInt(XLEN.W), misaInitVal)
254  // MXL = 2          | 0 | EXT = b 00 0000 0100 0001 0001 0000 0101
255  // (XLEN-1, XLEN-2) |   |(25, 0)  ZY XWVU TSRQ PONM LKJI HGFE DCBA
256
257  val mvendorid = RegInit(UInt(XLEN.W), 0.U) // this is a non-commercial implementation
258  val marchid = RegInit(UInt(XLEN.W), 0.U) // return 0 to indicate the field is not implemented
259  val mimpid = RegInit(UInt(XLEN.W), 0.U) // provides a unique encoding of the version of the processor implementation
260  val mhartid = RegInit(UInt(XLEN.W), 0.U) // the hardware thread running the code
261  val mstatus = RegInit(UInt(XLEN.W), "h00001800".U)
262  // val mstatus = RegInit(UInt(XLEN.W), "h8000c0100".U)
263  // mstatus Value Table
264  // | sd   |
265  // | pad1 |
266  // | sxl  | hardlinked to 10, use 00 to pass xv6 test
267  // | uxl  | hardlinked to 00
268  // | pad0 |
269  // | tsr  |
270  // | tw   |
271  // | tvm  |
272  // | mxr  |
273  // | sum  |
274  // | mprv |
275  // | xs   | 00 |
276  // | fs   |
277  // | mpp  | 00 |
278  // | hpp  | 00 |
279  // | spp  | 0 |
280  // | pie  | 0000 |
281  // | ie   | 0000 | uie hardlinked to 0, as N ext is not implemented
282  val mstatusStruct = mstatus.asTypeOf(new MstatusStruct)
283  def mstatusUpdateSideEffect(mstatus: UInt): UInt = {
284    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
285    val mstatusNew = Cat(mstatusOld.fs === "b11".U, mstatus(XLEN-2, 0))
286    mstatusNew
287  }
288
289  val medeleg = RegInit(UInt(XLEN.W), 0.U)
290  val mideleg = RegInit(UInt(XLEN.W), 0.U)
291  val mscratch = RegInit(UInt(XLEN.W), 0.U)
292
293  val pmpcfg0 = RegInit(UInt(XLEN.W), 0.U)
294  val pmpcfg1 = RegInit(UInt(XLEN.W), 0.U)
295  val pmpcfg2 = RegInit(UInt(XLEN.W), 0.U)
296  val pmpcfg3 = RegInit(UInt(XLEN.W), 0.U)
297  val pmpaddr0 = RegInit(UInt(XLEN.W), 0.U)
298  val pmpaddr1 = RegInit(UInt(XLEN.W), 0.U)
299  val pmpaddr2 = RegInit(UInt(XLEN.W), 0.U)
300  val pmpaddr3 = RegInit(UInt(XLEN.W), 0.U)
301
302  // Superviser-Level CSRs
303
304  // val sstatus = RegInit(UInt(XLEN.W), "h00000000".U)
305  val sstatusWmask = "hc6122".U
306  // Sstatus Write Mask
307  // -------------------------------------------------------
308  //    19           9   5     2
309  // 0  1100 0000 0001 0010 0010
310  // 0  c    0    1    2    2
311  // -------------------------------------------------------
312  val sstatusRmask = sstatusWmask | "h8000000300018000".U
313  // Sstatus Read Mask = (SSTATUS_WMASK | (0xf << 13) | (1ull << 63) | (3ull << 32))
314  val stvec = RegInit(UInt(XLEN.W), 0.U)
315  // val sie = RegInit(0.U(XLEN.W))
316  val sieMask = "h222".U & mideleg
317  val sipMask  = "h222".U & mideleg
318  //val satp = RegInit(UInt(XLEN.W), "h8000000000087fbe".U)
319  val satp = RegInit(UInt(XLEN.W), 0.U)
320  val sepc = RegInit(UInt(XLEN.W), 0.U)
321  val scause = RegInit(UInt(XLEN.W), 0.U)
322  val stval = Reg(UInt(XLEN.W))
323  val sscratch = RegInit(UInt(XLEN.W), 0.U)
324  val scounteren = RegInit(UInt(XLEN.W), 0.U)
325  BoringUtils.addSource(satp, "CSRSATP")
326
327  // User-Level CSRs
328  val uepc = Reg(UInt(XLEN.W))
329
330  // fcsr
331  class FcsrStruct extends Bundle{
332    val reserved = UInt((XLEN-3-5).W)
333    val frm = UInt(3.W)
334    val fflags = UInt(5.W)
335    assert(this.getWidth == XLEN)
336  }
337  val fcsr = RegInit(0.U(XLEN.W))
338  // set mstatus->sd and mstatus->fs when true
339  val csrw_dirty_fp_state = WireInit(false.B)
340
341  def frm_wfn(wdata: UInt): UInt = {
342    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
343    csrw_dirty_fp_state := true.B
344    fcsrOld.frm := wdata(2,0)
345    fcsrOld.asUInt()
346  }
347  def frm_rfn(rdata: UInt): UInt = rdata(7,5)
348
349  def fflags_wfn(wdata: UInt): UInt = {
350    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
351    csrw_dirty_fp_state := true.B
352    fcsrOld.fflags := wdata(4,0)
353    fcsrOld.asUInt()
354  }
355  def fflags_rfn(rdata:UInt): UInt = rdata(4,0)
356
357  def fcsr_wfn(wdata: UInt): UInt = {
358    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
359    csrw_dirty_fp_state := true.B
360    Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags)
361  }
362
363  val fcsrMapping = Map(
364    MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn, rfn = fflags_rfn),
365    MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn),
366    MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn)
367  )
368
369  // Atom LR/SC Control Bits
370//  val setLr = WireInit(Bool(), false.B)
371//  val setLrVal = WireInit(Bool(), false.B)
372//  val setLrAddr = WireInit(UInt(AddrBits.W), DontCare) //TODO : need check
373//  val lr = RegInit(Bool(), false.B)
374//  val lrAddr = RegInit(UInt(AddrBits.W), 0.U)
375//  BoringUtils.addSink(setLr, "set_lr")
376//  BoringUtils.addSink(setLrVal, "set_lr_val")
377//  BoringUtils.addSink(setLrAddr, "set_lr_addr")
378//  BoringUtils.addSource(lr, "lr")
379//  BoringUtils.addSource(lrAddr, "lr_addr")
380//
381//  when(setLr){
382//    lr := setLrVal
383//    lrAddr := setLrAddr
384//  }
385
386  // Hart Priviledge Mode
387  val priviledgeMode = RegInit(UInt(2.W), ModeM)
388
389  // perfcnt
390  val hasPerfCnt = !p.FPGAPlatform
391  val nrPerfCnts = if (hasPerfCnt) 0x80 else 0x3
392  val perfCnts = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W)))
393  val perfCntsLoMapping = (0 until nrPerfCnts).map(i => MaskedRegMap(0xb00 + i, perfCnts(i)))
394  val perfCntsHiMapping = (0 until nrPerfCnts).map(i => MaskedRegMap(0xb80 + i, perfCnts(i)(63, 32)))
395
396  // CSR reg map
397  val mapping = Map(
398
399    // User Trap Setup
400    // MaskedRegMap(Ustatus, ustatus),
401    // MaskedRegMap(Uie, uie, 0.U, MaskedRegMap.Unwritable),
402    // MaskedRegMap(Utvec, utvec),
403
404    // User Trap Handling
405    // MaskedRegMap(Uscratch, uscratch),
406    // MaskedRegMap(Uepc, uepc),
407    // MaskedRegMap(Ucause, ucause),
408    // MaskedRegMap(Utval, utval),
409    // MaskedRegMap(Uip, uip),
410
411    // User Counter/Timers
412    // MaskedRegMap(Cycle, cycle),
413    // MaskedRegMap(Time, time),
414    // MaskedRegMap(Instret, instret),
415
416    // Supervisor Trap Setup
417    MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask),
418
419    // MaskedRegMap(Sedeleg, Sedeleg),
420    // MaskedRegMap(Sideleg, Sideleg),
421    MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask),
422    MaskedRegMap(Stvec, stvec),
423    MaskedRegMap(Scounteren, scounteren),
424
425    // Supervisor Trap Handling
426    MaskedRegMap(Sscratch, sscratch),
427    MaskedRegMap(Sepc, sepc),
428    MaskedRegMap(Scause, scause),
429    MaskedRegMap(Stval, stval),
430    MaskedRegMap(Sip, mip.asUInt, sipMask, MaskedRegMap.Unwritable, sipMask),
431
432    // Supervisor Protection and Translation
433    MaskedRegMap(Satp, satp),
434
435    // Machine Information Registers
436    MaskedRegMap(Mvendorid, mvendorid, 0.U, MaskedRegMap.Unwritable),
437    MaskedRegMap(Marchid, marchid, 0.U, MaskedRegMap.Unwritable),
438    MaskedRegMap(Mimpid, mimpid, 0.U, MaskedRegMap.Unwritable),
439    MaskedRegMap(Mhartid, mhartid, 0.U, MaskedRegMap.Unwritable),
440
441    // Machine Trap Setup
442    // MaskedRegMap(Mstatus, mstatus, "hffffffffffffffee".U, (x=>{printf("mstatus write: %x time: %d\n", x, GTimer()); x})),
443    MaskedRegMap(Mstatus, mstatus, "hffffffffffffffff".U, mstatusUpdateSideEffect),
444    MaskedRegMap(Misa, misa), // now MXL, EXT is not changeable
445    MaskedRegMap(Medeleg, medeleg, "hbbff".U),
446    MaskedRegMap(Mideleg, mideleg, "h222".U),
447    MaskedRegMap(Mie, mie),
448    MaskedRegMap(Mtvec, mtvec),
449    MaskedRegMap(Mcounteren, mcounteren),
450
451    // Machine Trap Handling
452    MaskedRegMap(Mscratch, mscratch),
453    MaskedRegMap(Mepc, mepc),
454    MaskedRegMap(Mcause, mcause),
455    MaskedRegMap(Mtval, mtval),
456    MaskedRegMap(Mip, mip.asUInt, 0.U, MaskedRegMap.Unwritable),
457
458    // Machine Memory Protection
459    MaskedRegMap(Pmpcfg0, pmpcfg0),
460    MaskedRegMap(Pmpcfg1, pmpcfg1),
461    MaskedRegMap(Pmpcfg2, pmpcfg2),
462    MaskedRegMap(Pmpcfg3, pmpcfg3),
463    MaskedRegMap(PmpaddrBase + 0, pmpaddr0),
464    MaskedRegMap(PmpaddrBase + 1, pmpaddr1),
465    MaskedRegMap(PmpaddrBase + 2, pmpaddr2),
466    MaskedRegMap(PmpaddrBase + 3, pmpaddr3)
467
468  ) ++
469    perfCntsLoMapping ++ (if (XLEN == 32) perfCntsHiMapping else Nil) ++
470    (if(HasFPU) fcsrMapping else Nil)
471
472  val addr = src2(11, 0)
473  val rdata = Wire(UInt(XLEN.W))
474  val csri = ZeroExt(io.cfIn.instr(19,15), XLEN) //unsigned imm for csri. [TODO]
475  val wdata = LookupTree(func, List(
476    CSROpType.wrt  -> src1,
477    CSROpType.set  -> (rdata | src1),
478    CSROpType.clr  -> (rdata & (~src1).asUInt()),
479    CSROpType.wrti -> csri,//TODO: csri --> src2
480    CSROpType.seti -> (rdata | csri),
481    CSROpType.clri -> (rdata & (~csri).asUInt())
482  ))
483
484  val wen = valid && func =/= CSROpType.jmp
485  // Debug(){when(wen){printf("[CSR] addr %x wdata %x func %x rdata %x\n", addr, wdata, func, rdata)}}
486  MaskedRegMap.generate(mapping, addr, rdata, wen, wdata)
487  val isIllegalAddr = MaskedRegMap.isIllegalAddr(mapping, addr)
488  val resetSatp = addr === Satp.U && wen // write to satp will cause the pipeline be flushed
489  io.out.bits := rdata
490
491  // Fix Mip/Sip write
492  val fixMapping = Map(
493    MaskedRegMap(Mip, mipReg.asUInt, mipFixMask),
494    MaskedRegMap(Sip, mipReg.asUInt, sipMask, MaskedRegMap.NoSideEffect, sipMask)
495  )
496  val rdataDummy = Wire(UInt(XLEN.W))
497  MaskedRegMap.generate(fixMapping, addr, rdataDummy, wen, wdata)
498
499  when(io.fpu_csr.fflags.asUInt() =/= 0.U){
500    fcsr := fflags_wfn(io.fpu_csr.fflags.asUInt())
501  }
502  // set fs and sd in mstatus
503  when(csrw_dirty_fp_state || io.fpu_csr.dirty_fs){
504    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
505    mstatusNew.fs := "b11".U
506    mstatusNew.sd := true.B
507    mstatus := mstatusNew.asUInt()
508  }
509  io.fpu_csr.frm := fcsr.asTypeOf(new FcsrStruct).frm
510
511  // CSR inst decode
512  val ret = Wire(Bool())
513  val isEcall = addr === privEcall && func === CSROpType.jmp
514  val isMret = addr === privMret   && func === CSROpType.jmp
515  val isSret = addr === privSret   && func === CSROpType.jmp
516  val isUret = addr === privUret   && func === CSROpType.jmp
517
518  XSDebug(wen, "csr write: pc %x addr %x rdata %x wdata %x func %x\n", io.cfIn.pc, addr, rdata, wdata, func)
519  XSDebug(wen, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", io.cfIn.pc, mstatus, mideleg , medeleg, priviledgeMode)
520
521
522  // MMU Permission Check
523
524  // def MMUPermissionCheck(ptev: Bool, pteu: Bool): Bool = ptev && !(priviledgeMode === ModeU && !pteu) && !(priviledgeMode === ModeS && pteu && mstatusStruct.sum.asBool)
525  // def MMUPermissionCheckLoad(ptev: Bool, pteu: Bool): Bool = ptev && !(priviledgeMode === ModeU && !pteu) && !(priviledgeMode === ModeS && pteu && mstatusStruct.sum.asBool) && (pter || (mstatusStruct.mxr && ptex))
526  // imem
527  // val imemPtev = true.B
528  // val imemPteu = true.B
529  // val imemPtex = true.B
530  // val imemReq = true.B
531  // val imemPermissionCheckPassed = MMUPermissionCheck(imemPtev, imemPteu)
532  // val hasInstrPageFault = imemReq && !(imemPermissionCheckPassed && imemPtex)
533  // assert(!hasInstrPageFault)
534
535  // dmem
536  // val dmemPtev = true.B
537  // val dmemPteu = true.B
538  // val dmemReq = true.B
539  // val dmemPermissionCheckPassed = MMUPermissionCheck(dmemPtev, dmemPteu)
540  // val dmemIsStore = true.B
541
542  // val hasLoadPageFault  = dmemReq && !dmemIsStore && !(dmemPermissionCheckPassed)
543  // val hasStorePageFault = dmemReq &&  dmemIsStore && !(dmemPermissionCheckPassed)
544  // assert(!hasLoadPageFault)
545  // assert(!hasStorePageFault)
546
547  //TODO: Havn't test if io.dmemMMU.priviledgeMode is correct yet
548  io.imemMMU.priviledgeMode := priviledgeMode
549  io.dmemMMU.priviledgeMode := Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpp, priviledgeMode)
550  io.imemMMU.status_sum := mstatusStruct.sum.asBool
551  io.dmemMMU.status_sum := mstatusStruct.sum.asBool
552  io.imemMMU.status_mxr := DontCare
553  io.dmemMMU.status_mxr := mstatusStruct.mxr.asBool
554
555  val hasInstrPageFault = io.exception.bits.cf.exceptionVec(instrPageFault) && io.exception.valid
556  val hasLoadPageFault = io.dmemMMU.loadPF
557  val hasStorePageFault = io.dmemMMU.storePF
558  val hasStoreAddrMisaligned = io.exception.bits.cf.exceptionVec(storeAddrMisaligned)
559  val hasLoadAddrMisaligned = io.exception.bits.cf.exceptionVec(loadAddrMisaligned)
560
561  when(hasInstrPageFault || hasLoadPageFault || hasStorePageFault){
562    val tval = Mux(
563      hasInstrPageFault,
564      Mux(
565        io.exception.bits.cf.crossPageIPFFix,
566        SignExt(io.exception.bits.cf.pc + 2.U, XLEN),
567        SignExt(io.exception.bits.cf.pc, XLEN)
568      ),
569      SignExt(io.dmemMMU.addr, XLEN)
570    )
571    when(priviledgeMode === ModeM){
572      mtval := tval
573    }.otherwise{
574      stval := tval
575    }
576  }
577
578  val lsuAddr = WireInit(0.U(64.W))
579  BoringUtils.addSink(lsuAddr, "LSUADDR")
580  when(hasLoadAddrMisaligned || hasStoreAddrMisaligned)
581  {
582    mtval := SignExt(lsuAddr, XLEN)
583  }
584
585  // Exception and Intr
586
587  // interrupts
588
589  val ideleg =  (mideleg & mip.asUInt)
590  def priviledgedEnableDetect(x: Bool): Bool = Mux(x, ((priviledgeMode === ModeS) && mstatusStruct.ie.s) || (priviledgeMode < ModeS),
591    ((priviledgeMode === ModeM) && mstatusStruct.ie.m) || (priviledgeMode < ModeM))
592
593  val intrVecEnable = Wire(Vec(12, Bool()))
594  intrVecEnable.zip(ideleg.asBools).map{case(x,y) => x := priviledgedEnableDetect(y)}
595  val intrVec = mie(11,0) & mip.asUInt & intrVecEnable.asUInt
596  val intrBitSet = intrVec.orR()
597  ExcitingUtils.addSource(intrBitSet, "intrBitSetIDU")
598  val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(intrVec(i), i.U, sum))
599  val raiseIntr = intrBitSet && io.exception.valid
600  XSDebug(raiseIntr, "interrupt: pc=0x%x, %d\n", io.exception.bits.cf.pc, intrNO)
601
602  val mtip = WireInit(false.B)
603  val meip = WireInit(false.B)
604  BoringUtils.addSink(mtip, "mtip")
605  BoringUtils.addSink(meip, "meip")
606  mipWire.t.m := mtip
607  mipWire.e.m := meip
608
609  // exceptions
610  val csrExceptionVec = Wire(Vec(16, Bool()))
611  csrExceptionVec.map(_ := false.B)
612  csrExceptionVec(ecallM) := priviledgeMode === ModeM && io.in.valid && isEcall
613  csrExceptionVec(ecallS) := priviledgeMode === ModeS && io.in.valid && isEcall
614  csrExceptionVec(ecallU) := priviledgeMode === ModeU && io.in.valid && isEcall
615  // csrExceptionVec(instrPageFault) := hasInstrPageFault
616  csrExceptionVec(illegalInstr) := isIllegalAddr && wen // Trigger an illegal instr exception when unimplemented csr is being read/written
617  csrExceptionVec(loadPageFault) := hasLoadPageFault
618  csrExceptionVec(storePageFault) := hasStorePageFault
619  val iduExceptionVec = io.cfIn.exceptionVec
620  val exceptionVec = csrExceptionVec.asUInt() | iduExceptionVec.asUInt()
621  io.cfOut.exceptionVec.zipWithIndex.map{case (e, i) => e := exceptionVec(i) }
622  io.wenFix := DontCare
623
624  val raiseExceptionVec = io.exception.bits.cf.exceptionVec.asUInt()
625  val exceptionNO = ExcPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(raiseExceptionVec(i), i.U, sum))
626  val causeNO = (raiseIntr << (XLEN-1)).asUInt() | Mux(raiseIntr, intrNO, exceptionNO)
627  val difftestIntrNO = Mux(raiseIntr, causeNO, 0.U)
628  ExcitingUtils.addSource(difftestIntrNO, "difftestIntrNOfromCSR")
629
630  val raiseExceptionIntr = io.exception.valid
631  val retTarget = Wire(UInt(VAddrBits.W))
632  val trapTarget = Wire(UInt(VAddrBits.W))
633  ExcitingUtils.addSource(trapTarget, "trapTarget")
634  io.redirect := DontCare
635  io.redirectValid := (valid && func === CSROpType.jmp && !isEcall) || resetSatp
636  //TODO: use pred pc instead pc+4
637  io.redirect.target := Mux(resetSatp, io.cfIn.pc+4.U, retTarget)
638
639  XSDebug(io.redirectValid, "redirect to %x, pc=%x\n", io.redirect.target, io.cfIn.pc)
640
641  XSDebug(raiseExceptionIntr, "int/exc: pc %x int (%d):%x exc: (%d):%x\n",io.exception.bits.cf.pc, intrNO, io.exception.bits.cf.intrVec.asUInt, exceptionNO, raiseExceptionVec.asUInt)
642  XSDebug(raiseExceptionIntr, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", io.exception.bits.cf.pc, mstatus, mideleg, medeleg, priviledgeMode)
643
644  XSDebug(io.redirectValid, "redirect to %x\n", io.redirect.target)
645
646  XSDebug(valid && isMret, "Mret to %x!\n[CSR] int/exc: pc %x int (%d):%x exc: (%d):%x\n",retTarget, io.cfIn.pc, intrNO, io.cfIn.intrVec.asUInt, exceptionNO, raiseExceptionVec.asUInt)
647  XSDebug(valid && isMret, "[MST] pc %x mstatus %x mideleg %x medeleg %x mode %x\n", io.cfIn.pc, mstatus, mideleg , medeleg, priviledgeMode)
648
649  XSDebug(valid && isSret, "Sret to %x!\n[CSR] int/exc: pc %x int (%d):%x exc: (%d):%x\n",retTarget, io.cfIn.pc, intrNO, io.cfIn.intrVec.asUInt, exceptionNO, raiseExceptionVec.asUInt)
650  XSDebug(valid && isSret, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", io.cfIn.pc, mstatus, mideleg , medeleg, priviledgeMode)
651  XSDebug(io.redirectValid, "Redirect %x raiseExcepIntr:%d valid:%d instrValid:%x \n", io.redirect.target, raiseExceptionIntr, valid, io.instrValid)
652
653  // Branch control
654
655  val deleg = Mux(raiseIntr, mideleg , medeleg)
656  // val delegS = ((deleg & (1 << (causeNO & 0xf))) != 0) && (priviledgeMode < ModeM);
657  val delegS = (deleg(causeNO(3,0))) && (priviledgeMode < ModeM)
658  val tvalWen = !(hasInstrPageFault || hasLoadPageFault || hasStorePageFault || hasLoadAddrMisaligned || hasStoreAddrMisaligned) || raiseIntr // in noop-riscv64, no exception will come together with PF
659
660  ret := isMret || isSret || isUret
661  trapTarget := Mux(delegS, stvec, mtvec)(VAddrBits-1, 0)
662  retTarget := DontCare
663  // val illegalEret = TODO
664
665  when (valid && isMret) {
666    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
667    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
668    // mstatusNew.mpp.m := ModeU //TODO: add mode U
669    mstatusNew.ie.m := mstatusOld.pie.m
670    priviledgeMode := mstatusOld.mpp
671    mstatusNew.pie.m := true.B
672    mstatusNew.mpp := ModeU
673    mstatus := mstatusNew.asUInt
674//    lr := false.B
675    retTarget := mepc(VAddrBits-1, 0)
676  }
677
678  when (valid && isSret) {
679    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
680    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
681    // mstatusNew.mpp.m := ModeU //TODO: add mode U
682    mstatusNew.ie.s := mstatusOld.pie.s
683    priviledgeMode := Cat(0.U(1.W), mstatusOld.spp)
684    mstatusNew.pie.s := true.B
685    mstatusNew.spp := ModeU
686    mstatus := mstatusNew.asUInt
687//    lr := false.B
688    retTarget := sepc(VAddrBits-1, 0)
689  }
690
691  when (valid && isUret) {
692    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
693    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
694    // mstatusNew.mpp.m := ModeU //TODO: add mode U
695    mstatusNew.ie.u := mstatusOld.pie.u
696    priviledgeMode := ModeU
697    mstatusNew.pie.u := true.B
698    mstatus := mstatusNew.asUInt
699    retTarget := uepc(VAddrBits-1, 0)
700  }
701
702  when (raiseExceptionIntr) {
703    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
704    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
705
706    when (delegS) {
707      scause := causeNO
708      sepc := SignExt(io.exception.bits.cf.pc, XLEN)
709      mstatusNew.spp := priviledgeMode
710      mstatusNew.pie.s := mstatusOld.ie.s
711      mstatusNew.ie.s := false.B
712      priviledgeMode := ModeS
713      when(tvalWen){stval := 0.U} // TODO: should not use =/=
714      // printf("[*] mstatusNew.spp %x\n", mstatusNew.spp)
715      // trapTarget := stvec(VAddrBits-1. 0)
716    }.otherwise {
717      mcause := causeNO
718      mepc := SignExt(io.exception.bits.cf.pc, XLEN)
719      mstatusNew.mpp := priviledgeMode
720      mstatusNew.pie.m := mstatusOld.ie.m
721      mstatusNew.ie.m := false.B
722      priviledgeMode := ModeM
723      when(tvalWen){mtval := 0.U} // TODO: should not use =/=
724      // trapTarget := mtvec(VAddrBits-1. 0)
725    }
726    // mstatusNew.pie.m := LookupTree(priviledgeMode, List(
727    //   ModeM -> mstatusOld.ie.m,
728    //   ModeH -> mstatusOld.ie.h, //ERROR
729    //   ModeS -> mstatusOld.ie.s,
730    //   ModeU -> mstatusOld.ie.u
731    // ))
732
733    mstatus := mstatusNew.asUInt
734  }
735
736  io.in.ready := true.B
737  io.out.valid := valid
738
739
740  XSDebug(io.redirectValid, "Rediret %x raiseExcepIntr:%d isSret:%d retTarget:%x sepc:%x delegs:%d deleg:%x cfInpc:%x valid:%d instrValid:%x \n",
741    io.redirect.target, raiseExceptionIntr, isSret, retTarget, sepc, delegS, deleg, io.cfIn.pc, valid, io.instrValid)
742  XSDebug(raiseExceptionIntr && delegS, "Red(%d, %x) raiseExcepIntr:%d isSret:%d retTarget:%x sepc:%x delegs:%d deleg:%x cfInpc:%x valid:%d instrValid:%x \n",
743    io.redirectValid, io.redirect.target, raiseExceptionIntr, isSret, retTarget, sepc, delegS, deleg, io.cfIn.pc, valid, io.instrValid)
744  XSDebug(raiseExceptionIntr && delegS, "sepc is writen!!! pc:%x\n", io.cfIn.pc)
745
746
747  // perfcnt
748
749  val perfCntList = Map(
750//    "Mcycle"      -> (0xb00, "perfCntCondMcycle"     ),
751//    "Minstret"    -> (0xb02, "perfCntCondMinstret"   ),
752    "MbpInstr"    -> (0xb03, "perfCntCondMbpInstr"   ),
753    "MbpRight"    -> (0xb04, "perfCntCondMbpRight"   ),
754    "MbpWrong"    -> (0xb05, "perfCntCondMbpWrong"   ),
755    "MbpBRight"   -> (0xb06, "perfCntCondMbpBRight"   ),
756    "MbpBWrong"   -> (0xb07, "perfCntCondMbpBWrong"   ),
757    "MbpJRight"   -> (0xb08, "perfCntCondMbpJRight"   ),
758    "MbpJWrong"   -> (0xb09, "perfCntCondMbpJWrong"   ),
759    "MbpIRight"   -> (0xb0a, "perfCntCondMbpIRight"   ),
760    "MbpIWrong"   -> (0xb0b, "perfCntCondMbpIWrong"   ),
761    "MbpRRight"   -> (0xb0c, "perfCntCondMbpRRight"   ),
762    "MbpRWrong"   -> (0xb0d, "perfCntCondMbpRWrong"   )
763//    "Custom1"     -> (0xb1b, "Custom1"             ),
764//    "Custom2"     -> (0xb1c, "Custom2"             ),
765//    "Custom3"     -> (0xb1d, "Custom3"             ),
766//    "Custom4"     -> (0xb1e, "Custom4"             ),
767//    "Custom5"     -> (0xb1f, "Custom5"             ),
768//    "Custom6"     -> (0xb20, "Custom6"             ),
769//    "Custom7"     -> (0xb21, "Custom7"             ),
770//    "Custom8"     -> (0xb22, "Custom8"             ),
771//    "Ml2cacheHit" -> (0xb23, "perfCntCondMl2cacheHit")
772  )
773  val perfCntCond = List.fill(0x80)(WireInit(false.B))
774  (perfCnts zip perfCntCond).map { case (c, e) => when (e) { c := c + 1.U } }
775
776//  ExcitingUtils.addSource(WireInit(true.B), "perfCntCondMcycle", ConnectionType.Perf)
777  perfCntList.foreach {
778    case (_, (address, boringId)) =>
779      if(hasPerfCnt){
780        ExcitingUtils.addSink(perfCntCond(address & 0x7f), boringId, ConnectionType.Perf)
781      }
782//      if (!hasPerfCnt) {
783//        // do not enable perfcnts except for Mcycle and Minstret
784//        if (address != perfCntList("Mcycle")._1 && address != perfCntList("Minstret")._1) {
785//          perfCntCond(address & 0x7f) := false.B
786//        }
787//      }
788  }
789
790  val xstrap = WireInit(false.B)
791  BoringUtils.addSink(xstrap, "XSTRAP")
792  def readWithScala(addr: Int): UInt = mapping(addr)._1
793
794  if (!p.FPGAPlatform) {
795
796    // display all perfcnt when nooptrap is executed
797    when (xstrap) {
798      printf("======== PerfCnt =========\n")
799      perfCntList.toSeq.sortBy(_._2._1).foreach { case (str, (address, boringId)) =>
800        printf("%d <- " + str + "\n", readWithScala(address))
801      }
802    }
803
804    // for differential testing
805//    BoringUtils.addSource(RegNext(priviledgeMode), "difftestMode")
806//    BoringUtils.addSource(RegNext(mstatus), "difftestMstatus")
807//    BoringUtils.addSource(RegNext(mstatus & sstatusRmask), "difftestSstatus")
808//    BoringUtils.addSource(RegNext(mepc), "difftestMepc")
809//    BoringUtils.addSource(RegNext(sepc), "difftestSepc")
810//    BoringUtils.addSource(RegNext(mcause), "difftestMcause")
811//    BoringUtils.addSource(RegNext(scause), "difftestScause")
812    BoringUtils.addSource(priviledgeMode, "difftestMode")
813    BoringUtils.addSource(mstatus, "difftestMstatus")
814    BoringUtils.addSource(mstatus & sstatusRmask, "difftestSstatus")
815    BoringUtils.addSource(mepc, "difftestMepc")
816    BoringUtils.addSource(sepc, "difftestSepc")
817    BoringUtils.addSource(mcause, "difftestMcause")
818    BoringUtils.addSource(scause, "difftestScause")
819  } else {
820//    BoringUtils.addSource(readWithScala(perfCntList("Minstret")._1), "ilaInstrCnt")
821  }
822}
823