Linux驱动等待队列与poll机制

Linux驱动等待队列与poll机制

  当我们在操作设备时,我们经常遇到当设备获取不到资源时就会挂起进程,当设备资源满足要求时再唤醒进程(如read函数,当读不到数据时就会挂起,读到了数据则可立刻返回)。这种通过阻塞方式访问设备,可以极大的减轻CPU负荷,在进程挂起是可以让CPU去执行其它资源。而通过等待队列的方式就可实现进程阻塞,满足要求时再唤醒进程。
  因为阻塞的进程会进入休眠状态, 因此, 必须确保有一个地方能够唤醒休眠的进程。 唤醒进程的地方最大可能发生在中断里面, 因为硬件资源获得的同时往往伴随着一个中断。
  在内核中,等待队列的合理应用可以极大的提供CPU执行效率,尤其是在中断处理、进程同步、定时等场合。可以使用等待队列实现阻塞进程的唤醒。它以队列为基础数据结构,与进程调度机制紧密结合,能够用于实现内核中的异步事件通知机制,同步对系统资源的访问等。
  等待队列是一种基于资源状态的线程管理的机制,它可以使线程在资源不满足的情况下处于休眠状态,让出CPU资源,而资源状态满足时唤醒线程,使其继续进行业务的处理。
  等待队列(wait queue)用于使线程等待某一特定的事件发生而无需频繁的轮询,进程在等待期间睡眠,在某件事发生时由内核自动唤醒。它是以双循环链表为基础数据结构,与进程的休眠唤醒机制紧密相联,是实现异步事件通知、跨进程通信、同步资源访问等技术的底层技术支撑。

1.等待队列相关接口函数

  在Linux中,等待队列是由等待队列头wait_queue_head_t *q进行管理,结构体信息如下:

struct __wait_queue_head {
    
    
	spinlock_t lock;
	struct list_head task_list;
};

1.1 等待队列头初始化

  初始化等待队列头可以静态初始化或者动态初始化

#define DECLARE_WAIT_QUEUE_HEAD(name)
功能: 静态初始化等待队列头
参数: name --等待队列头结构体变量名

#define init_waitqueue_head(q)
功能: 静态初始化等待队列头
参数: q–等待队列头结构体指针变量

  注意:动态初始化时需要手动创建一个等待队列头结构体变量,而静态初始化只需要填入等待队列头变量名即可。即:
  DECLARE_WAIT_QUEUE_HEAD(q)等价于下面两行代码:

wait_queue_head_t q;
init_waitqueue_head(&q);//动态初始化等待队列头

1.2 休眠进程

  休眠进程由两类函数:可中断休眠不可中断休眠可中断休眠可中断休眠是可以通过信号方式唤醒;不可中断休眠则在休眠期间无法收到信号(如CTRL+C、CTRL+),信号将会被阻塞,必须等待进程唤醒后才能响应信号。

  • 可中断休眠函数
#define wait_event_interruptible(wq, condition)				\
({
      
      									\
	int __ret = 0;							\
	if (!(condition))						\
		__wait_event_interruptible(wq, condition, __ret);	\
	__ret;								\
})
//不可中断休眠,但可以指定超时时间
#define __wait_event_timeout(wq, condition, ret)			\
do {
      
      									\
	DEFINE_WAIT(__wait);						\
									\
	for (;;) {
      
      							\
		prepare_to_wait(&wq, &__wait, TASK_UNINTERRUPTIBLE);	\
		if (condition)						\
			break;						\
		ret = schedule_timeout(ret);				\
		if (!ret)						\
			break;						\
	}								\
	finish_wait(&wq, &__wait);					\
} while (0)

  wq为等待队列头;
  condition为唤醒标志,condition为真唤醒进程,为假则为休眠状态;
  ret为要指定的超时时间,单位为时钟节拍jiffies

  • 不可中断休眠函数
