简单的字符设备驱动

实验:写一个简单的字符设备驱动

本实验我们编写一个简单的字符设备驱动,实现基本的 open()read()write() 方法。接着编写用户空间的测试程序,测试 read() 方法。

代码清单 1 是实验字符设备驱动的完整代码。

代码清单 1 simple character device
  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/uaccess.h>
  4. #include <linux/init.h>
  5. #include <linux/cdev.h>
  6.  
  7. #define DEMO_NAME "my_demo_dev"
  8. static dev_t dev;
  9. static struct cdev* demo_cdev;
  10. static signed count = 1;
  11.  
  12. static int demodrv_open(struct inode* inode, struct file* file)
  13. {
  14.     int major = MAJOR(inode->i_rdev);
  15.     int minor = MINOR(inode->i_rdev);
  16.  
  17.     printk("%s: major=%d, minor=%d\n", __func__, major, minor);
  18.  
  19.     return 0;
  20. }
  21.  
  22. static int demodrv_release(struct inode* inode, struct file* file)
  23. {
  24.     return 0;
  25. }
  26.  
  27. static ssize_t demodrv_read(struct file* file, char __user* buf, size_t lbuf, loff_t* ppos)
  28. {
  29.     printk("%s: enter\n", __func__);
  30.     return 0;
  31. }
  32.  
  33. static ssize_t demodrv_write(struct file* file, const char __user* buf, size_t count, loff_t* f_pos)
  34. {
  35.     printk("%s: enter\n", __func__);
  36.     return 0;
  37. }
  38.  
  39. static const struct file_operations demodrv_fops =
  40. {
  41.     .owner = THIS_MODULE,
  42.     .open = demodrv_open,
  43.     .release = demodrv_release,
  44.     .read = demodrv_read,
  45.     .write = demodrv_write
  46. };
  47.  
  48. static int __init simple_char_init(void)
  49. {
  50.     int ret;
  51.  
  52.     ret = alloc_chrdev_region(&dev, 0, count, DEMO_NAME);
  53.     if (ret)
  54.     {
  55.         printk("failed to allocate char device region");
  56.         return ret;
  57.     }
  58.  
  59.     demo_cdev = cdev_alloc();
  60.     if (!demo_cdev)
  61.     {
  62.         printk("cdev_alloc failed\n");
  63.         goto unregister_chrdev;
  64.     }
  65.  
  66.     cdev_init(demo_cdev, &demodrv_fops);
  67.    
  68.     ret = cdev_add(demo_cdev, dev, count);
  69.     if (ret)
  70.     {
  71.         printk("cdev_add failed\n");
  72.         goto cdev_fail;
  73.     }
  74.  
  75.     printk("succeeded register char device: %s\n", DEMO_NAME);
  76.     printk("major number = %d, minor number = %d\n", MAJOR(dev), MINOR(dev));
  77.  
  78.     return 0;
  79.  
  80. cdev_fail:
  81.     cdev_del(demo_cdev);
  82. unregister_chrdev:
  83.     unregister_chrdev_region(dev, count);
  84.  
  85.     return ret;
  86. }
  87.  
  88. static void __exit simple_char_exit(void)
  89. {
  90.     printk("removing device\n");
  91.  
  92.     if (demo_cdev)
  93.         cdev_del(demo_cdev);
  94.  
  95.     unregister_chrdev_region(dev, count);
  96. }
  97.  
  98. module_init(simple_char_init);
  99. module_exit(simple_char_exit);
  100.  
  101. MODULE_AUTHOR("rlk");
  102. MODULE_LICENSE("GPL v2");
  103. MODULE_DESCRIPTION("simple character device");

我们首先看到字符设备驱动的初始化函数 simple_char_init。其中最先调用 alloc_chrdev_region() 函数为字符设备驱动动态分配一个未被使用的设备号。其函数原型如下:

  • int alloc_chrdev_region(dev_t *dev,
  •     unsigned int firstminor,
  •     unsigned int count,
  •     char *name);

其中,dev 会返回最终分配的设备号。firstminor 是请求的第一个次设备号的基数,count 是需要分配的此设备好的数量。name 是与设备关联的名字,这个名字将出现在 /proc/devices 中。

设备号分配成功时会返回 0,否则返回负值。最终分配的设备号需要使用 unregister_chrdev_region() 函数释放。

举个例子:如果 firstminor 为 0, count 为 10,那么就会得到 10 个设备号,它们的次设备号分别为 0、1、2、……、10。

接着我们使用 cdev_alloc() 函数分配并初始化一个 cdev 结构。目前没有过多了解 cdev 结构,可以把它看作是字符设备的抽象。最终我们需要使用 cdev_del() 函数来释放分配的结构资源。

再接着调用 cdev_init() 函数来初始化字符设备结构,主要是初始化它的 file_operations 成员,其中定义了设备如何读、写等,后续我们会实现这些操作函数。

最后我们通过 cdev_add() 函数将以上分配的设备结构添加到系统中。

可能会有多个设备由同一个驱动程序管理。

接着我们看实现的操作函数,实现比较简单:open() 函数打印设备的主、次号;read() 和 write() 函数只是打印一下日志。

字符设备驱动的退出函数内容,在上面已经介绍到了。要通过 cdev_del() 函数释放分配的字符设备结构空间;还要调用 unregister_chrdev_region() 函数释放字符设备号资源。

编写如下 Makefile:

  1. BASEINCLUDE ?= /lib/modules/`uname -r`/build
  2.  
  3. mydemo-objs := simple_char.o
  4.  
  5. obj-m := mydemo.o
  6.  
  7. all:
  8.     $(MAKE) -C $(BASEINCLUDE) M=$(PWD) modules;
  9.  
  10. clean:
  11.     $(MAKE) -C $(BASEINCLUDE) M=$(PWD) clean;
  12.     rm -f *.ko

编译成功后加载内核模块:

  • tim@tim:~$ sudo insmod mydemo.ko
  • tim@tim:~$ sudo dmesg
  • [ 7849.308204] succeeded register char device: my_demo_dev
  • [ 7849.308206] major number = 238, minor number = 0

可以通过查看 /proc/devices 文件核对:

  • tim@tim:~$ cat /proc/devices
  • Character devices:
  • 238 my_demo_dev

'proc' 是 'process' 的缩写。

最后我们手动创建一个 dev 节点,这样就能在用户层使用这个字符设备了:

  • tim@tim:~$ sudo mknod /dev/demo_drv c 238 0

使用 device_create 等系列函数也能自动创建设备节点。

创建好 dev 节点之后,我们就可以写一个测试程序验证写的驱动程序。如代码清单 2 所示,调用用户态的 open() 和 read(),最终会调用到驱动中的 open() 和 read()。

代码清单 2 测试程序
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <unistd.h>
  4.  
  5. #define DEMO_DEV_NAME "/dev/demo_drv"
  6.  
  7. int main()
  8. {
  9.     char buffer[64];
  10.     int fd;
  11.  
  12.     fd = open(DEMO_DEV_NAME, O_RDONLY);
  13.     if (fd < 0)
  14.     {
  15.         printf("open device %s failed\n", DEMO_DEV_NAME);
  16.         return -1;
  17.     }
  18.  
  19.     read(fd, buffer, 64);
  20.     close(fd);
  21.  
  22.     return 0;
  23. }

编译测试程序后运行,并查看内核日志,可以看到符合预期。

  • tim@tim:~$ gcc test.c -o test
  • tim@tim:~$ ./test
  • tim@tim:~$ sudo dmesg
  • [ 926.311786] demodrv_open: major=238, minor=0
  • [ 926.311790] demodrv_read: enter

实验:使用 misc 机制来创建设备驱动

杂项设备(Miscellaneous Device)是Linux内核中一种特殊类型的设备,用于表示一些无法被常规设备类型(如字符设备或块设备)所归类的设备。它提供了一种通用的机制,可以将各种类型的设备注册到内核中,以便用户空间程序可以通过文件系统接口与这些设备进行交互。

代码清单 3 中把之前的字符设备驱动代码改写成了杂项设备驱动。

代码清单 3 simple miscellaneous device
  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/uaccess.h>
  4. #include <linux/init.h>
  5. #include <linux/cdev.h>
  6. #include <linux/miscdevice.h>
  7.  
  8. #define DEMO_NAME "my_demo_dev"
  9.  
  10. static int demodrv_open(struct inode* inode, struct file* file)
  11. {
  12.     int major = MAJOR(inode->i_rdev);
  13.     int minor = MINOR(inode->i_rdev);
  14.  
  15.     printk("%s: major=%d, minor=%d\n", __func__, major, minor);
  16.  
  17.     return 0;
  18. }
  19.  
  20. static int demodrv_release(struct inode* inode, struct file* file)
  21. {
  22.     return 0;
  23. }
  24.  
  25. static ssize_t demodrv_read(struct file* file, char __user* buf, size_t lbuf, loff_t* ppos)
  26. {
  27.     printk("%s: enter\n", __func__);
  28.     return 0;
  29. }
  30.  
  31. static ssize_t demodrv_write(struct file* file, const char __user* buf, size_t count, loff_t* f_pos)
  32. {
  33.     printk("%s: enter\n", __func__);
  34.     return 0;
  35. }
  36.  
  37. static const struct file_operations demodrv_fops =
  38. {
  39.     .owner = THIS_MODULE,
  40.     .open = demodrv_open,
  41.     .release = demodrv_release,
  42.     .read = demodrv_read,
  43.     .write = demodrv_write
  44. };
  45.  
  46. static struct device* mydemodrv_device;
  47.  
  48. static struct miscdevice mydemodrv_misc_device =
  49. {
  50.     .minor = MISC_DYNAMIC_MINOR,
  51.     .name = DEMO_NAME,
  52.     .fops = &demodrv_fops,
  53. };
  54.  
  55. static int __init simple_char_init(void)
  56. {
  57.     int ret;
  58.  
  59.     ret = misc_register(&mydemodrv_misc_device);
  60.     if (ret)
  61.     {
  62.         printk("failed register misc device\n");
  63.         return ret;
  64.     }
  65.  
  66.     mydemodrv_device = mydemodrv_misc_device.this_device;
  67.  
  68.     printk("succeeded register char device: %s\n", DEMO_NAME);
  69.  
  70.     return 0;
  71. }
  72.  
  73. static void __exit simple_char_exit(void)
  74. {
  75.     printk("removing device\n");
  76.  
  77.     misc_deregister(&mydemodrv_misc_device);
  78. }
  79.  
  80. module_init(simple_char_init);
  81. module_exit(simple_char_exit);
  82.  
  83. MODULE_AUTHOR("rlk");
  84. MODULE_LICENSE("GPL v2");
  85. MODULE_DESCRIPTION("simple character device");

