Linux 字符设备驱动简单总结

看完宋宝华的《Linux设备驱动开发详解》及其有关博客,对字符设备驱动做一个小总结。

一、字符设备、字符设备驱动与用户空间访问该设备的程序三者之间的关系。

        如图,在Linux内核中使用cdev结构体来描述字符设备,通过其成员dev_t来定义设备号(分为主、次设备号)以确定字符设备的唯一性。通过其成员file_operations来定义字符设备驱动提供给VFS的接口函数,如常见的open()、read()、write()等。

        在Linux字符设备驱动中,模块加载函数通过register_chrdev_region( ) 或alloc_chrdev_region( )来静态或者动态获取设备号,通过cdev_init( )建立cdev与file_operations之间的连接,通过cdev_add( )向系统添加一个cdev以完成注册。模块卸载函数通过cdev_del( )来注销cdev,通过unregister_chrdev_region( )来释放设备号。

        用户空间访问该设备的程序通过Linux系统调用,如open( )、read( )、write( ),来“调用”file_operations来定义字符设备驱动提供给VFS的接口函数。

二、字符设备驱动模型

        (PS:神马情况!本地上传的图片,质量下降这么多)

     1. 驱动初始化

     1.1. 分配cdev

        在2.6的内核中使用cdev结构体来描述字符设备,在驱动中分配cdev,主要是分配一个cdev结构体与申请设备号,以按键驱动为例:

01 /*……*/
02 /* 分配cdev*/
03 struct cdev btn_cdev;
04 /*……*/
05 /* 1.1 申请设备号*/
06     if(major){
07         //静态
08         dev_id = MKDEV(major, 0);
09         register_chrdev_region(dev_id, 1, "button");
10     else {
11         //动态
12         alloc_chardev_region(&dev_id, 0, 1, "button");
13         major = MAJOR(dev_id);
14     }
15 /*……*/

        从上面的代码可以看出,申请设备号有动静之分,其实设备号还有主次之分。

        在Linux中以主设备号用来标识与设备文件相连的驱动程序。次编号被驱动程序用来辨别操作的是哪个设备。cdev 结构体的 dev_t 成员定义了设备号,为 32 位,其中高 12 位为主设备号,低20 位为次设备号。

        设备号的获得与生成:

        获得:主设备号:MAJOR(dev_t dev);

                  次设备号:MINOR(dev_t dev);

        生成:MKDEV(int major,int minor);

        设备号申请的动静之分:

        静态:   

1 int register_chrdev_region(dev_t from, unsigned count, const char *name);
2 /*功能:申请使用从from开始的count 个设备号(主设备号不变,次设备号增加)*/

        静态申请相对较简单,但是一旦驱动被广泛使用,这个随机选定的主设备号可能会导致设备号冲突,而使驱动程序无法注册。

        动态:

1 int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,const char *name);
2 /*功能:请求内核动态分配count个设备号,且次设备号从baseminor开始。*/

        动态申请简单,易于驱动推广,但是无法在安装驱动前创建设备文件(因为安装前还没有分配到主设备号)。

    1.2. 初始化cdev

        void cdev_init(struct cdev *, struct file_operations *); 

        cdev_init()函数用于初始化 cdev 的成员,并建立 cdev 和 file_operations 之间的连接。

    1.3. 注册cdev

        int cdev_add(struct cdev *, dev_t, unsigned);

        cdev_add()函数向系统添加一个 cdev,完成字符设备的注册。

    1.4. 硬件初始化

        硬件初始化主要是硬件资源的申请与配置,以TQ210的按键驱动为例:

1 /* 1.4 硬件初始化*/
2     //申请GPIO资源
3     gpio_request(S5PV210_GPH0(0), "GPH0_0");
4     //配置输入
5     gpio_direction_input(S5PV210_GPH0(0));

    2.实现设备操作

        用户空间的程序以访问文件的形式访问字符设备,通常进行open、read、write、close等系统调用。而这些系统调用的最终落实则是file_operations结构体中成员函数,它们是字符设备驱动与内核的接口。以TQ210的按键驱动为例:

