25、IMX6ULL學習筆記-非阻塞IO

一、實驗說明

1、poll函數
APP中調用select(),poll()函數時,會使驅動調用其poll()函數.
在單個線程中, select 函數能夠監視的文件描述符數量有最大的限制,一般爲 1024,可以修改內核將監視的文件描述符數量改大,但是這樣會降低效率!這個時候就可以使用 poll 函數,poll 函數本質上和 select 沒有太大的差別,但是 poll 函數沒有最大文件描述符限制.
poll機制實際上可以理解爲定時阻塞,超過時間就會喚醒。這就像在APP進入休眠之前,先定義一個定時器,定時器時間到,就可以自動喚醒,然後返回,也可以在中斷中調用wake_up函數,在定時器未溢出之前提前喚醒。
2、epoll 函數
傳統的 selcet 和 poll 函數都會隨着所監聽的 fd 數量的增加,出現效率低下的問題,而且poll 函數每次必須遍歷所有的描述符來檢查就緒的描述符,這個過程很浪費時間。爲此, epoll因運而生, epoll 就是爲處理大併發而準備的,一般常常在網絡編程中使用 epoll 函數。
3、以select(),poll()爲例,兩者的驅動函數相同,app函數不同。

二、原理圖

在這裏插入圖片描述

三、設備樹

在這裏插入圖片描述

四、 app-select() >>driver-poll()和app-poll()>>driver-poll()的驅動程序

驅動程序如下

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/gpio.h>
#include <linux/of_gpio.h>
#include <linux/string.h>
#include <linux/irq.h>
#include <asm/mach/map.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <linux/wait.h>
#include <linux/ide.h>
#include <linux/interrupt.h>
#include <linux/poll.h>
#define DeviceName 		"devicetree-key0-interrupt" //設備驅動名稱
#define DeviceNodes 	1 					  	 //設備節點個數
#define KEY_NUM 		0X01             
#define KEY0VALUE       0X01
#define INVAKEY         0XFF
struct irq_keydesc{
    int gpio_num;           /* io編號 */
    int irq_num;            /* 中斷號 */
    unsigned char value;    /* 鍵值 */
    char name[25];          /* 名字 */
    irqreturn_t (*handler) (int, void *);  /* 中斷處理函數 */
};
/* 定義一個設備結構體 */
struct mod_struct {
	dev_t devid;			     /* 設備號 */
	int major;				     /* 主設備號 */
	int minor;				     /* 次設備號 */
	struct cdev cdev;		     /* cdev */
	struct class *class;	  	 /* 類 */
	struct device *device;	 	 /* 設備 */
	struct device_node *nd;  	 /* 設備節點 */
	struct irq_keydesc irqkey0;  /* 按鍵中斷 */
	struct timer_list timer;	 /* 內核定時器 */
	
	atomic_t keyvalue;			 /* 原子變量1->整形*/
    atomic_t releasekey;		 /* 原子變量2->整形*/
	wait_queue_head_t  r_wait;   /* 讀等待隊列頭 */
};
struct mod_struct mod_device;	 /* 定義一個設備 */
/*
 * @description		: 打開設備
 * @param - inode 	: 傳遞給驅動的inode
 * @param - filp 	: 設備文件,file結構體有個叫做private_data的成員變量
 * 					  一般在open的時候將private_data指向設備結構體。
 * @return 			: 0 成功;其他 失敗
 */
static int key0_interrupt_open(struct inode *inode, struct file *filp)
{
	filp->private_data = &mod_device; /* 設置私有數據 */
	return 0;
}
/*
 * @description		: 從設備讀取數據 
 * @param - filp 	: 要打開的設備文件(文件描述符)
 * @param - buf 	: 返回給用戶空間的數據緩衝區
 * @param - cnt 	: 要讀取的數據長度
 * @param - offt 	: 相對於文件首地址的偏移
 * @return 			: 讀取的字節數,如果爲負值,表示讀取失敗
 */
