1. dev_t 型別
(1)在核心中,dev_t型別(定義在linux/types.h 中)用來保存裝置編號 - 包括major和minor。
(2)在核心 2.6.0中,dev_t是一個『32位的數』,其中12位表示major,20位表示minor。
(3)獲得dev_t的major、minor:
MAJOR(dev_t dev);
MINOR(dev_t dev);
(4)轉換成dev_t 類型:
MKDEV(int major, int minor);
2. 向kernel註冊
(1)include linux/fs.h
fs.h 是編寫device drivers 所需要的header file. 許多重要的函數和數據結構在此定義.
(2) 註冊函數
事先設定major==> int register_chrdev_region(dev_t first, unsigned int count, char *name)
動態分配major==> int alloc_chrdev_region(dev_t *dev, unsigned int firstminor, unsigned int count, char *name)
反註冊都相同 ==> void unregister_chrdev_region(dev_t first, unsigned int count);
ps: 核心2.6以前的方法 ==>int register_chrdev(unsigned int major, const char *name, struct file_operations *fops);
2.6也還能用,但效能彈性有限。
而反註冊方法===> int unregister_chrdev(unsigned int major, const char *name);
3. cdev 結構管理的函數, 它代表内核中的字元設備.
(1)include linux/cdev.h
struct cdev *cdev_alloc(void);
void cdev_init(struct cdev *dev, struct file_operations *fops);
int cdev_add(struct cdev *dev, dev_t num, unsigned int count);
void cdev_del(struct cdev *dev);
4. file_operations 結構
這個結構定義在linux/fs.h中,用來建立驅動程式操作到設備編號的連接。
它包含了一组函數指標,每個打開的文件(在內部用file表示)和一组函數關聯(通過包含指向一個file_operations结構的『f_op』字段)。
5. file结構
stuct file定義在linux/fs.h中,是一個內核結構,它不會出現在用戶程序中。
(與用戶空間程序中的FILE结構沒有任何關聯,FILE不會出现在內核代碼中。)
file结構代表一個打開的文件(不僅限於設備驅動程序,系统中每個打開的文件在內核空間中都有一個對應的file结構)。
然而,指向『struct file』的指標通常稱為『flip』。
6. read和write方法
(1)ssize_t read(struct file *filp, char __user *buff, size_t count, loff_t *offp);
ssize_t write(struct file *filp, const char __user *buff, size_t count, loff_t *offp);
(2)參數filp是文件指標,count是請求傳輸的數據長度,buff是指向用戶空間的緩衝區,
offp是一個指向“long offset type”對象的指標,
它指明用戶在文件中進行存取操作的位置。
返回值是“signed size type(有符號的尺寸類型)”。
(3)read和write方法不能直接引用buff參數(用戶空間)的內容,
安全訪問應該通過『内核提供的專用函數』完成:(定義在asm/uaccess.h中)
unsigned long copy_to_user(void __user *to,const void *from,unsigned long count);
unsigned long copy_from_user(void *to,const void __user *from,unsigned long count);
(4)read和write方法的返回值
http://wiki.magiclinux.org/ftp/haulm/book/Device/ch03s07.html (3.7.1/2)
其中『負值』意味著『錯誤』,錯誤碼 在linux/errno.h中定義,
如:-EINTR(系统調用被中斷)-EFAULT(無效地址)
沒有留言:
張貼留言