linux__select_poll_驱动编程(不断更新中)

作者: sno_guo
发布时间:2015-07-29 11:42:04

关于在驱动程序中编写poll函数的理解
poll函数的实质,是把一个队列加入到poll_table这个大的轮循中,开始轮循,不断的循环检查是否有可以执行的队列,如果有
在file_operations这个结构体中的poll函数 指针是这样定义的:
static unsigned int s3c64xx_buttons_poll( struct file *file, struct poll_table_struct *wait)
其中参数 file是文件名,这个每个函数都有的,第二个参数是: struct poll_table_struct 结构体的指针,作用是利用poll_wait函数把某个DECLARE_WAIT_QUEUE_HEAD定义
的队列变量加入到队列中。然后设置一下这个设备的访问权限。
一般的模板是:
static unsigned int XXX_poll(struct file *filp, poll_table *wait)
{
    unsigned int mask = 0;
        struct XXX_dev *dev = filp->private_data;     //获得设备结构指针
    ...
    poll_wait(filp, &dev->r_wait, wait);    //加读等待对列头
    poll_wait(filp ,&dev->w_wait, wait);    //加写等待队列头
    
    if(...)//可读  这里可以加判断语句,也可以不加
    {
          mask |= POLLIN | POLLRDNORM;    //标识数据可获得
     }
    if(...)//可写
    {
          mask |= POLLOUT | POLLRDNORM;    //标识数据可写入
     }
    ..
    return mask;
}


对模板中poll_wait函数的理解:
定义:
void poll_wait(struct file *filp, wait_queue_head_t *queue, poll_table *wait);
  参数解释: wait_queue_head_t类型的指针,就是你定义的队列,poll_table 是要加入的轮循,是有函数的形参,直接写上就可以了。
  函数目的: 把定义的wait_queue_head_t类型的变量加入到 轮循中,开始轮循。注意,千万不要被"poll_wait"这个“wait”字眼迷惑了,这里不是等待。
一般返回的mask有:
    mask |= POLLIN | POLLRDNORM; //说明当前的设备可以进行非阻塞读,即应用层调用read函数后立即返回,不在这里阻塞。
    mask |= POLLOUT | POLLRDNORM; //说明当前的设备可以进行非阻塞写,即应用层调用write函数后可被写入而不阻塞.


返回的其他参数有:
POLLIN	普通或优先级带数据可读
POLLRDNORM	普通数据可读
POLLRDBAND	优先级带数据可读
POLLPRI	高优先级数据可读
POLLOUT	普通数据可写
POLLWRNORM	普通数据可写
POLLWRBAND	优先级带数据可写
POLLERR	发生错误
POLLHUP	发生挂起
POLLNVAL	描述字不是一个打开的文件






驱动的编写可以采用这样的形式 主要是实现:
static const struct file_operations mem_fops =
{
  .owner = THIS_MODULE,
  .llseek = mem_llseek,
  .read = mem_read,
  .write = mem_write,
  .open = mem_open,
  .release = mem_release,
  .poll = mem_poll,
};
其中 .poll是用让应用层使用select或poll设备用的。  至于这个file_operations是用misc设备或者cdev设备,就是把这个mem_fops套进相关函数即可。
下面是先写出cdev设备的,相关程序/

 /*//memdev.h 自定义头文件
******************************************************************************/
#ifndef _MEMDEV_H_
#define _MEMDEV_H_
#ifndef MEMDEV_MAJOR
#define MEMDEV_MAJOR 201   /*预设的mem的主设备号 if run insmod  terminal print Device or resource busy change here*/
#endif
#ifndef MEMDEV_NR_DEVS
#define MEMDEV_NR_DEVS 2    /*设备数*/
#endif
#ifndef MEMDEV_SIZE
#define MEMDEV_SIZE 4096//分配内存的大小
#endif
/*mem设备描述结构体*/
struct mem_dev                                     
{                                                        
  char *data; //分配到的内存的起始地址                     
  unsigned long size;  //内存的大小 
   wait_queue_head_t inq;    
};
#endif /* _MEMDEV_H_ */





#include <Linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/uaccess.h>

#include <linux/poll.h>
#include "memdev.h"

static mem_major = MEMDEV_MAJOR;
bool have_data = false; /*表明设备有足够数据可供读*/

