设备模型
覆盖: kobject/kset → device/driver/bus/class → sysfs 绑定 → probe 生命周期 → udev → device tree (DT) → ACPI → platform device
内核版本: 2.6 ~ 6.x
概述
Linux 设备模型是一套内核内部框架,为所有设备、驱动、总线提供统一的表示和生命周期管理。它的核心价值不在于"设备怎么工作",而在于"设备和驱动怎么找到对方"——即设备-驱动匹配 (device-driver binding)。
kobject: 基础构建块
struct kobject {
const char *name; struct kobject *parent; struct kset *kset; struct kernfs_node *sd; struct kref kref; unsigned int state_initialized:1;
};
kset: kobject 集合
struct kset {
struct list_head list; struct kobject kobj; const struct kobj_type *ktype; };
Device / Driver / Bus
struct device
struct device {
struct kobject kobj; struct device *parent; const char *init_name;
struct bus_type *bus; struct device_driver *driver; void *driver_data; struct device_node *of_node; u64 *dma_mask; const struct attribute_group **groups; void (*release)(struct device *dev); };
struct device_driver
struct device_driver {
const char *name;
struct bus_type *bus;
int (*probe)(struct device *dev); void (*remove)(struct device *dev); void (*shutdown)(struct device *dev);
const struct of_device_id *of_match_table; const struct acpi_device_id *acpi_match_table;
const struct attribute_group **groups;
};
struct bus_type
struct bus_type {
const char *name; int (*match)(struct device *dev, struct device_driver *drv);
int (*probe)(struct device *dev); struct subsys_private *p; };
绑定流程
device_register(dev)
→ device_add(dev)
→ bus_add_device(dev) → bus_probe_device(dev)
→ device_initial_probe(dev)
→ __device_attach(dev, true)
→ bus_for_each_drv(dev->bus, ...) → driver_match_device(drv, dev) → device_driver_attach(drv, dev)
→ driver_probe_device(drv, dev)
→ really_probe(dev, drv)
→ call_driver_probe(dev, drv) → drv->probe(dev)
关键: 绑定是双向的——新设备到来时遍历驱动,新驱动注册时也遍历设备。无论谁先注册,匹配都会发生。
sysfs 与属性
struct device_attribute {
struct attribute attr;
ssize_t (*show)(struct device *dev, struct device_attribute *attr, char *buf);
ssize_t (*store)(struct device *dev, struct device_attribute *attr, const char *buf, size_t count);
};
Device Tree vs ACPI
udev
参考
- 源码:
drivers/base/core.c, drivers/base/bus.c, drivers/base/dd.c, include/linux/device.h
- 内核文档:
Documentation/driver-api/driver-model/
关键词: kobject, device, driver, bus, probe, sysfs, device tree, ACPI, udev, modalias