CComputer Science, Built

Act VI · One Machine, Many Programs

Part 31 of 61

The Kernel

Degreestarts at this level50 min of film17 chaptersprerequisites: Part 6, Part 10, Part 11, Part 13

How can one processor run many programs at once, safely, and why does a busy one feel so slow?

The part opens with one user who thinks for 10 seconds and computes for half a second, so the processor idles 95% of the time, and with PebbleOS booting and two processes printing interleaved letters. Time-sharing, from CTSS to Unix, needs three protections: Pebble gains a mode bit, privileged instructions, control registers and a timer, and a hostile halt, a wild store and a processor hog are each stopped. The trap, the process control block, the context switch and fork, exec and wait are traced in PebbleOS and measured on this machine. Scheduling follows: the convoy under FCFS, shortest-job-first by an exchange argument, round robin and its quantum, Corbato's multi-level feedback queue and how to game it, lottery, stride and CFS, work stealing, and the real-time bound of Liu and Layland with Mars Pathfinder's priority inversion. The part turns to queueing theory, where Little's law, M/M/1 and Pollaczek-Khinchine explain why response time explodes near full load and grows with the variance of the job size. It ends with PebbleOS, a kernel of 284 instructions, running the Job as two processes joined by a pipe: ledger row 11, 2.17 seconds against 0.81 bare.

What you need. Programming in C or a similar language; means, variances and the exponential distribution for the queueing chapter.

Mathematics, ideas and history
protection, traps and interrupts, processes, fork/exec, scheduling (SJF, MLFQ, CFS, EDF, Liu–Layland), queueing theory
What we build or compute
PebbleOS boots and runs two processes

What you will be able to do

Degree

  • Trace a system call through the trap, the kernel's dispatch and the return, and say what the mode bit, the bounds check and the timer each protect.
  • Draw the Gantt chart of a small workload under FCFS, SJF, SRTF and round robin, and compute its mean turnaround and response times.
  • Describe a process's states and what a context switch saves.

Graduate

  • Prove by an exchange argument that shortest-job-first minimizes mean turnaround, and state the rules of the multi-level feedback queue and the rule that stops gaming.
  • Test a periodic task set against the Liu-Layland bound and by response-time analysis, and explain why EDF schedules what rate-monotonic priorities miss.
  • Derive the M/M/1 response time, and apply Little's law and Pollaczek-Khinchine to a server.

Research

  • Explain what the proofs of seL4, CertiKOS and Hyperkernel establish and what they assume.
  • Compare a queue per core, one central queue and preemptive quanta for the 99.9th percentile of short requests, and state the open problem of the best quantum under switching overhead.

Industry

  • Read a system's cost in system calls and context switches with strace-style counts, and choose a buffer size from the measured cost per call.
  • Size a server from its load and job-size variance, and say why running near full utilization trades throughput for latency.
  • Compare monolithic kernels, microkernels, exokernels and unikernels by what runs in kernel mode.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 31 min · Graduate 47 min · Research 50 min · Industry 33 min.

  1. 0One machine, many programsDegree2 min
  2. 1From batch to time-sharingDegree3 min
  3. 2Protection: the mode bitDegree3 min
  4. 3Traps and the system callDegree3 min
  5. 4The processDegree2 min
  6. 5The context switchDegree2 min
  7. 6fork, exec and waitDegree3 min
  8. 7Scheduling: FCFS, SJF, SRTFDegree3 min
  9. 8Round robin and the multi-level feedback queueDegree4 min
  10. 9Proportional share: lottery, stride, CFSGraduate2 min
  11. 10Many processorsGraduate2 min
  12. 11Real timeGraduate4 min
  13. 12Queueing theoryGraduate6 min
  14. 13Kernel designsIndustry2 min
  15. 14PebbleOS runs the JobDegree4 min
  16. 15Frontier: verified kernels and microsecond schedulingResearch3 min
  17. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

One machine, many programsDegree2 min

In 1960 a computer cost millions of dollars, and it spent most of its time waiting. Put one person at the console, and the pattern is always the same: think for ten seconds, then ask for half a second of computing. The processor sits idle ninety-five percent of the time. The first answer was batch processing: hand your program to an operator on punched cards, and come back for the printout hours later. The machine stayed busy, and programmers waited. The second answer was time-sharing: connect many terminals, and give each user the machine for a fraction of a second in turn. Every user then sees a whole computer of their own, while the computer itself works through a queue.

By the end of this part, our own machine will do the same. Here is PebbleOS, a kernel we are about to write, booting on the Pebble computer with two programs loaded. Each program prints its letter, A or B, twenty-four times. The chart shows who has the processor, instruction by instruction: program A, then the kernel, in orange, then program B. A timer interrupts whichever program is running every nine hundred instructions, and the kernel hands the processor to the other. The output interleaves. Neither program knows the other exists. Fifteen switches, fourteen timer interrupts, fifty-two system calls. And here the kernel itself ran forty-four percent of all instructions, because every single letter was a request to the kernel. Making that cheaper is part of the story.

1From batch to time-sharingDegree3 min

Five systems tell the story. In 1956, General Motors and North American Aviation wrote a monitor for the IBM 704 that loaded the next job as soon as the last one finished: batch processing, and arguably the first operating system. In 1961, Fernando Corbató's group at MIT demonstrated CTSS, the Compatible Time-Sharing System. A clock interrupted each user's program after a short slice and moved to the next, and memory protection kept the programs apart. It eventually served about thirty users at once. Multics, begun in 1965 by MIT, Bell Labs and General Electric, aimed at a computer utility, like the electricity grid, with rings of protection and a tree of files. It was ambitious and late, and Bell Labs withdrew. Two of the Bell Labs people, Ken Thompson and Dennis Ritchie, then wrote something smaller on a spare PDP-7 in 1969: Unix. They rewrote it in C in 1973 and described it in 1974. In 1991 a Finnish student, Linus Torvalds, announced a free Unix-like kernel for his PC. Today Linux runs most servers, every Android phone, and every one of the five hundred fastest supercomputers. The ideas in this part were all settled between 1961 and 1974, and they are the ones in the phone in your pocket.

How many users can share one machine? Treat each user as a loop. Think for ten seconds, then ask for half a second of processor time, and wait for the answer. We simulated this, with the processor shared equally among everyone waiting, which is what fast time-slicing approximates. With a few users, nobody waits: the response time is the half second of work. But the processor can only do two jobs per second, and twenty users thinking ten seconds each ask for about two per second. Past twenty-one users, the machine is always busy, and each additional user adds half a second to everybody's response. The knee sits where the two straight lines meet, and the simulation follows them. This is the interactive response time law, from the theory of closed queues: response equals users over throughput, minus think time. We will come back to queues in chapter twelve.

2Protection: the mode bitDegree3 min

Before time-sharing, the one program running owned the machine, and could do anything. With several programs at once, any one of them can ruin everybody's day, in three ways. By an instruction: halting the machine, or reprogramming a device. By memory: storing over the kernel, or over another program's data. And by time: a loop that never gives the processor back. On the Pebble we have built so far, a single halt in any program stops everything. So the hardware must take three things away from ordinary programs: some instructions, most of memory, and control of time. And there must be exactly one way to ask for them back, through the kernel.

Here is what Pebble gains, in under two hundred lines of the emulator. Four instructions, in the opcodes we left free in Part 6. E-call traps into the kernel; it is the one door. E-ret returns from a trap. And two instructions read and write control registers. The control registers hold the mode, where a trap happened and why, where traps should go, a countdown timer, and the bounds of the memory the running program may touch. And one bit of state, the mode. The machine starts in kernel mode, and the only way down to user mode is e-ret. In user mode, the privileged instructions are illegal, and any address outside the bounds, or in the device page, is a fault. The timer counts instructions down; at zero it interrupts whatever is running, and hands the processor back to the kernel. IBM's System/360 had the same idea in 1964, and called the two modes the problem state and the supervisor state.

Now the test. PebbleOS starts four processes, three of them hostile. One prints the letter A twelve times. One executes halt. One stores a zero into the kernel's memory. And one loops sixty thousand times without ever calling the kernel. The halt is an illegal instruction in user mode: the hardware refuses it and traps, and the kernel kills that process. The store is outside the process's bounds: another trap, another kill. The hog is interrupted by the timer a hundred and twenty-one times, and the other processes run in between. The good process prints all twelve letters. In every case the offending instruction never completes. The hardware stops it and jumps into the kernel, which decides what to do. And protection is nearly free while programs behave: a comparison the hardware makes on every access, in parallel with the access itself.

3Traps and the system callDegree3 min

A program asks the kernel for something by setting up its request in registers, here call number three, get my process id, and executing e-call. The hardware then does five things in a single step. It saves the program counter, so it knows where to come back. It records the cause: an e-call, or for a fault, the bad address too. It turns interrupts off. It switches to kernel mode, remembering the old mode. And it jumps to the one address the kernel chose at boot. The program cannot choose where in the kernel it lands, and that is the point: every request goes through one gate the kernel controls. E-ret reverses the last three steps, and the program continues after its e-call. The same mechanism serves every event the instruction itself causes, from an e-call to a division by zero. Interrupts from outside, like the timer, use the same five steps, between two instructions of whatever program is running.

