8. Context switch

The context switch Two processes, each with a user trapframe (the frozen 280-byte layout) and a kernel context (ra, sp, s0-s11). ecall and tick arrows descend into the scheduler; swtch runs sideways between kernel contexts; sret arrows ascend into the other user. Below, muted and labelled Part IV, the ghost of a VM-exit saving the same two shapes for a guest. U:1 trapframe 280 B 31 regs + 4 CSRs kernel stack U=0 ctx: ra sp s0–s11 U:2 trapframe 280 B 31 regs + 4 CSRs kernel stack U=0 ctx: ra sp s0–s11 ecall, tick ↓ ↓ ecall, tick the scheduler swtch: 14 words, sideways sret ↑ ↑ sret a VM-exit saves the same shape — Part IV

Why this layer exists

Chapter 7 ends with one process and a kernel that has nowhere else to go: exit is a halt, because the only alternative to running that process is stopping the machine. A kernel with one process forever is a bootloader with a page table. The object this chapter adds is the switch — the kernel leaves one process in the middle of a system call and resumes another in the middle of a different one — and with it two things exist for the first time: more than one process, and the possibility that a process loses the hart without asking. That second thing is preemption, and it is the whole scheduling story of a hypervisor. Chapter 37’s hearth decides which guest believes it has a hart by doing exactly what this chapter’s tick handler does — taking the hart away on an interrupt and giving it to someone else — one privilege level up.

The switch is small: fourteen stores, fourteen loads, one ret. The reason it is small is the chapter’s mechanism, and the reason it must be called from exactly the right place is the chapter’s lesson.

Mechanism

Two register files, saved once each

A process in this kernel has two contexts, and the switch touches only one of them.

The first is the user register file — all 31 integer registers, sepc, scause, stval, sstatus — and it is already saved, by chapter 7’s user_vec, into the 280-byte frame on the proc’s kernel stack, the moment the process traps. By the time the kernel decides to switch, the process’s own registers are in memory and will be restored by user_ret when the process next runs. Nothing in this chapter saves them again.

The second is the kernel’s state on behalf of that process: where in the kernel it was, on which stack. That is what swtch saves, and it is much less than a register file. swtch is a C function call — swtch(&curproc->ctx, &sched_ctx) — and the C ABI already says what a call may destroy. The caller-saved registers (t0–t6, a0–a7, ra from the callee’s point of view) are dead across any call: the compiler has spilled whatever it still needs before the call. The callee-saved registers (s0–s11, sp) must survive; that is what “callee-saved” means. So a function that returns somewhere else has to preserve exactly the set a normal return would have preserved — s0–s11, sp — plus the one thing a normal return takes for granted, ra, which is where this world resumes. Fourteen words.

struct ctx {
    unsigned long ra, sp;
    unsigned long s[12]; /* s0–s11 */
};

The derivation is the ABI, not a design choice: save fewer and the caller’s live values are corrupted on resume; save more and you are re-saving registers the compiler already declared dead. Exercise (a) makes the first case observable.

    .globl swtch
swtch:
    sd      ra, 0(a0)           /* where this world resumes */
    sd      sp, 8(a0)           /* the stack it resumes on  */
    sd      s0, 16(a0)
    sd      s1, 24(a0)
    sd      s2, 32(a0)
    sd      s3, 40(a0)
    sd      s4, 48(a0)
    sd      s5, 56(a0)
    sd      s6, 64(a0)
    sd      s7, 72(a0)
    sd      s8, 80(a0)
    sd      s9, 88(a0)
    sd      s10, 96(a0)
    sd      s11, 104(a0)
    ld      ra, 0(a1)           /* the other world's resume point */
    ld      sp, 8(a1)
    ld      s0, 16(a1)
    ld      s1, 24(a1)
    ld      s2, 32(a1)
    ld      s3, 40(a1)
    ld      s4, 48(a1)
    ld      s5, 56(a1)
    ld      s6, 64(a1)
    ld      s7, 72(a1)
    ld      s8, 80(a1)
    ld      s9, 88(a1)
    ld      s10, 96(a1)
    ld      s11, 104(a1)
    ret

