Operating Systems · Lecture Notes

Chapter 10: File Systems

When a process ends, its memory is reclaimed and the data in it is lost. Everything that must persist is written to disk. A disk, however, knows only numbered blocks: “read this block,” “write this block.” The file system builds on top of these raw blocks files with names, sizes, and owners, nested directories, and access rights. These notes first describe the face the user sees: the file, attributes, system calls, open-file tables, directories, links, and permissions. They then turn to implementation: partitioning the disk, allocating blocks to files by contiguous, linked-list, FAT, and i-node methods, tracking free space, and caching. The last sections address consistency after a crash: fsck, journaling, copy-on-write, and log-structured file systems. The chapter closes with VFS and NFS.

Learning outcomes

File abstraction
Define a file by its name, type, attributes, and operations; trace open-file tables and file descriptors.
Directories
Compare directory structures, resolve a path step by step, and explain hard and symbolic links and mounting.
Protection
Read the rwx permission bits and the special bits; distinguish what r, w, and x mean on a file and on a directory.
Allocation
Apply contiguous, linked-list, FAT, and i-node allocation to the same file; compute the maximum file size and the disk block of a given file offset.
Free space and performance
Compute the sizes of the bitmap, list, grouping, and counting methods; explain the buffer cache, the page cache, and read-ahead.
Reliability and real systems
Compare fsck, journaling, copy-on-write, and LFS; recognize NTFS, ext4, FAT32/exFAT, VFS, NFS, and TRIM on SSDs.

10.1Why a file system?

While a program runs, its data lives in its address space. This place is inadequate for three requirements. The first is size: a database or a video archive may be too large for the address space, or even for main memory. The second is persistence: when the process ends, or even when the machine is switched off, the data must stay where it is. The third is concurrent access: many processes must be able to read and modify the same data. Files written to disk meet these three requirements.

The disk offers the operating system a very plain interface. Both a hard disk and an SSD present themselves as a long array of numbered, fixed-size blocks. The number of a block is called its logical block address (LBA). The disk knows two operations: read block k and write block k. Which block belongs to which file, what the file is called, and who may read it are questions the disk does not care about. The file system answers them.

Definition 10.1

A file is a named, persistent sequence of bytes together with its attributes. A file system is the operating system component that turns the blocks on disk into files and directories; it names, places, and protects them.

A file is a logical unit, similar to an address space in memory. Processes create, read, write, and delete files. The operating system manages naming, internal structure, access, protection, and the placement on disk. Figure 10.1 shows these layers. The application talks to files through the calls open, read, write, and close. The file system translates a request such as “byte 5000 of the file” into an address such as “disk block 1729.” The block device then simply reads that block.

Applicationopen · read · write · closeFile abstractionname · byte sequence · attributesFile systemfile offset → block numberBlock device (SSD / HDD)LBA 0 … N−1 · 512 B / 4 KiBdisk = numbered fixed-size blocks
Figure 10.1: The layers from the application to the block device. The file abstraction hides the blocks; the disk knows only numbered, fixed-size blocks.

The subject can be viewed from two sides. The user is concerned with what is visible: the file's name, its type, the directory it is in, its permissions, and which operations can be performed. The implementer thinks about what goes on inside: how are blocks distributed to files, how is free space tracked, and how do the structures stay consistent if the power fails? These notes follow the user's view first and then the implementer's.

10.2The file concept

10.2.1File names and extensions

The process that creates a file gives it a name; after that process ends, other processes find the file by that name. Naming rules vary from file system to file system. Table 10.1 compares four common systems. The FAT system of old MS-DOS used the “8.3” format: a name of at most eight characters, a dot, and an extension of three characters. Long names were stored in additional directory entries in VFAT, which came with Windows 95. The short name continued to exist in truncated form such as REPORT~1.TXT for backward compatibility.

Table 10.1: File-naming rules.
File systemName lengthCaseNote
FAT (MS-DOS)8.3 (e.g. REPORT~1.TXT)insensitiveVFAT long name in extra entries: 255 UTF-16
NTFS255 UTF-16 unitspreserving, insensitive\ / : * ? " < > | forbidden
ext4, XFS255 bytessensitiveonly / and NUL forbidden
APFS255 UTF-8 charactersinsensitive by default on macOSUnicode normalization

On a “case-sensitive” system, Report.txt and report.txt are two different files. ext4 is like this. NTFS stores the name as written but ignores case when searching: the two names find the same file. All of today's systems store names as Unicode, so names with non-ASCII characters cause no trouble. One should also note that ext4's limit is in bytes, not characters. In UTF-8 a letter such as “ş” takes two bytes, so a name dominated by such characters reaches the limit before 255 characters.

The part of the name after the last dot is called the extension: the extension of the file thesis.pdf is pdf. In UNIX the extension is only a convention; the kernel attaches no meaning to it. Programs may. For example, gcc compiles a source file with the extension .c and merely links an object file with the extension .o. On Windows an extension is associated with a program in the registry. Double-clicking the file opens that program. This association also creates a security trap. Because Explorer hides known extensions by default, a program named invoice.pdf.exe appears on screen as invoice.pdf.

File systems have changed over time. Older Windows versions used FAT16 and FAT32; current Windows uses NTFS for the system disk. FAT32 and exFAT live on today in removable media such as USB sticks and SD cards, because almost every device can read them.

10.2.2Magic numbers and file structure

An extension is a name the user can change; it does not prove the real type of the file. A more reliable clue is the first bytes of the file. Many formats begin with a particular byte sequence. This sequence is called a magic number. Figure 10.2 gives a few examples: a PNG image begins with 89 50 4E 47, a PDF with %PDF, Linux's executable format ELF with 7F 45 4C 46, and a ZIP archive with PK. The UNIX command file report tells the type by looking at these bytes, not at the extension. An interesting consequence: docx, xlsx, and pptx files also begin with PK, because they are ZIP archives containing XML files.

first bytes of the filePNG89 50 4E 47‰PNGPDF25 50 44 46%PDFELF7F 45 4C 46.ELFZIP · docx · pptx50 4B 03 04PK..Windows PE4D 5AMZgzip1F 8B..
Figure 10.2: Magic numbers that identify the file type: the header bytes of PNG, PDF, ELF, ZIP, Windows PE, and gzip.

How the inside of a file is organized is called the file structure. Figure 10.3 shows three structures seen in history. In the byte-sequence structure in (a), the operating system sees the file only as an ordered sequence of bytes. Anything can be put in it; the application determines the structure. This is the most flexible choice, and UNIX, Windows, and macOS all use it. In the fixed-length record structure in (b), the unit of reading and writing is the record; 80-byte records are a legacy of the 80 columns of punched cards. This structure lives on today in mainframe data sets. In the record tree in (c), each record has a key field. A request such as “fetch the record whose key is Pony” is supported directly.

(a) Byte sequence1 byte = smallest unitUNIX, Windows, macOSthe application gives the meaning(b) Fixed-length recordsrecord 1 · 80 bytesrecord 2 · 80 bytesrecord 3 · 80 bytesrecord 4 · 80 bytesrecord 5 · 80 bytesrecord 6 · 80 bytespunched-card image (80 columns)today: mainframe data sets(c) Tree of keyed recordsDog · PonyAnt Cat CowFox Hen LionRat Worma record is found by its key fieldtoday: database / B-tree files
Figure 10.3: Three file structures: (a) a sequence of bytes, (b) a sequence of fixed-length records, (c) a tree of records searched by key.

Today access by key is done not in the operating system but in libraries and databases. SQLite places a B+ tree inside an ordinary byte-sequence file. The kernel thus stays simple, and complex structures are built in user space.

Binary files also have their own internal layout. Figure 10.4 gives three examples. (a) In the a.out format of old UNIX, the file opens with a header. The header holds the magic number, the sizes of the code, data, and BSS segments, the size of the symbol table, and the entry point. The header is followed by the code, data, relocation bits, and the symbol table. (b) Linux's current format, ELF, builds on the same idea more flexibly: the program headers are aimed at the loader and the section headers at the linker. Its counterpart on Windows is PE, and on macOS the Mach-O format. (c) An archive file (.a or .lib) stores compiled but unlinked object modules (.o) one after another, each preceded by a member header carrying its name and size. The kernel runs a file as a program only if it begins with the right magic number.

(a) Old UNIX a.outmagic numbertext sizedata sizeBSS sizesymbol table sizeentry pointtext (code)datarelocation bitssymbol tableheader + sections(b) Today: ELF (Linux)ELF header · 7F 45 4C 46program headers.text (code).rodata.data.symtab · .strtabsection headersWindows: PE · macOS: Mach-O(c) Archive (.a / .lib)!<arch> headermember header: name · sizeobject module (.o)member header: name · sizeobject module (.o)member header: name · sizeobject module (.o)compiled, unlinked modules
Figure 10.4: Executable and archive formats: (a) old a.out, (b) ELF, (c) an object-module archive.

10.2.3File types

UNIX divides files into several types. Regular files hold user data. They are either text (lines of printable characters; the line ending is LF in UNIX and CRLF in Windows) or binary (only the program that uses it knows its structure). Directories are system files that hold the structure of the file system. Special files model input/output devices. Character devices (terminal, serial port) deliver bytes in sequence. Block devices (disks) are open to random access in blocks.

UNIX's famous principle “everything is a file” says that devices, pipes, and sockets are also used through the same open/read/write interface. For example, anything written to /dev/null disappears, and reading from it returns end-of-file at once. Table 10.2 lists the types together with the first character of the ls -l output.

Table 10.2: UNIX file types and their letters in the ls -l output.
LetterTypeExample
-regular file (text or binary)notes.txt, /bin/ls
ddirectory/home
lsymbolic link/bin → usr/bin
ccharacter device (serial, byte by byte)/dev/tty, /dev/null
bblock device (block by block, random)/dev/nvme0n1, /dev/sda
pnamed pipe (FIFO)mkfifo channel
sUNIX socket/run/systemd/notify

10.2.4Attributes, stat, and ls -l

Besides the name and the data, the operating system keeps a set of information for every file. These are called attributes or metadata. Table 10.3 lists the common attributes.

Table 10.3: File attributes.
AttributeMeaningWhere / how
Name, type, locationthe name is in the directory entry; the type and block addresses are in the i-node or the MFT recordall systems
Sizelogical size (st_size) and allocated space (st_blocks)the two differ for a sparse file
Owner, groupUID / GID; SID on Windowschown, icacls
Protectionrwx bits, ACLchmod, setfacl
Timestampsaccess (atime), content change (mtime), i-node change (ctime), creation (btime)stat; relatime on Linux
Link countnumber of names that point to the fileblocks are freed at 0
Read-only, Hidden, Systemread-only, hidden, system fileWindows attrib; in UNIX hidden = name starts with a dot
Archivechanged since the last backupcleared by the backup tool
Compressed, Encryptedcompressed / encryptedNTFS, Btrfs, APFS; fscrypt, BitLocker
Sparse, Temporaryzero blocks not on disk; temporary (cache hint)NTFS flags
Reparse pointspecial handling: symbolic link, junction, cloud placeholderNTFS
Extended attributesname = value pairsxattr (SELinux label), NTFS ADS

Some attributes need explanation. In a sparse file, regions that were never written take no space on disk; when read, they return zeros. A sparse file of size 1 GiB can therefore occupy only a few kilobytes on disk: st_size is 1 GiB but st_blocks is small. The three timestamps are often confused. mtime is the moment the content was last changed, and ctime the moment the i-node (permissions, owner, link count) was last changed; ctime is not the “creation time.” The creation time (btime) is a separate field. Updating atime on every read would turn every read into a write. Linux therefore uses relatime by default: atime is updated only if it is older than mtime or older than a day.

Some Windows attributes are also misunderstood. The Temporary attribute does not delete the file automatically; it merely tells the cache manager “do not hurry to write this to disk.” Symlink, Device, and Junction are not attributes but file types. Fields such as Creator and Max size belong to old systems.

A program reads attributes with the stat system call. The call fills in the following structure:

struct stat {
  dev_t     st_dev;      /* device (file system)   */
  ino_t     st_ino;      /* i-node number          */
  mode_t    st_mode;     /* type + permission bits */
  nlink_t   st_nlink;    /* hard link count        */
  uid_t     st_uid;      /* owner user             */
  gid_t     st_gid;      /* owner group            */
  dev_t     st_rdev;     /* no. if a device file   */
  off_t     st_size;     /* size (bytes)           */
  blksize_t st_blksize;  /* preferred I/O size     */
  blkcnt_t  st_blocks;   /* 512 B units allocated  */
  struct timespec st_atim; /* last access  */
  struct timespec st_mtim; /* last content */
  struct timespec st_ctim; /* last i-node  */
};

Most of the fields correspond to the attributes in the table. st_ino is the file's i-node number; within one file system it identifies a file uniquely. st_mode carries the type and permission bits together. st_nlink is the hard-link count. st_blocks gives the space allocated to the file in units of 512 bytes; even if the block size is 4 KiB, the unit is 512 B. Since POSIX.1-2008 the times are struct timespec fields with nanosecond resolution. The old name st_atime remains as a macro for backward compatibility. On Linux the creation time is read with a separate call, statx().

$ ls -l b.txt-rwxr-x---typeownergroupothers1→ hard link count (st_nlink)root root→ owner and group81→ size, bytes (st_size)May 26 19:20→ last modification (mtime)b.txt→ name: comes from the directory entrythe name is in the directory, not in the i-node!
Figure 10.5: The fields of the ls -l output: type, permissions, link count, owner, group, size, modification time, and name.

ls -l converts this structure into a form humans can read (Figure 10.5). The first character is the type, and the next nine characters are the permissions of the owner, the group, and others. Then come the link count, the owner and group names, the size in bytes, the mtime, and the name. The name is not in the stat structure: the name lives in the directory entry, not in the i-node. This is also why one i-node can be given several names.

10.2.5File operations and system calls

A file is an abstract data type: it is defined by the operations that can be performed on it. Table 10.4 gives the basic operations and their POSIX counterparts.

Table 10.4: File operations and POSIX system calls.
OperationPOSIX callWhat it does
Createopen(O_CREAT), creatcreates an empty file and a directory entry and sets the attributes
Deleteunlinkremoves the name; when the link count reaches 0 and the last descriptor is closed, the space is freed
Openopenresolves the path, brings the i-node into memory, returns a descriptor (fd)
Closeclosereleases the fd and, if necessary, the table entries
Read / writeread, writereads / writes from the file position and advances the position
Appendopen(O_APPEND)every write goes atomically to the end of the file
Seeklseekchanges the position (random access); performs no I/O
Read / write attributesstat, chmod, chown, utimensatreads / changes the attributes
Renamerenamechanges the name; atomic within the same file system
Truncate, mapftruncate, mmapshortens or extends the size; maps the file into the address space

A few details in the table matter. unlink deletes not the file but a name. The file's blocks are freed only when no name remains and the last descriptor holding it open has been closed. This is why a process can keep reading a file that is open even after the file is deleted. lseek only changes the position counter in the kernel; it does not touch the disk. On a file opened with O_APPEND, the operation “go to the end and write” is indivisible. Even if two processes write to the same log file at the same time, their records do not overlap.

That rename is atomic is the basis of a common pattern in applications (Figure 10.6). To save a document safely, the new content is first written to a temporary file. Then fsync is used to wait until the data reaches the disk. Finally rename(tmp, target) is called. Whenever the crash occurs, the disk shows either the whole old file or the whole new file; a half-written file never appears.

1 · write to report.tmpreport: old2 · fsync(report.tmp)data on disk3 · rename → reportreport: new (atomic)
Figure 10.6: Safe saving: write to a temporary file, fsync, and rename. At every moment either the old or the new file is visible.
Common mistake

Opening the document in place, truncating it with O_TRUNC, and writing the new content. If a crash occurs between the truncation and the write, neither the old nor the new content remains. Skipping the fsync step is also dangerous: rename can reach the disk before the data itself, and the result is a “new” file of zero bytes.

