字符设备驱动

Linux字符设备驱动结构

cdev结构体

在Linux内核中,使用cdev结构体描述一个字符设备,cdev结构体的定义如下所示。

  1. struct cdev {
  2.     struct kobject kobj;    /* 内嵌的kobject对象 */
  3.     struct module *owner;   /* 所属模块 */
  4.     const struct file_operations *ops;  /* 文件操作结构体 */
  5.     struct list_head list;
  6.     dev_t dev;      /* 设备号 */
  7.     unsigned int count;
  8. };

cdev结构体的dev_t成员定义了设备号,为32位,其中12位为主设备号,20位为次设备号。使用下列宏可以从dev_t获得主设备号和次设备号:

  • #define MAJOR(dev) ((unsigned int) ((dev) >> MINORBITS))
  • #define MINOR(dev) ((unsigned int) ((dev) & MINORMASK))
  • #define MKDEV(ma,mi)  (((ma) << MINORBITS) | (mi))

而使用下列宏可以通过主设备号和次设备号生成dev_t:

  • #define MKDEV(ma,mi)  (((ma) << MINORBITS) | (mi))

cdev结构体的另一个重要成员file_operations定义了字符设备驱动提供给虚拟文件系统的接口函数。


Linux内核提供了一组函数用于操作cdev结构体:

  • void cdev_init(struct cdev *, const struct file_operations *);
  • struct cdev *cdev_alloc(void);
  • void cdev_put(struct cdev *p);
  • int cdev_add(struct cdev *, dev_t, unsigned);
  • void cdev_del(struct cdev *);

cdev_init()函数用于初始化cdev的成员,并建立cdev和file_operations之间的连接,其源代码如下所示:

  1. void cdev_init(struct cdev *cdev, const struct file_operations *fops)
  2. {
  3.     memset(cdev, 0, sizeof *cdev);
  4.     INIT_LIST_HEAD(&cdev->list);
  5.     kobject_init(&cdev->kobj, &ktype_cdev_default);
  6.     cdev->ops = fops;   /* 将传入的文件操作结构体指针赋给 cdev ops */
  7. }

cdev_alloc()函数用于动态申请一个cdev内存,其源码如下所示:

  1. struct cdev *cdev_alloc(void)
  2. {
  3.     struct cdev *p = kzalloc(sizeof(struct cdev), GFP_KERNEL);
  4.     if (p) {
  5.         INIT_LIST_HEAD(&p->list);
  6.         kobject_init(&p->kobj, &ktype_cdev_dynamic);
  7.     }
  8.     return p;
  9. }

cdev_add()函数和cdev_del()函数分别向系统添加和删除一个cdev,完成字符设备的注册和注销。对cdev_add()的调用通常发生在字符设备驱动模块加载函数中,而对cdev_del()函数的调用则通常发生在字符设备驱动模块卸载函数中。

分配和释放设备号

在调用cdev_add()函数向系统注册字符设备之前,应首先调用register_chrdev_region()或alloc_chrdev_region()函数向系统申请设备号,这两个函数的原型为:

  • extern int alloc_chrdev_region(dev_t *, unsigned, unsigned, const char *);
  • extern int register_chrdev_region(dev_t, unsigned, const char *);

register_chrdev_region()函数用于已知起始设备的设备号情况,而alloc_chrdev_region()用于设备号未知,向系统动态申请未被占用的设备号的情况,函数成功调用之后,会把得到的设备号放入第一个参数dev中。alloc_chrdev_region()相比register_chrdev_region()的优点在于它会自动避开设备号重复的冲突。

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

  • extern void unregister_chrdev_region(dev_t, unsigned);
file_operations结构体

file_operations结构体中的成员函数是字符设备驱动程序设计的主体内容,这些函数实际会在应用程序进行Linux的open()、write()、read()、close()等系统调用时最终被内核调用。file_operations结构体目前已经比较庞大,它的定义如下所示(下面抄录的是5.3版本的源码,aio_read()似乎变成了read_iter()):

  1. struct file_operations {
  2.     struct module *owner;
  3.     loff_t (*llseek) (struct file *, loff_t, int);
  4.     ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
  5.     ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
  6.     ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
  7.     ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
  8.     int (*iopoll)(struct kiocb *kiocb, bool spin);
  9.     int (*iterate) (struct file *, struct dir_context *);
  10.     int (*iterate_shared) (struct file *, struct dir_context *);
  11.     __poll_t (*poll) (struct file *, struct poll_table_struct *);
  12.     long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
  13.     long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
  14.     int (*mmap) (struct file *, struct vm_area_struct *);
  15.     unsigned long mmap_supported_flags;
  16.     int (*open) (struct inode *, struct file *);
  17.     int (*flush) (struct file *, fl_owner_t id);
  18.     int (*release) (struct inode *, struct file *);
  19.     int (*fsync) (struct file *, loff_t, loff_t, int datasync);
  20.     int (*fasync) (int, struct file *, int);
  21.     int (*lock) (struct file *, int, struct file_lock *);
  22.     ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
  23.     unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
  24.     int (*check_flags)(int);
  25.     int (*setfl)(struct file *, unsigned long);
  26.     int (*flock) (struct file *, int, struct file_lock *);
  27.     ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
  28.     ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
  29.     int (*setlease)(struct file *, long, struct file_lock **, void **);
  30.     long (*fallocate)(struct file *file, int mode, loff_t offset,
  31.               loff_t len);
  32.     void (*show_fdinfo)(struct seq_file *m, struct file *f);
  33. #ifndef CONFIG_MMU
  34.     unsigned (*mmap_capabilities)(struct file *);
  35. #endif
  36.     ssize_t (*copy_file_range)(struct file *, loff_t, struct file *,
  37.             loff_t, size_t, unsigned int);
  38.     loff_t (*remap_file_range)(struct file *file_in, loff_t pos_in,
  39.                    struct file *file_out, loff_t pos_out,
  40.                    loff_t len, unsigned int remap_flags);
  41.     int (*fadvise)(struct file *, loff_t, loff_t, int);
  42. };

