A process calls write(fd, user_buf, 4096). The descriptor is valid, but user_buf + 4096 wraps around the machine word and the kernel checks only the starting address. A naive kernel then copies across an unintended mapping while executing with supervisor privilege. The trap instruction worked exactly as designed; the security failure occurred because privilege transfer is not argument validation.
A controlled entry must solve three different problems:
- transfer control without trusting a user-supplied destination;
- preserve enough interrupted state to resume or terminate correctly; and
- convert untrusted register values into validated kernel objects.
Prediction — what must already be safe?
At the first supervisor instruction after a user ecall, decide whether each item has already been established by hardware: kernel stack, kernel page table, complete general-register save, previous program counter, trap cause, interrupts disabled, trusted handler address.
HintExpandCollapse
Separate architectural CSRs from conventions implemented by entry assembly.
Worked solutionExpandCollapse
Hardware has written the interrupted PC to sepc, written the cause to scause, recorded the previous privilege and interrupt-enable state in sstatus, disabled supervisor interrupts, and set the PC from the protected stvec configuration. It has not selected a kernel stack, switched satp, or saved all integer registers. xv6’s first assembly instructions must preserve user registers while arranging those software-owned transitions. Treating a trap like a high-level function call misses the dangerous interval before a normal C environment exists.
Event taxonomy: source, timing, and restart point
“Trap” is the umbrella term for a control transfer caused by an exception or interrupt. The exact vocabulary varies across architectures; the causal distinction does not.
| Event | Relation to current instruction | RISC-V example | Typical continuation |
|---|---|---|---|
| Requested synchronous exception | Caused deliberately by the current instruction | ecall from U-mode | Advance past ecall after servicing. |
| Fault-like synchronous exception | Current instruction cannot complete as requested | load page fault | Repair cause and retry the same instruction, or terminate. |
| Terminal synchronous exception | Current execution cannot safely continue | illegal instruction with no emulator | Report or terminate; retry is not useful. |
| Asynchronous interrupt | Raised independently of the current instruction boundary | timer or external-device interrupt | Service event, then resume the interrupted instruction stream. |
The classification determines the return PC. xv6 adds four bytes to its saved user PC for an ecall, because that instruction is four bytes and sepc points to it. A recoverable page fault leaves the PC unchanged so the load or store can retry. An interrupt resumes the interrupted stream without pretending the instruction requested the event.
Cause classification from raw state
For each snapshot, state the event class and correct PC action. Assume RV64 and a direct trap vector.
| Snapshot | scause | sepc | stval |
|---|---|---|---|
| A | 8 | 0x1040 | 0 |
| B | 13 | 0x2088 | 0x4000_1000 |
| C | high interrupt bit + 5 | 0x30ac | unspecified |
Worked solutionExpandCollapse
A is an environment call from U-mode: dispatch it and, on normal return, resume at 0x1044. B is a load page fault: stval supplies the faulting virtual address when the implementation reports it; resolve the mapping and retry at 0x2088, or terminate. C is a supervisor timer interrupt: acknowledge/rearm it as required and resume at 0x30ac, unless scheduling deliberately changes which saved context runs. Advancing every sepc by four would skip the faulting load and corrupt program semantics.
The architectural transition into supervisor mode
For a trap delegated to S-mode, RISC-V supplies a small, protected landing contract:
sepcreceives the address of the interrupted or exception-causing instruction;scauserecords interrupt-versus-exception and a cause code;stvalmay record cause-specific information such as a faulting address;sstatus.SPPrecords the prior privilege,SPIEreceives the oldSIE, andSIEis cleared;- the PC is loaded from
stvecaccording to its direct or vectored mode.
The architecture intentionally does not prescribe a process structure, syscall ABI, kernel stack, page-table switch, or complete context frame. Software chooses those mechanisms.
The two diagrams are intentionally not equivalent: the rendered sequence above names the ownership transfers and saved state. Any generic arrow chain that omits the user page table at first entry conceals xv6’s hardest constraint.
Architectural boundary check
Why can xv6 not set stvec directly to an ordinary C function compiled into the kernel text?
Worked solutionExpandCollapse
On a trap from user space, RISC-V has not switched satp; the user page table remains active. The first instruction address must therefore be mapped there, and C additionally assumes a valid stack and calling-convention state that do not yet exist. xv6 maps trampoline code at the same virtual address in user and kernel page tables, saves registers to a per-process trapframe, installs the kernel stack and page table, then enters C. “C cannot run in supervisor mode” is wrong; C cannot run safely until its software conventions are established.
Scrub the complete request path
Before moving the control, predict the first stage at which fd, byte count, and the user address can all be interpreted in the caller’s process context. Then find the first stage that may block.
Scrub through a read system call
Follow one xv6/RISC-V request across the ABI, hardware trap, trampoline, validation, blocking I/O, kernel completion, and architectural return. The active box shows who controls execution—not merely which function name appears in source.
Transition
Calls read(fd, buffer, 4)
PC is in the C library wrapper; the buffer is only a user virtual address.
Invariant to check
User code cannot dereference kernel memory or program the disk controller.
At kernel dispatch, the call number, descriptor, byte count, and user address are validated before the kernel acts on the request.
The model fixes one read path and suppresses cache hits, short reads, signals, partial device completion, and concurrent descriptor mutation. Its point is control ownership. In particular, the library wrapper is not the privilege boundary, and trap entry is not proof that the request is legal.
The eight-stage model deliberately combines two source-level cuts in “Dispatcher and read handler.” Generic syscall dispatch validates only that saved a7 selects a defined handler. The read handler and lower file/copy helpers collectively decode and check the descriptor, byte count, and destination buffer in the caller’s context. Attributing those object/range checks to the dispatcher alone hides where their authority and address-space information becomes available.
The return occupies two stages. “Kernel completion” copies completed bytes to the checked destination, records the result in saved a0, and has C prepare sepc/sstatus for the chosen continuation. “Trampoline + sret” first uses assembly to switch mappings and restore the saved register file; the sret instruction then applies the prepared privilege and PC state. Hardware does not copy file bytes, choose the result, or restore registers from xv6’s trapframe.
Reconstruct the hardware/trampoline handoff
At the component’s “RISC-V trap hardware” and “xv6 trampoline entry” stages, draw a table with rows for a0, a7, user SP, user PC, kernel SP, satp, stvec, and privilege. Fill columns “before ecall,” “after RISC-V trap hardware,” and “after xv6 trampoline entry.” Hardware changes privilege and protected trap CSRs; only trampoline software selects the kernel stack and satp.
HintExpandCollapse
Hardware preserves some values by not changing them; that is different from copying them into durable storage.
Worked solutionExpandCollapse
| State | Before ecall | After RISC-V trap hardware | After xv6 trampoline entry |
|---|---|---|---|
a0 | first argument | still first argument, not yet durably saved | saved in trapframe; register reused/restored later |
a7 | syscall number | unchanged | saved in trapframe |
| user SP | in sp | still in sp | saved; sp is kernel-stack top |
| user PC | current ecall | copied to sepc; PC is trap vector | copied into process trapframe by C path |
| kernel SP | stored in trapframe metadata | not selected | loaded into sp |
satp | user page table | user page table | kernel page table |
stvec | trampoline address | source of new PC | changed to kernel vector before kernel traps are enabled |
| privilege | U | S | S |
The likely reasoning gap is confusing “register not overwritten yet” with “safe across arbitrary handler code.” The assembly must save it before reuse.
Dispatch and validation are separate proof steps
An ABI converts source arguments into raw machine words. In rev5, the syscall number is in saved a7, six raw arguments are available from saved a0–a5, and the result is written to saved a0. syscall() verifies only that the number indexes a defined handler. For read, sys_read and lower file/copy routines collectively interpret the descriptor, count, and user address under type-, authority-, and process-specific contracts; pointer legality is established by checked copying, not by argaddr() alone. The interactive’s combined stage reflects that collective proof without pretending all checks live in syscall.c.
For a range [u, u+n), a check such as u < process_size is insufficient. At minimum, reasoning must reject arithmetic overflow and every inaccessible page touched by the copy. A robust pattern either checks n <= limit - u after establishing u <= limit, or walks/copies in bounded chunks with explicit failure at each mapping.
/* Schematic boundary logic, not an xv6 patch. */
int copy_from_user_checked(void *dst, uint64 u, uint64 n, uint64 limit) {
if (u > limit || n > limit - u)
return -1;
return copy_mapped_chunks(dst, u, n);
}
The subtraction form avoids constructing u+n before proving that addition is representable. It still delegates page permissions and mapping continuity to copy_mapped_chunks.
Application — kill four validators
For write(fd, u, n), give one input that defeats each implementation.
- checks only
u < size; - checks
u+n <= sizeusing wrapping unsigned addition; - validates the user range, then passes
fdas a direct pointer to a kernel file object; - validates everything, but holds a spinlock while copying a page that may fault or block.
Worked solutionExpandCollapse
- Choose
u=size-1,n=2; the start is legal and the range is not. - Choose
unearUINT64_MAXandnlarge enough thatu+nwraps to a small value. - Supply an integer whose bit pattern names arbitrary kernel memory; descriptors must be resolved through the caller’s descriptor table, not cast.
- Arrange a missing or reclaim-contended user page. If copying can sleep, sleeping while holding a spinlock can deadlock or violate lock rules. If this particular kernel’s copy path never faults, the design must state that invariant rather than rely on wishful behavior.
The four defects concern range, arithmetic, authority, and execution context. One “validate inputs” slogan does not diagnose them.
System Call Address Range Validation Matrix
Evaluate each statement regarding how kernel entry code validates a user address range [u, u+n) before copying:
Classify each option as correct or incorrect, or leave uncertain options unanswered (“I don't know”) and verify at any time.
Worked trace: a recoverable load page fault
Assume a user load at PC 0x2088 reads virtual address 0x40001000. The address lies in a lazily allocated region but has no present leaf mapping.
- The load raises a synchronous exception.
sepc=0x2088;scauseidentifies a load page fault;stvalreports the attempted address on the modeled platform. - Entry assembly preserves the process state exactly as for a syscall. The common mechanism does not imply a common policy.
- The handler verifies that the address belongs to a region eligible for lazy allocation and that the requested access is readable.
- It allocates and initializes a frame, installs a user-readable mapping, and performs required translation-cache synchronization.
- Return leaves the saved PC at
0x2088. The load retries and may now complete.
If allocation fails, the kernel must not loop forever retrying an impossible instruction. It reports or records a fatal process condition and returns control through a termination path.
Transfer — same cause number, different trust
A load page fault occurs while supervisor code dereferences a kernel pointer. Why is “allocate a page and retry” generally unsafe even though that response was correct for the user fault?
Worked solutionExpandCollapse
The faulting protection domain and address-space contract differ. An unexpected kernel fault can indicate a dangling pointer, corrupted page table, stack overflow, or violation of a no-fault region; allocating could hide corruption and continue with supervisor authority. A kernel may deliberately support recoverable faults during bounded user-copy routines, but that requires an explicit exception table or recovery protocol. Cause code alone does not determine policy; origin, expected region, and current lock/interrupt context matter.
Worked trace: a timer interrupt through a context switch
Assume process runs in user mode when the timer fires.
| Moment | Saved continuation | Active stack | Scheduling consequence |
|---|---|---|---|
| interrupt entry | ‘s user PC in trap state | transition to ‘s kernel stack | none yet |
| kernel handler | ‘s full trapframe plus kernel frames | ‘s kernel stack | handler may call yield() |
| scheduler switch | ‘s kernel continuation saved in scheduler context | per-CPU scheduler stack/context | another runnable process may run |
| eventual resume | switch returns inside ‘s suspended handler | ‘s kernel stack | handler restores trap CSRs |
sret | ‘s user continuation restored | user stack | interrupted user execution resumes |
There are two nested resumptions: scheduler-to-kernel-handler and kernel-handler-to-user. Saving only the user trapframe cannot resume the suspended C call chain; saving only the kernel context cannot reconstruct all user registers.
Counterexample — enabling interrupts too early
Suppose usertrap() enables supervisor interrupts before changing stvec away from uservec and before installing a valid kernel stack. Construct the failure.
Worked solutionExpandCollapse
A timer can arrive while supervisor code is running but stvec still names the user-entry trampoline. That entry assumes a user trapframe and transition context; it can overwrite saved user state or load stale process metadata while already on a kernel path. The safe design disables interrupts during the ambiguous interval, points kernel-origin traps at a handler that assumes a kernel page table and stack, and enables interrupts only after trap CSRs needed for classification have been consumed or saved.
Deep Practice
Solve these problems to test and consolidate your understanding. Complete worked solutions and diagnostic hints are available for each problem.
Exercise 1.2.1: Hardware Trap Transition and Software Invariants
Identify what architectural state transitions are performed automatically by RISC-V hardware on an ecall trap into supervisor mode, and contrast them with the responsibilities that must be performed by software in trampoline.S.
HintExpandCollapse
Distinguish hardware CSR updates from software stack selection and register saving.
Worked solutionExpandCollapse
Hardware automatically saves the faulting/call PC to sepc, writes the trap cause code to scause, captures previous privilege mode and interrupt enables in sstatus, disables interrupts in supervisor mode, and sets PC to stvec. Hardware does NOT switch the stack pointer (sp), does NOT switch the page table (satp), and does NOT save general-purpose registers (x1..x31). Software entry code (trampoline.S) must exchange sp with the per-process trapframe, save all integer registers, configure the kernel stack pointer, and switch satp to the kernel page table before entering C code.
Exercise 1.2.2: Subtraction-Based Range Validation Against Wraparound
A kernel system call receives user address u and length n. Prove that the condition u + n <= limit fails to detect integer wraparound in modular arithmetic, and explain why the ordered check u <= limit && n <= limit - u is sound.
HintExpandCollapse
Consider boundary values where u + n exceeds the maximum 64-bit integer.
Worked solutionExpandCollapse
In fixed-width unsigned arithmetic modulo if u = 0xFFFFFFFFFFFFFF00 and n = 0x200, the sum wraps around to 0x100. Testing u + n <= limit succeeds because even though the buffer spans across memory into invalid or kernel space. By contrast, testing u <= limit first establishes that limit - u is non-negative and mathematically bounded without overflow. The subsequent check n <= limit - u ensures that the entire span fits below limit without ever computing the wrapping sum.
Exercise 1.2.3: Synchronous Recoverable Page Fault Execution Trace
Trace the control flow, CSR state, and page-table modifications when a process triggers a recoverable demand-paging load fault at instruction PC 0x2088 accessing virtual address 0x40001000.
HintExpandCollapse
Trace why sepc remains at the faulting load instruction rather than incrementing by 4.
Worked solutionExpandCollapse
The load instruction triggers a synchronous exception. Hardware writes sepc = 0x2088, sets scause to load page fault (cause 13), writes stval = 0x40001000, and jumps to stvec. The kernel trapframe preserves user registers. The VM fault handler verifies that 0x40001000 lies within a valid VMA, allocates a physical frame, maps it with read permissions, and flushes the TLB (sfence.vma). Crucially, sepc is NOT incremented; on sret, execution returns to 0x2088 to re-execute the load instruction, which now hits the valid translation.
Exercise 1.2.4: Stale Trampoline Interrupts and Trap Vector Swapping
Explain the failure mode if supervisor interrupts are re-enabled inside kernel mode while stvec still points to the user-mode trampoline entry vector.
HintExpandCollapse
Consider what trapframe stvec dereferences when an interrupt occurs while already on the kernel stack.
Worked solutionExpandCollapse
If an asynchronous timer or device interrupt arrives while stvec points to the user trampoline, the CPU executes the user entry code while already in supervisor mode. The trampoline attempts to read sscratch (which now points to the kernel or contains user register data), swaps the stack pointer to an invalid state, and overwrites the active user trapframe with kernel register values. To prevent state corruption, kernel entry must switch stvec to kernelvec before enabling interrupts, and disable interrupts before switching stvec back to uservec on exit.
Exercise 1.2.5: Complete Boundary Protocol and Snapshot Semantics for copy_digest
Design the complete validation sequence for a system call copy_digest(in_ptr, length, out_ptr, flags). Specify the argument decoding order, memory bounds validation, chunked copy strategy, and error reporting.
HintExpandCollapse
Reject invalid flags first, validate non-wrapping bounds, copy into bounded kernel buffers, and protect against concurrent modification.
Worked solutionExpandCollapse
- Decode and reject unknown flags immediately with
-EINVAL. - Check range bounds: verify
in_ptr <= USER_MAX && length <= USER_MAX - in_ptr, and verifyout_ptr <= USER_MAX && 32 <= USER_MAX - out_ptr. - Accept zero length without reading
in_ptr, but still verify thatout_ptris writable. - Process input in bounded kernel-allocated chunks (e.g., 4 KiB buffers) via
copyin, feeding each chunk into a kernel cryptographic digest context. This bounds kernel memory usage and prevents unbounded locks. - Once hashing completes, write the 32-byte digest to
out_ptrviacopyout. If a fault occurs duringcopyout, return-EFAULT. - Advance
sepc += 4before executingsretso the user process resumes at the instruction followingecall.
References & Further Reading
- RISC-V International, The RISC-V Instruction Set Manual, Volume II: Privileged Architecture, Sections 3.3.1 and 12.1.
- MIT PDOS, xv6: a simple, Unix-like teaching operating system, Chapter 4.
- MIT PDOS, xv6 rev5
kernel/trampoline.S,kernel/trap.c,kernel/syscall.c,kernel/sysfile.c,kernel/file.c, andkernel/vm.c. - The Open Group, POSIX.1-2024
read(), for short-read, interruption, and user-visible I/O semantics used in the examples.