File System Concepts
A disk, an SSD or a USB stick is, to the hardware, just a long row of numbered blocks (usually 512 bytes or 4 KiB each). There are no names, no folders, no owners: only "write these bytes at block 81 920". A file system is the data structure the operating system keeps on that row of blocks so that people and programs can talk about /home/ada/notes.txt or C:\Users\ada\notes.txt instead.
Every file system, from FAT32 on a camera card to ext4 on a Linux server and NTFS on a Windows laptop, has to solve the same four problems:
- Where is a file's data? Map a file to the blocks that hold its bytes.
- Which blocks are free? Keep track of free space so new data does not overwrite old data.
- What is it called? Map human names (and folders) to files.
- What survives a crash? Keep the structure consistent when the power fails halfway through an update.
The on-disk layout
Most Unix-style file systems split the partition into a few regions. The exact sizes differ, but the idea is the same:
+------------+-----------------+---------------+---------------+------------------------+
| superblock | block bitmap | inode bitmap | inode table | data blocks ... |
| (sizes, | 1 bit per data | 1 bit per | fixed-size | file contents and |
| counts, | block: used or | inode: used | records with | directory contents |
| magic no.)| free | or free | file metadata | |
+------------+-----------------+---------------+---------------+------------------------+- The superblock describes the file system itself: block size, how many blocks and inodes exist, a "magic number" that identifies the type, and a clean/dirty flag. It is so important that ext4 keeps backup copies of it.
- An inode (index node) describes one file: type, size, owner, permissions, timestamps, link count and the list (or ranges) of blocks that hold the data. Note what is missing: the file's name.
- A directory is just a special file whose content is a table of
name → inode numberentries. - Bitmaps record which inodes and blocks are in use.
NTFS uses different words (the Master File Table, see NTFS & Windows File Systems), but it solves the same problems.
A tiny file system you can run
The program below builds a miniature inode file system in memory: 16 data blocks of 8 bytes, a block bitmap, an inode table and directories. Watch how creating a file touches the bitmap, an inode and a directory entry.
BLOCK = 8 # bytes per block (tiny, to see the splitting)
blocks = [b""] * 16 # the "disk"
bitmap = [0] * 16 # 1 = block in use
inodes = {} # inode number -> metadata
next_ino = 2 # inode 2 is the root directory, as on ext4
def alloc_block():
i = bitmap.index(0) # first free block
bitmap[i] = 1
return i
def new_inode(kind):
global next_ino
ino = next_ino
next_ino += 1
inodes[ino] = {"type": kind, "size": 0, "blocks": [], "links": 0, "entries": {}}
return ino
def write_file(ino, data):
node = inodes[ino]
for chunk_start in range(0, len(data), BLOCK):
b = alloc_block()
blocks[b] = data[chunk_start:chunk_start + BLOCK]
node["blocks"].append(b)
node["size"] = len(data)
def read_file(ino):
node = inodes[ino]
return b"".join(blocks[b] for b in node["blocks"])[:node["size"]]
def create(dir_ino, name, kind="file"):
ino = new_inode(kind)
inodes[dir_ino]["entries"][name] = ino # the name lives in the directory
inodes[ino]["links"] += 1
return ino
root = new_inode("dir")
inodes[root]["links"] = 2
home = create(root, "home", "dir")
notes = create(home, "notes.txt")
write_file(notes, b"Hello, file systems!")
print("bitmap :", "".join(map(str, bitmap)))
print("inode", notes, inodes[notes]["type"], "size", inodes[notes]["size"], "blocks", inodes[notes]["blocks"])
print("root entries:", inodes[root]["entries"])
print("home entries:", inodes[home]["entries"])
print("content:", read_file(notes).decode())bitmap : 1110000000000000
inode 4 file size 20 blocks [0, 1, 2]
root entries: {'home': 3}
home entries: {'notes.txt': 4}
content: Hello, file systems!
A 20-byte file needs three 8-byte blocks; the last one is only half full. That wasted tail is called internal fragmentation, and it is why a 1-byte file still uses 4 KiB on a real disk.
Path resolution
When a program opens /home/notes.txt, the kernel walks the path one component at a time: start at the root inode, look up home in its entries, load that inode, look up notes.txt, and so on. Each step also checks the "execute" (search) permission on the directory. Linux caches the results in the dentry cache, so a second lookup costs almost nothing.
inodes = {
2: {"type": "dir", "entries": {"home": 3, "etc": 5}},
3: {"type": "dir", "entries": {"ada": 4}},
4: {"type": "dir", "entries": {"todo.txt": 6}},
5: {"type": "dir", "entries": {"hostname": 7}},
6: {"type": "file", "data": "buy milk"},
7: {"type": "file", "data": "tad"},
}
def lookup(path):
ino = 2 # always start at the root inode
for part in [p for p in path.split("/") if p]:
node = inodes[ino]
if node["type"] != "dir":
return f"{path}: Not a directory"
if part not in node["entries"]:
return f"{path}: No such file or directory"
ino = node["entries"][part]
print(f" {part!r:12} -> inode {ino}")
return f"{path} is inode {ino}"
for p in ["/home/ada/todo.txt", "/etc/hostname", "/home/bob", "/etc/hostname/x"]:
print(lookup(p)) 'home' -> inode 3
'ada' -> inode 4
'todo.txt' -> inode 6
/home/ada/todo.txt is inode 6
'etc' -> inode 5
'hostname' -> inode 7
/etc/hostname is inode 7
'home' -> inode 3
/home/bob: No such file or directory
'etc' -> inode 5
'hostname' -> inode 7
/etc/hostname/x: Not a directory
The two error strings are exactly the ones real Linux prints (ENOENT and ENOTDIR), because the kernel fails at the same step.
How files find their blocks
| Method | Idea | Used by |
|---|---|---|
| Contiguous | One start block + length | CD-ROM (ISO 9660) |
| Linked list / table | Each block points to the next; the chain is kept in a table | FAT12/16/32, exFAT |
| Indexed (block pointers) | The inode lists block numbers, with indirect blocks for big files | ext2, ext3 |
| Extents | The inode lists ranges: "start 5000, length 300" | ext4, XFS, Btrfs, NTFS (runs) |
Extents keep the metadata small for large files: a 1 GiB video written in one go might need only a handful of extents instead of 262 144 block pointers.
Crash consistency and journaling
Creating a file means several separate writes: the bitmap, the inode, the directory entry, the data. If the power fails between them, the file system is left half-updated: a block marked used that nobody owns, or a directory entry pointing to an empty inode. Old file systems needed a slow full scan (fsck, chkdsk) after every crash.
A journal (write-ahead log) fixes this. The file system first writes a description of the whole change to a log area, then a commit record, and only then updates the real structures. After a crash, it replays committed transactions and throws away uncommitted ones.
disk = {"bitmap": "1100", "dir": ["a.txt"]}
journal = [
("T1", "bitmap", "1110"), ("T1", "dir", ["a.txt", "b.txt"]), ("T1", "COMMIT", None),
("T2", "bitmap", "1111"), ("T2", "dir", ["a.txt", "b.txt", "c.txt"]),
# crash! T2 never wrote its COMMIT record
]
def replay(disk, journal):
committed = {tx for tx, key, _ in journal if key == "COMMIT"}
for tx, key, value in journal:
if key == "COMMIT":
continue
if tx in committed:
disk[key] = value
print(f"redo {tx}: {key} = {value}")
else:
print(f"skip {tx}: {key} (not committed)")
return disk
print("after recovery:", replay(disk, journal))redo T1: bitmap = 1110
redo T1: dir = ['a.txt', 'b.txt']
skip T2: bitmap (not committed)
skip T2: dir (not committed)
after recovery: {'bitmap': '1110', 'dir': ['a.txt', 'b.txt']}
b.txt survives completely and c.txt never existed: no half-created file. That property, "all or nothing", is what ext4, XFS and NTFS all get from their journals. Most of them journal only metadata by default, so the contents of a file written just before a crash may still be stale; applications that care call fsync().
Copy-on-write file systems (Btrfs, ZFS, ReFS, Apple's APFS) take a different route: they never overwrite live data, they write the new version elsewhere and then flip one pointer. That also makes snapshots almost free.
Mounting
A file system is useless until it is mounted: attached to the directory tree (Linux) or given a drive letter (Windows). The kernel reads the superblock, checks the type, and from then on routes every path below the mount point to that file system's driver. That is how one tree can contain ext4, tmpfs, a FAT32 USB stick and the virtual /proc side by side, as the next lessons show.
Note: "File system" also means the tree of folders you see. In this section it mostly means the format on the disk. The tree itself is covered in The Linux Directory Tree and The Windows Folder Layout.
Learn more: Linux File Systems · Links, Inodes & File Metadata · Bash: Disk & Memory
Test yourself
Where does a Unix-style file system store a file's name?
- In the file's inode
- In the superblock
- In the directory entry that points to the inode
- In the block bitmap
After a crash, a journaling file system finds a transaction with no commit record. What does it do?
- Replays it anyway
- Discards it, so the change never happened
- Runs a full fsck of the disk
- Marks all its blocks as bad
Why does ext4 use extents instead of a list of every block number?
- Extents encrypt the data
- A range (start, length) describes many contiguous blocks with tiny metadata
- Extents are required for directories
- Extents make files smaller