基于等待队列及poll机制的按键驱动代码分析和测试代码

时间:2021-11-05 17:37:19

按键驱动分析:

#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/wait.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <asm/uaccess.h>
#include <linux/gpio.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/miscdevice.h>
//#include <linux/time.h>

#include <linux/device.h>

struct class *key_class;//udev机制自动创建文件结点

#define USING_TASKLET
//struct timespec start_time;
//struct timespec end_time;
static int key_major = 0;

struct key_irq_desc {
 //       unsigned int irq;//对拥鼻暗膇  irq 号
    int pin;             //对应的管脚
    int pin_setting;//将邋邋GPIO口设置为外部中断源
    int number;
    char *name;    
};

/* 用来指定按键所用的外部中断引脚及中断触发方式, 名字 */
static struct key_irq_desc key_irqs [] = {
    {S5PV210_GPH0(3), S3C_GPIO_SFN(0xf), 0, "KEY1"}, /* K1 */
    {S5PV210_GPH0(4), S3C_GPIO_SFN(0xf), 1, "KEY2"}, /* K2 */
    {S5PV210_GPH0(5), S3C_GPIO_SFN(0xf), 2, "KEY3"}, /* K3 */
    {S5PV210_GPH0(6), S3C_GPIO_SFN(0xf), 3, "KEY4"}, /* K4 */
    {S5PV210_GPH0(7), S3C_GPIO_SFN(0xf), 4, "KEY5"}, /* K5 */
};

/* 按键被按下的次数(准确地说,是发生中断的次数) */
static volatile int key_values[] = {0, 0, 0, 0, 0};

/* 等待队列: 
 * 当没有按键被按下时,如果有进程调用key_read函数,
 * 它将休眠
 */
static DECLARE_WAIT_QUEUE_HEAD(key_waitq); //初始化一个等待队列头key_waitq

/* 中断事件标志, 中断服务程序将它置1,key_read将它清0 */
static volatile int ev_press = 0;//按下为1,抬起为0

#ifdef USING_TASKLET
static struct tasklet_struct key_tasklet;
static void key_do_tasklet(unsigned long);
//DECLARE_TASKLET(key_tasklet, key_do_tasklet, 0);//在init中初始化

static void key_do_tasklet(unsigned long data)
{
    printk("key_do_tasklet\n");
}
#endif

static irqreturn_t key_interrupt(int irq, void *dev_id)
{    
    printk("in the key_interrupt before wake_up!!\n");
//    clock_gettime(CLOCK_REALTIME, &start_time);
//    printk("%d\n%d\n",start_time.tvsec,start_time.tv_nsec);
    struct key_irq_desc *key_irqs = (struct key_irq_desc *)dev_id;//see at request_irq
        int up = gpio_get_value(key_irqs->pin);

    printk("<1>up=%d\n",up);
    if (up)
        key_values[key_irqs->number] = (key_irqs->number + 1) + 0x80;
    else
        key_values[key_irqs->number] += 1;
    
        ev_press = 1;                  /* 表示中断发生了 */
        wake_up_interruptible(&key_waitq);   /* 唤醒休眠的进程 */
    printk("in the key_interrupt after wake_up!!\n");
#ifdef USING_TASKLET
    tasklet_schedule(&key_tasklet);//调度key_do_tasklet
#endif
    
        return IRQ_RETVAL(IRQ_HANDLED);
//    clock_gettime(CLOCK_REALTIME, &end_time);
//    printf("%d\n%d\n",end_time.tvsec,end_time.tv_nsec);
}


/* 应用程序对设备文件/dev/key执行open(...)时,
 * 就会调用key_open函数
 */
static int key_open(struct inode *inode, struct file *file)
{
    printk("in the key_open!\n");
    int i;
    int err;
    int irq;
    
    for (i = 0; i < sizeof(key_irqs)/sizeof(key_irqs[0]); i++) {
        // 注册中断处理函数
    s3c_gpio_cfgpin(key_irqs[i].pin,key_irqs[i].pin_setting);//配置邋邋GPIO口
    irq=gpio_to_irq(key_irqs[i].pin);
    err = request_irq(irq, key_interrupt, IRQ_TYPE_EDGE_BOTH, 
                          key_irqs[i].name, (void *)&key_irqs[i]);// 设备ID号
    //set_irq_type(key_irqs[i].irq, IRQ_TYPE_EDGE_FALLING);//<linux/irq.h> 下降沿触发
    // IRQ_TYPE_EDGE_RISING, IRQ_TYPE_EDGE_BOTH, IRQ_TYPE_EDGE_HIGH, 
    // IRQ_TYPE_EDGE_LOW
        if (err)
            break;
    }
    if (err) {
        // 释放已经注册的中断
        i--;
        for (; i >= 0; i--) {
        irq=gpio_to_irq(key_irqs[i].pin);    
        disable_irq(irq);
        free_irq(irq, (void *)&key_irqs[i]);
        }
        return -EBUSY;
    }
    
    return 0;
}


