Operating Systems · Lecture Notes

Chapter 14: Operating-System Design

Taken one at a time, processes, memory, file systems, and I/O each look like a problem solved by its own algorithms. A team designing an operating system from scratch faces questions of a different kind. Which abstractions should it offer? How many system calls should there be, and how general should each be? Should drivers run inside the kernel or outside it? At what moment should a name be bound to an object? Where should code be made fast, and where left simple? These questions have no definitive answers; what exists is a body of principles and trade-offs accumulated through experience. The notes first describe what makes design hard and the four basic goals of an operating system. They then turn to interface design, the options for system structure, and design principles such as the separation of mechanism and policy, orthogonality, naming, and binding time. Indirection, reentrancy, the space-time trade-off, caching, hints, and optimizing the common case are traced step by step on short C programs. The last sections cover the management of large software projects, how kernel code is tested and debugged, and current trends in operating systems. All traces and numbers were recomputed in Python and checked.

Learning outcomes

Challenges and goals
Explain what makes operating-system design hard and state the four basic goals of an operating system.
Interface design
Discuss the principles of simplicity, completeness, and efficiency, and the execution and data paradigms, using system-call examples.
System structure
Evaluate the structural options through the isolation–performance trade-off; discuss layer ordering, safe extensibility, and kernel threads as design decisions.
Design principles
Apply the separation of mechanism and policy, orthogonality, two-level naming, binding time, and static versus dynamic structures.
Techniques and performance
Use indirection, reentrancy, the space-time trade-off, caching, hints, and optimization of the common case on concrete examples.
Projects, testing, and trends
Interpret Brooks's law; choose kernel testing and debugging tools; assess the trends of virtualization, many cores, Rust, eBPF, and unikernels.

14.1Design challenges and goals

A team writing a compiler or a database knows fairly well what it is building. The compiler's input is fixed by a language definition and its output by an instruction set. The job of an operating system is not drawn so sharply. Which programs will run on it, on what hardware, and for how many years is not known in advance. Designing an operating system is therefore less a matter of choosing an algorithm than of balancing demands that conflict with one another.

14.1.1Why is designing an operating system hard?

Tanenbaum lists eight factors that make operating-system design harder than other software projects (Table 14.1). Some of them stem simply from size, others from the operating system's position: it sits between the hardware and all the applications and must survive changes in both.

Table 14.1: Tanenbaum's eight factors that make operating-system design difficult.
FactorDescription
1. Sheer sizeThe Linux kernel is about 40 million lines; no single person understands all of it.
2. ConcurrencyDevices, interrupts, and threads run at the same time; race conditions and deadlocks arise.
3. Hostile usersSome users want to break the system or steal data; every input is suspect.
4. Sharing despite isolationUsers must be kept apart, yet able to share the information they choose.
5. Long lifeAn operating system lives 20–30 years; future hardware and applications must be anticipated.
6. GeneralityHow the system will be used is unknown: anywhere from a phone to a supercomputer.
7. PortabilityIt must run on different processors and platforms: x86-64, ARM64, RISC-V.
8. Backward compatibilityOld programs must keep working; new ideas are limited by old constraints.

Size alone is a serious problem. Most of the forty million lines are driver code, but the rest is still far more than one person can keep in mind. In such a system it is hard to predict what a change will affect. Well-designed interfaces and a structure that limits dependencies are therefore as important as the code itself.

Concurrency is a difficulty peculiar to operating systems. An application programmer can often think in terms of a single thread. The kernel, by contrast, is concurrent from the start: it deals with interrupts, with several cores, and with system calls arriving at the same moment. A bug may show up only when a particular timing occurs, and reproducing it can take days.

Hostile users and sharing despite isolation are two demands that pull against each other. The system must protect every user from the others, yet users also want to share files and memory in order to work together. Every door opened for sharing is also an attack surface.

The last four factors concern time. A long life requires the system to adapt to hardware that does not yet exist. When UNIX was designed in the 1970s, there were neither multicore processors nor SSDs. Generality prevents the designer from optimizing for a single way of using the system. Portability forces hardware-dependent code to be confined. Backward compatibility makes every published interface permanent. The need for long maintenance and repair is a natural consequence of a long life and the obligation to stay compatible.

Common mistake

Reducing all the difficulties to the problem of “large software.” Size is present in every big project. What sets an operating system apart is that concurrency, hostile users, and backward compatibility come together in the same code. A bug in an application brings down that application; a bug in the kernel brings down everything running on top of it.

14.1.2The four basic goals

Faced with these difficulties, we must state clearly what an operating system is for. Tanenbaum names four basic goals. They can be pictured as layers: applications on top, hardware at the bottom, and the operating system in between (Figure 14.1).

BrowserCompilerDatabaseAbstractionsprocessthreadaddress spacefilesocketPrimitive operations (system calls)fork · execve · mmap · open · read · write · send · recv · futexHardware managementCPUmemorySSD/disknetwork cardGPU
Figure 14.1: The four goals of an operating system. Applications (browser, compiler, database) use abstractions; the primitive operations on the abstractions are system calls; isolation keeps each process in its own address space; at the bottom, the hardware is managed.
Definition 14.1

An abstraction is a concept that hides the complexity of the hardware and gives the programmer a more convenient model: process, thread, address space, file, socket. A primitive is a basic operation on an abstraction; in an operating system, the primitives are the system calls.

  1. Defining abstractions. A disk is really an array of numbered blocks. A file, on the other hand, is an object with a name, a size, and permissions, read byte by byte. The operating system closes the gap between the two. The hardest part of design is finding the right abstraction. One that is too detailed does not hide the hardware enough; one that is too coarse is too narrow for some applications.
  2. Providing primitives. An abstraction is useful only when operations can be performed on it. For files these operations are open, read, write, and close; for processes, fork and execve; for address spaces, mmap; for synchronization, futex.
  3. Providing isolation. Users and processes must not interfere with one another. Each process runs in its own address space; if one crashes, the others are unaffected. Even so, controlled ways of sharing, such as file permissions and shared memory, must remain open.
  4. Managing the hardware. Interrupts, timers, the MMU, and device controllers are the subject of this goal. Most low-level work is done in this layer, and all the goals above rest on it.

The four goals are not independent of one another. Isolation can be achieved only through hardware management, that is, through the MMU and privilege levels. Abstractions without primitives are mere names. The rest of these notes is largely an answer to the question: with what structure and what principles, and at what cost, are these goals realized?

Common mistake

Counting the compilation of programs among the goals of an operating system. Compilation is the job of a toolchain, that is, of the compiler. The operating system loads the compiled program into memory, creates a process for it, and runs it. The compiler is itself an ordinary application running on top of the operating system.

14.2Interface design

The face an operating system shows to the outside world is its system-call interface. Applications are written against this interface, and once it has been published it can hardly be changed in practice. How the interface is designed is therefore a longer-lived decision than how the inside of the kernel is written.

14.2.1Guiding principles

There is no precise recipe for a good interface, but three principles guide the designer: simplicity, completeness, and efficiency.

Definition 14.2

Simplicity: the interface should consist of a small number of well-thought-out concepts. Completeness: the interface should be able to do everything users need. Efficiency: every feature should be implementable efficiently, and the programmer should be able to sense the approximate cost of a call.

The saying most often cited for simplicity is Antoine de Saint-Exupéry's: perfection is reached not when there is nothing left to add, but when there is nothing left to take away. A small number of concepts is easy to learn, implement, and verify. Every new concept also brings its interactions with all the other concepts.

Completeness is the counterweight to simplicity. A remark attributed to Einstein sums it up: everything should be as simple as possible, but no simpler. If an interface is so spare that it cannot do a needed job, applications look for ways around it, and the result is more complicated. The ideal is to get a lot done with few mechanisms. The MINIX 3 kernel offers only a handful of primitives for interprocess communication: send, receive, sendrec, and notify. The file system, the drivers, and memory management are built on these few primitives.

The efficiency principle says two things. First, a feature that cannot be implemented efficiently probably is not worth adding. Second, the programmer should be able to sense the approximate cost of a call. lseek merely changes the file offset and is cheap; read may need a disk access and can be expensive. If a call that looks cheap is secretly expensive, the programmer makes wrong decisions.

A practical rule follows from these three principles: every system call should do one thing well. Adding a feature is easy; removing one is almost impossible. Because of backward compatibility, a wrong decision is carried for years.

applicationlibrary: printf, fopen, fgets, qsort, getaddrinfo … (many, convenient, changeable)kernel: open, read, write, close, mmap … (few, general; changing them breaks compatibility)
Figure 14.2: Convenience functions (printf, fopen, qsort, getaddrinfo) live in the library; they are numerous and may change. The calls in the kernel (open, read, write, mmap) are few and general; changing them breaks compatibility.
Example 14.1

Can we give an example from the UNIX interface for each principle?

  1. Simplicity. In UNIX, files, devices, and pipes are all used with the same four calls: open, read, write, close. The programmer learns a single model.
  2. Completeness. There are six different exec library functions, but all of them reduce to a single execve call. Because execve takes a path, an argument array, and an environment array, it meets every need.
  3. Efficiency. lseek only changes a number, whereas read may read from disk. The difference in cost between the two calls can be sensed from their names and definitions.

14.2.2Small is beautiful

The most concrete measure of the simplicity principle is the number of system calls. A few general calls are better than many special ones. Real systems differ greatly on this measure (Figure 14.3).

1101001000seL4 microkernel≈ 12UNIX V7 (1979)≈ 50Linux x86-64 (6.x)≈ 460Windows NT + win32k≈ 1700number of system calls (log scale, approximate)The fewer the calls, the smaller the attack surface and the verification burden
Figure 14.3: Approximate numbers of system calls, on a logarithmic scale: seL4 ≈ 12, UNIX V7 (1979) ≈ 50, Linux x86-64 (6.x) ≈ 460, Windows NT and win32k together ≈ 1700.

Because the scale is logarithmic, the differences between the bars can deceive the eye. Windows has about 140 times as many calls as seL4, and Linux has more than nine times as many as UNIX V7. As the number of calls grows, so does the attack surface: every call is a door through which malicious input can reach the kernel.

The seL4 microkernel is the extreme example of this principle. Its kernel is about 10 thousand lines and has been formally verified: it has been proved that the C code conforms to a mathematical specification. For a kernel of millions of lines, such a proof is not possible with today's methods.

In Linux, by contrast, the number of calls grows by a few every year. The recently added io_uring_*, landlock_*, and mseal calls are examples. Windows follows a different path: the documented interface is not the kernel calls but the Win32 API. The kernel calls may change from release to release, because applications do not use them directly. In this arrangement, the library layer in between preserves compatibility.

Common mistake

Taking a small interface to mean a “system with few features.” The fifty or so calls of UNIX V7 were enough to build a rich programming environment with pipes, redirection, and process creation. The point of smallness is not to cut features but to obtain them from the combination of a few general mechanisms.

14.2.3User-interface paradigms

The user interface is often not part of the kernel. Even so, the paradigm chosen affects the design of the whole system. Four paradigms live side by side today.

  • Command line (CLI, command-line interface). The shell, text commands, and pipes. It remains indispensable for automation and remote administration.
  • WIMP / GUI. Windows, icons, menus, and a pointer (windows, icons, menus, pointer). The meaning of the mouse buttons should be the same in every application.
  • Touch and mobile. Gestures such as swiping and pinching, full-screen applications, a notification center.
  • Voice, chat, and agents. Voice assistants and natural-language interfaces open a new entry point to operating-system services.

The effect of the paradigm on the kernel is clearest in the graphical interface. A GUI requires an event-driven execution model, a fast window system, and a consistent application framework. A click follows a path from the device to the application (Figure 14.4).

mouse / touchkernel: evdevwindow systemevent queueapplication: on_clickredrawlatency budget: touch to screen ≈ 16 ms (60 Hz); one long handler freezes the whole interface
Figure 14.4: The path of a click: the input device, the evdev driver in the kernel, the window system, the application's event queue, and the on_click handler; finally the screen is redrawn. On a 60 Hz display, the budget from touch to screen is about 16 ms.

The 16 ms budget comes from the calculation 1000 ms / 60 ≈ 16.7 ms. Within this time the event must pass from the kernel to the window system and then to the application, be processed, and a new frame must be drawn. A single long-running handler freezes the whole interface. The principle common to all the paradigms is consistency: the same action should give the same result everywhere.

14.2.4Execution paradigms

Who determines the flow of a program also determines what it will ask of the operating system. There are two basic paradigms.

Definition 14.3

In algorithmic code, the program determines its own flow and calls the operating system only to obtain services. In event-driven code, external events determine the flow: a key, a click, a network packet, a timer. The program waits in a loop for the next event and calls the matching handler.

The typical form of algorithmic code is similar to the one below. The program starts, does things in order, reads and writes when needed, and finally ends. Compilers, sorting programs, and batch jobs have this structure.

int main(void)
{
    int x, y;
    init();
    do_something();
    read(fd, &x, sizeof x);
    do_something_else();
    write(fd, &y, sizeof y);
    keep_going();
    exit(0);
}

Event-driven code, on the other hand, is built around a loop. get_message fetches the next event, and switch routes it to the relevant code according to its type. GUIs, network servers, and microkernel servers have this structure.

int main(void)
{
    msg_t msg;
    init();
    while (get_message(&msg)) {
        switch (msg.type) {
        case 1: ... ; break;
        case 2: ... ; break;
        case 3: ... ; break;
        }
    }
}

The choice of paradigm also shapes the system calls. The algorithmic model wants a blocking read: wait until data arrives, then continue from where the flow left off. The event-driven model wants a call of the “give me the next event” kind: get_message, epoll_wait, or io_uring_enter. An operating system must support both paradigms.

14.2.5Code trace: the event loop

How an event loop works can be followed on concrete code. The program below has three kinds of events: key (KEY), click (CLICK), and timer (TIMER). Each goes to its own handler.

int main(void) {
    msg_t m;
    init();
    while (get_message(&m)) {
        switch (m.type) {
        case KEY:   on_key(&m);   break;
        case CLICK: on_click(&m); break;
        case TIMER: on_timer(&m); break;
        }
    }
    return 0;
}

init() prepares the window and the resources. The while condition is the return value of the call get_message(&m). The call returns 1 if it delivers an event, and 0 on the QUIT event, which signals that the program should shut down. The switch calls the handler on_key, on_click, or on_timer according to the event type. When the handler finishes, the loop returns to the top. The trace takes eight steps (Table 14.2).

Table 14.2: Trace of the event loop. CLICK, KEY, and TIMER arrive in the queue in that order, and QUIT comes last.
StepQueueget_messageCode running
1emptynot called yetinit()
2CLICK, KEY, TIMERwaiting for an eventthe window system adds the events
3KEY, TIMERreturned CLICKon_click
4TIMERreturned KEYon_key
5emptyreturned TIMERon_timer
6emptyblockedthe process sleeps
7QUITwaiting for an eventthe process wakes up
8emptyreturned 0the loop ends, return 0
event queueKEYTIMER↑ head of queueget_messagereturned CLICKon_keyon_clickon_timerm.type = CLICK
event queue(empty)get_messageblockedon_keyon_clickon_timer
Figure 14.5: (a) get_message has returned the CLICK at the head of the queue, and the switch has routed it to on_click. (b) When the queue empties, get_message blocks; the process sleeps and uses no CPU.

