notes

Exceptions

One mechanism, three purposes

The most important thing to see before building any of it: on aarch64 these are the same mechanism.

Cause Milestone
Fault bad memory access, illegal instruction, misaligned sp 2 (here)
Interrupt the timer fires, the UART has a byte 5
System call userspace executes svc 7

All three suspend the current instruction stream, switch to EL1, and jump to an address the kernel chose. Only the reason differs. So we build the plumbing once, in milestone 2, and milestones 5 and 7 are mostly a matter of adding cases to a match.

The table's shape is dictated by silicon

VBAR_EL1 holds the base address of the vector table. When an exception fires, the hardware computes the target as VBAR_EL1 + a fixed offset, where the offset is determined by two things: where the exception came from, and what kind it is.

Four sources × four kinds = 16 entries, each exactly 128 bytes, and the whole table must be 2048-byte aligned.

offset  source                    kind
0x000   Current EL, SP_EL0        Synchronous
0x080                             interrupt
0x100                             FIQ
0x180                             SError
0x200   Current EL, SP_ELx        Synchronous   <- a kernel bug lands HERE
0x280                             interrupt           <- the timer, milestone 5
0x300                             FIQ
0x380                             SError
0x400   Lower EL, AArch64         Synchronous   <- `svc` lands HERE, milestone 7
0x480                             interrupt
0x500                             FIQ
0x580                             SError
0x600   Lower EL, AArch32         Synchronous
0x680                             interrupt
0x700                             FIQ
0x780                             SError

The 2048-byte alignment is not style. The CPU assumes the low 11 bits of VBAR_EL1 are zero. A misaligned table sends every exception in the machine to a wrong address. There's a test for it.

The four kinds

The four sources

128 bytes is 32 instructions

That's enough to save state and branch. It is nowhere near enough to do real work. This constraint is why every aarch64 kernel on earth looks nearly identical right here: each slot saves the register file, records which slot it was, and branches to common code.

Our VECTOR_ENTRY macro comes to 24 instructions. Comfortable, but not by much.

The trap frame

SAVE_CONTEXT pushes 272 bytes onto the kernel stack: x0–x30, plus ELR_EL1, plus SPSR_EL1, plus 8 bytes of padding to keep sp 16-byte aligned (nifeos/nife:notes/stack.md).

This is the registers.md punchline made real. The register file is the CPU's state. Save it, and you have frozen exactly what the machine was doing. Restore it, and execution resumes with no way to detect the interruption ever happened.

Two registers beyond the general-purpose file are essential:

The layout is a contract with assembly

struct TrapFrame in exceptions.rs must match SAVE_CONTEXT in vectors.s byte for byte. The compiler cannot check this. There is a const _: () = assert!(size_of::<TrapFrame>() == 272), which catches maybe half the ways to get it wrong. It will not catch two same-typed fields being swapped.

A bug here is the nastiest possible failure: it scrambles a register while still returning happily to the right address, corrupting the caller's state and blaming a completely innocent piece of code thousands of instructions later. registers_survive_an_exception exists purely to catch it.

ESR_EL1 tells you what happened

The Exception Syndrome Register. Bits 31:26 hold the Exception Class (EC), and it is the single most useful field in the machine when something has gone wrong.

EC Meaning
0x15 SVC from AArch64: a system call. Milestone 7 (user mode).
0x21 Instruction abort, same EL: we jumped somewhere bad
0x24 Data abort, lower EL: userspace touched bad memory. Milestone 7 makes this a segfault.
0x25 Data abort, same EL: the kernel touched bad memory. Our bug.
0x26 SP alignment fault: sp wasn't 16-byte aligned
0x3c BRK instruction

FAR_EL1 (Fault Address Register) holds the address that faulted, but only for aborts and alignment faults. For anything else it's stale garbage from some earlier fault. Printing it unconditionally would be a lie, so fatal() checks the EC first.

brk vs svc: the gotcha

ELR_EL1 points at different places depending on the exception.

For svc, the hardware sets ELR_EL1 to the instruction after the svc. You handle the system call and eret, and the program continues normally.

For brk, ELR_EL1 points at the brk itself. So a naive eret re-executes it, forever.

Stepping over it means advancing ELR_EL1 by one instruction:

frame.elr += 4;

Four, because every aarch64 instruction is exactly 4 bytes. The fixed-width design we admired in aarch64.md is what makes this a += 4 rather than an instruction decode. On x86 you would have to disassemble the instruction to know how long it was.

The ISB that is easy to forget

VBAR_EL1.set(base);
barrier::isb(barrier::SY);

An Instruction Synchronization Barrier forces the CPU to discard everything it has already fetched or speculated past this point, and start again.

Without it, the write to VBAR_EL1 is not architecturally guaranteed to be in effect for the very next instruction. And "the very next instruction" is exactly when a fault might arrive.

One line. Easy to leave out. Leaving it out produces a bug that appears only under timing you cannot reproduce.

What a fault looks like now

Before milestone 2, a bad memory access killed the machine in silence. Now:

[EXCEPTION]  Current EL, SP_ELx, Synchronous
             Data abort from the same EL (EC 0x25)

  ESR_EL1   0x0000000096000050   what happened
  FAR_EL1   0x00000000dead0000   the address that faulted
  ELR_EL1   0x0000000040081a40   the instruction that did it
  SPSR_EL1  0x00000000400003c5   the state it was in

  x0  0x0000000000000001  x1  0x0000000000000008  ...

FAR_EL1 is the address we tried to touch. ELR_EL1 is the instruction that touched it, and rust-objdump or GDB will turn it straight into a source line.

The exception-return race: mask interrupts before you touch SPSR and ELR

Found 2026-07-29, while landing milestone 22 phase B.2, from a failure that reads as impossible:

[EXCEPTION]  Current EL, SP_ELx, Synchronous
             Instruction abort from the same EL (EC 0x21)
  FAR_EL1   0x0000000000400000      <- a USER code address
  ELR_EL1   0x0000000000400000
  SPSR_EL1  0x0000000060000345      <- M[3:0] = 0b0101 = EL1h

The kernel was at EL1, executing at the user's entry point, and faulted because a user code page is not executable from EL1 (PXN). x0 held the init role and x1 the initrd length, so the trap frame we had just fabricated was intact and correct. Only the exception level was wrong.

The mechanism. SPSR_EL1 and ELR_EL1 are the eret's only record of where to go and at what level, and they are single copies the hardware overwrites on every exception. RESTORE_CONTEXT wrote them from the frame, then restored the general registers, then eret'd. An interrupt taken between the msr spsr_el1 and the msr elr_el1 two instructions later does this:

  1. hardware saves the interrupted EL1 state into SPSR_EL1/ELR_EL1, clobbering ours;
  2. the nested handler runs and its own RESTORE_CONTEXT puts the EL1 state back (SPSR = EL1h);
  3. execution resumes at msr elr_el1, x1, which sets ELR back to the user entry;
  4. our eret returns to the user's entry point at EL1.

Why it was rare, and why it showed up now. On a normal trap return the window is already closed, because taking the exception set PSTATE.DAIF. The exposed path is enter_userspace, which branches into exception_restore from ordinary kernel code with interrupts enabled, so every first entry to a process carried a two-instruction window. Phase B.2's supervision-tree tests enter several more processes per run, and the suite started failing about one run in four.

The fix is one instruction at the top of RESTORE_CONTEXT:

    msr     daifset, #0xf

It costs nothing at the far end, because the eret restores DAIF from SPSR anyway, so the state we return to is unchanged. It lives in the macro rather than in enter_userspace so that any future path reaching the restore with interrupts on is covered by construction.

RISC-V had the same window, found by inspection rather than by a failure. trap_return writes sepc and then sstatus. A trap taken between the two leaves sepc pointing at kernel code while sstatus says "return to U-mode", so the sret would drop a user thread into a kernel address. Closed the same way, with csrci sstatus, 2 (clear SIE) at the top of trap_return. On that side the trap-return path was already safe, because trap entry clears SIE and the frame's saved sstatus carries SIE = 0 through the csrw; again it is the first-entry path (user_return) that was exposed.

The general lesson, which generalizes past these two files: any sequence that stages return-from-exception state in architectural registers must be atomic with respect to exceptions. There is one copy of those registers, so a nested exception is a write to the thing you are building.

So we went looking for the siblings, in both architectures' assembly, and wrote down what we found and what we cleared: arch-audit.md. One correction it makes to the account above, worth carrying here: the claim that the mask "covers any future path by construction" is true on aarch64 and not on RISC-V. sstatus is one register holding both the staged fields and the live SIE bit, so trap_return's own csrw sstatus would put interrupts back on if a frame ever carried SIE = 1. It never does, and now the compiler enforces that rather than a comment asking for it.

The dispatcher's arms, and what each relies on

kernel/src/arch/aarch64/exceptions.rs dispatches an interrupt by vector slot and everything else by ESR_EL1's class. Slots 8 to 11 are "Lower EL, AArch64": the same class is a kernel bug that halts the machine at slot 4 and a user bug that kills one thread at slot 8.

A user fault is published, then counted

user_fault writes the fault record (its kind and address) with two relaxed stores, then bumps USER_FAULTS with Release. last_user_fault issues an Acquire fence before reading the record. Every reader finds the record by watching the counter rise, so the counter is the publication flag and must be written last. Written first, a reader gets the record of an earlier fault, or, for the first fault of a boot, a zero that reads as "no user thread has faulted"; ARM permits exactly that reordering.

user_fault can simply hand the thread to sched::fault, which does not return: the thread is not resumed, exception_restore is never reached, and the kernel stack it stands on is freed by the next thread, for the reason in threads.md.

Entering EL0 for the first time

enter_user is #[inline(always)] because the trap frame it loads sits at the top of the caller's own kernel stack, overlapping live call frames. It survives only until enter_userspace does mov sp, x0, and only if nothing is pushed in between; a real call would push a return address over it (seen as a child thread with sp_el0 = 0). It also refuses a frame with elr == 0, which would fetch from address 0 and end far from the cause in the lost-wakeup watchdog. The check is a load and a branch on the frame, and its panic path is out of line and reads its argument first, so nothing is pushed over the frame before it is read.

The split around the interrupt stack

exception_dispatch chooses the stack the handler runs on and, after it returns, runs any deferred schedule(). exception_body is the handler proper and may run on the per-core interrupt stack. schedule() parks the running sp in the outgoing thread, so it may run only on a stack the thread owns; kernel/src/interrupt_stack.rs holds the rule. The interrupt handler writes end-of-interrupt before returning, so the GIC is not left refusing interrupts to the thread switched to.

Costs the debug build pays

An opt-level 0 kernel inlines nothing, and these two choices come from measuring one. So the branch for "no stack switch", which every system call takes, is made in Rust rather than in the trampoline (routing it through anyway cost 8.6 instructions per null_system_call). And is_from_lower_el is two comparisons written out under #[inline(always)], because (8..=11).contains(&index) is a real call into RangeInclusive on every trap at opt-level 0.

What moves out of fatal() next

Every case currently falls into fatal(). As the kernel grows, they migrate into real handlers:

The plumbing is already there. Those milestones are mostly a matter of adding arms to a match.


Add to this file as new exception classes come up.