和字符设备主要的差异是,杂项设备的注册很简单,一个 misc_register() 函数即可完成。而且能够自动在 /dev 目录下分配设备文件,无需我们手动创建。它的原型为:

  • int misc_register(struct miscdevice* misc);

针对传入的 miscdevice 结构体,我们一般需要赋值以下成员:

minor:次设备号。可以手动指定,一般使用 MISC_DYNAMIC_MINOR 进行动态分配。

杂项设备的主设备号是 10。

name:设备名称。就是出现在 /dev 目录下的设备文件名。

fops:文件操作函数集合。这块和上一节字符设备驱动中提及的文件操作函数集合是同一个内容。

与 misc_register 对应,misc_deregister 用于注销杂项设备。

注意引入头文件 linux/miscdevice.h。

实验:为虚拟设备编写驱动

本实验为 read()write() 方法添加实现。为此我们创建一个虚拟设备,通过它来进行读写操作。

代码清单 4 是它的实现,大部分内容和上节内容是一样的。我们关注 device_buffer 指针,它在模块加载时分配空间,同时注意释放。这段分配的内存就是模拟我们读写操作作用的内存。

代码清单 4 simple fifo device
  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/uaccess.h>
  4. #include <linux/init.h>
  5. #include <linux/cdev.h>
  6. #include <linux/miscdevice.h>
  7.  
  8. #define DEMO_NAME "my_demo_dev"
  9. /* 虚拟 FIFO 设备的缓冲区 */
  10. static char* device_buffer;
  11. #define MAX_DEVICE_BUFFER_SIZE 64
  12.  
  13. static struct device* mydemodrv_device;
  14.  
  15. static int demodrv_open(struct inode* inode, struct file* file)
  16. {
  17.     int major = MAJOR(inode->i_rdev);
  18.     int minor = MINOR(inode->i_rdev);
  19.  
  20.     printk("%s: major=%d, minor=%d\n", __func__, major, minor);
  21.  
  22.     return 0;
  23. }
  24.  
  25. static int demodrv_release(struct inode* inode, struct file* file)
  26. {
  27.     return 0;
  28. }
  29.  
  30. static ssize_t demodrv_read(struct file* file, char __user* buf, size_t lbuf, loff_t* ppos)
  31. {
  32.     int actual_readed;
  33.     int max_free;
  34.     int need_read;
  35.     int ret;
  36.  
  37.     printk("%s enter\n", __func__);
  38.  
  39.     max_free = MAX_DEVICE_BUFFER_SIZE - *ppos;
  40.     need_read = max_free > lbuf ? lbuf : max_free;
  41.     if (need_read == 0)
  42.         dev_warn(mydemodrv_device, "no space for read");
  43.  
  44.     ret = copy_to_user(buf, device_buffer + *ppos, need_read);
  45.     if (ret == need_read)
  46.         return -EFAULT;
  47.  
  48.     actual_readed = need_read - ret;
  49.     *ppos += actual_readed;
  50.  
  51.     printk("%s, actual_read=%d, pos=%lld\n", __func__, actual_readed, *ppos);
  52.  
  53.     return actual_readed;
  54. }
  55.  
  56. static ssize_t demodrv_write(struct file* file, const char __user* buf, size_t count, loff_t* ppos)
  57. {
  58.     int actual_write;
  59.     int free;
  60.     int need_write;
  61.     int ret;
  62.  
  63.     printk("%s: enter\n", __func__);
  64.  
  65.     free = MAX_DEVICE_BUFFER_SIZE - *ppos;
  66.     need_write = free > count ? count : free;
  67.     if (need_write == 0)
  68.         dev_warn(mydemodrv_device, "no space for write");
  69.  
  70.     ret = copy_from_user(device_buffer + *ppos, buf, need_write);
  71.     if (ret == need_write)
  72.         return -EFAULT;
  73.  
  74.     actual_write = need_write - ret;
  75.     *ppos += actual_write;
  76.     printk("%s: actual_write=%d, ppos=%lld\n", __func__, actual_write, *ppos);
  77.  
  78.     return actual_write;
  79. }
  80.  
  81. static const struct file_operations demodrv_fops =
  82. {
  83.     .owner = THIS_MODULE,
  84.     .open = demodrv_open,
  85.     .release = demodrv_release,
  86.     .read = demodrv_read,
  87.     .write = demodrv_write
  88. };
  89.  
  90. static struct miscdevice mydemodrv_misc_device =
  91. {
  92.     .minor = MISC_DYNAMIC_MINOR,
  93.     .name = DEMO_NAME,
  94.     .fops = &demodrv_fops,
  95. };
  96.  
  97. static int __init simple_char_init(void)
  98. {
  99.     int ret;
  100.  
  101.     device_buffer = kmalloc(MAX_DEVICE_BUFFER_SIZE, GFP_KERNEL);
  102.     if (!device_buffer)
  103.         return -ENOMEM;
  104.  
  105.     ret = misc_register(&mydemodrv_misc_device);
  106.     if (ret)
  107.     {
  108.         printk("failed register misc device\n");
  109.         kfree(device_buffer);
  110.         return ret;
  111.     }
  112.  
  113.     mydemodrv_device = mydemodrv_misc_device.this_device;
  114.  
  115.     printk("succeeded register char device: %s\n", DEMO_NAME);
  116.  
  117.     return 0;
  118. }
  119.  
  120. static void __exit simple_char_exit(void)
  121. {
  122.     printk("removing device\n");
  123.  
  124.     kfree(device_buffer);
  125.     misc_deregister(&mydemodrv_misc_device);
  126. }
  127.  
  128. module_init(simple_char_init);
  129. module_exit(simple_char_exit);
  130.  
  131. MODULE_AUTHOR("rlk");
  132. MODULE_LICENSE("GPL v2");
  133. MODULE_DESCRIPTION("simple character device");

关注实现的 read() 函数,代码里对应为 demodrv_read,其定义为:

  • static ssize_t demodrv_read(struct file* file, char __user* buf, size_t lbuf, loff_t* ppos);

file:设备文件指针,包含文件描述符等设备文件信息。

buf:指向用户空间(特别用 __user 宏加以指示)缓冲区的指针。之后读取的数据就会传输到这里。

lbuf:要读取的最大字节数。

ppos:文件位置偏移量的指针。它用于跟踪在文件中读取的位置,以便下一次读取可以从适当的位置开始。

demodrv_read() 函数的操作:根据 ppos 确定要读取的数据位置,将内核空间缓冲区内容复制到用户空间缓冲区。更新 ppos 的值,以便下次从适当的位置开始。返回读取的字节数或错误码。

将数据从内核空间复制到用户空间,使用 copy_to_user() 函数。它的原型如下:

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

to:指向用户空间目标地址的指针。数据将从内核空间复制到这个目标地址。

from:指向内核空间源地址的指针。数据将从这个源地址复制到用户空间。

n:要复制的字节数。

copy_to_user 函数的返回值是复制失败的字节数。如果返回值为0,则表示复制成功。

注意,copy_to_user 函数的返回值是复制失败的字节数。

demodrv_write() 是实现的写操作函数,参数定义和写操作是类似,这边就不一一讲解说明了。copy_from_user() 用于将数据从用户空间复制到内核空间。

接着,如代码清单 5 所示,我们写一个测试程序,来进行读写测试。

代码清单 5 测试程序
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. #define DEMO_DEV_NAME "/dev/my_demo_dev"
  8.  
  9. int main()
  10. {
  11.     char buffer[64];
  12.     int fd;
  13.     int ret;
  14.     size_t len;
  15.     char message[] = "Testing the virtual FIFO device";
  16.     char* read_buffer;
  17.  
  18.     len = sizeof(message);
  19.  
  20.     fd = open(DEMO_DEV_NAME, O_RDWR);
  21.     if (fd < 0)
  22.     {
  23.         printf("open device %s failed\n", DEMO_DEV_NAME);
  24.         return -1;
  25.     }
  26.  
  27.     /* 1. write the message to device */
  28.     ret = write(fd, message, len);
  29.     if (ret != len)
  30.     {
  31.         printf("cannot write on device %d, ret=%d", fd, ret);
  32.         return -1;
  33.     }
  34.  
  35.     /* close the fd, and reopen it */
  36.     close(fd);
  37.  
  38.     fd = open(DEMO_DEV_NAME, O_RDWR);
  39.     if (fd < 0)
  40.     {
  41.         printf("open device %s failed\n", DEMO_DEV_NAME);
  42.         return -1;
  43.     }
  44.  
  45.     read_buffer = (char*)malloc(2 * len);
  46.     memset(read_buffer, 0, 2 * len);
  47.  
  48.     ret = read(fd, read_buffer, 2*len);
  49.     printf("read %d bytes\n", ret);
  50.     printf("read buffer=%s\n", read_buffer);
  51.  
  52.     close(fd);
  53.     free(read_buffer);
  54.  
  55.     return 0;
  56. }

测试程序首先打开设备,写入 message 数组,大小是 32 字节(包含 null 终止字符)。接着关闭设备再重新打开,可以读取刚才写入的内容。

需要打开两次设备的原因是我们没有实现 llseek 函数。驱动程序中,每次读写操作都会维护增加文件偏移量。

我们可以从 log 中核实具体的操作:

  • tim@tim:~$ sudo ./test
  • read 64 bytes
  • read buffer=Testing the virtual FIFO device
  • tim@tim:~$ sudo dmesg
  • [23093.876971] demodrv_open: major=10, minor=120
  • [23093.876975] demodrv_write: enter
  • [23093.876975] demodrv_write: actual_write=32, ppos=32
  • [23093.876999] demodrv_open: major=10, minor=120
  • [23093.877010] demodrv_read enter
  • [23093.877010] demodrv_read, actual_read=64, pos=64

实验:使用 KFIFO 环形缓冲区改进设备驱动

上节的实验,缓冲区的写入和读取都是基于文件偏移值的,这不利于“生产者和消费者”的情况。针对这种情况,我们这节介绍一种 Linux 内核实现的称为 KFIFO 的机制。

书中介绍 KFIFO 无需额外加锁就能保证数据的安全。猜测内部实现是无锁队列。

代码清单 6 是 KFIFO 的例子,主要是 DEFINE_KFIFO、kfifo_to_user 和 kfifo_from_user 的使用。

