Skip to content

Level 4 · Chapter 4.5

Files, devices and I/O

The operating system's I/O instructions: files as byte streams, file descriptors and what open, read, write and lseek do, what small reads cost, the path from write() to the disk through the page cache and fsync, inodes, directories and hard links, today's file systems, devices as files, memory-mapped files, and how drivers use polling, interrupts and DMA.

At the ISA level, input and output means writing bits into device registers, waiting, and checking status bits for a long list of possible errors. A disk controller might report a failed seek, a nonexistent sector, a checksum error. Two points follow: no ordinary program wants to deal with that, and no ordinary program should be allowed to, since whoever can drive the disk directly can read everybody's data. So the operating system machine replaces the real I/O instructions with its own, much higher-level ones. Their central abstraction is the file.

A file is a sequence of bytes

To UNIX and every system that followed it, a file is a numbered sequence of bytes, from 0 up to its length, and nothing more. The OS imposes no structure: a text file is a file whose bytes happen to be characters, with a line feed at the end of each line by convention; a JPEG is a file whose bytes a JPEG decoder understands. Traditional mainframe systems were different: there, a file was a sequence of records of a declared layout, and the OS read "the next record". The byte-stream model won so completely that record-oriented files now mostly survive in databases, which build them on top of byte files.

File descriptors

A program asks for a file by name once, with open, and the kernel answers with a small integer, a file descriptor. Every later call names the file by that number:

int in  = open("data", O_RDONLY);
int out = open("copy", O_WRONLY | O_CREAT | O_TRUNC, 0644);
char buf[65536];
ssize_t n;
while ((n = read(in, buf, sizeof buf)) > 0)   // returns 0 at end of file
    write(out, buf, n);
close(in);
close(out);

read returns how many bytes it actually read: fewer than asked near the end of the file, 0 at the end, −1 on error. Each open file has a current offset: read and write start there and advance it, so consecutive calls walk through the file, and lseek moves it anywhere for random access. Descriptors 0, 1 and 2 are open before main runs: standard input, output and error. A shell connects them to the terminal, to files for > and <, or to pipes for |, and the program never needs to know which.

Behind the number are three levels of kernel tables. Each process has a descriptor table mapping numbers to open file descriptions, the kernel objects that hold the offset and the access mode, and those point to the file itself. dup and fork copy descriptors that share one open file description; a second open of the same file creates a new one. This test opens a 10-byte file, duplicates the descriptor, opens the file again, and reads 4 bytes through the first descriptor:

fds 3 4 5; after reading 4 bytes through fd 3: offset of fd 4 = 4, of fd 5 = 0

Same output on macOS and Linux. The shared offset is why a parent and its children, writing to one inherited log file, append after one another instead of overwriting each other's lines. The numbers are also worth a look: the kernel always gives out the lowest free descriptor, so the first file a program opens is 3. Descriptor numbers used to stay small; today's limits are far higher: the default soft limit is 256 descriptors per process on macOS, commonly 1,024 on Linux distributions, and 1,048,576 in the containers used for this chapter.

What a read costs

Each read is a system call, with its fixed cost of a trip into the kernel. Reading a 64 MiB file that's already in memory with buffers of different sizes:

buffercallsmacOS: per callmacOS: throughputLinux VM: per callLinux VM: throughput
16 B4,194,304390 ns0.04 GB/s240 ns0.07 GB/s
256 B262,144400 ns0.64 GB/s250 ns1.0 GB/s
4 KiB16,384590 ns6.9 GB/s430–450 ns9–9.5 GB/s
64 KiB1,0243.7 µs18 GB/s4.7 µs14 GB/s
1 MiB6457–63 µs17–19 GB/s110–120 µs9 GB/s

Below a few kilobytes, the cost is the call itself, whatever the size; above, it's copying the bytes, and throughput levels off. The C library's fread hides this: reading the same file 16 bytes at a time through a FILE * took 25 ns per call on macOS and 11 ns on Linux, because fread reads 4 KiB or more from the kernel at once and hands out the pieces from its own buffer.

The simulator makes the fixed cost visible in a different way. This program writes hello\n byte by byte, then all at once:

Live · Six system calls, then one

