Operating Systems · Lecture Notes

Chapter 11: Input/Output

A computer manages a wildly varied set of devices at the same time. A keyboard sends a few bytes per second, while an NVMe disk serves millions of requests per second. Their speeds differ by nine orders of magnitude, and their interfaces have little in common. The I/O part of the operating system tames this variety in two ways. On the hardware side, it issues commands to devices, reads their status, catches interrupts, and moves data without tying up the CPU. On the software side, it presents every device to applications through one uniform interface. The chapter starts with controllers, device registers, and the two addressing schemes. It then compares polling, interrupt-driven I/O, and DMA on one running printer example. The layers of I/O software, buffering, asynchronous interfaces, and clocks follow. The last sections cover the access time of a hard disk, disk-arm scheduling algorithms, SSDs, RAID arrays, and stable storage. Every numerical example (head movements, access times, buffer traces, XOR parity) was checked by actually running the algorithms.

Learning outcomes

Hardware
Recognize device controllers, device registers, and buses such as PCIe, USB, and NVMe; explain port-mapped and memory-mapped I/O.
Transfer methods
Compare polling, interrupt-driven I/O, and DMA in terms of CPU cost; state the roles of MSI-X and the IOMMU.
Software layers
Follow a read() call through the interrupt handler, the device driver, the device-independent layer, and the user library; trace the circular buffer and the timer list in code.
Interfaces
Distinguish blocking, nonblocking, and asynchronous I/O; compare the models of epoll and io_uring.
Disks
Compute access time; find the head path and total head movement for FCFS, SSTF, SCAN, C-SCAN, LOOK, and C-LOOK.
SSD and RAID
Explain the FTL, wear leveling, TRIM, and blk-mq; work out RAID 0/1/5/6/10 layouts, XOR parity, the small write, and recovery.

11.1Overview of the I/O system

11.1.1What the operating system does with devices

When a program reads a file, prints text on the screen, or receives a packet from the network, it ultimately has to talk to a device. The program does not do that talking itself. The operating system issues commands to devices, reads their status, catches the interrupts that announce completion, and handles errors. To the application it offers a layered, device-independent, uniform interface. The same read() call can read from an SSD, a USB stick, or a serial port.

One number conveys the scale of the job. Roughly 60–70% of the Linux source code lives in the drivers/ directory. The largest part of the kernel is neither process management nor memory management but the drivers for thousands of different devices. Every new network card, graphics card, or sensor adds another driver to the kernel.

Processor (SoC)cores · memory controllerPCIe root complex · APICDRAM (DDR5)main memorymemory busGPUPCIe 5.0 x16NVMe SSDPCIe 4.0/5.0 x4USB4 / Thunderbolt40–80 Gb/sChipset (PCH)I/O controllersDMI ≈ PCIe x4/x8SATAHDD / opticalUSB 3.xkeyboard, mouseEthernetNICWi-Fi / BTM.2 cardAudioHD Audiocontroller + device
Figure 11.1: The I/O layout of a modern computer. The memory controller and the PCIe root complex are inside the processor. Fast devices (GPU, NVMe SSD) attach directly to the processor over PCIe. Slow devices come in through controllers in the chipset (PCH).

Figure 11.1 shows the I/O layout of a present-day desktop computer. Every device consists of two parts: a controller and the actual device it drives. The operating system talks only to the controller. Controllers, in turn, connect to the processor over various buses.

11.1.2Buses: PCIe, USB4, SATA

Definition 11.1

A bus is a connection that carries data, address, and control signals between components. Older PCs had parallel buses (ISA, PCI) shared by many devices. Today point-to-point serial links are used: PCIe, USB, SATA.

On a shared parallel bus only one device can talk at a time. As the bus gets wider, timing skew between the wires becomes a problem too. Serial links solve both problems at once. Each link joins exactly two endpoints, and data flows at a very high frequency over a single pair of wires. In PCIe a lane is full duplex; a link combines x1, x4, x8, or x16 lanes. Bandwidth is available separately in each direction: an x4 link can use the same speed whether an NVMe disk is reading or writing.

Table 11.1: The main links in use today and their speeds.
LinkRaw rateEffective data rateNote
PCIe 4.016 GT/s per lane≈ 1.97 GB/s per lane; x4 ≈ 7.9 GB/s128b/130b encoding; NVMe SSDs
PCIe 5.032 GT/s per lane≈ 3.94 GB/s per lane; x16 ≈ 63 GB/sGPUs, SSDs in the 14 GB/s class
PCIe 6.064 GT/s (PAM4)≈ 7.6 GB/s per lane; x16 ≈ 121 GB/sFLIT + FEC; spreading in servers
USB 2.0 / 3.2480 Mb/s / 5–20 Gb/s≤ 60 MB/s / ≤ 2.5 GB/sHost-polled protocol
USB4 v1 / v240 / 80 Gb/sTunnels PCIe and DisplayPortCompatible with Thunderbolt 4/5
SATA III6 Gb/s≈ 600 MB/s (8b/10b)AHCI: one queue, 32 commands
Ethernet1 / 10 / 100 / 400 Gb/s125 MB/s … 50 GB/sData center: 400–800 GbE
Example 11.1

One lane of PCIe 4.0 runs at 16 GT/s (16 billion transfers per second) and uses 128b/130b encoding. What are the effective data rates of one lane and of an x4 link?

  1. Encoding overhead. Of every 130 bits, 128 are data; the remaining 2 bits are a synchronization header. The effective bit rate is 16 × 128 / 130 ≈ 15.75 Gb/s.
  2. Converting to bytes. 15.75 / 8 ≈ 1.97 GB/s. This is the rate of one lane in one direction.
  3. An x4 link. 4 × 1.97 ≈ 7.9 GB/s. This is why PCIe 4.0 NVMe disks on the market top out around 7 GB/s: once protocol overhead is added, the limit is close to this figure.

The same calculation for PCIe 5.0 gives 32 × 128 / 130 / 8 ≈ 3.94 GB/s, which is 63 GB/s on an x16 link. PCIe 6.0 changes the encoding entirely: PAM4 signaling carries two bits per symbol, and data travels in 256-byte FLIT packets that include forward error correction (FEC). 242 bytes of each FLIT are useful payload. This gives 64 × 242 / 256 / 8 ≈ 7.6 GB/s.

Some rows of the table are historical as well. FireWire, the 56K modem, and 10/100 Mb/s Ethernet are now just textbook examples. The Pentium-era “northbridge” has disappeared too. The memory controller moved into the processor (AMD in 2003, Intel in 2008). Today fast devices connect directly to the processor over PCIe, and slow devices to the chipset.

11.1.3Device data rates

The first property that separates devices is their speed. Figure 11.2 shows typical upper limits on a logarithmic axis. Each line on the axis is 1000 times the one before it.

1 B/s1 KB/s1 MB/s1 GB/s100 GB/sKeyboard10 B/sMouse (1 kHz gaming mouse)8 KB/sGigabit Ethernet125 MB/sHDD (7200 rpm, sequential)250 MB/sSATA SSD550 MB/sUSB 3.2 Gen 21.25 GB/sUSB4 (40 Gb/s)5 GB/sNVMe PCIe 4.0 x47 GB/sNVMe PCIe 5.0 x414 GB/s400 GbE50 GB/sDDR5-6400 (one channel)51.2 GB/sPCIe 5.0 x1663 GB/slog axis: each line ×1000
Figure 11.2: Device data rates on a logarithmic axis: the keyboard about 10 B/s, Gigabit Ethernet 125 MB/s, a PCIe 4.0 x4 NVMe disk 7 GB/s, a PCIe 5.0 x16 link 63 GB/s.

Between a keyboard and PCIe 5.0 x16 there is a factor of 63 × 109 / 10 ≈ 6 × 109. The same operating system has to handle both a few keystrokes per second and millions of NVMe requests per second. That is why no single transfer method suits every device. For a slow device, it does no harm for the CPU to attend to every byte individually. For a fast device, the CPU must stay out of the data path altogether. The values in the figure are typical upper limits. Real speed depends on signal quality, protocol overhead, and the device itself.

11.1.4Device classes: block, character, network

After speed, the second distinction is how the data is addressed. The Unix tradition divides devices into three classes.

Definition 11.2

A block device stores data in fixed-size, numbered blocks; each block can be read and written independently of the others. A character device produces or consumes a stream of bytes; the stream is not addressable and there is no seek operation. A network device works with packets and is used through the socket interface.

Table 11.2: Device classes.
ClassExamplePropertyTypical interface
BlockHDD, SSD, USB stick, SD cardFixed-size, addressable blocks (512 B / 4 KiB); each block is read and written independentlyread, write, lseek; file system, mmap
CharacterKeyboard, mouse, serial port, printer, audioByte stream; not addressable, no positionread/write, ioctl; /dev/ttyS0
NetworkEthernet, Wi-FiPacket-based; neither block nor characterSocket API (send, recv); no file in /dev
OtherClocks, timers, GPUNeither stream nor block: generates interrupts or is memory-mappedtimerfd, DRM/KMS, mmap

On Linux, block and character devices appear as special files under /dev. The first letter of the ls -l output tells the class:

$ ls -l /dev/nvme0n1 /dev/ttyS0
brw-rw---- 1 root disk    259, 0  nvme0n1   b = block, major/minor 259,0
crw-rw---- 1 root dialout   4, 64 ttyS0     c = character

b marks a block device and c a character device. The two numbers where the file size would be are the major and minor numbers. The major number (259) tells the kernel which driver to call, and the minor number (0) says which unit of that driver is meant. File systems can be built only on block devices, because it must be possible to reach any block of a file by its number.

Common mistake

Counting a network interface as a character device. In Unix and Linux, networking is a separate class; there is no file in /dev for eth0 or wlan0, and these interfaces are reached through sockets, not open(). The classification does not fit every device perfectly either. A tape drive writes blocks, but seeking is very slow. A clock produces neither a byte stream nor blocks; it only generates interrupts.

11.2I/O hardware

11.2.1Device controllers

Definition 11.3

An I/O unit has two parts: the mechanical or actual device part, and the electronic device controller that drives it. The controller is a chip or a card and attaches to the device through a connector. The operating system talks to the controller, not to the device.

Mechanical partplatter, head, motorController (electronic part)Registersstatus, commandBuffersector / trackECC + DMAerror correctionSystem busPCIe / SATA / USBconnectorserial bit stream:preambledata: 512 B = 4096 bits (or 4 KiB)ECC
Figure 11.3: A disk controller sits between the mechanical part and the system bus. Inside are registers, a sector buffer, and an error-correction unit. The serial bit stream from the disk consists of a preamble, data, and an ECC field.

The controller's job is to turn the device's raw signals into units the operating system understands. Consider the disk controller in Figure 11.3. A stream of bits passes under the read head. The stream starts with a preamble. The preamble carries a pattern that synchronizes the controller's clock to the stream, together with the cylinder and sector numbers. Then come 512 bytes (4096 bits) or 4 KiB of data, and last the error-correcting code (ECC). The controller assembles the bit stream into a block, corrects errors with the ECC, and places the block in its own buffer. Only then is the block transferred to memory.

A standard controller interface is a great convenience for the operating system. Thanks to the SATA or NVMe interface, a single driver can run disks from many manufacturers. The operating system scans the buses at boot and whenever a device is hot-plugged. It reads the PCIe configuration space and the USB descriptors, learns the device's identity, and loads the appropriate driver. This arrangement is called plug and play.

Sector sizes have changed too. Modern disks use 4 KiB physical sectors (Advanced Format). Disks that present 512 B sectors to the outside for compatibility with old software are called 512e. When an unaligned 512-byte write arrives at such a disk, the controller first reads the entire 4 KiB sector, patches in the changed part, and writes the sector back.

11.2.2Device registers: status, command, data

The controller talks to the operating system through its registers. A controller usually has four registers.

StatusBUSYRDYERRDRQ––––CPU readsCommandWRITECMDRDYREADIRQEN––––CPU writesData-out01000001CPU → deviceData-in????????device → CPUbit 7bit 0
Figure 11.4: The four registers of an example controller. The status register holds the busy (BUSY), ready (RDY), and error (ERR) bits; the command register holds the write (WRITE) and command-ready (CMDRDY) bits. The value 0100 0001 in the data-out register is the code of the character 'A' (0x41).
  • Status register: the CPU reads it. It reports whether the device is busy, whether the result is ready, and whether an error has occurred.
  • Command register: the CPU writes it. It tells the controller what to do: read or write, and in which mode.
  • Data-out register: data going from the CPU to the device is placed here.
  • Data-in register: data coming from the device waits here for the CPU to read it.

The rule is simple: writing a register issues a command, and reading a register learns the status. Some controllers have large data buffers in addition to registers. The frame buffer of a graphics card and the transmit and receive rings of a network card (NIC) are examples. The layout of the registers is device-specific, and only the driver knows this detail. The bit names in Figure 11.4 are illustrative too; the register layout of a real SATA or NVMe controller is different.

11.2.3Port-mapped and memory-mapped I/O

The question of how the CPU reaches a device register has two classic answers.

Definition 11.4

Port-mapped I/O places device registers in an address space separate from memory, the I/O ports. The CPU reaches these ports with the special IN/OUT instructions. Memory-mapped I/O (MMIO), on the other hand, puts the registers at ordinary memory addresses. Access uses normal load and store instructions; the address decoder routes the access to the device concerned.

(a) Separate spaces(b) Memory-mapped(c) HybridMemoryI/Oports0 … 2ⁿ−10 … 0xFFFFdevice registersMemory← address rangeone address spacebuffersMemorycontrolportse.g. VGA on an old PC
Figure 11.5: Three approaches: (a) separate address spaces for memory and I/O ports, (b) the memory-mapped layout, in which a range of a single address space is reserved for device registers, (c) the hybrid layout, in which control registers sit in ports and data buffers sit in memory.

The x86 family carries both methods. Many devices inherited from the IBM PC still sit at fixed port numbers (Table 11.3). The classic example of the hybrid layout in Figure 11.5 is the VGA card of the old PC: its control registers were in ports, while the screen memory was at memory addresses.

Table 11.3: Some fixed I/O ports on x86.
Port (x86)Device
0x20–0x218259 interrupt controller
0x40–0x438254 timer (PIT)
0x60, 0x648042 keyboard controller
0x3F8–0x3FFCOM1 serial port
0xCF8–0xCFFPCI configuration

The two access styles look like this in machine code:

in  al, 0x60          ; port: special instruction
mov eax, [rbx+0x14]   ; MMIO: ordinary load

Linux: inb()/outb()  ·  ioremap() + readl()/writel()
/proc/ioports  ·  /proc/iomem

The first line reads a byte from port 0x60, that is, from the data register of the keyboard controller. This needs a separate instruction (in). The second line is an ordinary memory load. If rbx points to the address where a device is mapped, this instruction reads the register at offset 0x14 of that device; from the CPU's point of view it is no different from reading memory. In the Linux kernel, ports are reached with inb()/outb(), while memory-mapped registers are first mapped with ioremap() and then accessed with readl()/writel(). Which ports and which physical address ranges belong to which device can be seen in the files /proc/ioports and /proc/iomem.

Today the weight is clearly on memory-mapped I/O. ARM and RISC-V processors have no port instructions at all; they use only MMIO. Even on x86, PCIe devices expose their registers memory-mapped through address windows called BARs (base address registers).

11.2.4Memory-mapped I/O: pros and cons

Memory-mapped I/O became widespread for three reasons. First, no special instructions are needed. A driver can be written entirely in C; a register is read and written through a volatile pointer. Second, protection comes with the page table. If the page holding the registers is not mapped into user space, no user program can touch the device. If desired, this page can be given to a single process; user-space drivers such as VFIO and DPDK work this way. Third, every instruction that accesses memory also works on a register: instructions such as TEST or AND can operate directly on the register.

The method has costs as well.

  • Caching. If the status register is cached, the CPU's later reads look at an old copy in the cache rather than at the register itself. Even when the device is ready, the program cannot see it. For this reason register pages are marked uncacheable (PAT/MTRR on x86; ioremap does this on Linux).
  • Multiple buses. If memory sits on a separate, fast bus, I/O devices cannot see the addresses on that bus (Figure 11.6). A bridge or the root complex decides which address range goes to memory and which to devices.
  • Compiler and processor ordering. The compiler may hoist a read that seems to have an unchanging value out of a loop, or swap two writes. The register pointer must be volatile, and memory barriers must be placed where order matters.
(a) single busCPUMemoryI/Oall addresses on one bus(b) dual busCPUMemoryI/Ofast memory busI/O bus
Figure 11.6: (a) On a single bus the CPU, memory, and I/O devices all see every address. (b) With dual buses, memory is on a separate, fast bus; I/O devices cannot see memory addresses, and routing is done by address ranges.
Common mistake

Not declaring the pointer volatile in a driver that waits for the status register with while ((*status & READY) == 0) ;. The compiler assumes the value of *status does not change inside the loop, performs the read once, and the loop never ends. The same symptom appears when the register page is mapped cacheable. Both safeguards are needed together: a volatile pointer and an uncacheable mapping.

11.3Programmed I/O

11.3.1Polling and the handshake

Let us examine in its plainest form how the CPU and a controller hand over a byte. The two sides agree through a few bits in the status and command registers. This agreement is called a handshake.