下面我们对file_operations结构体中的主要成员进行分析。

llseek()函数用来修改一个文件的当前读写位置,并将新位置返回,在出错时,这个函数返回一个负值。

read()函数用来从设备中读取数据,成功时函数返回读取的字节数,出错时返回一个负值。它与用户空间程序中的read()和fread()对应。

write()函数向设备发送数据,成功时改函数返回写入的字节数。如果此函数未被实现,当用户进行write()系统调用时,将得到-EINVAL返回值。它与用户空间应用程序中的write()和fwrite()对应。

read()和write()如果返回0,则暗示end-of-file(EOF)。

unlocked_ioctl()提供设备相关控制命令的实现(既不是读操作,也不是写操作),当调用成功时,返回给调用程序一个非负值。它与用户空间应用程序调用的fcntl()和ioctl()对应。

mmap()函数将设备内存映射到进程的虚拟地址空间中,如果设备驱动未实现此函数,用户进行mmap()函数调用时将获得-ENODEV返回值。这个函数对于帧缓冲等设备特别有意义,帧缓冲被映射到用户空间后,应用程序可以直接访问它而无须在内核和应用间进行内存复制。它与用户空间应用程序中的mmap()函数对应。

当用户空间调用Linux API函数open()打开设备文件时,设备驱动的open()函数最终被调用。驱动程序可以不实现这个函数,在这种情况下,设备打开操作永远不成功。与open()函数对应的是release()函数。

poll()函数一般用于询问设备是否可被非阻塞地立即读写。当询问的条件未触发时,用户空间进行select()和poll()系统调用将引起进程的阻塞。

aio_read()和aio_write()函数分别对文件描述符对应的设备进行异步读、写操作。设备实现这两个函数后,用户空间可以对设备文件描述符执行SYS_io_setup、SYS_io_submit、SYS_io_getevents、SYS_io_destroy等系统调用进行读写。

Linux字符设备驱动的组成

在Linux中,字符设备驱动由如下几个部分组成。

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

在字符设备驱动模块加载函数中应该实现设备号的申请和cdev的注册,而在卸载函数中应实现设备号的释放和cdev的注销。

Linux内核的编码习惯是为设备定义一个设备相关的结构体,该结构体包含设备所涉及的cdev、私有数据及锁等信息。常见的设备结构体、模块加载和卸载函数形式如下面代码所示:

  1. /* 设备结构体 */
  2. struct xxx_dev_t
  3. {
  4.     struct cdev cdev;
  5.     /* ... 附加内容 ... */
  6. } xxx_dev;
  7.  
  8. static int __init xxx_init(void)
  9. {
  10.     /* ... 附加内容 ... */
  11.     cdev_init(&xxx_dev.cdev, &xxx_fops); /* 初始化cdev */
  12.     xxx_dev.cdev.owner = THIS_MODULE;
  13.     /* 获取字符设备号 */
  14.     if (xxx_major)
  15.     {
  16.         register_chrdev_region(xxx_dev_no, 1, DEV_NAME);
  17.     }
  18.     else
  19.     {
  20.         alloc_chrdev_region(&xxx_dev_no, 0, 1, DEV_NAME);
  21.     }
  22.  
  23.     ret = cdev_add(&xxx_dev.cdev, xxx_dev_no, 1); /* 注册设备 */
  24.     /* ... 附加内容 ... */
  25. }
  26.  
  27. /* 设备驱动模块卸载函数 */
  28. static void __exit xxx_exit(void)
  29. {
  30.     unregister_chrdev_region(xxx_dev_no, 1); /* 释放占用的设备号 */
  31.     cdev_del(&xxx_dev.cdev); /* 注销设备 */
  32.     /* ... 附加内容 ... */
  33. }

2.字符设备驱动的file_operations结构体中的成员函数

file_operations结构体中的成员函数是字符设备驱动与内核虚拟文件系统的接口,是用户空间对Liux进行系统调用最终的落实者。大多数字符设备驱动会实现read()、write()和ioctl()函数,常见的字符设备驱动的这3个函数的形式如下面代码所示:

  1. /* 读设备 */
  2. ssize_t xxx_read(struct file* filp, char __user* buf, size_t count, loff_t* f_ops)
  3. {
  4.     /* ... 附加内容 ... */
  5.     copy_to_user(buf, from, n);
  6.     /* ... 附加内容 ... */
  7. }
  8.  
  9. /* 写设备 */
  10. ssize_t xxx_write(struct file* filp, const char __user* buf, size_t count, loff_t* f_ops)
  11. {
  12.     /* ... 附加内容 ... */
  13.     copy_from_user(to, buf, n);
  14.     /* ... 附加内容 ... */
  15. }
  16.  
  17. /* ioctl函数 */
  18. long xxx_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
  19. {
  20.     /* ... 附加内容 ... */
  21.     switch (cmd)
  22.     {
  23.     case XXX_CMD1:
  24.         /* code */
  25.         break;
  26.     case XXX_CMD2:
  27.         /* code */
  28.         break;
  29.     default:
  30.         /* 不能支持的指令 */
  31.         return -ENOTTY;
  32.     }
  33.     return 0;
  34. }

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