#define wait_event(wq, condition) 					\
do {
      
      									\
	if (condition)	 						\
		break;							\
	__wait_event(wq, condition);					\
} while (0)
//可中断休眠,但可以指定超时时间
#define __wait_event_interruptible_timeout(wq, condition, ret)		\
do {
      
      									\
	DEFINE_WAIT(__wait);						\
									\
	for (;;) {
      
      							\
		prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE);	\
		if (condition)						\
			break;						\
		if (!signal_pending(current)) {
      
      				\
			ret = schedule_timeout(ret);			\
			if (!ret)					\
				break;					\
			continue;					\
		}							\
		ret = -ERESTARTSYS;					\
		break;							\
	}								\
	finish_wait(&wq, &__wait);					\
} while (0)

  wq为等待队列头;
  condition为唤醒标志,condition为真唤醒进程,为假则为休眠状态。
  ret为要指定的超时时间,单位为时钟节拍jiffies

1.3 唤醒进程

  唤醒休眠进程函数分为两类:一是可唤醒可中断和不可中断休眠进程;二是只能唤醒可中断休眠进程。
  唤醒进程函数一般是在设备获取到资源时调用,调用位置常处于中断处理函数中。

//可唤醒可中断和不可中断休眠进程
#define wake_up(x)			__wake_up(x, TASK_NORMAL, 1, NULL)  //随机唤醒一个休眠进程
#define wake_up_nr(x, nr)		__wake_up(x, TASK_NORMAL, nr, NULL)  //唤醒多个休眠进程
#define wake_up_all(x)			__wake_up(x, TASK_NORMAL, 0, NULL)  //唤醒所有休眠进程
//只能唤醒可中断休眠进程
#define wake_up_interruptible(x)	__wake_up(x, TASK_INTERRUPTIBLE, 1, NULL) //随机唤醒一个休眠进程
#define wake_up_interruptible_nr(x, nr)	__wake_up(x, TASK_INTERRUPTIBLE, nr, NULL) //唤醒多个休眠进程
#define wake_up_interruptible_all(x)	__wake_up(x, TASK_INTERRUPTIBLE, 0, NULL) //唤醒所有休眠进程

1.4 等待队列应用示例

  下面以按键为例,实现中断方式按键检测,通过工作队列处理底半部分代码,杂项设备框架实现设备注册。在按键的工作函数中唤醒休眠进程。在位获取到按键信息时将进程休眠。
  Linux中断编程参考:https://blog.csdn.net/weixin_44453694/article/details/126812705

#include <linux/kernel.h>
#include <linux/module.h>
#include <asm/io.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/suspend.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/wait.h>

#include <linux/gpio.h>
#include <mach/gpio.h>
#include <plat/gpio-cfg.h>
#define KEY_CNT sizeof(key_info)/sizeof(struct key_info)  //按键个数

//static wait_queue_head_t key_q;/*等待队列头(动态初始化时需要定义)*/
DECLARE_WAIT_QUEUE_HEAD(key_q);//静态初始化等待队列头
struct key_info
{
    
    
	unsigned int gpio;//gpio口
	int irq;//中断号
	char key_name[20];//注册中断名字
	int key_num;//按键编号
};
//按键信息保存
static struct key_info key_info[]=
{
    
    
	{
    
    EXYNOS4_GPX3(2),0,"key1",1},
	{
    
    EXYNOS4_GPX3(3),0,"key2",2},
	{
    
    EXYNOS4_GPX3(4),0,"key3",3},
	{
    
    EXYNOS4_GPX3(5),0,"key4",4}
};
static struct key_info *key_p;
static struct work_struct key_work;/*工作结构体*/
static int key_val;
static int condition=0;/*唤醒标志*/
/*工作处理函数*/
void work_func(struct work_struct *work)
{
    
    
	msleep(10);//按键消抖
	if(gpio_get_value(key_p->gpio)==0)
	{
    
    
		//printk("KEY %d 按下\n",key_p->key_num);
		key_val=key_p->key_num;
	}
	condition=1;//将唤醒标志置位
	wake_up(&key_q);
	
}
/*中断服务函数*/
static irqreturn_t key_exit_work(int irq, void *dev)
{
    
    
	key_p=(struct key_info *)dev;
	schedule_work(&key_work);//工作调度
	return IRQ_HANDLED;
}

static int key_open(struct inode *inode, struct file *file)
{
    
    
	printk("设备打开成功\n");
	return 0;
}
static ssize_t key_read(struct file *file, char __user *data, size_t size, loff_t *offset)
{
    
    
	int ret;
	int key;
	//wait_event(key_q, condition);//休眠进程(不可中断休眠)
	wait_event_interruptible(key_q, condition);//休眠进程(可中断休眠)
	key=key_val;
	condition=0;//清除唤醒标志
	ret=copy_to_user(data,&key,sizeof(key));
	return sizeof(key)-ret;
}
static int key_release(struct inode *inode, struct file *file)
{
    
    
	printk("设备关闭成功\n");
	return 0;
}
/*文件操早集合*/
static struct file_operations key_fops=
{
    
    
	.open=		key_open,
	.read=		key_read,
	.release=	key_release
};


/*杂项设备结构体*/
static struct miscdevice key_misc=
{
    
    
	.minor=MISC_DYNAMIC_MINOR,//次设备号,255,有内核分配
	.name="key_exit",//在/dev下生成的设备节点名字
	.fops=&key_fops
};
static int __init wbyq_key_exit_init(void)
{
    
    
	int i=0;
	int ret;
	/*初始化等待队列头*/
	//init_waitqueue_head(&key_q);
	/*初始化工作*/
	INIT_WORK(&key_work, work_func);
	for(i=0;i<KEY_CNT;i++)
	{
    
    
		key_info[i].irq=gpio_to_irq(key_info[i].gpio);/*获取中断号*/
		/*注册中断*/
		ret=request_irq(key_info[i].irq,key_exit_work,IRQF_TRIGGER_FALLING,key_info[i].key_name,&key_info[i]);
		if(ret)
		{
    
    	
			disable_irq(key_info[i].irq);//禁止中断
			free_irq(key_info[i].irq,&key_info[i]);//注销中断
			printk("注册中断失败irq=%d,i=%d\n",key_info[i].irq,i);
			return ret;
		}
	}
	/*注册杂项设备*/
	misc_register(&key_misc);
	return 0;
	
}
/*驱动释放*/
static void __exit wbyq_key_exit_cleanup(void)
{
    
    
	int i=0;
    printk("驱动出口,驱动注销成功\n");
	/*注销中断*/
	for(i=0;i<KEY_CNT;i++)
	{
    
    
		disable_irq(key_info[i].irq);//禁止中断
		free_irq(key_info[i].irq,&key_info[i]);//注销中断
	}
	/*注销杂项设备*/
	misc_deregister(&key_misc);
}
module_init(wbyq_key_exit_init);//驱动入口函数
module_exit(wbyq_key_exit_cleanup);//驱动出口函数

MODULE_LICENSE("GPL");//驱动注册协议
MODULE_AUTHOR("it_ashui");
MODULE_DESCRIPTION("Exynos4 key_exit Driver");

2.驱动层与应用层poll调用机制

  使用等待队列时,当设备获取不到资源就会被阻塞,直到获取资源后才能唤醒进程,这样就导致在主进程中无法干其它事件,若要实现进程休眠,又想不阻塞进程,我们就可以采用poll机制来监测文件描述符,poll机制可以设置监听的超时时间,允许一个进程来决定它是否可读或者写一个或多个文件而不阻塞。当然,poll调用也可阻塞进程直到任何一个给定集合的文件描述符可用来读或写。 因此,它们常常用在使用多输入输出流的应用程序。
  对应事件监听,应用层有select、poll、epoll三种机制。其中poll和epoll机制是select机制的升级版。

