Skip to content
systemcoding.dev
Assembly

Handle Traps in RISC-V Machine Mode With mtvec, mepc and mcause

Write a RISC-V machine-mode trap handler in assembly: set mtvec, save registers, decode mcause, advance mepc past ecall and return with mret.

7 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the RISC-V, Linux and AMD logos.

A RISC-V core that takes a trap does not push a frame, switch stacks or consult a vector table in memory. It writes four control registers, jumps to one address and leaves everything else to you. Every byte of that handler is your code, which is why a wrong mepc or a forgotten mret turns into a hang with no message. This post builds a complete machine-mode trap handler for an RV64 core following the privileged architecture specification 1.12: the boot code that installs it, the assembly entry that saves state, a C routine that decodes mcause, and the return path. We assume a bare-metal program running in M-mode from reset, such as the one a riscv64-unknown-elf-gcc 14 cross toolchain produces for the QEMU virt machine.

What the hardware does on a trap

When an exception or interrupt is taken in M-mode, the hart performs a fixed set of updates, described in the privileged specification chapter on machine-level CSRs:

RegisterWhat the hardware writes
mepcThe address of the instruction that trapped (for an interrupt, the one that would have run next)
mcauseThe reason: top bit set for an interrupt, low bits hold the code
mtvalExtra detail, such as the faulting address or the illegal instruction bits, or zero
mstatusMPIE gets the old MIE, MIE is cleared, MPP gets the privilege level before the trap
pcSet from mtvec

Nothing else changes. All 31 general registers still hold the interrupted code's values, and sp still points wherever the interrupted code left it. That is the whole contract, and it explains the shape of every handler: first save what you will clobber, then work, then restore, then mret, which copies mepc back into pc and restores MIE from MPIE.

Install the vector with mtvec

mtvec holds a base address and a two-bit mode. Mode 0 is direct: every trap goes to BASE. Mode 1 is vectored: interrupts go to BASE + 4 * cause, while exceptions still go to BASE. Direct mode is simpler and what we use here. The spec requires BASE to be 4-byte aligned, so the handler label needs .align 2, and a handler written for vectored mode needs more alignment because of the jump table.

start.Sasm
    .section .text.init
    .globl _start
_start:
    la      sp, _stack_top          // M-mode stack for the handler and for main
    la      t0, trap_entry
    csrw    mtvec, t0               // direct mode: low two bits are 0

    csrr    t1, mstatus
    li      t2, (1 << 3)            // MSTATUS_MIE
    or      t1, t1, t2
    csrw    mstatus, t1             // global interrupt enable (exceptions never need it)

    call    main
1:  wfi
    j       1b

Exceptions do not depend on mstatus.MIE, so the handler already works before this write. The MIE bit only gates interrupts, which later posts on this cluster cover with the CLINT and PLIC.

Save registers in the entry stub

The entry point runs with the interrupted code's registers live, so it must spill every register the C handler may overwrite. The RISC-V calling convention lets a called function clobber ra, t0 to t6 and a0 to a7, so those 16 are the minimum. Saving all 31 is easier to reason about and lets the handler edit a saved register, which matters in the next section.

trap.Sasm
    .section .text
    .align  2
    .globl  trap_entry
trap_entry:
    addi    sp, sp, -256            // 32 slots of 8 bytes keeps sp 16-byte aligned
    sd      x1,   8(sp)
    sd      x3,  24(sp)
    sd      x4,  32(sp)
    sd      x5,  40(sp)
    sd      x6,  48(sp)
    sd      x7,  56(sp)
    sd      x8,  64(sp)
    sd      x9,  72(sp)
    sd      x10, 80(sp)
    sd      x11, 88(sp)
    sd      x12, 96(sp)
    sd      x13, 104(sp)
    sd      x14, 112(sp)
    sd      x15, 120(sp)
    sd      x16, 128(sp)
    sd      x17, 136(sp)
    sd      x18, 144(sp)
    sd      x19, 152(sp)
    sd      x20, 160(sp)
    sd      x21, 168(sp)
    sd      x22, 176(sp)
    sd      x23, 184(sp)
    sd      x24, 192(sp)
    sd      x25, 200(sp)
    sd      x26, 208(sp)
    sd      x27, 216(sp)
    sd      x28, 224(sp)
    sd      x29, 232(sp)
    sd      x30, 240(sp)
    sd      x31, 248(sp)

    mv      a0, sp                  // a0 = pointer to the saved frame
    csrr    a1, mcause
    csrr    a2, mepc
    csrr    a3, mtval
    call    trap_handler
    csrw    mepc, a0                // handler returns the pc to resume at