Two points of the trace matter. The first is step six. When the queue is empty, get_message does not return immediately; it puts the process to sleep. The process uses no CPU meanwhile; when a new event arrives, the kernel wakes it up. The loop is not a “busy wait” but a structure built around a blocking call.

The second is the duration of the handlers. The loop is single-threaded; while one handler runs, the other events in the queue wait. on_timer does a short job such as blinking the cursor. But if a handler sets about reading a large file, the interface freezes for that time. Long jobs are therefore handed to a separate thread. The same pattern is used with epoll in servers such as nginx and Node.js, and with message queues in microkernel servers.

Example 14.2

Let the handlers keep a counter: KEY increases the counter by 1, CLICK by 10; TIMER resets the counter if it is greater than 10. If the events arrive in the order KEY CLICK KEY TIMER CLICK KEY KEY QUIT, what is the counter at the end of the loop?

  1. KEY, CLICK, KEY. 0 → 1 → 11 → 12.
  2. TIMER. Because 12 > 10, the counter is reset: 0.
  3. CLICK, KEY, KEY. 0 → 10 → 11 → 12.
  4. QUIT. get_message returns 0 and the loop ends. The result is 12.

The result is determined not by the text of the program but by the order of the events. Had the same events arrived in a different order, the counter would have come out differently.

Common mistake

Thinking that an event loop keeps the CPU constantly busy when the queue is empty. get_message is a blocking call; if there is no event, the process goes to sleep. The problem is not the loop itself but long-running handlers.

14.2.6Data paradigms

The execution paradigm determines the flow; the data paradigm determines how resources are named and used. There are two great traditions (Figure 14.6).

open · read · write · closeone interface, one kind of descriptor (fd)regular file/home/ali/not.txtdevice/dev/nvme0n1pipepipe(fd)kernel information/proc/cpuinfosocketsocket()UNIX: “everything is a file” · Plan 9: network and windows are file systems tooWindows: “everything is an object” → HANDLEobject manager: \Device\HarddiskVolume1, event, mutex, process, thread
Figure 14.6: Data paradigms. In UNIX a single file interface (open, read, write, close) applies to a regular file, a device, a pipe, /proc information, and a socket. In Windows everything is an object and is used through a HANDLE.

The UNIX principle is summed up as “everything is a file.” The regular file /home/ali/not.txt, the NVMe disk /dev/nvme0n1, a pipe, the kernel information /proc/cpuinfo, and a socket are all used through the same kind of descriptor, the file descriptor (fd). Plan 9 pushed this idea further, offering the network and windows as file systems too. In Windows, everything is an object. The object manager keeps files, events, mutexes, processes, and threads in a single namespace under names such as \Device\HarddiskVolume1; a program reaches them through a HANDLE.

The gain from a common data paradigm is that the same tools work on every resource. cat, dd, and shell redirection work on a file, on a device, and on kernel information alike. The command cat /proc/loadavg shows the system's load average with no special tool needed.

There is a price as well. Some devices do not fit the file model. Setting a camera's resolution or changing a network card's settings cannot be expressed naturally with read and write. Everything then piles up in “escape hatches” such as ioctl. ioctl takes a command number whose meaning changes from device to device, and hundreds of different operations hide behind a single call. The complexity has been lifted off the surface of the interface, but it has not been lost inside.

14.2.7The system-call interface

The most concrete application of the interface principles is the relationship between system calls and the library. The kernel holds few, general calls, and the library holds convenience functions (Figure 14.7).

library (glibc, user space)execlexeclpexecleexecvexecvpexecvpeuser / kernel boundaryexecveone system call: path, argv[], envp[]
Figure 14.7: The six exec library functions (execl, execlp, execle, execv, execvp, execvpe) live in user space; all of them reduce to the single execve system call.

The six functions differ in how the arguments are given (a list or an array), whether the program is searched for in PATH, and whether the environment is passed explicitly. All of these differences are resolved in user space. The kernel sees only a path, an argument array, and an environment array. Adding a new convenience does not change the kernel; only the library grows.

The second principle is independent components. UNIX splits process creation into two calls: fork and execve. In between, the child process can prepare its own environment: it can redirect input and output, change its working directory, and close unneeded files. In Windows, by contrast, CreateProcess takes ten parameters in a single call. That call is powerful, but every new need means a new parameter or flag.

Modern trends move in two directions. posix_spawn creates a process in a single step, to avoid the cost of copying the entire address space with fork. io_uring is a batched-call interface: many requests are submitted in a single user–kernel transition. Both trends arise from the principle that cost should be predictable.

Common mistake

Taking printf or fopen to be a system call. They are C library functions; when necessary, they make a write or openat call inside. printf often just writes to a buffer in user space and never enters the kernel at all.

14.3System structure

The interface is the face seen from outside; the structure describes how the inside of the kernel is divided. Which code runs in which address space and with what privilege? How does one component call another? The answers to these questions determine both the speed of the system and its resilience to faults.

14.3.1Structural options: isolation versus speed

The structural options are usually listed under names such as “monolithic,” “layered,” and “microkernel.” Behind each name is really a design decision. Every decision gains something and costs something (Table 14.3).

Table 14.3: System-structure options as design decisions.
Design decisionGainedPaidExample
Calling everything directly in a single address spaceSpeed: one trap, direct function callsNo fault isolation: one driver bug brings the system downLinux, FreeBSD
Restricting dependencies to one direction (layers)Layer-by-layer testing; changes stay localChoosing the layer order; the cost of every crossingTHE, MULTICS
Putting services in separate address spacesA crashed server is restarted; small, verifiable kernelIPC, context switching, and copying on every requestMINIX 3, QNX, seL4, Zircon
Separating protection from managementApplication-specific abstractions (libOS)Sharing between applications is hard; libOS complexityAegis/ExOS, unikernels
Loading code at run timeAdaptation without recompilingSafety of the extension: needs a verifier or a safe languageSPIN, Linux eBPF
Compromising the pure modelMicrokernel layout, monolithic speedPart of the isolation is lostWindows NT, macOS XNU

Every row of the table is a different point on the same trade-off. The basic trade-off is between isolation and performance. Each time an isolation boundary is crossed, a price is paid: a trap, a context switch, or a data copy. The more boundaries there are, the better faults are contained, but the slower the system becomes.

Definition 14.4

In a monolithic kernel, all services, including the file system, drivers, and memory management, run in a single privileged address space and call one another directly. In a microkernel, the kernel does only the most basic jobs, such as IPC, scheduling, and memory mapping. The other services run in user space as separate server processes and communicate by messages.

The difference between the two structures is plain in a single file read (Figure 14.8). In a monolithic kernel, the application enters the kernel with one trap; the VFS, ext4, and the disk driver call one another directly as function calls. In a microkernel, the application's request goes as a message to the file server, and from there by another message to the disk driver; the reply returns along the same path. Each message means at least one kernel crossing and a context switch.

monolithic: one address spaceappkernel: VFS + ext4 + driver1 trap, direct callsmicrokernel: messagesappfile serverdisk drivermicrokernel: IPC, scheduling, memory mapping
Figure 14.8: On the left, a monolithic kernel: one address space, one trap, and direct calls. On the right, a microkernel: the application, the file server, and the disk driver are separate processes; the kernel does only IPC, scheduling, and memory mapping.
Example 14.3

A team is considering taking the network driver out of the kernel and running it as a separate server process in user space. When the driver has a NULL-pointer bug, what happens in the two designs, and what is the cost of the user-space design?

  1. Monolithic kernel. The driver is in the kernel address space. The faulty access is a kernel fault (an oops); most of the time the system is left unstable or crashes entirely.
  2. User-space driver. The fault kills only the driver process. In MINIX 3, the reincarnation server notices this and restarts the driver; the other processes keep running.
  3. Cost. Every packet is now carried between the kernel and the driver process by messages. Each message adds a context switch and often a data copy; the packet rate drops.

The options are not mutually exclusive. Linux is monolithic, but it is extensible while running through loadable modules and eBPF; it also uses kernel threads. Windows NT and macOS XNU started with microkernel ideas but, for performance, moved most services back into the kernel address space. These hybrid structures show that both pure models have had to compromise in practice.

Common mistake

Assuming that a microkernel is slower in every case. In modern microkernels such as L4 and seL4, IPC has been brought down to a few hundred cycles. The real cost often lies not in a single message but in the number of messages a request needs and in how many times the data is copied.

14.3.2Layered systems

A layered structure is the oldest way of restricting dependencies to one direction. Dijkstra's THE system (1968) was built on this idea. Each layer uses only the abstractions offered by the layer below it and knows nothing of the one above. Tanenbaum proposes a seven-layer design for a modern operating system (Figure 14.9).

Definition 14.5

In a layered system, the system is divided into ordered layers, each of which uses only the services of the layer below it. A layer can be tested on its own if the layers beneath it work correctly.

7System call handler6File systemext4BtrfsNFS5Virtual memory4Device driversNVMenetworkUSBGPU3Threads, scheduling, synchronization2Interrupt handling, context switching, MMU1Hiding low-level hardware
Figure 14.9: Tanenbaum's seven-layer design. 1: hiding the low-level hardware; 2: interrupt handling, context switching, MMU; 3: threads, scheduling, synchronization; 4: device drivers; 5: virtual memory; 6: file systems; 7: system-call handler.

The order of the layers is not arbitrary; it follows from the dependencies. Virtual memory sits above the device drivers because it writes pages to disk and reads them back. The file system sits above virtual memory because it allocates frames for the page cache. Threads sit above layer 2 because they depend on interrupt handling and context switching. Layer 1, which hides the hardware, provides portability: when porting to a new processor, this layer is rewritten first.

The passage of a read call through the layers shows the structure in action.

  1. Layer 7. The application calls read(fd, buf, n) and the trap arrives at the system-call handler. The parameters are checked here: is fd valid, and is the buffer in user space?
  2. Layer 6. The file system (for example ext4) translates the file offset to a disk block; the block to be read is 4711. If the block is not in the cache, it is requested from the lower layers.
  3. Layer 5. Virtual memory allocates the page-cache frame where the data will be placed and validates the mapping of the user buffer.
  4. Layer 4. The NVMe driver writes the read command into the device's queue.
  5. Layer 3. The calling thread blocks until the I/O finishes; the scheduler runs another thread.
  6. Layer 2. When the device finishes, it raises an interrupt. The interrupt handler makes the sleeping thread ready. The result travels back up through the layers, and read returns the number of bytes read.
7System call handler6File systemext4BtrfsNFS5Virtual memory4Device driversNVMenetworkUSBGPU3Threads, scheduling, synchronization2Interrupt handling, context switching, MMU1Hiding low-level hardwareblock 4711 needed
7System call handler6File systemext4BtrfsNFS5Virtual memory4Device driversNVMenetworkUSBGPU3Threads, scheduling, synchronization2Interrupt handling, context switching, MMU1Hiding low-level hardwareinterrupt arrived
Figure 14.10: The path of the read call. (a) In the file-system layer, the offset is translated to block 4711. (b) When the device finishes, the interrupt arrives at layer 2 and the result returns upward.

The price of a layered structure is the cost of crossing each layer. In a purely layered system, a request must pass through every layer one by one, and each crossing adds a function call and sometimes a copy of the parameters. The real difficulty, though, is choosing the layer order. In real systems, dependencies are not always one-directional. Virtual memory uses drivers, but a driver may also ask for memory for its own buffers. Today's systems therefore use the idea of layers as a thinking tool, not as a rigid rule.

Common mistake

Reading the layer number as an order of importance. Layer 7 is not “more important” than layer 1; it merely depends on more layers below it. The order shows dependency: a layer works only if everything beneath it is ready.

14.3.3Extensible systems

As needs change, new capabilities must be added to the kernel. Recompiling the kernel and rebooting the machine every time is impractical. In extensible systems, the kernel provides the basic functions and new components are added while it runs.

Definition 14.6

An extensible system is one that allows new code to be loaded into the kernel while it runs. eBPF (extended Berkeley Packet Filter) is the mechanism in Linux that lets small, verified programs be attached to kernel hooks and run.

The biggest problem of extension is safety. When third parties can add features to the system, it must also be ensured that the added code does not break the kernel. A classic loadable module (insmod) has full privileges: a bug in the module is no different from a bug in the kernel itself and can crash the system. The SPIN system of 1995 tried to solve this problem with a safe language, having extensions written in Modula-3 so that memory errors were prevented at compile time.

eBPF in Linux is today's answer (Figure 14.11). The program is written in C and compiled to BPF bytecode with clang. User space hands this bytecode to the kernel with the bpf() system call. The verifier in the kernel examines every path of the program. Are the loops bounded, and is every memory access safe? If the program fails a condition, loading is rejected. A program that passes is translated to native machine code by the JIT compiler and attached to a hook.

user spaceC sourceprog.bpf.cclangBPF bytecodebpf()system callkernelVerifierbounded loops, memory safeJITnative codeload rejectedkprobe/tracingXDP (network)security (LSM)sched_extLoadable module (insmod): unchecked
Figure 14.11: The path of an eBPF program: the C source is compiled to bytecode with clang, reaches the kernel through the bpf() call, passes the verifier, is translated to native code by the JIT, and is attached to hooks (tracing, XDP, LSM, sched_ext). A loadable module, in contrast, is unchecked.

Today eBPF hooks are used in four areas: tracing (kprobes and tracepoints), networking (processing packets at the driver level with XDP), security (LSM hooks), and, since Linux 6.12, scheduling (sched_ext). The importance of eBPF is that it provides isolation and extensibility at the same time. The code is fast because it runs in the kernel address space, and thanks to the verifier it cannot crash the kernel.

14.3.4Kernel threads

Some of the kernel's work is not tied to a system call or an interrupt. Reclaiming pages when memory runs low, writing the journal to disk, and finishing jobs too long to do in an interrupt are examples. For these jobs the kernel uses its own threads (Figure 14.12).

Definition 14.7

A kernel thread is a thread created and managed by the kernel that runs only in the kernel address space. It has no user address space. In Linux it is created with kthread_create.

user processes (own address spaces)bashfirefoxpostgreskernel address space (shared by all processes)kthreaddkworker/0:1ksoftirqd/0kswapd0jbd2/nvme0n1
Figure 14.12: Each of the user processes (bash, firefox, postgres) has its own address space. The kernel threads (kthreadd, kworker, ksoftirqd, kswapd, jbd2) run in the kernel address space, which is common to all processes.

Kernel threads are scheduled like ordinary threads and can block and sleep. Sleeping in an interrupt handler is forbidden; long jobs that cannot be done in an interrupt are therefore deferred to a kernel thread. Context switching is also cheap, because the address space, that is, the page table, does not change. Typical examples in Linux are the following:

  • kworker: runs deferred work (workqueue).
  • ksoftirqd: handles soft interrupts, such as the processing of network packets.
  • kswapd: reclaims pages when free memory runs low.
  • jbd2: writes ext4's journal to disk.

