60k · Preemption¶
Released Fri Dec 4, in class: posted here early
This is the README OSlings will give every student for 60k_preemption (oslings
lesson shows it) when the exercise is released on Fri Dec 4. The starter code
is not published here: it reaches you through OSlings, in class on the
class network. It is extra credit, +0.5: see
Extra Credit. Back to All Exercises.
Extra credit. No session of its own: it is released with a core exercise and worked once that day's core exercise passes, in class or in office hours. Prerequisites: 51k_fork_wait (do 53k first if you want your own commands to keep working). Nothing later depends on the code you write here.
Learn → Understand → Implement. Let the timer take the CPU away from a user process. One program stuck in a loop can no longer freeze the machine, and round robin finally shares the CPU among programs that never give it up.
Learn¶
The hole in cooperative scheduling¶
Since exercise 51k, rv6 has run several processes at once, but only
cooperatively: a process keeps the CPU until it gives it back, by blocking in
wait or by exiting. Every program so far has been polite. This one is not:
It never makes a system call, so it never gives the CPU back. Today that
freezes rv6: a program like that at the rv6$ prompt never returns, and the
only way out is Ctrl-A X.
The odd part is that the kernel does get control, ten times a second. The
timer from exercise 44k fires while user code runs, and each tick traps into
usertrap. But all usertrap does with a tick is clear the pending bit and
return to the same process. The kernel holds the CPU on every tick and hands it
straight back.
Preemption: the timer takes the CPU back¶
Preemption means the kernel takes the CPU away from a process that did not offer it. Nothing new is needed, only a use for the tick you already get:
user code running ... tick!
→ uservec saves every register in the trapframe (given, 48k)
→ usertrap: clear the pending bit (given, 44k)
→ preempt(p): one more tick of p's time slice <- YOU
slice used up? → proc_yield(p) (given, 51k)
p stays Runnable; swtch to the scheduler
→ round robin picks the next process; it runs
... later, p's turn comes around again ...
→ proc_yield returns, into preempt
→ back in usertrap → usertrapret → p continues where the tick stopped it
proc_yield is the call wait has used since 51k to wait without freezing the
machine. A preempted process takes exactly the same path. The only difference is
who decided: with wait the process gave up the CPU itself; with preemption the
kernel decides for it.
Why stopping a program anywhere is safe¶
The tick can land between any two instructions: in the middle of a loop, halfway through computing a value. Picking up later where it left off works because none of the program's state is lost:
- Its registers and pc.
uservecsaves all 31 registers in the trapframe,usertrapsavessepc, anduserretputs them all back. A loop counter int0comes back with the same value. This is why the trapframe saves every register, not just the ones the calling convention says survive a call: a tick is not a call, and the program had no chance to save anything. - Its kernel-side state. Everything between the trap and
proc_yieldsits on the process's own kernel stack, which nothing else touches while it waits. - Its memory. Its page table is its own.
Only user code is preempted¶
rv6 preempts only user code. While the kernel is running, inside a system call
or in the scheduler, a tick never switches processes. Under cargo run it goes
to kerneltrap, which only counts it (exercise 44k). Under the harness the
kernel keeps interrupts off, so the tick waits until the next return to user
mode.
This matters because rv6's kernel data has no locks: the process table, the
free page list, CURPROC. They are safe only because one CPU runs one piece of
kernel code at a time, start to finish. Switching away halfway through
allocproc to run another process's fork would corrupt the table. Kernels
that do preempt kernel code must guard every shared structure with locks that
also turn interrupts off, like the spinlocks of exercise 37k.
One given line enforces this on the way out. usertrapret now turns interrupts
off before it points stvec at the trampoline. Under cargo run the kernel
runs with interrupts on, and a tick between that line and sret would enter
uservec from kernel mode and wreck the trapframe. sret turns interrupts back
on for user mode.
The time slice¶
Yielding on every tick would work, but every switch costs time: saving and restoring registers, switching page tables, flushing the TLB, and a cold cache for the next process. So each process gets a time slice (or quantum) of several ticks before it has to yield. The tradeoff:
- A long slice wastes less time switching, but a process waiting its turn waits longer: with n processes, up to (n − 1) slices. Interactive programs feel sluggish.
- A short slice keeps everyone responsive, but spends more of the CPU on switching.
rv6's quantum is QUANTUM = 2 ticks (in param.rs), about 0.2 s. That is far
too long for a real system (Linux slices are a few milliseconds), but long
enough to see processes take turns.
Each process counts its own slice in a new field, Proc::ticks. preempt adds
one per tick. When the count reaches QUANTUM, it sets the count back to 0, so
the next turn starts with a full slice, and yields.
Round robin, finally¶
The policy you wrote in exercise 36k (scan the table from just past the last process picked, and take the first Runnable one) has run every process since 51k. With cooperative processes it was only ever handed the CPU when someone blocked or exited. With preemption, three processes that never stop share the CPU in turns:
time → | A A | B B | C C | A A | B B | C C | A A | ...
one time slice = 2 ticks; each | is a preemption
That is time sharing: every runnable process makes progress, and none can starve the others.
Understand¶
Read in this order. Skip whatever is not named here.
rv6/src/param.rs:QUANTUM.rv6/src/proc.rs: the newticksfield at the end ofProc, and whereallocproczeroes it.rv6/src/usermode.rs:proc_yield(given since 51k): what your code calls.preempt: yours. Read its doc comment.usertrap: the interrupt branch, cause1. The given lines clear the pending bit; your call goes after them.usertrapret: the new first line, which turns interrupts off, and the comment above it.- Skip the "test's stopwatch" section near the top, and the
#[cfg(feature = "harness")]lines inschedulerandusertrap. They record each time slice for the harness and never change which process runs.
rv6/src/exec.rs: the comments above the three new programs at the end of the assembly:hog,rr, andspin3, which only the harness can run because it never ends.- Optional,
rv6/src/main.rs:preempt_self_check, to see which[fail]line points at which mistake.
Implement¶
Both steps are in rv6/src/usermode.rs:
preempt: count the tick in(*p).ticks. Once the count reachesQUANTUM, set it back to 0 and callproc_yield(p). About five lines.usertrap: in the timer branch, after the given lines, callpreempt(p).
Check your work:
The harness runs three programs:
hog: one child spins forever while another writes "worker done" and exits. The parent'swaithands the CPU to the spinner first, so the run can only finish if the timer takes the CPU away from it.spin3: three processes spin forever. The harness watches nine time slices, prints the schedule asprocess:ticksfor each slice (a correct kernel printsA:2 B:2 C:2three times), and checks that the order is round robin and that every slice lasted exactlyQUANTUMticks.forks2andexectest, to check that fork, wait and exec still work.
| If you see | It means |
|---|---|
hog never finished |
Nothing preempts: usertrap doesn't call preempt, or preempt never yields |
lasted 1 tick, with every slice :1 |
preempt yields on every tick instead of counting to QUANTUM |
lasted 3 ticks |
preempt yields a tick late: > instead of >=, or it compares before it counts |
later ones short, or preempted once, then kept the CPU |
The count is never set back to 0 |
not left Runnable |
The process was parked where the scheduler never picks it: call proc_yield |
Then watch it live:
At the rv6$ prompt, run rr forks three children that print A, B and C,
each pausing 50 ms between letters. Each run of one letter is one time slice:
Without preemption the same program prints all the A's, then all the B's, then
all the C's. run hog comes back with exited with status 15 instead of
freezing the shell. (Exit QEMU with Ctrl-A then X.)
Stuck? oslings hint.