arm9+linux fl2440之按鍵驅動 plat_button.c

#include "s3c_driver.h"

#define DRV_AUTHOR              
#define DRV_DESC                  "S3C24XX button driver"

/* Driver version*/
#define DRV_MAJOR_VER             1
#define DRV_MINOR_VER             0
#define DRV_REVER_VER             0

#define DEV_NAME                  DEV_BUTTON_NAME

//#define DEV_MAJOR               DEV_BUTTON_MAJOR
#ifndef DEV_MAJOR
#define DEV_MAJOR                 0 /* dynamic major by default */
#endif

#define BUTTON_UP                 0 /* Button status is up */
#define BUTTON_DOWN               1 /* Button status is pushed down */
#define BUTTON_UNCERTAIN          2 /* Button status uncerntain */

#define TIMER_DELAY_DOWN          (HZ/50)   /*Remove button push down dithering timer delay 20ms  */
#define TIMER_DELAY_UP            (HZ/10)   /*Remove button up dithering timer delay 100ms  */

static int debug = DISABLE;
static int dev_major = DEV_MAJOR;
static int dev_minor = 0;

/*============================ Platform Device part ===============================*/
/* Button hardware informtation structure*/
struct s3c_button_info
{
    unsigned char           num;       /*Button nubmer  */
    char *                  name;      /*Button nubmer  */
    int                     nIRQ;      /*Button IRQ number*/
    unsigned int            setting;   /*Button IRQ Pin Setting*/
    unsigned int            gpio;      /*Button GPIO port */
};

/* The button platform device private data structure */
struct s3c_button_platform_data
{
    struct s3c_button_info *buttons;
    int                     nbuttons;
};

/* Button hardware informtation data*/
static struct s3c_button_info  s3c_buttons[] = {
    [0] = {
        .num = 1,
        .name = "KEY1",
        .nIRQ = IRQ_EINT0,
        .gpio = S3C2410_GPF(0),
        .setting = S3C2410_GPF0_EINT0,
    },
    [1] = {
        .num = 2,
        .name = "KEY2",
        .nIRQ = IRQ_EINT2,
        .gpio = S3C2410_GPF(2),
        .setting = S3C2410_GPF2_EINT2,
    },
    [2] = {
        .num = 3,
        .name = "KEY3",
        .nIRQ = IRQ_EINT3,
        .gpio = S3C2410_GPF(3),
        .setting = S3C2410_GPF3_EINT3,
    },
    [3] = {
        .num = 4,
        .name = "KEY4",
        .nIRQ = IRQ_EINT4,
        .gpio = S3C2410_GPF(4),
        .setting = S3C2410_GPF4_EINT4,
    },
};

/* The button platform device private data */
static struct s3c_button_platform_data s3c_button_data = {
    .buttons = s3c_buttons,
    .nbuttons = ARRAY_SIZE(s3c_buttons),
};

struct button_device
{
    unsigned char                      *status;      /* The buttons Push down or up status */
    struct s3c_button_platform_data    *data;        /* The buttons hardware information data */

    struct timer_list                  *timers;      /* The buttons remove dithering timers */

//參考博客 http://blog.csdn.net/lanmanck/article/details/4528759

    wait_queue_head_t                  waitq;           /* Wait queue for poll()  */

//參考博客http://blog.csdn.net/lanmanck/article/details/4770103

    volatile int                       ev_press;     /* Button pressed event */

    struct cdev                        cdev;           
    struct class                       *dev_class; 
} button_device;

static void platform_button_release(struct device * dev)
{
    return; 
}

static struct platform_device s3c_button_device = {
    .name    = "s3c_button",
    .id      = 1,
    .dev     = 
    {
        .platform_data = &s3c_button_data, 
        .release = platform_button_release,
    },
};

static irqreturn_t s3c_button_intterupt(int irq,void *de_id)

{

關於中斷處理函數的返回值:中斷程序的返回值是一個特殊類型—irqreturn_t。但是中斷程序的返回值卻只有兩個—IRQ_NONE和IRQ_HANDLED。

#ifndef _LINUX_IRQRETURN_H

#define _LINUX_IRQRETURN_H

typedef int irqreturn_t;

#define IRQ_NONE       (0)

#define IRQ_HANDLED       (1)

#define IRQ_RETVAL(x)      ((x) != 0)  //這個宏只是返回0或非0

#endif

以上是在linux/irqreturn.h中的內容

    int i;
    int found = 0;
    struct s3c_button_platform_data *pdata = button_device.data;

    for(i=0; i<pdata->nbuttons; i++)
    {
        if(irq == pdata->buttons[i].nIRQ)
        {
            found = 1; 
            break;
        }
    }

    if(!found) /* An ERROR interrupt  */
        return IRQ_NONE;

    /* Only when button is up then we will handle this event */
    if(BUTTON_UP  == button_device.status[i])
    {
       button_device.status[i] = BUTTON_UNCERTAIN;
       mod_timer(&(button_device.timers[i]), jiffies+TIMER_DELAY_DOWN);
    }

    return IRQ_HANDLED;
}

