RISC-V Traps 1: Exceptions, Interrupts, mtvec Modes, mepc/mcause/mtval and mret on QEMU

Sunhong··24 min read·0 views·Translated from Korean

Key points of this post

  • A trap is a bundle of writes the hardware does all at once. It records where to return (mepc) and why (mcause, mtval), pushes MIE into MPIE and the current mode into MPP, and sends pc to mtvec. mret is the inverse. On QEMU, an ecall with MIE=1 showed MIE, MPIE, MPP = 0, 1, 3 right after entry and 1, 1, 0 after mret.
  • With mtvec in vectored mode (0x80000401), the software interrupt and the timer interrupt went to slots 3 and 7 (= their cause numbers) and synchronous exceptions went to slot 0. mepc was the instruction itself for exceptions (even ecall) and the next, not yet executed instruction for interrupts.
  • mtval holds something different for each event: instruction bits for an illegal instruction (0xf1401073), the instruction's own address for ebreak, 0 for ecall, and the address for address exceptions (the virtual address, even for access faults, once Sv39 is on). When a handler enabled MIE before saving mepc, a nested trap overwrote mepc and changed MPP from S (1) to U (0), so execution returned to U instead of S (the next ecall showed mcause=8).

Part 23 ran ecall in three modes and read mcause as 8, 9 and 11. Part 24 read mcause=2 as proof that a CSR access was illegal. Both times we treated the trap handler as a black box. This post opens it. When a trap arrives, what does the hardware write and where, how does mtvec choose pc, what does mret undo, and what goes wrong when a handler does not protect mepc? Delegation (medeleg), S-mode traps, exception priority and WFI are in Part 26.

The experiments are RV64 only: QEMU 11.1.3 virt, riscv64-elf-gcc 16.2, and the Unprivileged and Privileged specifications, version 20240411. Every test ran with -cpu rv64,c=false (C extension off). With C on, a jump to a 2-byte-aligned address is legal, so no misaligned-fetch exception can be seen (section 3). The test code is probe.c (182 lines) and start.S (310 lines). check.py runs it under three QEMU configurations, compares 62 expected values computed from the spec rules, and writes results.json. Method and full results are in section 8.

1. What a trap is: exceptions, interrupts, cause numbers

In the spec's vocabulary, a trap covers both exceptions and interrupts. An exception is a synchronous event that happens while an instruction executes. Run the same program again and it happens at the same instruction. An interrupt is an asynchronous event from outside the instruction stream, so which instruction boundary receives it differs from run to run. In hardware terms, an exception is a tag on one instruction in the pipeline (Part 27), and an interrupt is an external signal that is checked at an instruction boundary.

mcause tells them apart with one register. The top bit is the interrupt flag, and the lower bits are the cause number (the Exception Code, a WLRL field). The spec gives the reason: "one branch on the sign of mcause separates interrupts from other traps, and one left shift removes the interrupt bit and scales the code to index a vector table" (Privileged 3.1.15). On RV64 a software interrupt reads as 0x8000000000000003 and a timer interrupt as 0x8000000000000007. The causes exercised in this post:

Number Exception name Test in this post
0 Instruction address misaligned jalr to odd+2
1 Instruction access fault jump to an unmapped address
2 Illegal instruction .word 0xffffffff etc.
3 Breakpoint ebreak
4 Load address misaligned lr.w at an odd address
5 Load access fault lw from an unmapped address
6 Store/AMO address misaligned sc.w, amoadd
7 Store/AMO access fault sw to an unmapped address
8, 9, 11 ecall from U, S, M the three modes
12, 13, 15 Instruction, load, store/AMO page fault Sv39

Numbers 10 and 14 are reserved. 18 is software check and 19 is hardware error, which this post does not use. Remember one distinction: loads and lr raise load exceptions (4, 5, 13), while stores, sc and AMOs raise store/AMO exceptions (6, 7, 15).

Number Interrupt name Note
1 S-mode software (SSI) mip.SSIP
3 M-mode software (MSI) CLINT msip
5 S-mode timer (STI) mip.STIP
7 M-mode timer (MTI) mtime >= mtimecmp
9 S-mode external (SEI) interrupt controller
11 M-mode external (MEI) interrupt controller