The ancestor of them all is kthreadd. In the output of ps -ef they appear in square brackets, for example [kswapd0]. User processes cannot create kernel threads. System calls can hand work only to threads the kernel is already running; the worker pool of io_uring is an example. Kernel threads make the structure one step more flexible: even a monolithic kernel can divide its work into independent flows that are scheduled separately.

14.4Design principles

Once the structure is chosen, the designer meets hundreds of small decisions. A few principles prove useful in these decisions again and again. They are not a single algorithm but a way of thinking; the same principle turns up in memory management and in file systems alike.

14.4.1Separating mechanism from policy

Definition 14.8

A mechanism determines how something is done; a policy decides what is to be done. The mechanism stays fixed in the kernel; the policy can be changed and is often set in user space.

The value of this separation is that different behaviors can be obtained without changing the kernel. The kernel cannot foresee every situation. But if it offers a good mechanism, the party that knows the situation best, the application or the administrator, chooses the policy itself. Scheduling is the clearest example of this principle (Figure 14.13).

Example 14.4

A database process has four threads: T1 UI (priority 5), T2 query (3), T3 backup (8), T4 log (1). The kernel's mechanism is “run the highest-priority ready thread.” Which thread runs, and what happens when the policy changes?

  1. Initially. The highest priority is 8; the CPU goes to T3, the backup. The queries wait.
  2. Policy. The database is the party that knows its own threads best. It decides that queries matter and the backup can wait, and says so with a system call: sched_setattr(T2, prio=9), sched_setattr(T3, prio=2).
  3. Result. The priorities are now 5, 9, 2, 1. Without any change to kernel code, it picks T2.
  4. Another policy. An interactive application puts the UI first: the priorities become 9, 6, 2, 1 and T1 runs.

The same mechanism has produced different behavior under different policies.

Policy (user space)no intervention yetkernelMechanism: priority-based scheduler (pick the highest-priority ready thread)T1 UIpriority 5T2 querypriority 3T3 backuppriority 8T4 logpriority 1CPU → T3 backup
Policy (user space)sched_setattr(T2, prio=9); sched_setattr(T3, prio=2);kernelMechanism: priority-based scheduler (pick the highest-priority ready thread)T1 UIpriority 5T2 querypriority 9T3 backuppriority 2T4 logpriority 1CPU → T2 query
Figure 14.13: Mechanism and policy. (a) User space has not yet intervened; the kernel picks T3 (backup), which has the highest priority. (b) The database has changed the priorities; the same scheduler now picks T2 (query).

The sched_ext facility in Linux 6.12 takes this principle a step further. Not just priorities but the entire scheduling policy can be loaded as an eBPF program. The kernel provides the task queues, the context switching, and the distribution to CPUs; the loaded program decides which task runs when.

The same separation appears everywhere in an operating system:

  • Paging. The mechanism is the MMU and frame allocation; the policy is the rule that decides which page to evict (LRU, clock).
  • CPU frequency. The mechanism is the cpufreq driver; the policy is the schedutil or powersave governor.
  • Security. The mechanism is the LSM hooks; the policy is the SELinux rules.
Common mistake

Counting all kernel code as mechanism and all user-space code as policy. The distinction is made by the kind of work, not by where the code lives. The page-replacement rule runs in the kernel, but it is a policy: the clock algorithm can be chosen instead of LRU. The MMU's address translation or the saving of registers in a context switch, on the other hand, are mechanisms independent of any policy.

14.4.2Orthogonality

Definition 14.9

Orthogonality is the ability to combine separate concepts independently of one another. In an orthogonal design, changing one concept does not affect another.

The term comes from geometry: moving in one direction along two perpendicular axes does not change the position on the other axis. In design, orthogonality makes it possible to obtain many combinations from a small number of concepts. The C language offers a simple example. The lifetime of a variable (static) and its type are chosen independently: static int, static char *, and static struct proc are all valid.

The best example in operating systems is Linux's clone call (Figure 14.14). When a new execution unit is created, what is shared is chosen with separate flags. CLONE_VM shares the address space, CLONE_FS the root and working directory, CLONE_FILES the open-file table, CLONE_SIGHAND the signal handlers, and CLONE_THREAD the thread group.

fork()intermediate formpthread_create()CLONE_VMaddress spacecopycopyshareCLONE_FSroot/working directorycopyshareshareCLONE_FILESopen filescopyshareshareCLONE_SIGHANDsignal handlerscopycopyshareCLONE_THREADsame thread groupcopycopyshareprocess ← one call: clone(flags) → thread
Figure 14.14: Independent flags in the Linux clone call. fork() shares nothing, pthread_create() shares everything; every combination in between is possible.

If none of the flags is given, the result is fork: everything is copied. If all are given, the result is pthread_create: everything is shared. Process and thread are thus not two separate concepts but the two ends of the same mechanism. Containers are also built with the same call, using the CLONE_NEW* namespace flags such as CLONE_NEWPID and CLONE_NEWNET.

Windows approaches the same problem with a different orthogonal design. A process is a resource container: the address space, the handles, and the security information belong to the process. A thread is the unit of scheduling. The two concepts are separate from the start, and every process contains one or more threads.

14.4.3Naming: two-level names

An operating system manages thousands of objects: files, processes, devices, memory pages, network endpoints. People want to refer to these objects by memorable names. Inside the system, a fast and unique number is more useful. The solution is two-level naming.

Definition 14.10

An external name is the name people use, usually an ASCII or Unicode string. An internal name is a fast, unique number used inside the system. A table or a service performs the mapping between the two.

external name (for humans)/usr/ast/mboxdirectory (mapping table)grants64books92mbox60minix81internal name (for the system)i-node 60owner, permissions, sizeblock list →
Figure 14.15: Two-level naming. The external name /usr/ast/mbox is mapped through the directory (the mapping table) to the internal name, i-node 60; the i-node holds the owner, the permissions, the size, and the block list.

The same pattern recurs in many places in the operating system (Table 14.4).

Table 14.4: Examples of two-level naming.
External nameMapped byInternal name
/usr/ast/mboxdirectoryi-node number
www.giresun.edu.trDNSIP address → (ARP) MAC address
file descriptor 3process file tablestruct file in the kernel
virtual addresspage tablephysical frame
\Device\Harddisk0object managerkernel object (HANDLE)

The biggest gain from the mapping in between is that an object can be moved without changing its name. When a website is moved to another server, only the DNS record changes; users go on typing the same name. When a page is written out to disk and later restored to a different frame, only the page table is updated; the program uses the same virtual address. The DNS row in the table is interesting: there the mapping is done twice. The name is first translated to an IP address, and the IP address to a MAC address by ARP.

14.4.4Name resolution step by step

Two-level naming has a cost: every time a name is used, the mapping must be performed. In a file path, this mapping proceeds component by component, and each component may need a disk access.

Example 14.5

The kernel receives the call open("/usr/ast/mbox") and nothing is in the cache. How many disk reads are needed to reach the file's i-node?

  1. Root directory. The i-node of the root directory (i-node 1) is read; it tells us the directory data is in block 1. Block 1 is read, and a linear search finds usr → i-node 6. Total: 2 reads.
  2. /usr. i-node 6 is read, then block 132 of the /usr directory. ast → i-node 26. Total: 4 reads.
  3. /usr/ast. i-node 26 is read, then directory block 406. mbox → i-node 60. Total: 6 reads.
  4. The file. Finally, the file's own i-node (60) is read. Total: 7 reads.

The rule is: two reads for every directory on the path (its i-node and its directory block), and one read at the end for the file's i-node. This path with three directories needs 2 × 3 + 1 = 7 reads.

/usr/ast/mboxdisk reads: 7i-node 1 → root directory · block 1.1..1bin4dev7lib14etc9usr6tmp8i-node 6 → /usr · block 132.6..1dick19erik30jim51ast26bal45i-node 26 → /usr/ast · block 406.26..6grants64books92mbox60minix81src17mbox → i-node 60 (7th read)
Figure 14.16: Resolving the path /usr/ast/mbox component by component. Reading the root directory (i-node 1, block 1), /usr (i-node 6, block 132), and /usr/ast (i-node 26, block 406) yields i-node 60.

Seven disk accesses were needed just to find the file. On a hard disk, where each access takes milliseconds, this means a delay of tens of milliseconds; not a single byte of the file has been read yet. The flexibility of two-level naming becomes cheap only if the mappings are kept in a cache.

Common mistake

Counting only the directory blocks, or forgetting the file's own i-node. To read the contents of a directory, that directory's i-node must be read first, because it says in which block the directory data lies. The path /home/ali/ders/notlar.txt, with four directories, therefore needs 2 × 4 + 1 = 9 reads.

14.4.5Binding time

Definition 14.11

Binding time is the moment at which a name is bound to the actual object. In early binding, the association is fixed in advance; in late binding, it is made at the latest possible moment.

A name can be bound at many different moments. Memory addresses are a good example (Figure 14.17). An absolute address embedded in the code while the program is written is the earliest binding. At compile time, a fixed load address can be chosen. At link time, static libraries are added to the program. At load time, relocation and ASLR determine the addresses. At run time, virtual memory, dlopen, and DNS leave the binding to the last moment.

at writing timeabsolute addressembedded in codecompilefixed loadaddresslinkstaticlibraryloadrelocation,ASLRrunvirtual memory,dlopen, DNS← early binding: simple, fast, less flexiblelate binding: complex, flexible →
Figure 14.17: The binding-time line: at writing time, compile time, link time, load time, and run time. Flexibility grows from left to right; early binding is simple and fast, late binding is complex but flexible.

Early binding is simple and fast, but less flexible. The program runs only at a particular address; when a library is updated, the program must be recompiled. Late binding is more complex, because it brings an extra indirection and a run-time cost. In return, flexibility is gained: the program runs wherever in memory the page is loaded, and it does not change when the library is updated.

Operating systems generally choose late binding. Virtual memory is the extreme example: the physical location of a page is resolved anew on every access. This cost is bearable thanks to the TLB. The price of late binding is paid, but hardware help is enlisted to reduce it.

14.4.6Static versus dynamic structures

The size of kernel data structures is also a design decision. Should the process table, the open-file table, or the buffer pool be kept as a fixed-size array at compile time, or as a structure that grows and shrinks at run time?

Definition 14.12

A static structure is one whose size is fixed at compile time or boot time, for example a fixed-size array. A dynamic structure grows and shrinks at run time by allocating memory, for example a linked list or a hash table.

In old UNIX kernels, the process table was a fixed-size array, and a process was looked up like this:

found = 0;
for (p = &proc_table[0];
     p < &proc_table[PROC_TABLE_SIZE];
     p++) {
    if (p->proc_pid == pid) {
        found = 1;
        break;
    }
}

found is cleared and the pointer p is set to the first element of the table. The loop continues until p reaches &proc_table[PROC_TABLE_SIZE], the address at the end of the table. On each iteration, the entry's proc_pid field is compared with the pid being sought. When there is a match, found = 1 is set and break leaves the loop. p++ advances the pointer not by one byte but by the size of one struct proc; in C, pointer arithmetic is done in units of the size of the pointed-to type.

Pid 42 is being sought in a table of six entries. The pids in the table are, in order, 1, 314, 0, 42, 977, 0; 0 means an empty entry (Table 14.5).

Table 14.5: Linear search for pid 42 in a static process table.
Iterationpp->proc_pidComparisonfound
1&proc_table[0]11 ≠ 420
2&proc_table[1]314314 ≠ 420
3&proc_table[2]0 (empty)0 ≠ 420
4&proc_table[3]42equal, break1
proc_table[PROC_TABLE_SIZE = 6]1[0]314[1]empty[2]42[3]977[4]empty[5]ppid sought = 42
Figure 14.18: A static process table of six entries (PROC_TABLE_SIZE = 6). The pointer p finds pid 42 at the fourth comparison.

Empty entries are scanned one by one too; that is the cost of linear search. In the worst case the whole table is scanned and the search takes O(n). But for a small, fixed table, this simple code is enough.

The advantages of a static table are simplicity and predictability: no memory allocator is needed, and the table is never fragmented. The disadvantage is that once the table is full, no new process can be created. In old UNIX this limit was the constant NPROC. A dynamic structure, such as a linked list, a hash table, or Linux's xarray, removes this limit; a hash table and an xarray also bring the search close to O(1). The price is a memory allocator, fragmentation, and more complicated locking. There is a middle way too: tables whose size is tunable. In Linux, the largest pid value is read from the file /proc/sys/kernel/pid_max and can be changed.

14.4.7Top-down versus bottom-up implementation

Once a system has been designed, from which end should writing begin? There are two approaches (Figure 14.19).

System call handlerFile systemVirtual memoryDriversThreadsHardware abstraction (HAL)topdownlower layersstubbottomupeach layertested at once
Figure 14.19: In top-down implementation, the lower layers are left as stubs; in bottom-up implementation, one starts from the hardware abstraction and tests each layer as soon as it is finished.

In top-down implementation, the system-call handlers are written first. The lower layers are left as stubs. A stub is a function declared with the correct signature but with an empty body or returning a constant value. The interface becomes clear early. But realistic testing is hard until the whole system is done, because stubs do not imitate real behavior.

In bottom-up implementation, the layer that hides the hardware is written first, then interrupts, the timer, and threads. Each layer is tested when it is finished, because everything beneath it is real. Tanenbaum recommends this route for implementation. The design itself, however, should be thought through top-down: first the interface is determined, and then the layers that will provide that interface are built from the bottom up.

14.4.8Synchronous versus asynchronous communication

Definition 14.13

In synchronous communication, after sending a request the sender blocks until the reply arrives. In asynchronous communication, the sender keeps running; completion is reported to it later by a signal, a callback, or a completion queue.

Synchronous (blocking)senderreceiver / deviceAsynchronous (non-blocking)senderreceiver / devicesend(request)blockedreplycontinuessubmit(request)does other workcompletion: signal / callback / CQ
Figure 14.20: On the left, synchronous communication: after send(request) the sender blocks until the reply arrives. On the right, asynchronous communication: after submit(request) the sender does other work; completion is reported by a signal, a callback, or the CQ.

Synchronous communication is easy to program. The flow reads sequentially: request, reply, next line. The price is that a thread sits idle for every pending request. In microkernels, IPC is usually synchronous; L4 and seL4 follow this route. Because the sender waits for the reply, the kernel does not need to buffer the message, and the message can be transferred directly to the receiver. This makes IPC very fast.

In asynchronous communication, a single thread can have thousands of requests in flight at once. But race conditions, error handling, and buffering become harder. The failure of a request arrives when the code that sent it has long since moved on to something else. io_uring in Linux is a current example of this model. The submission (SQ, submission queue) and completion (CQ, completion queue) rings are shared between user space and the kernel. With the right setup, requests can be submitted even without a system call, because a kernel thread watches the submission ring.