static ssize_t key0_interrupt_read(struct file *filp, char __user *buf, size_t cnt, loff_t *offt)
{
    int ret = 0;
    unsigned char keyvalue;
    unsigned char releasekey;
    struct mod_struct *dev = filp->private_data;
	if(filp->f_flags & O_NONBLOCK) {/*非阻塞*/
		if(atomic_read(&dev->releasekey) == 0){/*按鍵未按下*/
			return  -EAGAIN;/*返回錯誤數值*/
		}		
	}
	else/*阻塞*/
	{
		wait_event_interruptible(dev->r_wait, atomic_read(&dev->releasekey)); /* 等待按鍵有效 */
	}
	
    keyvalue = atomic_read(&dev->keyvalue);
    releasekey = atomic_read(&dev->releasekey);
    if(releasekey) {        /* 有效按鍵 */
        if(keyvalue & 0x80) {
            keyvalue &= ~0x80;
            ret = copy_to_user(buf, &keyvalue, sizeof(keyvalue));
        } else {
            goto data_error;
        }
        atomic_set(&dev->releasekey, 0); /* 按下標誌清零 */
    } else {
        goto data_error;
    }
    return ret;
data_error:
    return -EINVAL;
}
/*
 * @description		: 向設備寫數據 
 * @param - filp 	: 設備文件,表示打開的文件描述符
 * @param - buf 	: 要寫給設備寫入的數據
 * @param - cnt 	: 要寫入的數據長度
 * @param - offt 	: 相對於文件首地址的偏移
 * @return 			: 寫入的字節數,如果爲負值,表示寫入失敗
 */
static ssize_t key0_interrupt_write(struct file *filp, const char __user *buf,size_t cnt, loff_t *offt)
{
	return 0;
}
/*
 * @description		: 關閉/釋放設備
 * @param - filp 	: 要關閉的設備文件(文件描述符)
 * @return 			: 0 成功;其他 失敗
 */
static int key0_interrupt_release(struct inode *inode, struct file *filp)
{
	return 0;
}
static unsigned int key0_interrupt_poll(struct file *filp,struct poll_table_struct * wait)
{
	int mask = 0;
	struct mod_struct *dev = filp->private_data;
	
	poll_wait(filp,&dev->r_wait,wait);

	/*判斷是否可讀*/
	if(atomic_read(&dev->releasekey)){/*如果按下*/
		mask = POLLIN | POLLRDNORM;/*返回POLLIN*/
	}
	return mask;
}
/* 設備操作函數 */
static struct file_operations beep_fops = {
	.owner    	=  THIS_MODULE,
	.open     	=  key0_interrupt_open,
	.read     	=  key0_interrupt_read,
	.write    	=  key0_interrupt_write,
	.release  	=  key0_interrupt_release,
	.poll 		=  key0_interrupt_poll,
};
/* 按鍵中斷處理函數 */
static irqreturn_t key0_handler(int irq, void *dev_id)
{
	struct mod_struct *dev = dev_id;
	dev->timer.data = (volatile long)dev_id;
	mod_timer(&dev->timer, jiffies + msecs_to_jiffies(20)); /* 20ms定時 */
	return IRQ_HANDLED;
}
/* 定時器處理函數 */
static void timer_func(unsigned long arg) {
    int value = 0;
    struct mod_struct *dev = (struct mod_struct*)arg;

    value = gpio_get_value(dev->irqkey0.gpio_num);
    if(value == 0)   {          /* 按下 */
        atomic_set(&dev->keyvalue, dev->irqkey0.value);/*=0x01*/
    } else if(value == 1) {     /* 釋放 */
        atomic_set(&dev->keyvalue, 0X80 | (dev->irqkey0.value));
        atomic_set(&dev->releasekey, 1);  /* 完成的按鍵過程 */
    }
	/* 喚醒進程 */
    if(atomic_read(&dev->releasekey)) {
         wake_up(&dev->r_wait);
    }
}
/*
 * @description	: 按鍵初始化函數
 * @param 		: dev
 * @return 		: 無
 */
