1 字符設備驅動程序框架簡介
我們在學習 C 語言的時候,知道每個應用程序的入口函數,即第一個被執行的函數是 main函數,那么,我們自己的驅動程序,哪個函數是入口函數呢?
在寫驅動程序的時候,如果函數的名字可以任意取,常常為 xxxx_init(),當實現好這個 xxxx_init()函數以后,內核其實并不知道這個就是我們驅動的入口函數,因此我們要想辦法告訴內核,我們的入口函數是哪個?我們通過 module_init()函數來告訴內核,具體如下。
module_init(RT5350_drv_init);
通過上面的修飾以后, RT5350_drv_init()這個函數就變成了我們的驅動程序的入口函數了。當然,有入口函數,自然還需要一個出口函數,我們通過 module_exit()函數來告訴內核,具體如下。
module_exit(RT5350_drv_exit);
從上一章中,我們知道,應用程序是通過 open、read、write ...函數來和我們的驅動程序進行交互的,那么我們的驅動程序是怎么給應用程序提供這些接口的呢?我們在寫驅動程序的時候,我們首先需要定義出一個 file_operations 結構體,該結構體便是驅動和應用程序交互的接口。具體定義如下。
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 *, loff_t, loff_t, 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);
};