Operating Systems · Lecture Notes
Chapter 15: Linux
How do the general concepts of the course (processes, threads, scheduling, virtual memory, file systems, and protection) look in a real system? This chapter treats Linux as a case study. It does not redefine the concepts; it concentrates on the structures and decisions specific to Linux. It starts with the history from UNIX to Linux and with how the shell builds pipelines. Then it descends into the kernel: task_struct, the clone() flags, signal delivery, fair scheduling from CFS to EEVDF, four- and five-level page tables, the buddy and SLUB allocators, the page cache, and the OOM killer. For I/O and file systems it follows device files, blk-mq, the VFS, and ext4 journaling. The security section covers permission arithmetic, capabilities, and namespaces and cgroups, the foundation of containers. The chapter closes with Android.
Learning outcomes
- History and family
- Place the line from UNIX through BSD, MINIX, GNU, and Linux; distributions, the release model, and Android.
- Interfaces and the shell
- Distinguish the library, system-call, and kernel layers; trace how redirections and pipelines are built with
pipe,fork,dup2, andexec. - Processes and scheduling
- Explain the kernel steps of
forkandexecve, signal delivery,task_struct, theclone()flags, and NPTL; compute eligibility and virtual deadlines in EEVDF. - Memory
- Interpret the address-space layout and VMAs, the four-level page-table walk, zones, the buddy and SLUB allocators, the page cache, and the OOM killer.
- I/O and files
- Recognize device files, blk-mq, and sockets; explain the VFS objects, ext4's extent and journaling design, the link count, and
/proc. - Security
- Compute rwx, setuid, and umask; apply the first-matching-class rule; recognize capabilities, namespaces, cgroups, seccomp, LSMs, and the Android sandbox.
15.1The roots of Linux
Throughout the course, the concepts of process, thread, scheduling, virtual memory, file system, and protection were presented in general terms. This last chapter is a case study: it looks at how the same concepts are implemented in a widely used real system. The system is Linux, the most widely deployed kernel, from servers to phones and from supercomputers to embedded devices. Its source code is open, so the name and field of every structure can be read directly. For that reason this chapter does not redefine concepts. It focuses on Linux-specific detail: task_struct, the clone() flags, the EEVDF scheduler, the SLUB allocator, namespaces, and cgroups.
15.1.1From UNIX to Linux
The story of Linux begins with UNIX (Figure 15.1). In 1969 Ken Thompson and Dennis Ritchie wrote a small operating system on a PDP-7 at Bell Laboratories. The system was ported to the PDP-11 in 1971, and in 1973 the kernel was rewritten in C. That step was unprecedented: operating systems had always been written in assembly language. UNIX written in C could be moved to a new machine simply by porting the compiler. Portability is the real reason UNIX spread.
AT&T, bound by an antitrust decree, was not allowed to sell computers. It licensed the source code to universities for a small fee. The University of California at Berkeley improved this code and distributed it as BSD (Berkeley Software Distribution). Virtual memory and the TCP/IP stack entered UNIX through BSD. AT&T's own line became System V. In the 1980s every vendor shipped its own UNIX: SunOS, AIX, HP-UX, Xenix. As these versions diverged, running one program on all of them became hard. In 1988 the IEEE published the POSIX standard. POSIX is not an implementation; it defines the common interface of system calls and library functions.
The second half of the 1980s was spent searching for a free UNIX. Richard Stallman started the GNU project in 1983. The goal was a completely free, UNIX-compatible system. The project produced the compiler (GCC), the shell (bash), the C library, and hundreds of tools, but it never finished a kernel. In 1987 Andrew Tanenbaum wrote MINIX for teaching. MINIX was a small microkernel, and its code was published together with a textbook. In 1991 Linus Torvalds, a student at the University of Helsinki, began developing his own kernel on top of MINIX. Linux 0.01 was released the same year. In 1992, with version 0.12, Torvalds moved the kernel to the GPL license. The GPL requires that modified code be distributed with the same freedoms. When the GNU tools and the Linux kernel were combined, a usable, completely free system emerged. The first distributions, such as Slackware and Debian, appeared in 1993.
Linux contains no UNIX code. It implements the POSIX interface with freshly written code. Its design, however, is the opposite of MINIX's. Torvalds chose a monolithic kernel instead of a microkernel. In 1992 this choice led to a famous e-mail debate between Tanenbaum and Torvalds. Tanenbaum considered the monolithic design obsolete; Torvalds defended simplicity and speed. Today's Linux is monolithic, but it gained flexibility through a modular structure.
Over the next fifteen years the kernel matured. Linux 1.0 appeared in 1994. Version 2.0 (1996) supported multiprocessor machines, that is, symmetric multiprocessing (SMP). The 2.6 series (2003) brought the preemptible kernel and new schedulers. In 2005 the license of BitKeeper, the commercial version-control tool used by kernel developers, became a problem. Torvalds wrote git in a few weeks; most of the software world uses it today. The first Android phone, the HTC Dream, went on sale in 2008. Since version 3.0 in 2011, version numbers carry no technical meaning; they merely grow. The release after 6.19 is 7.0, published in April 2026. Since November 2017, all of the 500 fastest supercomputers in the world run Linux. The 6.x series brought Rust support (6.1), the EEVDF scheduler (6.6), and the extensible scheduler sched_ext together with the real-time patch (6.12).
15.1.2GNU, distributions, and the release model
Strictly speaking, the word “Linux” names only the kernel. What a user installs on a computer is a distribution (Figure 15.2). A distribution adds layers on top of the kernel: the GNU tools and the C library (mostly glibc), the init program that starts the system (today mostly systemd), a package manager, and applications. This is why the name “GNU/Linux” is also used for the complete system. Android uses the same kernel but not the GNU tools; its C library is Bionic.
Distributions are grouped into families by package format (Table 15.1). Members of the same family use the same package manager. Pardus, developed in Türkiye, belongs to the Debian family. Alpine, on the other hand, uses the small musl library instead of glibc and BusyBox tools bundled in a single binary, which is why it is popular for container images.
| Family | Examples | Package format / tool |
|---|---|---|
| Debian | Debian, Ubuntu, Mint, Pardus | .deb / apt |
| Red Hat | Fedora, RHEL, Rocky, Alma | .rpm / dnf |
| Arch | Arch, Manjaro | pacman |
| SUSE | openSUSE, SLES | zypper |
| Lightweight | Alpine (musl + BusyBox) | apk |
The kernel's own release model is regular. When a release is published, a two-week merge window opens. During this period the new features accumulated by the subsystem maintainers are pulled into the mainline tree. Weekly release candidates follow: rc1, rc2, and so on, usually up to rc7. Only bug fixes are accepted in these weeks. A new major release thus appears about every 9–10 weeks. The last major release of each year receives long-term support (LTS): 6.6 (2023), 6.12 (2024), and 6.18 (2025) are such releases. Distributions usually pick an LTS kernel and follow its security patches for years.
15.1.3Design principles
UNIX was designed by programmers for themselves. The principles that come from this origin continue in Linux. The system is simple: it rests on a small number of well-defined concepts, namely the process, the file, and the pipe. It is consistent: a disk file, a terminal, a pipe, and a network socket are all used with the same read and write calls (Figure 15.3). The saying “everything is a file” expresses this consistency. The system is flexible: tools combine over text streams without knowing each other. It shows the programmer little “magic”; a successful command usually prints nothing.
Doug McIlroy, who gave UNIX its pipelines, summed up this thinking in three rules. Each program should do one thing well. Programs should be written to work together. Programs should handle text streams, because text is a universal interface. POSIX standardizes this interface. The same source code can be compiled and run on Linux, BSD, and macOS.
15.2Interfaces and the shell
15.2.1Three interfaces: the journey of a printf
A Linux system can be thought of as a stack of layers (Figure 15.4). Hardware is at the bottom, with the kernel above it. Above the kernel sits the standard C library, and above that the standard utility programs such as the shell, the editor, and the compiler. Users are at the top. There are three interfaces between the layers. The system-call interface lies between the library and the kernel. The library interface consists of the functions that programs call, such as printf, open, and fork. The user interface is the shell and the programs themselves. POSIX defines the library interface, not the system calls. Which function is a system call can vary from system to system.
printf("hello!\n").It is instructive to see these layers by following the trace of a single line. Suppose the program calls printf("hello!\n").
- Application.
printfis not a system call. glibc writes the formatted text into a buffer in user space. If the output is attached to a terminal, the buffer is flushed at the end of the line. - glibc. When the buffer is flushed, glibc's
write(1, buf, 8)wrapper runs. On x86-64 the system-call number is placed in theraxregister; the number ofwriteis 1. The arguments go into therdi,rsi, andrdxregisters. Then thesyscallinstruction executes. - Kernel entry. The CPU switches to kernel mode and jumps to the entry code
entry_SYSCALL_64. The entry code uses the number as an index into thesys_call_tablearray and calls the handler ofwrite. The handler passes to the VFS layer: it finds the object behind file descriptor 1. - Driver. In an interactive session, descriptor 1 is attached to a pseudo-terminal (pty). The tty layer passes the bytes to the terminal emulator. Had the output been redirected to a disk, the path would have gone to the page cache and the block layer.
- Return. The number of bytes written (8) is returned in
rax. Thesysretinstruction switches back to user mode. Had there been an error, the kernel would have returned a negative error code; glibc stores it inerrnoand returns −1 to the caller.
There are about 460 system calls on Linux x86-64. All of them enter through the same door: the number in rax, the arguments in registers, and entry with syscall. Which calls a program makes can be observed with strace.
Assuming every library function is a system call. printf, malloc, opendir, and readdir are library functions. Some make no call at all; others occasionally rely on an underlying call (write, brk/mmap, getdents64). Calling printf 1000 times in a loop may produce only a few write calls, thanks to buffering.
15.2.2Commands and redirection
Most commands on Linux are small, single-purpose programs (Table 15.2). Programs called filters read from standard input and write to standard output, which is why they can be chained in a pipeline. Some names are misleading. touch updates a file's timestamp; if the file does not exist, it creates an empty one. sync writes the kernel's dirty buffers to disk; the tool that synchronizes between two machines is rsync. /proc is not a command but a pseudo file system: cat /proc/meminfo reads the kernel's memory counters. The networking tools have also been renewed: ip addr, ip route, ss, and nft replaced the old ifconfig, route, netstat, and iptables.
| Category | Commands |
|---|---|
| File / directory | ls cd pwd mkdir rm -r cp mv touch find tar |
| Text (filters) | cat less head tail grep sort uniq wc echo |
| Process / system | ps top kill chmod chown df du sync |
| Network | ssh scp ping curl wget traceroute ip ss |
| Information | man uname free lsblk |
Every process finds three open file descriptors when it is born: 0 is standard input, 1 is standard output, and 2 is standard error. Before running the program, the shell can redirect these descriptors to other files:
# redirection: 0 = stdin, 1 = stdout, 2 = stderr
sort < input.txt > output.txt 2> errors.log # < reads, > writes (overwrites)
echo "line" >> log.txt # >> appends
make 2>&1 | tee build.log & # stderr→stdout, pipe, backgroundOn the sort line, the shell sets up sort's descriptor table (Figure 15.5). It connects 0 to input.txt, 1 to output.txt, and 2 to errors.log. Then it runs sort. sort is unaware of the redirection; it simply reads from 0 and writes to 1. > overwrites the file, and >> appends to it. 2>&1 means “copy 1's current target to 2.” The trailing & starts the command in the background.
sort < input.txt > output.txt 2> errors.log.Redirections are applied from left to right. The shell turns each one into a dup2 call. The order therefore changes the result.
The directory /nodir does not exist. Where does the error message go in the commands ls /nodir /tmp > c.txt 2>&1 and ls /nodir /tmp 2>&1 > c.txt?
- First command.
> c.txt: 1 → c.txt.2>&1: 2 is copied from 1's current target, that is, c.txt. Both the listing and the error go to the file. - Second command.
2>&1: 1 is the terminal at that moment, so 2 is also attached to the terminal.> c.txt: only 1 changes. The listing goes to the file, the error to the screen. 2>&1does not create a “link”; it copies the current target. Even if 1 changes afterwards, 2 stays at the old target.
15.2.3The pipeline
A pipeline is a chain of commands in which the output of one program is connected to the input of the next. Consider the line cat log.txt | grep error | sort | uniq -c (Figure 15.6). The shell parses the line and creates 3 pipes and 4 processes. The four processes run at the same time. Each knows only its own standard input and output.
cat log.txt | grep error | sort | uniq -c: seven lines, five matches, five sorted lines, and two counts.cat writes the 7 lines of the file into the pipe. A pipe's buffer in the kernel is bounded; on Linux the default is 64 KiB. If the buffer fills, the writing process blocks, and it continues as the reading process drains the buffer. This is a ready-made kernel solution to the producer–consumer problem. grep reads line by line and forwards the 5 matching lines immediately. A filter is stateless and does not hold the stream back. sort is different. It cannot write even a single line before it sees the end of input (EOF), because the last line may move to the first position in the sorted order. uniq -c counts only consecutive repeats, which is why it needs sort in front of it. The result is two lines: 2 × “error: net” and 3 × “error: disk”.
Assuming uniq merges all repeats. In five unsorted lines (disk, net, disk, net, disk), no line equals the one before it. uniq -c prints five separate lines, each preceded by 1. A Python simulation gives the same result.
15.2.4Code trace: how does the shell build a pipeline?
The shell builds the line ls | wc -l with four system calls: pipe, fork, dup2, and exec. A simplified version of the shell doing this job looks like this:
int fd[2];
pipe(fd); /* 3: read, 4: write */
if (fork() == 0) { /* child 1 */
dup2(fd[1], 1);
close(fd[0]); close(fd[1]);
execlp("ls", "ls", NULL);
}
if (fork() == 0) { /* child 2 */
dup2(fd[0], 0);
close(fd[0]); close(fd[1]);
execlp("wc", "wc", "-l", NULL);
}
/* shell: close both ends */
close(fd[0]); close(fd[1]);
wait(NULL); wait(NULL);The first line of the code declares an array of two elements. pipe(fd) creates a buffer and two ends in the kernel. The kernel always hands out the smallest free descriptor number. Since 0, 1, and 2 are taken, the read end becomes 3 and the write end becomes 4. The first fork creates the child process. The child receives a copy of the parent's descriptor table; both processes point to the same pipe. With dup2(fd[1], 1) the child redirects descriptor 1 to the write end of the pipe. It closes 3 and 4, which are no longer needed. execlp replaces the process image with ls. The descriptor table is preserved across exec. ls writes to 1, unaware of anything, and the data flows into the pipe. The second child does the same job for the read end: dup2(fd[0], 0), closes both ends, and becomes wc -l. Finally the shell closes both ends and waits for the two children.
| Step | Shell 0 1 2 3 4 | Child 1 | Child 2 |
|---|---|---|---|
pipe(fd) | tty tty tty r w | — | — |
1. fork | tty tty tty r w | tty tty tty r w | — |
dup2(4, 1) + two close calls | tty tty tty r w | tty w tty – – | — |
execlp("ls") | same | tty w tty – – (now ls) | — |
2. fork, dup2(3, 0), exec("wc") | tty tty tty r w | same | r tty tty – – |
| The shell closes both ends | tty tty tty – – | same | same |
ls, and the read end only in wc.The two close calls in the second-to-last line look insignificant, but the correct operation of the system depends on them. The reader of a pipe sees EOF only when all write ends are closed. Had the shell not closed 4, the write end would have stayed open. Even after ls finished and closed its own end, wc would assume more data might arrive and wait forever. Since the shell waits for wc, the two would hang together. In the opposite case, when all read ends are closed, a process writing to the pipe receives the SIGPIPE signal and, by default, terminates.
Forgetting to close the extra ends in the children. If the child that runs wc does not close 4, it never sees its own EOF because of the write end it holds itself. The rule is short: every process closes every pipe end it does not use.
15.3The structure of the kernel
15.3.1Components of the monolithic kernel
The Linux kernel is divided into three main components (Figure 15.8). The I/O component manages terminals, the network, and file systems. Memory management runs virtual memory, paging, and the page cache. Process management creates processes and threads, handles signals, and schedules the CPU. The system-call interface sits above all of them, and the interrupts and the dispatcher below. The dispatcher is the code that performs the context switch. The classic 4.4BSD kernel was divided into the same three components.
The I/O component is itself divided into three columns. Character devices pass through terminals and the line discipline. Network devices pass through the socket layer and the protocols. Block devices pass through the file systems, the generic block layer, and the I/O scheduler. The three columns meet at the top in the virtual file system (VFS). All the boxes in the figure run in a single address space, in kernel mode. One component can call another's functions directly; no message passing or context switch is needed. That is what makes Linux monolithic. The price is also clear: a bug in any component, for example an invalid pointer in a driver, can crash the entire kernel.
15.3.2Loadable kernel modules
A monolithic kernel that included the driver for every conceivable device from the start would be very large. Linux solves this problem with modules.
A loadable kernel module (LKM) is an object file with the .ko extension that can be added to and removed from the kernel while the system is running. A loaded module runs in the kernel's address space with kernel privilege.
Most drivers, and some of the file systems and network protocols, are modules. The loading of a module can be followed in six steps (Figure 15.9). As an example, let the Intel network-card driver e1000e be loaded.
- Request. The administrator types
modprobe e1000e. The more common path is automatic loading: when a device is plugged into the system, the kernel generates an event, andudevin user space finds and loads the module that matches the device's ID. - Dependencies.
modprobereads from the file/lib/modules/$(uname -r)/modules.depwhich modules the module needs and loads those first. The more primitiveinsmoddoes not do this; it tries to load the single file it is given. - Copy and signature. The
finit_module()system call copies the module file into kernel memory. The caller must hold theCAP_SYS_MODULEcapability. When Secure Boot is on, the module's signature is verified; an unsigned module is rejected. - Linking. The kernel performs the module's relocations. It looks up every external symbol the module uses in the kernel's symbol table. Only kernel functions exported with
EXPORT_SYMBOLare visible to the module. - Initialization. The module's function marked with
module_initruns. The driver registers itself with the relevant subsystem; for a PCI card this is thepci_register_drivercall. - Matching. The PCI subsystem compares the IDs the driver supports with the devices in the system. For each matching device, the driver's
probe()function is called and a network interface such aseth0comes into being.
modprobe, finit_module(), signature check, relocation and symbol linking, module_init(), and probe().Loaded modules are listed with lsmod and removed with rmmod. The module system makes the kernel flexible but brings no protection. A module is as privileged as the kernel itself. For this reason the right to load modules is tightly controlled.
The kernel source tree passed 40 million lines in early 2025. Most of those lines are drivers. In recent years two innovations have aimed at improving kernel security. The first is Rust. Rust support entered the kernel in 6.1; the first Rust driver, a network PHY driver, was added in 6.8. Rust's type system catches some of the memory errors common in C drivers at compile time. The second is eBPF. eBPF lets small programs written by the user run safely inside the kernel. Before a program is loaded, it passes through a verifier. The verifier does not allow loading until it has proved that the program terminates and accesses only permitted memory. With eBPF, network packets are filtered and kernel events are traced; the kernel's behavior is extended without writing a module.
15.4Processes and threads
15.4.1fork and execve in the kernel
On Linux a new program starts in two steps (Figure 15.10). The shell (PID 501) first copies itself with fork(); the copy receives PID 748 and still runs the shell's code. The copy then replaces its own image with ls using execve(). The PID does not change; what changes is the program the process runs.
fork() produces a new process (same program); execve() produces a new program in the same process.In the kernel, fork() does the following:
- It allocates a new
task_struct, fills it in from the parent's, and assigns a new PID. - It allocates a separate kernel stack for the child. It copies the parent's saved registers, setting only the return-value register to 0 in the child. This is where the “double return” of
forkcomes from. - It copies the page tables and marks writable pages read-only on both sides. This is copy-on-write (COW): a page is copied only when one of them tries to write to it.
- It shares the open files. The child's descriptor table is a copy of the parent's; each entry points to the same
struct fileobject, and the object's reference count is incremented. - It copies the signal handlers, the working directory, and the credentials.
execve(), on the other hand, discards the old image. First it reads the file's ELF header. It drops the mm_struct that describes the process's old address space and builds a new one. It maps the program's code and data segments from the file with mmap; it reads no page immediately. If the file's setuid or setgid bit is set, it prepares the process's new credentials (cred). Finally it sets the program counter. In a dynamically linked program, the first code to run is not the program itself but the dynamic linker ld.so, which maps the shared libraries and jumps to the program's entry point. A successful execve never returns, because the code that called it no longer exists. If it fails, it returns −1. In that case the child traditionally exits with _exit(127); this is where the shell's “command not found” exit status 127 comes from.
Old UNIX systems really copied the process's data and stack segments on fork. Linux copies only the page tables. Since most forks are immediately followed by an exec, very few pages end up being copied. Even if the shell's address space holds thousands of pages, fork takes microseconds.
15.4.2Process-management calls
The life of a process is managed with a few system calls (Table 15.4). clone and clone3 are the general creation calls; fork is a special case of them. The difference between exit and _exit is small but important: exit is a library function that flushes the stdio buffers and calls the atexit functions; _exit goes directly to the kernel.
| Call | Function |
|---|---|
fork() | Creates a new process by copying the process (COW) |
clone(), clone3() | A new task whose shared parts are chosen with flags (thread, container) |
execve() | Replaces the process image with a new program |
waitpid() | Waits for a child to finish, obtains its exit status, and reaps the zombie |
exit() / _exit() | Terminates the process (exit flushes the stdio buffers) |
kill() | Sends a signal to a process; a signal need not terminate it |
sigaction(), sigprocmask() | Installs a handler; reads and changes the set of blocked signals |
sigpending(), sigsuspend() | Returns the pending signals; temporarily changes the mask and waits for a signal |
rt_sigreturn() | Restores the saved context on return from a handler |
alarm() / pause() | Generates SIGALRM after n seconds / sleeps until a signal arrives |
fork, execve, running, exit, zombie, and reaping with waitpid.A process that terminates does not vanish at once (Figure 15.11). It releases its memory and files, but its task_struct remains, carrying the exit status. A process in this state is called a zombie; ps shows it with the letter Z. When the parent reads the status with waitpid, the zombie is removed completely. If the parent dies first, its children are re-parented to PID 1 (or to a process that has declared itself a “subreaper”), which reaps them. The process tree can be seen with pstree -p or ps -ef --forest.
15.4.3The process descriptor: task_struct
The Linux counterpart of the textbook process control block (PCB) is struct task_struct (Figure 15.12). The structure is large; on x86-64 it takes a few kilobytes and varies from version to version. But most of what it contains is not data directly but pointers to other structures.
task_struct and the structures it points to. Those on the left can be shared among threads; each task has its own kernel stack.The fields the structure holds itself describe the task's identity and scheduling state. __state is the task's state. pid and tgid are identifiers. prio and policy give the priority and the scheduling policy. The se field is an embedded sched_entity structure; the vruntime and deadline values used by the fair scheduler live here. parent and children build the process tree. The remaining fields are pointers:
mm→mm_struct: the address space. The list of memory regions (VMAs) and the address of the top-level page table (pgd) are here. Kernel threads have a nullmm.files→files_struct: the file-descriptor table. Each entry points to astruct file.fs→fs_struct: the root directory, the working directory, and the umask.sighandandsignal: the signal handlers and the process-wide signal state.cred: uid, gid, and capabilities.nsproxy: the namespaces the task lives in (PID, network, mount, and so on).cgroups→css_set: the control groups the task belongs to and their limits.
The consequence of this layout is Linux's most surprising design decision: there is no structural difference between a process and a thread. Both are a task, that is, a task_struct. The difference is whether the substructures are shared. The mm pointers of two separate processes point to different mm_structs. The mm pointers of two threads of the same process point to the same object.
On Linux, the unique in-kernel identifier of every task is pid. The identifier common to the threads of one process is the thread group ID (tgid). The value a user sees as the “PID” is the tgid: getpid() returns the tgid, and gettid() returns the task's own pid.
A single-threaded process with PID 900 calls pthread_create twice. The kernel gives the new tasks the IDs 901 and 902 in turn. What do getpid() and gettid() return in each task?
- Main thread:
pid= 900,tgid= 900.getpid()= 900,gettid()= 900. The group leader is the task whose ID equals the group ID. - The new threads are born with
CLONE_THREAD, so they inherit the group'stgid:getpid()is 900 in both.gettid()is 901 and 902. psshows a single process, 900.ps -Lor the directory/proc/900/task/lists the three tasks separately.
The values of the __state field appear as letters in the STAT column of ps. R means running or ready to run; Linux does not distinguish these two states. S is interruptible sleep: the task waits for an event and can be woken by a signal. D is uninterruptible sleep: the task is usually waiting for a disk operation to finish, and signals do not wake it. T means stopped and Z means zombie. A task in state D does not die immediately even with SIGKILL. An unresponsive network file system could therefore produce processes that resist kill -9. To reduce this problem, the kernel now uses TASK_KILLABLE in most waits: the task can be woken only by a fatal signal.
15.4.4The clone() flags and NPTL
Since a process and a thread are represented by the same structure, the same call can create both. That call is clone().
clone(flags, …) is the Linux system call that creates a new task. Each flag chooses whether one substructure of the parent is shared with the child or the child gets a new copy of it. A structure for which no flag is given is copied.
The sharing flags map one to one onto the pointers of task_struct (Table 15.5). If CLONE_VM is given, the child's mm points to the same object as the parent's; if not, the address space is copied with COW. CLONE_FILES shares the descriptor table, CLONE_FS the root and working directories, and CLONE_SIGHAND the signal handlers. CLONE_THREAD puts the child into the parent's thread group: the child gets the same tgid and looks like the same process from the outside.
| Flag | If given | If not given |
|---|---|---|
CLONE_VM | the address space (mm) is shared | copied with COW |
CLONE_FILES | the descriptor table is shared | the table is copied (same struct files) |
CLONE_FS | root, working directory, and umask are shared | copied |
CLONE_SIGHAND | signal handlers are shared (requires CLONE_VM) | copied |
CLONE_THREAD | same thread group, same tgid (requires CLONE_SIGHAND) | new process, new tgid |
CLONE_NEWPID, CLONE_NEWNS, CLONE_NEWNET, CLONE_NEWUTS, CLONE_NEWIPC, CLONE_NEWUSER, CLONE_NEWCGROUP | the child starts in a new namespace | stays in the parent's namespace |
Three typical calls show the power of the flags (Figure 15.13).
fork(). In glibc,forkis aclonecalled with only theSIGCHLDflag. There are no sharing flags; the child gets a copy of every structure, and memory is shared with COW. Separate PID, separate TGID: a new process. HereSIGCHLDis not a sharing flag but the number of the signal to be sent to the parent when the child terminates.pthread_create(). Linux's thread library NPTL (Native POSIX Thread Library) passes these flags:CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM | CLONE_SIGHAND | CLONE_THREAD | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID. Everything is shared, and the new task joins the same TGID. The last three flags set up the thread's local storage and notifypthread_joinof its termination.- Container. The namespace flags give the child a new view of the world. A child born with
CLONE_NEWPIDis the first process of its own PID namespace: inside, it believes it is PID 1; outside, it carries an ordinary PID. This is the foundation of containers.
clone with namespace flags: the child gets copies of the structures and new namespaces; inside, it is PID 1.The model NPTL builds is 1:1: every user thread corresponds to one kernel task. The kernel schedules threads directly; when one blocks, the others keep running, and on a multicore machine they truly run in parallel. NPTL arrived in 2003 with the 2.6 series. LinuxThreads, which came before it, was also 1:1, but every thread carried a separate PID and signal handling did not conform to POSIX. CLONE_THREAD and the TGID concept were added to solve these problems.
Because the flags can be combined independently, “half-process, half-thread” tasks are also possible. A task born with CLONE_VM | CLONE_FILES but without CLONE_THREAD appears as a separate process; it has its own TGID. Yet it uses the same memory and the same descriptor table as its parent. A file opened by one is open in the other. Classic UNIX has no such intermediate form. clone3() (5.3) does the same job with a wider argument structure; new flags are now added to it.
Assuming the PID in ps refers to a thread. A multithreaded server is a single line in ps, because ps lists TGIDs. Sending a signal to one thread requires tgkill and the task ID; kill sends the signal to the whole group, and a suitable thread within the group receives it.
15.5Signals
15.5.1POSIX signals
A signal is a software interrupt that notifies a process of an event. Every signal has a number and a default action. For each signal, the process can choose the default action, ignoring it, or its own handler.
Signals arise in two ways. Synchronous signals are the result of the process's own instruction: an invalid memory access produces SIGSEGV, and integer division by zero produces SIGFPE. Asynchronous signals come from outside: Ctrl-C at the keyboard produces SIGINT, and the kill command produces SIGTERM by default. A handler's usual jobs are cleaning up resources, writing a log, or re-reading the configuration.
| Signal | No. | When is it generated? | Default |
|---|---|---|---|
SIGHUP | 1 | Terminal connection lost; in daemons, “re-read the configuration” | terminate |
SIGINT | 2 | Ctrl-C (to the foreground process group) | terminate |
SIGQUIT | 3 | Ctrl-\ | core dump |
SIGABRT | 6 | abort() | core dump |
SIGFPE | 8 | Arithmetic error | core dump |
SIGKILL | 9 | kill -9; cannot be caught or ignored | terminate |
SIGUSR1 / SIGUSR2 | 10 / 12 | User-defined | terminate |
SIGSEGV | 11 | Invalid memory access | core dump |
SIGPIPE | 13 | Writing to a pipe with no reader | terminate |
SIGALRM | 14 | alarm() timer expired | terminate |
SIGTERM | 15 | Default of kill; a polite request to terminate | terminate |
SIGCHLD | 17 | Child terminated or stopped | ignore |
SIGCONT / SIGSTOP | 18 / 19 | Continue / stop (cannot be caught); Ctrl-Z generates SIGTSTP (20) | continue / stop |
SIGKILL and SIGTERM are both sent with the kill command. The difference is catchability. A process can catch SIGTERM; it closes its open files, deletes its temporary files, and exits gracefully. SIGKILL and SIGSTOP, on the other hand, cannot be caught, blocked, or ignored. They are designed this way so that the administrator can always stop a runaway process. The right order is SIGTERM first and, if necessary, SIGKILL. The numbers between SIGRTMIN and SIGRTMAX (34–64 in glibc) are reserved for real-time signals. Unlike classic signals, these are queued: if the same signal arrives three times, it is delivered three times.
15.5.2The delivery path of a signal
Generating a signal and handling it are separate moments (Figure 15.14). In between, the signal is pending. The Ctrl-C example shows the path from start to finish.
- Generation. The user presses Ctrl-C. The line discipline of the tty driver recognizes the character and generates
SIGINTfor every process in the foreground process group. The only thing the kernel does is set the bit of signal 2 in the target task's pending-signal set. - Check. The signal is not handled immediately. When a process returns to user mode from a system call or an interrupt, the kernel asks, “is there a pending, unblocked signal?” A sleeping process is woken by the signal and goes through this check on its return path.
- Frame. If the process has installed a handler with
sigaction, the kernel writes a signal frame onto the process's user stack. The frame holds the registers of the interrupted moment and a return trampoline. The kernel sets the program counter to the address of the handler. - Handler. The handler runs in user mode, as part of the process's own code.
- Return. When the handler returns, the trampoline makes the
rt_sigreturnsystem call. The kernel restores the registers from the frame. - Resume. The process continues from the instruction at which it was interrupted (PC = 0x401a2c in the figure). Had no handler been installed, the default action would have been applied; for
SIGINT, that means the process terminates.
rt_sigreturn call.The handler runs in the middle of the interrupted code, in the same thread. The process may have been interrupted right inside malloc, while holding the heap's lock. If the handler also calls malloc or printf, it tries to take the same lock a second time and the process deadlocks. For this reason only async-signal-safe functions may be used in a handler, such as write and _exit. The most robust pattern is for the handler to set just a flag of type volatile sig_atomic_t to 1 and for the main loop to do the real work by checking the flag.
Assuming sigreturn is the call that enters the handler. Entering the handler is not a system call; the kernel “sends” the process to the handler by changing the program counter. rt_sigreturn performs the return from the handler, and it is the trampoline, not the programmer, that calls it.
15.5.3Code trace: selecting pending signals
The kernel keeps two bit sets for every task: the pending signals and the blocked signals. Signal number n sits at bit (n − 1). A simplified version of the check on return to user mode looks like this:
/* on return to user mode (kernel) */
void check_signals(task *t) {
unsigned long h = t->pend & ~t->blk;
while (h) {
int sig = __builtin_ctzl(h) + 1;
t->pend &= ~(1UL << (sig - 1));
deliver(t, sig); /* handler/default */
h = t->pend & ~t->blk;
}
}
/* before: sigprocmask(SIG_BLOCK, {SIGINT}) */
/* after: sigprocmask(SIG_UNBLOCK, {SIGINT}) */The third line computes the set that is ready for delivery: ready = pending & ~blocked. The loop runs until this set is empty. __builtin_ctzl(h) counts the trailing zero bits of the number, that is, it gives the position of the lowest set bit; +1 converts that to a signal number. The lowest-numbered ready signal is therefore chosen first. The chosen signal's bit is cleared from the pending set and the signal is delivered. After delivery the set is recomputed, because running the handler may change the sets.
The scenario is as follows. Before entering a critical section, the process blocks SIGINT with sigprocmask(SIG_BLOCK, {SIGINT}). While it sleeps, three signals arrive: Ctrl-C (2), kill -USR1 (10), and a child's termination (17). A handler is installed for SIGUSR1.
| Event | pending | blocked | ready | Result |
|---|---|---|---|---|
SIG_BLOCK {SIGINT} | {} | {2} | {} | — |
| 2, 10, 17 arrive | {2, 10, 17} | {2} | — | only bits are set |
| Return to user mode | {2, 10, 17} | {2} | {10, 17} | lowest: 10 |
| 10 delivered | {2, 17} | {2} | {17} | SIGUSR1 handler runs |
| 17 delivered | {2} | {2} | {} | SIGCHLD: default, ignore |
SIG_UNBLOCK {SIGINT} | {2} | {} | {2} | same check on return |
| 2 delivered | {} | {} | {} | no handler: the process terminates |
In bit notation, after the three signals arrive, the pending set is 0x10202: signal 2 is bit 1 (0x2), signal 10 is bit 9 (0x200), and signal 17 is bit 16 (0x10000). The blocked set is 0x2. The ready set is 0x10202 & ~0x2 = 0x10200. The lowest set bit is 9, that is, signal 10.
SIGINT enters the ready set and the default action terminates the process.Two lessons come out of the trace. First, blocking is deferring, not ignoring. SIGINT was not lost during the critical section; it stayed in the pending set and was delivered as soon as the block was lifted. Ignoring (SIG_IGN), on the other hand, discards the signal at the moment it arrives. Second, classic signals are not counted. The pending set is a bit set. Had Ctrl-C been pressed three times during the critical section, the bit would still be set only once and the signal would be delivered only once.
15.6Scheduling
15.6.1Scheduling classes
The Linux scheduler is not a single algorithm but a set of scheduling classes arranged in priority order. Every task belongs to a class. When a CPU becomes free, the kernel asks the classes in order, and the first class that yields a task to run wins. The order is as follows:
- stop: an internal class the kernel uses to stop a CPU or to migrate tasks.
- deadline: the
SCHED_DEADLINEpolicy. A task declares a runtime, a deadline, and a period; the scheduler runs the earliest deadline first. - rt:
SCHED_FIFOandSCHED_RR, fixed priorities from 1 to 99. A FIFO task runs until it yields voluntarily; RR rotates among tasks of the same priority with a time slice. - fair:
SCHED_NORMAL(formerlySCHED_OTHER),SCHED_BATCH, andSCHED_IDLE. All ordinary processes are here. Since 6.6 this class is governed by EEVDF. - idle: the idle task that runs when the CPU has no other work.
sched_ext, which arrived with 6.12, allows the scheduling policy to be loaded as an eBPF program. A company can try a scheduler suited to its own workload without recompiling the kernel. If the program misbehaves, the kernel removes it and gives the tasks back to the fair class. The mechanism is in the kernel, the policy in user space.
Every CPU has its own run queue (struct rq). Each class keeps its own data structure in this queue. Tasks are balanced between CPUs from time to time. The load balancer sees the CPUs as a hierarchy of scheduling domains: the hardware threads of the same core, the cores on the same chip, the chips in the same NUMA node. A task is migrated at the nearest level first, because its cache and memory are warmer there.
15.6.2From O(n) to CFS
The selection rule of the fair class changed three times in twenty years (Table 15.8). The scheduler in the 2.4 kernel scanned all ready tasks at every selection. This cost, which grows linearly with the number of tasks, became a problem on servers with hundreds of tasks. The O(1) scheduler, which arrived with 2.6.0, kept a separate list for each priority level: an array of 140 lists and a bitmap showing which lists were non-empty. The highest-priority task was selected by a single instruction that finds the first set bit in the bitmap. A task whose time slice expired moved to a second, “expired” array, and when the active array emptied, the roles of the two arrays were swapped. The speed problem was solved, but the heuristic rules used to recognize interactive tasks became complicated and produced unpredictable behavior.
| Version | Selection rule | Data structure |
|---|---|---|
| 2.4 (2001) | O(n): all ready tasks are scanned at every selection | single list |
| 2.6.0–2.6.22 (2003) | O(1): a list per priority, active and expired arrays | array of 140 lists + bitmap |
| 2.6.23–6.5 (2007) | CFS: smallest vruntime | red-black tree |
| 6.6+ (2023) | EEVDF: earliest virtual deadline among eligible tasks (v ≤ V) | the same tree, augmented with subtree information |
In 2.6.23 came Ingo Molnár's Completely Fair Scheduler (CFS). The idea of CFS is to emulate an ideal multitasking processor. On the ideal processor, n tasks would run at the same time, each at 1/n speed. A real processor cannot do this, but it can track which task has fallen furthest behind its share. This tracking is done with each task's virtual runtime.
15.6.3Weights and virtual runtime
Every task has a weight w derived from its nice value; the weight of nice 0 is 1024. When a task runs for a real time Δt, its virtual runtime (vruntime) grows by:
The nice value lies between −20 and +19; a smaller value means a higher priority. The weights are read from the kernel's sched_prio_to_weight table. At each nice step the table changes the weight by a factor of about 1.25: nice 1 → 820, nice 0 → 1024, nice −1 → 1277. The result is that a task whose nice value increases by one loses roughly 10% of its CPU share. The extremes are 88,761 for nice −20 and 15 for nice 19.
The formula agrees with intuition at both ends. The virtual clock of a task with a large weight runs slowly; even if it runs a lot in real time, its virtual time grows little. The virtual clock of a task with a small weight runs fast. The rule of CFS is to run the task with the smallest vruntime. Tasks are ordered by vruntime in a red-black tree, and the leftmost node is chosen. Insertion and deletion are O(log n). Because the leftmost node is cached, selection is O(1).
Three tasks with nice 0 (w = 1024), nice 5 (w = 335), and nice −5 (w = 3121) run for 6 ms. How far does each one's vruntime advance? In what ratio do a continuously ready nice 0 task and a nice 5 task share a single CPU?
- nice 0: 6 × 1024 / 1024 = 6 ms.
- nice 5: 6 × 1024 / 335 ≈ 18.34 ms. Its virtual clock runs three times as fast.
- nice −5: 6 × 1024 / 3121 ≈ 1.97 ms.
- In the long run the
vruntimes of the two tasks stay close to each other. For that, the real run times must be proportional to the weights: 1024 / (1024 + 335) ≈ 75.3% for nice 0, and 335 / 1359 ≈ 24.7% for nice 5.
What happens to a task that has just woken up? A task that has slept for hours has a vruntime far behind. If it were put on the queue as it is, it would monopolize the CPU for a long time. CFS therefore pulled the woken task's vruntime to slightly behind the queue's minimum value. Adjustments of this kind multiplied over time: the latency target (sched_latency), the minimum slice, the wakeup granularity. Each solved one problem while creating a new one in another workload. The real shortcoming of CFS was theoretical. CFS determined well how much CPU a task would get, but gave no guarantee about when it would get it. A latency-sensitive task, such as audio or a game, needs the CPU at short intervals even when its share is small.
15.6.4EEVDF: eligibility and virtual deadline
Linux 6.6 (2023) replaced the selection rule of the fair class with EEVDF (Earliest Eligible Virtual Deadline First). The algorithm is based on the 1995 work of Ion Stoica and Hussein Abdel-Wahab; Peter Zijlstra adapted it to the kernel. EEVDF adds two concepts: eligibility and virtual deadline.
The average virtual time of a queue is the weighted average of the tasks' vruntimes: V = Σ wᵢvᵢ / Σ wᵢ. A task's lag is lagᵢ = wᵢ (V − vᵢ). A task whose lag is zero or positive, that is, which satisfies vᵢ ≤ V, is eligible. Every task has a virtual deadline: dᵢ = vᵢ + slice × 1024 / wᵢ. EEVDF chooses, among the eligible tasks, the one with the earliest virtual deadline.
Lag is the difference between the service a task would have received on the ideal processor and the service it actually received. A positive lag shows that the task has fallen behind its share; the scheduler owes it. A negative lag shows that the task has received more than its share; the task is not eligible and waits until its turn comes. The sum of the lags of all tasks is zero at every moment. The eligibility condition prevents a task from monopolizing the CPU by exceeding its share. The virtual deadline, in turn, answers the question of when. A task with a short slice has a near deadline and moves ahead as soon as it is eligible.
Not a few things stay unchanged in the move from CFS to EEVDF. The vruntime in sched_entity, the nice-to-weight table, and the red-black tree in the run queue remained as they were. The tree is still ordered by vruntime. Each node additionally stores the earliest deadline in its own subtree. With this extra information the scheduler finds the “eligible task with the earliest deadline” in a single descent of the tree, in O(log n) steps. What changed are CFS's tuning knobs. The latency target and the wakeup granularity were removed; a single base slice took their place. Its value can be seen in the file /sys/kernel/debug/sched/base_slice_ns. The default is a base value of a fraction of a millisecond scaled by the number of CPUs; on machines with eight or more CPUs it is a few milliseconds. The examples in this chapter take the slice as 3 ms.
On a single CPU there are two continuously ready tasks: A with nice 0 (w = 1024) and B with nice 5 (w = 335). Both start from v = 0, and the slice is 3 ms. Each task, once selected, runs until it finishes its slice. What do the selections look like over the first 24 ms?
- t = 0. V = 0; both are eligible. Deadlines: dA = 0 + 3 = 3, dB = 0 + 3 × 1024 / 335 ≈ 9.17. A is chosen.
- t = 3. vA = 3, dA = 6. V = (3 × 1024 + 0 × 335) / 1359 ≈ 2.26. A is not eligible (3 > 2.26). The only eligible task is B; it is chosen.
- t = 6. vB ≈ 9.17, dB ≈ 18.34. V ≈ 4.52. A is eligible (3 ≤ 4.52), B is not. A is chosen.
- t = 9 and t = 12. V is 6.78 and 9.04, respectively; vA is 6 and 9. A is eligible two more times and is chosen. Since B's v is 9.17, V has not yet passed it.
- t = 15. vA = 12, V ≈ 11.30. A is not eligible, B is eligible (9.17 ≤ 11.30). B is chosen. After that the pattern repeats.
In 24 ms, A runs six slices (18 ms) and B runs two slices (6 ms): 75% and 25%. This is the ratio of the weights (1024 : 335 ≈ 3 : 1).
| t (ms) | vA / dA | vB / dB | V | Eligible | Chosen |
|---|---|---|---|---|---|
| 0 | 0 / 3 | 0 / 9,17 | 0 | A, B | A |
| 3 | 3 / 6 | 0 / 9,17 | 2,26 | B | B |
| 6 | 3 / 6 | 9,17 / 18,34 | 4,52 | A | A |
| 9 | 6 / 9 | 9,17 / 18,34 | 6,78 | A | A |
| 12 | 9 / 12 | 9,17 / 18,34 | 9,04 | A | A |
| 15 | 12 / 15 | 9,17 / 18,34 | 11,30 | B | B |
| 18 | 12 / 15 | 18,34 / 27,51 | 13,56 | A | A |
| 21 | 15 / 18 | 18,34 / 27,51 | 15,82 | A | A |
The share is determined by the weights, as in CFS. The difference of EEVDF appears when the two tasks have different slices. A latency-sensitive task can request a shorter slice with the sched_setattr() call; the call's sched_runtime field is interpreted as a slice request in the fair class. This facility was completed in 6.12. A short slice means an earlier deadline, and therefore being chosen more often. The share, however, does not change.
A and B are both nice 0. A's slice is 3 ms; B has asked for 1 ms. What is the selection order over the first 12 ms?
- t = 0: both are eligible; dA = 3, dB = 1. B is chosen and runs for 1 ms.
- t = 1: vB = 1, V = 0.5. Only A is eligible; A runs for 3 ms.
- t = 4: vA = 3, V = 2. B is eligible, dB = 2. B is chosen. At t = 5 (V = 2.5, dB = 3) and at t = 6 (V = 3, both eligible; dB = 4 < dA = 6), B is chosen again.
- t = 7: vB = 4 > V = 3.5. A runs (7–10). Then B gets two more slices.
The order is B AAA BBB AAA BB. In 12 ms both tasks ran for 6 ms; the shares are equal. But B got its first slice immediately and never waited longer than 3 ms.
Confusing EEVDF with “CFS, which picks the smallest vruntime.” The task with the smallest vruntime is always eligible, but it may not be the one chosen. For example, with V = 12, A (v = 10, d = 14) and B (v = 12, d = 13) are eligible. EEVDF chooses B, which has the earlier deadline; CFS would have chosen A.
15.7Booting
From the moment the power button is pressed to the login screen, a series of programs hand control to one another (Figure 15.16).
- UEFI. The firmware on the motherboard tests the hardware. It finds the EFI system partition (ESP) on the disk and loads the EFI application there. If Secure Boot is on, each stage verifies the signature of the next.
- Bootloader. GRUB2 or systemd-boot loads the kernel image (
vmlinuz) and theinitramfsinto memory and passes command-line parameters to the kernel. The kernel can also be started directly as an EFI application. When the kernel, the initramfs, and the command line are combined in a single signed file, it is called a unified kernel image (UKI). - Kernel. The compressed image unpacks itself.
start_kernel()sets up memory management, interrupts, and the scheduler. The first task to run this code becomes PID 0 and eventually turns into the idle task. The kernel createskernel_init(PID 1) andkthreadd(PID 2), the ancestor of kernel threads. - initramfs. The drivers needed to mount the root file system may not be in the kernel: NVMe, RAID, an encrypted disk. The initramfs provides a temporary root in RAM. The scripts in it load the necessary modules, mount the real root, and switch to it with
switch_root. - systemd. PID 1 is now systemd. It starts services in parallel according to the dependencies in unit files and reaches a target:
multi-user.targetorgraphical.target. - Session. On the console
agetty→login→ shell, on the desktop gdm, and remotely sshd greets the user. Asystemd --userinstance is also started for the user's session.
The init → getty → login → sh chain of classic UNIX is still recognizable today. The difference is that PID 1 is now a large program that starts services in parallel according to a dependency graph, tracks them in cgroups, and restarts a service that crashes. How long each stage of boot takes is measured with systemd-analyze.
Assuming PID 1 is an ordinary process. If PID 1 terminates, the kernel panics. Orphaned processes are re-parented to it, and it reaps their zombies. In a container, the PID 1 inside takes on these duties; if an application that does not reap zombies is run as PID 1, zombies accumulate in the container.
15.8Memory management
15.8.1The process address space and VMAs
With four-level paging on x86-64, virtual addresses are 48 bits. Linux divides this space into two halves (Figure 15.17). The lower half, 247 B = 128 TiB, belongs to the user. The upper half, again 128 TiB, belongs to the kernel. The kernel half is the same in all processes and cannot be accessed in user mode. Between the two halves lies a huge unusable hole. With five-level paging (LA57), user space grows to 256 B = 64 PiB.
The layout of the user half, from bottom to top, is as follows. The lowest page is never mapped; a program that accesses a NULL pointer receives SIGSEGV. Next comes the program code (text): read-only and executable, and shared among all processes running the same program. Then come the initialized global variables (data) and the zero-initialized globals (bss). The heap starts right above bss and grows upward with brk. At the top end of the address space is the stack, which grows downward. Below the stack is the mmap region, which also grows downward: shared libraries (libc.so, ld.so), mapped files, and thread stacks are placed here. ASLR (address space layout randomization) changes the starting points of the stack, the mmap region, and the heap on every run, making it harder for an attacker to guess addresses. The gap between the heap and the mmap region is only virtual and consumes no physical memory.
A virtual memory area (VMA, struct vm_area_struct) is a contiguous region of the address space that carries the same permissions and the same backing. Each VMA holds its start and end addresses, its permissions (r, w, x, shared or private), and, if there is one, the file it maps.
A process's VMAs are kept in its mm_struct. Since 6.1 they are stored in a maple tree. This tree is a cache-friendly kind of B-tree suited to range lookups; it replaced the earlier red-black tree and linked list. On a page fault, the kernel's first question is “which VMA is this address in?” If the address is in no VMA, or the VMA does not permit the access, the process is sent SIGSEGV. If the address is in a valid VMA, the page is either read from the file or given as a fresh zeroed frame. A process's VMAs can be seen line by line with cat /proc/PID/maps.
15.8.2Sharing, mapped files, and memory calls
When two processes run the same program, they keep the text pages in physical memory only once (Figure 15.18). The page tables of the two processes point to the same frames. Two processes that map the same file as shared also see the same page-cache frames. The data and stack pages of each process, however, belong to it alone.
data.db in the same physical frames.| Call | Function |
|---|---|
brk / sbrk | Grows or shrinks the heap by moving its end |
mmap | Maps a file, a device, or anonymous memory into the address space |
munmap | Removes the mapping and returns the memory to the system |
mprotect | Changes the permissions (r/w/x) of a region |
madvise | Gives the kernel a usage hint (e.g. MADV_DONTNEED) |
msync | Writes the dirty pages of a shared mapping to the file |
mmap has two kinds of mapping. With MAP_SHARED, what is written is visible in the file and to other processes that map the same file. With MAP_PRIVATE, the page is copied on the first write and the file does not change; a program's data segment is mapped this way. A mapping that has no file is called an anonymous mapping; its pages come from zeroed frames on first touch. glibc's malloc serves small requests from the heap and grows the heap with brk as needed. Requests of 128 KiB and above it serves directly with an anonymous mmap. This threshold is a default, and glibc can adapt it at run time. Large blocks thus go straight back to the system with munmap at free time.
15.8.3The page-table walk: four and five levels
On x86-64, a 4 KiB page needs a 12-bit offset. The remaining 36 bits of the 48-bit address are split among four tables. Each table is a 4 KiB page and holds 512 entries of 8 bytes; a table index is 9 bits. Linux's names for the tables are: PGD (bits 47–39), PUD (38–30), PMD (29–21), and PTE (20–12). Bits 63–48 must be a copy of bit 47. An address that satisfies this condition is called a canonical address. In user addresses these bits are 0; in kernel addresses they are 1.
The virtual address is 0x00007f3a1c2b5e88. What are the four indices and the offset? If the frame number in the PTE is 0x3c5a1, what is the physical address?
- The offset is the lowest 12 bits, that is, the last three hexadecimal digits: 0xe88.
- PGD = address >> 39 = 0xfe = 254. Bits 63–48 are 0 and bit 47 is also 0; the address is canonical.
- PUD = (address >> 30) & 0x1ff = 232. PMD = (address >> 21) & 0x1ff = 225. PTE = (address >> 12) & 0x1ff = 181.
- Physical address = frame × 4096 + offset = 0x3c5a1 × 0x1000 + 0xe88 = 0x3c5a1e88. In hexadecimal, the multiplication is just appending three zeros to the frame number.
The walk itself goes as follows (Figure 15.19). The CR3 register holds the physical address of the process's PGD table; on a context switch the kernel loads CR3 with the new process's mm->pgd. PGD[254] points to a PUD table. PUD[232] points to a PMD table; a 1 GiB huge page can also end at this level. PMD[225] points to a PTE table; 2 MiB huge pages and transparent huge pages (THP) end here. PTE[181] is the actual entry: the present bit, the frame number, read/write (R/W), user/supervisor (U/S), no-execute (NX), dirty (D), and accessed (A) bits. If the present bit is 0, the hardware generates a page fault.
Making four extra reads on every memory access is expensive. The TLB caches the translation; on the next access the four reads are skipped. On a TLB miss, the hardware does the walk; the kernel only builds the tables. Huge pages shorten the walk by one or two levels and cover a much larger area with a single TLB entry.
Five-level paging (LA57) has been supported since Linux 4.14. It adds a level called P4D between the PGD and the PUD and extends the virtual address to 57 bits. Linux's page-table code is generically five-level. If the hardware uses fewer, the intermediate levels are “folded”: on a four-level machine the P4D is treated as having a single entry and embedded in the PGD. The same code thus works from two-level 32-bit ARM to five-level x86-64.
Trying to read the indices directly from the hexadecimal digits of the address. The 9-bit fields are not aligned with the 4-bit digits. The right way is to shift and mask: (address >> k) & 0x1ff, with k = 39, 30, 21, 12. Only the 12-bit offset corresponds to the last three digits.
15.8.4Representing physical memory
Linux describes physical memory with a three-level hierarchy: node → zone → page (Figure 15.20). On a multi-socket server, each processor socket has memory close to itself. This arrangement is called NUMA (non-uniform memory access). Each NUMA node is described by a pglist_data structure. A CPU allocates memory from its own node first, because accessing a remote node is slower.
struct page array, and the buddy free lists.Each node is divided into zones. ZONE_DMA is the first 16 MiB; it is for old ISA devices that can address only 24 bits. ZONE_DMA32 is the first 4 GiB; it is for devices that can do 32-bit DMA. ZONE_NORMAL is the rest of RAM. ZONE_MOVABLE holds only movable pages; it can be emptied before a memory module is removed and makes it easier to create huge pages. On 32-bit kernels there was also ZONE_HIGHMEM for high memory that the kernel could not map directly. On 64-bit systems this zone does not exist, because the kernel address space is large enough to map all of RAM directly.
For every physical page frame there is a struct page in the kernel. The structure is 64 bytes. These live in a large array called mem_map. 64 B for every 4 KiB page means 64 / 4096 ≈ 1.56% of RAM. On a 16 GiB machine this array takes 256 MiB. To manage consecutive pages as a single unit, the folio concept arrived with 5.16. A folio can cover multiple pages; the page-cache and reclaim code work folio by folio instead of page by page.
Each zone's free_area array holds the buddy allocator's free lists. List k contains free blocks of 2k pages. k runs from 0 to 10: from 4 KiB to 4 MiB. A request is served from the smallest suitable block; a larger block is split in two, and when a freed block's “buddy” is also free, the two merge. The numbers of free blocks in the zones can be read from /proc/buddyinfo. Each zone also has three watermarks (min, low, high); reclaim works according to them.
15.8.5The SLUB object allocator
The kernel allocates large numbers of small objects of the same size: a task_struct for every process, a struct file for every open file, a dentry (192 B) for every name, an inode for every file. Allocating a page for each of them would be both slow and wasteful.
SLUB is Linux's object allocator. For each object type it keeps an object cache (kmem_cache). The cache divides one or several consecutive pages it takes from the buddy allocator (a slab) into objects of the same size. Free objects are linked into a free list.
Some of the caches belong to specific types: task_struct, dentry, inode_cache (Figure 15.21). kmalloc, on the other hand, is general-purpose and uses caches divided into size classes: kmalloc-8, kmalloc-16 … kmalloc-8k. A 100-byte request is served from kmalloc-128. Larger requests go directly to the buddy allocator. For large areas that need not be physically contiguous, vmalloc is used; it maps scattered frames into a virtually contiguous region.
A cache has three kinds of slabs. Each CPU has an active slab; most allocation and freeing happens here without taking a lock. Partial slabs contain both full and free objects. In full slabs, all objects are in use. When the active slab has no free objects left, the CPU takes a new slab from the partial list; if there is none, it asks the buddy allocator for pages. The state of the caches can be watched in /proc/slabinfo or with the slabtop command.
The name SLUB comes from history. For many years three allocators coexisted in Linux. SLAB was the first adaptation of the design Bonwick proposed for Solaris, and it kept complicated queues. SLOB was written for small embedded systems. SLUB arrived in 2.6.22 as a simplified version of SLAB and over time became the default. SLOB was removed in 6.4 and SLAB in 6.8. Today the only allocator is SLUB.
A dentry object is 192 bytes. How many dentries fit in a single-page (4 KiB) slab, and how many bytes are left over?
- 4096 / 192 = 21.33. The integer part is 21 objects.
- 21 × 192 = 4032. The remainder is 4096 − 4032 = 64 bytes.
- The waste is 1.6% of the page. Had a separate 4 KiB page been allocated for each dentry, the waste would have been 95%.
15.8.6Code trace: the SLUB free list
The secret of SLUB's speed is that it uses no extra memory to hold the free list. The inside of a free object is unused anyway. SLUB writes the “next free object” pointer into the object itself. A simplified version of the fast path looks like this:
void *slab_alloc(kmem_cache *c) {
void *obj = c->freelist; /* head of list */
if (!obj)
obj = new_slab(c); /* slow path */
c->freelist = *(void **)obj; /* next */
return obj;
}
void slab_free(kmem_cache *c, void *obj) {
*(void **)obj = c->freelist; /* inside the object */
c->freelist = obj;
}
/* a,b = alloc; free(a); c,d,e,f = alloc */slab_alloc takes the head of the list. If the list is empty, it enters the slow path: new_slab asks the buddy allocator for a page, divides it into objects, and hands out the first one. Then it advances c->freelist to the pointer written in the first 8 bytes of the object just taken. The expression *(void **)obj means “read the 8 bytes at the start of the object as a pointer.” slab_free does the opposite: it writes the old head of the list into the freed object and makes the object the new head. The list thus works like a stack: the last one freed is the first one handed out.
The trace is done in the kmalloc-1k cache. A slab is a single 4 KiB page and holds four 1 KiB objects: +0, +1024, +2048, +3072. At the start the list is +0 → +1024 → +2048 → +3072 → NULL. The program first allocates a and b, frees a, and then allocates c, d, e, and f.
| Operation | Object returned | freelist afterwards | Explanation |
|---|---|---|---|
| a = alloc | +0 | +1024 | head of the list; the pointer inside it is +1024 |
| b = alloc | +1024 | +2048 | fast path: no lock, no page allocation |
| free(a) | — | +0 | the old head (+2048) is written into +0 |
| c = alloc | +0 | +2048 | the “hot” object that a has just released |
| d = alloc | +2048 | +3072 | |
| e = alloc | +3072 | NULL | slab full |
| f = alloc | 2:+0 | 2:+1024 | slow path: new page, four objects |
Three observations from the trace sum up the design of SLUB. First, c landing in a's place is no accident. The bytes of the most recently freed object are most likely still in the CPU cache; handing it out again immediately reduces cache misses. Second, the common case takes a few instructions: one load, one store, one return. The real SLUB does this step with per-CPU structures and an atomic compare-and-swap instruction instead of a lock. Third, the rare case, f, which needs a new page, is slow but correct. Because all objects are the same size, no external fragmentation arises inside a slab; every hole left behind fits the next request exactly.
Continuing to use an object that has been freed. The first bytes of a freed object are now the free list's pointer. Faulty code that writes to the object corrupts the list; the next allocation returns an arbitrary address. Bugs of this kind are a frequent source of kernel vulnerabilities. For this reason the kernel can store the pointer mixed with a secret value, and with debugging options it can fill freed objects with a pattern and check them.
15.8.7The page cache, reclaim, and the OOM killer
Linux's memory philosophy can be summed up in one short sentence: free memory is wasted memory. Unused RAM is used for file data as the page cache. Once a file has been read, its pages stay in the cache; the second read does not go to the disk. This is why the “available” column in the output of free -h is larger than “free”: it also counts the reclaimable part of the cache. Suppose a 16 GiB machine starts with 5 GiB of application memory, 8 GiB of page cache, and 2 GiB of free memory (Table 15.12). The kernel itself and its buffers hold the remaining 1 GiB.
| Stage | Anonymous | Cache | Free | Swap | Kernel's reaction |
|---|---|---|---|---|---|
| Start | 5 | 8 | 2 | 0 | — |
| The application grew | 8,3 | 6 | 0,7 | 0 | low watermark crossed: kswapd wakes up |
| Cold pages go | 9 | 4,7 | 1,3 | 1 | MGLRU, zswap → swap |
| Pressure continues | 11,5 | 3,2 | 0,3 | 2 | below min: direct reclaim |
| OOM | 4,6 | 2 | 8,4 | 2 | mem_hog (PID 7311) killed |
Reclaim works in stages according to the watermarks (Figure 15.23).
- Background. When free memory falls below the low watermark, each node's
kswapdkernel thread wakes up. It drops clean cache pages immediately; dirty ones it writes to disk first. When free memory rises to the high level, it sleeps again. The application does not slow down noticeably in the meantime. - Victim selection. Which pages go is decided by the multi-generational LRU (MGLRU) that arrived with 6.1. Pages are divided into access generations; the coldest generation goes first. A cache page can be discarded, because its data is in the file on disk. Cold anonymous pages, on the other hand, have no file. zswap first compresses them in RAM and, if necessary, writes them to the swap area.
- Direct reclaim. If the allocation rate outpaces reclaim and free memory falls below the min level, a process requesting memory cannot wait for pages. It performs the reclaim itself and stalls in the process. The application's latency rises noticeably.
- OOM. If nothing is enough, the OOM killer (the mechanism that kills a process when memory runs out) steps in. It kills the process with the highest
oom_scorewithSIGKILL. The score is mostly proportional to the process's memory usage. The administrator protects a process or singles it out by writing a value between −1000 and +1000 to/proc/PID/oom_score_adj. If a cgroup's memory limit is exceeded, the victim is chosen only from that group.
mem_hog, and free memory rose to 8.4 GiB.How eagerly the swap area is used is determined by the vm.swappiness setting; the default is 60. As the value falls, the kernel prefers dropping cache pages over sending anonymous pages to swap.
Mistaking the small “free” value in the free output for a memory shortage. On a Linux machine that has been running for a long time, free memory is always low, because RAM is full of cache. The real indicators are the “available” value, swap activity, and the memory-pressure (PSI) counters in /proc/pressure/memory.
15.9Input/output
15.9.1Devices are files: major and minor numbers
On Linux, disks and terminals are accessed through device files in the /dev directory. An application reaches a disk and a terminal with the same open, read, and write calls. For these files ls -l shows two numbers instead of a size:
$ ls -l /dev # selected lines
brw-rw---- 1 root disk 8, 0 sda
brw-rw---- 1 root disk 8, 1 sda1
brw-rw---- 1 root disk 259, 0 nvme0n1
crw-rw-rw- 1 root root 1, 3 null
crw-rw-rw- 1 root tty 5, 0 ttyThe first letter of the line is the device type. c is a character device: it provides a byte stream and is usually unbuffered; terminals, /dev/null, and the mouse are like this. b is a block device: it provides random access to fixed-size blocks and uses the page cache and the I/O scheduler. The two numbers in the size column are the major and minor numbers (Figure 15.24). The major number selects the driver: 8 is the SCSI disk driver sd; SATA and USB disks are attached to it as well. The minor number selects the unit that driver manages. The sd driver reserves 16 minors per disk: 0 is the whole disk, 1–15 are partitions. That is why sda1 is 8,1; the second disk sdb starts at 8,16, and sdb3 is 8,19. NVMe disks are attached to the extended block major 259 (blkext).
open("/dev/sda1"): the type and major number in the inode select the driver, and the minor number selects the partition.A device file holds no data on disk. Its inode stores only the type and the two numbers. open looks up the kernel's device table with these numbers and finds the driver. Today there is no need to create the nodes in /dev by hand. When the kernel finds a device, it creates the node itself in the devtmpfs pseudo file system; udev sets the permissions and adds persistent names (/dev/disk/by-uuid/…). Network interfaces (eth0, wlan0), on the other hand, are not in /dev. They are reached through sockets. This is the best-known exception to the “everything is a file” principle.
15.9.2The structure of the I/O system
The three device types descend through the kernel along three separate paths (Figure 15.25). Character devices go from the VFS to the tty layer and the line discipline, and from there to the character driver. The path to block devices passes through the file system (ext4, XFS, Btrfs), the page cache, the block layer, and the I/O scheduler. The network path starts at the socket layer: TCP or UDP, IP and the netfilter packet filter, the queueing discipline (qdisc), and the network driver. Network drivers use the NAPI interface: under heavy traffic, instead of generating an interrupt for every packet, they disable interrupts and poll for packets in batches.
On the network path, data is carried in sk_buff structures. An sk_buff holds the packet's data and space reserved up front for headers; as each layer adds its header, it does not copy the data but only moves a pointer. With XDP and eBPF, packets can be filtered or redirected at the driver level, before entering the stack. Classic BSD had a similar three-way split. System V's module stack called STREAMS never entered the mainline Linux kernel.
15.9.3The driver interface: file_operations and the terminal
Old UNIX textbooks list the separate entry points of each driver in a table: k_open and k_read for the disk, tty_open and tty_read for the terminal, and so on. Linux gathers these entry points in a single structure of function pointers:
static const struct file_operations my_fops = {
.owner = THIS_MODULE,
.open = my_open,
.release = my_release, /* close */
.read = my_read,
.write = my_write,
.unlocked_ioctl = my_ioctl,
.poll = my_poll,
.mmap = my_mmap,
};
cdev_init(&cdev, &my_fops); /* major:minor → fops */A character driver fills in this structure and attaches it to a major:minor range with cdev_init. When an application calls read() on the device file, the VFS routes the call to the f_op->read pointer of the corresponding struct file. The counterpart of close is .release, and it is called only when the last descriptor is closed. Device-specific commands arrive through .unlocked_ioctl. .poll lets the device be waited on with select, poll, and epoll. .mmap maps device memory directly into the process's address space. This is object-oriented design in C: the table of function pointers works like a virtual method table. The same pattern repeats throughout the VFS.
Terminal I/O is configured through the termios interface. tcgetattr and tcsetattr read and write the terminal parameters. In canonical mode (ICANON) the line discipline does line editing itself: backspace is handled, and the program receives the line only after Enter. In raw mode every key is delivered immediately; text editors and programs that ask for passwords use this mode. The ECHO flag determines whether what is typed is echoed to the screen. cfsetispeed and cfsetospeed set the input and output baud rates. Today this setting is meaningful mostly for real serial ports; terminal windows are pseudo-terminals (pty).
15.9.4The block layer: blk-mq
The old single-queue block layer was designed for spinning disks that perform hundreds of operations per second. Every request went through a single queue and a single lock. On NVMe SSDs, which can perform millions of operations per second, this lock became a bottleneck. Today's block layer, blk-mq, is multi-queue. Each CPU writes its requests to its own software queue. The requests pass through an optional I/O scheduler and are distributed to the device's hardware queues. NVMe controllers offer many hardware queues; usually one queue falls to each CPU, and no lock is shared between CPUs.
There are four scheduler options. none does no ordering at all; on fast NVMe devices it is usually the best. mq-deadline orders reads and writes by deadlines and ensures that no request starves. bfq (budget fair queueing) shares bandwidth fairly among processes; on slow desktop disks it preserves interactivity. kyber adjusts the queue depth according to target latencies. The active scheduler is read per device from the file /sys/block/<device>/queue/scheduler; the one in square brackets is selected. Writing a name to the file changes the scheduler. The newer asynchronous I/O interface io_uring is also built on top of this layer. The application and the kernel exchange requests and results through two shared ring buffers, which reduces the number of system calls.
15.9.5The network: sockets and connection setup
A socket is the endpoint of network communication and is represented by a file descriptor. The establishment of a TCP connection can be followed through the calls on the two sides (Figure 15.26).
- The server prepares.
socket()creates a socket; it gets 3, the smallest free descriptor.bindattaches the socket to port 80.listen(3, 128)puts the socket into the listening state and opens a queue for pending connections. - Waiting. The server blocks in
accept. The client creates its own socket. - Handshake. The client calls
connect. The client's kernel sends SYN, the server's kernel replies with SYN-ACK, and the client completes with ACK. The two kernels carry out this three-way handshake; applications never see the packets. - The new socket. When the connection is established,
acceptreturns a new socket (fd 4). fd 3 keeps listening. A single listening socket can thus give rise to thousands of connection sockets. - Data and close. Data flows with
writeandread. The kernel puts the data intosk_buffs and adds the TCP/IP headers; the driver writes the packet to the card's ring buffer.closesends FIN to the other side.
socket, bind, listen, accept, connect, the three-way handshake, data, and FIN.A server with many clients can open a thread for every connection. With thousands of connections this becomes expensive. Linux's answer is epoll. The server registers the sockets it is interested in once. Then, with a single epoll_wait call, it gets only the list of sockets that are ready. The cost is proportional not to the total number of connections but to the number of ready sockets.
15.10File systems
15.10.1The directory tree and mounting
Unlike the drive letters of Windows, Linux has a single directory tree (Figure 15.27). Another file system is mounted on any directory of the tree. After the command mount /dev/sdb1 /mnt/usb, the root directory of the USB stick appears at /mnt/usb. The old contents of the mount point are hidden for as long as the mount lasts.
/mnt/usb.The roles of the directories are defined by the Filesystem Hierarchy Standard (FHS). /usr holds read-only, shareable software: commands in /usr/bin, shared libraries in /usr/lib, and kernel modules in /usr/lib/modules. /etc holds configuration files in text form. /var holds variable data (logs, queues, caches), /home the user directories, and /root the administrator's directory. The kernel and the initramfs are in /boot. /tmp is for temporary files and on most distributions is a tmpfs in RAM. /dev, /proc, and /sys are not on disk; they are pseudo file systems the kernel generates in memory. Most distributions have moved /bin, /sbin, and /lib under /usr with “usrmerge”. The old paths remain as symbolic links for compatibility.
15.10.2VFS objects
Linux uses dozens of file systems through the same calls: ext4, XFS, Btrfs, FAT, NFS, procfs. The virtual file system (VFS) makes this possible. The VFS defines four object types (Figure 15.28):
- superblock: a mounted file system. The block size, the root inode, and the file-system operations are here.
- inode: the file itself. Its size, permissions, times, and the location of its data. The in-memory
struct inodeis a copy of the on-disk inode. - dentry: the link between a name and an inode.
"x.txt" → inode 1234. It is kept in a cache to speed up path resolution. - file: an open-file session. The file position (
f_pos), the open flags, and the reference count.
struct file, the dentry, and the inode. A and its child A′ share the same struct file; C has opened the same file separately.The situation in the figure makes the three levels of open-file tables concrete. Process A opened x.txt and read 150 bytes. Then it called fork. Descriptor 3 of the child A′ points to the same struct file #1; its reference count is 2 and the position is shared. If A′ reads 10 more bytes, A's position also becomes 160. Process C opened the same file by itself. Its struct file #2 is separate and its position is 0. Both struct files point to the same dentry, and the dentry to the same inode. A process's descriptor table lives in task_struct → files_struct.
Every object has an operations table: super_operations, inode_operations, file_operations, dentry_operations. When the VFS does a job, it calls the function pointer in these tables. On ext4, read goes to ext4's read function; on NFS, to an RPC over the network; on procfs, to a function that turns kernel data into text on the spot. The calling program does not see the difference.
15.10.3File and directory calls, stat
The system-call interface of the file system is small (Table 15.13). A few details are often confused. rmdir removes only an empty directory. rename is atomic: if the target name exists, it is replaced in one step; the safe way to update a file is to write the new contents to a temporary file and rename it. opendir, readdir, and closedir are not system calls; they are library functions built on getdents64.
| Call | Function |
|---|---|
open, creat, close | Open / create and return an fd; close the descriptor |
read, write, lseek | Read / write at the position; move the position |
stat, fstat, lstat | Get information (lstat: the link itself) |
pipe, dup2, fcntl | Create a pipe; duplicate an fd; locks and flags |
mkdir, rmdir | Create / remove a directory (if empty) |
link, unlink, symlink | Add / remove a name; create a symbolic link |
rename, chdir | Move (atomic); change the working directory |
getdents64 | Read directory entries |
stat resolves a path, reads the inode, and copies its fields into struct stat (Figure 15.29). st_ino is the inode number, st_mode the type and permission bits, st_nlink the hard-link count, and st_size the size in bytes. st_blocks gives the space allocated on disk in 512-byte units; for a sparse file it can be much smaller than st_size. There are three timestamps: st_atime is the last access, st_mtime the last content change, and st_ctime the last inode change. st_ctime is not the creation time; chmod or link updates it as well. The creation time can be read only with the newer statx() call, from the stx_btime field.
stat: the path is resolved, the inode is read, and the fields are copied into struct stat.15.10.4File locking
Processes that share a file can lock byte ranges with fcntl. A lock is described with a struct flock: the type (F_RDLCK shared, F_WRLCK exclusive), the start (l_start), and the length (l_len). Shared locks may overlap one another; an exclusive lock may overlap no lock at all. This is the byte-level counterpart of the readers–writers lock.
On a 16-byte file, A places a shared lock on bytes 4–7, B on 6–9, and C on 2–11, in that order. Then D asks for an exclusive lock on byte 9 alone. Which requests are granted?
- A:
F_RDLCK,l_start= 4,l_len= 4. There is no lock on the file; granted. - B: the range 6–9 overlaps A at 6–7. Both are shared; granted.
- C: 2–11 covers all of A and B. Shared again; granted. Bytes 6 and 7 are now covered by three locks.
- D: byte 9 is within the ranges of B and C. An exclusive lock conflicts with shared locks. If requested with
F_SETLK, the call returns an error without waiting (EAGAINorEACCES). If requested withF_SETLKW, D waits until B and C release their locks.
Two processes waiting with F_SETLKW may end up waiting for each other's locks. The kernel tracks the wait relationships; if it detects a cycle, it returns EDEADLK to the waiting call. This is a real example of deadlock detection. These locks are advisory: a process that does not ask for the lock can still write to the file. For a whole file there is the simpler flock(). An important flaw of fcntl locks is that they belong to the process. When the process closes any descriptor of the file, all its locks are dropped. Threads in the same process also cannot tell the locks apart. OFD locks (F_OFD_SETLK), tied to the open file description, fix this flaw.
15.10.5The disk layout of ext2 and ext4
The layout of the classic UNIX file system was simple: a boot block, a superblock, an inode table, and data blocks. In this layout a file's inode could be at the start of the disk while its data was anywhere; the disk arm kept travelling between the two. ext2 divided the disk into block groups (Figure 15.31). Each group has its own block bitmap, inode bitmap, inode table, and data blocks. The kernel tries to place a file's inode and data in the same group, and a directory's files near the directory's group. The superblock and the group descriptors are backed up in some groups; if the first copy is damaged, it is recovered from the backup.
An ext2 inode holds 12 direct block pointers plus single, double, and triple indirect pointers. With 4 KiB blocks, one indirect block holds 1024 pointers. The reachable space grows multiplicatively: 12 × 4 KiB = 48 KiB, + 1024 × 4 KiB = 4 MiB, + 1024² × 4 KiB = 4 GiB, + 1024³ × 4 KiB = 4 TiB. The theoretical limit with indirect blocks is thus about 4 TiB. The real limit in ext2, however, is 2 TiB: the 32-bit i_blocks field in the inode counts allocated space in 512-byte units and runs out at 232 × 512 B = 2 TiB. The inode number of the root directory is always 2; 1 was formerly reserved for the list of bad blocks.
For large files, ext4 uses extents instead of indirect blocks. An extent describes a contiguous range of blocks with three numbers: logical block, length, and physical block. The extent (0, 2048, 34816) says that the first 2048 blocks of the file, that is, its first 8 MiB, sit contiguously on disk starting at block 34816. With indirect blocks the same information meant 2048 pointers and two indirect blocks. Four extents fit in the inode; if more are needed, the extents are placed in a tree rooted at the inode. A single extent covers at most 32,768 blocks, that is, 128 MiB with 4 KiB blocks. With 4 KiB blocks a file can be at most 16 TiB. ext4 also uses delayed allocation: it does not decide where the data blocks go until the moment the data is to be written to disk, so it can choose large contiguous extents.
15.10.6Journaling in ext4
A write() followed by fsync() changes several blocks. The data itself (D) is written; alongside it the metadata changes: the inode (M1), the block bitmap (M2), and the extent (M3). If the power fails after some of these blocks have been written and before the others, the file system is left inconsistent. For example, the bitmap shows a block as in use but no inode points to that block. ext4 solves this problem with journaling. The journal is managed by the JBD2 layer (Figure 15.32).
- Data first. In the default
data=orderedmode, D is written first to its final place. The metadata therefore never points to a block containing garbage. - The journal transaction. M1, M2, and M3 are written to the journal as a single transaction (T42): a descriptor block, copies of the metadata blocks, and, at the end, a commit record. The moment the commit record reaches the disk, the transaction is durable.
- Checkpoint. The metadata blocks are then written to their final places, without hurry. The space in the journal is reused; the journal is a circular buffer.
- Recovery. After a crash, a full fsck scan is not performed at mount time. The journal is read. Transactions that have a commit record are replayed. Incomplete transactions without a commit are discarded, and the file system stays in its old consistent state. This takes seconds.
The other two modes offer different trade-offs. data=journal writes the data to the journal too: it is the safest, but the slowest, because every data block is written twice. data=writeback gives no ordering guarantee between data and metadata: it is fast, but after a crash a file may show old blocks or blocks containing garbage. By default ext4 commits about every five seconds. An append for which fsync was not called can be lost entirely if the power fails before the commit; but thanks to data=ordered, the file never shows garbage. XFS also uses metadata journaling. Btrfs, instead of a journal, stays consistent through copy-on-write.
Believing that journaling protects data. In the default mode the journal protects only metadata and guarantees only consistency. The application's latest writes can be lost without fsync. A program that wants to be sure data has reached the disk must call fsync.
15.10.7Directories and path resolution
In ext2/ext4, a directory is an ordinary file made of entries. Each entry holds the inode number, the record length, the name length, the file type, and the name itself. A deleted entry is not destroyed; its space is added to the record length of the previous entry. In directories with thousands of entries, linear search becomes slow. For such directories ext4 uses a tree (htree) ordered by the hash of the names.
How is open("/home/ali/notes.txt") resolved? (Figure 15.33)
- The path is absolute; the search starts at the root. The root directory's inode (2) is read.
homeis looked up among the entries in its data blocks: 131073. The x (search) permission is checked for the root. aliis looked up in the data of thehomedirectory (131073): 131074.notes.txtis looked up in thealidirectory (131074): 132010. Had the path been relative, the search would have started at the process's working directory.- Inode 132010 is read. The permissions are checked; if read permission is granted, a
struct fileis created and the smallest free descriptor, for example 3, is returned.
/home/ali/notes.txt: inode 2 → 131073 → 131074 → 132010.Inode numbers are not random. The closeness of 131073 and 132010 reflects ext4's effort to put a directory's files in the same block group. If every step required a disk read, path resolution would be very slow. The dentry cache (dcache) keeps name → inode mappings in memory. Frequently used paths are resolved without ever going to disk. The dcache also stores negative results: the fact that “there is no such name in this directory” is cached too. A program that looks up a nonexistent file on every open therefore does not burden the disk.
15.10.8Code trace: the link count and unlink
On Linux, a file's name and the file itself are separate things. The name is a directory entry; the file is the inode. Two kinds of links make use of this separation (Figure 15.34):
$ ln a.txt backup/b.txt # hard
$ ln -s a.txt s # symbolic
$ ls -li
500 -rw-r--r-- 2 ali ali 9 a.txt
777 lrwxrwxrwx 1 ali ali 5 s -> a.txtA hard link is a second name given to the same inode. a.txt and backup/b.txt point to the same inode (500), and the link count is 2. A symbolic link, on the other hand, is a separate inode (777); its content is just the path of the target. ls -l shows it with type l and in the form s -> a.txt. Its size is 5, because "a.txt" is five characters. A hard link cannot cross a file-system boundary, because an inode number is meaningful only within its own file system. It also cannot be made to directories, because it could create a cycle in the tree. A symbolic link can point to another file system and to directories. The price is that the link dangles when the target is deleted.
An inode carries two counters. The link count counts the directory entries on disk; the open-file count counts the references in memory. The data is freed only when both drop to zero. The following program changes these two counters step by step:
int fd = open("a.txt", O_CREAT|O_RDWR, 0644);
write(fd, "data", 4);
link("a.txt", "b.txt"); /* hard link */
symlink("a.txt", "s.txt"); /* symbolic */
unlink("a.txt");
int r1 = open("b.txt", O_RDONLY);
int r2 = open("s.txt", O_RDONLY);
unlink("b.txt");
close(r1);
close(fd);| Line | Directory entries | 812 links | 812 open | Result |
|---|---|---|---|---|
1–2 open, write | a.txt → 812 | 1 | 1 | fd = 3 |
3 link | a.txt, b.txt → 812 | 2 | 1 | the data is not copied |
4 symlink | + s.txt → 813 ("a.txt") | 2 | 1 | 812 does not change |
5 unlink("a.txt") | b.txt, s.txt | 1 | 1 | data reachable through b.txt |
6 open("b.txt") | b.txt, s.txt | 1 | 2 | r1 = 4 |
7 open("s.txt") | b.txt, s.txt | 1 | 2 | r2 = −1, ENOENT |
8 unlink("b.txt") | s.txt | 0 | 2 | no name, but the data remains |
9 close(r1) | s.txt | 0 | 1 | fd 3 still works |
10 close(fd) | s.txt | 0 | 0 | inode and blocks freed |
The meaning of the lines is as follows. open allocates a new inode (812) and adds the entry a.txt → 812 to the directory. link only writes a new directory entry; a.txt and b.txt are equal, and the question of which one is the “original” has no answer. symlink creates a separate inode (813) and does not touch 812. unlink("a.txt") removes one name and lowers the link count to 1; “deleting” a name is not deleting the file. b.txt opens without trouble, and the smallest free descriptor, 4, is returned. When s.txt is opened, the kernel follows the path inside it, "a.txt". That name no longer exists: the symbolic link dangles, and open returns −1. unlink("b.txt") removes the last name too. The link count is 0, but since two descriptors are open, the inode and the data are not yet freed. ls no longer shows the file, yet reading and writing through fd 3 work. When the last descriptor is closed, both counters drop to zero and the blocks are freed.
The well-known pattern for temporary files relies on this behavior. The program opens the file and immediately calls unlink. The file appears in no directory, and no other process can find it by name. Even if the program crashes, the kernel closes the descriptors and the space returns by itself. Linux also offers the O_TMPFILE flag for this pattern: the file is created nameless from the start.
Deleting a large log file to free disk space and expecting the space to come back at once. As long as the process writing to the file keeps the descriptor open, the blocks are not freed; df does not change. Such deleted but open files can be found with lsof +L1. The right way is to restart the process, or to truncate the file instead of deleting it.
15.10.9Beyond ext4
The file systems Linux supports answer different needs (Table 15.15). ext4 is the default on most distributions because it is mature, fast, and has a reliable repair tool. XFS is strong in parallel I/O and with very large files; it is the default of RHEL. F2FS is a log-structured design suited to flash memory and is common on Android phones.
| File system | Notable feature | Typical use |
|---|---|---|
| ext4 | Journaling, extents, mature and fast fsck | Default on most distributions |
| XFS | Parallel I/O, large files, delayed allocation | RHEL default, large servers |
| Btrfs | Copy-on-write, snapshots, checksums, compression, subvolumes | Default on Fedora and openSUSE |
| F2FS | Flash-friendly log-structured design | Android phones |
| tmpfs | Entirely in RAM (page cache + swap) | /tmp, /run, /dev/shm |
| NFS, SMB | Network file systems | Shared home directories |
Btrfs's method of staying consistent differs from journaling (Figure 15.36). No block is ever overwritten. When block B4 changes, the new content is written to a free place, B4′. The node pointing to B4 must also change; a new copy of it (node′) is written as well. This chain continues up to the root, and a new root (v2) is created. The last step is for the superblock to point to the new root; this is a single atomic write. If the crash comes before this write, the old root (v1) is entirely valid. Keeping the old root gives a snapshot for free: the tree reached through v1 is the file system as it was before the change.
Thanks to the VFS, all of these file systems are used with the same system calls. Which file system is mounted on which directory is shown by findmnt or df -T.
15.10.10/proc and /sys
Linux also presents the kernel's internal state as files. These files are not on disk; they are generated on the kernel side at the moment they are read.
$ cat /proc/loadavg
0.42 0.37 0.30 2/1234 98765
$ grep -E "MemTotal|MemAvailable" /proc/meminfo
MemTotal: 16303452 kB
MemAvailable: 9876544 kB
$ ls /proc/self
cmdline cwd environ exe fd maps status …
$ cat /sys/block/nvme0n1/queue/scheduler
[none] mq-deadline kyber bfq
$ sysctl vm.swappiness # = /proc/sys/vm/swappiness
vm.swappiness = 60/proc (procfs) carries two kinds of information. There is a directory for every process: /proc/PID/status shows the state and memory usage, maps the VMAs, and fd/ the open descriptors. /proc/self is the directory of the reading process itself. Kernel statistics are here too. The first three numbers in the /proc/loadavg output are the load averages of the last 1, 5, and 15 minutes. 2/1234 gives the number of running and total tasks; the last number is the most recently assigned PID. The /proc/meminfo lines in the example say that 9.42 GiB (60.6%) of the total 15.55 GiB of memory is available. ps, top, and free read their data from here. The files under /proc/sys are tunable kernel parameters. sysctl vm.swappiness actually reads the file /proc/sys/vm/swappiness.
/sys (sysfs) presents the kernel's device model. Every device, driver, and bus is a directory. Each file holds a single value. The file /sys/block/nvme0n1/queue/scheduler shows the blk-mq scheduler: none, in square brackets, is selected. /sys/fs/cgroup is the interface of cgroup v2; resource limits are set by writing to the files in this directory.
15.11Security
15.11.1chmod and umask arithmetic
On Linux every file has three permission bits each for the owner, the group, and others: r for read, w for write, x for execute. In front of them stand three special bits: setuid, setgid, and the sticky bit. The twelve bits are written with four octal digits. Each octal digit is three bits: 7 = 111 = rwx, 5 = 101 = r-x, 4 = 100 = r--. chmod 754 script.sh therefore gives rwxr-xr--.
The symbolic form of chmod modifies the existing bits. g+w is a bitwise OR (OR 020), and o-r is bitwise masking (AND ~004). When chmod g+w,o-r is applied to 0754, the group write bit is set and the others' read bit is cleared: the result is 0770, rwxrwx--- (Figure 15.37).
chmod g+w,o-r: 0754 OR 020 AND ~004 = 0770.The umask is the mask of permission bits to be removed from the files a process newly creates. A new file asks for 666 and a new directory for 777. The actual permission is request & ~umask.
With umask 022 and 027, what permissions do touch a and mkdir d produce?
- umask 022: file 666 & ~022 = 0644 (
rw-r--r--), directory 777 & ~022 = 0755 (rwxr-xr-x). This is the default on most distributions. - umask 027: file 666 & ~027 = 0640 (
rw-r-----), directory 777 & ~027 = 0750 (rwxr-x---). Others can see nothing. - Octal subtraction happens to give the right result in the first case; in the second it produces a value such as 666 − 027 = 637 (
rw--wxrwx) that turns on wrong bits. umask clears bits; it does not subtract.
Each of the three special bits solves a different problem (Figure 15.38). setuid (4xxx), on an executable file, makes the effective user ID of the running process that of the file's owner. The passwd command has permission 4755 (rwsr-xr-x): when an ordinary user runs it, the process can write to /etc/shadow with root privilege. setgid (2xxx) does the same for the group; on a directory, it makes new files inherit the directory's group. The sticky bit (1xxx) is meaningful on directories. /tmp has permission 1777 (rwxrwxrwt): anyone can write, but a file can be deleted and renamed only by the file's owner, the directory's owner, or root (or a process with the CAP_FOWNER capability). An s or t that takes the place of x in the symbolic notation shows that the underlying x bit is also set. If x is off, an uppercase letter (S, T) is written.
rwsr-xr-x) and sticky + 777 = 1777 (rwxrwxrwt).The results can be checked with stat -c "%a %A" file; the command prints the octal and symbolic permissions together. umask -S shows the mask in symbolic form.
15.11.2Access control, root, and capabilities
When a process accesses a file, the kernel looks at the process's effective identities and selects a single permission class:
- If the effective uid is 0 (root), permission is granted. Only for an execute request is at least one x bit required on the file.
- If the effective uid is the file's owner, only the owner bits are examined.
- If the effective gid or one of the supplementary groups is the file's group, only the group bits are examined.
- Otherwise the others bits are examined.
The first matching class wins; later classes are never looked at. That is why the owner cannot read a file with permission ----rw-rw-, while group members and others can. The owner can, if they wish, give the permission back to themselves with chmod.
A process has two kinds of identities. The real uid is the user who started the process. The effective uid is the identity used in permission checks; in setuid programs the two diverge. The access() call deliberately tests access with the real uid. It lets a setuid program answer the question “can this user really read this file?” setuid and setresuid change identities; a well-written service uses these calls to drop its privileges once its privileged work is done. User and group IDs are kept in the files /etc/passwd and /etc/group. Password hashes are in /etc/shadow, which only root can read. sudo gives an authorized user root privilege on a per-command basis.
In the classic model, root can do everything and everyone else can do no privileged work. This “all or nothing” approach is dangerous. ping had to be setuid root just to open a raw socket. A bug inside it opened the whole system to an attacker.
A capability is a piece of root's privileges that can be granted and taken away independently. Linux divides root's power into more than 40 capabilities. Examples: CAP_NET_RAW is for opening raw sockets, CAP_NET_BIND_SERVICE for binding to ports below 1024, CAP_SYS_MODULE for loading modules, and CAP_DAC_OVERRIDE for bypassing file permissions.
After the command setcap cap_net_raw+ep /usr/bin/ping, ping can open raw sockets without being setuid root. Even if a vulnerability is found, the attacker can only open raw sockets; they cannot read files or load modules. Capabilities are kept as per-process sets and stored in the cred structure of task_struct.
15.11.3Code trace: the file permission check
The kernel's permission check is done, roughly, by the following function. req is a bit mask: read is 4, write is 2, execute is 1.
int has_perm(cred *c, inode *f, int req) {
int bit, m = f->mode; /* r4 w2 x1 */
if (c->euid == 0) /* root */
return !(req & 1) || (m & 0111);
if (c->euid == f->uid)
bit = (m >> 6) & 7; /* owner */
else if (in_group(c, f->gid))
bit = (m >> 3) & 7; /* group */
else
bit = m & 7; /* other */
return (bit & req) == req;
}The return expression in the root branch is a little surprising. !(req & 1) is true if the request does not include execute; for read and write, the permission bits are never looked at. If execute is requested, m & 0111 looks for at least one x bit among owner, group, or others. Even root cannot execute a file that has no x bit at all, because such a file is most likely not a program. The following if chain selects a single class. The three selected bits are taken by shifting and masking: (m >> 6) & 7 for the owner, (m >> 3) & 7 for the group, and m & 7 for others. The last line tests whether all the requested bits are set.
Let the file report.txt be owned by ali (uid 1000), with group team and mode 0640 (rw-r-----). veli (1001) is in the team group; can (1002) is not.
| Who, request | Mode | Class | Bits | Test | Result |
|---|---|---|---|---|---|
| ali, w (2) | 0640 | owner | 6 (rw-) | 6 & 2 == 2 | granted |
| veli, w (2) | 0640 | group | 4 (r--) | 4 & 2 = 0 ≠ 2 | denied |
| veli, r (4) | 0640 | group | 4 (r--) | 4 & 4 == 4 | granted |
| can, r (4) | 0640 | other | 0 (---) | 0 & 4 = 0 ≠ 4 | denied |
| root, r (4) | 0640 | root | — | no x in the request | granted |
| ali, r (4) | 0066 | owner | 0 (---) | 0 & 4 = 0 ≠ 4 | denied |
EACCES).The last row is the most instructive case of the trace. With mode 0066 (----rw-rw-), can and veli can read the file. ali, being the file's owner, falls into the owner class; group membership is never looked at. Since the owner bits are empty, the request is denied. In the real kernel there are other layers before and after this check: access control lists (ACLs), capabilities, and security modules.
15.11.4Containers: namespaces and cgroups
A container is not a separate object in the Linux kernel. It is ordinary processes isolated by two kernel features: namespaces and cgroups.
A namespace is a kernel feature that gives a group of processes a separate view of system resources. The processes in a namespace see only the PIDs, mount points, network interfaces, or user IDs of that view. A control group (cgroup) is a kernel feature that limits and measures the resource use of a group of processes, such as CPU, memory, I/O, and the number of processes.
A short rule separates the two: a namespace determines what is seen; a cgroup determines how much is used. Linux has eight namespace types (Table 15.17). Each is selected by a flag in the clone, unshare, or setns call. Which namespaces a process is in can be read from the links in the directory /proc/PID/ns/; if two processes are in the same namespace, the links show the same number.
| Namespace | Flag | Resource it isolates |
|---|---|---|
| PID | CLONE_NEWPID | Process IDs; the first process inside is PID 1 |
| Mount | CLONE_NEWNS | Mount points, the file-system tree |
| Network | CLONE_NEWNET | Network interfaces, routing table, ports, firewall |
| UTS | CLONE_NEWUTS | Hostname and domain name |
| IPC | CLONE_NEWIPC | System V IPC, POSIX message queues |
| User | CLONE_NEWUSER | uid/gid mapping: root inside is an ordinary uid outside |
| cgroup | CLONE_NEWCGROUP | The visible root of the cgroup tree |
| Time | CLONE_NEWTIME | Boot-time and monotonic clocks (5.6+) |
The mount namespace was the first historically. Since nobody then expected other types, the flag is named just CLONE_NEWNS. The user namespace is special: even an unprivileged process can create it and be root inside. The uid 0 inside is mapped to, for example, uid 100000 outside. The root inside has authority only over resources in its own namespace. “Rootless” containers rely on this feature.
What a container runtime (runc, crun) does can be followed in five steps (Figure 15.40).
- Namespaces. New namespaces are created with
clone()orunshare(): its own PID numbers, mount tree, network stack, hostname, IPC, user mapping, cgroup, and clock view. - Root file system. In the mount namespace,
pivot_rootswitches to the image's root file system. The root is usually overlayfs: the image's read-only layers are stacked, and a writable layer private to the container is added on top. A hundred containers running from the same image share the lower layers. - Resource limits. Limits are written to the cgroup v2 directory:
cpu.max="50000 100000",memory.max= 512M,pids.max= 100. - Attack surface. Unneeded capabilities are dropped. The
no_new_privsflag is set, so even setuid programs cannot grant privilege. A seccomp filter that blocks dozens of risky system calls and an AppArmor or SELinux profile are applied. - Launch. Finally
execveruns the application. Inside, the application is PID 1; on the host it is PID 48213.
What does "50000 100000" in the cpu.max file mean? What is written to give a container exactly two CPUs?
- The format is
"quota period", both in microseconds. In each period of 100,000 µs (100 ms), the group may use a total of 50,000 µs of CPU time. - 50,000 / 100,000 = 0.5: the group gets half a CPU's worth of time. If it exhausts the quota, it is not run for the rest of the period, even if there are idle CPUs on the machine.
- For two CPUs the quota must be twice the period:
"200000 100000". The quota can be spread over several CPUs; the group's two threads can run on two cores at the same time.
In cgroup v2, all controllers (cpu, memory, io, pids) share a single hierarchy. In the old v1, each controller had its own tree, and a process could end up in inconsistent groups in different trees. If the memory limit is exceeded, the OOM killer chooses a victim only from that group. systemd also puts every service in its own cgroup. systemd-cgls shows the tree and systemd-cgtop the groups' live usage.
Containers all share the same kernel. This makes them much lighter than virtual machines: a container starts in milliseconds and spends no memory on a kernel of its own. The price is weaker isolation. A vulnerability in the kernel can affect all containers at once. With a virtual machine, an attacker must first break through the guest kernel and then the hypervisor.
Treating a namespace as a security boundary and a cgroup as a visibility tool. A PID namespace hides processes but does not limit memory use; an unlimited container can consume the host's memory. Conversely, a cgroup limits memory but does not hide the processes on the host. For a container, both are needed together.
15.11.5seccomp and Linux security modules
A system call passes through several checks before reaching its object (Figure 15.41). As an example, let an application call open("/etc/shadow").
EPERM or EACCES.- seccomp. If the process has installed a seccomp-BPF filter on itself, the call passes through it first. The filter is a small BPF program that looks at the call's number and arguments. It can allow the call, return an error code, or kill the process. Chrome's renderer processes, systemd services, Docker, and Android applications use these filters.
- DAC. Discretionary access control looks at the rwx bits, the uid, and the gid. It is called discretionary because the file's owner can change the permissions at will.
- Capabilities. If DAC denies, the kernel checks whether the process has a capability that overrides the denial, for example
CAP_DAC_OVERRIDE. - LSM. Finally the hooks of the Linux security modules run. These implement mandatory access control: the rules are set by the administrator, and even root cannot bypass them.
There are three main security modules. SELinux is label-based: every process and file has a type, and the policy says what each type may do to each other type. It is used on RHEL, Fedora, and Android. AppArmor uses path-based profiles: “this program may access only these files.” It is easier to write and is common on Ubuntu, SUSE, and Debian. Landlock (5.13) lets an unprivileged process put itself in a sandbox: “from now on I can write only under ./data.” Once a process has set this restriction, it cannot lift it; its children inherit it too.
15.12Android
Android is a system that runs on the Linux kernel but does not use the GNU user space (Figure 15.42). Its C library is Bionic, written by Google. Applications are written in Java or Kotlin and run on the Android Runtime (ART). The hardware abstraction layer (HAL) separates vendors' drivers from the framework. Android brought three important additions to the kernel: the Binder IPC mechanism, wakelocks for power management, and mandatory SELinux. Binder eventually entered the mainline kernel as well.
The launch of an application is an interesting use of fork. At boot, init starts a process called zygote. zygote loads ART and the framework's thousands of classes and resources once, and waits. When an application is opened, zygote calls fork. The loaded pages are shared with COW; each application need not reload the classes, and startup is faster. Memory is saved too, because the framework's pages are a single copy across all applications. The child process then switches to the application's unique uid, its SELinux context (untrusted_app), and its seccomp filter. No exec follows the fork here; the image that is already ready is used.
An application calls a system service such as location or the camera through Binder. Binder is a remote procedure call mechanism that works over the /dev/binder device. The kernel moves the data to the receiver's pre-mapped buffer with a single copy. It also passes along the caller's uid. The application cannot forge this uid, because the kernel adds it. The service checks permission accordingly.
Android's sandbox rests on Linux's oldest protection mechanism: every application is a separate Linux user. The application in the figure runs with uid 10123, and the directory /data/data/com.example.app is open only to this uid. If an application tries to read another application's files, ordinary file permissions stop it. When memory runs low, lmkd in user space steps in instead of the kernel's OOM killer. lmkd watches memory pressure with PSI counters and kills unimportant background applications. When the user returns to that application, Android restarts it from its saved state.
15.13The course's concepts in Linux
This case study found a concrete counterpart in Linux for each of the general concepts of the course (Table 15.18). The last row of the table sums up the direction Linux is taking today: while the mechanism stays in the kernel, the policy is increasingly left to the user.
| Topic | Concept | Counterpart in Linux |
|---|---|---|
| Structures | System call, monolithic kernel | syscall, LKM, eBPF |
| Processes | PCB, creation, IPC | task_struct, fork/exec/wait, signals, pipes |
| Threads | Kernel-thread model | clone(), NPTL 1:1 |
| Scheduling | Fair share, real time | EEVDF, FIFO/RR/DEADLINE, sched_ext |
| Synchronization | Lock, condition variable | futex, spinlock, RCU |
| Deadlock | Detection and prevention | lockdep, fcntl EDEADLK |
| Memory | Allocation, fragmentation | zones, buddy lists, SLUB |
| Virtual memory | Paging, replacement | 4/5-level tables, COW, MGLRU, zswap, OOM |
| File systems | Inode, directory, journal | VFS, ext4, XFS, Btrfs |
| I/O | Driver, scheduling | device files, blk-mq, io_uring |
| Multiprocessor | Load balancing, NUMA | per-CPU queues, scheduling domains |
| Security | Access control, isolation | rwx, capabilities, namespaces, SELinux, seccomp |
| Design | Separation of mechanism and policy | cgroup, sched_ext: policy in user space |
Two mechanisms named in the table but not detailed in this chapter deserve a short explanation. The futex (fast user-space mutex) is the foundation of pthread locks. When the lock is free, acquiring and releasing it happen entirely in user space, with a single atomic instruction. The kernel is entered only when there is contention, that is, when a thread has to sleep. RCU (read-copy-update) is a synchronization method in which readers read the data structure without taking any lock. The writer prepares a new copy of the structure and swaps the pointer atomically. The old copy is not freed until all readers that might still be reading it have finished. lockdep is the kernel's own deadlock checker: it tracks the order in which locks are taken and, the moment it sees a cycle in that order, it warns, before any deadlock has actually occurred.
15.14Summary
- Linux is a monolithic kernel that implements the POSIX interface of UNIX with freshly written code. Combined with the GNU tools, it forms distributions. A release comes out about every 9–10 weeks; the last release of each year becomes an LTS.
- There are three interfaces between the layers: user, library, and system call.
printfwrites to a buffer; the real system call iswrite, which enters the kernel with thesyscallinstruction. - The shell builds redirections from left to right with
dup2, and pipelines withpipe,fork,dup2, andexec. If an unused write end is not closed, the reader cannot see EOF. - Loadable modules give the monolithic kernel flexibility but run with kernel privilege. eBPF safely runs small verified programs in the kernel.
- On Linux a process and a thread are the same structure:
task_struct. The difference is whether substructures such asmm,files,fs, andsighandare shared. Theclone()flags select this; NPTL builds the 1:1 model. The PID the user sees is thetgid. - Signals wait as a bit in the pending set and, on return to user mode, are delivered starting from the lowest number of the set ready = pending & ~blocked. Blocking is deferring; classic signals are not counted.
- The fair class has run with EEVDF since 6.6: among eligible tasks (v ≤ V), the one with the earliest virtual deadline is chosen. The share depends on weights (nice 0 → 1024); a short slice gets a task chosen more often.
- The address space consists of VMAs and is kept in a maple tree. On x86-64, a 48-bit address is translated by a four-level walk of 9+9+9+9+12 bits; LA57 adds a fifth level.
- Physical memory follows the node → zone → page hierarchy; the buddy allocator manages blocks of 20–210 pages. SLUB keeps small objects in slabs; the free-list pointer lives inside the free object, and the fast path is lock-free.
- Free RAM goes to the page cache. Under pressure, kswapd, MGLRU, zswap/swap, direct reclaim, and, as a last resort, the OOM killer come into play.
- In device files the major number selects the driver and the minor number selects the unit. The block layer is multi-queue with blk-mq. Drivers attach to the VFS through the
file_operationstable. - The four VFS objects are the superblock, inode, dentry, and file. ext4 uses block groups, extents, and
data=orderedjournaling. Data is freed when both the link count and the open-file count reach zero. - In permission checks the first matching class wins; umask clears bits (request & ~umask). Capabilities split root into pieces. Container = namespaces (what is seen) + cgroups (how much is used) + seccomp and LSM.
- Android uses the same kernel with Bionic, ART, Binder, zygote, and a uid per application.
15.15Key terms
- monolithic kernel
- loadable kernel module
- system call
- shell
- pipe, pipeline
- file descriptor
- process control block (
task_struct) - thread group ID
- signal
- copy-on-write
- virtual runtime
- eligibility, virtual deadline
- bootloader
- virtual memory area (VMA)
- buddy system
- slab allocator
- page cache
- virtual file system (VFS)
- file locking
- journaling
- hard link / symbolic link
- capability
- namespace
- control group (cgroup)
- container
15.16Test Yourself
On x86-64, 4 KiB pages and a four-level table are used. What are the four indices and the offset of the address 0x00007ffd4a3b2010? If the frame number in the PTE is 0x2f00a, what is the physical address?
Answer
PGD = address >> 39 = 255, PUD = 501, PMD = 81, PTE = 434, offset = 0x010. The physical address is 0x2f00a × 4096 + 0x010 = 0x2f00a010. This is a stack address: PGD 255 is the last entry of the user half.
Two continuously ready tasks, nice 0 (w = 1024) and nice 1 (w = 820), share a single CPU. How is the CPU shared in the long run? By how much does the
vruntimeof the nice 1 task grow when it runs for 4 ms?Answer
The share is proportional to the weight: 1024 / 1844 ≈ 55.5% and 820 / 1844 ≈ 44.5%. One nice step shifts the share by about 10 points. Δv = 4 × 1024 / 820 ≈ 4.995 ms.
On a queue, V = 12 ms. There are tasks A (v = 10, d = 14), B (v = 12, d = 13), and C (v = 13, d = 12). Which does EEVDF choose? Which would CFS have chosen?
Answer
The eligible tasks are those with v ≤ V: A and B. Although C has the earliest deadline, it is not eligible, because it has received more than its share. Between A and B, the one with the earlier deadline, B, is chosen. CFS would have chosen the smallest
vruntime, that is, A.A process has blocked
SIGUSR1and installed a handler forSIGINT. While it sleeps, signals 17, 10, and 2 arrive in that order. On return to user mode, which signals are delivered, and in what order? Which one waits?Answer
Pending {2, 10, 17}, blocked {10}; ready {2, 17}. The lowest number goes first: 2 (the handler runs), then 17 (
SIGCHLD, default: ignore). 10 stays in the pending set and is delivered when the block is lifted. Arrival order plays no role in the selection.On a fresh
kmalloc-512slab (4 KiB, eight objects: +0, +512, …), the following operations are performed: a, b, c = alloc; free(b); free(a); d, e, f = alloc. Which addresses do d, e, and f get?Answer
a = +0, b = +512, c = +1024; freelist +1536. free(b): +512 → +1536. free(a): +0 → +512 → +1536. The last one freed is handed out first: d = +0, e = +512, f = +1536.
How does a task created with
clone(CLONE_VM | CLONE_FILES | SIGCHLD, …), withoutCLONE_THREAD, appear inps? If the child opens a new file, can the parent use it?Answer
Because there is no
CLONE_THREAD, the child has its own TGID; it appears inpsas a separate process and sendsSIGCHLDto the parent when it ends. Even so, it shares the address space and the descriptor table with the parent. The number of the file the child opened is also valid in the parent; the parent can read with the same number.With umask 077 and 002, what permissions do
touch aandmkdir dproduce?Answer
umask 077: file 0600 (
rw-------), directory 0700 (rwx------). umask 002: file 0664 (rw-rw-r--), directory 0775 (rwxrwxr-x). 002 is used in shared directories for group work.The file
progis owned by ali, with group team and mode 0750. veli is in the team group; can is not. Can veli executeprog? Can can read it? Can root execute a script whose mode is 0644?Answer
veli falls into the group class: bit 5 (r-x), 5 & 1 = 1, granted. can falls into the others class: bit 0, denied. For root, the bits are not examined for read and write, but execution requires at least one x bit; 0644 has none, so it is denied (
EACCES).echo x > f,ln f g, andln -s f hare run. A process opensgand keeps the descriptor. Thenrm fandrm gare run. When are the data blocks freed? What doescat hprint?Answer
f and g are the same inode; the link count is 2. After the two
rms the link count is 0, but because an open descriptor exists, the blocks are freed only when the process closes the descriptor. h holds the path"f"; that name no longer exists.cat hgives the error “No such file or directory” (ENOENT).A container's
cpu.maxfile contains"25000 100000". How much CPU can the container use? Does this limit affect the output ofpsinside?Answer
25 ms in every 100 ms period, that is, a quarter of a CPU. The limit is a cgroup setting; it determines only how much is used. What
psshows is determined by the PID namespace, not by the cgroup.
15.17Further reading
- R. Love, Linux Kernel Development, 3rd ed., Addison-Wesley, 2010: its chapters on process management, scheduling, memory, and the VFS show, in plain language, the kernel-code counterparts of the structures in this chapter, from
task_structto the slab allocator. It belongs to the CFS era. - M. Kerrisk, The Linux Programming Interface, No Starch Press, 2010: the most comprehensive programmer's reference for signals, process creation, pipes, file locking, and capabilities; the author's manual pages at man7.org are kept up to date.
- Linux kernel documentation, docs.kernel.org, the pages “EEVDF Scheduler” and “Control Group v2”: first-hand accounts of the concepts of EEVDF and of all the files of the cgroup v2 controllers.
- I. Stoica, H. Abdel-Wahab, “Earliest Eligible Virtual Deadline First: A Flexible and Accurate Mechanism for Proportional Share Resource Allocation”, Old Dominion University technical report, 1995: the theoretical foundation of the concepts of lag, eligibility, and virtual deadline.
15.18References
- A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th ed. (2014) / 5th ed. (2023), Pearson — Chapter 10: Case Study 1: Unix, Linux and Android.
- A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th ed., Wiley, 2018 — Chapter 20: The Linux System.
- R. Love, Linux Kernel Development, 3rd ed., Addison-Wesley, 2010.
- M. Kerrisk, The Linux Programming Interface, No Starch Press, 2010; man7.org manual pages (namespaces(7), capabilities(7), signal(7), fcntl(2), clone(2)).
- The Linux Kernel Documentation, docs.kernel.org — scheduler (EEVDF, sched-ext), admin-guide/mm (MGLRU, zswap), block (blk-mq), filesystems (vfs, ext4), userspace-api (seccomp, landlock), admin-guide/cgroup-v2.
- Android Open Source Project, source.android.com — architecture, Binder, application sandbox.
- D. M. Ritchie, K. Thompson, “The UNIX Time-Sharing System”, Communications of the ACM, 17(7), 1974.
- I. Stoica, H. Abdel-Wahab, “Earliest Eligible Virtual Deadline First: A Flexible and Accurate Mechanism for Proportional Share Resource Allocation”, technical report, Old Dominion University, 1995.
Related pages: Chapter 15 slides · © Sercan Külcü. All rights reserved.