10.2.6Open-file tables

Resolving the file's path from scratch at every read call would be very expensive. The file is therefore opened first. open resolves the path once, brings the file's i-node into memory, and returns a small integer to the process. Later calls refer to the file by this number.

Definition 10.2

A file descriptor (fd) is an index into the descriptor table the kernel keeps for each process. 0, 1, and 2 are standard input, standard output, and standard error, respectively. open always returns the smallest free number.

The kernel tracks open files at three levels (Figure 10.7). At the top is each process's own descriptor table; its entries point to the middle table. In the middle is the system-wide open-file table. Each of its entries represents one opening and carries two important pieces of information: the current position in the file (the offset) and the access mode (read-only, read-write). At the bottom is the in-memory i-node table. Here each file appears exactly once, however many times it has been opened.

Process A · fd table0 stdin1 stdout2 stderr3Process B (A’s child)0 stdin1 stdout2 stderr34System-wide open-file tableposition = 4096O_RDONLYref = 2position = 0O_RDWRref = 1In-memory i-node tablei-node 4711size = 6000ref = 2i-node + blocks on diskopen()fork() shares
Figure 10.7: The per-process fd tables, the system-wide open-file table, and the in-memory i-node table. A's fd 3 and its child B's fd 3 share the same entry; B's fd 4 is a second opening of the same file.

The consequence of this separation can be summarized as follows. fork and dup copy the entry in the descriptor table; the copies point to the same open-file entry. They therefore share the position: if one reads 10 bytes, the other's position also advances by 10 bytes. Opening the same file a second time with open, however, creates a new entry. The position of this entry is separate and starts at 0. In both cases the i-node is single. The reference count in the open-file entry records how many descriptors point to it, and the reference count in the i-node records how many entries point to it. When a count drops to 0 the corresponding structure is released. On Windows the same role is played by each process's handle table.

Example 10.1

The contents of the file letters.txt are ABCDEFGHIJ (10 bytes). A process opens the file and reads 4 bytes. Then it calls fork; the child reads 3 bytes from the same descriptor and exits. The parent waits for the child, opens the file a second time, and reads 2 bytes from the new descriptor. Finally it reads 2 bytes from the first descriptor. Which bytes are read?

  1. First read. open returns fd 3; entry E1 is created, position 0. ABCD is read, and E1's position is 4.
  2. fork. The child's fd 3 also points to E1; E1's reference count is 2.
  3. Child. It reads 3 bytes from the shared position 4: EFG. E1's position is 7. When the child exits, the reference count drops to 1 and the position stays 7.
  4. Second open. A new entry E2 is created, fd 4, position 0. AB is read; E1 is unaffected.
  5. The parent's fd 3. E1's position is 7: HI is read, and the position becomes 9.

The parent's last read is HI, not EF, because the child advanced the shared position.

10.2.7Code trace: open, read, close

The program below reads the 6000-byte file notes.txt three times with a 4096-byte buffer and closes it.

#include <fcntl.h>
#include <unistd.h>

int main(void) {
  char buf[4096];
  int fd = open("notes.txt", O_RDONLY);
  ssize_t n = read(fd, buf, sizeof buf);
  n = read(fd, buf, sizeof buf);
  n = read(fd, buf, sizeof buf);
  close(fd);
  return 0;
}

open resolves the path and brings the file's i-node (let its number be 4711) into the in-memory table. It creates an open-file entry with position 0 and returns the smallest free number, 3; 0, 1, and 2 are the terminal descriptors inherited from the shell. The first read brings the file's first block into the cache (reading from disk if necessary) and copies 4096 bytes into buf. The position becomes 4096. The second read also asks for 4096 bytes, but only 6000 − 4096 = 1904 bytes remain in the file. The call returns 1904; the position becomes 6000. This is not an error: a read that returns fewer bytes than requested, a short read, is a normal situation. The third read returns 0. A return of zero means end of file (EOF); if it were an error, −1 would be returned and errno set. close frees fd 3. The entry's reference count drops to 0 and the entry is deleted. The i-node's count also becomes 0; it can now be evicted from memory. Table 10.5 summarizes these steps.

Table 10.5: Trace of open, read, close (6000-byte file, 4096-byte buffer).
StepReturnsPositionEntry ref.i-node ref.
open3011
1st read4096409611
2nd read1904600011
3rd read0 (EOF)600011
close0—0 (deleted)0
fd table0 tty1 tty2 tty3open-file entryposition = 4096O_RDONLYref = 1i-node 4711size 6000ref = 1notes.txt (6000 bytes)0 – 40954096 – 5999position
Figure 10.8: The tables after the first read: fd 3 points to the open-file entry with position 4096; the entry points to i-node 4711.

10.2.8Code trace: copying a file

Copying is the simplest program that uses reading and writing together:

#define BUF 4096

int copy(const char *src, const char *dst) {
  char buf[BUF];
  int in  = open(src, O_RDONLY);
  int out = open(dst, O_WRONLY | O_CREAT
                      | O_TRUNC, 0644);
  ssize_t n;
  while ((n = read(in, buf, BUF)) > 0)
    write(out, buf, n);
  close(in);
  close(out);
  return 0;
}

The source is opened for reading and gets number 3. The destination is opened with three flags and gets number 4. O_WRONLY asks for write-only access. O_CREAT creates the file if it does not exist. O_TRUNC erases the contents if it does. When O_CREAT is used, the third argument is the permissions of the new file: 0644, that is, read-write for the owner and read-only for the others. On each turn the loop reads at most BUF bytes and writes as many as it read. The assignment in the condition needs care: the return value of read is first stored in n, and then it is tested whether it is greater than 0.

Let abc be 10,000 bytes. The trace is given in Table 10.6. The first two turns copy 4096 bytes each; 8192 in total. The third read returns the remaining 10,000 − 8192 = 1808 bytes and write writes exactly 1808 bytes. The fourth read returns 0 and the loop ends. In all, 4 read and 3 write calls are made.

Table 10.6: Trace of copy("abc", "xyz") (abc is 10,000 bytes, BUF = 4096).
Turnread return (n)writeTotal copied
140964096 bytes4096
240964096 bytes8192
318081808 bytes10.000
40 (EOF)—10,000; the loop ends
Common mistake

Writing write(out, buf, BUF) in the loop. On the last turn the buffer holds only 1808 valid bytes; the remaining 2288 bytes are garbage left over from the previous turn. The destination file becomes 12,288 bytes and its end is corrupt. The amount to write is always the n returned by read.

The code above does not check for errors, to keep it short. In a real program the −1 return of every call must be checked. write can also write fewer bytes than requested (for example when the disk is filling up or when writing to a pipe); the remainder must therefore be completed with an inner loop. The buffer size matters too. If a 6 MiB (6,291,456-byte) file is copied byte by byte, 6,291,457 read and 6,291,456 write calls are needed. If each entry into the kernel takes 0.3 µs, this overhead alone is about 3.77 seconds. With a 4096-byte buffer the number of calls falls to 1537 + 1536 = 3073 and the overhead to about 0.92 ms. 4096 bytes also matches the page and block size.

10.2.9Access methods

The order in which the inside of a file is accessed is called the access method (Figure 10.9). In sequential access the file is read or written from beginning to end. The current position advances with every operation; to go back, one has to rewind. Tapes and cassettes worked this way. Even today it is the most common pattern for log files, video streams, and a compiler reading a source file.

Sequential access0123456current positionrewindread next · write nexttape, log, streamDirect (random) access0123456read 5lseek(fd, 5·B, SEEK_SET)disk, database, mmapIndexed accessindexAdaKaanSelinZeyneprecord blocksblock 1block 4block 7block 10key → index → blockISAM, B+ tree
Figure 10.9: Sequential, direct, and indexed access.

In direct (random) access the file is a sequence of numbered blocks or fixed-length records. One can start at any wanted record: with records of B bytes, lseek(fd, 5·B, SEEK_SET) is enough for record 5. pread does the positioning and the reading in a single call and does not change the shared position. Disks and SSDs support direct access; databases use it. Indexed access is built on top of direct access. A small index maps a key to the block in which the record lies. If the index grows, an index of the index is kept. IBM's ISAM method and today's B+ trees are examples of this idea. Finally, in memory-mapped access (mmap) the file's pages are mapped into the address space; reading and writing turn into ordinary memory accesses.

10.3Directories

10.3.1Directory operations

Definition 10.3

A directory is a special file that maps file names to files. Each mapping is called a directory entry; in UNIX an entry maps a name to an i-node number.

A directory is also a file, but the user cannot modify it with write. Because a corrupt directory can make a whole subtree unreachable, the kernel changes the contents of directories only through certain calls. Table 10.7 lists these calls.

Table 10.7: Directory operations.
CallFunction
mkdircreates an empty directory (containing only . and ..)
rmdirremoves a directory; the directory must be empty
opendir / closediropens / closes a directory stream
readdirreturns the next entry (name, i-node no., type) in an open directory
renamerenames or moves a file or directory (atomic within the same file system)
linkadds a new name (hard link) to an existing file; the i-node's link count rises
symlinkcreates a symbolic link containing the target path
unlinkremoves a name; if the link count reaches 0 the file is deleted

A new directory has two entries from the start: . points to the directory itself and .. to the parent. These two entries also affect the link counts (Figure 10.10). Let the i-node of /home be 20 and let it contain no other subdirectory. Its link count is 2: the home entry in the root and its own . entry. mkdir /home/ali gives the new directory i-node 31. The entry ali → 31 is added to /home; the new directory contains . → 31 and .. → 20. As a result the link count of i-node 31 becomes 2 (ali and .). That of i-node 20 rises to 3, because the new directory's .. entry also points to it. The general rule is: the link count of a directory is 2 plus the number of its subdirectories.

/home (i-node 20).20..2ali31ali (i-node 31).31..20link count: 20 → 3 (new ..), 31 → 2 (ali and .)
Figure 10.10: mkdir /home/ali: the entry ali is added to the parent directory; in the new directory . points to itself and .. to the parent.

The name link can mislead. This call does not link one directory to another; it gives an existing file a second name. Giving hard links to directories is forbidden to ordinary users, because it can create cycles in the directory tree.

10.3.2Directory structures

How directories are organized relative to one another has changed over time. The simplest structure is the single-level directory (Figure 10.11): all files sit in a single root directory. Early supercomputers such as the CDC 6600 and some embedded devices were like this. The structure is simple but causes two problems. Two users cannot use the same name, for example test. Files also cannot be grouped by subject.

single directory (root)catboatestdatamailconthexrecordsFiles of all users in the same place: two users cannot both ask for the name “test,”and files cannot be grouped. The first systems (CDC 6600) and some embedded devices were like this.
Figure 10.11: A single-level directory: all users' files in the same place.

In a two-level directory, a master file directory (MFD) gives each user a separate user file directory (UFD) (Figure 10.12). Name conflicts disappear: ali/test and can/test are different files. The full name of a file is now a path of the form “user/file.” System programs need a separate “user” directory. The idea of a search path, which says which directories to look in when a command is typed, comes from here. Sharing and grouping are still hard.

master file directory (MFD)aliayşecanececatbotestadatatestxdataaFile directory per user (UFD): no name conflicts (ali/test ≠ can/test), but sharing and grouping are hard.
Figure 10.12: A two-level directory: one directory per user under the master directory.

All of today's general-purpose systems use a tree (hierarchical) structure. The user can create as many subdirectories as wanted, and every file has a single path starting from the root. When sharing is added to the tree, the structure becomes a directed acyclic graph (DAG) (Figure 10.13). In the figure project.c appears under both ali/homework and ayşe/shared: the same file has two names. Sharing brings two new questions. A backup or counting program that walks the tree may count the same file twice. When a shared file is deleted, it becomes unclear which name is deleted and when the data is freed. The link count answers the second question: the data is freed when the last name is deleted.

/binhomeusraliayşeliblsnotes.txthomeworkphoto.pngsharedproject.cshared/back → homecycle!
Figure 10.13: The shared project.c turns the structure into a directed acyclic graph. If a link named shared/back returns to home, a cycle arises in the general graph.

If giving links to a directory is allowed, a general graph arises. The link shared/back → home in the figure builds a cycle. A search walking the tree can go on forever. The link counts of a cycle that can no longer be reached from anywhere also do not fall to zero; finding these directories requires an expensive garbage collection. UNIX therefore forbids hard links to directories.

10.3.3Path names

Definition 10.4

An absolute path starts from the root directory: /home/sercan/os/slides. A relative path starts from the process's working directory. The working directory is seen with pwd and changed with cd.

Two special names present in every directory make relative paths powerful: . is the current directory and .. the parent. In the root, .. again points to the root. In Figure 10.14 the working directory is /home/sercan/course. ../os/slides first goes up to the parent, that is, /home/sercan, and from there down to os and slides. The separator is / in UNIX and \ in Windows. The Windows API accepts / too. On Windows an absolute path begins with a drive letter (C:\Users\sercan\os), and a network share with two backslashes (\\server\share).

/binetchomeusrdevsercanlibcourseosslidespasswdworking directory../os/slides
Figure 10.14: A UNIX directory tree; the working directory is /home/sercan/course, the relative path ../os/slides.

Directory names have a history too. In the first UNIX systems user directories were under /usr; the /usr/ast in Tanenbaum's examples comes from this. Today user directories are under /home (/Users on macOS). /usr is reserved for read-only system software.

Example 10.2

The working directory is /home/elif/homework/os. Which file does ../../notes/./chapter10.txt refer to?

  1. The first ..: /home/elif/homework.
  2. The second ..: /home/elif.
  3. notes: /home/elif/notes.
  4. . is the current directory; the path does not change.
  5. chapter10.txt: the result is /home/elif/notes/chapter10.txt.

10.3.4Path resolution

Converting a path to an i-node number is called path resolution. The kernel walks the path component by component. For each directory it first reads the directory's i-node; the i-node says in which block the directory's contents are. Then it reads that block and searches for the name of the next component. The entry it finds gives the next i-node number.

Tanenbaum's classic example resolves the path /usr/ast/mbox (Figure 10.15). Because the path is absolute, the search starts at the root. The i-node number of the root directory is known: in this example 1; in V7 UNIX and ext4 it is 2. The root i-node was brought into memory at mount time.

  1. The root directory block is read. usr is searched for and i-node 6 is found.
  2. i-node 6 is read. /usr is a directory; its contents are in block 132. The permission check is also done at this step: x permission is needed to pass through the directory.
  3. Block 132 is read. ast is searched for and i-node 26 is found.
  4. i-node 26 is read. The contents of /usr/ast are in block 406.
  5. Block 406 is read. mbox is searched for and i-node 60 is found.
root directory1.1..4bin7dev14lib9etc6usr8tmpi-node 6mode, size,times …→ block 132block 132: /usr6.1..19dick30erik51jim26ast45bali-node 26mode, size,times …→ block 406block 406: /usr/ast26.6..64grants92books60mbox81minix17srci-node 60/usr/ast/mbox
Figure 10.15: Resolving the path /usr/ast/mbox: root directory → i-node 6 → block 132 → i-node 26 → block 406 → i-node 60.

Without a cache this resolution costs 5 disk reads. Two more reads are needed to read the file's own i-node (60) and its first data block. The general rule is easy to derive. Let the root i-node be in memory and each directory fit in one block. Reaching the last i-node of a path with k components takes 2k reads, and reading the first data block as well takes 2k + 1 reads. In a relative path the search starts at the i-node of the working directory instead of the root; since the working directory is already in memory, it is cheaper. Linux keeps freshly resolved name → i-node mappings in the dentry cache. When the same path is opened a second time, most of the disk reads disappear.

Example 10.3

The first data block of the file /var/log/system/events.txt is to be read. Only the root i-node is in the cache; each directory fits in one block. What is the minimum number of disk reads?

  1. There are four components in the path: var, log, system, events.txt.
  2. Two reads are made for each component: the block of the directory in which it is searched and the i-node found. The root directory's block is the first read; four components cost 4 × 2 = 8 reads.
  3. Finally the file's first data block is read: 2 · 4 + 1 = 9 reads in total.