由于用户空间不能直接访问内核空间的内存,因此借助了函数copy_from_user()完成用户空间缓存区到内核空间的复制,以及copy_to_user()完成内核空间到用户空间缓冲区的复制。

完成内核空间和用户空间内存复制的copy_from_user()和copy_to_user()的原型分别为:

  • unsigned long copy_from_user(void *to, const void __user *from, unsigned long n);
  • unsigned long copy_to_user(void __user *to, const void *from, unsigned long n);

上述函数均返回不能被复制的字节数,因此,如果完全复制成功,返回值为0.如果复制失败,则返回负值。

如果要复制的内存是简单类型,如char、int、long等,则可以使用简单的put_user()和get_user()。

I/O控制函数的cmd参数为事先定义的I/O控制命令,而arg为对应于改命令的参数。例如对于串行设备,如果SET_BAUDRATE是一道设置波特率的命令,那后面的arg就应该是波特率值。

在字符设备驱动中,需要定义一个file_operations的实例,并将具体设备驱动的函数赋值给file_operations的成员。

下图为字符设备驱动的结构、字符设备驱动与字符设备以及字符设备驱动与用户空间访问该设备的程序之间的关系。


globalmem虚拟设备实例描述

从本章开始,后续的章节都将基于虚拟的globalmem设备进行字符设备驱动的讲解。globalmem意味着“全局内存”,在globalmem字符设备驱动中会分配一片大小为GLOBALMEM_SIZE(4KB)的内存空间,并在驱动中提供针对该片内存的读写、控制和定位函数,以供用户空间的进程能通过Linux系统调用获取或设置这片内存的内容。

实际上,这个虚拟的globalmem设备几乎没有任何实用价值,仅仅是一种为了讲解问题的方便而凭空制造的设备。

本章将给出globalmem设备驱动的雏形,而后续章节会在这个雏形的基础上添加并发与同步控制等复杂功能。

globalmem设备驱动

头文件、宏及设备结构体

在globalmem字符设备驱动中,应包含它要使用的头文件,并定义globalmem设备结构体及相关宏。

  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/init.h>
  4. #include <linux/cdev.h>
  5. #include <linux/slab.h>
  6. #include <linux/uaccess.h>
  7.  
  8. #define GLOBALMEM_SIZE 0x1000
  9. #define MEM_CLEAR 0x01
  10. #define GLOBALMEM_MAJOR 230
  11.  
  12. static int globalmem_major = GLOBALMEM_MAJOR;
  13. module_param(globalmem_major, int, S_IRUGO);
  14.  
  15. struct globalmem_dev
  16. {
  17.     struct cdev cdev;
  18.     unsigned char mem[GLOBALMEM_SIZE];
  19. };

从代码中可以看出,定义的globalmem_dev设备结构体包含了对应于globalmem字符设备的cdev、使用的内存mem。当然,程序中并不一定要把mem和cdev包含在一个设备结构体中,但这样定义的好处在于,它借用了面向对象程序设计中“封装”的思想,体现了一种良好的编程习惯。

加载与卸载设备驱动

globalmem设备驱动的模块加载和卸载函数遵循上述类似的模板。

  1. static void globalmem_setup_cdev(struct globalmem_dev* dev, int index)
  2. {
  3.     int err;
  4.     int devno = MKDEV(globalmem_major, index);
  5.     cdev_init(&dev->cdev, &globalmem_fops);
  6.     dev->cdev.owner = THIS_MODULE;
  7.     err = cdev_add(&dev->cdev, devno, 1);
  8.     if (err)
  9.         printk(KERN_NOTICE "Error %d adding globalmem%d", err, index);
  10. }
  11.  
  12. static int __init globalmem_init(void)
  13. {
  14.     int ret;
  15.     dev_t devno = MKDEV(globalmem_major, 0);
  16.  
  17.     if (globalmem_major)
  18.         ret = register_chrdev_region(devno, 1, "globalmem");
  19.     else
  20.     {
  21.         ret = alloc_chrdev_region(&devno, 0, 1, "globalmem");
  22.         globalmem_major = MAJOR(devno);
  23.     }
  24.     if (ret < 0)
  25.         return ret;
  26.  
  27.     globalmem_devp = kzalloc(sizeof(struct globalmem_dev), GFP_KERNEL);
  28.     if (!globalmem_devp)
  29.     {
  30.         ret = -ENOMEM;
  31.         goto fail_malloc;
  32.     }
  33.  
  34.     globalmem_setup_cdev(globalmem_devp, 0);
  35.     return 0;
  36.  
  37.     fail_malloc:
  38.     unregister_chrdev_region(devno, 1);
  39.     return ret;
  40. }
  41. module_init(globalmem_init);
  42.  
  43. static void __exit globalmem_exit(void)
  44. {
  45.     cdev_del(&globalmem_devp->cdev);
  46.     kfree(globalmem_devp);
  47.     unregister_chrdev_region(MKDEV(globalmem_major, 0), 1);
  48. }
  49. module_exit(globalmem_exit);