Try it: Press Step to run one instruction, Run to animate or Continue to finish; the L2–L7 buttons zoom in and out one level at a time.

program· ▸ is the next instruction
  1. .data
  2. msg: .ascii "hello\n"
  3. .text
  4. lea rbx, [rip+msg] ; next byte to write
  5. mov r12d, 6 ; bytes left
  6. one_byte:
  7. mov eax, 1 ; write(
  8. mov edi, 1 ; fd 1,
  9. mov rsi, rbx ; one byte,
  10. mov edx, 1 ; length 1)
  11. syscall ; one trap per byte
  12. inc rbx
  13. dec r12d
  14. jnz one_byte
  15. mov eax, 1 ; write(1, msg, 6): the whole buffer
  16. mov edi, 1
  17. lea rsi, [rip+msg]
  18. mov edx, 6
  19. syscall ; one trap for all six bytes
  20. mov eax, 60 ; exit(0)
  21. xor edi, edi
  22. syscall
step 0
Loading emulator…
The process as the operating system sees it: an address space of code, globals, heap and stack.

Both halves print the same hello, but the first makes six system calls and the second one. That's the whole idea of output buffering: printf collects text in memory and makes one write when the buffer fills, at a newline on a terminal, or at exit.

From write() to the disk

When write returns, the data isn't on the disk. It has been copied into the page cache: the kernel's cache of file contents, held in otherwise unused RAM, in pages. The page is marked dirty and written to the device later, in the background. Reads come from the page cache too when the data is there, which is why the table above could read at 18 GB/s. No disk was involved.

Writing a 256 MiB file in the Linux VM and watching /proc/meminfo shows it:

before:        Cached:  374280 kB   Dirty:    128 kB
after writing: Cached:  636424 kB   Dirty: 262272 kB
after sync:    Cached:  636496 kB   Dirty:      0 kB

The page cache grew by exactly 262,144 kB, the size of the file, and all of it was dirty until sync wrote it out; the pages stayed cached afterwards, clean. By default, Linux starts writing dirty pages back after 30 seconds (dirty_expire_centisecs is 3000), or sooner when too much memory is dirty. A crash in between loses them.

A program that needs its data to survive a crash (a database committing a transaction, an editor saving a file) calls fsync, which doesn't return until the file's dirty pages and metadata are on the device. Writing 4 KiB at a time:

macOS (APFS, internal SSD)Linux VM (virtual disk)
write only4.5–5 µs0.8–0.9 µs
write + fsync40–44 µs740 µs
write + fcntl(F_FULLFSYNC)4.5 ms-

macOS has a documented subtlety: its fsync sends the data to the drive but doesn't make the drive flush its own internal cache, so a power cut can still lose it. F_FULLFSYNC does, and costs a hundred times more. On Linux, fsync includes the flush; in this VM, it passes through the virtual disk to the host's storage. Either way, a durable write costs tens of microseconds to milliseconds: that's why databases batch many commits into one fsync.

A read that misses the page cache goes all the way to the device. On this Mac's SSD, a random 4 KiB read with the cache bypassed takes 82 µs (measured in the chapter on disks and SSDs), 139 times the 590 ns of a 4 KiB read served from the cache. Below, a program reads an 8-block file through a page cache of only 4 pages. Read blocks 0–3 twice and watch the hit rate climb; read the whole file twice and notice that every read misses, because each new block evicts the oldest one just before it's needed again. Then write a block or two, cut the power, and see which writes vanish, and try again with fsync.

Between read() and the disk: the page cache

Try it: Click Read blocks 0–3: each read misses and travels to the SSD. Click it again: four hits straight from RAM. Then click write() a block twice and Power cut to see which writes are lost; try again with write() + fsync().

Read:
Write:
Idle: pick a read or a write above.
your programbufsystem call: into the kernelpage cache (RAM), 4 pages, LRUemptyemptyemptyemptySSD: your file, 8 blocks of 4 KiBread() block 00read() block 11read() block 22read() block 33read() block 44read() block 55read() block 66read() block 77click a block to read() it
reads0 (0 hits, 0 misses)
hit rate-
average per read-
hit / miss590 ns / 82 µs
program time (real costs)0 ns
0 hits0 ns
0 misses0 ns
0 write()0 ns
0 write() + fsync()0 ns