Now follow one system call all the way down. A process calls get-pid, and we record every instruction the kernel executes before the process runs again. Each bar is one instruction, coloured by what it is for. First, twenty-six instructions save the program's registers into its process control block, because the kernel is about to use those registers itself. Then twenty-three find out which call this is. The work itself takes three instructions: load the process id, and store it where the program's a-zero will be restored from. Then twenty-six more put every register back, and e-ret returns. Seventy-eight instructions, to return one number. And for calls that take a buffer, the kernel first checks that the buffer lies inside the caller's memory. A program that passes a pointer into the kernel gets an error, not the kernel's secrets.

On a real machine, this one, the numbers look like this. An ordinary function call takes one and a half nanoseconds. Asking the kernel for the process id takes a hundred and twelve: about seventy-five function calls. The hardware trap is part of it. Saving state is part of it. And since 2018, the defences against Spectre and Meltdown from Part 8 add work to every crossing. Some requests skip the trap altogether. Linux maps a page of kernel code and data into every process, the vDSO, so reading the clock is an ordinary function call: twenty-nine nanoseconds, with no change of mode.

4The processDegree2 min

A process is a program while it runs: the code, plus everything that changes as it runs. Here is the job's process under PebbleOS: one mebibyte of memory, from its lower bound to its upper bound. At the bottom, the small library that every process links, and its two buffers. Then the compiled code of the Job itself, under two kibibytes. Then its globals, mostly the hash table from Part 17. And at the top, the stack, growing down. The rest of the process lives in the kernel, in its process control block. Its state; its fifteen registers and its program counter, saved at every trap; its bounds; its number; where its input comes from and its output goes; and a few counters. That is everything the kernel needs to stop a program at any instruction, and later resume it as if nothing had happened. PebbleOS keeps four of these blocks in a table. The Linux equivalent has hundreds of fields, but the same idea.

Every process moves through a few states. It is created and loaded, and becomes ready: able to run, waiting for a processor. The kernel dispatches it, and it runs. When the timer fires, it goes back to ready, and another process gets the processor. When it asks for something that is not there yet, like bytes from an empty pipe, it is blocked, and costs nothing until the bytes arrive and it is woken. When it calls exit, it is finished. The numbers are counted in PebbleOS, while our two processes ran the Job on a short passage: forty-one dispatches, thirty-eight timer interrupts, one wait for the pipe. At any moment one process per processor is running, and any number may be ready. Choosing which ready process runs next is the scheduler's whole job, and the subject of chapters seven to eleven.

5The context switchDegree2 min

To switch from process A to process B, the kernel does three things. A trap brings it in, from the timer or a system call, and it saves A's registers and program counter in A's process control block. The scheduler chooses B. Then the kernel loads B's saved registers, sets B's bounds, and returns with e-ret, into B, at exactly the instruction where B was stopped last time. In PebbleOS that is eighteen words per process, and a switch through yield costs a hundred and eighteen kernel instructions. A real kernel saves more: the floating-point and vector registers, two kibibytes of them on a processor with AVX-512, and it changes the address space, which is Part 32's subject. And neither process can tell. Each resumes with its registers exactly as it left them.

How long does a switch take on a real machine? The standard experiment: two processes joined by two pipes, bouncing one byte back and forth. Each must block until the other answers, so every round trip forces two context switches and four system calls. With both processes on one processor, a round trip takes two point nine microseconds. With the processes on different processors it is much slower, twenty-five microseconds here, because the other core has gone to sleep and must be woken by an interrupt between processors, and on a virtual machine that is expensive. And the largest cost is often invisible in this measurement: the incoming process finds the caches full of the other one's data, and runs slowly until it has refilled them. So a scheduler should not switch more often than it must. How often it must is the question of the quantum.

6fork, exec and waitDegree3 min

Unix creates processes with three calls. Fork makes the calling process into two. Parent and child are identical, with the same memory contents and the same open files, except that fork returns zero in the child and the child's number in the parent. Exec replaces the program a process is running with another, keeping the same process and its open files. And wait puts the parent to sleep until a child exits, then hands back its exit code. Why separate fork from exec? Because in between, the child is still running the shell's code, and it can rearrange its own files with ordinary calls before becoming the new program. That is how output redirection and pipes work, with no special support in the call that starts the program.

With those three calls a shell is short. This one is twenty-five lines of C, and it runs on this machine. It reads a line and splits it at a bar. For each command it forks; the child connects the pipe to its standard input or output with dup-two, then execs the command. The parent closes its copies of the pipe and waits for both children. We typed echo hello world, and then echo the cat sat, piped into tr, which translates lower case to upper. The pipe is a buffer inside the kernel with two ends. Echo writes into one; tr reads from the other; neither knows the other exists. Doug McIlroy pushed pipes into Unix in 1973, and they changed how people wrote programs: small tools, joined together.

What does a new process cost? On this machine, a fork whose child exits at once takes a hundred and fifty microseconds. Fork followed by exec of a tiny program takes about a millisecond and a quarter, and posix-spawn, which does both in one call, about the same. But watch what happens when the parent is using memory. With a gibibyte in use, fork takes thirty-three milliseconds. Fork does not copy the memory itself: it copies the map of it, and marks every page to be copied later, only if someone writes. That trick is Part 32's. But the map grows with the memory. In 2019 researchers from Microsoft, Boston University and ETH Zurich argued that fork no longer fits modern systems, and that new code should use spawn. PebbleOS has no fork at all. With bounds but no relocation, a copy of a process would need the very same addresses. Part 32 gives each process its own addresses, and then fork becomes possible.

7Scheduling: FCFS, SJF, SRTFDegree3 min

Scheduling: first come first served, shortest job first, and shortest remaining time. A scheduler decides which ready process runs next. What should it optimise? For a batch job, the turnaround time: from arrival to finish. For a person at a keyboard, the response time: how long until the program first does something. The waiting time: how long a job sat ready but not running. The throughput: how many jobs finish per second. And fairness. These conflict. We will see that the best order for turnaround starves long jobs, and that switching often for good response time costs throughput.

The simplest scheduler runs jobs in the order they arrive, to completion: first come, first served. Three jobs arrive together. A needs a hundred ticks of processor time, B and C need ten each. If A happens to be first, B and C wait behind it, like cars behind a truck on a mountain road. The finish times are a hundred, a hundred and ten, and a hundred and twenty: a mean turnaround of a hundred and ten. This is the convoy effect. Run the short jobs first instead, and they finish at ten and twenty, and A still finishes at a hundred and twenty. The mean falls to fifty.

Shortest first is not just better here: for jobs that are all present at the start, it is the best possible order, and the proof is a single swap. Take any order in which a long job, of length L, runs immediately before a short one, of length S. Swap them. The short job now finishes L earlier, the long one finishes S later, and every other job finishes at the same time as before. So the total of the completion times changes by S minus L, which is negative. An order with a long job before a short one can always be improved, so the best order has none: shortest first. The same exchange, made whenever a new job arrives, shows that shortest remaining processing time first is optimal even when jobs arrive over time. Linus Schrage proved it in 1968.

Jobs do not all arrive at the start. Here A starts alone, and B and C arrive ten ticks later. Shortest job first never interrupts a running job, so B and C wait for all of A: a mean turnaround of a hundred and three. Shortest remaining time first preempts: when B arrives needing ten ticks, and A still needs ninety, A is set aside. The mean falls to fifty. On four hundred random jobs arriving at eighty percent load, shortest remaining time first has the best mean turnaround, half that of first come first served. Round robin, the next chapter, has the best response time. But all of this assumes the scheduler knows how long each job will run, and it does not. Real schedulers guess, from how long each process ran the last few times.

8Round robin and the multi-level feedback queueDegree4 min

For people at keyboards, response time is what matters, and the fix is to take turns. Three jobs of thirty ticks each. First come first served answers the third job only after sixty ticks. Round robin gives each job a quantum of five ticks, then moves to the next: every job starts within ten ticks, and the mean response time falls from thirty to five. But look at the finish times. Every job is still running near the end, so the mean turnaround rises from sixty to eighty-five. For jobs of equal length, round robin is the worst order for turnaround. This is the time-sharing of CTSS: a timer interrupt at the end of every quantum, and the next ready job.

How long should the quantum be? We ran round robin on the four hundred random jobs, charging one tick for every switch. With a quantum of one tick, half the processor's time goes on switching. The machine is effectively overloaded and the queue explodes. Around twelve ticks, the response time is lowest. And with a very long quantum, round robin turns back into first come first served. Real kernels choose quanta of a few milliseconds, a thousand times longer than a switch, so switching costs under one percent.

Shortest first needs to know the future. Round robin ignores it. Corbató's multi-level feedback queue, from CTSS in 1962, learns it from behaviour. There are several queues, each with a priority. A higher queue always runs first, and within a queue jobs take turns. Every new job starts at the top, where the quantum is short. A job that uses up its allotted time at a level is demoted: it has shown that it computes for long stretches. And every so often, every job goes back to the top. We will see why. Here are two long computations, H1 and H2, and an interactive job, I, which computes for one tick and then waits nine for input. The hogs sink to the bottom. I never uses up its allotment, stays at the top, and runs the moment it is ready. It finishes at three hundred and forty-one ticks, against six hundred and forty-one under round robin, and nobody told the scheduler which job was which.

