xv6 的 VFS
磁盘结构
磁盘存储布局如下图所示
- boot: 存储系统启动引导程序
- super: 记录总容量、inode数量等文件系统全局元数据
- log: 记录系统日志
- inodes: 存储文件元数据(如权限、大小、数据块位置)的区域,每个文件对应一个inode
- bitmap: 用一个比特位标记一个数据块是否被使用,用于快速分配和回收空间
- Data: 实际存储目录结构和文件内容的地方

Buffer Cache
Buffer Cache 在 xv6 中用于缓存磁盘的数据,减少重复读写的次数,其在xv6中使用如下结构体表示:
buf.h
struct buf {
int valid; // 内存与磁盘存储的内容是否一致
int disk; // does disk "own" buf?
uint dev;
uint blockno;
struct sleeplock lock;
uint refcnt;
struct buf *prev; // LRU cache list
struct buf *next;
uchar data[BSIZE];
};
xv6 使用双向链表组织 Buffer Cache
bio.c
struct {
struct spinlock lock;
struct buf buf[NBUF];
// Linked list of all buffers, through prev/next.
// Sorted by how recently the buffer was used.
// head.next is most recent, head.prev is least.
struct buf head;
} bcache;
日志系统
inode
inode 在磁盘中用于存储文件的元数据,在 xv6 中,使用dinode
结构体表示磁盘中的inode
fs.h/dinode
// On-disk inode structure
struct dinode {
short type; // File type
short major; // Major device number (T_DEVICE only)
short minor; // Minor device number (T_DEVICE only)
short nlink; // Number of links to inode in file system
uint size; // Size of file (bytes)
uint addrs[NDIRECT+1]; // Data block addresses
};
inode
结构体表示内存对磁盘inode的拷贝,lock
用于同步磁盘dinode的数据字段
fs.h/inode
// in-memory copy of an inode
struct inode {
uint dev; // Device number
uint inum; // Inode number
int ref; // Reference count
struct sleeplock lock; // protects everything below here
int valid; // inode has been read from disk?
short type; // copy of disk inode
short major;
short minor;
short nlink;
uint size;
uint addrs[NDIRECT+1];
};
创建文件
struct inode* ialloc(uint dev, short type) {
int inum;
struct buf *bp;
struct dinode *dip;
for(inum = 1; inum < sb.ninodes; inum++){
bp = bread(dev, IBLOCK(inum, sb));
dip = (struct dinode*)bp->data + inum%IPB;
if(dip->type == 0){ // a free inode
memset(dip, 0, sizeof(*dip));
dip->type = type;
log_write(bp); // mark it allocated on the disk
brelse(bp);
return iget(dev, inum);
}
brelse(bp);
}
panic("ialloc: no inodes");
}