Definition 11.5

Polling means the CPU repeatedly reads the device's status register until the device is ready. Because the CPU does nothing else while it waits, it is also called busy waiting. The method in which the CPU itself carries every byte of data is called programmed I/O (PIO).

while (status & BUSY)
    ;          /* busy-wait */
command = WRITE;
data_out = 'A';
command |= CMDRDY;
/* --- controller side --- */
/* sees CMDRDY → BUSY = 1 */
/* read command, send byte */
/* CMDRDY = ERR = BUSY = 0 */

The driver executes the upper half of the code; the controller carries out the steps described by the comments in the lower half. Writing one byte, the character 'A' (0x41), takes eight steps:

  1. Waiting. The driver reads the status register. The controller has not finished the previous job, so BUSY = 1 and the while loop keeps spinning. The CPU can do nothing else in the meantime.
  2. Exit. When BUSY becomes 0, the loop exits. This wait can last anywhere from a few cycles to milliseconds, depending on the device.
  3. Command. The WRITE bit is written to the command register: the job to do is a write.
  4. Data. The byte to send (0x41) is placed in the data-out register.
  5. Command ready. CMDRDY = 1 is set. This bit tells the controller that the job can begin. Order matters: CMDRDY must be set only after the command and data are in place.
  6. Controller busy. The controller sees CMDRDY and sets BUSY = 1, thereby telling the host that it is busy.
  7. Work. The controller reads the command register (WRITE), takes the byte from the data-out register, and sends it to the device.
  8. Completion. CMDRDY, ERR, and BUSY are cleared. ERR = 0 shows that the job finished successfully. The loop starts over for the next byte.
CPUdriverController0BUSY0CMDRDY1WRITE0ERRdata-out = 0x41controller registers
Figure 11.7: The end of the handshake: BUSY = 0, CMDRDY = 0, ERR = 0. The data-out register holds the last byte sent (0x41).

Programmed I/O is simple and needs no extra hardware. But the CPU spins uselessly throughout the wait. Worse, if the CPU switches to another process and does not pick up a byte in time, data can be lost. If the controller's buffer overflows, a newly arrived byte has nowhere to go.

11.3.2The printer example

Tanenbaum's classic example is a user process sending the string “ABCD” to the printer. The kernel part of the system call looks like this:

copy_from_user(buffer, p, count);
for (i = 0; i < count; i++) {
    while (*printer_status_reg != READY)
        ;   /* busy-wait */
    *printer_data_register = p[i];
}
return_to_user();

The first line copies the user's string into a kernel buffer (copy_from_user). The kernel does not use user memory directly, because the process could modify that memory from another thread, or the address might be invalid. Then two things happen for each character. The inner while loop spins until the status register is READY. When the printer is ready, the character is written to the data register; the printer prints it and becomes busy again. After all four characters have been printed, control returns to the process.

CPUPIO loopprinterABCD
Figure 11.8: The end of the PIO loop: the printer has printed the characters A, B, C, D. The CPU stayed tied to this process the whole time.
Example 11.2

A printer prints 100 characters per second. With PIO, how long does the CPU wait for each character? How many loop iterations does a 2 GHz CPU spend in that time?

  1. Time per character. 1 s / 100 = 10 ms. After each character the CPU polls the status register for about 10 ms.
  2. Wasted iterations. 10 ms × 2 × 109 iterations/s = 2 × 107 iterations. In that time the CPU could have executed tens of millions of instructions.
  3. Result. The four-character job takes about 40 ms and is limited entirely by the printer's speed. A faster CPU changes nothing.

Even so, PIO is not always bad. In an embedded system where the CPU has nothing else to do, or when the device responds very quickly, polling is the simplest and fastest solution. The next example shows in numbers when polling is harmless and when it is impossible.

Example 11.3

On a 2 GHz CPU, one poll (read the status, compare, fetch the data) takes 600 cycles. What percentage of CPU time is spent on a keyboard polled 100 times per second, and on a device that produces 50 MB/s and hands over 32 bytes per poll?

  1. Ratio. CPU share = (polls/s × cycles/poll) / (cycles/s).
  2. Keyboard. 100 × 600 = 60,000 cycles/s; 60,000 / (2 × 109) = 0.003%. Negligible.
  3. Fast device. 50 × 106 / 32 ≈ 1.56 × 106 polls/s. That comes to 1.56 × 106 × 600 ≈ 9.4 × 108 cycles/s; about 47% of CPU time goes to polling alone.
  4. Interpretation. For a slow device with rare events, polling is harmless. For high-speed block transfer, it is unacceptable for the CPU to deal with every piece individually; the solution is DMA.

11.4Interrupts

11.4.1Interrupt hardware: from a wire to MSI

The flaw of polling is that the CPU queries the device constantly. A better arrangement is for the device to notify the CPU when it finishes.

Definition 11.6

An interrupt is a signal by which a device asks for the CPU's attention. The CPU finishes the current instruction, suspends the running program, and runs the interrupt handler belonging to that device. When the handler finishes, control returns to the suspended program.

DiskcontrollerKeyboardcontrollerPrintercontrollerInterrupt controller(I/O APIC)CPUlocal APICMemory / PCIe root complexMSI: vector 0x41 is written to the 0xFEE0_0000 region
Figure 11.9: Interrupt hardware. Device controllers connect to the interrupt controller (I/O APIC), which connects to the core's local APIC. A modern PCIe device uses no wire at all: it sends a memory write containing the vector number (here 0x41) to the 0xFEE0_0000 region.

In the classic arrangement, each device has a line (IRQ) to the interrupt controller. The controller shares the CPU's single interrupt input among the devices and sets priorities. A disk read is signaled in this order:

  1. Signal. When the disk controller finishes its job, it asserts its own interrupt line.
  2. Forwarding. If no other interrupt is being handled at that moment, or the new interrupt has higher priority, the interrupt controller forwards the interrupt to the CPU. Otherwise the request is held back; the line stays active until the CPU acknowledges it.
  3. Vector. The CPU accepts the interrupt and the controller supplies a vector number. The CPU uses this number as an index into the interrupt vector table and finds the address of the handler.

This description is based on the historical PC arrangement: two 8259 PICs and 15 IRQ lines. The controller “putting the vector on the address bus” is likewise true only for that arrangement. Today an x86 system has an I/O APIC and one local APIC per core (x2APIC); on ARM the GIC takes over this job.

Definition 11.7

MSI (message-signaled interrupts) and its extended form MSI-X deliver an interrupt through a memory write instead of a wire. The device sends a write containing the vector number to a special address region (0xFEE0_0000 on x86); the local APIC of the target core turns it into an interrupt.

MSI has two advantages. Line sharing disappears, because each device can obtain as many separate vectors as it wants. The interrupt can also be steered to a chosen core. MSI-X allows up to 2048 vectors for one PCIe function. NVMe disks and network cards get a separate vector for each queue and send that queue's interrupt to the core that uses the queue.

11.4.2Vectors, priority, NMI, and exceptions

Definition 11.8

An interrupt vector is an index into the interrupt vector table. Each entry of the table holds the address of a handler. On x86 this table is called the IDT; it has 256 entries, and its location is given by the IDTR register.

vector 14IDT (at IDTR)0divide_error…14page_fault…32device interrupthandler
Figure 11.10: Vector 14 (page fault) selects entry 14 of the IDT; the entry gives the address of the handler.

Some of the vectors belong not to devices but to the processor itself. On x86, vectors 0–31 are reserved for processor exceptions (Table 11.4).

Table 11.4: Some interrupt vectors on x86.
VectorEventType
0Divide errorfault
1 / 3Debug / breakpointtrap
2NMI (non-maskable interrupt)interrupt
6Invalid opcodefault
13General protection faultfault
14Page faultfault
18Machine checkabort
32–255Device interrupts, IPIs, APIC timermaskable
Definition 11.9

An exception is a synchronous event caused by the running instruction itself. Two kinds stand out. A fault (such as a page fault) prevents the instruction from completing; after the handler, the same instruction is executed again. A trap (a system call, int3) is triggered deliberately; after the handler, execution continues from the next instruction.

Interrupts differ among themselves as well. Maskable interrupts can be deferred in a critical region; on x86 the cli instruction disables interrupts and sti enables them again. An NMI (non-maskable interrupt), however, cannot be deferred. Hardware errors, memory ECC errors, and the watchdog use this path, because these events cannot tolerate waiting. Priority matters too. The APIC orders interrupts by vector class; a high-priority interrupt can interrupt a low-priority handler.

When there are more devices than vectors, one vector may be shared by several devices. In that case the table entry points not to a single handler but to a list of handlers. When the interrupt arrives, the handlers on the list take turns asking their own device “was this interrupt mine?”. This arrangement is called interrupt chaining or a shared IRQ. On Linux, which vector arrived how many times on which core can be seen in the file /proc/interrupts; the irqbalance service spreads interrupts across cores.

11.4.3Interrupt handling step by step

Let us follow how an interrupt is handled from start to finish in a concrete case. Process A is running; process B is waiting for a disk read to finish. The disk read completes and the controller requests an interrupt.

A runsuserHardwarePC, PSW savedIDT → ISRentry codeISRdevice + EOIB wakes upready queueSchedulerMMU, registersiretreturn to user modekernel stackRIP, CSRFLAGS (PSW)RSP, SSmode:kernelinterrupts:maskedrunning:—waiting: B (read)
A runsuserHardwarePC, PSW savedIDT → ISRentry codeISRdevice + EOIB wakes upready queueSchedulerMMU, registersiretreturn to user modekernel stackB's contextmode:userinterrupts:enabledrunning:BB ready
Figure 11.11: Two moments of the interrupt-handling flow. Above, the hardware saves the context; below, control returns to the chosen process with iret.
  1. Acceptance. The CPU finishes the current instruction and then accepts the interrupt. An interrupt is taken only at an instruction boundary.
  2. Hardware save. The hardware pushes the program counter (RIP on x86-64), the status word (PSW, RFLAGS), and the stack pointer onto the kernel stack. It switches to kernel mode and masks interrupts.
  3. Finding the handler. The vector number becomes an index into the IDT, and the handler's address is found. The entry code (assembly) also saves the registers that the hardware did not save. Now the context and stack are ready for the interrupt service routine (ISR) written in C.
  4. ISR. The handler reads the device's status, fetches the data, and sends an acknowledgment (EOI, end of interrupt) to the interrupt controller. After that, new interrupts may arrive. Work that will take long is deferred to later, to the bottom half.
  5. Wake-up. The waiting process B is moved from the blocked state to the ready queue.
  6. Scheduling. The scheduler picks the next process; let us assume it picks B here. B's page table is loaded into the MMU (the CR3 register on x86), and its registers are restored from the process table or from the stack.
  7. Return. The iret instruction restores the saved PC and PSW, returns to user mode, and enables interrupts. B resumes at the instruction where it left off.

This sequence follows Tanenbaum's steps for an interrupt handler. The scheduler could also have picked A; that choice depends on the policy. Apart from making a waiting process ready, an interrupt does not change the scheduling decision by itself.

Common mistake

Thinking that the interrupt handler runs before the state is saved. Since the handler will use A's registers, first the hardware saves the return address and status word, and then the entry code saves the other registers. Without the save, the return address would be lost and A could not continue where it left off. The correct order: the device requests, the CPU stops at an instruction boundary, the state is saved, the handler is found through the vector, the handler acknowledges the device and wakes the waiter, the scheduler chooses, and control returns with iret.

11.4.4Precise and imprecise interrupts

For a program to resume where it left off after an interrupt, “where it left off” must be well defined. In a pipelined processor this does not come automatically.

Definition 11.10

An interrupt is precise if it satisfies four conditions: (1) the PC is saved in a known place; (2) all instructions before the PC have completed fully; (3) none of the instructions after the PC has started; (4) the state of the instruction at the PC is known. An interrupt that does not satisfy these conditions is called imprecise.

(a) Precise interrupt: PC = 316300done304done308done312done316not started320not started324not started328not started332not startedPC
(b) Imprecise: instructions at different stages300done304%60308done312%30316%80320not started324%50328not started332%20
Figure 11.12: (a) Precise interrupt: PC = 316; the instructions at addresses 300–312 have completed, and 316 onward have not started. (b) Imprecise interrupt: instructions are left at different stages (304 at 60%, 312 at 30%, 316 at 80%, …).

In a pipeline, many instructions are at different stages at the same time. On a superscalar processor, instructions can also complete out of order. In the situation of part (b) of Figure 11.12, a single PC value does not describe where the program stopped. To restart, either the hardware must undo half-finished work or the operating system must save and decode a large amount of internal state. The second option makes the handler both slower and more complicated.

Modern x86, ARM, and RISC-V processors provide precise interrupts. They do this with a reorder buffer (ROB). Even though instructions execute out of order, the ROB “retires” them in program order, that is, makes their results permanent. When an interrupt arrives, the effects of instructions that have not yet retired are discarded. The price is chip area and design complexity, but the operating system stays simple as a result.

11.4.5Interrupt-driven I/O: the printer example

The printer example can be rewritten with interrupts. The goal is that the CPU does not spin while waiting for the printer.

Definition 11.11

In interrupt-driven I/O, the CPU gives the device a job and goes off to run another process. When the device finishes the job, it raises an interrupt; the interrupt handler either hands out the next job or wakes the waiting process.

/* system call */
copy_from_user(buffer, p, count);
enable_interrupts();
while (*printer_status_reg != READY) ;
*printer_data_register = p[0];
i = 1; count = count - 1;
scheduler();      /* block process */
/* interrupt service routine */
if (count == 0) {
    unblock_user();
} else {
    *printer_data_register = p[i];
    count = count - 1;
    i = i + 1;
}
acknowledge_interrupt();
return_from_interrupt();

The code has two parts. The upper part is the system call. It copies the string into a kernel buffer, enables the printer's interrupts, writes only the first character when the printer is ready, updates the counters, and calls the scheduler. The process blocks and the CPU runs another process. The lower part is the interrupt service routine. An interrupt arrives each time the printer finishes a character. The routine looks at count: if it is zero, all characters have been printed and the user process is woken. Otherwise the next character is written, count decreases by one, and i increases by one. In both cases the interrupt is acknowledged and control returns to the interrupted process.

Table 11.5: Interrupt-driven printing of the string “ABC” (initially count = 3).
EventWrittenicountProcess
System callp[0] = 'A'12blocked
Interrupt 1 ('A' printed)p[1] = 'B'21blocked
Interrupt 2 ('B' printed)p[2] = 'C'30blocked
Interrupt 3 ('C' printed)—30ready (unblock_user)
printerABCprocess: readyCPU: ISR
Figure 11.13: After the third interrupt: A, B, C have been printed; the ISR has moved the user process to the ready queue.

Table 11.5 reveals one detail: three characters produce three interrupts, but the third interrupt writes no new character. It only reports that the job is done. Because the system call writes the first character, the number of interrupts equals the number of characters. The price of the method is the context save and handler time per interrupt, typically 1–2 µs. While waiting for the printer, the CPU runs other processes; this gain is far larger than the few microseconds an interrupt costs.

11.4.6Top half, bottom half, and hybrid polling

While an interrupt handler runs, at least interrupts on the same line are disabled. If the handler runs long, interrupts from other devices are delayed or even lost. For this reason operating systems split the handler in two.

Definition 11.12

The top half (hardirq on Linux) is the actual interrupt handler: it is kept short, acknowledges the device, copies the data into a buffer, and schedules the rest of the work. The bottom half is deferred work and runs with interrupts enabled. It takes the form of softirqs, tasklets, workqueues, or threaded IRQs (request_threaded_irq) on Linux, and of ISR + DPC (deferred procedure call) on Windows.

There are other ways to reduce the number of interrupts.

  • Interrupt coalescing. Network cards and NVMe disks report several completions in a single interrupt. The number of interrupts drops, and latency rises slightly.
  • NAPI: interrupts combined with polling. Under heavy network traffic, the Linux driver turns the interrupt off and polls the queue. When traffic falls, it returns to interrupts. Interrupts are efficient for rare events and polling for frequent ones; the hybrid method takes the best of both.
  • Pure polling. When the event rate is very high and latency is critical, interrupts are not used at all. DPDK and SPDK, NVMe polled queues, and the IOPOLL mode of io_uring choose this path. One core is dedicated entirely to polling.

Interrupts also have a failure mode. If a faulty device raises interrupts continuously, the processor does nothing but run the handler and the system locks up. This is called an interrupt storm. If many interrupts arrive that no handler claims, Linux shuts the line off with a “nobody cared” message; there are also mechanisms that limit the interrupt rate.

11.5Direct memory access (DMA)

11.5.1The DMA controller

Interrupt-driven I/O removes the waiting, but an interrupt still arrives for every byte or word. Moving a 4 KiB disk block word by word means thousands of interrupts. The solution is to take the transfer job away from the CPU altogether.

Definition 11.13

Direct memory access (DMA) is a hardware mechanism that performs block transfers between a device and memory without the CPU's involvement. The CPU only sets up the transfer and deals with the single interrupt that arrives when the transfer is finished.

The registers of a DMA controller describe the transfer: a memory address, a byte count, and a control register. The control register determines the I/O port, the direction (read or write), the transfer unit (byte or word), and how many units are moved at a time (the burst size). A multichannel controller keeps a separate register set for each channel and manages many transfers at once.