Common mistake

Thinking that asynchronous communication is always faster. The latency of a single request is about the same in the two models; the asynchronous model only lets other work be done while waiting. The gain appears when there are many concurrent requests. The price is code that is more complicated and harder to debug.

14.5Useful techniques

Principles say what to aim for; techniques say how to get there. The techniques in this part are used everywhere in operating-system code, often without being named. Each has a gain and a cost.

14.5.1Hiding the hardware

An operating system must run on more than one processor architecture. Each architecture has different startup code, register width, and interrupt layout. Letting these differences spread through all the code kills portability. The solution is to gather the hardware-dependent code in a few files. In C, the oldest tool for this is conditional compilation.

Definition 14.14

Conditional compilation means that, with the preprocessor directives #if, #elif, and #endif, only those parts of the source code that satisfy certain conditions are compiled. Lines that do not satisfy the condition never reach the compiler.

The first example selects different startup code according to the CPU type. The file config.h defines the constant CPU, and the preprocessor lets only the matching block through to compilation.

#include "config.h"
void init(void)
{
#if (CPU == X86_64)
    /* x86-64 init code */
#endif
#if (CPU == ARM64)
    /* ARM64 init code */
#endif
#if (CPU == RISCV64)
    /* RISC-V init code */
#endif
}

The second example selects a register type according to the word length. On a 32-bit machine Register becomes an int, on a 64-bit machine a long. The last branch is today's portable solution: uintptr_t from <stdint.h> is an integer type large enough to hold a pointer on every platform.

#include "config.h"
#include <stdint.h>
#if (WORD_LENGTH == 32)
typedef int Register;
#elif (WORD_LENGTH == 64)
typedef long Register;
#else  /* today: portable */
typedef uintptr_t Register;
#endif
Register R0, R1, R2, R3;

The listings are an updated version of Tanenbaum's Pentium–UltraSPARC example. In today's systems the same idea is applied at the directory level. In Windows, the hardware-dependent code is gathered in the HAL (Hardware Abstraction Layer). In Linux it lives in directories such as arch/x86, arch/arm64, and arch/riscv. When porting to a new processor, only this part is rewritten.

Example 14.6

In config.h, the constant CPU is defined as ARM64 and WORD_LENGTH as 64. Which startup block does the code compile, and what is sizeof(Register)? What changes if the same code is compiled on 64-bit Windows?

  1. Startup. Only the #if (CPU == ARM64) block is compiled. The x86-64 and RISC-V blocks are removed in the preprocessor; the compiler never sees them.
  2. Register. Because WORD_LENGTH == 64, Register is a long. 64-bit Linux uses the LP64 model; in this model long is 8 bytes, so sizeof(Register) is 8.
  3. Windows. 64-bit Windows uses the LLP64 model; there long is 4 bytes. The same source code produces a register type of a different size. This is why uintptr_t is preferred in portable code.
Common mistake

Scattering conditional compilation everywhere. #ifdef blocks sprinkled into every function make the code unreadable, and since some combinations are never compiled, bugs go unnoticed for years. The right approach is to gather the hardware-dependent code in a few files and offer the rest of the code a common interface.

14.5.2Indirection

Definition 14.15

Indirection is reaching an object not directly but through an intervening table, pointer, or name. By changing the intermediate step, behavior can be changed without touching the parties at the two ends.

A remark attributed to David Wheeler sums up the power of the technique: every problem in computer science can be solved by another level of indirection. Keyboard input is a good example. When a key is pressed, the keyboard does not send a character; it sends a scan code that gives the position of the key. What turns this code into a character is the operating system's key map (keymap).

Example 14.7

A user presses the key to the right of U on a US keyboard. Which character is produced with three different keymaps?

  1. Hardware. The keyboard sends scan code 0x17 in set 1. On USB keyboards what arrives is an HID usage code; the driver translates it to a common code.
  2. US (QWERTY) map. 0x17 → i.
  3. Turkish Q map. Only the table is changed: the same key now produces ı.
  4. Turkish F map. The same key becomes n.

In all three cases the hardware and the application are the same; only the table in between changes.

physical keyright of Uscan code0x17 (set 1)key map table (keymap)US (QWERTY)iTurkish QıTurkish Fnncharacter delivered to the application
Figure 14.21: Indirection in keyboard input. The physical key produces scan code 0x17; the keymap translates it to i in the US layout, to ı in Turkish Q, and to n in Turkish F.

The gain of the extra step is flexibility, and its cost is a table lookup. The cost is usually negligible, but it can add up on a hot path. In operating systems, indirection is everywhere: the page table in virtual memory, the process file table for file descriptors, another path in symbolic links, the i-node in file systems, device classes in drivers. Two-level naming and late binding are also examples of indirection.

14.5.3Reuse and reentrancy

In a large system, the same kinds of problems recur in different places. Keeping track of free disk blocks, free memory frames, and unused PIDs is the same problem: recording which elements of a large set are free. Writing a single bitmap module for these three is better than writing three separate pieces of code. Linux follows this principle by offering common data structures: the doubly linked list in list.h, the red-black tree, and the xarray are used throughout the kernel.

Code that is to be reused must meet one condition: it must be callable from several places at the same time.

Definition 14.16

A piece of code is reentrant if it works correctly even when the same code is called again while one of its calls is still in progress. The rule: there is no static variable shared between calls; the state is kept in a place supplied by the caller, and if it must be shared, it is protected by a lock.

In the kernel, reentrancy is needed for two reasons. The first is interrupts: while a function is running, an interrupt arrives, and the interrupt handler may call the same function. The second is multiple cores: another CPU core may run the same code at the same time. strtok in the standard C library is a classic example of code that fails this condition.

char *strtok(char *s, const char *d)
{
    static char *last; /* shared state! */
    ...
}

/* reentrant version: state in the caller */
char *strtok_r(char *s, const char *d,
               char **saveptr);

strtok splits a string into pieces at delimiters. On the first call the string is passed; on later calls NULL is passed and the function continues from where it left off. It remembers where it left off in its internal static char *last variable. This variable is not on the stack but in the data segment, shared by all threads. The reentrant version, strtok_r, keeps the same information in the saveptr pointer supplied by the caller.

14.5.4Code trace: strtok

To see how the problem arises, we can trace a simplified version of strtok. my_strtok takes a one-character delimiter and keeps its state in the variable static char *rest.

char *my_strtok(char *s, char sep) {
    static char *rest;      /* shared by all! */
    if (s) rest = s;
    if (!rest || !*rest) return NULL;
    char *tok = rest;
    while (*rest && *rest != sep) rest++;
    if (*rest) *rest++ = '\0';
    return tok;
}
/* main:  my_strtok(a, ',')  a = "ali,veli" */
/* irq:   my_strtok(b, ';')  b = "x;y"      */
/* main:  my_strtok(NULL, ',')              */

The function works line by line as follows. If s is given, rest is set to its start. If rest is NULL or points to the end of the string, no pieces are left and NULL is returned. Otherwise the start of the piece is saved in tok. The while loop advances rest to the delimiter or to the end of the string. If a delimiter was found, '\0' is written over it and rest moves to the next character. The function returns tok; the returned string ends at the '\0' that was written.

The scenario is as follows. main is splitting the string a = "ali,veli" at commas. Right after it gets the first piece, an interrupt arrives, and the interrupt handler uses the same function to split the string b = "x;y" at semicolons. Then main continues from where it left off (Table 14.6).

Table 14.6: Trace of my_strtok. The rest column shows the value after the call.
CallerCallState of the stringsrestReturns
mainmy_strtok(a, ',')a: ali\0veli\0&a[4] (v)"ali"
interruptmy_strtok(b, ';')b: x\0y\0&b[2] (y)"x"
mainmy_strtok(NULL, ',')unchanged&b[3] (\0)"y"
  • First call. rest = a. The loop advances to the comma at a[3]; '\0' is written over the comma and rest moves to a[4], the start of “veli.” It returns "ali".
  • Interrupt. The handler's call arrives with s = b and overwrites the shared rest. The semicolon becomes '\0', rest points to b[2], and it returns "x". The place where main left off is lost.
  • main continues. main passes NULL and assumes the function is still working on a. But rest points into b[2]. The loop advances to the end of the string; there is no delimiter, so rest stays at b[3]. It returns "y"; the expected result was "veli".
aali\0veli\0static rest:a[4] (v)main1st call → "ali"
aali\0veli\0bx\0y\0static rest:b[3] (\0)main continuesmain was waiting: "veli" — got: "y"
Figure 14.22: (a) After the first call, rest points to a[4] (v). (b) When main continues after the interrupt handler's call, rest is inside b; main expects “veli” but gets “y.”

The bug shows up rarely and depending on timing. If the interrupt does not fall exactly between two calls, the program works correctly. Catching this kind of bug by testing is therefore hard. The root cause is clear: the state between calls is kept in a shared static variable. The fix is clear too: carry the state to the caller, as in strtok_r(s, d, &rest). Then every caller has its own rest, and the interrupt cannot touch the state of main.

Common mistake

Thinking that a static variable is kept on each thread's own stack. Local static variables live in the data segment, and all the threads in the program share them. If two threads use strtok at the same time, the pieces may come from the wrong string. A single-core machine is not immune to this bug either: an interrupt or preemption creates the same interleaving.

14.5.5Brute force and checking for errors first

Definition 14.17

Brute force means preferring the simplest and most obvious solution, even if it seems slow. One moves to a complicated algorithm only when measurement shows it is needed.

For a table of fifty entries, linear search can be both faster and less error-prone than a hash table. Computing the hash function, the collision chains, and resizing cost more in a small table than they gain. A complicated algorithm is needed only if n is large or the code is on a frequently executed path. Sorting is similar: insertion sort suits small arrays, and merge sort or heap sort suits large ones.

The second technique concerns where error checks go. A system-call handler receives a size and a buffer address from the user; it also needs a lock and memory. A bad ordering looks like this:

lock(&tbl_lock);
buf = kmalloc(n, GFP_KERNEL);
if (n > MAX || !access_ok(u, n)) {
    kfree(buf);
    unlock(&tbl_lock);
    return -EINVAL;
}

The code first takes the lock, then allocates the memory, and only after that checks whether the parameters are valid. If a parameter is bad, it has to give back everything it took, in reverse order: kfree, unlock, then the error code. This code also never checks whether kmalloc failed. A good ordering looks like this:

if (n > MAX || !access_ok(u, n))
    return -EINVAL; /* check first */
buf = kmalloc(n, GFP_KERNEL);
if (!buf)
    return -ENOMEM;
lock(&tbl_lock);
...

The parameters are checked first; if they are bad, -EINVAL is returned without any resource having been acquired. Then the memory is allocated and the success of the allocation is checked. The lock is taken last. Nothing is left to undo on the error path. One of the most common bugs in real kernels is forgetting an unlock on an error path. Checking for errors first eliminates this class of bug.

Common mistake

Taking brute force to mean “sloppy code.” The principle is to choose the simple solution knowingly and by measurement. A brute-force scan of a table is a sound design decision as long as n stays small. Only when n grows, or when a profile shows this code to be a bottleneck, should it be rethought.

14.6Performance

Every operating system wants to be fast. But speed is meaningful only once correctness is secured, and every speedup makes the code more complicated. This part first covers how to decide what to speed up, and then the most commonly used techniques.

14.6.1Why is it slow, and what should be sped up?

Hardware has become thousands of times faster over the decades, but the speed the user feels has not grown at the same rate. A large part of the gain was consumed by the growth of software. There are three reasons. The first is feature bloat: every release adds new features and cannot remove the old ones. The second is layers of backward compatibility. The third is security measures. The patches added against the Spectre and Meltdown vulnerabilities, such as separating the kernel and user page tables, raised the cost of every system call. The indirection added for generality also takes a little time at every layer.

Measurement decides what to speed up. Donald Knuth's saying is often cited here: premature optimization is the root of all evil. First write correct code, then fast code. Speedups are applied only to the parts shown by measurement to be bottlenecks. The principle of “good enough” also belongs here: making the code twice as complicated for a 5% gain is usually not worth it. In Linux, the measurement tools are perf, the eBPF-based bpftrace, and flame graphs.

A simple calculation shows how to read a profile (Figure 14.23).

Example 14.8

A profile shows that 70% of the running time is spent in the function f() and 30% in g(). Which pays off more, making f() twice as fast or g() twice as fast?

  1. Starting point. Take the total time to be 100 units: f 70, g 30.
  2. f twice as fast. f drops to 35 units; the total is 35 + 30 = 65. The speedup is 100 / 65 ≈ 1.54×.
  3. g twice as fast. g drops to 15 units; the total is 70 + 15 = 85. The speedup is 100 / 85 ≈ 1.18×.
  4. Result. For the same effort, speeding up f pays off far more. Even if g were infinitely fast, the total time would not drop below 70.
nowf() 70g() 30f() 2× fasterf() 35g() 3065 → 1.54× speedupg() 2× fasterf() 70g() 1585 → 1.18× speedup
Figure 14.23: A profile: 70% of the time is in f(). Making f() twice as fast brings the total down to 65 (1.54×); making g() twice as fast brings it to 85 (1.18×).

The general form of this calculation is called Amdahl's law.

Theorem 14.1 (Amdahl's law)

If a fraction p of the running time is made k times faster, the overall speedup is

S = 1 / ((1 − p) + p / k)

no matter how large k is, the speedup cannot exceed 1 / (1 − p).

The values in the example fit the formula: for p = 0.7 and k = 2, S = 1 / (0.3 + 0.35) ≈ 1.54; for p = 0.3, S = 1 / (0.7 + 0.15) ≈ 1.18. Even if f were infinitely fast, the speedup could not exceed 1 / 0.3 ≈ 3.33. The law shows numerically that optimization effort should be spent on the common case.

There are five classic techniques to turn to after measuring: the space-time trade-off, caching, hints, exploiting locality, and optimizing the common case.

14.6.2Space-time trade-off: counting bits

Definition 14.18

A space-time trade-off means shortening the running time by using more memory or, conversely, saving memory by running longer.

The classic example is counting the 1 bits in a byte. This operation is common in the bitmaps of memory allocators and in permission masks. The first version tests each bit one by one in a loop:

#define BYTE_SIZE 8
int bit_count(int byte)
{
    int i, count = 0;
    for (i = 0; i < BYTE_SIZE; i++)
        if ((byte >> i) & 1)
            count++;
    return count;
}

The loop counts i from 0 to 7. On each iteration the byte is shifted right by i bits and the lowest bit is masked with 1: (byte >> i) & 1. If the result is 1, the counter is incremented. The example byte is 0xB7: 183 in decimal, 1011 0111 in binary (Table 14.7).

Table 14.7: Trace of bit_count(0xB7). 0xB7 = 1011 0111.
i01234567
(byte >> i) & 111101101
count12334556
byte = 0xB7 = 1011 01111b01b11b20b31b41b50b61b7count = 6
Figure 14.24: The eight bits of 0xB7 are counted one by one in a loop; the result is 6.

Bits 3 and 6 are zero; on those iterations the branch is not taken and the counter does not change. The loop runs eight times and returns 6. Memory use is negligible. But there are eight iterations per byte, and on each a shift, a mask, a comparison, and a branch. When branch prediction fails, the processor's pipeline is flushed, which adds cost.

Two faster versions buy time with space:

/* (b) macro: no loop */
#define bit_count(b) ((b&1) + ((b>>1)&1) + \
    ((b>>2)&1) + ... + ((b>>7)&1))