Interrupt number i is bit i of mip and mie (the same numbering as the views in Part 24). Numbers 16 and above are left for platform use. The M/S split in this table carries through the rest of this post and into delegation in Part 26.

2. What happens when a trap enters

When a trap from mode y enters M-mode, the hardware does the following (Privileged 3.1.6.1 and 3.1.14 to 3.1.16).

Target New value
mepc Exception: address of the instruction that trapped. Interrupt: address of the next instruction, not yet executed
mcause interrupt bit + cause number
mtval address, instruction bits or 0, depending on the event (section 4)
mstatus.MPIE old MIE
mstatus.MIE 0
mstatus.MPP y (the mode before the trap)
current mode M
pc BASE of mtvec (direct) or BASE + 4 x cause (vectored, for interrupts)

From software's point of view the whole table happens at once. By the time the handler's first instruction runs, mepc, mcause, mtval and mstatus already hold these values, and MIE is 0, so no interrupt barges in mid-handler. The spec explains why a two-level stack (MIE/MPIE, mode/MPP) is enough: a handler either returns immediately, or, if it does not, saves the stack before re-enabling interrupts, so one entry per stack suffices.

For hardware this is one cycle that writes three CSRs and three mstatus fields and also changes the current mode and pc. Part 24 showed the merged write where writing fflags also changes mstatus.FS. Trap entry is the largest case of that merge. In a pipeline, the write may only happen once the trapping instruction reaches the write-back stage and all earlier instructions have finished. That is why mepc points at exactly that instruction (precise exceptions, Part 27).

The measurement: run ecall in M-mode with MIE equal to 1 and to 0, and record mstatus just before, at the first line of the handler, and right after mret.

With MIE=1, ecall gives MIE 0, MPIE 1, MPP 3 right after entry, and MIE 1, MPIE 1, MPP 0 (U) after mret. With MIE=0, MPIE becomes 0 at entry and MIE stays 0 after mret

Two things stand out. First, starting from MIE=0 gives MPIE=0 at entry and MIE=0 after mret. MPIE stores the pre-trap MIE exactly, so code that ran with interrupts off comes back with them off. Second, MPP was 0 (U) before the trap and 3 (M) right after entry. This test did its ecall in M-mode, so "previous mode = M" went into MPP, and the earlier 0 is a trace left by a previous mret. Section 6 explains that trace.

For traps from S and U, MPP is that mode. We dropped to S and U with mret, executed ecall, and read mstatus in the handler.

From mcause MPP right after entry
S 9 1
U 8 0

3. mepc: where the trap returns to

The spec defines mepc like this. When a trap enters M-mode, mepc is written with "the virtual address of the instruction that was interrupted or that encountered the exception", and otherwise the hardware never writes it. We checked the two cases separately.

An exception points at the instruction itself. Of the sixteen synchronous exceptions raised in M-mode, fifteen had mepc equal to the instruction that raised them (the remaining one is the instruction access fault below). That includes ecall and ebreak. Section 3.3.1 says ecall and ebreak set epc to "the address of the instruction itself, not the following instruction", and since they cause exceptions they do not retire and must not increment minstret. A handler that wants to continue after ecall has to add 4 to mepc in software, which is what our handler's skip does. Skipping an illegal instruction is a shortcut with no guarantee that the state is right afterwards, so it is for the experiment only.

There is one trap. For an instruction access fault, mepc is the target, not the jump. When jalr jumped to the unmapped address 0x20000, the jump itself succeeded and the next step, fetching, failed, so mepc and mtval were both 0x20000. A misaligned target, by contrast, is raised by the jump instruction itself. The spec note says that instruction-address-misaligned exceptions are raised by control-flow instructions with misaligned targets, not by the act of fetching. With C off, jalr x0, 2(t1) (a jump to a 2-byte position that is not 4-byte aligned) gave mcause=0, mepc equal to that jalr, and mtval equal to the target. The same test with the default C-on configuration (-cpu rv64) raised no trap, because a 2-byte-aligned target is legal. This rule follows directly from Part 21's compressed instructions and IALIGN (instruction alignment: 16 bits with C, 32 without).