swtch stores the current world into a0’s struct ctx, loads the other world from a1’s, and rets — which jumps to the loaded ra on the loaded sp. It never touches sstatus, stvec, or sscratch: those describe whichever world is about to run, and the code on each side of the switch already set them. The function is a leaf that returns into a different function’s frame. Everything above it on the new stack was put there by the new world before it last called swtch, and everything above it on the old stack waits, intact, for the old world’s turn.

sp is the world

A process’s kernel stack is a page, allocated in proc_create, whose top is parked in sscratch while the process runs. It holds two things: the 280-byte user frame, pushed by user_vec at the moment of the trap, and below it every kernel frame the trap handler grew — trapper, syscall, and, if the process is about to lose the hart, sched and swtch’s fourteen words in the proc’s ctx. Switching sp therefore switches all of it at once: the frame that user_ret will restore, the C frames that will unwind through trapper back into user_vec’s tail, and the ra that says where. There is no separate “which process is this” state to update on the fast path; curproc is set by the scheduler loop for the kernel’s bookkeeping, but the hardware-visible identity of the running world is sp.

This is why each process needs its own kernel stack, and why a single shared kernel stack — a natural first thought, since only one process runs at a time — is not a simplification but a bug. Exercises (b) and (c) derive the failure in both the cooperative and preemptive cases. The invariant is not “never switch inside a trap handler” — this chapter’s tick handler switches inside a trap handler on every tick, legally — but “each frame lives on the stack of the world it belongs to.”

The loop, and why nobody names a successor

The scheduler is a loop on the kernel’s boot stack with its own ctx, and every switch goes through it. A process never switches to another process; it switches to the scheduler, which picks. Two switches per handoff instead of one is the price, and what it buys is that the picking policy lives in one function, pick, and the two paths that give up the hart — a yield syscall and a timer tick — are identical from sched onward. The preemptive run in the lab proves the scheduler is the mechanism precisely because the tick calls the same sched() that yield calls.

/* The whole switch, kernel side: save this proc's context, land in
 * the scheduler's. Nothing else — picking is the loop's job. */
void sched(void)
{
    swtch(&curproc->ctx, &sched_ctx);
}

void scheduler(void)
{
    for (;;) {
        struct proc *p = pick();

        if (!p) {
#if HP_CH == 8
            if (phase == 1) {
                /* the cooperative pair is DEAD: same programs again,
                 * yields removed, the tick driving the switch */
                phase_two();
                continue;
            }
#endif
            return; /* nothing runnable: the caller decides what that means */
        }
        last = (int)(p - proc_tab);
        p->state = RUNNING;
        curproc = p;
        swtch(&sched_ctx, &p->ctx);
        curproc = 0;
        /* back in the loop: the proc yielded or died */
    }
}

/* A never-run proc's fabricated ra: its own kernel stack, curproc
 * already set, and the chapter 7 crossing ahead of it. */
static void proc_entry(void)
{
    proc_run(curproc); /* returns only if U stopped without exiting */
    halt(1);
}

Three things in that listing are the chapter’s shape. sched() is one line, the switch into the scheduler’s context. scheduler() marks the pick RUNNING, sets curproc, switches in, and on return — the process yielded or died — clears curproc and goes around. proc_entry is the resume point of a process that has never run: launch fabricates its ctx with ra = proc_entry and sp at the top of its fresh kernel stack, so the first swtch into it “returns” into proc_entry, which calls chapter 7’s proc_run — the parking of sscratch, the stvec write, user_ret. Fabricating a kernel context is the same move as chapter 7’s fabricated user frame: a resume point and a stack, nothing else. s0–s11 start at zero because the ABI lets a function begin with anything in them.

pick is round-robin: the first RUNNABLE slot after the last runner, in a table of four. The table is the chapter’s size — two runs of two processes — and claims no generality. Death is a state now, not a halt: sys_exit prints, marks the process DEAD, and calls sched(), which never returns to it because the loop skips DEAD slots.

case SYS_yield:
    /* Still runnable — the loop decides for how long. */
    curproc->state = RUNNABLE;
    sched();
    a0 = 0;
    break;

yield is the cooperative handoff: the process is still RUNNABLE, it just calls sched(). When the loop picks it again, swtch returns into sched, sched returns into syscall, syscall writes tf->a0 = 0 and tf->sepc += 4, trapper returns into user_vec’s tail, and user_ret restores the frame — the process resumes at the instruction after its ecall, as if the ecall had simply taken a while. From its side, that is exactly what happened.