第1~10行的globalmem_setup_cdev()函数完成cdev的初始化和添加,17~22行完成了设备号的申请,第27行调用kzalloc()申请了一份globalmem_dev结构体的内存并清0。在cdev_init()函数中,与globalmem的cdev关联的file_operations结构体如下所示。

  1. static const struct file_operations globalmem_fops = {
  2.     .owner = THIS_MODULE,
  3.     .llseek = globalmem_llseek,
  4.     .read = globalmem_read,
  5.     .write = globalmem_write,
  6.     .unlocked_ioctl = globalmem_ioctl,
  7.     .open = globalmem_open,
  8.     .release = globalmem_release
  9. };
读写函数

globalmem设备驱动的读写函数主要是让设备结构体的mem数组与用户空间交互数据,并随着访问的字节数变更更新文件读写偏移位置。

  1. static ssize_t globalmem_read(struct file* filp, char __user* buf, size_t size, loff_t* ppos)
  2. {
  3.     unsigned long p = *ppos;
  4.     unsigned int count = size;
  5.     int ret = 0;
  6.     struct globalmem_dev* dev = filp->private_data;
  7.  
  8.     if (p >= GLOBALMEM_SIZE)
  9.         return 0;
  10.     if (count > GLOBALMEM_SIZE - p)
  11.         count = GLOBALMEM_SIZE - p;
  12.  
  13.     if (copy_to_user(buf, dev->mem +p, count) )
  14.         ret = -EFAULT;
  15.     else
  16.     {
  17.         *ppos += count;
  18.         ret = count;
  19.  
  20.         printk(KERN_INFO "read %u byte(s) from %lu\n", count, p);
  21.     }
  22.    
  23.     return ret;
  24. }

*ppos是要读的位置相对于文件开头的偏移,如果该偏移大于或等于GLOBALMEM_SIZE,意味着已经到达文件末尾,所以返回0(EOF)。

  1. static ssize_t globalmem_write(struct file* filp, const char __user* buf, size_t size, loff_t* ppos)
  2. {
  3.     unsigned long p = *ppos;
  4.     unsigned int count = size;
  5.     int ret = 0;
  6.     struct globalmem_dev* dev = filp->private_data;
  7.  
  8.     if (p >= GLOBALMEM_SIZE)
  9.         return 0;
  10.     if (count > GLOBALMEM_SIZE - p)
  11.         count = GLOBALMEM_SIZE -p;
  12.  
  13.     if (copy_from_user(dev->mem + p, buf, count) )
  14.         ret = -EFAULT;
  15.     else
  16.     {
  17.         *ppos += count;
  18.         ret = count;
  19.  
  20.         printk(KERN_INFO "write %u byte(s) from %lu\n", count, p);
  21.     }
  22.  
  23.     return ret;
  24. }
seek函数

seek()函数对文件定位的起始地址可以是文件开头(SEEK_SET,0)、当前位置(SEEK_CUR,1)和文件尾(SEEK_END,2),假设globalmem支持从文件开头和当前位置的相对偏移。

在定位的时候,应该检查用户请求的合法性,若不合法,函数返回-EINVAL,合法时更新文件的当前位置并返回该位置。

  1. static loff_t globalmem_llseek(struct file* filp, loff_t offset, int orig)
  2. {
  3.     loff_t ret = 0;
  4.     switch (orig)
  5.     {
  6.     case 0: /* 从文件开头位置seek */
  7.         if (offset < 0 || offset > GLOBALMEM_SIZE)
  8.         {
  9.             ret = -EINVAL;
  10.             break;
  11.         }
  12.  
  13.         filp->f_pos = offset;
  14.         ret = filp->f_pos;
  15.         break;
  16.    
  17.     case 1:
  18.         if ( (filp->f_pos + offset) < 0 || (filp->f_pos + offset) > GLOBALMEM_SIZE)
  19.         {
  20.             ret = -EINVAL;
  21.             break;
  22.         }
  23.         filp->f_pos += offset;
  24.         ret = filp->f_pos;
  25.         break;
  26.     default:
  27.         ret = -EINVAL;
  28.         break;
  29.     }
  30.  
  31.     return ret;
  32. }
ioctl函数

1.globalmem设备驱动的ioctl()函数

globalmem设备驱动的ioctl()函数接受MEM_CLEAR命令,这个命令会将全局内存的有效数据长度清0,对于设备不支持的命令,ioctl()函数应该返回-EINVAL。

  1. static long globalmem_ioctl(struct file* filp, unsigned int cmd, unsigned long arg)
  2. {
  3.     struct globalmem_dev* dev = filp->private_data;
  4.  
  5.     switch (cmd)
  6.     {
  7.         case MEM_CLEAR:
  8.             memset(dev->mem, 0, GLOBALMEM_SIZE);
  9.             printk(KERN_INFO "globalmem is set to zero\n");
  10.             break;
  11.        
  12.         default:
  13.             return -EINVAL;
  14.     }
  15.  
  16.     return 0;
  17. }

