《Linux 內核修煉之道》讀書筆記。設備模型是理解 Linux 驅動的骨架,而這副骨架由三個資料結構撐起。
總線(bus)、設備(device)、驅動(device_driver)構成設備模型的「上層建築」,三者之間的連接關係正是設備模型要表達的內容。
所有設備都掛在某條總線上。總線可以是實體的(如 PCI、USB),也可以是虛擬的,例如內部使用的 platform 總線。
設備是掛在實體或虛擬總線上的物件,同樣可能是真實硬體,也可能是純軟體的虛擬物件。
驅動則是與設備通訊的程式:它從設備取得資料,也把資料下發給設備處理。
struct bus_type {
const char *name; // 總線類型名稱
struct bus_attribute *bus_attrs;
struct device_attribute *dev_attrs;
struct driver_attribute *drv_attrs;
int (*match)(struct device *dev, struct device_driver *drv);
int (*uevent)(struct device *dev, struct kobj_uevent_env *env);
int (*probe)(struct device *dev);
int (*remove)(struct device *dev);
void (*shutdown)(struct device *dev);
int (*suspend)(struct device *dev, pm_message_t state);
int (*suspend_late)(struct device *dev, pm_message_t state);
int (*resume_early)(struct device *dev);
int (*resume)(struct device *dev);
struct pm_ext_ops *pm;
struct bus_type_private *p;
};
其中 match 決定設備與驅動能否配對,而每條總線的配對方式並不相同:PCI 看 Vendor/Device ID,platform 總線則看 name 字串比對。probe 在配對成功後被呼叫,是驅動真正動手初始化硬體的地方。
比對現行源碼會發現,結構與早期書籍所述略有出入,多包了一層 struct bus_type_private *p:
struct bus_type_private {
struct kset subsys; // 該總線的子系統,連到全域 kset bus_subsys
struct kset *drivers_kset; // 該總線上所有驅動的集合
struct kset *devices_kset; // 該總線上所有設備的集合
struct klist klist_devices; // 以 klist 串起設備鏈表
struct klist klist_drivers; // 驅動鏈表
struct blocking_notifier_head bus_notifier;
unsigned int drivers_autoprobe:1;
struct bus_type *bus; // 指回所屬的 bus_type
};
這層封裝的用意在於:真正作為 kobject 存在的是 bus_type_private,如此一來 bus_type 本身就能安全地靜態配置,而不必在初始化時動態配置 kobject。註解也明白交代——除錯核心以外不該去碰這些欄位。
kset bus_subsys 對應 /sys/bus 目錄,每個 bus_type 物件對應其下一個子目錄,例如 PCI 對應 /sys/bus/pci。而在每個這樣的目錄底下,都存在 devices 與 drivers 兩個子目錄,分別列出掛在這條總線上的設備與驅動。想快速確認某個裝置綁到了哪個驅動,往這兩個目錄裡一看便知,這也是除錯時最實用的一招。