代码清单 6 simple kfifo device
  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/uaccess.h>
  4. #include <linux/init.h>
  5. #include <linux/cdev.h>
  6. #include <linux/miscdevice.h>
  7. #include <linux/kfifo.h>
  8.  
  9. #define DEMO_NAME "my_demo_dev"
  10. static struct device* mydemodrv_device;
  11.  
  12. DEFINE_KFIFO(mydemo_fifo, char, 64);
  13.  
  14. static int demodrv_open(struct inode* inode, struct file* file)
  15. {
  16.     int major = MAJOR(inode->i_rdev);
  17.     int minor = MINOR(inode->i_rdev);
  18.  
  19.     printk("%s: major=%d, minor=%d\n", __func__, major, minor);
  20.  
  21.     return 0;
  22. }
  23.  
  24. static int demodrv_release(struct inode* inode, struct file* file)
  25. {
  26.     return 0;
  27. }
  28.  
  29. static ssize_t demodrv_read(struct file* file, char __user* buf, size_t count, loff_t* ppos)
  30. {
  31.     int actual_readed;
  32.     int ret;
  33.     printk("%s: count=%lu\n", __func__, count);
  34.  
  35.     ret = kfifo_to_user(&mydemo_fifo, buf, count, &actual_readed);
  36.     if (ret)
  37.         return -EIO;
  38.  
  39.     printk("%s, actual_readed=%d, pos=%lld\n", __func__, actual_readed, *ppos);
  40.     return actual_readed;
  41. }
  42.  
  43. static ssize_t demodrv_write(struct file* file, const char __user* buf, size_t count, loff_t* ppos)
  44. {
  45.     int actual_write;
  46.     int ret;
  47.  
  48.     printk("%s: count=%lu\n", __func__, count);
  49.  
  50.     //if (kfifo_avail(&mydemo_fifo) < count)
  51.     //  return -EAGAIN;
  52.  
  53.     ret = kfifo_from_user(&mydemo_fifo, buf, count, &actual_write);
  54.     if (ret)
  55.         return -EIO;
  56.  
  57.     printk("%s: actual_write=%d, ppos=%lld\n", __func__, actual_write, *ppos);
  58.  
  59.     return actual_write;
  60. }
  61.  
  62. static const struct file_operations demodrv_fops =
  63. {
  64.     .owner = THIS_MODULE,
  65.     .open = demodrv_open,
  66.     .release = demodrv_release,
  67.     .read = demodrv_read,
  68.     .write = demodrv_write
  69. };
  70.  
  71. static struct miscdevice mydemodrv_misc_device =
  72. {
  73.     .minor = MISC_DYNAMIC_MINOR,
  74.     .name = DEMO_NAME,
  75.     .fops = &demodrv_fops,
  76. };
  77.  
  78. static int __init simple_char_init(void)
  79. {
  80.     int ret;
  81.  
  82.     ret = misc_register(&mydemodrv_misc_device);
  83.     if (ret)
  84.     {
  85.         printk("failed register misc device\n");
  86.         return ret;
  87.     }
  88.  
  89.     mydemodrv_device = mydemodrv_misc_device.this_device;
  90.  
  91.     printk("succeeded register char device: %s\n", DEMO_NAME);
  92.  
  93.     return 0;
  94. }
  95.  
  96. static void __exit simple_char_exit(void)
  97. {
  98.     printk("removing device\n");
  99.  
  100.     misc_deregister(&mydemodrv_misc_device);
  101. }
  102.  
  103. module_init(simple_char_init);
  104. module_exit(simple_char_exit);
  105.  
  106. MODULE_AUTHOR("rlk");
  107. MODULE_LICENSE("GPL v2");
  108. MODULE_DESCRIPTION("simple character device");

DEFINE_KFIFO 的定义如下,用于申明一个 kfifo 变量:

  • DEFINE_KFIFO(name, type, size)

name 是为 kfifo 分配的变量名;type 是存储在 kfifo 中的数据类型;size 是 kfifo 的大小,单位是 type 类型元素的数量。

kfifo_to_user 的定义如下,用于将 kfifo 中的数据复制到用户空间。

  • unsigned int kfifo_to_user(
  •      struct kfifo* fifo,
  •      void __user* to,
  •      unsigned int len,
  •      unsigned int* copied);

fifo 是指向 kfifo 结构的指针;to 是指向用户空间的指针,数据将被复制到这个地址;len 是请求复制的字节数;copied 是一个指向无符号整数的指针,将返回实际复制的字节数。

kfifo_to_user 如果操作成功,将返回 0;否则返回错误码。

kfifo_from_user 用于将用户空间的数据复制到 kfifo 中,其定义和 kfifo_to_user 的类似,不再赘述。

与上一节的测试程序不同,使用 kfifo 就不用打开两次设备文件了,因为 kfifo 内部有维护 “队列指针”。这边我们再介绍另一种验证方法,使用 cat 命令和重定向命令写入:

  • tim@tim:~$ sudo su
  • root@tim:~$ echo "Hello World!" > /dev/my_demo_dev
  • root@tim:~$ cat /dev/my_demo_dev
  • Hello World!

我们可以从日志里核对读写操作。可以推测,cat 的逻辑是一直读取到没有内容读为止,即 read 的返回值为 0。

  • [13235.125900] demodrv_open: major=10, minor=120
  • [13235.125914] demodrv_write: count=13
  • [13235.125916] demodrv_write: actual_write=13, ppos=0
  • [13244.102314] demodrv_open: major=10, minor=120
  • [13244.102324] demodrv_read: count=131072
  • [13244.102326] demodrv_read, actual_readed=13, pos=0
  • [13244.102341] demodrv_read: count=131072
  • [13244.102342] demodrv_read, actual_readed=0, pos=0

重定向写入的逻辑也是类似,直到 write 的返回值累计达到需要写入的值为止。所以目前的程序,当需要写入的内容大于 kfifo 的容量时,会一直尝试写入,导致控制台一直不会返回。

目前想到一种简单的方法,写入的字节数大于 kfifo 容量时,直接返回错误:

if (kfifo_avail(&mydemo_fifo) < count) return -EAGAIN;

实验:把虚拟设备驱动改为非阻塞模式

open() 函数的定义如下,其中 flags 可以设置为 O_NONBLOCK,指示以非阻塞模式打开文件。

  • int open(const char* pathname, int flags);

我们修改之前的驱动代码,如代码清单 7 所示,以适配非阻塞模式。

代码清单 7 simple nonblock kfifo device
  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/uaccess.h>
  4. #include <linux/init.h>
  5. #include <linux/cdev.h>
  6. #include <linux/miscdevice.h>
  7. #include <linux/kfifo.h>
  8.  
  9. #define DEMO_NAME "my_demo_dev"
  10. static struct device* mydemodrv_device;
  11.  
  12. DEFINE_KFIFO(mydemo_fifo, char, 64);
  13.  
  14. static int demodrv_open(struct inode* inode, struct file* file)
  15. {
  16.     int major = MAJOR(inode->i_rdev);
  17.     int minor = MINOR(inode->i_rdev);
  18.  
  19.     printk("%s: major=%d, minor=%d\n", __func__, major, minor);
  20.  
  21.     return 0;
  22. }
  23.  
  24. static int demodrv_release(struct inode* inode, struct file* file)
  25. {
  26.     return 0;
  27. }
  28.  
  29. static ssize_t demodrv_read(struct file* file, char __user* buf, size_t count, loff_t* ppos)
  30. {
  31.     int actual_readed;
  32.     int ret;
  33.     printk("%s: count=%lu\n", __func__, count);
  34.  
  35.     if (kfifo_is_empty(&mydemo_fifo))
  36.     {
  37.         if (file->f_flags & O_NONBLOCK)
  38.             return -EAGAIN;
  39.     }
  40.  
  41.     ret = kfifo_to_user(&mydemo_fifo, buf, count, &actual_readed);
  42.     if (ret)
  43.         return -EIO;
  44.  
  45.     printk("%s, actual_readed=%d, pos=%lld\n", __func__, actual_readed, *ppos);
  46.     return actual_readed;
  47. }
  48.  
  49. static ssize_t demodrv_write(struct file* file, const char __user* buf, size_t count, loff_t* ppos)
  50. {
  51.     int actual_write;
  52.     int ret;
  53.  
  54.     printk("%s: count=%lu\n", __func__, count);
  55.  
  56.     if (kfifo_is_full(&mydemo_fifo))
  57.     {
  58.         if (file->f_flags & O_NONBLOCK)
  59.             return -EAGAIN;
  60.     }
  61.  
  62.     ret = kfifo_from_user(&mydemo_fifo, buf, count, &actual_write);
  63.     if (ret)
  64.         return -EIO;
  65.  
  66.     printk("%s: actual_write=%d, ppos=%lld\n", __func__, actual_write, *ppos);
  67.  
  68.     return actual_write;
  69. }
  70.  
  71. static const struct file_operations demodrv_fops =
  72. {
  73.     .owner = THIS_MODULE,
  74.     .open = demodrv_open,
  75.     .release = demodrv_release,
  76.     .read = demodrv_read,
  77.     .write = demodrv_write
  78. };
  79.  
  80. static struct miscdevice mydemodrv_misc_device =
  81. {
  82.     .minor = MISC_DYNAMIC_MINOR,
  83.     .name = DEMO_NAME,
  84.     .fops = &demodrv_fops,
  85. };
  86.  
  87. static int __init simple_char_init(void)
  88. {
  89.     int ret;
  90.  
  91.     ret = misc_register(&mydemodrv_misc_device);
  92.     if (ret)
  93.     {
  94.         printk("failed register misc device\n");
  95.         return ret;
  96.     }
  97.  
  98.     mydemodrv_device = mydemodrv_misc_device.this_device;
  99.  
  100.     printk("succeeded register char device: %s\n", DEMO_NAME);
  101.  
  102.     return 0;
  103. }
  104.  
  105. static void __exit simple_char_exit(void)
  106. {
  107.     printk("removing device\n");
  108.  
  109.     misc_deregister(&mydemodrv_misc_device);
  110. }
  111.  
  112. module_init(simple_char_init);
  113. module_exit(simple_char_exit);
  114.  
  115. MODULE_AUTHOR("rlk");
  116. MODULE_LICENSE("GPL v2");
  117. MODULE_DESCRIPTION("simple character device");

较上一节的代码,增加非阻塞操作逻辑:如果读取时 kfifo 为空,则直接返回错误值;如果写入时 kfifo 已经满了,则直接返回错误值。

EAGAIN 可以记忆成 "Error, Try AGAIN"。

这也是上一节一直写入问题的一种解决方式。

从这个例子可以看出,标志在驱动层是否起作用,取决于具体的设备驱动程序是否适配此标志。

实验:把虚拟设备驱动改为阻塞模式

上一节实验的设备驱动是非阻塞的,只要驱动当时无法满足请求的资源,就会立即返回 -EAGAIN。应用程序在驱动非阻塞模式下,为了能成功读写数据,需要采用轮询的方式。

而应用程序在驱动阻塞模式下,就不用这么麻烦:当请求的数据无法立刻满足时,驱动会让进程睡眠,直到数据准备好为止。