2.1 poll机制驱动层相关函数接口

  • poll机制接口函数

  应用层select、poll、epoll三种机制共用一个驱动层接口。

unsigned int (*poll) (struct file *, struct poll_table_struct *);
  • 等待事件触发函数
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);
}
  • poll唤醒函数
//唤醒休眠进程
#define wake_up_poll(x, m)				\
	__wake_up(x, TASK_NORMAL, 1, (void *) (m))
#define wake_up_locked_poll(x, m)				\
	__wake_up_locked_key((x), TASK_NORMAL, (void *) (m))
#define wake_up_interruptible_poll(x, m)			\
	__wake_up(x, TASK_INTERRUPTIBLE, 1, (void *) (m))
#define wake_up_interruptible_sync_poll(x, m)				\
	__wake_up_sync_key((x), TASK_INTERRUPTIBLE, 1, (void *) (m))
//或者直接使用等待队列唤醒函数
#define wake_up(x)			__wake_up(x, TASK_NORMAL, 1, NULL)	

2.2 poll机制应用层相关函数接口

#include <poll.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
形参: fds --poll结构体
 struct pollfd {
   int fd; /*要监听的文件描述符 */
   short events; /*要监听的事件 */
  short revents; /*返回事件 */
  };
    nfds --监听的描述符个数
    timeout --超时时间,<0永久等待;==0立刻返回;>0超时时间
返回值: >0有事件产生;==0超时;<0函数出错

  • 监听事件
  • POLLIN --有数据可读
  • POLLRDNORM --有普通数据可读
  • POLLRDBAND --有优先数据可读
  • POLLPRI --有紧迫数据可读
  • POLLOUT --数据可写
  • POLLERR --发生错误
  • POLLHUP --发生挂起
  • POLLNVAL --指定的文件描述符非法。
  • 应用层poll机制示例
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>
int main()
{
    
    
	int fd=open("/dev/key_exit",2);
	if(fd<0)
	{
    
    
		printf("设备打开失败\n");
		return 0;
	}
	int key_val;
	int ret;
	struct pollfd fds=
	{
    
    
		.fd=fd,//要监听的文件描述符
		.events=POLLIN,//监听读事件
		.revents=0,//返回事件
	};
	while(1)
	{
    
    
		ret=poll(&fds,1, 1000);
		if(ret>0)
		{
    
    
			if(fds.revents & POLLIN)
			{
    
    
				read(fd,&key_val,4);
				printf("KEY %d 按下\n",key_val);
			}
		}
		else if(ret==0)
		{
    
    
			printf("超时\n");
		}
		else 
		{
    
    
			printf("poll函数出错\n");
		}
	}
	close(fd);
}
  • 驱动层poll接口实现
#include <linux/kernel.h>
#include <linux/module.h>
#include <asm/io.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <linux/timer.h>
#include <linux/delay.h>
#include <linux/suspend.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/wait.h>
#include <linux/poll.h>

#include <linux/gpio.h>
#include <mach/gpio.h>
#include <plat/gpio-cfg.h>
#define KEY_CNT sizeof(key_info)/sizeof(struct key_info)  //按键个数

