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结构体与申请设备号,以按键驱动为例:

 1 /*……*/
 2 /* 分配cdev*/
 3 struct cdev btn_cdev;
 4 /*……*/
 5 /* 1.1 申请设备号*/
 6     if(major){
 7         //静态
 8         dev_id = MKDEV(major, 0);
 9         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

        

1 void cdev_init(struct cdev *, struct file_operations *); 
2 /* cdev_init()函数用于初始化 cdev 的成员,并建立 cdev 和 file_operations 之间的连接。*/

 

    1.3. 注册cdev

1 int cdev_add(struct cdev *, dev_t, unsigned);
2 /*cdev_add()函数向系统添加一个 cdev,完成字符设备的注册。*/

 

    1.4. 硬件初始化

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

1 s3c2410_gpio_cfg(S3C2410_GPG(0),S3C2410_GPIO_INPUT);
2 /*
3 void s3c2410_gpio_cfgpin(unsigned int pin, unsigned int function)
4 pin 是哪个引脚, function 是引脚模式
5 函数功能:是设置引脚模式
6 void s3c2410_gpio_setpin(unsigned int pin, unsigned int to);
7 unsigned int s3c2410_gpio_getpin(unsigned int pin);
8 */

 

    2.实现设备操作

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

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 /*打开*/

 

        案例:

 1 static int button_open(struct inode *inode, struct file *file){
 2     unsigned long flags;
 3     //获取分配好的私有数据结构的首地址
 4     struct button_priv *pbtnp = container_of(inode->i_cdev, 
 5                                              struct button_priv, 
 6                                              btn_cdev);
 7     /*
 8 struct button_priv{
 9         char *name;
10         strcut cdev btn_cdev;
11 }  
12 container_of 是个宏定义。功能是通过结构体种某个变量的首地址,
13 就可得到这个结构体的首地址
14 */
15     //保存首地址到file->private_data
16     file->private_data = pbtnp;
17     if(down_interruptible(&pbtnp->sema)){
18         printk("Proccess is INT!\n");
19         return -EINTR;
20     }
21     printk("open button successfully !\n");
22     return 0;
23 }

 

    2.2. read( )函数

     原型:

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

 

    案例:

 1 static ssize_t button_read(struct file *file, char __user *buf,
 2                 size_t count, loff_t *ppos){
 3     //获取首地址
 4     struct button_priv *pbtnp = file->private_data;
 5     //判断按键是否有操作,如果有,则读取键值并上报给用户;反之,则休眠
 6     wait_event_interruptible(pbtnp->btn_wq, is_press != 0);
 7     is_press = 0;
 8     //上报键值
 9     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返回值*/

 

    案例:

 1 static ssize_t mem_write(struct file *filp, const char __user *buf, 
 2                          size_t size, loff_t *ppos){
 3     unsigned long p =  *ppos;
 4     unsigned int count = size;
 5     int ret = 0;
 6     int *register_addr = filp->private_data; /*获取设备的寄存器地址*/ 
 7     /*分析和获取有效的写长度*/
 8     if (p >= 5*sizeof(int))
 9         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、私有数据及信号量等信息。

 1 /*字符设备驱动模块加载与卸载函数模板*/
 2 /* 设备结构体
 3 struct xxx_dev_t {
 4     struct cdev cdev;
 5     ...
 6 } xxx_dev;
 7 /* 设备驱动模块加载函数
 8 static int __init xxx_init(void) {
 9     ...
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控制函数模板

 1 /*字符设备驱动读、写、IO控制函数模板*/
 2 /* 读设备*/
 3 ssize_t xxx_read(struct file *filp, char__user *buf, 
 4                  size_t count,loff_t*f_pos) {
 5     ...
 6     copy_to_user(buf, ..., ...);
 7     ...
 8 }
 9  
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是读的位置相对于文件开头的偏移。

 

mini2440按键驱动实例

 1 #include <linux/init.d>
 2 #include <linux/module.h>
 3 #include <linux/cdev>
 4 #include <linux/fs.h>
 5 #include <linux/types.h>
 6 #include <linux/uaccess.h>
 7 #include <linux/device.h>
 8  
 9 #include <plat/gpio-cfg.h>
10 #include <asm/gpio.h>
11  
12 static int major;
13 /* 分配cdev*/
14 struct cdev btn_cdev;
15  
16 /* 记录按键值*/
17 static unsigned char key_value;
18  
19 /* 2. 实现设备操作*/
20 /* 2.1 read*/
21 static ssize_t button_read(struct file *file, char __user *buf,
22                             size_t count, loff_t *ppos) {
23     int status = 0;
24  
25     //1. 获取GPIO的状态
26     status =  s3c2410_gpio_getpin(S3C2410_GPG(0)); 
27 
28     if(status == 1)
29         key_value = 0x50;
30     else
31         key_value = 0x51;
32  
33     //2. 上报GPIO的状态
34     copy_to_user(buf, &key_value, sizeof(key_value));
35  
36     return count;
37 }
38  
39 /* 2.2 设备操作集合*/
40 static struct file_operations btn_fops = {
41     .owner = THIS_MODULE,
42     .read = button_read
43 };
44  
45 //设备类
46 static struct class *btn_cls;
47  
48 /* 1. 驱动初始化*/
49 static init button_init(void){
50     dev_t dev_id;
51 /* 1.1 申请设备号*/
52     if(major){
53         //静态
54         dev_id = MKDEV(major, 0);
55         register_chrdev_region(dev_id, 1, "button");
56     } else {
57         //动态
58         alloc_chardev_region(&dev_id, 0, 1, "button");
59         major = MAJOR(dev_id);
60     }
61  
62 /* 1.2 初始化cdev*/
63     cdev_init(&btn_cdev, &btn_fops);
64  
65 /* 1.3 注册cdev*/
66     cdev_add(&btn_cdev, dev_id, 1);
67  
68 /* 1.4 自动创建设备节点*/
69 /* 1.4.1 创建设备类*/
70     //sys/class/button
71     btn_cls = class_create(THIS_MODULE, "button");
72 /* 1.4.2 创建设备节点*/
73     device_create(btn_cls, NULL, dev_id, NULL, "button");
74  
75 /* 1.4 硬件初始化*/
76    s3c2410_gpio_cfgpin(S3C2410_GPG(0),S3C2410_GPIO_INPUT); 
77     return 0;
78  
79 }
80  
81  
82 /* 3. 驱动注销*/
83 static void button_exit(void){
84  
85 /* 3.1 删除设备节点*/
86     device_destroy(btn_cls, MKDEV(major, 0));
87     class_destroy(btn_cls);
88  
89 /* 3.2 删除cdev*/
90     cdev_del(&btn_cdev);
91  
92 /* 3.3 释放设备号*/
93     unregister_chrdev_region(MKDEV(major, 0), 1);
94 }
95  
96 module_init(button_init);
97 module_exit(button_exit);
98 MODULE_LICENSE("GPL v2");
View Code

 

转载于:https://www.cnblogs.com/jetli-/p/5221975.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值