在内核中,我们可以使用等待队列来维护进程的阻塞模式相关操作。等待队列的定义如下:

书上说可使用等待队列机制来实现进程的阻塞,我认为用“维护”更合适一点。

  • typedef struct __wait_queue_head {
  •     spinlock_t lock;
  •     struct list_head task_list;
  • } wait_queue_head_t;

我们可以把等待队列简单理解成一个带锁的链表,以满足同步需求。等待队列上的相关操作有睡眠等待和唤醒,这边先仅介绍实验代码中用到的。

睡眠等待相关的操作函数是 wait_event_interruptible,其定义如下:

  • wait_event_interruptible(q, condition)

其中,q 是 wait_queue_head_t 类型的等待队列头部,condition 是等待条件。wait_event_interruptible 会让进程在满足等待条件时进入睡眠状态。

这边说明一下 wait_event_interruptible 的大致流程:首先判断传入的等待条件是否满足,如果不满足则直接返回,以防止进程进行无故的睡眠等待。如果满足等待条件,会把当前进程信息放入等待队列中,并主动让出执行时间,进入睡眠状态,这部分是内核中的进程调度机制。当满足唤醒条件时,调度机制会重新恢复睡眠前保存的上下文,继续运行。后续会把唤醒的进程从等待队列中删除。

驱动在内核态也是进程上下文相关的,驱动部分也同样进入阻塞。

唤醒相关的操作函数是 wake_up_interruptible,其定义如下:

  • void wake_up_interruptible(wait_queue_head_t *q);

wake_up_interruptible 会唤醒传入等待队列中记录的所有进程。函数中进行的“唤醒”操作仅仅是标记进程的状态为就绪,即不保证进程马上就能唤醒,还是依赖于调度策略。

以上就是睡眠等待和唤醒的介绍,可以看到机制都是基于本身的调度机制,所以我觉得等待队列用“维护”一词更加妥当。

等待队列的维护者是本驱动。单从等待队列上来看就是带锁的链表,就是进程信息的插入、删除和遍历,并不是高深的知识,不用“害怕”。

如代码清单 8 所示,我们看阻塞版本的 kfifo 实验代码。

代码清单 8 simple block kfifo device
  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/uaccess.h>
  4. #include <linux/init.h>
  5. #include <linux/cdev.h>
  6. #include <linux/slab.h>
  7. #include <linux/miscdevice.h>
  8. #include <linux/kfifo.h>
  9.  
  10. #define DEMO_NAME "my_demo_dev"
  11. DEFINE_KFIFO(mydemo_fifo, char, 64);
  12.  
  13. struct mydemo_device
  14. {
  15.     const char* name;
  16.     struct device* dev;
  17.     struct miscdevice* miscdev;
  18.     wait_queue_head_t read_queue;
  19.     wait_queue_head_t write_queue;
  20. };
  21.  
  22. struct mydemo_private_data
  23. {
  24.     struct mydemo_device* device;
  25. };
  26.  
  27. static struct mydemo_device* mydemo_device;
  28.  
  29. static int demodrv_open(struct inode* inode, struct file* file)
  30. {
  31.     struct mydemo_private_data* data;
  32.     struct mydemo_device* device = mydemo_device;
  33.  
  34.     printk("%s: major=%d, minor=%d\n", __func__, MAJOR(inode->i_rdev), MINOR(inode->i_rdev));
  35.  
  36.     data = kmalloc(sizeof(struct mydemo_private_data), GFP_KERNEL);
  37.     if (!data)
  38.         return -ENOMEM;
  39.  
  40.     data->device = device;
  41.     file->private_data = data;
  42.  
  43.     return 0;
  44. }
  45.  
  46. static int demodrv_release(struct inode* inode, struct file* file)
  47. {
  48.     struct mydemo_private_data* data = file->private_data;
  49.     kfree(data);
  50.     return 0;
  51. }
  52.  
  53. static ssize_t demodrv_read(struct file* file, char __user* buf, size_t count, loff_t* ppos)
  54. {
  55.     struct mydemo_private_data* data = file->private_data;
  56.     struct mydemo_device* device = data->device;
  57.  
  58.     int actual_readed;
  59.     int ret;
  60.     printk("%s: count=%lu\n", __func__, count);
  61.  
  62.     if (kfifo_is_empty(&mydemo_fifo))
  63.     {
  64.         if (file->f_flags & O_NONBLOCK)
  65.             return -EAGAIN;
  66.  
  67.         printk("%s: pid=%d, going to sleep\n", __func__, current->pid);
  68.         ret = wait_event_interruptible(device->read_queue, !kfifo_is_empty(&mydemo_fifo));
  69.         if (ret)
  70.             return ret;
  71.     }
  72.  
  73.     ret = kfifo_to_user(&mydemo_fifo, buf, count, &actual_readed);
  74.     if (ret)
  75.         return -EIO;
  76.  
  77.     if (!kfifo_is_full(&mydemo_fifo))
  78.         wake_up_interruptible(&device->write_queue);
  79.  
  80.     printk("%s, pid=%d, actual_readed=%d, pos=%lld\n", __func__, current->pid, actual_readed, *ppos);
  81.     return actual_readed;
  82. }
  83.  
  84. static ssize_t demodrv_write(struct file* file, const char __user* buf, size_t count, loff_t* ppos)
  85. {
  86.     struct mydemo_private_data* data = file->private_data;
  87.     struct mydemo_device* device = data->device;
  88.  
  89.     int actual_write;
  90.     int ret;
  91.  
  92.     printk("%s: count=%lu\n", __func__, count);
  93.  
  94.     if (kfifo_is_full(&mydemo_fifo))
  95.     {
  96.         if (file->f_flags & O_NONBLOCK)
  97.             return -EAGAIN;
  98.  
  99.         printk("%s: pid=%d, going to sleep\n", __func__, current->pid);
  100.         ret = wait_event_interruptible(device->write_queue, !kfifo_is_full(&mydemo_fifo));
  101.         if (ret)
  102.             return ret;
  103.     }
  104.  
  105.     ret = kfifo_from_user(&mydemo_fifo, buf, count, &actual_write);
  106.     if (ret)
  107.         return -EIO;
  108.  
  109.     if (!kfifo_is_empty(&mydemo_fifo))
  110.         wake_up_interruptible(&device->read_queue);
  111.  
  112.     printk("%s: pid=%d, actual_write=%d, ppos=%lld\n", __func__, current->pid, actual_write, *ppos);
  113.  
  114.     return actual_write;
  115. }
  116.  
  117. static const struct file_operations demodrv_fops =
  118. {
  119.     .owner = THIS_MODULE,
  120.     .open = demodrv_open,
  121.     .release = demodrv_release,
  122.     .read = demodrv_read,
  123.     .write = demodrv_write
  124. };
  125.  
  126. static struct miscdevice mydemodrv_misc_device =
  127. {
  128.     .minor = MISC_DYNAMIC_MINOR,
  129.     .name = DEMO_NAME,
  130.     .fops = &demodrv_fops,
  131. };
  132.  
  133. static int __init simple_char_init(void)
  134. {
  135.     int ret;
  136.  
  137.     struct mydemo_device* device = kmalloc(sizeof(struct mydemo_device), GFP_KERNEL);
  138.     if (!device)
  139.         return -ENOMEM;
  140.  
  141.     ret = misc_register(&mydemodrv_misc_device);
  142.     if (ret)
  143.     {
  144.         printk("failed register misc device\n");
  145.         goto free_device;
  146.     }
  147.  
  148.     device->dev = mydemodrv_misc_device.this_device;
  149.     device->miscdev = &mydemodrv_misc_device;
  150.  
  151.     init_waitqueue_head(&device->read_queue);
  152.     init_waitqueue_head(&device->write_queue);
  153.  
  154.     mydemo_device = device;
  155.     printk("succeeded register char device: %s\n", DEMO_NAME);
  156.  
  157.     return 0;
  158.  
  159. free_device:
  160.     kfree(device);
  161.     return ret;
  162. }
  163.  
  164. static void __exit simple_char_exit(void)
  165. {
  166.     struct mydemo_device* device = mydemo_device;
  167.     printk("removing device\n");
  168.  
  169.     misc_deregister(&mydemodrv_misc_device);
  170.     kfree(device);
  171. }
  172.  
  173. module_init(simple_char_init);
  174. module_exit(simple_char_exit);
  175.  
  176. MODULE_AUTHOR("rlk");
  177. MODULE_LICENSE("GPL v2");
  178. MODULE_DESCRIPTION("simple character device");

在驱动设备加载时,初始化读和写的等待队列。设备进行读取时,如果 kfifo 为空,则进入睡眠等待。读取内容后,如果 kfifo 没满,则唤醒写等待队列中的进程。设备进行写操作时,如果 kfifo 已满,则进入睡眠等待。写入内容后,如果 kfifo 非空,则唤醒读等待队列中的进程。

我们使用 cat 和 echo 来验证驱动。

  • tim@tim:~$ sudo su
  • root@tim:~$ cat /dev/my_demo_dev &
  • root@tim:~$ echo "Hello World" > /dev/my_demo_dev
  • root@tim:~$ Hello World

在命令后加 &,表示让其在后台运行。因为一开始驱动内部的 kfifo 是空的,所以此时 cat 读取进程会进入睡眠等待。接着我们使用 echo 写入,则会唤醒读进程,控制台上就打印了写入的内容。

实验:向虚拟设备中添加 I/O 多路复用支持

多路复用在应用层上对应的函数是 poll() 函数。因为之前接触它不多,所以这个实验我们先从测试应用程序开始。先了解应用层想得到什么功能,再去实现驱动对应的内容。

poll 函数用于监控多个文件描述符以查看它们是否已经准备好进行 I/O 操作。函数原型如下:

  • int poll(struct pollfd fds[], nfds_t nfds, int timeout);

参数 fds 是一个指向 pollfd 结构数组的指针。每个 pollfd 结构表示一个文件描述符以及想要监视的事件类型。

参数 nfds 指定 fds 数组中的元素数目。

参数 timeout 指定返回前等待的最大毫秒数。设置为 -1,表示会一直阻塞,直到想要的事件发生。

参数 fds 对应的 pollfd 结构定义如下:

  • struct pollfd {
  •     int   fd;         /* 文件描述符 */
  •     short events;     /* 请求的事件 */
  •     short revents;    /* 返回的事件 */
  • };

成员 fd 为要被监控的文件描述符。

成员 events 指定感兴趣的事件的位掩码。常见的值包括 POLLIN(数据可读),POLLOUT(数据可写)。

成员 revents 的内容是,当 poll 返回时,包含的实际发生的事件的位掩码。