/* (c) table: 256 bytes */
char bits[256] =
    {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, ...};
#define bit_count(b) (int) bits[b]

The macro (b) unrolls the loop: eight terms are summed directly. There is no loop and no branch, but about 24 instructions are needed. Version (c) uses a table of 256 entries. Entry i of the table is the number of 1 bits in the binary representation of i. Counting bits comes down to a single memory read (Figure 14.25). The methods are compared in Table 14.8.

bits[0..31] (computed with Python: bin(i).count("1"))00111223142526371829210311212313314415116217218319220321322423224325326427328429430531bits[0xB7] = bits[183] = 6
Figure 14.25: The first 32 values of the 256-entry bit-count table and bits[0xB7] = bits[183] = 6.
Table 14.8: Space and time cost of the bit-counting methods.
MethodMemoryWork per byte
(a) loop~08 iterations: shift, mask, branch
(b) macro~0~24 instructions, no branch
(c) 256-entry table256 B1 memory read
16-entry table (nibble)16 B2 reads + an addition
POPCNT instruction01 instruction (__builtin_popcount)

The last row of the table is today's reality. x86-64 and ARM64 processors have a special instruction that counts 1 bits, and the compiler turns a call to __builtin_popcount into that instruction. Even so, the space-time trade-off keeps its importance, because the same idea is used in hundreds of other computations where the hardware does not help.

14.6.3Code trace: the nibble table

Between the 256-byte table and the loop there is a middle ground. If a byte is split into two nibbles (nibble), a table of 16 entries is enough. The table, too, can be built by a loop instead of being written by hand:

char nib[16];            /* 16 bytes */
void build_table(void) {
    nib[0] = 0;
    for (int i = 1; i < 16; i++)
        nib[i] = (i & 1) + nib[i >> 1];
}
int bit_cnt(unsigned char b) {
    return nib[b & 0x0F] + nib[b >> 4];
}

The observation behind build_table is this. The number of 1 bits in i is the value of its lowest bit plus the number of 1 bits in i >> 1. Since i >> 1 is always smaller than i, that value has already been computed when the loop proceeds from small to large. This is a dynamic-programming recurrence.

Example 14.9

With which values does build_table() fill the table?

  1. Start. nib[0] = 0; there are no bits in 0.
  2. i = 1 … 3. nib[1] = 1 + nib[0] = 1, nib[2] = 0 + nib[1] = 1, nib[3] = 1 + nib[1] = 2.
  3. i = 4 … 7. 1, 2, 2, 3. For example, nib[7] = 1 + nib[3] = 3.
  4. i = 8 … 15. 1, 2, 2, 3, 2, 3, 3, 4. For example, nib[15] = 1 + nib[7] = 4.

The whole table: 0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4.

Once the table is ready, bit_cnt splits the byte into two halves. b & 0x0F gives the low four bits and b >> 4 the high four. The two table values are added. There is no loop and no branch (Table 14.9).

Table 14.9: Calls to bit_cnt.
bBinaryLow halfHigh halfSum
0xB71011 0111nib[7] = 3nib[B] = 36
0x5C0101 1100nib[C] = 2nib[5] = 24
nib[16]001112231425263718292A3B2C3D3E4Fb = 0xB7 =10110111high = Blow = 7nib[7] + nib[B] = 3 + 3 = 6
Figure 14.26: The 16-entry nib table, filled in. bit_cnt(0xB7): two reads, for low half 7 and high half B, give 3 + 3 = 6.

Two memory reads and an addition suffice for 0xB7; the loop version had gone around eight times for the same byte. The nibble table takes 16 bytes, one-sixteenth of the 256-entry table. In exchange, there is one extra read and one extra addition. We see that the same question can be answered in several different ways depending on how much space is spent.

Common mistake

Assuming that the table method is always the fastest. The table lives in memory, and if it is not in the cache, a single read can take longer than a whole loop. A 256-byte table occupies four cache lines. As long as it is used constantly on a hot path, it stays in the cache and is fast. If it is used rarely, it may miss every time. So here, too, the decision is made by measurement.

14.6.4Space-time trade-off: the color palette

The trade-off works in the opposite direction too: by spending a little time, a great deal of space can be saved. The color palette is the classic example (Figure 14.27).

(a) 24 bits/pixelRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGB3 bytes/pixel(b) 8-bit index/pixel00110221324435541 byte/pixel(c) color palette0#3b82f61#22a05a2#e9a23b3#e76f514#8b5cf65#14b8a6256 entries × 3 bytes
Figure 14.27: (a) 24 bits per pixel (3-byte RGB). (b) An 8-bit palette index per pixel (1 byte). (c) A color palette of 256 entries; each entry is 3 bytes.

In an image, the red, green, and blue values can be stored directly for each pixel. That is 3 bytes per pixel. If the image uses at most 256 different colors, there is another way. The colors used are collected in a palette table, and for each pixel only a 1-byte index is stored. When the image is displayed, each index is translated to the real color through the palette.

Example 14.10

A 1024 × 768 image is stored in two formats. What are the sizes and the ratio?

  1. 24 bits/pixel. 1024 × 768 × 3 = 2,359,296 bytes; 2,359,296 / 2²⁰ = 2.25 MiB.
  2. 8-bit index + palette. The indices take 1024 × 768 × 1 = 786,432 bytes; the palette 256 × 3 = 768 bytes. Total: 787,200 bytes.
  3. Ratio. 2,359,296 / 787,200 ≈ 3.0. The space drops to about a third.
Table 14.10: Size of a 1024 × 768 image in two formats.
FormatSize (bytes)Ratio
(a) 24 bits/pixel2,359,296 (2.25 MiB)1
(b)+(c) 8-bit index + palette786,432 + 768 = 787,200≈ 1/3

The space gained costs in two ways. The time cost is the table lookup made as each pixel is displayed. The constraint cost is the limit of 256 colors; an image with thousands of colors, such as a photograph, does not fit this format without loss. GIF and PNG-8 use this method; GIF also compresses with LZW. The palette itself is 768 bytes, and as the image grows its share of the total becomes negligible.

Common mistake

Leaving out the size of the palette, or counting the palette per pixel. The palette is stored once per image. In an 800 × 600 image the indices are 480,000 bytes and the palette 768 bytes; the total is 480,768 bytes. The 24-bit format takes 1,440,000 bytes, and the ratio is again about 3.

14.6.5Caching

Definition 14.19

A cache is a structure that stores the result of an expensive computation or a slow access so that it can be supplied quickly when the same request comes again. The value in the cache must always be correct; when the source changes, the entry is invalidated.

The general rule is simple: if the same result is computed again and again, store it. Name resolution is tailor-made for this. Finding the path /usr/ast/mbox without a cache took seven disk reads. If the kernel keeps the result of every path it resolves in a table, then when the same path is asked for a second time, the disk is not visited at all (Table 14.11).

Table 14.11: A path → i-node cache.
Pathi-node
/usr6
/usr/ast26
/usr/ast/mbox60
/usr/ast/books92
/usr/bal45
/usr/bal/paper.ps85

Three cases are distinguished. With no cache, finding /usr/ast/mbox reads the root i-node, the root directory, the /usr i-node, the /usr directory, the /usr/ast i-node, and the /usr/ast directory. That is six disk reads; with the file's own i-node it makes seven. If the full path is in the cache, a single memory lookup suffices and the disk accesses are zero. If only /usr/ast is in the cache, the search continues from there: a partial hit is also a gain.

In Linux this job is done by several caches. The directory-entry cache (dcache, dentry cache) maps path components to i-nodes. The i-node cache holds the i-nodes themselves, and the page cache holds file contents. This is why free RAM in Linux often looks “full”: unused memory is given to these caches and taken back when needed.

The price of a cache is consistency. If a file is deleted or renamed, its entry must be invalidated; otherwise the cache points to a file that does not exist. This burden comes from the requirement that the value in the cache always be correct. In an operating system, caches exist at every layer: the TLB, the CPU caches, the page cache, the dcache, the ARP and DNS caches.

14.6.6Code trace: the path cache

A path resolver that also exploits partial hits can be written in a few lines. c[] holds the components of the path and n the number of components. The function finds the longest prefix in the cache and resolves only the remaining components from disk.

/* c[]: "usr","bal","thesis.tex"; n = 3 */
int resolve(char *c[], int n) {
    int k = n, ino = ROOT, reads = 0;
    while (k > 0 && !in_cache(c, k, &ino))
        k--;              /* longest prefix */
    for (int j = k; j < n; j++) {
        ino = dir_lookup(ino, c[j]);
        reads += 2;       /* i-node + block */
        cache_add(c, j + 1, ino);
    }
    return ino;
}

The function has two phases. In the first, k starts at n and decreases. in_cache(c, k, &ino) checks whether the path made of the first k components is in the cache; if it is, it writes the i-node number to ino. The loop stops at the first hit or when k falls to 0. If k falls to 0, ino stays at its initial value, the root i-node (ROOT = 1). In the second phase, dir_lookup is called for every remaining component. This call reads the directory's i-node and the directory block, so reads grows by 2. The result found is added to the cache with cache_add.

Initially the cache holds five paths: /usr (6), /usr/ast (26), /usr/ast/mbox (60), /usr/bal (45), and /usr/bal/paper.ps (85). Three lookups are made in turn (Table 14.12).

Table 14.12: Trace of resolve().
Pathk (prefix)Initial inoResolved from diskreadsResult
/usr/bal/thesis.tex2 (/usr/bal)45thesis.tex → 1312131
/usr/bal/thesis.tex3 (full path)131none0131
/etc/passwd01 (root)etc → 14, passwd → 2124212
  • First lookup. The full path /usr/bal/thesis.tex is not in the cache, so k drops to 2. /usr/bal is in the cache: ino = 45. There was no need to start from the root; two components came for free. For the one remaining component, the i-node of 45 and its directory block are read: thesis.tex → 131. The result is added to the cache.
  • The same path again. The full path is now in the cache. The first loop stops at once, and the second loop never runs. There are 0 disk reads.
  • /etc/passwd. Neither the full path nor /etc is in the cache; k drops to 0 and resolution starts from the root i-node. The root i-node and the root directory block are read: etc → 14; /etc enters the cache. Then the /etc i-node and directory block: passwd → 212. Total: 4 reads.
path:usrbalthesis.texdisk reads: 2cache (path → i-node)/usr6/usr/ast26/usr/ast/mbox60/usr/bal45/usr/bal/paper.ps85/usr/bal/thesis.tex131from disk: directory /usr/bal → thesis.tex
path:etcpasswddisk reads: 4cache (path → i-node)/usr6/usr/ast26/usr/ast/mbox60/usr/bal45/usr/bal/paper.ps85/usr/bal/thesis.tex131/etc14/etc/passwd212passwd in directory etc → 212
Figure 14.28: (a) /usr/bal comes from the cache; only thesis.tex is resolved from disk (2 reads) and added to the cache. (b) /etc/passwd is resolved from the root (4 reads); at the end the cache holds eight paths.

Without a cache, two reads are needed per component; if the longest prefix is in the cache, only the remaining components are paid for. The worst case is when no prefix is in the cache, and then the cost is proportional to the number of components. In Linux this cache is the dcache, which keeps the components separately; the logic is the same. The reads the code counts do not include the file's own i-node; the function returns only the i-node number.

Common mistake

Using the cache only for full hits. If the full path is not in the cache, starting the search from the root throws away the cached knowledge of /usr/bal. The longest-prefix rule exploits partial hits as well.

14.6.7Hints

Definition 14.20

A hint is a piece of information that is probably right but may be wrong. A hint is not invalidated; instead, before it is used, it is verified by a cheap check.

A hint resembles a cache, but the difference is important. The value in a cache must always be correct; when the source changes, the cache must therefore be updated, and this brings a consistency burden. A hint carries no such burden. If the hint turns out to be wrong, the system notices at the moment of use and falls back on the slow path (Figure 14.29).

read the hint“file server is on B”checka cheap proberightfast path: go straight to Bwrongslow path: ask the directory serviceupdate the hint
Figure 14.29: Using a hint. The hint is read (“the file server is on B”) and verified by a cheap probe. If it is right, the fast path goes straight to B; if wrong, the slow path asks the directory service and the hint is updated.

An example from a distributed file system explains the technique. A client keeps, as a hint, which server a file lives on. The file may be moved from one server to another, and the client may not know. The client first asks server B, named in the hint. If B really holds the file, the job is done. If not, the client consults the directory service, learns the file's new location, and updates the hint. When a file is moved, no client needs to be told.

Other examples:

  • Redirect cache on the Web. The place a page has moved to is remembered; if it is wrong, the server redirects again.
  • Branch prediction. The processor guesses the direction of a branch and starts running down that path; if the guess is wrong, it discards the results.
  • madvise(MADV_SEQUENTIAL). The application tells the kernel it will read a memory region sequentially. The kernel does more aggressive read-ahead. If the hint is wrong, only performance suffers; correctness is not affected.
Common mistake

Regarding the possibility that a hint is wrong as a flaw. That is where its whole value lies: because it is allowed to be wrong, there is no need for invalidation messages, locks, or consistency protocols. The requirement is one thing only: a wrong hint must not lead to a wrong result, only to the slow path.

14.6.8Exploiting locality

Definition 14.21

Temporal locality: data used recently will soon be used again. Spatial locality: when one item is used, nearby items are used too.

Temporal locality is the basis of the cache: if what was used recently is kept, the next request is likely to hit. Spatial locality is the basis of read-ahead and large pages: when one block is requested, several blocks after it are fetched too.

One way to exploit locality is to place data that is used together side by side (Figure 14.30). The BSD Fast File System (FFS) divides the disk into cylinder groups, and ext4 into block groups. A file's i-node and its data blocks are put in the same group, so after reading the i-node the disk arm does not have to travel far to reach the data. The same principle holds in the processor. If a thread is always scheduled on the same CPU core, that core's L1 and L2 caches stay “warm.” On NUMA machines, memory is allocated from the node where the thread runs.

ext4 disk layout: block groupsblock group 0i-nodedata blocksblock group 1i-nodedata blocksblock group 2i-nodedata blocksi-node and its data in the same group: short seekCPU affinitycore 0L1/L2 cachecore 1L1/L2 cachecore 2L1/L2 cachecore 3L1/L2 cacheif the thread stays on the same core, its cache stays “warm”
Figure 14.30: Exploiting locality. Top, ext4 block groups: the i-node and its data are in the same group, so the seek is short. Bottom, CPU affinity: if the thread stays on the same core, its L1/L2 cache stays warm.