The tick is a yield the process did not ask for

Chapter 6’s tick — mtime compare in M, mtimecmp reloaded by the M shim, SSIP injected into S — is untouched. What changes is what the S-mode handler does with it. In chapter 6 the handler counted; from this chapter it also calls preempt_tick:

/* Called from the tick handler on every SSIP — chapter 6's 1 Hz tick,
 * reused untouched. In the cooperative run, or when the kernel itself
 * is the running context, there is nothing to preempt. */
void preempt_tick(void)
{
    struct proc *next;

    if (phase != 2 || !curproc)
        return;
#if HP_CH == 8
    if (preempts >= 4) {
        /* four preempted rounds is the proof; the tick after them
         * ends the lab. Chapter 8's terminator, gated like trap.c's. */
        uart_puts("PASS\r\n");
        halt(0);
    }
#endif
    preempts++;
    next = pick(); /* who the loop is about to choose — announced, then done */
    if (!next)
        return;
    uart_puts("S: preempt ");
    uart_puthex(preempts);
    uart_puts(" to U:");
    uart_putc((char)('0' + next->pid));
    uart_puts("\r\n");
    curproc->state = RUNNABLE; /* still runnable; the tick says next */
    sched();
}

The interrupted process is still RUNNABLE — it did nothing wrong — and sched() is called from inside the tick handler, on that process’s kernel stack, exactly as yield is called from inside the ecall handler. The frames are the same shape: user_vec pushed the user frame, trapper and preempt_tick grew below it, swtch parked the kernel context. When this process is picked again, it unwinds the same way and srets back to the instruction the tick interrupted. The user program, which contains no yield and no exit, ran on a hart that was taken from it and returned four times; it cannot tell.

Preemption needs interrupts on in U, and the frame chapter 7 fabricated already has SPIE=1 for this reason. Who owns sstatus.SIE across a switch is worth stating, because swtch does not save it and the register is global to the hart, not per-context. Hardware clears SIE on every trap into S. Once a process has trapped in, the kernel never sets it again itself except once, in timer_on at the start of the preemptive run. So after the first trap, every kernel path runs with interrupts masked — the scheduler loop included, whatever SIE was when it was last switched away from — and a process regains interrupts only through sret, which copies SPIE from its own frame’s sstatus into SIE. The user side of SIE lives in the frame; the kernel side is “off after the first trap.” That is a non-preemptible kernel, and it is deliberate: the tick handler can call sched without worrying that a second tick lands under it. Exercise (d) follows a tick that arrives while the kernel is in the middle of a syscall.

The M shim gets a stack too

One thing in Part I could not survive preemption, and it is one privilege up. The M-mode timer interrupt does not care what privilege the hart is in; from this chapter it can arrive while U is running. Without the mscratch swap chapter 3’s shim carries, the shim would push its saved registers on the incoming sp, which is a kernel stack for every trap before this chapter. A user sp is a low virtual address — 0x12000 for the first program — and M-mode runs untranslated: satp does not apply, so the shim’s first sd is a store to physical 0x12000, which on this board is neither DRAM nor a device. The store faults — cause 7, store/AMO access fault, to M — on the same sp, and the shim recurses the way chapter 7’s exercise (c′) recursed one level down.

The fix is the same instruction one level up, through mscratch — the M-mode scratch CSR chapter 3 introduced, the twin of sscratch — where drop.c parks a 4 KiB shim stack’s top before the first mret to S. mshim_entry opens with csrrw sp, mscratch, sp and closes by swapping back before mret. For a trap from S the shim runs on its own stack instead of the kernel’s, and nothing in a transcript can observe which stack it used; the swap exists for the trap from U that this chapter makes possible.

Two programs, one table, one fact in a0