module_param(mem_major, int, S_IRUGO);

struct mem_dev *mem_devp; /*设备结构体指针*/

struct cdev cdev; 

/*文件打开函数*/
int mem_open(struct inode *inode, struct file *filp)
{
    struct mem_dev *dev;
    
    /*获取次设备号*/
    int num = MINOR(inode->i_rdev);

    if (num >= MEMDEV_NR_DEVS) 
            return -ENODEV;
    dev = &mem_devp[num];
    
    /*将设备描述结构指针赋值给文件私有数据指针*/
    filp->private_data = dev;
    
    return 0; 
}
int mem_release(struct inode *inode, struct file *filp)/*文件释放函数*/
{
  return 0;
}


static ssize_t mem_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)/*读函数*/
{
  unsigned long p =  *ppos;
  unsigned int count = size;
  int ret = 0;
  struct mem_dev *dev = filp->private_data; /*获得设备结构体指针*/

  /*判断读位置是否有效*/
  if (p >= MEMDEV_SIZE)
    return 0;
  if (count > MEMDEV_SIZE - p)
    count = MEMDEV_SIZE - p;
    
  while (!have_data) /* 没有数据可读,考虑为什么不用if,而用while */
  {
        if(filp->f_flags & O_NONBLOCK)
            return -EAGAIN;   
       wait_event_interruptible(dev->inq,have_data);//waiting for have_datea ==ture
  }

  /*读数据到用户空间*/
  if (copy_to_user(buf, (void*)(dev->data + p), count))
  {
    ret =  - EFAULT;
  }
  else
  {
    *ppos += count;
    ret = count;
    printk(KERN_INFO "read %d bytes(s) from %d\n", count, p);
  }
       have_data = false; /* 表明不再有数据可读 */
  
  return ret;
}
static ssize_t mem_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos)/*写函数*/
{
  unsigned long p =  *ppos;
  unsigned int count = size;
  int ret = 0;
  struct mem_dev *dev = filp->private_data; /*获得设备结构体指针*/
  
  /*分析和获取有效的写长度*/
  if (p >= MEMDEV_SIZE)
    return 0;
  if (count > MEMDEV_SIZE - p)
    count = MEMDEV_SIZE - p;

  /*从用户空间写入数据*/
  if (copy_from_user(dev->data + p, buf, count))
    ret =  - EFAULT;
  else
  {
    *ppos += count;
    ret = count;
    
    printk(KERN_INFO "written %d bytes(s) from %d\n", count, p);
  }
  
  have_data = true; /* 有新的数据可读 */
    
    /* 唤醒读进程 */
    wake_up(&(dev->inq));

  return ret;
}
static loff_t mem_llseek(struct file *filp, loff_t offset, int whence)/* seek文件定位函数 */
{ 
    loff_t newpos;

    switch(whence) {
      case 0: /* SEEK_SET */
        newpos = offset;
        break;

      case 1: /* SEEK_CUR */
        newpos = filp->f_pos + offset;
        break;

      case 2: /* SEEK_END */
        newpos = MEMDEV_SIZE -1 + offset;
        break;

      default: /* can't happen */
        return -EINVAL;
    }
    if ((newpos<0) || (newpos>MEMDEV_SIZE))
        return -EINVAL;
        
    filp->f_pos = newpos;
    return newpos;

}
unsigned int mem_poll(struct file *filp, poll_table *wait)
{
    struct mem_dev  *dev = filp->private_data; 
    unsigned int mask = 0;  
   
    poll_wait(filp, &dev->inq,  wait);/*将等待队列添加到poll_table表中 */
     
    if (have_data)         
    mask |= POLLIN | POLLRDNORM;  /* readable */

    return mask;
}


/*文件操作结构体*/
static const struct file_operations mem_fops =
{
  .owner = THIS_MODULE,
  .llseek = mem_llseek,
  .read = mem_read,
  .write = mem_write,
  .open = mem_open,
  .release = mem_release,
  .poll = mem_poll,
};

