VFS(Virtual File System Switch)以面向對象設計統一管理 ext4、xfs、btrfs、procfs、sysfs 等數十種文件系統。核心抽象為四大對象:super_block、inode、dentry、file。本文深入內核源碼(include/linux/fs.h),逐一拆解數據結構、關鍵字段、操作函數表與實例化流程。
struct super_block {
struct list_head s_list; // 全局超級塊雙向鏈表
struct list_head s_inodes; // 本文件系統所有 inode 鏈表
spinlock_t s_lock; // 保護上述鏈表
struct super_operations *s_op; // 操作函數表(核心)
unsigned long s_flags; // 掛載標誌(MS_RDONLY 等)
unsigned long s_magic; // 魔數(識別文件系統類型)
struct dentry *s_root; // 掛載點根目錄 dentry
void *s_fs_info; // 具體文件系統私有數據(如 ext4_sb_info)
int s_dirt; // 髒標誌,需回寫磁盤
// ... 時間戳、配額、設備號等
};
super_operationsstruct super_operations {
struct inode *(*alloc_inode)(struct super_block *sb);
void (*destroy_inode)(struct inode *);
void (*dirty_inode)(struct inode *);
int (*write_inode)(struct inode *, struct writeback_control *);
void (*evict_inode)(struct inode *);
void (*put_super)(struct super_block *);
void (*write_super)(struct super_block *);
int (*sync_fs)(struct super_block *, int wait);
int (*statfs)(struct dentry *, struct kstatfs *);
int (*remount_fs)(struct super_block *, int *, char *);
// ... 配額、凍結/解凍、顯示選項等
};
調用範例:sb->s_op->write_super(sb);(C 語言模擬虛函數,需傳 this 指針 sb)。
alloc_super() 分配 → 讀取磁盤超級塊填充 → 掛入全局 super_blocks 鏈表。sync_fs() 定期回寫髒 inode/超級塊。put_super() 釋放資源 → 從全局鏈表移除 → destroy_super() 釋放結構體。| 字段 | 含義 | 用戶可見命令 |
|---|---|---|
| i_ino | inode 號 | ls -i |
| i_mode | 文件類型+權限 | ls -l |
| i_uid/i_gid | 擁有者/組 | ls -n |
| i_size | 文件大小 | ls -l |
| i_atime/i_mtime/i_ctime | 訪問/修改內容/修改屬性時間 | ls -lu/-l/-lc |
| i_nlink | 硬鏈接數 | ls -l 第2欄 |
| i_blocks | 佔用塊數 | ls -s |
| i_sb | 指向超級塊 | 內核內部 |
| i_op | inode 操作表 | 創建/刪除/重命名/鏈接等 |
| i_fop | 文件操作表 | open/read/write/mmap 等 |