Any rule based on behaviour can be gamed. The first version of rule four reset a job's allotment whenever it gave up the processor for input or output. So a clever program computes for nine ticks, does a token one-tick read, and computes again, always just inside its quantum of ten. It never looks like a hog, stays in the top queue, and takes eighty-nine percent of the machine. Counting each job's time at a level in total, however it is broken up, fixes this: the gamer drops to seventeen percent. The other danger is starvation. With three interactive jobs keeping the top queue busy, a long job at the bottom got ten ticks in fifteen hundred. Rule five, the periodic boost to the top, guarantees it a slice every two hundred ticks. Variants of this design scheduled Solaris and the BSD systems, and Windows still boosts the priority of threads that have just finished waiting.

9Proportional share: lottery, stride, CFSGraduate2 min

Sometimes we want shares, not priorities: three quarters of the machine for A, one quarter for B. Carl Waldspurger and William Weihl's lottery scheduling, in 1994, gives A three hundred tickets and B a hundred, and at every quantum draws a ticket at random. On average A gets three quarters. But in any one run, after a hundred and twenty quanta, A's share might be anything from two thirds to eighty-five percent. A year later Waldspurger gave the deterministic version, stride scheduling. Each job's stride is a large number divided by its tickets, and each job keeps a pass value. Run the job with the smallest pass, and add its stride to it. Stride keeps the ratio exactly three to one, give or take one quantum, at every moment.

Linux took a different road to proportional share. Since 2007 its main scheduler, Ingo Molnár's completely fair scheduler, tracks a virtual runtime for each task. The virtual runtime grows as the task runs, more slowly for tasks with more weight. The scheduler always runs the task whose virtual runtime is smallest, and keeps the tasks sorted in a red-black tree, the balanced tree of Part 17, so the choice takes logarithmic time. Tasks a and b alternate. When c arrives at tick forty, it starts at the smallest virtual runtime, not at zero, or it would monopolise the processor while it caught up. The weights come from the nice value: each level is a factor of one point two five. A task at nice zero against one at nice five gets seventy-five point four percent, as the weights predict. In 2023, Linux 6.6 replaced it with EEVDF, an algorithm from 1995 that keeps the same shares but also gives each task a virtual deadline, so that tasks needing short, frequent slices get them promptly.

10Many processorsGraduate2 min

With several processors, the first question is where the queue lives. One shared queue is simple and balances load perfectly, but every core must lock it to take a job, and a job runs on whichever core happens to be free, far from the data it left in another core's cache. So Linux, since version 2.6, keeps a queue per core. A job that stays on one core finds its data still in that core's caches. That is called affinity. Moving work is expensive. Waking a job on another core took twenty-five microseconds here, against three on the same one. But queues drift out of balance, so the kernel periodically moves work, from busy cores to idle ones, trying nearby cores first.

For programs that split themselves into many small tasks, there is a better scheme than a balancer. Each worker keeps its own double-ended queue of tasks, pushing and popping at the bottom. A worker that runs out picks another at random and steals from the top of its queue. We simulated a fork-join computation with eighty-three thousand units of work and a critical path of seventy-one. Blumofe and Leiserson proved in 1999 that work stealing finishes in expected time the work divided by the workers, plus a multiple of the critical path. The simulation sits right on that line, up to sixty-four workers, which run sixty times faster with only four hundred and eighty-seven steals. Steals are rare because the top of a queue holds the oldest task, which is usually the biggest. This is the scheduler inside Cilk, Java's fork-join pool, Go's runtime, and Rust's Rayon and Tokio.

11Real timeGraduate4 min

In a car's brakes or an aircraft's controls, a late answer is a wrong answer. Real-time systems run periodic tasks, each needing some work every period, finished before the next one starts. Task one needs two ticks every five, and task two four ticks every seven. Together they keep the processor ninety-seven percent busy. The classic scheme gives fixed priorities by rate: the shorter the period, the higher the priority. That is rate-monotonic scheduling. At tick seven, task two has had only three of its four ticks, because task one keeps preempting it. It misses its deadline. Earliest deadline first instead runs whichever task's deadline is nearest, so priorities change from moment to moment. It meets every deadline. Liu and Layland proved in 1973 that on one processor, earliest deadline first succeeds whenever the total utilisation is at most one for independent, preemptible tasks whose deadlines equal their periods, with no blocking or scheduling overhead. Fixed priorities are still the common choice: they are simple, and when the system is overloaded only by lower-priority work, the higher-priority tasks remain protected. If their own demand is excessive, higher-priority tasks can miss deadlines too.

For rate-monotonic scheduling, Liu and Layland found a simple sufficient test. If the utilisation is at most n times two to the one over n, minus one, every deadline is met. For one task that is a hundred percent; for two, eighty-three; for four, seventy-six; and as n grows it falls to the natural logarithm of two, about sixty-nine percent. The proof sketch: the worst moment is when all tasks are released together, and the worst task set has periods within a factor of two, each task's work just filling the gap between the next two periods. But the test is only sufficient. We generated random sets of four tasks at each target utilisation and rounded their work to whole ticks, changing the realized load. The sufficient utilization bound admits fewer samples than response-time analysis, which computes each task's worst response time. Earliest deadline first accepts exactly the generated sets with realized load at most one. Rounding can make that fraction less than one near a target of one hundred percent. And when the periods divide one another, rate monotonic can use the whole processor: periods of ten, twenty and forty, at eighty-seven and a half percent, are comfortably on time.

Days after Mars Pathfinder landed in July 1997, its computer started resetting itself. Three tasks matter. A low-priority meteorological task takes a lock on the information bus. The high-priority bus manager arrives and waits for the lock. Then a medium-priority communications task, which needs no lock, preempts the meteorological task, and runs for a long time. The high-priority task is now stuck behind a medium-priority one: priority inversion. It misses its deadline, and a watchdog concludes that something is badly wrong and resets the system. The cure is priority inheritance: while a task holds a lock that a higher-priority task wants, it runs at that higher priority. Now the meteorological task finishes with the lock quickly, and the bus manager is done at tick thirteen. Engineers at the Jet Propulsion Laboratory reproduced the fault on a copy of the spacecraft on Earth, and fixed it by uploading a change to one setting of the VxWorks operating system, turning inheritance on.

12Queueing theoryGraduate6 min

Queueing theory begins with a law so general it is almost a tautology. Plot the number of customers who have arrived at a server, and below it the number who have left. Between the two curves, each horizontal strip is one customer, from arrival to departure: its width is that customer's time in the system. Now read the same area by columns: at any moment the height between the curves is the number of customers inside. So the total of everyone's time equals the integral of the number present. Divide both sides by the length of time. On the left, arrivals per unit time times the mean time each spends; on the right, the mean number inside. L equals lambda W. John Little proved it in general in 1961: it holds for any queue, any order, any distribution. In our simulation at eighty percent load, the two sides agree to three decimal places.

The simplest queue with randomness in it is called M/M/1: customers arrive at random, at rate lambda; one server works on them at rate mu, each job taking a random, exponentially distributed time. Its state is just the number of customers inside. Arrivals push it up one, at rate lambda; completions pull it down one, at rate mu. In the long run, the flow across each cut between neighbouring states must balance: lambda times the probability of n equals mu times the probability of n plus one. So the probabilities fall off geometrically, by the ratio rho, lambda over mu, which is the fraction of time the server is busy. The mean number inside is rho over one minus rho. And by Little's law, the mean time inside is one over mu minus lambda.

Plot one over one minus rho, the mean response time in units of the service time. It is the hockey stick. The dots are our simulation, a million jobs at each load, and they sit on the formula. At fifty percent load, a request takes twice as long as on an idle machine. At ninety percent, ten times as long: five times worse than at fifty, though the server is only working eighty percent harder. The tail is worse still: at ninety percent load, one request in a hundred takes forty-six service times, because the response time of this queue is itself exponentially distributed. Near a hundred percent, every extra percent of load costs more than the one before, which is why people who plan capacity aim for fifty to seventy percent, and why a server that seemed fine yesterday can fall over today with only a little more traffic.

Why so steep? Watch the number of jobs in the system over time. It is a random walk: up one at each arrival, down one at each completion, and it cannot go below zero. At fifty percent load the walk is pulled firmly down, and bursts of arrivals drain away quickly. At ninety percent the pull is weak. A burst builds a queue of fifteen or twenty, and it takes a long time to drain, so most jobs arrive to find a crowd. The averages hide this: the queue is usually short or very long, and it is the long stretches that people remember.

Exponential service times are a convenient assumption. Felix Pollaczek and Aleksandr Khinchine found the mean response time for any distribution of service times. It depends on the variance, through the squared coefficient of variation, C squared. At eighty percent load, with mean service time one: if every job takes exactly one, the mean response is three. With exponential times, five. With a mix of many short jobs and a few long ones, twenty-three. Same load, same mean, and the variable server is nearly eight times slower than the steady one. The few long jobs block everyone behind them: the convoy effect from chapter seven, now as a formula.

