Skip to content

48k · User mode

Released Fri Nov 13, in class

This is the README OSlings gives every student for 48k_user_mode (oslings lesson shows it). The starter code is not published here: it reaches you through OSlings, in class on the class network. Back to All Exercises.

Learn -> Understand -> Implement. Until now, every line of code you wrote ran inside the kernel, with total power over the machine. In this exercise rv6 runs its first real user program: code that runs at the CPU's lowest privilege level, inside its own private address space, and that can only talk to the kernel through system calls. This wall between user programs and the kernel is the defining feature of every real OS.

Learn

Why build a wall at all?

Every kernel exercise so far trusted itself completely: shell, filesystem, and drivers are all kernel code, which can read any memory, write any register, and halt the machine. But an operating system exists to run other people's programs, and those crash, scribble on memory, and loop forever. The OS must be able to say: "if this program misbehaves, only the program dies, not the machine." Two hardware features you have already met make that enforceable - privilege levels (exercise 43k) and page tables (exercises 33k and 39k) - and this exercise snaps them together.

The third privilege level: user mode

In exercise 43k the kernel dropped from machine mode (M) to supervisor mode (S) with an mret. RISC-V has one level below that: user mode (U), the weakest of the three.

level who runs there what it may do
M (machine) start.rs, timervec everything
S (supervisor) the rv6 kernel use CSRs, manage page tables, take traps
U (user) user programs ordinary computation only

Code in user mode cannot touch any CSR, cannot change satp, cannot turn interrupts off - it cannot even ask what mode it is in. If it tries, the CPU traps to the kernel. The drop into U-mode works like exercise 43k's drop into S-mode, one level down: clear sstatus.SPP (bit 8, "where will sret go") and execute sret.

The only ways back up are traps into the kernel: the program asks (an ecall), or the hardware forces the issue (an interrupt, or a fault).

A private world: the user address space

Privilege alone is not enough - a user program could still read the kernel's memory. So each process gets its own page table (allocated per process since exercise 34k, used for the first time here). When the program runs, satp points at its table, so the only memory that exists, from its point of view, is what the kernel chose to map:

virtual address       what lives there              who may touch it
---------------       --------------------------    ----------------
0x3F_FFFF_F000        TRAMPOLINE (uservec/userret)   kernel only (R X)
0x3F_FFFF_E000        TRAPFRAME (saved registers)    kernel only (R W)
     ...                    (unmapped)
0x0000_2000           <- initial stack pointer
0x0000_1000           the stack page                 user (R W U)
0x0000_0000           the program's code             user (R X U)

Two things to notice:

  • PTE_U is the wall. A page table entry built with PTE_U set can be touched from user mode; one without it cannot (the CPU faults). That single bit makes the kernel's parts of this table invisible to the program. (It cuts both ways: the kernel cannot casually touch PTE_U pages either, which is why copyin, below, translates addresses explicitly.)
  • The program's code sits at virtual address 0. In a fresh, private address space, 0 is an ordinary address (xv6 loads programs there too).

The trapframe: a parking lot for 31 registers

When the program executes ecall, the CPU jumps into the kernel - but every register still holds the user program's values, and the kernel must hand every one of them back, exactly as they were, when the program resumes. So each process owns a trapframe: one page where, on every trap, all 31 general-purpose registers are parked (and reloaded on the way back out). It also carries notes for the kernel's own trap path (its satp, the kernel stack pointer, the address of usertrap) and epc, the user program counter to resume at.