代码清单 9 poll test
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <sys/ioctl.h>
  7. #include <fcntl.h>
  8. #include <errno.h>
  9. #include <poll.h>
  10. #include <linux/input.h>
  11. #include <unistd.h>
  12.  
  13. int main()
  14. {
  15.     int ret;
  16.     struct pollfd fds[2];
  17.     char buffer0[64];
  18.     char buffer1[64];
  19.  
  20.     fds[0].fd = open("/dev/mydemo0", O_RDWR);
  21.     if (fds[0].fd == -1)
  22.         goto fail;
  23.     fds[0].events = POLLIN;
  24.  
  25.     fds[1].fd = open("/dev/mydemo1", O_RDWR);
  26.     if (fds[1].fd == -1)
  27.         goto fail;
  28.     fds[1].events = POLLIN;
  29.  
  30.     while (1)
  31.     {
  32.         ret = poll(fds, 2, -1);
  33.         if (ret == -1)
  34.             goto fail;
  35.  
  36.         if (fds[0].revents & POLLIN)
  37.         {
  38.             ret = read(fds[0].fd, buffer0, sizeof(buffer0));
  39.             if (ret < 0)
  40.                 goto fail;
  41.             printf("%s\n", buffer0);
  42.         }
  43.  
  44.         if (fds[1].revents & POLLIN)
  45.         {
  46.             ret = read(fds[1].fd, buffer1, sizeof(buffer1));
  47.             if (ret < 0)
  48.                 goto fail;
  49.             printf("%s\n", buffer1);
  50.         }
  51.     }
  52.  
  53. fail:
  54.     perror("poll test failed");
  55.     exit(EXIT_FAILURE);
  56. }

代码清单 9 是 poll 函数的测试程序。它一直监控两个设备是否数据可读,一旦数据可读,就从中读取数据。

代码清单 10 simple poll kfifo device
  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/uaccess.h>
  4. #include <linux/init.h>
  5. #include <linux/miscdevice.h>
  6. #include <linux/device.h>
  7. #include <linux/slab.h>
  8. #include <linux/kfifo.h>
  9. #include <linux/wait.h>
  10. #include <linux/sched.h>
  11. #include <linux/cdev.h>
  12. #include <linux/poll.h>
  13.  
  14. #define DEMO_NAME "mydemo_dev"
  15. #define MYDEMO_FIFO_SIZE 64
  16.  
  17. static dev_t dev;
  18. static struct cdev* demo_cdev;
  19.  
  20. struct mydemo_device
  21. {
  22.     char name[64];
  23.     struct device* dev;
  24.     wait_queue_head_t read_queue;
  25.     wait_queue_head_t write_queue;
  26.     struct kfifo mydemo_fifo;
  27. };
  28.  
  29. struct mydemo_private_data
  30. {
  31.     struct mydemo_device* device;
  32.     char name[64];
  33. };
  34.  
  35. #define MYDEMO_MAX_DEVICES 8
  36. static struct mydemo_device* mydemo_device[MYDEMO_MAX_DEVICES];
  37.  
  38. static int demodrv_open(struct inode* inode, struct file* file)
  39. {
  40.     unsigned int minor = iminor(inode);
  41.     struct mydemo_private_data* data;
  42.     struct mydemo_device* device = mydemo_device[minor];
  43.  
  44.     printk("%s: major=%d. minor=%d, device=%s\n",
  45.         __func__, MAJOR(inode->i_rdev), MINOR(inode->i_rdev), device->name);
  46.  
  47.     data = kmalloc(sizeof(struct mydemo_private_data), GFP_KERNEL);
  48.     if (!data)
  49.         return -ENOMEM;
  50.  
  51.     sprintf(data->name, "private_data_%d", minor);
  52.  
  53.     data->device = device;
  54.     file->private_data = data;
  55.  
  56.     return 0;
  57. }
  58.  
  59. static int demodrv_release(struct inode* inode, struct file* file)
  60. {
  61.     struct mydemo_priavte_data* data = file->private_data;
  62.     kfree(data);
  63.     return 0;
  64. }
  65.  
  66. static ssize_t demodrv_read(struct file* file, char* __user buf, size_t count, loff_t* ppos)
  67. {
  68.     struct mydemo_private_data* data = file->private_data;
  69.     struct mydemo_device* device = data->device;
  70.     int actual_readed;
  71.     int ret;
  72.  
  73.     if (kfifo_is_empty(&device->mydemo_fifo))
  74.     {
  75.         if (file->f_flags & O_NONBLOCK)
  76.             return -EAGAIN;
  77.  
  78.         printk("%s:%s pid=%d, going to sleep, %s\n",
  79.             __func__, device->name, current->pid, data->name);
  80.         ret = wait_event_interruptible(device->read_queue, !kfifo_is_empty(&device->mydemo_fifo));
  81.         if (ret)
  82.             return ret;
  83.     }
  84.  
  85.     ret = kfifo_to_user(&device->mydemo_fifo, buf, count, &actual_readed);
  86.     if (ret)
  87.         return -EIO;
  88.  
  89.     if (!kfifo_is_full(&device->mydemo_fifo))
  90.         wake_up_interruptible(&device->write_queue);
  91.  
  92.     printk("%s:%s, pid=%d, actual_readed=%d, pos=%lld\n",
  93.         __func__, device->name, current->pid, actual_readed, *ppos);
  94.     return actual_readed;
  95. }
  96.  
  97. static ssize_t demodrv_write(struct file* file, const char* __user buf, size_t count, loff_t* ppos)
  98. {
  99.     struct mydemo_private_data* data = file->private_data;
  100.     struct mydemo_device* device = data->device;
  101.     unsigned int actual_write;
  102.     int ret;
  103.  
  104.     if (kfifo_is_full(&device->mydemo_fifo))
  105.     {
  106.         if (file->f_flags & O_NONBLOCK)
  107.             return -EAGAIN;
  108.  
  109.         printk("%s:%s pid=%d, going to sleep, %s\n",
  110.             __func__, device->name, current->pid, data->name);
  111.         ret = wait_event_interruptible(device->write_queue, !kfifo_is_full(&device->mydemo_fifo));
  112.         if (ret)
  113.             return ret;
  114.     }
  115.  
  116.     ret = kfifo_from_user(&device->mydemo_fifo, buf, count, &actual_write);
  117.     if (ret)
  118.         return -EIO;
  119.  
  120.     if (!kfifo_is_empty(&device->mydemo_fifo))
  121.         wake_up_interruptible(&device->read_queue);
  122.  
  123.     printk("%s:%s pid=%d, actual_write=%d, ppos=%lld, ret=%d\n",
  124.         __func__, device->name, current->pid, actual_write, *ppos, ret);
  125.  
  126.     return actual_write;
  127. }
  128.  
  129. static unsigned int demodrv_poll(struct file* file, poll_table* wait)
  130. {
  131.     int mask = 0;
  132.     struct mydemo_private_data* data = file->private_data;
  133.     struct mydemo_device* device = data->device;
  134.  
  135.     poll_wait(file, &device->read_queue, wait);
  136.     poll_wait(file, &device->write_queue, wait);
  137.  
  138.     if (!kfifo_is_empty(&device->mydemo_fifo))
  139.         mask |= POLLIN | POLLRDNORM;
  140.     if (!kfifo_is_full(&device->mydemo_fifo))
  141.         mask |= POLLOUT | POLLWRNORM;
  142.  
  143.     return mask;
  144. }
  145.  
  146. static const struct file_operations demodrv_fops =
  147. {
  148.     .owner = THIS_MODULE,
  149.     .open = demodrv_open,
  150.     .release = demodrv_release,
  151.     .read = demodrv_read,
  152.     .write = demodrv_write,
  153.     .poll = demodrv_poll,
  154. };
  155.  
  156. static int __init simple_char_init(void)
  157. {
  158.     int ret;
  159.     int i;
  160.     struct mydemo_device* device;
  161.  
  162.     ret = alloc_chrdev_region(&dev, 0, MYDEMO_MAX_DEVICES, DEMO_NAME);
  163.     if (ret)
  164.     {
  165.         printk("failed to allocate char device region\n");
  166.         return ret;
  167.     }
  168.  
  169.     demo_cdev = cdev_alloc();
  170.     if (!demo_cdev)
  171.     {
  172.         printk("cdev_alloc failed\n");
  173.         goto unregister_chrdev;
  174.     }
  175.  
  176.     cdev_init(demo_cdev, &demodrv_fops);
  177.  
  178.     ret = cdev_add(demo_cdev, dev, MYDEMO_MAX_DEVICES);
  179.     if (ret)
  180.     {
  181.         printk("cdev_add failed\n");
  182.         goto cdev_fail;
  183.     }
  184.  
  185.     for (i = 0; i < MYDEMO_MAX_DEVICES; i++)
  186.     {
  187.         device = kmalloc(sizeof(struct mydemo_device), GFP_KERNEL);
  188.         if (!device)
  189.         {
  190.             ret = -ENOMEM;
  191.             goto free_device;
  192.         }
  193.  
  194.         sprintf(device->name, "%s%d", DEMO_NAME, i);
  195.         mydemo_device[i] = device;
  196.         init_waitqueue_head(&device->read_queue);
  197.         init_waitqueue_head(&device->write_queue);
  198.  
  199.         ret = kfifo_alloc(&device->mydemo_fifo, MYDEMO_FIFO_SIZE, GFP_KERNEL);
  200.         if (ret)
  201.         {
  202.             ret = -ENOMEM;
  203.             goto free_kfifo;
  204.         }
  205.  
  206.         printk("mydemo_fifo=%px\n", &device->mydemo_fifo);
  207.     }
  208.  
  209.     printk("succeeded register char device: %s\n", DEMO_NAME);
  210.  
  211.     return 0;
  212.  
  213. free_kfifo:
  214.     for (i = 0; i < MYDEMO_MAX_DEVICES; i++)
  215.     {
  216.         if (&device->mydemo_fifo)
  217.             kfifo_free(&device->mydemo_fifo);
  218.     }
  219. free_device:
  220.     for (i = 0; i < MYDEMO_MAX_DEVICES; i++)
  221.     {
  222.         if (mydemo_device[i])
  223.             kfree(mydemo_device[i]);
  224.     }
  225. cdev_fail:
  226.     cdev_del(demo_cdev);
  227. unregister_chrdev:
  228.     unregister_chrdev_region(dev, MYDEMO_MAX_DEVICES);
  229.     return ret;
  230. }
  231.  
  232. static void __exit simple_char_exit(void)
  233. {
  234.     int i;
  235.     printk("removing device\n");
  236.  
  237.     if (demo_cdev)
  238.         cdev_del(demo_cdev);
  239.  
  240.     unregister_chrdev_region(dev, MYDEMO_MAX_DEVICES);
  241.  
  242.     for (i = 0; i < MYDEMO_MAX_DEVICES; i++)
  243.     {
  244.         if (mydemo_device[i])
  245.             kfree(mydemo_device[i]);
  246.     }
  247. }
  248.  
  249. module_init(simple_char_init);
  250. module_exit(simple_char_exit);
  251.  
  252. MODULE_AUTHOR("rlk");
  253. MODULE_LICENSE("GPL v2");
  254. MODULE_DESCRIPTION("simple character device");