The kernel has one page table, and two processes in it need distinct virtual addresses. prog1 is linked at chapter 7’s frozen 0x10000; prog2 is the same program linked at 0x20000 (--defsym=USER_BASE=0x20000 on its link), and proc_create gained a va argument to map each where it was linked. Because the table is shared, one process could in principle address the other’s pages — both are U=1 — and this chapter does not prevent it. That is a real hole, and this kernel keeps it: ember runs on one page table through Part II and never switches satp. Per-process tables — the thing that makes U pages private, at the cost of a satp write and a fence on every switch — are xv6’s design (chapter 16) and every production kernel’s. Here the two programs are cooperating halves of one proof, and the hole is not in the proof’s way.

struct proc *proc_create(const void *blob, unsigned long size,
                         unsigned long va)
{
    struct proc *p = 0;
    unsigned long code_pa = proc_page();
    unsigned long stack_pa = proc_page();
    unsigned long kstack_pa = proc_page();
    unsigned long a;
    int i, slot;

    for (slot = 0; slot < NPROC; slot++)
        if (proc_tab[slot].state == UNUSED || proc_tab[slot].state == DEAD) {
            p = &proc_tab[slot];
            break;
        }
    if (!p)
        halt(1);

    p->pid = (int)(p - proc_tab) + 1;
    p->state = RUNNABLE;
    p->kstack_top = kstack_pa + PAGE_SIZE;

    /* Code pages at va, U=1. The kernel's identity map entry for the
     * same PA stays U=0: one PA, two VAs, two permissions — the
     * kernel reaches its copy, U reaches only this one. */
    for (a = 0; a < size; a += PAGE_SIZE) {
        unsigned long off = a & (PAGE_SIZE - 1);
        unsigned long n = PAGE_SIZE - off;
        unsigned long *dst = (unsigned long *)(code_pa + a);
        const unsigned char *src = (const unsigned char *)blob + a;
        if (n > size - a)
            n = size - a;
        for (i = 0; i < (int)n; i++)
            ((unsigned char *)dst)[i] = src[i];
        map_page(va + a, code_pa + a,
                 PTE_R | PTE_W | PTE_X | PTE_U);
    }

    /* One U page for the stack, growing down. */
    map_page(va + 0x1000UL, stack_pa, PTE_R | PTE_W | PTE_U);

    /* The table changed under a live satp. The hart may hold the old
     * translation for these VAs (chapter 8 maps them twice); the
     * fence orders the PTE writes before any use of the new ones. */
    __asm__ volatile("sfence.vma" ::: "memory");

    /* Fabricate the frame: entering U is the mirror of returning
     * from a trap. SPP=0 so sret drops privilege; SPIE=1 so sret
     * copies it into SIE — U must run with interrupts enabled or
     * chapter 8's preemption never fires. */
    for (i = 0; i < 35; i++)
        ((unsigned long *)&p->tf)[i] = 0;
    p->tf.sepc = va;
    p->tf.sp = va + 0x2000UL;
    p->tf.sstatus = MSTATUS_SPIE; /* SPP=0 | SPIE=1 */

    /* The heap break starts just above the stack page; chapter 9's
     * sbrk maps pages there on demand. */
    p->brk = va + 0x2000UL;

    return p;
}

The sfence.vma at the end is new in this chapter and belongs to the mapping, not to the switch. The preemptive run maps 0x10000 and 0x20000 a second time, to fresh physical pages, while satp is live. A hart may hold the old translation, and the privileged spec requires an sfence.vma after a PTE write before the new translation can be relied on. In this lab the old and new pages hold identical bytes — the same blob, freshly copied — so a stale entry would be invisible in the transcript; the fence is there because the spec says so, not because the capture would catch its absence. A kernel that remaps pages to different contents without it would run the wrong code with no fault to show for it.

The user programs branch on a fact the kernel hands them in the fabricated frame’s a0: 1 for the cooperative run, 2 for the preemptive one. _start has to capture that register before it zeroes .bss, because .bss is where the captured value will live:

void _start(void)
{
    extern char __bss_start[], __bss_end[], stack_top[];
    char *p;
    register long a0r __asm__("a0");

    __asm__ volatile("" : "+r"(a0r)); /* a0: the spawn-time fact */
    for (p = __bss_start; p < __bss_end; p++)
        *p = 0;
    boot_mode = a0r; /* after the wipe; the register held it alive */
    __asm__ volatile(
        "mv sp, %0\n"
        "call main\n"
        :: "r"(stack_top) : "memory");
    __builtin_unreachable();
}
/* Chapter 8: the same program, spawned with the fact in a0. The
 * cooperative run writes a fixed line and yields; the preemptive run
 * writes the same line and spins — no yield anywhere, the tick is
 * the only switcher. */