在上述程序中,MEM_CLEAR被宏定义为0x01,实际上这并不是一种值得推荐的方法,简单地对命令定义为0x0、0x1、0x2等类似值会导致不同地设备驱动拥有相同的命令号。如果设备A、B都支持0x0、0x1、0x2这样的命令,就会造成命令码的污染。因此,Linux内核推荐采用一套统一的ioctl()命令生成方式。

I/O控制命令的组成
设备类型 序列号 方向 数据尺寸
8位 8位 2位 13/14位
使用文件私有数据

之前的代码中都使用了filp->private_data获取globalmem_dev的实例指针。实际上,大多数Linux驱动遵循一个“潜规则”,那就是将文件的私有数据private_data指向设备结构体,再用read()、write()、ioctl()、llseek()等函数通过private_data访问设备结构体。私有数据的概念在Linux驱动的各个子系统中广泛存在,实际上体现了Linux的面向对象的设计思想。对于globalmem驱动而言,私有数据的设置是在globalmem_open()中完成的。

  1. static int globalmem_open(struct inode* inode, struct file* filp)
  2. {
  3.     filp->private_data = globalmem_devp;
  4.     return 0;
  5. }
完整代码

为了方便复现实验,以下给出完整代码。

  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/init.h>
  4. #include <linux/cdev.h>
  5. #include <linux/slab.h>
  6. #include <linux/uaccess.h>
  7.  
  8. #define GLOBALMEM_SIZE 0x1000
  9. #define MEM_CLEAR 0x01
  10. #define GLOBALMEM_MAJOR 230
  11.  
  12. static int globalmem_major = GLOBALMEM_MAJOR;
  13. module_param(globalmem_major, int, S_IRUGO);
  14.  
  15. struct globalmem_dev
  16. {
  17.     struct cdev cdev;
  18.     unsigned char mem[GLOBALMEM_SIZE];
  19. };
  20.  
  21. struct globalmem_dev* globalmem_devp;
  22.  
  23. static ssize_t globalmem_read(struct file* filp, char __user* buf, size_t size, loff_t* ppos);
  24. static ssize_t globalmem_write(struct file* filp, const char __user* buf, size_t size, loff_t* ppos);
  25. static loff_t globalmem_llseek(struct file* filp, loff_t offset, int orig);
  26. static long globalmem_ioctl(struct file* filp, unsigned int cmd, unsigned long arg);
  27. static int globalmem_open(struct inode* inode, struct file* filp);
  28. static int globalmem_release(struct inode* inode, struct file* filp);
  29.  
  30. static const struct file_operations globalmem_fops = {
  31.     .owner = THIS_MODULE,
  32.     .llseek = globalmem_llseek,
  33.     .read = globalmem_read,
  34.     .write = globalmem_write,
  35.     .unlocked_ioctl = globalmem_ioctl,
  36.     .open = globalmem_open,
  37.     .release = globalmem_release
  38. };
  39.  
  40. static ssize_t globalmem_read(struct file* filp, char __user* buf, size_t size, loff_t* ppos)
  41. {
  42.     unsigned long p = *ppos;
  43.     unsigned int count = size;
  44.     int ret = 0;
  45.     struct globalmem_dev* dev = filp->private_data;
  46.  
  47.     if (p >= GLOBALMEM_SIZE)
  48.         return 0;
  49.     if (count > GLOBALMEM_SIZE - p)
  50.         count = GLOBALMEM_SIZE - p;
  51.  
  52.     if (copy_to_user(buf, dev->mem +p, count) )
  53.         ret = -EFAULT;
  54.     else
  55.     {
  56.         *ppos += count;
  57.         ret = count;
  58.  
  59.         printk(KERN_INFO "read %u byte(s) from %lu\n", count, p);
  60.     }
  61.    
  62.     return ret;
  63. }
  64.  
  65. static ssize_t globalmem_write(struct file* filp, const char __user* buf, size_t size, loff_t* ppos)
  66. {
  67.     unsigned long p = *ppos;
  68.     unsigned int count = size;
  69.     int ret = 0;
  70.     struct globalmem_dev* dev = filp->private_data;
  71.  
  72.     if (p >= GLOBALMEM_SIZE)
  73.         return 0;
  74.     if (count > GLOBALMEM_SIZE - p)
  75.         count = GLOBALMEM_SIZE -p;
  76.  
  77.     if (copy_from_user(dev->mem + p, buf, count) )
  78.         ret = -EFAULT;
  79.     else
  80.     {
  81.         *ppos += count;
  82.         ret = count;
  83.  
  84.         printk(KERN_INFO "write %u byte(s) from %lu\n", count, p);
  85.     }
  86.  
  87.     return ret;
  88. }
  89.  
  90. static loff_t globalmem_llseek(struct file* filp, loff_t offset, int orig)
  91. {
  92.     loff_t ret = 0;
  93.     switch (orig)
  94.     {
  95.     case 0: /* 从文件开头位置seek */
  96.         if (offset < 0 || offset > GLOBALMEM_SIZE)
  97.         {
  98.             ret = -EINVAL;
  99.             break;
  100.         }
  101.  
  102.         filp->f_pos = offset;
  103.         ret = filp->f_pos;
  104.         break;
  105.    
  106.     case 1:
  107.         if ( (filp->f_pos + offset) < 0 || (filp->f_pos + offset) > GLOBALMEM_SIZE)
  108.         {
  109.             ret = -EINVAL;
  110.             break;
  111.         }
  112.         filp->f_pos += offset;
  113.         ret = filp->f_pos;
  114.         break;
  115.     default:
  116.         ret = -EINVAL;
  117.         break;
  118.     }
  119.  
  120.     return ret;
  121. }
  122.  
  123. static long globalmem_ioctl(struct file* filp, unsigned int cmd, unsigned long arg)
  124. {
  125.     struct globalmem_dev* dev = filp->private_data;
  126.  
  127.     switch (cmd)
  128.     {
  129.         case MEM_CLEAR:
  130.             memset(dev->mem, 0, GLOBALMEM_SIZE);
  131.             printk(KERN_INFO "globalmem is set to zero\n");
  132.             break;
  133.        
  134.         default:
  135.             return -EINVAL;
  136.     }
  137.  
  138.     return 0;
  139. }
  140.  
  141. static int globalmem_open(struct inode* inode, struct file* filp)
  142. {
  143.     filp->private_data = globalmem_devp;
  144.     return 0;
  145. }
  146.  
  147. static int globalmem_release(struct inode* inode, struct file* filp)
  148. {
  149.     return 0;
  150. }
  151.  
  152. static void globalmem_setup_cdev(struct globalmem_dev* dev, int index)
  153. {
  154.     int err;
  155.     int devno = MKDEV(globalmem_major, index);
  156.     cdev_init(&dev->cdev, &globalmem_fops);
  157.     dev->cdev.owner = THIS_MODULE;
  158.     err = cdev_add(&dev->cdev, devno, 1);
  159.     if (err)
  160.         printk(KERN_NOTICE "Error %d adding globalmem%d", err, index);
  161. }
  162.  
  163. static int __init globalmem_init(void)
  164. {
  165.     int ret;
  166.     dev_t devno = MKDEV(globalmem_major, 0);
  167.  
  168.     if (globalmem_major)
  169.         ret = register_chrdev_region(devno, 1, "globalmem");
  170.     else
  171.     {
  172.         ret = alloc_chrdev_region(&devno, 0, 1, "globalmem");
  173.         globalmem_major = MAJOR(devno);
  174.     }
  175.     if (ret < 0)
  176.         return ret;
  177.  
  178.     globalmem_devp = kzalloc(sizeof(struct globalmem_dev), GFP_KERNEL);
  179.     if (!globalmem_devp)
  180.     {
  181.         ret = -ENOMEM;
  182.         goto fail_malloc;
  183.     }
  184.  
  185.     globalmem_setup_cdev(globalmem_devp, 0);
  186.     return 0;
  187.  
  188.     fail_malloc:
  189.     unregister_chrdev_region(devno, 1);
  190.     return ret;
  191. }
  192. module_init(globalmem_init);
  193.  
  194. static void __exit globalmem_exit(void)
  195. {
  196.     cdev_del(&globalmem_devp->cdev);
  197.     kfree(globalmem_devp);
  198.     unregister_chrdev_region(MKDEV(globalmem_major, 0), 1);
  199. }
  200. module_exit(globalmem_exit);
  201.  
  202. MODULE_AUTHOR("HanHan");
  203. MODULE_LICENSE("GPL v2");