(a) third-party DMA (8237, on the motherboard)CPUDMAchannels 0–7DeviceMemory(b) bus masterCPUNVMe / NIC / GPUown DMA engineMemory
Figure 11.14: (a) Third-party DMA: a single DMA controller (8237) on the motherboard performs transfers on behalf of devices. (b) Bus master: an NVMe disk, a network card, or a GPU writes directly to memory with its own DMA engine.

The arrangement in which a single DMA controller on the motherboard serves all devices holds only for the historical 8237 chip (Figure 11.14 (a)). Today most devices have their own DMA engine, and these devices perform PCIe writes directly to memory. The concept stays the same: the CPU sets up the transfer, and the device carries it out.

11.5.2A DMA transfer step by step

Let us follow a disk sector being read into memory with DMA. The sector is 4096 bytes and will be written to address 0x7A000 in memory.

CPUDMA controlleraddress0x7B000count0controlread → memoryDisk controllerbuffer (sector)ECC verifiedDiskMain memorybuffer @ 0x7A000system bus⑤ count = 0 → interrupt
Figure 11.15: The last step of a DMA transfer: the count has dropped to 0, and the DMA controller sends an interrupt to the CPU. The data is already in memory.
  1. Setup. The CPU programs the DMA controller (address = 0x7A000, count = 4096, direction = read) and the disk controller (“read the sector”), then returns to other work.
  2. Buffer. The disk controller reads the sector into its own buffer and verifies it with the ECC. Thanks to the buffer, no data is lost if the bus is busy at that moment.
  3. Request. The DMA controller requests the bus, places the memory address on it, and sends a read request to the disk controller.
  4. Write. The disk controller writes the word directly to memory. The CPU is not involved in this transfer.
  5. Acknowledgment. The disk controller sends an acknowledgment; the DMA controller increments the address and decrements the count. The request, write, and acknowledgment steps repeat until the count reaches 0.
  6. Interrupt. When the count reaches 0, the DMA controller alerts the CPU with an interrupt. By the time the operating system handles the interrupt, the data is already in memory.

How DMA uses the bus matters too. In cycle stealing mode, the controller takes the bus from the CPU for a few cycles for each word. The CPU does not stop completely; it only waits a little when it wants to access memory. In burst mode the bus is held for an entire block; the transfer is faster, but the CPU may wait longer. There is one more distinction. In fly-by mode, data goes from the device to memory directly. In the other mode, the DMA controller first reads the word itself and then writes it to the destination; these two bus cycles are costly, but they also allow memory-to-memory copies.

11.5.3Scatter-gather and the IOMMU

In a system with virtual memory, a process's 12 KiB buffer is contiguous in virtual addresses but may be scattered over three separate pages in physical memory. A simple DMA controller can write only to a single contiguous region. In that case the kernel must either bring the data into a contiguous buffer and copy it afterwards, or perform three separate transfers.

Scatter-gatherdescriptor list0x7A00040960x3100040960x9C0002048physical memory (not contiguous)0x7A0000x310000x9C000one command, three pieces: no extra copyIOMMU (Intel VT-d, AMD-Vi, Arm SMMU)DeviceIOVA 0x1000Rogue deviceIOVA 0xDEAD000IOMMUtableRAM0x7A000✗ blocked
Figure 11.16: On the left, scatter-gather: the descriptor list gives three pieces (0x7A000/4096, 0x31000/4096, 0x9C000/2048) in a single command. On the right, the IOMMU: the address the device sees (IOVA) is translated to a physical address through a table; an access to an address that is not in the table is blocked.
Definition 11.14

In scatter-gather DMA, the device is given a list of (address, length) pairs; the device writes to or reads from the noncontiguous pages in a single operation. The IOMMU is a unit that translates the addresses a device uses (IOVAs) to physical addresses through a page table.

Scatter-gather underlies the readv/writev calls on Linux, fragmented network packets, and the PRP and SGL lists in NVMe. No extra copy is needed. The IOMMU has three jobs. The first is protection: a device can access only the pages mapped for it. This blocks DMA attacks in which an externally attached device such as one on Thunderbolt tries to read all of memory. The second is virtualization: a device can be assigned directly to a virtual machine (VFIO); the guest operating system supplies its own “physical” addresses, and the IOMMU translates them to real addresses. The third is that old devices that can address only 32 bits can use memory above 4 GiB. The unit is called VT-d on Intel, AMD-Vi on AMD, and SMMU on ARM.

11.5.4The printer example with DMA

The third version of the printer example uses DMA:

/* system call */
copy_from_user(buffer, p, count);
set_up_DMA_controller();
scheduler();     /* block process */

/* interrupt service routine */
acknowledge_interrupt();
unblock_user();
return_from_interrupt();

The system call copies the data into the kernel buffer, programs the DMA controller (buffer address, count = 3, the printer port as destination), and blocks the process. The DMA controller passes the characters to the printer without the CPU. During this time no interrupt reaches the CPU. When all characters have been transferred, DMA raises a single interrupt. The interrupt service routine does just two things: it acknowledges the interrupt and wakes the user process. There is one interrupt per buffer, not per character.

DMA → printerABCprocess: readyCPU: ISR
Figure 11.17: The end of printing with DMA: three characters have been transferred, and a single interrupt woke the process.

DMA does not always pay off. A DMA controller is usually slower than the CPU. If the device is very slow, or the CPU has nothing else to do, interrupt-driven I/O or PIO can be simpler and sufficient. Tanenbaum stresses this point in particular: the gain from DMA depends on the CPU being able to do useful work in the time it frees.

11.5.5The cost of the three methods

Let us compare the three methods in numbers on the same job.

Example 11.4

A printer prints 1000 characters per second; 4096 characters are to be printed. Interrupt handling costs 2 µs and DMA setup 5 µs. How much time does the CPU spend on this job with each method?

  1. Polling. The CPU waits for every character. At 1 ms per character, the CPU is busy for 4096 × 1 ms = 4.096 s. In programmed I/O, the time the CPU spends depends on the device's speed.
  2. Interrupt-driven. One interrupt arrives per character: 4096 × 2 µs = 8192 µs ≈ 8.19 ms. This is 0.2% of the total duration of the job (4.096 s). The waiting disappears; the price is the number of interrupts.
  3. DMA. 5 µs of setup and 1 interrupt × 2 µs: a total of ≈ 7 µs. Compared with the interrupt-driven method, 8192 / 7 ≈ 1170 times less CPU time is spent.
  4. Interpretation. Between polling and DMA there is a gap of about six orders of magnitude (4.096 s / 7 µs ≈ 585,000 times), and between interrupt-driven I/O and DMA a gap of more than three (Figure 11.18). DMA still steals cycles from the bus, and its setup cost does not pay for itself in small transfers.
Polling (PIO)4.096 sInterrupt-driven8.19 msDMA≈ 7 µsCPU time (log): 1 µs … 10 s
Figure 11.18: CPU time of the three methods for printing 4096 characters, on a logarithmic axis: polling 4.096 s, interrupt-driven 8.19 ms, DMA ≈ 7 µs.
Example 11.5

512 KiB of data is read from a disk controller. In the interrupt-driven method, one interrupt arrives for every 512-byte sector, and the handler spends 5 µs copying the sector into memory. With DMA, the setup takes 8 µs and the single interrupt at the end of the transfer 5 µs. What are the CPU loads?

  1. Number of sectors. 512 KiB = 524,288 B; 524,288 / 512 = 1024 sectors.
  2. Interrupt-driven. 1024 × 5 µs = 5120 µs ≈ 5.1 ms.
  3. DMA. 8 + 5 = 13 µs. The CPU load falls by a factor of 5120 / 13 ≈ 394.
  4. Edge case. If a single 512-byte sector is read on the same system, the interrupt-driven method spends 5 µs and DMA 13 µs. The fixed setup cost wipes out the gain on a small transfer.

These two examples make the rule clear. As the transfer grows, the fixed cost of DMA becomes negligible and the CPU load becomes independent of transfer length. As the transfer shrinks, the device slows down, or the CPU sits idle, the gain from DMA disappears.

11.6I/O software

11.6.1Goals of I/O software

The sheer variety of hardware makes it necessary for the software to be orderly. Six goals guide the design of I/O software.

  • Device independence. A program should be able to work without knowing which device it is working with. The command sort < input works the same way whether the file input sits on an SSD or on a USB stick.
  • Uniform naming. The name of a file or device should not depend on the type of device. /dev/nvme0n1 and /mnt/usb/report.txt are parts of the same tree; different devices are attached to a single tree by mounting.
  • Error handling. Errors should be solved as close to the hardware as possible. The controller corrects a bit error with the ECC, and the driver retries a failed operation. The upper layer learns about the error only when necessary.
  • Synchronous and asynchronous transfer. At the hardware level most transfers are asynchronous: the CPU starts the job and waits for the interrupt. Offering the user a blocking interface makes programming easier. The operating system bridges the two.
  • Buffering. A packet arriving from the network must be put somewhere before it is known where it is going. Real-time devices such as audio also depend on buffers.
  • Shared and dedicated devices. A disk can serve many users at the same time. A printer or a scanner, on the other hand, is dedicated to a single user at a given moment. Dedicated devices create a deadlock risk: two processes can wait for devices held by each other.

11.6.2I/O software layers

The way to reach these goals is a layered structure. Each layer has a well-defined task and an interface that it offers to the layer above.

User processread(), printf(), spoolingSystem call + VFSfd → file, permissions, namingPage cachebuffering, cachingFile system + block layeroffset → LBA, blk-mq, schedulerDevice driverbuild command, write registersInterrupt handlercompletion, wake the processHardwarecontroller + device (DMA)userkernelhardwarerequestresponse
Figure 11.19: I/O software layers: user process, system call and VFS, page cache, file system and block layer, device driver, interrupt handler, and hardware. The request flows from top to bottom and the response from bottom to top.

Tanenbaum counts four layers: user-level I/O software, device-independent software, device drivers, and interrupt handlers. On Linux the “device-independent” part is itself divided into several pieces: the VFS (virtual file system), the page cache, the file system, and the block layer (Figure 11.19). The example below shows how a request passes through these layers.

11.6.3The path of a read() call

User processread(), printf(), spoolingSystem call + VFSfd → file, permissions, namingPage cachebuffering, cachingFile system + block layeroffset → LBA, blk-mq, schedulerDevice driverbuild command, write registersInterrupt handlercompletion, wake the processHardwarecontroller + device (DMA)userkernelhardwareDMA → cache page, MSI-X
Figure 11.20: The path of a read() request through the layers. At this moment the SSD has written the data to the cache page by DMA and raised an MSI-X interrupt.
Example 11.6

A process reads 4 KiB from a file on an NVMe SSD with read(fd, buf, 4096), and the requested page is not in memory. What steps does the request go through?

  1. System call. The libc wrapper enters the kernel with the syscall instruction.
  2. VFS. The file descriptor is resolved to an open file object, and the open file to an inode. The access permission was already checked when the file was opened.
  3. Page cache. The requested page is not in the cache. A cache page is allocated and the read is started.
  4. File system and block layer. The file system translates the file offset into a disk block (LBA, logical block address). The block layer builds a request (bio) and hands it to the hardware queue.
  5. Driver. The NVMe driver writes the read command into the submission queue and notifies the device by writing to the doorbell register. The process blocks; on Linux its state appears as D (uninterruptible sleep).
  6. Device. The SSD writes the data to the cache page by DMA, adds an entry to the completion queue, and raises an MSI-X interrupt.
  7. Interrupt handler. The completion entry is processed, the page is marked “up to date”, and the waiting process becomes ready.
  8. Return. When the process runs again, the VFS copies the data from the cache into the user buffer and the call returns 4096.

If the same data is read a second time, the page is found in the cache at the third step. The device is never visited; the operation finishes within microseconds. This difference also explains why the operating system devotes free memory to caching.

11.6.4Device drivers

Definition 11.15

A device driver is a kernel component that encapsulates the code specific to a particular device or family of devices. Only the driver knows the device's registers, commands, and quirks.

User programkerneldevice-independent layerNVMedriverUSB/HIDdriverNetdriverPCIeNVMe ctrl.SSDxHCI ctrl.keyboardNICcable
Figure 11.21: Device drivers run in the kernel and talk to controllers over the bus.

A driver follows a similar sequence of work for every request from the layer above. First it validates the parameters. Then it translates the request into a command the device understands; for a disk, this means an LBA and a queue entry. If necessary it starts the device, writes to registers, and waits for the interrupt, that is, it blocks. When the job finishes, it checks for errors and returns the result to the upper layer.

Writing a driver has two difficulties. First, a driver must be reentrant: while it is handling one request, a new request or an interrupt may arrive. Second, a hot-pluggable device can vanish while it is in use; the driver must handle this without crashing.

On Linux most drivers are inside the kernel source tree; some come separately from the vendor. Drivers are usually loadable modules: modprobe loads a module, and lsmod lists the loaded modules. But a faulty driver running in the kernel can crash the whole system. To reduce this risk, there are designs that move drivers into user space. In MINIX 3 all drivers are in user space. FUSE, VFIO/UIO, DPDK, and SPDK on Linux and UMDF on Windows are used for this purpose.

11.6.5Device-independent I/O software

The layer above the driver takes on the jobs that are common to all drivers. Foremost among them is a uniform interface. Every device class offers the same functions, and the kernel calls the driver through a table of function pointers:

struct file_operations nvme_fops = {
  .open           = nvme_open,
  .release        = nvme_release,
  .read_iter      = nvme_read,
  .unlocked_ioctl = nvme_ioctl,
  .poll           = nvme_poll,
};

This table is the C counterpart of object-oriented programming. When a read is requested on a file, the VFS does not ask which device it is; it calls the read_iter pointer in the table attached to the file. For NVMe this is nvme_read; for a serial port it is a different function. Adding a new device means writing a new table without touching the rest of the kernel.

(a) no interfaceOperating systemSATANetUSB(b) uniform interfaceOperating systemopen/read/write/ioctlSATANetUSB
Figure 11.22: (a) Without a standard interface, the kernel calls each driver differently. (b) With a standard interface, all drivers offer the same functions.

The same layer does other jobs as well. Naming: a name such as /dev/nvme0n1 is translated into a pair of a major number (driver) and a minor number (unit). Protection: the permissions of the device file decide who can access the device. It also presents a device-independent block size, manages buffering and error reporting, and handles the allocation and release of dedicated devices.

11.6.6Buffering

Definition 11.16

A buffer is a memory area that temporarily holds data being transferred between two devices or between a device and an application. Using such an area is called buffering.

Silberschatz lists three reasons for buffering. The first is the speed mismatch between producer and consumer: a slow stream from a modem is not written to disk one piece at a time but accumulated in a buffer. The second is the transfer-size mismatch: small packets on the network are reassembled on the receiving side. The third is copy semantics: after write returns, the application must be able to modify its own buffer; the data to be written to disk must already have been copied in the kernel as it was at that moment.

Consider a process that reads characters from a modem or a serial port. There are five different levels of buffering (Figure 11.23).

(a) no bufferuser processkernelmodem / deviceper character:interrupt + wake-up
(d) double bufferuser processkernelmodem / deviceuserbuffer 1buffer 2fillingbeing copied
(e) a packet over the network: five copiesuser (sender)kernel buffernetwork controller bufferuser (receiver)kernel buffernetwork controller buffer123: wire45zero copy: sendfile, splice, MSG_ZEROCOPY, io_uring
Figure 11.23: Buffering options. At the top the unbuffered arrangement, in the middle the double buffer, at the bottom the five copies of a packet over the network.
  1. Unbuffered. An interrupt arrives for every character and the process is woken. There are many context switches; it is inefficient.
  2. User buffer. The interrupt handler writes the characters directly into a buffer in the process; the process is woken only when the buffer fills. But if the buffer's page has been swapped out to disk in the meantime, where does the handler write? The page must be locked in memory. If many processes lock pages, the available memory shrinks.
  3. Kernel buffer. Characters first accumulate in a buffer in the kernel; when the buffer fills, they are copied to the user in one go. But where does a character that arrives during the copy go?
  4. Double buffer. The kernel has two buffers: one fills while the other is copied to the user, and then the roles swap. The general form of this arrangement is the circular buffer.
  5. Copies on the network. A packet can be copied five times on its way across the network: from the sender's user space to the kernel, from the kernel to the network card, over the wire to the receiver's network card, from there to the kernel, and finally to the user. Every copy costs memory bandwidth and latency. That is why zero-copy techniques such as sendfile, splice, MSG_ZEROCOPY, and io_uring were developed.
Example 11.7

A block arrives from a device in T = 10 ms, the process takes C = 6 ms to process a block, and copying from the buffer to user space takes M = 2 ms. What is the time per block in steady state?

  1. Unbuffered. Reading and processing happen one after the other: T + C = 16 ms.
  2. Single buffer. While the next block arrives in the kernel buffer, the previous block is processed. But during the copy the buffer is busy and the new block cannot start: max(T, C) + M = 10 + 2 = 12 ms.
  3. Double buffer. One fills while the other is copied; the copy overlaps too. Since C + M = 8 ≤ T, the bottleneck is the device: max(T, C) = 10 ms.
  4. Interpretation. The limit is now the speed of the device (T > C). Adding more buffers does not raise the average rate; it only absorbs sudden bursts.