因为 poll 是监控多个文件描述符的,为了方便,我们让此驱动程序支持多设备。如代码清单 10 的第 36 行所示,我们定义了长度为 8 的设备信息数组,里面包含各自的 kfifo 和读写等待队列。

各个设备信息的初始化可以看设备初始化函数 simple_char_init,其中为 8 个设备分配设备号并初始化和添加注册。然后初始化各个设备信息,包括初始化 kfifo 和读写等待队列。

因为副设备号是从 0 开始的,所以在 open 的时候,可以直接用副设备号对设备信息进行索引。我们将索引到的设备信息指针保存到 private_data 中,以供后续的 read、write、poll 操作函数使用。

read 和 write 操作函数和之前的逻辑是一样的,使用 private_data 里指定的 kfifo 和读写等待队列。

不同的设备使用不同的 kfifo。这在设计上是容易理解的。

接下来就开始介绍重点了:我们需要实现 file_operations 中的 poll 接口,在 129 至 144 行。

  • void poll_wait(struct file* filp, wait_queue_head_t* wait_address, poll_table* p);

首先调用 poll_wait 函数,它将当前进程添加到等待队列中,然后将文件设备指针 filp 以及等待队列 wait_address 关联记录到 poll_table 中。

然后会根据 kfifo 的实际情况,设置设备状态掩码。

poll_wait 只是起到添加、关联的作用。不会引起阻塞。

最后需要说明很重要的点:驱动 poll 接口中不引起阻塞,那是在哪里进行阻塞的,才能达到性能控制?用户层 poll 函数最终会调用到内核中的 do_sys_poll 函数。在 do_sys_poll 中,它会根据文件设备指针调用各个设备驱动层的 poll 接口。

do_sys_poll 中会根据驱动层 poll 接口掩码返回值判断各个设备的读写状态,如果有设备满足需求,那最好,do_sys_poll 可以直接返回;如果各个设备都不满足,那就只能把当前进程进入睡眠状态。

因为之前我们已经在 poll_wait 中把当前进程加入到读写队列里了,睡眠的进程可以通过 wake_up_interruptible 被唤醒。唤醒的 do_sys_poll 会再次调用驱动层的 poll 函数进行检查,然后返回最新的设备状态。

还遗留一个问题,在驱动代码中即使设备可读写,也通过 poll_wait 把当前进程加入到等待队列中,会不会引起性能问题?其实不用担心,do_sys_poll 在返回时会移除 poll_table 中记录的进程项。

以上其实已经讲清了 poll 的基本原理。书上没讲这么详细。

驱动程序和测试程序都有了,现在我们开始测试功能。首先我们需要手动创建设备节点:

  • tim@tim:~$ cat /proc/devices
  • 238 mydemo_dev
  • tim@tim:~$ sudo mknod /dev/mydemo0 c 238 0
  • tim@tim:~$ sudo mknod /dev/mydemo1 c 238 1

接着后台运行测试程序。因为一开始两个设备都是不可读的,所以此时程序会进入阻塞状态。

我们使用 echo 命令先往 /dev/mydemo0 设备里写入数据,此时程序会被唤醒,poll 返回 /dev/mydemo0 可读,然后读取其中的内容进行打印;接着继续调用 poll,程序又进入阻塞状态;再往 /dev/mydemo1 设备里写入数据,也是如预期打印了写入的数据。

  • tim@tim:~$ sudo ./test &
  • tim@tim:~$ sudo su
  • root@tim:~$ echo "Hello0" > /dev/mydemo0
  • Hello0
  • root@tim:~$ echo "Hello1" > /dev/mydemo1
  • Hello1

实验:为什么不能唤醒读写进程

这个实验是上一个实验的延续,是作者故意制造的错误。

代码清单 11 是错误代码的一个片段,需要注意它和上一节实验的差异:上一节实验的等待队列是每个不同设备有一个,而此处是每个 open “会话”一个。

代码清单 11 错误代码片段
  1. static dev_t dev;
  2. static struct cdev *demo_cdev;
  3.  
  4. struct mydemo_device {
  5.     char name[64];
  6.     struct device *dev;
  7. };
  8.  
  9. struct mydemo_private_data {
  10.     struct mydemo_device *device;
  11.     char name[64];
  12.     struct kfifo mydemo_fifo;
  13.     wait_queue_head_t read_queue;
  14.     wait_queue_head_t write_queue;
  15. };
  16.  
  17. #define MYDEMO_MAX_DEVICES  8
  18. static struct mydemo_device *mydemo_device[MYDEMO_MAX_DEVICES];
  19.  
  20. static int demodrv_open(struct inode *inode, struct file *file)
  21. {
  22.     unsigned int minor = iminor(inode);
  23.     struct mydemo_private_data *data;
  24.     struct mydemo_device *device = mydemo_device[minor];
  25.     int ret;
  26.    
  27.  
  28.     printk("%s: major=%d, minor=%d, device=%s\n", __func__,
  29.             MAJOR(inode->i_rdev), MINOR(inode->i_rdev), device->name);
  30.  
  31.     data = kmalloc(sizeof(struct mydemo_private_data), GFP_KERNEL);
  32.     if (!data)
  33.         return -ENOMEM;
  34.  
  35.     sprintf(data->name, "private_data_%d", minor);
  36.  
  37.     ret = kfifo_alloc(&data->mydemo_fifo,
  38.             MYDEMO_FIFO_SIZE,
  39.             GFP_KERNEL);
  40.     if (ret) {
  41.         kfree(data);
  42.         return -ENOMEM;
  43.     }
  44.  
  45.     init_waitqueue_head(&data->read_queue);
  46.     init_waitqueue_head(&data->write_queue);
  47.  
  48.     data->device = device;
  49.  
  50.     file->private_data = data;
  51.  
  52.     return 0;
  53. }

上一节我们已经知道了 poll 的原理,poll 中关联维护的等待队列就是驱动中的等待队列。而上述错误代码中,一个 open “会话”就单独使用一个等待队列,如果在一个“会话”内,那是没有问题的。但是往往“生产者/消费者”对驱动的操作都是不同的进程,即使用上述驱动,open 后都对应自己的等待队列,那添加、唤醒的操作肯定是彼此影响不到。它们根本没有关联。

实验:向虚拟设备添加异步通知

除了阻塞之外,异步通知机制也是一种节约资源的手段,它允许应用程序在事件发生时接收通知。类似中断或者回调函数的概念。

一般在驱动中实现异步通知的步骤如下:

1. 初始化 fasync 结构:驱动中需要包含一个指向 fasync_struct 结构的指针。这个结构用于跟踪注册了异步通知的进程。其定义如下:

  • struct fasync_struct {
  •     rwlock_t    fa_lock;
  •     int         magic;
  •     int         fa_fd;
  •     struct fasync_struct* fa_next; /* singly linked list */
  •     struct file* fa_file;
  •     struct rcu_head      fa_rcu;
  • };

根据定义我们可以简单的把 fasync_struct 看成是带锁的、带有通知信息的链表。

2. 实现驱动文件操作函数中的 .fasync 接口:应用程序会使用 fcntl 注册异步通知,最终会调用到 .fasync 接口。我们需要在 .fasync 接口中更新维护 fasync_struct 链表,可使用现有的 fasync_helper 函数来进行维护。

我们先看 .fasync 接口的定义:

  • int my_fasync(int fd, struct file* filp, int on);

其中,fd 参数就是用户态的文件描述符,用作信号标识;filp 参数和其他文件操作函数中的一样,标识内核驱动的文件实例;on 参数表示是添加还是删除异步通知。

fasync 接口相比于 read、write 函数有一个 fd 参数。这边可以这么理解:

filp 是驱动设备的文件抽象,所以各个接口都需要。但是异步通知信号是按进程通知的,所以需要额外区分打开设备的进程,这边用用户态的 fd 进行表示。

再看到 fasync_helper 函数:

  • int fasync_helper(int fd, struct file* filp, int on, struct fasync_struct** fapp);

其中,fd、filp、on 的含义和 .fasync 接口中定义的是一致的。特别关注 fapp 参数,它是一个二级指针,可以知道链表的维护都是在 fasync_helper 内部进行。在内部维护的意思是说,链表节点空间的分配都是在函数内部,外部只需要记录一个链表头就可以了。

fasync_helper 函数的主要作用也是很容易“猜测”的:将 fd 和 filp 参数作为链表的关键字进行索引,再根据 on 参数来觉得是添加节点还是删除节点。

3. 向用户空间发送通知:当驱动满足条件时,可以通过 kill_fasync 函数来发送信号,通知到用户。

注意仅是发送信号。用户接收到信号,调用对应的信号处理函数是另一套机制。

kill_fasync 函数的原型为:

  • void kill_fasync(struct fasync_struct** fa, int sig, int band);

其中,fa 参数就是上文中维护的 fasync_struct 结构指针;sig 参数指定要发送的信号,通常是 SIGIO 信号;band 参数指定事件的类型,一般为 POLL_IN(数据可读)或 POLL_OUT(数据可写)。

kill_fasync 函数中会遍历链表,为每个进程发送通知信号。

这边的 'kill' 应该是做发送信号含义。可能是因为我们熟知杀死进程会发送终止信号。

驱动中实现异步同步的步骤已经介绍完毕。如代码清单 12 所示,我们结合实验代码再整体梳理一遍。

