
Recall first from What a trap is and the trap CSRs
- Supervisor exceptions and interrupts use the same trap mechanism, and RV64 scause bit 63 distinguishes their classes.
- On supervisor trap entry, the hart records the saved PC in sepc, the cause in scause, and cause-dependent information in stval.
- The hart records the previous privilege in sstatus.SPP, saves SIE in SPIE, and clears SIE on entry.
Point stvec at the assembly entry
3 min readThe last lesson named the trap CSRs. Now you point stvec at a handler and write the assembly entry that saves all registers and sepc into a trap frame.
Consider an interrupt that arrives while the kernel has a value in a0. The assembly entry also needs a0 to pass the frame address to Rust. If the first instruction that touches a0 replaces its value with that address, the interrupted code gets the wrong value when execution resumes. The address installed in stvec has to be valid in the execution environment in which the trap arrives, for example a physical address while paging is off.
stvec combines an entry address, called BASE, with a mode in its low two bits. In direct mode, those bits are zero. A four-byte-aligned entry symbol already has two zero low bits, so writing its address sets direct mode without a separate operation. This alignment applies even when the assembler can emit two-byte compressed instructions. During kernel initialization, with a valid stack already in use, install the vector on the current hart:
la t0, trap_entry
csrw stvec, t0
If you install the vector from Rust instead of assembly, write trap_entry as *const () as usize for the value you pass to csrw. With Rust 1.100.1 a direct trap_entry as usize compiles but prints the warning direct cast of function item into an integer (lint function_casts_as_integer).
Here trap_entry is the address of executable assembly and should be declared with .balign 4 before its label. These two instructions run during initialization, where t0 is available as a temporary. At trap entry, every writable integer register can contain a live value from the code that was interrupted.
In direct mode, every trap that enters S-mode starts at BASE. The processor selects that address for both interrupts and synchronous exceptions. A first kernel uses direct mode because one entry saves the same state in the same layout for every cause. You can review a single save and return sequence and let the Rust handler decide what happened after the interrupted registers are safe.
Going deeperExplore the mechanism
With stvec mode 1, synchronous exceptions still enter at BASE. An interrupt with cause number n enters at BASE + 4*n. Use the cause number by itself in that calculation. The high bit of scause identifies an interrupt and is excluded from n. For example, cause number 5 selects a location 20 bytes above BASE for an interrupt, while an exception with cause number 5 still enters at BASE.
A vectored implementation places instructions at those addresses, often one four-byte jump per slot. The BASE slot can jump to exception entry code. The interrupt slots can jump to cause-specific entry code that preserves the interrupted state before using any of its registers. A jump that discards its link, jal x0, target, leaves ra available to save with its interrupted value. The fixed stride is four bytes even on a core with compressed instructions. When building a table with one jump per slot, keep each jump four bytes wide and check the resulting slot positions. Vectored mode can impose stricter BASE alignment than direct mode.
Separate entry addresses can remove the common software branch that would otherwise select an interrupt handler based on its cause. The destination still has to preserve the state needed for a correct return. With a single common destination and the same cause dispatch as direct mode, the table by itself saves no dispatch work.
Save the interrupted integer state
4 min readAn ordinary function call comes with an agreement about registers. The caller expects some registers to change and saves any values it still needs from those registers. A trap can occur between instructions while those same registers contain live values. The entry stub has to preserve them before it can call a Rust function using the ordinary calling convention. The call instruction itself writes ra, and putting the first argument in a0 overwrites another interrupted value.
A a memory record of the state saved on trap entry and used during trap return is the agreement between the assembly and Rust. For the RV64 example, use 32 eight-byte slots in register-number order, then one eight-byte slot for sepc. The slot for x0 contains zero. The slot for x2, also called sp, contains the value from before the frame allocation. Those 33 slots occupy 264 bytes. Reserve 272 bytes, including eight bytes of padding, so that subtracting the frame size from a 16-byte-aligned stack pointer keeps it aligned for the Rust call.
This entry assumes a trap from S-mode code that is already using a valid, aligned kernel stack with enough free space for both the frame and the handler's call stack. The processor starts executing the entry with the interrupted sp. This example uses that value to allocate the frame. It also assumes the trap path leaves floating-point and vector state untouched. The 32 slots account for the integer registers. Linux's RISC-V vector documentation describes additional vector state, which would need its own preservation policy if the handler could modify it.
The following excerpt shows the ordering for the registers the stub itself changes first. The remaining register stores follow the same offset rule.
.balign 4
trap_entry:
addi sp, sp, -272
sd zero, 0(sp)
sd ra, 8(sp)
sd t0, 40(sp)
addi t0, sp, 272
sd t0, 16(sp)
csrr t0, sepc
sd t0, 256(sp)
After subtracting 272, the original sp is the current sp plus 272. Save the interrupted t0 in its own slot before using it to reconstruct the original sp or read sepc. To complete the save sequence, store x3, x4, and x6 through x31 at 8*n(sp) for register number n. The excerpt has already filled the slots for x0, x1, x2, and x5. The store for x10, which is a0, belongs at byte offset 80 and must happen before a0 is used to pass the frame address.
I assembled the complete entry (the excerpt above plus the 28 remaining sd lines, generated by a loop) and ran it on QEMU 8.2.2 with a repr(C) frame of [usize; 32] plus sepc (size_of is 264 bytes). The kernel set t1 = 0x2222, a0 = 0x1111, a1 = 0, ran ebreak, and the Rust handler printed the frame, bumped the saved sepc past the ebreak and wrote 0xdead into the frame slot of a1. Real output:
frame=0x80210c50 scause=0x3 sepc=0x802001a8 x10(a0)=0x1111 x6(t1)=0x2222 x2(sp)=0x80210d60 size=264
after: a0=0x1111 t1=0x2222 a1=0xdead sp_before=0x80210d60 sp_after=0x80210d60
The frame address 0x80210c50 is exactly the saved sp (0x80210d60) minus 272. The slot for x2 holds the interrupted sp, a0 and t1 came back unchanged, sp is the same after sret, and the edit made in the frame reached the register (a1 = 0xdead). That edit is how a system call will later return a value to its caller.
Call Rust and return with sret
3 min readOnce all the slots are filled, put the frame address in a0 with mv a0, sp, then use call rust_trap_handler. The assembly needs a Rust function exported under that symbol with the extern "C" calling convention, taking a raw pointer to the frame. The return sequence below assumes the function returns normally with sp back at the frame base. The frame stays allocated throughout the call. Any locations the Rust function reads or writes must match the offsets used by assembly.
There are two different return addresses in this sequence. The call sets ra to the point in the entry stub where assembly should continue after Rust returns. The saved sepc contains the address the eventual trap return will use. If the handler changes where the interrupted code should resume, it can change the saved sepc slot. The assembly reloads from that slot after the call, so sret uses the selected address.
Start restoring sepc while t0 is still available as a temporary. Then reload x1 and x3 through x31 from their numbered slots, including the original t0. Register x0 always reads as zero, so it needs no load. Leave sp pointing at the frame until every load that uses the frame base has finished. The return excerpt shows where the remaining loads belong.
ld t0, 256(sp)
csrw sepc, t0
ld ra, 8(sp)
# Reload x3, x4, and x6 through x31 here.
ld t0, 40(sp)
ld sp, 16(sp)
sret
The final load uses sp as both the address base and the destination. The address comes from the current frame base plus 16. The loaded value then becomes sp. After that instruction, loads relative to sp would use the interrupted stack pointer, so sret follows directly. A normal function return would jump through ra. sret uses sepc and applies the supervisor trap-return rules for privilege and interrupt state.
This small entry keeps the trap-return fields in sstatus available in the CSR and assumes the handler leaves them intact, keeps supervisor interrupts disabled during handling, and avoids another exception. A second trap could replace the live trap CSRs on the same hart. Saving sepc in memory gives the outer frame its own copy, but nested handling also needs a plan for preserving the other trap-return state. The frame in this lesson is enough for the stated single-entry path.
When reviewing an entry stub, trace a register that the interrupted code could still need. For a0, the original value goes into slot 10, the live register carries the frame pointer through the call, and slot 10 supplies the value on return. That trace checks both sides of the boundary between assembly and Rust. In The TrapContext and scause codes, you will give the frame a matching Rust layout and use scause to determine why the entry ran.
Key takeaways
- Direct mode sends every trap taken into supervisor mode to BASE.
- Vectored mode sends synchronous exceptions to BASE and interrupts to BASE plus four times the interrupt cause number.
- The assembly entry records all 32 integer register slots, including zero and the original stack pointer, and saves sepc before calling Rust.
- The return sequence writes sepc, restores the integer registers with sp last, and executes sret.
Reflect
- Explain to a colleague, in two sentences: encode a four-byte-aligned direct entry address in stvec
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Kernel documentationRISC-V Kernel Boot Requirements
- Kernel documentationRISC-V Vector Extension Support for Linux
Official documentation first. Links checked when the lesson was published.