1 /*设备操作集合*/
2 static struct file_operations btn_fops = {
3     .owner = THIS_MODULE,
4     .open = button_open,
5     .release = button_close,
6     .read = button_read
7 };

        上面代码中的button_open、button_close、button_read是要在驱动中自己实现的。file_operations结构体成员函数有很多个,下面就选几个常见的来展示:

    2.1. open()函数

        原型:

1 int(*open)(struct inode *, struct file*); 
2 /*打开*/

        案例:

01 static int button_open(struct inode *inode, struct file *file){
02     unsigned long flags;
03     //获取分配好的私有数据结构的首地址
04     struct button_priv *pbtnp = container_of(inode->i_cdev, 
05                                              struct button_priv, 
06                                              btn_cdev);
07     //保存首地址到file->private_data
08     file->private_data = pbtnp;
09     if(down_interruptible(&pbtnp->sema)){
10         printk("Proccess is INT!\n");
11         return -EINTR;
12     }
13     printk("open button successfully !\n");
14     return 0;
15 }

    2.2. read( )函数

     原型:

1 ssize_t(*read)(struct file *, char __user*, size_t, loff_t*); 
2 /*用来从设备中读取数据,成功时函数返回读取的字节数,出错时返回一个负值*/

    案例:

01 static ssize_t button_read(struct file *file, char __user *buf,
02                 size_t count, loff_t *ppos){
03     //获取首地址
04     struct button_priv *pbtnp = file->private_data;
05     //判断按键是否有操作,如果有,则读取键值并上报给用户;反之,则休眠
06     wait_event_interruptible(pbtnp->btn_wq, is_press != 0);
07     is_press = 0;
08     //上报键值
09     copy_to_user(buf, &key_value, sizeof(key_value));
10     return count;
11 }
12 /*参数:file是文件结构体指针,buf是用户空间内存的地址,该地址在内核空间不能直接读写,
13   count 是要读的字节数,ppos是读的位置相对于文件开头的偏移*/

    2.3. write( )函数

    原型:

1 ssize_t(*write)(struct file *, const char__user *, size_t, loff_t*);
2 /*向设备发送数据,成功时该函数返回写入的字节数。如果此函数未被实现,
3   当用户进行write()系统调用时,将得到-EINVAL返回值*/

    案例:

01 static ssize_t mem_write(struct file *filp, const char __user *buf, 
02                          size_t size, loff_t *ppos){
03     unsigned long p =  *ppos;
04     unsigned int count = size;
05     int ret = 0;
06     int *register_addr = filp->private_data; /*获取设备的寄存器地址*/ 
07     /*分析和获取有效的写长度*/
08     if (p >= 5*sizeof(int))
09         return 0;
10     if (count > 5*sizeof(int) - p)
11         count = 5*sizeof(int) - p;   
12     /*从用户空间写入数据*/
13     if (copy_from_user(register_addr + p, buf, count))
14         ret = -EFAULT;
15     else {
16         *ppos += count;
17         ret = count;
18     }
19     return ret;
20 }
21 /*参数:filp是文件结构体指针,buf是用户空间内存的地址,该地址在内核空间不能直接读写,
22   count 是要读的字节数,ppos是读的位置相对于文件开头的偏移*/

    2.4. close( )函数

    原型:

1 int(*release)(struct inode *, struct file*); 
2 /*关闭*/

    案例:

