
Recall first from fork, exit and wait: the process lifecycle
- fork copies memory and the trapframe, sets the child's saved a0 to 0, and marks it RUNNABLE; the scheduler, not fork, decides when the child runs.
- exit cannot free its own kernel stack, so it becomes a ZOMBIE; the parent's wait frees the slot, and orphans go to init, which always waits.
- sleep_prepare records the wait channel under p->lock before the caller drops the condition lock, and wakeup clears that channel and marks a matching sleeper RUNNABLE under p->lock, so sleep returns at once if the wakeup came first and no wakeup is lost.
struct context and swtch: fourteen registers
5 min readfork, exit and wait showed what happens to a process over its lifetime. This lesson looks at the mechanism underneath: how swtch moves the CPU between kernel threads, how the lock is handed over, and how the kernel finds the current process.
A process carries two saved register sets, and confusing them is the classic mistake. The trapframe saves the user's 32 registers when a trap enters the kernel, and userret restores them on the way out. The second set, the context, saves only the kernel thread's state, and it is what sched and scheduler swap:
// kernel/proc.h
struct context {
uint64 ra;
uint64 sp;
uint64 s0;
uint64 s1;
uint64 s2;
uint64 s3;
uint64 s4;
uint64 s5;
uint64 s6;
uint64 s7;
uint64 s8;
uint64 s9;
uint64 s10;
uint64 s11;
};
Fourteen registers: ra, sp, and s0 through s11. Why so few? The RISC-V lesson defined the split: caller-saved registers (ra, t0-t6, a0-a7) may be clobbered by any call, so a C caller that needs them afterwards saves them on its own stack before the call. swtch is called from C, so by the time it runs, the caller has already spilled everything it cares about. What remains is the callee-saved set, s0-s11 and sp, which swtch must preserve, plus ra, which holds the instruction to resume at. There is no separate program counter field: the saved ra is the resume point, because swtch ends with ret.
Here is the whole function, abridged from kernel/swtch.S:
# kernel/swtch.S (abridged): a0 = old context, a1 = new context
swtch:
sd ra, 0(a0)
sd sp, 8(a0)
sd s0, 16(a0)
# ... s1 through s10 at offsets 24 through 96 ...
sd s11, 104(a0)
ld ra, 0(a1)
ld sp, 8(a1)
ld s0, 16(a1)
# ... s1 through s10 ...
ld s11, 104(a1)
ret
Read it as two halves. The stores write the current registers into the old context. The loads overwrite the live registers from the new context, including sp and ra. The final ret jumps to the restored ra, on the restored sp. The hart entered swtch from one function on one kernel stack and leaves it from a different function on a different kernel stack, as if that other function's call to swtch had just returned. Nothing else changed: no memory was copied, no page table was touched.
This is why a context switch is not a trap. It runs entirely in supervisor mode, between two kernel threads. It saves and restores no sepc, no sstatus, no scause; those belong to the user-to-kernel boundary and were handled once, on entry. It does not even switch satp: every kernel thread runs on the kernel page table, and the new process's user page table is loaded only later, by userret on the trampoline, when the kernel returns to user mode. The user registers sit untouched in the trapframe throughout. A full process change is therefore two context switches (out to the scheduler, into the next process) wrapped around one trap entry and one trap return.
The pattern is a pair of Coroutines are functions that transfer control to each other directly, each resuming where it last paused, rather than following a strict caller-callee order.. sched always switches to the scheduler's saved context, and scheduler always switches to some process's saved context, which resumes inside sched. The single exception is a brand-new process, whose context was aimed at forkret by allocproc, so its first switch lands there instead. If you logged every switch site in a running xv6, you would see the same two call sites alternating, with an occasional forkret entry.
Going deeperWhat a switch costs, and what it does not do
The direct cost is fourteen stores and fourteen loads, a few tens of instructions, which is tiny even on a small embedded core. Because satp does not change, xv6's switch needs no TLB flush; the flush happens once per return to user mode, when userret writes satp and executes sfence.vma. The real cost on production systems is indirect: the new thread touches different memory, so caches warm up again, and branch predictors relearn. Linux's context_switch does two jobs, switch_mm for the address space and switch_to for the registers, as Love describes; xv6 splits the same work across the switch and the trampoline return. When you measure switching on a board, measure the whole path, not just the register save.
scheduler, sched and yield: the lock handoff
6 min readEach hart runs its own The scheduler thread is a per-CPU kernel thread, with its own stack and saved context, that loops choosing RUNNABLE processes and switching into them., the loop the boot lesson ended on. It needs its own stack for a sharp reason: if the scheduler ran on the yielding process's kernel stack, another hart could wake that process and start running it on the same stack at the same time. Two CPUs, one stack, instant corruption. The per-hart boot stack slice from stack0 serves as the scheduler stack, and struct cpu holds its saved context.
The policy is Round robin runs each ready process in turn, giving every one a slice before returning to the first. 1. Timer traps the shell: uservec saves user registers to the shell's trapframe; usertrap sees the timer and calls yield. 2. yield marks RUNNABLE: it takes the shell's p->lock, sets state, and calls sched. 3. sched switches out: swtch saves the shell's kernel context and loads the scheduler's; the hart is now on the scheduler stack, still holding the shell's lock. 4. Scheduler releases: it clears c->proc and releases the shell's lock; the shell is now safely parked. 5. Scheduler picks cat: it takes cat's lock, sets RUNNING, sets c->proc, and swtches into cat's context. 6. cat resumes: inside its own earlier sched call; it releases its lock, returns through prepare_return and userret, and runs in user mode. 7. Later, cat yields: the mirror image runs, and the scheduler may switch back into the shell, which resumes inside its own sched as if nothing happened. {{< /steps >}}
Going deeperintena, noff, and the interrupt state that crosses the switch
xv6's acquire calls push_off, which disables interrupts and counts the nesting in mycpu()->noff; release calls pop_off, which restores the previous interrupt state when the count reaches zero. That previous state is stored in mycpu()->intena. While a thread is switched out, the scheduler may acquire and release other locks, changing intena. So sched saves intena before swtch and restores it after, ensuring the resumed process gets back the interrupt state it had before it yielded, not whatever the scheduler left behind. The noff != 1 panic in sched enforces that you hold exactly one lock, your own, so the accounting stays simple.
When a scan finds nothing runnable, recent revisions execute wfi, wait-for-interrupt, which halts the hart until an interrupt arrives instead of spinning. On a battery-powered board this is the difference between a hot idle core and a cool one. The timer or a device interrupt wakes the hart, and the loop scans again. Check your proc.c: older revisions simply loop, and one of the book's exercises asks you to add wfi yourself. In the revision this course builds, kerneltrap also calls yield on a timer interrupt when a process is running in the kernel (which_dev == 2 && myproc() != 0); read your trap.c to see the exact rule.
mycpu and myproc: the tp register
3 min readKernel code constantly asks "which process am I working for?" On one hart a global variable would do. On several harts, each running a different process, a global is wrong. xv6's answer uses a register you already know: tp, the thread pointer, holds the hartid of the executing hart. The RISC-V lesson showed start.c writing it in machine mode, and the compiler promises never to use tp in kernel code.
// kernel/riscv.h
static inline uint64
r_tp(void)
{
uint64 x;
asm volatile("mv %0, tp" : "=r" (x));
return x;
}
// kernel/proc.c
int
cpuid()
{
int id = r_tp();
return id;
}
struct cpu *
mycpu(void)
{
int id = cpuid();
struct cpu *c = &cpus[id];
return c;
}
struct proc*
myproc(void)
{
push_off();
struct cpu *c = mycpu();
struct proc *p = c->proc;
pop_off();
return p;
}
One mv instruction reads the hartid; it indexes cpus[NCPU], the per-hart array of struct cpu. Each struct cpu holds proc, the process running on that hart (or null), context, the scheduler's saved registers, and the noff and intena accounting from the previous section. myproc reads c->proc and returns it.
Why does myproc disable interrupts around two reads? Because a timer could fire between them, yield, and resume this thread on a different hart. The cpuid value would then name the old hart, and c->proc would be the wrong process. With interrupts off, the pair is atomic with respect to migration. The returned struct proc * is safe to keep even after interrupts return: if the process later migrates, its structure does not move. The raw cpuid() and mycpu() results are the fragile ones, and callers must use them with interrupts disabled.
There is one more wrinkle. User code is free to clobber tp, since it is a general register in user mode. So prepare_return saves the kernel's tp value into the trapframe, and uservec restores it on every entry from user space. The hartid therefore survives any user program, and mycpu is correct on the first instruction after a trap. RISC-V lets software read the hartid from a CSR only in machine mode, which is why xv6 keeps it in a register instead of asking the hardware each time.
Linux solves the same problem with its own per-architecture trick. The kernel's process descriptor is called The process descriptor is the kernel's per-process structure, struct task_struct in Linux, holding everything the kernel knows about one task., struct task_struct, and the current macro finds the running one. Love describes the 2.6-era x86 method of masking the stack pointer to locate a thread_info at the stack's base, while register-rich PowerPC simply kept current in r2. Modern x86-64 uses a per-CPU data area addressed through the GS segment register; arm64 keeps the task pointer in sp_el0. The shape is identical to xv6's: one fast per-hart anchor, then a lookup.
The state model differs in one instructive way. Linux's TASK_RUNNING covers both "on a CPU" and "ready to run", so the kernel has one state where xv6 has two; ps distinguishes them by asking whether the task is actually on a CPU. Linux also has interruptible and uninterruptible sleep, stopped and traced states, and the zombie state you already know. User-space ps reads all of this from /proc/[pid]/stat, one file per process. On an embedded board this matters concretely: BusyBox ps is a small reader of /proc, so if that filesystem, procfs, is not mounted, ps fails, and its options are a subset of the full procps-ng tool. Your xv6 ps will read the table directly instead, which is the same idea with the filesystem layer removed.
Key takeaways
- swtch saves only ra, sp and s0-s11 because the C caller already spilled the caller-saved registers; restoring ra and sp resumes another kernel thread.
- A context switch is not a trap: it stays in supervisor mode, touches no sepc or sstatus, and leaves the user registers in the trapframe untouched.
- p->lock is held across swtch and released by the code that switches in, so no two CPUs can ever run on the same kernel stack.
- tp holds the hartid, so mycpu and myproc find the current CPU and process in a few instructions; ps walks the same table under the same locks.
Reflect
- Explain to a colleague, in two sentences: explain why swtch saves only ra, sp and s0-s11, and why a context switch is not a trap.
- Which objective are you least sure about? Re-read that section.
References and further reading
Official documentation first. Links checked when the lesson was published.