static int key_initx(struct mod_struct *dev)
{
	int ret = 0;
	/* 1、獲取設備節點:/devicetree-leds-pincrl */
	dev->nd = of_find_node_by_path("/devicetree-key0-interrupt");
	if(dev->nd == NULL) {
			printk("devicetree-key0-interrupt node not find!\r\n");
			ret = -EINVAL;
			goto fail_fd;
	} else {
		printk("devicetree-key0-interrupt node find!\r\n");
	}
	/* 2、從設備節點下的led-gpio屬性裏獲取gpio編號 */
	dev->irqkey0.gpio_num = of_get_named_gpio(dev->nd,"key-gpio", 0);
	if(dev->irqkey0.gpio_num < 0) {
			printk("can't get key-gpio\r\n");
			ret = -EINVAL;
			goto fail_gpio;
	}
	printk("key-gpio num = %d\r\n", dev->irqkey0.gpio_num);
	/*3、申請gpio(檢查是否被佔用)*/
	sprintf(dev->irqkey0.name,"%s","key0-gpio-interrupt");
	ret = gpio_request(dev->irqkey0.gpio_num,dev->irqkey0.name);
	if(ret)
	{
		ret = -EBUSY;
		printk("IO %d busy,can't request!\r\n",dev->irqkey0.gpio_num);
		goto fail_ioreq;
	}
	/*4、設置key0爲輸入 */
	ret = gpio_direction_input(dev->irqkey0.gpio_num);
	if(ret < 0) {
			printk("can't set gpio!\r\n");
			goto fail_ioset;
	}
	/*5、根據IO編號獲取其中斷號*/
	dev->irqkey0.irq_num=gpio_to_irq(dev->irqkey0.gpio_num);
#if 0
	dev->irqkey0.irq_num = irq_of_parse_and_map(dev->nd,0);
#endif
	/*6、設置中斷函數*/
	dev->irqkey0.handler = key0_handler;
    dev->irqkey0.value  = KEY0VALUE;
	/*7、註冊中斷*/
	ret = request_irq(dev->irqkey0.irq_num,
					  dev->irqkey0.handler,
					  IRQF_TRIGGER_RISING|IRQF_TRIGGER_FALLING,
					  dev->irqkey0.name,
					  &mod_device);
	if(ret){
		printk("irq %d request failed!\r\n", dev->irqkey0.irq_num);
		goto fail_irq;
	}
	/*8、初始化定時器*/
	init_timer(&mod_device.timer);
    mod_device.timer.function = timer_func;
	return 0;
fail_irq:
fail_ioset:
	gpio_free(dev->irqkey0.gpio_num);
fail_ioreq:
fail_gpio:
fail_fd:
	return ret;
}
/*
 * @description	: 驅動出口函數
 * @param 		: 無
 * @return 		: 無
 */
static int __init key0_interrupt_init(void)
{
	int ret = 0;
/*一、 註冊字符設備驅動 */
	/* 1、創建設備號 */
	if (mod_device.major)
	{		
		mod_device.devid = MKDEV(mod_device.major,0);//設備號起始點(major,0)
		//設備號起始點開始,申請DeviceNodes個設備號
		ret = register_chrdev_region(mod_device.devid,DeviceNodes,DeviceName);
	} 
	else {
		ret = alloc_chrdev_region(&mod_device.devid,0,DeviceNodes,DeviceName);	/* 申請設備號 */
		mod_device.major = MAJOR(mod_device.devid);	/* 獲取分配號的主設備號 */
		mod_device.minor = MINOR(mod_device.devid);	/* 獲取分配號的次設備號 */	
	}
	if(ret < 0){ printk("設備號申請失敗\r\n");goto fail_chrdev; }
	printk("mod_device major=%d,minor=%d\r\n",mod_device.major,mod_device.minor);	
	/* 2、初始化cdev並添加cdev */
	mod_device.cdev.owner = THIS_MODULE;
	cdev_init(&mod_device.cdev,&beep_fops);
	ret = cdev_add(&mod_device.cdev,mod_device.devid,DeviceNodes);
	if(ret < 0){ printk("添加cdev失敗!\r\n");goto fail_cdev; }
	/* 3、創建類 */
	mod_device.class = class_create(THIS_MODULE,DeviceName);
	if (IS_ERR(mod_device.class)) { ret = PTR_ERR(mod_device.class);goto fail_class; } 
	/* 4、創建設備節點*/
	mod_device.device = device_create(mod_device.class,NULL,mod_device.devid,NULL,DeviceName);
	if (IS_ERR(mod_device.device)) { ret = PTR_ERR(mod_device.device);goto fail_device; }
	/* 5、初始化IO */
    ret = key_initx(&mod_device);
    if(ret < 0) {
        goto fail_keyinit;
    }
	/* 6、初始化原子變量 */
	atomic_set(&mod_device.keyvalue, INVAKEY);/*mod_device.keyvalue=INVAKEY*/
    atomic_set(&mod_device.releasekey, 0);/*mod_device.releasekey=0*/
	/* 7、等待隊列頭 */
    init_waitqueue_head(&mod_device.r_wait);
    return 0;
/*X、模塊加載失敗處理部分*/
fail_keyinit:
	device_destroy(mod_device.class,mod_device.devid);
fail_device:	
	class_destroy(mod_device.class);
fail_class:	
	cdev_del(&mod_device.cdev);
fail_cdev:
	unregister_chrdev_region(mod_device.devid,DeviceNodes);
fail_chrdev:
	return ret;
}
/*
 * @description	: 驅動出口函數
 * @param 		: 無
 * @return 		: 無
 */