static void run8(void)
{
    long i;

    if (boot_mode == 1) {
        for (i = 0; i < 3; i++) {
            syscall3(2, 1, (long)"U:1\r\n", 5); /* write */
            syscall3(3, 0, 0, 0);               /* yield  */
        }
    } else { /* boot_mode == 2: one line, then the spin */
        syscall3(2, 1, (long)"U:1\r\n", 5); /* write */
        for (;;)
            ; /* no yield, no exit: the tick is the only way out */
    }
    syscall3(1, 0, 0, 0); /* exit */
}

prog2 is the same file with U:2 in place of U:1. In the cooperative run each writes its line and yields, three times, then exits. In the preemptive run each writes its line once and spins — no yield, no exit, no way out but the tick.

mem_init();
trap_init();
uart_puts("S: kernel up\r\n");
sched_boot();

sched_boot launches both programs with the fact set to 1 and enters the loop. When the loop finds nothing runnable and both have died, it launches the same pair with the fact set to 2, arms the tick with chapter 6’s timer_on, and goes around again.

Walkthrough

ch08-main (the entry: two launches and the loop), ch08-swtch (fourteen words, sideways), ch08-sched (sched, the loop, proc_entry), ch08-yield (the cooperative door), ch08-preempt (the same door, opened by the tick), ch08-boot-mode (the user prologue that reads a0 before wiping .bss), ch08-prog1-loop (write-and-yield, then write-and-spin). The regenerated ch07-proc-create shows the va argument, the slot loop over the table, and the fence.

Exercises

(a) Save only ra and sp in swtch — drop s0–s11 — and run the cooperative pair. Predict what breaks first, and where.

Answer

The kernel, not a user program, and immediately after the first U:1. The first yield switches into the scheduler loop, whose live values — the loop’s p, the table cursor — the compiler kept in callee-saved registers across the swtch call, as the ABI allows. They come back holding whatever prog1’s kernel path left there. The loop dereferences a garbage p and takes a load page fault in S: the transcript reads U:1, then S: unexpected scause=0xd, then the halt. The user register file was never at risk — it lives in the frame — but the kernel’s own continuation was, and the ABI is the only thing that says which registers carry it.

(b) Give every process the same kernel stack — one page, one kstack_top — and run the cooperative pair. Derive the failure.

Answer

prog1 traps for its first yield: user_vec pushes its 280-byte frame at the top of the shared page, trapper, syscall, and sched grow below it, and swtch records prog1’s ctx.sp somewhere inside that region. The loop picks prog2, whose fabricated ctx.sp is the same page top; proc_entry → proc_run → sret. prog2 traps for its first yield, and user_vec pushes prog2’s frame at the same page top, over prog1’s, with prog2’s kernel frames over prog1’s. When the loop next resumes prog1, its swtch returns onto memory that now holds prog2’s frames of identical shape: it unwinds through prog2’s trapper frame into user_vec’s tail and user_ret restores prog2’s user frame — prog2’s sepc, prog2’s sp. The hart is now running prog2’s code while curproc says prog1, and the transcript prints U:2 where U:1 was due. A stack that two worlds share is a frame that two worlds share.

(c) Same shared stack, but the preemptive run. Which process’s frame does the second user_vec overwrite, and what is the invariant that a per-process kernel stack actually enforces?

Answer

The same overwrite, at the tick instead of the yield: the first tick preempts prog1 mid-spin, its frame sits at the page top, the loop switches to prog2, and prog2’s first trap — the second tick — pushes over it. The tempting rule, “never call swtch from a trap handler,” is wrong: preempt_tick calls sched from inside trapper on every tick in the working kernel, and it is correct, because that trapper frame is on the preempted process’s own stack. The invariant is that every frame — user or kernel — lives on the stack of the world it belongs to, so that switching sp switches all of them together and none of them is under anyone else’s feet. Per-process kernel stacks are how that invariant is spelled.

(d) Arrange for the tick to arrive while the kernel is in the middle of a write syscall for prog1. What state is already saved, by whom, and where does the tick actually land?

