Linux 驅動程式觀念解析, #3: Device File

jollen 發表於 May 4, 2006 8:38 AM

Linux 驅動程式大架構的第二層為 VFS 層,由 VFS 所帶出來的重要觀念便是 device files。

作者/陳俊宏
www.jollen.org

什麼是 Device File

Device files 是 UNIX 系統的獨特觀念,在 UNIX 系統底下我們把外部的周邊裝置均視為一個檔案,並透過此檔案與實體硬體溝通,這樣的檔案就叫做 device files,或 special files。

Linux device driver 與 user 的重要溝通橋梁為 device files,在 Linux 系統底下,我們看到的 device files 如圖所示。檔案屬性的第一個位元如果顯示為 “c” 表示這是一個字元型裝置的 device file、若為 “b” 表示這是一個區塊型裝置的Device file。

Device file 的 major number 代表一個特定的裝置,例如 major number 為 1 為 null 虛擬裝置,major number 定義於 kernel 文件目錄 Documentation/devices.txt 。Minor number 代表裝置上的子裝置,例如同一個硬碟上的分割區就用不同的 minor number 來代表,但其 major number 相同。

Device File 與驅動程式的關係

我們在設計 device driver 時,會先透過一個 “註冊” (register) 的動作將自己註冊到 kernel 裡,註冊時,我們會指定一個 major number 參數,以指定此驅動程式所要實作的週邊裝置。當 user 開啟 device file 時,kernel 便會根據 device file 的major number 找到對應的驅動程式來回應使用者。Minor number 則是 device driver 內部所使用,kernel 並不會處理不同的 minor number。

設計 device driver 的第一個步驟就是要定義 driver 所要提供的功能 (capabilities),當 user application 呼叫open() system call 時,kernel 就會連繫相對應的 driver 來回應使用者。

file_operations 是學習 device driver 最重要的一個資料結構,file_operations內的成員為函數指標,指向 “system call 的實作函數”。file_operations 即是圖中的 VFS 層。換句話說,Linux驅動程式是透過file_operations來建構VFS層的支援。而file_operation裡的函數指標,即是指向每一個system call的實作函數。

變更紀錄

  • 2006-12-21: 勝良兄反應了一個錯誤,已修正。

Jollen's Blog 使用 Github issues 與讀者交流討論。請點擊上方的文章專屬 issue,或 open a new issue

您可透過電子郵件 jollen@jollen.org,或是 Linkedin 與我連絡。更歡迎使用微信,請搜尋 WeChat ID:jollentw