The order of service matters as much. Same load, same jobs, three disciplines. Processor sharing, round robin with a tiny quantum, has a remarkable property: its mean response time is the mean size over one minus rho, whatever the distribution of sizes. Variance does not hurt it. Shortest remaining processing time first is optimal, by chapter seven's exchange argument, as Schrage proved in 1968: two point three six against five, for exponential sizes. With heavy-tailed sizes, the kind measured for files, web pages and jobs in data centres, first come first served is thirteen times worse than SRPT. The usual worry is that big jobs starve. Mor Harchol-Balter and her colleagues showed that for web servers they barely suffer, and built a server that schedules its connections this way.

13Kernel designsIndustry2 min

How much of the operating system should run in kernel mode? There are four main answers. A monolithic kernel, like Unix and Linux, puts everything inside: the file systems, the drivers, the network stack, memory and scheduling. Calls between them are ordinary function calls, which is fast, but a bug in any driver can bring down the machine. A microkernel keeps only the minimum inside, messages between processes, memory and scheduling, and runs file systems and drivers as ordinary processes. A crashed driver can be restarted, but every request now costs messages and switches. An exokernel goes further: the kernel only divides the hardware safely, and each application links its own operating system as a library. And a unikernel links one application with just the operating-system code it needs into a single image, run directly on a hypervisor, the subject of Part 32.

The choice was argued in public. In January 1992 Andrew Tanenbaum, author of the teaching system MINIX, posted that Linux was obsolete: a monolithic kernel, he wrote, was a giant step back into the nineteen-seventies. Linus Torvalds replied that the microkernel might be cleaner in theory, but Linux worked, and was fast, now. The argument was about the cost of messages. Mach's were slow, but Jochen Liedtke showed in the L4 kernels that a message between processes could be an order of magnitude faster, with a kernel designed around it. Sizes tell the story. PebbleOS is two hundred and eighty-four instructions. seL4, a microkernel in the L4 family, is about eight thousand seven hundred lines of C, and in 2009 it became the first general-purpose kernel with a machine-checked proof that it does what its specification says. Linux has more than thirty million lines, most of them drivers. In practice the winners mix: macOS is the Mach microkernel fused with BSD Unix, cars run the QNX microkernel, and Linux loads its drivers as modules.

14PebbleOS runs the JobDegree4 min

Now PebbleOS runs the Job, and the Job becomes two processes, joined by a pipe, as a Unix user would write it. The first process, tok, reads the text from the tape and writes one lower-case word per line. It is eighteen lines of our own language. The second, job, is Part 17's hash-table program, unchanged. It reads words from the pipe as if they were the novels, and prints the same twenty lines. Both are compiled by Part 13's compiler with one change: get-c and put-c become calls into the small library, which talks to the kernel four kibibytes at a time. The kernel moves the bytes, blocks whichever end has to wait, and preempts each process after twenty thousand instructions.

Here is a short passage of seven thousand bytes going through. The top chart shows who has the processor: tok in blue, job in yellow, the kernel in orange between them. Below, the number of bytes waiting in the pipe. Tok writes in four-kibibyte bursts, and the pipe fills; job reads, and it drains. Fifteen context switches, thirty-eight timer interrupts, a dozen system calls, and once, the job had to wait for an empty pipe. Neither program knows the other exists, or that it is being interrupted. And the output is byte for byte the Job's twenty lines, on every one of the thirty-two test passages.

What does all this cost? We ran the pipeline on thirty-two passages and counted every instruction, in each process and in the kernel, then fitted the counts and projected them to all thirty novels. Per byte of text: thirty-four instructions in tok, fifty in job, and twenty-three in the kernel. A hundred and seven in all. The bare program of Part 17 needed thirty-nine. The kernel's share is almost all copying, one byte at a time: from the tape into tok, from tok into the pipe, from the pipe into job. Tok is extra work the single program never did, and job pays eleven more instructions a byte because every get-c is now a function call. Run alone under PebbleOS, the job needs one point four four times its bare instructions. The fitted counts match passages held out of the fit to within about two percent. Copying is the price here, and later parts remove it: Part 32 lets processes share pages, and Part 34 moves data without the processor touching each byte.

So the ledger gets row eleven. Two point six seven billion instructions, priced on Part 8's out-of-order core at the same rate as row eight, with the same memory stalls, and thirty-five cycles of pipeline drain for every trap and every return. Two point one seven seconds, against point eight one for the bare program: two point seven times slower. Like the garbage-collected row of Part 15, it goes backwards, and that is the honest result. An operating system does not make one program faster. It makes many programs safe from one another, lets them share the machine, and lets two programs that know nothing about each other work as one. Making that cheap is the work of the next three parts.

15Frontier: verified kernels and microsecond schedulingResearch3 min

The kernel is the one program everything else trusts, so it is where proofs pay most. In 2009 a team at NICTA in Sydney proved that seL4, a microkernel of eight thousand seven hundred lines of C, implements its formal specification exactly: it cannot crash, overflow a buffer or dereference a bad pointer. Later work carried the proof down to the machine code, and proved that seL4 keeps processes' data both intact and secret. CertiKOS, in 2016, verified a kernel that runs on several cores at once. Hyperkernel, in 2017, made verification push-button, with an SMT solver checking each system call automatically. The cost is the obstacle. seL4's proof is about two hundred thousand lines, some twenty person-years of work. Still, it has flown an autonomous helicopter, in a DARPA programme where professional attackers failed to break in. The open problem is to verify a kernel with the speed and the features of Linux, with proof effort that does not grow faster than the code.

The second frontier is speed. A data-centre service may answer requests in half a microsecond, and its users care about the slowest one in a thousand. We simulated sixteen cores serving a mix like a key-value store's: nearly all requests take half a microsecond, and one in two hundred is a scan of five hundred. With a queue per core, as network cards usually spread requests, a short request that lands behind a scan waits for it: four thousand microseconds at the ninety-ninth point nine percentile, at seventy percent load. One shared queue is much better, but when all sixteen cores happen to be busy with scans, the short requests still wait. Preempting every five microseconds, even losing one microsecond at every preemption, brings it down to ten. That is what the Shinjuku system did in 2019, with tricks from virtualisation hardware to interrupt a core that fast. Linux's timer, by comparison, ticks every one to four milliseconds.

The third frontier changes what a kernel is. eBPF lets an ordinary user load small programs into the running Linux kernel. Count system calls, filter network packets, enforce a security policy. Before running anything, the kernel's verifier checks that every path through the program ends, and that every memory access stays in bounds: the halting problem of Part 25, avoided by allowing only programs simple enough to check. Then a just-in-time compiler turns it into machine code, and the kernel runs it whenever its event occurs. It now traces production systems and routes packets for large websites. But the verifier and the compilers are themselves complicated code, and their bugs have become ways to take over the kernel. So researchers are verifying the verifier: with abstract interpretation in PREVAIL, with proofs of the just-in-time compilers in Jitterbug, and by machine-checking the verifier's arithmetic on ranges in Agni.

Recap, problems, and where this comes backAll tracks3 min

What we built in this part. Time-sharing, from CTSS to Linux. A mode bit, traps and a timer for Pebble, and a kernel that uses them. Processes, context switches, and fork, exec and a shell, measured on this machine. Schedulers from first come first served to MLFQ, lottery, stride and Linux's own, with the proof that shortest first is optimal. Rate monotonic and earliest deadline first, and a bug on Mars. And queueing theory: Little's law, the hockey stick, and why variance and order matter.

Where this comes back. Part 32 gives every process its own addresses, which makes fork cheap and lets one machine pretend to be several. Part 33 deals with the races that preemption creates. Part 34 adds a disk, its interrupts and a file system to PebbleOS. Part 40 applies Little's law to work in progress, and Part 43 to queues between services. And Parts 45 and 50 plan capacity with queueing theory, and find where time goes with eBPF.

In practice. Before optimising, count the system calls with strace, perf or bpftrace. Batch them, with big buffers or Linux's io-uring, and let the vDSO answer the clock. Prefer posix-spawn to fork in large programs, and pin latency-critical threads to cores. Remember that nice values and control-group weights are just shares in the fair scheduler. And plan servers to run at fifty to seventy percent, watching the ninety-ninth percentile, not the mean.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: give PebbleOS a sleep call and a stride scheduler. The last, marked with a star, is a research problem: how short the quantum should be when preemption costs time, which the microsecond schedulers of the frontier chapter set by trial.

Next time, Part 32: Virtual Memory. Every process believes it owns a huge, private, contiguous memory, and none of them does. Page tables, the translation cache that makes them fast, and page faults; which page to throw out when memory is full, and the surprise that more memory can mean more faults; and the virtual machines and containers built on top. PebbleOS gains an MMU. Part 32, Virtual Memory.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 32 gives every process its own addresses, which makes fork cheap, and Part 33 deals with the races that preemption creates. Part 34 adds a disk to PebbleOS. Little's law returns for work in progress in Part 40 and for queues between services in Part 43, and Parts 45 and 50 plan capacity with queueing theory. The verified kernels of the Frontier chapter return in Part 54.