14.6.9Optimizing the common case: the futex

One piece of advice from Butler Lampson on system design is this: make the common case fast and the rare case correct. Amdahl's law shows why; the gain comes mostly from speeding up the part that takes the most time. Locks are the best example of this principle.

Entering the kernel every time to take a lock is expensive: a system call, a mode switch, and queue operations. Yet measurements show that the great majority of locks are taken without contention. The thread asking for the lock is usually alone. If this is the common case, it is what needs to be made fast.

Definition 14.22

A futex (fast userspace mutex) is the Linux synchronization mechanism in which the state of the lock is kept in an integer in user space and the kernel is entered only to wait and to wake. The lock word takes the value 0 (free), 1 (held), or 2 (held, with waiters).

The atomic compare-and-swap (CAS, compare-and-swap) operation is used on the lock word. CAS replaces a memory word with a new value if it equals the expected value, in a single indivisible step, and reports whether it succeeded. A scenario in which two threads ask for the lock in turn is traced in four steps (Table 14.13).

Table 14.13: Trace of a futex-based lock.
StepEventLock wordWait queueSystem call
1The lock is free, A wants the lock0empty—
2A: CAS 0 → 1 succeeds1emptynone
3B: CAS fails, sets the value to 22Bfutex(FUTEX_WAIT)
4A releases; old value 20emptyfutex(FUTEX_WAKE)
user spaceThread Aacquired the lockThread Brunninglock wordvalue = 1kernelfutex wait queueemptyCAS 0→1 succeeds: no system call
user spaceThread Ain critical sectionThread Bsleepinglock wordvalue = 2kernelfutex wait queueBfutex(WAIT)CAS fails → 2 “there are waiters”
Figure 14.31: A futex-based lock. (a) No contention: A takes the lock in user space with CAS 0 → 1; no system call is made. (b) The rare case: B's CAS fails, it sets the value to 2 and sleeps in the kernel with futex(WAIT).
  • Fast path. A turns 0 into 1 with CAS. The kernel is never entered; the operation takes a few nanoseconds.
  • Slow path. B also wants the lock; because the lock word is not 0, its CAS fails. B sets the value to 2, that is, puts down the “there are waiters” mark, and sleeps in the kernel with futex(FUTEX_WAIT). The kernel is entered only here.
  • Release. When A releases the lock, it sets the word to 0 and looks at the old value. If the old value is 2, it calls futex(FUTEX_WAKE), and B wakes up and takes the lock. Had the old value been 1, it would have made no call at all.

An uncontended lock acquire and release thus finishes without making any system call. The kernel steps in only when waiting is really needed. The distinction between the values 1 and 2 is part of the common-case principle too: if nobody is waiting, the kernel is not visited even on release.

There are other examples of the same principle. The frequently used system calls have a short fast path in the kernel. Some calls, such as clock_gettime, are served by the vDSO without entering the kernel at all, read from a page mapped into user space. A TLB hit follows the same logic: the common case of address translation completes without a page-table walk.

Common mistake

Thinking that a futex is a lock in itself. A futex is not a lock but a wait–wake mechanism. The lock itself is the integer in user space and the CAS operations applied to it. Library locks such as pthread_mutex combine the two parts.

14.7Project management

An operating system is the work of hundreds, sometimes thousands, of people over many years. At this scale, how people work together decides the outcome as much as technical decisions do. The lessons Fred Brooks drew from IBM's OS/360 project are still valid today.

14.7.1The mythical man-month and Brooks's law

Definition 14.23

A man-month is one person's work for one month, used to measure the size of a project. Brooks's law: adding staff to a late software project makes it later.

The man-month is a misleading unit, because it assumes that work can be divided freely among people. A job of 12 man-months is not finished in 1 month by 12 people. People must coordinate with one another, and the number of communication paths grows quadratically as the team grows.

Example 14.11

If there is one communication path between every pair, how many paths are there in a team of n people? What do we see if we compute it for 2, 4, 6, 8, and 10 people?

  1. Formula. Each of the n people is connected to the other n − 1; since each path is counted twice, the total is n(n − 1) / 2.
  2. Values. 1 path for 2 people, 6 for 4, 15 for 6, 28 for 8, 45 for 10.
  3. Interpretation. While the number of people grows fivefold from 2 to 10, the number of paths rises from 1 to 45. Adding 3 people to a team of 5 raises the headcount by a factor of 1.6 but the number of paths from 10 to 28, a factor of 2.8.
12345678n = 8 people → 28 communication paths1n=26n=415n=628n=845n=10number of paths = n(n−1)/2
Figure 14.32: 28 communication paths in a team of 8. The bars on the right show the quadratic growth of the number of paths as n(n − 1)/2: 1, 6, 15, 28, 45.

Every new person must coordinate with everyone: meetings, documents, and interface agreements multiply. A person added to a late project must also be trained. And those who will train the newcomer are the people who already know the project, the most valuable ones. In the short run, every person added lowers the team's total productivity. Brooks's law is the combination of these two effects.

Based on his OS/360 experience, Brooks also proposes a distribution of time: 1/3 for planning, 1/6 for coding, 1/4 for module testing, 1/4 for system testing. In a 12-month project, that means 4 months for planning, 2 for coding, 3 for module testing, and 3 for system testing. Writing code is only a sixth of the work; half the time goes to testing.

Common mistake

Reading Brooks's law as “a team should never be enlarged.” The law is about people added late to a late project. In the planning stage, on a project whose work can be split into independent parts, enlarging the team can help. The problem is adding people at a moment when the work cannot be divided and the cost of learning is high.

14.7.2Team structure, experience, and the silver bullet

The way to reduce the communication burden is to divide the team into small, strong teams. In the surgical team model proposed by Harlan Mills and adopted by Brooks, the chief programmer designs and codes, and the others support him: one is an assistant, one manages the documents, one prepares the tools. Conceptual integrity stays in the hands of a few. According to Brooks, the conceptual integrity of a system is the most important quality of its design.

The development process of Linux is a present-day, large-scale form of this idea (Figure 14.33). The patches of thousands of contributors flow first to driver and subarea maintainers, then to subsystem maintainers, and finally to Linus Torvalds. At every level there is a small group that preserves conceptual integrity.

Linus Torvaldsnetworking maintainermemory maintainerfile-system maintainernetwork-driver maintainermm subarea maintainerext4 maintainerpatches from thousands of contributors flow upward (~4-5 thousand developers a year)
Figure 14.33: The Linux development hierarchy: contributors' patches flow to driver and subarea maintainers (network driver, mm, ext4), from there to subsystem maintainers (networking, memory, file system), and to Linus Torvalds. About 4–5 thousand developers contribute each year.

Experience plays a large role too. A good programmer is many times more productive than average; this difference can matter more than the number of people on the team. Two of Brooks's warnings belong here. The first is his saying “plan to throw one away”: the first version will most likely be thrown away, so it should be thought of from the start as a prototype. The second is the second-system effect: a designer who has successfully finished a first system adds to the second all the embellishments left out of the first, and the system bloats.

In his 1986 essay “No Silver Bullet,” Brooks reaches a more general conclusion: there is no single “silver bullet” that will by itself raise productivity in software development tenfold. He divides complexity into two kinds. Accidental complexity (accidental complexity) comes from tools and languages; better compilers, editors, and languages reduce it. Essential complexity (essential complexity) lies in the problem itself, and no tool can eliminate it. An operating system's concurrency, security requirements, and compatibility burden are essential. AI-assisted coding tools do not change this picture: they speed up the writing of code, but they do not remove the responsibility for design.

14.8Testing and debugging

In Brooks's distribution of time, testing takes half. In operating systems the share is perhaps even larger, because a bug in the kernel affects the whole system. This part describes why kernel code is hard to test, which kinds of tests and tools are used, and by what means a bug is found.

14.8.1Why is operating-system code hard to test?

In an application, a failing test usually produces just an error message. In the kernel, five factors make the job harder.

  • Privileged mode. There is no higher layer to catch the bug. In the kernel, a single bad pointer produces an oops or a panic and brings down the whole system, test harness included.
  • Concurrency. Interrupts, preemption, and multiple cores produce countless interleavings. A bug appears only under a rare timing.
  • Nondeterminism. Some bugs do not repeat on every run. These are jokingly called heisenbugs: even adding a printk can change the timing and hide the bug.
  • Variety. There are thousands of drivers, many architectures (x86-64, arm64, RISC-V), and tens of thousands of Kconfig options. Trying all the combinations is impossible.
  • Long-lived state. Memory leaks and counter overflows show up only after the system has run for days.

The kinds of tests are layered according to these difficulties (Table 14.14).

Table 14.14: Kinds of tests and their counterparts in the kernel.
KindWhat does it test? (kernel example)
UnitA single function or module, in isolation (KUnit)
IntegrationSubsystems working together, the user-space interface (kselftest)
SystemThe whole operating system, on a real or virtual machine (LTP, boot tests)
RegressionHas a fixed bug come back? Rerun on every change (KernelCI)
Stress / loadOverload, long durations, resource scarcity (stress-ng, rcutorture)

In the kernel, a failed test often means losing the machine itself. Tests are therefore run in virtual machines; every test has a timeout, and if the machine crashes it is restarted automatically.

14.8.2The kernel test pyramid

The test tools in Linux form a pyramid (Figure 14.34). At the base are many fast unit tests; at the top are a few slow but realistic system tests.

LTPsystem calls, POSIXkselftestkernel APIs from user spaceKUnitunit tests inside the kernel · seconds↑ realism and cost increase · ↓ speed and number of tests increaseKernelCIcontinuous integration• many trees and branches• many architectures, Kconfig• QEMU + real-board labs• runs KUnit, kselftest, LTP• automatically bisects regressionssimilar: 0-day bot, syzbotruns
Figure 14.34: The kernel test pyramid. At the base, KUnit unit tests that run inside the kernel; in the middle, kselftest, which tests kernel APIs from user space; at the top, LTP system tests. Going up, realism and cost increase; going down, speed and the number of tests increase. KernelCI runs them all continuously.
  • KUnit. The tests are compiled together with the kernel and call internal functions directly. They run in seconds under UML (User-Mode Linux) or QEMU; they are started with the kunit.py run command. The output is in KTAP format.
  • kselftest. It lives under tools/testing/selftests. It tests the running kernel's system calls and interfaces such as cgroup, bpf, and networking from the outside, from user space; it is run with make kselftest.
  • LTP. The Linux Test Project consists of thousands of tests: the semantics of system calls, POSIX conformance, file-system and stress scenarios. Distributions run LTP before a new release.

KernelCI runs these tests as continuous integration on many trees and branches, across many architectures and Kconfig combinations. Besides QEMU, labs of real boards are also used. When a regression is found, KernelCI automatically narrows it down to a single commit by binary search. The 0-day bot and syzbot are similar continuous-testing services.

14.8.3Dynamic checkers

A test catches a bug only if it can see some symptom of it. Most memory bugs give no symptom: writing one byte past the end of an array often silently corrupts another object, and the system crashes much later in an unrelated place. Dynamic checkers make these silent bugs visible at the moment of the first invalid access (Table 14.15).

Table 14.15: The kernel's dynamic checkers.
ToolBug it catchesHow it works
KASAN
CONFIG_KASAN
Use after free; heap, stack, and global array overflow; double freeThe compiler inserts a check before every memory access. Shadow memory (1 byte per 8 bytes) records which bytes are valid. The report also gives the allocation and free stack traces.
KCSAN
CONFIG_KCSAN
Data race: concurrent, lock-free accesses, at least one of which is a writeOn random accesses it sets a watchpoint and waits briefly; if another core touches the same address meanwhile, it reports.
UBSAN
CONFIG_UBSAN
Undefined behavior: signed overflow, division by zero, invalid shift, array boundsRun-time checks inserted by the compiler.
lockdep
CONFIG_PROVE_LOCKING
Lock-order violation (AB-BA), wrong lock use in interrupt contextMaintains the “before–after” graph among lock classes; on seeing a cycle, it warns before the deadlock actually happens.
kmemleak
CONFIG_DEBUG_KMEMLEAK
Memory leakScans memory like a garbage collector; reports allocated blocks that no pointer points to.

A typical KASAN report begins with two lines:

BUG: KASAN: slab-use-after-free in mydrv_release+0x54/0x90
Read of size 8 at addr ffff888012a4c010 by task cat/1432

The first line gives the type of the bug (slab-use-after-free: an access to a freed slab object) and its location: the instruction at byte 0x54 of the function mydrv_release. The second line gives the size and address of the access and which task made it: process 1432 of the cat command made an 8-byte read. The rest of the report brings two stack traces showing where the object was allocated and where it was freed; the object's lifetime can be read off from them.

The checkers are costly. KASAN slows the kernel down several times over and sets aside about one-eighth of memory for the shadow. KCSAN and lockdep also add noticeable overhead. They are therefore enabled in development, testing, and continuous-integration kernels. In production systems, the sampling, low-cost KFENCE can be used: it checks only occasionally chosen allocations.

14.8.4Code trace: KASAN shadow memory

Definition 14.24

Shadow memory is the 1 byte of state that KASAN keeps for every 8-byte region of memory. If the value is 0, all 8 bytes of the region are valid. A value k between 1 and 7 means that only the first k bytes are valid. Negative values mean a red zone or freed memory.

The check KASAN makes before every access looks, in simplified form, like this:

/* 1 shadow byte per 8-byte region:
   0: all valid, 1..7: first k bytes,
   < 0: redzone or freed */
void kasan_check(void *a, int size) {
    int8_t s = *(int8_t *)(((uintptr_t)a >> 3)
                           + SHADOW_OFS);
    if (s == 0) return;            /* fast path */
    if ((int)((uintptr_t)a & 7) + boy - 1 >= s)
        report(a, s);
}
/* p = kmalloc(13); p[3]; p[12]; p[13]; */
/* kfree(p); p[0]; */

The function first finds the shadow byte. The address is shifted right by 3 bits, that is, divided by 8, and a fixed offset is added to the result. If the shadow byte is 0, the whole region is valid and the check ends with a single comparison. This is the fast path, and the great majority of accesses go through it. If the value is not zero, the position of the access's last byte within the region is computed: (a & 7) + size - 1. If this position is greater than or equal to the shadow value, the access spills beyond the valid bytes and a report is produced. It matters that the comparison is signed: because the position is converted to an integer with (int), s is also compared as a signed value. A negative shadow value then satisfies this condition at every position; Linux KASAN also makes this check with a signed byte. Without the cast, the comparison would become unsigned because of uintptr_t, −5 would turn into a very large number, and freed memory would never be reported.

In the scenario, p = kmalloc(13) is called. The kernel's allocator gives a 16-byte slot for a 13-byte request. The shadow is set up as follows: the first 8 bytes are fully valid (0); the first 13 − 8 = 5 bytes of the second region are valid (5); the region after it is a red zone (0xfc, that is, −4). Then p[3], p[12], and p[13] are read in turn; after that come kfree(p) and p[0] (Table 14.16).