//static wait_queue_head_t key_q;/*等待队列头(动态初始化时需要定义)*/
DECLARE_WAIT_QUEUE_HEAD(key_q);//静态初始化等待队列头
struct key_info
{
    
    
	unsigned int gpio;//gpio口
	int irq;//中断号
	char key_name[20];//注册中断名字
	int key_num;//按键编号
};
//按键信息保存
static struct key_info key_info[]=
{
    
    
	{
    
    EXYNOS4_GPX3(2),0,"key1",1},
	{
    
    EXYNOS4_GPX3(3),0,"key2",2},
	{
    
    EXYNOS4_GPX3(4),0,"key3",3},
	{
    
    EXYNOS4_GPX3(5),0,"key4",4}
};
static struct key_info *key_p;
static struct work_struct key_work;/*工作结构体*/
static int key_val;
/*工作处理函数*/
void work_func(struct work_struct *work)
{
    
    
	msleep(10);//按键消抖
	if(gpio_get_value(key_p->gpio)==0)
	{
    
    
		//printk("KEY %d 按下\n",key_p->key_num);
		key_val=key_p->key_num;
	}
	wake_up_poll(&key_q, POLLIN);//唤醒进程
}
/*中断服务函数*/
static irqreturn_t key_exit_work(int irq, void *dev)
{
    
    
	key_p=(struct key_info *)dev;
	schedule_work(&key_work);//工作调度
	return IRQ_HANDLED;
}

static int key_open(struct inode *inode, struct file *file)
{
    
    
	printk("设备打开成功\n");
	return 0;
}
static ssize_t key_read(struct file *file, char __user *data, size_t size, loff_t *offset)
{
    
    
	int ret;
	int key;
	key=key_val;
	key_val=0;
	ret=copy_to_user(data,&key,sizeof(key));
	return sizeof(key)-ret;
}
static unsigned int key_poll(struct file *file, struct poll_table_struct *wait)
{
    
    
	int mask = 0;
	poll_wait(file,&key_q, wait);//等待事件产生
	if(key_val)mask|=POLLIN;
	return mask;
		
	
}
static int key_release(struct inode *inode, struct file *file)
{
    
    
	printk("设备关闭成功\n");
	return 0;
}
/*文件操早集合*/
static struct file_operations key_fops=
{
    
    
	.open=		key_open,
	.read=		key_read,
	.poll=		key_poll,
	.release=	key_release
};


/*杂项设备结构体*/
static struct miscdevice key_misc=
{
    
    
	.minor=MISC_DYNAMIC_MINOR,//次设备号,255,有内核分配
	.name="key_exit",//在/dev下生成的设备节点名字
	.fops=&key_fops
};
static int __init wbyq_key_exit_init(void)
{
    
    
	int i=0;
	int ret;
	/*初始化等待队列头*/
	//init_waitqueue_head(&key_q);
	/*初始化工作*/
	INIT_WORK(&key_work, work_func);
	for(i=0;i<KEY_CNT;i++)
	{
    
    
		key_info[i].irq=gpio_to_irq(key_info[i].gpio);/*获取中断号*/
		/*注册中断*/
		ret=request_irq(key_info[i].irq,key_exit_work,IRQF_TRIGGER_FALLING,key_info[i].key_name,&key_info[i]);
		if(ret)
		{
    
    	
			disable_irq(key_info[i].irq);//禁止中断
			free_irq(key_info[i].irq,&key_info[i]);//注销中断
			printk("注册中断失败irq=%d,i=%d\n",key_info[i].irq,i);
			return ret;
		}
	}
	/*注册杂项设备*/
	misc_register(&key_misc);
	return 0;
	
}
/*驱动释放*/
static void __exit wbyq_key_exit_cleanup(void)
{
    
    
	int i=0;
    printk("驱动出口,驱动注销成功\n");
	/*注销中断*/
	for(i=0;i<KEY_CNT;i++)
	{
    
    
		disable_irq(key_info[i].irq);//禁止中断
		free_irq(key_info[i].irq,&key_info[i]);//注销中断
	}
	/*注销杂项设备*/
	misc_deregister(&key_misc);
}
module_init(wbyq_key_exit_init);//驱动入口函数
module_exit(wbyq_key_exit_cleanup);//驱动出口函数

MODULE_LICENSE("GPL");//驱动注册协议
MODULE_AUTHOR("it_ashui");
MODULE_DESCRIPTION("Exynos4 key_exit Driver");
  • 执行效果
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44453694/article/details/126826448