globalmem驱动在用户空间中的验证

在源目录下执行make指令编译驱动,makefile内容如下(源文件名为main.c):

  1. KVERS = $(shell uname -r)
  2.  
  3. # Kernel modules
  4. obj-m += main.o
  5.  
  6. build: kernel_modules
  7.  
  8. kernel_modules:
  9.     make -C /lib/modules/$(KVERS)/build M=$(CURDIR) modules
  • $ make

命令加载模块,通过insmod命令。再通过cat /proc/devices命令查看,可以发现主设备号为230的globalmem字符设备驱动。

  • $ sudo insmod main.ko
  • $ cat /proc/devices
  • 230 globalmem

接下来创建/dev/globalmem设备节点:

  • $ sudo mknod -m 0666 /dev/globalmem c 230 0

接下来写了一段验证程序,通过printk和程序输出验证驱动。主要关注的点,一是加载的时机;二是用户程序调用和驱动程序之间的对应关系;三是指针的移动。

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <sys/ioctl.h>
  6.  
  7. char buf[1024];
  8. int main()
  9. {
  10.     int res;
  11.  
  12.     int fd = open("/dev/globalmem", O_RDWR);
  13.     if (fd == -1)
  14.     {
  15.         printf("open failed.\n");
  16.         return -1;
  17.     }
  18.  
  19.     res = snprintf(buf, sizeof(buf), "Hello World");
  20.     write(fd, buf, res);
  21.  
  22.     read(fd, buf, res);
  23.     printf("read buf: %s\n", buf);
  24.    
  25.     memset(buf, 0x00, sizeof(buf) );
  26.     lseek(fd, 0, 0);
  27.  
  28.     read(fd, buf, res);
  29.     printf("read buf: %s\n", buf);
  30.  
  31.     memset(buf, 0x00, sizeof(buf) );
  32.     lseek(fd, 0, 0);
  33.     ioctl(fd, 0x01);
  34.    
  35.     read(fd, buf, res);
  36.     printf("read buf: %s\n", buf);
  37.  
  38.     res = close(fd);
  39.     if (res == -1)
  40.     {
  41.         printf("close failed.\n");
  42.         return -1;
  43.     }
  44.  
  45.     return 0;
  46. }

