1. 前言
device和device driver是Linux驱动开发的基本概念。Linux kernel的思路很简单:驱动开发,就是要开发指定的软件(driver)以驱动指定的设备,所以kernel就为设备和驱动它的driver定义了两个数据结构,分别是device和device_driver。因此本文将会围绕这两个数据结构,介绍Linux设备模型的核心逻辑,包括:
设备及设备驱动在kernel中的抽象、使用和维护;
设备及设备驱动的注册、加载、初始化原理;
设备模型在实际驱动开发过程中的使用方法。
注:在介绍device和device_driver的过程中,会遇到很多额外的知识点,如Class、Bus、DMA、电源管理等等,这些知识点都很复杂,任何一个都可以作为一个单独的专题区阐述,因此本文不会深入解析它们,而会在后续的文章中专门描述。
2. struct device和struct device_driver
在阅读Linux内核源代码时,通过核心数据结构,即可理解某个模块60%以上的逻辑,设备模型部分尤为明显。
在include/linux/device.h中,Linux内核定义了设备模型中最重要的两个数据结构,struct device和struct device_driver。
- struct device
1: /* include/linux/device.h, line 660 */
2: struct device {
3: struct device *parent;
4:
5: struct device_private *p;
6:
7: struct kobject kobj;
8: const char *init_name; /* initial name of the device */
9: const struct device_type *type;
10:
11: struct mutex mutex; /* mutex to synchronize calls to
12: * its driver.
13: */
14:
15: struct bus_type *bus; /* type of bus device is on */
16: struct device_driver *driver; /* which driver has allocated this
17: device */
18: void *platform_data; /* Platform specific data, device
19: core doesn't touch it */
20: struct dev_pm_info power;
21: struct dev_pm_domain *pm_domain;
22:
23: #ifdef CONFIG_PINCTRL
24: struct dev_pin_info *pins;
25: #endif
26:
27: #ifdef CONFIG_NUMA
28: int numa_node; /* NUMA node this device is close to */
29: #endif
30: u64 *dma_mask; /* dma mask (if dma'able device) */
31: u64 coherent_dma_mask;/* Like dma_mask, but for
32: alloc_coherent mappings as
33: not all hardware supports
34: 64 bit addresses for consistent
35: allocations such descriptors. */
36:
37: struct device_dma_parameters *dma_parms;
38:
39: struct list_head dma_pools; /* dma pools (if dma'ble) */