Animation not to scale: on screen a miss lasts about three times as long as a hit; really it takes 139 times as long. The program time adds up the real costs measured on this Mac for 4 KiB: read() from the page cache 590 ns, a random read from the SSD with the cache bypassed 82 µs, write() 4.5–5 µs and write() + fsync() 40–44 µs (ranges counted at their middle: 4.75 µs, 42 µs). Write-back runs in the background and isn't charged to the program, not even when every page is dirty and one must be written back before it can be reused. A real page cache holds thousands of pages in otherwise unused RAM; this one holds 4. The power cut behaves as on Linux, where fsync includes the drive's flush; on macOS only F_FULLFSYNC (4.5 ms) guarantees it.

Inodes and directories

The operating system sees a file differently from the program: not as a byte sequence but as a set of allocation blocks on the device, not necessarily consecutive, plus an index saying which block holds which part. On UNIX file systems that index lives in the file's inode, along with everything else about the file except its name: type, permissions, owner, size, timestamps, link count. stat shows it:

  File: a.txt
  Size: 6         	Blocks: 8          IO Block: 4096   regular file
Device: 0,62	Inode: 817047      Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)

Six bytes of content occupy one 4 KiB block (Blocks counts 512-byte units: 8 of them): the last block of every file is partly wasted, the internal fragmentation of allocation units.

A directory is a file whose content is a list of (name, inode number) pairs. Opening /usr/lib/libc.so means reading the root directory to find usr's inode, reading that directory to find lib, and so on. Since a name is just an entry pointing to an inode, one file can have several: ln a.txt b.txt creates a hard link, and both names then show inode 817047 links 2. Removing a name (the system call is unlink) decrements the count; the file's blocks are freed only when it reaches zero and no process still has the file open.

An inode can also describe blocks that don't exist. truncate -s 1G sparse creates a file of length 1,073,741,824 bytes with Blocks: 0: a sparse file, whose unwritten ranges read as zeros without occupying the disk, as after an lseek to position 1,000,000 followed by a one-byte write.

The classic UNIX inode was 64 bytes, with 13 disk addresses (10 direct, then single, double and triple indirect blocks), and free blocks kept on a linked list. Current file systems keep the idea and change the details. ext4's inodes are 256 bytes by default and map files with extents ("N consecutive blocks starting at block B", up to 32,768 blocks per extent), which describe a large contiguous file in a few entries instead of thousands of block numbers. Free space is tracked with bitmaps or B-trees rather than a list. NTFS long stood out for using runs of consecutive clusters; today the UNIX side does too.

File systems today

  • ext4 (2008) is Linux's default, alongside XFS, favored for large servers, and btrfs, which adds copy-on-write, snapshots and checksums.
  • APFS (2017) replaced HFS+ on all of Apple's systems. It is copy-on-write: modified data goes to new blocks, never overwriting the old ones in place, which makes snapshots and clones almost free. Copying a 1 GiB file on this Mac with cp took 1.12 s and used 1 GiB of disk; cp -c, which asks for an APFS clone, took under 10 ms and used nothing, because the new file shares the old one's blocks until one of them is modified. The macOS system volume itself is a sealed, read-only APFS snapshot.
  • NTFS (1993) is still Windows's file system, with its master file table, and small files stored directly in their MFT entry. FAT, obsolete except for USB sticks and memory cards, survives exactly there, as FAT32 and exFAT.

All three journal or copy-on-write their metadata so that a crash can't leave a directory half-updated, a property every current file system has.

Everything is a file

UNIX extends the file interface to things that aren't stored anywhere. Special files in /dev stand for devices, and open, read and write on them reach the device's driver. ls -l /dev in a Linux container:

crw-rw-rw- 1 root root 1, 3 Sep 30 00:55 null
crw-rw-rw- 1 root root 1, 5 Sep 30 00:55 zero
crw-rw-rw- 1 root root 1, 8 Sep 30 00:55 random
crw-rw-rw- 1 root root 5, 0 Sep 30 00:55 tty

