Poll 机制的简单分析

参考:韦东山老师视频教程

用户空间应用程序向设备驱动请求数据时,一般有以下几种方式:

1.不断查询,条件不满足的情况下就是死循环,这种情况下非常耗费CPU。

2.休眠唤醒的方式,如果条件不满足,应用程序则一直休眠下去。

3.poll机制,如果条件不满足,休眠指定时间,休眠时间内条件满足唤醒进程,条件一直不满足,达到指定时间,则自动唤醒。

4,异步通知,应用程序注册信号处理函数,驱动程序发信号。

poll在linux内核中的实现过程。

    所有的系统调用,基于都可以在它的名字前加上“sys_”前缀,这就是它在内核中对应的函数。比如系统调用open、read、write、poll,与之对应的内核函数为:sys_open、sys_read、sys_write、sys_poll。

    对于系统调用poll或select,他们对应的内核函数都是sys_poll。分析sys_poll,即可理解poll机制。

1.sys_poll函数在include/linux/syscalls.h中声明

asmlinkage long sys_poll(struct pollfd __user *ufds, unsigned int nfds,
				int timeout);

在系统调用表arch\arm\kernel\calls.S中调用

		CALL(sys_poll)//系统调用跳转表的一项

sys_poll函数位于fs/select.c文件中,SYSCALL_DEFINE3是有3个参数的系统调的宏定义。

SYSCALL_DEFINE3(poll, struct pollfd __user *, ufds, unsigned int, nfds,
		int, timeout_msecs)
{
	struct timespec end_time, *to = NULL;
	int ret;

	if (timeout_msecs >= 0) {
		to = &end_time;
		poll_select_set_timeout(to, timeout_msecs / MSEC_PER_SEC,     //对timeout参数稍作处理
			NSEC_PER_MSEC * (timeout_msecs % MSEC_PER_SEC));
	}

	ret = do_sys_poll(ufds, nfds, to);
}

它对超时参数稍作处理后,直接调用do_sys_poll。

2,do_sys_poll函数也位于fs/select.c文件中,我们忽略其他代码。

int do_sys_poll(struct pollfd __user *ufds, unsigned int nfds,
		struct timespec *end_time)
{

	poll_initwait(&table);
	fdcount = do_poll(nfds, head, &table, end_time);
	poll_freewait(&table);

}

poll_initwait函数非常简单,它初始化一个poll_wqueues 变量table;

poll_initwait > init_poll_funcptr(&pwq->pt, __pollwait);  > pt->_qproc = qproc;

即table->pt->qproc=__pollwait,__pollwait将在驱动的poll函数里用到。

void poll_initwait(struct poll_wqueues *pwq)
{
	init_poll_funcptr(&pwq->pt, __pollwait);
        ......
}
static inline void init_poll_funcptr(poll_table *pt, poll_queue_proc qproc)
{
	pt->_qproc = qproc;
	pt->_key   = ~0UL; /* all events enabled */
}
接着往下看,do_poll函数位于fs/select.c文件中,代码如下:
static int do_poll(unsigned int nfds,  struct poll_list *list,
		   struct poll_wqueues *wait, struct timespec *end_time)
{
......

	for (;;) {                                             //死循环,它的退出条件是if (count || timed_out)为真
		struct poll_list *walk;                        

		for (walk = list; walk != NULL; walk = walk->next) {
			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 poll_table->_qproc, 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)) {     //重点是这里的do_pollfd ,如果这里返回真,则count++,循环退出。
					count++;
					pt->_qproc = NULL;
				}
			}
		}
		/*
		 * All waiters have already been registered, so don't provide
		 * a poll_table->_qproc to them on the next loop iteration.
		 */
		pt->_qproc = NULL;
		if (!count) {
			count = wait->error;
			if (signal_pending(current))
				count = -EINTR;
		}
		if (count || timed_out)  //count非0,表示上文中的do_pollfd至少有一个成功。timeout超时以后也退出循环。
			break;

		/*
		 * If this is the first loop and we have a timeout
		 * given, then we convert to ktime_t and set the to
		 * pointer to the expiry value.
		 */
		if (end_time && !to) {
			expire = timespec_to_ktime(*end_time);
			to = &expire;
		}

		if (!poll_schedule_timeout(wait, TASK_INTERRUPTIBLE, to, slack)) //让本进程休眠一段时间
			timed_out = 1;
	}
	return count;
}

在程序的最后调用poll_schedule_timeout,让本进程休眠一段时间,注意应用程序执行poll调用后,如果timeout没超时或者count为0则进程会进入休眠。那么谁会唤醒进程呢?除了休眠到指定时间被系统唤醒外,还可以被驱动程序唤醒----这点要记住,这就是为什么驱动的poll里要调用poll_wait的原因,后面分析。

do_pollfd函数位于fs_select.c文件中,代码如下:

static inline unsigned int do_pollfd(struct pollfd *pollfd, poll_table *pwait)
{
	unsigned int mask;
	int fd;

	mask = 0;
	fd = pollfd->fd;
	if (fd >= 0) {
		struct fd f = fdget(fd);
		mask = POLLNVAL;
		if (f.file) {
			mask = DEFAULT_POLLMASK;
			if (f.file->f_op && f.file->f_op->poll) {
				pwait->_key = pollfd->events|POLLERR|POLLHUP;
				mask = f.file->f_op->poll(f.file, pwait);//关键点,调用到了驱动中注册的poll函数
			}
			/* Mask out unneeded events. */
			mask &= pollfd->events | POLLERR | POLLHUP;
			fdput(f);
		}
	}
	pollfd->revents = mask;

	return mask;
}

可见,就是在do_pollfd函数中调用到了我们驱动中注册的poll函数。

驱动程序里与poll相关的地方有两处:一是构造file_operation结构时,要定义自己的poll函数。二是通过poll_wait来调用上面说到的__pollwait函数,poll_wait函数代码如下:

static inline void poll_wait(struct file * filp, wait_queue_head_t * wait_address, poll_table *p)
{
	if (p && p->_qproc && wait_address)
		p->_qproc(filp, wait_address, p);
}

上面的分析我们知道p->qproc就是__pollwait函数,从它的代码可知,它只是把当前进程挂入我们驱动程序里定义的一个队列里而已。它的代码如下,

/* Add a new entry */
static void __pollwait(struct file *filp, wait_queue_head_t *wait_address,
				poll_table *p)
{
	struct poll_wqueues *pwq = container_of(p, struct poll_wqueues, pt);
	struct poll_table_entry *entry = poll_get_entry(pwq);
	if (!entry)
		return;
	entry->filp = get_file(filp);
	entry->wait_address = wait_address;
	entry->key = p->_key;
	init_waitqueue_func_entry(&entry->wait, pollwake);
	entry->wait.private = pwq;
	add_wait_queue(wait_address, &entry->wait);
}

执行到驱动的poll_wait函数时,进程并没有休眠,我们的驱动程里实现的poll函数是不会引起进程休眠的,让进程进入休眠的是前面分析的do_poll函数中的poll_schedule_timeout(wait, TASK_INTERRUPTIBLE, to, slack)函数。

poll_wait只是把本进程挂入某个队列,应用程序调用poll > sys_poll > do_sys_poll >poll_initwait,do_poll > do_pollfd>我们驱动中自己写的poll函数后,再调用poll_schedule_timeout函数让本进程进入休眠。如果我们驱动程序发现情况就绪,可以把这个队列上挂着的进程唤醒。可见,poll_wait的作用,只是为了让驱动程序能找到要唤醒的进程。即使不用poll_wait,我们的程序也有机会被唤醒:

现在来总结一下poll机制:

1.poll  > sys_poll > do_sys_poll > poll_initwait , poll_initwait函数注册一下回调函数__pollwait,他就是我们驱动程序执行poll_wait时,真正被调用的函数。

2.接下来执行file->fop->poll,即我们驱动程序里自己实现的poll函数。它会调用poll_wait把自己挂入某个队列,这个队列也是我们自己驱动定义的。它还判断一下设备是否就绪。

3.如果设备没有就绪,do_sys_poll里会让进程休眠一段时间,这个时间是应用层传进来的超时时间。

4.进程被唤醒的条件有2:一是上面说的超时间到了,二是被驱动程序唤醒。驱动程序发现条件就绪时就把某个队列上挂着的进程唤醒,这个队列就是前面通过pollwait把本进程挂进去的队列。


再来回顾一遍调用流程:

