struct file 定義在 include/linux/fs.h。它代表一個已開啟的檔案:系統中每個被開啟的檔案,在核心空間都有一個對應的 struct file。這個結構由核心在 open 時建立,並傳給所有要在該檔案上操作的函式;當這個檔案的所有實例都關閉後,核心便釋放它。
在核心與驅動原始碼中,struct file 的指標通常命名為 file 或 filp。
struct file {
union {
struct list_head fu_list; // 檔案物件鏈表指標
struct rcu_head fu_rcuhead; // RCU(Read-Copy Update)鎖機制
} f_u;
struct path f_path; // 含 dentry 與 mnt,用於確定檔案路徑
#define f_dentry f_path.dentry // 當前檔案的 dentry 結構
#define f_vfsmnt f_path.mnt // 當前檔案所在檔案系統的掛載根目錄
const struct file_operations *f_op; // 與該檔案相關的操作函式
atomic_t f_count; // 引用計數(多少行程開啟了該檔)
unsigned int f_flags; // 對應 open 時指定的 flag
mode_t f_mode; // 讀寫模式(open 的 mode 參數)
loff_t f_pos; // 當前檔案指標位置
struct fown_struct f_owner; // 透過信號進行 I/O 通知的資料
unsigned int f_uid, f_gid; // 檔案所有者 ID 與所屬組 ID
struct file_ra_state f_ra; // 檔案預讀相關
unsigned long f_version; // 檔案版本號,每次使用後遞增
#ifdef CONFIG_SECURITY
void *f_security;
#endif
void *private_data; // 用來指向配置好的私有資料
#ifdef CONFIG_EPOLL
struct list_head f_ep_links; // eventpoll 用來串起所有 hook
spinlock_t f_ep_lock;
#endif
struct address_space *f_mapping;
};
f_u:一個 union。fu_list 是檔案物件鏈表指標(見 linux/include/linux/list.h),全系統所有開啟的 file 會串在一起;fu_rcuhead 供 RCU 機制使用——RCU 是 2.6 核心引入的新鎖機制,讀取端幾乎零成本,適合讀多寫少的場景。
f_path:包含 dentry 與 mnt 兩個成員,合起來才能確定檔案的完整路徑。f_dentry 指向當前檔案的 dentry 結構,f_vfsmnt 則是該檔案所在檔案系統的掛載根目錄。
f_op:指向 file_operations,也就是 open、read、write、ioctl 這一整套操作函式,是 VFS 抽象層向下分派呼叫的入口。
f_count:引用計數,記錄有多少個地方打開了這個檔案,歸零時核心才回收。
f_flags:open 時傳入的旗標(O_RDONLY、O_WRONLY、O_NONBLOCK 等)。f_mode:讀寫模式,對應 open 的 mode 參數。
f_pos:當前檔案指標位置,也就是 read/write 的起點,每次 I/O 後會前移。
f_owner:透過信號做非同步 I/O 通知時所需的資料,記錄誰該收到 SIGIO。
f_uid / f_gid:檔案擁有者與所屬組 ID。
f_ra:預讀(readahead)狀態,定義於 linux/include/linux/fs.h,用來提升循序讀取效能。
f_version:版本號,每次使用後遞增,可用來偵測快取是否過期。
f_security:開啟 CONFIG_SECURITY 時存在,供 SELinux 等安全模組掛載自己的上下文。
private_data:通用私有資料指標,驅動常拿它指向自己配置的結構。
f_ep_links / f_ep_lock:僅在 CONFIG_EPOLL 下存在,由 fs/eventpoll.c 用來把該檔案掛上所有等待的 epoll 實例,並以自旋鎖保護。
f_mapping:指向該檔案的 address_space,也就是頁快取在核心中的落點,page cache 的頁就是靠它組織的。