/* 应用程序对设备文件/dev/key执行close(...)时,
 * 就会调用key_close函数
 */
static int key_close(struct inode *inode, struct file *file)
{
    int i;
    int irq;
    for (i = 0; i < sizeof(key_irqs)/sizeof(key_irqs[0]); i++) {
        irq=gpio_to_irq(key_irqs[i].pin);
        // 释放已经注册的中断
        disable_irq(irq);
        free_irq(irq, (void *)&key_irqs[i]);
        //释放gpio口
        gpio_free(key_irqs[i].pin);
    }

    return 0;
}


/* 应用程序对设备文件/dev/key执行read(...)时,
 * 就会调用key_read函数
 */
static int key_read(struct file *filp, char __user *buff, 
                        size_t count, loff_t *offp)
{
    printk("in the key_read before wait_event!!\n");
    
    unsigned long err;

    if (!ev_press) {
        if (filp->f_flags & O_NONBLOCK)
            return -EAGAIN;//如果是阻塞访问则直接返回
        else
            {
            /* 如果ev_press等于0,休眠,直到key_waitq被唤醒,并且ev_press为真*/
            wait_event_interruptible(key_waitq, ev_press);
        
        printk("(1)in the key_read after wait_event!!\n");
            }
    }
    
    printk("(2)in the key_read after wait_event!!\n");
    /* 执行到这里时,ev_press等于1,将它清0 */
    ev_press = 0;

    /* 将按键状态复制给用户,并清0 */
    //copy_to_user(void __user * to,const void * from,unsigned long n)
    err = copy_to_user(buff, (const void *)key_values, min(sizeof(key_values), count));
    memset((void *)key_values, 0, sizeof(key_values));//清零

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

/**************************************************
* 当用户程序调用select函数时,本函数被调用
* 如果有按键数据,则select函数会立刻返回
* 如果没有按键数据,本函数使用poll_wait等待
**************************************************/
static unsigned int key_poll(struct file *file,
                     struct poll_table_struct *wait)
{
    printk("in the key_poll!!\n");
    unsigned int mask = 0;
        poll_wait(file, &key_waitq, wait);//将等待队列添加到poll_table
        if (ev_press)
            mask |= POLLIN | POLLRDNORM;/*数据可获得*/

        return mask;//mask=0;休眠timeout
}


/* 这个结构是字符设备驱动程序的核心
 * 当应用程序操作设备文件时所调用的open、read、write等函数,
 * 最终会调用这个结构中的对应函数
 */
static struct file_operations key_fops = {
    .owner   =   THIS_MODULE,    /* 这是一个宏,指向编译模块时自动创建的__this_module变量 */
    .open    =   key_open,
    .release =   key_close, 
    .read    =   key_read,
    .poll    =   key_poll,
};


/*
 * Set up the cdev structure for a device.
 */
static void key_setup_cdev(struct cdev *dev, int minor,
                struct file_operations *fops)
{
        int err, devno = MKDEV(key_major, minor);

        cdev_init(dev, fops);
        dev->owner = THIS_MODULE;
        dev->ops = fops;
        err = cdev_add (dev, devno, 1);
        /* Fail gracefully if need be */
        if (err)
                printk (KERN_NOTICE "Error %d adding key%d", err, minor);
}


/*
 * We export one key device.  There's no need for us to maintain any
 * special housekeeping info, so we just deal with raw cdev.
 */
static struct cdev key_cdev;


/*
 * 执行"insmod key_drv.ko" 命令时就会调用这个函数
 */
static int __init userkey_init(void)
//static int key_init(void)
{
    int result;
    dev_t dev = MKDEV(key_major, 0);
    char dev_name[]="key";

    /*request gpio*/
    int ret;
    int i=0;
    for(i=0;i<5;i++)
        {
            ret = gpio_request(key_irqs[i].pin, "KEY");
            if (ret) 
            {
                printk("%s:request GPIO %d for KEY failed,ret= %d\n",dev_name,key_irqs[i],ret);    
            }
        }

                                                                                                         
    /* Figure out our device number. */
    if (key_major)
                result = register_chrdev_region(dev, 1, dev_name);
    else {
                result = alloc_chrdev_region(&dev, 0, 1, dev_name);
                key_major = MAJOR(dev);
        }
    if (result < 0) {
                printk(KERN_WARNING "key: unable to get major %d\n", key_major);
                return result;
    }
    if (key_major == 0)
                key_major = result;

#ifdef USING_TASKLET
    tasklet_init(&key_tasklet, key_do_tasklet, 0);//初始化底半部机制tasklet
#endif                                                                                                         
    /* Now set up cdev. */
    key_setup_cdev(&key_cdev, 0, &key_fops);

    /*udev自动创建文件结点*/
    key_class = class_create(THIS_MODULE, "key_class");
    device_create(key_class, NULL, dev, NULL,dev_name);

    printk("key device installed, with major %d\n", key_major);
    printk("The device name is: /dev/%s\n", dev_name);
 
    return 0;
}

/*
 * 执行rmod key_drv”命令时就会调用这个函数 
 */
static void __exit userkey_exit(void)
{

    
    device_destroy(key_class, key_cdev.dev);
    class_destroy(key_class);
    cdev_del(&key_cdev);
    unregister_chrdev_region(MKDEV(key_major, 0), 1);

#ifdef USING_TASKLET
    tasklet_kill(&key_tasklet);
#endif
        printk("key device uninstalled\n");
}

/* 这两行指定驱动程序的初始化函数和卸载函数 */
module_init(userkey_init);
module_exit(userkey_exit);

/* 描述驱动程序的一些信息,不是必须的 */
MODULE_AUTHOR("mhb@SEU");             // 驱动程序的作者
MODULE_DESCRIPTION("KEY Driver");   // 一些描述信息
MODULE_LICENSE("Dual BSD/GPL");                              // 遵循的协议

测试实例代码:

#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(void)
{

    int i;
    int key_fd;
    int key_value[]={0,0,0,0,0};

    /*打开键盘设备文件*/
    key_fd = open("/dev/key", 0);
    printf("key_fd=%d!!\n",key_fd);
    if (key_fd < 0) {
        perror("open device key");
        exit(1);
    }
    for (;;) {
        fd_set rds;
        int ret;

        FD_ZERO(&rds);
        FD_SET(key_fd, &rds);

        /*使用系统调用select检查是否能够从/dev/key设备读取数据*/
        ret = select(key_fd + 1, &rds, NULL, NULL, NULL);
        
        /*读取出错则退出程序*/
        if (ret < 0) {
            perror("select");
            exit(1);
        }
        
        if (ret == 0) {
            printf("Timeout.\n");
        } 
        /*能够读取到数据*/
        else if (FD_ISSET(key_fd, &rds)) {
            /*开始读取键盘驱动发出的数据,注意key_value和键盘驱动中定义为一致的类型*/
            int ret = read(key_fd, key_value, sizeof key_value);
            if (ret != sizeof key_value) {
                if (errno != EAGAIN)
                    perror("read key\n");
                continue;
            } else {
                /*打印键值*/
                for (i = 0; i < 5; i++)
                    printf("K%d %s, key value = 0x%02x\n", \
                       i+1, (key_value[i] & 0x80) ? "released": \
                                   key_value[i] ? "pressed down" : "", key_value[i]);
                     key_value[i] = 0;
            }
                
        }
    }

    /*关闭设备文件句柄*/
    close(key_fd);
    return 0;
}

输出:

/*output
[root@FORLINX210]# insmod int_key_drv.ko 
[   27.114321] key device installed, with major 247
[   27.118175] The device name is: /dev/key
[root@FORLINX210]# ./key_test 
[   30.396897] in the key_open!
[   30.398527] in the key_poll!!
key_fd=3!!
[   33.959336] in the key_interrupt before wake_up!!
[   33.962558] up=0
[   33.964379] in the key_interrupt after wake_up!!
[   33.968974] key_do_tasklet
[   33.971669] in the key_poll!!
[   33.974631] in the key_read before wait_event!!
[   33.979124] (2)in the key_read after wait_event!!
[   33.983897] in the key_poll!!
K1 pressed down, key value = 0x01
K2 , key value = 0x00
K3 , key value = 0x00
K4 , key value = 0x00
K5 , key value = 0x00
[   37.173298] in the key_interrupt before wake_up!!
[   37.176516] up=1
[   37.178338] in the key_interrupt after wake_up!!
[   37.182932] key_do_tasklet
[   37.185625] in the key_poll!!
[   37.188582] in the key_read before wait_event!!
[   37.193085] (2)in the key_read after wait_event!!
[   37.197830] in the key_poll!!
K1 released, key value = 0x81
K2 , key value = 0x00
K3 , key value = 0x00
K4 , key value = 0x00
K5 , key value = 0x00
[   42.013178] in the key_interrupt before wake_up!!
[   42.016393] up=0
[   42.018213] in the key_interrupt after wake_up!!
[   42.022808] key_do_tasklet
[   42.025501] in the key_poll!!
[   42.028457] in the key_read before wait_event!!
[   42.032961] (2)in the key_read after wait_event!!
[   42.037702] in the key_poll!!
K1 , key value = 0x00
K2 pressed down, key value = 0x01
K3 , key value = 0x00
K4 , key value = 0x00
K5 , key value = 0x00
[   51.785335] in the key_interrupt before wake_up!!
[   51.788557] up=1
[   51.790377] in the key_interrupt after wake_up!!
[   51.794971] key_do_tasklet
[   51.797664] in the key_poll!!
[   51.800603] in the key_read before wait_event!!
[   51.805127] (2)in the key_read after wait_event!!
[   51.809867] in the key_poll!!
K1 , key value = 0x00
K2 released, key value = 0x82
K3 , key value = 0x00
K4 , key value = 0x00
K5 , key value = 0x00
*/