static void button_timer_handler(unsigned long data)
{
    struct s3c_button_platform_data *pdata = button_device.data;
    int num =(int)data;
    int status = s3c2410_gpio_getpin( pdata->buttons[num].gpio );

    if(LOWLEVEL == status)
    {
        if(BUTTON_UNCERTAIN == button_device.status[num]) /* Come from interrupt */
        {
            //dbg_print("Key pressed!\n");
            button_device.status[num] = BUTTON_DOWN;

            printk("%s pressed.\n", pdata->buttons[num].name);

            /* Wake up the wait queue for read()/poll() */
            button_device.ev_press = 1;
            wake_up_interruptible(&(button_device.waitq));//喚醒註冊到等待隊列上的進程
        }

        /* Cancel the dithering  */
        mod_timer(&(button_device.timers[num]), jiffies+TIMER_DELAY_UP);
    }
    else
    {
        //dbg_print("Key Released!\n");
        button_device.status[num] = BUTTON_UP;
     //   enable_irq(pdata->buttons[num].nIRQ);
    }

    return ;
}

/*===================== Button device driver part ===========================*/
static int button_open(struct inode *inode, struct file *file)

    struct button_device *pdev ;
    struct s3c_button_platform_data *pdata;
    int i, result;

    pdev = container_of(inode->i_cdev,struct button_device, cdev);

//通過一個容器(結構體)中某個成員的指針得到指向這個容器(結構體)的指針,簡單的說就是通過成員找容器。

    pdata = pdev->data;
    file->private_data = pdev;

    /* Malloc for all the buttons remove dithering timer */
    pdev->timers = (struct timer_list *) kmalloc(pdata->nbuttons*sizeof(struct timer_list), GFP_KERNEL);
    /*
    #define GFP_KERNEL  (__GFP_WAIT | __GFP_IO | __GFP_FS) 在include/linux/gfp.h中定義的一個宏,是分配內核空間的一個標誌位。這個標誌位分配內存的一個選項,GFP_KERNEL是內核內存分配時最常
    用的,無內存可用是則引起休眠。
     */
    if(NULL == pdev->timers)
    {
        printk("Alloc %s driver for timers failure.\n", DEV_NAME);
        return -ENOMEM;
    }
    memset(pdev->timers, 0, pdata->nbuttons*sizeof(struct timer_list));

    /* Malloc for all the buttons status buffer */
    pdev->status = (unsigned char *)kmalloc(pdata->nbuttons*sizeof(unsigned char), GFP_KERNEL);
    if(NULL == pdev->status)
    {
        printk("Alloc %s driver for status failure.\n", DEV_NAME);
        result = -ENOMEM; 
        goto  ERROR;
    }
    memset(pdev->status, 0, pdata->nbuttons*sizeof(unsigned char));

    init_waitqueue_head(&(pdev->waitq));

    for(i=0; i<pdata->nbuttons; i++) 
    {
        /* Initialize all the buttons status to UP  */
        pdev->status[i] = BUTTON_UP; 

        /* Initialize all the buttons' remove dithering timer */
        setup_timer(&(pdev->timers[i]), button_timer_handler, i);

        /* Set all the buttons GPIO to EDGE_FALLING interrupt mode */
        s3c2410_gpio_cfgpin(pdata->buttons[i].gpio, pdata->buttons[i].setting);
        irq_set_irq_type(pdata->buttons[i].nIRQ, IRQ_TYPE_EDGE_FALLING);
        //設置觸發類型的中斷的引腳

        /* Request for button GPIO pin interrupt  */

        result = request_irq(pdata->buttons[i].nIRQ, s3c_button_intterupt, IRQF_DISABLED, DEV_NAME, (void *)i);

/*在linux內核中用於申請中斷的函數是request_irq(),函數原型在Kernel/irq/manage.c中定義:

int request_irq(unsigned int irq, irq_handler_t handler,
                         unsigned long irqflags, const char *devname, void *dev_id)

irq是要申請的硬件中斷號

handler是向系統註冊的中斷處理函數,是一個回調函數,中斷髮生時,系統調用這個函數,dev_id參數將被傳遞給它。

irqflags是中斷處理的屬性,若設置了IRQF_DISABLED (老版本中的SA_INTERRUPT,本版zhon已經不支持了),則表示中斷處理程序是快速處理程序,快速處理程序被調用時屏蔽所有中斷,慢速處理程序不屏蔽;若設置了IRQF_SHARED (老版本中的SA_SHIRQ),則表示多個設備共享中斷,若設置了IRQF_SAMPLE_RANDOM(老版本中的SA_SAMPLE_RANDOM),表示對系統熵有貢獻,對系統獲取隨機數有好處。(這幾個flag是可以通過或的方式同時使用的)

devname設置中斷名稱,通常是設備驅動程序的名稱  在cat /proc/interrupts中可以看到此名稱。

dev_id在中斷共享時會用到,一般設置爲這個設備的設備結構體或者NULL。

request_irq()返回0表示成功,返回-INVAL表示中斷號無效或處理函數指針爲NULL,返回-EBUSY表示中斷已經被佔用且不能共享。*/


        if( result )
        {
            result = -EBUSY;
            goto ERROR1;
        }
    }

    return 0;