An interrupt points at the instruction not yet executed. That instruction has not run, so a handler that only does mret continues from it. In the test, a pending MSI was held while csrs mstatus, MIE turned interrupts on, and the address of the very next instruction was recorded. mepc equalled that next instruction, because the enabling csrs had already completed (the spec requires the conditions to be re-evaluated right after a write to a CSR such as mstatus, 3.1.9).

mepc itself is WARL. Bit 0 is always 0, and on an implementation with IALIGN=32 bit 1 is also masked when read (including the implicit read by mret). It must be able to hold every valid virtual address, and the rest is up to the implementation (3.1.14). In a design, the usual choice is to make mepc as wide as pc and mask only the low bits.

4. mcause and mtval: different contents for different events

mcause only says why. Where and which instruction is the job of mtval. The spec says only that mtval is "exception-specific information" and leaves it to the platform which exceptions write something useful (3.1.16). So the table below is what QEMU actually wrote, not what the spec requires.

Illegal instruction: mtval is the instruction bits 0xffffffff. ebreak: the instruction's own address. ecall: 0. lr.w misaligned: the access address. Jump to an unmapped address: mepc and mtval both 0x20000. Load from an unmapped address: 0x20000. Sv39 page faults 13, 15, 12: the virtual address 0x20000

Some details:

  • Illegal instruction: .word 0xffffffff gave 0xffffffff, csrw mhartid, zero gave 0xf1401073, and reading the nonexistent CSR with csrr t0, 0x5c0 gave 0x5c0022f3 in mtval. If a nonzero value is written, the spec says it is the shortest of the actual instruction, the first ILEN bits and the first MXLEN bits, right-justified, and writing 0 is also allowed. A value of 0 then means either "not supported" or "a zero-filled instruction was fetched", so telling them apart requires re-reading memory at mepc. QEMU gave mtval=0 for .word 0x00000000. Having the instruction bits saves instruction emulation (for example, emulating an FPU in software) from reloading them via mepc.
  • Breakpoint: for ebreak, mtval was its own address (the same as mepc). The spec says that if a nonzero value is written, it is the address.
  • ecall: 0.
  • All address exceptions: misaligned, access fault and page fault write the accessed virtual address. The spec adds one thing: with paging on, "mtval is written with the faulting virtual address, even for physical-memory access-fault exceptions. This design reduces datapath cost for most implementations, particularly those with hardware page-table walkers."

We checked the last one with Sv39. In S-mode we turned on satp (one root table with a few 1 GiB gigapages) and accessed different virtual addresses with the same ld. In every case mtval was the virtual address.

Virtual address Situation mcause
0x20000 invalid PTE; load, store, jump 13, 15, 12
0x40020000 valid leaf, physical 0x20000 does not exist 5
0xC0000000 U=1 page, S-mode with SUM=0 13
0x100000000 next-level table pointer points at a nonexistent physical address 5
0x4000000000 non-canonical Sv39 address (upper bits differ from bit 38) 13

The second and fourth rows deserve attention. They are access faults (5), yet mtval was the virtual address 0x40020000, not the physical address 0x20000. An access fault in the middle of the walk (fourth row) and one after the walk (second row) use the same cause number, so mcause alone cannot tell them apart. What order the page-table walker checks things in is built in Part 31.

QEMU mostly did not raise misaligned exceptions. Plain lw, lh, ld, sw and sd at odd addresses, to RAM and to the UART (MMIO), raised no trap in nine out of nine cases. lr.w (4), sc.w (6), amoadd.w (6) and amoadd.d (6), on the other hand, always trapped at odd addresses, with mtval equal to the access address. This does not contradict the spec. Unprivileged 2.6 lets the execution environment handle misaligned loads and stores in hardware, or raise an address-misaligned or access-fault exception. Atomic instructions (chapter 14) are specified to raise an address-misaligned or access-fault exception. Implementations choose, so when you design one you must tell software which you chose (through the platform documentation rather than a configuration register).

5. mtvec: direct mode and vectored mode

