Operating Systems · Lecture Notes
Chapter 2: Operating-System Structures
An operating system looks like a single program. Inside it, however, are dozens of components such as process management, memory management, the file system, device drivers, and the network stack. In which mode these components run and how they talk to each other determine the system's speed, reliability, and maintainability. These notes begin with the services the operating system offers to users and programs. They then introduce the basic concepts of process, address space, file, mounting, pipe, and deadlock. How the hardware protects the operating system, how programs request services from the kernel through system calls, and the basic POSIX calls are explained step by step with code traces. The last sections compare monolithic, layered, microkernel, modular, hybrid, and exokernel structures, and touch on virtual machines, the linker and loader, and the boot process.
Learning outcomes
- Services and concepts
- Explain the services an operating system provides and the concepts of process, address space, file, mounting, and pipeline.
- System calls
- Trace step by step the transition from user mode to kernel mode, parameter passing, and the basic POSIX calls.
- Kernel structures
- Compare the monolithic, layered, microkernel, modular, hybrid, and exokernel structures with their strengths and weaknesses.
- Virtualization and booting
- Recognize the concepts of virtual machine and container, the work of the linker and loader, and the steps of booting.
2.1Structure and services
An operating system can be studied from two angles. Someone looking from the outside asks what the system does: which services does it offer, and how do programs reach them? Someone looking from the inside asks how the system is built: where do the components run, and how do they call one another? This section takes up both questions briefly. It first introduces what is meant by “structure” and then the services the operating system offers to the outside.
2.1.1Why does structure matter?
Today's operating system is not a small program by itself. The process manager that creates and terminates processes, the memory manager that shares out memory, and the file system that presents data on disk as files are only three of its parts. Each device has its own driver, and network packets have a stack of their own. The source code of the Linux kernel passed 40 million lines in 2025. Writing, understanding, and maintaining software of this size as a single disorganized heap is impossible.
The designer makes two decisions for each component. The first is where the component will run: in kernel mode, which uses all the privileges of the hardware, or in user mode, with restricted privileges? The second is how the components will communicate: will one call the other like an ordinary function, or will the two components send each other messages?
The general strategy for where the components of an operating system run (kernel mode or user mode) and how they communicate (function call or message) is called the operating system structure.
The choice of structure directly affects the system's everyday life. How well complexity is managed and how many files a change touches depend on this choice. So do how many lines of code a bug must be searched for in and how easily the system can be ported to another processor. However, no structure is best by every criterion. Figure 2.1 places three main goals at the corners of a triangle: performance, reliability and isolation, and flexibility and maintainability. A design that approaches one corner usually moves away from the others.
An example makes this trade-off concrete. If file system code runs inside the kernel together with the other components, reading a file costs no more than a few function calls. If the same code runs in user mode as a separate process, every request needs a message and several mode switches; reading becomes more expensive. In return, a bug in the file system code crashes only that process in the second case, while in the first it can bring down the whole kernel. A desktop computer, a data center server, an embedded device, and an aircraft's flight control computer strike this balance at different points. This is why there is no single correct structure.
Confusing the structure with the interface the user sees. Two operating systems can offer the same system calls, the same commands, and the same disk format and still have very different structures. Structure concerns the division of labor inside the system; a user looking from outside often does not see the difference.
2.1.2Operating system services
The operating system prepares a working environment for the programs running on it and offers a set of services that are part of this environment. The details of the services vary from system to system, but the main groups are the same in almost every system. Figure 2.2 shows these groups as layers.
The most important detail in the figure is the transition point between the layers. Whether the user clicks a window or types a command at the command line, what they do ultimately turns into one or more system calls. The interface is an intermediary that translates the user's request into system calls. The services themselves are below the system call layer, inside the operating system, and manage the hardware directly.
2.1.3Whom do the services serve?
It is customary to divide the services into two groups according to the party that benefits from them. The first group helps the user and programs directly:
- Interface. The user talks to the system through the command line, a graphical user interface (GUI), a touch screen, or voice commands.
- Program execution. The system loads a program into memory, runs it, and terminates it. It also records whether the program ended normally or with an error.
- Input/output (I/O) operations. A program does not access a device directly; it passes its request to the operating system. In this way both efficiency and protection are achieved.
- File system. Creating, deleting, reading, writing, and searching files and managing permissions fall within the scope of this service.
- Communication. Processes exchange information on the same machine or over the network. The two basic ways are shared memory and message passing.
- Error detection. Situations such as a memory error, a device failure, division by zero, or unauthorized memory access are detected and handled appropriately.
The second group is not directly visible to the user; it makes the system work efficiently and safely as a whole:
- Resource allocation. The processor (CPU), memory, and storage are shared among many processes.
- Accounting. Which user or process uses how many resources is recorded; logs are kept.
- Protection. Processes cannot harm each other or the kernel.
- Security. Authentication, authorization, and defense against outside attacks are the job of this service.
Most users know the operating system not through system calls but through system programs. ls, which lists directory contents, cp, which copies files, ps, which shows running processes, the package manager, the compiler, and the file manager are such programs. They are ordinary user programs, but they make heavy use of system calls to do their work. In the user's eyes the “operating system” is often the sum of these programs.
Is recalculating a formula in a spreadsheet program an operating system service?
Solution. It is not. Computing the formula is the program's own logic; the processor does this computation by executing the program's own code. During this time the operating system provides the program only with processor time and memory. When the spreadsheet is saved to disk, however, things change: the program has no authority to access the disk directly, and it uses the file system service through system calls. One job of the same program is its own code; its other job is an operating system service.
2.2Core concepts
Operating systems hide the complicated details of the hardware behind a few basic abstractions. These abstractions are so widespread that every text describing operating systems relies on the same concepts: process, address space, file, directory, mounting, pipe, and deadlock. The aim of this section is to give a first definition of these concepts. The details of each are deepened in the chapter devoted to that concept; what matters here is to see how the concepts relate to one another.
2.2.1Process
A program file on disk does nothing by itself. It is a passive file made of machine instructions and initial data. When the program is run, the operating system loads it into memory, allocates a stack for it, points the processor at its first instruction, and starts watching the program. This living instance that is running is called a process.
A process is a program in execution. The program is the passive file on disk; the process is its active instance. With each process come an address space (code, data, stack), the values of the registers (including the program counter and the stack pointer), open files, alarms, a list of related processes, and other resources.
Several processes can be created from the same program at the same time. On the machine of a user running bash in two separate terminals, there are two processes from the single bash file on disk. Both execute the same code, but the variables, open files, and current instruction of each are different.
From time to time the operating system has to suspend one process and run another. For the suspended process to continue later where it left off, all of its current state must be stored somewhere. This information is kept in the process table. Each entry of the table belongs to one process and is called a process control block (PCB). Figure 2.3 shows a small process table and the PCB contents of the running process.
systemd, sleeping), 812 (bash, waiting), 1045 (ls, running), and 1046 (grep, ready). The PCB of the running process holds the PID, state, and priority; the program counter, stack pointer, and other registers; the memory map; the open file table; signals, alarms, the user ID, and parent information.Each process in the figure is identified by a process identifier (PID). The state column shows what the process is doing at that moment. On a single-processor machine only one process runs at a time. The other processes either wait for their turn on the processor (ready) or wait for an event such as a key being pressed on the keyboard. The register values in the PCB are saved when the process is taken off the processor and restored to the processor when the process is about to run again. The process does not notice the interruption in between.
Processes often do not work alone; they exchange data with each other. The common name for the mechanisms the operating system offers for this is interprocess communication (IPC). Pipes, shared memory, message queues, and sockets are some of these mechanisms.
2.2.2The process tree
On UNIX-like systems a new process is created from an existing process by the fork() system call. The process that makes the call is called the parent and the process that results is called the child. Because a child can create children of its own, processes arrange themselves naturally in the shape of a tree. Figure 2.4 shows two stages of this tree.
fork() twice; B and C are A's children. Bottom: process B has also created three children, D, E, and F.At the beginning there is only process A. When A calls fork() twice, B and C are born; A is the parent of both. Then B calls fork() three times and processes D, E, and F are created. In this tree D's parent is B, and B's parent is A. On Linux the root of the whole tree is the systemd process (init on older systems), which the kernel starts at boot and which has PID 1. On a running system the pstree -p command prints this tree together with the process identifiers.
Thinking that fork() starts a new, empty program. fork() creates a copy of the parent; the child continues executing the same code as the parent from the same point. For the child to run a different program, an execve call is needed as well. This pair is traced in detail with the shell example in 2.5.2.
2.2.3Address space and memory segments
Each process sees memory as if it were using it alone. The set of addresses a process can use is called its address space. The address space starts at 0 and extends to an upper limit. On Linux on the x86-64 architecture, a process's user space is 128 TiB; this is much larger than the physical memory of most machines. The technique that makes address spaces larger than physical memory possible is virtual memory.
Many processes are in memory at the same time. The operating system must protect these processes both from each other and from itself: a faulty pointer in one process must not corrupt another process's data or the kernel's code. This protection is provided by the memory management unit in the hardware and the operating system working together.
A process's address space is divided into several segments. Figure 2.5 shows the typical layout from bottom to top.
- Text. The machine code of the program. It is kept read-only; processes that run the same program, and all the threads of a process, share this segment.
- Data and BSS. Global and
staticvariables live here. Those whose initial value is given in the source code go to the data segment, and those without one go to the BSS segment. - Heap. Dynamic memory allocated at run time with
mallocornew. Like the data segment, the heap is shared by all threads of the process. - Stack. Function parameters, local variables, and return addresses are kept here. Each thread has its own stack.
In a C program, int counter = 5; and int table[1000]; are defined as globals, and int i; and char *p = malloc(64); are defined inside main. In which segment is each object?
Solution. counter is a global variable with an initial value: it is in the data segment. table is a global array without an initial value: it is in the BSS segment and is filled with zeros at load time. i and the pointer p itself are local variables of main: they are on the stack. The 64-byte area that p points to is on the heap, because it was allocated with malloc. The machine code of the functions is in the text segment as well.
2.2.4Files and the directory hierarchy
A disk by itself is just a storage area made of numbered blocks. If a program had to work with requests such as “read block number 47,291”, every programmer would have to learn the internal structure of the disk. The operating system hides this detail and offers programs a cleaner abstraction: the file.
A file is a named unit that stores data persistently. Text, images, video, or an executable program can be stored in a file. Files are gathered in directories; because directories can contain other directories, a tree results.
A file in the tree is reached by its path name. An absolute path starts at the root directory (/): /home/ali/notes.txt. A relative path starts at the process's current working directory. A process whose working directory is /home reaches the same file as ali/notes.txt. Figure 2.6 shows a sample directory tree.
bin, home, usr, and dev directories. The /home/ali directory contains the files notes.txt and hw.c, and the /dev directory contains the device files sda and tty.When a process opens a file, the operating system gives it a small integer. This number is called a file descriptor (fd). The process afterward refers to the file not by its name but by this number: “read 100 bytes from file number 3”. Every process starts with three open descriptors: 0 is standard input (stdin), 1 is standard output (stdout), and 2 is standard error (stderr). When the process opens a new file, it is given the smallest free number; the first file opened therefore usually gets number 3.
A remarkable idea of UNIX is that devices also look like files. These are called special files, and there are two kinds. Block devices store data in fixed-size blocks and allow access to the blocks in any order: disks such as /dev/sda and /dev/nvme0n1. Character devices produce or consume data as a stream of characters: the terminal (/dev/tty) and the serial port, for example. A program uses the same write call whether it writes to a terminal or to a file.
2.2.5Mounting a file system
When a USB drive is plugged into a computer, the file system on the drive is at first a separate tree. It has no connection to the system's main tree, and it cannot be reached by any path name. UNIX has a single directory tree; adding a new file system to this tree is called mounting.
Mounting is the operation of attaching the root directory of a file system to a directory in the existing tree. The directory where the attachment is made is called the mount point. After mounting, the files in the new file system are reached by path names that begin with the mount point.
/dev/nvme0n1p2) and the separate tree on the USB drive; the a and b directories on the USB drive cannot be reached by any path. At the bottom the root of the USB drive has been mounted on the /mnt directory; now the paths /mnt/a/x and /mnt/b/z are valid.Figure 2.7 shows the operation at two moments. An empty directory is usually used as the mount point. If the directory is not empty, its old contents are not deleted; they merely become invisible until the mount is removed. Windows solves this question differently: each disk or partition usually gets a separate drive letter (C:, D:) and remains a separate tree.
On Linux, mounting is done with the mount command. The following command sequence shows the commonly used forms:
$ lsblk # list disks and partitions
$ sudo mount /dev/sdb1 /mnt # mount sdb1 on /mnt
$ sudo mount -o ro /dev/sdb1 /mnt # mount read-only
$ sudo mount -o remount,rw /mnt # remount read-write
$ findmnt /mnt # show mount information
$ sudo umount /mnt # unmountlsblk lists the disks and partitions in the system; from it one sees that the USB drive has been named /dev/sdb1. The second line mounts it on /mnt in read-write mode. The -o ro option mounts read-only; in recovery and forensic work this mode is preferred so as not to change the data on the disk by accident. remount,rw switches an already mounted file system to read-write mode. findmnt shows mount information, and umount removes the mount. Most of these commands need administrator privileges and are therefore run with sudo.
File systems to be mounted automatically at boot are defined in the /etc/fstab file or in systemd mount units. On desktop systems, a USB drive that is plugged in is mounted automatically under /run/media/… by the udisks2 service. Figure 2.8 summarizes how, after mounting, the file doc.pdf on the USB drive becomes reachable by the path /mnt/doc.pdf.
mount /dev/sdb1 /mnt. The /mnt directory has been attached to the file system on the USB drive; doc.pdf at the root of the USB drive is now opened by the path /mnt/doc.pdf.2.2.6Pipes
When a command such as ls -l | grep "notes" is typed in the shell, two programs run at the same time: ls produces the directory listing, and grep selects from this listing the lines that contain “notes”. There is no temporary file between the two programs. The structure that carries data from one to the other is a pipe.
A pipe is a one-way byte channel, buffered in the kernel, that connects two processes. One process writes to the write end of the pipe, and the other process reads from the read end. Processes use the pipe like an ordinary file, with the read and write calls.
There are two kinds of pipes. An anonymous pipe is created by the pipe() call and has no name; it can therefore be used only among processes with a common ancestor, typically parent and child processes. A named pipe (FIFO) is created with mkfifo and has a name in the file system. Even processes unrelated to each other can use the same pipe by opening this name.
How the shell sets up the command above can be traced in four steps:
- The pipe is created. The shell first calls
pipe(fd). The kernel allocates a buffer and returns two descriptors:fd[0]is the read end andfd[1]is the write end. - Processes are created and the ends are redirected. The shell calls
forktwice. In the first child, standard output (1) is redirected to the write end of the pipe with thedup2call; in the second child, standard input (0) is redirected to the read end. Then the children replace themselves with the programslsandgrep. - Data flows.
lswrites the listing to its standard output, that is, into the pipe.grepreads from its standard input, that is, from the pipe, and writes only the lines containing “notes” to the terminal. Neither program knows it is connected to a pipe. - Flow control and termination. When the buffer is full the writing process blocks, and when it is empty the reading process blocks. When
lsfinishes and all the write ends of the pipe are closed, thereadcall ofgrepreturns 0. This value means end of file (EOF), andgrepfinishes too.
ls -l | grep "notes". Top: redirection of the ends: the standard output of ls is connected to fd[1] and the standard input of grep to fd[0]. Bottom: flow control: the pipe buffer (64 KiB) is in the kernel; when the buffer is full the writer waits, when it is empty the reader waits, and when the write end is closed the reader sees end of file.The shell forgetting to close the pipe ends it holds itself. A reading process sees end of file only when all write ends of the pipe have been closed. If the parent shell keeps the write end in its own copy open after fork, grep waits forever for new data even after ls has finished.
2.2.7Deadlock
Processes use not only the processor but also other resources such as printers, files, memory buffers, or locks. Some resources can be held by only one process at a time. If two or more processes start waiting for resources held by one another, none of them can make progress.
If every process in a set of processes is waiting for a resource held by another process in the set, and as a result none can make progress, there is a deadlock in the set.
Its counterpart in daily life is four cars that enter an intersection from four directions at the same time, each waiting for the car on its right to pass. None of the law-abiding drivers budges. The standard way to draw the situation is the resource allocation graph. Figure 2.10 shows an example with two processes and two resources in two stages.
In case (a) there is no problem yet: P1 holds R1 and P2 holds R2, and later each will request the other's resource. When both of these requests have been made, case (b) is reached. P1 waits for R2, held by P2; P2 waits for R1, held by P1. A closed cycle has formed in the graph and both processes wait forever. If each resource has a single instance, a cycle in the graph is a sure sign of deadlock. If resources have multiple instances, a cycle indicates the possibility of deadlock but is not proof by itself.
2.3Protection
The kernel and dozens of user processes are in memory at the same time. One of the processes may be faulty or malicious. If such a process writes to the disk directly, it can corrupt the file system; if it disables interrupts, it can put the operating system out of action; if it enters an infinite loop, it may never give up the processor. The operating system cannot defend itself against these dangers with software alone, because the problem code runs on the same processor. The foundation of protection is in the hardware.
2.3.1Dual-mode operation
Today's processors recognize at least two modes of operation. Which mode the processor is in is kept in a mode bit in the processor. In the notation Silberschatz uses, this bit is 0 in kernel mode and 1 in user mode.
Dual-mode operation is the processor's distinction between kernel mode and user mode. Privileged instructions can be executed only in kernel mode. If such an instruction is attempted in user mode, the hardware raises a trap and control passes to the operating system.
What privileged instructions have in common is that, if used wrongly, they can harm other processes or the system as a whole. Accessing I/O devices directly, setting the timer, disabling interrupts, and changing page tables belong to this group. Jobs that harm no one, such as reading the system clock, can be done freely in user mode.
When a privileged instruction is attempted in user mode, the hardware does not execute the instruction; instead it raises a trap. The processor switches to kernel mode and jumps to a handler that the operating system set up beforehand. The operating system usually terminates the faulty process. There are only three legitimate ways into the kernel: a system call, a hardware interrupt, and an exception (such as division by zero or an invalid memory access). In all three the processor jumps not to an address chosen by the process but to a fixed entry point determined by the kernel.
In real processors there can be more than two modes. The x86 architecture defines four protection rings, numbered 0 to 3, but Linux and Windows use only ring 0 (kernel) and ring 3 (user). The ARM architecture has four privilege levels, EL0 to EL3; of these, EL2 is reserved for virtualization.
Thinking that dual mode alone is enough. The mode distinction prevents a process from executing privileged instructions, but it does not solve two problems. A process can enter an infinite loop and hold the processor without using any privileged instruction; the remedy for this is the timer. A process can try to reach another process's memory with an ordinary load instruction; the remedy for that is the memory management unit (MMU).
2.3.2The timer
If a process enters a loop such as while (1) ;, it can hold the processor forever without executing any privileged instruction. Because the operating system itself needs the processor to run, it cannot notice this situation on its own. The solution is a piece of hardware that interrupts the processor after a certain time.
A timer is a hardware counter that raises an interrupt after a certain time. The operating system loads a value into the counter; on every tick of the physical clock the counter decreases by one; when the counter reaches zero an interrupt is raised and control passes to the operating system.
Loading a value into the counter is a privileged instruction. In this way a user program cannot stop the timer or extend its period. When the timer interrupt arrives, the operating system asks: has the process running at that moment used up the time slice allotted to it? If so, the process is taken off the processor and the processor is given to another process. This arrangement is called preemptive scheduling. The process itself is not terminated; only its turn passes to another. A process is terminated only if it exceeds the limit on total processor time granted to it (RLIMIT_CPU on Linux).
There are two processes, A and B. Before running A, the operating system loads 3 into the counter. What happens on each tick of the clock?
- Loading. In kernel mode the operating system writes 3 into the counter, then switches to user mode and starts A.
- Tick 1. The counter becomes 2. A continues to run, unaware of what is going on.
- Tick 2. The counter becomes 1. A is still on the processor.
- Tick 3. The counter drops to 0 and the timer interrupt is raised. The processor switches to kernel mode and the interrupt handler runs.
- Scheduling. The scheduler sees that A's slice has run out, saves A's state in its PCB, and chooses B. It loads the counter again and starts B in user mode.
A has used the processor for three ticks. Even if A were in an infinite loop, it would have to give up the processor at the end of this period.
On Linux the timer interrupt is raised at regular intervals, between 100 and 1000 times per second; each interrupt is called a tick. Frequent ticks give finer time slices and more responsive scheduling, but handling each tick takes time from the processor. Moreover, even when the system is idle, the processor has to wake up on every tick. For this reason current kernels also offer a mode that raises no ticks while idle (tickless, NO_HZ); this mode saves energy, especially on laptops.
2.4System calls
Dual-mode operation forbids user programs to access the hardware directly. Yet programs need to read files, ask for memory, write to the screen, and create new processes. The only party that can do these jobs is the kernel. The controlled way for a program to request service from the kernel is the system call.
2.4.1What is a system call?
A system call is the defined interface that programs use to reach operating system services such as files, memory, processes, time, and the network. The application starts the call; the kernel carries out the requested work in kernel mode.
Programmers often do not use system calls directly. In between sits an application programming interface (API). On UNIX-like systems this interface is the POSIX standard, implemented inside the C library (glibc or musl). On Windows the Windows API, and in Java the Java API, serve the same purpose. An API provides two benefits. The first is portability: a program written to POSIX can be compiled and run on another UNIX whose system call numbers and details are different. The second is convenience: API functions hide the laborious details of raw system calls.
The set of system calls varies from system to system. Linux on x86-64 has about 370 system calls. The basic concepts are common, though: every system has calls that create processes and open, read, and write files. To see which system calls a program makes, one uses strace on Linux, dtruss on macOS, and the Process Monitor tool on Windows.
2.4.2From the API to the kernel
Let us follow the call open("notes.txt", O_RDONLY) of a C program. Figure 2.13 shows the call's journey from start to finish.
- The wrapper. The program calls the
open()function in the C library like an ordinary function. This function is a wrapper: it puts the call number and parameters into registers and then executes the trap instruction. The processor switches to kernel mode. - The system call interface. The entry code in the kernel uses the call number as an index into the system call table. On x86-64 Linux,
readis number 0,write1,open2, andclose3. - The implementation. The pointer in the table points to the kernel's
opencode. This code resolves the path name, finds the file, checks the permissions, and creates an open file record. - The return. The result goes back to the user. Because 0, 1, and 2 are taken, the first free descriptor is 3;
openreturns 3 and the processor switches back to user mode.
open call from user mode to kernel mode. The system call interface finds entry number 2, the pointer in the table leads to the kernel's open() implementation, and the result (fd = 3) returns to user mode.One detail shows well the relationship between the library and the kernel. Current glibc actually implements the open() that the program calls with the openat system call (number 257 on x86-64). The program still writes open and gets the same result; the API hides the change in between. Looking with strace, however, the name of the call that goes to the kernel appears as openat.
2.4.3The system call table
How the system call table works can be followed with a small C model. In the code below the table consists of only three entries. In the real Linux kernel the table holds a few hundred entries, but the logic is the same.
typedef long (*syscall_t)(long, long, long);
syscall_t table[3] = {sys_read, sys_write,
sys_open};
long syscall_entry(long no, long a,
long b, long c) {
if (no < 0 || no >= 3)
return -ENOSYS; /* bad number */
return table[no](a, b, c);
}The first line defines a pointer type for a function that takes three long parameters and returns long, and names it syscall_t. The table in the second line is an array of three pointers of this type: entry 0 points to sys_read, entry 1 to sys_write, and entry 2 to sys_open. The syscall_entry function represents the kernel's single entry point. It first checks whether the call number lies within the bounds of the table. If the number is invalid it returns -ENOSYS; if it is valid, it uses the pointer in the table to call the right function and returns its result.
Suppose the program makes three calls in a row: a write that writes three bytes, open("notes.txt", 0), and syscall(99), which has no counterpart in the table. How does syscall_entry work on each call?
| Call | no | Bounds check | Code run | Result |
|---|---|---|---|---|
write | 1 | 0 ≤ 1 < 3: valid | table[1] → sys_write | 3 (bytes written) |
open | 2 | 0 ≤ 2 < 3: valid | table[2] → sys_open | 3 (new descriptor) |
syscall(99) | 99 | 99 ≥ 3: invalid | none | −ENOSYS (−38); the program gets −1, errno = ENOSYS |
In the first two calls the libc wrapper puts the number into the rax register and executes the syscall instruction. The hardware switches to kernel mode and jumps to the single entry point. The bounds check passes and the function pointer in the table calls the right handler. In the third call the number is outside the table. Without the check, table[99] would use a memory cell far beyond the end of the array as a function pointer; the kernel would jump to a random address. Thanks to the check, the call is rejected with the value −38. libc turns this negative value into errno = ENOSYS and returns −1 to the program.
no = 1: table[1] has been selected and sys_write has returned 3. In the second frame no = 99: because the number lies outside the table, the call has been rejected with −ENOSYS.The lesson from this model is general: the kernel trusts no value from the user without validating it. The call number, the file descriptor, and the buffer's address and length are values written by the user program, and all of them are checked. Whether the buffer address given to a read call really lies in that process's memory is one of these checks.
2.4.4Example: copying a file
Even a program that looks ordinary makes many system calls. Consider a program that copies one file to another and asks the user for the file names. The steps of the program and the system calls each step uses are as follows:
| Step | System calls |
|---|---|
| Prompt for and read the input file name | write, read |
| Prompt for and read the output file name | write, read |
| Open the input file (if it does not exist, report an error and exit) | open |
| Create the output file (if it exists, report an error and exit) | open + O_CREAT |
| Loop: read from the input, write to the output | read, write |
| Close the files | close |
| Write “done” to the screen | write |
| Terminate normally | exit |
Even getting a file name from the user takes two calls: write to put a prompt on the screen and read to read from the keyboard. Opening a file can fail: the file does not exist or there is no read permission. In that case open returns −1, and the program writes an error message and exits. If the output file is opened with the flags O_WRONLY | O_CREAT | O_EXCL, the call fails when a file of the same name already exists; in this way an existing file is not overwritten by accident. The real work is in the loop: until read returns 0, that is, until the end of the file is reached, the bytes read are written with write. Even such a simple program makes dozens of system calls; on Linux the command strace -c cp a b counts the calls made by the cp program by type.
To trace the loop itself in detail, let us consider the following piece of code:
char buf[4096];
int in = open("src", O_RDONLY);
int out = creat("dst", 0644);
ssize_t n; long total = 0;
while ((n = read(in, buf, 4096)) > 0) {
write(out, buf, n);
total += n;
}
close(in); close(out);
printf("%ld bytes\n", total);The program allocates a 4096-byte buffer. It opens the file src read-only and puts its descriptor in in. The creat call creates an empty file named dst and sets its permissions to 0644 (the owner reads and writes, others only read). The loop condition both does the reading and tests the result: read reads at most 4096 bytes and writes the number of bytes it read into n; as long as n is positive the loop continues. The body of the loop writes the n bytes in the buffer to the destination and updates total. At the end the two files are closed and the number of bytes copied is printed.
src is a file of 10,000 bytes, and only the descriptors 0, 1, and 2 of the process are open. The piece of code proceeds step by step as follows.
| Step | Call | n | File offset | total |
|---|---|---|---|---|
| 1 | open("src") → in = 3 | — | 0 | 0 |
| 2 | creat("dst") → out = 4 | — | 0 | 0 |
| 3 | read, write | 4096 | 4096 | 4096 |
| 4 | read, write | 4096 | 8192 | 8192 |
| 5 | read, write | 1808 | 10000 | 10000 |
| 6 | read | 0 | 10000 | 10000 |
| 7 | close(3), close(4) | 0 | — | 10000 |
| 8 | printf → write(1, …) | 0 | — | 10000 |
The first open returns the smallest free descriptor; because 0, 1, and 2 are taken, in = 3 and then out = 4. The first read reads 4096 bytes and the kernel advances the file offset by 4096. The second round also reads 4096 bytes; the offset reaches 8192. Only 10,000 − 8192 = 1808 bytes are now left in the file. The third read returns less than requested, 1808 bytes; this is not an error. The offset is at the end of the file and the fourth read returns 0. The loop condition becomes false and the loop ends. The program prints 10000 bytes.
The total number of system calls is 12: 1 open, 1 creat, 4 read, 3 write, 2 close, and 1 write made by printf.
read: the first 4096 bytes of the source have been taken into the buffer. In the second frame, the third read: the remaining 1808 bytes of the file have been read.Writing write(out, buf, 4096) in the loop body. In the last round the buffer holds only 1808 valid bytes; the remaining 2288 bytes are old data left over from the previous round. If a fixed 4096 is written, the destination file becomes 12,288 bytes and meaningless data is appended to its end. The correct way is to write as many bytes as n, the value read returned.
The buffer size directly determines the number of system calls made. Because of the two mode switches and the in-kernel input-output work, each system call is much more expensive than an ordinary function call. If the same 10,000 bytes had been copied with a 1-byte buffer, about 20,000 calls would have been needed for reading and writing alone: 10,001 read calls and 10,000 write calls. With a 4096-byte buffer this number is 7.
2.4.5The eleven steps of a read call
Tanenbaum's textbook describes the read(fd, buffer, nbytes) call by dividing it into eleven steps. The example is based on the historical 32-bit x86 convention: parameters are passed on the stack. Today's x86-64 systems pass the first six parameters in registers, but the order and meaning of the steps do not change.
- Steps 1–3. The user program pushes the parameters on the stack: first
nbytes, then the address ofbuffer, and lastfd. C compilers push parameters from last to first. - Step 4. The program calls the
read()function in the library like an ordinary function; the return address goes on the stack. - Step 5. The library puts the call number into the register the kernel expects (
rax = 0on Linux x86-64). - Step 6. The trap instruction (
syscallon x86-64) executes. The processor switches to kernel mode and jumps to a fixed address in the kernel. - Step 7. The kernel looks at the call number and branches to the right handler through the system call table.
- Step 8. The handler copies at most
nbytesbytes from the file thatfdrefers to intobuffer. If the data is not ready, for example if a line has not yet arrived from the keyboard, the process blocks and the processor is given to another process. - Step 9. When the work is done, control returns to user mode, to the instruction after the trap instruction. The result, the number of bytes read, is in a register.
- Step 10. The
read()function in the library returns to the user program that called it. - Step 11. The program cleans up the parameters it pushed on the stack (increments the stack pointer) and continues with the next instruction.
read call. The parameters (nbytes, &buffer, fd) and the return address are on the user stack. The library has moved into the kernel with the trap instruction, and the dispatcher in the kernel has branched to the sys_read handler through table[no]. The dashed line separates user space from kernel space.The first four steps and the last two take place entirely in user mode; these are ordinary function call steps. Entry into the kernel happens at step 6 and exit at step 9. Step 8 shows the most important difference between a system call and an ordinary function: the call can wait for an event. Until the awaited event happens, the process does not use the processor; the operating system uses this time for other processes.
2.4.6Parameter passing
There are three general ways to pass parameters to a system call:
- Registers. The fastest way. Linux passes at most six parameters to a system call in registers.
- A block or table in memory. The parameters are written into a structure in memory; the address of the structure is passed in a register. This way is used when there are many parameters. The
clone3(struct clone_args *)call in Linux is an example. - The stack. The program pushes the parameters on the stack and the operating system pulls them from there. It was common in the historical 32-bit systems.
On x86-64 Linux the roles of the registers are fixed:
| Register | Role |
|---|---|
rax | call number; the result on return |
rdi, rsi, rdx | 1st, 2nd, and 3rd parameters |
r10, r8, r9 | 4th, 5th, and 6th parameters (r10 instead of the rcx of the C function call convention) |
syscall | the instruction that moves into the kernel; the values of the rcx and r11 registers are destroyed |
| ARM64 | x8 call number, x0–x5 parameters; the transition instruction is svc #0 |
The answer to the question of why the fourth parameter is in r10 instead of rcx is in the last row of the table. The syscall instruction saves the return address in rcx and the flags register in r11. A parameter placed in rcx would therefore be erased before reaching the kernel.
Error reporting follows a common rule as well. When there is an error, the kernel returns a value between −1 and −4095; this value is the negative of the error code (−errno). When the libc wrapper sees this value, it writes the error code into the errno variable and gives −1 to the caller. The program notices the error by checking whether a system call returned −1 and learns the cause from errno.
2.4.7Code trace with write and read
One of the smallest programs that writes text to the screen is this one, which uses write directly instead of printf:
#include <unistd.h> // write()
#include <string.h> // strlen()
int main(void) {
const char *msg = "Hello, Türkiye!\n";
size_t len = strlen(msg); // 17 bytes
ssize_t n = write(1, msg, len); // 1: stdout
if (n == -1)
return 1; // error
return 0;
}The pointer msg points to the string in the read-only data segment. strlen(msg) gives the string's length in bytes. write(1, msg, len) writes len bytes to descriptor 1, that is, to standard output. If the returned value is −1, an error has occurred and the program exits with 1; otherwise it exits with 0.
The program runs line by line as follows. The non-ASCII character in the string affects the byte count.
strlen. In UTF-8 encoding, “Hello, ” is 7 bytes (including the space after the comma). “Türkiye” is 8 bytes, because the letter ü takes 2 bytes. “!” and the newline character “\n” are 2 bytes. The total islen = 17; the number of characters is 16.- The wrapper. libc fills the registers:
rax = 1(write),rdi = 1,rsi = msg,rdx = 17. Then it executes thesyscallinstruction. - The kernel. In kernel mode,
sys_writepasses the 17 bytes to the terminal to which descriptor 1 is attached.Hello, Türkiye!appears on the screen. - The return. Control returns to user mode and
n = 17. This value is the number of bytes written; in some cases it can be smaller than requested (a partial write). - Error check.
nis not −1, so there is no error. Had there been an error,writewould have returned −1 anderrnowould have been set. - Exit.
mainreturns 0; libc terminates the process with theexit_group(0)call.
If the programmer had computed the length by hand and written a fixed 15, the last two bytes (“!” and “\n”) would not be sent and the output would be cut off as “Hello, Türkiye”. Computing the length with strlen prevents this mistake.
The counterpart program on the reading side reads one line from the keyboard and writes it back to the screen unchanged:
#include <unistd.h>
#include <stdio.h>
int main(void) {
char buf[100];
ssize_t n = read(0, buf, sizeof(buf));
if (n == -1) {
perror("read error");
return 1;
}
write(1, buf, n); // exactly n bytes
return 0;
}While the program is running, the user types hello and presses the Enter key. How does the program proceed?
- The buffer.
bufis a 100-byte array allocated on the stack; its contents are uninitialized, that is, they hold random values. - Blocking.
read(0, buf, 100)wants to read from standard input, that is, from the keyboard. No line has been typed yet. The process blocks and the scheduler runs another process. - The user types. The user types
helloand presses Enter. The terminal driver echoes the characters to the screen and accumulates the line in its own buffer. - Wake-up. When the line is complete, 6 bytes (
helloand “\n”) are copied intobuf, the process wakes up, andreadreturns 6. No “\0” is added to the end of the buffer. - Error check.
n = 6, there is no error;perroris skipped. - Writing.
write(1, buf, 6)writes exactly 6 bytes to the screen.helloappears twice on the screen: the first is the terminal driver's echo, the second is the program's output. - Exit. The program terminates with 0.
Printing the buffer that was read with printf("%s", buf). read does not put a string-terminating character (“\0”) at the end of the buffer; buf is not a C string. printf keeps reading until it finds the first zero byte and dumps the random bytes in uninitialized memory onto the screen as well. The correct way is to write exactly n bytes, using the value n that read returned.
2.4.8The standard C library
The printf that a C programmer uses every day is not a system call. It is a library function that runs in user mode and makes a system call when needed. Figure 2.18 shows the path of the call printf("Hello\n").
printf call into the write system call. The program calls printf; the standard C library formats the text and puts it into the stdout buffer. When the newline arrives, the library makes the system call write(1, buffer, 6); the kernel passes the bytes to the terminal and returns 6.- The program calls
printf. This is an ordinary function call running in user mode. - libc processes the format string and puts the result into the buffer of
stdout. If the output goes to a terminal, the buffer is line-buffered: it is flushed when a newline arrives. If the output is redirected to a file or a pipe, the buffer is fully buffered: it is flushed when it fills up or when the program ends. - Because the text ends with “\n”, libc makes the call
write(1, buffer, 6). “Hello” is 5 bytes and the newline is 1 byte. writereturns 6, andprintfreturns to the caller. The commandstrace ./helloshows onlywrite; becauseprintfis not a system call, it does not appear in the list.
The functions of the standard C library are grouped by header file: stdio.h (printf, fopen), stdlib.h (malloc, exit), string.h (strlen, memcpy), math.h, and time.h. POSIX also defines system call wrappers such as fork, read, and write in the unistd.h header. The widespread implementations of the library are glibc and musl on Linux and UCRT on Windows. Library functions fall into two groups. Functions such as strlen run entirely inside the library and never enter the kernel. Functions such as write wrap a system call.
2.4.9Types of system calls
System calls are grouped into six groups according to the work they do. Table 2.3 lists the tasks of each group and their POSIX examples.
| Type | Tasks | POSIX examples |
|---|---|---|
| Process control | create, terminate, load, wait, send a signal | fork, execve, exit, waitpid, kill |
| File management | create, delete, open, close, read, write, get attributes | open, read, write, close, stat |
| Device management | request and release a device, read, write, control | ioctl, read, write, mmap |
| Information maintenance | time, date, system and process information | getpid, uname, clock_gettime |
| Communication | set up a connection, send and receive messages, shared memory | pipe, socket, sendmsg, shm_open |
| Protection | get and set permissions, user identity | chmod, chown, umask, setuid |
The same groups exist on Windows; only the names change. CreateProcess is used to create a process, ReadFile to read a file, DeviceIoControl for device control, GetSystemTime to read the clock, CreatePipe to create a pipe, and SetFileSecurity for file permissions. It is natural for some calls to appear in more than one group: read and write are used for both files and devices, because on UNIX devices look like files too.
2.5POSIX and Win32 calls
The POSIX standard defines hundreds of calls, but a few dozen are enough to understand the basic behavior of a UNIX system. This section takes up the basic calls chosen by Tanenbaum in three groups: process management, file management, and directory management. At the end of the section, the Windows counterparts of the same calls are given. A common notation is used in the tables: pid stands for a process identifier, fd for a file descriptor, n for a byte count, and s for the return code of the call. In case of error all of the calls return −1 and set the errno variable.
2.5.1Process management
| Call | Description |
|---|---|
pid = fork() | Creates a child process that is a copy of the parent. |
pid = waitpid(pid, &statloc, options) | Waits for a child to terminate; writes the exit status into statloc. |
s = execve(name, argv, envp) | Replaces the process's memory image with a new program; does not return if successful. |
exit(status) | Terminates the process and passes the exit status to the parent. |
fork is the only way to create a new process on UNIX. The call creates a new process with a copy of the parent's memory image, open files, and registers. After the call there are two processes, and both continue from the same point where fork returned. The only way to tell which of the two processes is which is the return value: in the parent fork returns the child's PID, and in the child it returns 0. If the call fails, −1 returns to the parent and no child is created. This is why it is said that fork “is called once and returns twice”.
The child is often wanted to do a different job from the parent. For this the child calls execve. execve replaces the process's code, data, and stack with the image of the new program on disk. The process is the same process and its PID does not change; it is simply running another program now. A successful execve does not return, because the code that called it is no longer in memory. The line after execve runs only if the call fails.
fork() and blocks with waitpid. The child moves to the new program with execve() and calls exit(status) when it has finished its work. At this moment the parent's waitpid call returns and the exit status is received.Windows does not split this job into two calls: a single CreateProcess call both creates the new process and loads the new program into it. The benefit of UNIX's two-step approach is the short interval between fork and execve. In this interval the child can change its own open files; for example, it can redirect its standard output to a file or a pipe. The shell's > redirection and pipelines are set up in exactly this interval.
2.5.2A simple shell
The best way to see how the process management calls work together is to write a shell. A shell is an ordinary user program that takes commands from the user and runs them. The skeleton given by Tanenbaum hides the details and shows only the essential structure:
#define TRUE 1
while (TRUE) { /* forever */
type_prompt(); /* print the prompt */
read_command(command, parameters);
if (fork() != 0) { /* parent */
waitpid(-1, &status, 0);
} else { /* child process */
execve(command, parameters, 0);
perror("execve"); /* on failure */
_exit(127);
}
}The shell runs in an infinite loop. In each round it prints the prompt (type_prompt) and reads the line the user typed, splitting it into the command name and parameters (read_command). Then it calls fork. If the return value is not 0, this code is running in the parent, that is, in the shell itself; the shell waits for the child to finish with waitpid. If the return value is 0, the code is running in the child; the child replaces itself with the requested program using execve. Because a successful execve does not return, the next two lines run only if the call fails: the child prints the error and terminates with _exit(127) (127 is the exit status shells use for “command not found”).
In the shell with PID 812 the user types ls. The working directory contains the files notes.txt and hw.c. One round of the shell is shown in the table below.
| Step | Line | Event | Processes | Screen |
|---|---|---|---|---|
| 1 | 4 | The prompt is printed and the shell waits for the user. | shell (812) | $ |
| 2 | 5 | The line is parsed: command = "/bin/ls", parameters = ["ls", NULL]. | shell (812) | $ ls |
| 3 | 7 | fork: returns 1045 in the parent and 0 in the child. | shell (812), child (1045) | $ ls |
| 4 | 8 | The parent blocks with waitpid(-1, …). | shell (waiting), child (1045) | $ ls |
| 5 | 10 | The child becomes ls with execve; it lists the directory. | shell (waiting), ls (1045) | notes.txt hw.c |
| 6 | 8 | ls ends with exit(0); waitpid returns, status = 0. | shell (812) | |
| 7 | 4 | The loop returns to the start and a new prompt is printed. | shell (812) | $ |
In step 3, after fork the same code runs in two processes at once. In the shell the condition fork() != 0 is true (1045 ≠ 0) and the shell goes to line 8. In the child the condition is false (0) and the child goes to line 10 in the else branch. In step 5 the child's PID remains 1045; only the program it runs has changed. Because the first parameter of waitpid is −1, the shell waits for the first child to finish, whichever child it is.
Real shells go far beyond this skeleton. They search for the command name in the directories in the PATH environment variable, manage jobs running in the background with &, and set up redirections and pipelines. But at the heart of all of them is the same fork–execve–waitpid trio.
Forgetting to terminate the child when execve fails. If the user types a nonexistent command, execve returns −1 and the child goes on running with the shell's code. If there is no exit after execve in the child, the child returns to the top of the loop and starts behaving like a shell itself. The user now faces two shells. This is why the line _exit(127) is in the skeleton.
2.5.3File management
| Call | Description |
|---|---|
fd = open(file, how, …) | Opens the file for reading, writing, or both; creates it if necessary. |
s = close(fd) | Closes an open file. |
n = read(fd, buffer, nbytes) | Reads at most nbytes bytes from the file into the buffer. |
n = write(fd, buffer, nbytes) | Writes data from the buffer to the file. |
position = lseek(fd, offset, whence) | Moves the file position pointer (SEEK_SET, SEEK_CUR, SEEK_END). |
s = stat(name, &buf) | Gets the file's status information (size, permissions, times). |
For each open file the kernel keeps a position pointer. This pointer determines from which byte of the file the next read or write call will start. Every read and write advances the pointer by the number of bytes processed. This is how, in the copy example, the file can be read in order from beginning to end: the program specifies no position anywhere; the kernel tracks the position itself.
read or write. lseek moves the pointer to any desired point in the file.lseek is used to go to a particular place in the file. The whence parameter determines what offset is measured from: SEEK_SET from the beginning of the file, SEEK_CUR from the pointer's current place, SEEK_END from the end of the file. The call returns the pointer's new position in bytes from the start of the file. For example, lseek(fd, 0, SEEK_END) moves the pointer to the end of the file and the return value equals the file's size.
A file of 1000 bytes is opened with fd = open(…, O_RDONLY). Then the calls read(fd, buf, 300), lseek(fd, 100, SEEK_CUR), read(fd, buf, 300), lseek(fd, -50, SEEK_END), and read(fd, buf, 300) are made. What does each call return?
Solution. The pointer is 0 at open. The first read reads 300 bytes and returns 300; the pointer reaches 300. lseek(fd, 100, SEEK_CUR) moves the pointer 100 forward and returns 400. The second read reads bytes 400–699 and returns 300; the pointer becomes 700. lseek(fd, -50, SEEK_END) moves the pointer 50 bytes back from the end, to 950, and returns 950. The last read asks for 300 bytes, but only 50 bytes remain in the file; it returns 50.
stat fills a structure with information about a file without touching its contents: its size, owner, permission bits, and last access and modification times. Alongside these basic calls, current Linux offers extended versions such as openat, pread / pwrite (calls that read and write at a given position without changing the position pointer), and statx.
2.5.4Directory management and other calls
| Call | Description |
|---|---|
s = mkdir(name, mode) | Creates a new directory. |
s = rmdir(name) | Deletes an empty directory. |
s = link(name1, name2) | Creates a new directory entry named name2 for the file that name1 points to. |
s = unlink(name) | Deletes a directory entry. |
s = mount(special, name, flag) | Mounts a file system (its form on Linux: mount(source, target, type, flags, data)). |
s = umount(special) | Unmounts a file system. |
s = chdir(dirname) | Changes the working directory. |
s = chmod(name, mode) | Changes the file's protection (permission) bits. |
s = kill(pid, signal) | Sends a signal to a process; despite its name, it is not used only to kill processes. |
seconds = time(&seconds) | Gives the number of seconds elapsed since 00:00 UTC on 1 January 1970 (the Unix epoch). |
The last call in the table is the source of a well-known problem in the software world. In old systems the time value was kept in a 32-bit signed integer (time_t). The largest value such an integer can hold is 231 − 1 = 2,147,483,647. This many seconds, counted from the start of 1970, corresponds to 19 January 2038. After that moment the counter overflows and the date goes back to 1901. This problem is known as the “year 2038 problem”. Current systems remove the problem by keeping time in a 64-bit time_t.
Note that the chdir call changes a property of the process. The working directory belongs to the process; even if a child process changes its own working directory, the parent's working directory stays the same. This is why the shell's cd command is implemented not as a separate program but as a built-in command inside the shell itself.
2.5.5link and unlink
On UNIX, a file's name and the file itself are separate things. The file's real information (its owner, permissions, size, and the disk blocks of its data) is kept in a structure called an inode. A directory is just a table made of (inode number, name) pairs. A name is nothing more than a directory entry that points to an inode.
This separation has a natural consequence: there can be several directory entries that point to the same inode. A file then has several names. Each of these names is called a hard link. The inode keeps the number of names pointing to it in a counter called the link count.
In the directory /usr/jim there is a file named memo that points to inode number 70. First link("/usr/jim/memo", "/usr/ast/note") and then unlink("/usr/jim/memo") are called.
- Initial state. The directory
/usr/jimhas the entries (31, bin), (70, memo), (59, f.c.), and (38, prog1). The link count of inode 70 is 1. link. The entry (70, note) is added to the directory/usr/ast. No data is copied; the new entry points to the same inode. The link count becomes 2. Now/usr/jim/memoand/usr/ast/noteare the same file: a change made through one is seen through the other.unlink. The entry (70, memo) in/usr/jimis deleted. The file itself is not deleted; it lives on under the namenote. The link count drops to 1.
When the link count drops to 0 and no process keeps the file open, the kernel releases the inode and the file's data blocks. This is why UNIX has no separate call for “deleting a file”; the rm command actually calls unlink.
link call. Top, the initial state: /usr/jim/memo points to inode number 70 and the link count is 1. Bottom, after link, /usr/ast also has the entry note pointing to 70; the link count is 2.Whether a file is open is tracked by a counter separate from the link count. When a process opens a file with open, the kernel resolves the path name and reaches the inode. From then on the process accesses the file not through its name but through the descriptor, going directly to the inode. Even if the name is deleted, the open descriptor keeps working. The following code traces this situation:
int fd = open("/usr/jim/memo", O_RDONLY);
link("/usr/jim/memo", "/usr/ast/note");
unlink("/usr/jim/memo");
unlink("/usr/ast/note");
n = read(fd, buf, 100); /* still readable */
close(fd);memo is a file of 85 bytes, and only the descriptors 0, 1, and 2 of the process are open. The table gives the link count and open count of inode 70 after each line.
| Line | Call | Link count | Open | Note |
|---|---|---|---|---|
| — | start | 1 | 0 | only the name memo exists |
| 1 | open | 1 | 1 | fd = 3 |
| 2 | link | 2 | 1 | note added |
| 3 | unlink(memo) | 1 | 1 | only note remains |
| 4 | unlink(note) | 0 | 1 | no path left, but the file is open |
| 5 | read | 0 | 1 | n = 85 |
| 6 | close | 0 | 0 | inode and blocks freed |
After line 4 the file has no name in the directory tree at all. Even so, because descriptor 3 keeps it open, the kernel does not delete the inode and the blocks. The read in line 5 goes through the descriptor directly to the inode; it needs no name. It asks for 100 bytes and, because the file has 85 bytes, returns 85. When the last descriptor is closed in line 6, both the link count and the open count become 0, and only at this moment does the kernel release the inode and the data blocks.
link: /usr/jim/memo and /usr/ast/note point to the same inode, and the link count is 2. In the second frame, after the two unlink calls: the directories no longer hold a name for the file, but the inode lives on because the descriptor is open.Programs make deliberate use of this behavior. A program that creates a temporary file deletes its name with unlink right after opening the file. The file can be used through the descriptor as long as the program runs, but it is not visible in the directory tree. Whether the program ends normally or crashes, when the last descriptor is closed the kernel cleans up the file automatically.
2.5.6Win32 API equivalents
Windows's programming interface is the Win32 API. This interface contains thousands of functions, and most of the basic calls in POSIX have a counterpart in it. Table 2.7 gives Tanenbaum's list with current counterparts.
| UNIX | Win32 | UNIX | Win32 |
|---|---|---|---|
fork | CreateProcess | mkdir | CreateDirectory |
waitpid | WaitForSingleObject | rmdir | RemoveDirectory |
execve | (none: CreateProcess) | link | CreateHardLink |
exit | ExitProcess | unlink | DeleteFile |
open | CreateFile | mount | SetVolumeMountPoint |
close | CloseHandle | umount | DeleteVolumeMountPoint |
read | ReadFile | chdir | SetCurrentDirectory |
write | WriteFile | chmod | (none: ACL, SetFileSecurity) |
lseek | SetFilePointerEx | kill | (none: TerminateProcess) |
stat | GetFileAttributesEx | time | GetSystemTime |
The “none” marks in the table come from design differences. execve has no counterpart, because Windows combines process creation and program loading in the single CreateProcess call. chmod has no counterpart, because Windows manages file permissions with access control lists (ACLs) instead of UNIX's nine permission bits. kill has no counterpart, because Windows has no signal mechanism like UNIX's; TerminateProcess is used to terminate a process. link and mount, which had no counterpart in old editions of Tanenbaum's book, are possible today with CreateHardLink and SetVolumeMountPoint.
Win32 functions do not move into the kernel directly. The real kernel transition is made by the functions beginning with Nt… in the ntdll.dll library; for example, CreateFile ends up calling NtCreateFile. The call numbers of these functions inside the kernel change from one Windows version to another and are not documented. Programs therefore always use the API; a program that relies directly on the numbers can stop working at the next Windows update.
2.6Kernel structures
System calls are the outward-facing side of the operating system. The subject of this section is the inside: how are the components that serve a call organized? The answers to this question have, over decades, gathered around a few main structures. Each structure chooses a different point on the trade-off triangle of 2.1.1.
2.6.1Overview
A useful way to order the structures is to look at how much work is done in kernel mode. Figure 2.23 arranges the structures on a line by this criterion.
Two concepts do not fit this line neatly. Layered structure is not a placement but an organizing principle: components are divided into hierarchical layers. The THE system and MULTICS's protection rings are examples of this principle, and the principle can be applied to a system at any point on the line. Virtual machines are a separate axis: the hardware itself is virtualized and several operating systems run on a single machine.
2.6.2Simple structure: MS-DOS
Some operating systems have no clear structure. These systems were written for small, simple, and limited hardware and grew over time beyond what was expected. MS-DOS is the best-known example.
In MS-DOS the interfaces and levels of functionality are not well separated. An application can call BIOS routines directly instead of using the services MS-DOS offers, and can even write directly to screen memory or device ports. The basic reason is hardware: the Intel 8088 processor for which MS-DOS was written had no dual mode. Because there was no hardware protection, a single faulty program could crash the whole system. There were also no clear boundaries between modules and no data hiding: every component could touch the data of the others. Silberschatz treats such systems under the heading “simple structure”, separately from monolithic kernels.
2.6.3The monolithic system
The most common structure is the one in which the whole operating system is linked as a single program that runs in kernel mode.
In a monolithic kernel, all operating system services run in a single address space in kernel mode. Every procedure in the kernel can call any other directly.
The word “monolithic” does not mean disorder. Tanenbaum describes the basic organization that even a monolithic system has, in three layers:
- The main program. It looks at the number of the system call and starts the requested service procedure.
- Service procedures. Each does the work of one system call.
- Utility procedures. They do the jobs that several services need in common; for example, fetching data from the user program's memory.
Traditional UNIX and Linux are monolithic kernels. Figure 2.26 shows the layers of traditional UNIX. Users and system programs (shells, commands, compilers, libraries) are above the system call interface. The kernel below this interface hosts signals, terminal handling, the file system, swapping, disk drivers, CPU scheduling, and virtual memory as a single whole. Below the kernel are the interface between the kernel and the hardware and the device controllers.
The strengths of the monolithic structure are clear. Components use each other by direct function calls; there is no message preparation, copying, or mode switching in between. That is why monolithic kernels are fast. Their design and implementation are also relatively simple. Their weaknesses come from the same closeness. Because all components are in the same address space, a faulty pointer in a single driver can corrupt any structure of the kernel and crash the whole system. The code base is also huge: in Linux, which has passed 40 million lines, finding a bug and doing maintenance is not easy. Most monolithic kernels today also accept drivers and file systems as modules that can be loaded at run time; this added flexibility is touched on in 2.6.9.
2.6.4Layered structure
The classic way to make a large system manageable is to divide it into layers.
In a layered system, the operating system is divided into layers. The bottom layer is closest to the hardware and the top layer closest to the user. Each layer uses only the services of the layers below it.
The first example of this structure is the THE system that Edsger Dijkstra developed with his students in 1968. Figure 2.27 shows the six layers of THE.
- Layer 0 switches among processes when interrupts arrive and when the timer expires. Those above this layer do not have to think about several processes sharing a single processor; each process is written as if it had its own processor.
- Layer 1 allocates memory to processes and moves pages between main memory and the drum, the secondary memory of that era. The upper layers do not know whether a page is in memory or on the drum.
- Layer 2 manages the communication between each process and the operator console. Each process above behaves as if it had its own console.
- Layer 3 manages the I/O devices. The upper layers work with abstract devices instead of the details of the real ones.
- Layer 4 is the user programs. These programs do not deal with the details of memory, the console, or I/O.
- Layer 5 is the system operator.
The greatest benefit of the layered structure is that debugging and verification can be done layer by layer. Layer 0 is tested alone and its correctness is made certain. Then layer 1 is added; if an error appears, then since the layer below is correct, the error is in layer 1. Abstraction and data hiding are easy too: each layer hides its own data structures from the upper layers.
The structure has two important difficulties. The first is defining the layers correctly. The dependencies among components are often two-way. For example, the memory manager needs the I/O driver to write pages to disk; the I/O driver needs the memory manager to allocate buffers. It is hard to decide which will be below. The second is performance: with every layer crossing, a request incurs extra work such as parameter preparation and checking. For this reason purely layered operating systems have not become widespread. The idea lives on today in network protocol stacks: a network packet passes in turn through the application, transport, network, and link layers.
2.6.5The microkernel
The biggest problem of the monolithic structure is that a bug in one component can bring down the whole system. The microkernel approach gives a radical answer to this problem: only the things that really have to be there stay in the kernel.
In a microkernel, only interprocess communication (message passing), basic scheduling, address space management, and interrupt handling stay in kernel mode. Drivers, file systems, and the network stack run in user mode as server processes and communicate with each other by messages.
Adding a new service in a microkernel means adding a new server in user space; the kernel itself does not change. Mach, MINIX 3, QNX Neutrino (common in the automotive sector), the L4 family, the formally verified seL4, and Google Fuchsia's Zircon kernel are examples of this approach. macOS, although derived from Mach, is not a pure microkernel but a hybrid kernel.
A principle often cited in microkernel design is the separation of mechanism and policy. Mechanism determines how a job is done, and policy what is done. For example, the kernel provides the mechanism for running the highest-priority ready process. Which priorities are given to processes is decided by a component in user mode. In this way, when the policy is to be changed, the kernel need not be touched.
The advantages of the microkernel are these. A crashed driver does not bring down the system; only that driver's process dies and it can be restarted. Because the kernel is small, it is easy to test, to verify, and to port to other hardware; the correctness of seL4's kernel of a few thousand lines has been proved mathematically. Because there is little privileged code, the surface an attacker can target is also small. The disadvantage is performance: every request between components needs a message and several mode switches. The designs of the L4 family have greatly reduced this overhead by making message passing extremely fast.
2.6.6Message passing in a microkernel
In a microkernel, an application reading from a file follows a much longer path than in a monolithic kernel. Figure 2.29 shows two moments of this path.
The application hands its request to the kernel as a message; the kernel delivers the message to the file system server in user mode. The file system finds which disk block is to be read, but it cannot access the disk itself; so it sends a message to the disk driver, again through the kernel. The driver reads the block with the I/O operations the kernel permits. The replies follow the same path in reverse. In a monolithic kernel, the same job is a chain of functions calling one another inside a single system call.
To see the path in more detail, let us trace the code of the client and the file system server (FS). The code below is written with two primitives named send and receive. send(destination, &m) sends a message to the destination; receive(source, &m) waits until a message arrives from the specified source (or from anyone, if ANY).
/* client */
m.type = READ; m.file = 7; m.offset = 0;
send(FS, &m);
receive(FS, &m); /* wait for reply */
/* file-system server (FS) */
while (1) {
receive(ANY, &m);
block = find_block(m.file, m.offset);
send(DISK, &block);
receive(DISK, &data);
m.result = data;
send(m.source, &m);
}The client wants to read from byte 0 of file number 7. The file system knows that this position is in block 120. At the start, FS and the disk driver are waiting for work in receive.
- The request is prepared. The client writes its request into the message structure:
m.type = READ,m.file = 7,m.offset = 0. - Message 1.
send(FS, &m)is a trap into the kernel. The kernel copies the message into FS's buffer and wakes FS up. The client blocks inreceive(FS, &m)waiting for the reply. - FS gets the job. FS's
receive(ANY, &m)call returns. Who the message came from is in the fieldm.source. Withfind_block, FS finds that the requested data is in block 120. - Message 2. FS cannot access the disk directly either. With
send(DISK, &block)it sends the second message to the driver and waits for the reply withreceive(DISK, &data). - Message 3. The driver reads the block with the I/O the kernel permits and sends the data to FS in the third message. FS prepares the reply with
m.result = data. - Message 4.
send(m.source, &m)carries the reply to the client; the client becomes ready. - FS returns to the loop. FS starts waiting for a new job in
receive(ANY, &m)at the top of thewhileloop. - The client continues. The client's
receivecall returns; the data is in the fieldm.result.
Four messages were sent for a single read. Each message involves at least one user → kernel and one kernel → user transition. In a monolithic kernel, the same job finishes inside a single system call, with two mode switches and a few function calls.
Measuring the overhead of a microkernel only by the number of messages. Besides two mode switches, each message usually needs a context switch too. The processor moves from the client process to the server process, and the server's address space becomes active. The data in the caches also becomes largely useless. The real source of the overhead is often these context switches.
2.6.7MINIX 3 and the client–server model
MINIX 3 is a microkernel operating system developed by Andrew Tanenbaum and his team that puts reliability in the foreground. Figure 2.31 shows its structure.
Two features of MINIX 3 stand out. The first is the reincarnation server (RS). RS constantly checks the health of the drivers. If a driver, for example the terminal driver (TTY), crashes or stops responding, RS restarts it without the user noticing. The system repairs itself. The second is split privilege. Drivers run in user mode and can reach the I/O ports only through kernel calls, to the extent they are allowed. A faulty driver can corrupt its own memory, but it cannot touch the memory of the kernel or of another process.
It is natural to divide the processes running on a microkernel into two classes: the clients that request service and the servers that provide it. Communication takes place only by messages. This arrangement is called the client–server model.
The model has an important consequence. The client does not have to know whether the message is handled on its own machine or on another machine in the network: it sends a message and waits for the reply. For this reason the model extends naturally to distributed systems. Today's web applications and microservice architectures are large-scale applications of the same idea. Even so, message passing is not secure in itself. Security depends on the kernel's checking which process may send messages to which server.
2.6.8The Tanenbaum–Torvalds debate
In 1991 Linus Torvalds released the first version of the Linux kernel. A few months later, in early 1992, MINIX's author Andrew Tanenbaum wrote a message in a newsgroup titled “LINUX is obsolete”. This message started one of the most frequently cited debates in the history of operating systems.
Tanenbaum's claim was this: the monolithic design is an outdated approach of the 1970s. A microkernel is more modular, more flexible, and easier to port; a bug in one component does limited damage. As hardware gets faster, the overhead of message passing will become negligible. Torvalds replied as follows: the monolithic kernel is simpler to design and implement, and direct function calls are faster. There is no need for message passing between processes; what really matters is code that works in practice. Besides, the open-source development model would make Linux develop quickly.
In the thirty years since, both sides have turned out partly right. Linux stayed monolithic and became one of the most widespread kernels in the world. But for the sake of flexibility it also borrowed ideas from microkernels. Loadable modules, and file systems (FUSE) and drivers (VFIO) running in user space, are examples. eBPF, which makes it possible to load small programs into the kernel safely, points in the same direction. Microkernels, in turn, have become widespread in safety-critical and embedded systems (QNX, seL4), where reliability matters more than performance.
2.6.9Modular structure
Most of today's operating systems follow a modular approach, to gain flexibility while keeping the speed of the monolithic kernel.
In a modular structure, the kernel holds only the core components; other services are added to the kernel at boot or at run time as loadable kernel modules (LKMs). Modules run in kernel mode and in the kernel's address space.
Linux, FreeBSD, and Solaris use this structure. The modular structure resembles two separate structures but differs from both. It resembles the layered structure, because each module has a defined interface; it is more flexible than that, because any module can call any other. It resembles the microkernel, because the core of the kernel is small and the services are in separate pieces; it differs from it in that the modules communicate by direct function calls without using messages and run in kernel mode.
usb_storage module is loaded; the vfat module is added when the drive is mounted.The life cycle of a module can be followed on Linux as follows. At boot, the kernel and the necessary modules in the initial RAM disk (initramfs) are loaded; the lsmod command lists the loaded modules. The user plugs in a USB drive. The kernel generates an event. The udev service sees this event and has the usb-storage module loaded, together with its dependencies, with modprobe. The vfat module needed to read the FAT file system on the drive, however, is loaded not at this time but when the drive is mounted (when the mount call asks for the file system type). Once loaded, a module registers itself with the kernel and from then on works through direct function calls. When no one is using the module any longer, that is, when its use count drops to 0, the modprobe -r or rmmod command removes it from memory.
The price of the modular structure is the lack of isolation. Because a module runs in kernel mode, a faulty module can crash the kernel; a malicious module can take over complete control of the system. Moreover, modules must be compiled to be compatible with the version of the kernel they are loaded into.
Counting Linux as a microkernel because it has loadable modules. What defines a microkernel is not that components are separate pieces, but that they run as separate processes in user mode and communicate by messages. Linux modules run in kernel mode, in the kernel's address space, and communicate by function calls. Linux is therefore a modular monolithic kernel.
2.6.10Hybrid kernels
Some systems set out with microkernel ideas and, out of performance concerns, moved many services back into kernel mode. These systems are called hybrid kernels. Windows and macOS are the two best-known examples.
ntdll.dll; in kernel mode, the executive, win32k.sys, device drivers, the kernel, and the HAL. At the bottom, the XNU kernel of macOS and iOS: Mach, BSD, and I/O Kit are merged in the same kernel address space.The design of Windows NT bears traces of microkernel ideas: subsystems, an object- and message-based structure, and a layer that abstracts the hardware (the hardware abstraction layer, HAL). But for performance, the executive, which includes the I/O, memory, process, and object managers, the graphics subsystem, and the device drivers were moved into kernel mode. XNU, the kernel of macOS and iOS, combines the Mach microkernel and a BSD UNIX layer in the same kernel address space. Mach provides IPC, scheduling, and virtual memory; BSD provides the POSIX interface, networking, and file systems; I/O Kit provides the object-oriented driver framework. The aim is to bring the modularity of the microkernel together with the speed of the monolithic kernel. In recent years Apple has been moving new drivers out of the kernel into the DriverKit framework in user space.
2.6.11The exokernel
At the far end of the spectrum is the exokernel. This approach is a research architecture proposed in 1995 by Dawson Engler and Frans Kaashoek at MIT. The kernel is called Aegis, and the library operating system that works with it is ExOS. The exokernel is not a commercial operating system but an idea.
An exokernel is a kernel that only distributes hardware resources in a protected way and tracks which resource belongs to whom. Abstractions such as files and virtual memory are provided not by the kernel but by library operating systems (LibOS) that run in user mode together with the applications.
Comparing the exokernel with the virtual machine approach makes the idea easier to grasp. A virtual machine monitor gives each virtual machine a copy of the whole machine. The virtual machine thinks it starts at block 0 of its own disk; the monitor has to map this block to a block on the real disk. An exokernel, on the other hand, gives each application a part of the real resource and only checks ownership. The application knows which real disk blocks it has received; no remapping layer in between is needed.
The slogan of the approach is to separate management from protection. The kernel only protects: an application cannot touch someone else's block or page. How the resources are managed is left to the application. A database can set up its own caching and disk layout strategy, and a web server its own network buffers. This application-specific management gives high performance; its price is that application development becomes more complicated. The exokernel idea lives on today in two forms. The first is unikernels, which compile a single application together with its own small operating system. The second is libraries such as DPDK and SPDK, which bypass the kernel in network and storage I/O and reach the device from user space.
2.6.12Comparing the structures
| Structure | What is in the kernel? | Strength | Weakness | Example |
|---|---|---|---|---|
| Simple | everything, unrestricted | small, simple | no protection | MS-DOS |
| Monolithic | all services | speed | no fault isolation | UNIX, Linux |
| Layered | hierarchical layers | easy to verify | overhead, layers hard to define | THE, MULTICS |
| Microkernel | IPC, scheduling, memory | reliability | message overhead | MINIX 3, QNX, seL4 |
| Modular | kernel core + modules | flexibility, speed | module = full privilege | Linux, FreeBSD |
| Hybrid | microkernel + selected services | balance | complexity | Windows, macOS |
| Exokernel | protection only | application-specific speed | hard to develop for | Aegis/ExOS |
The table gives the structures in their pure forms. Real systems are seldom pure. Linux is monolithic and modular; Windows and macOS are hybrid; nearly all are layered to some degree. Instead of placing a system in a single box, it is more instructive to ask which decisions it made and why.
2.7Virtual machines and multiprocessor systems
Kernel structures describe how an operating system organizes its own inside. The two topics of this section concern the hardware beneath the operating system: the duplication of hardware in software, and several processors sharing the same memory.
2.7.1Virtual machines
A hypervisor, or virtual machine monitor (VMM), is a layer of software that creates virtual machines (VMs) on a single piece of physical hardware, each looking like an independent computer. The operating system running inside a virtual machine is called a guest operating system.
Each guest operating system believes it has its own processor, memory, disk, and I/O devices. For this reason different operating systems can run on the same hardware at the same time: on the same server, Linux can run in one virtual machine and Windows in another. Figure 2.36 compares a nonvirtual machine with virtual machines.
The idea is not new; it goes back to IBM's VM/370 system, released in 1972. Today it is the foundation of cloud computing. The main benefits of virtualization are these:
- Server consolidation. Many lightly used servers are gathered on a single powerful machine.
- Isolation. A problem in one virtual machine does not spread to the others.
- Snapshots. The current state of a virtual machine is saved, and if needed one can return to this state.
- Live migration. A running virtual machine is moved to another physical machine without being shut down.
Hypervisors fall into two types according to where they run. A Type 1 hypervisor runs directly on the hardware; there is no other operating system beneath it. The hypervisors used in data centers are of this kind. A Type 2 hypervisor runs like an application on top of an ordinary operating system; the programs that run virtual machines on a desktop computer are of this kind.
A concept often confused with the virtual machine is the container. A container does not carry its own kernel. It isolates a group of processes that share the same kernel from other processes through the kernel's namespaces and resource-limiting mechanisms. A container is therefore much lighter than a virtual machine and can be started in under a second. But because it shares the same kernel, only programs compatible with that kernel can run inside it, and its isolation is not as strong as a virtual machine's.
Thinking that an exokernel and a hypervisor are the same thing. Both share resources among several parties, but in different ways. A hypervisor gives each virtual machine a complete copy of the machine and maps virtual resources to real resources itself. An exokernel distributes pieces of the real resources and only checks ownership; the application's LibOS builds the abstractions.
2.7.2Symmetric multiprocessing and multicore architecture
Almost every computer today has several processors or processor cores. This affects the structure of the operating system too.
In a symmetric multiprocessor (SMP) system, each processor has its own registers and cache, but main memory is common. The word “symmetric” says that all processors have equal rights: all of them can do every job, including running operating system code. This has an important consequence. Because two processors can run kernel code at the same time, the kernel's shared data structures must be protected with locks.
The kernel has a linked list of ready processes, and the pointer head points to the head of the list. At the start the list consists only of task A. Two processors add tasks to the list at the same time: CPU0 adds task X and CPU1 adds task Y. Insertion is two steps: (1) t->next = head; (2) head = t;. What happens if the steps are executed in the order CPU0(1), CPU1(1), CPU0(2), CPU1(2)?
Solution. CPU0(1): X.next = A. CPU1(1): Y.next = A. CPU0(2): head = X; the list becomes X → A. CPU1(2): head = Y; the list becomes Y → A. Task X has vanished from the list: it cannot be reached from any pointer and is never scheduled. The result depends on the order in which the steps are executed; this is called a race condition. The solution is to protect the insertion with a lock: acquire the lock, do (1) and (2), release the lock.
The first multiprocessor Linux versions solved this problem in a crude way: they protected the whole kernel with a single lock, the “big kernel lock”. Only one processor at a time could run kernel code. Over the years this lock was replaced by finer-grained locks and was removed completely in 2011.
In a multicore chip, several cores are on the same chip. Because the cores share nearby caches, they communicate faster and with less energy than processors on separate chips. A design that is common in 2026 is to have two kinds of cores on the same chip: performance (P) cores that are fast but consume energy, and efficiency (E) cores that are slow but frugal. This design gives the scheduler a new task: deciding which job runs on which kind of core.
2.8Linking, loading, and booting
The last two topics are how a program and an operating system start running. The source code the programmer writes goes through several stages before it becomes a process. In the same way, there is a series of steps from the moment the power button is pressed until the login screen appears.
2.8.1Compiling, linking, and loading
main.c is translated by the compiler (gcc -c) into the object file main.o. The linker (ld) combines this with other object files and static libraries (libm.a) and produces the executable program. The loader (execve and ld.so) brings the program into memory together with the shared libc.so.6, and the process starts running.- Compiling. The compiler translates the source code into a relocatable object file. The addresses in this file are not yet final, because where the code will be placed in memory is not known. Symbols that the program uses but that are defined in another file, for example
printf, are also unresolved. - Linking. The linker combines the object files and static libraries. It finds in which file each symbol is defined, fixes the addresses, and produces an executable file.
- Loading. The shell calls
execve. The loader in the kernel reads the file's header and maps the code and data segments into the process's address space. If the program uses shared libraries, it starts the dynamic linker (ld-linux.so). - Dynamic linking. Shared libraries, for example
libc.so.6, are linked at run time. The library's code stays in memory as a single copy, and all processes that use it share this copy.
On a server, 50 different programs that use the C library are running at the same time, and the library's code takes 3 MiB. How much memory is needed for the library code if the library is linked statically, and if it is linked dynamically?
Solution. In static linking, the library code that is used is copied into each executable file. Each process loads its own copy into memory: 50 × 3 MiB = 150 MiB is needed. In dynamic linking, because the library's code pages are read-only, a single copy is mapped into the address spaces of all processes: about 3 MiB is enough. Each process additionally uses a small private area for the library's writable data. Dynamic linking has one more benefit: when a security hole in the library is closed, only libc.so is updated. With static linking, all 50 programs would have to be relinked.
The format of the executable file is specific to the operating system: Linux uses ELF (Executable and Linkable Format), Windows uses PE (Portable Executable), and macOS uses the Mach-O format. This is one reason a program cannot be moved directly from one operating system to another. Even on the same processor, one system's executable file is in a format that the other system's loader does not understand, and the system calls of the two systems differ too.
2.8.2The boot process
Booting is the process from the moment power is applied to the computer until the kernel is loaded into memory and starts the first user process.
On old PCs, booting was handled by the BIOS (firmware running in 16-bit real mode), in use since 1981. The BIOS loaded the master boot record (MBR) in the first sector of the disk into memory and ran it. Today's computers use UEFI. UEFI loads not a sector but a file (a program with the .efi extension). Figure 2.39 shows the boot steps of a Linux computer that uses UEFI.
systemd).- Power and reset. When power is applied, the processor is reset and starts executing the firmware that sits in flash memory on the motherboard, from a fixed address determined by the hardware. At this moment there is no operating system in memory yet.
- UEFI. The firmware first performs the power-on self-test (POST): it tests memory and finds devices. Then it looks at the boot order recorded in its persistent settings (NVRAM) and tries, in turn, the NVMe disk, USB, or network boot (PXE) options. It loads the bootloader from the EFI system partition (a FAT32 file system) of the GPT-formatted disk. If Secure Boot is on, the bootloader's digital signature is verified; an unsigned or modified bootloader is not run.
- The bootloader. The bootloader, GRUB 2 or systemd-boot, presents the user with a menu. It places the selected kernel and the initial RAM disk (initramfs) into memory and hands control to the kernel.
- The kernel. The kernel starts memory management, the scheduler, and the drivers. The scripts in initramfs load the modules needed to reach the real root file system (for example, disk controller or encrypted disk support).
- The root file system. The real root file system is mounted, and initramfs, no longer needed, is released from memory.
- PID 1. The kernel starts the first user process,
systemd, whose PID is 1.systemdstarts the services, the network, and the login screen as much in parallel as possible.
PID 1 has a special place. Every process created in the system from then on is its descendant; it is the root of the process tree. Processes whose parent has died are also adopted by PID 1, which collects their exit statuses. On Linux, the systemd-analyze command shows how long each stage of booting took. On Windows, the counterpart of the same chain is winload.efi → ntoskrnl.exe → smss.exe → winlogon.exe.
2.9Summary
- The operating system structure is the strategy for where the components run (kernel or user mode) and how they communicate (function call or message). Each structure chooses a trade-off among performance, reliability, and flexibility.
- The operating system offers the user and programs the services of an interface, program execution, I/O, a file system, communication, and error detection; and the system as a whole the services of resource allocation, accounting, protection, and security. The services are reached through system calls.
- A process is a running program; its information is kept in the PCB in the process table. Processes form a tree through
fork(). The address space consists of the text, data, BSS, heap, and stack segments. - Files live in a directory tree; open files are referred to by small integers (descriptors), and a new file gets the smallest free number. Mounting attaches a file system to a directory in the tree. A pipe is a one-way byte channel connecting two processes.
- Dual-mode operation reserves privileged instructions for kernel mode; the timer makes sure the processor always returns to the operating system. The kernel is entered only by system call, interrupt, and exception.
- In a system call, the libc wrapper puts the call number and parameters into registers and executes the trap instruction; the kernel checks the number and finds the handler in the system call table. On error the call returns −1 and
errnois set. printfis a library function and makes thewritesystem call when it flushes its buffer. The buffer size determines the number of system calls made.- The shell works with the
fork,execve, andwaitpidtrio.linkadds a new name to an inode, andunlinkremoves a name; a file disappears only when both the link count and the open count are 0. - A monolithic kernel is fast but has no fault isolation. A layered structure makes verification easier but adds overhead. A microkernel is reliable but carries message overhead. A modular structure combines flexibility with speed, and hybrid kernels blend these ideas. An exokernel only protects and leaves management to the application.
- A hypervisor virtualizes the hardware and runs several operating systems on the same machine; a container isolates processes that share the same kernel. In SMP systems, kernel data structures must be protected with locks.
- Source code becomes a process by passing through the compiler, the linker, and the loader. At boot, the firmware, the bootloader, and the kernel run in turn, and the kernel starts PID 1, the first user process.
2.10Key terms
- operating system services
- process
- process control block (PCB)
- parent / child process
- address space
- interprocess communication (IPC)
- file descriptor
- path name
- block / character device
- mount
- pipe
- deadlock
- resource allocation graph
- dual-mode operation
- kernel mode / user mode
- trap
- timer
- system call
- application programming interface
- shell
- i-node
- hard link
- monolithic kernel
- layered system
- microkernel
- message passing
- policy / mechanism
- client–server model
- loadable kernel module (LKM)
- hybrid kernel
- exokernel
- virtual machine (VM)
- hypervisor
- guest operating system
- container
- symmetric multiprocessor (SMP)
- race condition
- executable file
- shared library
- booting
- bootloader
2.11Test Yourself
In a newly started process only 0, 1, and 2 are open. The following run in order:
a = open("x", O_RDONLY),b = open("y", O_RDONLY),close(a),c = open("z", O_RDONLY),close(2), andd = dup(b). What area,b,c, andd?Answer
Each call gives the smallest free number.
a = 3,b = 4.close(a)frees 3;c = 3.close(2)closes standard error and the smallest free number becomes 2;d = dup(4) = 2. Result: 3, 4, 3, 2. The error messages in this process are now directed to filey; but since the file was opened read-only, an attempt to write there fails.The copy code traced in these notes copies a 9000-byte file with a 4096-byte buffer. How many
readand how manywritecalls are made, and what does eachreadreturn? How many system calls are made in total, together withopen,creat, the twoclosecalls, andprintf?Answer
readreturns 4096, 4096, 808, and 0 in turn: 4readcalls. Because the last call reports end of file, nowritefollows it: 3writecalls. The total is 1 + 1 + 4 + 3 + 2 + 1 = 12 system calls. The program prints9000 bytes.In the call
write(1, "Günaydın\n", n), what mustnbe for the whole text to be written? What appears on the screen ifnis given as the number of characters?Answer
The text has 9 characters (G, ü, n, a, y, d, ı, n, \n). Because ü and ı take two bytes each in UTF-8, the number of bytes is 11;
n = 11must be given. Ifn = 9is given, the last two bytes, that is, the final letter “n” and the newline, are not sent, and “Günaydı” appears on the screen; the cursor stays on the same line.On x86-64 Linux, in which registers are the six parameters and the call number of
mmap(addr, length, prot, flags, fd, offset)placed? Why is the fourth parameter not placed inrcx?Answer
The call number goes into
rax;addrintordi,lengthintorsi,protintordx,flagsintor10,fdintor8, andoffsetintor9. Because thesyscallinstruction saves the return address inrcxand the flags register inr11, a parameter inrcxwould be erased before reaching the kernel; that is whyr10is used instead of thercxof the C convention.A timer's counter decreases by 1 on every tick of a 1 MHz clock. The kernel wants 100 ticks per second. What value must be loaded into the counter? If handling each tick interrupt takes 5 µs, what percentage of the processor's time goes to ticks?
Answer
1,000,000 / 100 = 10,000; 10,000 is loaded into the counter and the time between two ticks is 10 ms. The overhead is 100 × 5 µs = 500 µs per second; this is 0.05% of the processor's time.
A process creates a file named
f(link count 1). Thenlink("f", "g"),link("g", "h"),unlink("f"),fd = open("h", O_RDONLY),unlink("g"), andunlink("h")are called. What is the link count after each step? When are the file's blocks freed?Answer
The link count becomes 2, 3, 2, 2, 1, and 0 in turn.
link("g", "h")adds a third name to the inode thatgpoints to, that is, to the same file.opendoes not change the link count; it makes the open count 1. After the lastunlinkthe file has no name left, but because the descriptor is open the blocks are not freed. The blocks are freed only whenclose(fd)is called (or the process terminates).Suppose the
perrorand_exit(127)lines in the child have been deleted from the simple shell skeleton: the child does not callexitafterexecve. What happens if the user types a nonexistent command such aslss?Answer
execvecannot find the program and returns −1. The child, running the shell's code, leaves theelseblock and returns to the top of thewhileloop: it prints the prompt and starts waiting for a command. The parent shell, meanwhile, is still waiting inwaitpidfor this child to finish. Without noticing, the user talks to a second shell; only when that “shell” is exited does the parent wake up.In a microkernel system, the file block the client wants is found in the file system server's cache. With how many messages and at least how many mode switches does the read complete? How many mode switches occur in a monolithic kernel?
Answer
There is no need to go to the disk driver. Two messages suffice: the client's request and the server's reply. Because each message needs one user → kernel and one kernel → user transition, there are at least 4 mode switches. In a monolithic kernel the read is a single system call: one transition on entry and one on return, 2 in total.
Which of the following operations are completed with library code alone, and which need a system call:
strlen,getpid,sqrt,fork,printf("a")(no newline, output on the terminal)?Answer
strlenandsqrtwork only with the process's own data; they are library code.getpidandforktouch process information in the kernel; they are system calls.printf("a")is a library function, and because it is line-buffered on a terminal, it does not enter the kernel before a newline arrives; the “a” waits in the buffer. When the buffer is flushed later (at a newline,fflush, or the end of the program),writeis called.Suppose a driver corrupts memory through a faulty pointer. What can this bug harm in MINIX 3, in Linux (with the driver as a loadable module), and in an exokernel-based system (with the driver in the application's LibOS)?
Answer
In MINIX 3 the driver is a separate process in user mode; it can corrupt only its own memory, it crashes, and the reincarnation server restarts it. In Linux the module runs in kernel mode in the kernel's address space; it can corrupt any structure of the kernel and crash the whole system. In an exokernel the LibOS is in the same address space as the application; the bug corrupts that application, but because the exokernel checks ownership, it cannot touch the resources of the other applications.
2.12Further reading
- A. Silberschatz, P. B. Galvin, and G. Gagne, Operating System Concepts (10th ed., 2018), Chapter 2: covers operating system services, system calls, the linker and loader, structures, and booting in the order these notes follow, with plenty of figures.
- A. S. Tanenbaum and H. Bos, Modern Operating Systems (4th ed., 2014), Sections 1.5–1.7: treats the concepts of process, address space, and file, the POSIX calls, the eleven steps of
read, and the monolithic, layered, microkernel, client–server, and exokernel structures in detail. - R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces (version 1.10), the chapters “Process API” and “Limited Direct Execution”: explain the
fork/exec/waittrio and the protection based on traps and the timer with short, clear examples; free and online. - D. R. Engler, M. F. Kaashoek, and J. O'Toole, “Exokernel: An Operating System Architecture for Application-Level Resource Management” (SOSP 1995): the original paper that put forward the exokernel idea; it defends the principle of separating management from protection with measurements on Aegis and ExOS.
2.13References
- R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, version 1.10, pages.cs.wisc.edu/~remzi/OSTEP.
- D. R. Engler, M. F. Kaashoek, and J. O'Toole, “Exokernel: An Operating System Architecture for Application-Level Resource Management”, SOSP, 1995.
- Linux man pages:
syscalls(2),syscall(2),fork(2),pipe(7),mount(8). - A. Silberschatz, P. B. Galvin, and G. Gagne, Operating System Concepts, 10th ed., Wiley, 2018 (Chapters 2 and 18).
- A. S. Tanenbaum and H. Bos, Modern Operating Systems, 4th ed., Pearson, 2014 (Sections 1.5–1.7 and 7).
Related pages: Chapter 2 slides · © Sercan Külcü. All rights reserved.