之前在Linux驅動之按鍵驅動編寫(中斷方式)中編寫的驅動程序,如果沒有按鍵按下。read函數是永遠沒有返回值的,現在想要做到即使沒有按鍵按下,在一定時間之后也會有返回值。要做到這種功能,可以使用poll機制。分以下幾部來介紹poll機制
1、poll機制的使用,編寫測試程序
2、poll機制的調用過程分析
3、poll機制的驅動編寫
1、poll機制的使用,編寫測試程序。
直接看到測試程序的代碼。
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <poll.h> /* *usage ./buttonstest */ int main(int argc, char **argv) { int fd; char* filename="dev/buttons"; unsigned char key_val; unsigned long cnt=0; int ret; struct pollfd *key_fds;//定義一個pollfd結構體key_fds fd = open(filename, O_RDWR);//打開dev/firstdrv設備文件 if (fd < 0)//小於0說明沒有成功 { printf("error, can't open %s\n", filename); return 0; } if(argc !=1) { printf("Usage : %s ",argv[0]); return 0; } key_fds ->fd = fd;//文件 key_fds->events = POLLIN;//poll直接返回需要的條件 while(1) { ret = poll(key_fds, 1, 5000);//調用sys_poll系統調用,如果5S內沒有產生POLLIN事件,那么返回,如果有POLLIN事件,直接返回 if(!ret) { printf("time out\n"); } else { if(key_fds->revents==POLLIN)//如果返回的值是POLLIN,說明有數據POLL才返回的 { read(fd, &key_val, 1); //讀取按鍵值 printf("key_val: %x\n",key_val);//打印 } } } return 0; }
從代碼可以看出,相比較第三個測試程序third_test。程序源碼見Linux驅動之按鍵驅動編寫(中斷方式),多定義了一個pollfd 結構體,它的結構如下:
struct pollfd { int fd; //打開的文件節點 short events; //poll直接返回,需要產生的事件 short revents; //poll函數返回的事件 };
測試程序調用C庫函數的poll函數時會用到這個結構體poll(key_fds, 1, 5000);其中第一個參數就是這個結構體的指針,對於多個目標文件來說是首地址,第二個參數為poll等待的文件個數,第三個參數為超時時間。那么poll是怎么實現的呢?
2、poll機制的調用過程分析
應用層利用C庫函數調用poll函數的時候,會通過swi軟件中斷進入到內核層,然后調用sys_poll系統調用。它位於fs\Select.c中。
asmlinkage long sys_poll(struct pollfd __user *ufds, unsigned int nfds, long timeout_msecs) { s64 timeout_jiffies; if (timeout_msecs > 0) {//超時參數驗證以及處理 #if HZ > 1000 /* We can only overflow if HZ > 1000 */ if (timeout_msecs / 1000 > (s64)0x7fffffffffffffffULL / (s64)HZ) timeout_jiffies = -1; else #endif timeout_jiffies = msecs_to_jiffies(timeout_msecs); } else { /* Infinite (< 0) or no (0) timeout */ timeout_jiffies = timeout_msecs; } return do_sys_poll(ufds, nfds, &timeout_jiffies);//調用do_sys_poll
}
可以看到sys_poll系統調用經過一些參數的驗證之后直接調用了do_sys_poll,對於do_sys_poll做一個簡單的介紹,它也位於fs\Select.c,它主要調用poll_initwait、do_poll函數
653 int do_sys_poll(struct pollfd __user *ufds, unsigned int nfds, s64 *timeout) 654 { ... ... 670 poll_initwait(&table);//最終table->pt->qproc = __pollwait ... ... 709 fdcount = do_poll(nfds, head, &table, timeout); ... ... 737 }
先看到poll_initwait函數,它的主要功能是將table->pt->qproc = __pollwait,后面會用到
void poll_initwait(struct poll_wqueues *pwq) { init_poll_funcptr(&pwq->pt, __pollwait);//pt->qproc = qproc;即table->pt->qproc = __pollwait pwq->error = 0; pwq->table = NULL; pwq->inline_index = 0; }
接着看到do_poll(nfds, head, &table, timeout),這里面的主要函數是do_pollfd(pfd, pt)與schedule_timeout(__timeout);下面分別介紹
static int do_poll(unsigned int nfds, struct poll_list *list, struct poll_wqueues *wait, s64 *timeout) { int count = 0; poll_table* pt = &wait->pt; /* Optimise the no-wait case */ if (!(*timeout))//處理沒有超時的情況 pt = NULL; for (;;) {//大循環,一直等待超時時間到或者有相應的事件觸發喚醒進程 struct poll_list *walk; long __timeout; set_current_state(TASK_INTERRUPTIBLE);//設置當前進程為可中斷狀態 for (walk = list; walk != NULL; walk = walk->next) {//循環查找poll_fd列表 struct pollfd * pfd, * pfd_end; pfd = walk->entries; pfd_end = pfd + walk->len; for (; pfd != pfd_end; pfd++) { /* * Fish for events. If we found one, record it * and kill the poll_table, so we don't * needlessly register any other waiters after * this. They'll get immediately deregistered * when we break out and return. */ if (do_pollfd(pfd, pt)) {//pwait = table->pt。調用驅動的poll函數獲取mask值,另外將進程放入等待隊列 count++; pt = NULL; } } } /* * All waiters have already been registered, so don't provide * a poll_table to them on the next loop iteration. */ pt = NULL; if (count || !*timeout || signal_pending(current))//如果超時時間到了或者沒有poll_fd或者事件發生了,直接退出 break; count = wait->error; if (count) break; if (*timeout < 0) { /* Wait indefinitely */ __timeout = MAX_SCHEDULE_TIMEOUT; } else if (unlikely(*timeout >= (s64)MAX_SCHEDULE_TIMEOUT-1)) { /* * Wait for longer than MAX_SCHEDULE_TIMEOUT. Do it in * a loop */ __timeout = MAX_SCHEDULE_TIMEOUT - 1; *timeout -= __timeout; } else { __timeout = *timeout; *timeout = 0; } __timeout = schedule_timeout(__timeout);//設置超時時間,進程休眠 if (*timeout >= 0) *timeout += __timeout; } __set_current_state(TASK_RUNNING);//重新運行調用sys_poll的進程 return count; }
現在看到do_pollfd(pfd, pt)函數,它最終會調用驅動層的poll函數file->f_op->poll(file, pwait),這就跟驅動扯上關系了, __pollwait在這里就被用到了,它將當前進程放入驅動層的等待列表,但是這時候當前進程還未休眠。
static inline unsigned int do_pollfd(struct pollfd *pollfd, poll_table *pwait) { unsigned int mask; int fd; mask = 0; fd = pollfd->fd;//根據pollfd找到文件節點 if (fd >= 0) { int fput_needed; struct file * file; file = fget_light(fd, &fput_needed);//根據文件節點fd找到文件的file結構 mask = POLLNVAL; if (file != NULL) { mask = DEFAULT_POLLMASK; if (file->f_op && file->f_op->poll) mask = file->f_op->poll(file, pwait);//根據file結構找到驅動的f_op結構,然后調用它的poll函數,並且返回mask //這個函數就跟驅動相關了,猜測調用poll_wati將當前進程放到驅動的等待列表。如果有數據的話,那么設置mask = POLLIN /* Mask out unneeded events. */ mask &= pollfd->events | POLLERR | POLLHUP; fput_light(file, fput_needed); } } pollfd->revents = mask; return mask; }
繼續看到schedule_timeout(__timeout)函數,它位於kernel\Timer.c,它的主要作用就是設置一個定時器,當超時時間到的時候利用定時器的函數將進程喚醒。最后它還調用schedule(),進行進程的切換,因為在do_poll中已經被設置為TASK_INTERRUPTIBLE狀態了。
fastcall signed long __sched schedule_timeout(signed long timeout) { struct timer_list timer; unsigned long expire; switch (timeout) { case MAX_SCHEDULE_TIMEOUT: /* * These two special cases are useful to be comfortable * in the caller. Nothing more. We could take * MAX_SCHEDULE_TIMEOUT from one of the negative value * but I' d like to return a valid offset (>=0) to allow * the caller to do everything it want with the retval. */ schedule(); goto out; default: /* * Another bit of PARANOID. Note that the retval will be * 0 since no piece of kernel is supposed to do a check * for a negative retval of schedule_timeout() (since it * should never happens anyway). You just have the printk() * that will tell you if something is gone wrong and where. */ if (timeout < 0) { printk(KERN_ERR "schedule_timeout: wrong timeout " "value %lx\n", timeout); dump_stack(); current->state = TASK_RUNNING; goto out; } } expire = timeout + jiffies; setup_timer(&timer, process_timeout, (unsigned long)current);//設置一個定時器,處理函數為process_timeout,傳入的參數為當前進程,作用是時間到喚醒當前進程 __mod_timer(&timer, expire);//修改定時器的定時時間 schedule();//調度其它進程運行 del_singleshot_timer_sync(&timer);//刪除定時器 timeout = expire - jiffies; out: return timeout < 0 ? 0 : timeout; }
這就是整個poll機制的過程,接下來需要編寫驅動程序file_operations 的poll函數
3、poll機制的驅動編寫
直接看到源代碼,從源碼可以看到相比較third_drv.c驅動,這個在forth_drv_ops結構體中增加了一個forth_drv_poll函數,它的作用就是將調用sys_poll系統調用的的進程放入button_waitq等待隊列。如果有按鍵值改變,那么將返回值設為POLLIN。這個函數在do_pollfd被調用。
#include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/init.h> #include <asm/io.h> //含有iomap函數iounmap函數 #include <asm/uaccess.h>//含有copy_from_user函數 #include <linux/device.h>//含有類相關的處理函數 #include <asm/arch/regs-gpio.h>//含有S3C2410_GPF0等相關的 #include <linux/irq.h> //含有IRQ_HANDLED\IRQ_TYPE_EDGE_RISING #include <asm-arm/irq.h> //含有IRQT_BOTHEDGE觸發類型 #include <linux/interrupt.h> //含有request_irq、free_irq函數 #include <linux/poll.h> //#include <asm-arm\arch-s3c2410\irqs.h> static struct class *forth_drv_class;//類 static struct class_device *forth_drv_class_dev;//類下面的設備 static int forthmajor; static unsigned long *gpfcon = NULL; static unsigned long *gpfdat = NULL; static unsigned long *gpgcon = NULL; static unsigned long *gpgdat = NULL; static unsigned int key_val; struct pin_desc { unsigned int pin; unsigned int key_val; }; static struct pin_desc pins_desc[4] = { {S3C2410_GPF0,0x01}, {S3C2410_GPF2,0x02}, {S3C2410_GPG3,0x03}, {S3C2410_GPG11,0x04} }; unsigned int ev_press; DECLARE_WAIT_QUEUE_HEAD(button_waitq);//注冊一個等待隊列button_waitq /* *0x01、0x02、0x03、0x04表示按鍵被按下 */ /* *0x81、0x82、0x83、0x84表示按鍵被松開 */ /* *利用dev_id的值為pins_desc來判斷是哪一個按鍵被按下或松開 */ static irqreturn_t buttons_irq(int irq, void *dev_id) { unsigned int pin_val; struct pin_desc * pin_desc = (struct pin_desc *)dev_id;//取得哪個按鍵被按下的狀態 pin_val = s3c2410_gpio_getpin(pin_desc->pin); if(pin_val) //按鍵松開 key_val = 0x80 | pin_desc->key_val; else key_val = pin_desc->key_val; wake_up_interruptible(&button_waitq); /* 喚醒休眠的進程 */ ev_press = 1; return IRQ_HANDLED; } static int forth_drv_open (struct inode * inode, struct file * file) { int ret; ret = request_irq(IRQ_EINT0, buttons_irq, IRQT_BOTHEDGE, "s1", (void * )&pins_desc[0]); if(ret) { printk("open failed 1\n"); return -1; } ret = request_irq(IRQ_EINT2, buttons_irq, IRQT_BOTHEDGE, "s2", (void * )& pins_desc[1]); if(ret) { printk("open failed 2\n"); return -1; } ret = request_irq(IRQ_EINT11, buttons_irq, IRQT_BOTHEDGE, "s3", (void * )&pins_desc[2]); if(ret) { printk("open failed 3\n"); return -1; } ret = request_irq(IRQ_EINT19, buttons_irq, IRQT_BOTHEDGE, "s4", (void * )&pins_desc[3]); if(ret) { printk("open failed 4\n"); return -1; } return 0; } static int forth_drv_close(struct inode * inode, struct file * file) { free_irq(IRQ_EINT0 ,(void * )&pins_desc[0]); free_irq(IRQ_EINT2 ,(void * )& pins_desc[1]); free_irq(IRQ_EINT11 ,(void * )&pins_desc[2]); free_irq(IRQ_EINT19 ,(void * )&pins_desc[3]); return 0; } static ssize_t forth_drv_read(struct file * file, char __user * userbuf, size_t count, loff_t * off) { int ret; if(count != 1) { printk("read error\n"); return -1; } // wait_event_interruptible(button_waitq, ev_press);//將當前進程放入等待隊列button_waitq中 ret = copy_to_user(userbuf, &key_val, 1); ev_press = 0;//按鍵已經處理可以繼續睡眠 if(ret) { printk("copy error\n"); return -1; } return 1; } static unsigned int forth_drv_poll(struct file *file, poll_table *wait) { unsigned int ret = 0; poll_wait(file, &button_waitq, wait);//將當前進程放到button_waitq列表 if(ev_press) ret |=POLLIN;//說明有數據被取到了 return ret; } static struct file_operations forth_drv_ops = { .owner = THIS_MODULE, .open = forth_drv_open, .read = forth_drv_read, .release = forth_drv_close, .poll = forth_drv_poll, }; static int forth_drv_init(void) { forthmajor = register_chrdev(0, "buttons", &forth_drv_ops);//注冊驅動程序 if(forthmajor < 0) printk("failes 1 buttons_drv register\n"); forth_drv_class = class_create(THIS_MODULE, "buttons");//創建類 if(forth_drv_class < 0) printk("failes 2 buttons_drv register\n"); forth_drv_class_dev = class_device_create(forth_drv_class, NULL, MKDEV(forthmajor,0), NULL,"buttons");//創建設備節點 if(forth_drv_class_dev < 0) printk("failes 3 buttons_drv register\n"); gpfcon = ioremap(0x56000050, 16);//重映射 gpfdat = gpfcon + 1; gpgcon = ioremap(0x56000060, 16);//重映射 gpgdat = gpgcon + 1; printk("register buttons_drv\n"); return 0; } static void forth_drv_exit(void) { unregister_chrdev(forthmajor,"buttons"); class_device_unregister(forth_drv_class_dev); class_destroy(forth_drv_class); iounmap(gpfcon); iounmap(gpgcon); printk("unregister buttons_drv\n"); } module_init(forth_drv_init); module_exit(forth_drv_exit); MODULE_LICENSE("GPL");
再回到測試程序,可以看到如果在5s內按鍵沒有按鍵則也會返回,而不會一直睡眠。
具體程序的編譯參考Linux驅動之按鍵驅動編寫(中斷方式)。
以上就是poll機制的實現過程以及使用方法。