1 字符設(shè)備驅(qū)動(dòng)程序框架簡(jiǎn)介
我們?cè)趯W(xué)習(xí) C 語(yǔ)言的時(shí)候,知道每個(gè)應(yīng)用程序的入口函數(shù),即第一個(gè)被執(zhí)行的函數(shù)是 main函數(shù),那么,我們自己的驅(qū)動(dòng)程序,哪個(gè)函數(shù)是入口函數(shù)呢?
在寫驅(qū)動(dòng)程序的時(shí)候,如果函數(shù)的名字可以任意取,常常為 xxxx_init(),當(dāng)實(shí)現(xiàn)好這個(gè) xxxx_init()函數(shù)以后,內(nèi)核其實(shí)并不知道這個(gè)就是我們驅(qū)動(dòng)的入口函數(shù),因此我們要想辦法告訴內(nèi)核,我們的入口函數(shù)是哪個(gè)?我們通過 module_init()函數(shù)來(lái)告訴內(nèi)核,具體如下。
module_init(RT5350_drv_init);
通過上面的修飾以后, RT5350_drv_init()這個(gè)函數(shù)就變成了我們的驅(qū)動(dòng)程序的入口函數(shù)了。當(dāng)然,有入口函數(shù),自然還需要一個(gè)出口函數(shù),我們通過 module_exit()函數(shù)來(lái)告訴內(nèi)核,具體如下。
module_exit(RT5350_drv_exit);
從上一章中,我們知道,應(yīng)用程序是通過 open、read、write ...函數(shù)來(lái)和我們的驅(qū)動(dòng)程序進(jìn)行交互的,那么我們的驅(qū)動(dòng)程序是怎么給應(yīng)用程序提供這些接口的呢?我們?cè)趯戲?qū)動(dòng)程序的時(shí)候,我們首先需要定義出一個(gè) file_operations 結(jié)構(gòu)體,該結(jié)構(gòu)體便是驅(qū)動(dòng)和應(yīng)用程序交互的接口。具體定義如下。
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);
};