11.6.7The circular buffer

Definition 11.17

A circular buffer (also ring buffer) uses an array of N slots as if its ends were joined. The producer writes to the slot at the tail index, and the consumer reads from the slot at the head index; both indices wrap around to 0 when they reach the end (mod N). If head = tail, the buffer is empty; if (tail + 1) mod N = head, it is full.

i01c2d3e4f5g6h7head = 2 tail = 1full slots: 7 / 8data (producer: ISR / DMA)tail: next slot to writehead: next slot to readone more byte: buffer fullempty: head == tail full: (tail + 1) % 8 == head
Figure 11.24: An eight-slot circular buffer when full: head = 2, tail = 1. Seven slots hold c, d, e, f, g, h, i; one slot always stays empty.
Example 11.8

A buffer with N = 8 slots is empty (head = tail = 0). The interrupt handler writes 3 bytes (a, b, c), the process reads 2 bytes, and then the producer writes 5 bytes (d … h) and one more byte (i). How do the indices change?

  1. Empty. Head and tail point to the same slot.
  2. Three writes. a, b, c go to slots 0, 1, 2; tail = 3. The consumer has not read yet.
  3. Two reads. a and b are read; head = 2. Slots 0 and 1 can be reused.
  4. Five writes. d … h go to slots 3–7. When the tail reaches the end, it wraps to the start: 8 mod 8 = 0.
  5. The last write. i is written to slot 0, and tail = 1. Now (1 + 1) mod 8 = 2 = head: the buffer is full. The buffer holds 3 + 5 + 1 − 2 = 7 bytes, that is, N − 1.

When the buffer is full, the producer can do one of two things: wait for the consumer to make room, or drop the data. On a network card the second happens and the packet is lost. The reason one slot is always left empty is simple. If all slots could be filled, head = tail would hold for a full buffer too, and empty could not be told from full. The price is that a buffer of N slots holds at most N − 1 bytes.

Circular buffers are everywhere in I/O: keyboard and serial port drivers, the receive and transmit rings of network cards, the submission and completion queues of NVMe, io_uring. With a single producer and a single consumer, no lock is needed. The producer changes only the tail and the consumer only the head; to maintain the correct order, only memory barriers are required.

11.6.8Code trace: the circular buffer

The two functions below implement the circular buffer in C. put runs in the interrupt handler and get in the process.

int put(char c) {          /* producer */
  int s = (tail + 1) % N;
  if (s == head) return -1; /* full */
  buf[tail] = c;
  tail = s;
  return 0;
}
int get(char *c) {         /* consumer */
  if (head == tail) return -1; /* empty */
  *c = buf[head];
  head = (head + 1) % N;
  return 0;
}

put first computes the next value of the tail in s. If s equals head, writing would make the buffer look “empty”; so the buffer is considered full and -1 is returned. Otherwise the byte is written to buf[tail] and the tail advances. The order matters here: first the data is written, then the index is updated. Otherwise the consumer could read a slot that has not been written yet. get checks whether head equals tail; if so, the buffer is empty. Otherwise buf[head] is read and the head advances. Both functions run in O(1) time. The space of the buffer is N slots and never changes.

Table 11.6: put and get calls for N = 5. Each row shows the state after the call.
CallDetailheadtailReturns
—buffer empty00
put('a')buf[0] = 'a'010
put('b')buf[1] = 'b'020
put('c')buf[2] = 'c'030
gethead ≠ tail; 'a' is read130
put('d')buf[3] = 'd'140
put('e')buf[4] = 'e'; the tail wraps around100
put('f')s = (0 + 1) mod 5 = 1 = head: full10−1
get'b' is read200
N = 5 slots; at most N − 1 = 4 bytes are held·0·1'c'2'd'3'e'4headtail
Figure 11.25: The end of the trace: slots 2, 3, 4 hold 'c', 'd', 'e'; head = 2, tail = 0.

When 'f' is rejected, the buffer holds four bytes ('b', 'c', 'd', 'e'): N − 1 = 4. After one read, room opens up and the next put succeeds.

Common mistake

Writing the full condition as tail == head. This condition is true for an empty buffer as well; when the buffer fills, the producer would have overwritten all the data on top of an “empty” buffer and the consumer could read nothing. If you do not want to leave a slot empty, you must keep a separate counter; but then both sides modify the same variable and lock-free operation breaks.

11.6.9Caching, spooling, and error handling

A cache and a buffer are different things. A buffer temporarily holds the only copy of the data. A cache, on the other hand, is a fast-access copy of data that lives somewhere else. The Linux page cache combines the two: data to be written to disk is buffered there, and data read from disk is cached there. Idle RAM goes to the cache; the buff/cache column in the output of free -h shows this.

Definition 11.18

Spooling means queuing the jobs destined for a dedicated device on disk, while a single background process sends them to the device one after another.

The printer is the classic example of spooling. The user puts the file to be printed in the spool directory; a single background process (CUPS on Linux, directory /var/spool/cups) prints the files in order. No user process locks the printer, so there is no deadlock over the printer either.

Error handling separates two kinds of errors. For programming errors, such as an invalid file descriptor, the call returns an error code (EBADF, EINVAL). For a real I/O error, the driver retries the operation; if the error is permanent, the call returns EIO and the event is written to the kernel log (dmesg).

Allocation and protection. A dedicated device is reserved with open. If the device is busy, the request is queued or the call returns EBUSY. All I/O instructions are privileged; a user process can perform I/O only through system calls.

At the very top sits the I/O software in user space. Library routines such as printf and scanf do formatting and keep their own buffers. stdio writes to a terminal line by line and to a file block by block. A write system call is made when the buffer is full or the line ends. This way each printf does not turn into a system call.

11.7I/O interfaces

11.7.1Blocking, nonblocking, and asynchronous I/O

When an application requests I/O, when the call returns determines the whole structure of the program. There are three models.

Definition 11.19

A blocking I/O call does not return until the requested data arrives; the process sleeps in the meantime. A nonblocking I/O call returns immediately: it gives whatever data is available at that moment, or returns the EAGAIN error if there is none. An asynchronous I/O call starts the job and returns immediately; the job completes in the background and the process is notified afterward.

Blockingread() waits for datarunningblocked: waiting for I/Oresumes with dataNonblockingreturns immediately; what is ready, or EAGAINrunningEAGAINother workEAGAINother workdatacontinueAsynchronousrequest is submitted, result is reported laterrunningrequestkeeps runningcompletedcontinuedevice data ready
Figure 11.26: Timelines of the three models. In a blocking call the process sleeps until data arrives. In a nonblocking call the process does other work whenever it gets EAGAIN and tries again. In an asynchronous call the process keeps running and is notified when the job is done.

The blocking model is the easiest to program, and it is the model most programs use. But if a process is to serve thousands of network connections at once, starting a thread for each connection is expensive. So that a single thread can watch many descriptors, the kernel offers interfaces that answer the question “which descriptor is ready?” (Table 11.7).

Table 11.7: Multiple-descriptor interfaces.
InterfaceModelNote
select / pollreadiness notificationthe whole descriptor list is scanned on every call: O(n)
epoll (Linux), kqueue (BSD)readiness notificationinterest list in the kernel; only the ready ones are returned
io_uring, Windows IOCPcompletion notificationtrue asynchronous I/O; disk included

11.7.2The event loop: epoll

int ep = epoll_create1(0);
for (k = 0; k < nsock; k++)   /* O_NONBLOCK */
    epoll_ctl(ep, EPOLL_CTL_ADD, s[k], &ev);
for (;;) {
  int n = epoll_wait(ep, evs, 64, -1);
  for (int i = 0; i < n; i++) {
    int fd = evs[i].data.fd;
    ssize_t r = read(fd, buf, sizeof buf);
    if (r < 0 && errno == EAGAIN) continue;
    handle(fd, buf, r);
  }
}

The code is the event loop of a typical server. epoll_create1 creates an epoll object in the kernel. This object keeps two lists: the interest list of the descriptors being watched and the ready list of those that are ready at the moment. Then the sockets are added to the interest list in nonblocking mode (O_NONBLOCK). This is done once; unlike select, the list does not have to be passed again on every iteration.

In the endless loop, epoll_wait blocks the process while no socket is ready; the CPU does not spin. Suppose a packet arrives for socket 7. The network card raises an interrupt, the network stack processes the packet and adds fd 7 to the ready list; the process wakes up and n = 1 is returned. The inner loop handles only the ready descriptor: 512 bytes are read and handle is called. The cost is proportional to the number of ready descriptors, not to the total number of descriptors. If the next read returns EAGAIN, no data is left to read and the loop goes back to epoll_wait.

interest list (in the kernel)fd 5fd 6fd 7ready list(empty)
Figure 11.27: After the data is handled: fd 5, 6, 7 in the interest list; the ready list is empty.

With this arrangement, a single thread can manage tens of thousands of connections. nginx, Node.js, and Redis work this way. epoll has a limit too. epoll only says “you may read”; the work is still done by read, and the copying comes out of the process's time. Disk files always look “ready”, because the kernel never refuses a disk read with EAGAIN; it completes it by blocking. So true asynchrony for disks comes with io_uring.

11.7.3io_uring: shared rings

Definition 11.20

io_uring (Linux 5.1, 2019) is an asynchronous I/O interface in which the application and the kernel share two circular buffers in shared memory. The application writes request entries (SQEs) to the submission ring (SQ); the kernel adds the results of completed jobs to the completion ring (CQ) as entries (CQEs).

Application (user space)Kernel: file system, block layer, NVMeSQ (submission ring)CQ (completion ring)shared memory (mmap)read without a system call
Figure 11.28: io_uring: the submission (SQ) and completion (CQ) rings shared between the application and the kernel. The application reads completions without making a system call.
  1. Rings. The application and the kernel see the two rings in shared memory through mmap. Requests and results are not copied.
  2. Submission entries. The application writes three SQEs: two reads and a write. Each entry carries the opcode, the file descriptor, the buffer address, and the offset.
  3. Batch submission. A single io_uring_enter call submits all three requests at once. In SQPOLL mode a kernel thread polls the ring continuously and no system call is needed at all.
  4. Completion. As devices finish the jobs, the kernel adds CQEs to the ring. The result field of each CQE carries the number of bytes transferred or a negative error code (−errno).
  5. Reaping. The application reads the CQEs directly from memory and advances the head of the ring. Thanks to batch submission and batch reaping, context switches drop sharply.

io_uring is a completion model: the kernel says “your job is done”, like IOCP on Windows. epoll, on the other hand, is a readiness model: it says “you may read now”. io_uring supports hundreds of operation types, including network, file, accept, and timers. Because it is a complex interface, many vulnerabilities have been found in it; for this reason it is disabled in places such as Android and some container environments.

Common mistake

Treating nonblocking I/O and asynchronous I/O as the same thing. A nonblocking call does not do the job; it does only as much as can be done at that moment and leaves the rest to the process, which has to try again. An asynchronous call hands the whole job to the kernel and receives the result later. The price is more complicated programming: buffers must stay valid until the job is done, and the error path of every request has to be tracked separately.

11.8Clocks and other devices

11.8.1Clock hardware

Clocks are neither block nor character devices, but they are among the devices the operating system uses most. They drive time slices, the time of day, and all timers.

Definition 11.21

A programmable clock is a circuit that decrements a counter on each pulse from a crystal oscillator and raises an interrupt when the counter reaches zero. In one-shot mode the clock raises a single interrupt and stops. In square-wave (periodic) mode the counter is reloaded from a holding register and interrupts arrive at regular intervals. Each interrupt is called a tick.

Crystal oscillator1.193182 MHzpulseCounter−1 on each pulseat 0InterruptIRQ 0 / vectorHolding register = 1193reload (square-wave mode)CPUclock handlermodes: one-shot · square wave (periodic)
Figure 11.29: The 8254 PIT: a 1.193182 MHz oscillator decrements the counter on each pulse; when the counter reaches 0, IRQ 0 is raised and the counter is reloaded from the holding register (1193).
Example 11.9

The 8254 PIT counts 1,193,182 pulses per second. What is loaded into the holding register for a 1 kHz and a 100 Hz tick? What are the actual frequencies?

  1. 1 kHz. 1,193,182 / 1000 = 1193.18. The counter must be an integer: 1193. The actual frequency is 1,193,182 / 1193 ≈ 1000.15 Hz.
  2. 100 Hz. 1,193,182 / 100 = 11,931.82 → 11,932. The actual frequency is 1,193,182 / 11,932 ≈ 99.998 Hz.
  3. Result. Because of rounding, the clock drifts slightly from the desired frequency. This drift, which accumulates over a long time, makes it necessary to correct the time of day now and then against a real time source.

The 8254 survives today only for compatibility. Modern x86 processors use the TSC (timestamp counter), the HPET, and the local APIC timer on each core. In the TSC-deadline mode of the APIC timer, the operating system tells it directly “raise an interrupt when the TSC reaches this value”. On ARM processors the generic timer takes over this job. The battery-backed real-time clock (RTC) keeps the date while the computer is off; at boot the time of day is read from it.

The tasks of clock software are: keeping the time of day, calling the scheduler when a process's time slice expires, accounting for CPU usage, running the alarms and timers that processes request, feeding watchdog timers, and sampling for profiling.

Common mistake

Keeping the time of day in a 32-bit seconds counter. A signed 32-bit time_t can count at most 231 − 1 seconds from 1 January 1970. This limit is reached at 03:14:07 UTC on 19 January 2038, and the counter overflows to negative. The time of day must be kept in a 64-bit counter. Linux has moved to a 64-bit time_t, but the problem persists in old embedded systems.

11.8.2Ticks and the tickless kernel

The classic kernel uses the clock in periodic mode. The timer raises an interrupt every 1/HZ seconds. On Linux, HZ is chosen at configuration time: 100, 250, or 1000; the tick interval is 10, 4, and 1 ms respectively. On every tick the handler advances time, decrements the remaining time slice of the running process, and runs timers that have expired.

(a) periodic tick: HZ = 250 → 4 ms0481216202428323640time (ms)workCPU idle (deep C-state wanted)timer event6 needless wake-ups while idle: each one pulls the CPU out of deep sleephrtimer: nanosecond-resolution timers, ordered in a red-black tree
(b) tickless (NO_HZ): one-shot for the next event0481216202428323640time (ms)workCPU idle (deep C-state wanted)timer eventno tick while idle: the timer is programmed once for 30 mshrtimer: nanosecond-resolution timers, ordered in a red-black tree
Figure 11.30: (a) A periodic tick (HZ = 250, 4 ms): the CPU wakes on every tick even when idle; in the empty interval in the figure there are six needless wake-ups. (b) A tickless kernel: there is no tick while idle, and the clock is set to the next event (30 ms) with a one-shot.

The problem with a periodic tick is that the CPU wakes even when idle. Every wake-up pulls the CPU out of a deep sleep state and spends energy. The tickless kernel (NO_HZ_IDLE on Linux, 2007) stops the tick while the CPU is idle and sets the clock with a one-shot for the time of the next event. The nohz_full option goes one step further. On a core where only a single process runs, it removes the tick even while the process is running. This matters for high-performance computing and real-time workloads. Tickless operation saves battery on laptops and CPU time in virtual machines. For short waits at the microsecond level, soft timers and polling are used together. Linux's high-resolution timers (hrtimer) have nanosecond resolution and are kept ordered in a red-black tree.

11.8.3The timer list

Many processes can set an alarm saying “notify me after this many ticks”. How can the clock software keep track of these alarms without looking at all of them on every tick? Tanenbaum's answer is the delta list.

Definition 11.22

A delta list is a linked list that keeps pending timers ordered by expiry time. Each node stores not the absolute time but how many ticks after the previous node it expires (the delta). The delta of the first node is relative to the current time.

(c) timer list: current time 4200Now4200Next signalin 3 ticks+3t = 4203+4t = 4207+6t = 4213+2t = 4215+1t = 4216delta list: on each tick only the counter at the head is decremented
Figure 11.31: The current time is 4200; pending signals are at 4203, 4207, 4213, 4215, and 4216. The list stores only the differences: 3, 4, 6, 2, 1.

The advantage of this arrangement is in the tick handler: on each tick only the counter at the head is decremented. When the head delta reaches 0, the event fires and the node is removed from the list. No matter how many timers are in the list, the work per tick is O(1). The cost is in insertion: finding the place of a new timer means walking the list, which takes O(n).

11.8.4Code trace: add and tick

void add(Timer *z, int t) {  /* t: ticks */
  Timer **p = &head;
  while (*p && (*p)->delta <= t) {
    t -= (*p)->delta;
    p = &(*p)->next;
  }
  z->delta = t; z->next = *p;
  if (*p) (*p)->delta -= t;
  *p = z;
}
void tick(void) {
  if (head) head->delta--;
  while (head && head->delta == 0)
    head = run(head);   /* remove */
}

add inserts a new timer into the list for t ticks from now. p is a pointer to a pointer: first it points to the list head (&head), then at each step to the next field of the previous node. This way insertion at the head and insertion in the middle need not be written separately. The loop subtracts the delta of each node it passes from t; t now means “how many ticks after that node”. The loop stops when it reaches a node whose delta is larger than t. The new node goes in there, and the delta of the node behind it is reduced by t; so the absolute time of the node behind does not change. tick, for its part, decrements only the delta at the head, and runs and removes, in order, every node whose delta is 0. Of two timers that expire at the same moment, the second has delta 0; that is why the while loop is there.