mtvec consists of BASE (upper bits) and MODE (low 2 bits). Mode 0 (Direct) sends every trap to BASE. Mode 1 (Vectored) sends synchronous exceptions to BASE and interrupts to BASE + 4 x cause. Values of 2 and above are reserved, and Part 23 showed that writing 2 or 3 makes the whole write ignored. The spec's example: "a machine-mode timer interrupt causes the pc to be set to BASE+0x1c."

The test builds a 256-byte-aligned table vtable with a 4-byte jump (j vec_N) in each slot, and vec_N records vecidx = N. Writing mtvec = vtable | 1 and reading it back gave 0x80000401. We triggered three events.

A 16-slot table for mtvec 0x80000401. Slot N is at BASE+4N. ecall went to slot 0, the software interrupt (MSI) to slot 3, and the timer interrupt (MTI) to slot 7

Event mcause Slot taken
ecall 11 0
MSI (CLINT msip=1) 0x8000000000000003 3
MTI (mtimecmp=0) 0x8000000000000007 7
MSI, direct mode (mtvec=trap_entry) 0x8000000000000003 (table not used)

The cost of vectored mode is a design decision. Each slot is 4 bytes, so it holds only one jump, and the real handler runs at the jump's destination. Slot 0 receives all synchronous exceptions, so its jump plays the role of the handler in direct mode. The spec allows vectored mode to have stricter alignment than direct mode, and a note gives the reason: coarser alignment lets BASE + 4 x cause be built without an adder. For example, requiring BASE to sit on a 64-byte boundary (16 slots x 4 bytes) leaves the low 6 bits at 0, so the address is {BASE[63:6], cause[3:0], 2'b00}. QEMU requires only 4-byte alignment for BASE, so the 256-byte alignment of vtable was our own choice.

6. mret: undoing one level

mret is the inverse of what a trap does. The spec (3.1.6.1) defines xRET like this. With xPP holding y: set xIE to xPIE, change the mode to y, set xPIE to 1, set xPP to the least-privileged mode supported (U if U is implemented, otherwise M), and if y is not M, also set MPRV to 0. pc becomes mepc. The values we saw match this exactly. In the figure above, right after mret, MPIE=1 and MPP=0.

Rule Test Result
MIE <- MPIE, MPIE <- 1 start with MIE=1 and 0 figure above
MPP <- least-privileged mode with U / without U 0 / 3
returning to MPP=M keeps MPRV set MPRV=1, ecall stays 1
returning to MPP!=M clears MPRV set MPRV=1, drop to U 0

In a configuration without U (-cpu rv64,h=false,s=false,u=false), MPP stayed 3 even after mret. "Set to the least-privileged mode" simply means M there. The spec note gives the reason for making MPP the least-privileged mode: it helps identify software bugs in managing the two-level privilege stack.

Two things are easy to miss in a design. One is MPRV. MPRV means "M-mode loads and stores use the privilege of MPP", and mret to a lower mode must clear it automatically. If that is missing, translation and protection rules get tangled in lower modes. The other is re-evaluating interrupts right after mret. When MIE returns to 1, an interrupt that was pending must be taken in front of the instruction after mret (3.1.9 requires re-evaluation right after an xRET).

There is one more point about LR/SC. The spec says xRET is allowed to clear an LR reservation but is not required to; a handler that needs it cleared must do so itself, for example with a dummy sc (3.3.2). It meets the reservation-set policy of Part 20.

7. Nested traps and mscratch

mepc, mcause, MPIE and MPP, written at trap entry, exist in only one copy. If another trap arrives before the handler is done, the earlier values are overwritten. A spec note says that trap handlers must neither enable interrupts nor cause exceptions while saving the state needed to resume. We tested what actually happens.

We made code in S-mode do an ecall, held one pending MSI, and let the handler enable MIE before saving (nest_safe=0). The result:

Item Right after the outer (ecall) entry After the inner trap returned
mepc 0x80000820 (the ecall) 0x800002fc (inside the handler)
MPP 1 (S) 0 (U)
MPIE 1 1
mode the handler returned to the next ecall had mcause 8 (U)