Key results

The part's results in one place, for revision.

Interactive response time\(\displaystyle R=\frac{N}{X}-Z,\qquad\allowbreak N^*=\frac{S+Z}{S}\)
Liu-Layland bound\(\displaystyle \sum_{i=1}^{n}\frac{C_i}{T_i}\le n\bigl(2^{1/n}-1\bigr)\ \to\ \ln 2\)
Little's law\(\displaystyle L=\lambda W\)
M/M/1\(\displaystyle E[T]=\frac{1}{\mu-\lambda},\qquad\allowbreak P(T>x)=e^{-(\mu-\lambda)x}\)
Pollaczek-Khinchine\(\displaystyle E[T]=E[S]+\frac{\lambda\,E[S^2]}{2(1-\rho)},\qquad\allowbreak \rho=\lambda E[S]\)
Work stealing\(\displaystyle T_P\approx \frac{T_1}{P}+T_\infty\)

Try it

Lab 31 · The convoy, and why a busy server is slow

Schedule one long job and two short ones under FCFS, SJF and round robin; check by brute force that shortest-job-first has the least mean turnaround of every order; then simulate a single-server queue at load 0.8 with three job-size laws and compare each mean response time with Pollaczek-Khinchine's formula.

Figure produced by Lab 31: The convoy, and why a busy server is slow
Produced by the lab below, seed 0, in 0.9 s.
python -m videos.cs.labs 31 needs numpy, scipy, matplotlib · download lab31.py · source on GitHub
convoy, mean turnaround               FCFS 110   SJF 50   RR(5) 58.3   (the film: 110 and 50)
convoy, mean response                 FCFS 70   SJF 10   RR(5) 5.0
six random jobs, 720 orders           best 65.67   worst 118.67   SJF 65.67
M/G/1 at load 0.8, deterministic      simulated 2.97   formula 3
M/G/1 at load 0.8, exponential        simulated 4.97   formula 5
M/G/1 at load 0.8, hyperexponential   simulated 22.34   formula 23
Little's law, the last run            L = 17.77   lambda W = 17.77
M/M/1 mean response at load 0.5, 0.9  2.03, 10.40   (1/(1 - rho): 2, 10)

At the same load of 0.8 the mean response is 3, 5 or 23 service times: Pollaczek-Khinchine says the wait grows with the second moment of the job size, and with 1/(1 - rho) as the load rises.
The code (97 lines; it asserts its own result)
"""Lab 31: run the convoy through four schedulers, then check a queue against Pollaczek-Khinchine."""

from videos.coursekit import labs  # noqa: I001  (first, so the library imports without manim)

import itertools

import numpy as np

from explainer.cs.os import queueing as Q
from explainer.cs.os import sched as S

TITLE = "The convoy, and why a busy server is slow"
GOAL = ("Schedule one long job and two short ones under FCFS, SJF and round robin; check by brute force that "
        "shortest-job-first has the least mean turnaround of every order; then simulate a single-server queue at "
        "load 0.8 with three job-size laws and compare each mean response time with Pollaczek-Khinchine's formula.")
TASKS = [
    "Let B and C arrive at tick 10 instead of 0 and compare 'sjf' with 'srtf'. Which one still reaches 50?",
    "Change discipline='fcfs' to 'srpt' for the hyperexponential sizes. How far below 23 does the mean fall?",
    "Raise the load in the right panel to 0.95 and 0.98. How many jobs does the simulation need before it settles?",
]
LOADS = (0.2, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9)


