xv6 Lab8 File system - MIT 6.1810 Fall 2025 Operating System
Last updated on August 18, 2026 pm
This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.
Reading
Just read the book briefly, have GPT translate it and extract the key points, then read the corresponding parts.
xv6 divides the file system into 7 layers:
- Disk layer: actually reads and writes blocks to/from the VirtIO disk.
- Buffer cache: caches disk blocks in memory, and ensures that only one thread modifies a block at any given time.
- Logging: groups modifications of multiple blocks into a transaction, guaranteeing that after a crash either all of them take effect or none of them do.
- Inode: represents a file as an inode + several data blocks.
- Directory: a directory is actually a special kind of file whose content is a series of
name -> inode numbermappings. - Pathname: parses
/a/b/c. - File descriptor: finally provides the user with a unified interface like
open/read/write/....
The so-called "crash consistency": when a crash happens midway through operations like modifying an inode or writing logs, inconsistency results. xv6's approach is logging — instead of directly modifying the real file system, it first writes the modifications of this transaction into the log.
As for the log design, it resides in a specific region of the disk.
Inodes are split into the on-disk struct dinode and the in-memory struct inode. The in-memory inode is just a cached copy of the disk inode.
Important fields of the disk inode:
type
nlink
size
addrs[]Meanings:
type: regular file, directory, device, ...nlink: how many directory entries point to it.size: file size.addrs[]: the disk block numbers where the file's data resides.
The inode number (inum) is simply the index of the inode in the disk's inode region.
The in-memory struct inode additionally has:
ref
lock
valid
...ref indicates how many C pointers in the kernel are currently referencing this inode.
Then there is the distinction between direct blocks and indirect blocks, i.e., first-level and second-level indexing:

Querying inodes and directories also involves a bunch of APIs, e.g., for a full path, namex() splits it by separators and recursively looks up the inode at each level.
Large files
Follow the hints:
Analyzing the bmap() function
代码
// Return the disk block address of the nth block in inode ip.
// If there is no such block, bmap allocates one.
// returns 0 if out of disk space.
static uint
bmap(struct inode *ip, uint bn)
{
uint addr, *a;
struct buf *bp;
if(bn < NDIRECT){
if((addr = ip->addrs[bn]) == 0){
addr = balloc(ip->dev);
if(addr == 0)
return 0;
ip->addrs[bn] = addr;
}
return addr;
}
bn -= NDIRECT;
if(bn < NINDIRECT){
// Load indirect block, allocating if necessary.
if((addr = ip->addrs[NDIRECT]) == 0){
addr = balloc(ip->dev);
if(addr == 0)
return 0;
ip->addrs[NDIRECT] = addr;
}
bp = bread(ip->dev, addr);
a = (uint*)bp->data;
if((addr = a[bn]) == 0){
addr = balloc(ip->dev);
if(addr){
a[bn] = addr;
log_write(bp);
}
}
brelse(bp);
return addr;
}
panic("bmap: out of range");
}- Figure 10.3 in the "Reading" section is extremely, extremely important.
bnis the logical block number, i.e., which block of the file this block is, relative to the beginning of the file. What is returned is the actual disk block number.- If
bn < NDIRECT, as shown in the figure, it maps directly to the data block atip->addrs[bn].- But the actual implementation first checks whether it exists, and if not, it has to allocate one with
balloc().
- But the actual implementation first checks whether it exists, and if not, it has to allocate one with
- If
bn > NDIRECT:- First
bn -= NDIRECT; this step converts the logical block number, originally relative to the whole file, into an index within the first-level indirect block array.- In fact, looking at the figure you can see that after entering the first-level block, the addresses are again 1 ~ 256, though in reality it should be 0 ~ 255.
- Check
bn < NINDIRECT; this is really just checking whether the previousbnis within the maximum range (MAXFILE = NDIRECT + NINDIRECT). - After the check passes, check the existence of the indirect block, and allocate one if it doesn't exist.
- Then, first use
bread()to get thestruct bufof the indirect block on disk, and get the data inside it.- If the data is empty, continue allocating; if not empty, just get the address and it can be returned directly (though the code isn't written that way, it's logically equivalent).
- After confirming it's non-empty, map the newly allocated block into
a[bn], then log it. - Finally release it, then return the address.
- First
Modifying the macro definitions
Currently xv6 files can have at most 268 blocks. Analyzing the reason: it's because #define NDIRECT 12 is specified, and dinode and inode contain uint addrs[NDIRECT+1];.
That is, 12 direct block numbers, plus 1 first-level indirect block number.
Also, BSIZE 1024 (bytes per block) is specified, and sizeof(uint) = 4, so one indirect block can hold at most 256 block numbers, hence MAXFILE = 12 + 256 = 268 blocks.
This lab requires implementing doubly-indirect blocks, which becomes $256^2 + 256 + 11 = 65803 \text{blocks}$
#define NDIRECT 11
#define NINDIRECT (BSIZE / sizeof(uint))
#define NINDIRECT2 (NINDIRECT * NINDIRECT)
#define MAXFILE (NDIRECT + NINDIRECT + NINDIRECT2)Then, modify the fields of struct inode and struct dinode:
uint addrs[NDIRECT+2];Thinking through the calculation
Think: given a file's logical block number, how should you compute its position within the doubly-indirect block, i.e., first which singly-indirect block to pick, and then which data block within it.
Here I'll borrow an image from Zhihu, which is drawn very well:

