Lesson 20 of 26 · 12 min read
Files, directories, and building a simple file system
Separate POSIX file descriptors from open-file offsets and inodes, trace pathname traversal down to data blocks, and lay out the Very Simple File System (VSFS) on disk.

Course syllabus · lesson 20 of 26
In this lesson
Everything we call a "file" or "folder" is an OS persistence abstraction built out of raw numbered disk blocks. Under UNIX, two clean concepts anchor the entire storage hierarchy: files (linear byte arrays identified internally by an inode number) and directories (special files mapping human names like "report.txt" to inode numbers).
The crux of the problem is how the file system organizes on-disk structures — metadata, free-space tracking, multi-level file pointers, and directories — and coordinates open file descriptors with in-RAM caching so reading and creating files is both fast and exact.
Resolve a pathname and read its data
Step 1 of 3
Start from the root
For open("/foo/bar.txt"), the lookup starts at the root directory and finds the entry mapping foo to inode 4.
The UNIX File API: Descriptors, offsets, fsync(), and links
Before looking at disk blocks, keep the user-facing POSIX abstractions straight:
- Process FD -> Open-File Entry -> Inode: Calling
int fd = open("/foo/bar.txt", O_RDONLY);walks the path and allocates a file descriptor integer (3) private to that process, pointing to a kernel open file table entry that tracks the current byte offset and access mode (O_RDONLY/O_WRONLY), which in turn points to the shared in-memory inode! That indirection is why twoopen()calls hold independent read offsets, while a child that inherits the descriptor throughfork()shares the same open-file offset.dup()also creates a descriptor that shares that open-file entry. read(),write(),lseek(), andfsync(): A successfulread()advances the open-file offset by the number of bytes returned. At end of file, it returns zero.write()usually buffers dirty blocks in RAM's page cache for batching. A successfulfsync(fd)requests durability for the file's pending data and the metadata needed to retrieve it.- Atomic rename (
rename(tmp, final)): Editing a config safely writesconfig.tmp, callsfsync(), and runsrename("config.tmp", "config")in the same directory. Other processes see the name switch atomically. For crash durability, also synchronize the containing directory after the rename on a filesystem that supports directory synchronization. - Hard links (
ln) vs. Symbolic links (ln -s): A hard link adds a second directory entry pointing straight to the same inode number and increments itslinks_count. The filesystem frees the inode and data blocks after the last link is removed and the last open reference is released. Hard links cannot cross file systems or target directories (avoiding cycles). A symbolic link is its own small file storing a pathname string, which can point across partitions or dangle if the target moves!
On-disk organization of VSFS (Very Simple File System)
Chop a 64-block (4 KiB each) disk partition into five contiguous zones:
- Block 0 — Superblock (
S): Records file system type, block count, inode count, and where the bitmaps and inode table start. The mount code checks its format identifier before using the rest of the layout. - Block 1 — Inode bitmap (
i):1bit per inode (0= free,1= allocated). - Block 2 — Data bitmap (
d):1bit per data block (0= free,1= allocated). - Blocks 3–7 — Inode table (
I): Array of fixed256-byteinodestructs (16inodes per 4 KiB block =80inodes total). Index directly byinum! - Blocks 8–63 — Data region (
D): Holds user file bytes and directory entries ((name, inum)records plus.and..).
Inside the Inode: Direct, indirect, and extent pointers
Most files on real machines are tiny (<= 48 KiB), yet a few videos or database tables grow gigabytes large. How does a fixed 256-byte inode support both cleanly? Multi-level index trees (an asymmetric tree biased toward small files!):
12direct pointers: Point straight to the first12data blocks (48 KiBat4 KiBblocks) with zero indirection!1single indirect pointer: Points to a block holding10244-byte block addresses (+4 MiB).- Double & triple indirect pointers: Two or three levels of pointer blocks scale capacity past gigabytes/terabytes (modern filesystems like ext4/XFS also pack contiguous ranges compactly as extents:
(start_block, length)pairs).
For this 64-block layout an inode number selects a slot using disk block = 3 + floor(inum / 16) and byte offset = 256 * (inum mod 16). Inode 29 is in disk block 4, starting at byte 13 * 256 = 3328. Reading it brings all 16 slots in block 4 into the block cache. The inode contains the file type, owner and mode, link count, file size, timestamps, and block addresses. Directory contents connect names to these records. A directory entry needs an inode number and a name, and a variable-length format also needs a record length so lookup can advance to the next entry. Addressing a directory's own bytes uses the same inode-to-data relationship as accessing a regular file.
An inode layout with 12 direct slots and one slot at each indirect depth stores 15 four-byte addresses, or 60 bytes, inside the 256-byte record. Each full indirect block has 4096 / 4 = 1024 addresses. With zero-based file block numbers, a byte offset of 49,151 lands at byte 4,095 of direct block 11. Offset 49,152 lands at byte zero of the first single-indirect data block, so a cold read there needs one more index read than a direct read. Direct plus single-indirect addresses cover blocks 0 through 1,035, for 4 MiB + 48 KiB of payload. Block 1,036 is the first double-indirect block. Subtract 1,036 from a block index in that region, then use the quotient by 1,024 to choose the top-level index entry and the remainder to choose the next entry. Double indirection adds 4 GiB of addressable payload. Triple indirection adds 4 TiB in this pointer-tree model. Actual file size is also limited by the size field, filesystem format, and available address space. The 64-block teaching disk has only 56 data-region blocks to share among directories, payload, and indirect blocks.
Access trace: Read /foo/bar.txt vs. Create & Write
Even reading one short file triggers a surprising cascade of disk reads without caching:
open("/foo/bar.txt"): Start at well-known root inode2(/). Read root inode -> read root data block -> locate"foo"'sinum. Readfoo's inode -> readfoo's data block -> locate"bar.txt"'sinum. Readbar.txt's inode (check permissions!) and returnfd. (5 block reads when the three inode slots occupy distinct cold inode-table blocks.)read(fd, buf, 4096): Readbar.txt's data block0(may block process until device IRQ completes!), and advance the file offset. A strict access-time policy also dirties the inode and can incur a subsequent inode-block write.
Exact create and write counts with a warm parent
Count physical filesystem-block transfers in a simple VSFS with no journal. Start immediately after the path walk to the parent found free room in its directory block and established that the name was absent. The parent inode block and directory block are cached. Let the free inode slot be in a different, cold inode-table block. Start with both allocation bitmaps cold, and write three full aligned 4 KiB blocks through direct pointers. Count an explicit flush of all dirty blocks so the write totals include deferred work.
- Resolve the missing name. The lookup that got us here costs four cold block reads if root and parent live in different inode-table blocks. Two reads fetch inodes and two fetch directories. The name search stops in the parent directory. There is no child inode to look up.
- Create an empty file. Read the inode bitmap and the target inode-table block. The inode-table read preserves neighboring inode slots during a block-sized rewrite. Set the chosen bitmap bit, initialize the new inode, insert the parent directory entry, and update the parent's timestamps. If flushed here, creation costs 2 reads and 4 writes after lookup: one write each for the inode bitmap, child inode block, parent inode block, and parent directory block.
- Write three blocks as one batch after that flush. Read the cold data bitmap once, set three bits, fill three full data blocks, and update the cached child inode's size and direct pointers. At flush there are 1 read and 5 writes: one data bitmap, one child inode block, and three payload blocks. Full-block writes to new blocks need no old payload reads.
- Combine the create and the writes before flushing. The new child inode block needs only one write containing its final size and pointers. After lookup that yields 3 reads and 8 writes, or 7 reads and 8 writes including the cold parent walk. If the new inode slot shares the warm parent inode-table block, remove one read and one write from the combined totals.
The counts depend on placement and cache policy. For example, inodes 2 and 14 both lie in block 3. In the worked /docs/os.txt lookup below, use those inode numbers and inode 29 to get four cold reads for open(): two inode-table blocks and two directory blocks. A first read that touches one cold data block adds exactly one read under the no-access-time-update assumption. A second read from the same cached data block adds zero. A first read straddling two cold direct blocks adds two. Permission checks and offset bookkeeping operate on the metadata already in memory.
With all relevant directory, inode, and data blocks cached, a repeated open followed by the same small read requires zero device reads. The kernel still resolves the names, checks access, and allocates an open-file entry. The create trace shows the complementary use of the cache: repeated changes to the same bitmap or inode block can collapse into one write of its final state.
Now extend the three-block file until the next write allocates its first indirect block. If the inode and bitmap are still cached, appending one full page at that boundary requires a new data block and a new index block. Set two allocation bits and update the inode's size and indirect pointer. The flush writes the data bitmap, the inode block, the new index block, and the payload block. A direct append under the same conditions writes three blocks. A later cold read of the indirect payload needs both its index block and its data block after the inode is resolved.
open("/foo/bar.txt") -> read root inode(2) -> read "/" data -> inum(foo)
-> read foo inode -> read "foo" data -> inum(bar)
-> read bar inode -> return FD -> open-file(offset=0)
Worked trace: trace FD isolation and directory lookup
Trace opening /docs/os.txt, reading its first 100 bytes, and sharing the descriptor:
- Lookup chain: Root inode (
2) ->/data block givesdocs -> inum 14-> read inode14->/docsdata block givesos.txt -> inum 29-> read inode29-> check read permissions -> allocate kernel open-file entry(inode=29, offset=0)-> bind Process FD3. - Interrupt boundary during
read(3, buf, 100): If data block0of inode29is absent from the page cache, the process entersBlocked(SLEEPING) while DMA fetches block0. The device interrupt lets the kernel mark it ready. When the read resumes, the kernel copies 100 bytes intobufand advances the open-file offset to100(the on-disk inode itself does not store any read offset!). - Change one input: Suppose Process P calls
fork()after opening FD3(offset = 100), and Child C reads50bytes from FD3. What offset does Parent P read from next?150— because parent and child share the exact same kernel open-file table entry created beforefork()!
Next, see how real file systems tame random disk seeks across those scattered bitmaps, inodes, and data blocks in disk locality: FFS and Log-Structured FS.
Before you move on
Try it in your workspace
Draw pathname -> directory entry -> inode -> data block for reading `/foo/bar.txt`. Keep the per-process file descriptor and open-file offset distinct from the on-disk inode and data bitmap.
Keep a short note of what you tried, what passed, and what you still need to check.
0 of 3 checked.
Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.