The inner trap (the MSI) came in while M-mode handler code was running, so mepc became an address inside the handler, and the inner mret set MPP to U (0). The information that the outer trap came from S was lost. If the handler had saved the return address separately, the address could be recovered, but there was nothing saved for the mode. When the code after the ecall ran, it ran in U, not S, and the next ecall had mcause 8. For the hardware this is normal (it followed the rules). It is software that broke the rules.

The fix is nest_safe=1. The handler first saves mepc and mstatus on the stack, enables interrupts, and restores them when it comes back. In the same test mepc and MPP are overwritten in the same way inside, but they are restored, and this time the next ecall had mcause 9 (S). The skeleton of the handler becomes this order.

# ecall handler (safe version), excerpt
trap_entry_nest:
    csrr t0, mepc
    sd   t0, 24(sp)    # 1) save return address, state
    csrr t0, mstatus
    sd   t0, 16(sp)
    li   t0, 8
    csrs mie, t0       # 2) then open interrupts
    csrs mstatus, t0
    ...                # 3) do the work
    csrc mstatus, t0   # 4) close them again
    ld   t0, 24(sp)
    csrw mepc, t0      # 5) restore, then mret
    ld   t0, 16(sp)    #    (restore only MPP and MPIE)

A handler also needs registers to work with. At the handler's first instruction no register is free, because the user code's values must be preserved. mscratch is the CSR for this (3.1.13). Usually it holds "this hart's kernel stack (or per-hart structure) pointer", and csrrw sp, mscratch, sp swaps it with the user sp. Right after the swap sp is the kernel stack and mscratch keeps the user sp. Swapping again on the way out restores both.

The test had U set sp to a nonsense value (0x1234560) and then do ecall.

Item Value
mscratch seen in the handler (= user sp) 0x1234560
sp inside the handler 0x80002260 (32 bytes below the top of the kernel stack, 0x80002280)
user sp after return 0x1234560
mscratch after return 0x80002280 (back to the kernel stack)

Even though U's sp was unusable, the handler started on a safe stack and the user sp did not change by a single bit. A widely used convention to tell traps taken in M-mode apart is to keep mscratch=0 while in M-mode. If the sp swapped in at the first line is 0, the trap came from M, so you swap back and use it as is. This convention is a software agreement, not part of the spec.

8. Summary of the experiments: what we ran and how

trap_entry in start.S records (mcause, mepc, mtval, mstatus) into rec[] for each trap, clears the source if it is an interrupt, returns to the caller of enter_mode for an ecall with a7=0, and for every other exception adds 4 to mepc to skip the instruction. The essence is these lines.

trap_entry:             # entry for every trap (direct mode)
    addi sp, sp, -64    # keep t0..t6 on the stack
    ...
    csrr t0, mcause     # read the four values the hardware
    csrr t1, mepc       # wrote and copy them into rec[nrec]
    csrr t2, mtval
    csrr t3, mstatus    # MIE/MPIE/MPP right after entry
    ...
    bltz t0, intr       # sign: interrupt or exception

probe.c writes each test as TRY(name, instruction). Just before the instruction, la %0, 1f captures the instruction's address, and after the trap it is compared with mepc. There are three configurations.

Configuration QEMU -cpu Purpose
full rv64,c=false all the main tests
m_only rv64,c=false,h=false,s=false,u=false MPP after mret without U
with_c rv64 jalr to odd+2 raises no trap when C is on

check.py compares 62 expected values computed from the spec, and all matched. Representative ones:

Expectation Result
ecall mcause: U 8, S 9, M 11 matched
synchronous exception mepc = that instruction (including ecall, ebreak) matched
vectored slot number = interrupt number, synchronous exceptions in slot 0 matched
after entry MIE=0, MPIE=previous MIE, MPP=previous mode matched
after mret MIE=MPIE, MPIE=1, MPP=U (or M) matched
enabling MIE before saving overwrites mepc and MPP matched

QEMU did not disagree with the spec anywhere. But it did expose several places where the spec leaves things to the implementation. Misaligned loads and stores were handled without a trap (section 4), the mtval of an illegal instruction was the instruction bits, and the mtval of ebreak was pc. Another core doing these differently would not violate the spec. Software written for these tests must use mtval as "use it if present, read mepc if 0" to be portable.