代码清单 12 simple fasync kfifo device
  1. #include <linux/module.h>
  2. #include <linux/fs.h>
  3. #include <linux/uaccess.h>
  4. #include <linux/init.h>
  5. #include <linux/miscdevice.h>
  6. #include <linux/device.h>
  7. #include <linux/slab.h>
  8. #include <linux/kfifo.h>
  9. #include <linux/wait.h>
  10. #include <linux/sched.h>
  11. #include <linux/cdev.h>
  12. #include <linux/poll.h>
  13.  
  14. #define DEMO_NAME "mydemo_dev"
  15. #define MYDEMO_FIFO_SIZE 64
  16.  
  17. static dev_t dev;
  18. static struct cdev* demo_cdev;
  19.  
  20. struct mydemo_device
  21. {
  22.     char name[64];
  23.     struct device* dev;
  24.     wait_queue_head_t read_queue;
  25.     wait_queue_head_t write_queue;
  26.     struct kfifo mydemo_fifo;
  27.     struct fasync_struct* fasync;
  28. };
  29.  
  30. struct mydemo_private_data
  31. {
  32.     struct mydemo_device* device;
  33.     char name[64];
  34. };
  35.  
  36. #define MYDEMO_MAX_DEVICES 8
  37. static struct mydemo_device* mydemo_device[MYDEMO_MAX_DEVICES];
  38.  
  39. static int demodrv_open(struct inode* inode, struct file* file)
  40. {
  41.     unsigned int minor = iminor(inode);
  42.     struct mydemo_private_data* data;
  43.     struct mydemo_device* device = mydemo_device[minor];
  44.  
  45.     printk("%s: major=%d. minor=%d, device=%s\n",
  46.         __func__, MAJOR(inode->i_rdev), MINOR(inode->i_rdev), device->name);
  47.  
  48.     data = kmalloc(sizeof(struct mydemo_private_data), GFP_KERNEL);
  49.     if (!data)
  50.         return -ENOMEM;
  51.  
  52.     sprintf(data->name, "private_data_%d", minor);
  53.  
  54.     data->device = device;
  55.     file->private_data = data;
  56.  
  57.     return 0;
  58. }
  59.  
  60. static int demodrv_release(struct inode* inode, struct file* file)
  61. {
  62.     struct mydemo_priavte_data* data = file->private_data;
  63.     kfree(data);
  64.     return 0;
  65. }
  66.  
  67. static ssize_t demodrv_read(struct file* file, char* __user buf, size_t count, loff_t* ppos)
  68. {
  69.     struct mydemo_private_data* data = file->private_data;
  70.     struct mydemo_device* device = data->device;
  71.     int actual_readed;
  72.     int ret;
  73.  
  74.     if (kfifo_is_empty(&device->mydemo_fifo))
  75.     {
  76.         if (file->f_flags & O_NONBLOCK)
  77.             return -EAGAIN;
  78.  
  79.         printk("%s:%s pid=%d, going to sleep, %s\n",
  80.             __func__, device->name, current->pid, data->name);
  81.         ret = wait_event_interruptible(device->read_queue, !kfifo_is_empty(&device->mydemo_fifo));
  82.         if (ret)
  83.             return ret;
  84.     }
  85.  
  86.     ret = kfifo_to_user(&device->mydemo_fifo, buf, count, &actual_readed);
  87.     if (ret)
  88.         return -EIO;
  89.  
  90.     if (!kfifo_is_full(&device->mydemo_fifo))
  91.     {
  92.         wake_up_interruptible(&device->write_queue);
  93.         kill_fasync(&device->fasync, SIGIO, POLL_OUT);
  94.     }
  95.  
  96.     printk("%s:%s, pid=%d, actual_readed=%d, pos=%lld\n",
  97.         __func__, device->name, current->pid, actual_readed, *ppos);
  98.     return actual_readed;
  99. }
  100.  
  101. static ssize_t demodrv_write(struct file* file, const char* __user buf, size_t count, loff_t* ppos)
  102. {
  103.     struct mydemo_private_data* data = file->private_data;
  104.     struct mydemo_device* device = data->device;
  105.     unsigned int actual_write;
  106.     int ret;
  107.  
  108.     if (kfifo_is_full(&device->mydemo_fifo))
  109.     {
  110.         if (file->f_flags & O_NONBLOCK)
  111.             return -EAGAIN;
  112.  
  113.         printk("%s:%s pid=%d, going to sleep, %s\n",
  114.             __func__, device->name, current->pid, data->name);
  115.         ret = wait_event_interruptible(device->write_queue, !kfifo_is_full(&device->mydemo_fifo));
  116.         if (ret)
  117.             return ret;
  118.     }
  119.  
  120.     ret = kfifo_from_user(&device->mydemo_fifo, buf, count, &actual_write);
  121.     if (ret)
  122.         return -EIO;
  123.  
  124.     if (!kfifo_is_empty(&device->mydemo_fifo))
  125.     {
  126.         wake_up_interruptible(&device->read_queue);
  127.         kill_fasync(&device->fasync, SIGIO, POLL_IN);
  128.         printk("%s kill fasync\n", __func__);
  129.     }
  130.  
  131.     printk("%s:%s pid=%d, actual_write=%d, ppos=%lld, ret=%d\n",
  132.         __func__, device->name, current->pid, actual_write, *ppos, ret);
  133.  
  134.     return actual_write;
  135. }
  136.  
  137. static unsigned int demodrv_poll(struct file* file, poll_table* wait)
  138. {
  139.     int mask = 0;
  140.     struct mydemo_private_data* data = file->private_data;
  141.     struct mydemo_device* device = data->device;
  142.  
  143.     poll_wait(file, &device->read_queue, wait);
  144.     poll_wait(file, &device->write_queue, wait);
  145.  
  146.     if (!kfifo_is_empty(&device->mydemo_fifo))
  147.         mask |= POLLIN | POLLRDNORM;
  148.     if (!kfifo_is_full(&device->mydemo_fifo))
  149.         mask |= POLLOUT | POLLWRNORM;
  150.  
  151.     return mask;
  152. }
  153.  
  154. static int demodrv_fasync(int fd, struct file* file, int on)
  155. {
  156.     struct mydemo_private_data* data = file->private_data;
  157.     struct mydemo_device* device = data->device;
  158.  
  159.     printk("%s send SIGIO\n", __func__);
  160.     return fasync_helper(fd, file, on, &device->fasync);
  161. }
  162.  
  163. static const struct file_operations demodrv_fops =
  164. {
  165.     .owner = THIS_MODULE,
  166.     .open = demodrv_open,
  167.     .release = demodrv_release,
  168.     .read = demodrv_read,
  169.     .write = demodrv_write,
  170.     .poll = demodrv_poll,
  171.     .fasync = demodrv_fasync,
  172. };
  173.  
  174. static int __init simple_char_init(void)
  175. {
  176.     int ret;
  177.     int i;
  178.     struct mydemo_device* device;
  179.  
  180.     ret = alloc_chrdev_region(&dev, 0, MYDEMO_MAX_DEVICES, DEMO_NAME);
  181.     if (ret)
  182.     {
  183.         printk("failed to allocate char device region\n");
  184.         return ret;
  185.     }
  186.  
  187.     demo_cdev = cdev_alloc();
  188.     if (!demo_cdev)
  189.     {
  190.         printk("cdev_alloc failed\n");
  191.         goto unregister_chrdev;
  192.     }
  193.  
  194.     cdev_init(demo_cdev, &demodrv_fops);
  195.  
  196.     ret = cdev_add(demo_cdev, dev, MYDEMO_MAX_DEVICES);
  197.     if (ret)
  198.     {
  199.         printk("cdev_add failed\n");
  200.         goto cdev_fail;
  201.     }
  202.  
  203.     for (i = 0; i < MYDEMO_MAX_DEVICES; i++)
  204.     {
  205.         device = kmalloc(sizeof(struct mydemo_device), GFP_KERNEL);
  206.         if (!device)
  207.         {
  208.             ret = -ENOMEM;
  209.             goto free_device;
  210.         }
  211.  
  212.         device->fasync = NULL;
  213.         sprintf(device->name, "%s%d", DEMO_NAME, i);
  214.         mydemo_device[i] = device;
  215.         init_waitqueue_head(&device->read_queue);
  216.         init_waitqueue_head(&device->write_queue);
  217.  
  218.         ret = kfifo_alloc(&device->mydemo_fifo, MYDEMO_FIFO_SIZE, GFP_KERNEL);
  219.         if (ret)
  220.         {
  221.             ret = -ENOMEM;
  222.             goto free_kfifo;
  223.         }
  224.  
  225.         printk("mydemo_fifo=%px\n", &device->mydemo_fifo);
  226.     }
  227.  
  228.     printk("succeeded register char device: %s\n", DEMO_NAME);
  229.  
  230.     return 0;
  231.  
  232. free_kfifo:
  233.     for (i = 0; i < MYDEMO_MAX_DEVICES; i++)
  234.     {
  235.         if (&device->mydemo_fifo)
  236.             kfifo_free(&device->mydemo_fifo);
  237.     }
  238. free_device:
  239.     for (i = 0; i < MYDEMO_MAX_DEVICES; i++)
  240.     {
  241.         if (mydemo_device[i])
  242.             kfree(mydemo_device[i]);
  243.     }
  244. cdev_fail:
  245.     cdev_del(demo_cdev);
  246. unregister_chrdev:
  247.     unregister_chrdev_region(dev, MYDEMO_MAX_DEVICES);
  248.     return ret;
  249. }
  250.  
  251. static void __exit simple_char_exit(void)
  252. {
  253.     int i;
  254.     printk("removing device\n");
  255.  
  256.     if (demo_cdev)
  257.         cdev_del(demo_cdev);
  258.  
  259.     unregister_chrdev_region(dev, MYDEMO_MAX_DEVICES);
  260.  
  261.     for (i = 0; i < MYDEMO_MAX_DEVICES; i++)
  262.     {
  263.         if (mydemo_device[i])
  264.             kfree(mydemo_device[i]);
  265.     }
  266. }
  267.  
  268. module_init(simple_char_init);
  269. module_exit(simple_char_exit);
  270.  
  271. MODULE_AUTHOR("rlk");
  272. MODULE_LICENSE("GPL v2");
  273. MODULE_DESCRIPTION("simple character device");

如代码第 27 行所示,我们在设备信息结构体中添加 fasync_struct 指针。并在驱动加载时(simple_char_init)将 fasync_struct 指针设置为空,即头节点为空。实现的 .fasync 接口为 demodrv_fasync 函数,可以看到其中调用了 fasync_helper 函数对异步通知链表进行维护。在原本的读写接口中(demodrv_read 和 demodrv_write)添加信号发送功能。以写接口为例,当 kfifo 中写入了数据,则调用 kill_fasync 发送设备可读信号。

我们再看到实现的测试程序。

