Search Knowledge

© 2026 LIBREUNI PROJECT

Operating Systems Engineering/Crossing the kernel boundary
Page 2 of 29

Traps, Interrupts, and System Calls

Derive RISC-V privilege transfer from architectural trap state to a validated xv6 system call, then test the same path against faults and asynchronous interrupts.

Lesson briefCrossing the kernel boundary · 5 h 30 min · 4 outcomes

Required knowledge

  • RISC-V integer registers, calling convention, and control-flow instructions
  • User and supervisor privilege modes
  • Virtual addresses, page tables, and the purpose of a kernel stack

Learning outcomes

  • Classify synchronous exceptions, environment calls, and asynchronous interrupts by cause and resumability.
  • Reconstruct the RISC-V supervisor trap transition from sstatus, sepc, scause, stval, and stvec without assuming hardware saves a complete context.
  • Trace xv6 from a user ecall through the trampoline, dispatcher, argument validation, service, and sret.
  • Design a system-call boundary that rejects malformed numbers, handles, lengths, and user pointers without corrupting kernel state.

Assessment target

Given an unseen RISC-V trap snapshot and kernel entry sketch, classify the event, reconstruct saved and unsaved state, identify the first unsafe transition, and specify a validated return path with one failure test.

Scope boundary

  • Hypervisor traps, RISC-V vectored interrupt implementations, interrupt-controller programming, and nested-interrupt policy are bounded to explicit interfaces.
  • Page-fault resolution, copy-on-write, device-driver completion, and signal delivery are traced only far enough to distinguish their control paths.
  • Assembly listings are schematic; xv6 rev5 at the course hash remains the implementation authority.

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:

  1. transfer control without trusting a user-supplied destination;
  2. preserve enough interrupted state to resume or terminate correctly; and
  3. 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.

HintExpand

Separate architectural CSRs from conventions implemented by entry assembly.

Worked solutionExpand

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.

EventRelation to current instructionRISC-V exampleTypical continuation
Requested synchronous exceptionCaused deliberately by the current instructionecall from U-modeAdvance past ecall after servicing.
Fault-like synchronous exceptionCurrent instruction cannot complete as requestedload page faultRepair cause and retry the same instruction, or terminate.
Terminal synchronous exceptionCurrent execution cannot safely continueillegal instruction with no emulatorReport or terminate; retry is not useful.
Asynchronous interruptRaised independently of the current instruction boundarytimer or external-device interruptService 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.

Snapshotscausesepcstval
A80x10400
B130x20880x4000_1000
Chigh interrupt bit + 50x30acunspecified
Worked solutionExpand

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:

  • sepc receives the address of the interrupted or exception-causing instruction;
  • scause records interrupt-versus-exception and a cause code;
  • stval may record cause-specific information such as a faulting address;
  • sstatus.SPP records the prior privilege, SPIE receives the old SIE, and SIE is cleared;
  • the PC is loaded from stvec according 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.

Code
participant "user code" as U
participant "RISC-V hart" as H
participant "xv6 uservec" as V
participant "xv6 usertrap" as T
participant "syscall dispatcher" as D
participant "read handler" as R
participant "VFS / device service" as S

U -> H : ecall with number in a7 and arguments in a0..a5
activate H
H -> H : sepc/scause/sstatus updated; PC = stvec
H -> V : first S-mode instruction, user page table still active
deactivate H
activate V
V -> V : save registers in trapframe
V -> V : load kernel stack, hart id, kernel satp
V -> T : jump after page-table switch
deactivate V
activate T
T -> D : classify scause = user ecall; save epc + 4
D -> D : validate saved a7 names a defined syscall
D -> R : invoke read handler with raw a0..a2
R -> R : resolve fd; check count and copy contract
R -> S : request bytes through open-file object
S --> R : completed kernel data or error
R -> R : checked copyout to user range
R --> D : byte count or error
D --> T : record result in saved a0
T -> T : prepare stvec, sstatus, and sepc
T -> V : pass user satp to return trampoline
deactivate T
activate V
V -> V : switch satp; restore saved user registers
V -> H : execute sret
deactivate V
H -> U : restore privilege and PC from sstatus/sepc

note over H,V
Hardware changes privilege and CSRs.
Entry assembly constructs a C-safe context.
end note
RISC-V hartxv6 uservecxv6 uservecxv6 usertrapuser codeRISC-V hartxv6 uservecxv6 usertrapsyscall dispatcherread handlerVFS . device serviceuser codeuser codeRISC-V hartRISC-V hartxv6 uservecxv6 uservecxv6 usertrapxv6 usertrapsyscall dispatchersyscall dispatcherread handlerread handlerVFS / device serviceVFS / device serviceRISC-V hartxv6 uservecxv6 uservecxv6 usertrapecall with number in a7and arguments in a0..a5sepc/scause/sstatusupdated; PC = stvecfirst S-mode instruction,user page table stillactivesave registers intrapframeload kernel stack, hartid, kernel satpjump after page-tableswitchclassify scause = userecall; save epc + 4validate saved a7names a defined syscallinvoke read handler withraw a0..a2resolve fd; check countand copy contractrequest bytes throughopen-file objectcompleted kernel dataor errorchecked copyout to userrangebyte count or errorrecord result in saved a0prepare stvec, sstatus,and sepcpass user satp to returntrampolineswitch satp; restoresaved user registersexecute sretrestore privilege and PCfrom sstatus/sepcHardware changes privilege andCSRs.Entry assembly constructs aC-safe context.

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 solutionExpand

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.

Interactive exploration

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.

Stage 1 of 8: user mode
1Application

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.