def mean_turnaround(order):
    """All jobs arrive at 0 and run to completion in this order."""
    return float(np.mean(np.cumsum(order)))


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. the convoy (Chapter 7): one job of 100 ticks ahead of two of 10
    convoy = [S.Job("A", 0, [100]), S.Job("B", 0, [10]), S.Job("C", 0, [10])]
    runs = {p: S.simulate(convoy, p, quantum=5) for p in ("fcfs", "sjf", "rr")}
    turn = {p: r.metrics()["mean"]["turnaround"] for p, r in runs.items()}
    resp = {p: r.metrics()["mean"]["response"] for p, r in runs.items()}
    lab.row("convoy, mean turnaround", f"FCFS {turn['fcfs']:.0f}   SJF {turn['sjf']:.0f}   RR(5) {turn['rr']:.1f}"
                                       "   (the film: 110 and 50)")
    lab.row("convoy, mean response", f"FCFS {resp['fcfs']:.0f}   SJF {resp['sjf']:.0f}   RR(5) {resp['rr']:.1f}")
    assert turn["fcfs"] == 110 and turn["sjf"] == 50
    assert resp["rr"] < resp["sjf"] < resp["fcfs"], "round robin answers first"

    # 2. the exchange argument, by brute force: no order of six random jobs beats shortest first
    bursts = [int(b) for b in rng.integers(1, 60, 6)]
    best = min(mean_turnaround(p) for p in itertools.permutations(bursts))
    worst = max(mean_turnaround(p) for p in itertools.permutations(bursts))
    sjf = S.simulate([S.Job(f"j{i}", 0, [b]) for i, b in enumerate(bursts)], "sjf").metrics()["mean"]["turnaround"]
    lab.row("six random jobs, 720 orders", f"best {best:.2f}   worst {worst:.2f}   SJF {sjf:.2f}")
    assert abs(sjf - best) < 1e-9, "SJF is the best of all 720 orders"

    # 3. Pollaczek-Khinchine at load 0.8 (Chapter 12): the mean size is 1 in all three, only E[S^2] differs
    pk = []
    for name, size, es2 in (("deterministic", Q.det(1.0), 1.0), ("exponential", Q.expo(1.0), 2.0),
                            ("hyperexponential", Q.hyper(1.0, 10.0), 11.0)):
        r = Q.mg1(0.8, size, n=400_000, seed=seed + 3)
        theory = Q.pk(0.8, 1.0, es2)
        pk.append((name, r["mean"], theory))
        lab.row(f"M/G/1 at load 0.8, {name}", f"simulated {r['mean']:.2f}   formula {theory:.0f}")
        assert abs(r["mean"] / theory - 1) < 0.12, name
    lab.row("Little's law, the last run", f"L = {r['L']:.2f}   lambda W = {r['lam_hat'] * r['W_all']:.2f}")
    assert pk[0][1] < pk[1][1] < pk[2][1], "more variable sizes wait longer at the same load"

    # 4. the hockey stick: M/M/1 against 1/(mu - lambda)
    sim = [Q.mg1(rho, Q.expo(1.0), n=60_000, seed=seed + 10 + i)["mean"] for i, rho in enumerate(LOADS)]
    for rho, m in zip(LOADS, sim):
        if rho <= 0.8:
            assert abs(m * (1 - rho) - 1) < 0.10, rho
    lab.row("M/M/1 mean response at load 0.5, 0.9", f"{sim[2]:.2f}, {sim[-1]:.2f}   (1/(1 - rho): 2, 10)")
    lab.note = ("At the same load of 0.8 the mean response is 3, 5 or 23 service times: Pollaczek-Khinchine says "
                "the wait grows with the second moment of the job size, and with 1/(1 - rho) as the load rises.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    colors = {"A": labs.RED, "B": labs.BLUE, "C": labs.GREEN}
    for row, p in enumerate(("fcfs", "sjf", "rr")):
        for a, b, name in runs[p].segments:
            if name in colors:
                ax[0].barh(row, b - a, left=a, color=colors[name], height=0.6, edgecolor=labs.BG, linewidth=0.4)
    ax[0].set_yticks(range(3), [f"FCFS\nmean {turn['fcfs']:.0f}", f"SJF\nmean {turn['sjf']:.0f}",
                                f"RR, q = 5\nmean {turn['rr']:.0f}"])
    ax[0].set_ylim(3.15, -0.5)
    for name, c in colors.items():
        ax[0].plot([], [], color=c, lw=6, label=f"job {name}")
    ax[0].legend(loc="lower center", ncols=3)
    ax[0].set(title="The convoy: A needs 100 ticks, B and C 10 each", xlabel="tick")
    grid = np.linspace(0.05, 0.95, 200)
    ax[1].plot(grid, 1 / (1 - grid), color=labs.GOLD, label="M/M/1: 1/(1 − ρ)")
    ax[1].plot(LOADS, sim, "o", color=labs.BLUE, label="simulated, exponential sizes")
    for (name, m, theory), c in zip(pk, (labs.GREEN, labs.BLUE, labs.RED)):
        ax[1].plot([0.8], [theory], "_", color=c, ms=16, mew=2)
        ax[1].plot([0.8], [m], "s", color=c, ms=5, label=f"{name}: {m:.1f} (formula {theory:.0f})")
    ax[1].set(title="Mean response time against load (mean job size 1)", xlabel="load ρ", ylabel="service times",
              yscale="log")
    ax[1].set_ylim(0.8, 600)
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Let B and C arrive at tick 10 instead of 0 and compare 'sjf' with 'srtf'. Which one still reaches 50?
  2. Change discipline='fcfs' to 'srpt' for the hyperexponential sizes. How far below 23 does the mean fall?
  3. Raise the load in the right panel to 0.95 and 0.98. How many jobs does the simulation need before it settles?

Problems, with solutions

Try each problem before opening its solution.

  1. SRPT is optimal. Prove by an exchange argument that SRPT minimises the mean response time for jobs arriving over time, on one server.

    Solution

    Take any schedule, and the first moment t at which it runs some job j while another present job k has less remaining work, r_k < r_j. Consider the slots, from t on, in which the schedule runs j or k. Reassign them: k's remaining work first, then j's.

    • The last of the two still finishes in the last of those slots, so the later completion time is unchanged.
    • The earlier completion now comes after r_k units of those slots, which is no later than before.
    • Every other job runs in exactly the same slots.

    So the sum of completion times does not increase, and the schedule now agrees with SRPT at time t. Repeating at each disagreement (there are finitely many in any bounded horizon) transforms the schedule into SRPT's without increasing the total. Since the arrival times are fixed, minimising the total completion time minimises the mean response time (Schrage, 1968).

  2. Liu and Layland for two tasks. Derive the bound 2(√2 − 1) for two tasks.

    Solution

    Let T₁ < T₂ (T₁ has priority) and r = T₂/T₁.

    • If r > 2, shrinking T₂ to a value between T₁ and 2T₁ only makes the set harder for the same utilisation, so assume 1 < r ≤ 2.
    • The worst case releases both together. Task 1 runs twice before T₂, and task 2 fits exactly when C₂ = T₂ − 2C₁ (if C₁ ≤ T₂ − T₁). The utilisation is least when C₁ just fills the gap, C₁ = T₂ − T₁.
    • Then C₂ = 2T₁ − T₂, and U = (T₂ − T₁)/T₁ + (2T₁ − T₂)/T₂ = r − 1 + 2/r − 1 = r + 2/r − 2.
    • This is minimised at r = √2, where U = 2√2 − 2 = 2(√2 − 1) ≈ 0.828.

    Any set below this utilisation is schedulable, and this set (made the slightest bit heavier) is not.

  3. M/M/1's response time. Show that the response time is exponential with rate μ − λ, and find its 99th percentile.

    Solution
    • By PASTA (Poisson arrivals see time averages), an arrival finds n jobs with probability (1 − ρ)ρⁿ.
    • By memorylessness, the job in service still needs an exponential(μ) time. So the arrival's response time is a sum of K = n + 1 independent exponential(μ) times, where P(K = k) = (1 − ρ)ρ^{k−1} is geometric.
    • A geometric sum of exponentials is exponential: its transform is ∑ₖ (1 − ρ)ρ^{k−1} (μ/(μ + s))ᵏ = μ(1 − ρ)/(μ(1 − ρ) + s), the transform of an exponential with rate μ(1 − ρ) = μ − λ.
    • So P(T > x) = e^{−(μ−λ)x}, and the 99th percentile is ln 100/(μ − λ) ≈ 4.6 W.

    At ρ = 0.9 and μ = 1 that is 46 service times; our simulation measured 49, since the high-load tail converges slowly.

  4. Gaming the old MLFQ. Show that a job that yields just before its quantum ends keeps the top queue under the old rule, and bound its share.

    Solution

    Under the old rule 4, a job that gives up the processor before its allotment is used keeps its priority, and its allotment is reset. A job that runs q − 1 ticks and then does one tick of I/O never uses a full allotment, so it never moves down. Rule 1 lets it preempt every lower job whenever it is ready. Against one hog at a lower level, the hog runs only during the gamer's I/O ticks, so the gamer takes at least (q − 1)/q of the processor in the long run: 90% for q = 10 (we measured 89%, the difference being the hog's first allotment at the top). With k gamers sharing the top level by round robin, together they take all the processor time that their I/O ticks allow, and the hog can be starved. Rule 4 as fixed, counting time at a level whatever the pattern, demotes the gamer after its allotment, and the boost (rule 5) bounds starvation.

  5. Build: sleep and stride in PebbleOS. Add sleep(n) and a stride scheduler to PebbleOS, and show two processes sharing 3 to 1.

    Solution
    • Add three PCB fields: wake, pass and stride = L/tickets, with tickets set in the boot table.
    • sys_sleep: read the instruction counter (IO_CYCLES), set wake = now + n, mark the process BLOCKED, and schedule.
    • In tick and schedule: first make every BLOCKED process whose wake has passed READY (a process blocked on the pipe has wake = 0 and is woken as before).
    • Replace the round-robin scan with a scan for the READY process of least pass, and add its stride when it is dispatched.
    • Test: two processes that loop forever, incrementing a counter in memory, with tickets 300 and 100, preempted by the timer. After 10⁶ instructions, the dispatch counts in their PCBs (and the counters) are within one quantum of 3:1.

    sleep lets a process wait without spinning. With the stride, PebbleOS gives proportional shares exactly, as the simulation in chapter 9 does.

  6. ★ Research: the quantum for tail latency. For k servers, bimodal sizes and preemption overhead δ, find the quantum that minimises the short requests' p99.9, and how it scales with δ and the load.

    Where to start.

    • Run explainer/cs/os/queueing.multi(..., policy="ps", quantum=q, overhead=δ) over a grid of q, δ (0.1–2 µs), load (0.3–0.85), k (4–64) and the long fraction. Check first that q → ∞ gives c-FCFS and δ = 0 favours q → 0.
    • The shorts' tail has two causes: waiting for a free core when all k hold long requests, which grows as q grows; and the capacity lost to overhead, a fraction δ/(q + δ) of the long work, which grows as q shrinks and pushes the effective load towards 1.
    • A first model balances the two. The probability that all k cores hold scans falls roughly geometrically in k; the overhead raises the load to ρ(1 + f·δ/q), where f is the long requests' share of the work. Does the optimum scale like √δ, as such balances usually do, or does the cliff near effective load 1 dominate?
    • Compare with the measured systems: Shinjuku (Kaffes et al., NSDI 2019) used 5–15 µs; Concord (Iyer et al., SOSP 2023) cut the overhead with cooperative preemption.
    • Analytical footholds: Kleinrock's time-sharing models (1967), and the heavy-traffic results for many-server queues (Halfin and Whitt, 1981).

    Nobody has a closed form for the multi-server case with overhead. A good approximation, checked against simulation, would be useful to every system that sets a quantum.

Notes and sources

Glossary

内核 kernel · 分时 time-sharing · 批处理 batch processing · 用户态 user mode · 内核态 kernel mode · 模式位 mode bit · 特权指令 privileged instruction · 控制寄存器 control register · 陷阱 trap · 中断 interrupt · 系统调用 system call · vDSO · 定时器 timer · 进程 process · 进程控制块 process control block · 就绪 ready · 阻塞 blocked · 上下文切换 context switch · 管道 pipe · 文件描述符 file descriptor · 外壳 shell · 调度器 scheduler · 周转时间 turnaround time · 响应时间 response time · 护航效应 convoy effect · 先来先服务 first come, first served · 短作业优先 shortest job first · 最短剩余时间优先 shortest remaining time first · 轮转 round robin · 时间片 quantum · 多级反馈队列 multi-level feedback queue · 彩票调度 lottery scheduling · 步幅调度 stride scheduling · 完全公平调度器 completely fair scheduler · 虚拟运行时间 virtual runtime · 亲和性 affinity · 负载均衡 load balancing · 工作窃取 work stealing · 速率单调 rate monotonic · 最早截止期优先 earliest deadline first · 优先级反转 priority inversion · 优先级继承 priority inheritance · 利特尔法则 Little's law · 排队论 queueing theory · 利用率 utilisation · 处理器共享 processor sharing · 尾延迟 tail latency · 宏内核 monolithic kernel · 微内核 microkernel · 外核 exokernel · 单一内核 unikernel · 形式化验证 formal verification

Sources

Canon. Books:

  • Arpaci-Dusseau & Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP, v1.10, 2023), virtualisation of the CPU;
  • Tanenbaum & Bos, Modern Operating Systems (5th ed., 2023);
  • Anderson & Dahlin, Operating Systems: Principles and Practice (2nd ed., 2014); Silberschatz, Galvin & Gagne, Operating System Concepts (10th ed., 2018);
  • Cox, Kaashoek & Morris, xv6: a simple, Unix-like teaching operating system (2020);
  • Harchol-Balter, Performance Modeling and Design of Computer Systems (2013); Kleinrock, Queueing Systems (vols. 1–2, 1975–76).

