3 Introduction scull Simple Character Utility for Loading





































- Slides: 37
3 --Introduction • 範例:scull--( Simple Character Utility for Loading Localities ) – Makefile, main. c, access. c, empty. c, pipe. c, scull. h, scull. init, scull_load, scull_unload, alpha. checkthem • scull的作用是“讓使用者可把一塊記憶區當成字元裝置 來使用” scull所驅動的目標裝置是一塊記憶區 – 不需依賴任何“特殊”硬體 – 只要有linux平台就可以編譯與執行 – 未提供任何實用功能,只展示核心與char driver之間軟體介面
3. 2. 1—裝置編號的配置與釋放 • 大部份常見的裝置幾乎都有固定的主編號,可在核心 源碼樹的Documentation/devices. txt檔案內找到一份“裝 置-主編號”對照表。<挑選可用主編號> less /usr/src/kernel/linux 3. 0. 8/Documentation/devices. txt • “實驗性或自家使用”的主編號: – 60~63 、 120~127、240. 254<真正公開給大眾使用的驅動程式 不該使用這些範圍內的主編號> extern int register_chrdev_region(dev_t first, unsigned int count, const char *name); extern int unregister_chrdev_region (dev_t first , unsigned int count);
3. 2. 2—動態配置主編號 cat /proc/devices Character devices: 1 mem 2 pty 226 drm 253 scull 254 pcmcia Block devices: 2 fd 3 ide 0
Read() Scull_read()
• ssize_t (*write) (struct file *, const char *, size_t, loff_t *); – 將資料寫入裝置。 • int (*readdir) (struct file *, void *, filldir_t); – 對於裝置檔而言,此欄位必須是NULL,因為他是用來讀取目 錄,而且只對檔案系統有意義。 • unsigned int (*poll) (struct file *, struct poll_table_struct *); – 查詢裝置的I/O狀態。 • int (*mmap) (struct file *, struct vm_area_struct *); – mmap用來將I/O memory對應到行程的位址空間。若驅動程式 沒提供此方法,則mmap()系統呼叫將傳回-ENODEV
Scull_Dev next data 配額集 個別配額 Scull_Dev next data scull 裝置 的記憶佈局 Scull_Dev next data
3. 7—read & write ssize_t read(struct file *filp, char *buff, size_t count, loff_t *offp); ssize_t write(struct file *filp, const char *buff, size_t count, loff_t *offp); • • filp 檔案指標 buff 引數指向user-space的緩衝區 count 要被傳輸的資料量 offp 是一個指向“long offset type”的物件指標,代表 使用者正在存取的檔案位置
3. 8—read & write • “跨空間”資料傳輸(在kernel-space與user-space之間傳遞 資料) • scull的read作業方法,需有可將整段資料寫到user-sapce 的能力。write作業方法,需要能從kernel-space讀取一整 段資料的能力。 • 由以下兩個核心函式(具有檢查功能)提供: unsigned long copy_to_user(void *to, const void *from, unsigned long count ); unsigned long copy_from_user(void *to, const void *from, unsigned long count ); • 預防動作必須注意(user-space有換出功能-swapped out)
ssize_t dev_read( struct file *file, *file char *buf, *buf size_t count, count loff_t *ppos); *ppos struct file f_count f_flags f_mode f_pos …. …. Read 作業方法 的引數之應用 Buffer ( in the (in the user-space Kernel-space Copy_to_user( ) or ) Libc ) 核心空間( 不可置換) 使用者空間 (可被置換)
DEMO - 1 ls –al /dev/ |less brw-rw---- 1 root disk 66, 72 Apr 11 2002 sdak 8 brw-rw---- 1 root disk 66, 73 Apr 11 2002 sdak 9 crw-r--r-- 1 root 253, 1 Mar 1 22: 58 scull 1 crw-r--r-- 1 root 253, 2 Mar 1 22: 58 scull 2 crw-r--r-- 1 root 253, 3 Mar 1 22: 58 scull 3 brw-rw---- 1 root disk 8, 0 Apr 11 2002 sda crw-rw---- 1 root uucp 裝置類型 154, 18 Apr 11 2002 tty. SR 18 主編號 次編號 代表名稱
DEMO - 3 • . /scull_load • cat /proc/devices • . /scull_unload