2.2 struct file_operations

在开始讨论字符设备驱动程序内核机制前,有必要先交代一下struct file_operations数据结构,其定义如下:

<include/linux/fs.h>
struct file_operations {
    struct module *owner;
    loff_t (*llseek) (struct file *, loff_t, int);
    ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
    ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
    ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
    ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
    int (*readdir) (struct file *, void *, filldir_t);
    unsigned int (*poll) (struct file *, struct poll_table_struct *);
    long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
    long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
    int (*mmap) (struct file *, struct vm_area_struct *);
    int (*open) (struct inode *, struct file *);
    int (*flush) (struct file *, fl_owner_t id);
    int (*release) (struct inode *, struct file *);
    int (*fsync) (struct file *, int datasync);
    int (*aio_fsync) (struct kiocb *, int datasync);
    int (*fasync) (int, struct file *, int);
    int (*lock) (struct file *, int, struct file_lock *);
    ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
    unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long,
                                  unsigned long);
    int (*check_flags)(int);
    int (*flock) (struct file *, int, struct file_lock *);
    ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
    ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
    int (*setlease)(struct file *, long, struct file_lock **);
    long (*fallocate)(struct file *file, int mode, loff_t offset, loff_t len);
};

可以看到,struct file_operations的成员变量几乎全是函数指针,因为本书的后续章节会陆续讨论到这个结构体中绝大多数成员的实现,所以这里不再解释其各自的用途。读者也许很快会发现,现实中字符设备驱动程序的编写,其实基本上是围绕着如何实现struct file_operations中的那些函数指针成员而展开的。通过内核文件系统组件在其间的穿针引线,应用程序中对文件类函数的调用,比如read()等,将最终被转接到struct file_operations中对应函数指针的具体实现上。

该结构中唯一非函数指针类成员owner,表示当前struct file_operations对象所属的内核模块,几乎所有的设备驱动程序都会用THIS_MODULE宏给owner赋值,该宏的定义为:

<include/linux/module.h>
#define THIS_MODULE (&__this_module)

__this_module是内核模块的编译工具链为当前模块产生的struct module类型对象,所以THIS_MODULE实际上是当前内核模块对象的指针,file_operations中的owner成员可以避免当file_operations中的函数正在被调用时,其所属的模块被从系统中卸载掉。如果一个设备驱动程序不是以模块的形式存在,而是被编译进内核,那么THIS_MODULE将被赋值为空指针,没有任何作用。