ERROR1:
     kfree((unsigned char *)pdev->status);
     while(--i) 
     { 
         disable_irq(pdata->buttons[i].nIRQ); 
         free_irq(pdata->buttons[i].nIRQ, (void *)i); 
     }

ERROR:
     kfree(pdev->timers);

     return result;
}

static int button_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)

    struct button_device *pdev = file->private_data;
    struct s3c_button_platform_data *pdata;
    int   i, ret;
    unsigned int status = 0;

    pdata = pdev->data;

    dbg_print("ev_press: %d\n", pdev->ev_press);
    if(!pdev->ev_press)
    {
         if(file->f_flags & O_NONBLOCK)
             //使I/O變成非擱置模式,在讀取不到數據或是寫入緩衝區已滿馬上return,而不會擱置程序動作,知道有數據或寫入完成。
         {
             dbg_print("read() without block mode.\n");
             return -EAGAIN;
             /* 從字面上看,是提示再試一次的意思。這個錯誤經常出現在當應用程序進行一些非阻塞(non-blocking)操作(對文件或socket)的時候。
              */
         }
         else
         {
             /* Read() will be blocked here */
             dbg_print("read() blocked here now.\n");
             wait_event_interruptible(pdev->waitq, pdev->ev_press);
             /*
              這個函數先將當前進程的狀態設置成TASK_INTERRUPTIBLE, 然後調用schedule(), 而schedule()會將位於TASK_INTERRUPTIBLE狀態的當前進程從runqueue隊列中刪除。從runqueue隊列中刪除的結果是,當前這個進程將不再參與調度,除非通過其他函數將這個進程重新放入到runqueue隊列中,這就是wake_up()的作用。
              */
         }
    }

    pdev->ev_press = 0;

    for(i=0; i<pdata->nbuttons; i++)
    {
        dbg_print("button[%d] status=%d\n", i, pdev->status[i]);
        status |= (pdev->status[i]<<i); 
    }

    ret = copy_to_user(buf, (void *)&status, min(sizeof(status), count));

    return ret ? -EFAULT : min(sizeof(status), count);
}

static unsigned int button_poll(struct file *file, poll_table * wait)

    struct button_device *pdev = file->private_data;
    unsigned int mask = 0;

    poll_wait(file, &(pdev->waitq), wait);
    /* poll_wait()是用在select系統調用中的。一般你的代碼有一個struct
     * file_operations結構,其中fop->poll函數指針指向一個你自己的函數,在這個函數裏應該調用poll_wait().當用戶調用select系統調用時,select系統調用會先調用poll_initwait(&table);然後調用你的fop->poll();從而將current加到某個等待隊列(這裏調用poll_wait());並檢查是否有效,如果無效就調用schedule_timeout()去睡眠。事件發生後,schedule_timeout()回來,調用fop->poll();檢查到可以運行,就調用poll_freewait(&table);從而完成select調用。重要的是fop->poll()裏面要檢查是否就緒。如果是,要返回相應標誌。
     */
    if(pdev->ev_press)
    {
        mask |= POLLIN | POLLRDNORM; /* The data aviable */ 
        //POLLIN普通或優先級帶數據可讀;POLLRDNORM普通數據可讀
    }

    return mask;
}

static int button_release(struct inode *inode, struct file *file)

    int i;
    struct button_device *pdev = file->private_data;
    struct s3c_button_platform_data *pdata;
    pdata = pdev->data;

    for(i=0; i<pdata->nbuttons; i++) 
    {
        disable_irq(pdata->buttons[i].nIRQ);
        free_irq(pdata->buttons[i].nIRQ, (void *)i);
        del_timer(&(pdev->timers[i]));
    }

    kfree(pdev->timers);
    kfree((unsigned char *)pdev->status);

    return 0;
}

