xv6:File system
xv6:File system
本文逐段翻译 xv6 book rev5 的 Chapter 10,保留 file system 的层次结构、on-disk layout、buffer cache、logging、inode、directory、pathname、file descriptor、system calls、图件和 11 道练习。
TL;DR
- 目标:组织并存储 data,同时支持 users/applications 之间的 sharing,以及 reboot 之后仍然可用的 persistence。
- 核心挑战:on-disk data structures、crash recovery、并发访问和 disk 与 memory 之间的巨大速度差异。
- 七层结构:disk、buffer cache、logging、inode、directory、pathname、file descriptor;低层的 abstraction 为高层提供清晰边界。
- 关键机制:buffer cache 保证一个 disk block 只有一个 cached copy,并串行化访问;logging 让多个 block 的更新对 crash 呈现 atomic 性。
- 文件表示:inode 记录文件 metadata 和 data-block addresses;directory 是特殊 inode;pathname lookup 逐级解析 directory;file descriptor 统一 files、pipes、devices 等 Unix resources。
名词解释
| 名词 | 含义 | 本文对应物 |
|---|---|---|
| file system | 组织和持久化 data 的 OS subsystem | xv6 file system |
| buffer cache | disk blocks 的内存 cache 与访问同步层 | kernel/bio.c |
| transaction | 一组对 crash 呈现为 atomic 的 disk updates | begin_op / end_op |
| inode / i-number | 文件的 metadata/data-block 索引及其编号 | struct dinode / struct inode |
| directory entry | directory 中的 name 与 inode number 映射 | struct dirent |
| link count | 指向 inode 的 directory entries 数量 | nlink |
| absorption | 同一 transaction 中多次写同一 block 时复用 log slot | log_write |
| LRU | least recently used 的 buffer replacement policy | buffer cache 链表 |
目录
| 章节 | 说明 |
|---|---|
| Chapter 10:File system | file system 的目标与挑战 |
| 10.1 Overview | 七层结构与 disk layout |
| 10.2 Buffer cache layer | buffer cache 的两个职责 |
| 10.3 Code:Buffer cache | bget、bread、bwrite、brelse |
| 10.4 Logging layer | crash recovery 的基本思路 |
| 10.5 Log design | log header、group commit 与空间限制 |
| 10.6 Code:logging | transaction API 与 recovery |
| 10.7 Code:Block allocator | free bitmap 与 block 分配 |
| 10.8 Inode layer | on-disk/in-memory inode |
| 10.9 Code:Inodes | ialloc、iget、ilock、iput |
| 10.10 Code:Inode content | direct/indirect blocks 与 bmap |
| 10.11 Code:directory layer | dirlookup 与 dirlink |
| 10.12 Code:Path names | namei、nameiparent 与 pathname lookup |
| 10.13 File descriptor layer | open files 与 Unix uniformity |
| 10.14 Code:System calls | link、create、open、pipe |
| 10.15 Real world | xv6 与现代 file systems 的差异 |
| 10.16 Exercises | 原文 11 道练习 |
Chapter 10:File system
File system 的用途是组织和存储 data。File systems 通常支持 users 与 applications 之间共享 data,也支持 persistence,使 data 在 reboot 之后仍然可用。
xv6 file system 提供 Unix-like files、directories 和 pathnames(见 Chapter 1),并把 data 持久化存储在 virtio disk 上。File system 需要面对以下 challenges:
- file system 需要 on-disk data structures 来表示 named directories 和 files 的 tree,记录保存每个 file content 的 blocks 的 identities,并记录 disk 的哪些区域是 free 的。
- file system 必须支持 crash recovery。也就是说,如果发生 crash(例如 power failure),file system 在 restart 后仍应正确工作。风险在于,crash 可能中断一串 updates,只完成其中一部分,从而留下不一致的 on-disk data structures(例如某个 block 同时被 file 使用、又被标记为 free)。
- 不同 processes 可能同时操作 file system,因此 file-system code 必须协调这些操作,以维护 invariants。
- 访问 disk 比访问 memory 慢多个数量级,因此 file system 必须在 memory 中 cache popular blocks。
本章余下部分将解释 xv6 如何应对这些 challenges。
10.1 Overview
xv6 file system implementation 组织为七个 layers,如 Figure 10.1 所示。Disk layer 从 virtio hard drive 读取和写入 blocks。Buffer cache layer cache disk blocks 并同步对它们的访问,确保同一时刻最多只有一个 kernel process 能修改某个 block 中存储的 data。Logging layer 允许 higher layers 把对多个 blocks 的 updates 包装进一个 transaction,并保证这些 blocks 在 crash 面前以 atomic 方式更新(要么全部更新,要么一个都不更新)。Inode layer 提供 individual files;每个 file 都由一个 inode 表示,并有若干 blocks 保存它的 data。
Directory layer 把每个 directory 实现为一种特殊的 inode;其 content 是一串 directory entries,每个 entry 包含 file name 和 i-number。Pathname layer 提供 /usr/rtm/xv6/fs.c 这样的 hierarchical pathnames,并通过 recursive lookup 解析它们。File descriptor layer 使用 file-system interface 抽象多种 Unix resources(例如 pipes、devices、files 等),简化 application programmers 的工作。
Disk hardware 传统上把 disk 呈现为带编号的 512-byte blocks 序列(也称为 sectors):sector 0 是前 512 bytes,sector 1 是接下来的 512 bytes,以此类推。Operating system 为 file system 使用的 block size 可能与 disk 使用的 sector size 不同,但通常 block size 是 sector size 的 multiple。Xv6 把读入 memory 的 blocks 保存在 struct buf (3900) 类型的 objects 中。这个 structure 中保存的 data 有时与 disk 不同步:它可能还没有从 disk 读入(disk 正在处理,但还没有返回 sector content),或者 software 已经更新了它,但还没有写回 disk。
File system 必须规划在 disk 上存储 inodes 和 content blocks 的位置。因此 xv6 把 disk 划分为若干 sections,如 Figure 10.2 所示。File system 不使用 block 0(它保存 boot sector)。Block 1 称为 superblock,包含 file system 的 metadata(file system 的 block 数量、data block 数量、inode 数量以及 log 中 block 的数量)。从 block 2 开始是 log。Log 之后是 inodes,每个 block 中保存多个 inodes。再之后是 bitmap blocks,用于追踪哪些 data blocks 正在使用。剩余 blocks 是 data blocks;每个 block 要么在 bitmap block 中被标记为 free,要么保存 file 或 directory 的 content。Superblock 由名为 mkfs 的独立 program 填充;mkfs 构建初始 file system。
本章其余部分将从 buffer cache 开始,依次讨论每个 layer。请留意:低层精心选择的 abstractions 如何减轻 higher layers 的设计工作。
10.2 Buffer cache layer
Buffer cache 有两个职责:
- 同步对 disk blocks 的访问,确保 memory 中只有一个 block copy,并且同一时刻只有一个 kernel thread 使用这个 copy。
- Cache popular blocks,使它们不必再次从 slow disk 读取。
相关 code 位于 bio.c。
Buffer cache 对外提供的主要 interface 是 bread 和 bwrite。前者获得一个 buf,其中包含 block 的 copy;caller 可以在 memory 中读取或修改该 copy。后者把修改过的 buffer 写入 disk 上对应的 block。Kernel thread 使用完 buffer 后必须调用 brelse 释放它。Buffer cache 为每个 buffer 使用一个 sleep-lock,确保同一时刻只有一个 thread 使用每个 buffer(从而也只有一个 thread 使用对应的 disk block);bread 返回 locked buffer,而 brelse 释放该 lock。
Buffer cache 拥有固定数量的 buffers 来保存 disk blocks。这意味着,如果 file system 请求的 block 尚未在 cache 中,buffer cache 必须 recycle 当前保存其他 block 的某个 buffer。Buffer cache 为新 block recycle least recently used buffer,依据是:最近最少使用的 buffer 最不可能很快再次被使用。
10.3 Code:Buffer cache
Buffer cache 是一个 doubly-linked list of buffers。binit 由 main (1176) 调用,它使用 static array buf (4292–4301) 中的 NBUF 个 buffers 初始化该 list。之后对 buffer cache 的所有访问都通过 bcache.head 引导的 linked list,而不是直接访问 buf array。
一个 buffer 有两个与 state 相关的 fields。valid 表示 buffer 是否包含该 block 的 copy。disk 表示 buffer content 是否已经交给 disk;disk 可能会修改 buffer(例如把 data 从 disk 写入 data)。
bread (4352) 调用 bget,为给定 sector 获得 buffer (4356)。如果 buffer 需要从 disk 读取,bread 会先调用 virtio_disk_rw 完成读取,然后再返回 buffer。
bget (4308) 扫描 buffer list,查找 device number 和 sector number 都匹配的 buffer (4314–4322)。如果找到这样的 buffer,bget 获取该 buffer 的 sleep-lock,然后返回 locked buffer。
如果给定 sector 没有 cached buffer,bget 必须创建一个,可能需要复用曾经保存另一个 sector 的 buffer。它再次扫描 buffer list,寻找没有被使用的 buffer(b->refcnt = 0);任何这样的 buffer 都可以使用。bget 修改 buffer metadata,记录新的 device 和 sector number,并获取其 sleep-lock。注意,赋值 b->valid = 0 确保 bread 会从 disk 读取 block data,而不会错误地使用 buffer 之前的 content。
Memory 中每个 disk sector 至多只能有一个 cached buffer,这一点非常重要:这样 readers 才能看到 writes,并且 file system 才能使用 buffer locks 做 synchronization。bget 从第一次检查 block 是否 cached 开始,到通过设置 dev、blockno 和 refcnt 宣布它已经 cached 为止,始终持有 bcache.lock。这使得检查 block 是否存在,以及在不存在时指定一个 buffer 保存该 block,成为 atomic operation。
在离开 bcache.lock critical section 后再获取 buffer 的 sleep-lock 是安全的,因为非零的 b->refcnt 会阻止该 buffer 被重新用于另一个 disk block。Sleep-lock 保护 buffered content 的 reads 和 writes;bcache.lock 保护哪些 blocks 被 cache 的 information。
如果所有 buffers 都 busy,说明有太多 processes 正在同时执行 file-system calls;bget 会 panic。更 graceful 的 response 可能是 sleep,直到某个 buffer free,但这样会引入 deadlock 的可能性。
bread 完成 disk read(如果需要)并把 buffer 返回给 caller 后,caller 便独占该 buffer,可以读写其中的 data bytes。如果 caller 修改了 buffer,必须在释放 buffer 之前调用 bwrite,把修改后的 data 写入 disk。bwrite (4366) 调用 virtio_disk_rw 与 disk hardware 通信。
Caller 使用完 buffer 后必须调用 brelse 释放它。(brelse 是 b-release 的缩写,这个名字看起来 cryptic,但值得记住:它源于 Unix,也被 BSD、Linux 和 Solaris 使用。)brelse (4376) 释放 sleep-lock,并把 buffer 移到 linked list 的 front (4387–4392)。移动 buffer 会使 list 按 buffer 最近使用时间(也就是 release 时间)排序:list 的第一个 buffer 是 most recently used,最后一个是 least recently used。bget 中的两个 loops 利用了这一点:寻找已有 buffer 的 scan 在最坏情况下仍须遍历整个 list,但如果存在 good locality of reference,从 bcache.head 沿 next pointers 优先检查 recently used buffers,会减少 scan time。选择待复用 buffer 的 scan 则沿 prev pointers 向后扫描,选择 least recently used buffer。
10.4 Logging layer
File system design 中最有趣的问题之一是 crash recovery。问题源于许多 file-system operations 都涉及对 disk 的 multiple writes;如果 crash 发生在部分 writes 完成之后,on-disk file system 可能处于 inconsistent state。
例如,假设 crash 发生在 file truncation 期间(把 file length 设为 zero 并释放它的 content blocks)。根据 disk writes 的顺序,crash 可能留下两种结果之一:inode 仍然 reference 一个已被标记为 free 的 content block,或者留下一个已分配、但没有任何 reference 的 content block。
后一种情况相对 benign,但 inode reference 一个已经 freed 的 block 很可能在 reboot 后造成严重问题。Reboot 后,kernel 可能把该 block 分配给另一个 file,于是两个不同 files 会无意中指向同一个 block。如果 xv6 支持 multiple users,这可能成为 security problem:旧 file 的 owner 将能够读写新 file 中的 blocks,而新 file 属于另一个 user。
Xv6 使用一种 simple form of logging 解决 file-system operations 期间的 crash 问题。Xv6 system call 不会直接写入 on-disk file system data structures。相反,它把自己希望执行的所有 disk writes 的 description 放入 disk 上的 log。System call 记录完所有 writes 后,会向 disk 写入一个特殊的 commit record,表示 log 包含一个完整 operation。此时 system call 才把这些 writes copy 到 on-disk file system data structures。那些 writes 完成后,system call 擦除 disk 上的 log。
如果 system crash 并 reboot,file-system code 会在运行任何 processes 之前按如下方式 recovery:如果 log 被标记为包含一个 complete operation,recovery code 就把其中的 writes copy 到它们在 on-disk file system 中应当位于的位置。如果 log 没有被标记为 complete operation,recovery code 就忽略它。最后,recovery code 擦除 log。
为什么 xv6 的 log 能解决 file-system operations 期间的 crash 问题?如果 crash 发生在 operation commit 之前,disk 上的 log 不会被标记为 complete;recovery code 会忽略它,disk state 就像 operation 从未开始过。如果 crash 发生在 operation commit 之后,recovery 会 replay operation 的全部 writes;如果 operation 已经开始把 writes 写入 on-disk data structure,recovery 可能会重复这些 writes。无论哪种情况,log 都使 operation 相对于 crash 呈现 atomic:recovery 之后,operation 的 writes 要么全部出现在 disk 上,要么一个也不出现。
10.5 Log design
Log 位于一个已知的固定位置,该位置由 superblock 指定。它由一个 header block 和其后的一串 updated block copies(logged blocks)组成。Header block 包含一个 sector numbers array,每个 logged block 对应一个 sector number,以及 log blocks 的 count。Disk 上 header block 中的 count 要么是 zero,表示 log 中没有 transaction;要么是 non-zero,表示 log 包含一个 complete committed transaction,并且 count 表示该 transaction 中 logged blocks 的数量。
Xv6 只在 transaction commit 时写 header block,在此之前不会写;在把 logged blocks copy 到 file system 之后,则把 count 设为 zero。因此,transaction 中途发生 crash 会让 log header 中的 count 为 zero;commit 之后发生 crash 则会让 count 为 non-zero。
每个 system call 的 code 都标明一串相对于 crash 必须保持 atomic 的 writes 的 start 和 end。为了允许不同 processes 并发执行 file-system operations,logging system 可以把多个 system calls 的 writes 累积到一个 transaction 中。因此一次 commit 可能包含多个完整 system calls 的 writes。为了避免把一个 system call 拆到多个 transactions 中,logging system 只有在没有 file-system system calls 正在执行时才 commit。
把多个 transactions 一起 commit 的思想称为 group commit。Group commit 减少 disk operations 的数量,因为它把 commit 的 fixed cost amortize 到多个 operations 上。Group commit 还会同时把更多 concurrent writes 交给 disk system,也许能让 disk 在一次 rotation 中写完它们。Xv6 的 virtio driver 不支持这种 batching,但 xv6 file system 的 design 允许它。
Xv6 在 disk 上分配固定大小的空间保存 log。一个 transaction 中 system calls 写入的 blocks 总数必须适合这块空间。这带来两个 consequences:
- 任何单个 system call 都不能写入多于 log 空间所能容纳的 distinct blocks。大多数 system calls 不会有这个问题,但两个 system calls 可能写入很多 blocks:
write和unlink。Large file write 可能写入许多 data blocks、许多 bitmap blocks 和一个 inode block;unlink 一个 large file 可能写入许多 bitmap blocks 和一个 inode。Xv6 的writesystem call 会把 large writes 拆成多个更小、能放入 log 的 writes;unlink在实践中不会造成问题,因为 xv6 file system 实际只使用一个 bitmap block。 - log 空间有限的另一个 consequence 是:logging system 不能允许 system call 开始,除非它确信该 system call 的 writes 能放入 log 剩余空间。
10.6 Code:logging
System call 中使用 log 的典型形式如下:
begin_op();
...
bp = bread(...);
bp->data[...] = ...;
log_write(bp);
...
end_op();
begin_op (4702) 会等待两个条件:logging system 当前没有正在进行的 commit;以及 log 中有足够的 unreserved space 保存本次 call 的 writes。log.outstanding 统计已经 reserve log space 的 system calls 数量;总 reserved space 是 log.outstanding * MAXOPBLOCKS。增加 log.outstanding 同时完成 space reservation,并阻止本次 system call 执行期间发生 commit。Code 保守地假设每个 system call 最多可能写入 MAXOPBLOCKS 个 distinct blocks。
log_write (4790) 是 bwrite 的 proxy。它把 block 的 sector number 记录在 memory 中,为它 reserve 一个 disk log slot,并 pin 住 block cache 中的 buffer,防止 block cache eviction。Block 必须一直留在 cache 中直到 commit:在此之前,cached copy 是 modification 的唯一记录;直到 commit 之后它才能写回 disk 上属于它的位置;并且同一 transaction 中的其他 reads 必须看到这些 modifications。
如果某个 block 在同一 transaction 中被写入多次,log_write 会注意到这一点,并为该 block 分配同一个 log slot。这种 optimization 通常称为 absorption。例如,包含多个 files 的 inodes 的 disk block 在一个 transaction 中被多次写入是很常见的。把多个 disk writes absorption 为一次,file system 可以节省 log space,并提升 performance,因为只需把该 disk block 的一个 copy 写入 disk。
end_op (4722) 首先减少 outstanding system calls 的 count。如果 count 变为 zero,它就调用 commit() 提交当前 transaction。这个过程有 four stages:
write_log (4754)把 transaction 中每个 modified block 从 buffer cache copy 到 disk 上对应的 log slot。write_head (4668)把 header block 写入 disk;这是 commit point,在此 write 之后发生 crash,recovery 将 replay log 中的 transaction writes。install_trans (4619)从 log 读取每个 block,并把它写入 file system 中正确的位置。- 最后,
end_op把 log header 的 count 写为 zero;这必须在下一个 transaction 开始写 logged blocks 之前完成,否则 crash 可能让 recovery 把一个 transaction 的 header 与后续 transaction 的 logged blocks 错配。
recover_from_log (4682) 由 initlog (4606) 调用;initlog 在 boot 期间由 fsinit (4891) 调用,发生在第一个 user process 运行之前 (2666)。它读取 log header;如果 header 表示 log 包含一个 committed transaction,就模仿 end_op 的 actions。
filewrite (5803) 展示了 log 的一个使用例:
begin_op();
ilock(f->ip);
r = writei(f->ip, ...);
iunlock(f->ip);
end_op();
这段 code 被一个 loop 包裹;loop 把 large writes 拆成多个 individual transactions,每个 transaction 只处理几个 sectors,以避免 log overflow。writei call 会在这个 transaction 中写入多个 blocks:file 的 inode、一个或多个 bitmap blocks,以及一些 data blocks。
10.7 Code:Block allocator
File 和 directory content 存储在 disk blocks 中,而这些 blocks 必须从 free pool 中分配。Xv6 的 block allocator 在 disk 上维护一个 free bitmap,每个 block 对应一个 bit。Zero bit 表示对应 block free;one bit 表示它正在使用。mkfs 设置 boot sector、superblock、log blocks、inode blocks 和 bitmap blocks 对应的 bits。
Block allocator 提供两个 functions:balloc 分配一个新的 disk block,bfree 释放一个 block。balloc 中的 loop (4923) 从 block 0 开始,一直检查到 sb.size(file system 中的 block 数量)。它寻找 bitmap bit 为 zero 的 block,表示该 block free。如果 balloc 找到这样的 block,就更新 bitmap 并返回该 block。
为了提高 efficiency,这个 loop 分为两部分。Outer loop 读取每一组 bitmap bits 对应的 block;inner loop 检查一个 bitmap block 中的全部 Bits-Per-Block(BPB)个 bits。如果两个 processes 同时尝试分配同一个 block,buffer cache 对同一个 bitmap block 一次只允许一个 process 使用,因此可以避免由此产生的 race。
bfree (4952) 找到正确的 bitmap block,并清除正确的 bit。同样,bread 和 brelse 所隐含的 exclusive use 使得不需要 explicit locking。
和本章后面描述的许多 code 一样,balloc 和 bfree 必须在 transaction 内调用。
10.8 Inode layer
术语 inode 有两个相关含义。它可能指 on-disk data structure,其中包含 file size 和 data block numbers 的 list;也可能指 in-memory inode,其中包含 on-disk inode 的 copy,以及 kernel 内使用所需的 extra information。
On-disk inodes 紧密排列在 disk 上一块连续区域中,该区域称为 inode blocks。每个 inode 大小相同,因此给定一个 number n 后,很容易找到 disk 上的第 n 个 inode。事实上,implementation 正是使用这个 number n 来标识 inode;它称为 inode number 或 i-number。
On-disk inode 由 struct dinode (4131) 定义。type field 区分 files、directories 和 special files(devices)。Type zero 表示 on-disk inode free。nlink field 统计 reference 该 inode 的 directory entries 数量,用于判断何时应释放 on-disk inode 及其 data blocks。size field 记录 file content 的 bytes 数量。addrs array 记录保存 file content 的 disk blocks 的 numbers。
Kernel 在一个称为 itable 的 table 中把 active inodes 保存在 memory。struct inode (4216) 是 on-disk struct dinode 的 in-memory copy。只有在存在 C pointers 指向某个 inode 时,kernel 才把它保存在 memory 中。ref field 统计指向 in-memory inode 的 C pointers 数量;reference count 降为 zero 后,kernel 就从 memory 中丢弃该 inode。指向 inode 的 pointers 可能来自 file descriptors、current working directories,以及像 kexec 这样的 transient kernel code。
Xv6 inode code 中有 four 种 lock 或类似 lock 的 mechanisms:
itable.lock保护两个 invariants:一个 inode 在 inode table 中最多出现一次;in-memory inode 的reffield 等于指向它的 in-memory pointers 数量。- 每个 in-memory inode 都有一个包含 sleep-lock 的
lockfield,确保对 inode fields(例如 file length)以及 inode 的 file/directory content blocks 的 exclusive access。 - Inode 的
ref如果大于 zero,会使 system 保持该 inode 在 table 中,而不把 table entry 复用于另一个 inode。 - 每个 inode 都有一个
nlinkfield(disk 上有一份;如果 inode 在 memory 中,也会 copy 到 memory),用于统计 reference file 的 directory entries 数量。只要 link count 大于 zero,xv6 就不会释放 inode。
iget() 返回的 struct inode pointer 保证在对应的 iput() 调用之前有效;inode 不会被删除,pointer 指向的 memory 也不会被复用于另一个 inode。iget() 提供 non-exclusive access,因此可以同时有多个 pointers 指向同一个 inode。File-system code 的很多部分都依赖 iget() 的这个行为:一方面用它持有 inodes 的 long-term references(例如 open files 和 current directories),另一方面在操作多个 inodes(例如 pathname lookup)时避免 races 和 deadlock。
iget() 返回的 struct inode 可能没有任何 useful content。要确保它包含 on-disk inode 的 copy,code 必须调用 ilock。该 function 获取 inode lock(因此没有其他 process 能同时 ilock 它);如果 inode 尚未 read,它还会从 disk 读取 inode。iunlock 释放 inode lock。把 inode pointer 的获取与 locking 分开,有助于在某些情况下避免 deadlock,例如 directory lookup。多个 processes 可以持有 iget 返回的 inode pointer,但同一时刻只有一个 process 能 lock 该 inode。
Inode table 只保存那些被 kernel code 或 data structures 持有 C pointer 的 inodes。它的主要工作是同步多个 processes 对 inode 的访问;它也会顺便 cache frequently-used inodes,但 caching 是次要的:如果某个 inode 使用频繁,buffer cache 很可能已经把它保留在 memory 中。修改 in-memory inode 的 code 通过 iupdate 把它写入 disk。
10.9 Code:Inodes
要分配一个新的 inode(例如创建 file 时),xv6 调用 ialloc (5059)。ialloc 与 balloc 类似:它逐个 disk block 扫描 inode structures,寻找被标记为 free 的 inode。找到后,它把新的 type 写入 disk 来 claim 该 inode,然后通过调用 iget (5073) 返回 inode table 中的一个 entry。ialloc 能正确工作的前提是:同一时刻最多只有一个 process 持有 bp 的 reference;因此 ialloc 可以确定没有其他 process 同时看到 inode available 并尝试 claim 它。
iget (5107) 搜索 inode table,查找 active entry(ip->ref > 0),且 device 与 inode number 都符合要求。如果找到,就返回该 inode 的一个新 reference (5116–5120)。扫描过程中,它还记录第一个 empty slot 的位置 (5121–5122);如果需要分配 table entry,就使用这个位置。
Code 在读取或写入 inode metadata 或 content 之前,必须使用 ilock lock inode。ilock (5153) 为此使用 sleep-lock。获得 inode 的 exclusive access 后,如果需要,它会从 disk(更可能是从 buffer cache)读取 inode。iunlock (5181) 释放 sleep-lock;这可能使 sleeping processes 被唤醒。
iput (5208) 通过减少 reference count (5231) 来释放一个指向 inode 的 C pointer。如果这是最后一个 reference,那么 inode 在 inode table 中的 slot 现在 free,可以复用于另一个 inode。
如果 iput 发现某个 inode 没有 C-pointer references,并且也没有 links 指向它(即它不出现在任何 directory 中),那么 inode 及其 data blocks 必须被释放。iput 调用 itrunc 把 file truncate 为 zero bytes,释放 data blocks;把 inode type 设置为 zero(unallocated);并将 inode 写入 disk (5213)。
iput 在释放 inode 时使用的 locking protocol 值得仔细观察。一种 danger 是:另一个 concurrent thread 可能正在 ilock 中等待使用该 inode(例如读取 file 或列出 directory),但它没有准备好面对 inode 已不再 allocated 的情况。不过这不可能发生,因为当一个 on-disk inode 没有 links 且 ip->ref 为 one 时,system call 没有办法获得指向它的 in-memory inode pointer。那个唯一的 reference 正是调用 iput 的 thread 所持有的 reference。
另一个主要 danger 是 concurrent ialloc 可能选择 iput 正在释放的同一个 inode。只有在 iupdate 把 disk 上 inode 的 type 写为 zero 之后,这种情况才可能发生。这个 race 是 benign 的:allocating thread 会礼貌地等待 inode 的 sleep-lock;之后才会读取或写入 inode,此时 iput 已经完成。
iput() 可能写入 disk。这意味着任何使用 file system 的 system call 都可能写 disk,因为该 system call 可能是最后一个持有 file reference 的调用。即使看起来只读的 read() 也可能最终调用 iput()。因此,只要使用 file system,即使 read-only system calls 也必须包在 transactions 中。
iput() 与 crash 之间存在 challenging interaction。File 的 link count 降为 zero 时,iput() 不会立即 truncate file,因为某些 process 可能仍然在 memory 中持有对该 inode 的 reference:该 process 可能已经成功打开 file,仍在读写它。但是,如果在 file 的最后一个 process close file descriptor 之前发生 crash,那么 disk 上的 file 会被标记为 allocated,却没有任何 directory entry 指向它。
File systems 有两种处理这种情况的方法。简单的 solution 是:recovery 时、reboot 后,file system 扫描整个 file system,寻找被标记为 allocated、但没有 directory entry 指向的 files。如果存在这样的 file,就可以释放它。第二种 solution 不需要扫描整个 file system:当某个 file 的 link count 降为 zero、但 reference count 不为 zero 时,file system 在 disk 上记录它的 inode number(例如记录在 superblock 中)。当 reference count 降到 zero、file system 删除该 file 时,它再从 on-disk list 中移除该 inode。Recovery 时,file system 释放 list 中的每个 file。
Xv6 两种 solution 都没有实现。这意味着 inode 可能在 disk 上被标记为 allocated,即使它们已经不再使用;随着时间推移,xv6 有耗尽 disk space 的风险。
10.10 Code:Inode content
On-disk inode structure struct dinode 包含一个 size 和一个 block numbers array(见 Figure 10.3)。Inode data 位于 dinode 的 addrs array 列出的 blocks 中。前 NDIRECT 个 data blocks 位于 array 的前 NDIRECT 个 entries 中;这些 blocks 称为 direct blocks。接下来的 NINDIRECT 个 data blocks 不直接列在 inode 中,而是列在一个称为 indirect block 的 data block 中。addrs array 的最后一个 entry 给出 indirect block 的 address。
因此,file 的前 12 kB(NDIRECT × BSIZE bytes)可以从 inode 列出的 blocks 加载;接下来的 256 kB(NINDIRECT × BSIZE bytes)则必须先查阅 indirect block 才能加载。这是一个很好的 on-disk representation,但对 clients 来说比较复杂。Function bmap 管理这种 representation,使 higher-level routines(例如稍后会看到的 readi 和 writei)不必处理这一复杂性。bmap 返回 inode ip 的第 bn 个 data block 的 disk block number。如果 ip 还没有这样的 block,bmap 就分配一个。
bmap (5283) 首先处理 easy case:前 NDIRECT 个 blocks 直接列在 inode 中 (5288–5296)。接下来的 NINDIRECT 个 blocks 位于 ip->addrs[NDIRECT] 指向的 indirect block 中。bmap 读取 indirect block (5308),然后从 block 中正确的位置读取 block number (5309)。如果 block number 超过 NDIRECT + NINDIRECT,bmap 就 panic;writei 中的 check 防止这种情况发生 (5415)。
bmap 会按需分配 blocks。ip->addrs[] 或 indirect entry 为 zero 表示没有分配 block。bmap 遇到 zero 时,会用新分配的 block number 替换它:这些 blocks 是 on demand 分配的 (5289–5290、5302–5303)。
itrunc 释放 file 的 blocks,并把 inode size 重置为 zero。itrunc (5327) 首先释放 direct blocks (5333–5338),然后释放 indirect block 中列出的 blocks (5343–5346),最后释放 indirect block 自身 (5348–5349)。
bmap 让 readi 和 writei 很容易访问 inode data。readi (5373) 首先确保 offset 和 count 没有越过 file end。Start beyond file end 的 read 返回 error (5378–5379);start at 或 cross file end 的 read 返回少于请求数量的 bytes (5380–5381)。Main loop 逐个处理 file block,把 data 从 buffer copy 到 dst (5383–5395)。writei (5408) 与 readi 相同,但有 three differences:从或跨 file end 开始的 writes 会增长 file,直到 maximum file size (5415–5416);loop 把 data copy 到 buffers,而不是 copy out;如果 write 扩展了 file,writei 必须更新 file size (5432–5433)。
Function stati (5359) 把 inode metadata copy 到 stat structure;user programs 可以通过 stat system call 访问该 structure。
10.11 Code:directory layer
Directory 在内部的实现很像 file。它的 inode type 是 T_DIR,其 data 是一串 directory entries。每个 entry 是一个 struct dirent (4165),包含 name 和 inode number。Name 最多 DIRSIZ (14) 个 characters;如果更短,则以 NULL(0)byte 结束。Inode number 为 zero 的 directory entries 是 free 的。
Function dirlookup (5453) 在 directory 中搜索给定 name 的 entry。如果找到,就返回对应的、unlocked 的 inode pointer,并将 entry 在 directory 中的 byte offset 写入 *poff,以便 caller 需要编辑它时使用。如果 dirlookup 找到正确 name,就更新 *poff,并通过 iget 返回一个 unlocked inode。
dirlookup 正是 iget 返回 unlocked inodes 的原因。Caller 已经 lock 了 dp;如果 lookup 的对象是 .(current directory 的 alias),那么在返回前尝试 lock 该 inode 就会再次 lock dp,从而 deadlock。(涉及多个 processes 的更复杂 deadlock 场景还包括 ..,即 parent directory 的 alias;. 并不是唯一问题。)Caller 可以先 unlock dp,然后 lock ip,确保同一时刻只持有一个 lock。
dirlink (5481) 在 directory dp 中写入一个带有给定 name 和 inode number 的新 directory entry。如果 name 已存在,dirlink 返回 error (5487–5491)。Main loop 读取 directory entries,寻找一个 unallocated entry。找到后,它提前停止 loop (5493–5498),并把 available entry 的 offset 保存到 offset。否则,loop 以 dp->size 作为 offset 结束。无论哪种情况,dirlink 都通过在 offset off 写入来添加新的 directory entry (5502–5503)。
10.12 Code:Path names
Pathname lookup 包含一连串 dirlookup calls,每个 path component 对应一个 call。namei (5590) 计算 path 并返回对应的 inode。Function nameiparent 是它的 variant:它在最后一个 element 之前停止,返回 parent directory 的 inode,并把最后一个 element copy 到 name 中。两者都调用 generalized function namex 完成真正的 work。
namex (5555) 首先决定 path evaluation 从哪里开始。如果 path 以 slash 开头,就从 root 开始;否则从 current directory 开始 (5559–5562)。然后它使用 skipelem 依次处理每个 element (5564)。Loop 的每次 iteration 都必须在 current inode ip 中 lookup name。
Iteration 首先 lock ip 并检查它是 directory。如果不是,lookup 失败 (5565–5569)。(需要 lock ip 并不是因为 ip->type 可能被 concurrent 修改——它不会变化;而是因为在 ilock 运行之前,不能保证 ip->type 已经从 disk load。)如果调用者是 nameiparent,且当前 element 是最后一个 path element,loop 会提前停止,符合 nameiparent 的定义;最后一个 path element 已经 copy 到 name,因此 namex 只需返回 unlocked ip (5570–5574)。最后,loop 使用 dirlookup 查找 path element,并通过设置 ip = next 为下一次 iteration 准备 (5575–5580)。Path elements 耗尽后,它返回 ip。
namex 过程可能需要很长时间:如果 traversed directories 不在 buffer cache 中,它可能需要多个 disk operations 来读入 inodes 和 directory blocks。Xv6 对此做了 carefully designed 的 concurrency 处理:如果一个 kernel thread 的 namex invocation 被 disk I/O block,另一个正在查找不同 pathname 的 kernel thread 仍可继续。namex 分别 lock path 中的每个 directory,使对不同 directories 的 lookups 能够并行。
这种 concurrency 带来了一些 challenges。例如,一个 kernel thread 正在 lookup pathname 时,另一个 kernel thread 可能通过 unlink 一个 directory 来修改 directory tree。潜在风险是:lookup 可能正在搜索一个已被另一个 kernel thread 删除的 directory,而该 directory 的 blocks 已被 re-use,成为另一个 directory 或 file。
Xv6 避免了这类 races。例如,namex 执行 dirlookup 时,lookup thread 持有 directory lock;dirlookup 使用 iget 获取一个 inode,并返回它。iget 增加 inode 的 reference count。只有在从 dirlookup 收到 inode 之后,namex 才 release directory lock。此时另一个 thread 可以 unlink 该 inode,但 xv6 不会立即删除它,因为 inode 的 reference count 仍大于 zero。
另一个 risk 是 deadlock。例如,lookup . 时,next 指向的 inode 与 ip 是同一个。若在释放 ip lock 之前先 lock next,就会造成 deadlock。为避免该 deadlock,namex 在获得 next 的 lock 之前先 unlock directory。这里我们再次看到,把 iget 与 ilock 分开是多么重要。
10.13 File descriptor layer
Unix interface 的一个 cool aspect 是:Unix 中大多数 resources 都表示为 files,包括 console、pipes 这样的 devices,当然也包括 regular files。File descriptor layer 正是实现这种 uniformity 的 layer。
Xv6 为每个 process 提供自己的 open-file table,即 file descriptors,这一点在 Chapter 1 已经看到。每个 open file 都由一个 struct file (4200) 表示;它是 inode 或 pipe 的 wrapper,外加一个 I/O offset。每次 open 都会创建一个新的 open file(一个新的 struct file):如果多个 processes 独立打开同一个 file,它们得到的 instances 会拥有不同的 I/O offsets。
另一方面,同一个 open file(同一个 struct file)可以在一个 process 的 file table 中出现多次,也可以出现在多个 processes 的 file tables 中。例如,一个 process 使用 open 打开 file,随后通过 dup 创建 aliases,或者通过 fork 与 child 共享 file,就会出现这种情况。Reference count 跟踪某个 open file 的 references 数量。File 可以以 reading、writing 或两者同时打开;readable 和 writable fields 跟踪这一状态。
System 中所有 open files 都保存在 global file table ftable 中。File table 提供 filealloc 分配 file、filedup 创建 duplicate reference、fileclose 释放 reference,以及 fileread 和 filewrite 读写 data 的 functions。
前三个 functions 遵循现在熟悉的形式:filealloc (5679) 扫描 file table,寻找 unreferenced file(f->ref == 0)并返回一个新 reference;filedup (5702) 增加 reference count;fileclose (5714) 减少 reference count。当 file 的 reference count 达到 zero 时,fileclose 根据 type 释放底层 pipe 或 inode。
Functions filestat、fileread 和 filewrite 实现对 files 的 stat、read 和 write operations。filestat (5753) 只允许用于 inodes,并调用 stati。fileread 和 filewrite 检查 operation 是否被 open mode 允许,然后把 call 传递给 pipe 或 inode implementation。如果 file 表示一个 inode,fileread 和 filewrite 使用 I/O offset 作为 operation 的 offset,然后推进它 (5787–5788、5830–5831)。Pipes 没有 offset 的概念。
注意,inode functions 要求 caller 负责 locking (5759–5761、5786–5789、5829–5832)。Inode locking 带来一个方便的 side effect:read 和 write offsets 会 atomic 地更新,因此多个 processes 同时写入同一个 file 时不会相互覆盖 data,尽管这些 writes 最终可能 interlaced。
10.14 Code:System calls
借助 lower layers 提供的 functions,大多数 system calls 的 implementation 都很 trivial(见 sysfile.c (5850))。有几个 calls 值得仔细看。
Functions sys_link 和 sys_unlink 修改 directories,创建或移除指向 inodes 的 references。它们也是 transaction power 的好例子。sys_link (6002) 首先获取两个 string arguments:old 和 new (6007)。假设 old 存在且不是 directory (6011–6014),sys_link 增加 ip->nlink count。然后 sys_link 调用 nameiparent,寻找 new 的 parent directory 和 final path element (6027),并创建一个指向 old inode 的新 directory entry (6030)。新的 parent directory 必须存在,并且必须与已有 inode 位于同一 device 上:inode numbers 只在单个 disk 上具有 unique meaning。如果发生这样的 error,sys_link 必须回退并减少 ip->nlink。
Transactions 简化了 implementation:虽然它们要求更新多个 disk blocks,但我们不必担心更新顺序;这些 updates 要么全部成功,要么一个都不成功。例如,如果没有 transactions,在创建 link 之前更新 ip->nlink 会让 file system 暂时处于 unsafe state;中间发生 crash 可能导致 havoc。有了 transactions,就不必担心这种情况。
sys_link 为已有 inode 创建一个 new name。Function create (6124) 则为 new inode 创建一个 new name。它是三个 file-creation system calls 的 generalization:带 O_CREATE flag 的 open 创建 ordinary file;mkdir 创建 directory;mknod 创建 device file。
与 sys_link 类似,create 首先调用 nameiparent 获得 parent directory inode。然后调用 dirlookup 检查 name 是否已经存在 (6089)。如果 name 已存在,create 的行为取决于它由哪个 system call 使用:open 与 mkdir、mknod 的 semantics 不同。如果 create 代表 open (type == T_FILE),并且已存在的 name 本身是 regular file,那么 open 将其视为 success,create 也如此处理 (6138)。否则返回 error (6139–6140)。如果 name 不存在,create 使用 ialloc (6143) 分配一个新的 inode。如果新 inode 是 directory,create 用 . 和 .. entries 初始化它。现在 data 已正确初始化,create 就可以把该 inode link 到 parent directory (6158)。create 与 sys_link 一样,会同时持有两个 inode locks:ip 和 dp。这里没有 deadlock 的可能,因为 ip 是 freshly allocated 的;system 中没有其他 process 会持有 ip lock 后再尝试 lock dp。
有了 create,实现 sys_open、sys_mkdir 和 sys_mknod 就很容易。sys_open (6185) 最复杂,因为创建 new file 只是它能做的事情之一。如果 open 传入 O_CREATE flag,它调用 create (6201);否则调用 namei (6207)。create 返回 locked inode,而 namei 不返回 locked inode,因此 sys_open 必须自行 lock inode。这也是检查 directories 只能 read、不能 write 的方便位置。无论 inode 通过哪条路径取得,sys_open 都分配一个 file 和 file descriptor (6225),然后填充 file (6237–6242)。注意,在当前 process 的 table 中,其他 processes 无法访问这个 partially initialized file。
Chapter 9 在还没有 file system 的时候就考察了 pipes 的 implementation。Function sys_pipe 把 pipe implementation 连接到 file system:它提供一种创建 pipe pair 的方式。它的 argument 是一个 pointer,指向能保存两个 integers 的 space;sys_pipe 会把两个新的 file descriptors 写入那里。随后它分配 pipe 并安装这两个 file descriptors。
10.15 Real world
Real-world operating system 的 buffer cache 比 xv6 的复杂得多,但仍服务于相同的两个 purposes:cache,以及同步对 disk 的 access。Xv6 的 buffer cache 与 V6 一样,使用简单的 least recently used(LRU)eviction policy;还可以实现许多更复杂的 policies,每种 policy 对某些 workloads 更好、对另一些 workloads 更差。更 efficient 的 LRU cache 可以去掉 linked list,改用 hash table 做 lookups,使用 heap 做 LRU evictions。Modern buffer caches 通常与 virtual memory system 集成,以支持 memory-mapped files。
Xv6 logging system 的 efficiency 不高。Commit 不能与 file-system system calls 并发发生。Log 会记录整个 blocks,即使只修改了一个 block 中的少量 bytes。它执行 synchronous log writes,一次写一个 block;每次 write 很可能都需要完整的 disk rotation time。Real logging systems 会处理这些问题。
Logging 不是提供 crash recovery 的唯一方法。Early file systems 会在 reboot 时使用 scavenger(例如 UNIX fsck program),检查每个 file 和 directory,以及 block 和 inode free lists,寻找并解决 inconsistencies。对 large file systems 来说,scavenging 可能耗费数小时;并且有些情况下,无法以保持原始 system calls atomic 的方式解决 inconsistencies。Log recovery 快得多,而且能使 system calls 在 crash 面前保持 atomic。
Xv6 使用的 inode 和 directory 基本 on-disk layout 与 early UNIX 相同;这个 scheme 多年来 remarkably persistent。BSD 的 UFS/FFS 和 Linux 的 ext2/ext3 本质上使用相同的 data structures。File system layout 中最 inefficient 的部分是 directory:每次 lookup 都需要线性扫描所有 disk blocks。当 directory 只有几个 disk blocks 时这很合理,但对于包含大量 files 的 directories 就很昂贵。Microsoft Windows 的 NTFS、macOS 的 HFS 和 Solaris 的 ZFS,仅举几例,会把 directory 实现为 on-disk balanced tree of blocks。这样更复杂,但能保证 logarithmic-time directory lookups。
Xv6 对 disk failures 的处理很 naive:如果 disk operation 失败,xv6 就 panic。这是否合理取决于 hardware:如果 operating system 架在使用 redundancy mask disk failures 的 special hardware 之上,那么 operating system 看到 failure 的频率可能低到 panic 也没关系。另一方面,使用 plain disks 的 operating systems 应该预期 failures,并更 graceful 地处理它们,使一个 file 中某个 block 的丢失不会影响整个 file system 其余部分的使用。
Xv6 要求 file system 适合一个 disk device,并且大小不能变化。随着 large databases 和 multimedia files 不断推高 storage requirements,operating systems 正在发展方法,消除“一个 file system 对应一个 disk”的 bottleneck。基本方法是把多个 disks 组合成一个 logical disk。Hardware solutions(例如 RAID)仍然最流行,但当前趋势是尽可能多地在 software 中实现这些 logic。这些 software implementations 通常支持丰富功能,例如通过在线添加或移除 disks,让 logical device 增长或缩小。
当然,一个能在线增长或缩小的 storage layer 需要一个也能这样做的 file system:xv6 使用的固定大小 inode-block array 在这样的环境中不会工作得很好。把 disk management 与 file system 分离可能是最 clean 的 design,但两者之间复杂的 interface 已经导致一些 systems(例如 Sun 的 ZFS)把它们组合起来。
Xv6 的 file system 还缺少许多 modern file systems 的 features,例如 snapshots 和 incremental backup。
Modern Unix systems 允许使用与 on-disk storage 相同的 system calls 访问多种 resources:named pipes、network connections、remote-accessed network file systems,以及 /proc 这样的 monitoring/control interfaces。它们通常不会像 xv6 的 fileread 和 filewrite 那样使用 if statements,而是为每个 open file 提供一个 function-pointers table,每个 operation 一个 pointer,并通过调用 function pointer 来调用该 inode 的 implementation。Network file systems 和 user-level file systems 提供的 functions 会把这些 calls 转换为 network RPC,并在 response 返回前等待。
10.16 Exercises
- 为什么
balloc要 panic?Xv6 能 recovery 吗? - 为什么
ialloc要 panic?Xv6 能 recovery 吗? filealloc没有 files 可用时,为什么不 panic?为什么这种情况更常见,因此值得处理?- 假设对应
ip的 file 在sys_link调用iunlock(ip)与dirlink之间被另一个 process unlink。Link 能正确创建吗?为什么? create进行了四个它要求成功的 function calls(一次ialloc和三次dirlink)。如果其中任何一个失败,create就 panic。为什么这可以接受?为什么这四个 calls 都不能失败?sys_chdir在iput(cp->cwd)之前调用iunlock(ip);而iput可能尝试 lockcp->cwd。但如果把iunlock(ip)延后到iput之后,为什么不会造成 deadlock?- 实现
lseeksystem call。支持lseek还要求修改filewrite:当lseek把 offset 设置到f->ip->size之外时,用 zero 填充 file 中的 holes。 - 为
open增加O_TRUNC和O_APPEND,使 shell 中的>和>>operators 能工作。 - 修改 file system,使其支持 symbolic links。
- 修改 file system,使其支持 named pipes。
- 修改 file 和 VM systems,使其支持 memory-mapped files。
图与格式复核
- Figure 10.1:按原文七层 file-system stack 重建为 SVG,放在 layer overview 段落之后。
- Figure 10.2:按原文 disk sections 重建为 SVG,放在 superblock 与 disk layout 说明之后。
- Figure 10.3:按原文 dinode、indirect block、data blocks 的关系重建为 SVG,放在 inode content 说明之后。
- 代码与列表:保留 xv6 APIs、源码 identifiers、line references、C code、constants、process/file-system state 和原文 11 道 exercises;不把 established technical terms 强行翻译。
术语对照
| English | 译法/处理 |
|---|---|
| file system / filesystem | 保留 file system;必要处译作文件系统 |
| buffer cache | 保留 buffer cache;必要处解释为缓冲区缓存 |
| log / logging | 保留 log/logging;必要处解释为日志机制 |
| transaction | 保留 transaction;必要处解释为事务 |
| inode / directory / pathname | 保留 established terms,按语境补充中文解释 |
| block / sector | 保留 block/sector,区分 disk block 与 sector |
| direct / indirect block | 保留 direct/indirect block |
| link / unlink | 保留 system-call/API 名称 |
| crash recovery | 保留 crash recovery;必要处译作崩溃恢复 |
| LRU / eviction / cache | 保留缩写和 systems terminology |
参考资料
- MIT 6.1810 Fall 2025:课程主页
- Russ Cox、Frans Kaashoek、Robert Morris:xv6 book rev5
- MIT PDOS:xv6-riscv source
评论 (0)