10.3.5Hard and symbolic links

Definition 10.5

A hard link is a second directory entry that points to an existing i-node. A symbolic link is a small special file with its own i-node whose content is the path of another file.

The difference between the two kinds of link is best seen with a trace (Table 10.8). echo hello > a.txt creates a new file. The directory has the entry a.txt → 812 and the link count of i-node 812 is 1. ln a.txt b.txt makes a hard link. The new entry b.txt → 812 points to the same i-node and the link count becomes 2. The two names are completely equal; the question of which is the “original” has no answer. ln -s a.txt c.txt makes a symbolic link: a new file with i-node 905 is created and its content is the string "a.txt". The link count of i-node 812 does not change.

Table 10.8: Trace of hard and symbolic links (simulated with Python).
CommandDirectory entrieslink count of i-node 812Result
echo hello > a.txta.txt → 8121new file
ln a.txt b.txta.txt → 812, b.txt → 8122two equal names
ln -s a.txt c.txt+ c.txt → 905 (content "a.txt")2the symbolic link has its own i-node
rm a.txtb.txt → 812, c.txt → 9051cat b.txt: hello; cat c.txt: ENOENT
directory /home/alia.txtdeleted (rm)b.txt812c.txt905i-node 812type: regular filelink count = 1"hello\n"i-node 905type: symbolic link"a.txt"a.txt missing → ENOENT (dangling link)
Figure 10.16: After rm a.txt: b.txt still points to the same i-node; c.txt now points to a name that no longer exists and is left dangling.

The last row shows the essence of the two kinds (Figure 10.16). rm a.txt deletes only a name and lowers the link count to 1. The data stays in place; b.txt works. A symbolic link, however, stores not the i-node but the name. When c.txt is opened, the kernel resolves the path "a.txt" again, cannot find the name, and returns the error ENOENT (no such file). This situation is called a dangling link. If a new file is created with the same name, the symbolic link silently starts opening that new file; a hard link keeps pointing to the old data.

Tanenbaum points to a subtle side effect of hard links. B gives a hard link to user C's file; then C deletes the file. B's name and the data remain, but the owner of the i-node is still C. The space the file occupies also keeps being charged to C's quota.

Let us compare the two kinds. A hard link has no extra cost; but it can be made only within the same file system (an i-node number is meaningless in another file system) and cannot be given to directories. A symbolic link can point to directories, to files in other file systems, even to network paths. Its price is an extra path resolution at every access. Symbolic links can also form cycles. The kernel therefore limits the number of links followed while resolving a path; if the limit is exceeded, the error ELOOP is returned. On Windows a hard link is made with mklink /H and a symbolic link with mklink. For directories there is also a junction kind.

10.3.6Mounting

A machine has several file systems: the partitions of the system disk, an attached USB stick, a share from the network. UNIX combines them in a single tree.

Definition 10.6

Mounting means attaching the root of a file system to a directory in the existing directory tree, the mount point.

Figure 10.17 shows the process in three steps. Initially there are two separate file systems: the root system in ext4 format and a USB stick in exFAT format. /mnt/usb is an ordinary directory and contains old.txt. mount /dev/sdb1 /mnt/usb adds a record to the kernel's mount table. From then on, when path resolution reaches /mnt/usb, it jumps to the root i-node of the USB stick. /mnt/usb/photos is now the photos directory on the USB stick. old.txt is not deleted, only hidden. umount /mnt/usb removes the mount if there are no open files in that file system; if there are open files it returns the error EBUSY. When the mount is removed, old.txt becomes visible again.

root file system (/dev/nvme0n1p2, ext4)/binhomemntusbphotosdocumentsUSB root took the place of /mnt/usb/mnt/usb/photos → photos on the USB stickold.txt temporarily hidden
Figure 10.17: After mount /dev/sdb1 /mnt/usb: the root of the USB stick takes the place of /mnt/usb; the old content is temporarily hidden.

At boot time the root file system is mounted first. The others are mounted according to the definitions in the file /etc/fstab or in systemd units. The command findmnt shows the mount tree. Options can be given when mounting: ro mounts read-only, noexec disables the execution of programs on that system, and nosuid disables the effect of the setuid bit. With these options a safe boundary is drawn around an attached USB stick. Windows gives each volume a drive letter (C:, D:), but NTFS can also mount a volume on an empty folder.

10.4Protection

10.4.1The rwx permission bits

On a shared system it must be determined what each user may do with each file. UNIX uses a crude but fast method for this. Users are divided into three classes: the file's owner (u), the file's group (g), and others (o). Each class has three rights: read (r), write (w), and execute (x). The nine bits are thus written as three octal digits: r = 4, w = 2, x = 1. chmod 754 script.sh gives the owner 7 = rwx, the group 5 = r-x, and others 4 = r--, and rwxr-xr-- appears in ls -l.

setuid1×4setgid0×2sticky0×1r1×4w1×2x1×1r1×4w0×2x1×1r1×4w0×2x1×1special bits= 4owner (u)= 7group (g)= 5others (o)= 5example: chmod 4755 → -rwsr-xr-x (setuid + rwx r-x r-x)
Figure 10.18: The 12 permission bits: special bits, owner, group, and others. Example 4755 = setuid + rwx r-x r-x.

The meaning of the rights differs on a file and on a directory (Table 10.9). On a file, r means reading the content, w modifying it, and x running it as a program. The content of a directory is name → i-node mappings. On a directory r means listing the entries (ls), w adding, deleting, or renaming entries, and x passing through the directory: path resolution and cd require it.

Table 10.9: The meaning of r, w, and x on a file and on a directory.
RightOn a fileOn a directory
rread the contentlist the entries (ls)
wmodify the contentadd, delete, or rename entries (the file's own permission is irrelevant)
xrun as a programpass through (path resolution, cd)

This table has two surprising consequences. The first: deleting a file requires the w right not on the file but on the directory that contains it. Deleting removes a directory entry; it does not touch the file's content. A read-only file can be deleted in a directory with w permission. The second: having x without r on a directory is a meaningful combination. If the directory /home/ali is drwx--x--x, another user cannot list it. But if they know the name of a file inside, the path resolves, and they can read the file if the file's own r bit allows it.

The order of checking also matters. The kernel first looks at whether the requester is the owner of the file; if so, it applies only the owner's rights. If not, and the requester is in the file's group, it applies the group rights; otherwise it applies the rights of others. The first matching class is used and the later ones are not examined.

Example 10.5

-r--rw-rw- 1 ali students 120 report.txt. ali is also a member of the group students. Can ali write to the file?

  1. The requester is ali and the owner of the file is ali: the owner class matches.
  2. The owner's rights are r--; there is no w.
  3. The group and others classes are not examined at all. The write is rejected with EACCES.

The result looks odd at first sight: the owner cannot write to a file that the group, and even everyone, can write. If the owner wishes, they can give themselves w with chmod u+w, because the right to change permissions belongs to the owner.

10.4.2Special bits, umask, and ACLs

In front of the nine bits there are three more special bits (Figure 10.18): setuid (4), setgid (2), and sticky (1). A program with the setuid bit runs with the identity of the file's owner, not of the user who runs it. The passwd command belongs to root and has the setuid bit; when an ordinary user changes their password, this is how it updates the password file that only root can write. ls -l shows setuid as an s in the place of the owner's x: 4755 → -rwsr-xr-x. The sticky bit is used on directories. In a directory that everyone can write, only the owner of the file, the owner of the directory, or root can delete or rename an entry. /tmp is like this: drwxrwxrwt (1777). If the sticky bit is set but the x right of others is off, the last character is a capital T: 1770 → drwxrwx--T.

The permissions of a new file are determined by the umask. Programs usually ask to create files with permission 666 and directories with 777. The kernel turns off the bits in the umask from this request: permission = request & ~umask. With umask 027, a new file gets 666 & ~027 = 640 (rw-r-----) and a new directory 777 & ~027 = 750 (rwxr-x---). With this setting the group can only read, and others can do nothing.

Common mistake

Subtracting the umask from the request. Octal subtraction gives 666 − 027 = 637: the group could write and execute, and others could do everything. The umask is a bit-by-bit mask: 666 & ~027 = 640. The two operations give the same result only if all the bits of the umask are also set in the request.

The distinction between owner, group, and others is coarse-grained. It does not meet a request such as “let ali read this file but not can, if both are in the same group.” An access control list (ACL) is used for this. An ACL keeps separate entries for named users and groups; on Linux it is set with setfacl and a + appears at the end of the permissions in the ls -l output. All of NTFS's protection is ACL-based.

10.5Disk layout

10.5.1Partitioning: MBR and GPT

A disk is divided into one or more partitions. Each partition can hold a separate file system; a partition can also be swap space, an LVM physical volume, or an encrypted container. The list of partitions is kept in a table at the beginning of the disk. This table has two formats (Figure 10.19).

MBR (BIOS, 1983)LBA 0512 Bcode 446 Bboot loader4 × 16 Bpartition table55 AAPartition 1 (active)Partition 2extended → logicalat most 4 primary partitions; 32-bit LBA × 512 B ⇒ 2 TiB limitGPT (UEFI, 2000s)LBA 0protective MBRLBA 1GPT headerLBA 2–33128 entries × 128 BESPFAT32, 100+ MiBWindowsNTFSLinuxext4 / Btrfsbackup entrieslast LBAsbackup headerlast LBA64-bit LBA, 128 partitions, CRC32 checksum, backup at the end of the disk; each partition has a GUID and a type GUID
Figure 10.19: The MBR and GPT disk layouts.

MBR (master boot record) is the old format in use since 1983. The first sector of the disk, LBA 0, is 512 bytes. The first 446 bytes hold the boot loader code, followed by four 16-byte partition entries, and finally the signature 55 AA. Each entry keeps the start and the length of the partition as 32-bit sector numbers. Two limits follow from this. At most four primary partitions can be created; for more, logical partitions are chained inside an “extended” partition. The second and more serious limit is the largest addressable area: 232 × 512 B = 2 TiB. If a 3 TiB disk is partitioned with MBR, no partition can be defined on the last 1 TiB.

GPT (GUID partition table) is part of the UEFI standard and uses 64-bit LBAs. At LBA 0 sits a protective MBR; this dummy table prevents old tools that do not recognize GPT from thinking the disk is “empty” and writing over it. At LBA 1 is the GPT header, and at LBA 2–33 there are 128 partition entries of 128 bytes. Each partition has its own GUID and a type GUID indicating its type. The header and the entries are protected with a CRC32 checksum. Backups are kept at the end of the disk. Disks larger than 2 TiB and Windows 11 require GPT.

10.5.2Booting

The format of the partition table also determines how the machine boots (Figure 10.20). When power is applied, the hardware tests itself (POST). The following steps differ in the two schemes.

The old BIOS runs in 16-bit real mode and does not recognize file systems. It loads the first sector of the disk, the MBR, into memory and runs it. The MBR code finds the partition marked “active” in the partition table and runs its first block, the boot block. This block loads the real boot loader (GRUB; NTLDR in old Windows). UEFI, on the other hand, runs in 32 or 64 bits and has its own drivers and FAT file-system support. It looks for files, not sectors. It reads the boot entries in non-volatile memory (NVRAM) and loads the .efi program in the EFI system partition (ESP, formatted as FAT32). The active flag is not used. In both schemes the boot loader then loads the kernel; the difference lies only in how the boot loader is reached.

BIOS + MBR (old)UEFI + GPT (today)BIOS / POSTUEFI / POSTMBR code (446 B)NVRAM bootentryboot block of theactive partitionESP: \EFI\…\*.efiboot loader(GRUB, NTLDR)GRUB or WindowsBoot Managerkernelkernel +initramfs
Figure 10.20: The BIOS/MBR and UEFI/GPT boot chains.

PCs have shipped with UEFI since around 2012. The BIOS compatibility mode (CSM) has been removed from most new systems since 2020.

10.5.3The layout of a file system

The inside of a partition, although it varies with the file system, consists of similar parts (Figure 10.21). The first block of the partition is the boot block. This place is set aside even if the partition is not used for booting. The first block of the disk is the MBR; the two should not be confused.

Definition 10.7

The superblock is the block that holds the identity and basic parameters of the file system: the magic number, the block size, the numbers of blocks and i-nodes, the free counters, and the mount state. It is the first structure read when the file system is mounted.

The superblock is followed by the structure that tracks free space (a bitmap or a list), the i-node table with one i-node per file, the root directory, and the rest of the data blocks. In this layout every file access goes first to the i-node at the start of the disk and then to the distant data blocks. On a hard disk this means long arm movements. ext4 therefore divides the partition into block groups. With 4 KiB blocks each group has 32,768 blocks, that is, 128 MiB. Each group has its own bitmaps and i-node table. By placing a file's i-node and data in the same group, head movement is reduced. The idea comes from the cylinder groups of BSD's fast file system (FFS). Backups of the superblock and the group descriptors are kept in some groups; if the primary superblock is damaged, it is recovered from a backup.

DiskMBR / GPTpartition 1partition 2partition 3bootblocksuperblocksize, block countfree spacebitmap / listi-nodes1 per fileroot directoryfiles and directoriesdata blocksext4: the partition is divided into block groups (each 128 MiB, 32768 blocks with 4 KiB blocks)group 0group 1group 2…group nsuperblock*group descriptorblock bitmapi-node bitmapi-node tabledata blocks* backups of the superblock and descriptors are kept in some groups
Figure 10.21: The layout of a file system in a partition and the ext4 block groups.

10.5.4From i-node number to disk address

Because the i-node table lies in consecutive blocks, the location of an i-node is computed from its number. Three pieces of information from the superblock are needed for this: the block where the table starts, the block size, and the i-node size. The computation has three steps:

offset = n × i-node size,   (table block, offset in block) = (offset div block size, offset mod block size),   disk block = table start + table block

Example 10.6

The block is 4 KiB and the i-node 128 B. Block 0 is the superblock, blocks 1–2 are the bitmaps, and blocks 3–10 are the i-node table. i-node numbers start at 0; the disk is addressed with 512-byte sectors. Where on disk is i-node 77?

  1. i-nodes per block. 4096 / 128 = 32. The table holds 256 i-nodes in 8 blocks.
  2. Offset from the start of the table. 77 × 128 = 9856 = 2 × 4096 + 1664. The table's block 2 (counting from 0), byte 1664 inside the block; 1664 / 128 = 13, that is, the 13th i-node of that block.
  3. Disk block. 3 + 2 = block 5.
  4. Sector. The byte address is 5 × 4096 + 1664 = 22,144; 22,144 / 512 = 43.25 → sector 43, and inside it byte 0.25 × 512 = 128. There are 512 / 128 = 4 i-nodes in a sector.
disk blocks (4 KiB)Ssuper0iBi-bitmap1dBd-bitmap20–31332–63464–95596–1276128–1597160–1918192–2239224–25510data11data12data13data14data15…i-node table: 8 blocks × 32 = 256 i-nodesblock 2 of the table (from 0): i-nodes 64–95, 128 B each77016644096 Bsector 40sector 41sector 42sector 43sector 44sector 45sector 46sector 47
Figure 10.22: The location of i-node 77: block 2 of the table (disk block 5), byte 1664 inside the block, sector 43.

The “where is the i-node table” information in the superblock is indispensable for this computation. Two details are added in ext4. Numbers start at 1 and the table is divided into block groups. If there are g i-nodes per group, group = (n − 1) div g and the index within the group = (n − 1) mod g. With g = 8192 and an i-node size of 256 B, for i-node 20,000: 19,999 div 8192 = 2, 19,999 mod 8192 = 3615. The offset in the group's table is 3615 × 256 = 925,440 = 225 × 4096 + 3840: block 225 of the group's table, offset 3840.

Common mistake

Mistaking the table block for the disk block. 9856 div 4096 = 2 is the table's block 2; the disk block is found by adding the start of the table (3 + 2 = 5). Whether numbers start at 0 or 1 also shifts the computation by one i-node.

10.6Allocation methods

The central question in implementing a file system is this: how is it recorded where the blocks of a file are on disk? The recording method determines three things: how efficiently free space is used, whether the file can grow, and how quickly a block in the middle of the file can be reached. There are four basic methods: contiguous, linked-list, FAT, and indexed allocation.

10.6.1The same file, four methods

The file jeep in Silberschatz's example is five blocks long. Below we place it on a 32-block disk with the four methods; Figure 10.23 shows the indexed layout.

  • Contiguous: five blocks side by side, at 9–13. The directory entry has only the start (9) and the length (5). Block i = start + i.
  • Linked list: the blocks are scattered over the disk: 9, 16, 1, 10, 25. Each block carries the number of the next one; the directory entry knows the first and the last block.
  • FAT: the same chain, but the pointers are not in the blocks but in a table in memory: FAT[9] = 16, FAT[16] = 1, FAT[1] = 10, FAT[10] = 25, FAT[25] = EOF. The blocks are left entirely to data.
  • Indexed: all five addresses sit in order in a single index block (19): 9, 16, 1, 10, 25. Block i is accessed directly.
disk (32 blocks)02123456780931011121314151161718idx192021222324425262728293031directory entrynamejeepindex block19size5 blocksindex block 1991611025−1−1entry i = address of block i
Figure 10.23: Indexed allocation of the file jeep: the directory entry points to the index block (19), and the index block points to the five data blocks in order.

10.6.2Contiguous allocation

Definition 10.8

Contiguous allocation means placing each file in consecutive blocks on disk. The directory entry holds the (start, length) pair.

The advantages of the method are clear. It is simple to implement: only two numbers are stored. Random access is easy: the file's block i is start + i. The whole file is read with a single seek and sequential reads; on a hard disk there is no faster layout.

The drawbacks appear as time goes by. Table 10.10 follows Tanenbaum's example. A 40-block disk is full with seven files: A 4, B 3, C 6, D 5, E 12, F 6, G 4 blocks. D and F are deleted. Two holes are left behind: 5 blocks at 13–17 and 6 blocks at 30–35. There are 11 free blocks in total. Now file H of 8 blocks arrives. The total free space suffices, but no hole is 8 blocks: H does not fit.

Table 10.10: External fragmentation in contiguous allocation (40 blocks; recomputed with Python).
StateHoles (start, size)Total freeLargest hole
7 files, disk full—0—
D and F deleted(13, 5), (30, 6)116
H (8 blocks) arrives(13, 5), (30, 6)116 < 8 → does not fit
after compactionH goes to 29–36, (37, 3)33

This is the same as external fragmentation in memory management. One solution is compaction (defragmentation): E and G are shifted left, a single hole of 11 blocks forms, and H fits (Figure 10.24). The cost is high: 12 + 4 = 16 blocks on disk must be read and rewritten. The second problem of contiguous allocation is that the final size of the file must be known in advance. If a file wants to grow and the block behind it is occupied, it either cannot grow or must be moved entirely to another place.

A0A1A2A3B4B5B6C7C8C9C10C11C12E13E14E15E16E17E18E19E20E21E22E23E24G25G26G27G28H29H30H31H32H33H34H35H36373839compaction: G and E shifted, a single hole of 11 blocks → H fitscost: rewriting 16 blocks on disk
Figure 10.24: Compaction: G and E were shifted, a single hole of 11 blocks formed, and H was placed. The cost is rewriting 16 blocks.

Despite these drawbacks, contiguous allocation is still used today in media whose content is written once and does not change: CD-ROM and DVD file systems (ISO 9660, UDF) are like this. The method also has a modern descendant. The file is divided into several contiguous pieces instead of a single piece. These pieces are called extents; they are the basis of ext4 and NTFS.

10.6.3Linked-list allocation

Definition 10.9

In linked-list allocation each block carries the number of the file's next block. The directory entry knows the first block (and, in Silberschatz's layout, the last block).

