-----------------
linux kernel玩久了,就會有想要有方便debug的方式
是不是能針對某一個檔案做讀取動作,就能讀取某一個硬體元件裡的 register呢?
是否能針對否一個檔案做寫的動作,就能設定某個硬體內部的 register 呢?

既然有了需求,開始查詢資料,發現 debug filesystem 很適合這樣的情況

何謂 debugfs

  debugfs是一種虛擬文件系統,與 procfs, sysfs相似,這種虛擬文件系統
並不會實際儲存在硬碟上,而是當 linux kernel運行後才建立起來的。
debugfs可以看作是一個臨時的文件系統,可以把我們所關心的數據映射到
用戶空間,且這相關的調適interface需要在相當長的一段時間內存在kernel中
這時就需要 debugfs。

預設狀況下,debugfs被掛載的目錄為 /sys/kernel/debug,如果沒有掛載,沒關係
可以用以下指令手動完成掛載

# mount -t debugfs none /sys/kernel/debug

接下來我們在 ubuntu上實作一下如果再debugfs下新增一個 目錄及檔案,並利用 file operarion
來對其中的檔案做 read, write。

首先按照一般 linux module 寫法將大架構寫出來,之後在  mydebugfs_init 函式中,呼叫以下函式

my_debugfs_root=debugfs_create_dir("mydebug",NULL);

函式原型定義在 linux/kernel/include/linux/debugfs.h
struct dentry *debugfs_create_dir(const char *name, struct dentry *parent)
第一個參數為[目錄名稱]設定為 mydebug,第二參數為 [上層目錄],設定NULL 表示上層目錄為/sys/kernel/debug
回傳值為 dentry 結構,定義在 linux/kernel/include/linux/dcache.h

目錄建立完成後,可以依照需求去建立檔案,呼叫以下函式建立檔案
debugfs_create_file("reg", 0644, my_debugfs_root,NULL, &c_fops)
函式原型
static inline struct dentry *debugfs_create_file(const char *name, umode_t mode,
                    struct dentry *parent, void *data,
                    const struct file_operations *fops)

參數依序為 [檔案名稱],[檔案權限],[上層目錄],[私人資料],[檔案存取結構指標]
因暫時不傳送資料到kernel,所以 data設定為NULL

[檔案存取結構指標]c_fops宣告如下:

struct file_operations c_fops = {
    .owner = THIS_MODULE,
    .open = c_open,
    .read = c_read,
    .write = c_write,
};

當使用者對 reg 檔案做開啟、讀(cat reg)、寫(echo 1> reg)時,就會呼叫 c_fops
 所定義的函式c_open,c_read,c_write


進階應用

在cat reg時呼叫c_read,在c_read 函式內就可以利用 I2C去讀取周邊硬體的 registers
然後秀出來。

或是在 c_write中可以設定要讀取的 i2c register address然後呼叫 cat去秀出值。


arrow
arrow
    文章標籤
    debugfs linux
    全站熱搜

    CuteParrot 發表在 痞客邦 留言(0) 人氣()