Scrub through a read system call
user#1
Application
user#2
Library wrapper
hardware#3
RISC-V trap hardware
kernel#4
xv6 trampoline entry
kernel#5
Dispatcher and read handler
kernel#6
VFS and device path
kernel#7
Kernel completion
hardware#8
Trampoline and sret

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.

HintExpand

Hardware preserves some values by not changing them; that is different from copying them into durable storage.

Worked solutionExpand
StateBefore ecallAfter RISC-V trap hardwareAfter xv6 trampoline entry
a0first argumentstill first argument, not yet durably savedsaved in trapframe; register reused/restored later
a7syscall numberunchangedsaved in trapframe
user SPin spstill in spsaved; sp is kernel-stack top
user PCcurrent ecallcopied to sepc; PC is trap vectorcopied into process trapframe by C path
kernel SPstored in trapframe metadatanot selectedloaded into sp
satpuser page tableuser page tablekernel page table
stvectrampoline addresssource of new PCchanged to kernel vector before kernel traps are enabled
privilegeUSS

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.

  1. checks only u < size;
  2. checks u+n <= size using wrapping unsigned addition;
  3. validates the user range, then passes fd as a direct pointer to a kernel file object;
  4. validates everything, but holds a spinlock while copying a page that may fault or block.
Worked solutionExpand
  1. Choose u=size-1, n=2; the start is legal and the range is not.
  2. Choose u near UINT64_MAX and n large enough that u+n wraps to a small value.
  3. Supply an integer whose bit pattern names arbitrary kernel memory; descriptors must be resolved through the caller’s descriptor table, not cast.
  4. 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

0 / 4 answered

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.

1
Validating user memory requires verifying page-table presence and write permissions across every page.
2
Verifying only that starting address u lies within user space guarantees that all u + n bytes are valid.
3
Testing u + n <= limit using wrapping unsigned addition safely detects all integer overflow conditions.
4
Checking u <= limit followed by n <= limit - u prevents arithmetic wraparound without forming u + n.

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.

  1. The load raises a synchronous exception. sepc=0x2088; scause identifies a load page fault; stval reports the attempted address on the modeled platform.
  2. Entry assembly preserves the process state exactly as for a syscall. The common mechanism does not imply a common policy.
  3. The handler verifies that the address belongs to a region eligible for lazy allocation and that the requested access is readable.
  4. It allocates and initializes a frame, installs a user-readable mapping, and performs required translation-cache synchronization.
  5. 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 solutionExpand

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 AA runs in user mode when the timer fires.

MomentSaved continuationActive stackScheduling consequence
interrupt entryAA‘s user PC in trap statetransition to AA‘s kernel stacknone yet
kernel handlerAA‘s full trapframe plus kernel framesAA‘s kernel stackhandler may call yield()
scheduler switchAA‘s kernel continuation saved in scheduler contextper-CPU scheduler stack/contextanother runnable process BB may run
eventual resumeswitch returns inside AA‘s suspended handlerAA‘s kernel stackhandler restores trap CSRs
sretAA‘s user continuation restoreduser stackinterrupted 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 solutionExpand

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.

Section Exercises

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

Descriptionapplication

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.

HintExpand

Distinguish hardware CSR updates from software stack selection and register saving.

Worked solutionExpand

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

Verificationapplication

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.

HintExpand

Consider boundary values where u + n exceeds the maximum 64-bit integer.

Worked solutionExpand

In fixed-width unsigned arithmetic modulo 2642^{64} if u = 0xFFFFFFFFFFFFFF00 and n = 0x200, the sum wraps around to 0x100. Testing u + n <= limit succeeds because 256≤limit256 \le \mathrm{limit} 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 [u,u+n)[u, u + n) fits below limit without ever computing the wrapping sum.

Exercise 1.2.3: Synchronous Recoverable Page Fault Execution Trace

Descriptiontransfer

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.

HintExpand

Trace why sepc remains at the faulting load instruction rather than incrementing by 4.

Worked solutionExpand

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

Constructiontransfer

Explain the failure mode if supervisor interrupts are re-enabled inside kernel mode while stvec still points to the user-mode trampoline entry vector.

HintExpand

Consider what trapframe stvec dereferences when an interrupt occurs while already on the kernel stack.

Worked solutionExpand

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

Constructionsynthesis

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.

HintExpand

Reject invalid flags first, validate non-wrapping bounds, copy into bounded kernel buffers, and protect against concurrent modification.

Worked solutionExpand
  1. Decode and reject unknown flags immediately with -EINVAL.
  2. Check range bounds: verify in_ptr <= USER_MAX && length <= USER_MAX - in_ptr, and verify out_ptr <= USER_MAX && 32 <= USER_MAX - out_ptr.
  3. Accept zero length without reading in_ptr, but still verify that out_ptr is writable.
  4. 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.
  5. Once hashing completes, write the 32-byte digest to out_ptr via copyout. If a fault occurs during copyout, return -EFAULT.
  6. Advance sepc += 4 before executing sret so the user process resumes at the instruction following ecall.

References & Further Reading

  1. RISC-V International, The RISC-V Instruction Set Manual, Volume II: Privileged Architecture, Sections 3.3.1 and 12.1.
  2. MIT PDOS, xv6: a simple, Unix-like teaching operating system, Chapter 4.
  3. MIT PDOS, xv6 rev5 kernel/trampoline.S, kernel/trap.c, kernel/syscall.c, kernel/sysfile.c, kernel/file.c, and kernel/vm.c.
  4. The Open Group, POSIX.1-2024 read(), for short-read, interruption, and user-visible I/O semantics used in the examples.