There is no external fragmentation in this method: any free block can be appended to the end of the file. The file grows easily and its size need not be known in advance. Internal fragmentation exists here as in every method: the unfilled part of the last block is wasted.

The problem is random access. The blocks of file A in Figure 10.25 are in the chain 4 → 7 → 2 → 10 → 12. Suppose we want to read logical block 3 (counting from 0). The directory entry knows only physical 4. Physical 4 is read: the next is 7. 7 is read: the next is 2. 2 is read: the next is 10. Only now is it clear that physical 10 is logical block 3, and it is read. For a single block, 4 disk reads have been made. Logical block k takes k + 1 reads; random access is O(n). On a hard disk each of these reads may also be a separate seek.

File Ablock 0data7physical 4block 1data2physical 7block 2data10physical 2block 3data12physical 10block 4data−1physical 12File Bblock 0data3physical 6block 1data11physical 3block 2data14physical 11block 3data−1physical 14read: 4 blocks
Figure 10.25: Linked-list allocation: to reach logical block 3 of A (physical 10), 4 blocks are read.

There are two more small problems. Because a few bytes of each block go to the pointer, the amount of data in a block is 4096 − 4 = 4092 bytes. This number is not a power of two; for programs working with 4096-byte pages each read spreads over two blocks. The second is reliability: if a single pointer is damaged, the rest of the chain, that is, the end of the file, is lost.

10.6.4FAT: allocation with a table

The remedy for both problems of the linked list is to take the pointers out of the blocks. The pointers are gathered in a single table at the beginning of the disk: the file allocation table (FAT). Entry i of the table is the number of the block that comes after block i. Free blocks are marked 0, and the end of a chain is marked with a special EOF value. The blocks are now entirely data.

FAT (in memory): entry i = the block after block i0rsv.1rsv.210311475free63728free9free1012111412EOF13free14EOF15freeA: start 4B: start 6A chain: 4 → 7 → 2 → 10 → 12
Figure 10.26: In the FAT table, the chain 4 → 7 → 2 → 10 → 12 of file A; file B is 6 → 3 → 11 → 14.

There are two files in the table in Figure 10.26. For A: entry 4 = 7, entry 7 = 2, entry 2 = 10, entry 10 = 12, entry 12 = EOF. For B: 6 → 3 → 11 → 14 → EOF. Random access still requires following the chain, but since the table is in memory, the chain is followed in memory: there is no disk read. Because the table is so important, it is kept on disk in two copies.

The real problem of FAT is its size. The table has an entry for every block on the disk; the table grows in proportion to the disk size and must reside entirely in memory to be fast.

Example 10.7

A 200 GiB disk is divided into 1 KiB blocks; each FAT entry is 4 bytes. How much memory does the table need?

  1. Number of blocks: 200 × 230 / 210 = 200 × 220 = 209,715,200.
  2. Table: 209,715,200 × 4 B = 838,860,800 B = 800 MiB. Even if the entry is squeezed to 3 bytes, 600 MiB.

Real FAT32 uses clusters made of several blocks instead of blocks. A 2 TiB volume with 32 KiB clusters has 241 / 215 = 67,108,864 clusters; with 4-byte entries the table is 256 MiB.

10.6.5Code trace: a FAT chain

The function below finds the disk block that contains byte number off in a file whose first block is first. The block size is BLOCK = 1024 bytes; fat is the table in memory and END marks the end of the chain.

int find_block(int first, long off) {
  int b = first;
  long n = off / BLOCK;  /* block index */
  while (n > 0 && b != END) {
    b = fat[b];          /* follow chain */
    n--;
  }
  return b;          /* END: past EOF */
}

n = off / BLOCK is an integer division and gives which block of the file (counting from 0) the wanted byte is in. The loop advances n steps along the chain; at each step b moves to the next block. The loop's second condition, b != END, is a guard against the chain ending early. If the requested block is not in the file, the function returns END. The running time is O(n), but each step is only a memory access.

Let us trace two calls (Table 10.11). In find_block(4, 3500), file A starts at block 4. 3500 / 1024 = 3: the wanted byte is in the file's block 3, and one must advance 3 steps along the chain. fat[4] = 7 (n = 2), fat[7] = 2 (n = 1), fat[2] = 10 (n = 0). The loop ends; the disk block is 10. Byte 3500 is byte 3500 − 3 · 1024 = 428 of this block.

Table 10.11: Trace of find_block (run by translating it one to one into Python).
Calln at startChain followed (b, n)Returns
find_block(4, 3500)3(4, 3) → (7, 2) → (2, 1) → (10, 0)10; byte 428 in the block
find_block(6, 5000)4(6, 4) → (3, 3) → (11, 2) → (14, 1) → (END, 0)END: past the end of the file
FAT (in memory) · A: 4→7→2→10→12 · B: 6→3→11→140·1·210311475·63728·9·1012111412END13·14END15·followed: 4 → 7 → 2 → 10blue: file blocks · green: followed · orange: b
Figure 10.27: The last step of find_block(4, 3500): the chain followed is 4 → 7 → 2 → 10.

find_block(6, 5000) is more instructive. File B is 4 blocks, so it holds at most 4096 bytes. 5000 / 1024 = 4: the file's block 4 (the fifth block) is requested. The chain goes 6 → 3 → 11 → 14; at the fourth step fat[14] = END arrives and n = 0. The file has no block 4; the offset lies outside the file. A read from this offset returns 0 bytes (end of file). If a write is made at the same offset, the file system allocates a new block and links it to the entry of 14.

Example 10.8

The cluster size is 4 KiB; in the FAT, FAT[5] = 9, FAT[9] = 2, FAT[2] = 11, FAT[11] = EOF. The first cluster of slides.pptx is 5. In which clusters does the file lie, and in which cluster is byte 9000?

  1. 9000 / 4096 = 2 (integer division): the byte is in the file's cluster 2 (counting from 0).
  2. The chain: 5 (cluster 0) → 9 (1) → 2 (2) → 11 (3) → EOF. The file is in 4 clusters; it holds at most 16 KiB and is scattered on disk.
  3. Cluster 2 of the file is physical cluster 2. The position inside the cluster is 9000 − 2 × 4096 = byte 808.

10.6.6The FAT family

The name FAT describes a family running from MS-DOS to today. The family members are named by the number of bits in the FAT entry (Table 10.12). The wider the entry, the more clusters can be addressed.

Table 10.12: FAT12, FAT16, FAT32, and exFAT.
FAT12FAT16FAT32exFAT
FAT entry12 bits16 bits28 bits used32 bits
Largest volume≈ 16 MiB2 GiB (32 KiB cluster)2 TiB (512 B sector)128 PiB
Largest fileas large as the volume2 GiB4 GiB − 1 byte16 EiB (theoretical)
Free space0 in the FAT0 in the FAT0 in the FAT + FSInfo hintseparate bitmap
Usefloppy diskold disksUSB, UEFI ESPSDXC/SDUC, large USB

In FAT the directory entry carries everything: name, extension, attributes, time, date, first cluster, and size (Figure 10.28). Since the size field is 32 bits, a file in FAT32 can be at most 4 GiB − 1 bytes. A 4 GiB movie file cannot be copied to a FAT32-formatted USB stick. exFAT removes this limit. It also keeps free space in a separate bitmap and, for files known to be contiguous, may not use the FAT chain at all. Windows's graphical formatting tool has historically limited FAT32 to 32 GB; this limit belongs to the tool, not to the file system.

MS-DOS directory entry (32 bytes)Name8 BExtension3 BAttr1 BReserved10 BTime2 BDate2 BCluster2 BSize4 BAttr: attributes. FAT32: the creation/access times and the upper 16 bits of the first cluster went into the “reserved” field; long names in extra entries.
Figure 10.28: The 32-byte directory entry of MS-DOS. In FAT32 the creation and access times and the upper 16 bits of the first cluster were placed in the “reserved” field.

10.6.7Indexed allocation and the i-node

Definition 10.10

In indexed allocation all the block addresses of a file are gathered in an index block; entry i is the address of block i. In UNIX this structure is called an i-node (index node). The i-node holds the file's block addresses and attributes together.

Indexed allocation keeps the good sides of the linked list: there is no external fragmentation, and the file grows wherever there are free blocks. On top of that it speeds up random access: the address of block i is in entry i of the index block, and there is no chain to follow.

A big advantage of the i-node over FAT lies in memory use. An i-node is in memory only while the file is open. If K files are open, the memory needed is K × the i-node size. Unlike FAT, it is proportional not to the disk size but to the number of open files. With 1000 open files and 256-byte i-nodes, 256,000 bytes (about 250 KiB) suffice, whether the disk is 1 TB or 100 TB.

The price is twofold. Even for a small file, space is spent on the index. Because the i-node has a fixed size, the addresses of a large file do not all fit in it. The solution is to use the last few entries of the i-node to point not to data blocks but to other index blocks: indirect blocks.

i-nodemode (type, permissions)UID, GIDsize, block counttimes (a/m/c)link countdirect 0…direct 11single indirectdouble indirecttriple indirectdatadatasingledatadatadoublesingledatadatatripledoublesingledata4 KiB block, 4 B pointer:1024 addresses per block12 direct48 KiBsingle indirect+ 4 MiBdouble indirect+ 4 GiBtriple indirect+ 4 TiBeach level ×1024
Figure 10.29: The UNIX i-node: attributes, 12 direct block addresses, and single, double, and triple indirect blocks. With 4 KiB blocks each level multiplies the capacity by 1024.

Figure 10.29 shows the structure of ext2/ext3 and classical UNIX. The i-node has 12 direct pointers; the addresses of the first 12 blocks of the file are directly here. The 13th pointer is single indirect: it points not to data but to an index block full of addresses. The 14th pointer is double indirect: it points to an index block that points to index blocks. The 15th pointer is triple indirect: one more level. Small files use only the direct pointers and no indirect block is ever allocated. As the file grows, the tree gets deeper. In V7 UNIX the number of direct pointers was 10.

10.6.8Maximum file size

With this structure the largest size a file can have can be computed. Assumptions: the block is 4 KiB = 4096 B and a block address is 4 B. An index block holds 4096 / 4 = 1024 addresses; let P = 1024.

Example 10.9

The i-node has 12 direct, 1 single, 1 double, and 1 triple indirect pointer. How many bytes is the largest file?

  1. Direct: 12 blocks × 4 KiB = 48 KiB (49,152 B).
  2. Single indirect: one index block points to 1024 data blocks: 1024 × 4 KiB = 4 MiB.
  3. Double indirect: each of 1024 index blocks points to 1024 data blocks: 10242 = 1,048,576 blocks = 4 GiB.
  4. Triple indirect: one more level: 10243 = 1,073,741,824 blocks = 4 TiB.
  5. Total: 12 + 1024 + 10242 + 10243 = 1,074,791,436 blocks; × 4096 = 4,402,345,721,856 B ≈ 4.004 TiB.

Almost all of the size comes from the triple indirect block; the contribution of the direct pointers is negligibly small.

The general formula is: with D direct pointers, block size B, and address size a, P = B / a and the maximum size is (D + P + P2 + P3) × B. In Tanenbaum's example the block is 1 KiB, the address 4 B (P = 256), and there are 10 direct pointers: 10 + 256 + 65,536 + 16,777,216 = 16,843,018 blocks, about 16 GiB.

This calculation is only the limit of the pointer structure. In real systems other limits come into play earlier. In ext2/ext3 the block counter in the i-node is 32 bits and counts 512-byte units. With 4 KiB blocks the real limit is 232 × 512 B = 2 TiB. ext4 raises this limit to 16 TiB with extents.

Common mistake

Taking the double indirect capacity to be 2 × 1024 blocks. The double indirect block points to 1024 index blocks and each of them to 1024 data blocks: the product is 10242. Each level of indirection multiplies the capacity by P; it does not add P.

10.6.9From file offset to disk block