/*设备驱动模块加载函数*/
static int memdev_init(void)
{
  int result;
  int i;

  dev_t devno = MKDEV(mem_major, 0);

  /* 静态申请设备号*/
  if (mem_major)
    result = register_chrdev_region(devno, 2, "memdev");
  else  /* 动态分配设备号 */
  {
    result = alloc_chrdev_region(&devno, 0, 2, "memdev");
    mem_major = MAJOR(devno);
  }  
  
  if (result < 0)
    return result;

  /*初始化cdev结构*/
  cdev_init(&cdev, &mem_fops);
  cdev.owner = THIS_MODULE;
  cdev.ops = &mem_fops;
  
  /* 注册字符设备 */
  cdev_add(&cdev, MKDEV(mem_major, 0), MEMDEV_NR_DEVS);
   
  /* 为设备描述结构分配内存*/
  mem_devp = kmalloc(MEMDEV_NR_DEVS * sizeof(struct mem_dev), GFP_KERNEL);
  if (!mem_devp)    /*申请失败*/
  {
    result =  - ENOMEM;
    goto fail_malloc;
  }
  memset(mem_devp, 0, sizeof(struct mem_dev));
  
  /*为设备分配内存*/
  for (i=0; i < MEMDEV_NR_DEVS; i++) 
  {
        mem_devp[i].size = MEMDEV_SIZE;
        mem_devp[i].data = kmalloc(MEMDEV_SIZE, GFP_KERNEL);
        memset(mem_devp[i].data, 0, MEMDEV_SIZE);
  
      /*初始化等待队列*/
     init_waitqueue_head(&(mem_devp[i].inq));
     //init_waitqueue_head(&(mem_devp[i].outq));
  }
   
  return 0;

  fail_malloc: 
  unregister_chrdev_region(devno, 1);
  
  return result;
}

/*模块卸载函数*/
static void memdev_exit(void)
{
  cdev_del(&cdev);   /*注销设备*/
  kfree(mem_devp);     /*释放设备结构体内存*/
  unregister_chrdev_region(MKDEV(mem_major, 0), 2); /*释放设备号*/
}

MODULE_AUTHOR("David Xie");
MODULE_LICENSE("GPL");

module_init(memdev_init);
module_exit(memdev_exit);
=============================================================
写文件  app_write
#include <stdio.h>

int main()
{
    FILE *fp = NULL;
    char Buf[128];
    
    
    /*打开设备文件*/
    fp = fopen("/dev/memdev","r+");
    if (fp == NULL)
    {
        printf("Open Dev memdev0 Error!\n");
        return -1;
    }
    
    /*写入设备*/
    strcpy(Buf,"memdev is char dev!");
    printf("Write BUF: %s\n",Buf);
    fwrite(Buf, sizeof(Buf), 1, fp);
    
   // sleep(1);
    fclose(fp);
    
    return 0;    

}
=================================
读文件 app_read
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <errno.h> 
 int main() 
{ 
    int fd; 
    fd_set rds;    //声明描述符集合
    int ret; 
    char Buf[128]; 
     
    struct   timeval   timeout; 
    
    /*初始化Buf*/ 
    strcpy(Buf,"memdev is char dev!"); 
    printf("BUF: %s\n",Buf); 
     
    /*打开设备文件*/ 
    fd = open("/dev/memdev",O_RDWR); 
    if(fd< 0) {
        perror("open dev/memdev");
        exit(1);
    }
    FD_ZERO(&rds);   //清空描述符集合
    FD_SET(fd, &rds); //设置描述符集合
 
    /*清除Buf*/ 
    strcpy(Buf,"Buf is NULL!"); 
    printf("Read BUF1: %s\n",Buf); 
timeout.tv_sec=10; 
timeout.tv_usec=0; 

    ret = select(fd + 1, &rds, NULL, NULL, &timeout);//调用select()监控函数
    if (ret < 0)  
    {
        printf("select error!\n");
        exit(1);
    }
    if (FD_ISSET(fd, &rds))   //测试fd1是否可读  
        read(fd, Buf, sizeof(Buf));             
     
    /*检测结果*/ 
    printf("Read sssssBUF2: %s\n",Buf);
    
    close(fd); 
     
    return 0;     
}


====================================================
makefile  文件:

ARCH = arm
CROSS_COMPILE = arm-linux-

#target name #################
TARGET_NAME=test_mem_dev