Answer

It does not land in the middle of the syscall. Hardware cleared sstatus.SIE when the ecall trapped into S, and nothing in the kernel sets it again, so SSIP sits pending through trapper, syscall, and user_ret. The sret copies SPIE=1 into SIE and the pending interrupt is taken at the very next instruction boundary — in U, with sepc at the instruction after the ecall. By then everything the syscall produced is already in the frame (tf->a0, the advanced sepc), saved by syscall itself, and the second trap saves the user register file again through user_vec. Had the kernel run with SIE set, the tick would have entered through trap_entry — stvec is the kernel’s entry while the kernel runs — pushed a frame below the syscall’s, and preempt_tick would have switched from there, on the same per-process stack, also correctly. The non-preemptible kernel is a simplification the design chooses, not a requirement the mechanism has.

(e) Compute the kernel-stack budget: the deepest path this chapter’s kernel takes on a process’s stack, against the page it has.

Answer

From the image’s disassembly: user_vec’s frame is 280 bytes; trapper allocates 32; syscall 176 (its 128-byte kbuf for write is inlined there); preempt_tick 32; uart_puthex 32; sched allocates nothing and tail-calls swtch, which uses no stack — the fourteen words go into struct ctx inside struct proc, not onto the stack. The ecall path is therefore 280+32+176=488280 + 32 + 176 = 488 bytes; the tick path 280+32+32+32=376280 + 32 + 32 + 32 = 376. Against a 4096-byte page that is under 12 %, with nothing nested because the kernel is non-preemptible. The budget is generous by design: what would eat it is not depth but a second frame on the same stack, which (b) and (c) rule out.

(f) swtch saves no floating-point registers, and neither does the trap frame. Is that because this hart has no FPU?

Answer

No. Read misa at boot: 0x80000000001411ad, and bits 5 and 3 — F and D — are set; QEMU’s virt hart has a full double-precision unit. What makes the omission correct is mstatus.FS: bits 14:13 read 0, Off, at reset, and no code in ember ever sets them. With FS=Off every floating-point instruction traps as illegal (cause 2), so there is no floating-point state that could be live, and a save would be saving nothing. The kernel and every user program are compiled -march=rv64ima_zicsr, so the compiler never emits such an instruction in the first place — that is what guarantees no path needs FS on. The choice buys 32 registers plus fcsr — 264 bytes — not saved on every trap and every switch, and no dirty-tracking. A kernel that lets processes use the FPU has to turn FS on, save that state, and usually save it lazily; the march flag in Part I’s build is where this kernel declined that work.

Lab

make lab CH=08
make lab CH=08 IMPL=mine

The transcript has two halves. The cooperative run alternates U:1 and U:2 three times, then S: proc 1 exited, S: proc 2 exited. Then S: preemptive run, U:1, and the tick takes over: S: tick 0xN is chapter 6’s handler still counting, S: preempt N to U:M is this chapter announcing the pick, and U:2 appears once — the second program’s single line before it spins. Four preemptions, then the fifth tick prints PASS. The tick is 1 Hz, so the run takes about five seconds; the lab’s timeout is thirty.

The order is fixed, with one dependency worth naming: the cooperative half must finish inside the first tick interval, so that the tick handler’s first call finds the preemptive pair already running. It takes milliseconds under QEMU; the margin is three orders of magnitude, and the line order within each interval is fixed because a program’s single write takes microseconds against a one-second tick. Nothing in the transcript is a counter value.

IMPL=mine copies exactly the objects chapter 8 links and stubs swtch to print MINE: swtch stub and halt — the lab boots, prints S: kernel up, and fails loudly at the first switch with no user lines.

Further reading

  • The RISC-V Instruction Set Manual, Volume II: Privileged Architecture (RISC-V International, v20260120, January 2026) — sstatus.SIE/SPIE across sret, mscratch/sscratch, mstatus.FS, sfence.vma after PTE updates, and the interrupt-taking rule at instruction boundaries.
  • xv6-riscv (MIT PDOS) — kernel/swtch.S is the same fourteen words; kernel/proc.c’s scheduler/sched pair is the same two-switch loop, with a per-CPU scheduler context this single-hart kernel collapses to one.

results matching ""

    No results matching ""