x0 is hard-wired to zero and x2 is sp itself, so slots 0 and 2 stay empty. The frame is 256 bytes because the psABI wants sp 16-byte aligned at a call, and 32 slots of 8 bytes satisfies that without arithmetic. The handler receives the frame pointer, the cause, the mepc value and mtval, in the argument registers a0 to a3. Its return value goes back into mepc, which lets C decide where execution resumes.

The restore half mirrors the saves and ends with mret:

trap.Sasm
    ld      x1,   8(sp)
    ld      x3,  24(sp)
    ld      x4,  32(sp)
    ld      x5,  40(sp)
    ld      x6,  48(sp)
    ld      x7,  56(sp)
    ld      x8,  64(sp)
    ld      x9,  72(sp)
    ld      x10, 80(sp)
    ld      x11, 88(sp)
    ld      x12, 96(sp)
    ld      x13, 104(sp)
    ld      x14, 112(sp)
    ld      x15, 120(sp)
    ld      x16, 128(sp)
    ld      x17, 136(sp)
    ld      x18, 144(sp)
    ld      x19, 152(sp)
    ld      x20, 160(sp)
    ld      x21, 168(sp)
    ld      x22, 176(sp)
    ld      x23, 184(sp)
    ld      x24, 192(sp)
    ld      x25, 200(sp)
    ld      x26, 208(sp)
    ld      x27, 216(sp)
    ld      x28, 224(sp)
    ld      x29, 232(sp)
    ld      x30, 240(sp)
    ld      x31, 248(sp)
    addi    sp, sp, 256
    mret

Decode mcause in C

mcause packs two things. On RV64 the most significant bit is the interrupt flag, and the rest is the exception or interrupt code. A handler therefore tests the sign of the value first, then switches on the low bits:

trap.cc
#include <stdint.h>

extern void uart_puts(const char *s);
extern void uart_hex(uint64_t v);

#define MCAUSE_INTERRUPT (1ULL << 63)

uint64_t trap_handler(uint64_t *frame, uint64_t mcause,
                      uint64_t mepc, uint64_t mtval)
{
    if (mcause & MCAUSE_INTERRUPT)
        return mepc;                         // interrupts resume in place

    switch (mcause) {
    case 2:                                  // illegal instruction
        uart_puts("illegal instruction at ");
        uart_hex(mepc);
        uart_puts(" bits ");
        uart_hex(mtval);
        uart_puts("\n");
        for (;;) ;                           // nothing sensible to resume
    case 11:                                 // environment call from M-mode
        uart_puts("ecall, a7=");
        uart_hex(frame[17]);                 // saved a7 lives in slot x17
        uart_puts("\n");
        return mepc + 4;                     // skip the 4-byte ecall
    default:
        uart_puts("unhandled cause ");
        uart_hex(mcause);
        uart_puts("\n");
        for (;;) ;
    }
}

Two details deserve attention. An interrupt returns mepc unchanged because the saved address is the instruction that never executed. A synchronous exception such as ecall leaves mepc pointing at the trapping instruction itself, so returning it unchanged re-executes the call forever. The handler has to move it forward, and it has to move it by the right amount: 4 for the 32-bit ecall and ebreak, but 2 for the compressed c.ebreak when the C extension is on. A careful handler reads the halfword at mepc and checks whether its low two bits are 11 before choosing the step.

Code 2 is an illegal instruction, and the spec says mtval may hold the offending instruction bits, though an implementation is free to leave it zero. Treat it as a hint, not a guarantee.

A short caller proves the path end to end:

main.cc
void main(void)
{
    register unsigned long a7 asm("a7") = 93;
    asm volatile ("ecall" : : "r"(a7));
    extern void uart_puts(const char *);
    uart_puts("back from ecall\n");
}
Text
ecall, a7=0x000000000000005d
back from ecall

The a7 value of 93 prints as 0x5d, which shows the handler read the register of the interrupted code, not one the entry stub reused. Without the mepc + 4, the output would show the first line repeating until you stopped the machine.

Failure you will hit first

The most common mistake is a handler that works once and then locks up. The usual causes, in order of how often they appear:

  • mtvec was written with a label that is not 4-byte aligned, so the low bits select a vectored mode by accident and traps land at the wrong address.

  • The handler returns with ret instead of mret. ret jumps to ra, which holds some stale value, and MIE is never restored.

  • The stub saved registers but the C code ran with a bad sp, because sp was never initialized before the first trap.

  • mepc was not advanced after a synchronous exception.

Where this design stops

A single stack for the handler and the interrupted code is fine when the interrupted code is trusted. It is wrong once you run user code in U-mode, because a user program could hand you a bad sp. Real kernels swap in a kernel stack using mscratch for exactly this reason: the entry stub starts with csrrw sp, mscratch, sp, which exchanges the user sp for the kernel one in a single instruction with no register spared. This post leaves that out because a bare-metal M-mode program has no other privilege level to protect.

Also inKernels
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.