# path define here
INSTALL_PATH := /home/sno/mini2440/rootfs_qtopia_qt4/home/drivers/
KERNEL_DIR := /opt/FriendlyARM/mini2440/linux-2.6.32.2/
PWD := $(Shell pwd)

obj-m := $(TARGET_NAME).o


all:
	make ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) -C $(KERNEL_DIR) SUBDIRS=$(PWD) modules
clean:
	rm *.o *.ko *.mod.c
install:
		sudo install $(TARGET_NAME).ko  $(INSTALL_PATH)
uninstall:
		rm -f $(INSTALL_PATH)/$(TARGET_NAME).ko	
.PHONY:clean


===============================================================================================
********************************************************************************************
******************************************************************************************
或者采用:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/poll.h>
#include <linux/irq.h>
#include <asm/irq.h>
#include <linux/interrupt.h>
#include <asm/uaccess.h>
#include <mach/regs-gpio.h>
#include <mach/hardware.h>
#include <linux/platform_device.h>
#include <linux/cdev.h>
#include <linux/miscdevice.h>
#include <linux/sched.h>
#include <linux/gpio.h>

#define DEVICE_NAME     "buttons"

struct button_irq_desc {
    int irq;
    int pin;
    int pin_setting;
    int number;
    char *name;	
};


static struct button_irq_desc button_irqs [] = {
   /* {IRQ_EINT8 , S3C2410_GPG(0) ,  S3C2410_GPG0_EINT8  , 0, "KEY0"},
    {IRQ_EINT11, S3C2410_GPG(3) ,  S3C2410_GPG3_EINT11 , 1, "KEY1"},
    {IRQ_EINT13, S3C2410_GPG(5) ,  S3C2410_GPG5_EINT13 , 2, "KEY2"},
    {IRQ_EINT14, S3C2410_GPG(6) ,  S3C2410_GPG6_EINT14 , 3, "KEY3"},
    {IRQ_EINT15, S3C2410_GPG(7) ,  S3C2410_GPG7_EINT15 , 4, "KEY4"},
    {IRQ_EINT19, S3C2410_GPG(11),  S3C2410_GPG11_EINT19, 5, "KEY5"},*/
	{IRQ_EINT19,	S3C2410_GPG(11),	S3C2410_GPG11_EINT19,	0, "KEY1"}, /* K1 */
	{IRQ_EINT11,	S3C2410_GPG(3),	S3C2410_GPG3_EINT11,	1, "KEY2"}, /* K2 */
	{IRQ_EINT2,	S3C2410_GPF(2),	S3C2410_GPF2_EINT2,	2, "KEY3"}, /* K3 */
	{IRQ_EINT0,	S3C2410_GPF(0),	S3C2410_GPF0_EINT0,	3, "KEY4"}, /* K4 */
};
static volatile char key_values [] = {'0', '0', '0', '0'};

static DECLARE_WAIT_QUEUE_HEAD(button_waitq);

static volatile int ev_press = 0;


static irqreturn_t buttons_interrupt(int irq, void *dev_id)
{
    struct button_irq_desc *button_irqs = (struct button_irq_desc *)dev_id;
    int down;

    // udelay(0);
    down = !s3c2410_gpio_getpin(button_irqs->pin);

    if (down != (key_values[button_irqs->number] & 1)) { // Changed

	key_values[button_irqs->number] = '0' + down;
	
        ev_press = 1;
        wake_up_interruptible(&button_waitq);
    }
    
    return IRQ_RETVAL(IRQ_HANDLED);
}


static int s3c24xx_buttons_open(struct inode *inode, struct file *file)
{
    int i;
    int err = 0;
    
    for (i = 0; i < sizeof(button_irqs)/sizeof(button_irqs[0]); i++) {
	if (button_irqs[i].irq < 0) {
		continue;
	}
        err = request_irq(button_irqs[i].irq, buttons_interrupt, IRQ_TYPE_EDGE_BOTH, 
                          button_irqs[i].name, (void *)&button_irqs[i]);
        if (err)
            break;
    }

    if (err) {
        i--;
        for (; i >= 0; i--) {
	    if (button_irqs[i].irq < 0) {
		continue;
	    }
	    disable_irq(button_irqs[i].irq);
            free_irq(button_irqs[i].irq, (void *)&button_irqs[i]);
        }
        return -EBUSY;
    }

    ev_press = 1;
    
    return 0;
}


