第一、二期銜接——4.5 字符驅動設備之按鍵驅動—poll機制

編寫按鍵中斷驅動——poll機制

  • 硬件平臺:韋東山嵌入式Linxu開發板(S3C2440.v3)
  • 軟件平臺:運行於VMware Workstation 12 Player下UbuntuLTS16.04_x64 系統
  • 參考資料:《嵌入式Linux應用開發手冊》、《嵌入式Linux應用開發手冊第2版》、https://blog.csdn.net/juS3Ve/article/details/81437432
  • 開發環境:Linux 2.6.22.6 內核、arm-linux-gcc-3.4.5-glibc-2.3.6工具鏈


一、前言

  問題:在我們的應用程序中的,存在如下狀況,在執行read()函數時,假如按鍵一直沒有按下,則該進程會一直處於阻塞狀態,此時應用不可以執行其他進程,導致程序卡死
  假設:那麼我們是否可以像上一個程序一樣,讓進程在處於休眠,在一定的條件下才可以喚醒
  答案:是可以的,這個時候就要引用poll機制使阻塞型函數超時返回,避免一直等待造成的阻塞。

二、簡述Linux中的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)
{
/*……*/
	poll_initwait(&table);
/*……*/
	fdcount = do_poll(nfds, head, &table, timeout);
/*……*/
}

比較關鍵的函數有兩個:

2.1 poll_initwait()函數

void poll_initwait(struct poll_wqueues *pwq)
{
	init_poll_funcptr(&pwq->pt, __pollwait);
	pwq->error = 0;
	pwq->table = NULL;
	pwq->inline_index = 0;
}

static inline void init_poll_funcptr(poll_table *pt, poll_queue_proc qproc)
{
	pt->qproc = qproc;
}

poll_initwait() ---------> init_poll_funcptr(&pwq->pt, __pollwait) --------->pt->qproc = qproc
最終這個qproc就是init_poll_funcptr(&pwq->pt, __pollwait);中的__pollwait

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

2.2 do_poll()函數大致框架

static int do_poll(unsigned int nfds,  struct poll_list *list,
		   struct poll_wqueues *wait, s64 *timeout)
{
	/*........*/
	
