话说linux driver 机制博大精深,但归根到底主要由:设备(device),驱动(driver),总线(bus)组成,它们三者相互关联,互相寻找,互相映射。
1,device 、driver、bus 之间的关系
何为设备?linux主要由字符设备,块设备,网络设备等组成。如何驱动这些设备,那就需要相应的driver来控制设备或者硬件。那设备如何去寻找驱动呢?在这里我先给你透露一下,这种牵线搭桥的工作,主要交给了bus。就拿usb 来说吧,一个usb host controller 就对应一条bus;
上图大致描述三者之间相互依赖的关系,如要理清需从设备查找驱动的流程入下:
首先,当一个设备接入到系统中,系统会将注册相应的设备节点,并告知bus(bus_type);
然后,通过bus_type 中的match函数,来查找driver,并进行匹配的动作。
最后,bus正确查找到设备驱动。进而调用驱动的probe函数,来进行初始化工作。
注意!
驱动模块在内核中有两种模式,一种为编译到内核中,另一种为编译成ko。后者需将模块的ko加载到linux kernel 。
总之,device,driver,bus 这三架战车,统统有bus 来进行来管理。它主要提供设备匹配驱动,管理设备,管理驱动的功能。
2,重要的数据结构
2.1 bus_type
<p>/**
* struct bus_type - The bus type of the device
*
* @name: The name of the bus.
* @dev_name: Used for subsystems to enumerate devices like ("foo%u", dev->id).
* @dev_root: Default device to use as the parent.
* @bus_attrs: Default attributes of the bus.
* @dev_attrs: Default attributes of the devices on the bus.
* @drv_attrs: Default attributes of the device drivers on the bus.
* @match: Called, perhaps multiple times, whenever a new device or driver
* is added for this bus. It should return a nonzero value if the
* given device can be handled by the given driver.
* @uevent: Called when a device is added, removed, or a few other things
* that generate uevents to add the environment variables.
* @probe: Called when a new device or driver add to this bus, and callback
* the specific driver's probe to initial the matched device.
* @remove: Called when a device removed from this bus.
* @shutdown: Called at shut-down time to quiesce the device.
* @suspend: Called when a device on this bus wants to go to sleep mode.
* @res