(Each process also gets its own kernel stack, kstack: the trap handler needs a stack, and it cannot trust the user's stack pointer, which the program controls.)

The trampoline: the cleverest page in the kernel

Switching page tables while executing changes what every address means, including the next instruction's. So one page of assembly, the trampoline, is mapped at the SAME virtual address (TRAMPOLINE, the top page, no PTE_U) in the kernel's table and every user table: code standing on it can flip satp and nothing moves under its feet. Its two halves:

  • uservec - traps from user mode land here (stvec points here while user code runs). It parks all the registers in the trapframe, switches to the kernel page table and kernel stack, and jumps to usertrap (Rust).
  • userret - the road back. It switches to the user page table, reloads every register from the trapframe, and srets back into the program.

System calls: a function call across the wall

A user program cannot print: the UART is not in its address space, so it has to ask the kernel. The asking convention (the "system call ABI") is a function call across the privilege wall:

register role
a7 WHICH call (the system call number)
a0, a1, a2 the arguments
a0 (after) the return value

The program loads those registers and executes ecall, which traps into the kernel with scause = 8 ("environment call from U-mode"). rv6 starts with three calls (xv6's numbers, so the table can grow later):

number call meaning
2 exit(status) the program is finished
11 getpid() which process am I?
16 write(fd, buf, len) print len bytes from buf (fd 1 = console)

One sharp edge you will handle in usertrap: on an ecall, sepc points at the ecall instruction itself, not after it. Resume there and the program makes the same system call forever. The fix is one line: add 4 (the instruction's size in bytes) to the saved epc.

copyin: a user pointer is not a kernel pointer

The buf in write(1, buf, len) is a virtual address in the user's world, so sys_write hands it to copyin (vm.rs, given this time), which translates it page by page through the user's table with walkaddr - and walkaddr refuses anything that is not a PTE_U page, so a hostile pointer gets an error, not a peek at kernel memory. It mirrors the given copyout right above it; read the two side by side, since exercise 50k's read() will need copyout.

The first user program

There is no loader for user programs yet (that is exercise 49k), so the first user program is a dozen lines of assembly, baked into the kernel image as data and copied onto the code page at setup time:

write(1, "hello from user mode\n", 21)     # syscall 16
pid = getpid()                             # syscall 11
exit(pid + 41)                             # syscall 2

Why pid + 41? It proves the round trip: the kernel's return value had to travel back through the wall into the program's a0, and the program's argument had to travel into the kernel again. The first process gets pid 1, so a healthy run exits with status 42.

Understand

These files total about 965 lines; the parts below are the ~500 that matter today. Line numbers are approximate. Read them in this order:

  1. rv6/src/memlayout.rs, lines 29-69: the user address-space picture and its constants (MAXVA, TRAMPOLINE, TRAPFRAME, USER_CODE, USER_STACK, USER_STACK_TOP).
  2. rv6/src/usermode.rs:
    • the Trapframe struct (lines 32-74): the field offsets match the assembly, so the order is load-bearing;
    • the trampoline (lines 76-215): read the header comment, then skim the comments on uservec and userret - one pass, nothing to memorize;
    • setup (lines 310-346) and run (lines 356-388): how the kernel builds a process, launches it, and gets control back (exercise 35k's swtch, reused);
    • usertrap (lines 404-490): your ecall branch lives here;
    • usertrapret (lines 492-530): the road back. Skip the user program's assembly (the pseudocode above says what it does) and everything else in the file.
  3. rv6/src/vm.rs, lines 186-289: map_user_pages (yours), walkaddr, then the given copyout and copyin side by side. Skip everything above (you built it in exercise 39k; kvmmake only gained the trampoline mapping) and free_user_pagetable below.
  4. rv6/src/syscall.rs, lines 1-76: the numbers, dispatch (yours), and the three handlers; sys_write is where copyin gets used. Skip emit and the capture module.
  5. rv6/src/proc.rs: Proc (lines 30-42) grew trapframe and kstack; proc_pagetable (lines 136-145) maps the trampoline + trapframe, with no PTE_U.
  6. rv6/src/main.rs, user_mode_self_check (lines 208-300): read only the [fail] strings. The check verifies your page table BEFORE running the program (exercise 39k's verify-before-use trick), then runs it and checks what came out.

Control flow of one system call, the full round trip:

user code:  ecall
   -> CPU: trap! mode = S, pc = stvec = TRAMPOLINE (uservec)
   -> uservec:  park 31 registers in TRAPFRAME, switch to kernel
                page table + kernel stack, jump to usertrap
   -> usertrap: scause == 8, so: epc += 4, dispatch(a7, a0, a1, a2),
                return value into trapframe a0        <- YOU
   -> dispatch: match the number, call the handler    <- YOU
   -> usertrapret: aim stvec back at uservec, sstatus.SPP = User,
                sepc = epc, jump to userret
   -> userret: switch to user page table, reload the 31 registers,
                sret
user code:  ...continues after the ecall, result in a0

Implement

Three pieces, in the order the self-check meets them:

  1. vm.rs - map_user_pages: two mappages calls - the code page (USER_CODE, PTE_R | PTE_X | PTE_U) and the stack page (USER_STACK, PTE_R | PTE_W | PTE_U). Without PTE_U the program cannot even fetch its first instruction.
  2. usermode.rs - usertrap, the scause == 8 branch: step over the ecall (epc += 4), pull a7 and a0..a2 out of the trapframe and hand them to crate::syscall::dispatch, put the return value back in the trapframe's a0.
  3. syscall.rs - dispatch: a match on the number, routing to sys_exit / sys_getpid / sys_write. Unknown numbers return -1 (a user program must never be able to crash the kernel with a bad number).

copyin (vm.rs) is given: read it beside copyout, but there is nothing to write there.

Check your work:

oslings run 48k_user_mode
# or
oslings watch

The self-check tells you which piece it got stuck on, in the same order.

Then the payoff:

cd rv6 && cargo run        # boots to the rv6$ prompt

Type run. That is your kernel launching a user program, the program printing through a system call, and the shell getting the CPU back when it exits. Run it a few times and watch the pid (and the exit status) climb. The file commands from exercise 47k all still work alongside it. (Exit QEMU with Ctrl-A then X.)

Stuck? oslings hint.