Example 11.10

The list is A 3, B 4, C 6, D 2, E 1 (absolute times 4203, 4207, 4213, 4215, 4216). At time 4200, timer X is inserted for 10 ticks later (4210): add(X, 10). Then three ticks pass.

  1. A. A's delta 3 ≤ 10: X comes after it. t = 10 − 3 = 7; *p moves to B.
  2. B. B's delta 4 ≤ 7: X comes after that one too. t = 7 − 4 = 3; *p moves to C.
  3. C. C's delta 6 > 3: X must go in before C; the loop ends.
  4. Insertion. X goes in with delta = 3; C's delta becomes 6 − 3 = 3. The list is A 3, B 4, X 3, C 3, D 2, E 1. C's absolute time is 4203 + 4 + 3 + 3 = 4213, that is, unchanged. Only one node was updated.
  5. Ticks. On the first two ticks only A's delta decreases: 2, then 1. On the third tick (4203) the delta becomes 0; A is run and removed from the list. The list is B 4, X 3, C 3, D 2, E 1.
now = 4200in box: delta from previous eventA34203B44207X34210C34213D24215E14216*pbelow: absolute event time
now = 4203in box: delta from previous eventB44207X34210C34213D24215E14216below: absolute event time
Figure 11.32: On the left, after X is inserted: A 3, B 4, X 3, C 3, D 2, E 1. On the right, after A leaves at 4203: the list starts at B.
Example 11.11

The current tick is 8000; alarms are at 8002, 8006, 8006, 8011, and 8020. What is the delta list? Which alarms have fired after 8 ticks?

  1. Deltas. 8002 − 8000 = 2, 8006 − 8002 = 4, 8006 − 8006 = 0, 8011 − 8006 = 5, 8020 − 8011 = 9. The list is 2, 4, 0, 5, 9.
  2. First alarm. After 2 ticks the delta at the head becomes 0: the alarm at 8002 fires.
  3. Simultaneous alarms. After 4 more ticks (8006) the delta at the head becomes 0. The loop removes this node; since the delta of the node behind it is also 0, it removes that one too. The two alarms at 8006 fire together.
  4. Remaining. By 8008 two more ticks have passed: the delta at the head is 5 − 2 = 3. The list is 3, 9 (8011 and 8020).

11.8.5Terminals, input devices, and power management

Terminals. In Unix there is a line discipline between the terminal driver (tty) and the application. In canonical mode the line discipline edits the line: backspace and line kill are handled there, and the line is delivered to the application only when Enter is pressed. In raw mode every key goes to the application immediately; text editors use this mode (stty -icanon). Terminal emulators and ssh sessions use a pseudo-terminal (pty). Screen control is done with ANSI escape sequences that move the cursor or change the color.

Keyboards and input devices. A keyboard sends scan codes, not characters: pressing and releasing each key are separate codes. The driver translates them into characters using a key map. This is why the Shift key is a separate event. USB keyboards and mice (HID devices) do not raise interrupts; the host polls them 125–1000 times per second. On Linux, input events travel from the input subsystem to the /dev/input/event* files (evdev), from there to libinput and the Wayland compositor, and finally to the window.

Power management. ACPI defines sleep states for the system: S0 is the working state (S0ix is modern standby), S3 is suspend to RAM, S4 is hibernation to disk, and S5 is off. The processor has two separate settings. C-states determine how deeply it sleeps when idle, and P-states determine which frequency and voltage are used while it runs; on Linux the schedutil governor chooses the P-states. Devices also have states between D0 (on) and D3 (off). Runtime power management puts an unused device to sleep while the system is running: APST on NVMe, ASPM on PCIe, Wi-Fi power saving, and screen dimming are examples. The operating system must put devices to sleep and wake them in the right order and decide which devices (keyboard, network, clock) may wake the system. The battery life of a laptop depends largely on how little power it draws during idle time.

11.9Disks

11.9.1Magnetic disk geometry

top viewsectortrackside viewcylinderarmspindleheadzoned recording (ZBR)32 sectors/track24 sectors/track16 sectors/trackvirtual geometry: flat LBA 0 … N−1
Figure 11.33: A hard disk: platters, tracks, sectors, a cylinder, read-write heads, and the arm. On the right, zoned bit recording (ZBR): the outer zones have more sectors per track; the operating system sees this as a flat array of LBAs.
Definition 11.23

A hard disk (HDD) consists of one or more magnetic platters spinning on the same spindle. Each surface has a read-write head; the heads move together on a common arm. The concentric rings on a surface are called tracks, the pieces of a track sectors, and the set formed by the tracks at the same radius on all surfaces a cylinder.

Platters spin at 5400–7200 rpm in desktop disks and 10,000–15,000 rpm in server disks. Because the outer tracks are longer, the outer zones have more sectors per track. This is called zoned bit recording; the disk transfers faster on the outer tracks.

The operating system no longer sees this geometry today. Disks used to be addressed with cylinder-head-sector (CHS) triples. Today the operating system sees only an LBA (logical block address), that is, blocks numbered from 0 to N − 1. The controller inside the disk translates the LBA to the real geometry, spare sectors, and its own cache by itself. The limit of the old CHS interface was 1024 cylinders × 255 heads × 63 sectors × 512 B ≈ 8.4 GB.

11.9.2Access time

Definition 11.24

The access time of a disk request is the sum of three components. Seek time is the time for the arm to reach the right cylinder. Rotational latency is the wait for the desired sector to come under the head; its average is half a revolution. Transfer time is the time for the data to pass under the head.

seek: the arm changes cylindersrotationred: the head's cylinder
Figure 11.34: A seek is the arm changing cylinders; rotational latency is the platter bringing the desired sector under the head.
Example 11.12

A disk spins at 7200 rpm; the average seek time is 8 ms and the media transfer rate is 200 MB/s. How long does it take to read a random 4 KiB block?

  1. One revolution. 60,000 ms / 7200 = 8.33 ms.
  2. Rotational latency. On average the desired sector is half a revolution away: 8.33 / 2 = 4.17 ms.
  3. Transfer. 4096 B / (200 × 106 B/s) = 0.020 ms.
  4. Total. 8 + 4.17 + 0.02 = 12.19 ms. The transfer time, however small, is one of the three components and must be counted.
seek 8 msrotation 4.17 mstransfer 0.02 ms ← (0.2%)total 12.19 ms
Figure 11.35: In a random 4 KiB read: seek (8 ms), rotational latency (4.17 ms), and transfer (0.02 ms; 0.2% of the total).

The conclusion is clear: the time is spent almost entirely on mechanical movement. In these 12 ms the CPU can execute tens of millions of instructions; the operating system does not wait but runs another process. The same disk gives very different speeds depending on the access pattern:

  • Random 4 KiB. 1000 / 12.19 ≈ 82 requests per second (IOPS) can be served. That comes to 82 × 4096 B ≈ 0.34 MB/s.
  • Sequential 1 MiB. The transfer takes 1,048,576 / (200 × 106) = 5.24 ms; the total is 8 + 4.17 + 5.24 = 17.41 ms. The rate is 1,048,576 B / 17.41 ms ≈ 60 MB/s.

These calculations make two simplifications: the media rate is taken as constant, and the seek and rotational latency are paid again for each piece. In a real long sequential read, the seek is made only once at the start; the following blocks pass under the head without interruption and the rate approaches the media rate (here 200 MB/s).

The same disk is about 180 times faster on a large sequential read than on small random reads. The effort of file systems to place blocks close together, and the importance of disk-arm scheduling, come from this gap. For comparison: a 4 KiB random read on an NVMe SSD takes 50–100 µs, and with parallel queues more than a million requests per second can be served.

Example 11.13

A server disk spinning at 15,000 rpm has an average seek time of 3.5 ms and a media rate of 250 MB/s (1 MB = 106 B). How long does a 64 KiB sequential read take, and how long does reading 16 scattered 4 KiB blocks take?

  1. Revolution and rotation. 60,000 / 15,000 = 4 ms; the average rotational latency is 2 ms.
  2. 64 KiB sequential. The transfer is 65,536 / (250 × 106) s = 0.262 ms; the total is 3.5 + 2 + 0.262 ≈ 5.76 ms.
  3. 16 × 4 KiB scattered. Per block 3.5 + 2 + 0.016 = 5.516 ms; 16 blocks take 16 × 5.516 ≈ 88.3 ms. The same data is read about 15 times slower.
  4. Does a faster medium help? If the media rate doubled, the transfer share in the scattered read would drop from 16 × 0.016 = 0.26 ms to 0.13 ms: a gain of only 0.15% of the total. In a small random read, seek and rotation dominate the time.

11.9.3Formatting and cylinder skew

A disk must be formatted at two levels before it can be used. Low-level formatting is done at the factory. Tracks and sectors are written onto the surface; each sector gets a preamble, a data field, and an ECC, and spare sectors are set aside. This is why formatted capacity is less than raw capacity. High-level formatting writes an empty file system to a partition: a boot block, free-space management structures, and the root directory.

sector format (low-level format)preambledata 512 B / 4 KiBECCskew: sector 0 must not be missed when moving between trackstrack 00123456789101112131415track 11314150123456789101112track 21011121314150123456789
Figure 11.36: Sector format and cylinder skew. Sector 0 of each track is shifted relative to the previous one; sector 0 is not missed while the head changes tracks.
Definition 11.25

Cylinder skew is the shifting of the sector 0 positions of successive tracks relative to one another. While the head finishes one track and moves to the next, the disk keeps rotating; the shift ensures that when the head arrives at the new track, sector 0 is just about to arrive.

Example 11.14

A disk spins at 10,000 rpm and has 300 sectors per track. A track switch takes 800 µs. How many sectors should the skew be?

  1. Revolution. 60,000 / 10,000 = 6 ms.
  2. Sector time. 6 ms / 300 = 20 µs.
  3. Skew. During the track switch 800 / 20 = 40 sectors pass under the head. Sector 0 of the next track must be shifted by 40 sectors.

In the past, interleaving was also used for slow controllers: so that the next sector would not pass under the head and be missed while the controller transferred one sector to memory, consecutive sectors were laid out on the track with gaps between them. Today the controller reads the whole track into its own buffer, so interleaving is unnecessary.

11.9.4Optical discs

On optical discs the data lies along a single spiral track running from the inside out, instead of the concentric tracks of a magnetic disk. The track has pits and lands; each transition between a pit and a land stands for a 1 bit, and no transition for a 0. On pressed discs the pits are stamped into the polycarbonate with a mold, not burned with a laser. On recordable CD-R and DVD-R discs, the laser heats a layer of organic dye and changes its reflectivity.

optical: one spiralmagnetic: concentric
Figure 11.37: On an optical disc the data lies along a single spiral track; on a magnetic disk it lies in concentric tracks.
Table 11.8: Generations of optical discs.
CD (1982)DVD (1996)Blu-ray (2006)
Capacity650–700 MB4.7 / 8.5 / 9.4 / 17 GB25 / 50 GB; BDXL 100–128 GB
Laser780 nm (infrared)650 nm (red)405 nm (blue-violet)
Smallest pit0.83 µm0.40 µm0.15 µm
Track pitch1.6 µm0.74 µm0.32 µm

As in Table 11.8, the capacity growth between generations comes from the shortening of the laser wavelength: a shorter wavelength focuses to a smaller spot, and the pits and track pitch shrink. The coding of the CD-ROM is interesting too. Each byte is converted to a 14-bit channel symbol by EFM (eight-to-fourteen modulation). This is a modulation code, not an error-correcting code; error correction is done with CIRC. Each of 98 frames carries 24 data bytes, forming a sector of 98 × 24 = 2352 B. In Mode 1, 2048 B of this is user data; the rest is synchronization, header, and additional ECC/EDC fields.

In the dual-layer versions of DVD, the upper layer is semitransparent; the laser reads the layer underneath by changing its focus. Optical media are mostly used today for archiving and distribution; they lag behind magnetic and flash media in density.

11.10Disk-arm scheduling

11.10.1Goal and criterion

The access-time example showed that most of the time of a disk request goes to seek and rotation. If many requests are waiting at the disk at the same time, the order in which they are served determines how far the arm travels.

Definition 11.26

Disk scheduling aims to reduce arm movement (and therefore seek time) and raise throughput by choosing the order in which pending disk requests are served. For each request the driver keeps the cylinder number and the arrival time. The criterion used to compare algorithms is the head's total movement in cylinders.

It must be said up front that this model is a simplification. Today the mapping of LBA to physical location is inside the disk; the operating system does not know the cylinders. The disk also reorders 32 requests by itself according to rotational position using NCQ (native command queuing). The operating system therefore schedules approximately by “LBA proximity”: it assumes that blocks with nearby numbers are also near each other on the disk.

0143753656798122124183199total: 0 cylindersservedwaiting
Figure 11.38: The common queue: the head is at cylinder 53; the pending requests are 98, 183, 37, 122, 14, 124, 65, 67. Cylinders 0–199.

To compare the algorithms, we will give all of them the same queue. In Silberschatz's classic example the cylinders range from 0 to 199, the head is at 53, and the requests in arrival order are 98, 183, 37, 122, 14, 124, 65, 67 (Figure 11.38). Table 11.9 summarizes the essence of the algorithms in advance.

Table 11.9: Disk-arm scheduling algorithms.
AlgorithmIdeaProblem
FCFSArrival orderFair, but the arm travels a lot
SSTFRequest closest to the head (greedy)Requests at the edges may starve
SCAN (elevator)Go to the end in one direction, then reverseThe edges and the middle do not wait equally
C-SCANSweep in one direction, jump from the end to the startThe return movement is wasted
LOOK / C-LOOKSCAN / C-SCAN, but only as far as the last requestThe forms used in practice

11.10.2FCFS

Definition 11.27

FCFS (first-come, first-served) serves requests in the order they arrive.

Example 11.15

What is the total head movement of FCFS on the common queue?

  1. 53 → 98: 45 cylinders; total 45.
  2. 98 → 183: 85; total 130.
  3. 183 → 37: 146; total 276.
  4. 37 → 122: 85; total 361.
  5. 122 → 14: 108; total 469.
  6. 14 → 124: 110; total 579.
  7. 124 → 65: 59; total 638.
  8. 65 → 67: 2; total 640 cylinders.
0143753656798122124183199total: 640 cylindersservedwaiting
Figure 11.39: The head's path under FCFS: 53, 98, 183, 37, 122, 14, 124, 65, 67. Total 640 cylinders.

FCFS is fair and causes no starvation: every request is certainly served once those before it finish. But back-and-forth movements such as 122 → 14 → 124 are very expensive. The arm goes from one end of the disk to the other and back twice; the two requests to 14 and 124 alone consume 218 cylinders.

11.10.3SSTF

Definition 11.28

SSTF (shortest seek time first) picks, at each step, the pending request closest to the head.

Example 11.16

What order does SSTF follow on the common queue, and what is the total movement?

  1. Head at 53: the candidates are 65 (12 away) and 37 (16 away). 53 → 65: 12; total 12.
  2. 65 → 67: 2; total 14.
  3. Head at 67: 37 (30 away) is closer than 98 (31 away). 67 → 37: 30; total 44.
  4. 37 → 14: 23; total 67.
  5. The lower region is done. 14 → 98: 84; total 151.
  6. 98 → 122: 24; total 175.
  7. 122 → 124: 2; total 177.
  8. 124 → 183: 59; total 236.
0143753656798122124183199total: 236 cylindersservedwaiting
Figure 11.40: The head's path under SSTF: 53, 65, 67, 37, 14, 98, 122, 124, 183. Total 236 cylinders.

236 is about 37% of FCFS's 640. But SSTF is greedy and does not guarantee the best result. If the head had gone down first, the order would have been 53 → 37 → 14 → 65 → 67 → 98 → 122 → 124 → 183. The total comes to 16 + 23 + 51 + 2 + 31 + 24 + 2 + 59 = 208. In SSTF, the short 30-cylinder step at the third move led to an 84-cylinder turnaround afterward.

Common mistake

Thinking SSTF is the best algorithm. SSTF chooses the shortest move at each step, but it does not minimize the total movement; on the common queue it makes 236, while the best order is 208. The more important problem is fairness. Suppose that under heavy load requests keep arriving in the middle region of the disk: the head stays in the middle, and a request at cylinder 190 may wait for minutes. This is a case of starvation. FCFS and the sweep algorithms have no starvation.

11.10.4Code trace: sstf()

A C version of SSTF is below. The array done[] records which requests have been served.

int sstf(int head, int q[], int n) {
  int total = 0;
  for (int k = 0; k < n; k++) {
    int best = -1;
    for (int i = 0; i < n; i++)
      if (!done[i] && (best < 0 ||
        abs(q[i]-head) < abs(q[best]-head)))
        best = i;          /* closest */
    total += abs(q[best] - head);
    head = q[best];
    done[best] = 1;
  }
  return total;
}