9. Design checklist: trap entry and mret

Item Rule
Write all at once Apply mepc, mcause, mtval, MIE, MPIE, MPP, mode and pc in the same cycle. No moment where only some are visible
The trapping instruction mepc is the instruction that raised the exception. All earlier instructions finish, and that instruction and the following ones change no state
mepc for interrupts The next instruction not yet executed. Right after a branch, the branch result address
ecall, ebreak mepc is the instruction itself. They do not retire, so they are not counted in minstret
Misaligned Distinguish the jump raising it (mepc=jump) from fetch raising it (mepc=target). With IALIGN=16, 2-byte alignment is legal
mtval policy Virtual address for address exceptions (access faults too when paging). Instruction bits or 0 for illegal instruction, 0 for ecall. Document the policy
mcause Top bit is the interrupt flag. The rest is WLRL, so unimplemented numbers need not be representable
mtvec Ignore writes with MODE >= 2 (Part 23). Choose vectored-mode alignment so BASE + 4 x cause is a concatenation
On entry MPIE <- MIE, MIE <- 0, MPP <- mode. A readable MIE is 0 after the trap
mret MIE <- MPIE, MPIE <- 1, MPP <- least-privileged mode, mode <- MPP, clear MPRV if MPP is not M, pc <- mepc
Re-evaluate interrupts Right after mret and after writes to mstatus, mie, mip, mideleg
mscratch Readable and writable for the csrrw sp, mscratch, sp at the handler's first line, and untouched by traps
Nesting mepc and MPP exist in one copy, so software enables MIE only after saving them

Summary

  • A trap writes mepc, mcause, mtval and, in mstatus, MIE -> MPIE, mode -> MPP, pc <- mtvec all at once, and mret undoes it with MIE <- MPIE, MPIE <- 1, MPP <- least-privileged mode, pc <- mepc. QEMU's mstatus matched this rule exactly (0, 1, 3 with MIE=1, then 1, 1, 0 after mret).
  • mepc is the instruction itself for exceptions (ecall too) and the next instruction for interrupts. An instruction access fault gives the target, and a misaligned target is raised by the jump. Vectored mode sent interrupts to BASE + 4 x number (MSI 3, MTI 7) and synchronous exceptions to slot 0.
  • mtval differs by event and is up to the platform. It was the instruction bits for an illegal instruction, pc for ebreak, and the virtual address for address exceptions. QEMU raised no trap for plain loads and stores at odd addresses and raised them only for lr, sc and AMOs.
  • mepc and MPP exist in one copy, so enabling interrupts before saving them overwrites them. In the measurement, code meant to return to S returned to U. Swapping sp through mscratch gave a safe stack and kept the user sp intact.

Next: Part 26 is the second half of traps. We look at delegating traps to S-mode with medeleg and mideleg, the S-mode trap CSRs (stvec, sepc, scause, stval, sstatus.SPP and SPIE), which traps can and cannot be delegated, the priority of synchronous exceptions and of interrupts, how mstatus.MIE and sstatus.SIE gate interrupts in each mode, and WFI with TW, all with the same QEMU experiments.

References

  • The RISC-V Instruction Set Manual, Volume II: Privileged Architecture, Version 20240411. 3.1.6.1 Privilege and global interrupt-enable stack in mstatus, 3.1.7 mtvec, 3.1.9 mip and mie, 3.1.13 mscratch, 3.1.14 mepc, 3.1.15 mcause (cause table, synchronous exception priority), 3.1.16 mtval, 3.3.1 ecall and ebreak, 3.3.2 Trap-return instructions. https://github.com/riscv/riscv-isa-manual
  • The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture, Version 20240411. 2.5 Control transfer instructions (instruction address misaligned), 2.6 Load and store (the execution environment's choice for misaligned accesses), 2.8 ecall and ebreak, chapter 14 A extension (alignment of atomics).
  • D. Harris et al., RISC-V System-on-Chip Design, 2023. Privileged unit and trap handling implementation (CORE-V Wally)
  • QEMU documentation: RISC-V virt board and CPU options. https://www.qemu.org/docs/master/system/target-riscv.html

Similar posts