Skip to content
BIASED

Exceptions and interrupts

Block 1 of 4~2 min

Exception, interrupt, trap

Five instructions may be in flight when something goes wrong: a bad page, an illegal word, a kernel request, a timer. RISC-V names: an exception is tied to an instruction of this hart; an interrupt is asynchronous from outside; a trap is the control transfer either causes.

Modes: U (0) < S (1) < M (3). Traps only go up; mret/sret go down. Linux: firmware M, kernel S, programs U.

Worked example. Before the ecall, mstatus has MIE = 1, MPIE = 1, MPP = U: the value 23+27=136=2^3 + 2^7 = 136 =23+27=136= 0x88 in its low bits. On trap entry MIE becomes 0 and MPP stays 00 for U, so mstatus reads 0x80, and the hart jumps to 0x80000100. Step 5 matters: by step 2, mepc points at the ecall itself, not after it (RISC-V Privileged ISA, section 3.3.1). Without the + 4, mret would return to the ecall, which would trap again, forever. For a page fault the handler does the opposite and leaves mepc alone, so the load runs again once the page is mapped. The Code section runs this sequence in a model of the hart.

Vectored mode saves those instructions on every interrupt, which matters most where interrupts are frequent and must be served fast, as in microcontrollers that react to sensors. How much do a few instructions matter? A timer that fires 1000 times a second with a handler of 2000 cycles costs 2×1062 \times 10^62×106 cycles per second, 0.1 % of a 2 GHz core; skipping ten dispatch instructions per interrupt changes the total cost by less than 1 % of that. The point of vectoring is the latency to the first useful instruction, not the throughput.

Answers are saved on the server and tied to this browser until you sign in.