Papers:

  • History: Corbató, Merwin-Daggett & Daley, "An Experimental Time-Sharing System" (1962); Corbató & Vyssotsky, "Introduction and Overview of the Multics System" (1965); Ritchie & Thompson, "The UNIX Time-Sharing System" (1974).
  • Processes and switching: Baumann et al., "A fork() in the road" (HotOS 2019); Li, Ding & Shen, "Quantifying the cost of context switch" (2007).
  • Scheduling:
    • Schrage (1968);
    • Waldspurger & Weihl, "Lottery Scheduling" (OSDI 1994), and "Stride Scheduling" (MIT TM-528, 1995);
    • Stoica & Abdel-Wahab, EEVDF (1995);
    • Blumofe & Leiserson, "Scheduling Multithreaded Computations by Work Stealing" (JACM 1999).
  • Real time:
    • Liu & Layland (JACM 1973); Joseph & Pandya (1986); Bini & Buttazzo, UUniFast (2005);
    • Sha, Rajkumar & Lehoczky, "Priority Inheritance Protocols" (1990);
    • Reeves, "What really happened on Mars?" (1997).
  • Queueing: Little (1961); Pollaczek (1930); Khinchine (1932); Harchol-Balter, Schroeder, Bansal & Agrawal, "Size-based scheduling to improve web performance" (TOCS 2003); Scully, Harchol-Balter & Scheller-Wolf, SOAP (2018).
  • Kernel designs:
    • Accetta et al., Mach (1986); Liedtke, "On µ-Kernel Construction" (SOSP 1995);
    • Engler, Kaashoek & O'Toole, exokernel (SOSP 1995); Madhavapeddy et al., unikernels (ASPLOS 2013);
    • the Tanenbaum–Torvalds exchange, comp.os.minix (January 1992).
  • Frontier:
    • Klein et al., "seL4: Formal Verification of an OS Kernel" (SOSP 2009); Gu et al., CertiKOS (OSDI 2016); Nelson et al., Hyperkernel (SOSP 2017);
    • Kaffes et al., Shinjuku (NSDI 2019); Ousterhout et al., Shenango (NSDI 2019); Fried et al., Caladan (OSDI 2020);
    • Gershuni et al., PREVAIL (PLDI 2019); Nelson et al., Jitterbug (OSDI 2020); Vishwanathan et al., Agni (CAV 2023).
About this partfrom its README

Part 31 of a sixty-one-part course in computer science (see the series plan and the syllabus), and the first part of Act VI, One Machine, Many Programs. Early computers ran one job at a time, and an expensive machine sat idle while a person thought. Time-sharing gave every user the illusion of a whole machine. That needed protection, traps, processes and a scheduler. Queueing theory then explains why a busy server is slow. Pebble gains a kernel mode, and PebbleOS, a kernel of 284 instructions, boots on it and runs the Job as two processes joined by a pipe: ledger row 11.