Table 14.16: The KASAN check. One-byte reads (size = 1).
AccessRegion (a >> 3)Shadow s(a & 7) + size − 1Result
p[3]00—fast path, valid
p[12]1544 ≥ 5 is false, valid
p[13]1555 ≥ 5, report
kfree(p)0, 10xfb (−5)—shadow is marked “freed”
p[0]0−500 ≥ −5, report (use after free)
memory p[0..23]048121620shadow0x000x050xfc (-4)p[13]: 5 ≥ 5 → report
memory p[0..23]048121620shadow0xfb (-5)0xfb (-5)0xfc (-4)p[0]: s = −5 < 0 → report
Figure 14.35: (a) p[13]: one byte past the end of the array; because 5 ≥ 5, a report is produced. (b) After kfree(p), the object's shadow is 0xfb; the read of p[0] is reported as a use after free.

p[12] is the last valid byte of the 13-byte object and passes without trouble. p[13], however, is one byte past the end of the array. In a real kernel this byte might belong to the slot's padding or to another object; without KASAN the bug would stay silent. KASAN reports it at the first invalid access.

kfree(p) marks the object's shadow as 0xfb (freed). The slot is held in quarantine for a while; if it were reused immediately, the new object's shadow would be valid and an access through the old pointer would be hidden. When p[0] is read, the shadow is −5, and the report comes with the stack traces of where the object was allocated and freed.

Common mistake

Thinking that KASAN catches only code that crashes. KASAN's value is just the opposite: the read of p[13] gives no symptom at all on a kernel without KASAN. The checker catches, at the first moment, a bug that would have stayed silent. Another mistake is forgetting multi-byte accesses: a 4-byte read can spill into invalid bytes even if its start address is valid. That is why the formula has the term size - 1.

14.8.5Code trace: the lockdep lock-order graph

The most common cause of deadlocks is two locks being taken in opposite orders in different places. If one thread holds A and wants B while another holds B and wants A, the two may wait forever. lockdep finds this situation before the deadlock occurs.

Definition 14.25

lockdep is the Linux kernel's lock validator. It tracks lock classes, not lock instances, and accumulates the relation “L was acquired while H was held” as an edge H → L in a directed graph. If a new edge closes a cycle in the graph, it warns of a possible deadlock.

void lock_acquire(task *t, int L) {
    for (int i = 0; i < t->n; i++) {
        int H = t->held[i];
        if (path_exists(L, H))   /* L → … → H */
            warn("possible deadlock", H, L);
        add_edge(H, L);    /* H before L */
    }
    t->held[t->n++] = L;
}
void lock_release(task *t) { t->n--; }
/* T1: A,B   T2: B,C   T3: C,A */

lock_acquire is called when a task acquires lock L. For each lock H that the task is holding at that moment, two things are done. First, the graph is checked for a path from L to H. If such a path exists, then somewhere H has been acquired (perhaps indirectly) while L was held, and now the reverse is being done: a warning is given. Then the edge H → L is added. Finally L is put in the list of held locks. lock_release removes the last lock from the list.

Three tasks run at different times: T1 takes A and then B, T2 takes B and then C, T3 takes C and then A (Table 14.17).

Table 14.17: Trace of lockdep.
EventHeldPath checkEdge addedGraph
T1: acquires A—loop does not run—empty
T1: acquires BAB → … → A? noneA → BA → B
T2: acquires C (while holding B)BC → … → B? noneB → CA → B → C
T3: acquires C—loop does not run—same
T3: acquires A (while holding C)CA → B → C exists: warningC → AA → B → C → A (cycle)
ABCheld:C, AA → B → C → A: cycle!
Figure 14.36: T3 asks for A while holding C. The graph has the path A → B → C; the new edge C → A closes a cycle and lockdep warns.

The three tasks never ran at the same time, and no real deadlock occurred. But if one day T1 holds A, T2 holds B, and T3 holds C at once, each waits for the next one's lock: T1 for B, T2 for C, T3 for A. This circular wait is a deadlock. lockdep shows it in a single run, before it happens. Its power comes from this: it turns a rare, timing-dependent bug into a deterministic graph check.

Common mistake

Looking only for the two-lock AB-BA order. The cycle in the example consists of three locks, and no task takes two locks in reverse order: T1 takes A–B, T2 takes B–C, T3 takes C–A. The problem is seen only when the three relations are combined. This is why lockdep's path search in the graph is necessary.

14.8.6Fuzzing: the syzkaller loop

Definition 14.26

Fuzzing means looking for crashes and bugs by running a program on a great many random or semi-random inputs. In coverage-guided fuzzing, inputs that open up a new code path are saved and become seeds for later attempts.

The most productive bug finder for the Linux kernel is syzkaller (Figure 14.37). The loop works in six steps.

  1. Descriptions. syzkaller knows the signatures of the system calls from syzlang descriptions: which argument is a file descriptor, which is a flag, which is a pointer. The corpus is initially empty or consists of seed programs.
  2. Generation and mutation. The generator picks a program from the corpus and modifies it, or produces a new one; for example openat → ioctl → mmap → close. Because the arguments are chosen to suit their types, the calls are not immediately rejected with EINVAL.
  3. Execution. The program runs in QEMU virtual machines running a test kernel with KASAN, KCSAN, and lockdep enabled. Even if the VM crashes, the host is unaffected; syz-manager restarts the VM.
  4. Coverage. KCOV records the basic blocks (PC values) passed in the kernel. This feedback turns random trial into a guided search.
  5. Corpus. A program that opens a new code path is added to the corpus and becomes a seed for later mutations. The loop turns without stopping, with hundreds of programs per second on every VM.
  6. Report. If a crash or a KASAN report arrives, syzkaller reproduces the program, reduces it to its smallest form, and often produces a C reproducer. syzbot reports this to the developers automatically.
corpusprograms that open coveragegenerate / mutatesyzlang call descriptionsrun in a QEMU VMKASAN-enabled test kernelKCOV coveragewhich blocks ran?crash reportreproduce, minimizeprogramnew coverage
Figure 14.37: The syzkaller loop: corpus, generation and mutation (syzlang call descriptions), execution in a QEMU VM on a KASAN-enabled test kernel, KCOV coverage feedback. If a crash occurs, it is reproduced, minimized, and reported.

The fuzzer and the checker complement each other. A fuzzer alone sees only crashes. A bug that corrupts memory but does not crash looks, to the fuzzer, like a successful run. Checkers such as KASAN make these silent corruptions visible at the first invalid access and turn them into crashes. This is why syzkaller is run with a KASAN-enabled kernel.

14.8.7Observation and tracing tools

Once a bug has been found, you need to see inside the system to understand its cause. Linux offers tools layer by layer for this (Table 14.18).

Table 14.18: Observation and tracing tools.
ToolWhat it providesExample
printkLog levels 0 (EMERG) … 7 (DEBUG); written to a ring buffer, and those above the threshold are printed on the consolepr_warn("queue full: %d\n", n);
dmesgReads the ring buffer; if kernel.dmesg_restrict=1, only holders of CAP_SYSLOG can read it (prevents address leaks)dmesg -w --level=err,warn
dynamic debugTurns on pr_debug lines at run time without recompilingecho 'module e1000e +p' > …/dynamic_debug/control
ftraceIn-kernel tracer: function and function-graph tracing, tracepoint events (tracefs)trace-cmd record -p function_graph -g vfs_read
perfHardware counters and sampling profiler: hot spots, cache misses, scheduler latencyperf record -g -- ./app, perf report
eBPF / bpftraceSmall programs that pass the verifier are attached to kprobes and tracepoints; safe observation in productionone-line example in the text
kdump / crashOn a panic, switches to a backup kernel with kexec and saves a memory dump (/proc/vmcore); the dump is examined offline latercrash vmlinux vmcore

With bpftrace, a one-line program shows live which process is opening which file on the system:

# which process opens which file?
bpftrace -e 'tracepoint:syscalls:sys_enter_openat { printf("%s %s\n", comm, str(args.filename)); }'

The program attaches to the sys_enter_openat tracepoint. It runs every time an openat system call begins and prints the process name (comm) and the name of the file to be opened. There is no need to recompile the kernel or reboot the machine; because the program passes the verifier, it can be used safely even on a running production system.

The general rule in choosing a tool is observation before guessing: logs and traces let you form a hypothesis. But a heavy printk can change the timing and hide a race bug. Low-overhead tracers, ftrace and eBPF, are therefore preferred.

14.8.8Kernel debugging with QEMU and gdb

Sometimes traces are not enough and the kernel must be run step by step. The easiest way is to run the kernel in QEMU and attach gdb from outside.

# terminal 1: -s → gdb server :1234
#             -S → CPU halted at start
qemu-system-x86_64 -kernel bzImage \
  -append "console=ttyS0 nokaslr" \
  -nographic -s -S
# terminal 2
gdb vmlinux
(gdb) target remote :1234
(gdb) hbreak start_kernel
(gdb) continue
(gdb) bt
(gdb) lx-dmesg  # kernel gdb script

In the first terminal, QEMU starts the kernel. The -s option opens a gdb server on port 1234; -S halts the CPU at the very beginning, so that one can attach before even the first instruction. console=ttyS0 redirects the kernel's output to the serial line, that is, to the terminal. nokaslr turns off kernel address space randomization, so that the symbols in gdb match the real addresses. In the second terminal, gdb is opened with the uncompressed vmlinux file that contains symbol information (CONFIG_DEBUG_INFO). target remote :1234 connects to QEMU. hbreak start_kernel puts a hardware breakpoint at the kernel's entry point in C. continue runs up to it, and bt shows the call stack. lx-dmesg is one of the kernel's own gdb scripts and prints the log buffer. The same session can also be set up on real hardware over a serial line with kgdb (kgdboc=ttyS0,115200).

In a real bug, the first thing to look at is the oops message:

BUG: kernel NULL pointer dereference,
     address: 0000000000000010