static int s3c24xx_buttons_close(struct inode *inode, struct file *file)
{
    int i;
    
    for (i = 0; i < sizeof(button_irqs)/sizeof(button_irqs[0]); i++) {
	if (button_irqs[i].irq < 0) {
	    continue;
	}
	free_irq(button_irqs[i].irq, (void *)&button_irqs[i]);
    }

    return 0;
}


static int s3c24xx_buttons_read(struct file *filp, char __user *buff, size_t count, loff_t *offp)
{
    unsigned long err;

    if (!ev_press) {
	if (filp->f_flags & O_NONBLOCK)
	    return -EAGAIN;
	else
	    wait_event_interruptible(button_waitq, ev_press);
    }
    
    ev_press = 0;

    err = copy_to_user(buff, (const void *)key_values, min(sizeof(key_values), count));

    return err ? -EFAULT : min(sizeof(key_values), count);
}

static unsigned int s3c24xx_buttons_poll( struct file *file, struct poll_table_struct *wait)
{
    unsigned int mask = 0;
    poll_wait(file, &button_waitq, wait);
    if (ev_press)
        mask |= POLLIN | POLLRDNORM;
    return mask;
}


static struct file_operations dev_fops = {
    .owner   =   THIS_MODULE,
    .open    =   s3c24xx_buttons_open,
    .release =   s3c24xx_buttons_close, 
    .read    =   s3c24xx_buttons_read,
    .poll    =   s3c24xx_buttons_poll,
};

static struct miscdevice misc = {
	.minor = MISC_DYNAMIC_MINOR,
	.name = DEVICE_NAME,
	.fops = &dev_fops,
};

static int __init dev_init(void)
{
	int ret;

	ret = misc_register(&misc);

	printk (DEVICE_NAME"\tinitialized\n");

	return ret;
}

static void __exit dev_exit(void)
{
	misc_deregister(&misc);
}

module_init(dev_init);
module_exit(dev_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("FriendlyARM Inc is gt2440 .");

/*实现原理 :  就是使用等待队列。。。。。。。

1、等待队列的实现:
  在linux中,等待队列的结构如下:
struct __wait_queue_head {
spinlock_t lock; //自旋锁,用来对task_list链表起保护作用,实现了对等待队列的互斥访问
struct list_head task_list; //用来存放等待的进程
};
typedef struct __wait_queue_head wait_queue_head_t;
 
2、等待队列的使用
(1)定义和初始化等待队列:
wait_queue_head_t wait;//定义等待队列
init_waitqueue_head(&wait);//初始化等待队列
定义并初始化等待队列:
#define DECLARE_WAIT_QUEUE_HEAD(name) wait_queue_head_t name = __WAIT_QUEUE_HEAD_INITIALIZER(name)
(2)添加或移除等待队列:
void add_wait_queue(wait_queue_head_t *q, wait_queue_t *wait);//将等待队列元素wait添加到等待队列头q所指向的等待队列链表中。
void remove_wait_queue(wait_queue_head_t *q, wait_queue_t *wait);

(3)等待事件:
wait_event(wq, condition);//在等待队列中睡眠直到condition为真。
wait_event_timeout(wq, condition, timeout);
wait_event_interruptible(wq, condition) ;   ///没有分析透他们的区别????????????????????!!!!!!!!!!!!!!!
wait_event_interruptible_timeout(wq, condition, timeout) ;
(4)睡眠:
sleep_on(wait_queue_head_t *q);
interruptible_sleep_on(wait_queue_head_t *q);

 
(5)唤醒等待队列:
//可唤醒处于TASK_INTERRUPTIBLE和TASK_UNINTERRUPTIBLE状态的进程;
#define wake_up(x) __wake_up(x, TASK_NORMAL, 1, NULL)

//只能唤醒处于TASK_INTERRUPTIBLE状态的进程
#define wake_up_interruptible(x) __wake_up(x, TASK_INTERRUPTIBLE, 1, NULL)
*/

版权声明:本文为博主原创文章,未经博主允许不得转载。

标签: Linux select 编程
来源:http://blog.csdn.net/sno_guo/article/details/7646269

推荐: