欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

字符驱动设备之poll机制

程序员文章站 2022-07-14 10:00:58
...

概念

poll机制引入前,我们来先来说下I/O复用,所谓I/O复用就是解决能够同时操作多个设备的方法,及时处理多个设备的数据,I/O复用的方法大概有如下,应用程序使用poll,select系统调用,应用程序使用多线程技术,比如处理按键一个线程,处理鼠标一个线程,由于线程是并行运行,所有可以同时处理按键和鼠标,工作机制如下,poll和select的机制道理是一样的,监听文件描述符集,当没有文件可以读写则挂入等待队列睡眠,当有一个或多个fd发生变化的,则从阻塞状态返回,转而处理该文件描述符IO操作,poll函数比select函数更强大的功能,更细粒的等待时间
字符驱动设备之poll机制

函数介绍

字符驱动设备之poll机制
poll()接受一个指向结构"struct pollfd"列表的指针,其中包括了你想测试的文件描述符和事件,事件由一个在结构中事件域的比特掩码确定
struct pollfd
{
int fd; //文件描述符
short event;//等待的需要测试事件
short revents //实际发生了的事件
};

events和revents的值见表
字符驱动设备之poll机制

内核源码分析

所有的系统调用,基于都可以在它的名字前加上“sys_”前缀,这就是它在内核中对应的函数.比如系统调用open,rea,write,poll,与之对应的内核函数为:sys_open,sys_read,sys_write,sys_poll.
1.
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
2.
do_sys_poll函数也位于位于fs/select.c文件中,我们取出主要部分的代码:

int do_sys_poll(struct pollfd __user *ufds, unsigned int nfds, s64 *timeout)
{
     ……
     struct poll_wqueues table;
     poll_initwait(&table);
     ……
	 fdcount = do_poll(nfds, head, &table, timeout);
     ……
}

poll_initwait函数非常简单,它初始化一个poll_wqueues变量table,table->pt->qproc = __pollwait,从__pollwait的代码可知,它只是把当前进程挂入我们驱动程序里定义的一个队列里而已,__pollwait将在驱动的poll函数里用到,进而调用do_poll函数。
3.do_poll函数位于fs/select.c文件中,代码如下:

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) {
			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)) {
					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))
			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);
	return count;
}

*if (count || !timeout || signal_pending(current))可以看出当count非0,超时,有信号等待处理结束循环,count非0表示do_pollfd至少有一个成功,__timeout = schedule_timeout(__timeout)使进程进入休眠状态一段时间,除了休眠到指定时间被系统唤醒外,还可以被驱动程序唤醒,这就是为什么驱动的poll里要调用poll_wait的原因,后面分析。
4.do_pollfd函数位于fs/select.c文件中,代码如下:

static inline unsigned int do_pollfd(struct pollfd *pollfd, poll_table *pwait)
{
……
			if (file->f_op && file->f_op->poll)
				mask = file->f_op->poll(file, pwait);
……
}

可见,它就是调用我们的驱动程序里注册的poll函数。

驱动程序设计

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

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);
}

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

static void __pollwait(struct file *filp, wait_queue_head_t *wait_address,
				poll_table *p)
{
	struct poll_table_entry *entry = poll_get_entry(p);
	if (!entry)
		return;
	get_file(filp);
	entry->filp = filp;
	entry->wait_address = wait_address;
	init_waitqueue_entry(&entry->wait, current);
	add_wait_queue(wait_address, &entry->wait);
}

内核程序设计时我们在fops写我们的poll函数时,我们会调用poll_wait函数(这里调用的是回调函数__pollwait,刚函数在do_sys_poll阶段被注册,可见,poll_wait的作用,只是为了让驱动程序能找到要唤醒的进程)把进程放入等待队列,进程并没有休眠,我们的驱动程序里实现的poll函数是不会引起休眠的.让进程进入休眠,是前面分析的do_sys_poll函数的“__timeout = schedule_timeout(__timeout)”,进入睡眠后如果我们的驱动程序发现情况就绪,可以把这个队列上挂着的进程唤醒
现在来总结一下poll机制:

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

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

  3. 如果设备未就绪,do_sys_poll里会让进程休眠一定时间

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

  5. 如果驱动程序没有去唤醒进程,那么shedule_timeout(__timeou)超时后,会重复2,3动作,直到应用程序的poll调用传入的时间到达。

流程图:
字符驱动设备之poll机制
字符驱动设备之poll机制
driver.c

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <asm/uaccess.h>
#include <asm-arm/irq.h>
#include <linux/irq.h>
#include <asm/io.h>
#include <asm-arm/arch-s3c2410/gpio.h>
#include <asm/arch/regs-gpio.h>
#include <asm/hardware.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/poll.h>

int chr_major;
struct cdev  cgs_dev;
static struct class *led_class;
static struct class_device *led_class_dev;
volatile unsigned long *gpfcon = NULL;
volatile unsigned long *gpfdat = NULL;
DECLARE_WAIT_QUEUE_HEAD(button_queue);
static volatile int ev_press = 0;
static unsigned char value;
struct pin_desc
{
   char *name;
   unsigned int pin;  
   unsigned int irq;
   unsigned int key_val;
};
static struct pin_desc  pd[4] = 
{
   {"S1",S3C2410_GPF0,0,0x01},
   {"S2",S3C2410_GPF2,0,0x02},
   {"S3",S3C2410_GPG3,0,0x03},
   {"S4",S3C2410_GPG11,0,0x04},
};
static irqreturn_t buttons_handler(int irq,void *dev_id)
{
    struct pin_desc *desc =  (struct pin_desc*)dev_id;
	if(strcmp("S1",desc->name)==0)
	{
        value = desc->key_val;
		*gpfdat &= ~(1<<6);
		ev_press = 1;                  /* 表示中断发生了 */
        wake_up_interruptible(&button_queue);   /* 唤醒休眠的进程 */
	}
    if(strcmp("S2",desc->name)==0)
	{
        value = desc->key_val;
		*gpfdat &= ~(1<<5);
		ev_press = 1;                  /* 表示中断发生了 */
        wake_up_interruptible(&button_queue);   /* 唤醒休眠的进程 */
	}
	if(strcmp("S3",desc->name)==0)
	{
        value = desc->key_val;
		*gpfdat &= ~(1<<4);
		ev_press = 1;                  /* 表示中断发生了 */
        wake_up_interruptible(&button_queue);   /* 唤醒休眠的进程 */
	}
	if(strcmp("S4",desc->name)==0)
	{
        value =  0x88;
		*gpfdat &= ~((1<<4) | (1<<5) | (1<<6));
		ev_press = 1;                  /* 表示中断发生了 */
        wake_up_interruptible(&button_queue);   /* 唤醒休眠的进程 */
	}
	return IRQ_RETVAL(IRQ_HANDLED);
}
static int cgs_led_open (struct inode *inode, struct file *file)
{   
    int i;
    *gpfcon &= ~((0x3<<(4*2)) | (0x3<<(5*2)) | (0x3<<(6*2)));
	*gpfcon |= ((0x1<<(4*2)) | (0x1<<(5*2)) | (0x1<<(6*2)));
	for(i=0;i<4;i++)
	{
      pd[i].irq = gpio_to_irq(pd[i].pin);
      request_irq(pd[i].irq,buttons_handler, IRQT_BOTHEDGE,pd[i].name,&pd[i]);
	}
	return 0;
}
ssize_t cgs_led_read (struct file *file, char __user *buf, size_t size, loff_t *ppos)
{
   if (size != 1)
		return -EINVAL;
   wait_event_interruptible(button_queue, ev_press);
   copy_to_user(buf,&value,1);
   ev_press = 0;
   return 1;
}
static unsigned cgs_led_poll(struct file *file, poll_table *wait)
{
   unsigned int mask = 0;
   poll_wait(file,&button_queue,wait);
   if(ev_press)
   	   mask |= POLLIN|POLLRDNORM;
   return mask;
}

struct file_operations cgs_fops ={
   .owner   = THIS_MODULE,
   .open   =  cgs_led_open,
   .read    = cgs_led_read,
   .poll    = cgs_led_poll,
};
static int __init cgs_lcd_init(void)
{

    dev_t dev;
	int result;
	cgs_dev.owner = THIS_MODULE;
	result = alloc_chrdev_region(&dev,0, 1,"cgs_led");
	if(result<0)
	{
       return result;
	}
	chr_major = MAJOR(dev);
	cdev_init(&cgs_dev,&cgs_fops);
	cdev_add(&cgs_dev,MKDEV(chr_major,0),1);
	led_class = class_create(THIS_MODULE,"cgs_led");
	led_class_dev = class_device_create(led_class,NULL,MKDEV(chr_major,0),NULL,"cgs_led");
	gpfcon = (volatile unsigned long*)ioremap(0x56000050,16);
	gpfdat = gpfcon + 1;
	return 0;
}
static void __exit cgs_lcd_exit(void)
{   
    int j;
    unregister_chrdev_region(MKDEV(chr_major,0),1);
	cdev_del(&cgs_dev);
    device_destroy(led_class,MKDEV(chr_major,0));
	class_destroy(led_class);
	iounmap(gpfcon);
	for(j=0;j<4;j++)
    {
       free_irq(pd[j].irq, &pd[j]);
	}
}
module_init(cgs_lcd_init);
module_exit(cgs_lcd_exit);
MODULE_LICENSE("GPL");


test.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
  int fd;
  int ret;
  unsigned char buf;
  fd = open("/dev/cgs_led",O_RDWR);
  struct pollfd fds[1];
  fds[0].fd = fd;
  fds[0].events = POLLIN;
  if(fd<0)
  {
    printf("can't open!\n");
  }
  while(1)
  {
   ret = poll(fds,1,4000);
   if (ret == 0)
		{
			printf("time out\n");
		}
		else
		{
			read(fd, &key_val, 1);
			printf("key_val = 0x%x\n", key_val);
		}
  }
  return 0;
}

相关标签: Linux驱动