【app:】  
poll();  
【kernel:】  
sys_poll  
    do_sys_poll(struct pollfd __user *ufds, unsigned int nfds,struct timespec *end_time)  
        poll_initwait(&table);  
            init_poll_funcptr(&table->pt, __pollwait);-->pt->qproc = __pollwait; //初始化qproc函数指针,让他指向__pollwait函数  
        do_poll(nfds, head, &table, end_time);  
            for(;;)  
            {  
                for (; pfd != pfd_end; pfd++) //查询多个驱动程序  
                {  
                   if (do_pollfd(pfd, pt))  -> mask = file->f_op->poll(file, pwait);return mask;  
{ //do_pollfd函数相当于调用驱动里面的xxx_poll函数,下面另外再进行分析,返回值mask非零,count++,记录等待事件发生的进程数 count++; pt = NULL; } } if (count || timed_out) //若count不为0(有等待的事件发生了)或者timed_out不为0(有信号发生或超时),则推出休眠 break; //上述条件不满足下面开始进入休眠,若有等待的事件发生了,超时或收到信号则唤醒 poll_schedule_timeout(wait, TASK_INTERRUPTIBLE, to, slack) }

驱动里边的xxx_poll()函数分析

xxx_poll(struct file *file, poll_table *wait)  
    poll_wait(file, &xxxx_waitq, wait);  
//  
static inline void poll_wait(struct file * filp, wait_queue_head_t * wait_address, poll_table *p)  
{  
    if (p && wait_address)  
        p->qproc(filp, wait_address, p); //调用之前poll_initwait()函数设置的函数qproc即__pollwait,__pollwait函数只是把当前进程挂到等待队列,只是add_wait_queue(wait_address, &entry->wait);不进入休眠  
}  

看一下驱动程序:

#include <linux/delay.h>  
#include <linux/irq.h>  
#include <asm/uaccess.h>  
#include <asm/irq.h>  
#include <asm/io.h>  
#include <linux/module.h>  
#include <linux/device.h>         //class_create  
#include <mach/regs-gpio.h>       //S3C2440_GPF1   
#include <mach/hardware.h>  
#include <linux/interrupt.h>  //wait_event_interruptible  
#include <linux/fs.h>  
#include <linux/poll.h>           //poll  
  
/* 定义并初始化等待队列头 */  
static DECLARE_WAIT_QUEUE_HEAD(button_waitq);  
  
static struct class *buttondev_class;  
static struct device *buttons_device;  
  
static struct pin_desc{  
    unsigned int pin;  
    unsigned int key_val;  
};  
  
static struct pin_desc pins_desc[4] = {  
        {S3C2410_GPF1,0x01}, //S3C2410_GPF1是对GPF1引脚这种“设备”的编号dev_id  
        {S3C2410_GPF4,0x02},  
        {S3C2410_GPF2,0x03},  
        {S3C2410_GPF0,0x04},  
};   
static int ev_press = 0;  
  
static unsigned char key_val;  
int major;  
  
/* 中断处理函数 */  
static irqreturn_t handle_irq(int irq, void *dev_id)  
{  
    struct pin_desc *irq_pindesc = (struct pin_desc *)dev_id;//  
    unsigned int pinval;  
      
    pinval = s3c2410_gpio_getpin(irq_pindesc->pin);//获取按键值:有按键按下返回按键值0  
    /* 键值: 按下时, 0x01, 0x02, 0x03, 0x04 */  
    /* 键值: 松开时, 0x81, 0x82, 0x83, 0x84 */  
    if(pinval)  
    {  
        /* 松开 */  
        key_val = 0x80 | (irq_pindesc->key_val);  
    }  
    else  
    {  
        /* 按下 */  
        key_val = irq_pindesc->key_val;  
    }  
  
    ev_press = 1;                           /* 表示中断已经发生 */  
    wake_up_interruptible(&button_waitq);   /* 唤醒休眠的进程 */  
    return IRQ_HANDLED;  
}  
  
static int buttons_dev_open(struct inode * inode, struct file * filp)  
{  
    /*  K1-EINT1,K2-EINT4,K3-EINT2,K4-EINT0 
     *  配置GPF1、GPF4、GPF2、GPF0为相应的外部中断引脚 
     *  IRQT_BOTHEDGE应该改为IRQ_TYPE_EDGE_BOTH 
     */  
    request_irq(IRQ_EINT1, handle_irq, IRQ_TYPE_EDGE_FALLING, "K1",&pins_desc[0]);  
    request_irq(IRQ_EINT4, handle_irq, IRQ_TYPE_EDGE_FALLING, "K2",&pins_desc[1]);  
    request_irq(IRQ_EINT2, handle_irq, IRQ_TYPE_EDGE_FALLING, "K3",&pins_desc[2]);  
    request_irq(IRQ_EINT0, handle_irq, IRQ_TYPE_EDGE_FALLING, "K4",&pins_desc[3]);  
    return 0;  
}  
  
static int buttons_dev_close(struct inode *inode, struct file *file)  
{  
    free_irq(IRQ_EINT1,&pins_desc[0]);  
    free_irq(IRQ_EINT4,&pins_desc[1]);  
    free_irq(IRQ_EINT2,&pins_desc[2]);  
    free_irq(IRQ_EINT0,&pins_desc[3]);  
    return 0;  
}  
  
static ssize_t buttons_dev_read(struct file *file, char __user *user, size_t size,loff_t *ppos)  
{  
    if (size != 1)  
            return -EINVAL;  
    //wait_event_interruptible(button_waitq, ev_press);//使用poll机制,这里就不需要再判断要不要进入睡眠了。  
    copy_to_user(user, &key_val, 1);  
      
    /* 将ev_press清零 */  
    ev_press = 0;  
    return 1;     
}  
  
//关键点///  
static unsigned int buttons_dev_poll(struct file *file, poll_table *wait) //该函数一旦被调用就触发poll机制  
{  
    unsigned int mask = 0;  
  
    /* 该函数,只是将进程挂在button_waitq队列上,而不是立即休眠 */  
    poll_wait(file, &button_waitq, wait);   
    /*** 
     * 假设进程还poll在上面这一函数里边,尚未超时,假设此时有中断到来,中断处理程序将ev_press置位,然后唤醒休眠队列上对应的进程 
     ***/  
    /* 进程唤醒之后,立马往下执行。唤醒的可能原因:超时/中断处理 */  
    if(ev_press)  
    {  
        mask |= POLLIN | POLLRDNORM;  /* 有数据可读 */  
    }  
  
    /* 如果有按键按下时,mask |= POLLIN | POLLRDNORM,否则mask = 0 */  
    return mask;    
}  
///  
  
/* File operations struct for character device */  
static const struct file_operations buttons_dev_fops = {  
    .owner      = THIS_MODULE,  
    .open       = buttons_dev_open,  
    .read       = buttons_dev_read,  
    .release    = buttons_dev_close,  
    .poll       = buttons_dev_poll,  
};  
  
/* 驱动入口函数 */  
static int buttons_dev_init(void)  
{  
    /* 主设备号设置为0表示由系统自动分配主设备号 */  
    major = register_chrdev(0, "buttons_dev", &buttons_dev_fops);  
  
    /* 创建buttondev类 */  
    buttondev_class = class_create(THIS_MODULE, "buttondev");  
  
    /* 在buttondev类下创建buttons设备,供应用程序打开设备*/  
    buttons_device = device_create(buttondev_class, NULL, MKDEV(major, 0), NULL, "buttons");//  
  
    return 0;  
}  
  
/* 驱动出口函数 */  
static void buttons_dev_exit(void)  
{  
    unregister_chrdev(major, "buttons_dev");  
    device_unregister(buttons_device);  //卸载类下的设备  
    class_destroy(buttondev_class);     //卸载类  
}  
  
/* 模块加载和卸载函数的修饰 */  
module_init(buttons_dev_init);    
module_exit(buttons_dev_exit);   
  
MODULE_AUTHOR("CLBIAO");  
MODULE_DESCRIPTION("Just for Demon");  
MODULE_LICENSE("GPL");  //遵循GPL协议  

再看一下测试程序:

/* 文件的编译指令是arm-linux-gcc -static -o app_poll app_poll.c */  
#include <stdio.h>  
#include <sys/types.h>  
#include <sys/stat.h>  
#include <fcntl.h>  
#include <unistd.h>  
#include <poll.h>  
  
/* fourth_test 
 */   
int main(int argc ,char *argv[])  
  
{  
    int fd;  
    unsigned char key_val;  
    struct pollfd fds;  
    int ret;  
  
    fd = open("/dev/buttons",O_RDWR);  
    if (fd < 0)  
    {  
        printf("open error\n");  
    }  
    fds.fd = fd;//查询的文件  
    fds.events = POLLIN; //期待收到poll_in值,表示有数据  
    while(1)  
    {  
        /* A value of 0 indicates  that the call timed out and no file descriptors were ready 
         * poll函数返回0时,表示5s时间到了,而这段时间里,没有事件发生"数据可读" 
         */  
        ret = poll(&fds,1,5000);  
        if(ret == 0)  
        {  
            printf("time out\n");  
        }  
  
        else    /* 如果没有超时,则读出按键值 */  
        {  
            read(fd,&key_val,1);  
            printf("key_val = 0x%x\n",key_val);  
        }     
    }  
    return 0;  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值