Operating Systems · Lecture Notes
Chapter 1: Introduction
Every program on a computer relies on a layer of software beneath it: the operating system. A browser writes a file to disk without knowing the disk's brand. A game draws to the screen without touching the graphics card's registers. A compiler runs without being able to corrupt the memory of other programs. The operating system provides all of this convenience and protection. These notes begin with the place of the operating system between hardware and applications and with its two basic roles: the extended machine, which presents the hardware through useful abstractions, and the resource manager, which shares resources among programs. They then cover kernel mode and user mode, the controlled transition between the two, the historical development of operating systems, and the hardware features that drove that development. The last sections deal with I/O methods, the kinds of operating systems, the separation of policy from mechanism, and how a C program becomes a running process.
Learning outcomes
- Definition and place
- Explain where the operating system sits between hardware and applications and describe its two basic roles (extended machine, resource manager).
- Protection
- Explain kernel mode and user mode and the controlled transitions between them (system call, interrupt, exception).
- Historical development
- Describe which problems the ideas of batch processing, multiprogramming, and time sharing solved; draw the timeline of two jobs and compute CPU utilization.
- Hardware foundations
- Interpret how the processor and its registers, the memory hierarchy, and multicore chips affect the operating system.
- I/O methods
- State the basic difference between polling, interrupts, and DMA, compute the CPU load, and distinguish an interrupt from a trap.
- Concepts
- Illustrate the kinds of operating systems, the policy–mechanism separation, and the transformation of a program into an executable file with examples.
1.1What is an operating system?
In everyday speech, “operating system” is often confused with the desktop on the screen: the Start menu, the file explorer, the wallpaper, and the icons. These are only the visible face of the operating system, and most of them are ordinary programs. The real work happens out of sight, in the software layer that decides which program runs when, who uses which part of memory, and in what order requests to the disk are served. This section explains what that layer is and why it exists.
1.1.1Why do we need an intermediate layer?
Consider the inside of an ordinary laptop today. It has a multicore processor, gigabytes of memory, an SSD, wireless and wired network cards, a graphics processing unit (GPU), a keyboard, a touchpad, a camera, a microphone, speakers, and a few USB ports. Each of these devices comes from a different manufacturer, and each has its own way of being controlled. To write data to an SSD, command queues are prepared, block addresses are computed, and error codes are checked. To receive a packet from a network card, ring buffers are set up and interrupts are configured.
It is unreasonable to expect every application developer to learn all of these details and write them directly into each program. If that were the case, a text editor would have to contain separate code for every disk model on the market. Worse, if two programs running at the same time tried to write to the same disk in their own way, the data on the disk would be mixed up. So there are two separate needs: a common interface that hides the complexity of the hardware, and order and protection among the programs that use the same hardware. The operating system is the answer to these two needs.
An operating system (OS) is the layer of software that manages a computer's hardware and offers applications a simple, safe, and common interface.
Each of the three adjectives in the definition corresponds to a separate job. A simple interface means that an application only has to say “write these bytes to that file”; the internal structure of the disk is the OS's problem. A safe interface means that the bug or malice of one program cannot harm other programs or the system as a whole. A common interface means that the same program can run unchanged on different hardware: a C program writes to a file with the same write call whichever SSD is installed.
Today very different operating systems run in very different environments. On the desktop, Windows 11, macOS, Linux distributions such as Ubuntu or Fedora, and ChromeOS are common. Phones and tablets use Android, iOS/iPadOS, and HarmonyOS. On servers and in the cloud, Linux is far ahead, with Windows Server and FreeBSD also present. Inside cars, household appliances, and Internet of Things (IoT) devices run small, special-purpose systems such as Zephyr, FreeRTOS, Contiki-NG, VxWorks, and QNX. These systems differ greatly in size and goals, but all of them solve the same two basic problems.
1.1.2The kernel and the rest of the software
When an operating system is installed, thousands of files are written to disk: drivers, libraries, utilities, fonts, configuration tools, the desktop environment. Calling all of them “the operating system” would make the term almost meaningless. For this reason, textbooks distinguish a narrow and a broad meaning.
The kernel is the part of the operating system that stays in memory as long as the computer is on and runs in the processor's privileged mode. In the narrow sense, “operating system” means the kernel.
The kernel creates and schedules processes, allocates memory, hosts the file systems and device drivers, and handles interrupts. Most of the rest of the software runs on top of the kernel like ordinary programs. The two interfaces through which the user talks to the computer are both in this second group: the shell, that is, the command line, and the GUI (graphical user interface). Both are discussed in detail below; what matters here is that neither is part of the kernel.
1.1.3Components of a computer system
Thinking of a computer system in layers is the easiest way to see who does what. Figure 1.1 shows these layers from bottom to top.
The lowest layer, the hardware, contains the processor, the memory, the storage devices, and the input/output (I/O) devices. These are physical components; on their own they understand only very simple commands. The operating system just above it is the only software that controls the hardware directly, and it runs in the processor's privileged mode. The top layer holds everything else: the applications the user runs and, at the same level, the shell and the GUI.
The separation in the figure divides the software world in two. The software that runs in kernel mode is the operating system. Everything that runs in user mode, even the shell and the GUI, is an ordinary user program. Why this separation matters so much is explained in 1.2.2, which covers the modes.
Taking the desktop, the windows, or the command line to be the operating system itself. A Linux server has no GUI at all, yet its operating system runs in full. On top of the same Linux kernel there can be GNOME, KDE Plasma, or just a terminal. The visible interface changes; the kernel stays the same.
1.1.4The shell and the GUI
When users want to get something done, they say so either by typing a command or by clicking an icon with the mouse. A separate program serves each of these two routes.
The shell is the command-line interface (CLI) that reads the commands a user types, interprets them, and starts the corresponding programs. A GUI, in contrast, is a visual interaction environment made of windows, icons, menus, and a pointer (WIMP).
ls ~/notes lists two files, ps aux | grep firefox finds the running Firefox process, and uname -sr prints the kernel version (Linux 6.12.8). On the right, a desktop (GUI) made of windows, icons, menus, and a pointer.Common shells include bash, zsh, and fish on Linux and macOS, and PowerShell and the older cmd.exe on Windows. On the GUI side, Windows Explorer, macOS Finder, and the GNOME and KDE Plasma environments on Linux are well known. Figure 1.2 shows that two interfaces can run side by side on the same computer.
Neither the shell nor the GUI is part of the kernel. Both are programs running in user mode, and when they want a service from the kernel, for example to open a file or start a new program, they make a system call. This has practical consequences. The shell can be replaced: switching from bash to zsh does not require touching the kernel. Several shells can be open at once. If a shell crashes, only that window closes and the system keeps running. Users can customize their interfaces because what they change is only a program.
1.1.5Shell or GUI?
There is no contest between the two interfaces; each excels at different jobs. The greatest strength of the shell is automation. Once commands are written to a script file, the same job can be repeated thousands of times without a single click. Its second strength is that small tools can be combined. The output of one command is connected to the input of the next with a pipeline:
$ ps aux | grep ssh | wc -lIn this line, ps aux lists all running processes. grep ssh selects the lines of that list that contain “ssh”. wc -l counts the remaining lines. The combination of three simple tools answers the question “how many process lines contain ssh?” in one line. The shell uses few resources and is the natural way to manage a remote server over an SSH connection. It does specific tasks quickly and precisely.
The strength of the GUI is discoverability. Users do not have to memorize commands; they see what can be done by looking at the menus. It is the natural environment for working with visual content such as photos, maps, or designs. It reaches a wide audience and works together with accessibility tools such as screen readers. Touch and voice interfaces belong to the same family.
In practice the two complement each other: the GUI for everyday tasks, the shell for repetitive and remote ones. Both use the same kernel services. From the kernel's point of view, it makes no difference whether a file was copied with the shell's cp command or by drag and drop in the file explorer. In both cases, what reaches the kernel is system calls of the same kind.
1.1.6Device Manager
A concrete way to see how the operating system views the hardware is the Device Manager tool in Windows. It lists the hardware devices attached to the computer, and the software that drives them, in a tree organized by category. It is opened by typing devmgmt.msc on the command line and is a snap-in written for the Microsoft Management Console (MMC).
Device Manager shows each device's type, manufacturer, driver version, and the resources it uses (which interrupt line, which memory range). From here a driver can be updated or rolled back to a previous version, and a device can be disabled. Problem devices are marked with a warning icon, as in Figure 1.3.
Note that the tool itself does not do the work. What detects devices, assigns them resources, and loads the appropriate driver is the Plug and Play (PnP) manager in the kernel, together with the device drivers. Device Manager is only a window onto the information they hold. On Linux the same information is read with the lspci (PCI devices), lsusb (USB devices), lsblk (block devices), and lsmod (loaded kernel modules) commands. The files under /sys and the udev service, which manages device events, expose the same information as well.
1.2Position and modes
It is easy to say that the operating system stands “between the hardware and the applications”. The real question is how that position is protected. Why can't an application simply write to the disk itself? Why can't a malicious program bypass the operating system? The answer lies not in software but in the processor itself. This section first describes the position of the operating system and then the hardware feature that secures it: the processor modes.
1.2.1Where the operating system sits
Hardware is the name for the physical components: the CPU, the RAM, and the disk. Software is the code that describes what the computer will do. The operating system is the interface between the two. Applications do not reach the hardware directly; they reach it through the system calls that the OS offers.
A system call is the controlled entry point a user program uses to request a service from the kernel. Opening, reading, and writing files, creating new processes, and requesting memory, in short everything that needs privilege, is done through system calls.
Figure 1.4 shows five layers stacked on top of each other. The layer that stands out is the thin “system call interface” between the applications and the operating system. This interface is the only door between two worlds. Everything an application can ask of the OS is written on this door's list; an application cannot get done anything that is not on the list. On Linux the list holds a few hundred calls, and each has a number.
The three items to the right of the figure summarize what the operating system does from this position. Control: the OS decides which program accesses which hardware, when, and how much. Optimization: it keeps the hardware from sitting idle and makes sure jobs finish in reasonable time. Security and isolation: it prevents programs from harming each other and the system.
1.2.2Kernel mode and user mode
It is impossible to stop a program from accessing the hardware directly merely by telling it that it should not. After all, the program runs on the processor, and the processor executes every instruction it is given. The barrier is built by a hardware feature placed inside the processor.
The processor has a mode bit (or a privilege level of a few bits) that shows the current privilege level. In kernel mode all instructions and all of memory can be used. In user mode privileged instructions are forbidden; when one is attempted, the processor does not execute it, raises an exception, and hands control to the kernel.
Privileged instructions are those that can affect the system as a whole. Accessing I/O devices directly, disabling interrupts, and changing the page table (that is, which virtual address maps to which physical memory) belong to this group. When one of them is attempted in user mode, the processor raises a trap: it abandons the current instruction, switches to kernel mode, and jumps to a handler the kernel set up in advance. The kernel usually terminates the program. The rest of the system is unaffected.
Different processor families give these levels different names. The x86 architecture has four rings: ring 0 is the most privileged and ring 3 the most restricted. In ARMv8 the exception levels run from EL0 to EL3; applications run at EL0 and the kernel at EL1. RISC-V has U (user), S (supervisor), and M (machine) modes.
Figure 1.5 shows that operating systems use only two of the four levels. The reason is portability: Linux and Windows run on many processor families, and the common denominator is two levels. The shell and the GUI sit on the lowest rung of user-mode software; even they have no access to ring 0.
There are only three controlled ways to move from user mode to kernel mode:
- System call: the program deliberately requests a service from the kernel with a special instruction (
syscallon x86-64). - Interrupt: a device, such as the timer or the network card, sends a signal to the processor from outside.
- Exception: the executing instruction itself causes a problem, such as division by zero, access to an invalid address, or a privileged instruction in user mode.
What the three paths have in common is that the program cannot choose where to jump. The target addresses are written in a table that the kernel fills in at boot. The program can only say “I want to go to the kernel”; it cannot decide at which point of the kernel it enters. The protection rests on exactly this.
Confusing kernel mode with “running as the administrator (root or Administrator) account”. A program started with the administrator account also runs in user mode; the kernel merely allows it more. For example, it can open any file. But everything such a program does is still done through system calls, and the program itself never runs in ring 0.
1.2.3A mode switch step by step: read()
To make the mode switch concrete, let us follow the single line in which a C program reads from a file:
char buf[100];
int n = read(fd, buf, 100); /* n: number of bytes read */To the programmer this is an ordinary function call. In reality, this line starts a five-step journey from user mode into kernel mode and back. The values below are for Linux on the x86-64 architecture.
read() system call (left to right, top to bottom). (a) The libc wrapper puts the call number and the arguments into registers; the mode bit is 1, that is, user mode. (b) The syscall instruction raises a trap; the mode bit becomes 0. (c) The kernel finds sys_read() in entry 0 of the system call table, checks the arguments, and copies the data. (d) sysret sets the mode bit back to 1 and the process continues where it left off.- Start. The process is running in user mode (mode bit = 1). It wants to read from a file, but it cannot reach the disk itself; instructions that touch the disk controller's registers are privileged.
- The wrapper. The
read()that the program calls is really a small wrapper function in the C library (libc). It puts the call number into theraxregister (on x86-64 Linux the number ofreadis 0) and places the arguments in therdi,rsi, andrdxregisters in order:fd,buf, 100. Then it executes thesyscallinstruction. - The trap. With the
syscallinstruction the hardware does three things: it sets the mode bit to 0, saves the return address, and jumps to the kernel's fixed entry point. The process cannot choose where to jump; the kernel wrote the entry point into a register at boot. - Work in the kernel. The kernel uses the number in
raxto look into the system call table and findssys_read()at entry 0. This function first validates the arguments: isfdan open file of this process, and does the addressbufreally lie in the process's own memory? If the checks pass, it copies the data from the file into the process's buffer. - The return. The result, the number of bytes read, is written to
rax. Thesysretinstruction sets the mode bit back to 1, and the process continues from the instruction afterread(). As far as the program can tell, the variablenhas received the number of bytes read.
The validation in the fourth step is the heart of protection. A malicious program could pass the address of the kernel's own memory as buf. If the kernel used this address without checking, it would write the file's data over its own structures and become open to takeover. For this reason the kernel trusts no value that comes from the user.
Which of the following operations cause a transition from user mode to kernel mode? (a) int x = a + b; (b) read(fd, buf, 100); (c) an instruction accessing an invalid address (d) strlen(s); (e) the timer raising an interrupt.
Solution. (a) Addition is an ordinary operation on registers and the ALU; the mode does not change. (b) This is a system call; the libc wrapper deliberately raises a trap with the syscall instruction, so a transition occurs. (c) This is an exception caused by the instruction itself; the processor jumps to the kernel's handler, so a transition occurs. (d) strlen is a library function that counts characters in memory up to the zero byte; it stays entirely in user mode. (e) This is a hardware interrupt coming from outside; a transition occurs. Result: (b), (c), and (e) go to the kernel; they are, respectively, a system call, an exception, and an interrupt.
Thinking that every library function goes to the kernel. Functions such as strlen, memcpy, and sqrt live in libc but work only with user memory and registers. Only system call wrappers such as read, write, open, and fork go to the kernel. printf is a mixture of the two: it does the formatting in user mode and finally sends the output with the write system call.
1.2.4Physical devices, microarchitecture, machine language
There are layers below the operating system as well. Separating them helps to delimit the OS's job.
- Physical devices: chips, memory modules, SSDs, and I/O devices; the electronic components themselves.
- Microarchitecture: the internal design of the processor. The data path, registers, arithmetic logic unit (ALU), caches, and control unit are at this level.
- Machine language: the binary instructions that the hardware executes directly. The instruction set of a processor family is called its instruction set architecture (ISA). x86-64, ARM64, and RISC-V are today's main ISAs.
The operating system's job in these layers is to translate, through drivers, the requests of the upper layer into low-level commands the device understands. There is one boundary to keep in mind: it is the compiler that translates a program into machine language, not the operating system. The compiler is an ordinary user program that sits among the system programs, as in Figure 1.7. The operating system loads the compiled program into memory, runs it, and mediates its access to the hardware.
1.3Roles of the operating system
The operating system can be viewed from two different angles. From above, that is, from the application's point of view, the OS is a layer that hides the ugly details of the hardware and puts useful concepts in their place. From below, that is, from the hardware's point of view, it is a manager that arbitrates among many programs that all want the same processor, the same memory, and the same devices. Textbooks call these two views the extended machine and the resource manager.
1.3.1The extended machine
The interface that bare hardware offers is both complicated and fragile for the programmer. To write a single block to an SSD, one first prepares NVMe command queues and computes the logical block address (LBA). The command is placed in the queue and the controller is notified. Then the completion queue is watched and any error codes are interpreted. The application needs to know none of this; it only says:
write(fd, "Welcome", 7);It is the operating system that bridges the gap. Tanenbaum describes this role in a concise sentence: the operating system turns ugly hardware into beautiful abstractions.
An abstraction is a simplified model that hides the unnecessary details of something and shows only its useful properties. Because the operating system builds abstractions on top of the hardware, it is viewed as an extended machine: it presents the programmer with a more useful, “extended” computer than the bare hardware.
open, read, write, fork …). The operating system deals with the ugly interface of the hardware (registers, interrupts, timing).The extended machine role has three consequences. The first is convenience: the capabilities of the hardware become usable and their complicated details are hidden. The second is protection: because applications cannot reach the hardware directly, they cannot interfere with each other's work. The third is portability: even if the SSD changes, or storage over a network is used instead of a disk, the write call stays the same.
1.3.2Abstractions and roles
Each abstraction that the operating system builds corresponds to a particular piece of hardware. Table 1.1 gives the main correspondences.
| Hardware | OS abstraction |
|---|---|
| Processor (CPU) | Process and thread |
| Memory (RAM) | Address space (virtual memory) |
| Storage (SSD/disk) | File and directory |
| Network card | Socket |
| Display, keyboard | Window, terminal |
Each abstraction in the table makes a limited and shared resource of the hardware look as if it belonged to each program alone. There is a single processor, yet each process is written as if it were the only one using it. There is a single physical memory, yet each process sees its own address space starting at address 0. The disk holds millions of blocks, yet the program knows only a file name. The network card is one, yet each connection has its own socket.
Four distinct roles can be told apart around these abstractions. The hardware designer designs the ISA, the devices, and the devices' interfaces. The kernel developer implements the abstractions on top of this hardware; the process, virtual memory, and the file system are the developer's products. The application developer uses the abstractions through system calls and application programming interfaces (APIs). The end user sees only the applications and the interface. Most of this course is devoted to understanding the work of the second role.
1.3.3The journey of a write() call
To see what an abstraction hides, let us follow the call write(fd, "Welcome", 7) from the application down to the SSD. This call asks to write the 7-byte string “Welcome” to the file the program has opened.
write() call. In user mode are the application and the C library; in kernel mode are the system call interface, the virtual file system (VFS), the file system (ext4, NTFS, APFS), the page cache and block layer, and the device driver (NVMe); at the very bottom is the SSD controller. In the last step the driver and the SSD controller are highlighted.- The application supplies only three things: a file descriptor (
fd), a buffer, and a length. It does not know the type of the disk, nor even whether the data is going to a local disk or over the network. - The libc wrapper puts the arguments into registers and moves to the kernel with
syscall, just likeread()in 1.2.3. - The virtual file system (VFS) resolves
fdthrough the process's open file table to a file object, and from there to the file's inode. The VFS is the layer common to all file systems. - The file system (ext4, NTFS, APFS …) translates the position in the file, that is, the file offset, into a block address on the disk. If the file is growing, it allocates a new block.
- The page cache: the data is usually written first to the page cache in memory, and
write()returns immediately. The page is marked “dirty”; the write to disk happens later. If the data must become durable at once, the program callsfsync(). - The device driver prepares an NVMe write command. The SSD controller fetches the data from memory by direct memory access (DMA), writes it to a flash page, and raises an interrupt when the job is done.
Six layers have worked for a seven-byte write. Only the first of them is the application's own code. The detail in the fifth step matters too: when write() returns, the data is most likely not yet on the disk. If the power fails at that moment, the most recent writes may be lost. That is why programs that need reliability, such as databases, use fsync() deliberately.
1.3.4The resource manager
Seen from below, the operating system's task looks different. Many programs want to run at the same time; all of them need the processor, memory, disk, and network. The operating system divides these resources among the programs and protects each program's share against the others.
As a resource manager, the operating system allocates and protects resources such as the CPU, memory, and I/O devices among multiple programs. Its goal is to use the resources efficiently and to share them fairly among programs.
Resources are shared in two ways. In time multiplexing, programs use the resource in turn: first one, then another. In space multiplexing, the resource is divided into parts and each program uses its own part at the same time.
Which resource is shared in which way depends on whether the resource can be divided. The processor executes only one instruction stream at a time; it cannot be divided and is shared in time. Memory can be divided: several programs reside in memory at once and each uses its own region. Disk space is divided too, with separate blocks given to each file; but because read and write requests to the disk are served one after another, the disk is also shared in time. A printer cannot be divided; there is no sense in giving half a page to one program and half to another.
The resource manager view raises the basic questions of operating system design. What happens if many programs want to print at the same time? How is the amount of resources each process uses measured? As resources multiply, for example as the number of cores grows, how are fairness and efficiency achieved? The following subsections take up these questions in turn.
1.3.5Printing at the same time: spooling
Imagine three people in an office sending documents to print almost at the same time. One sends a report from a word processor, one a photo from a PDF viewer, and one a note from a browser. There is only one printer. If all three programs could write to the printer directly, the pages would be mixed up line by line: under the first line of the report, a piece of the photo would be printed, and below that the first sentence of the note.
The operating system's solution is to give the printer to a single process alone.
Spooling means that jobs headed for a slow, unshareable device are first written to a queue on disk, and a single service process then sends these jobs to the device one at a time.
Figure 1.12 shows how it works. Programs write their jobs not to the printer but to the operating system's spool queue on disk, and return to their own work at once. The only process that uses the printer is the spooler service: CUPS on Linux, Print Spooler on Windows. This monopoly prevents the mix-up, because only one job goes to the printer at a time. The service usually sends jobs in first-come, first-served (FCFS) order. An administrator can give a job priority or pause a job.
The second gain of spooling is time. A printer is extremely slow compared with the processor; printing a page takes seconds. If programs had to wait for the printer to finish, the user would stare at a frozen window for minutes at every print. Thanks to spooling, while the slow printer works, programs and the processor do other things. I/O and computation advance at the same time; that is, they overlap. This idea comes up again and again in the history of operating systems.
1.3.6Code trace: the spool queue
The essence of spooling can be modeled with a little C code. The queue is an array of 4 slots; programs call enqueue() and the spooler service calls the spooler() function.
char *queue[4];
int in = 0, out = 0, count = 0;
void enqueue(char *file) { /* programs */
queue[in] = file;
in = (in + 1) % 4;
count++;
}
void spooler(void) {
while (count > 0) {
send_to_printer(queue[out]);
queue[out] = NULL; /* slot freed */
out = (out + 1) % 4;
count--;
}
}The code reads line by line as follows. The first line defines an array of 4 pointers that will hold the file names. The three counters in the second line keep the state of the queue: in is the index of the next free slot, out is the index of the oldest job to be printed, and count is the number of jobs in the queue. The enqueue() function writes the file name into slot in, advances in by one, and increments count. The % 4 operation used in advancing makes the queue circular: after slot 3 it returns to slot 0. As long as jobs remain in the queue, spooler() sends the oldest job to the printer, writes NULL into the slot it sent to free it, advances out in the same way, and decrements count.
Suppose four programs submit a.pdf, b.txt, c.doc, and d.png in turn and then the spooler runs. Table 1.2 gives the state of the variables and the queue after each call. In the queue column, “·” marks an empty slot.
| Step | Operation | in | out | count | Queue [0] [1] [2] [3] | Printed |
|---|---|---|---|---|---|---|
| 0 | start | 0 | 0 | 0 | · · · · | — |
| 1 | enqueue("a.pdf") | 1 | 0 | 1 | a.pdf · · · | — |
| 2 | enqueue("b.txt") | 2 | 0 | 2 | a.pdf b.txt · · | — |
| 3 | enqueue("c.doc") | 3 | 0 | 3 | a.pdf b.txt c.doc · | — |
| 4 | enqueue("d.png") | 0 | 0 | 4 | a.pdf b.txt c.doc d.png | — |
| 5 | send (round 1) | 0 | 1 | 3 | · b.txt c.doc d.png | a.pdf |
| 6 | send (round 2) | 0 | 2 | 2 | · · c.doc d.png | a.pdf, b.txt |
| 7 | send (round 3) | 0 | 3 | 1 | · · · d.png | a.pdf, b.txt, c.doc |
| 8 | send (round 4) | 0 | 0 | 0 | · · · · | a.pdf, b.txt, c.doc, d.png |
in and out point to slot 0. (b) After four enqueue calls the queue is full, count = 4; in has wrapped around. (c) a.pdf has gone to the printer, out = 1, count = 3. (d) Four jobs have been printed, the queue is empty again, and the printer is idle.Two rows of the table call for special attention. In the fourth step, in = (3 + 1) % 4 = 0: the index wraps around to the beginning of the array. At this moment in and out are equal, but the queue is full, not empty. Equality of the two indices alone cannot tell empty from full; that is exactly why the count counter is kept. In the eighth step out also wraps to 0, and because count = 0 the loop ends. The jobs have been printed in arrival order, that is, in FCFS order. Because only the service uses the printer, the outputs have not been mixed.
The line queue[out] = NULL;, which frees the slot, is not required for the queue to work correctly: the counters out and count already determine which slots are full. The line makes the trace readable and keeps the name of a printed job from lingering in the array. The empty slots shown as “·” from the fifth step of the table onward are the result of this line.
Cost. enqueue() makes three assignments; it finishes in constant time, that is, O(1), regardless of the number of jobs in the queue. If the queue holds n jobs, spooler() runs its loop n times: O(n). The queue itself takes a fixed space of 4 slots.
Using this code as it is in a real system. Two things are missing. First, enqueue() does not check whether the queue is full; if a fifth job arrives, it overwrites the oldest one. Second, the programs and the service are separate processes and may run at the same time. count++ and count-- are not a single instruction but a “read, modify, write” sequence; if the other side slips in between, one update is lost. This situation is called a race condition. Real spool queues are therefore protected by a lock.
1.3.7Measuring resource usage
To distribute resources fairly, one must first know who uses how much. The operating system keeps this information separately for each process. Table 1.3 summarizes the metrics for three basic resources and the tools that show them.
| Resource | Metric | Linux | Windows |
|---|---|---|---|
| CPU | CPU time spent in user and kernel mode, utilization percentage | /proc/[pid]/stat, top, time | Task Manager, Performance Monitor |
| Memory | Resident set, virtual size, working set; allocation and release pattern | /proc/[pid]/status, smem | “Working set” column |
| I/O | Bytes read and written, number of system calls and I/O requests | /proc/[pid]/io, iotop, strace -c | Resource Monitor |
Splitting CPU time into user mode and kernel mode is meaningful. A program that is computing spends its time in user mode. A program that reads many small files spends most of its time in the kernel, inside system calls. On Linux the time command prints these two values separately as user and sys.
For memory, the value most often examined is the resident set size (RSS): the total of the process's pages that are currently in physical memory. The virtual size is the whole address space the process has reserved and can be much larger than the RSS, because not every reserved page is actually brought into memory. On Linux these values are read from files in the /proc directory:
$ grep -E 'VmRSS|Threads' /proc/4211/status
VmRSS: 412360 kB
Threads: 57Here two lines are selected for process 4211 (the Firefox process of the earlier terminal example). VmRSS says that 412,360 kB of the process is in physical memory, and Threads says that the process contains 57 threads. /proc is not a directory that really exists on disk. The kernel generates the contents of these files from the current values on every read.
The source of these measurements is the kernel. On every context switch, every system call, and every page fault, the kernel updates the per-process counters it keeps. Tools such as Task Manager or top merely read and display these counters.
1.3.8Fairness and efficiency
The growth of resources, that is, more cores and more memory, improves performance and response time. But it also makes it harder to share resources fairly and efficiently. On a four-core machine, deciding which process runs on which core is far more complicated than the “who is next?” question of a single-core machine. Operating systems approach this problem with four tools.
- Scheduling: which process runs when, and on which core? The kernel component that makes this decision is called the scheduler. Linux used CFS (the Completely Fair Scheduler) for many years; with Linux 6.6 (2023) it was replaced by the EEVDF scheduler.
- Prioritization: some processes are given a larger share than others.
nicevalues on Linux, priority classes on Windows, and real-time classes on both systems serve this purpose. - Quotas and limits: an upper bound is placed on the resources a process or a group of processes may use. On Linux, cgroups v2 (the foundation of containers),
ulimit, and disk quotas serve this purpose; on Windows, Job objects do. - Trade-offs: throughput, response time, and fairness cannot all be optimized at once. While one improves, another may get worse.
The last item rests on three concepts. Throughput is the number of jobs completed per unit time. Response time is the time from a request being made to the system's first response. Fairness is whether each process gets the share it deserves. For example, switching often between processes shortens response time, because no process waits long. But every switch has a cost; as the number of switches grows, the time the processor spends on real work, and therefore throughput, falls.
The right balance depends on the workload. On a server the priority is throughput: the number of requests processed per hour should be as high as possible. On a desktop computer the priority is response time: a mouse click must get an immediate response. In a real-time system the priority is that jobs finish before their deadlines.
1.3.9Three big ideas: four small experiments
The book Operating Systems: Three Easy Pieces (OSTEP) by Arpaci-Dusseau and Arpaci-Dusseau organizes operating system topics around three big ideas: virtualization, concurrency, and persistence. Each idea can be made concrete with a small experiment run on Linux. Because virtualization is shown separately for the processor and for memory, there are four experiments.
Virtualization is the technique of making a single physical resource look to each program like a separate resource of its own. The operating system virtualizes the processor and memory.
Experiment 1: virtualizing the processor. A program called print prints the letter it is given to the screen in an endless loop. Three copies are started in the background on a single-core machine:
./print X & ./print Y & ./print Z & starts three processes numbered 3101, 3102, and 3103; the letters X, Y, and Z appear in the output in mixed order. Each program thinks “the CPU is mine”; in reality the single CPU is given to processes X, Y, and Z in turn. Each slice is a few milliseconds, and the OS decides who runs when.All three programs appear to do their work without interruption; in the output the three letters appear in mixed order. Yet the machine has a single core. The operating system gives the processor to the three processes in turn, in slices of a few milliseconds. Because the switches are too frequent for the human eye to notice, each behaves as if it had its own processor. Two separate questions arise here. Deciding who gets the next slice is a question of policy and is answered by the scheduling algorithm. How the switch is carried out is a question of mechanism and is answered by the context switch. The distinction between the two concepts is covered in 1.8.1.
Experiment 2: virtualizing memory. A program called counter allocates memory for an integer, prints the address of that memory, and then increments and prints the value in a loop. Two copies are run at the same time:
0x5555555592a0), but each one's value increases independently as 1, 2, … Both processes use the same virtual address; the OS maps these addresses to different physical frames (17 and 42).Both processes print the same address. If the memory were really shared, the two processes would increment the same integer and the values would advance together as 1, 2, 3, 4. Instead, in each process the value starts at 1 and increases independently. The explanation is that the address programs see is a virtual address. Each process sees its own address space, and the operating system, with the help of the hardware, maps the same virtual address to a different physical memory frame for each process. The experiment used the setarch -R command, which turns off address space layout randomization (ASLR). Had ASLR stayed on, the addresses would change on every run and the sameness would not be visible.
Experiment 3: concurrency. The incr program starts two threads. Each thread increments a shared counter variable N times. The expected result is 2N.
./incr 1000 gives the correct result (2000). ./incr 1000000, however, gives 1,318,442 in one run and 1,407,715 in another instead of 2,000,000. T1 and T2 increment the same counter; counter++ is really three instructions (read, increment, write), and if the other thread slips in between, one increment is lost.For N = 1000 the result looks correct, because the threads run so briefly that they hardly meet each other. When N reaches a million, the result is less than 2N and a different value comes out on every run. The reason is that the expression counter++ is not atomic: at the machine level it is three separate instructions, reading the value from memory into a register, incrementing it in the register, and writing it back. If two threads read the same old value, both increment it by one, and both write the same new value, one of the two increments is lost. Managing concurrent access to shared data correctly is one of the hardest topics in operating systems.
Concurrency is the progress of several jobs interleaved in time. Jobs can advance on a single processor by taking turns in slices; their running truly at the same time on several cores is called parallelism.
Experiment 4: persistence. The save program writes “hello disk” to the file note.txt. After the computer is restarted, the file can still be read:
./save is run, and cat note.txt prints “hello disk”; after the system boots again with sudo reboot, the same content is still read. The program only calls open, write, and close; the file system, the device driver, and the I/O request are inside the OS; the data is persistent on the SSD or disk.Main memory (DRAM) is volatile: its contents are erased when power is cut. If the data is to survive a restart, it is written to a persistent device through the file system. All the program does is call open, write, and close. Which block the data goes to, where metadata such as the file's name, size, and permissions is kept, and how to talk to the device are the operating system's job.
1.4History
Many ideas found in today's operating systems were born as solutions to a particular problem of a particular era. Spooling, multiprogramming, and time sharing are not fashions but ways of not wasting an expensive resource. Knowing the history makes it easier to understand why these ideas exist.
1.4.1Generations
Tanenbaum divides the development of computers and operating systems into generations according to the leaps in hardware technology.
Each generation begins with a new electronic technology: the vacuum tube, the transistor, the integrated circuit, the microprocessor. As the technology changes, the size, price, and reliability of the machines change. What does not change is the question asked anew in every generation: how can we make better use of the expensive resource? In the first generations that resource was the processor itself. As prices fell, the expensive resource became memory and finally human time.
1.4.2First and second generation
The first generation (1945–55) is the era of machines built with vacuum tubes. Machines such as ENIAC (1945) filled a room; they were slow and broke down often because tubes burned out frequently. The same small group of engineers designed, built, programmed, and maintained the machine. Programming was done in machine language or by changing connections on plugboards; in the early 1950s punched cards began to be used. There was neither a programming language nor an operating system. The machines were mostly used to compute numerical tables.
The second generation (1955–65) began with the transistor. The transistor replaced the tube; machines became smaller and more reliable and used less energy. The mainframes of this era sat in air-conditioned rooms and cost millions of dollars. An operator came between the programmer and the machine: the programmer handed the card deck to the operator, the operator ran the job and returned the result as printed paper.
This arrangement had a big loss. When a job finished, the million-dollar machine sat idle until the operator had the cards of the next job read in and the compiler loaded. The solution was batch processing.
A batch system is a system in which jobs are collected together in advance and a small control program, the monitor, runs these jobs one after another without human intervention.
The purpose of batch processing was to eliminate the manual transition time between jobs. Jobs were collected on a magnetic tape, and the monitor ran them automatically in sequence; the operator only carried tapes. But two limits remained. Because only one job was in memory at a time, the processor sat idle while the job did I/O. The programmer could also get the result only hours after submitting the job; there was no interaction. Batch processing was unsuitable for interactive and real-time use.
1.4.3An early batch system
A typical second-generation installation used two separate IBM machines together: an inexpensive IBM 1401 and an expensive IBM 7094.
- (a) Programmers bring their punched card decks to the 1401's card reader.
- (b) The inexpensive 1401 reads the cards of a group of jobs and writes them to the input tape. In this way the slow card reading is separated from the expensive machine.
- (c) The operator carries the filled input tape to the 7094.
- (d) Under the control of the monitor program on the system tape, the 7094 computes the jobs one after another and writes the outputs to the output tape.
- (e) The operator carries the output tape back to the 1401.
- (f) The 1401 prints the outputs on the printer. This was called offline printing.
The logic of this arrangement is clear: the expensive 7094 never bothers with reading cards or printing. Reading from tape is much faster than reading from cards, so the expensive machine's time is left for computation. Slow I/O jobs were handed over to the cheap machine. The same principle lives on, in a slightly different form, in today's spooling.
1.4.4IBM 1401, 7094, and System/360
The three machines of this period are each a separate step in the evolution of operating systems. Table 1.4 compares them.
| Machine | Year | Characteristics |
|---|---|---|
| IBM 1401 | 1959 | Commercial data processing; character-based and relatively cheap. It was also used for I/O jobs such as reading cards, copying to tape, and printing. It was one of the most widespread computers of the 1960s. |
| IBM 7094 | 1962 | Scientific computing; a 36-bit word and an architecture entirely different from the 1401. It ran batch jobs under IBSYS and FMS. Time sharing with CTSS was tried at MIT on a modified 7094. |
| System/360 | 1964 | A family of machines sharing the same architecture from small to large. Its operating system, OS/360, was a giant project of millions of lines, full of bugs, that included multiprogramming and spooling. |
Two details in the table are often confused. First, the 1401 and the 7094 did not run under OS/360; OS/360 was written for the System/360 family announced in 1964. Second, the 7094 was not a powerful version of the 1401; it was a separate machine with a completely different architecture that complemented it. The fact that the two machines could not run each other's programs pushed IBM to build, with System/360, a family based on a single architecture. This family idea meant that a program written on a small machine could run unchanged on a large one, and it is also the foundation of today's x86 and ARM families.
The development of OS/360 became one of the classic examples of software engineering. Fred Brooks, one of the project's managers, described his experience in the book The Mythical Man-Month. The best-known observation in the book is that adding people to a late software project makes it later still.
1.4.5A typical FMS job
FMS is a batch monitor written for the IBM 709 and 7094; its name is short for Fortran Monitor System. A job was a deck of cards wrapped in special cards that told the monitor what to do.
$JOB (maximum run time, account number, programmer name), $FORTRAN, the FORTRAN program, $LOAD, $RUN, the program data, and $END.Cards that begin with $ are called control cards. The monitor reads the deck in order and does one job at each control card. $JOB starts a new job and opens its account. $FORTRAN loads the compiler and has it compile the cards that follow. $LOAD loads the compiled program into memory. $RUN runs the program and supplies the following cards as its data. $END ends the job. These cards are the ancestors of today's shell scripts and of IBM's job control language, JCL. A shell script, too, is a list of commands that spells out the “compile, link, run” steps in order.
Confusing the abbreviation FMS with the Flexible Manufacturing System of factory automation. The FMS here is the FORTRAN Monitor System; there is no connection between the two concepts.
1.4.6Third generation: integrated circuits and multiprogramming
The third generation (1965–80) is the era of integrated circuits. Compatible families such as System/360 appeared; machines became smaller, cheaper, and more reliable. This generation gave operating systems three lasting ideas.
The first idea is multiprogramming.
Multiprogramming is the technique of dividing memory into partitions, keeping a separate job in each partition, and giving the processor immediately to another job in memory when one job waits for I/O.
In the second generation there was a single job in memory, and the processor waited while the job read from tape. In scientific computing this wait was small; but in commercial data processing jobs spent most of their time on I/O and most of the processor's time was wasted. In multiprogramming, as in Figure 1.21, several jobs sit in memory together. While one waits for I/O, the processor runs another.
On a single-processor machine the jobs do not really run at the same time; the processor executes only one at a given instant. The jobs advance interleaved in time. This is concurrency, not true parallelism. Having several jobs in memory also brings a new problem: a job must not write to another's memory, whether through a bug or on purpose. For this reason multiprogramming cannot be done safely without hardware that protects memory.
The second idea is spooling. Cards were no longer read through a separate machine and tape but directly onto disk. When one job finished, the next was loaded from disk into memory. The 1401-and-tape-carrying arrangement thus disappeared.
The third idea is time sharing.
Time sharing is rotating the processor among processes in short time slices so that many users can use the same machine interactively from their own terminals. When a process's slice runs out, the processor is taken from it by a timer interrupt even if it does no I/O.
The difference between multiprogramming and time sharing is subtle but important. In multiprogramming the processor is taken from a job only when that job starts waiting; a job that does no I/O at all can hold the processor for hours. In time sharing, a hardware timer raises an interrupt at regular intervals and each process's slice is limited. The goal is less throughput than a short response time for every user. The programmer no longer submits a job and waits for hours; they type a command and get a reply within seconds.
The family tree of time sharing extends to today's systems: CTSS (1961), developed at MIT; then the very ambitious MULTICS project; then UNIX (1969), written by Bell Labs researchers who had left MULTICS. The BSD releases at Berkeley were born from UNIX. The POSIX standard was written so that the different UNIX derivatives would be compatible with each other. Andrew Tanenbaum developed MINIX for teaching, and Linus Torvalds, inspired by MINIX, wrote the Linux kernel in 1991.
1.4.7Multiprogramming timeline
To see the gain of multiprogramming in numbers, let us run two jobs on a single-processor machine. Times are in time units:
- Job A: 2 units of CPU, 4 units of I/O, 2 units of CPU.
- Job B: 3 units of CPU, 3 units of I/O, 1 unit of CPU.
The total CPU need of the two jobs is 2 + 2 + 3 + 1 = 8 units. Each job's I/O is done on its own device, so A's I/O and B's I/O do not wait for each other.
Single-programmed system. There is only one job in memory; B starts only when A has completely finished.
- t = 0–2: A uses the CPU.
- t = 2–6: A does I/O. Because there is no other job in memory, the CPU stays idle for 4 units.
- t = 6–8: A uses its last CPU burst and finishes.
- t = 8–11: B uses the CPU.
- t = 11–14: B does I/O; the CPU is idle for 3 units.
- t = 14–15: B uses its last CPU burst and finishes.
The total time is 15 units, and the time the CPU was working is 8 units. CPU utilization is 8 / 15 ≈ 0.53, that is, about 53%. The 7 idle units are exactly the sum of the two jobs' I/O times (4 + 3).
Multiprogrammed system. Both jobs are in memory; when the CPU becomes free it is given to a job that is ready.
- t = 0–2: A uses the CPU; B waits, ready.
- t = 2: A goes to I/O (2–6). The CPU does not stay idle; it is given to B at once: B runs during t = 2–5. Meanwhile A's I/O continues in the background.
- t = 5: B goes to I/O (5–8). A's I/O has not finished yet; there is no ready job, and the CPU is idle only during t = 5–6.
- t = 6: A's I/O finishes; A uses its last CPU burst during t = 6–8 and finishes.
- t = 8: B's I/O finishes at exactly this moment; B uses its last burst during t = 8–9 and finishes.
The two jobs have finished in 9 units instead of 15. CPU utilization is 8 / 9 ≈ 0.89, that is, about 89%. The only idle unit is the interval t = 5–6, when both jobs are waiting for I/O at the same time.
The difference between the two examples has a single source: in multiprogramming, CPU and I/O overlap. In the single-programmed system the CPU waits idle during A's 4 units of I/O, while in the multiprogrammed system 3 units of that time are filled with B's computation. The jobs' total CPU need has not changed; the waits are merely covered by other jobs' computation. That is why the gain of multiprogramming grows as the jobs' share of I/O rises. For two jobs that do no I/O at all, the gain is zero.
Thinking that multiprogramming makes jobs “run faster”. Each job's own CPU time stays the same; A still uses 4 units of CPU and B still uses 4. What gets shorter is the total time for all the jobs to finish. In the example A finishes at t = 8 in both systems; the gain comes entirely from B finishing at 9 instead of 15. If A's I/O had lasted 2 units, it would have finished at t = 4. Because the CPU would be with B at that time, A would wait until t = 5 and finish at t = 7; running alone it would have finished at t = 6. Multiprogramming speeds up the total work, but it can delay the completion of an individual job.
1.4.8Fourth generation: personal computers
The fourth generation (1980–) began with very-large-scale integrated circuits that fit thousands of transistors onto a single chip, that is, microprocessors. For the first time the computer became small enough to fit on one person's desk and cheap enough for one person to buy. Table 1.5 lists the operating system milestones of this period.
| Year | Development |
|---|---|
| 1974 | CP/M, written by Gary Kildall for the Intel 8080: the first widespread disk-based OS for microcomputers. |
| 1981 | The IBM PC and MS-DOS, derived from 86-DOS; the BASIC interpreter in ROM. |
| 1973–84 | The GUI ideas developed at Xerox PARC turned into a user-friendly interface with the Apple Lisa (1983) and the Macintosh (1984). |
| 1985–2000 | Windows 1.0 … 3.x was a graphical environment running on top of MS-DOS; Windows 95/98/ME were still MS-DOS-based. |
| 1993– | Windows NT, written from scratch; then 2000, XP, 7, 10, and 11. The kernel of today's Windows is NT. |
| 1991– | Linus Torvalds's Linux kernel; in 2001, the UNIX-based Mac OS X (Darwin/XNU), the ancestor of today's macOS. |
In this period the goal of the operating system changed. In earlier generations the machine was expensive and human time was cheap; the operating system tried never to leave the machine idle even for a moment. When rapidly falling prices opened the computer to everyone, the balance reversed. Now what was valuable was the user's time, and the OS's goal shifted from “use the machine efficiently” to “make things easy for the user”. The rise of the GUI is a result of this shift.
The transition from MS-DOS to Windows NT is also instructive. MS-DOS was a single-tasking system with no memory protection; a bug in one program could crash the whole system. Windows 95/98/ME were built on this foundation and became known for their instability. Windows NT, on the other hand, was written from the start with protection, multitasking, and multiuser operation in mind. In 2001, with XP, home users moved to the NT kernel too.
1.4.9Fifth generation: mobile devices and today
The fifth generation (1990–) is the era of mobile devices. In the 1990s PDAs and Palm OS were common, and in the 2000s Symbian and BlackBerry OS. In 2007 iOS arrived with the iPhone, and in 2008 Android, built on the Linux kernel. Microsoft's Windows Phone entered the market in 2010, and its development was stopped in 2017. Today Android and iOS share the market. In mobile operating systems, the touch interface, battery management, and the permission model that determines which data applications can access stand out.
Alongside the mobile world, four trends shape today's operating systems:
- Virtualization and the cloud: hypervisors (KVM, Hyper-V, Xen) run many virtual machines on a single physical server. This is the foundation of cloud services.
- Containers: tools such as Docker and Kubernetes set up environments that share the same kernel but are isolated from each other. The isolation is provided by Linux namespaces and cgroups.
- Heterogeneous hardware: a chip holds a CPU, a GPU, and an NPU for artificial intelligence workloads together; large and small cores are used side by side in processors.
- Security: languages that provide memory safety at the language level are entering the kernel. Since Linux 6.1 the kernel has had Rust support.
1.5Hardware
Because the operating system manages the hardware, the hardware's characteristics directly shape OS design. The number of registers determines the cost of a context switch, the speed gap between memory levels shapes scheduling decisions, and the number of cores determines the scale of concurrency problems. This section summarizes the hardware features that matter from the operating system's point of view.
1.5.1Components of a personal computer
Figure 1.23 is a simplified model. The processor, memory, and I/O devices communicate over a bus. Each device has a controller: the display controller drives the monitor, and the disk controller drives the disk. The processor talks not to the device directly but to its controller.
The MMU (memory management unit) seen inside the processor is the hardware that translates the virtual addresses programs use into physical addresses. It is thanks to this unit that, in the second experiment of 1.3.9, the same virtual address of two processes could be mapped to different physical frames. The translation rules, that is, the page tables, are written by the operating system; the MMU performs the translation on every memory access.
In real systems, point-to-point links such as PCIe are used instead of a single shared line; each device connects to the processor with its own link. But the conceptual model stays the same: the processor, memory, and device controllers are connected to each other, and the operating system manages the devices by talking to the controllers.
1.5.2The processor and its registers
The processor is the computer's “brain”: it executes all instructions. Its operation rests on a simple loop.
The processor's basic mode of operation is the fetch–decode–execute cycle: the next instruction is fetched from memory, what to do is decoded, and the instruction is executed. Then the processor moves on to the next instruction.
Because memory is slow compared with the processor, variables and intermediate results are kept in small, very fast storage units inside the processor, the registers. The instruction that moves data from memory into a register is called load, and the one that moves it from a register to memory is called store. Besides the general-purpose registers, there are special registers that hold the state of the processor.
| Register | x86-64 | ARM64 |
|---|---|---|
| Program counter: address of the next instruction | RIP | PC |
| Stack pointer: top of the stack | RSP | SP |
| PSW: condition bits, mode, interrupt enable | RFLAGS | PSTATE |
| Number of general-purpose registers | 16 | 31 |
0x1008) points to the next instruction and the SP (0x7FF0) to the top of the stack. The PSW holds the mode, condition, and interrupt bits; R0 … R15 hold intermediate results.The program counter (PC) holds the address of the next instruction; it advances after each instruction and takes the new address on jump instructions. The stack pointer (SP) points to the top of the stack, where local variables and return addresses are kept during function calls. The program status word (PSW) holds the condition bits that record the result of the last comparison, the processor's mode (kernel or user), and whether interrupts are enabled. The mode bit in 1.2.2 is in this register as well.
Each processor family has its own instruction set. A program compiled for x86-64 does not run directly on an ARM processor; it must either be recompiled or pass through a translation layer. A processor's performance cannot be expressed by a single number: clock speed, number of cores, cache size, the number of pipeline stages through which instructions are processed, and memory bandwidth all play a part.
The real importance of registers for the operating system is the context switch.
A context switch is the processor's leaving one process and moving on to run another. When doing this, the operating system saves all the registers of the process being left to memory and restores the previously saved registers of the next process.
It is easy to see why saving is mandatory. The processor has a single set of registers. When the next process starts running, it overwrites all of these registers with its own values. If the interrupted process is later to continue where it left off, it must return to the same PC, the same SP, and the same intermediate values. If even a single register were saved incompletely, the process would continue computing with a wrong value when it returned, and the error would stay hidden so well that its cause could not be found.
1.5.3Multicore chips
Raising the clock speed hit the heat limit in the mid-2000s. As a result, manufacturers began to put several processors on the same chip instead of a single fast one. Today even phones have eight or more cores.
Three separate ideas coexist in multicore chips:
- Multicore: a chip holds several independent processors. The operating system sees each of them as a separate processor and schedules a separate process on each.
- Simultaneous multithreading (SMT; Intel's commercial name is Hyper-Threading): one core runs two hardware threads at the same time. The operating system sees two “logical CPUs”, but these two share the same core's execution units and caches.
- Hybrid cores: the same chip has performance (P) cores and efficiency (E) cores. ARM's big.LITTLE design and the processors Intel has made since 2021 are of this kind. The scheduler must know which kind of core to run which job on: a background update can proceed on an E core without draining the battery, while a game's main thread belongs on a P core.
A laptop processor has 6 performance cores with SMT and 8 efficiency cores without SMT. How many logical CPUs does the operating system see?
Solution. Because each P core runs two hardware threads, it gives 6 × 2 = 12 logical CPUs. The E cores count as one logical CPU each: 8. In total 12 + 8 = 20 logical CPUs are visible. These 20 CPUs are not equal in power. Two logical CPUs that share the same P core are not as fast as two separate cores; that is why the scheduler first tries to fill the idle physical cores.
For the operating system the consequences of multicore fall under three headings. Parallelism: jobs now really run at the same time, and the operating system must distribute them evenly across the cores. Synchronization: two processor cores may try to modify the same data structure of the OS kernel at the same time; the problem of the counter experiment in 1.3.9 now exists inside the OS itself. Cache coherence: because each core has its own cache, a value written by one core must invalidate the stale copy in the other core's cache. This last job is done by the hardware, but its cost affects operating system design.
1.5.4The memory hierarchy
The ideal memory would be very fast, very large, and very cheap at the same time. No such technology exists. Fast memory is expensive and made small; large and cheap memory is slow. Computers therefore use different technologies together in layers.
| Level | Access (approx.) | Capacity (typical) |
|---|---|---|
| Registers | < 1 ns | < 1 KB |
| L1 cache | ~1 ns | 32–64 KB |
| L2 / L3 | 3–20 ns | 1–100+ MB |
| DRAM | 60–100 ns | 8–64 GB |
| NVMe SSD | 20–100 µs | 0.5–4 TB |
| HDD | 5–10 ms | 2–24 TB |
A memory hierarchy is the arrangement of memory technologies of different speed, capacity, and cost in layers, so that each level works as a cache for the one below it.
Two boundaries in the table deserve special attention. The first is the volatility boundary: DRAM and the levels above it lose their contents when power goes, while SSDs and HDDs are persistent. This makes clear why persistence requires a file system. The second is the size of the gaps: between neighboring levels the speed changes sometimes by a factor of ten and sometimes by a factor of a thousand. Going from DRAM to SSD, access time rises from nanoseconds to microseconds, and to milliseconds for an HDD.
The reason the hierarchy works is locality. Within a short time, programs usually access the same data again and again, or data at nearby addresses. A loop uses the same variables on every iteration; an array is read in order from start to finish. So a small copy kept at the upper level satisfies most accesses, and the slow lower level is rarely visited. As a result the system behaves like a memory with almost the speed of the upper level and the capacity of the lower level.
How long does one clock cycle take on a core running at 2.5 GHz? To how many clock cycles does a 100 ns DRAM access correspond, and an 8 ms HDD access?
Solution. 2.5 GHz means 2.5 × 109 cycles per second. One cycle takes 1 / (2.5 × 109) s = 0.4 ns; in other words, 2.5 cycles pass in 1 ns. A DRAM access corresponds to 100 × 2.5 = 250 cycles. The HDD access is first converted to nanoseconds: 8 ms = 8 × 106 ns; from this, 8 × 106 × 2.5 = 2 × 107, that is, 20 million cycles.
These numbers explain the behavior of the operating system. The hardware caches hide the 250-cycle DRAM wait; it is not worth the operating system stepping in to switch processes, because the context switch itself takes longer than that. The 20-million-cycle disk wait, however, is huge. During this time the operating system keeps the process waiting and gives the processor to another process. This is the basic justification for multiprogramming.
Thinking of the SSD as “a fast kind of memory”. An NVMe SSD is about a hundred times faster than an HDD, but it is still about a thousand times slower than DRAM. For the operating system an SSD is also an I/O device: while a read is awaited, the process is kept waiting and the processor is given to other work.
1.6I/O methods
The processor's talking to devices is one of the things the operating system does most often. A key press, the arrival of a network packet, the reading of a disk block: all are I/O events. This section covers how the processor learns that an I/O job has finished.
1.6.1Controller and driver
Every I/O device has a device controller. The controller is a small processor or circuit on the device; it drives the device physically and presents the processor with an interface made of a few registers. Typically it has a command register (what to do), a status register (is the job done, is there an error), and a data register or buffer.
The device driver in the kernel is the software that knows how to talk to a particular controller. The driver writes commands into the controller's registers and reads its status. Because every controller is different, each type of device has its own driver; the rest of the operating system talks to drivers through a common interface. These are the drivers listed in Device Manager in 1.1.6.
1.6.2Polling, interrupts, and DMA
After the driver gives the controller a command, it must find out when the job is done. There are three ways to do this.
| Method | Key difference |
|---|---|
| Polling | The CPU reads the status register in a loop until the device is ready; it cannot do other work while waiting (busy waiting). |
| Interrupt | The device signals the CPU at the end of each unit of work; in between, the CPU runs another process. |
| DMA (direct memory access) | The controller moves the whole block to memory itself; the CPU is involved only at the start (programming) and at the end (a single interrupt). |
The logic of polling is simple: the processor reads the status register in a loop, reading it again until it sees the “ready” bit. This method is also called busy waiting, because while waiting the processor runs at full power but does no useful work. If the device responds very quickly, that is, if the wait is only a few cycles, polling is the cheapest way. If the wait is long, processor time is wasted.
With interrupts, after giving the controller the command, the processor goes back to running another process. When the device finishes a unit of work, for example a byte or a word, it sends the processor an interrupt signal. The processor completes the current instruction, switches to kernel mode, finds the relevant interrupt handler in a table called the interrupt vector, and runs it. The handler takes the data, gives the device the next job, and the interrupted process continues where it left off. In this way the processor does useful work during the waits. But because an interrupt arrives at the end of every unit of work, in large transfers the number of interrupts and their total cost become very high.
DMA (direct memory access) solves this last problem. The processor gives the controller only the information “starting at this address, write this many bytes to memory”. The controller moves the whole block to memory itself and raises a single interrupt when the transfer is over. The processor is involved only at the start, when programming the DMA, and at the end, when handling that single interrupt.
1.6.3Computing CPU load
A 4 KiB block is to be received from a device. In interrupt-driven I/O, one interrupt occurs for every 4 bytes, and each interrupt costs the CPU 2 µs. With DMA, the CPU programs the controller in 3 µs and a single interrupt (2 µs) arrives at the end of the transfer. How much time does the CPU spend on this transfer in the two methods?
- First the block is converted to bytes. KiB is a binary prefix: 4 KiB = 4 × 1024 = 4096 bytes.
- Interrupt-driven I/O: the number of interrupts is 4096 / 4 = 1024. The time the CPU spends is 1024 × 2 µs = 2048 µs ≈ 2.05 ms.
- DMA: 3 µs + 2 µs = 5 µs.
- Ratio: 2048 / 5 ≈ 410. DMA reduces the CPU load by a factor of about 410.
The transfer itself depends on the device's speed in both methods and takes about the same time. The difference lies in how the processor spends that time. With DMA, the processor runs other processes apart from those 5 µs. For slow devices such as a keyboard, which produce a few events per second, this difference is negligible; for fast block devices such as SSDs and network cards, working without DMA is unthinkable.
Thinking that DMA also provides security. DMA is a performance mechanism; it takes the copying load off the processor. On the contrary, a device that can write directly to memory can corrupt any part of memory if it is programmed wrongly or is malicious. A separate hardware unit called the IOMMU is needed to limit the memory regions that devices can access.
1.6.4Interrupt, trap, and exception
The word interrupt is used for two different events, so care is needed here. A hardware interrupt comes from a device outside the processor: the timer has expired, a packet has arrived at the network card, the user has pressed a key. These events are independent of the instruction stream being executed and can arrive at any moment; that is why they are asynchronous.
A trap or exception, on the other hand, arises from the executing instruction itself: division by zero, an invalid memory access, a page fault, or a deliberate system call. Because it is the result of a particular instruction, it is synchronous: if the same program is run with the same input, the trap occurs at the same point every time.
Although their sources differ, the two events reach the kernel in the same way. The processor enters kernel mode, saves the current state, and jumps to the relevant handler from a table (the interrupt vector or the exception table) according to the type of event. When the handler finishes, it either returns to just after the interrupted instruction or, if there is a fatal error, terminates the process. This common path is the same as the “three doors” of 1.2.2: system calls and exceptions come from within the instruction stream, interrupts from outside.
Which of the following events are interrupts and which are traps? (a) the disk completing a read, (b) a program reading through a NULL pointer, (c) a fork() call, (d) a mouse movement, (e) a page fault.
Solution. (a) and (d) come from outside devices and are independent of the instruction stream: interrupts. (b) is an invalid memory access and is the result of a particular instruction: a trap (exception). (c) is a system call the program makes deliberately: a trap. (e) arises because the page accessed is not in memory and is tied to the instruction that made the access: a trap (exception). When the program is rerun with the same input, (b) and (c) occur again at the same instructions; (e) also occurs at an instruction of the same kind, but only if the page is not in memory at that moment. The timing of (a) and (d), however, is different every time.
1.7Kinds of operating systems
The name “operating system” is used both for the software that runs a giant machine in a bank's data center and for the small program on a bank card's chip. What these systems have in common is that they take on the same two roles; what differs is which resource is scarce and what is considered most important.
1.7.1Systems from large to small
Figure 1.27 keeps its axis logarithmic because the memory sizes differ by a factor of a billion. The list below goes from the largest to the smallest.
- Mainframe: designed for very high I/O capacity, reliability, and uninterrupted availability. It provides batch processing, thousands of small transactions per second (for example a money transfer or an airline reservation), and time-sharing services. Banks and airlines depend on these systems. Examples: IBM z/OS, z/VM, Linux on Z, Unisys MCP, Fujitsu BS2000.
- Server: provides web, database, file, and email services to many users over the network. Data centers, the cloud, virtualization (KVM, Hyper-V), and containers belong to this world. Examples: Linux, Windows Server, FreeBSD.
- Multiprocessor: uses several cores or several processors in sockets and runs jobs in parallel. It deals with synchronization and with the NUMA layout, in which some regions of memory are closer to some processors. Today all general-purpose operating systems are in this class: Linux, Windows, macOS.
- Personal: offers a single user a good GUI and multitasking; used for browsing, office work, games, and file management. Examples: Windows 11, macOS, Linux distributions, ChromeOS.
- Handheld: the touch interface, battery and thermal management, sensors, the app store, and the permission model stand out. Examples: Android, iOS/iPadOS, HarmonyOS. Windows Phone ended in 2017.
- Embedded: runs inside cars, household appliances, network devices, and aircraft. The user generally does not install software; the system is fixed in flash memory. Examples: embedded Linux (Yocto), Zephyr, FreeRTOS, QNX, VxWorks.
- Sensor node: designed to run for years on a battery with a few tens of KB of RAM. It is event-driven: it sleeps most of the time and wakes when a measurement or a message arrives. It communicates over low-power radios (IEEE 802.15.4, BLE); it is used in IoT and machine-to-machine (M2M) networks. Examples: Contiki-NG, RIOT, Zephyr. TinyOS is now a historical example.
- Smart card: its processor and memory are extremely limited. It does authentication, payment, cryptography, and secure storage. Bank cards, SIMs and eSIMs, and ID cards are in this class. Examples: Java Card, MULTOS.
Between the two ends of the list the priorities reverse. In a mainframe or a server the scarce resource is the processing power and I/O capacity to serve the requests of thousands of users at the same time. In a sensor node the scarce resource is energy; the operating system's most important job is to keep the processor and the radio off for as long as possible.
1.7.2Real-time operating systems
In some systems it is not enough for a computation to be correct; it must also finish on time. A vehicle's brake control software must notice within a few milliseconds that a wheel has locked and adjust the brake pressure. A response that is correct but late is as dangerous as a wrong one.
A real-time operating system (RTOS) is an operating system that tries to guarantee that jobs finish before a particular deadline. What matters is not speed but predictability: even in the worst case, the response time must not exceed a known bound.
Real-time systems fall into two groups according to the consequence of missing a deadline:
- Hard real time: missing a deadline is a catastrophe. Brakes, airbags, flight control, and industrial robots are in this class. The brake task in Figure 1.28 arrives every 5 ms and finishes its 2 ms of work before its deadline every time.
- Soft real time: missing a deadline now and then is acceptable; only the quality drops. Audio and video streaming and games are in this class. For a video showing 60 frames per second, each frame must be ready within 1000 / 60 ≈ 16.7 ms. The second frame in the figure exceeded this time and was dropped; the viewer sees a brief stutter, but nobody is harmed.
Well-known RTOS examples include VxWorks, used in the Mars rovers, QNX, common in vehicle systems, and FreeRTOS and Zephyr for small microcontrollers. Linux could also run in real time with the PREEMPT_RT patches that were long kept separate. These patches were merged into the mainline kernel in 2024 with Linux 6.12; the old RTLinux project has ended. Real-time systems are used in applications that process audio, video, motion, and sensor data, in train control, and in defense systems.
Understanding “real time” as “very fast”. System A's average response time is 1 ms, but now and then it rises to 500 ms. System B's average is 5 ms and it never exceeds 8 ms. On average A is faster. Still, B is suitable for a hard real-time job, because its worst case is known and bounded.
1.8Key concepts
1.8.1Policy and mechanism
One of the most useful principles of operating system design is to separate two different questions: what will be done and how it will be done.
Policy is the decision about what will be done. Mechanism is the infrastructure that makes it possible to carry out that decision.
Separating the two provides the greatest flexibility: when policy decisions change later, the mechanism need not be rewritten. The timer interrupt and the context switch are the mechanism that makes it possible to rotate the processor among processes. Whether the time slice will be 4 ms or 10 ms is a policy. If the slice value is designed as a parameter plugged into the mechanism, as in Figure 1.29, the same kernel code can run with a short slice on a desktop and a long slice on a server. On Linux, a process's scheduling class can be changed with the sched_setscheduler() call and a disk's I/O scheduler by writing to a file under /sys, while the system is running; the kernel code does not change.
| Mechanism | Policy |
|---|---|
| Timer interrupt | How many ms should the time slice be? |
| Priority scheduler | Which process has high priority? |
| File permission bits (rwx) | Who is given which permission? |
| Page replacement infrastructure | Which page is to be evicted? |
| cgroups | How much CPU and memory for which container? |
In each row of the table, the column on the left is a “tool” and the column on the right is a “decision” about how to use that tool. The file permission bits form the mechanism that checks permission on every access; which user is given read and which write permission is the administrator's policy. An easy way to tell whether a distinction is a policy or a mechanism is to ask: “If this decision changes, does the code have to change?” If it does not, the decision is a policy. Operating system design takes creativity as much as engineering to strike these balances.
1.8.2MS-DOS and FreeBSD
How a program is started says a lot about the structure of an operating system. Single-tasking MS-DOS and FreeBSD, a multitasking UNIX derivative, make a good contrast in this respect.
MS-DOS is a single-tasking system and uses a single memory area. At boot the shell, that is, COMMAND.COM, is loaded into memory. When the user runs a program, the program is loaded by overwriting the transient part of the shell; only a small resident part of the shell stays in memory. When the program ends, the shell reloads itself from disk. Only one program runs at a time; there is no multitasking and no memory protection.
FreeBSD is multitasking. When a user logs in, a shell starts. When the user types a command, the shell first creates a new process that is a copy of itself with the fork() system call. This new process loads the requested program into its own memory with exec(). The shell either waits for the program to finish or, if & has been placed at the end of the command, runs the program in the background and goes on taking new commands. As in layout (c) of Figure 1.30, many processes are in memory at the same time, and each is protected in its own region.
1.8.3Building an executable file
A C source file becomes a running process through the successive work of several separate programs. The GCC compiler driver lets you have each of these steps done separately:
$ gcc -E code.c -o code.i
$ gcc -S code.i -o code.s
$ gcc -c code.s -o code.o
$ gcc code.o other.o -o prog
$ ./progcode.c goes through the preprocessor to become code.i, through the compiler to become code.s, and through the assembler to become code.o. The linker combines code.o with libc.so and other.o and produces the prog (ELF) file. The loader creates a process from this file.- Source file:
code.cis C code that a human reads and writes. - Preprocessor (
gcc -E): inserts the header files named in#includelines into the text, expands macros, and resolves conditional-compilation blocks with#ifdef. The result is still C code:code.i. - Compiler (
gcc -S): translates the C code into the assembly language of the target processor and optimizes it:code.s. - Assembler (
gcc -c): translates the assembly into machine code and produces an object file:code.o. In this file the addresses of external functions such asprintfare not yet known; there is only a note saying “printfis called here”. - Linker (
gcc code.o other.o -o prog): combines the object files and libraries, resolves the open addresses, and produces the executable file. On Linux the format of this file is ELF, on Windows it is PE (.exe). - Loading (
./prog): the shell doesforkandexec. The kernel's loader maps the ELF file into memory, the dynamic linker attaches shared libraries such aslibc.so, and the program starts running as a process.
In this chain the operating system's share is only in the last step. The first four steps are done by ordinary programs running in user mode: the preprocessor, the compiler, the assembler, and the linker. As noted in 1.2.4, it is the compiler that translates the program into machine language. The operating system turns the resulting file into a process: it allocates memory, maps the code and data into this memory, sets up the stack, and points the processor at the program's first instruction.
Thinking that a program and a process are the same thing. A program is a passive file sitting on disk (prog). A process is a running instance of that program: it has its own memory, registers, and open files. Three processes can be started at the same time from the same prog file; the print experiment in 1.3.9 does exactly this.
1.8.4Metric units
Operating system topics involve both very small times (nanoseconds) and very large sizes (terabytes). Table 1.10 gives the decimal prefixes and Table 1.11 the binary prefixes.
| Exponent | Name | Symbol | Exponent | Name | Symbol |
|---|---|---|---|---|---|
| 10−3 | milli | m | 103 | kilo | k |
| 10−6 | micro | µ | 106 | mega | M |
| 10−9 | nano | n | 109 | giga | G |
| 10−12 | pico | p | 1012 | tera | T |
| 10−15 | femto | f | 1015 | peta | P |
| 10−18 | atto | a | 1018 | exa | E |
| Unit | Value |
|---|---|
| 1 KiB (kibibyte) | 210 = 1024 B |
| 1 MiB (mebibyte) | 220 B |
| 1 GiB (gibibyte) | 230 B |
| 1 TiB (tebibyte) | 240 B |
Using the two families of prefixes together often causes confusion. Memory is usually measured in binary: “16 GB RAM” is really 16 GiB, that is, 16 × 230 = 17,179,869,184 bytes. Disk and network are measured in decimal: 1 TB = 1012 B and 1 Gb/s = 109 bit/s. A capital B is used for byte and a small b for bit; a 1 Gb/s link carries at most 109 / 8 = 125 million bytes per second.
How many GiB does an SSD labeled “512 GB” show up as in an operating system that displays sizes with binary prefixes? How many TiB is 1 TB?
Solution. The label is decimal: 512 GB = 512 × 109 B. One GiB is 230 = 1,073,741,824 bytes. The quotient is 512 × 109 / 230 ≈ 476.8 GiB. In the same way, 1 TB = 1012 / 240 ≈ 0.91 TiB. Nothing is missing from the disk; the same number of bytes has been shown in two different units. The difference grows as the unit grows: the 2.4% difference at the kilo level rises to about 9% at the tera level.
Figure 1.32 shows at a glance the scale of the times that appear in these notes. Between an L1 cache hit and a hard disk access there is a factor of about ten million. Human perception lies beyond all of them: in the time of a blink, the processor executes hundreds of millions of instructions. It is thanks to this difference in scale that an operating system can give a user the impression of running many programs “at the same time”.
1.9Summary
- The operating system is the layer of software that manages the hardware and offers applications a simple, safe, and common interface. In the narrow sense, the operating system is the kernel running in privileged mode; the shell and the GUI are ordinary user programs.
- Protection rests on the mode bit in the processor. In user mode privileged instructions are forbidden; the kernel is entered only through the doors of system call, interrupt, and exception, at predetermined entry points.
- In a
read()call, the libc wrapper puts the number and the arguments into registers,syscallraises a trap, the kernel findssys_read()in the table and checks the arguments, andsysretreturns to user mode. - Viewed from above, the operating system is an extended machine: it turns ugly hardware into abstractions such as the process, the address space, the file, and the socket. Viewed from below, it is a resource manager: it shares resources in time or in space and balances throughput and fairness.
- Spooling gives a slow, unshareable device to a single service process and overlaps I/O with computation. In a circular queue, the equality of
inandoutdoes not tell empty from full; that is why thecountcounter is kept. - Batch processing removed the manual transition between jobs. Multiprogramming raised CPU utilization by giving the CPU to another job while one waited for I/O; in the example two jobs finished in 9 units instead of 15 and utilization rose from 53% to 89%. Time sharing gave every user a short response time through the timer interrupt.
- In a context switch all registers are saved, because the processor has a single set of registers. Multicore chips bring problems of parallelism, synchronization, and cache coherence; SMT makes each core look like two logical CPUs.
- Thanks to locality, the memory hierarchy works with almost the speed of the upper level and the capacity of the lower level. Because a disk wait lasts millions of clock cycles, the operating system runs another process during that time.
- In polling the CPU busy-waits; with interrupts one interrupt arrives for every unit of work; with DMA the controller moves the whole block and raises a single interrupt. An interrupt arises from outside and asynchronously, a trap from the instruction itself and synchronously; both reach the kernel by the same path.
- Operating systems are very diverse, from mainframes to smart cards. In real-time systems what matters is not speed but predictability; in a hard system, missing a deadline is a catastrophe, and in a soft system it lowers quality.
- Policy decides what will be done and mechanism how it will be done; if the two are separated, policy can be changed without changing the kernel code.
- The preprocessor, compiler, assembler, and linker turn C source into an executable file; the operating system loads this file and turns it into a process. Memory is measured in binary (GiB), disk and network in decimal (GB, Gb/s).
1.10Key terms
- operating system (OS)
- kernel
- shell
- graphical user interface
- system call
- kernel mode
- user mode
- dual-mode operation
- trap
- exception
- interrupt
- interrupt handler
- abstraction
- address space
- virtualization
- virtual address
- concurrency
- parallelism
- race condition
- spooling
- batch system
- multiprogramming
- time sharing
- scheduler
- throughput
- response time
- register
- program counter (PC)
- fetch–decode–execute cycle
- context switch
- multicore
- simultaneous multithreading
- cache coherence
- memory hierarchy
- locality
- memory management unit
- bus
- device controller
- device driver
- polling
- busy waiting
- direct memory access
- real-time operating system (RTOS)
- policy / mechanism
- executable file
- hypervisor
- container
1.11Test Yourself
Which of the following events cause the processor to move from user mode to kernel mode? (a) a
getpid()call, (b)i++, (c) a page fault, (d) a packet arriving at the network card, (e)memcpyin user memory.Answer
(a), (c), and (d) do.
getpid()is a system call; the libc wrapper raises a trap withsyscall. A page fault is an exception arising from the instruction that accessed memory. The arrival of a packet is a hardware interrupt from the network card.i++is an ordinary operation on registers and memory, andmemcpyis a library function that copies within user memory; both stay in user mode.In a single-CPU system, job A uses 1 unit of CPU, 3 units of I/O, and 1 unit of CPU; job B uses 2 units of CPU, 1 unit of I/O, and 2 units of CPU. When do the two jobs finish in a single-programmed and in a multiprogrammed system, and what is the CPU utilization? (In multiprogramming, when the CPU becomes free, A is chosen first among the ready jobs.)
Answer
Single-programmed: A 0–1, idle 1–4, A 4–5; B 5–7, idle 7–8, B 8–10. Finish t = 10, CPU utilization 6 / 10 = 60%. Multiprogrammed: A 0–1; when A goes to I/O, B runs 1–3; B goes to I/O (3–4), and since A's I/O also ends at 4, the CPU is idle during 3–4; at t = 4 both jobs are ready, A runs 4–5, B 5–7. Finish t = 7, CPU utilization 6 / 7 ≈ 85.7%.
In the spooling code, if a program calls
enqueue("e.jpg")while the queue is full (a.pdf, b.txt, c.doc, d.png), what happens? Ifspooler()then runs, which files are printed, and in what order?Answer
enqueue()does not check for fullness. Becausein = 0, e.jpg is written into slot 0, over a.pdf; thenin = 1andcount = 5. The service runs its loop 5 times:outtakes the values 0, 1, 2, 3, 0. In order, e.jpg, b.txt, c.doc, and d.png are printed; after each is sent, its slot is set toNULL. In the fifth roundoutis 0 again and this slot is now empty:NULLis sent to the printer. a.pdf is lost, and the counter has counted a job that does not exist. A correctenqueue()should reject the job or wait whencount == 4.On a core running at 4 GHz, how many clock cycles does a 60 ns DRAM access and a 50 µs NVMe read take? Why does the operating system behave differently for these two waits?
Answer
One cycle is 0.25 ns; 4 cycles pass in 1 ns. DRAM: 60 × 4 = 240 cycles. NVMe: 50 µs = 50,000 ns, 50,000 × 4 = 200,000 cycles. The DRAM wait is shorter than a context switch and is hidden by the caches; the operating system does not step in. For the 200,000-cycle SSD wait, however, the process is kept waiting and the CPU is given to another process.
16 KiB of data is received from a device. In interrupt-driven I/O, one interrupt occurs for every 16 bytes and each interrupt costs the CPU 2 µs. With DMA, programming takes 5 µs and the single interrupt at the end takes 2 µs. How much time does the CPU spend in the two methods?
Answer
16 KiB = 16 × 1024 = 16,384 bytes. The number of interrupts is 16,384 / 16 = 1024; the CPU time is 1024 × 2 = 2048 µs. DMA: 5 + 2 = 7 µs. The ratio is about 2048 / 7 ≈ 293.
A processor has 4 cores with SMT and 4 cores without SMT. How many logical CPUs does the operating system see? Are all of these CPUs equally powerful?
Answer
4 × 2 + 4 = 12 logical CPUs are visible. They are not equally powerful: two logical CPUs that share the same core share that core's execution units and cache, so they do not run as fast as two separate cores.
About how many GiB does a USB drive labeled “256 GB” show up as in an operating system that uses binary prefixes?
Answer
256 × 109 / 230 ≈ 238.4 GiB. The label is decimal and the operating system's display is binary; the number of bytes is the same.
Which of the following are mechanisms and which are policies? (a) The context switch code, (b) giving interactive processes a shorter time slice, (c) the hardware checking the valid bit in a page table entry, (d) evicting the least recently used page when memory is full.
Answer
(a) and (c) are mechanisms: they make it possible to carry out a job. (b) and (d) are policies: they are decisions answering the questions “how large a slice for whom?” and “which page is evicted?”. The same mechanisms can be used with other policies as well.
A pacemaker, a music streaming application, and a web server: which is hard real time, which is soft real time, and which is general purpose?
Answer
The pacemaker is hard real time: failing to deliver the pulse on time has vital consequences. Music streaming is soft real time: an occasional delay causes a brief interruption but is not dangerous. The web server is general purpose; it emphasizes average performance and fairness and has no hard deadline.
What hardware feature separates time sharing from multiprogramming? How does a job that does no I/O at all behave in the two systems?
Answer
The timer interrupt. In multiprogramming the CPU is taken from a job only when the job starts waiting; a job that does no I/O holds the CPU until it finishes. In time sharing the timer raises an interrupt at the end of each slice, and the kernel takes the CPU from this job and gives it to the next one; in this way the other users' response time stays short.
1.12Further reading
- A. S. Tanenbaum and H. Bos, Modern Operating Systems (5th ed., 2023), Chapter 1: presents the two roles of the operating system, the generations, the IBM 1401/7094 batch arrangement, and the kinds of OS in the same order as these notes, with plenty of historical detail.
- R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, Chapter 2: gives the C code of the virtualization, concurrency, and persistence experiments; the book can be read online for free.
- A. Silberschatz, P. B. Galvin, and G. Gagne, Operating System Concepts (10th ed., 2018), Chapter 1: covers interrupts, the memory hierarchy, DMA, and dual-mode operation in detail from the hardware side.
- F. P. Brooks, The Mythical Man-Month (1975; 20th anniversary edition, 1995): a classic book of essays on the software engineering lessons drawn from the OS/360 project.
1.13References
- R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, version 1.10, pages.cs.wisc.edu/~remzi/OSTEP.
- F. P. Brooks, The Mythical Man-Month: Essays on Software Engineering, 20th anniversary edition, Addison-Wesley, 1995.
- Linux manual pages: syscall(2), fork(2), execve(2), proc(5).
- A. Silberschatz, P. B. Galvin, and G. Gagne, Operating System Concepts, 10th ed., Wiley, 2018.
- A. S. Tanenbaum and H. Bos, Modern Operating Systems, 4th ed., Pearson, 2014; 5th ed., 2023.
Related pages: Chapter 1 slides · © Sercan Külcü. All rights reserved.