之前在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机制的实现过程以及使用方法。