static struct file_operations button_fops = { 
    .owner = THIS_MODULE,
    .open = button_open, 
    .read = button_read,
    .poll = button_poll, 
    .release = button_release, 
};

static int s3c_button_probe(struct platform_device *dev)
{
    int result = 0;
    dev_t devno;

    /* Alloc the device for driver  */ 
    if (0 != dev_major) 
    { 
        devno = MKDEV(dev_major, dev_minor); 
        result = register_chrdev_region(devno, 1, DEV_NAME); 
    } 
    else 
    { 
        result = alloc_chrdev_region(&devno, dev_minor, 1, DEV_NAME); 
        dev_major = MAJOR(devno); 
    }

    /* Alloc for device major failure */
    if (result < 0) 
    { 
        printk("%s driver can't get major %d\n", DEV_NAME, dev_major); 
        return result; 
    }

    /*  Initialize button_device structure and register cdev*/
     memset(&button_device, 0, sizeof(button_device));
     button_device.data = dev->dev.platform_data;
     cdev_init (&(button_device.cdev), &button_fops);
     button_device.cdev.owner  = THIS_MODULE;

     result = cdev_add (&(button_device.cdev), devno , 1); 
     if (result) 
     { 
         printk (KERN_NOTICE "error %d add %s device", result, DEV_NAME); 
         goto ERROR; 
     }

     button_device.dev_class = class_create(THIS_MODULE, DEV_NAME); 
     if(IS_ERR(button_device.dev_class)) 
     { 
         printk("%s driver create class failture\n",DEV_NAME); 
         result =  -ENOMEM; 
         goto ERROR; 
     }

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)     
     device_create(button_device.dev_class, NULL, devno, NULL, DEV_NAME);
#else
     device_create (button_device.dev_class, NULL, devno, DEV_NAME);
#endif

     printk("S3C %s driver version %d.%d.%d initiliazed.\n", DEV_NAME, DRV_MAJOR_VER, DRV_MINOR_VER, DRV_REVER_VER);
     return 0;
ERROR: 
     printk("S3C %s driver version %d.%d.%d install failure.\n", DEV_NAME, DRV_MAJOR_VER, DRV_MINOR_VER, DRV_REVER_VER);
     cdev_del(&(button_device.cdev)); 
     unregister_chrdev_region(devno, 1);
     return result;
}

static int s3c_button_remove(struct platform_device *dev)
{
    dev_t devno = MKDEV(dev_major, dev_minor);

    cdev_del(&(button_device.cdev));
    device_destroy(button_device.dev_class, devno);
    class_destroy(button_device.dev_class);

    unregister_chrdev_region(devno, 1); 
    printk("S3C %s driver removed\n", DEV_NAME);
    return 0;
}
/*===================== Platform Device and driver regist part ===========================*/

static struct platform_driver s3c_button_driver = { 
    .probe      = s3c_button_probe, 
    .remove     = s3c_button_remove, 
    .driver     = { 
        .name       = "s3c_button", 
        .owner      = THIS_MODULE, 
    },
};

static int __init s3c_button_init(void)
{
   int       ret = 0;
   ret = platform_device_register(&s3c_button_device);
   if(ret)
   {
        printk(KERN_ERR "%s: Can't register platform device %d\n", __FUNCTION__, ret); 
        goto fail_reg_plat_dev;
   }
   dbg_print("Regist S3C %s Device successfully.\n", DEV_NAME);

   ret = platform_driver_register(&s3c_button_driver);
   if(ret)
   {
        printk(KERN_ERR "%s: Can't register platform driver %d\n", __FUNCTION__, ret); 
        goto fail_reg_plat_drv;
   }
   dbg_print("Regist S3C %s Driver successfully.\n", DEV_NAME);

   return 0;
fail_reg_plat_drv:
   platform_driver_unregister(&s3c_button_driver);
fail_reg_plat_dev:
   return ret;
}

static void s3c_button_exit(void)
{
    platform_driver_unregister(&s3c_button_driver);
    dbg_print("S3C %s platform device removed.\n", DEV_NAME);

    platform_device_unregister(&s3c_button_device);
    dbg_print("S3C %s platform driver removed.\n", DEV_NAME);
}

module_init(s3c_button_init);
module_exit(s3c_button_exit);
module_param(debug, int, S_IRUGO);
module_param(dev_major, int, S_IRUGO);
module_param(dev_minor, int, S_IRUGO);
MODULE_AUTHOR(DRV_AUTHOR);
MODULE_DESCRIPTION(DRV_DESC);
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:S3C24XX_button");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章