xref: /XiangShan/src/main/scala/xiangshan/backend/fu/CSR.scala (revision 45a56a299b9533c4400bfe2945c10900485d9402)
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 wenFix = Output(Bool())
175}
176
177class CSR extends FunctionUnit(csrCfg) with HasCSRConst{
178  val io = IO(new CSRIO)
179
180  io.cfOut := io.cfIn
181
182  val (valid, src1, src2, func) = (io.in.valid, io.in.bits.src1, io.in.bits.src2, io.in.bits.func)
183  def access(valid: Bool, src1: UInt, src2: UInt, func: UInt): UInt = {
184    this.valid := valid
185    this.src1 := src1
186    this.src2 := src2
187    this.func := func
188    io.out.bits
189  }
190
191  // CSR define
192
193  class Priv extends Bundle {
194    val m = Output(Bool())
195    val h = Output(Bool())
196    val s = Output(Bool())
197    val u = Output(Bool())
198  }
199
200  val csrNotImplemented = RegInit(UInt(XLEN.W), 0.U)
201
202  class MstatusStruct extends Bundle {
203    val sd = Output(UInt(1.W))
204    val pad1 = Output(UInt((XLEN-37).W))
205    val sxl = Output(UInt(2.W))
206    val uxl = Output(UInt(2.W))
207    val pad0 = Output(UInt(9.W))
208    val tsr = Output(UInt(1.W))
209    val tw = Output(UInt(1.W))
210    val tvm = Output(UInt(1.W)) // TODO: add excp check
211    val mxr = Output(UInt(1.W))
212    val sum = Output(UInt(1.W))
213    val mprv = Output(UInt(1.W))
214    val xs = Output(UInt(2.W))
215    val fs = Output(UInt(2.W))
216    val mpp = Output(UInt(2.W))
217    val hpp = Output(UInt(2.W))
218    val spp = Output(UInt(1.W))
219    val pie = new Priv
220    val ie = new Priv
221    assert(this.getWidth == XLEN)
222  }
223
224  class SatpStruct extends Bundle {
225    val mode = UInt(4.W)
226    val asid = UInt(16.W)
227    val ppn  = UInt(44.W)
228  }
229
230  class Interrupt extends Bundle {
231    val e = new Priv
232    val t = new Priv
233    val s = new Priv
234  }
235
236  // Machine-Level CSRs
237
238  val mtvec = RegInit(UInt(XLEN.W), 0.U)
239  val mcounteren = RegInit(UInt(XLEN.W), 0.U)
240  val mcause = RegInit(UInt(XLEN.W), 0.U)
241  val mtval = RegInit(UInt(XLEN.W), 0.U)
242  val mepc = Reg(UInt(XLEN.W))
243
244  val mie = RegInit(0.U(XLEN.W))
245  val mipWire = WireInit(0.U.asTypeOf(new Interrupt))
246  val mipReg  = RegInit(0.U.asTypeOf(new Interrupt).asUInt)
247  val mipFixMask = "h777".U
248  val mip = (mipWire.asUInt | mipReg).asTypeOf(new Interrupt)
249
250  def getMisaMxl(mxl: Int): UInt = (mxl.U << (XLEN-2)).asUInt()
251  def getMisaExt(ext: Char): UInt = (1.U << (ext.toInt - 'a'.toInt)).asUInt()
252  var extList = List('a', 's', 'i', 'u')
253  if(HasMExtension){ extList = extList :+ 'm'}
254  if(HasCExtension){ extList = extList :+ 'c'}
255  if(HasFPU){ extList = extList ++ List('f', 'd')}
256  val misaInitVal = getMisaMxl(2) | extList.foldLeft(0.U)((sum, i) => sum | getMisaExt(i)) //"h8000000000141105".U
257  val misa = RegInit(UInt(XLEN.W), misaInitVal)
258  // MXL = 2          | 0 | EXT = b 00 0000 0100 0001 0001 0000 0101
259  // (XLEN-1, XLEN-2) |   |(25, 0)  ZY XWVU TSRQ PONM LKJI HGFE DCBA
260
261  val mvendorid = RegInit(UInt(XLEN.W), 0.U) // this is a non-commercial implementation
262  val marchid = RegInit(UInt(XLEN.W), 0.U) // return 0 to indicate the field is not implemented
263  val mimpid = RegInit(UInt(XLEN.W), 0.U) // provides a unique encoding of the version of the processor implementation
264  val mhartid = RegInit(UInt(XLEN.W), 0.U) // the hardware thread running the code
265  val mstatus = RegInit(UInt(XLEN.W), "h00001800".U)
266  // val mstatus = RegInit(UInt(XLEN.W), "h8000c0100".U)
267  // mstatus Value Table
268  // | sd   |
269  // | pad1 |
270  // | sxl  | hardlinked to 10, use 00 to pass xv6 test
271  // | uxl  | hardlinked to 00
272  // | pad0 |
273  // | tsr  |
274  // | tw   |
275  // | tvm  | // TODO: add excp check 3.1.6.4
276  // | mxr  |
277  // | sum  |
278  // | mprv |
279  // | xs   | 00 |
280  // | fs   |
281  // | mpp  | 00 |
282  // | hpp  | 00 |
283  // | spp  | 0 |
284  // | pie  | 0000 |
285  // | ie   | 0000 | uie hardlinked to 0, as N ext is not implemented
286  val mstatusStruct = mstatus.asTypeOf(new MstatusStruct)
287  def mstatusUpdateSideEffect(mstatus: UInt): UInt = {
288    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
289    val mstatusNew = Cat(mstatusOld.fs === "b11".U, mstatus(XLEN-2, 0))
290    mstatusNew
291  }
292
293  val medeleg = RegInit(UInt(XLEN.W), 0.U)
294  val mideleg = RegInit(UInt(XLEN.W), 0.U)
295  val mscratch = RegInit(UInt(XLEN.W), 0.U)
296
297  val pmpcfg0 = RegInit(UInt(XLEN.W), 0.U)
298  val pmpcfg1 = RegInit(UInt(XLEN.W), 0.U)
299  val pmpcfg2 = RegInit(UInt(XLEN.W), 0.U)
300  val pmpcfg3 = RegInit(UInt(XLEN.W), 0.U)
301  val pmpaddr0 = RegInit(UInt(XLEN.W), 0.U)
302  val pmpaddr1 = RegInit(UInt(XLEN.W), 0.U)
303  val pmpaddr2 = RegInit(UInt(XLEN.W), 0.U)
304  val pmpaddr3 = RegInit(UInt(XLEN.W), 0.U)
305
306  // Superviser-Level CSRs
307
308  // val sstatus = RegInit(UInt(XLEN.W), "h00000000".U)
309  val sstatusWmask = "hc6122".U
310  // Sstatus Write Mask
311  // -------------------------------------------------------
312  //    19           9   5     2
313  // 0  1100 0000 0001 0010 0010
314  // 0  c    0    1    2    2
315  // -------------------------------------------------------
316  val sstatusRmask = sstatusWmask | "h8000000300018000".U
317  // Sstatus Read Mask = (SSTATUS_WMASK | (0xf << 13) | (1ull << 63) | (3ull << 32))
318  val stvec = RegInit(UInt(XLEN.W), 0.U)
319  // val sie = RegInit(0.U(XLEN.W))
320  val sieMask = "h222".U & mideleg
321  val sipMask  = "h222".U & mideleg
322  // val satp = RegInit(0.U(XLEN.W))
323  val satp = RegInit(UInt(XLEN.W), "h8000000000087fbe".U) // only use for tlb naive debug
324  val satpMask = "hf0000fffffffffff".U // disable asid
325  val sepc = RegInit(UInt(XLEN.W), 0.U)
326  val scause = RegInit(UInt(XLEN.W), 0.U)
327  val stval = Reg(UInt(XLEN.W))
328  val sscratch = RegInit(UInt(XLEN.W), 0.U)
329  val scounteren = RegInit(UInt(XLEN.W), 0.U)
330
331  val tlbBundle = Wire(new TlbCsrBundle)
332  // val sfence    = Wire(new SfenceBundle)
333  tlbBundle.satp := satp.asTypeOf(new SatpStruct)
334  // sfence := 0.U.asTypeOf(new SfenceBundle)
335  BoringUtils.addSource(tlbBundle, "TLBCSRIO")
336  // BoringUtils.addSource(sfence, "SfenceBundle") // FIXME: move to MOU
337
338  // User-Level CSRs
339  val uepc = Reg(UInt(XLEN.W))
340
341  // fcsr
342  class FcsrStruct extends Bundle{
343    val reserved = UInt((XLEN-3-5).W)
344    val frm = UInt(3.W)
345    val fflags = UInt(5.W)
346    assert(this.getWidth == XLEN)
347  }
348  val fcsr = RegInit(0.U(XLEN.W))
349  // set mstatus->sd and mstatus->fs when true
350  val csrw_dirty_fp_state = WireInit(false.B)
351
352  def frm_wfn(wdata: UInt): UInt = {
353    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
354    csrw_dirty_fp_state := true.B
355    fcsrOld.frm := wdata(2,0)
356    fcsrOld.asUInt()
357  }
358  def frm_rfn(rdata: UInt): UInt = rdata(7,5)
359
360  def fflags_wfn(wdata: UInt): UInt = {
361    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
362    csrw_dirty_fp_state := true.B
363    fcsrOld.fflags := wdata(4,0)
364    fcsrOld.asUInt()
365  }
366  def fflags_rfn(rdata:UInt): UInt = rdata(4,0)
367
368  def fcsr_wfn(wdata: UInt): UInt = {
369    val fcsrOld = WireInit(fcsr.asTypeOf(new FcsrStruct))
370    csrw_dirty_fp_state := true.B
371    Cat(fcsrOld.reserved, wdata.asTypeOf(fcsrOld).frm, wdata.asTypeOf(fcsrOld).fflags)
372  }
373
374  val fcsrMapping = Map(
375    MaskedRegMap(Fflags, fcsr, wfn = fflags_wfn, rfn = fflags_rfn),
376    MaskedRegMap(Frm, fcsr, wfn = frm_wfn, rfn = frm_rfn),
377    MaskedRegMap(Fcsr, fcsr, wfn = fcsr_wfn)
378  )
379
380  // Atom LR/SC Control Bits
381//  val setLr = WireInit(Bool(), false.B)
382//  val setLrVal = WireInit(Bool(), false.B)
383//  val setLrAddr = WireInit(UInt(AddrBits.W), DontCare) //TODO : need check
384//  val lr = RegInit(Bool(), false.B)
385//  val lrAddr = RegInit(UInt(AddrBits.W), 0.U)
386//  BoringUtils.addSink(setLr, "set_lr")
387//  BoringUtils.addSink(setLrVal, "set_lr_val")
388//  BoringUtils.addSink(setLrAddr, "set_lr_addr")
389//  BoringUtils.addSource(lr, "lr")
390//  BoringUtils.addSource(lrAddr, "lr_addr")
391//
392//  when(setLr){
393//    lr := setLrVal
394//    lrAddr := setLrAddr
395//  }
396
397  // Hart Priviledge Mode
398  val priviledgeMode = RegInit(UInt(2.W), ModeM)
399
400  // perfcnt
401  val hasPerfCnt = !env.FPGAPlatform
402  val nrPerfCnts = if (hasPerfCnt) 0x80 else 0x3
403  val perfCnts = List.fill(nrPerfCnts)(RegInit(0.U(XLEN.W)))
404  val perfCntsLoMapping = (0 until nrPerfCnts).map(i => MaskedRegMap(0xb00 + i, perfCnts(i)))
405  val perfCntsHiMapping = (0 until nrPerfCnts).map(i => MaskedRegMap(0xb80 + i, perfCnts(i)(63, 32)))
406
407  // CSR reg map
408  val mapping = Map(
409
410    // User Trap Setup
411    // MaskedRegMap(Ustatus, ustatus),
412    // MaskedRegMap(Uie, uie, 0.U, MaskedRegMap.Unwritable),
413    // MaskedRegMap(Utvec, utvec),
414
415    // User Trap Handling
416    // MaskedRegMap(Uscratch, uscratch),
417    // MaskedRegMap(Uepc, uepc),
418    // MaskedRegMap(Ucause, ucause),
419    // MaskedRegMap(Utval, utval),
420    // MaskedRegMap(Uip, uip),
421
422    // User Counter/Timers
423    // MaskedRegMap(Cycle, cycle),
424    // MaskedRegMap(Time, time),
425    // MaskedRegMap(Instret, instret),
426
427    // Supervisor Trap Setup
428    MaskedRegMap(Sstatus, mstatus, sstatusWmask, mstatusUpdateSideEffect, sstatusRmask),
429
430    // MaskedRegMap(Sedeleg, Sedeleg),
431    // MaskedRegMap(Sideleg, Sideleg),
432    MaskedRegMap(Sie, mie, sieMask, MaskedRegMap.NoSideEffect, sieMask),
433    MaskedRegMap(Stvec, stvec),
434    MaskedRegMap(Scounteren, scounteren),
435
436    // Supervisor Trap Handling
437    MaskedRegMap(Sscratch, sscratch),
438    MaskedRegMap(Sepc, sepc),
439    MaskedRegMap(Scause, scause),
440    MaskedRegMap(Stval, stval),
441    MaskedRegMap(Sip, mip.asUInt, sipMask, MaskedRegMap.Unwritable, sipMask),
442
443    // Supervisor Protection and Translation
444    MaskedRegMap(Satp, satp, satpMask, MaskedRegMap.NoSideEffect, satpMask),
445
446    // Machine Information Registers
447    MaskedRegMap(Mvendorid, mvendorid, 0.U, MaskedRegMap.Unwritable),
448    MaskedRegMap(Marchid, marchid, 0.U, MaskedRegMap.Unwritable),
449    MaskedRegMap(Mimpid, mimpid, 0.U, MaskedRegMap.Unwritable),
450    MaskedRegMap(Mhartid, mhartid, 0.U, MaskedRegMap.Unwritable),
451
452    // Machine Trap Setup
453    // MaskedRegMap(Mstatus, mstatus, "hffffffffffffffee".U, (x=>{printf("mstatus write: %x time: %d\n", x, GTimer()); x})),
454    MaskedRegMap(Mstatus, mstatus, "hffffffffffffffff".U, mstatusUpdateSideEffect),
455    MaskedRegMap(Misa, misa), // now MXL, EXT is not changeable
456    MaskedRegMap(Medeleg, medeleg, "hbbff".U),
457    MaskedRegMap(Mideleg, mideleg, "h222".U),
458    MaskedRegMap(Mie, mie),
459    MaskedRegMap(Mtvec, mtvec),
460    MaskedRegMap(Mcounteren, mcounteren),
461
462    // Machine Trap Handling
463    MaskedRegMap(Mscratch, mscratch),
464    MaskedRegMap(Mepc, mepc),
465    MaskedRegMap(Mcause, mcause),
466    MaskedRegMap(Mtval, mtval),
467    MaskedRegMap(Mip, mip.asUInt, 0.U, MaskedRegMap.Unwritable),
468
469    // Machine Memory Protection
470    MaskedRegMap(Pmpcfg0, pmpcfg0),
471    MaskedRegMap(Pmpcfg1, pmpcfg1),
472    MaskedRegMap(Pmpcfg2, pmpcfg2),
473    MaskedRegMap(Pmpcfg3, pmpcfg3),
474    MaskedRegMap(PmpaddrBase + 0, pmpaddr0),
475    MaskedRegMap(PmpaddrBase + 1, pmpaddr1),
476    MaskedRegMap(PmpaddrBase + 2, pmpaddr2),
477    MaskedRegMap(PmpaddrBase + 3, pmpaddr3)
478
479  ) ++
480    perfCntsLoMapping ++ (if (XLEN == 32) perfCntsHiMapping else Nil) ++
481    (if(HasFPU) fcsrMapping else Nil)
482
483  val addr = src2(11, 0)
484  val rdata = Wire(UInt(XLEN.W))
485  val csri = ZeroExt(io.cfIn.instr(19,15), XLEN) //unsigned imm for csri. [TODO]
486  val wdata = LookupTree(func, List(
487    CSROpType.wrt  -> src1,
488    CSROpType.set  -> (rdata | src1),
489    CSROpType.clr  -> (rdata & (~src1).asUInt()),
490    CSROpType.wrti -> csri,//TODO: csri --> src2
491    CSROpType.seti -> (rdata | csri),
492    CSROpType.clri -> (rdata & (~csri).asUInt())
493  ))
494
495  // satp wen check
496  val satpLegalMode = (wdata.asTypeOf(new SatpStruct).mode===0.U) || (wdata.asTypeOf(new SatpStruct).mode===8.U)
497  val wen = valid && func =/= CSROpType.jmp && Mux(addr===Satp.U, satpLegalMode, true.B)
498  // TODO: problem: is wen under mode check?
499  // if satp.mode is illegal, will not write
500  // Debug(){when(wen){printf("[CSR] addr %x wdata %x func %x rdata %x\n", addr, wdata, func, rdata)}}
501  MaskedRegMap.generate(mapping, addr, rdata, wen, wdata)
502  io.out.bits := rdata
503  val isIllegalAddr = MaskedRegMap.isIllegalAddr(mapping, addr)
504
505  // Fix Mip/Sip write
506  val fixMapping = Map(
507    MaskedRegMap(Mip, mipReg.asUInt, mipFixMask),
508    MaskedRegMap(Sip, mipReg.asUInt, sipMask, MaskedRegMap.NoSideEffect, sipMask)
509  )
510  val rdataDummy = Wire(UInt(XLEN.W))
511  MaskedRegMap.generate(fixMapping, addr, rdataDummy, wen, wdata)
512
513  when(io.fpu_csr.fflags.asUInt() =/= 0.U){
514    fcsr := fflags_wfn(io.fpu_csr.fflags.asUInt())
515  }
516  // set fs and sd in mstatus
517  when(csrw_dirty_fp_state || io.fpu_csr.dirty_fs){
518    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
519    mstatusNew.fs := "b11".U
520    mstatusNew.sd := true.B
521    mstatus := mstatusNew.asUInt()
522  }
523  io.fpu_csr.frm := fcsr.asTypeOf(new FcsrStruct).frm
524
525  // CSR inst decode
526  val ret = Wire(Bool())
527  val isEcall = addr === privEcall && func === CSROpType.jmp
528  val isMret = addr === privMret   && func === CSROpType.jmp
529  val isSret = addr === privSret   && func === CSROpType.jmp
530  val isUret = addr === privUret   && func === CSROpType.jmp
531
532  XSDebug(wen, "csr write: pc %x addr %x rdata %x wdata %x func %x\n", io.cfIn.pc, addr, rdata, wdata, func)
533  XSDebug(wen, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", io.cfIn.pc, mstatus, mideleg , medeleg, priviledgeMode)
534
535
536  // MMU Permission Check
537
538  // def MMUPermissionCheck(ptev: Bool, pteu: Bool): Bool = ptev && !(priviledgeMode === ModeU && !pteu) && !(priviledgeMode === ModeS && pteu && mstatusStruct.sum.asBool)
539  // def MMUPermissionCheckLoad(ptev: Bool, pteu: Bool): Bool = ptev && !(priviledgeMode === ModeU && !pteu) && !(priviledgeMode === ModeS && pteu && mstatusStruct.sum.asBool) && (pter || (mstatusStruct.mxr && ptex))
540  // imem
541  // val imemPtev = true.B
542  // val imemPteu = true.B
543  // val imemPtex = true.B
544  // val imemReq = true.B
545  // val imemPermissionCheckPassed = MMUPermissionCheck(imemPtev, imemPteu)
546  // val hasInstrPageFault = imemReq && !(imemPermissionCheckPassed && imemPtex)
547  // assert(!hasInstrPageFault)
548
549  // dmem
550  // val dmemPtev = true.B
551  // val dmemPteu = true.B
552  // val dmemReq = true.B
553  // val dmemPermissionCheckPassed = MMUPermissionCheck(dmemPtev, dmemPteu)
554  // val dmemIsStore = true.B
555
556  // val hasLoadPageFault  = dmemReq && !dmemIsStore && !(dmemPermissionCheckPassed)
557  // val hasStorePageFault = dmemReq &&  dmemIsStore && !(dmemPermissionCheckPassed)
558  // assert(!hasLoadPageFault)
559  // assert(!hasStorePageFault)
560
561  //TODO: Havn't test if io.dmemMMU.priviledgeMode is correct yet
562  tlbBundle.priv.mxr   := mstatusStruct.mxr.asBool
563  tlbBundle.priv.sum   := mstatusStruct.sum.asBool
564  tlbBundle.priv.imode := priviledgeMode
565  tlbBundle.priv.dmode := Mux(mstatusStruct.mprv.asBool, mstatusStruct.mpp, priviledgeMode)
566
567  val hasInstrPageFault = io.exception.bits.cf.exceptionVec(instrPageFault) && io.exception.valid
568  val hasLoadPageFault = false.B // FIXME: add ld-pf/st-pf
569  val hasStorePageFault = false.B
570  val hasStoreAddrMisaligned = io.exception.bits.cf.exceptionVec(storeAddrMisaligned)
571  val hasLoadAddrMisaligned = io.exception.bits.cf.exceptionVec(loadAddrMisaligned)
572
573  when(hasInstrPageFault || hasLoadPageFault || hasStorePageFault){
574    val tval = Mux(
575      hasInstrPageFault,
576      Mux(
577        io.exception.bits.cf.crossPageIPFFix,
578        SignExt(io.exception.bits.cf.pc + 2.U, XLEN),
579        SignExt(io.exception.bits.cf.pc, XLEN)
580      ),
581      // SignExt(io.dmemMMU.addr, XLEN)
582      "hffffffff".U // FIXME: add ld/st pf
583    )
584    when(priviledgeMode === ModeM){
585      mtval := tval
586    }.otherwise{
587      stval := tval
588    }
589  }
590
591  val lsuAddr = WireInit(0.U(64.W))
592  BoringUtils.addSink(lsuAddr, "LSUADDR")
593  when(hasLoadAddrMisaligned || hasStoreAddrMisaligned)
594  {
595    mtval := SignExt(lsuAddr, XLEN)
596  }
597
598  // Exception and Intr
599
600  // interrupts
601
602  val ideleg =  (mideleg & mip.asUInt)
603  def priviledgedEnableDetect(x: Bool): Bool = Mux(x, ((priviledgeMode === ModeS) && mstatusStruct.ie.s) || (priviledgeMode < ModeS),
604    ((priviledgeMode === ModeM) && mstatusStruct.ie.m) || (priviledgeMode < ModeM))
605
606  val intrVecEnable = Wire(Vec(12, Bool()))
607  intrVecEnable.zip(ideleg.asBools).map{case(x,y) => x := priviledgedEnableDetect(y)}
608  val intrVec = mie(11,0) & mip.asUInt & intrVecEnable.asUInt
609  val intrBitSet = intrVec.orR()
610  ExcitingUtils.addSource(intrBitSet, "intrBitSetIDU")
611  val intrNO = IntPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(intrVec(i), i.U, sum))
612  val raiseIntr = intrBitSet && io.exception.valid
613  XSDebug(raiseIntr, "interrupt: pc=0x%x, %d\n", io.exception.bits.cf.pc, intrNO)
614
615  val mtip = WireInit(false.B)
616  val meip = WireInit(false.B)
617  ExcitingUtils.addSink(mtip, "mtip")
618  ExcitingUtils.addSink(meip, "meip")
619  mipWire.t.m := mtip
620  mipWire.e.m := meip
621
622  // exceptions
623  val csrExceptionVec = Wire(Vec(16, Bool()))
624  csrExceptionVec.map(_ := false.B)
625  csrExceptionVec(ecallM) := priviledgeMode === ModeM && io.in.valid && isEcall
626  csrExceptionVec(ecallS) := priviledgeMode === ModeS && io.in.valid && isEcall
627  csrExceptionVec(ecallU) := priviledgeMode === ModeU && io.in.valid && isEcall
628  // csrExceptionVec(instrPageFault) := hasInstrPageFault
629  csrExceptionVec(illegalInstr) := isIllegalAddr && wen // Trigger an illegal instr exception when unimplemented csr is being read/written // TODO: if csrrw under wrong priv mode will cause illegal instr now ?
630  csrExceptionVec(loadPageFault) := hasLoadPageFault
631  csrExceptionVec(storePageFault) := hasStorePageFault
632  val iduExceptionVec = io.cfIn.exceptionVec
633  val exceptionVec = csrExceptionVec.asUInt() | iduExceptionVec.asUInt()
634  io.cfOut.exceptionVec.zipWithIndex.map{case (e, i) => e := exceptionVec(i) }
635  io.wenFix := DontCare
636
637  val raiseExceptionVec = io.exception.bits.cf.exceptionVec.asUInt()
638  val exceptionNO = ExcPriority.foldRight(0.U)((i: Int, sum: UInt) => Mux(raiseExceptionVec(i), i.U, sum))
639  val causeNO = (raiseIntr << (XLEN-1)).asUInt() | Mux(raiseIntr, intrNO, exceptionNO)
640  val difftestIntrNO = Mux(raiseIntr, causeNO, 0.U)
641  ExcitingUtils.addSource(difftestIntrNO, "difftestIntrNOfromCSR")
642
643  val raiseExceptionIntr = io.exception.valid
644  val retTarget = Wire(UInt(VAddrBits.W))
645  val trapTarget = Wire(UInt(VAddrBits.W))
646  ExcitingUtils.addSource(trapTarget, "trapTarget")
647  val resetSatp = addr === Satp.U && satpLegalMode && wen // write to satp will cause the pipeline be flushed
648  io.redirect := DontCare
649  io.redirectValid := (valid && func === CSROpType.jmp && !isEcall) || resetSatp
650  //TODO: use pred pc instead pc+4
651  io.redirect.target := Mux(resetSatp, io.cfIn.pc+4.U, retTarget)
652
653  XSDebug(io.redirectValid, "redirect to %x, pc=%x\n", io.redirect.target, io.cfIn.pc)
654
655  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)
656  XSDebug(raiseExceptionIntr, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", io.exception.bits.cf.pc, mstatus, mideleg, medeleg, priviledgeMode)
657
658  XSDebug(io.redirectValid, "redirect to %x\n", io.redirect.target)
659
660  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)
661  XSDebug(valid && isMret, "[MST] pc %x mstatus %x mideleg %x medeleg %x mode %x\n", io.cfIn.pc, mstatus, mideleg , medeleg, priviledgeMode)
662
663  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)
664  XSDebug(valid && isSret, "pc %x mstatus %x mideleg %x medeleg %x mode %x\n", io.cfIn.pc, mstatus, mideleg , medeleg, priviledgeMode)
665  XSDebug(io.redirectValid, "Redirect %x raiseExcepIntr:%d valid:%d instrValid:%x \n", io.redirect.target, raiseExceptionIntr, valid, io.instrValid)
666
667  // Branch control
668
669  val deleg = Mux(raiseIntr, mideleg , medeleg)
670  // val delegS = ((deleg & (1 << (causeNO & 0xf))) != 0) && (priviledgeMode < ModeM);
671  val delegS = (deleg(causeNO(3,0))) && (priviledgeMode < ModeM)
672  val tvalWen = !(hasInstrPageFault || hasLoadPageFault || hasStorePageFault || hasLoadAddrMisaligned || hasStoreAddrMisaligned) || raiseIntr // in noop-riscv64, no exception will come together with PF
673
674  ret := isMret || isSret || isUret
675  trapTarget := Mux(delegS, stvec, mtvec)(VAddrBits-1, 0)
676  retTarget := DontCare
677  // val illegalEret = TODO
678
679  when (valid && isMret) {
680    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
681    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
682    // mstatusNew.mpp.m := ModeU //TODO: add mode U
683    mstatusNew.ie.m := mstatusOld.pie.m
684    priviledgeMode := mstatusOld.mpp
685    mstatusNew.pie.m := true.B
686    mstatusNew.mpp := ModeU
687    mstatus := mstatusNew.asUInt
688//    lr := false.B
689    retTarget := mepc(VAddrBits-1, 0)
690  }
691
692  when (valid && isSret) {
693    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
694    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
695    // mstatusNew.mpp.m := ModeU //TODO: add mode U
696    mstatusNew.ie.s := mstatusOld.pie.s
697    priviledgeMode := Cat(0.U(1.W), mstatusOld.spp)
698    mstatusNew.pie.s := true.B
699    mstatusNew.spp := ModeU
700    mstatus := mstatusNew.asUInt
701//    lr := false.B
702    retTarget := sepc(VAddrBits-1, 0)
703  }
704
705  when (valid && isUret) {
706    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
707    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
708    // mstatusNew.mpp.m := ModeU //TODO: add mode U
709    mstatusNew.ie.u := mstatusOld.pie.u
710    priviledgeMode := ModeU
711    mstatusNew.pie.u := true.B
712    mstatus := mstatusNew.asUInt
713    retTarget := uepc(VAddrBits-1, 0)
714  }
715
716  when (raiseExceptionIntr) {
717    val mstatusOld = WireInit(mstatus.asTypeOf(new MstatusStruct))
718    val mstatusNew = WireInit(mstatus.asTypeOf(new MstatusStruct))
719
720    when (delegS) {
721      scause := causeNO
722      sepc := SignExt(io.exception.bits.cf.pc, XLEN)
723      mstatusNew.spp := priviledgeMode
724      mstatusNew.pie.s := mstatusOld.ie.s
725      mstatusNew.ie.s := false.B
726      priviledgeMode := ModeS
727      when(tvalWen){stval := 0.U} // TODO: should not use =/=
728      // printf("[*] mstatusNew.spp %x\n", mstatusNew.spp)
729      // trapTarget := stvec(VAddrBits-1. 0)
730    }.otherwise {
731      mcause := causeNO
732      mepc := SignExt(io.exception.bits.cf.pc, XLEN)
733      mstatusNew.mpp := priviledgeMode
734      mstatusNew.pie.m := mstatusOld.ie.m
735      mstatusNew.ie.m := false.B
736      priviledgeMode := ModeM
737      when(tvalWen){mtval := 0.U} // TODO: should not use =/=
738      // trapTarget := mtvec(VAddrBits-1. 0)
739    }
740    // mstatusNew.pie.m := LookupTree(priviledgeMode, List(
741    //   ModeM -> mstatusOld.ie.m,
742    //   ModeH -> mstatusOld.ie.h, //ERROR
743    //   ModeS -> mstatusOld.ie.s,
744    //   ModeU -> mstatusOld.ie.u
745    // ))
746
747    mstatus := mstatusNew.asUInt
748  }
749
750  io.in.ready := true.B
751  io.out.valid := valid
752
753
754  XSDebug(io.redirectValid, "Rediret %x raiseExcepIntr:%d isSret:%d retTarget:%x sepc:%x delegs:%d deleg:%x cfInpc:%x valid:%d instrValid:%x \n",
755    io.redirect.target, raiseExceptionIntr, isSret, retTarget, sepc, delegS, deleg, io.cfIn.pc, valid, io.instrValid)
756  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",
757    io.redirectValid, io.redirect.target, raiseExceptionIntr, isSret, retTarget, sepc, delegS, deleg, io.cfIn.pc, valid, io.instrValid)
758  XSDebug(raiseExceptionIntr && delegS, "sepc is writen!!! pc:%x\n", io.cfIn.pc)
759
760
761  // perfcnt
762
763  val perfCntList = Map(
764//    "Mcycle"      -> (0xb00, "perfCntCondMcycle"     ),
765//    "Minstret"    -> (0xb02, "perfCntCondMinstret"   ),
766    "MbpInstr"    -> (0xb03, "perfCntCondMbpInstr"   ),
767    "MbpRight"    -> (0xb04, "perfCntCondMbpRight"   ),
768    "MbpWrong"    -> (0xb05, "perfCntCondMbpWrong"   ),
769    "MbpBRight"   -> (0xb06, "perfCntCondMbpBRight"   ),
770    "MbpBWrong"   -> (0xb07, "perfCntCondMbpBWrong"   ),
771    "MbpJRight"   -> (0xb08, "perfCntCondMbpJRight"   ),
772    "MbpJWrong"   -> (0xb09, "perfCntCondMbpJWrong"   ),
773    "MbpIRight"   -> (0xb0a, "perfCntCondMbpIRight"   ),
774    "MbpIWrong"   -> (0xb0b, "perfCntCondMbpIWrong"   ),
775    "MbpRRight"   -> (0xb0c, "perfCntCondMbpRRight"   ),
776    "MbpRWrong"   -> (0xb0d, "perfCntCondMbpRWrong"   ),
777    "DpqReplay"   -> (0xb0e, "perfCntCondDpqReplay"   ),
778    "RoqWalk"     -> (0xb0f, "perfCntCondRoqWalk"     ),
779    "RoqWaitInt"  -> (0xb10, "perfCntCondRoqWaitInt"  ),
780    "RoqWaitFp"   -> (0xb11, "perfCntCondRoqWaitFp"   ),
781    "RoqWaitLoad" -> (0xb12, "perfCntCondRoqWaitLoad" ),
782    "RoqWaitStore"-> (0xb13, "perfCntCondRoqWaitStore"),
783    "Dp1Empty"    -> (0xb14, "perfCntCondDp1Empty"    ),
784    "DTlbReqCnt0" -> (0xb15, "perfCntDtlbReqCnt0"     ),
785    "DTlbReqCnt1" -> (0xb16, "perfCntDtlbReqCnt1"     ),
786    "DTlbReqCnt2" -> (0xb17, "perfCntDtlbReqCnt2"     ),
787    "DTlbReqCnt3" -> (0xb18, "perfCntDtlbReqCnt3"     ),
788    "DTlbMissCnt0"-> (0xb19, "perfCntDtlbMissCnt0"    ),
789    "DTlbMissCnt1"-> (0xb20, "perfCntDtlbMissCnt1"    ),
790    "DTlbMissCnt2"-> (0xb21, "perfCntDtlbMissCnt2"    ),
791    "DTlbMissCnt3"-> (0xb22, "perfCntDtlbMissCnt3"    ),
792    "ITlbReqCnt0" -> (0xb23, "perfCntItlbReqCnt0"     ),
793    "ITlbMissCnt0"-> (0xb24, "perfCntItlbMissCnt0"    ),
794    "PtwReqCnt"   -> (0xb25, "perfCntPtwReqCnt"       ),
795    "PtwCycleCnt" -> (0xb26, "perfCntPtwCycleCnt"     ),
796    "PtwL2TlbHit" -> (0xb27, "perfCntPtwL2TlbHit"     )
797//    "Custom1"     -> (0xb1b, "Custom1"             ),
798//    "Custom2"     -> (0xb1c, "Custom2"             ),
799//    "Custom3"     -> (0xb1d, "Custom3"             ),
800//    "Custom4"     -> (0xb1e, "Custom4"             ),
801//    "Custom5"     -> (0xb1f, "Custom5"             ),
802//    "Custom6"     -> (0xb20, "Custom6"             ),
803//    "Custom7"     -> (0xb21, "Custom7"             ),
804//    "Custom8"     -> (0xb22, "Custom8"             ),
805//    "Ml2cacheHit" -> (0xb23, "perfCntCondMl2cacheHit")
806  )
807  val perfCntCond = List.fill(0x80)(WireInit(false.B))
808  (perfCnts zip perfCntCond).map { case (c, e) => when (e) { c := c + 1.U } }
809
810//  ExcitingUtils.addSource(WireInit(true.B), "perfCntCondMcycle", ConnectionType.Perf)
811  perfCntList.foreach {
812    case (_, (address, boringId)) =>
813      if(hasPerfCnt){
814        ExcitingUtils.addSink(perfCntCond(address & 0x7f), boringId, ConnectionType.Perf)
815      }
816//      if (!hasPerfCnt) {
817//        // do not enable perfcnts except for Mcycle and Minstret
818//        if (address != perfCntList("Mcycle")._1 && address != perfCntList("Minstret")._1) {
819//          perfCntCond(address & 0x7f) := false.B
820//        }
821//      }
822  }
823
824  val xstrap = WireInit(false.B)
825  if(!env.FPGAPlatform && EnableBPU){
826    ExcitingUtils.addSink(xstrap, "XSTRAP", ConnectionType.Debug)
827  }
828  def readWithScala(addr: Int): UInt = mapping(addr)._1
829
830  if (!env.FPGAPlatform) {
831
832    // display all perfcnt when nooptrap is executed
833    when (xstrap) {
834      printf("======== PerfCnt =========\n")
835      perfCntList.toSeq.sortBy(_._2._1).foreach { case (str, (address, boringId)) =>
836        printf("%d <- " + str + "\n", readWithScala(address))
837      }
838    }
839
840    // for differential testing
841//    BoringUtils.addSource(RegNext(priviledgeMode), "difftestMode")
842//    BoringUtils.addSource(RegNext(mstatus), "difftestMstatus")
843//    BoringUtils.addSource(RegNext(mstatus & sstatusRmask), "difftestSstatus")
844//    BoringUtils.addSource(RegNext(mepc), "difftestMepc")
845//    BoringUtils.addSource(RegNext(sepc), "difftestSepc")
846//    BoringUtils.addSource(RegNext(mcause), "difftestMcause")
847//    BoringUtils.addSource(RegNext(scause), "difftestScause")
848    BoringUtils.addSource(priviledgeMode, "difftestMode")
849    BoringUtils.addSource(mstatus, "difftestMstatus")
850    BoringUtils.addSource(mstatus & sstatusRmask, "difftestSstatus")
851    BoringUtils.addSource(mepc, "difftestMepc")
852    BoringUtils.addSource(sepc, "difftestSepc")
853    BoringUtils.addSource(mcause, "difftestMcause")
854    BoringUtils.addSource(scause, "difftestScause")
855  } else {
856//    BoringUtils.addSource(readWithScala(perfCntList("Minstret")._1), "ilaInstrCnt")
857  }
858}
859