← All lessons
How file systems work
Save a file
App
Directory
Inode
Disk
save.c
int fd = open("/home/ana/draft.txt", O_CREAT | O_WRONLY, 0644);write(fd, text, len);close(fd); fd = open("/home/ana/draft.txt", O_RDONLY);read(fd, buf, sizeof buf);fs/write.c
// open() with O_CREAT: the name isn't there yetstruct inode *dir = namei("/home/ana");if (!dir_find(dir, "draft.txt")) { ino = alloc_inode(); // 43 dir_add(dir, "draft.txt", ino->num);} // write(): each 16 bytes go into a free blockfor (size_t i = 0; i < len; i += BLOCK) { int b = alloc_block(); disk_write(b, text + i, BLOCK); ino->blocks[ino->nblocks++] = b;}ino->size = len;Directories are tables of names and inode numbers
Starts with / from the root, otherwise from /home/ana
Or try one
Lookups
The inode it lands on
The name lives in the directory, not in the inode. Two rows can point at one inode: a hard link
fs/namei.c
struct inode *namei(const char *path) { // absolute paths start at /, others at the working directory struct inode *ino = path[0] == '/' ? root : cwd; const char *name; while ((name = next_part(&path))) { if (!S_ISDIR(ino->mode)) return ERR(-ENOTDIR); int num = dir_find(ino, name); // one table lookup per name if (!num) return ERR(-ENOENT); ino = iget(num); } return ino;}Fragmentation when the free space is full of holes
Disk 32 blocks
free
largest run
Files
An SSD has no head to move, so pieces cost it far less than a spinning disk
alloc.js
function allocate(disk, n) { // first fit: one run that holds the whole file const run = freeRuns(disk).find((r) => r.length >= n); if (run) return run.slice(0, n); if (freeCount(disk) < n) throw new Error("ENOSPC"); // none fits, so take the lowest free blocks return freeBlocks(disk).slice(0, n);} function remove(disk, file) { // the data stays put, it's just marked free for (const b of file.blocks) disk[b] = null;} function defragment(disk, files) { let next = 0; // rewrite each file as one run for (const f of byFirstBlock(files)) { f.blocks = move(disk, f.blocks, next); next += f.blocks.length; }}Topics
Next: How a CPU cache works
Open lesson