1 static int button_close(struct inode *inode, struct file *file){
2     /* 1.获取首地址*/
3     struct button_priv *pbtnp = file->private_data;
4     up(&pbtnp->sema);
5     return 0;
6 }

    2.5. 补充说明

        1. 在Linux字符设备驱动程序设计中,有3种非常重要的数据结构:struct file、struct inode、struct file_operations。

        struct file 代表一个打开的文件。系统中每个打开的文件在内核空间都有一个关联的struct file。它由内核在打开文件时创建, 在文件关闭后释放。其成员loff_t f_pos 表示文件读写位置。

        struct inode 用来记录文件的物理上的信息。因此,它和代表打开文件的file结构是不同的。一个文件可以对应多个file结构,但只有一个inode结构。其成员dev_t i_rdev表示设备号。

        struct file_operations 一个函数指针的集合,定义能在设备上进行的操作。结构中的成员指向驱动中的函数,这些函数实现一个特别的操作, 对于不支持的操作保留为NULL。

        2. 在read( )和write( )中的buff 参数是用户空间指针。因此,它不能被内核代码直接引用,因为用户空间指针在内核空间时可能根本是无效的——没有那个地址的映射。因此,内核提供了专门的函数用于访问用户空间的指针:

1 unsigned long copy_from_user(void *to, const void __user *from, unsigned long count);
2 unsigned long copy_to_user(void __user *to, const void *from, unsigned long count);

    3. 驱动注销

    3.1. 删除cdev

        在字符设备驱动模块卸载函数中通过cdev_del()函数向系统删除一个cdev,完成字符设备的注销。

1 /*原型:*/
2 void cdev_del(struct cdev *);
3 /*例:*/
4 cdev_del(&btn_cdev);

    3.2. 释放设备号

        在调用cdev_del()函数从系统注销字符设备之后,unregister_chrdev_region()应该被调用以释放原先申请的设备号。

1 /*原型:*/
2 void unregister_chrdev_region(dev_t from, unsigned count);
3 /*例:*/
4 unregister_chrdev_region(MKDEV(major, 0), 1);

三、Linux字符设备驱动模板与案例

    1. 字符设备驱动模块加载与卸载函数模板

        在实际开发中,通常习惯为设备定义一个设备相关的结构体,其包含该设备所涉及到的cdev、私有数据及信号量等信息。

01 /*字符设备驱动模块加载与卸载函数模板*/
02 /* 设备结构体
03 struct xxx_dev_t {
04     struct cdev cdev;
05     ...
06 } xxx_dev;
07 /* 设备驱动模块加载函数
08 static int __init xxx_init(void) {
09     ...
10     cdev_init(&xxx_dev.cdev, &xxx_fops);/* 初始化cdev */
11     xxx_dev.cdev.owner = THIS_MODULE;
12     /* 获取字符设备号*/
13     if (xxx_major) {
14         register_chrdev_region(xxx_dev_no, 1,DEV_NAME);
15     else {
16         alloc_chrdev_region(&xxx_dev_no, 0, 1,DEV_NAME);
17     }
18     ret = cdev_add(&xxx_dev.cdev,xxx_dev_no, 1); /* 注册设备*/
19     ...
20 }
21  
22 /*设备驱动模块卸载函数*/
23 static void __exit xxx_exit(void) {
24     unregister_chrdev_region(xxx_dev_no, 1); /* 释放占用的设备号*/
25     cdev_del(&xxx_dev.cdev); /* 注销设备*/
26     ...
27 }

        2.字符设备驱动读、写、IO控制函数模板

01 /*字符设备驱动读、写、IO控制函数模板*/
02 /* 读设备*/
03 ssize_t xxx_read(struct file *filp, char__user *buf, 
04                  size_t count,loff_t*f_pos) {
05     ...
06     copy_to_user(buf, ..., ...);
07     ...
08 }
09  
10 /* 写设备*/
11 ssize_t xxx_write(struct file *filp, const char__user *buf, 
12                     size_t count,loff_t*f_pos) {
13     ...
14     copy_from_user(..., buf, ...);
15     ...
16 }
17  
18 /* ioctl函数 */
19 int xxx_ioctl(struct inode *inode, struct file*filp, 
20                 unsigned int cmd, unsigned long arg) {
21     ...
22     switch(cmd) {
23     caseXXX_CMD1:
24         ...
25         break;
26     caseXXX_CMD2:
27         ...
28         break;
29     default:
30     /* 不能支持的命令 */
31          return  - ENOTTY;
32     }
33     return 0;
34 }

        在设备驱动的读、写函数中,filp是文件结构体指针,buf是用户空间内存的地址,该地址在内核空间不能直接读写,count 是要读的字节数,f_pos是读的位置相对于文件开头的偏移。

    3.TQ210的最简单按键驱动示例