In a read call the file system converts a byte offset to a disk block. First the logical block number is found: lb = offset div 4096. Then one looks at which region this number falls into. For the same structure (12 direct, P = 1024) the regions are:

  • lb < 12: direct pointer lb. If the i-node is in memory, 1 read (the data).
  • 12 ≤ lb < 12 + 1024: entry (lb − 12) of the single indirect block. 2 reads.
  • the next 10242 blocks: double indirect. r = lb − 1036; outer index r div 1024, inner index r mod 1024. 3 reads.
  • the next 10243 blocks: triple indirect. r = lb − 1,049,612; indices r div 10242, (r div 1024) mod 1024, and r mod 1024. 4 reads.
Table 10.13: Translating four offsets (4 KiB block, 12 direct; verified with Python).
Offset (B)Logical blockLevel and indicesOffset in blockReads
40.0009direct 931361
1.000.000244single indirect [232]5762
5.000.0001220double indirect [0][184]28803
6.000.000.0001.464.843triple indirect [0][405][511]30724

The rows of the table can be followed one by one. 40,000 / 4096 = 9 and 9 < 12: direct pointer 9 gives the address of the block. 1,000,000 / 4096 = 244; since 244 − 12 = 232 < 1024, entry 232 of the single indirect block is consulted. 5,000,000 / 4096 = 1220; 1220 − 12 − 1024 = 184 falls in the double indirect region: outer index 184 div 1024 = 0, inner index 184. For 6 GB, 6,000,000,000 / 4096 = 1,464,843. Subtracting 12 + 1024 + 10242 = 1,049,612 leaves 415,231. The three indices are 415,231 div 10242 = 0, (415,231 div 1024) mod 1024 = 405, and 415,231 mod 1024 = 511.

offset → logical block40,000 Bblock 9 · direct1,000,000 Bblock 244 · single indirect5,000,000 Bblock 1,220 · double indirect6,000,000,000 Bblock 1,464,843 · triple indirecti-nodedirect 0–11single indirectdouble indirecttriple indirect[0]index[405]index[511]indexdataoffset in block = 6,000,000,000 mod 4096 = 3,072disk reads (if the i-node is in memory): 4
Figure 10.30: The path of byte 6,000,000,000: i-node → triple indirect block [0] → double indirect block [405] → single indirect block [511] → data. 4 reads if the i-node is in memory.

The read counts are worst cases. A program reading sequentially refers to the same indirect blocks again and again; the cache keeps the first levels in memory and most of the extra reads disappear.

Example 10.10

Logical block 699 of a file of 1000 blocks is to be read. The directory entry and the i-node are in memory; nothing else is in the cache. The block is 4 KiB, the address 4 B, and the i-node has 12 direct pointers. How many disk reads are needed with the four methods?

  1. Contiguous: 1. Address = start + 699.
  2. Linked list: 700. The address of block 699 cannot be learned without reading blocks 0 … 698; 699 is read too.
  3. FAT: 1. 699 steps are followed in memory along the chain, then a single read is made.
  4. i-node: 2. 699 − 12 = 687 < 1024: the single indirect block and the data block.

10.6.10Extents and NTFS

The classical i-node keeps a separate address for each block. For a large and mostly contiguous file this is very wasteful: to describe 32,768 consecutive blocks, 32,768 addresses are written. ext4 uses extents instead.

Definition 10.11

An extent is a triple (logical start, length, physical start) that describes a contiguous sequence of blocks with a single record.

i_block in the i-node (60 bytes)extent header · 0xF30A · entry 3 / 4 · depth 0logical 0 · length 1,000 · physical 34,000logical 1,000 · length 32,768 · physical 120,000logical 33,768 · length 200 · physical 9,100(empty entry)disk0160,0003 extents × 12 B = 36 B, no extra blockblock map: 33,968 pointers = 35 index blocks (140 KiB)extent ≤ 32,768 blocks = 128 MiB
Figure 10.31: The extent header and three extents in an ext4 i-node; each extent describes a contiguous region on disk.

The file in Figure 10.31 consists of three extents. 1000 blocks starting at logical 0 are at physical 34,000, 32,768 blocks starting at logical 1000 are at physical 120,000, and 200 blocks starting at logical 33,768 are at physical 9100. The file is 33,968 blocks in total. Since each extent takes 12 bytes, three extents fit in 36 bytes; there is room in the i-node's 60-byte i_block field and no extra block is needed. The same file with the classical block map needs 33,968 pointers. These spread over 12 direct pointers, 1 single indirect block, 1 double indirect block, and the 33 index blocks it points to: 35 index blocks, that is, 140 KiB.

In ext4 the physical address is 48 bits: with 4 KiB blocks a volume can grow up to 1 EiB. A file can be at most 16 TiB. One extent describes at most 32,768 blocks (128 MiB). Four extents fit in the i-node; if more are needed, the entries point to the index nodes of an extent tree. Extents pay off only if the file is actually written contiguously. ext4 uses delayed allocation for this: data waits in memory first, and blocks are chosen only when it is written to disk. Since by then it is known how large the file has grown, the multiblock allocator can find large contiguous areas. XFS, Btrfs, APFS, and NTFS also use extents.

At the center of NTFS lies the master file table (MFT) (Figure 10.32). In NTFS everything is a file; the MFT itself is record 0 of the MFT. The first records are reserved for the system's own metadata files: $MFTMirr (backup), $LogFile (journal), $Volume, the root directory (record 5), $Bitmap (the free-cluster bitmap), and so on. User files start from record 24.

MFT (1 KiB records)0$MFT1$MFTMirr2$LogFile3$Volume5. (root directory)6$Bitmap8$BadClus9$Secure……≥ 24user filesMFT record of a fileheader$STANDARD_INFORMATION$FILE_NAME$DATA (run list)times, attribute flagsname, parent directoryrun: (start, length)20, 464, 280, 3cluster 0cluster 100in a small file the data is inside the record: resident $DATA
Figure 10.32: The NTFS master file table: the metadata files, and the attributes and data runs of a file record.

Each file is at least one 1 KiB MFT record, and the content of the record is a list of attributes. $STANDARD_INFORMATION holds the times and flags, and $FILE_NAME the name and the parent directory. The data itself is also an attribute: $DATA. The data of a small file fits inside the record; this is called resident data, and no other block is read to read the file. Large data, by contrast, is kept as a run list. In the example, (20, 4), (64, 2), (80, 3) are three extents. Directories are B+ trees ($INDEX_ROOT, $INDEX_ALLOCATION). NTFS also supports hard links, reparse points, alternate data streams (ADS), compression, EFS encryption, and quotas. On Windows servers there is, in addition, ReFS, which uses copy-on-write and keeps checksums.

10.6.11Comparing file systems

Table 10.14 compares today's common file systems by their limits and crash-consistency methods.

Table 10.14: Comparison of file systems (* theoretical limit; the operating system and the cluster size impose a lower limit).
File systemLargest fileLargest volumeCrash consistencyTypical use
FAT324 GiB − 1 B2 TiBnone (chkdsk/fsck)USB, UEFI ESP
exFAT16 EiB*128 PiBnoneSD card, external disk
NTFS16 EiB* (Windows: 256 TiB–8 PiB)256 TiB–8 PiBmetadata journalWindows
ext416 TiB (4 KiB block)1 EiBjournal (jbd2)Linux, Android
XFS8 EiB8 EiBmetadata journalRHEL, large servers
Btrfs16 EiB16 EiBcopy-on-write + checksumsFedora, openSUSE, NAS
ZFS16 EiB2128 B (theoretical)copy-on-write + checksumsFreeBSD, TrueNAS, servers
APFS8 EiB8 EiBcopy-on-write, snapshotsmacOS, iOS

Since version 1709 of Windows 10, NTFS reaches volumes of 8 PiB with 2 MiB clusters. Apple's old HFS+ gave way to APFS in 2017, and on Linux ext3 gave way to ext4.

10.7Implementing directories

10.7.1Directory entries and long names

When a file is opened, the directory entry must supply enough information to find the file's data. This information varies with the allocation method. With contiguous allocation the address of the first block suffices, with linked lists and FAT the number of the first block, and in UNIX the i-node number. Where the attributes are kept is solved in two ways (Figure 10.33). (a) In MS-DOS the attributes and the disk address are directly inside the directory entry. (b) In UNIX the directory entry is only a name and an i-node number; the attributes are in the i-node. The second layout makes hard links possible: two entries pointing to the same i-node share the same attributes.

(a) attributes in the entry (MS-DOS)gamesattributes + disk addressmailattributes + disk addressnewsattributes + disk addressworkattributes + disk address(b) attributes in the i-node (UNIX)games14i-nodemail7i-nodenews29i-nodework51i-node(c) variable length, inlinelengthi-node · typeproject-budgetlengthi-node · typepersonnellengthi-node · typefooext4 entry: i-node, rec_len, name length, type, name(d) fixed entries + name heapname pointerattributesname pointerattributesname pointerattributesheapproject-budgetpersonnelfooentries aligned; names at the end of the directory block
Figure 10.33: Directory entry formats: (a) attributes in the entry, (b) attributes in the i-node, (c) variable-length entries, (d) fixed entries and a name heap.

Long names are a separate problem. Reserving a fixed 255-character name field for every entry wastes a lot of space, because most names are short. There are two solutions. (c) In variable-length entries each entry carries its own length, and the name sits inside the entry. ext4's entry is like this: the i-node, the entry length (rec_len), the name length, the type, and the name. When a file is deleted, a hole is left in the place of the entry. A new entry may not fit into this hole. If an entry falls on a page boundary, another page fault may occur while reading. (d) In the second solution the entries are fixed-length and aligned. Each entry carries a name pointer instead of the name itself; the names sit in a heap at the end of the directory block. Scanning the entries becomes easier, but the heap must be managed separately.

10.7.2Searching a directory

At each step of path resolution a name is searched for in a directory. The speed of the search depends on how the directory is kept (Figure 10.34).

The linear list is the simplest structure: entries sit one after another and the search scans from beginning to end. In the list in Figure 10.34, finding report.pdf takes 7 comparisons, against ., .., notes.txt, photo.png, homework, makefile, and report.pdf. The search is O(n). Before a new name is added, one must check that the same name does not exist, which means a full scan. On deletion the entry is marked empty, or the last entry is moved into the place of the deleted one.

linear list...notes.txtphoto.pnghomeworkmakefilereport.pdfthesis.docxhash table (8 buckets)01234567h("report.pdf") mod 8 = 5report.pdfthesis.docxh("thesis.docx") mod 8 = 5 → collisionat most 2 comparisons in the chainnotes.txt
Figure 10.34: A linear list and a hash table with 8 buckets. report.pdf and thesis.docx fall into the same bucket (5); the collision is resolved with a chain.

A hash table chooses a bucket from the digest of the name: h("report.pdf") mod 8 = 5. The search is O(1) on average. Two names can fall into the same bucket; in the figure thesis.docx also falls into 5. This collision is resolved with a chain hanging off the bucket, and at most 2 comparisons are made in the chain. A fixed number of buckets becomes a problem in a growing directory: in a directory of 100,000 entries each chain of 8 buckets has an average length of 12,500 entries and the search turns linear again. Hashing also does not preserve order; ls has to sort the entries separately for alphabetical output.

Modern systems therefore use trees. For large directories ext4 builds an htree ordered by the name digest. NTFS, XFS, and Btrfs use a B+ tree. In a B+ tree the search is O(log n) and the entries can be listed in order; two advantages are obtained at once. Linux also keeps the most recently used name → i-node mappings in the in-memory dentry cache; frequently opened paths are resolved without ever going down to the disk.

10.8Free-space management

10.8.1Choosing the block size

The disk is divided into fixed-size blocks; choosing the block size is a trade-off between two goals. A large block brings a lot of data in one seek and raises the data rate. With small files, however, most of the block stays empty and space is wasted. A small block does the opposite.

Tanenbaum's model shows this trade-off in numbers (Figure 10.35). The disk's average seek time is 5 ms and its rotation time 8.33 ms; a track holds 1 MB. The time to read a block is the sum of the seek, the average wait of half a rotation, and the transfer time:

time = 5 + 4.165 + (b / 1 MB) × 8.33 ms

Let all files be 4 KiB. With 4 KiB blocks a read takes 9.198 ms: the data rate is 4096 B / 9.198 ms ≈ 0.45 MB/s. With 128 KiB blocks a read takes 10.206 ms but brings 131,072 bytes: ≈ 12.8 MB/s. The data rate has risen by a factor of about 29. On the other hand, a 4 KiB file fills only 4/128 = 3.1% of a 128 KiB block. For blocks ≤ 4 KiB the space efficiency is 100%; it falls to 50% at 8 KiB and to 3.1% at 128 KiB.