使用dmesg命令查看期间的打印信息:

  • $ dmesg
  • [26666.982294] globalmem : init
  • [26699.877585] globalmem_write: *ppos = 0
  • [26699.877632] write 11 byte(s) from 0
  • [26699.877636] globalmem_write: *ppos = 11
  • [26699.877637] globalmem_read: read 11 byte(s) from 11
  • [26699.877725] globalmem_write: *ppos = 0
  • [26699.877726] globalmem_read: read 11 byte(s) from 0
  • [26699.877730] globalmem is set to zero
  • [26699.877731] globalmem_write: *ppos = 0
  • [26699.877731] globalmem_read: read 11 byte(s) from 0

支持N个globalmem设备的globalmem驱动

如果globalmem不止包括一个设备,而是同时包括两个或两个以上的设备,采用private_data的优势就会集中显现出来。只需简单地修改globalmem_init()、globalmem_exit()和globalmem_open(),就可以轻松地让globalmem驱动中包含N个相同的设备(次设备号分为0~N),如下代码将修改的部分标出。

  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/init.h>
  4. #include <linux/cdev.h>
  5. #include <linux/slab.h>
  6. #include <linux/uaccess.h>
  7.  
  8. #define GLOBALMEM_SIZE 0x1000
  9. #define MEM_CLEAR 0x01
  10. #define GLOBALMEM_MAJOR 230
  11. #define DEVICE_NUM 10
  12.  
  13. static int globalmem_major = GLOBALMEM_MAJOR;
  14. module_param(globalmem_major, int, S_IRUGO);
  15.  
  16. struct globalmem_dev
  17. {
  18.     struct cdev cdev;
  19.     unsigned char mem[GLOBALMEM_SIZE];
  20. };
  21.  
  22. struct globalmem_dev* globalmem_devp;
  23.  
  24. static ssize_t globalmem_read(struct file* filp, char __user* buf, size_t size, loff_t* ppos);
  25. static ssize_t globalmem_write(struct file* filp, const char __user* buf, size_t size, loff_t* ppos);
  26. static loff_t globalmem_llseek(struct file* filp, loff_t offset, int orig);
  27. static long globalmem_ioctl(struct file* filp, unsigned int cmd, unsigned long arg);
  28. static int globalmem_open(struct inode* inode, struct file* filp);
  29. static int globalmem_release(struct inode* inode, struct file* filp);
  30.  
  31. static const struct file_operations globalmem_fops = {
  32.     .owner = THIS_MODULE,
  33.     .llseek = globalmem_llseek,
  34.     .read = globalmem_read,
  35.     .write = globalmem_write,
  36.     .unlocked_ioctl = globalmem_ioctl,
  37.     .open = globalmem_open,
  38.     .release = globalmem_release
  39. };
  40.  
  41. static ssize_t globalmem_read(struct file* filp, char __user* buf, size_t size, loff_t* ppos)
  42. {
  43.     unsigned long p = *ppos;
  44.     unsigned int count = size;
  45.     int ret = 0;
  46.     struct globalmem_dev* dev = filp->private_data;
  47.  
  48.     if (p >= GLOBALMEM_SIZE)
  49.         return 0;
  50.     if (count > GLOBALMEM_SIZE - p)
  51.         count = GLOBALMEM_SIZE - p;
  52.  
  53.     if (copy_to_user(buf, dev->mem +p, count) )
  54.         ret = -EFAULT;
  55.     else
  56.     {
  57.         *ppos += count;
  58.         ret = count;
  59.  
  60.         printk(KERN_INFO "read %u byte(s) from %lu\n", count, p);
  61.     }
  62.    
  63.     return ret;
  64. }
  65.  
  66. static ssize_t globalmem_write(struct file* filp, const char __user* buf, size_t size, loff_t* ppos)
  67. {
  68.     unsigned long p = *ppos;
  69.     unsigned int count = size;
  70.     int ret = 0;
  71.     struct globalmem_dev* dev = filp->private_data;
  72.  
  73.     if (p >= GLOBALMEM_SIZE)
  74.         return 0;
  75.     if (count > GLOBALMEM_SIZE - p)
  76.         count = GLOBALMEM_SIZE -p;
  77.  
  78.     if (copy_from_user(dev->mem + p, buf, count) )
  79.         ret = -EFAULT;
  80.     else
  81.     {
  82.         *ppos += count;
  83.         ret = count;
  84.  
  85.         printk(KERN_INFO "write %u byte(s) from %lu\n", count, p);
  86.     }
  87.  
  88.     return ret;
  89. }
  90.  
  91. static loff_t globalmem_llseek(struct file* filp, loff_t offset, int orig)
  92. {
  93.     loff_t ret = 0;
  94.     switch (orig)
  95.     {
  96.     case 0: /* 从文件开头位置seek */
  97.         if (offset < 0 || offset > GLOBALMEM_SIZE)
  98.         {
  99.             ret = -EINVAL;
  100.             break;
  101.         }
  102.  
  103.         filp->f_pos = offset;
  104.         ret = filp->f_pos;
  105.         break;
  106.    
  107.     case 1:
  108.         if ( (filp->f_pos + offset) < 0 || (filp->f_pos + offset) > GLOBALMEM_SIZE)
  109.         {
  110.             ret = -EINVAL;
  111.             break;
  112.         }
  113.         filp->f_pos += offset;
  114.         ret = filp->f_pos;
  115.         break;
  116.     default:
  117.         ret = -EINVAL;
  118.         break;
  119.     }
  120.  
  121.     return ret;
  122. }
  123.  
  124. static long globalmem_ioctl(struct file* filp, unsigned int cmd, unsigned long arg)
  125. {
  126.     struct globalmem_dev* dev = filp->private_data;
  127.  
  128.     switch (cmd)
  129.     {
  130.         case MEM_CLEAR:
  131.             memset(dev->mem, 0, GLOBALMEM_SIZE);
  132.             printk(KERN_INFO "globalmem is set to zero\n");
  133.             break;
  134.        
  135.         default:
  136.             return -EINVAL;
  137.     }
  138.  
  139.     return 0;
  140. }
  141.  
  142. static int globalmem_open(struct inode* inode, struct file* filp)
  143. {
  144.     struct globalmem_dev* dev = container_of(indoe->i_cdev, struct globalmem_dev, cdev);
  145.     filp->private_data = dev;
  146.     return 0;
  147. }
  148.  
  149. static int globalmem_release(struct inode* inode, struct file* filp)
  150. {
  151.     return 0;
  152. }
  153.  
  154. static void globalmem_setup_cdev(struct globalmem_dev* dev, int index)
  155. {
  156.     int err;
  157.     int devno = MKDEV(globalmem_major, index);
  158.     cdev_init(&dev->cdev, &globalmem_fops);
  159.     dev->cdev.owner = THIS_MODULE;
  160.     err = cdev_add(&dev->cdev, devno, 1);
  161.     if (err)
  162.         printk(KERN_NOTICE "Error %d adding globalmem%d", err, index);
  163. }
  164.  
  165. static int __init globalmem_init(void)
  166. {
  167.     int ret, i;
  168.     dev_t devno = MKDEV(globalmem_major, 0);
  169.  
  170.     if (globalmem_major)
  171.         ret = register_chrdev_region(devno, DEVICE_NUM, "globalmem");
  172.     else
  173.     {
  174.         ret = alloc_chrdev_region(&devno, 0, DEVICE_NUM, "globalmem");
  175.         globalmem_major = MAJOR(devno);
  176.     }
  177.     if (ret < 0)
  178.         return ret;
  179.  
  180.     globalmem_devp = kzalloc(sizeof(struct globalmem_dev) * DEVICE_NUM, GFP_KERNEL);
  181.     if (!globalmem_devp)
  182.     {
  183.         ret = -ENOMEM;
  184.         goto fail_malloc;
  185.     }
  186.  
  187.     for (i = 0; i < DEVICE_NUM; i++)
  188.     {
  189.         globalmem_setup_cdev(globalmem_devp + i, i);
  190.     }
  191.  
  192.     return 0;
  193.  
  194.     fail_malloc:
  195.     unregister_chrdev_region(devno, 1);
  196.     return ret;
  197. }
  198. module_init(globalmem_init);
  199.  
  200. static void __exit globalmem_exit(void)
  201. {
  202.     int i;
  203.  
  204.     for (i = 0; i < DEVICE_NUM; i++)
  205.     {
  206.         cdev_del(&globalmem_devp->cdev);
  207.     }
  208.     kfree(globalmem_devp);
  209.     unregister_chrdev_region(MKDEV(globalmem_major, 0), DEVICE_NUM);
  210. }
  211. module_exit(globalmem_exit);
  212.  
  213. MODULE_AUTHOR("HanHan");
  214. MODULE_LICENSE("GPL v2");