The outer loop serves one request per iteration and takes n iterations. The inner loop looks at all pending requests; best is the index of the closest request found so far. The best < 0 || part of the condition makes the first pending request the candidate; later requests replace the candidate only if they are strictly closer. So if two requests are at equal distance, the one earlier in arrival order is chosen. At the end of the iteration the distance is added to total, the head moves to that request, and the request is marked done. Since n requests are scanned in each iteration, the algorithm uses O(n2) time and O(n) extra space for done[].

Table 11.10: Trace of sstf(). The head is at 50; the queue (arrival order) is 82, 170, 43, 140, 24, 16, 190.
kHeadClosest (distance)Next candidate (distance)total
05043 (7)24 (26)7
14324 (19)16 (27)26
22416 (8)82 (58)34
31682 (66)140 (124)100
482140 (58)170 (88)158
5140170 (30)190 (50)188
6170190 (20)—208
0501001501995043241682140170190total = 208 cylinders
Figure 11.41: The end of the sstf() trace: all requests are served, total = 208.

On this queue FCFS would spend 642 cylinders; SSTF falls below a third of that with 208. The k = 3 row shows the weak point of SSTF: when the requests below are finished, the arm travels back a long 66-cylinder stretch. If requests in the middle kept arriving, those at the edges could wait.

11.10.5SCAN (the elevator)

Definition 11.29

In the SCAN algorithm, the head moves in one direction to the end of the disk and serves the requests along its path; when it reaches the end it reverses and serves the requests in the other direction. Because it resembles an elevator going back and forth between the floors of a building, it is also called the elevator algorithm.

Example 11.17

On the common queue the head is moving toward 0 (downward). What is the total movement of SCAN?

  1. 53 → 37: 16; total 16.
  2. 37 → 14: 23; total 39.
  3. 14 → 0: 14; total 53. Even though no requests remain below, the head goes all the way to the end of the disk.
  4. The direction reverses. 0 → 65: 65; total 118.
  5. 65 → 67: 2; total 120.
  6. 67 → 98: 31; total 151.
  7. 98 → 122: 24; total 175.
  8. 122 → 124: 2; total 177.
  9. 124 → 183: 59; total 236.
0143753656798122124183199total: 236 cylindersservedwaiting
Figure 11.42: SCAN (downward): 53, 37, 14, 0, 65, 67, 98, 122, 124, 183. Total 236 cylinders.

On this queue SCAN gives the same total as SSTF but prevents starvation: the head serves every request along its path within one sweep. New requests that arrive ahead of the head are served in the same sweep, and those behind it on the return trip. The cost of going all the way to the end (14 → 0) is 14 wasted cylinders. The choice of direction also changes the result: on the same queue, if the head had started upward, the movement would have been 53 → 199 (146) and 199 → 14 (185), for a total of 331.

SCAN has a fairness flaw. When the head reaches one end and turns around, it has just served the region right behind it; few requests are waiting there. The place where requests are densest is the other end of the disk, and those requests have waited longest. The head passes the middle cylinders twice per round trip at equal intervals. The edge cylinders, however, it passes twice in quick succession, followed by a long gap. So requests that fall near the edges wait longer on average.

11.10.6C-SCAN

Definition 11.30

C-SCAN (circular SCAN) serves in one direction only. The head goes up to the end; on reaching the end it returns to the start of the disk (to 0) without serving, and begins sweeping upward again. The disk is viewed as a ring.

Example 11.18

What path does C-SCAN (upward) follow on the common queue? What is the total if the return movement is counted too?

  1. 53 → 65 → 67 → 98 → 122 → 124 → 183: 12 + 2 + 31 + 24 + 2 + 59 = 130.
  2. 183 → 199: 16; total 146. There are no requests above, but the head goes to the end.
  3. 199 → 0: the return, 199 cylinders, no service; total 345.
  4. 0 → 14: 14; total 359.
  5. 14 → 37: 23; total 382.
0143753656798122124183199total: 382 cylindersservedwaiting
Figure 11.43: C-SCAN (upward): 53 … 183, 199, return to 0, 14, 37. Total 382 if the return is counted, 183 cylinders if not.

If the return movement is not counted, the total is 382 − 199 = 183. Sources treat this differently; in an exam question it must be stated whether the return is counted. The return is in fact fast: the arm comes back in a single stroke without stopping at any sector. The gain of C-SCAN comes not from total movement but from fairness. Every request is served in the head's upward sweep, once; requests at the edge and in the middle wait about equally.

11.10.7LOOK and C-LOOK

Definition 11.31

LOOK works like SCAN but does not go to the end of the disk: it turns around at the last request in that direction. C-LOOK serves in one direction like C-SCAN but does not go to the end: after the last request above, it jumps directly to the smallest pending request.

Example 11.19

What is the total movement of LOOK (downward) and C-LOOK (upward) on the common queue?

  1. LOOK, down. 53 → 37 → 14: 16 + 23 = 39. No requests remain below; the head does not go to 0.
  2. LOOK, up. The direction reverses: 14 → 65 → 67 → 98 → 122 → 124 → 183: 51 + 2 + 31 + 24 + 2 + 59 = 169. The total is 39 + 169 = 208; 28 cylinders less than SCAN, because the 14 → 0 → 14 trip (2 × 14) is not made.
  3. C-LOOK, up. 53 → 65 … 183: 130.
  4. The jump. 183 → 14: 169 cylinders to the smallest pending request; the head does not go to 199 and 0. Total 299.
  5. The end. 14 → 37: 23; total 322. Without counting the jump, 322 − 169 = 153.
0143753656798122124183199total: 208 cylindersservedwaiting
0143753656798122124183199total: 322 cylindersservedwaiting
Figure 11.44: At the top, LOOK (downward): 53, 37, 14, 65 … 183; total 208. At the bottom, C-LOOK (upward): 53 … 183, jump to 14, 37; total 322 (153 no jump).

In practice, what is called “elevator” behavior is mostly LOOK; no real driver moves the arm to the end of the disk when there are no requests. Linux's old deadline and CFQ schedulers and today's mq-deadline dispatch requests in increasing LBA order and start over from the beginning after the highest LBA. This is behavior similar to C-LOOK.

11.10.8Code trace: look()

The version of LOOK that starts upward can be written with two loops over a sorted array:

/* s[] sorted; go up first, then down */
int look(int head, int s[], int n) {
  int i = 0, total = 0;
  while (i < n && s[i] < head) i++;
  for (int j = i; j < n; j++) {
    total += s[j] - head; head = s[j];
  }
  for (int j = i - 1; j >= 0; j--) {
    total += head - s[j]; head = s[j];
  }
  return total;
}

The first while loop finds the index (i) of the first request greater than or equal to the head. The first for loop advances upward from i to the end and adds up the distance of each step (s[j] - head). The second for loop descends from i - 1 to 0; this time the distance is head - s[j]. Because the head turns around after the last request above without going to the end, the code is LOOK, not SCAN. The function runs in O(n) when the array is given sorted; sorting takes O(n log n).

Table 11.11: Trace of look(). s = 16, 24, 43, 82, 140, 170, 190; the head is at 50, moving up.
StepjTargetMovementtotal
whilei = 3: the first request greater than 50 is s[3] = 82. The 16, 24, and 43 below it will be taken on the way back.
up382+3232
up4140+5890
up5170+30120
up6190+20140
down243+147287
down124+19306
down016+8314
0501001501995082140170190432416total = 314 cylinders
Figure 11.45: The end of the look() trace: total 314 cylinders.

On the same queue SSTF made 208; LOOK made 314. The difference comes from the choice of direction. If the head had started downward, LOOK would first have gone 50 → 16 (34 cylinders), then 16 → 190 (174 cylinders): 34 + 174 = 208. The choice of direction decides the result, but whichever direction is taken, no request starves.

11.10.9Comparing the algorithms

FCFS640SSTF236SCAN236C-SCAN382 (183 no jump)LOOK208C-LOOK322 (153 no jump)
Figure 11.46: Total head movement of the six algorithms on the common queue: FCFS 640, SSTF 236, SCAN 236, C-SCAN 382 (183 no jump), LOOK 208, C-LOOK 322 (153 no jump).

Figure 11.46 shows the results on the common queue together. Total movement alone is not enough to choose an algorithm. LOOK gives the least movement (208); SSTF and SCAN follow with 236, but SSTF can cause starvation. C-SCAN and C-LOOK travel farther but spread the waiting times more evenly. When the load is light, all algorithms behave like FCFS, because there is usually only one request in the queue at a time.

Example 11.20

Tanenbaum's example: the head is at cylinder 11, and the requests in arrival order are 1, 36, 16, 34, 9, 12. How many cylinders do FCFS, SSTF, and the elevator (upward) move?

  1. FCFS. 11 → 1 → 36 → 16 → 34 → 9 → 12: 10 + 35 + 20 + 18 + 25 + 3 = 111.
  2. SSTF. The order is 12, 9, 16, 1, 34, 36: 1 + 3 + 7 + 15 + 33 + 2 = 61. With the head at 9, 16 (7 away) is closer than 1 (8 away).
  3. Elevator, up. The order is 12, 16, 34, 36, 9, 1: 1 + 4 + 18 + 2 + 27 + 8 = 60.
  4. Interpretation. Tanenbaum's elevator turns around at the last request above (36) and does not go to the end; so it is actually LOOK.
Example 11.21

The cylinders are 0–199; the head is at 84 and moving upward because it last served 70. The requests in arrival order are 184, 142, 170, 8, 60, 155, 116, 37. What is the total movement of the six algorithms? Count the return trip in C-SCAN and C-LOOK.

  1. FCFS. 100 + 42 + 28 + 162 + 52 + 95 + 39 + 79 = 597.
  2. SSTF. 84 → 60 (24) → 37 (23) → 8 (29) → 116 (108) → 142 (26) → 155 (13) → 170 (15) → 184 (14): 252. At the start, 60 (24 away) is closer than 116 (32 away).
  3. SCAN. 84 → 116 … 184 → 199, then 60, 37, 8: (199 − 84) + (199 − 8) = 115 + 191 = 306.
  4. C-SCAN. 84 → 199 (115), 199 → 0 (199), 0 → 8 → 37 → 60 (60): 374. If the return is not counted, 175.
  5. LOOK. 84 → 184 (100), 184 → 8 (176): 276.
  6. C-LOOK. 84 → 184 (100), jump 184 → 8 (176), 8 → 60 (52): 328. If the jump is not counted, 152.
  7. Ranking. SSTF 252 < LOOK 276 < SCAN 306 < C-LOOK 328 < C-SCAN 374 < FCFS 597. LOOK differs from SCAN only in not going needlessly to the end (199).

11.10.10SPTF: counting rotational delay too

All the algorithms so far looked only at cylinder distance. Yet the time of a request is determined by seek and rotation together. If a nearby sector has just passed under the head, serving it means waiting almost a full revolution.

Definition 11.32

SPTF (shortest positioning time first) chooses, among the pending requests, the one for which the sum of seek time and rotational latency is smallest.

rotationhead: track 10A (track 11)B (track 30)7200 rpm: 1 revolution = 8.33 ms, the disk turns 43.2° in 1 msA: seek 1 ms, the sector arrives at the head 30° laterB: seek 3 ms, the sector arrives at the head 150° later0246810msSSTF → A9.03 msSPTF → B3.47 msseekrotational wait
Figure 11.47: The head is at track 10. A (track 11) is near, but its sector is 30° ahead; B (track 30) is far, but its sector is 150° ahead. SSTF chooses A and spends 9.03 ms; SPTF chooses B and spends 3.47 ms.
Example 11.22

A disk spins at 7200 rpm. The head is at track 10. Request A is on track 11: seek 1 ms, and its sector is 30° ahead of the head in the direction of rotation. Request B is on track 30: seek 3 ms, and its sector is 150° ahead. Which do SSTF and SPTF choose, and how long does it take?

  1. Rotation speed. One revolution is 60,000 / 7200 = 8.33 ms; the disk turns 360 / 8.33 = 43.2° in 1 ms.
  2. SSTF → A. In the 1 ms seek the disk turns 43.2°. The sector was 30° ahead; when the seek ends it has passed the head by 13.2°. To bring the sector around again, 360 − 13.2 = 346.8° must be waited: 346.8 / 43.2 = 8.03 ms. Total 1 + 8.03 = 9.03 ms.
  3. SPTF → B. In the 3 ms seek the disk turns 129.6°; 150 − 129.6 = 20.4° remain to B. The wait is 20.4 / 43.2 = 0.47 ms. Total 3 + 0.47 = 3.47 ms.
  4. Result. The far track gave its result 9.03 / 3.47 ≈ 2.6 times sooner than the near track.

SPTF minimizes positioning time, but the operating system does not know the angular positions of sectors. So SPTF is implemented inside the disk, with NCQ. SPTF is prone to starvation just like SSTF. One method used against starvation is F-SCAN: when a sweep begins, the queue is frozen; new requests that arrive during the sweep wait for the next sweep. This way the old requests cannot be left behind by a constant stream of new requests being dumped in front of the head.

11.10.11The controller cache and bad sectors

The controller cache. The disk keeps a track cache in its own DRAM (about 256 MB). It also reads blocks that pass under the head and have not yet been requested; the next sequential request is served directly from the cache. This cache is separate from the operating system's page cache.

Write cache and NCQ. The disk can take a write into its cache and immediately say “done”. The data has not yet reached the platter; if power is cut, it is lost. When durability is needed, the operating system uses the FLUSH command or a write with the FUA (force unit access) flag. NCQ orders the 32 queued requests by rotational position; this is an SPTF inside the hardware.

Bad sectors. Data written to a sector that goes bad during manufacture or use cannot be read back. The controller tracks the list of bad sectors found at the factory and those it finds in use. The “Reallocated Sectors” count in the SMART data shows the size of this list. A bad sector has two remedies (Figure 11.48).

(b) the bad sector is mapped to a spare01234567 ✗891011121314157Y2the controller redirects
(c) sectors are shifted, the bad one skipped0123456✗789101112131415Y2sectors 8 … 15 shift by one, one spare used; sequential reads are not disturbed
Figure 11.48: Two ways to handle bad sector 7. At the top, sector 7 is mapped to a spare. At the bottom, sectors 8–15 are shifted by one and one spare is used; sequential reads are not disturbed.
  1. Remapping to a spare. The bad sector is mapped to a spare sector at the end of the track. It is simple, but a sequential request reading sectors 6, 7, 8 has to go to the end of the track and back for 7, and may pay an extra revolution.
  2. Shifting. All sectors after the bad one are shifted by one. The whole track must be rewritten, but the order is preserved.

The operating system can keep a bad-block list too: on Linux the badblocks tool and the bad-block lists of file systems exist for this purpose. On today's disks, remapping is done entirely inside the disk, so this list often stays empty.

11.11SSDs and NVMe

11.11.1NAND flash

Definition 11.33

An SSD (solid-state drive) is a storage device with no moving parts that keeps data in NAND flash memory chips. The unit of reading and writing in flash is the page (about 16 KiB), and the unit of erasure is the block, made up of many pages (about 10–40 MiB).

SSD controllerFTLECC (LDPC)DRAM cachediediediediediediediediediediediedie4–8 channels × dies: parallelismblock (≈ 10–40 MiB) = erase unitpage (≈ 16 KiB) = read/write unit
Figure 11.49: SSD internals: the controller (FTL, LDPC error correction, DRAM cache) connects to the NAND dies over 4–8 channels. Channels and dies work in parallel.

An SSD differs from a hard disk in two basic ways. First, with no moving parts there is no seek or rotational latency. Random access is about as fast as sequential access. Second, flash has no in-place update. A page can be written only when it is in the erased state, and erasing is done only at block level. In addition, the number of erasures each cell can withstand is limited. This number is called the P/E (program/erase) cycle count, and it depends on how many bits a cell stores (Table 11.12).

Table 11.12: NAND cell types.
CellBits/cellTypical P/E cyclesUse
SLC1≈ 50–100 thousandcache region, industrial
MLC2≈ 3–10 thousandolder enterprise
TLC3≈ 1–3 thousandmost consumer and server SSDs
QLC4≈ 0.1–1 thousandhigh capacity, read-heavy

As the bits per cell increase, the number of voltage levels the cell must distinguish grows as 2, 4, 8, 16. As the levels get denser, reads slow down and the cell wears out faster. The other way to raise capacity is vertical stacking: today's 3D NAND chips have more than 200–300 layers. The price gap per GB between SSDs and HDDs has narrowed; still, HDDs are cheaper for large capacity and archives.

11.11.2The FTL, garbage collection, TRIM, and wear leveling

If in-place update is impossible, how is the operating system's request “overwrite LBA 1” satisfied? The answer is a translation layer in the SSD controller.

Definition 11.34

The flash translation layer (FTL) is controller software that maps logical block addresses (LBAs) to physical flash pages. Updated data is written to a new free page, the mapping table is changed, and the old page is considered invalid. This is called an out-of-place update.

Example 11.23