Specifically, if bn falls in the second-level index range:
-
First you need to subtract the previous two parts (which actually gets subtracted away step by step during the calculation).
-
Then, each address inside the 2nd indirect block maps to another 1st indirect block, i.e., another 256 actual data blocks.
-
So, for example, bn = 45162 (a random number that happens to satisfy the requirement)
- After the first- and second-level checks, bn = 45162 - 11 - 256 = 44895
- Then, dividing by 256 gives 175, meaning it's located at the 175th first-level index.
- Then, 44895 % 256 = 95, meaning it's located at the 95th data block pointed to by that first-level index.
That's the calculation.
Implementing the modification to bmap()
代码
static uint
bmap(struct inode *ip, uint bn)
{
uint addr, *a;
struct buf *bp;
if(bn < NDIRECT){
if((addr = ip->addrs[bn]) == 0){
addr = balloc(ip->dev);
if(addr == 0)
return 0;
ip->addrs[bn] = addr;
}
return addr;
}
bn -= NDIRECT;
if(bn < NINDIRECT){
// Load indirect block, allocating if necessary.
if((addr = ip->addrs[NDIRECT]) == 0){
addr = balloc(ip->dev);
if(addr == 0)
return 0;
ip->addrs[NDIRECT] = addr;
}
bp = bread(ip->dev, addr);
a = (uint*)bp->data;
if((addr = a[bn]) == 0){
addr = balloc(ip->dev);
if(addr){
a[bn] = addr;
log_write(bp);
}
}
brelse(bp);
return addr;
}
// 以下为实现代码
bn -= NINDIRECT;
if(bn < NINDIRECT2) {
// 这里的 addr 是二级间接块的地址
if ((addr = ip->addrs[NDIRECT + 1]) == 0) {
addr = balloc(ip->dev);
if (addr == 0) {
return 0;
}
ip->addrs[NDIRECT + 1] = addr;
}
// 这里的 bp 是二级间接块的实际 struct buf
bp = bread(ip->dev, addr);
a = (uint*)bp->data;
// 这里的 addr 是二级间接块指向的一级间接块的地址
if ((addr = a[bn / NINDIRECT]) == 0) {
addr = balloc(ip->dev);
if (addr == 0) {
return 0;
}
a[bn / NINDIRECT] = addr;
// 记得任何对于实际 buf 的修改都要落日志,维护崩溃一致性
log_write(bp);
}
brelse(bp);
// 这里的 bp 是一级间接块的实际的 struct buf
bp = bread(ip->dev, addr);
a = (uint*)bp->data;
// 这里的 addr 是最后实际的数据的地址
if ((addr = a[bn % NINDIRECT]) == 0) {
addr = balloc(ip->dev);
if (addr == 0) {
return 0;
}
a[bn % NINDIRECT] = addr;
log_write(bp);
}
brelse(bp);
return addr;
}
panic("bmap: out of range");
}Actually, many places reuse a single variable, such as bp, a, and addr, because the original code reuses them this way. Although it's not very clear, to keep the code style consistent, so be it.
Remember, for every block read via bread(), don't forget to eventually call brelse().
Modifying itrunc()
Don't forget to modify
itrunc(), making sure it can free all of a file's blocks, including the double-indirect block and the blocks beneath it.
Just like when you modified kalloc() to add a level, you certainly need to modify kfree() as well.
代码
void
itrunc(struct inode *ip)
{
int i, j, k;
struct buf *bp;
uint *a;
for(i = 0; i < NDIRECT; i++){
if(ip->addrs[i]){
bfree(ip->dev, ip->addrs[i]);
ip->addrs[i] = 0;
}
}
if(ip->addrs[NDIRECT]){
bp = bread(ip->dev, ip->addrs[NDIRECT]);
a = (uint*)bp->data;
for(j = 0; j < NINDIRECT; j++){
if(a[j])
bfree(ip->dev, a[j]);
}
brelse(bp);
bfree(ip->dev, ip->addrs[NDIRECT]);
ip->addrs[NDIRECT] = 0;
}
if(ip->addrs[NDIRECT + 1]) {
bp = bread(ip->dev, ip->addrs[NDIRECT + 1]);
a = (uint*)bp->data;
for(j = 0; j < NINDIRECT; j++) {
uint in1_addr;
if ((in1_addr = a[j]) != 0) {
struct buf *in1_bp = bread(ip->dev, in1_addr);
uint *in1_a = (uint*)in1_bp->data;
for(k = 0; k < NINDIRECT; k++) {
bfree(ip->dev, in1_a[k]);
}
brelse(in1_bp);
bfree(ip->dev, in1_addr);
}
}
brelse(bp);
bfree(ip->dev, ip->addrs[NDIRECT + 1]);
ip->addrs[NDIRECT + 1] = 0;
}
ip->size = 0;
iupdate(ip);
}Symbolic links
Add symbolic link / soft link functionality to xv6, i.e., implement the symlink system call.
As a refresher, a soft link is an alias that records the target pathname. Understand the difference this way:
hard link:
name → inode
symbolic link:
name → symlink inode → pathname → inodeThis lab doesn't require handling soft links pointing to directories.
Using the hints as a guide:
Adding the basic system call configuration
Create a new system call number for symlink:
// kernel/syscall.h
#define SYS_symlink 22Implement an empty sys_symlink() in kernel/sysfile.c:
uint64
sys_symlink(void)
{
}Declare it and add it to the system call array in kernel/syscall.c:
extern uint64 sys_symlink(void);
static uint64 (*syscalls[])(void) = {
[SYS_fork] sys_fork,
// ...
[SYS_symlink] sys_symlink,
};Add the corresponding entry in user/usys.pl:
entry("symlink");Add the declaration in user/user.h:
int symlink(char *target, char *path);How do we know the exact return value? RTFM
Adding a new file type identifier
// kernel/stat.h
#define T_DIR 1 // Directory
#define T_FILE 2 // File
#define T_DEVICE 3 // Device
#define T_SYMLINK 4 // soft linkAdding a new flag
#define O_RDONLY 0x000
#define O_WRONLY 0x001
#define O_RDWR 0x002
#define O_CREATE 0x200
#define O_TRUNC 0x400
#define O_NOFOLLOW 0x20000This is mainly for open (RTFM tells us this flag has this value)
Actually, you could also implement your own, as long as you follow the principle that the flags passed to open() are combined with bitwise OR, so the new flag must not overlap in bits with any existing flag.
According to man:
If the trailing component (i.e., basename) of pathname is a symbolic link, then the open fails, with the error ELOOP
Implementing symlink()
Create a new symbolic link at path pointing to target; note that target does not need to actually exist.
At first I couldn't figure out these APIs and concepts (I wasn't reading carefully), so I decided to read the implementation of sys_link():
代码
// Create the path new as a link to the same inode as old.
uint64
sys_link(void)
{
char name[DIRSIZ], new[MAXPATH], old[MAXPATH];
struct inode *dp, *ip;
if(argstr(0, old, MAXPATH) < 0 || argstr(1, new, MAXPATH) < 0)
return -1;
begin_op();
if((ip = namei(old)) == 0){
end_op();
return -1;
}
ilock(ip);
if(ip->type == T_DIR){
iunlockput(ip);
end_op();
return -1;
}
ip->nlink++;
iupdate(ip);
iunlock(ip);
if((dp = nameiparent(new, name)) == 0)
goto bad;
ilock(dp);
if(dp->dev != ip->dev || dirlink(dp, name, ip->inum) < 0){
iunlockput(dp);
goto bad;
}
iunlockput(dp);
iput(ip);
end_op();
return 0;
bad:
ilock(ip);
ip->nlink--;
iupdate(ip);
iunlockput(ip);
end_op();
return -1;
}Some key points I sorted out:
begin_op()andend_op()open a file system transaction, guaranteeing ACID.namei()returns theinodestruct pointer of the file corresponding to the path.- After getting the
inodepointer, if you want to modify it, you also need to useilock()to lock it andiunlock()to unlock; after modification, you need to useiupdateto persist it, writing the in-memoryinodeback to the on-diskstruct dinode.
But that's really all you can learn from it; then reading the book (actually asking an LLM for the key points) yields this additional information:
- The inode returned by
create()comes locked already, so you don't need to lock it yourself. - A soft link is implemented by creating an inode of type
T_SYMLINK, whose data block (actually theuchar data[BSIZE];of thebufpointed to by theinode'saddr(obtained viabmap())) containstarget. - Therefore, if you want to read or write it, there are corresponding APIs, namely
readi()andwritei(); you can figure out their usage with a quick Ctrl + F.
But in fact my understanding was still somewhat off; you also need to read create(). Here is the LLM's corrected version directly:
引用
Why does the result of
namei()leak?
namei()doesn't just return an ordinary pointer; it also holds an inode reference on behalf of the caller.You can think of it as:
struct inode *ip = namei(path); // ip->ref 被加了一次After the caller is done, it must:
iput(ip);Otherwise the reference count will never be decremented back.
What you originally wrote was:
if(namei(path) != 0){ end_op(); return -1; }If the file exists,
namei()returns an inode with a reference, but you didn't save the return value:namei() acquires a reference ↓ returns the inode pointer ↓ the pointer is discarded directly ↓ iput() can no longer be called ↓ reference leakIt's similar to:
if(malloc(100) != 0) return;The memory was successfully allocated, but the pointer is thrown away directly, so there's no way to
free()it.If you really want to do this check, you should at least:
struct inode *existing = namei(path); if(existing != 0){ iput(existing); end_op(); return -1; }However, in
sys_symlink(), this check should simply be deleted, becausecreate()already checks whether the path exists under the protection of the parent directory lock.Calling
namei()first and thencreate()also has a concurrency problem:Process A: namei(path) finds it doesn't exist Process B: creates path Process A: create(path)A truly reliable "check and create" must be done inside
create().The difference between
iunlock()andiunlockput()They control two different things:
iunlock(ip);Only releases the inode lock, but still keeps the reference:
Lock: released Reference: kept ip: can still be used laterWhereas:
iunlockput(ip);Is equivalent to:
iunlock(ip); iput(ip);The result is:
Lock: released Reference: also released ip: cannot be used anymoreThe complete state transitions can be viewed like this:
ip = namei(path);At this point:
ref = +1 locked = noThen:
ilock(ip);Becomes:
ref = +1 locked = yesIf you call:
iunlock(ip);It becomes:
ref = +1 locked = no
ipcan still be used again.If you call:
iunlockput(ip);It becomes:
ref = released locked = no
ipcan no longer be used.Why does
link()useiunlock()?The logic of
sys_link()is roughly:ip = namei(old); // 获得 old inode 的引用 ilock(ip); ip->nlink++; iupdate(ip); iunlock(ip); // 只解锁,仍保留引用At this point it hasn't finished using
ip. It still needs:dp = nameiparent(new, name); ilock(dp); dirlink(dp, name, ip->inum);So the reference to
ipmust be kept.But there's no need to keep
iplocked, and holding its lock while doing path lookups and acquiring the parent directory lock increases the risk of deadlock. Therefore it uses:iunlock(ip);That is:
I don't need to hold its lock for now, but this inode isn't finished being used yet, so I can't release the reference.
Only after successfully creating the new directory entry does it:
iput(ip);If something fails in the middle, it needs to re-lock it and roll back
nlink:ilock(ip); ip->nlink--; iupdate(ip); iunlockput(ip);So the lifecycle of
link()is:namei(old) acquire the reference ↓ ilock(ip) lock ↓ modify nlink ↓ iunlock(ip) unlock, but keep the reference ↓ create the new directory entry, during which ip->inum is still needed ↓ iput(ip) finally release the referenceMost places use
iunlockput()because after unlocking at those points, the inode is never needed again.Two other typical
iunlock()scenarios:
open(): the reference is handed over tof->ip, to be released atclose().chdir(): the reference is handed over toproc->cwd.The way to decide is:
After unlocking, do you still need this inode, or do you need to hand the reference to someone else? Yes → iunlock() No → iunlockput()
The misunderstanding above also led to my initial incorrect implementation (including open()).
So here is the implementation of symlink():
代码
uint64
sys_symlink(void)
{
char path[MAXPATH], target[MAXPATH];
struct inode *ip;
if(argstr(1, path, MAXPATH) < 0 || argstr(0, target, MAXPATH) < 0) {
return -1;
}
begin_op();
// 这段代码不需要,`create()` 自己会检查目标路径是否已存在
// if (namei(path) != 0) {
// end_op();
// return -1;
// }
ip = create(path, T_SYMLINK, 0, 0);
if (ip == 0) {
end_op();
return -1;
}
int len = strlen(target) + 1;
if (writei(ip, 0, (uint64)target, 0, len) != len) {
end_op();
return -1;
}
// iupdate(ip); 不需要,writei() 有
iunlockput(ip);
end_op();
return 0;
}Modifying open()
Because if the path passed to open() is actually just a symbolic link, you certainly can't directly return the fd corresponding to the symbolic link's inode; instead you should return the one corresponding to the target it points to. Just add special handling here.
代码
uint64
sys_open(void)
{
char path[MAXPATH];
int fd, omode;
struct file *f;
struct inode *ip;
int n;
argint(1, &omode);
if((n = argstr(0, path, MAXPATH)) < 0)
return -1;
begin_op();
if(omode & O_CREATE){
ip = create(path, T_FILE, 0, 0);
if(ip == 0){
end_op();
return -1;
}
} else {
if((ip = namei(path)) == 0){
end_op();
return -1;
}
ilock(ip);
// 目录检查放在展开之后
}
// ========
int depth = 0;
while (ip->type == T_SYMLINK && omode != O_NOFOLLOW) {
char target[MAXPATH];
if (readi(ip, 0, (uint64)target, 0, MAXPATH) <= 0) {
iunlockput(ip);
end_op();
return -1;
}
iunlockput(ip);
if ((ip = namei(target)) == 0) {
end_op();
return -1;
}
ilock(ip);
depth++;
if (depth > 10) {
iunlockput(ip);
end_op();
return -1;
}
}
if(ip->type == T_DIR && omode != O_RDONLY){
iunlockput(ip);
end_op();
return -1;
}
// ========
if(ip->type == T_DEVICE && (ip->major < 0 || ip->major >= NDEV)){
iunlockput(ip);
end_op();
return -1;
}
if((f = filealloc()) == 0 || (fd = fdalloc(f)) < 0){
if(f)
fileclose(f);
iunlockput(ip);
end_op();
return -1;
}
if(ip->type == T_DEVICE){
f->type = FD_DEVICE;
f->major = ip->major;
} else {
f->type = FD_INODE;
f->off = 0;
}
f->ip = ip;
f->readable = !(omode & O_WRONLY);
f->writable = (omode & O_WRONLY) || (omode & O_RDWR);
if((omode & O_TRUNC) && ip->type == T_FILE){
itrunc(ip);
}
iunlock(ip);
end_op();
return fd;
}The possible problem here is not knowing where to insert the code. My suggestion is to analyze the situations corresponding to each of the flags xv6 has, and then follow the branches to analyze.

Appendix: the initial incorrect implementation
代码
uint64
sys_symlink(void)
{
char path[MAXPATH], target[MAXPATH];
struct inode *ip;
if(argstr(0, path, MAXPATH) < 0 || argstr(1, target, MAXPATH) < 0) {
return -1;
}
begin_op();
if (namei(path) != 0) {
end_op();
return -1;
}
ip = create(path, T_SYMLINK, 0, 0);
if (ip == 0) {
end_op();
return -1;
}
if (writei(ip, 0, (uint64)target, 0, MAXPATH) < 0) {
end_op();
return -1;
}
iupdate(ip);
iunlock(ip);
end_op();
return 0;
}
uint64
sys_open(void)
{
char path[MAXPATH];
int fd, omode;
struct file *f;
struct inode *ip;
int n;
argint(1, &omode);
if((n = argstr(0, path, MAXPATH)) < 0)
return -1;
begin_op();
if(omode & O_CREATE){
ip = create(path, T_FILE, 0, 0);
if(ip == 0){
end_op();
return -1;
}
} else {
if((ip = namei(path)) == 0){
end_op();
return -1;
}
ilock(ip);
if(ip->type == T_DIR && omode != O_RDONLY){
iunlockput(ip);
end_op();
return -1;
}
}
// ========
ip = namei(path);
if (ip == 0) {
end_op();
return -1;
}
ilock(ip);
int depth = 0;
while (ip->type == T_SYMLINK && omode != O_NOFOLLOW) {
char target[MAXPATH];
if (readi(ip, 0, (uint64)target, 0, MAXPATH) < 0) {
iunlockput(ip);
end_op();
return -1;
}
iunlockput(ip);
if ((ip = namei(target)) == 0) {
end_op();
return -1;
}
ilock(ip);
depth++;
if (depth > 10) {
iunlockput(ip);
end_op();
return -1;
}
}
// ========
if(ip->type == T_DEVICE && (ip->major < 0 || ip->major >= NDEV)){
iunlockput(ip);
end_op();
return -1;
}
if((f = filealloc()) == 0 || (fd = fdalloc(f)) < 0){
if(f)
fileclose(f);
iunlockput(ip);
end_op();
return -1;
}
if(ip->type == T_DEVICE){
f->type = FD_DEVICE;
f->major = ip->major;
} else {
f->type = FD_INODE;
f->off = 0;
}
f->ip = ip;
f->readable = !(omode & O_WRONLY);
f->writable = (omode & O_WRONLY) || (omode & O_RDWR);
if((omode & O_TRUNC) && ip->type == T_FILE){
itrunc(ip);
}
iunlock(ip);
end_op();
return fd;
}