001 #include <linux/init.d>
002 #include <linux/module.h>
003 #include <linux/cdev>
004 #include <linux/fs.h>
005 #include <linux/types.h>
006 #include <linux/uaccess.h>
007 #include <linux/device.h>
008  
009 #include <plat/gpio-cfg.h>
010 #include <asm/gpio.h>
011  
012 static int major;
013 /* 分配cdev*/
014 struct cdev btn_cdev;
015  
016 /* 记录按键值*/
017 static unsigned char key_value;
018  
019 /* 2. 实现设备操作*/
020 /* 2.1 read*/
021 static ssize_t button_read(struct file *file, char __user *buf,
022                             size_t count, loff_t *ppos) {
023     int status = 0;
024  
025     //1. 获取GPIO的状态
026     status = gpio_get_value(S5PV210_GPH0(0));
027     if(status == 1)
028         key_value = 0x50;
029     else
030         key_value = 0x51;
031  
032     //2. 上报GPIO的状态
033     copy_to_user(buf, &key_value, sizeof(key_value));
034  
035     return count;
036 }
037  
038 /* 2.2 设备操作集合*/
039 static struct file_operations btn_fops = {
040     .owner = THIS_MODULE,
041     .read = button_read
042 };
043  
044 //设备类
045 static struct class *btn_cls;
046  
047 /* 1. 驱动初始化*/
048 static init button_init(void){
049     dev_t dev_id;
050 /* 1.1 申请设备号*/
051     if(major){
052         //静态
053         dev_id = MKDEV(major, 0);
054         register_chrdev_region(dev_id, 1, "button");
055     else {
056         //动态
057         alloc_chardev_region(&dev_id, 0, 1, "button");
058         major = MAJOR(dev_id);
059     }
060  
061 /* 1.2 初始化cdev*/
062     cdev_init(&btn_cdev, &btn_fops);
063  
064 /* 1.3 注册cdev*/
065     cdev_add(&btn_cdev, dev_id, 1);
066  
067 /* 1.4 自动创建设备节点*/
068 /* 1.4.1 创建设备类*/
069     //sys/class/button
070     btn_cls = class_create(THIS_MODULE, "button");
071 /* 1.4.2 创建设备节点*/
072     device_create(btn_cls, NULL, dev_id, NULL, "button");
073  
074 /* 1.4 硬件初始化*/
075     //申请GPIO资源
076     gpio_request(S5PV210_GPH0(0), "GPH0_0");
077     //配置输入
078     gpio_direction_input(S5PV210_GPH0(0));
079  
080     return 0;
081  
082 }
083  
084  
085 /* 3. 驱动注销*/
086 static void button_exit(void){
087 /* 3.1 释放GPIO资源*/
088     gpio_free(S5PV210_GPH0(0));
089  
090 /* 3.2 删除设备节点*/
091     device_destroy(btn_cls, MKDEV(major, 0));
092     class_destroy(btn_cls);
093  
094 /* 3.3 删除cdev*/
095     cdev_del(&btn_cdev);
096  
097 /* 3.4 释放设备号*/
098     unregister_chrdev_region(MKDEV(major, 0), 1);
099 }
100  
101 module_init(button_init);
102 module_exit(button_exit);
103 MODULE_LICENSE("GPL v2");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值