代码清单 13 测试程序
  1. #define _GNU_SOURCE
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <sys/ioctl.h>
  10. #include <fcntl.h>
  11. #include <errno.h>
  12. #include <poll.h>
  13. #include <signal.h>
  14.  
  15. static int fd;
  16.  
  17. void my_signal_fun(int signum, siginfo_t* siginfo, void* act)
  18. {
  19.     int ret;
  20.     char buf[64];
  21.  
  22.     if (signum == SIGIO)
  23.     {
  24.         if (siginfo->si_band & POLLIN)
  25.         {
  26.             printf("FIFO is not empty\n");
  27.             if ((ret = read(fd, buf, sizeof(buf))) != -1)
  28.             {
  29.                 buf[ret] = '\0';
  30.                 puts(buf);
  31.             }
  32.         }
  33.         if (siginfo->si_band & POLLOUT)
  34.             printf("FIFO is not full\n");
  35.     }
  36. }
  37.  
  38. int main()
  39. {
  40.     int ret;
  41.     int flag;
  42.     struct sigaction act, oldact;
  43.  
  44.     sigemptyset(&act.sa_mask);
  45.     sigaddset(&act.sa_mask, SIGIO);
  46.     act.sa_flags = SA_SIGINFO;
  47.     act.sa_sigaction = my_signal_fun;
  48.     if (sigaction(SIGIO, &act, &oldact) == -1)
  49.         goto fail;
  50.  
  51.     fd = open("/dev/mydemo0", O_RDWR);
  52.     if (fd < 0)
  53.         goto fail;
  54.  
  55.     /* 设置异步I/O信号的所有者为当前进程 */
  56.     if (fcntl(fd, F_SETOWN, getpid()) == -1)
  57.         goto fail;
  58.  
  59.     /* 设置文件描述符异步I/O通知时要发送的信号类型 */
  60.     if (fcntl(fd, F_SETSIG, SIGIO) == -1)
  61.         goto fail;
  62.  
  63.     /* 获取文件 flags */
  64.     if ((flag = fcntl(fd, F_GETFL)) == -1)
  65.         goto fail;
  66.  
  67.     /* 设置文件 flags,设置 FASYNC,支持异步通知 */
  68.     if (fcntl(fd, F_SETFL, flag | FASYNC) == -1)
  69.         goto fail;
  70.  
  71.     while (1)
  72.         sleep(1);
  73.  
  74. fail:
  75.     perror("fasync test");
  76.     exit(EXIT_FAILURE);
  77. }

如代码清单 13 所示,首先会调用 sigaction 函数来为特定信号绑定处理函数。其函数原型为:

  • int sigaction(int signum, const struct sigaction* act, struct sigaction* oldact);

其中,signum 参数指定要设置的信息;act 参数是一个 sigaction 指针,该结构体描述如何处理信号;可利用 oldact 参数存储原本的处理设置信息。

sigaction 结构体的定义如下:

  • struct sigaction
  • {
  •     void     (*sa_handler)(int);
  •     void     (*sa_sigaction)(int, siginfo_t*, void*);
  •     sigset_t   sa_mask;
  •     int        sa_flags;
  •     void     (*sa_restorer)(void);
  • };

其中,sa_handler 和 sa_sigaction 都是信号处理函数,从定义可以看到 sa_sigaction 接收的函数参数更多,可以实现更复杂的处理逻辑。

sa_flags 参数用于控制信号处理的各种选项。比如 SA_SIGINFO,指示信号处理函数使用 sa_sigaction 字段,而不使用 sa_handler。

sa_mask 参数用于指定一个信号集,表示在处理当前信号的过程中需要阻塞的其他信号。

当前的信号处理可能会被新来的信号打断。或者当前信号可能会和其他信号同时处理。为了确保信号处理的同步,可以使用 sa_mask 来阻塞其他信号。

紧接着程序会调用 fcntl 函数进行各种操作,我们逐一来看。

F_SETOWN:设置异步 I/O 通知的所有者。可以看到这边将 fd 和进程进行了关联。

F_SETOWN 应该是要显示指定一下,因为信号的接收者可能是一个单独的进程,也可能是一个进程组。

F_SETSIG:用于设置文件描述符异步 I/O 通知时要发送的信号类型。

理论上来说,驱动代码需要显式支持和尊重 F_SETSIG 设置。但是我们目前的驱动程序没有对此进行处理,可以使用 ioctl 接口进行设置。

F_GETFL 和 F_SETFL:用于获取和设置文件状态标志。

会根据 F_SETFL 的值调用 .fasync 接口。

不要忘记添加 _GNU_SOURCE 宏启用 GNU 扩展。以上命令参数不全是 POSIX 标准参数。

最后,我们来进行测试。我们首先将测试程序置于后台运行,此时程序没有接收到 SIGIO 信号,一直在循环睡眠中。再使用 echo 命令往设备写数据,会触发驱动发送 SIGIO 信号。从而触发测试程序调用信号处理函数,读取设备内容。

  • tim@tim:~$ sudo su
  • tim@tim:~$ ./test &
  • root@tim:~$ echo "Hello World" > /dev/mydemo0
  • FIFO is not empty
  • Hello World
  •  
  • FIFO is not full

实验:解决驱动的宕机难题

注意代码清单 12 中第 212 行代码(device->fasync = NULL),它对异步通知链表指针赋零。上一节我们已经介绍过,这个指针是充当头指针作用的,如果没对它赋零初始化,会引起异常地址访问的问题。

原书中特意暴露了这个问题,没有对头指针进行初始化。一运行测试程序直接系统卡死,错误日志塞满了原本空间就不多的硬盘😮。

我一开始还没注意到是程序的问题,还以为是虚拟机的问题。

这是第一次感受到驱动开发需要特别严谨,一出错误都是“致命”的。

书中介绍了在 qemu 环境下的错误排查。我们故意引入错误,然后在 qemu 环境下运行测试程序,可以看到控制台打印了错误现场:

  • [  618.588872] Unable to handle kernel paging request at virtual address 00000000886c3734
  • [  618.609669] Mem abort info:
  • [  618.610209]   ESR = 0x96000004
  • [  618.610851]   Exception class = DABT (current EL), IL = 32 bits
  • [  618.611503]   SET = 0, FnV = 0
  • [  618.611921]   EA = 0, S1PTW = 0
  • [  618.617500] Data abort info:
  • [  618.617670]   ISV = 0, ISS = 0x00000004
  • [  618.618433]   CM = 0, WnR = 0
  • [  618.619630] user pgtable: 4k pages, 48-bit VAs, pgdp = 000000003cdaeb78
  • [  618.620233] [00000000886c3734] pgd=0000000000000000
  • [  618.621310] Internal error: Oops: 96000004 [#1] SMP
  • [  618.622046] Modules linked in: mydemo(OE) binfmt_misc(E)
  • [  618.623390] CPU: 2 PID: 6293 Comm: test Kdump: loaded Tainted: G           OE     5.0.0+ #3
  • [  618.624249] Hardware name: linux,dummy-virt (DT)
  • [  618.627801] pstate: 20400005 (nzCv daif +PAN -UAO)
  • [  618.639836] pc : fasync_insert_entry+0x508/0x908
  • [  618.640489] lr :           (null)
  • [  618.640721] sp : ffff80002314f540
  • [  618.641071] x29: ffff80002314f540 x28: ffff800023113800
  • [  618.643366] x27: 0000000000000000 x26: 0000000000000000
  • [  618.643856] x25: 0000000056000000 x24: 0000000000000015
  • [  618.644246] x23: 0000000080001000 x22: 0000ffffa1c7ed04
  • [  618.644910] x21: 0000000000000000 x20: ffff8000298a9c00
  • [  618.647638] x19: 0000000000000000 x18: 0000000000000000
  • [  618.647911] x17: 0000000000000000 x16: 0000000000000000
  • [  618.648149] x15: 0000000000000000 x14: 0000000000000000
  • [  618.648334] x13: 0000000000000000 x12: 0000000000000000
  • [  618.648519] x11: 0000000000000000 x10: 0000000000000000
  • [  618.648735] x9 : ffff000010825900 x8 : ffff80002fdc6d40
  • [  618.648972] x7 : ffff80002fdc6d40 x6 : 0000000000000032
  • [  618.649257] x5 : ffff8000288d2300 x4 : ffff0000121e8530
  • [  618.649748] x3 : ffff0000121e8530 x2 : 0000000000000001
  • [  618.650029] x1 : 0000000000000000 x0 : 00000000886c371c
  • [  618.650330] Process test (pid: 6293, stack limit = 0x0000000012179b77)
  • [  618.650804] Call trace:
  • [  618.651138]  fasync_insert_entry+0x508/0x908
  • [  618.653995]  fasync_add_entry+0x4c/0x70
  • [  618.654380]  fasync_helper+0x4c/0x54
  • [  618.655582]  demodrv_fasync+0x64/0x6c [mydemo]
  • [  618.656047]  setfl+0x1d8/0x50c
  • [  618.656333]  do_fcntl+0x2e8/0xb48
  • [  618.656650]  __se_sys_fcntl+0x110/0x16c
  • [  618.656987]  __arm64_sys_fcntl+0x40/0x48
  • [  618.657348]  __invoke_syscall+0x24/0x2c
  • [  618.657491]  invoke_syscall+0xa4/0xd8
  • [  618.657625]  el0_svc_common+0x100/0x1e4
  • [  618.657764]  el0_svc_handler+0x414/0x440
  • [  618.658037]  el0_svc+0x8/0xc
  • [  618.665971] Code: f9400fe0 f9004fe0 140000ac f94053e0 (f9400c00)

错误日志里提供了很丰富的信息:

'Unable to handle kernel paging request at virtual address 00000000886c3734':访问此地址发生错误。

'Mem abort info' 和 'Data abort info':提供了内存异常的详细信息。

'Modules linked in: mydemo(OE) binfmt_misc(E)':奔溃发生在我们加载的 mydemo 模块。

'CPU: 2 PID: 6293 Comm: test':显示奔溃发生在 CPU2 上,进程 ID 是 6293,进程名是 test。

'pc : fasync_insert_entry+0x508/0x908':发生奔溃时的 pc 指针值。同时还有各个奔溃现场的寄存器值。

'Call trace':奔溃时的函数调用堆栈。比如 fasync_insert_entry+0x508/0x908,其中,fasync_insert_entry 是函数名,0x508 是此函数地址偏移值,0x908 表示此函数的大小(单位:字节)。

虽然我们已经知道错误是怎么引起的,但是还是假装不知道,结合堆栈排查一下。

  • tim@tim:~$ gdb-multiarch vmlinux
  • (gdb) list *(fasync_insert_entry+0x508)

我们使用 gdb 调试 vmlinux 文件,并使用 list 命令定位源码行数。

图1 list 结果
图2 具体源码

比如 fasync_insert_entry+0x508,定位的结果如图 1 所示:fa 变量解引用发生异常了,即 fa 地址内容有问题。我们再看看这个地址内容是从哪里来的,打开 fs/fcntl.c 源码,可以看到 fa 是从函数参数 fapp 中来的。

结合后续堆栈信息,同样的操作,我们看 fapp 参数是从哪里来的。最后追踪下来会发现 fapp 参数就是 fasync_helper 传进去的链表地址。我们需要把它初始化成空,非空就表示有结点,就引发了问题。

书中没显式初始化。而是直接使用了 kzalloc 来分配内存,它会将分配的内存清零。

书中没讲解实机环境下的 crash 信息查看。此问题先做标记。