024681012140%25%50%75%100%1248163264128block size (KiB, logarithmic)MB/sdata rate (MB/s)space efficiency (%)0.4512.8
Figure 10.35: As the block size grows, the data rate rises and the space efficiency for 4 KiB files falls (Tanenbaum's model; computed with Python).
Table 10.15: The block-size model (seek 5 ms, rotation 8.33 ms, track 1 MB = 220 B, files of 4 KiB).
BlockRead time (ms)Data rate (MB/s)Space efficiency
1 KiB9,1730,11%100
4 KiB9,1980,45%100
16 KiB9,2951,76%25
64 KiB9,6866,77%6,25
128 KiB10,20612,84%3,1

Measurements of real file sizes paint an interesting picture. Most files are small, but most of the disk space is taken up by a small number of large files. Today the default block size is 4 KiB, the same as the page size. Large files are supported with extents and cluster options: the block stays small, but the blocks of a large file are allocated contiguously.

10.8.2Four methods

The file system must know which blocks are free. In Silberschatz's example, 15 blocks of a 32-block disk are free: 2–5, 8–13, 17–18, and 25–27. The same set of free blocks can be kept in four ways.

Definition 10.12

A bitmap is an array that keeps one bit per block. In these notes and in the example in the slides 1 = free and 0 = in use; some systems use the opposite.

In the bitmap, 32 blocks take 32 bits, that is, 4 bytes (Figure 10.36). For example, the bitmap is 00111100 11111100 01100000 01110000. The size of the bitmap is fixed and small. Finding contiguous free blocks is easy: look for consecutive 1s. Because processors can find the first 1 bit in a word with a single instruction, finding the first free block is fast: the first nonzero word is found, and the first 1 bit in it is taken. For the bitmap to be fast, it must be kept in memory.

disk: green = free012345678910111213141516171819202122232425262728293031bitmap (1 = free)block 0–700111100block 8–1511111100block 16–2301100000block 24–310111000032 blocks → 32 bits = 4 bytesfirst free: the first 1 bit in the first nonzero word
Figure 10.36: The bitmap of a 32-block disk (1 = free): 15 free blocks, 32 bits = 4 bytes.

In the linked list the free blocks are chained together. A head pointer points to the first free block (2); each free block carries the number of the next: 2 → 3 → 4 → 5 → 8 → … → 13 → 17 → 18 → 25 → 26 → 27 → −1. No extra space is needed, because the information lies inside the free blocks. Taking a single free block is cheap: the head of the list is given. But finding many or contiguous free blocks is expensive; walking the list means an I/O for each block.

Grouping improves the linked list. The first free block holds the addresses of the next n − 1 free blocks and the block of the next group. With n = 4 the groups in the example are: block 2 → {3, 4, 5}, next group 8; block 8 → {9, 10, 11}, next 12; block 12 → {13, 17, 18}, next 25; block 25 → {26, 27}, end. With a single read, n − 1 free blocks are found. The free-list blocks of classical UNIX worked this way.

The counting method exploits the fact that free blocks are often found in contiguous runs. Each run is kept as a (first block, number of consecutive blocks) pair (Figure 10.37). The 15 free blocks in the example are just 4 pairs: (2, 4), (8, 6), (17, 2), (25, 3). This is the extent idea applied to free space. XFS keeps the counting pairs in two B+ trees, one ordered by start and one by length; thus both the question “free space near this block” and the question “a free run of at least this size” are answered quickly.

disk: green = free012345678910111213141516171819202122232425262728293031counting: (first block, consecutive count)(2, 4)block 2–5(8, 6)block 8–13(17, 2)block 17–18(25, 3)block 25–2715 free blocks → 4 pairsvery short if the free space is in contiguous runs
Figure 10.37: Counting: 15 free blocks are described by 4 (start, length) pairs.
Example 10.11

On a 32-block disk the free blocks are 3–6, 10–11, 20–24, and 30. How are they represented with the counting method and with a bitmap (1 = free, block 0 at the far left)?

  1. Counting: the start and the length of each run: (3, 4), (10, 2), (20, 5), (30, 1).
  2. Bitmap: 00011110 for blocks 0–7, 00110000 for 8–15, 00001111 for 16–23, 10000010 for 24–31.

The bitmap is 32 bits however full the disk is. The length of the counting list, however, depends on the number of runs; it is very short when the disk is full or when the free space is in large runs.

10.8.3Code trace: allocating a block with a bitmap

The function below looks for a free block in the bitmap of a disk of N = 16 blocks. In this code the meaning of the bitmap is reversed: bitmap[i] == 1 means the block is in use and 0 means free. The search starts from block number hint and wraps around to the beginning when it reaches the end of the array.

int alloc_block(int hint) {
  for (int k = 0; k < N; k++) {
    int i = (hint + k) % N;
    if (bitmap[i] == 0) {  /* free? */
      bitmap[i] = 1;
      return i;
    }
  }
  return -1;               /* disk full */
}

i = (hint + k) % N is the position k steps ahead of hint; the mod operation makes the search return to 0 after 15. When the first free block is found, its bit is set to 1 and its number is returned. If all the blocks are in use, the loop ends after N turns and −1 is returned. In the worst case the time is O(N). The purpose of the hint parameter is locality: if the file's new block is searched for right after its last block, the blocks fall close to one another and head movement is reduced in sequential reading.

Initially the bitmap is 1 1 0 1 1 1 0 0 1 1 1 0 1 0 1 1 (from block 0 to 15). The free blocks are 2, 6, 7, 11, and 13. A file ends at block 3 and wants 3 more blocks. The hint of each call is one more than the file's current last block. Table 10.16 gives the trace.

Table 10.16: Trace of alloc_block (run by translating it one to one into Python).
CallPositions examined (i)ReturnsBlocks of the file
alloc_block(4)4 (in use), 5 (in use), 6 (free)6…, 3, 6
alloc_block(7)7 (free)7…, 3, 6, 7
alloc_block(8)8, 9, 10 (in use), 11 (free)11…, 3, 6, 7, 11
bitmap: 1 = in use, 0 = free10110213141516171819110111112013114115iblocks of the file: 6, 7, 11green: allocated to this file
Figure 10.38: The bitmap after three calls: blocks 6, 7, and 11 were allocated to the file.

The file took blocks 6, 7, and 11. The blocks are not contiguous but are close to one another. If the search had no hint and always started from 0, the first call would have given block 2; the file would have gone back to the beginning of the disk. If the hint is near the end, wrap-around comes into play: with the same initial bitmap, alloc_block(14) finds 14 and 15 in use, also passes 0 and 1, and returns block 2.

10.8.4Numerical comparison

How much space the bitmap and the free-block list take can be computed on a large disk (Table 10.17). In the list each block number is 32 bits. A 1 KiB list block holds 256 numbers: 255 free-block addresses and 1 link to the next list block.

Table 10.17: The size of the free-space record (with the disk completely empty; computed with Python).
Tanenbaum's exampleModern example
Disk / block500 GB, 1 KiB block1 TiB, 4 KiB block
Number of blocks500 × 109 / 1024 ≈ 488.3 million240 / 212 = 268.435.456
List block1 KiB / 4 B = 256 → 255 addresses + 1 link4096 / 4 = 1024 → 1023 addresses + 1 link
List, with the disk empty488.3 M / 255 ≈ 1.91 million blocks268.4 M / 1023 ≈ 262,401 blocks (≈ 1 GiB)
Bitmap488.3 M bits / 8192 ≈ 59,605 blocks228 bits = 32 MiB = 8192 blocks

In Tanenbaum's example the number of blocks is 500 × 109 / 1024 = 488,281,250. With the disk completely empty the list takes 488,281,250 / 255 ≈ 1,914,828 blocks. The bitmap means one bit per block: a 1 KiB block carries 8192 bits, and 488,281,250 / 8192 ≈ 59,605 blocks suffice. The bitmap is about 32 times smaller than the list. The list is small only when the disk is nearly full, because it lists only the free blocks. The size of the bitmap is independent of how full the disk is.

Tanenbaum (500 GB, 1 KiB)bitmap59,605free list1,910,000Modern (1 TiB, 4 KiB)bitmap8,192free list262,401number of blocks, with the disk completely empty
Figure 10.39: The number of blocks of the bitmap and of the free list when the disk is empty.

The list has an advantage too: it is enough to keep a single list block in memory. When the block fills, it is written to disk; when it empties, a new one is read. This simple policy has a trap. If, while the block in memory is exactly full, a temporary file of three blocks is deleted, the block overflows and is written to disk. If the same file is created again right afterwards, the block empties and a new one is read from disk. Temporary files thus cause constant disk I/O. The solution Tanenbaum proposes is to keep the pointer block in memory half full; then both allocation and release proceed for a while without disk I/O.

Real systems use combinations of these methods. ext4 keeps a separate bitmap for each block group. XFS implements the counting method with two B+ trees. ZFS uses a space map that accumulates allocation and release records like a journal. Btrfs tracks free and used space in the extent tree.

10.8.5Disk quotas

On a multiuser system a single user must not fill the whole disk. A quota limits the number of blocks and files each user may use (Figure 10.40). When a file is opened, its entry in the open-file table points to its owner's quota record. At every new block or i-node allocation the user's counters are incremented and compared with the limits.

open-file tableattributes, addressesattributes, addressesattributes, addressesattributes, addressesentry: user = aliquota pointerquota table (one record per user, ali)block soft limit9 GiBblock hard limit10 GiBblocks used9.4 GiBwarning / time left6 daysfile soft limit90,000file hard limit100,000files used41,250soft limit exceeded: warning + grace period started
Figure 10.40: The open-file entry points to the user's quota record. ali's usage of 9.4 GiB has exceeded the soft limit of 9 GiB; a warning was issued and the grace period has begun.

Each limit has two levels. The soft limit can be exceeded; the user is warned and a grace period (for example 7 days) begins. Within this period the user must drop below the limit by deleting files. The hard limit can never be exceeded. If the period ends or the hard limit is reached, writing is rejected with the EDQUOT error. In the figure, ali has used 9.4 GiB and exceeded the soft limit of 9 GiB; 6 days remain, and ali can write up to the hard limit of 10 GiB. In the number of files, with 41,250 files, ali is far below the soft limit of 90,000. Today Linux has quota tools (project quotas on ext4 and XFS), NTFS has volume quotas, ZFS has dataset quotas, and Btrfs has subvolume (qgroup) quotas.

10.9Performance

10.9.1How many I/Os does it take to create a file?

To see how much work file-system calls put on the disk, let us consider a simple file system without a cache. Let it use i-nodes and a bitmap, and let each directory fit in a single block. Let the location of the root directory's i-node be known from the superblock. Counting of this kind in the OSTEP book by Arpaci-Dusseau and Arpaci-Dusseau reveals the hidden cost behind the calls. Table 10.18 lists the I/Os of four operations.

Table 10.18: Disk I/Os of calls in a file system without a cache.
CallI/O sequenceTotal
open("/course/note.txt"), file existsread root i-node, root data, course i-node, course data, note i-node5 = 5 reads
read(fd, buf, 4096)read note i-node, note data[0]; write note i-node (access time)3 = 2 reads + 1 write
creat("/course/note.txt"), file does not existread root i-node, root data, course i-node, course data, i-bitmap; write i-bitmap, course data; read note i-node; write note i-node, course i-node10 = 6 reads + 4 writes
write(fd, buf, 4096), new blockread note i-node, d-bitmap; write d-bitmap, note data, note i-node5 = 2 reads + 3 writes

Opening is proportional to the path length: an i-node and a data block for each directory, and at the end the file's i-node. The read finds the block address in the i-node, reads the block, and updates the access time in the i-node. The last write is often eliminated by the noatime or relatime mount options.

Creating is much more expensive. First the path is resolved (4 reads). Then a free i-node is chosen from the i-node bitmap and marked (1 read, 1 write). A new entry is added to the directory (1 write). The block that contains the new i-node is read, the i-node is initialized, and it is written (1 read, 1 write). Finally the size and time are updated in the directory's i-node (1 write). The total is 10 I/Os. Each write that needs a new block also costs 5 I/Os: the i-node is read, a block is chosen and marked in the data bitmap, the data is written, and the new address and size are written to the i-node. Only one of these 5 I/Os is the actual data.

creat + 3 × write(4096): 10 + 3 × 5 = 25 I/Osreadwritethe 3 boxes with thick borders are user data; the remaining 22 I/Os are metadata (bitmaps, i-nodes, directory)cache: reads come from memory · delayed write: the same block is written once→ 8 writes remain: i-bitmap, d-bitmap, course data, course i-node, note i-node, 3 data blocks
Figure 10.41: creat and three 4 KiB writes: 10 + 3 × 5 = 25 I/Os. The three boxes with thick borders are user data; the remaining 22 I/Os are metadata.

Creating a file without a cache and writing 12 KiB thus costs 10 + 3 × 5 = 25 I/Os (Figure 10.41). Only three of them are the user's data. The cache reduces this number dramatically. Reads are served from memory. Delayed writing also merges writes made to the same block: the i-node bitmap, the data bitmap, the directory data, the directory's i-node, the file's i-node, and the three data blocks are each written once. Of the 25 I/Os, 8 writes remain. This count shows why the buffer cache and delayed writing are indispensable. The order in which the writes are made determines crash consistency.

10.9.2The buffer cache

Definition 10.13

The buffer cache is the kernel cache that keeps copies of disk blocks in memory. If the requested block is in the cache, it is a hit; if not, a miss.

The value of the cache comes from the large speed gap between memory and disk (Table 10.19). Reading a random 4 KiB from an NVMe SSD takes about a thousand times as long as a DRAM access; on a hard disk, seek and rotation are that much slower again.

Table 10.19: Typical access latencies (2026).
AccessLatency
64 bytes from DRAM≈ 80–120 ns
NVMe SSD 4 KiB random read≈ 50–100 µs
HDD seek + rotation≈ 5–10 ms (100–280 MB/s sequential)

The classical buffer cache consists of two structures (Figure 10.42). A hash table finds a buffer from the (device, block number) pair in O(1) time; buffers that fall into the same bucket are chained. An LRU list arranges the buffers in order of last use. When space is needed, the buffer at the head of the list, the one unused for the longest time, is chosen. Important blocks such as i-nodes and directory blocks can be written without delay when they are modified; if they are damaged, the whole file system suffers.

hash table(device, block no.)01234block 12block 87block 6block 43block 8block 203block 19LRU list (oldest → newest)6 → 43 → 12 → 19 → 8 → 87 → 203lookup: O(1) by hashreplacement: head of the LRU listimportant blocks (i-node, directory)written at once if dirty
Figure 10.42: The buffer cache: hash-table chains and the LRU list (oldest → newest: 6, 43, 12, 19, 8, 87, 203).

There are two policies for writes. Write-through sends every change to disk immediately. It is safe but slow; old MS-DOS and removable media work this way, because the user may pull out the USB stick at any moment. Write-back accumulates the changed, that is, dirty, blocks in memory and writes them later. Linux writes dirty pages older than 30 seconds to disk in the background. If an application wants to wait until the data reaches the disk, it calls fsync.

Common mistake

Assuming that the data is on disk because write returned successfully. In a write-back cache, write only copies the data into the page cache. If the power fails within a few seconds, the data is lost. close does not guarantee writing to disk either. fsync(fd) or O_SYNC is required for durability.

10.9.3Code trace: bread

The function bread below reads a block through the cache:

Buffer *bread(int blk) {
  Buffer *t = hash_find(blk);
  if (t != NULL) {         /* hit */
    lru_to_tail(t);
    return t;
  }
  t = lru_head();          /* oldest */
  if (t->dirty)
    disk_write(t);       /* write back */
  t->blk = blk; t->dirty = 0;
  disk_read(t);            /* miss: I/O */
  lru_to_tail(t);
  return t;
}

The function first searches the hash table for the block. If it finds it (a hit), it moves the buffer to the end of the LRU list, the newest position, and returns it; there is no disk I/O. If it does not find it (a miss), it takes the oldest buffer at the head of the list. If the buffer is dirty, its contents are first written to disk so that they are not lost. Then the buffer is assigned to the new block, its dirty bit is cleared, the content is read from disk, and the buffer is added to the end of the list.

Let the cache have 3 buffers: in LRU order, blocks 5, 9, and 2. Block 9 is dirty, that is, modified but not yet written to disk. The requests are 9, 7, 2, and 4 in turn. Table 10.20 gives the trace.

Table 10.20: Trace of bread (initial LRU: 5, 9*, 2; * dirty; simulated with Python).
RequestResultEvictedLRU after (old → new)Read / write
9hit—5, 2, 9*0 / 0
7miss5 (clean)2, 9*, 71 / 0
2hit—9*, 7, 21 / 0
4miss9 (dirty → written)7, 2, 42 / 1

The first request is a hit; block 9 is moved to the newest position and the oldest block is now 5. bread(7) is a miss. Block 5 is clean: since its copy on disk is up to date, there is no need to write it back. The buffer is reused for block 7 and 1 read is made. bread(2) is a hit again. After this step the dirty block 9 has come to the head of the list. bread(4) is a miss and the oldest buffer holds 9. So that the change is not lost, block 9 is first written to disk, and then block 4 is read. Evicting a dirty buffer doubles the cost of a miss. In the end, 2 of the 4 requests were hits, with 2 reads and 1 write in total. Without a cache, 4 reads and a separate write for block 9's change would have been needed.

LRU list: oldest on the left, newest on the rightblock 7cleanblock 2cleanblock 4cleandisk I/O: 2 reads, 1 write
Figure 10.43: The cache after four requests: 7, 2, 4; 2 reads and 1 write in total.

10.9.4The page cache and the unified cache

Files are accessed in two ways: with read/write calls and with memory-mapped I/O through mmap. In old systems these two paths used separate caches (Figure 10.44). The data of mmap lived in the virtual memory system's page cache and the data of read/write in the buffer cache. When the same file was used through both paths, the same data was in memory twice. This double caching both wasted memory and made it hard to keep the two copies consistent.

memory-mapped I/O (mmap)read() / write()page cachebuffer cachefile systemthe same data twice!
Figure 10.44: A non-unified cache: the data of mmap and of read/write in two separate caches, the same data twice.

In a unified buffer cache the file pages live in a single place and both paths see the same pages. Linux has worked this way since 2.4; Windows's cache manager and Solaris follow the same path. The page cache shares the same page-replacement algorithms as virtual memory: a file page and a process's anonymous page compete in the same pool. There are exceptions too. ZFS keeps its own ARC cache. Databases that manage their own cache skip the operating system's cache completely with the O_DIRECT flag.

10.9.5Read-ahead, placement, and defragmentation

Read-ahead means sensing sequential access in advance. When block k is requested, block k + 1 is also read (if it is not in the cache); when the program asks for it, it is ready. Read-ahead helps only with sequential access. With random access, unnecessary reads keep the disk busy. A per-file trace of “is this file being read sequentially?” is therefore kept. Linux enlarges or shrinks the window according to the access pattern; the default window is 128 KiB. An application can also give hints with posix_fadvise.

On a hard disk the most expensive thing is arm movement. Putting blocks that will be read consecutively close together on the disk reduces this movement. With a bitmap, finding contiguous free blocks is easy. An old suggestion was to allocate blocks two at a time. Today extents, delayed allocation, and the multiblock allocator do this job. The placement of i-nodes also matters (Figure 10.45). (a) If i-nodes are gathered at the beginning of the disk, every file access requires a long arm movement between the i-node and the data. (b) If the disk is divided into cylinder groups or block groups and each group has its own i-nodes, the i-node and its data are in the same group. BSD FFS and ext2/3/4 work this way.

(a) i-nodes at the beginning of the diski-nodedata blocksevery file access: long arm movement(b) cylinder / block groupsigroup 0igroup 1igroup 2i-node and its data in the same groupBSD FFS, ext2/3/4
Figure 10.45: i-node placement: (a) at the beginning of the disk, (b) in each cylinder or block group.

Over time files become fragmented: their blocks are scattered over the disk. Defragmentation makes files contiguous again. On Windows the tool is called “Defragment and Optimize Drives.” Linux has similar tools: e4defrag, xfs_fsr, btrfs filesystem defragment. ext4's allocation policy greatly reduces this need. On an SSD, since there is no seek time, defragmentation brings no gain; on the contrary, it means unnecessary writes, that is, wear. On an SSD Windows sends TRIM instead of defragmenting.

10.9.6SSDs: FTL and TRIM

A page of flash memory cannot be updated in place; before it is written, the large erase block it belongs to must be erased as a whole. The flash translation layer (FTL) in the SSD's controller therefore directs every write to a new, empty page and maps the logical block address to that page. The old page becomes invalid. The inside of the SSD thus resembles a log-structured system. When free pages run low, the controller performs garbage collection: it copies the valid pages in an erase block elsewhere and erases the block.

A gap in information arises here. When the file system deletes a file, it merely marks the blocks free in its own bitmap. The SSD is unaware of this; it still considers those pages valid and copies them needlessly during garbage collection. Needless copies increase write amplification, which both lowers speed and accelerates wear. The solution is for the file system to tell the SSD about freed blocks with the TRIM command (Deallocate in NVMe). On Linux the notification is made either in bulk with the weekly fstrim.timer or at every delete with the discard mount option.

10.10Consistency and recovery

10.10.1Backup

Backup has two purposes. The first is disaster recovery: disk failure, fire, ransomware. The second is recovery from carelessness: restoring a file that was deleted or overwritten by mistake. In practice the second is needed far more often.

There are two basic forms of backup (Table 10.21). A physical dump copies the disk from block 0 to the end. It is very fast and simple, but it cannot skip directories, cannot take incremental backups, and makes restoring a single file hard. A logical dump copies chosen directories and files together with their paths. It is slower and more complex; in return it can take only the changed files and easily restores a single file, even onto another machine.

Table 10.21: Physical and logical dumps.
Physical dumpLogical dump
What is copied?all (used) blocks from block 0 to the endchosen directories and files, with their paths
Speed, simplicityvery fast, simpleslower, complex
Skipping directories, incremental backupcannotcan (the changed ones)
Restoring a single filehardeasy; on another machine too
Bad blocksthe controller must remap them or the OS must know the listnot a problem

A common strategy combines full and incremental dumps (Figure 10.46). For example, a full dump once a month and, every day, only what has changed since the last dump. In a restore, the last full dump is written first onto an empty file system: first the directories, then the files. Then the incremental dumps are applied in order. Temporary files and special files (/dev, /proc, /tmp) are not backed up. A backup taken while the system is in use can be inconsistent: a directory copied at the start of the dump may have changed by its end. A snapshot (LVM, ZFS/Btrfs, Windows VSS) is therefore taken first, and the backup is made from that frozen image.

day 1day 2day 3day 4day 5day 6day 7full dump+ incrementalsrestore: day 1 full,then 2 … 7 in order
Figure 10.46: Full and incremental dumps: a full dump on the first day, only the changes on the following days.

Where backups are kept also matters. The 3-2-1 rule says: 3 copies, 2 different media, 1 copy somewhere else (offline or immutable). Because ransomware can encrypt every disk on the network, the offline copy is the last safeguard. Tape still lives on today in archives; an LTO-10 cartridge holds up to 40 TB uncompressed.

10.10.2The logical dump algorithm

UNIX's incremental logical dump algorithm works in four phases and uses an i-node bitmap. In the tree in Figure 10.47, squares are directories and circles are files; the numbers are i-node numbers. Under root 1 there are 2, 3, and 4. Under 2 are 5 and 6, under 4 are 7 and 8, under 7 is 9, and under 8 is 10. The files changed since the last dump are 3, 6, and 10.

  1. Phase 1. The tree is walked starting from the root. Every changed file and all directories, changed or not, are marked: 1, 2, 3, 4, 6, 7, 8, 10.
  2. Phase 2. The tree is walked again. The mark is removed from directories that have nothing changed below them: 7, because it contains only the unchanged 9.
  3. Phase 3. The marked directories are dumped in i-node order: 1, 2, 4, 8. These directories are dumped even if they are unchanged, because they are needed to rebuild the paths of the changed files.
  4. Phase 4. The marked files are dumped: 3, 6, 10.
12345678910bitmap111213140516071809110phase 4
Figure 10.47: The last phase of the logical dump: the marked files 3, 6, 10 are dumped. In the bitmap 5, 7, and 9 are unmarked.

Dumping directories before files makes the restore easier: first the directory tree is built, then the files are put in their places. There are a few more details. The free list is not dumped; it is rebuilt after the restore. A file with several hard links should be dumped only once, and all of its names must be linked again on restore. The holes of sparse files should not be filled with zeros; otherwise the restored file swells to its real size on disk. FIFOs and device files are dumped not by content but by type.

10.10.3Consistency checking: fsck

After a crash, a file system may be left inconsistent: some of the changes have reached the disk and some have not. UNIX's fsck program (chkdsk on Windows) finds and repairs these inconsistencies. It makes two kinds of checks: block consistency and file consistency.

For block consistency, fsck keeps two counters for each block. It reads all the i-nodes and increments the “in use” counter of the blocks each i-node uses. Then it reads the free list or the bitmap and increments the “free” counter. In a consistent file system the sum of the two counters is 1 for every block: the block is either in a file or free (Figure 10.48). Three problems can arise:

  • Missing block (0, 0): the block appears nowhere. It is harmless but it is a loss of space; the block is added to the free list.
  • Duplicate block in the free list (0, 2): the same block could later be given to two files at once. The free list is rebuilt. With a bitmap this situation cannot occur, because a bit is either 0 or 1.
  • Duplicate data block (2, 0): two files use the same block. This is the most dangerous: when one of the files changes, the other is corrupted too. fsck allocates a new block, copies the content, gives the copy to one of the files, and informs the user.
block number0123456789101112131415in use1101021110011100on free list0010100001100011Block 5 in two files → allocate a new block, copy, notify the user.
Figure 10.48: The fsck counters: block 5 appears in two files (a duplicate data block). A new block is allocated, the content is copied, and the user is notified.

If a block appears both in use and on the free list (1, 1), it is removed from the free list.

For file consistency, fsck walks all directories starting from the root and keeps a seen counter for each i-node. Because of hard links, an i-node can appear in several directories. At the end the counter is compared with the link count in the i-node. If the link count is greater than the seen count, there is only a waste of space: even if all the names are deleted, the link count does not fall to 0 and the file is never freed. If it is smaller, the situation is dangerous: when one of the names is deleted, the link count falls to 0 and the file is freed while another name still exists. In both cases the link count is set equal to the seen count. I-nodes that appear in no directory but are in use are put in the lost+found directory.

Example 10.12

The fsck counters came out as follows (blocks 0–9): in use 1 0 1 1 0 2 1 0 0 1; on the free list 0 1 0 0 1 0 0 0 2 0. Which are the problem blocks?

  1. The total should be 1 for each block. Block 5: (2, 0), a duplicate data block; the most dangerous.
  2. Block 7: (0, 0), a missing block; it is added to the free list.
  3. Block 8: (0, 2), twice on the free list; the list is rebuilt.

fsck's big problem is its running time. All the i-nodes and all the directories have to be read. On a terabyte disk a full scan takes hours, and the system cannot be used during this time. This is why journaling and copy-on-write were born.

10.10.4Crashes and atomicity

The root of the problem is this: a file operation changes several blocks, but the disk guarantees atomically only the writing of a single sector. Deleting a file takes three steps (Figure 10.49): removing the directory entry, returning the i-node to the free pool, and returning the blocks to the free pool. If a crash occurs after the first step, the i-node and the blocks are left ownerless; this is a leak, and fsck finds it. If a crash occurs after the second step, the blocks leak. If the order were reversed, things would be much worse. If the i-node is freed first and given to another file, and a crash occurs before the directory entry is deleted, the directory points to the wrong file. The data of the two files gets mixed up.

1. remove the directory entrycrash2. i-node to the free poolcrash3. blocks to the free poolcrash after 1: i-node and blocks ownerless (leak, fsck finds it)crash after 2: blocks leakif the order were reversed: the directory could point to an i-node given to another file → data mixed up!
Figure 10.49: The three steps of deleting a file and the crash points.

There are four families of solutions to this problem. (1) Repair afterward: fsck. (2) Write the intent first: journaling. (3) Never overwrite: copy-on-write and log-structured file systems. (4) Order the writes carefully: BSD's soft updates method makes the writes in an order that leaves only harmless leaks, whenever the crash occurs.

Definition 10.14

An operation that gives the same result whether applied once or many times is called idempotent.

Journaling relies on idempotence. During recovery an operation may be replayed many times: the crash can even occur in the middle of recovery. “Mark block n free” is idempotent; however many times it is done, the block is free. “Append n to the end of the free list” is not idempotent; if done twice, n is on the list twice. This is why it is not operations but the new contents of blocks that are written to the journal.

10.10.5Journaling

Definition 10.15

Journaling means writing changes first to a separate area on disk, the journal, and only then applying them to their final places. In databases this idea is called write-ahead logging.

Suppose a new block is appended to a file. Three blocks change: the file's i-node (I), the data bitmap (B), and the new data block (Db). In ext4's default ordered mode the operation proceeds in five steps (Figure 10.50).

  1. Data. The new data block Db is first written to its final place.
  2. Journal write. The transaction-begin record TxB and the metadata blocks to be changed, that is, the new versions of I and B, are written sequentially to the journal.
  3. Commit. When it is certain that the earlier writes have reached the disk (a barrier or FLUSH command), the transaction-end record TxE is written. If TxE is on disk, the transaction is committed.
  4. Checkpoint. I and B are written to their final places. It does not matter if these writes are interrupted midway; they can be repeated from the journal.
  5. Free. The transaction is marked complete in the journal's superblock. The journal is reused like a circular buffer.
journalTxBI[v2]B[v2]TxEempty journal spacefinal placesi-node bitmapdata bitmap (v2)i-node table (v2)data block (new)checkpoint
Figure 10.50: Checkpoint: in the journal TxB, I[v2], B[v2], TxE; in the final places the bitmap and the i-node table have been updated to v2.

Recovery is simple. At boot the journal is scanned. Transactions that have a TxE are replayed from the beginning: their blocks are rewritten to their final places (redo). Because rewriting is idempotent, it does not matter that some of the blocks were already written before the crash. Transactions without a TxE are discarded; since their final places were never touched, the file system is in its old, consistent state. fsck is not needed; recovery takes seconds.

Whether the crash occurred before or after TxE is therefore decisive. If a crash occurs before TxE is written, the transaction counts as never having happened and the change is lost. If a crash occurs after TxE is written, for example in the middle of the checkpoint, the transaction is replayed from the journal and the change is preserved. In both cases the file system stays consistent.

ext4 has three modes. In journal mode the data is also written to the journal; it is the safest but the slowest, because every piece of data is written twice. In ordered mode only the metadata goes into the journal, but the data is always written before the metadata; thus an i-node never points to a block containing garbage. In writeback mode there is no ordering guarantee for the data. Among the systems that use journals are ext3/ext4 (jbd2), XFS, NTFS ($LogFile), and JFS. At Apple, the journaled HFS+ gave way to APFS, which uses copy-on-write.

10.10.6Code trace: recovery from the journal

The function recover below scans a journal of n records from the beginning. The type of a record is TXB, BLOCK, or TXE; BLOCK records carry the number of the target block and its new content.

void recover(Rec g[], int n) {
  int i = 0;
  while (i < n && g[i].type == TXB) {
    int j = i + 1;
    while (j < n && g[j].type == BLOCK)
      j++;
    if (j == n || g[j].type != TXE)
      break;              /* uncommitted: drop */
    for (int k = i + 1; k < j; k++)
      write(g[k].dest, g[k].data);
    i = j + 1;          /* next */
  }
}

i points to the start of a transaction. The outer loop continues as long as g[i] is a TxB. The inner loop moves j over the block records to the end of the transaction. If j has reached the end of the journal, or there is no TxE there, the transaction is uncommitted: the loop breaks and the transaction is discarded. The blocks of a committed transaction are copied to their final places with write, and i moves to just after the TxE. The function scans the journal once and writes each block record at most once: O(n).

The system crashed while the third transaction was being written. The journal has ten records: TxB 1, I7 v1, B v1, TxE 1, TxB 2, I9 v2, D40 v2, TxE 2, TxB 3, I7 v3. All blocks in the final places are still v0. Table 10.22 gives the trace.

Table 10.22: Trace of recover (run by translating it one to one into Python).
ij at the end of the inner loopg[j]DecisionFinal places after (I7, B, I9, D40)
0 (TxB 1)3TxE 1replay: I7 ← v1, B ← v1v1, v1, v0, v0
4 (TxB 2)7TxE 2replay: I9 ← v2, D40 ← v2v1, v1, v2, v2
8 (TxB 3)10 = n—uncommitted: drop, exit the loopv1, v1, v2, v2
Journal (on disk after the crash):TxB10I7v11Bv12TxE13TxB24I9v25D40v26TxE27TxB38I7v39Final places:I7v1Bv1I9v2D40v2
Figure 10.51: The end of recovery: transactions 1 and 2 were applied; the I7 v3 version of transaction 3 was never written.

Transactions 1 and 2 are applied completely, and transaction 3 is as if it never happened. The v1 version of I7 may already have been written to its final place before the crash; rewriting it changes nothing. The file system is consistent and no fsck scanning the disk from end to end is needed.

Common mistake

Replaying every block found in the journal. The I7 v3 record of transaction 3 sits in the journal, but it has no TxE. Writing it would mean applying only part of a transaction; that is inconsistency itself. Only committed transactions are replayed.

10.10.7Copy-on-write

Journaling writes every change twice: first to the journal, then to its final place. File systems that use copy-on-write (CoW) follow another way: they never overwrite any block. The file system is a tree of blocks (Figure 10.52). At the top is the superblock (the uberblock in ZFS), below it the root, the internal nodes, and at the bottom the data blocks.

  1. Leaf. Let block L3 be the one to change. L3 is not updated in place; its new version L3' is written to a free spot. The old L3 is still intact.
  2. Path. The parent nodes that point to L3 must also change, because their pointers will change. I2 and the root are also copied: I2', R'. The unchanged subtrees (I1, L4) are shared with the new version.
  3. Atomic switch. Finally the superblock is updated with a single atomic write to point to R'. If the crash occurs before this write, the old tree is seen; if after, the new tree. There is no intermediate state; no journal is needed.
superblockrootI1I2L1L2L3L4L3'I2'R'gray: old version = snapshot (or free)each pointer carries the checksum of the child
Figure 10.52: Copy-on-write: the changed leaf and its path are written to a new place, and the superblock is updated atomically. Gray: the old version, which can be kept as a snapshot.

This design has two nice by-products. If the old root is kept, the whole old tree is still valid: a snapshot comes for free. ZFS and Btrfs also keep, next to each pointer, a checksum of the block it points to. If a block on the disk is silently corrupted, it is caught on reading and repaired from the mirror copy. The operation that reads the whole disk and does this check is called a scrub.

The systems that use copy-on-write are ZFS (Sun, 2005; today OpenZFS), Btrfs (Linux), APFS (Apple, 2017), and ReFS (Windows Server). The price shows up with random overwrites. Because every small change in the middle of a file is written to a new place, the file becomes fragmented over time. Because a change to one leaf requires copying the entire path, write amplification also rises. CoW can therefore be turned off for database and virtual-machine disk files.

10.10.8The log-structured file system

In 1991 Rosenblum and Ousterhout proposed a radical design for the Sprite operating system: the log-structured file system (LFS). The design's assumption was this: as memories grow, most reads are served from the cache, and the traffic going to disk is mostly writes. Writes should then be done in the fastest way, that is, with a single long sequential write.

In LFS the whole disk is a single log. Writes are accumulated in memory: data blocks, modified i-nodes, and pieces of the i-node map (imap). When the buffer fills, everything is written sequentially to the end of the log as a single segment (for example 1–2 MiB) (Figure 10.53). I-nodes have no fixed place; they move at every write. The imap finds the latest location of an i-node from its number. The checkpoint region (CR) at a fixed place on the disk points to the latest pieces of the imap.

memory bufferD(A,0)'I(A)'imap'disk (log)CRcheckpointregionsegment 1D(A,0)D(B,0)I(A)I(B)imapsegment 2D(A,0)'I(A)'imap'
Figure 10.53: When a block of A changes, the new version is written to segment 2; the old D(A,0), I(A), and imap in segment 1 become dead.

When a block of file A changes, its new version, the new i-node, and the new piece of the imap are written to a new segment. The old copies in segment 1 are now dead but continue to occupy space. This space must be reclaimed before the disk fills up. The cleaner does this job: it reads segments with few live blocks, compacts the live blocks into a new segment, and frees the old segments. The cost of cleaning grows when the disk is full and under load; this is LFS's weak point.

LFS raises write bandwidth almost to the disk's sequential speed. The idea lives on in many places today: Android's F2FS, Linux's NILFS2, NetApp's WAFL, the copy-on-write of ZFS and Btrfs, and the FTLs of SSDs. The inside of an SSD is already a log-structured system.

10.11VFS and the network file system

10.11.1The virtual file system

On a Linux machine many file systems are mounted at the same time: ext4 in the root directory, XFS on a data disk, exFAT on an attached USB stick, an NFS share mounted from the network, and /proc, which lives in memory. The application reaches all of them with the same open and read calls. A layer of the kernel provides this unity.

Definition 10.16

The virtual file system (VFS) is the kernel layer that unifies different file systems behind a common object interface. Each concrete file system implements the operations of this interface with its own functions.

The Linux VFS works with four kinds of object: the superblock (a mounted file system), the inode (a file; the v-node in Sun's original design), the dentry (a name component in a path), and the file (an opening). Each object carries an operations table: a structure made of pointers to functions. The mechanism is set up in four steps (Figure 10.54).

  1. Registration. A file system registers with the VFS at boot or when its module is loaded, using register_filesystem(), and supplies the table of addresses of the functions the VFS will call.
  2. Mounting. The VFS asks that file system to build a superblock object. The object carries the superblock operations table (s_op).
  3. open. The path is resolved with dentries. The concrete file system places the i-node information into a VFS i-node; the tables of i-node operations (i_op) and file operations (f_op) are attached. A file object is created and added to the process's descriptor table.
  4. read. The VFS merely calls the function pointer file->f_op->read_iter. If the file is on ext4, ext4's function runs and brings the data through the page cache, the block layer, and the NVMe driver. If the file is on NFS, the NFS client's function runs and sends a remote procedure call (RPC) over the network.
process: read(fd, buf, n)VFSsuperblock · inode (v-node) · dentry · file objectsext4XFSNFS clientprocfspage cache → block layer → NVMe driverRPC → TCP/IP → networkf_op->read_iter()
Figure 10.54: The VFS layer: the read call is routed to the concrete file system's function through the f_op->read_iter pointer in the file object.

This is polymorphism written in C: exactly the same as a virtual method call in an object-oriented language. The application sees no difference. The extra cost is a single indirect call; the loss in performance is small. The purpose of the VFS is to present a single interface to different file systems at the same time. Keeping several file systems on the same disk does not require the VFS; partitioning already provides that. On Windows the I/O manager and the file-system drivers play the same role.

Common mistake

Believing that the application uses a different system call depending on the file system, or that the kernel tries the code of all file systems in turn. The system call is the same. The right code is selected with a single indirect call from the operations table that was attached to the file object during open.

10.11.2NFS

The network file system (NFS) attaches a directory of a remote machine to the local tree. The application uses remote files like local files. Sun designed NFS for SunOS in 1984 and published the protocol as an open standard. This is why it is found today in almost every UNIX-like system.

clientserverprocessVFSNFS clientRPC / XDRext4 / XFS / ZFS → diskVFSnfsdRPC / XDRTCP 2049READ(file handle, offset, n)mount server:/export /mnt/project
Figure 10.55: The NFS client and server layers: the NFS client under the VFS on the client, and nfsd and the local file system on the server.

Figure 10.55 shows the layers. On the client, mount server:/export /mnt/project mounts the remote directory. When a process reads a file under /mnt/project, the call goes from the VFS to the NFS client. The client prepares a READ(file handle, offset, n) request and sends it to the server on TCP port 2049. The nfsd on the server passes the request through its own VFS to the local file system (ext4, XFS, ZFS) and sends the reply back.

NFS achieves machine and architecture independence with two tools. Remote procedure call (RPC) makes a request-reply exchange look like a function call. External data representation (XDR) encodes numbers and structures in a form independent of byte order, so a client and a server of different architectures understand each other. The versions of NFS also show an important distinction in design. NFSv3 is stateless: the server does not remember which client has opened which file, and every request carries everything needed (file handle, offset). Even if the server crashes and restarts, the clients merely repeat their requests. NFSv4, however, is stateful. It uses only TCP and a single port (2049); it includes Kerberos security, ACLs, file locking, and delegation. pNFS in v4.1 allows data to be read in parallel from several servers. NFS originally used UDP/IP; today TCP is preferred. The only requirement is an IP network. Its counterpart in the Windows world is SMB 3, which supports encryption and multichannel connections.

10.12Summary

  • The disk offers only numbered blocks. On top of this, the file system builds files, which are named, persistent byte sequences, and the directories that map them. The type of a file is reliably recognized not by the extension but by the magic number.
  • Attributes live in the i-node and the name in the directory entry. stat reads the attributes; mtime is the moment the content changed, and ctime the moment the i-node changed.
  • An open file is tracked at three levels: the per-process descriptor table → the system-wide open-file table (position, mode) → the in-memory i-node. fork and dup share the position, and a second open creates a separate position. A short read is not an error; a return of 0 is end of file.
  • Safe saving: write to a temporary file → fsync → rename.
  • Directory structures evolved from single-level to trees and directed acyclic graphs; UNIX forbids hard links to directories. A path is resolved component by component: if the root i-node is in memory, k components take 2k reads, and 2k + 1 reads with the first data block.
  • A hard link is a second name for the same i-node and raises the link count; a symbolic link stores the path of the target and is left dangling when the target is deleted. Mounting combines separate file systems in a single tree.
  • The rwx bits are kept separately for owner, group, and others; the first matching class applies. On a directory w allows adding and deleting entries and x allows passing through. The setuid and sticky bits and the umask (permission = request & ~umask) complete this scheme.
  • MBR is limited to 2 TiB by its 32-bit LBAs; GPT offers 64-bit LBAs, 128 partitions, and a backup header. The location of an i-node is computed from its number: offset = n × size, disk block = table start + offset div block size.
  • Contiguous allocation is fast but produces external fragmentation. The linked list is flexible, but random access costs O(n) disk reads. FAT moves the chain into memory, but the table grows with the disk. The i-node needs memory only for open files; with 12 direct pointers and single, double, and triple indirect pointers it reaches ≈ 4 TiB with 4 KiB blocks. Extents describe contiguous blocks with a single record.
  • Directories are kept as a linear list, a hash, or a B+ tree; in large directories the tree gives both O(log n) search and ordered listing.
  • Free space is tracked with a bitmap, a linked list, grouping, or counting. The bitmap has a fixed size; the list is small only when the disk is full. The block size is a trade-off between data rate and space efficiency.
  • Creating a file without a cache and writing 12 KiB costs 25 I/Os. The buffer cache works with a hash and an LRU list; evicting a dirty buffer doubles the cost of a miss. The unified page cache prevents double caching. Read-ahead and close placement speed up sequential access; blocks deleted on an SSD are reported with TRIM.
  • The 3-2-1 rule applies to backups; the logical dump has four phases. fsck checks block and link counts but is slow. Journaling replays transactions that have a TxE and discards those that do not. Copy-on-write never overwrites any block and changes the superblock atomically. LFS writes everything to a sequential log and reclaims space with a cleaner.
  • The VFS presents a single interface to different file systems through tables of function pointers. NFS attaches remote directories to the local tree with RPC and XDR.

10.13Key terms

  • file system
  • file descriptor
  • open-file table
  • directory, directory entry
  • path name (absolute / relative)
  • hard link / symbolic link
  • mount
  • permission bits (rwx)
  • access control list (ACL)
  • superblock
  • i-node
  • contiguous allocation
  • linked allocation
  • indexed allocation
  • internal / external fragmentation
  • bitmap
  • buffer cache
  • page cache
  • journaling
  • copy-on-write
  • virtual file system (VFS)
  • network file system (NFS)

10.14Test Yourself

  1. A 9000-byte file is read with a 2048-byte buffer until read returns 0. What do the read calls return, in order?

    Answer

    2048, 2048, 2048, 2048, 808, and 0. Four full reads bring 8192 bytes; the remaining 9000 − 8192 = 808 bytes arrive with a short read, and the last call reports end of file. 6 calls in total.

  2. mkdir p, mkdir p/x, mkdir p/y, echo z > p/f, ln p/f p/g, and ln -s f p/h are run. What are the link counts of p, p/x, p/f, and p/h?

    Answer

    p: 4 (the entry in the parent directory, its own ., and the .. entries of x and y). p/x: 2. p/f: 2 (f and g are the same i-node). p/h: 1 (the symbolic link's own i-node).

  3. The i-node table starts at block 3; the block is 4 KiB, the i-node 128 B, and numbers start at 0. In which disk block and which sector (512 B) does i-node 50 start?

    Answer

    50 × 128 = 6400 = 1 × 4096 + 2304: block 1 of the table, that is, disk block 3 + 1 = 4, byte 2304 inside the block. The byte address is 4 × 4096 + 2304 = 18,688; 18,688 / 512 = 36.5 → sector 36, byte 256 inside it.

  4. The cluster is 2 KiB; in the FAT, FAT[8] = 3, FAT[3] = 13, FAT[13] = 6, FAT[6] = EOF. In which cluster, and at which byte of the cluster, is byte 5000 of the file whose first cluster is 8?

    Answer

    5000 div 2048 = 2: the file's cluster 2 (from 0). Since the chain is 8 → 3 → 13 → 6, cluster 2 is physical 13. The position within the cluster is 5000 mod 2048 = 904. Because the chain is followed in memory, the disk read is only for the data cluster itself.

  5. The block is 8 KiB, the address 4 B; the i-node has 12 direct, 1 single, 1 double, and 1 triple indirect pointer. About how large is the largest file?

    Answer

    P = 8192 / 4 = 2048. The number of blocks is 12 + 2048 + 20482 + 20483 = 8,594,130,956; × 8192 B ≈ 70.4 × 1012 B ≈ 64 TiB. Doubling the block size raises the capacity by a factor of about 24 = 16: the block grows twofold and each of the three levels holds twice as many addresses.

  6. 4 KiB block, 4 B address, 12 direct pointers. At which level is byte 10,000,000, and how many disk reads are needed if the i-node is in memory?

    Answer

    10,000,000 div 4096 = 2441. Since 2441 − 12 − 1024 = 1405 ≥ 0, it is in the double indirect region: outer index 1405 div 1024 = 1, inner index 1405 mod 1024 = 381. The offset in the block is 1664. Reads: the double indirect block, the single indirect block, the data = 3.

  7. On a 24-block disk the free blocks are 1, 2, 3, 7, 8, 9, 10, 15, 20, and 21. How is this free space represented with the counting method and with a bitmap (1 = free)?

    Answer

    Counting: (1, 3), (7, 4), (15, 1), (20, 2). Bitmap: 01110001 11100001 00001100. Ten free blocks reduce to four pairs.

  8. In a cache with 3 buffers the LRU order is 3, 8, 6 (3 is the oldest and dirty). The requests are 8, 1, 3, 6. How many reads and how many writes does bread make?

    Answer

    8 is a hit (order 3, 6, 8). 1 is a miss; since the oldest, 3, is dirty, it is written first, then 1 is read (6, 8, 1). 3 is a miss: the block just evicted is read again, and 6 is evicted (8, 1, 3). 6 is a miss and 8 is evicted (1, 3, 6). In total 3 reads, 1 write. In this small cache LRU evicts blocks that are requested right back.

  9. After a crash the journal contains these records: TxB 1, I4 v1, TxE 1, TxB 2, D8 v2, B v2. In the final places everything is v0. At the end of recover, in which version are I4, D8, and B?

    Answer

    Transaction 1 is committed: I4 ← v1. Transaction 2 has no TxE; j reaches the end of the journal (6) and the transaction is discarded. The result is I4 v1, D8 v0, B v0. Although D8 v2 is in the journal, it is not written.

  10. A file's permission is -rw-r--r-- and the permission of the directory it is in is drwxrwxrwx. Can an ordinary user who is not the file's owner delete the file? What would change if the directory's permission were drwxrwxrwt?

    Answer

    Yes. Deleting removes a directory entry and requires the directory's w right; the file's own permission is irrelevant. If the sticky bit (the t at the end) were set, only the file's owner, the directory's owner, or root could delete the entry.

10.15Further reading

  • R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, the chapters “File System Implementation,” “Crash Consistency: FSCK and Journaling,” and “Log-structured File Systems”: they describe the I/O counts and journaling steps of these notes in much more detail. The book is free at ostep.org.
  • M. K. McKusick, W. N. Joy, S. J. Leffler, R. S. Fabry, “A Fast File System for UNIX,” ACM TOCS, 1984: the classic paper that introduced cylinder groups and the idea of close placement and explains the layout of today's ext4.
  • M. Rosenblum and J. K. Ousterhout, “The Design and Implementation of a Log-Structured File System,” ACM TOCS, 1992: describes the design of LFS, the cleaner policies, and the measurements.
  • Linux kernel documentation, “Overview of the Linux Virtual File System” and “ext4 Data Structures and Algorithms”: first-hand descriptions of the VFS objects and of ext4's on-disk layout, extent tree, and journal.

10.16References

  1. A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th edition, Wiley, 2018 — Chapters 13 (File-System Interface), 14 (File-System Implementation), 15 (File-System Internals).
  2. A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th edition (2014) / 5th edition (2023), Pearson — Chapter 4: File Systems.
  3. R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP), ostep.org — “Files and Directories,” “File System Implementation,” “Fast File System,” “Crash Consistency: FSCK and Journaling,” “Log-structured File Systems,” “Flash-based SSDs,” “Data Integrity,” “Sun's NFS.”
  4. M. Rosenblum, J. K. Ousterhout, “The Design and Implementation of a Log-Structured File System,” ACM TOCS, 1992; M. K. McKusick et al., “A Fast File System for UNIX,” ACM TOCS, 1984.
  5. Linux kernel documentation: “Overview of the Linux Virtual File System,” “ext4 Data Structures and Algorithms”; Microsoft Learn: the NTFS and exFAT specifications; OpenZFS and Btrfs documentation; the UEFI specification (GPT).

Related pages: Chapter 10 slides · © Sercan Külcü. All rights reserved.