本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 3 · 本科三年级
12Storage Devices and File Systems
Memory forgets everything when the power goes; files must not. This chapter goes down to the devices that keep them, a disk whose head must travel and wait for the platter, a flash chip that cannot overwrite a page in place, and back up to the structures a file system builds on them: a superblock, bitmaps, inodes, blocks reached directly or through blocks of pointers, directories that are themselves files. A complete small file system, minifs, is written in C over an image file; then the machine is stopped in the middle of an update, at every possible moment, to see what a crash breaks and how a journal repairs it. Two last ideas make storage fast and safe at scale: writing everything as a log, and spreading data over several disks so that one can fail.
You already know
In the Year 2 volume a process reaches a file through a file descriptor, a small number the kernel gives it when it opens the file. The file itself is described by an inode, which holds its size, its owner, its permissions and where its data lie, but not its name: a name is an entry in a directory, a link to an inode, and an inode can have several. Earlier volumes described the hard disk and the SSD as the computer’s lasting memory, and the exclusive or (XOR) of two bits as 1 when they differ.
12.1 Disks and flash
A hard disk stores bits as magnetised spots on spinning platters, read and written by a head at the end of an arm that moves across them.
Definition 12.1 (Disk block, sector, seek time, rotational latency)
A sector is the smallest unit a disk reads or writes. A disk block is the unit a file system allocates and transfers, a fixed number of consecutive sectors. The seek time of an access is the time the arm takes to bring the head over the right track; the rotational latency is the time the platter then takes to bring the first sector under the head.
The time of one access is the seek, plus the rotational latency, plus the transfer:
where on average the platter must turn half a revolution. For a hypothetical disk spinning at 7,200 revolutions per minute with an average seek of 9 ms, the rotational latency alone is 4.2 ms, and a read of 4 KiB at 150 MB/s takes 0.03 ms to transfer: almost all of the 13 ms goes to moving the mechanics, nothing to the data. A disk therefore reads large runs of consecutive blocks far faster than scattered ones, and the order in which it serves the requests waiting for it matters.
Definition 12.2 (Disk scheduling, SCAN)
Disk scheduling chooses the order in which a disk serves the requests in its queue. Shortest seek time first serves the request nearest to the head. The SCAN algorithm, or elevator, moves the head in one direction to the last cylinder, serving every request on the way, then turns back and does the same in the other direction.
def fcfs(head, queue):
return list(queue)
def sstf(head, queue): # shortest seek time first: always the nearest request
left, order = list(queue), []
while left:
head = min(left, key=lambda c: abs(c - head))
left.remove(head)
order.append(head)
return order
def scan(head, queue, up=True): # the elevator: sweep to the end, then turn back
above = sorted(c for c in queue if c >= head)
below = sorted((c for c in queue if c < head), reverse=True)
return above + below if up else below + above
def travel(head, order, policy):
if policy is scan and order and min(order) < head: # up to the last cylinder first
return (CYLINDERS - 1 - head) + (CYLINDERS - 1 - min(order))
return sum(abs(b - a) for a, b in zip([head] + order, order))
if __name__ == "__main__":
rng = random.Random(12)
queue = [rng.randrange(CYLINDERS) for _ in range(10)]
head = 100
print(f"head at {head}, moving up; queue {queue}")
for name, policy in (("FCFS", fcfs), ("SSTF", sstf), ("SCAN", scan)):
order = policy(head, queue)
moves = travel(head, order, policy)
print(f"{name}: {' '.join(map(str, order))} travel {moves}")
$ python disk_sched.py
head at 100, moving up; queue [121, 68, 168, 135, 170, 89, 36, 97, 2, 95]
FCFS: 121 68 168 135 170 89 36 97 2 95 travel 625
SSTF: 97 95 89 68 36 2 121 135 168 170 travel 266
SCAN: 121 135 168 170 97 95 89 68 36 2 travel 296
Shortest seek time first travels least here, but it serves the requests near the head first, and a request far away can wait for ever while new ones keep arriving near the head; SCAN travels a little more and bounds every wait (exercise 12.11). A disk’s own controller can reorder the requests it holds too, since it knows where the platter is.
Flash memory has no moving parts and no seek, but a constraint of its own. It is written by pages of a few kilobytes, and a page can be written only once: to write it again, the whole erase block that contains it, many pages, must first be erased.
Definition 12.3 (Erase block, flash translation layer, wear levelling, write amplification)
An erase block is the smallest unit of flash that can be erased. The flash translation layer (FTL) is the controller’s software that maps the logical pages the computer writes to physical pages: an overwrite goes to a fresh page and the old copy becomes garbage, and cleaning erases a block after copying out its pages still valid. Wear levelling spreads the erasures over all blocks, since each block survives a limited number of them. Write amplification is the ratio of the pages written to the flash to the pages the computer asked to write.
def simulate(u, writes=60_000, seed=1):
rng = random.Random(seed)
logical = int(u * BLOCKS * PAGES)
where = {} # logical page -> (block, page)
valid = [set() for _ in range(BLOCKS)] # the logical pages each block holds
free = list(range(1, BLOCKS)) # erased blocks; block 0 is being filled
current, used = 0, 0
flash_writes, victims = 0, []
def program(lp): # write a logical page at the next free page
nonlocal current, used
if used == PAGES:
current, used = free.pop(0), 0
if lp in where:
valid[where[lp][0]].discard(lp) # the old copy becomes garbage
where[lp] = (current, used)
valid[current].add(lp)
used += 1
start = logical + writes // 3 # measure the last two thirds: the steady state
for k in range(logical + writes):
lp = k if k < logical else rng.randrange(logical) # fill, then overwrite
if k == start:
flash_writes, victims = 0, []
while not free: # clean: erase the block with the fewest valid pages
victim = min((b for b in range(BLOCKS) if b != current),
key=lambda b: len(valid[b]))
victims.append(len(valid[victim]) / PAGES)
free.append(victim)
for page in list(valid[victim]): # copy its valid pages out first
program(page)
flash_writes += 1
program(lp)
flash_writes += 1
return flash_writes / (logical + writes - start), sum(victims) / len(victims)
$ python ftl.py
64 blocks of 64 pages; the last 40,000 of 60,000 overwrites
u amplification victim valid 1/(1 - victim) 1/(1 - u)
0.50 1.26 0.21 1.26 2.00
0.55 1.36 0.26 1.36 2.22
0.60 1.50 0.33 1.50 2.50
0.65 1.67 0.40 1.67 2.86
0.70 1.92 0.48 1.92 3.33
0.75 2.26 0.56 2.26 4.00
0.80 2.79 0.64 2.79 5.00
0.85 3.70 0.73 3.70 6.67
0.90 5.61 0.82 5.61 10.00
Cleaning a block whose fraction of pages is valid copies pages to free for new data: each page the computer writes costs pages of flash, which is the measured amplification to two decimals. Greedy cleaning chooses blocks emptier than the average, so the amplification stays far below ; but it still grows without bound as the flash fills. In the model, two remedies lower : keeping part of the flash hidden from the computer, and telling the drive which pages a deleted file no longer uses.
12.2 The layout of a file system
A file system turns a device, an array of blocks, into a tree of named files. Every Unix-like file system rests on the same few structures.
Definition 12.4 (Superblock, block bitmap, inode table, direct and indirect blocks, directory entry)
The superblock describes the file system: its size and where its other structures lie. The block bitmap has one bit per block, set when the block is in use, and an inode bitmap does the same for inodes. The inode table holds the inodes, at fixed places, so that an inode number gives its position. An inode’s direct blocks are the blocks whose numbers it holds itself; an indirect block is a block that holds block numbers, reached from the inode. A directory entry pairs a name with an inode number; a directory is a file whose data are its entries.
minifs keeps 1,024 blocks of 1 KiB in an image file (Listing 12.3): a superblock, the two bitmaps, eight blocks of inodes, a journal of 32 blocks for later, and the data. Its inode holds ten direct block numbers and one indirect block of 256 numbers.
#define NAMELEN 28
#define ROOT 1 /* inode 0 is never used */
enum { SUPER = 0, IBITMAP = 1, BBITMAP = 2, ITABLE = 3, ITABLE_BLOCKS = 8,
JOURNAL = 11, JOURNAL_BLOCKS = 32, DATA = 43 };
enum { T_FREE, T_FILE, T_DIR };
struct inode { /* 64 bytes: 16 per block */
uint16_t type, nlink;
uint32_t size;
uint32_t direct[NDIRECT];
uint32_t indirect, dindirect; /* dindirect: exercise 6 */
uint32_t unused[2];
};
minifs image, by block number, from the first lines of Output 12.3 (not to scale). Block 1 is the inode bitmap, block 2 the block bitmap.To find the -th block of a file, bmap looks in the inode for , and otherwise in the indirect block; when asked to, it allocates the block, and the indirect block itself, on the way (Listing 12.4). Writing bytes is then a loop over blocks: find or allocate the block, read it if it is only partly overwritten, change it, write it; and at the end write the inode, with its new size and pointers (Listing 12.5).
static uint32_t bmap(struct inode *in, uint32_t k, int *fresh) /* fresh: allocate */
{
if (k < NDIRECT) {
if (!in->direct[k] && fresh) *fresh = 1, in->direct[k] = new_block(0);
return in->direct[k];
}
k -= NDIRECT;
if (k < NPTRS) {
if (!in->indirect && !fresh) return 0;
if (!in->indirect && !(in->indirect = new_block(1))) return 0;
uint32_t p[NPTRS];
get(in->indirect, p);
if (!p[k] && fresh && (p[k] = new_block(0))) *fresh = 1, put(in->indirect, p);
return p[k];
}
#ifdef DOUBLE_INDIRECT
return bmap_double(in, k - NPTRS, fresh);
#else
return 0; /* beyond the largest file */
#endif
}
*fresh. code/bachelor-3/12-file-systems/listings/minifs.cminifs inode, with the block numbers of big.dat in Output 12.3, whose indirect block is 57. Small files need only the inode; a larger file costs one more block, of pointers, and one more read for each of its blocks beyond the tenth. ext2’s inode has 12 direct pointers and one single, one double and one triple indirect pointer, each level a tree one deeper. /* ---- reading and writing bytes ---- */
static long iwrite(int ino, struct inode *in, uint32_t off, const uint8_t *buf, uint32_t n)
{
uint8_t b[BSIZE];
uint32_t done = 0;
while (done < n) {
uint32_t at = (off + done) % BSIZE, len = BSIZE - at;
if (len > n - done) len = n - done;
int fresh = 0;
uint32_t blk = bmap(in, (off + done) / BSIZE, &fresh);
if (!blk) break; /* disk full, or file too large */
if (fresh) memset(b, 0, BSIZE); else get(blk, b);
memcpy(b + at, buf + done, len);
put(blk, b); /* the data block */
done += len;
}
if (off + done > in->size) in->size = off + done;
iput(ino, in); /* then the inode: size, pointers */
return done;
}
long fs_write(int ino, uint32_t off, const void *buf, uint32_t n)
{
tx_begin();
struct inode in = iget(ino);
long done = iwrite(ino, &in, off, buf, n);
tx_commit();
return done;
}
fs_write wraps it in a transaction, which does nothing until the journal is on. code/bachelor-3/12-file-systems/listings/minifs.cA directory is a file of 32-byte entries, read and written by the same functions. Creating a file allocates an inode in the inode bitmap, writes the inode, and appends an entry to the directory (Listing 12.6).
int fs_create(int dir, const char *name, int type)
{
if (fs_lookup(dir, name)) return 0;
tx_begin();
int ino = alloc_bit(IBITMAP, ROOT + 1, NINODES); /* 1. the inode bitmap */
if (!ino) return 0;
struct inode in = {.type = type, .nlink = 1};
iput(ino, &in); /* 2. the inode */
struct dirent e = {.ino = ino};
strncpy(e.name, name, NAMELEN - 1);
struct inode d = iget(dir);
iwrite(dir, &d, d.size, (uint8_t *)&e, sizeof e); /* 3. the entry, 4. the size */
tx_commit();
return ino;
}
int main(void)
{
mkfs("demo.img");
printf("demo.img: %d blocks of %d bytes\n", NBLOCKS, BSIZE);
printf(" block 0 superblock, %d inode bitmap, %d block bitmap,\n", IBITMAP, BBITMAP);
printf(" %d-%d inode table (%d inodes), %d-%d journal, %d-%d data\n", ITABLE,
ITABLE + ITABLE_BLOCKS - 1, NINODES, JOURNAL, JOURNAL + JOURNAL_BLOCKS - 1,
DATA, NBLOCKS - 1);
fs_mount("demo.img");
const char *text = "Opening hours: 8:45 to 18:00.\n";
int notes = fs_create(ROOT, "notes.txt", T_FILE);
fs_write(notes, 0, text, strlen(text));
int src = fs_create(ROOT, "src", T_DIR);
int main_c = fs_create(src, "main.c", T_FILE);
fs_write(main_c, 0, "int main(void) { return 0; }\n", 29);
static char big[12 * 1024]; /* 12 KiB: past the 10 direct blocks */
memset(big, 'x', sizeof big);
fs_write(fs_create(ROOT, "big.dat", T_FILE), 0, big, sizeof big);
fs_ls(ROOT, "/");
fs_ls(src, "/src/");
char back[64] = {0};
fs_read(fs_lookup(ROOT, "notes.txt"), 0, back, sizeof back - 1);
printf("notes.txt: %s", back);
fs_unmount();
return 0;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o fs_demo fs_demo.c minifs.c -lm && ./fs_demo
demo.img: 1024 blocks of 1024 bytes
block 0 superblock, 1 inode bitmap, 2 block bitmap,
3-10 inode table (128 inodes), 11-42 journal, 43-1023 data
/notes.txt inode 2 file 30 bytes blocks 44
/src inode 3 dir 32 bytes blocks 45
/big.dat inode 5 file 12288 bytes blocks 47 48 49 50 51 52 53 54 55 56 | indirect 57: 58 59
/src/main.c inode 4 file 29 bytes blocks 46
notes.txt: Opening hours: 8:45 to 18:00.
Block 43, the first data block, is the root directory’s; each file then takes the lowest free blocks. The 12 KiB file fills its ten direct blocks, and its last two blocks go behind the indirect block, 57.
12.3 Crash consistency
Creating a file and writing 1,500 bytes into it makes nine block writes in minifs: the inode bitmap, the inode, the directory’s data and the directory’s inode, then for each of two data blocks the block bitmap and the block, and the file’s inode. A disk writes one block at a time. If the power fails between two of those writes, the disk holds a state that no correct sequence of operations could have produced.
Definition 12.5 (Crash consistency, journaling, idempotent replay)
A file system has crash consistency when, whatever the moment the machine stops, the disk afterwards holds a consistent state: every block in use is marked in the bitmap and belongs to one file, every allocated inode is in a directory. Journaling achieves it by writing the blocks an operation will change first to a journal, then a commit record, and only then the blocks in place; after a crash, the committed operations are copied again from the journal. That replay is idempotent: replaying once or several times leaves the same state.
A checker in the style of Unix’s fsck finds the damage: it walks the directory tree from the root, marking every inode and block it reaches, and compares with the bitmaps (Listing 12.8). Listing 12.9 stops the machine after each possible number of writes, reboots, and checks.
int fs_check(int verbose)
{
memset(used_block, 0, sizeof used_block);
memset(used_inode, 0, sizeof used_inode);
problems = 0;
verbose_check = verbose;
walk(ROOT);
for (int i = ROOT + 1; i < NINODES; i++)
if (bit(IBITMAP, i) && !used_inode[i])
report(" inode %d allocated but in no directory\n", i);
else if (!bit(IBITMAP, i) && used_inode[i])
report(" inode %d in use but free in the bitmap\n", i);
for (int b = DATA; b < NBLOCKS; b++)
if (bit(BBITMAP, b) && !used_block[b])
report(" block %d allocated but used by no file (a leak)\n", b);
else if (!bit(BBITMAP, b) && used_block[b])
report(" block %d in use but free in the bitmap\n", b);
return problems;
}
int main(void)
{
journaling = WITH_JOURNAL;
setup();
printf("blocks written, %s journal:", journaling ? "with a" : "without");
show_writes = 1;
long n = operation();
show_writes = 0;
printf("\n");
for (long k = 1; k < n; k++) {
setup();
crash_at = k; /* stop after k writes */
operation();
crash_at = 0;
fs_mount("crash.img"); /* reboot: replays the journal */
int ino = fs_lookup(ROOT, "log.txt");
printf("crash after write %2ld:%s log.txt ", k, replayed ? " replayed," : "");
if (ino) printf("%u bytes, ", fs_stat(ino).size); else printf("absent, ");
int problems = fs_check(0);
printf(problems == 1 ? "1 problem:\n" : problems ? "%d problems:\n" : "consistent\n",
problems);
fs_check(1);
fs_unmount();
}
return 0;
}
crash_at makes every later write vanish. code/bachelor-3/12-file-systems/listings/crash.c$ gcc -std=c17 -O2 -Wall -Wextra -o crash crash.c minifs.c -lm && ./crash
blocks written, without journal: 1 3 43 3 2 45 2 46 3
crash after write 1: log.txt absent, 1 problem:
inode 3 allocated but in no directory
crash after write 2: log.txt absent, 1 problem:
inode 3 allocated but in no directory
crash after write 3: log.txt absent, 1 problem:
inode 3 allocated but in no directory
crash after write 4: log.txt 0 bytes, consistent
crash after write 5: log.txt 0 bytes, 1 problem:
block 45 allocated but used by no file (a leak)
crash after write 6: log.txt 0 bytes, 1 problem:
block 45 allocated but used by no file (a leak)
crash after write 7: log.txt 0 bytes, 2 problems:
block 45 allocated but used by no file (a leak)
block 46 allocated but used by no file (a leak)
crash after write 8: log.txt 0 bytes, 2 problems:
block 45 allocated but used by no file (a leak)
block 46 allocated but used by no file (a leak)
The damage is only of one kind, an inode or a block marked in use that nothing uses: a leak, which a checker can repair by clearing the bit. That is because minifs writes in a careful order: the bitmap before the block it allocates, the block before the pointer to it, the inode before the directory entry that names it. The opposite order would leave a pointer to a block still free in the bitmap, which the next allocation would hand to another file: two files sharing a block, the worst damage of all. Careful ordering limits the damage; it does not prevent it, a checker must still read the whole disk after a crash, and a file of 0 bytes, created but never written, can survive a crash in the middle of an operation that should have written it whole.
A journal makes each operation all or nothing. Listing 12.10 writes the operation’s blocks to the journal, then a descriptor that lists where each belongs and carries the commit mark, in a single block write; then the blocks in place; then it clears the descriptor.
static void tx_commit(void)
{
if (!in_tx) return;
uint32_t desc[NPTRS] = {0};
for (int i = 0; i < ntx; i++) { /* 1. log the new blocks */
disk_write(JOURNAL + 1 + i, tx[i].data);
desc[2 + i] = tx[i].block; /* and where each belongs */
}
desc[0] = COMMIT, desc[1] = ntx;
disk_write(JOURNAL, desc); /* 2. commit: one block write */
for (int i = 0; i < ntx; i++) /* 3. checkpoint: write in place */
disk_write(tx[i].block, tx[i].data);
memset(desc, 0, sizeof desc);
disk_write(JOURNAL, desc); /* 4. the journal is empty again */
in_tx = ntx = 0;
}
static void replay(void) /* at mount, after a crash */
{
uint32_t desc[NPTRS];
uint8_t data[BSIZE];
disk_read(JOURNAL, desc);
replayed = desc[0] == COMMIT;
if (!replayed) return; /* nothing committed: ignore */
for (uint32_t i = 0; i < desc[1]; i++) {
disk_read(JOURNAL + 1 + i, data);
disk_write(desc[2 + i], data);
}
memset(desc, 0, sizeof desc);
disk_write(JOURNAL, desc);
}
log.txt: three blocks logged, the commit, three blocks written in place, the journal cleared. A crash before the commit loses the operation whole; after it, the replay at the next mount writes the three blocks again, whether or not they had already reached their place./* journal.c -- the same crashes, with the journal on. */
// capture: scratch with=minifs.c
#define WITH_JOURNAL 1
#include "crash.c"
$ gcc -std=c17 -O2 -Wall -Wextra -o journal journal.c minifs.c -lm && ./journal
blocks written, with a journal: 12 13 14 11 1 3 43 11 12 13 14 15 11 2 45 46 3 11
crash after write 1: log.txt absent, consistent
crash after write 2: log.txt absent, consistent
crash after write 3: log.txt absent, consistent
crash after write 4: replayed, log.txt 0 bytes, consistent
crash after write 5: replayed, log.txt 0 bytes, consistent
crash after write 6: replayed, log.txt 0 bytes, consistent
crash after write 7: replayed, log.txt 0 bytes, consistent
crash after write 8: log.txt 0 bytes, consistent
crash after write 9: log.txt 0 bytes, consistent
crash after write 10: log.txt 0 bytes, consistent
crash after write 11: log.txt 0 bytes, consistent
crash after write 12: log.txt 0 bytes, consistent
crash after write 13: replayed, log.txt 1500 bytes, consistent
crash after write 14: replayed, log.txt 1500 bytes, consistent
crash after write 15: replayed, log.txt 1500 bytes, consistent
crash after write 16: replayed, log.txt 1500 bytes, consistent
crash after write 17: replayed, log.txt 1500 bytes, consistent
log.txt is absent, empty, or complete with its 1,500 bytes.Every block is written twice, which is the price. A file system can therefore journal only the metadata (bitmaps, inodes, directories) and write the data blocks in place; exercise 12.12 shows why that order matters.
12.4 Log-structured file systems
Definition 12.6 (Log-structured file system, segment cleaning)
A log-structured file system writes every change, data and metadata alike, at the end of a log, in large sequential segments, never in place; an inode map records where the latest copy of each inode is. Segment cleaning reclaims space: it reads a segment, writes its blocks that are still live at the end of the log, and frees the segment.
On a disk, writing whole segments turns every write into a sequential one, the fastest kind; and a crash can only cut the end of the log. The cost is cleaning, the same mechanism as an FTL’s, with the same algebra: cleaning segments that are a fraction live costs, per block of new data, the reading of the segment, the writing of its live blocks and the writing of the new block, blocks of disk traffic (exercise 12.10). Mendel Rosenblum and John Ousterhout published the design of such a file system in 1992. An FTL like Listing 12.2’s is itself log-structured, whatever file system runs above it.
12.5 Redundancy across disks
Definition 12.7 (RAID, striping, mirroring, parity block)
RAID (redundant array of independent disks) presents several disks as one. Striping spreads consecutive blocks over the disks, so that a large transfer uses all of them at once (RAID 0, no redundancy). Mirroring keeps a copy of every block on two disks (RAID 1). A parity block holds the XOR of the blocks of one stripe on the other disks, so that any one of them can be rebuilt as the XOR of the others (RAID 5, with the parity moving from disk to disk).
If , then , since : the lost block is the XOR of the survivors.
def xor(blocks):
out = bytearray(BLOCK)
for b in blocks:
for i, byte in enumerate(b):
out[i] ^= byte
return bytes(out)
def stripe(data): # -> disks[d] = list of blocks; the parity moves left each stripe
disks = [[] for _ in range(DISKS)]
blocks = [data[i:i + BLOCK] for i in range(0, len(data), BLOCK)]
for s in range(len(blocks) // (DISKS - 1)):
group = blocks[s * (DISKS - 1):(s + 1) * (DISKS - 1)]
p = DISKS - 1 - s % DISKS # the parity's disk in stripe s
row = group[:p] + [xor(group)] + group[p:]
for d in range(DISKS):
disks[d].append(row[d])
return disks
def read_back(disks):
out = b""
for s in range(len(disks[0])):
p = DISKS - 1 - s % DISKS
out += b"".join(disks[d][s] for d in range(DISKS) if d != p)
return out
$ python raid5.py
disk: 0 1 2 3 4
stripe 0: D0 D1 D2 D3 P
stripe 1: D4 D5 D6 P D7
stripe 2: D8 D9 P D10 D11
stripe 3: D12 P D13 D14 D15
stripe 4: P D16 D17 D18 D19
data 137b2a0ad83f7e38
rebuilt 137b2a0ad83f7e38 disk 2 identical: True
The parity moves so that no disk becomes the bottleneck: every small write must also update its stripe’s parity. RAID 6 adds a second, independent redundancy block per stripe, to survive two failures. How safe is RAID 5? Suppose each of disks fails at random, with a mean time to failure , and that a failed disk is replaced and rebuilt in a time much shorter than . A first failure comes after on average; data are lost only if one of the others fails during the hours of rebuilding, which happens with probability about . The mean time to data loss is about
the square of the disks’ lifetime: that is the gain of a single parity block. The model assumes independent failures; disks bought together, in the same box, fail together more often than it says. David Patterson, Garth Gibson and Randy Katz made the case for arrays of inexpensive disks in 1988.
History — Storage
Patterson, Gibson and Katz’s A case for redundant arrays of inexpensive disks appeared at SIGMOD in 1988, and Rosenblum and Ousterhout’s log-structured file system in the ACM Transactions on Computer Systems in February 1992.
12.6 Exercises
Exercise 12.1 ★
A hypothetical disk turns at 7,200 rpm, seeks in 9 ms on average and transfers 150 MB/s. How long does reading 4 KiB at a random place take? And 4 MiB?
Solution
Solution of Exercise 12.1.
Half a revolution takes s = 4.17 ms. 4 KiB transfer in s = 0.027 ms: in all ms, of which 0.2 % moves data. 4 MiB transfer in 28.0 ms: ms, 68 % of it moving data. Reading in large runs is what makes a disk efficient.
Exercise 12.2 ★
The head is at cylinder 50, moving up, on a disk of 200 cylinders; the queue holds 82, 17, 43, 140, 24, 16 and 190. Give SCAN’s order and the distance the head travels.
Solution
Solution of Exercise 12.2.
Up first: 82, 140, 190, then on to cylinder 199; back down: 43, 24, 17, 16. The head travels cylinders (test_exercise_2_scan_by_hand).
Exercise 12.3 ★
How many blocks, and of which kinds, does a file of 50 KiB use in minifs?
Solution
Solution of Exercise 12.3.
50 data blocks of 1 KiB: 10 through the direct pointers and 40 through the indirect block, which is a 51st block. The inode itself sits in the inode table, which is allocated once for all.
Exercise 12.4 ★
After Listing 12.7, the program unlinks notes.txt, then creates todo.txt and writes 3 bytes in it. Which inode and which block does todo.txt get, and where does it appear in the root’s listing?
Solution
Solution of Exercise 12.4.
unlink frees inode 2 and block 44, and both allocators take the lowest free number: todo.txt gets inode 2 and block 44 (minifs_test.c). Its entry is appended after big.dat, since fs_create always appends: the root lists src, big.dat, todo.txt, and the cleared entry at offset 0 stays unused.
Exercise 12.5 ★★
A first version of fs_unlink is below. After it removes a file of 3,000 bytes, the checker reports three problems. Which ones, and what is missing?
static int unlink_bug(int dir, const char *name)
{
struct dirent e;
for (uint32_t off = 0; fs_read(dir, off, &e, sizeof e) == sizeof e; off += sizeof e) {
if (!e.ino || strcmp(e.name, name) != 0) continue;
tx_begin();
struct inode in, d = iget(dir);
uint32_t ino = e.ino;
memset(&e, 0, sizeof e);
iwrite(dir, &d, off, (uint8_t *)&e, sizeof e);
memset(&in, 0, sizeof in);
iput(ino, &in);
set_bit(IBITMAP, ino, 0);
tx_commit();
return 0;
}
return -1;
}
unlink, as first written. code/bachelor-3/12-file-systems/exercises/ex5_unlink_bug.cSolution
Solution of Exercise 12.5.
The checker reports the file’s three data blocks, 44, 45 and 46 on a fresh image, as allocated but used by no file: the function clears the entry, the inode and its bit, but never frees the blocks, and with the inode zeroed nothing records them any more. The fix reads the inode first, struct inode in = iget(e.ino), and calls free_blocks(&in) before clearing it, as fs_unlink does (unlink_bug_test.c). Since the blocks are marked in use, nothing is corrupted: the space is lost until a checker returns it.
Exercise 12.6 ★★
Give minifs a double-indirect pointer, the field dindirect: write bmap_double(in, k, fresh), which bmap calls for the blocks beyond the indirect block’s when DOUBLE_INDIRECT is defined. How many reads does a byte at 290 KiB then cost?
Solution
Solution of Exercise 12.6.
exercises/ex6_double.c: the outer block, allocated zeroed when first needed, holds 256 numbers of indirect blocks; entry names the indirect block, allocated zeroed when first needed and written back into the outer block, and its entry names the data block. Every block allocated on the way is written back to the block that points to it. A byte at 290 KiB, file block 290, is in the double region: 4 reads, the inode, the outer block, the indirect block and the data (double_test.c writes and reads back 300 KiB).
Exercise 12.7 ★★
Prove that the replay of Listing 12.10 is idempotent, and that after a crash at any moment, followed by a replay (itself possibly interrupted by crashes), the disk holds either the state before the operation or the state after it.
Solution
Solution of Exercise 12.7.
Facts used: a block write is atomic; the journal’s blocks are never the home of a logged block; the descriptor carries the commit mark only between the commit write and the final clear.
Replay copies each logged block to its home , then clears the descriptor. Copying changes only home blocks, never the journal, so a second replay reads the same descriptor and the same logged blocks and writes the same contents to the same homes: the result is the same, and replay is idempotent. A replay cut by a crash leaves the descriptor committed (the clear comes last), so the next mount replays again; by idempotence, any number of interrupted replays followed by a complete one give the state of one replay.
Now a crash during an operation. Before the commit write, no home block has been written (in-place writes come after the commit) and the descriptor is not committed, so the mount replays nothing: the disk holds the state before the operation. From the commit write on, every home block holds either its old or its new contents, and the logged copies of all the new contents are on disk: the replay writes every home block’s new contents, giving the state after the operation. After the final clear, all homes hold their new contents already. In every case, before or after, never between.
Exercise 12.8 ★★
How many block reads does fs_read make to read one byte at offset of a minifs file, given its inode number? Check against Output 12.8.
Solution
Solution of Exercise 12.8.
fs_read reads the inode’s block of the inode table (1), then, for a file block below 10, the data block: 2 reads. For a block from 10 to 265 it also reads the indirect block: 3. A block never written, a hole, costs no data read. Output 12.8 shows 2, 2, 3, 3 and 3, and minifs_test.c checks 2 at offset 5,000 and 3 at 15,000.
Exercise 12.9 ★★
One stripe of a RAID 5 holds the data bytes 0x3C, 0xA5, 0x0F and 0x81. Compute the parity byte, then rebuild 0xA5 after its disk is lost.
Solution
Solution of Exercise 12.9.
, , : the parity is 0x17. Rebuild: (test_exercise_9_parity_by_hand).
Exercise 12.10 ★★★
A log-structured file system cleans segments whose fraction of blocks is live, reading each segment whole. Show that writing new data costs blocks of disk traffic per block of new data, and when . Why can it be worth cleaning segments that are not the emptiest?
Solution
Solution of Exercise 12.10.
Clean segments of blocks: read blocks, write back the live ones, and the blocks freed take new data, written once. Disk traffic: for blocks of new data, per block. When the segment need not be read at all, so the cost is 1, the write itself. The emptiest segments are not always the best: a segment of data that rarely changes (cold) stays nearly full for a long time, and its free space, waiting there, is lost for that whole time, whereas a segment of data that changes often (hot) empties itself if left alone. Cleaning cold segments at a higher utilisation, and letting hot ones empty, can lower the total cost; that was the cost-benefit policy of the 1992 design.
Exercise 12.11 ★★★
Show that shortest seek time first can make a request wait for ever, while SCAN serves every request within two sweeps of the disk; bound the head’s travel before a request on a disk of cylinders is served.
Solution
Solution of Exercise 12.11.
Shortest seek time first: put the head at 50 and a request at 190, then let a request at 50, 51 or 52 arrive before each decision. Each new request is nearer than 190, so 190 is never chosen, for as long as the stream lasts (test_exercise_11_sstf_starves, over 100 decisions).
SCAN: take a request at cylinder , arriving when the head is at . If the head is moving up and , it reaches in this sweep, after at most cylinders. Otherwise it goes on to the last cylinder and turns back; on the way down it passes , or, if is above where it turned, it reaches the end of that sweep and comes back up to . In every case the head reaches within one full sweep in each direction, at most cylinders of travel, and it serves the request when it passes. The time also depends on how many requests are served on the way, but none of them can push back: the head never turns before the end.
Exercise 12.12 ★★★
Metadata journaling logs only bitmaps, inodes and directories; the data blocks are written in place, outside the journal. Show the crash that metadata journaling allows if a new data block is written after the commit, and explain why writing data blocks in place before the commit, the ordered mode, prevents it.
Solution
Solution of Exercise 12.12.
A file grows by one block . Metadata journaling commits the bitmap with marked and the inode pointing to . If the data are written after the commit and the machine stops in between, the replay restores the bitmap and the inode, and the file now ends with block as it was, the contents of some file deleted earlier: garbage at best, someone else’s data at worst. In ordered mode, ’s data reach the disk before the commit. A crash before the commit loses the metadata: is still free in the bitmap, and its new contents are harmless and unreachable; a crash after the commit finds the data already there. Overwriting existing blocks in place stays unprotected in both modes: a crash may leave some of them new and some old.
12.7 Weekend problem
Problem 12.1
Weekend problem — How big can a file be?
The size of an inode’s pointers decides how large a file can grow and how many reads it costs to reach its last byte. This problem computes both for a classic inode, measures them on minifs, and compares with extents.
"""max_file.py -- the largest file an inode with 12 direct pointers and one single, one
double and one triple indirect pointer can describe, and the reads to reach each
part."""
def regions(block, pointer=4, direct=12):
n = block // pointer # block numbers per pointer block
sizes = [direct, n, n**2, n**3] # blocks reached through each kind of pointer
names = ["direct", "single indirect", "double indirect", "triple indirect"]
return list(zip(names, sizes, [2, 3, 4, 5])) # reads: inode, pointer blocks, data
def human(nbytes):
for unit in ("bytes", "KiB", "MiB", "GiB", "TiB"):
if nbytes < 1024:
return f"{nbytes:.1f} {unit}" if unit != "bytes" else f"{nbytes} bytes"
nbytes /= 1024
return f"{nbytes:.1f} PiB"
for block in (1024, 2048, 4096):
print(f"blocks of {block} bytes, 4-byte block numbers:")
total = 0
for name, blocks, reads in regions(block):
total += blocks * block
print(f" {name:<16} {blocks:>13,} blocks {human(blocks * block):>10}"
f" {reads} reads")
print(f" largest file: {total:,} bytes = {human(total)}")
$ python max_file.py
blocks of 1024 bytes, 4-byte block numbers:
direct 12 blocks 12.0 KiB 2 reads
single indirect 256 blocks 256.0 KiB 3 reads
double indirect 65,536 blocks 64.0 MiB 4 reads
triple indirect 16,777,216 blocks 16.0 GiB 5 reads
largest file: 17,247,252,480 bytes = 16.1 GiB
blocks of 2048 bytes, 4-byte block numbers:
direct 12 blocks 24.0 KiB 2 reads
single indirect 512 blocks 1.0 MiB 3 reads
double indirect 262,144 blocks 512.0 MiB 4 reads
triple indirect 134,217,728 blocks 256.0 GiB 5 reads
largest file: 275,415,851,008 bytes = 256.5 GiB
blocks of 4096 bytes, 4-byte block numbers:
direct 12 blocks 48.0 KiB 2 reads
single indirect 1,024 blocks 4.0 MiB 3 reads
double indirect 1,048,576 blocks 4.0 GiB 4 reads
triple indirect 1,073,741,824 blocks 4.0 TiB 5 reads
largest file: 4,402,345,721,856 bytes = 4.0 TiB
int main(void)
{
mkfs("reads.img");
fs_mount("reads.img");
int ino = fs_create(ROOT, "big", T_FILE);
char block[BSIZE] = {0};
long size = 0, n;
while ((n = fs_write(ino, size, block, BSIZE)) > 0) /* until the file is full */
size += n;
printf("largest file: %ld bytes = (%d direct + %d indirect) blocks of %d bytes\n",
size, NDIRECT, NPTRS, BSIZE);
long offsets[] = {0, 9 * 1024 + 1000, 10 * 1024, 100 * 1024, size - 1};
for (int i = 0; i < 5; i++) {
char c;
reads = 0;
fs_read(ino, offsets[i], &c, 1);
printf("byte %6ld (file block %3ld): %ld block reads\n", offsets[i],
offsets[i] / BSIZE, reads);
}
fs_unmount();
return 0;
}
minifs measured: fill a file until the pointers run out, then count the reads of one byte. code/bachelor-3/12-file-systems/listings/file_reads.c$ gcc -std=c17 -O2 -Wall -Wextra -o file_reads file_reads.c minifs.c -lm && ./file_reads
largest file: 272384 bytes = (10 direct + 256 indirect) blocks of 1024 bytes
byte 0 (file block 0): 2 block reads
byte 10216 (file block 9): 2 block reads
byte 10240 (file block 10): 3 block reads
byte 102400 (file block 100): 3 block reads
byte 272383 (file block 265): 3 block reads
minifs file, and the reads per byte.Part I — The classic inode.
- With blocks of 4 KiB and block numbers of 4 bytes, how many block numbers does a pointer block hold?
- How many bytes are reached through the 12 direct pointers, and through the single, double and triple indirect pointers?
- Give the largest file exactly, in bytes, and check it against Output 12.7.
- Which part of the file dominates, and why does that make the direct pointers almost irrelevant to the maximum?
- ext2 uses blocks of 1, 2 or 4 KiB, and its documentation gives file size limits of 16 GB, 256 GB and 2,048 GB for them. Which of these limits does the pointer tree explain?
- Suppose the inode also counts the file’s size in units of 512 bytes, in a 32-bit field. What limit results, and which block size does it constrain?
Part II — Reads per access.
- Without caching, how many block reads reach a byte in each region, and what is read each time?
- In which region is the byte at offset 1 GiB, and what does reading it cost?
- And the byte at offset 10 GiB?
- Reading a 4 GiB file from start to end, how many pointer blocks are read, and what fraction of all the reads is that?
- With every pointer block kept in memory, what does a read at a random offset cost?
- Why must the inode be read too, and where is it found from its number?
Part III — minifs measured.
- Predict
minifs’s largest file from its inode, and compare with Output 12.8. - Explain the 2 and 3 block reads.
- How many blocks of the disk does the largest file use, pointer block included?
- What does the
fs_writethat finally returns 0 do, and why does it leave the disk consistent? - With exercise 12.6, how large could a file be, and what limits it first on this image?
Part IV — Extents.
- An extent describes a run of consecutive blocks by its first block and its length. How many extents describe a 4 GiB file written in one run on an empty disk, and how many pointer bytes did the classic inode need for it?
- What is the worst case for extents, and how does it compare with pointers?
- With the extents sorted by file offset in the inode, how many reads reach any byte, and how is the extent found?
- Why do extents also help the disk, beyond saving space?
- For a file of 3 KiB, which representation is better, and does it matter?
- Sum up: how big can a file be with the classic inode and 4 KiB blocks, what does its last block cost to reach, and what do extents change?
Solution
Solution of Problem 12.1.
1. .
2. Direct: KiB = 48 KiB. Single indirect: blocks, 4 MiB. Double: blocks, 4 GiB. Triple: blocks, 4 TiB.
3. bytes, as printed: just over 4 TiB.
4. The triple indirect part, of the blocks, 99.9 %. Each level multiplies by 1,024; the 48 KiB of direct blocks change the maximum by about one part in a hundred million.
5. With 1 KiB blocks the tree reaches 16.1 GiB and with 2 KiB 256.5 GiB, in line with 16 GB and 256 GB. With 4 KiB the tree would allow 4 TiB, twice the documented 2,048 GB: something else limits it.
6. bytes = 2 TiB. It is above the tree’s limit for 1 and 2 KiB blocks, so it changes nothing there, and below it for 4 KiB blocks (and for 8 KiB, whose tree reaches 64 TiB): a field of that kind would explain the 2,048 GB of both.
7. Direct: 2, the inode and the data. Single: 3, adding the indirect block. Double: 4, the double block and then an indirect block. Triple: 5, the inode, three pointer blocks and the data.
8. 1 GiB is file block 262,144. Direct and single cover blocks 0 to 1,035, the double region blocks 1,036 to 1,049,611: double, 4 reads.
9. File block 2,621,440, beyond 1,049,611: triple, 5 reads.
10. 4 GiB is 1,048,576 blocks: 12 direct, 1,024 behind the single indirect block, and 1,047,540 in the double region, which need indirect blocks and the double block. With the single block, 1,025 pointer blocks: about 0.1 % of the reads.
11. One read, the data block, once the inode and the pointer blocks are in memory; this is why systems cache them.
12. The inode holds the pointers. Its number gives its place: block of the table in minifs, at offset , one read.
13. bytes, as measured.
14. The inode’s block, then the data block; from file block 10 on, the indirect block in between.
15. 266 data blocks and the indirect block: 267 blocks of the disk.
16. bmap for block 266 finds beyond the indirect block and returns 0 before allocating anything; the loop stops with nothing written, and the inode is written back unchanged. Nothing was allocated, so nothing leaks.
17. KiB, about 64.3 MiB; but the image has only 981 data blocks, so the disk fills first.
18. One extent, if the length field can count 1,048,576 blocks (a real format caps an extent’s length, and needs a few). The classic inode needed 1,025 pointer blocks, about 4 MiB.
19. A file whose blocks are all apart needs one extent per block, and an extent (start and length) is larger than a block number: worse than pointers, by the ratio of their sizes.
20. With the extents in the inode, read the inode, find the extent by binary search on the offsets, compute the block: 2 reads, whatever the offset.
21. Recording runs encourages the allocator to make runs; a file in long runs is read sequentially, without seeks.
22. Three blocks: three direct pointers or one or two extents, all inside the inode: two reads either way; it does not matter.
23. With 12 direct pointers, single, double and triple indirect blocks, 4 KiB blocks and 4-byte numbers, a file can reach KiB TiB, the triple region holding 99.9 % of it, and its last block costs 5 reads without caching: the inode, three pointer blocks, the data. ext2’s documented limits match the tree for 1 and 2 KiB blocks and are lower for 4 KiB. Extents describe a contiguous file in a few entries and reach any byte in two reads, but degrade to worse than pointers on a fragmented file.
本章定义的术语
- Crash consistency, journaling, idempotent replay
- Disk block, sector, seek time, rotational latency
- Disk scheduling, SCAN
- Erase block, flash translation layer, wear levelling, write amplification
- Log-structured file system, segment cleaning
- RAID, striping, mirroring, parity block
- Superblock, block bitmap, inode table, direct and indirect blocks, directory entry