1. Why Do We Need a Device Model?
Linux kernel needs a common way to identify and manage the huge variety of hardware devices. This is the device model:
- It is the infrastructure in the Linux kernel used to uniformly manage various devices, buses, and driver relationships.
The device model forms a clear organizational system between devices, drivers, and buses, and presents them uniformly under kernel and sysfs.
You can think of it as the "management standard" inside the kernel.
Note
- The "driver frameworks" you learned before, such as character device drivers, block device drivers, etc., are the interface specifications and implementation procedures to follow when writing drivers. They all need to be registered and mounted to the kernel based on the device model in the end.
The device model is the kernel's unified object management architecture, while the driver framework is the specification for writing specific type driver code.
2. Core Objects of the Device Model
In the Linux kernel, there are three core concepts:
- bus: A bus. For example USB, PCI, I2C, SPI, etc., responsible for connecting the CPU and external devices, and connecting many devices under it.
- device: A device. Represents a specific hardware (such as /dev/sda, /dev/input/mice, etc.).
- driver: A driver. Responsible for controlling a certain type of device, allowing the hardware to be recognized and work by the kernel.
Relationship between the three:
- A bus can have many devices, and a device must belong to a bus;
- Each device is driven by one driver, and the driver is responsible for operating and managing the device;
- Drivers need to match with devices (through name, ID, and other information).
3. Reflection in Code
- Each bus/device/driver has a structure in the kernel, for example:
struct bus_typestruct devicestruct device_driver
- These structures and methods are defined in the
/include/linux/device.hheader file. - After registering bus, device, and driver, the kernel automatically binds the driver to the device according to rules (if they match).
4. Relationship with User Space
Linux uses the device model to generate sysfs nodes for each device/driver, presenting them in directories such as /sys/bus/, /sys/devices/, /sys/class/, etc., facilitating content visualization and debugging.