Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 19 (Nov 10), slide deck
fs_netprog1. Reading: CS:APP3e §11.1–§11.4 (plus file-system background for Lab 8,sfslab). Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and run on an Apple M4 Pro (macOS). The file system is a Python teaching model; the address code is real C. Code:code/lecture19/. Reading time: ~90 minutes; ~15 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Describe the on-disk layout of a simple file system — superblock, inode table, free bitmap, data blocks — and say what each part is for.
- Explain what an inode holds, why a file has no name of its own, and how a directory is just a file of (name → inode) records.
- Trace path lookup component by component and explain why it costs several block reads (and why kernels cache it).
- Explain why real inodes need indirect blocks, and what runs out first when a disk fills (blocks vs inodes).
- Describe the Internet as a hierarchy of networks, and the roles of IP, packets/routers, IP addresses (IPv4/IPv6), and DNS.
- Convert between host and network byte order (
htons/htonl), between dotted decimal and 32 bits (inet_pton/inet_ntop), and usegetaddrinfoto turn a name into ready-made socket addresses.
0.2 Prerequisites and scope
- Lecture 18: files as byte sequences, descriptors,
statmetadata. That was the interface; this is the implementation beneath it, and then the network. - Lecture 2: byte order. The Internet is big-endian and this machine is not, which is why every port and address needs conversion.
- Lectures 9–10: blocks and caching. A disk block is the unit of transfer, so a file system is a blocking problem too.
- In scope: a simple file system’s structures and path lookup; the Internet model, IP, DNS, and the address API (
getaddrinfo, byte order,sockaddr). - Out of scope here: the full sockets interface and HTTP — Lecture 20. Journaling, extents and modern file systems are mentioned only as “what real systems add”.
0.3 Section → code map
| Section | Idea | Demo in code/lecture19/ |
|---|---|---|
| §1–§3 | layout, inodes, directories, path lookup | 01_filesystem.py, tinyfs.py |
| §4 | indirect blocks; blocks vs inodes running out | 01_filesystem.py (§7–8) |
| §6 | byte order, dotted decimal, sockaddr | 02_addresses.c |
| §7 | DNS and getaddrinfo | 02_addresses.c |
1. A disk is an array of blocks
A disk (or SSD) offers exactly two operations: read block n, write block n. Blocks are fixed size (512 B to 4 KB in practice). There are no files, no names, no directories — those are conventions that software imposes on the flat array. A file system is precisely that set of conventions, plus the code that maintains it.
The classic Unix layout divides the blocks into four regions:
block 0 SUPERBLOCK magic number + geometry: where everything else is
blocks 1..k INODE TABLE one fixed-size record per file: type, size, blocks
block k+1 FREE BITMAP one bit per block: in use or free
blocks … DATA BLOCKS file contents, and directory contents
tinyfs.py implements exactly this over a 4096-byte bytearray, so every structure can be printed. 01_filesystem.py formats it:
disk = 64 blocks x 64 B = 4096 B
superblock magic = 0x15213 (a mount checks this first)
block 0 superblock
blocks 1-4 inode table (16 inodes)
block 5 free-block bitmap
blocks 6-63 data (57 free)
The superblock matters more than it looks: it is the map you need before you can interpret anything else, which is why it is at a known location, why it carries a magic number (so mounting the wrong thing fails loudly rather than corrupting it), and why real file systems keep backup copies of it.
The free bitmap is the allocator — one bit per block, exactly the “which blocks are in use” problem Lecture 13 solved for the heap. Allocation is “find a zero bit”; freeing is “clear a bit”.
2. Inodes and directories: where the name lives
2.1 The inode
An inode (“index node”) is a file’s identity: everything about the file except its name and its contents.
inode: type (file/dir/free) | size in bytes | block pointers [0..NDIRECT-1]
In the toy design each inode is 16 bytes: 1 type byte, a 2-byte size, and 8 one-byte block numbers. You can see them raw:
inode table block 1 (16-byte inodes: type, 2-byte size, 8 block pointers):
0000 02 30 00 06 00 00 00 00 00 00 00 00 00 00 00 00 |.0..............|
0010 02 20 00 07 00 00 00 00 00 00 00 00 00 00 00 00 |. ..............|
Inode 0 is type 02 (directory), size 0x0030 = 48 bytes, and its single data block is 6. The stat of Lecture 18 is a read of this record.
2.2 A file has no name
Notice what the inode does not contain: a name. Names live in directories, and a directory is simply a file whose contents are records mapping a name to an inode number. In the toy file system each record is 16 bytes (1 inode byte + a 15-byte name):
root directory's data block 6 (16-byte records: 1 inode byte + 15 name bytes):
0000 00 2e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
0010 01 64 6f 63 73 00 00 00 00 00 00 00 00 00 00 00 |.docs...........|
0020 03 72 65 61 64 6d 65 2e 74 78 74 00 00 00 00 00 |.readme.txt.....|
Three records: . → inode 0, docs → inode 1, readme.txt → inode 3. The directory is read and written with the same code as any other file — which is the elegance of the design, and the reason directory operations are just file operations underneath.
This separation explains several things at once:
- Hard links: two directory entries can name the same inode, so one file has two equally valid names. Deleting one name does not delete the file; the inode’s link count drops. Nothing is “the real name”.
- Renaming is cheap: it edits a directory record, never the file’s data.
- Permissions live on the file (in the inode), not on the name.
3. Path lookup is a walk
There is no table mapping /docs/notes/lec19.txt to an inode. The kernel must walk the path, one component at a time, starting at a known root (inode 0 here):
- read the root directory’s contents; find
docs→ inode 1; - read inode 1, confirm it is a directory, read its contents; find
notes→ inode 2; - read inode 2’s contents; find
lec19.txt→ inode 4.
tinyfs traces it and counts the block reads:
- start at root inode 0
- read dir inode 0 (3 entries), look for 'docs' -> inode 1
- read dir inode 1 (2 entries), look for 'notes' -> inode 2
- read dir inode 2 (2 entries), look for 'lec19.txt' -> inode 4
=> inode 4, costing 9 block reads for a 21-character path
(a one-component path '/readme.txt' costs only 3 reads -- deep paths are dearer)
Nine block reads to open one file — and a one-component path costs three. Each level needs at least an inode read plus a directory-data read. That is why:
- every operating system keeps a lookup cache (Linux’s dentry cache) so repeated paths cost nothing;
- deep directory trees and long paths genuinely cost more;
- opening a file is far more expensive than reading from an already-open descriptor — which is why Lecture 18’s descriptor exists at all. The descriptor is the cached result of this walk.
Errors fall out of the walk naturally: a missing component is ENOENT, and a non-directory in the middle of a path is ENOTDIR.
4. Two limits the toy design makes obvious
4.1 Direct pointers, and why indirect blocks exist
With 8 direct block pointers and 64-byte blocks, the largest possible file is 8 × 64 = 512 bytes:
8 direct pointers x 64 B = 512 B is the largest file this design can hold
writing 512 B: ok (512 B stored)
writing 513 B: file too large: 513 > 512 (8 direct blocks x 64B)
Scaling up by adding pointers does not work: an inode big enough for a 1 GB file would waste enormous space on the millions of tiny files that dominate a real disk. The standard solution is indirection. A real inode keeps ~12 direct pointers plus:
- a single indirect pointer → a block full of block numbers;
- a double indirect pointer → a block of pointers to blocks of block numbers;
- a triple indirect pointer → one more level.
Small files use only direct pointers (one lookup, no overhead); huge files pay one, two or three extra reads per access. A ~128-byte inode can then describe a multi-terabyte file. (Modern file systems often use extents — “N consecutive blocks starting at B” — instead, which is more compact for large contiguous files.)
4.2 Blocks and inodes run out independently
The inode table is allocated when the file system is created, so it is a fixed, separate resource from the data blocks. Filling the toy disk with one-block files shows which runs out first:
created 11 more 1-block files, then: no free inodes
free blocks now 32, inodes are the other finite resource (16 total)
Inodes ran out while half the data blocks were still free. This is a real failure mode: a disk full of tiny files reports “no space left” with gigabytes apparently available, because it is out of inodes. (This section was written expecting ENOSPC from the data blocks; the demo found the inode limit instead — see the code README’s “Plan vs reality”.)
4.3 What real file systems add
Everything above is the structure. Real systems add crash consistency — a power failure between “allocate the block” and “update the inode” leaves the file system inconsistent. The standard fix is journaling: write what you intend to do to a log first, then do it, so recovery can replay or discard partial operations. They also add caching (both of blocks and of path lookups), extents, checksums, and snapshots.
5. Turning outward: the Internet
A network is another I/O device: a connection is read and written with the same read/write of Lecture 18. What makes it interesting is that the bytes are going to another machine, which means naming, routing and failure.
The Internet is built as a hierarchy of networks. The lowest level is a LAN (e.g. Ethernet or Wi-Fi) that can deliver a frame between directly-connected hosts. Routers connect LANs into larger networks, and routers of routers make an internet. The unifying trick is a protocol — an agreed format and set of rules — that hides the differences between the physical networks underneath:
- IP (Internet Protocol) provides a naming scheme (IP addresses) and a delivery mechanism for packets between any two hosts. It is best-effort: packets may be lost, duplicated, reordered or delayed, and IP does not promise otherwise.
- TCP builds a reliable, ordered byte stream on top of that unreliable packet service, with connections, acknowledgements and retransmission. “A connection” is a TCP concept; this is what Lecture 20’s sockets give you.
- UDP leaves IP’s unreliability exposed, trading guarantees for lower latency.
A packet is a header (where it is going, where it came from, how big it is) plus a payload. Each layer wraps the layer above: your bytes sit inside a TCP segment, inside an IP packet, inside an Ethernet frame. Routers look only at the IP header.
5.1 Addresses
An IPv4 address is 32 bits, written as four decimal bytes — “dotted decimal” — purely for human convenience. 128.2.42.52 is the four bytes 80 02 2a 34. IPv4’s 4 billion addresses proved too few, so IPv6 uses 128 bits, written as colon-separated hex groups (::1 is IPv6’s loopback). Modern code must handle both, which is exactly why the address API looks the way it does (§7).
A connection endpoint is an address plus a port (a 16-bit number identifying which program on that host). A TCP connection is identified by the four-tuple (source address, source port, destination address, destination port). Ports below 1024 are well-known (80 = HTTP, 443 = HTTPS, 22 = SSH) and reserved for privileged programs.
6. Byte order, and the address structures
6.1 Network byte order
Lecture 2 established that this machine is little-endian (low byte first). The Internet standardized on big-endian, called network byte order. So every multi-byte field — every port, every address — must be converted. Four functions do it: htons/htonl (host→network, short/long) and ntohs/ntohl (network→host).
02_addresses.c dumps the actual bytes rather than asserting the swap:
port 8080 = 0x1f90
in memory (host order): 90 1f
after htons (network): 1f 90
address 0x80022a34
in memory (host order): 34 2a 02 80
after htonl (network): 80 02 2a 34
Skipping the conversion is a classic bug with a memorable symptom: a program meaning port 8080 (0x1F90) connects to port 36895 (0x901F) instead.
6.2 Dotted decimal ↔ bits, and sockaddr
inet_pton (“presentation to network”) parses a string into the binary form; inet_ntop renders it back. The demo round-trips 128.2.42.52 and shows it is the four bytes 80 02 2a 34.
The kernel takes addresses in a struct sockaddr_in (IPv4) or sockaddr_in6 (IPv6): a family tag, a port in network order, and the address in network order. The socket API’s generic struct sockaddr * is just a cast target so one function can accept any family.
sizeof(struct sockaddr_in) = 16 bytes
sizeof(struct sockaddr_in6) = 28 bytes (IPv6 is bigger)
sin_family=2 sin_port=0x5000 (= 80 via ntohs)
the whole struct: 00 02 00 50 80 02 2a 34 00 00 00 00 00 00 00 00
Note the first two bytes read 00 02, not 02 00: macOS/BSD places a 1-byte sin_len before a 1-byte sin_family, while Linux has no sin_len and a 2-byte family field. Both structs are 16 bytes and both work through the API — a good argument for never hand-assembling these bytes and letting getaddrinfo do it.
7. DNS and getaddrinfo
People use names, not numbers. The Domain Name System (DNS) is a worldwide, hierarchical, distributed database mapping domain names to addresses (and back). The hierarchy follows the dots, read right to left: a root server knows the .edu servers, which know cmu.edu’s servers, which know www.cmu.edu. Results are cached everywhere, which is why lookups are usually instant and why changes take time to propagate. One name may map to many addresses (for load balancing or because the host has both IPv4 and IPv6), and many names may map to one address.
Modern code performs name resolution with getaddrinfo, which handles DNS, IPv4-vs-IPv6, ports and byte order in one call, returning a linked list of ready-to-use sockaddrs. (It replaces the old gethostbyname, which was IPv4-only and not thread-safe.) getnameinfo goes the other way, address → printable string.
== 4. getaddrinfo("localhost", "80") ==
[0] family=IPv6 addr=::1 port=80
[1] family=IPv4 addr=127.0.0.1 port=80
Two observations that matter for Lecture 20:
- The result is a list, and the first entry is not always the usable one — here
localhostyields IPv6::1before IPv4127.0.0.1. A correct client tries each address in turn until one connects; one that grabbedres->ai_addrblindly would fail on a machine with no IPv6 route. - You pass the service as a string (
"80"or"http"), andgetaddrinfofills in the port in network order for you.
A real lookup behaves the same way: run the demo with a hostname and www.cmu.edu resolves to 128.2.42.52 — one IPv4 address, the same one CS:APP uses. (make run deliberately resolves only localhost so its output does not depend on the network or on DNS caching.)
7.1 The client/server model
Almost everything on a network is organized as client/server, and the asymmetry is worth stating precisely: a server manages a resource and waits passively to be contacted; a client initiates contact to request service. “Client” and “server” name roles in a transaction, not machines — one program can be both (a web proxy is a server to the browser and a client to the origin server). A transaction is four steps: the client sends a request, the server processes it, the server sends a response, the client processes it.
The endpoint abstraction that makes this programmable is the socket: to your code, a socket is a descriptor (Lecture 18) that happens to be connected to a process on another machine. Once connected, you read and write it exactly like a file — which is why Lecture 18’s RIO package works unchanged on sockets, and why “everything is a file” earns its keep. Lecture 20 builds the connections themselves.
Summary
- A disk is a flat array of blocks; a file system is the convention layered on it: superblock (magic + geometry), inode table, free bitmap, data blocks.
- An inode holds a file’s type, size and block pointers — but not its name. Names live in directories, which are ordinary files of (name → inode) records. Hence hard links, cheap renames, and permissions on the file rather than the name.
- Path lookup walks the path component by component, reading a directory at each level: measured at 9 block reads for a three-component path vs 3 for one component. That cost is why kernels cache lookups and why a descriptor (the cached result) exists.
- Direct pointers alone cap file size (512 B in the toy); real inodes add single/double/triple indirect blocks (or extents) so small files stay cheap and huge files are describable. Blocks and inodes run out independently — the demo exhausted inodes with half the blocks free.
- The Internet is a hierarchy of networks unified by IP: best-effort packet delivery plus a 32-bit (IPv4) or 128-bit (IPv6) address scheme. TCP adds a reliable ordered byte stream; an endpoint is an address + port.
- Multi-byte network fields use big-endian network byte order (
htons/htonl); dotted decimal is a rendering of raw bytes (inet_pton/inet_ntop).getaddrinfoturns a name and service into a list of readysockaddrs — and a correct client tries each of them.
Common pitfalls
- Thinking a file “contains” its name. The name is in the parent directory; the inode is the file. This is the key to hard links and to
unlinksemantics. - Assuming path lookup is free. Each component costs block reads; it is cached, not cheap.
- Expecting more pointers to scale. File size needs indirection, not a bigger inode.
- Assuming “disk full” means blocks. It can be inodes; millions of tiny files exhaust them with space to spare.
- Forgetting
htons/htonl. A port used without conversion silently becomes a different port. - Hand-building
sockaddrbytes. The layout differs across platforms (BSD’ssin_len); letgetaddrinfobuild it. - Using only the first
getaddrinforesult. Walk the list — the first may be an IPv6 address you cannot reach. - Using
gethostbyname. Obsolete, IPv4-only and not thread-safe; usegetaddrinfo. - Forgetting
freeaddrinfo. The list is heap-allocated (Lecture 13’s leak, in a networking costume).
Exercises
-
Where is the name? You run
ln original.txt second.txt(a hard link), thenrm original.txt. Can you still read the data throughsecond.txt? Why?Answer
Yes. Both names were directory entries pointing at the **same inode**; the data belongs to the inode. `rm` removed one directory entry and decremented the link count from 2 to 1. The file's blocks are freed only when the count reaches 0 (and no process still has it open). -
Count the reads. In the toy file system, roughly how many block reads does looking up
/a/b/c/d.txttake compared with/d.txt, and why?Answer
Four components instead of one, and each level needs an inode read plus a read of that directory's data — so roughly four times the work (the demo measured 9 reads for three components vs 3 for one). Each additional path component adds a directory read, which is why lookups are cached. -
File-size ceiling. A file system has 4 KB blocks and inodes with 12 direct pointers plus one single-indirect pointer; block numbers are 4 bytes. What is the largest file?
Answer
Direct: 12 × 4 KB = 48 KB. A single-indirect block holds 4096/4 = **1024** block numbers → 1024 × 4 KB = 4 MB. Total ≈ **4 MB + 48 KB**. Adding a double-indirect pointer would add 1024 × 1024 × 4 KB = 4 GB. -
Disk full, space available.
dfsays a volume is full, butdf -hshows 40 GB free. What happened, and what does the toy demo show?Answer
The **inodes** are exhausted, not the data blocks — typically from a huge number of tiny files. The inode table is sized when the file system is created and cannot grow. The demo hit this exactly: "no free inodes" with 32 of 64 blocks still free. -
Byte order. A program sets
sa.sin_port = 8080;instead ofhtons(8080). Which port does it actually use on a little-endian machine, and why?Answer
8080 is `0x1F90`. Stored little-endian it is the bytes `90 1F`, which the network interprets big-endian as `0x901F` = **36895**. So the program connects to or binds port 36895. The fix is `htons`. -
Why a list?
getaddrinfo("localhost", "80", …)returns::1then127.0.0.1. Write the connection strategy a correct client must use.Answer
Iterate the list: for each entry, create a socket of that entry's family/type/protocol and try to `connect`; on failure close the socket and try the next; declare failure only after the list is exhausted. Using only the first entry would fail on a host without IPv6 connectivity — which is why Lecture 20's client loops.
The related lab
Lab 8 (sfslab) has you implement a simple file system in C against the lab’s own interface — inodes, directories, allocation and path lookup are exactly its subject matter. Per the course’s academic-integrity policy these notes contain no lab solutions. tinyfs.py is deliberately a different design in a different language with no lab interface (1-byte block pointers, 16-byte inodes, a 4 KB array “disk”), built so the structures can be hexdumped in a lecture — the same policy as cachesim.py (L10) and heap.py (L13). The networking half of this lecture leads to the proxy lab, whose code appears in neither lecture.
Further reading
- CS:APP3e §11.1–§11.4 (the client/server model, networks, the global IP Internet, the sockets interface preview) and practice problems 11.1–11.4.
man 3 getaddrinfo,man 3 inet_ntop,man 7 ip— the authoritative address APIs; thegetaddrinfopage’s example client is the canonical “walk the list” loop.- CS:APP3e chapter 10 revisited for
stat, and any OS text’s file-system chapter (e.g. Operating Systems: Three Easy Pieces, chapters 39–42) for inodes, journaling and crash consistency.
Preview of Lecture 20: Network programming II
With names resolved and addresses in hand, Lecture 20 makes the connection: the full sockets interface — socket, bind, listen, accept on the server and socket, connect on the client — the difference between a listening and a connected descriptor, and a working echo server and client built on Lecture 18’s RIO package. Then the Web: what an HTTP request and response actually look like on the wire, static vs dynamic content, and what a proxy sits between.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| file system | 文件系统 |
| block / block size | 块 / 块大小 |
| superblock | 超级块 |
| magic number | magic 数(标识字) |
| inode (index node) | 索引节点 |
| inode table | 索引节点表 |
| free (block) bitmap | 空闲块位图 |
| data block | 数据块 |
| direct / indirect block pointer | 直接 / 间接块指针 |
| single / double / triple indirect | 一级 / 二级 / 三级间接 |
| extent | 区段(连续块) |
| directory | 目录 |
| directory entry (dirent) | 目录项 |
| path / path component | 路径 / 路径分量 |
| path lookup / resolution | 路径查找 / 解析 |
| hard link / link count | 硬链接 / 链接计数 |
unlink | 删除名字(解除链接) |
ENOENT / ENOTDIR / ENOSPC | 无此文件 / 非目录 / 空间不足 |
| dentry cache | 目录项缓存 |
| journaling / crash consistency | 日志 / 崩溃一致性 |
| network | 网络 |
| LAN / router | 局域网 / 路由器 |
| protocol | 协议 |
| packet / header / payload | 分组 / 首部 / 负载 |
| IP (Internet Protocol) | 网际协议 |
| best-effort delivery | 尽力而为交付 |
| TCP / UDP | 传输控制协议 / 用户数据报协议 |
| byte stream | 字节流 |
| IP address (IPv4 / IPv6) | IP 地址 |
| dotted-decimal notation | 点分十进制 |
| loopback | 回环地址 |
| port / well-known port | 端口 / 知名端口 |
| host byte order / network byte order | 主机字节序 / 网络字节序 |
htons / htonl / ntohs / ntohl | 字节序转换函数 |
inet_pton / inet_ntop | 地址字符串与二进制互转 |
struct sockaddr_in | 套接字地址结构 |
| DNS (Domain Name System) | 域名系统 |
| domain name | 域名 |
getaddrinfo / getnameinfo | 地址解析 / 反向解析 |
| client / server model | 客户端 / 服务器模型 |
| socket | 套接字 |
| connection / four-tuple | 连接 / 四元组 |