以上globalmem_init()和globalmem_exit()的修改都比较直观,globalmem_open()新增的代码让我琢磨了一会。以下是我理解的一些猜测,待验证:单个设备驱动里private_data可以直接指向globalmem_devp,而多设备不行,因为还要区分次设备号。indoe->i_cdev成员应该是cdev_add时绑定了globalmem_devp全局数组中的某个地址,所以可以通过indoe->i_cdev找到这个相关的地址。而通过container_of函数找到这个地址非常严谨,因为不一定默认cdev成员就在新结构体的开头(这一点在看Android HAL代码时就觉得有点奇怪,现在对比一下的确是有点不严谨)。

可以通过创建多个设备节点进行验证:

  • $ sudo mknod -m 0666 /dev/globalmem c 230 0
  • $ sudo mknod -m 0666 /dev/globalmem1 c 230 1

并可以使用cat命令进行快速验证:

  • $ sudo echo "hello world" > /dev/globalmem1
  • $ cat /dev/globalmem1
  • hello world

总结和思考

文中的那张图片对字符设备驱动总结的很好,cdev对应了一个字符设备,主要包括了设备号(dev_t)和相应的操作(file_operations)。module_init宏指定驱动加载函数,主要需要指定以下工作:register_chrdev_region、cdev_init和cdev_add。module_exit宏指定驱动卸载函数,主要需要指定以下工作:cdev_del和unregister_chrdev_region。module_init对应的printk消息能看到,但是module_exit还不清楚发生在什么条件,需要继续学习。

验证驱动的实验中感受到驱动设备和文件很好的匹配关系——“一切都是文件”,基本文件的操作函数都能很好的工作,比如fgets等。

并且文末还提及了支持多个相同设备的驱动,感觉非常全面的介绍了字符设备驱动的总体概貌。希望继续学习之后能看得懂以及分析真正生产环境中的驱动代码。