給核心裝置驅動增加sysfs除錯檔案

滕瑞發表於2017-06-13

我遇到的這個問題來自於Linux核心的一個培訓專案,具體可以搜尋Eudyptula關鍵字。目的是培養更多的核心開發者,不過這個專案現在已經截止報名。

首先需要了解的是sysfs,procfs和debugfs都是核心提供的偽檔案系統,實現核心/驅動和使用者空間的通訊。

對於sysfs來說,增加一個檔案的方法如下:

第一步:分別實現讀和寫的方法,命名規範是"檔名_show"和"檔名_store"。

static ssize_t <filename>_show(struct device *dev, struct device_attribute *attr, char *buf)

static ssize_t <filename>_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)

第二步:用巨集構造相關結構體。(整體替換<filename>為需要增加的檔名)

static DEVICE_ATTR_RW(<filename>);

這個巨集的作用就是字串的拼接,所以第一步裡面的函式名要符合規範才行。

#define DEVICE_ATTR_RW(_name) \  
struct device_attribute dev_attr_##_name = __ATTR_RW(_name)  

#define __ATTR_RW(_name) __ATTR(_name, (S_IWUSR | S_IRUGO),     \  
         _name##_show, _name##_store)  

#define __ATTR(_name, _mode, _show, _store) {               \  
    .attr = {.name = __stringify(_name), .mode = _mode },       \  
    .show   = _show,                        \  
    .store  = _store,                       \  
}  

第三步:在驅動程式的入口和結束的地方分別建立和刪除檔案,其中attr的名字應該是dev_attr_##_name處理後的名字,即dev_attr_<filename>

void device_remove_file (struct device * dev, struct device_attribute * attr);

int device_create_file (struct device * dev, const struct device_attribute * attr);

重新編譯核心,然後安裝並啟動,就能看到自己建立的sysfs檔案了。也有其他的方法可以實現相同的功能,但是DEVICE_ATTR_RW應該是比較簡單的一種。Linux核心有時會定義一些新的巨集替換老的方法,這也是練習提交補丁的好機會。

相關文章