In a small SSD with two blocks (B0, B1) of four pages each, the following operations are performed: LBAs 0, 1, 2 are written; LBA 1 is rewritten; the file holding LBA 2 is deleted; LBA 3 is written. Then B0 is cleaned.

  1. First writes. The FTL puts the data of the three LBAs into the free pages of B0 (s0, s1, s2) and records them in the table.
  2. Update. LBA 1 is rewritten. The old page cannot be overwritten; the new data goes to B0.s3 and B0.s1 becomes invalid.
  3. TRIM. When the file is deleted, the file system sends a TRIM command (Deallocate in NVMe). The SSD learns that the page of LBA 2 is no longer needed and marks it invalid.
  4. Block full. B0 has no free pages left; LBA 3 is written to B1. Half of B0 is invalid.
  5. Garbage collection. The valid pages in B0 (LBA 0 and LBA 1) are copied to B1 and B0 is erased. Two extra page writes that the user did not ask for have been made; this is called write amplification.
mapping table (FTL)LBA 0B0.s0LBA 1B0.s3LBA 2—LBA 3B1.s0block B0 (erases: 0)s0valid: LBA 0s1invalid (old LBA 1)s2invalid (old LBA 2)s3valid: LBA 1block B1 (erases: 0)s0valid: LBA 3s1frees2frees3freeB0 full: LBA 3 → B1only an erased (free) page can be written; erasure is at block level
mapping table (FTL)LBA 0B1.s1LBA 1B1.s2LBA 2—LBA 3B1.s0block B0 (erases: 1)s0frees1frees2frees3freeblock B1 (erases: 0)s0valid: LBA 3s1valid: LBA 0s2valid: LBA 1s3freewear leveling: lightly erased blocks are used tooonly an erased (free) page can be written; erasure is at block level
Figure 11.50: Two moments of the FTL. At the top, B0 is full and half of it is invalid; LBA 3 has been written to B1. At the bottom, after garbage collection: the valid pages have been moved to B1, and B0 is erased (erase count 1).

Without TRIM, the SSD would still consider the pages of a deleted file valid and would needlessly copy them during garbage collection too. Write amplification would rise, and both performance and lifetime would drop.

Definition 11.35

Wear leveling is the FTL policy that makes all flash blocks be erased roughly the same number of times. New writes are steered to lightly erased blocks; data that stays unchanged for a long time (cold data) is also moved occasionally so that the blocks it occupies can be used as well.

Without wear leveling, a few frequently updated blocks would wear out quickly, while the rest would stay almost unused. SSDs also set aside a spare area that is not shown to the user (over-provisioning). The spare area makes it easier for garbage collection to always find an empty block and reduces write amplification.

Common mistake

Defragmenting an SSD like a hard disk. On an SSD, having a file's pieces side by side brings no speedup, because there is no seek; defragmentation only adds needless writes and wear. The “Optimize” command in Windows does not defragment an SSD; it sends TRIM. What matters instead is aligning partitions to a 1 MiB boundary: logical blocks then sit on flash pages without being split, and a single write does not spill over into two pages.

11.11.3NVMe and multiple queues

Definition 11.36

NVMe (NVM Express) is a command protocol designed for flash storage attached over PCIe. Each core can be given its own pair of submission (SQ) and completion (CQ) queues; the queues are circular buffers that live in memory.

Core 0SQCQCore 1SQCQCore 2SQCQCore 3SQCQNVMe controller (PCIe x4)AHCI (SATA)one queue · 32 commands · lockNVMe65,535 queues × 65,536 commandsa queue per core: lock-free submission
Figure 11.51: In NVMe each core has its own SQ/CQ pair and submission is lock-free. AHCI (SATA) has a single queue and 32 commands; all cores share the same lock.

SATA and its AHCI interface were designed for spinning disks. It has a single queue and at most 32 commands; this limit was enough for a hard disk, because the disk carries out only one request at a time anyway. Flash, on the other hand, can run hundreds of jobs in parallel across channels and dies. NVMe exposes this parallelism: it defines 64 K queues and 64 K commands per queue. Because each core writes to its own queue, there is no lock contention among cores; the completion interrupt also reaches the same core through MSI-X.

A few terms are often confused. NVMe is a protocol; M.2 is a card form (a form factor). An M.2 card can also be SATA. U.2/U.3 and E1.S/E3.S are cabled or slotted forms used in servers. NVMe driver support has been built into all common operating systems since 2013; the incompatibility with AHCI is only at the protocol level. Latency on NVMe disks is between 10 and 100 µs; PCIe 5.0 x4 disks deliver about 14 GB/s and more than 2 million requests per second. NVMe-oF carries the same protocol over the network; ZNS (zoned namespaces) exposes the block structure of flash directly to software.

11.11.4Linux blk-mq and I/O schedulers

CPU 0software q.CPU 1software q.CPU 2software q.CPU 3software q.scheduler (optional)hw 0hw 1hw 2hw 3hardware submission queuesNVMe
Figure 11.52: Linux blk-mq: per-CPU software queues, an optional scheduler, and the device's hardware submission queues.

Linux's block layer follows NVMe's multi-queue model. blk-mq (the multi-queue block layer) gives each CPU a software queue and maps them to the device's hardware queues. In the old single-queue design, at millions of IOPS all cores would wait on the same queue lock; blk-mq removes this contention. In Linux 5.0 the old single-queue block layer and its schedulers (noop, deadline, CFQ) were removed entirely. Today's I/O schedulers are summarized in Table 11.13.

Table 11.13: Linux blk-mq I/O schedulers.
SchedulerIdeaSuited for
noneNo ordering, dispatch directlyNVMe (default), fast SSDs
mq-deadlineSorted by LBA + read/write deadlineSATA HDD/SSD (default in most distributions)
bfqPer-process budget, fair sharingDesktop, interactivity on slow devices
kyberLimits read/write latency with targetsFast multi-queue devices

A device's scheduler is read and changed through sysfs:

$ cat /sys/block/nvme0n1/queue/scheduler
[none] mq-deadline kyber bfq
$ echo bfq | sudo tee /sys/block/sda/queue/scheduler

The name in square brackets is the active scheduler; on an NVMe disk this is none. The second command sets the scheduler of a SATA disk to bfq. sudo tee is used because the redirection (>) would be performed outside sudo, with the user's own privileges.

Why is no sorting done at all on NVMe? The reason arm scheduling exists is to reduce seek time. An SSD has no seek, and access time is almost independent of position. Multiple hardware queues already give every core a parallel path. Sorting only spends CPU and adds latency. On an SSD the scheduler's job is not to sort but, when needed, to preserve fairness and latency targets; for that, mq-deadline, bfq, or kyber can be chosen.

11.12RAID and stable storage

11.12.1RAID: combining disks

Definition 11.37

RAID (Redundant Array of Independent Disks) is an arrangement that presents many disks to the operating system as a single disk. Striping distributes consecutive blocks across different disks to provide parallelism. Mirroring keeps a copy of every block on another disk. Parity stores the XOR of several blocks in a separate block so that a lost block can be recomputed.

The idea of RAID goes back to the 1988 paper by Patterson, Gibson, and Katz. The paper proposed building an array out of inexpensive disks instead of a single large expensive disk (SLED). That is why the “I” in the acronym originally stood for inexpensive. Today it is read as “independent”. The standard levels are 0 through 6. RAID can be built with a hardware card or in software: mdadm on Linux, RAID-Z in ZFS, Btrfs, and Windows Storage Spaces are examples of software RAID.

RAID 0: stripingdisk 0A0A2A4A6disk 1A1A3A5A7RAID 1: mirroringdisk 0A0A1A2A3disk 1A0A1A2A3parallel, no redundancyevery block twice
Figure 11.53: RAID 0 distributes consecutive blocks (A0, A1, …) across the disks in turn: parallel but with no redundancy. RAID 1 writes every block to two disks at once.
Table 11.14: RAID layouts with four 4 TB disks.
LayoutUsableToleratesCost of a small random write
RAID 0 (striping)16 TB0 disks1 I/O
RAID 1 (4-way mirror)4 TB3 disks4 I/Os (one to each copy)
RAID 10 (mirror + stripe)8 TB1 (2 if in different pairs)2 I/Os
RAID 5 (distributed parity)12 TB1 disk4 I/Os (2 reads + 2 writes)
RAID 6 (double parity)8 TB2 disks6 I/Os (3 reads + 3 writes)
Common mistake

Treating RAID as a backup. RAID protects against disk failure, but not against user error, software bugs, or ransomware. A deleted file is deleted on all disks at the same time; a corrupted file is corrupted in every copy. A backup is a copy made on a separate medium and at a separate time.

11.12.2RAID levels

RAID 0: striping, no redundancydisk 0s0s4s8s12disk 1s1s5s9s13disk 2s2s6s10s14disk 3s3s7s11s15
RAID 5: parity rotates across disksdisk 0s0s4s8s12disk 1s1s5s9P3disk 2s2s6P2s13disk 3s3P1s10s14disk 4P0s7s11s15
RAID 6: P and Q parity are distributeddisk 0Q0s3s6s9disk 1s0s4s7P3disk 2s1s5P2Q3disk 3s2P1Q2s10disk 4P0Q1s8s11
Figure 11.54: At the top, RAID 0: stripes (s0, s1, …) are spread over four disks in turn. In the middle, RAID 5: the parity blocks (P) sit on a different disk in each stripe. At the bottom, RAID 6: the P and Q parities are distributed over five disks.
  • RAID 0. Consecutive stripes go to different disks. On large requests, n disks give n times the bandwidth. There is no redundancy: if one disk fails, everything in the array is lost.
  • RAID 1. Every write is done twice. A read can be served from either disk; the load is spread across the disks. Half of the capacity goes to redundancy.
  • RAID 10. Mirror first, then stripe. Writes are fast, and a failed disk is rebuilt quickly by copying from its mirror alone. It is common in databases.
  • RAID 2 and 3. RAID 2 uses a Hamming code at the word level, and RAID 3 uses a single parity disk at the byte level. Both levels require all disks to spin in lockstep. They are not used today, because disks already do ECC internally.
  • RAID 4. Block-level striping and a separate parity disk. Every small write updates the parity disk too; the parity disk becomes a bottleneck.
  • RAID 5. Parity blocks are rotated across the disks and the bottleneck disappears. The capacity of n − 1 of the n disks is usable; it tolerates the loss of one disk.
  • RAID 6. It keeps two parities: P (XOR) and Q (a Reed–Solomon code over the field GF(28)). It tolerates the loss of two disks. Because rebuilding takes hours on large disks, it is preferred to guard against a second failure during that time.

11.12.3Parity and XOR

The foundation of parity is the XOR (⊕) operation. If two bits differ, XOR gives 1; if they are the same, 0. On bit strings, XOR is applied separately at each bit position. Three properties of the operation carry all of RAID's calculations: x ⊕ x = 0, x ⊕ 0 = x, and the operation is commutative and associative.

Theorem 11.1 (Recovery with parity)

Let P = D0 ⊕ D1 ⊕ … ⊕ Dn−1. Any block Dk whose loss is known equals the XOR of the remaining data blocks and P: Dk = P ⊕ (the XOR of all Di other than k).

XOR both sides of the definition of P with all the blocks other than Dk. Each Di (i ≠ k) appears twice on the right side and vanishes because x ⊕ x = 0; only Dk is left. A single parity suffices because we know which disk has failed: the disk either does not respond at all or reports an ECC error. Parity does not find the bad block; it only recomputes a block whose location we already know.

Example 11.24

In a RAID 5 stripe, D0 = 1011 0010, D1 = 0101 1100, D2 = 1110 0111 (8-bit sample blocks). What is the parity? If disk 1 fails, how is D1 found? If 0000 1111 is written in place of D1, what is the new parity?

  1. Parity. D0 ⊕ D1 = 1110 1110; ⊕ D2 = 0000 1001. P = 0000 1001. The number of 1s at each bit position is now even.
  2. Recovery. D1 = D0 ⊕ D2 ⊕ P = 1011 0010 ⊕ 1110 0111 ⊕ 0000 1001. The first two give 0101 0101, and with P this gives 0101 1100: the original D1. All stripes are rewritten onto the new disk this way; this is called rebuilding.
  3. Small write. D1' = 0000 1111. The old D1 and old P are read. P' = P ⊕ D1 ⊕ D1' = 0000 1001 ⊕ 0101 1100 ⊕ 0000 1111 = 0101 1010. Then D1' and P' are written: 4 I/Os (read-modify-write).
  4. Check. D0 ⊕ D1' ⊕ D2 = 1011 0010 ⊕ 0000 1111 ⊕ 1110 0111 = 0101 1010 = P'. The correct parity was found without reading the whole stripe.
D0 (disk 0)1011 0010D1 (disk 1)0101 1100D2 (disk 2)1110 0111P (disk 3)0000 1001D1 = 1011 0010 ⊕ 1110 0111 ⊕ 0000 1001 = 0101 1100
D0 (disk 0)1011 0010D1 (disk 1)0000 1111D2 (disk 2)1110 0111P (disk 3)0101 1010P' = P ⊕ D1 ⊕ D1' = 0101 1010
Figure 11.55: At the top, recovery: D1 = D0 ⊕ D2 ⊕ P = 0101 1100. At the bottom, a small write: when D1' = 0000 1111 is written, P' = P ⊕ D1 ⊕ D1' = 0101 1010.

Rebuilding carries a risk too. On consumer-class disks the rate of unrecoverable read errors (UREs) is about 1 in 1014 bits. To rebuild the failed disk, all of the remaining disks must be read.

Example 11.25

A disk in a RAID 5 array has failed; a total of 12 TB will be read from the remaining disks for the rebuild. The URE rate is 1 in 1014 bits. What are the expected number of errors during the read and the probability of at least one error?

  1. Number of bits. 12 × 1012 B × 8 = 9.6 × 1013 bits.
  2. Expected errors. 9.6 × 1013 / 1014 = 0.96.
  3. At least one error. If errors are independent and rare, their count is approximately Poisson distributed: 1 − e−0.96 ≈ 0.62. The probability that the rebuild hits at least one unreadable sector is about 62%.
  4. Interpretation. In RAID 5, no redundancy is left at this point; the stripe of the sector that is hit cannot be recovered. This is why RAID 6 is chosen for large arrays: the second parity corrects this error during the rebuild as well.

11.12.4Code trace: small write and recovery

void small_write(int d, uint8_t nv) {
  uint8_t ov = rd(d);      /* I/O 1 */
  uint8_t p = rd(P);       /* I/O 2 */
  p = p ^ ov ^ nv;
  wr(d, nv);               /* I/O 3 */
  wr(P, p);                /* I/O 4 */
}
uint8_t rebuild(int bad) {
  uint8_t x = 0;
  for (int d = 0; d <= P; d++)
    if (d != bad)
      x ^= rd(d);          /* incl. P */
  return x;
}

In the code, disks are numbered from 0; P is the number of the parity disk (here 3). rd and wr are single disk I/Os. small_write replaces the block on disk d with nv. First the old data and old parity are read (2 I/Os). p ^ ov removes the effect of the old data from the parity, since x ⊕ x = 0; ^ nv adds in the new value. Then the new data and new parity are written (2 I/Os). The other data disks of the stripe are never read. rebuild computes the lost block by XORing all the disks other than the failed one, parity included.

Table 11.15: small_write(1, 0011 0011) followed by rebuild(2). Initially D0 = 1011 0010, D1 = 0110 1001, D2 = 1100 0101, P = 0001 1110.
StepOperationValueI/O
1ov = rd(1)0110 10011
2p = rd(P)0001 11102
3p = p ^ ov ^ nv0001 1110 ⊕ 0110 1001 ⊕ 0011 0011 = 0100 01002
4wr(1, nv)D1 = 0011 00113
5wr(P, p)P = 0100 01004
6rebuild(2), d = 0x = 1011 0010
7d = 1x = 1011 0010 ⊕ 0011 0011 = 1000 0001
8d = 2 is skipped; d = 3 (P)x = 1000 0001 ⊕ 0100 0100 = 1100 01013 reads
disk 0D01011 0010disk 1D10011 0011disk 2D2????disk 3P0100 0100D2 = 1100 0101disk I/Os: 3
Figure 11.56: The result of rebuild(2): x = 1100 0101, the same as the lost D2.

The recovered value equals the original D2. The new disk is rebuilt by doing 3 reads for every stripe, and the array is unprotected during this time. The small write has a weak point too: if the system crashes between the two writes in steps 4 and 5, the data is new while the parity is old, and the stripe becomes inconsistent. This is called the write hole. If a disk then fails, wrong data is computed from the wrong parity. Hardware RAID cards prevent this with a battery-backed cache, and ZFS by never updating stripes in place.

Example 11.26

In a stripe with four data disks, D0 = 1100 1010, D1 = 0011 0110, D2 = 1010 0001, D3 = 0101 1100. Find P; if the disk of D3 fails, recover D3; if 1111 0000 is written in place of D0, what is the new P?

  1. P. D0 ⊕ D1 = 1111 1100; ⊕ D2 = 0101 1101; ⊕ D3 = 0000 0001. P = 0000 0001.
  2. Recovery. D0 ⊕ D1 ⊕ D2 ⊕ P = 0101 1101 ⊕ 0000 0001 = 0101 1100: the original D3.
  3. Small write. The changed bits are D0 ⊕ D0' = 1100 1010 ⊕ 1111 0000 = 0011 1010. P' = P ⊕ 0011 1010 = 0011 1011.
  4. Check. D0' ⊕ D1 ⊕ D2 ⊕ D3 = 1111 0000 ⊕ 0011 0110 ⊕ 1010 0001 ⊕ 0101 1100 = 0011 1011. The result is the same.

11.12.5RAID performance

