12. A file system small enough to read
Why this layer exists
A file system is the first kernel object in this book the reader has almost certainly only ever used. Every object before it — a page table, a trap frame, a scheduler, a ring — was new; a file system is familiar, and familiarity is the problem, because what is familiar is the interface (open, a path, read, a byte offset) and not the thing under it: a fixed arrangement of bytes on a disk that two programs, a formatter and a kernel, agree on without ever running at the same time. This chapter builds one that fits on a page. Small enough to read means small enough to trust, and later, in Part VI, small enough to hand to a guest whole: a unikernel that carries a disk image carries a format, and this is a format the reader will have written both ends of.
Nothing here is ext2 or FFS. The layout is this book’s own — a superblock, an inode array, a bitmap, data — chosen so that every number in it can be derived by hand and checked with xxd. What it leaves out, it names.
Mechanism
The layout, on one page
#define FS_MAGIC 0x52424d45u /* "EMBR", little-endian */
#define FS_VERSION 1u
#define FS_BLOCK 512u
#define FS_NBLOCKS 2048u /* 1 MiB */
#define FS_NINODES 32u
#define FS_INODE_START 1u /* first inode block */
#define FS_INODES_PER_BLOCK (FS_BLOCK / sizeof(struct dinode))
#define FS_BITMAP_BLOCK 3u
#define FS_DATA_START 4u
#define FS_NDIRECT 6u
#define FS_MAXFILE (FS_NDIRECT * FS_BLOCK) /* 3072 bytes */
#define FS_NAMELEN 14u
#define FS_ROOT_INO 1u
struct superblock {
unsigned int magic;
unsigned int version;
unsigned int nblocks;
unsigned int ninodes;
unsigned int inode_start;
unsigned int bitmap_block;
unsigned int data_start;
unsigned int pad;
};
#define T_FREE 0
#define T_FILE 1
#define T_DIR 2
struct dinode { /* 32 bytes */
unsigned short type;
unsigned short nlink;
unsigned int size; /* bytes */
unsigned int direct[FS_NDIRECT];
};
struct dirent { /* 16 bytes */
unsigned short inum; /* 0: unused entry */
char name[FS_NAMELEN]; /* NUL-padded, not necessarily terminated */
};
A block is a sector is 512 bytes, chapter 11’s unit kept so that no arithmetic hides a conversion. A 1 MiB image is 2048 blocks. Block 0 is the superblock: a magic value (EMBR, so a kernel that mounts the wrong disk says so), a version, and the counts and starting blocks the rest of the layout is derived from. Blocks 1 and 2 hold 32 inodes of 32 bytes, sixteen to a block. An inode is the fixed-size record that is a file as far as the disk is concerned: a type, a link count, a size in bytes, and six block numbers — where the file’s first six blocks are. Names are not in it; a file’s name lives in a directory, which is a file whose bytes are 16-byte entries of an inode number and a 14-character name. Block 3 is a bitmap, one bit per block, 2048 bits in a 512-byte block with room to spare. Data starts at block 4, and the root directory — inode 1 — is there, with two entries pointing at itself, . and .., before any file.
Six direct blocks and nothing else is a decision, not an oversight: the largest file is bytes. Exercise (a) prices the indirect block this design leaves out; the reason it is left out is that the walk from an inode to a byte should be one array index and one block read, with no second level to explain before the first is understood.
Two programs, one header
int main(int argc, char **argv)
{
unsigned char *sb = block(0);
unsigned next_ino = FS_ROOT_INO + 1; /* 2: the first file */
unsigned next_blk = FS_DATA_START + 1; /* 5: block 4 is the root dir */
unsigned root_direct[FS_NDIRECT] = { FS_DATA_START, 0, 0, 0, 0, 0 };
unsigned char *root = block(FS_DATA_START);
unsigned nent = 0, b;
int i;
if (argc < 2) {
fprintf(stderr, "usage: mkfs IMAGE [FILE...]\n");
return 2;
}
/* Superblock: the numbers the kernel checks and derives from. */
put32(sb + 0, FS_MAGIC);
put32(sb + 4, FS_VERSION);
put32(sb + 8, FS_NBLOCKS);
put32(sb + 12, FS_NINODES);
put32(sb + 16, FS_INODE_START);
put32(sb + 20, FS_BITMAP_BLOCK);
put32(sb + 24, FS_DATA_START);
/* Blocks 0..4 are spoken for before any file: superblock, two
* inode blocks, the bitmap, the root directory's one block. */
for (b = 0; b <= FS_DATA_START; b++)
bitmap_set(b);
/* The root directory: "." and ".." both name inode 1. */
put16(root + 16 * nent, FS_ROOT_INO);
memcpy(root + 16 * nent + 2, ".", 1);
nent++;
put16(root + 16 * nent, FS_ROOT_INO);
memcpy(root + 16 * nent + 2, "..", 2);
nent++;
for (i = 2; i < argc; i++) {
const char *base = strrchr(argv[i], '/');
unsigned direct[FS_NDIRECT] = { 0 };
unsigned size = 0, k = 0;
FILE *f;
size_t n;
base = base ? base + 1 : argv[i];
if (strlen(base) > FS_NAMELEN || next_ino >= FS_NINODES ||
nent * sizeof(struct dirent) >= FS_BLOCK) {
fprintf(stderr, "mkfs: cannot add %s\n", base);
return 1;
}
f = fopen(argv[i], "rb");
if (!f) {
perror(argv[i]);
return 1;
}
while ((n = fread(block(next_blk), 1, FS_BLOCK, f)) > 0) {
if (k == FS_NDIRECT) {
fprintf(stderr, "mkfs: %s exceeds %u bytes\n", base,
FS_MAXFILE);
return 1;
}
direct[k++] = next_blk;
bitmap_set(next_blk);
next_blk++;
size += (unsigned)n;
}
fclose(f);
write_inode(next_ino, T_FILE, 1, size, direct);
put16(root + 16 * nent, next_ino);
memcpy(root + 16 * nent + 2, base, strlen(base));
nent++;
next_ino++;
}
write_inode(FS_ROOT_INO, T_DIR, 2, nent * (unsigned)sizeof(struct dirent),
root_direct);
{
FILE *out = fopen(argv[1], "wb");
if (!out || fwrite(image, 1, sizeof image, out) != sizeof image ||
fclose(out) != 0) {
perror(argv[1]);
return 1;
}
}
return 0;
}
mkfs runs on the host. It writes the superblock, marks blocks 0 through 4 used, lays down the root directory with . and .., and then, for each file named on its command line, takes the next inode and the next data blocks in order and appends an entry to the root. Inodes are handed out from 2, data blocks from 5, in argument order, so the image is a function of its inputs and nothing else — a rebuild is byte-identical, and the lab checks that it is. The kernel and the formatter include the same fs.h; the constants and the two structs are the whole agreement, and neither side can drift from it without the other noticing at the magic value.
A formatter on the host is the honest place for it (exercise (e) asks why): formatting is not mounting. The kernel that reads this layout never needs to create it, and a guest with no way to get files in but the disk itself is served by a host that writes the disk.
Where the kernel keeps blocks
#define NBUF 8
struct buf {
unsigned int blockno;
int valid, dirty;
unsigned char data[FS_BLOCK];
};
static struct buf bufs[NBUF];
static int victim;
/* The block, in memory. A miss evicts the next buffer in rotation,
* writing it back first if it is dirty. */
static struct buf *bget(unsigned int b)
{
struct buf *bp;
int i;
for (i = 0; i < NBUF; i++)
if (bufs[i].valid && bufs[i].blockno == b)
return &bufs[i];
bp = &bufs[victim];
victim = (victim + 1) % NBUF;
if (bp->valid && bp->dirty)
blk_write(bp->blockno, bp->data);
blk_read(b, bp->data);
bp->blockno = b;
bp->valid = 1;
bp->dirty = 0;
return bp;
}
/* Every dirty block to the disk, in buffer order. Returns the count. */
static unsigned int bsync(void)
{
unsigned int n = 0;
int i;
for (i = 0; i < NBUF; i++)
if (bufs[i].valid && bufs[i].dirty) {
blk_write(bufs[i].blockno, bufs[i].data);
bufs[i].dirty = 0;
n++;
}
return n;
}
Every block the kernel touches goes through a cache of eight buffers. bget returns the block in memory, reading it through chapter 11’s blk_read on a miss and evicting the next buffer in rotation — writing it back first if it is dirty. A block that is changed is marked dirty and stays in memory; bsync, called from fs_close, writes every dirty buffer to the disk and counts them. The cache is not there for speed — with synchronous single-sector I/O nothing here is fast — it is there so that the order in which changes reach the disk is a fact in the code, visible and discussable, rather than an accident of when each write happened to be issued. That order is the subject of the section on consistency below.
Inodes are read out of and written back into their block by value: with eight buffers and a rotating victim, a pointer into a buffer does not survive another bget, so iread and iwrite copy.
Inodes, blocks, and a name
/* The first free inode, marked as the given type. Inode 0 is never
* handed out: it is the number that means "none". */
static unsigned int ialloc(unsigned short type)
{
struct dinode di;
unsigned int ino;
for (ino = 1; ino < sb.ninodes; ino++) {
iread(ino, &di);
if (di.type == T_FREE) {
unsigned int k;
di.type = type;
di.nlink = 1;
di.size = 0;
for (k = 0; k < FS_NDIRECT; k++)
di.direct[k] = 0;
iwrite(ino, &di);
return ino;
}
}
return 0;
}
/* The first free data block, zeroed: a file's new block must not show
* what the block held last. */
static unsigned int balloc(void)
{
struct buf *bm = bget(sb.bitmap_block);
unsigned int b;
for (b = sb.data_start; b < sb.nblocks; b++)
if (!(bm->data[b / 8] & (1u << (b % 8)))) {
struct buf *bp;
unsigned int i;
bm->data[b / 8] |= (unsigned char)(1u << (b % 8));
bm->dirty = 1;
bp = bget(b);
for (i = 0; i < FS_BLOCK; i++)
bp->data[i] = 0;
bp->dirty = 1;
return b;
}
return 0;
}
ialloc scans the array from inode 1 for a free one and stamps it with a type; inode 0 is never handed out because 0 is the number that means “no inode” in a directory entry. balloc scans the bitmap from the first data block for a clear bit, sets it, and zeroes the block in the cache — a file’s new block must not show what the block held last, which on a fresh image is nothing and on a used one is somebody’s old data.
long fs_read(unsigned int ino, unsigned long off, void *kbuf, long n)
{
struct dinode di;
long done = 0;
iread(ino, &di);
if (off >= di.size)
return 0;
if ((unsigned long)n > di.size - off)
n = (long)(di.size - off);
while (done < n) {
unsigned long o = off + (unsigned long)done;
unsigned int b = di.direct[o / FS_BLOCK];
unsigned long in = o % FS_BLOCK;
long chunk = (long)(FS_BLOCK - in);
struct buf *bp;
if (chunk > n - done)
chunk = n - done;
bp = bget(b);
kmemcpy((unsigned char *)kbuf + done, bp->data + in,
(unsigned long)chunk);
done += chunk;
}
return done;
}
Reading is the walk the layout promised: the inode’s size bounds the request, off / 512 picks a direct block, off % 512 an offset in it, and the bytes come out of the cached block. Writing is the same in reverse, allocating a block the first time an index is touched and raising the size. Neither knows anything about names.
/* One component under the root. Returns the inode number, creating
* the file if asked and it is absent. Nothing is opened in the sense
* of a kernel object here — that is fd.c's struct file; this is the
* name-to-inode step the directory exists for. */
int fs_open(const char *name, int flags)
{
unsigned int ino = dir_lookup(name);
if (ino == 0) {
if (!(flags & O_CREAT))
return -1;
ino = ialloc(T_FILE);
if (ino == 0 || dir_link(name, ino) < 0)
return -1;
uart_puts("S: fs: create ");
uart_puts(name);
uart_puts(" inode ");
uart_puthex(ino);
uart_puts("\r\n");
return (int)ino;
}
uart_puts("S: fs: open ");
uart_puts(name);
uart_puts(" inode ");
uart_puthex(ino);
uart_puts(" size ");
uart_puthex(fs_size(ino));
uart_puts("\r\n");
return (int)ino;
}
fs_open is where a name becomes an inode. It reads the root directory as a file — 16 bytes at a time through fs_read on inode 1 — and compares names; if the name is absent and O_CREAT was asked, it allocates an inode and appends an entry, which is a fs_write on inode 1. That the directory is a file, read and written through the same two functions as everything else, is the trick that keeps the design on one page. Paths are one component under the root; a hierarchy is the same lookup repeated per component on a directory inode instead of the root, and it is left out because repetition is not a mechanism.
/* The path comes in through the walk like any user bytes, bounded and
* NUL-terminated by the kernel, not trusted to be. */
static long sys_open(long path, long flags)
{
char name[FS_NAMELEN + 2];
struct file *f;
int ino;
unsigned int i;
for (i = 0; i < sizeof name; i++)
name[i] = 0;
if (fs_copy_name(curproc, (unsigned long)path, name, sizeof name) < 0)
return -1;
ino = fs_open(name, (int)flags);
if (ino < 0)
return -1;
f = file_alloc();
if (!f)
return -1;
f->type = FD_FILE;
f->ino = (unsigned int)ino;
f->off = 0;
f->readable = 1;
f->writable = (flags & O_WRONLY) != 0;
return fd_install(curproc, f);
}
The user’s side is the third kind of descriptor. open copies the path in through the walk, bounded and NUL-terminated by the kernel, asks fs_open for an inode, and installs a struct file of kind FD_FILE with that inode and an offset of 0. From then on read, write, and close are the three calls chapter 10 built, dispatched by kind: a file’s read moves bytes from the cache to the user through copy_out_user and advances the offset; its close is the moment the cache reaches the disk. A process cannot tell a pipe from a file by the calls it makes on it, which is the point of the descriptor table.
What a halt in the middle leaves behind
The lab creates note.txt, writes 17 bytes, and closes it. Between the create and the close, four blocks are dirty: block 1 (inode 3 now says file, size 17, block 6; inode 1’s size grew by one entry), block 4 (the root’s new entry names inode 3), block 3 (bit 6 now set), and block 6 (the bytes). bsync writes them in buffer order, which is the order the buffers were first used in this run: 1, 4, 3, 6 — inode, directory, bitmap, data. Now halt the machine between any two of those writes and read the disk.
After 1 alone: inode 3 exists with size 17 and block 6, the root’s size covers a fourth entry, but block 4 on disk still has zeros there — an entry with inode 0, which lookup skips. An allocated inode nobody can name, and block 6 not marked used: an orphan, and a block the next balloc will hand out again. After 1 and 4: the file has a name and an inode, its block is not marked used, and the block holds zeros; the next file to allocate a block gets block 6 too, and two files now share it — the next write to either silently corrupts the other. After 1, 4 and 3: the file is complete in every structure and its content is zeros. Exercise (d) asks which single lost write is worst; the answer is the bitmap, because a lost bitmap write is not a wrong file but a future double allocation, and nothing on the disk records that it happened.
The rule real file systems follow is that a change must never be reachable before it is consistent: write the data and the bitmap and the inode, then the directory entry that names them — and never in the order this cache happens to have. Either the writes are ordered by hand (FFS’s soft updates), or every group of writes is first written whole to a log and replayed after a crash (a journal, which is what ext3 added to ext2 and what every file system the reader runs has). This chapter builds neither. The cache makes the order visible; the reader now knows what a journal is for, which is more than the reader knew before, and a journal itself is a chapter this book does not have.
mem_init();
trap_init();
uart_puts("S: kernel up\r\n");
kalloc_init();
blk_init(); /* chapter 11: the disk */
fs_init(); /* the superblock: is this a disk we understand? */
{
struct proc *p = launch(user6_blob_start,
(unsigned long)(user6_blob_end -
user6_blob_start),
USER_BASE, 0);
console_attach(p);
}
scheduler();
{
int i;
for (i = 0; i < NPROC; i++)
if (proc_tab[i].state == WAITING) {
uart_puts("S: deadlock: proc ");
uart_putc((char)('0' + proc_tab[i].pid));
uart_puts(" still waiting\r\n");
halt(1);
}
}
uart_puts("PASS\r\n");
halt(0);
The boot stage mounts — reads the superblock and refuses anything but its own magic and version — and launches the probe with a console. fs_init’s line and the four lines the file system prints are the transcript’s evidence that the layout on disk and the layout in the header agree.
int main(void);
int main(void)
{
static const char note[] = "written by ember\n";
char buf[64];
long fd, n, i, same = 1;
fd = syscall3(7, (long)"hello.txt", O_RDONLY, 0); /* open */
n = syscall3(5, fd, (long)buf, sizeof buf); /* read */
tag();
puts(" hello.txt: ");
syscall3(2, 1, (long)buf, n);
syscall3(6, fd, 0, 0); /* close */
fd = syscall3(7, (long)"note.txt", O_CREAT | O_WRONLY, 0);
syscall3(2, fd, (long)note, slen(note)); /* write */
syscall3(6, fd, 0, 0); /* close: the sync */
fd = syscall3(7, (long)"note.txt", O_RDONLY, 0);
n = syscall3(5, fd, (long)buf, sizeof buf);
syscall3(6, fd, 0, 0);
if (n != slen(note))
same = 0;
for (i = 0; same && i < n; i++)
if (buf[i] != note[i])
same = 0;
tag();
puts(same ? " note.txt: readback equal\r\n" : " note.txt: readback DIFFERS\r\n");
syscall3(1, 0, 0, 0);
return 0;
}
Walkthrough
ch12-super (the layout: constants and two structs), ch12-mkfs (the formatter’s core), ch12-bcache (eight buffers, the rotation, the sync), ch12-ialloc (free inode, free block), ch12-read (inode → block → byte), ch12-open (name → inode, create), ch12-sys-open (the third descriptor kind), ch12-main (mount and launch), ch12-probe.
Exercises
(a) Compute the largest file this layout allows, and what one indirect block would add and cost.
Answer
Six direct blocks of 512 bytes: 3072 bytes. An indirect block is a data block that holds block numbers instead of bytes — 512 / 4 = 128 of them — so one indirect pointer in the inode adds 128 × 512 = 65536 bytes, for a maximum of 68608. Its cost is one extra block per file that uses it (the pointer block itself, a data block taken from the same pool), and one extra read on every access past 3 KiB: inode, then the indirect block, then the data. A doubly indirect block would add 128 × 128 × 512 = 8 MiB behind two extra reads. The layout stays at six because the first level should be understood before the second is added, and because every file in this book’s labs is smaller than a page.
(b) Suppose an unlink existed that removed a directory entry and decremented the inode’s link count, freeing it at zero. Apply it to . and to .. and derive what goes wrong.
Answer
Both entries name the root itself, inode 1, which is why its link count is 2 and not 1. Unlinking . removes an entry and decrements inode 1 to 1; unlinking .. then removes the other and decrements it to 0, and the naive rule frees the root directory — the very file the entries were being removed from, with the entries for hello.txt still in its block, now pointing into an inode marked free, and a bitmap that still says block 4 is in use. On a hierarchy the failure is quieter and worse: a subdirectory’s .. is a second link to its parent, so a parent’s count is 2 plus one per child, and an unlink that treated .. like a name would free parents that still had children pointing at them. unlink must refuse the two names outright, and a directory removal must check that nothing but those two remain — which is exactly what POSIX unlink(2) and rmdir(2) do, and why the two entries exist at all: they make “parent” a lookup rather than a separate structure.
(c) After the lab, read disk.img on the host with xxd and find the planted file and the created one by derived offsets.
Answer
Offsets are block × 512 plus the slot. The superblock is at 0: 45 4d 42 52 is EMBR, then version 1, 0x800 blocks, 0x20 inodes, inode start 1, bitmap 3, data 4. Inode i is at 0x200 + 32 i: inode 1 at 0x220 reads type 2, nlink 2, size 0x30 (three entries before the lab, four after: 0x40) and direct[0] = 4; inode 2 at 0x240 reads type 1, nlink 1, size 0x14, direct[0] = 5; inode 3 at 0x260, created by the lab, reads type 1, size 0x11, direct[0] = 6. The root directory is block 4 at 0x800: 01 00 2e is inode 1 named ., then .. at 0x810, then 02 00 68 65 6c 6c 6f 2e 74 78 74 — inode 2, hello.txt — at 0x820, and after the lab 03 00 6e 6f 74 65 2e 74 78 74 at 0x830. Block 5 at 0xa00 is hello from the disk; block 6 at 0xc00 is written by ember. The bitmap’s first byte at 0x600 is 7f: blocks 0 through 6 used. Observed on this image; the image is regenerated before every run, so a reader sees the same bytes.
(d) Of the four blocks the lab’s close writes, which single lost write does the most damage?
Answer
The bitmap. Lose the inode block and note.txt vanishes cleanly — the directory entry is there but names an inode the disk still calls free, and lookup would find a file whose inode says T_FREE with size 0 — plus one leaked block. Lose the directory block and the inode and its data exist with no name: an orphan and a leaked block, invisible but harmless. Lose the data block and the file exists, correctly sized, full of zeros — wrong, but wrong in a way a reader of the file can see. Lose the bitmap write and everything about note.txt is correct, and block 6 is marked free: the next balloc hands it to the next file, two inodes now point at one block, and the next write through either corrupts the other. No structure on the disk records the error, no read of either file reveals it until it happens, and it happens later. That is the shape of the worst file-system bug: not a missing file but a shared block, and it is why the bitmap is written before anything that depends on it in every design that takes crashes seriously.
(e) Why does mkfs run on the host and not in the kernel?
Answer
Because formatting and mounting are different jobs with different inputs. Mounting reads a layout that already exists and needs nothing but the disk. Formatting creates the layout from files — and the kernel has no files until the layout exists; the only way bytes get into this guest is the disk itself. The host has the files, a C compiler, xxd to check the result, and no need to be small. It also keeps the kernel honest: a kernel that could format its own disk would be tempted to “fix” a layout it did not understand, and the magic-value refusal in fs_init would have an escape hatch. Real systems draw the same line: mke2fs is a program, not a syscall, and the kernel’s ext4 driver has never created a file system.
(f) What would a unikernel guest (Part VI) delete from this design, and what would it keep?
Answer
It keeps the on-disk layout — that is the contract with whoever wrote the image, and a unikernel is often defined by shipping one — and it keeps the cache, or at least the write ordering the cache makes visible. It deletes the boundary this chapter built the file system behind: there is no U mode, so open is a function call and not an ecall, the path is a pointer and not a copy through the walk, read fills the caller’s buffer directly and copy_out_user is gone, and the descriptor table — the indirection that let a process treat a pipe and a file alike — becomes an ordinary struct the application holds. What that deletion buys is a copy per byte and a trap per call; what it gives up is that a bug in the application’s use of a pointer is now a bug in the file system’s memory. Chapter 32 fixes what a guest may assume about its disk; this chapter is what it would be assuming.
Lab
make lab CH=12
make lab CH=12 IMPL=mine
labs/ch12/extra.mk adds chapter 11’s device flags and builds disk.img from files/hello.txt with the reference mkfs — and rebuilds it before every run, because the lab creates a file: a second run on the same image would find note.txt already there and print a different transcript. The image is generated and gitignored; mkfs.c, fs.h and files/ are what is committed, and a rebuilt image is byte-identical.
After the block device’s lines: S: fs: superblock ok blocks=0x800 inodes=0x20 data from 0x4, the mount; S: fs: open hello.txt inode 0x2 size 0x14, the lookup; U:1 hello.txt: hello from the disk — the file’s bytes, newline included, printed by the process; S: fs: create note.txt inode 0x3; S: fs: sync wrote 0x4 blocks, the close of the written file — the four blocks the consistency section walks through; S: fs: open note.txt inode 0x3 size 0x11, the second open finding what the first created; U:1 note.txt: readback equal; S: proc 1 exited; PASS. Every number is a property of the layout or of the two files’ lengths.
IMPL=mine copies exactly the objects chapter 12 links and stubs fs_open to print MINE: fs_open stub and halt: the mount succeeds and the first open fails loudly.
Further reading
- A Fast File System for UNIX (McKusick, Joy, Leffler, Fabry; Computer Systems Research Group, UC Berkeley, 1984) — the paper behind the inode-array-plus-bitmap shape this layout is a miniature of, and behind the write-ordering discipline the consistency section names.
- xv6-riscv (MIT PDOS) —
kernel/fs.candmkfs/mkfs.care the same two-program shape with a log this chapter names and does not build; its inode has twelve direct blocks and one indirect, which is exercise (a) done. - pipe(2) — Linux manual page and its neighbours
open(2),unlink(2),rmdir(2)(man-pages project) — the contracts behind exercises (b) and (f); the./..rules are stated there as errors a call must return.