Oops: 0000 [#1] PREEMPT SMP NOPTI
CPU: 2 PID: 1432 Comm: cat
Tainted: G           O  6.12.0
RIP: 0010:mydrv_read+0x2a/0x80 [mydrv]
Call Trace:
 vfs_read+0xa4/0x2f0
 ksys_read+0x63/0xe0
 do_syscall_64+0x82/0x170

The message is read line by line. The first line gives the type of the bug: a NULL-pointer access at address 0x10. This is typically an access, through a NULL structure pointer, to a field 16 bytes from the start of the structure. CPU: 2 PID: 1432 Comm: cat says on which core and by which process the bug was triggered. Tainted: G O shows that the kernel is “tainted”; O means an out-of-tree module is loaded. RIP: mydrv_read+0x2a/0x80 is the location of the faulty instruction: 0x2a bytes from the start of the function mydrv_read, whose size is 0x80. scripts/faddr2line finds the line in the source file from this information. The call trace is read from bottom to top: do_syscall_64 → ksys_read → vfs_read → the driver. That is, a read system call came through the VFS to the driver and crashed in the driver.

An oops kills only that process; the system may keep running, but it is no longer trustworthy. The setting panic_on_oops=1 turns an oops directly into a panic. In the Windows world the counterpart is WinDbg: debugging is done in kernel mode over a network, USB, or a virtual machine, and blue-screen dumps are examined with !analyze -v. Driver Verifier (verifier.exe) stresses drivers with special-pool, IRQL, and resource-leak checks and so catches bugs early.

14.8.9Hunting regressions: git bisect

If a bug is absent in v6.11 and appears in v6.12, there is a systematic way to find the change that brought it. The commits between the two releases form a sequence, and after some point in the sequence the bug is present. Finding this point is a binary-search question.

Definition 14.27

A regression is the breaking of a feature that used to work correctly after a new change. git bisect is the command that finds the first commit that brought in the bug by binary search between a known good and a known bad commit.

git bisect start
git bisect bad v6.12
git bisect good v6.11
# #500: build, boot, test
git bisect bad
git bisect good   # #250
git bisect good   # #375
git bisect bad    # #437
git bisect run ./test.sh
git bisect reset

The commands do the following. git bisect start begins the search. bad v6.12 and good v6.11 declare the two ends. Git checks out the commit in the middle of those between them. At each step the kernel is built, booted, and tested; depending on the result, git bisect bad or git bisect good is entered. After some point the testing can be left to a script: git bisect run ./test.sh carries out the remaining steps by itself. When it finishes, git bisect reset returns to the starting branch.

Example 14.12

There are 1000 commits between v6.11 (good) and v6.12 (bad), and the first bad commit is #412. At each step Git tests the middle of the range, ⌊(good + bad) / 2⌋. Which commits are tested?

  1. #500. The bug is present: bad. The first bad commit is #500 or earlier; candidate 500.
  2. #250. The bug is absent: good. The first bad commit is between 251 and 500; candidate 250.
  3. #375. Good; candidates 376–500, that is, 125.
  4. #437. Bad; candidates 376–437, that is, 62.
  5. git bisect run. The script carries out the rest: 406 good, 421 bad, 413 bad, 409 good, 411 good, 412 bad.
  6. Result. “#412 is the first bad commit.” 10 tests in total.
first bad commit: #412v6.11 · goodv6.12 · badfound in 10 tests = ⌈log₂ 1000⌉
Figure 14.38: git bisect: 1000 commits between v6.11 (good) and v6.12 (bad). Each test halves the candidate range; the first bad commit, #412, is found in 10 tests.

Each answer halves the number of candidates: 1000 → 500 → 250 → 125 → 62 → … The number of tests needed therefore grows with the logarithm of the number of commits.

Theorem 14.2 (Test bound of binary search)

Among n candidate commits, the first bad commit is found by binary search in at most ⌈log₂ n⌉ tests.

For 1000 commits, ⌈log₂ 1000⌉ = 10, because 2⁹ = 512 < 1000 ≤ 1024 = 2¹⁰. Even with a million commits, only ⌈log₂ 10⁶⌉ = 20 tests would be needed. For 12,000 commits the bound is 14: 2¹³ = 8192 < 12,000 ≤ 16,384 = 2¹⁴.

git bisect run looks at the script's exit code. If the script exits with 0, the commit is considered good; if it exits with a code between 1 and 127 (except 125), bad. 125 has a special meaning: “this commit cannot be tested, skip it.” For example, if the kernel does not build at that commit, the script returns 125 and git tries a neighboring commit. For performance regressions, the measurement is noisy, so the script should average several measurements.

Common mistake

Returning 1 from the script for a commit that cannot be tested. If a commit that does not build is counted as “bad,” the binary search goes into the wrong half and in the end the wrong commit is blamed. For a version that does not build or does not boot, the right answer is 125.

14.9Trends in operating systems

Because operating systems live long, today's decisions must also serve the hardware and applications of decades from now. This part gathers the trends that most affect design today.

14.9.1The big picture

Table 14.19: Trends and their effects on the operating system.
TrendEffect on the operating system
Virtualization and the cloudThe guest kernel cooperates with the hypervisor through virtio; in a multi-tenant cloud, the isolation boundary moves to the hypervisor. Containers are light but weakly isolated; micro-VMs (Firecracker) offer VM isolation and millisecond startup.
Multicore chipsScalable locks, RCU, NUMA awareness, heterogeneous cores
Wide address space64 bits, 5-level page tables; single-address-space system ideas
Seamless data accessTransparent access among the network, cloud storage, and local disk; NVMe, CXL memory
Battery-powered systemsDVFS, “finish fast and sleep” (race-to-idle), Android Doze, energy-aware scheduling (EAS)
Embedded and sensor nodesSmall real-time kernels: Zephyr, FreeRTOS, Contiki-NG; kilobytes of memory
Safe languages and programmable kernelsRust in Linux (since 6.1), eBPF and sched_ext, unikernels

Networking, parallel and distributed systems, and multimedia, which were separate trends in Tanenbaum's older editions, are now ordinary parts of every system. They are therefore considered not as separate trends but within the relevant rows of the table.

The virtualization row is a redrawing of the isolation–performance trade-off. In a multi-tenant cloud, the code of different customers runs on the same machine, and the real boundary between them is no longer the operating-system kernel but the hypervisor. Containers are light and fast because they share the same kernel, but a hole in the kernel affects all containers. Micro-VMs such as Firecracker choose a point between the two worlds by giving each workload a separate, very small virtual machine.

In battery-powered systems the goal is energy. DVFS (dynamic voltage and frequency scaling) changes the processor's voltage and frequency according to the load. In the “finish fast and sleep” strategy, the work is finished at top speed and the processor is immediately put into a deep sleep state. Android Doze defers applications' background work to batched windows while the screen is off.

14.9.2Many cores and wide address spaces

Today servers have 128–192 cores per socket, and phones have chips mixing big and little cores (big.LITTLE). A single big kernel lock does not work at this scale: if all cores wait for the same lock, every added core is wasted. The tools needed are fine-grained locks, RCU (read-copy-update), in which readers take no lock at all, and separate data structures for each core. With heterogeneous cores, the scheduler also decides which kind of core each job goes to.

64-bit addresses open up new possibilities too (Figure 14.39).

32 bits2³² B = 4 GiB48 bits (4-level page table)2⁴⁸ B = 256 TiB57 bits (5-level, LA57)2⁵⁷ B = 128 PiBvirtual address space (bar length = number of address bits; each bit doubles the size)
Figure 14.39: Virtual address space sizes: 32 bits 4 GiB, 48 bits (4-level page table) 256 TiB, 57 bits (5-level, LA57) 128 PiB. Each bit doubles the size.
Example 14.13

How large are 48-bit and 57-bit virtual address spaces, and how do these bit counts follow from the page-table levels?

  1. 48 bits. 2⁴⁸ B = 2⁸ × 2⁴⁰ B = 256 TiB.
  2. 57 bits. 2⁵⁷ B = 2⁷ × 2⁵⁰ B = 128 PiB.
  3. Levels. In a 4 KB page the offset is 12 bits. Each table level has 512 entries and resolves 9 bits. 4 levels: 4 × 9 + 12 = 48 bits; 5 levels: 5 × 9 + 12 = 57 bits.

In an address space this wide, it becomes possible to map all files into memory (mmap) or to build systems in which all processes share a single address space. The price is a deeper page-table walk: in a 5-level table, a TLB miss needs five memory reads. A wide address space also increases the pressure on the TLB.

14.9.3Rust, eBPF, and unikernels

The last trend concerns the language in which the kernel is written and in what form. Three developments stand out.

The kernel in Rust. Rust support entered the mainline with Linux 6.1 (December 2022), followed by the first Rust drivers. The aim is to prevent memory bugs such as use after free and overflow at compile time. A significant share of kernel vulnerabilities are bugs of this kind. Rust's ownership and borrowing rules let the compiler check an object's lifetime. This means preventing, while the code is being compiled, the bugs that KASAN catches at run time. The Windows kernel also has components written in Rust.

eBPF. Extending the kernel with small verified programs without recompiling it; it is used for tracing, networking (XDP), security, and scheduling (sched_ext). The idea of the extensible system has gone into production at large scale for the first time with eBPF.

Unikernel. This is the cloud version of the exokernel's library operating system (libOS) idea. A single application is built, together with the operating-system libraries it needs, as a single image and runs in a single address space on a hypervisor (Figure 14.40). MirageOS and Unikraft are examples of this approach.

Traditional stackApplicationlibrariesgeneral-purpose operating systemhypervisorUnikernelApplication + only the neededOS libraries, single address spacesingle image of MBs, boots in mshypervisor
Figure 14.40: In the traditional stack, the application, the libraries, and a general-purpose operating system sit on top of the hypervisor. A unikernel combines the application with only the operating-system libraries it needs into a single image, with one address space, of a few megabytes; booting takes milliseconds.

The gain of a unikernel is smallness and speed. Because the image contains only the code that is needed, the attack surface is small and booting takes milliseconds. Because there is no user–kernel transition, system calls become ordinary function calls. It suits single-application microservices. The price is harder debugging and the impossibility of running more than one application in the same image. Isolation is now provided by the hypervisor.

14.10Summary

  • Eight factors make operating-system design hard: sheer size, concurrency, hostile users, sharing despite isolation, long life, generality, portability, and backward compatibility.
  • The four basic goals of an operating system are to define abstractions, to provide primitive operations (system calls) on those abstractions, to provide isolation, and to manage the hardware.
  • A good interface is simple, complete, and efficient. The kernel holds few, general calls, and the library holds convenience functions: the six exec functions reduce to a single execve. The number of system calls is ≈ 12 in seL4 and ≈ 460 in Linux.
  • In algorithmic code the program determines the flow; in event-driven code, external events do. The event loop is built around a blocking get_message; one long handler freezes the whole interface. In UNIX everything is a file, in Windows everything is an object.
  • The basic trade-off in system structure is between isolation and performance. A monolithic kernel is fast but has no fault isolation; a microkernel contains faults but pays IPC on every request. The layer order follows from the dependencies. eBPF provides safe extension thanks to the verifier.
  • A mechanism determines how something is done, a policy what is done; sched_ext loads the whole policy as an eBPF program. Orthogonality combines separate concepts independently: the clone flags give every combination between fork and pthread_create.
  • Two-level naming maps an external name to an internal number and lets an object be moved without changing its name. Resolving /usr/ast/mbox without a cache needs 7 disk reads. Operating systems generally choose late binding.
  • Static tables are simple but cannot grow when full; dynamic structures are flexible but need an allocator and locking. Implementation is done bottom-up, design top-down. Synchronous communication is easy, asynchronous communication scales.
  • Techniques: gathering hardware-dependent code in a few files, indirection, reuse, reentrancy (no shared static state; strtok_r), brute force, and checking for errors first.
  • Measurement decides what to speed up; Amdahl's law gives the limit of the gain. The space-time trade-off (bit-count table, color palette), caches (always correct), hints (may be wrong, verified before use), locality, and optimizing the common case (futex) are the classic techniques.
  • Brooks's law: adding staff to a late project makes it later; the number of communication paths grows quadratically as n(n − 1)/2. Writing code is only a sixth of the work, and there is no silver bullet.
  • Kernel testing is layered with KUnit, kselftest, and LTP. KASAN, KCSAN, UBSAN, lockdep, and kmemleak make silent bugs visible; syzkaller triggers them with coverage-guided fuzzing. ftrace, perf, and eBPF provide observation, QEMU and gdb step-by-step debugging, and git bisect hunts regressions in at most ⌈log₂ n⌉ tests.
  • Trends: virtualization and the cloud, many cores, wide address spaces, energy efficiency, embedded systems, Rust, eBPF, and unikernels.

14.11Key terms

  • abstraction
  • primitive
  • isolation
  • system call
  • simplicity, completeness, efficiency
  • event-driven code
  • event loop
  • monolithic kernel
  • microkernel
  • layered system
  • exokernel
  • extensible system
  • eBPF (extended Berkeley Packet Filter)
  • kernel thread
  • policy / mechanism
  • orthogonality
  • external name, internal name
  • binding time
  • stub
  • synchronous / asynchronous communication
  • conditional compilation
  • indirection
  • reentrancy
  • brute force
  • space-time trade-off
  • cache
  • hint
  • locality
  • futex (fast userspace mutex)
  • Brooks's law
  • shadow memory
  • fuzzing
  • regression
  • unikernel

14.12Test Yourself

  1. The handlers in an event loop keep a counter: KEY adds 1, CLICK adds 10; TIMER resets the counter if it is greater than 10. If the events arrive in the order CLICK CLICK TIMER KEY KEY KEY TIMER QUIT, what is the counter when the loop ends?

    Answer

    3. The counter goes 10, 20, 0 (20 > 10), 1, 2, 3. At the last TIMER, 3 > 10 does not hold, so the counter does not change. At QUIT, get_message returns 0 and the loop ends.

  2. The path cache has the entry /var → 30 and no other relevant entries. How many disk reads does resolve() count for /var/log/syslog? How many would it count if the cache were completely empty? What are the totals if the file's own i-node is also read?

    Answer

    With /var in the cache, it stops at k = 1; log and syslog are resolved from disk: 2 + 2 = 4 reads. With the cache empty, k drops to 0 and the three components are resolved from the root: 6 reads. If the file's i-node is counted too, it becomes 5 and 7.

  3. With the nib table, which two entries does bit_cnt(0xE3) read, and what does it return?

    Answer

    0xE3 = 1110 0011. The low half is 3 and the high half is E. nib[3] = 2 and nib[E] = 3; the result is 5. The loop version reaches the same result in eight iterations.

  4. A 1920 × 1080 image is stored (a) with 24-bit RGB per pixel, (b) with a 4-bit index per pixel and a 16-color palette (3 bytes per color). What are the sizes and the ratio?

    Answer

    (a) 1920 × 1080 × 3 = 6,220,800 bytes. (b) Two pixels fit in one byte: 1920 × 1080 / 2 = 1,036,800 bytes, and the palette is 16 × 3 = 48 bytes; the total is 1,036,848 bytes. The ratio is about 6. The price is a table lookup for every pixel and the limit of 16 colors.

  5. 40% of a program's running time is spent in the function compress(). One option is to make this function 4 times faster, the other to make the rest of the program 2 times faster. Which pays off more?

    Answer

    They are equal. In the first, the time becomes 60 + 40/4 = 70; in the second, 40 + 60/2 = 70; the speedup in both cases is 100 / 70 ≈ 1.43. By Amdahl's law: 1 / (0.6 + 0.1) = 1 / (0.4 + 0.3) ≈ 1.43. How much a part can be sped up matters as much as its share.

  6. A team of 12 adds 4 more people to a late project. From how many to how many does the number of communication paths rise? What do we see when we compare this with the increase in headcount?

    Answer

    It rises from 12 · 11 / 2 = 66 paths to 16 · 15 / 2 = 120 paths: about 1.82 times. The headcount has grown only 16 / 12 ≈ 1.33 times. Training the newcomers also takes time from the existing team; these are the two causes of Brooks's law.

  7. For git bisect, #0 is good and #64 is bad; the first bad commit is #45. At each step Git tests ⌊(good + bad) / 2⌋. Which commits are tested? In a range of 5000 commits, how many tests are needed at most?

    Answer

    #32 good, #48 bad, #40 good, #44 good, #46 bad, #45 bad: 6 tests, ⌈log₂ 64⌉ = 6. For 5000 commits, ⌈log₂ 5000⌉ = 13, because 2¹² = 4096 < 5000 ≤ 8192 = 2¹³.

  8. p = kmalloc(20) yields a 32-byte slot. What do the KASAN shadow bytes become? Which of the 4-byte reads p[8], p[16], and p[18] is reported?

    Answer

    The shadow: 0, 0, 4, 0xfc. The first two regions are fully valid, the first 20 − 16 = 4 bytes of the third region are valid, and the fourth is a red zone. p[8]: shadow 0, fast path. p[16]: (16 & 7) + 4 − 1 = 3, 3 ≥ 4 is false, valid. p[18]: 2 + 4 − 1 = 5 ≥ 4, report: the read covers bytes 18–21, and 20 and 21 lie outside the object.

  9. Four tasks run at different times: T1 takes A and then B, T2 takes C and then D, T3 takes B and then C, T4 takes D and then A. At what moment does lockdep warn? What would happen if T4 took A and then D?

    Answer

    The edges are A → B, C → D, B → C in turn. When T4, holding D, asks for A, the path A → B → C → D exists, and the new edge D → A closes a cycle: the warning comes when T4 takes A. If T4 took A first and then D, the edge A → D would be added; no cycle would form and no warning would be given.

  10. Which of the following are mechanisms and which are policies? (a) The cpufreq driver changing the processor frequency, (b) the schedutil governor choosing the frequency according to load, (c) the LRU replacement rule, (d) the MMU walking the page table on a TLB miss, (e) SELinux rules.

    Answer

    Mechanisms: (a) and (d); they determine how something is done and are independent of which decision is made. Policies: (b), (c), and (e); they decide what is to be done and can be changed on top of the same mechanism.

14.13Further reading

  • B. W. Lampson, “Hints for Computer System Design”, ACM SOSP, 1983: the classic collection of short pieces of advice on interfaces, implementation, and performance; the “make the common case fast” rule and the idea of a hint come from here.
  • F. P. Brooks Jr., The Mythical Man-Month, 20th anniversary edition, 1995: Brooks's law, the surgical team, the second-system effect, and the essay “No Silver Bullet” are collected in a single book.
  • U. Drepper, “Futexes Are Tricky”, 2011: explains step by step how to write a futex-based lock correctly, why the states 0–1–2 are used, and the common mistakes.
  • Linux kernel documentation, docs.kernel.org/dev-tools/: gives, in the kernel's own documentation, how to enable and use KASAN, KCSAN, UBSAN, kmemleak, KUnit, and kselftest.

14.14References

  1. A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th ed. (2014) / 5th ed. (2023), Pearson — Chapter 12: Operating System Design.
  2. B. W. Lampson, “Hints for Computer System Design”, ACM SOSP, 1983 (and the 2020 update, “Hints and Principles for Computer System Design”).
  3. F. P. Brooks Jr., The Mythical Man-Month: Essays on Software Engineering, 20th anniversary edition, Addison-Wesley, 1995 — including “No Silver Bullet” (1986).
  4. J. H. Saltzer, M. F. Kaashoek, Principles of Computer System Design: An Introduction, Morgan Kaufmann, 2009.
  5. D. R. Engler, M. F. Kaashoek, J. O'Toole, “Exokernel: An Operating System Architecture for Application-Level Resource Management”, SOSP 1995.
  6. G. Klein et al., “seL4: Formal Verification of an OS Kernel”, SOSP 2009; J. N. Herder et al., MINIX 3 reliability studies.
  7. Linux kernel documentation: Rust (docs.kernel.org/rust), BPF, and sched_ext; H. Franke et al., “Fuss, Futexes and Furwocks”, 2002.

Related pages: Chapter 14 slides · © Sercan Külcü. All rights reserved.