The instruments are in explainer/cs/os/ (tested in tests/test_cs31_os.py):

  • machine.py, Pebble with a kernel mode:
    • a mode bit and the privileged extension of explainer/cs/pebble/isa.py: ecall, eret, csrr, csrw;
    • nine control registers (status, epc, cause, tval, tvec, scratch, timer, lo, hi);
    • traps and a countdown timer;
    • bounds checks on every user fetch, load and store;
    • per-mode instruction counts and an event log;
  • kernel.py, PebbleOS:
    • boot; the trap entry that saves fifteen registers into a 128-byte PCB;
    • five system calls (exit, read, write, getpid, yield), with checked user pointers;
    • a 4 KiB pipe with blocking and restartable calls; round robin on the timer;
    • faults that kill only the offender;
    • attribute and timeline read per-process instruction counts out of the event log;
  • ulib.py: the user library every process links: _start, and getc/putc buffered 4 KiB at a time over read/write. Part 13's compiler gains target="os", which turns getc/putc into calls into it;
  • sched.py: a tick-by-tick simulator of FCFS, SJF, SRTF, round robin, MLFQ (with the old gameable rule 4 and the boost), lottery, stride and CFS (Linux's nice-to-weight table); a Cilk-style work-stealing simulator;
  • queueing.py: M/G/1 under FCFS, processor sharing and SRPT; M/M/1 sample paths; Pollaczek–Khinchine; k servers under d-FCFS, c-FCFS and preemptive quanta with overhead;
  • rt.py: the Liu–Layland bound, response-time analysis, UUniFast, RMS and EDF timelines, and the Mars Pathfinder inversion with and without priority inheritance.

The real-time model uses independent, preemptible periodic tasks, deadlines equal to periods, one processor, and zero blocking/scheduler overhead. Deadline checks include the final simulation tick. In the random task-set chart, the horizontal coordinate is target utilization: rounding execution costs to integer ticks changes actual load. EDF's acceptance fraction uses that realized load rather than assuming every generated set is feasible. Fixed priorities protect high-priority work from overload confined to lower-priority tasks; they do not protect an infeasible high-priority task set from itself.

Queueing examples distinguish stationary formulas from finite simulations. The reported L is derived from the total sojourn-time area over a window including the drain, so its agreement with Little's law is an accounting illustration rather than an independent validation of the event simulator.

Measured on this machine (videos/cs/cs31/compute.py compiles and runs small C programs):

  • a function call against getpid and a vDSO clock_gettime;
  • read() with buffers of 1 byte to 1 MiB, and strace -c of wc;
  • a pipe ping-pong between two processes on one CPU and on two;
  • fork, fork+exec, posix_spawn, and fork with up to 1 GiB resident;
  • a 25-line shell, run.
Chapter notes
  • Hook.
    • One user thinking 10 s and computing 0.5 s leaves the processor idle 95% of the time.
    • PebbleOS boots, and two processes print interleaved letters: 15 switches, 14 timer interrupts, 52 system calls.
  • 1. From batch to time-sharing.
    • GM-NAA I/O (1956), CTSS (1961), Multics (1965), Unix (1969–74), Linux (1991).
    • A closed queue of N users. The response time is flat until N* = (S + Z)/S = 21, then grows by S per user. The law R = N/X − Z checks.
  • 2. Protection: the mode bit.
    • Three threats (instructions, memory, time), and Pebble's new instructions and control registers.
    • Four processes, three hostile: the halt and the store into the kernel are killed (exits −2 and −7). The hog is preempted 121 times, and the good process finishes.
  • 3. Traps and the system call.
    • The five-step trap; one getpid traced: 78 kernel instructions (save 26, dispatch 23, handle 3, restore 26).
    • On this machine: a function call 1.5 ns, getpid 112 ns, the vDSO 29 ns.
    • read() costs 218 ns a byte one byte at a time, and 0.09 at 4 KiB.
  • 4. The process.
    • The job's 1 MiB region: library, buffers, 1.5 KB of code, a 512 KiB table, the stack. The PCB's fields.
    • The state diagram, counted in PebbleOS.
  • 5. The context switch.
    • 18 words saved; a switch through yield costs 118 kernel instructions.
    • Pipe ping-pong: 2.9 µs a round trip on one CPU, 25 µs across two.
  • 6. fork, exec and wait.
    • Why Unix split them; a 25-line shell with pipes, run.
    • fork takes 150 µs, fork+exec 1.3 ms, and fork with 1 GiB resident 33 ms. "A fork() in the road" (2019). PebbleOS has no fork until Part 32.
  • 7. Scheduling: FCFS, SJF, SRTF.
    • The metrics. The convoy: a mean turnaround of 110 under FCFS, 50 under SJF.
    • The exchange argument; SRTF with late arrivals (103 against 50).
    • 400 random jobs at load 0.8.
  • 8. Round robin and MLFQ.
    • RR: response 5, turnaround 85, on three jobs of 30. The quantum sweep with a one-tick switch (best near 12).
    • Corbató's MLFQ: the interactive job finishes at 341 against 641 under RR.
    • Gaming the old rule takes 89% of the machine, and accounting cuts it to 17%; starvation, and the boost.
  • 9. Proportional share.
    • Lottery against stride at 3:1, and lottery's unfairness against job length.
    • CFS: virtual runtime, the red–black tree, nice 0 against nice 5 (75.4%); EEVDF (Linux 6.6).
  • 10. Many processors.
    • Per-core queues, affinity and balancing.
    • Work stealing on a tree with T₁ = 83,647 and T∞ = 71: within 1% of T₁/P + T∞ up to 64 workers, with 487 steals.
  • 11. Real time.
    • (2, 5) and (4, 7) at U = 0.971: RMS misses at 7, and EDF meets every deadline.
    • Liu–Layland's n(2^{1/n} − 1) → ln 2; random task sets under the bound, the exact test and EDF; harmonic periods.
    • Mars Pathfinder's priority inversion, and priority inheritance.
  • 12. Queueing theory.
    • Little's law by areas, and measured (L = 3.9816 = λW).
    • M/M/1 derived: W = 1/(μ − λ). The hockey stick against a million-job simulation, and two sample paths.
    • Pollaczek–Khinchine at load 0.8: 3, 5 and 23. FCFS, PS and SRPT on exponential and heavy-tailed sizes.
  • 13. Kernel designs.
    • Monolithic, microkernel, exokernel, unikernel; Tanenbaum–Torvalds (1992); L4.
    • Sizes: PebbleOS, seL4, Linux.
  • 14. PebbleOS runs the Job.
    • tok | job; a short run's timeline and the pipe's fill.
    • Instructions per byte: tok 34.0, job 49.9, kernel 23.0, against 38.7 bare. They are fitted on 24 passages and held out on 8: errors of 0.17%, 0.01% and 2.2%.
    • Ledger row 11: 2.67 billion instructions, 2.17 s against row 8's 0.81 s.
  • 15. Frontier: verified kernels and microsecond scheduling.
    • seL4, CertiKOS, Hyperkernel.
    • 16 simulated cores with a bimodal service time. At load 0.7 the shorts' p99.9 is about 4,000 µs under d-FCFS, 186 µs under c-FCFS, and 10 µs with 5 µs quanta. The quantum sweep.
    • eBPF and verifying its verifier. Open problems. Outro.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. History: batch monitors; CTSS (1961) and time-sharing; Multics (1965); Unix (Thompson & Ritchie 1969–74); Linux (1991).
  2. Protection: user and kernel mode, privileged instructions. Pebble gains a mode bit, ecall, and a timer interrupt.
  3. Traps, exceptions and interrupts: the hardware sequence (save the PC, switch mode, vector); the system-call path drawn end to end.
  4. The process: address space, registers and state; the state diagram; the PCB; PebbleOS's process table.
  5. Context switches: what is saved, and the cost (measured on this machine by pipe ping-pong).
  6. fork, exec and wait: why Unix split them; a shell in a few lines; pipes and file descriptors.
  7. Scheduling metrics; FCFS and the convoy effect; SJF minimizes mean completion time (exchange argument); SRTF.
  8. Round robin and the quantum; MLFQ (Corbató 1962) and how to game it.
  9. Proportional share: lottery and stride (Waldspurger 1994–95); CFS's virtual runtime in a red–black tree (2007; callback to Part 17); EEVDF (Linux 6.6).
  10. Multiprocessor scheduling: affinity, load balancing, work stealing (callback to Part 10).
  11. Real time: rate-monotonic scheduling and Liu–Layland's U ≤ n(2^{1/n} − 1) → ln 2 (1973, sketched); EDF is optimal; priority inversion on Mars Pathfinder (1997) and priority inheritance.
  12. Queueing theory: Little's law L = λW (proved by areas); M/M/1's 1/(μ − λ) (derived) and its hockey stick; Pollaczek–Khinchine (variance matters); SRPT is optimal (Schrage 1968).
  13. Kernel designs: monolithic, microkernel (Mach, L4; the Tanenbaum–Torvalds debate of 1992), exokernel, unikernel; seL4 (Part 54).
  14. PebbleOS boots on the emulator and runs two processes doing the Job concurrently. Ledger row 11. Outro.

Computed: PebbleOS traces (traps, timer, context switches); simulations of FCFS, SJF, RR, MLFQ, stride and CFS-lite; M/M/1 against the formula; RMS and EDF schedulability; context-switch cost on this machine. Visuals: Gantt charts; the system call as a camera dive into the kernel and back; a queue's random walk under the hockey-stick curve; the process state machine. In practice: Linux internals (CFS and EEVDF, system calls, strace), real-time and embedded RTOSes, eBPF, capacity planning with queueing. Reading: Arpaci-Dusseau & Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP), virtualization of the CPU; Tanenbaum & Bos, Modern Operating Systems; Silberschatz, Galvin & Gagne; Anderson & Dahlin, Operating Systems: Principles and Practice; Cox, Kaashoek & Morris, xv6; Ritchie & Thompson 1974; Corbató et al. 1962; Liu & Layland 1973; Harchol-Balter, Performance Modeling and Design of Computer Systems; Kleinrock, Queueing Systems.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. SRPT 最优。 用交换论证证明:在单服务器上、作业随时间到达时,SRPT 使平均响应时间最小。

    解答

    取任意调度,找最早的时刻 t:此时它在运行作业 j,而另一个在场作业 k 的剩余工作量更少,r_k < r_j。考虑 t 之后 该调度用来运行 j 或 k 的所有时间片,重新分配:先做完 k 的剩余工作,再做 j 的。两者中较晚完成的那个仍在这些时间片的最后一片 完成,较晚的完成时间不变;较早的完成时间变为这些时间片中的第 r_k 个单位,不晚于原来;其他作业的时间片完全不变。所以完成时间 之和不增,且调度在时刻 t 与 SRPT 一致。对每处不一致重复(有限时间内只有有限处),就把调度变成 SRPT 而总和不增。到达时间固定, 完成时间总和最小即平均响应时间最小(Schrage,1968)。

  2. 两个任务的 Liu–Layland 界。 推导两任务的界 2(√2 − 1)。

    解答

    设 T₁ < T₂(T₁ 优先),r = T₂/T₁。若 r > 2,把 T₂ 缩到 T₁ 与 2T₁ 之间,在相同利用率下只会更难,故设 1 < r ≤ 2。 最坏情况是两者同时释放;在 T₂ 之前任务 1 运行两次,当 C₂ = T₂ − 2C₁ 时任务 2 恰好放得下(若 C₁ ≤ T₂ − T₁)。C₁ 恰好填满 空隙 C₁ = T₂ − T₁ 时利用率最小,此时 C₂ = 2T₁ − T₂,U = r − 1 + 2/r − 1 = r + 2/r − 2,在 r = √2 处取最小值 2√2 − 2 ≈ 0.828。

  3. M/M/1 的响应时间。 证明响应时间服从速率为 μ − λ 的指数分布,并求其第 99 百分位数。

    解答

    由 PASTA(泊松到达看到时间平均),到达者看到 n 个作业的概率为 (1 − ρ)ρⁿ;由无记忆性,正在服务的作业还需指数(μ) 时间。于是响应时间是 K = n + 1 个独立指数(μ) 之和,K 服从几何分布 P(K = k) = (1 − ρ)ρ^{k−1}。几何个指数之和仍是指数分布: 其变换为 μ(1 − ρ)/(μ(1 − ρ) + s),速率 μ(1 − ρ) = μ − λ。所以 P(T > x) = e^{−(μ−λ)x},第 99 百分位数为 ln 100/(μ − λ) ≈ 4.6W。ρ = 0.9、μ = 1 时为 46 个服务时间;我们的模拟测得 49,高负载下尾部收敛较慢。

  4. 钻旧 MLFQ 的空子。 证明:在旧规则下,一个总在时间片用完前让出处理器的作业会一直留在最高队列,并给出它份额的界。

    解答

    旧的规则 4 下,作业若在用完配额前让出处理器,就保持优先级,配额重置。运行 q − 1 个刻度再做一个刻度 I/O 的作业永远 用不完配额,永不降级;由规则 1,它一就绪就能抢占所有低优先级作业。对一个低层的计算密集作业,后者只能在它做 I/O 的刻度运行, 所以它长期至少占 (q − 1)/q:q = 10 时为 90%(我们测得 89%,差别来自那个作业在最高层的第一段配额)。修正后的规则 4 不论运行 方式如何都累计在该层的时间,配额用完即降级;提升(规则 5)则限制了饥饿。

  5. 动手:给 PebbleOS 加 sleep 与步幅调度。 并演示两个进程按 3 比 1 分享。

    解答

    PCB 增加 wake、pass 和 stride = L/票数(票数写在启动表中)。sys_sleep 读取指令计数器(IO_CYCLES),令 wake = 当前 + n,标为阻塞,然后调度。tick 与 schedule 先把 wake 已过的阻塞进程设为就绪(等管道的进程 wake = 0, 照旧唤醒);把轮转扫描换成找 pass 最小的就绪进程,调度它时加上它的 stride。测试:两个无限循环、在内存中计数的进程, 票数 300 和 100,由定时器抢占;执行 10⁶ 条指令后,PCB 中的调度次数(以及计数)与 3:1 相差不超过一个时间片。

  6. ★ 研究:为尾延迟选时间片。 对 k 个服务器、双峰作业大小与抢占开销 δ,找出使短请求 p99.9 最小的时间片,以及它如何随 δ 与负载变化。

    从哪里开始。 在 q、δ(0.1–2 µs)、负载(0.3–0.85)、k(4–64)和长请求比例的网格上运行 explainer/cs/os/queueing.multi(..., policy="ps", quantum=q, overhead=δ);先检查 q → ∞ 给出 c-FCFS,δ = 0 时 q 越小越好。 短请求的尾部有两个成因:k 个核全被长请求占住时的等待(随 q 增大);以及开销损失的容量,占长请求工作量的 δ/(q + δ)(随 q 减小,把有效负载推向 1)。第一个模型平衡两者:全部核都是长请求的概率大致随 k 几何下降;开销把负载抬到 ρ(1 + f·δ/q),f 是长请求 占的工作量份额。最优值是否像这类平衡通常那样按 √δ 变化,还是有效负载接近 1 的悬崖占主导?与实测系统比较:Shinjuku(Kaffes 等, NSDI 2019)用 5–15 µs;Concord(Iyer 等,SOSP 2023)用协作式抢占降低开销。理论落脚点:Kleinrock 的分时模型(1967),以及多服务器 排队的重载结果(Halfin 与 Whitt,1981)。多服务器加开销的情形没有闭式解;一个经模拟验证的好近似,对每个要设定时间片的系统都 有用。

Build the film

python -m videos.cs.cs31.compute        # the part's numbers, into .cache/cs31
python tools/build.py cs31                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs31 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs31. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs31.compute           # every number in the part (about five minutes)
python tools/build.py cs31 -q l            # a 480p preview
python tools/build.py cs31                 # 1080p