The c means character device: a stream of bytes with no positions, like a terminal or a random number generator. The two numbers are the major number, which selects the driver (1 is the memory devices driver), and the minor number, which selects the device within it. Disks are block devices (b): addressable in fixed-size blocks, with the page cache in between. macOS shows both faces of its SSD: /dev/disk0 is a block device, /dev/rdisk0 the same disk as a raw character device that bypasses the cache.

The same descriptors cover pipes, sockets, terminals and kernel information: in /proc/self/fd, a process's standard output shows up as 1 -> pipe:[13529], and /proc itself is a file system whose files are generated on the fly by the kernel. Windows uses one idea instead of another: handles to kernel objects, which the chapter on UNIX and Windows compares.

Memory-mapped files

There's an alternative to read and write: mmap maps a file into the address space, and the program reads it with ordinary loads. It's virtual memory applied to files: the mapped region's pages point at the page cache's pages for the file, the first access to each causes a page fault that brings it in, and writes to a shared mapping make those pages dirty, to be written back like any others. Summing a cached 256 MiB file took 18–20 ms both ways on macOS, and 9–10 ms with mmap against 15–17 ms with read on Linux, where mmap saves copying every byte into a buffer. The dynamic loader uses mmap for every library it loads, which is why so many mmap calls appeared in the system-call trace of a "hello".

How the kernel talks to devices

Underneath the files, the kernel's device drivers do what ordinary programs shouldn't: program device registers and handle their errors. They're the largest part of an operating system's code: the drivers directory is the biggest part of the Linux source tree. A driver has three ways to learn that a device has finished:

  • Polling: read the device's status register in a loop. Simple, and wasteful if the wait is long, but the fastest option when the device answers within microseconds.
  • Interrupts: start the operation, let the CPU do something else, and let the device interrupt when it's done. This is the mechanism of the traps chapter, with PCIe devices signaling through MSI messages.
  • DMA: let the device copy data to or from memory itself, as a bus master, and interrupt only once the whole transfer is done.

A modern NVMe SSD combines them. The driver writes commands into submission queues in RAM and signals the device with one write to a doorbell register. The SSD fetches the commands, moves the data by DMA, writes a completion entry into a completion queue, and raises an interrupt. The standard allows up to 65,535 queues of up to 65,536 commands, so each core can have its own queue and no lock is needed between them. When interrupts arrive faster than they can be handled (a network card receiving millions of packets per second), drivers switch back to polling: Linux's network stack disables a card's interrupt under load and polls it until the queue is empty. And Linux's io_uring can dedicate a kernel thread to polling the program's submission queue, so that I/O is started with no system call at all. The choice between polling and interrupts isn't settled once; it's made again for each device and each load.

Takeaways

  • The OS replaces device-level I/O with files: named sequences of bytes, with no structure imposed.
  • open returns a file descriptor; read, write and lseek use and move the open file's offset. Descriptors 0, 1 and 2 are standard input, output and error. dup and fork share an offset; a second open doesn't.
  • Every read is a system call: about 240–400 ns here whatever its size, so small reads are slow unless a library like stdio buffers them (11–25 ns per fread).
  • write only copies into the page cache; the kernel writes dirty pages later (after 30 s by default on Linux). fsync forces them out: 40 µs on this Mac's SSD, 4.5 ms with F_FULLFSYNC, 740 µs in the Linux VM.
  • An inode holds everything about a file but its name; a directory maps names to inode numbers, so a file can have several hard links. Modern file systems map files with extents and protect metadata with journaling or copy-on-write.
  • Devices appear as character or block special files with major and minor numbers; pipes, sockets and /proc are files too. mmap turns file I/O into memory accesses.
  • Drivers use polling, interrupts and DMA; NVMe SSDs use queues in memory, and busy systems go back to polling.

In this level

  1. 4.1Executable files: ELF, PE and Mach-O
  2. 4.2Processes and the address space
  3. 4.3System calls and privilege levels
  4. 4.4Virtual memory and paging
  5. 4.5Files, devices and I/O
  6. 4.6Threads and synchronization
  7. 4.7Hardware virtualization and hypervisors
  8. 4.8Inside UNIX and Windows