static void __exit key0_interrupt_exit(void)/*按照相反順序註銷*/
{
	/*1、釋放中斷*/
	free_irq(mod_device.irqkey0.irq_num, &mod_device);
	/*2、內核定定時器註銷部分*/
	del_timer_sync(&mod_device.timer);/* 刪除timer */
	/*3、LED設備註銷部分*/
	gpio_free(mod_device.irqkey0.gpio_num);/*註銷gpio*/		
	/*4、設備驅動註銷部分*/			
	device_destroy(mod_device.class,mod_device.devid);/*註銷設備節點*/
	class_destroy(mod_device.class);/*註銷類*/
	cdev_del(&mod_device.cdev);/*註銷cdev*/
	unregister_chrdev_region(mod_device.devid,DeviceNodes);/*註銷chrdev*/
}
module_init(key0_interrupt_init);
module_exit(key0_interrupt_exit);
MODULE_LICENSE("GPL");

五、app-select() >>driver-poll()的APP測試程序

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <poll.h>
/*
 *argc:應用程序參數個數
 *argv[]:具體的參數內容,字符串形式 
 *./devicetree-key-blockio-app.out <filename>  
 * ./devicetree-key-blockio-app.out /dev/mx6uirq
 */
int main(int argc, char *argv[])
{
    fd_set readfds;
    int fd, ret;
    char *filename;
    unsigned char data;
    struct timeval timeout;

    if(argc != 2) { printf("Error Usage!\r\n"); return -1; }
    filename = argv[1];
    fd = open(filename, O_RDWR | O_NONBLOCK);/*以非阻塞方式打開*/
    if(fd < 0) {
        printf("file %s open failed!\r\n", filename);
        return -1;
    }
    /* 循環讀取 */
    while(1) {
        FD_ZERO(&readfds);       /*清零readfds*/
        FD_SET(fd,&readfds);     /*把文件描述符加入readfds*/
        timeout.tv_sec = 3;      /*初始化超時時間秒(0s)*/
        timeout.tv_usec = 0;/*初始化超時時間毫秒(500ms)*/
        ret = select(fd+1,&readfds,NULL,NULL,&timeout);
        switch(ret)
        {
            case  0:/*超時*/
                printf("select->超時\r\n");
                break;
            case -1:/*錯誤*/
                printf("select->錯誤\r\n");
                break;
            default:/*可以讀取數據*/
                if(FD_ISSET(fd,&readfds)){
                    ret = read(fd, &data, sizeof(data));
                    if(ret < 0) {printf("read error code %d\r\n",ret);} 
                    else { if(data)printf("key value = %#x\r\n", data); }
                }
        }
    }
    close(fd);
    return 0;
}

六、app-poll() >>driver-poll()的APP測試程序

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <poll.h>
/*
 *argc:應用程序參數個數
 *argv[]:具體的參數內容,字符串形式 
 */
int main(int argc, char *argv[])
{
    struct pollfd fds;
    int fd, ret;
    char *filename;
    unsigned char data;
    if(argc != 2) {
        printf("Error Usage!\r\n");
        return -1;
    }
    filename = argv[1];
    fd = open(filename, O_RDWR | O_NONBLOCK);   /* 非阻塞打開 */
    if(fd < 0) {
        printf("file %s open failed!\r\n", filename);
        return -1;
    }
    /* 循環讀取 */
    while(1) {
        fds.fd = fd;
        fds.events = POLLIN;
        ret = poll(&fds, 1, 500); /* 超時500ms */
        if(ret == 0)  {     /* 超時 */
        } else if( ret < 0) { /* 錯誤 */
        } else {            /* 可以讀取 */
            if(fds.revents | POLLIN) {  /* 可讀取 */
                ret = read(fd, &data, sizeof(data));
                if(ret < 0) {
                 } else {
                if(data)
                     printf("key value = %#x\r\n", data);
                 }
            }
        }
    }
    close(fd);
    return 0;
}

七、歡迎加入全國大學生電子交流羣,這裏有很多程序和資源共享

歡迎加入屬於大學生的開源QQ電子討論羣
在這裏插入圖片描述

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