	for (;;) {
		/*........*/
			for (; pfd != pfd_end; pfd++) {
				
				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;

	/*........*/

		__timeout = schedule_timeout(__timeout);
		/*........*/
	__set_current_state(TASK_RUNNING);
	return count;
}

分析其中的代碼,可以發現,它的作用如下:
for(; ; )這是個循環,它退出的條件爲:

  • ①.a. if (count || !*timeout || signal_pending(current))——(count非0,超時、有信號等待處理)
    count非0表示do_pollfd()至少有一個成功。
    do_pollfd()函數大致框架:
static inline unsigned int do_pollfd(struct pollfd *pollfd, poll_table *pwait)
{
	mask = 0;
	fd = pollfd->fd;
	if (fd >= 0) {
		/*........*/
		if (file != NULL) {
			mask = DEFAULT_POLLMASK;
			if (file->f_op && file->f_op->poll)
				mask = file->f_op->poll(file, pwait);
			mask &= pollfd->events | POLLERR | POLLHUP;
			fput_light(file, fput_needed);
		}
	}
	pollfd->revents = mask;

	return mask;
}

可以看到:

  • mask = file->f_op->poll(file, pwait);:當在file_operation中定義了poll,則執行我們在驅動中編寫的poll,驅動中poll的返回值給mask

  • mask &= pollfd->events | POLLERR | POLLHUP:mask和應用程序中poll()傳入的events| POLLERR | POLLHUP進行與運算並返回。

  • ①.b. count = wait->error; if (count) break;:發生錯誤

②、 __timeout = schedule_timeout(__timeout);:讓本進程休眠一段時間。
注意應用程序執行poll調用後,如果①的條件不滿足,進程就會進入休眠。那麼,誰喚醒呢?除了休眠到指定時間被系統喚醒外,還可以被驅動程序喚醒──記住這點,這就是爲什麼驅動的poll裏要調用poll_wait的原因

3、總結

在這裏插入圖片描述

  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. 進程被喚醒的條件有:一是上面說的“一定時間”到了二是被驅動程序喚醒。驅動程序發現條件就緒時,就把“某個隊列”上掛着的進程喚醒,這個隊列,就是前面通過poll_wait把本進程掛過去的隊列。

  5. 如果驅動程序沒有去喚醒進程,那麼chedule_timeout(__timeou)超時後,會重複2、3動作直到應用程序的poll調用傳入的時間到達

三、代碼編寫

1、驅動程序修改

file_operations結構體中需要添加.poll

static struct file_operations button_drv_fops = {
	.owner   =  THIS_MODULE,    /* 這是一個宏,推向編譯模塊時自動創建的__this_module變量 */
    .open    =  button_drv_open,     
	.read    =	button_drv_read,
	.release =  button_drv_close,
	.poll    =  buton_drv_poll,
};

編寫buton_drv_poll()函數

unsigned int buton_drv_poll (struct file *file, poll_table *wait)
{
	unsigned int mask = 0;
	poll_wait(file, &button_waitq, wait); // 不會立即休眠

	/* 中斷已經發生 */
	if (ev_press)
		mask |= POLLIN | POLLRDNORM;

	return mask;	//返回給do_poll函數中的mask
}

2、完整驅動程序

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

int major;
static struct class *buttondrv_class;
static struct class_device	*buttondrv_class_dev;

volatile unsigned long *gpfcon;
volatile unsigned long *gpfdat;
volatile unsigned long *gpgcon;
volatile unsigned long *gpgdat;

/* 鍵值: 按下時, 0x01, 0x02, 0x03, 0x04 
 * 鍵值: 鬆開時, 0x81, 0x82, 0x83, 0x84 
 */
static unsigned char key_val;

/* 按鍵信息 */
struct pin_desc{
	unsigned int pin;
	unsigned int key_val;
};

/* 存儲4個按鍵的信息 */
struct pin_desc pins_desc[4] = {
 	{S3C2410_GPF0,  0x01},
 	{S3C2410_GPF2,  0x02},
 	{S3C2410_GPG3,  0x03},
	{S3C2410_GPG11, 0x04},
};

/* 中斷註冊信息 */
struct buttonirq_decs{
	unsigned int irq;
	unsigned long flags;
	const char *devname;
	void *dev_id;
};

struct buttonirq_decs buttonirqs_decs[4] = {
	{IRQ_EINT0,	 IRQT_BOTHEDGE, "S2", &pins_desc[0]},
	{IRQ_EINT2,	 IRQT_BOTHEDGE, "S3", &pins_desc[1]},
	{IRQ_EINT11, IRQT_BOTHEDGE, "S4", &pins_desc[2]},
	{IRQ_EINT19, IRQT_BOTHEDGE, "S5", &pins_desc[3]},
};

/* 生成一個等待隊列的隊頭,名字爲button_waitq */
static DECLARE_WAIT_QUEUE_HEAD(button_waitq);

/* 中斷事件標誌, 中斷服務程序將它置1,button_drv_read將它清0 */
static volatile int ev_press = 0;

/* 中斷服務函數 */
static irqreturn_t button_irq(int irq, void *dev_id)
{
	struct pin_desc *pindesc = (struct pin_desc *)dev_id;
	unsigned int pinval;

	pinval = s3c2410_gpio_getpin(pindesc->pin);	//讀取IO口電平

	if(pinval){
		/* 鬆開 */
		key_val = 0x80 | pindesc->key_val;
	}else{
		/* 按下 */
		key_val = pindesc->key_val;
	}

	ev_press = 1;	//發生中斷
	wake_up_interruptible(&button_waitq);   // 喚醒休眠的進程
	
	return IRQ_RETVAL(IRQ_HANDLED);
}

/* open驅動函數 */
static int button_drv_open(struct inode *inode, struct file *file)
{
	unsigned int i;
	int err;

	/* 註冊中斷 */
	for(i = 0; i < (sizeof(buttonirqs_decs)/sizeof(buttonirqs_decs[0])); i++){
		err = request_irq(buttonirqs_decs[i].irq, button_irq, buttonirqs_decs[i].flags,
					buttonirqs_decs[i].devname, buttonirqs_decs[i].dev_id);
		if(err){
			printk("func button_drv_open err: request_irq num:%d\n", i);
			break;
		}
	}

	/* 出現錯誤,釋放已經註冊的中斷 */
	if(err){
        i--;
        for (; i >= 0; i--)
            free_irq(buttonirqs_decs[i].irq, buttonirqs_decs[i].dev_id);
        return -EBUSY;
    }	
	return 0;
}

/* read驅動函數 */
static ssize_t button_drv_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
{
	
	unsigned long ret = 0;
	int err;

	/* 如果沒有按鍵動作, 休眠 */
	err = wait_event_interruptible(button_waitq, ev_press);

	if (err){
			printk("func button_drv_read() err: wait_event_interruptible\n");
		return err;
	}
	

	/* 如果有按鍵動作, 返回鍵值 */
	ret = copy_to_user(buf, &key_val, 1);
	ev_press = 0;	//清中斷標誌
	
	if(ret < 0){
		printk("func button_drv_read() err: copy_to_user\n");
		return -EFAULT;
	}
	
 	return sizeof(key_val);
}

/* close驅動函數 */
int button_drv_close (struct inode *inode, struct file *file)
{
	int i;

	/* 取消中斷 */
	for(i = 0; i < (sizeof(buttonirqs_decs)/sizeof(buttonirqs_decs[0])); i++)
		free_irq(buttonirqs_decs[i].irq, buttonirqs_decs[i].dev_id);

	return 0;
}

unsigned int buton_drv_poll (struct file *file, poll_table *wait)
{
	unsigned int mask = 0;
	poll_wait(file, &button_waitq, wait); // 不會立即休眠

	/* 中斷已經發生 */
	if (ev_press)
		mask |= POLLIN | POLLRDNORM;

	return mask;	//返回給do_poll函數中的mask
}

static struct file_operations button_drv_fops = {
	.owner   =  THIS_MODULE,    /* 這是一個宏,推向編譯模塊時自動創建的__this_module變量 */
    .open    =  button_drv_open,     
	.read    =	button_drv_read,
	.release =  button_drv_close,
	.poll    =  buton_drv_poll,
};

/* 入口函數 
 * 執行”insmod button_drv.ko”命令時就會調用這個函數
 */
static int button_drv_init(void)
{
	//註冊一個字符設備,名字爲button_drv
	major = register_chrdev(0, "button_drv", &button_drv_fops);	
	
	//創建一個類,名字爲buttond_rv(/class/button_drv)
	buttondrv_class = class_create(THIS_MODULE, "button_drv");	
	
	//創建一個設備節點,名爲button(/dev/button)
	buttondrv_class_dev = class_device_create(buttondrv_class, NULL, MKDEV(major, 0), NULL, "button"); 

	/* 映射物理地址 */
	gpfcon = (volatile unsigned long *)ioremap(0x56000050, 16);
	gpfdat = gpfcon + 1;

	gpgcon = (volatile unsigned long *)ioremap(0x56000060, 16);
	gpgdat = gpgcon + 1;
	
	return 0;
}

/* 出口函數 
 * 執行”rmmod button_drv.ko”命令時就會調用這個函數
 */
static void button_drv_exit(void)
{
	unregister_chrdev(major, "button_drv"); // 卸載字符

	class_device_unregister(buttondrv_class_dev);	//刪除設備節點
	class_destroy(buttondrv_class);	//銷燬類
	
	/* 取消映射 */
	iounmap(gpfcon);
	iounmap(gpgcon);
}

module_init(button_drv_init);
module_exit(button_drv_exit);

MODULE_LICENSE("GPL");

3、測試程序修改

要使用poll機制,需要在測試程序調用poll()函數,函數原型如下:

int poll(struct pollfd fd[], nfds_t nfds, int timeout);

   /* 第一個參數fd:一個結構數組,struct pollfd結構如下:
  	struct pollfd{
 			int fd;              //文件描述符
  		short events;    //請求的事件
  		short revents;   //返回的事件
  		};
    第二個參數nfds:要監視的描述符的數目
    第三個參數timeout:是一個用毫秒錶示的時間,是指定poll在返回前沒有接收事件時應該等待的時間
  */

4、完整測試程序代碼

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <poll.h>

int main(int argc, char **argv)
{
	int fd;
	int ret = 0;
	unsigned char key_val;
	int count = 0;

	struct pollfd fds[1];
	
	fd = open("/dev/button", O_RDWR);
	if (fd < 0){
		printf("can't open!\n");
		return -1;
	}
	
	fds[0].fd     = fd;
	fds[0].events = POLLIN;
	
	while (1)
	{
		ret = poll(fds, 1, 5000);
		if (ret == 0)
		{
			printf("time out\n");
		}else{
			ret = read(fd, &key_val, 1);
			if(ret < 0)
				printf(" func read() err\n");
			else
				printf("key_val = 0x%x\n", key_val);
		}
	}	
	return ret;
}

有關於測試程序如何與內核合作,完成poll機制的調用,可以參考這個篇博客https://www.cnblogs.com/andyfly/p/9480434.html

四、實際運行

在這裏插入圖片描述
可以看到,當我們運行測試程序時,不按下按鍵,測試測試程序不會一直等待read()函數有返回值,而是休眠5秒,在這5秒內,你可以採用中斷喚醒進程,或稱5秒過後,喚醒進程。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章