The speed of a RAID layout is easily expressed with two measures of a single disk: the rate R (IOPS) on small random requests, and the rate S (MB/s) on large sequential transfers. The model of Arpaci-Dusseau and coauthors starts from these two numbers.

Example 11.27

A single disk has 7200 rpm, an 8 ms average seek, and a 200 MB/s media rate. The array consists of N = 4 disks. What are R and S? What are the rates of RAID 0, 1, 4, and 5?

  1. R. A random 4 KiB read takes 12.19 ms; R = 1000 / 12.19 ≈ 82 IOPS (0.34 MB/s).
  2. S. A sequential 10 MiB chunk: the transfer is 10,485,760 / (200 × 106) = 52.43 ms; the total is 8 + 4.17 + 52.43 = 64.6 ms. S = 10.49 MB / 64.6 ms ≈ 162 MB/s. This value assumes that seek and rotational latency are paid again for each chunk and that the media rate is constant; in a real long sequential read the seek is made once and S approaches the media rate (200 MB/s).
  3. RAID 0. Each request goes to a single disk and the four disks work in parallel: sequential 4 · S ≈ 649 MB/s, random reads and writes 4 · R ≈ 328 IOPS.
  4. RAID 1 (two mirrored pairs). The capacity is 2 disks. A random read can be served from either copy: 4 · R ≈ 328. Every write goes to two disks: 2 · R ≈ 164. Sequential reads, however, reach only 2 · S ≈ 325 MB/s.
  5. RAID 4. The capacity is 3 disks. Sequential 3 · S ≈ 487 MB/s; random reads 3 · R ≈ 246. On a small write, the parity disk does 1 read and 1 write for every write: R / 2 ≈ 41 IOPS.
  6. RAID 5. The capacity is 3 disks. Sequential 3 · S ≈ 487 MB/s; random reads use all the disks: 4 · R ≈ 328. The 4 I/Os of a small write are spread across the disks: (4 / 4) · R ≈ 82 IOPS.
random 4 KiB writes (IOPS), N = 4RAID 0328RAID 1164RAID 441RAID 582
Figure 11.57: Random small-write rate on four disks: RAID 0 328, RAID 1 164, RAID 4 41, RAID 5 82 IOPS.
Table 11.16: Rates of arrays of N disks (R: random IOPS of a single disk, S: its sequential rate, D: the latency of a single request). The numbers are for N = 4, R ≈ 82, S ≈ 162 MB/s.
LayoutCapacitySequential read/writeRandom readRandom writeWrite latency
RAID 0N = 4N·S ≈ 649 MB/sN·R ≈ 328N·R ≈ 328D
RAID 1 (2-way mirror)N/2 = 2(N/2)·S ≈ 325 MB/sN·R ≈ 328(N/2)·R ≈ 164D (slower copy)
RAID 4N − 1 = 3(N−1)·S ≈ 487 MB/s(N−1)·R ≈ 246R/2 ≈ 412D
RAID 5N − 1 = 3(N−1)·S ≈ 487 MB/sN·R ≈ 328(N/4)·R ≈ 822D

Three rows of the table call for explanation. Why is sequential read on a mirror only (N/2)·S? The two copies can share the blocks: one disk reads the even-numbered blocks and the other the odd-numbered ones. But each disk must still rotate past the blocks it skips; skipped blocks save no time. A small write in RAID 4 requires one read and one write on the parity disk every time. The array's rate falls to half that of a single disk, and adding disks does not help at all. RAID 5 spreads the same 4 I/Os over all the disks, so the small-write rate is N·R/4 and grows with the number of disks. When a full stripe is written, the old data is not read; the parity is computed from the new data and the rate is (N − 1)·S.

Example 11.28

A single disk delivers 150 random IOPS. In an array of 8 disks, what is the small random write rate for RAID 0, RAID 10 (4 mirrored pairs), RAID 4, RAID 5, and RAID 6? If the number of disks rises to 16, which one does not speed up at all?

  1. RAID 0. 1 I/O per write: 8 × 150 = 1200 IOPS.
  2. RAID 10. Two copies, 2 I/Os: 1200 / 2 = 600.
  3. RAID 4. 4 I/Os, but two of them always on the parity disk: 150 / 2 = 75.
  4. RAID 5. 4 I/Os, spread across the disks: 1200 / 4 = 300.
  5. RAID 6. 6 I/Os (3 reads + 3 writes): 1200 / 6 = 200.
  6. 16 disks. RAID 4 stays at 75; the bottleneck is the single parity disk. RAID 5 rises to 600.

11.12.6Stable storage

RAID protects against bad sectors and failed disks, but it has no answer to what happens if there is a crash during a write. If power is cut while writing to two mirrored disks at the same time, both copies can be left half-written.

Definition 11.38

Stable storage is a storage arrangement that guarantees that a write either completes correctly or leaves the old data in place. Tanenbaum's model rests on three assumptions: the probability of the same block going bad on two disks at the same time is neglected; faulty data is detected by the ECC; if the CPU crashes, the write in progress stops.

The arrangement is built from two disks and three operations. Stable write: the block is first written to disk 1, read back and verified; if necessary it is retried up to n times, and failing that it is written to a spare sector. Once disk 1 is written successfully, the same is done for disk 2. Stable read: the block is read from disk 1; if it cannot be read with a valid ECC, it is read from disk 2. Recovery: after a crash, the blocks on the two disks are compared and any inconsistency is resolved.

disk 1ECC errordisk 2oldrecovery:copy disk 2 → disk 1
disk 1newdisk 2oldrecovery:copy disk 1 → disk 2
Figure 11.58: Recovery after a crash. At the top the crash happened while writing disk 1: disk 1 is bad (ECC), and the old value is restored from disk 2. At the bottom disk 1 was written and the crash came before disk 2 was written: the new value is copied to disk 2.
Example 11.29

What does recovery do if a crash occurs at each of the five moments of a stable write?

  1. Before writing disk 1. Both copies are old. Nothing is done; the write is treated as if it never happened.
  2. While writing disk 1. The block on disk 1 is half-written and gives an ECC error. The old value is copied from disk 2 to disk 1.
  3. Disk 1 written, disk 2 not started. Both copies are valid but different. The rule: disk 1 wins. The new value is written to disk 2 and the write is completed.
  4. While writing disk 2. Disk 2 is bad (ECC); the new value is copied from disk 1.
  5. Both copies new. The write is complete; nothing is done.

In every case the result is either entirely old or entirely new. What ensures this is the fixed order of the writes. At any moment at least one copy is either entirely old or entirely new and valid; recovery spreads that copy to the other. RAID 1 does not ensure this by itself, because it writes to both disks at the same time and keeps no order that says which is “correct”.

The same idea lives on today in other forms. File systems first write changes to a log (journaling) and apply them to their real places only once the log is durable. Write barriers and FUA make it possible to be sure that certain writes are durable on the disk. In enterprise SSDs, power-loss protection capacitors store enough energy to write the data in the cache to flash when the power goes out.

11.13Summary

  • The operating system talks not to the device but to the device controller. The controller has status, command, data-in, and data-out registers: writing a register issues a command, and reading it learns the status.
  • Registers are reached with the special IN/OUT instructions in port-mapped I/O and with ordinary load and store instructions in memory-mapped I/O. In MMIO the register page must be mapped uncacheable and the pointer must be volatile. Today PCIe devices use MMIO through BARs.
  • There are three transfer methods. In polling the CPU waits on the status register in a loop; in interrupt-driven I/O an interrupt arrives for every unit; in DMA the CPU handles only the setup and the completion interrupt. In the 4096-character example the CPU costs are 4.096 s, 8.19 ms, and about 7 µs.
  • When an interrupt arrives, the CPU stops at an instruction boundary, the hardware saves the PC and PSW, the vector becomes an index into the IDT, the handler acknowledges the device and wakes the waiter, the scheduler chooses, and control returns with iret. Modern devices send the interrupt as a memory write with MSI-X. The handler is split into a top half and a bottom half.
  • Scatter-gather writes to noncontiguous pages in a single DMA operation; the IOMMU translates device addresses and isolates devices from one another.
  • I/O software is layered: the user library, device-independent software (on Linux the VFS, page cache, file system, and block layer), the device driver, and the interrupt handler. Drivers offer a common function table (file_operations).
  • Buffering covers speed mismatch, size mismatch, and copy semantics. A circular buffer holds at most N − 1 bytes in N slots: head = tail means empty, (tail + 1) mod N = head means full. With a single producer and a single consumer no lock is needed.
  • A blocking call does not return until data arrives; a nonblocking call returns whatever is there, or EAGAIN; an asynchronous call starts the job and reports later. epoll reports readiness and io_uring reports completion.
  • Clock hardware decrements a counter on every pulse and raises an interrupt at zero. The tickless kernel stops the tick while idle. Pending timers are kept in a delta list: O(1) work per tick, O(n) for insertion.
  • Disk access time = seek + rotational latency + transfer. At 7200 rpm, an 8 ms seek, and 200 MB/s, a random 4 KiB read takes 12.19 ms (≈ 82 IOPS) and a sequential 1 MiB read takes 17.41 ms (≈ 60 MB/s).
  • Total head movements on the common disk-scheduling queue (head at 53): FCFS 640, SSTF 236, SCAN 236, C-SCAN 382 (183 without the return), LOOK 208, C-LOOK 322 (153 no jump). SSTF can cause starvation; the sweep algorithms cannot. SPTF accounts for rotational latency too and is implemented inside the disk with NCQ.
  • An SSD has no seek and cannot update in place. The FTL does out-of-place updates, garbage collection, and wear leveling; TRIM reduces write amplification. NVMe offers a queue per core; Linux blk-mq follows this model, and the default scheduler on NVMe is none.
  • RAID combines disks with striping, mirroring, and parity. Parity is XOR; a lost block is the XOR of the rest. In RAID 5 a small write needs 4 I/Os, in RAID 6 it needs 6. In RAID 4 the parity disk is a bottleneck. RAID is not a backup.
  • Stable storage writes to two disks in a fixed order and guarantees, after any crash, either entirely old or entirely new data. Today the same idea lives on in journaling, FUA, and power-loss protection.

11.14Key terms

  • bus
  • device controller
  • block / character device
  • memory-mapped I/O
  • polling
  • busy waiting
  • programmed I/O
  • interrupt
  • interrupt vector
  • interrupt handler
  • exception
  • trap
  • pipeline
  • interrupt-driven I/O
  • direct memory access (DMA)
  • device driver
  • buffer / buffering
  • page cache
  • spooling
  • blocking / nonblocking / asynchronous I/O
  • timer
  • hard disk drive (HDD)
  • seek time / rotational latency
  • disk scheduling
  • solid-state drive (SSD)
  • wear leveling
  • I/O scheduler
  • RAID
  • parity
  • journaling

11.15Test Yourself

  1. The cylinders are 0–199; the head is at 100 and moving upward. The requests in arrival order are 55, 58, 39, 18, 90, 160, 150, 38, 184. What is the total movement of FCFS, SSTF, LOOK, and C-LOOK (count the jump)?

    Answer

    FCFS: 45 + 3 + 19 + 21 + 72 + 70 + 10 + 112 + 146 = 498. SSTF: in the order 90, 58, 55, 39, 38, 18, 150, 160, 184: 10 + 32 + 3 + 16 + 1 + 20 + 132 + 10 + 24 = 248. LOOK: 100 → 184 (84), 184 → 18 (166): 250. C-LOOK: 100 → 184 (84), jump 184 → 18 (166), 18 → 90 (72): 322.

  2. A disk spinning at 5400 rpm has an average seek time of 10 ms and a media rate of 100 MB/s (1 MB = 106 B). How long does a random 8 KiB read take on average? About how many random reads per second can the disk perform?

    Answer

    One revolution is 60,000 / 5400 ≈ 11.11 ms; the average rotational latency is 5.56 ms. The transfer is 8192 / 108 s ≈ 0.08 ms. The total is 10 + 5.56 + 0.08 ≈ 15.64 ms; 1000 / 15.64 ≈ 64 reads per second.

  3. A circular buffer with N = 4 slots is empty. The calls in order are: put x, put y, get, put z, put w, put v, get, put u. Which call fails? What are head and tail at the end?

    Answer

    x is written to slot 0 and y to slot 1 (tail 2). get reads x (head 1). z is written to slot 2 and w to slot 3; the tail wraps around (0). At put v, (0 + 1) mod 4 = 1 = head: the buffer is full and −1 is returned. get reads y (head 2). u is written to slot 0 (tail 1). Result: head = 2, tail = 1; the buffer holds z, w, u.

  4. The delta list is A 5, B 2, C 6. If X, which expires in 9 ticks, is inserted, what does the list become? How many nodes does add pass?

    Answer

    A's delta 5 ≤ 9 → t = 4; B's delta 2 ≤ 4 → t = 2; C's delta 6 > 2, the loop stops. X goes in before C with delta 2, and C's delta becomes 6 − 2 = 4. The list is A 5, B 2, X 2, C 4. Two nodes are passed. C's absolute time stays at 13 ticks from now.

  5. In a RAID 5 stripe, D0 = 0110 1101, D2 = 1001 0011, P = 1010 0110. The disk of D1 has failed. What is D1?

    Answer

    D1 = D0 ⊕ D2 ⊕ P. D0 ⊕ D2 = 1111 1110; ⊕ P = 0101 1000. D1 = 0101 1000.

  6. A network card receives a burst of 2000 packets. The interrupt-driven method needs a 3 µs interrupt for each packet; a DMA ring needs 10 µs of setup and a single 3 µs interrupt at the end of the burst. What are the CPU costs? Which is cheaper for single-packet traffic?

    Answer

    Interrupt-driven: 2000 × 3 = 6000 µs = 6 ms. DMA: 10 + 3 = 13 µs; about 460 times less. For a single packet, interrupt-driven costs 3 µs and DMA 13 µs: the fixed setup cost does not pay for itself on a small transfer.

  7. A program wants to watch a file on disk with epoll and read it when it is “ready”. Why does this not give asynchronous reading? Which interface does?

    Answer

    epoll only reports readiness. Disk files always look ready, because the kernel does not refuse a disk read with EAGAIN; it completes it by blocking. The read still waits inside read. io_uring (or IOCP on Windows), which starts the job and reports completion later, provides true asynchrony.

  8. On an SSD the file system does not send TRIM. After the user deletes a large file, why does the disk slow down as it fills up again, and why does it wear out sooner?

    Answer

    The SSD still considers the pages of the deleted file valid. When garbage collection cleans a block, it copies these pages to another block too. Every page copied is an extra write: write amplification rises, writes wait for garbage collection, and cells are erased and written needlessly.

  9. A driver contains a wait loop that reads the status register through an int *status pointer. When optimization is turned on, the loop never ends. Why? What are the two fixes?

    Answer

    The compiler assumes *status does not change in the loop and performs the read once. The pointer must be made volatile int *. In addition, the register page must be mapped uncacheable (ioremap on Linux); otherwise the CPU reads the old value from the cache.

  10. In stable storage, both copies return valid ECC but their values differ. What does recovery do? At which moment of the crash does this situation point?

    Answer

    Disk 1 wins; its value is copied to disk 2 and the write is completed. This situation shows that the write to disk 1 had finished and been verified, while the write to disk 2 had not yet started. If the crash had come while writing disk 2, the block on disk 2 would have given an ECC error.

11.16Further reading

  • R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, the chapters “I/O Devices”, “Hard Disk Drives”, “Redundant Arrays of Inexpensive Disks”, and “Flash-based SSDs”: a short, quantitative treatment of disk scheduling, the RAID performance model, and the FTL; free at ostep.org.
  • D. A. Patterson, G. Gibson, and R. H. Katz, “A Case for Redundant Arrays of Inexpensive Disks (RAID)”, SIGMOD 1988: the short paper that first defined the RAID levels, still readable today.
  • J. Axboe, “Efficient IO with io_uring” (kernel.dk): the document in which io_uring's designer describes the interface, the rings, and the SQPOLL mode.
  • J. Corbet, A. Rubini, and G. Kroah-Hartman, Linux Device Drivers, 3rd ed., O'Reilly, 2005: the classic source on character drivers, interrupt handling, and DMA, with examples; some of the kernel interfaces are out of date, but the concepts remain valid.

11.17References

  1. A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th ed., Wiley, 2018 — Chapter 11: Mass-Storage Structure; Chapter 12: I/O Systems.
  2. A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th ed. (2014) / 5th ed. (2023), Pearson — Chapter 5: Input/Output.
  3. R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP), ostep.org — “I/O Devices”, “Hard Disk Drives”, “RAID”, “Flash-based SSDs”.
  4. D. A. Patterson, G. Gibson, R. H. Katz, “A Case for Redundant Arrays of Inexpensive Disks (RAID)”, SIGMOD 1988.
  5. NVM Express Base Specification 2.x; PCI-SIG PCIe 5.0/6.0; USB4 Specification; UEFI Specification (GPT).
  6. Linux kernel documentation: “Multi-Queue Block IO Queueing Mechanism (blk-mq)”, “NO_HZ: Reducing Scheduling-Clock Ticks”, io_uring (J. Axboe, “Efficient IO with io_uring”); J. Corbet, A. Rubini, G. Kroah-Hartman, Linux Device Drivers, 3rd ed.