1. 程式人生 > >Linux裝置驅動之字元裝置驅動---轉

Linux裝置驅動之字元裝置驅動---轉

一、linux系統將裝置分為3類:字元裝置、塊裝置、網路裝置。

應用程式呼叫的流程框圖:

三種裝置的定義分別如下,

字元裝置:只能一個位元組一個位元組的讀寫的裝置,不能隨機讀取裝置記憶體中的某一資料,讀取資料需要按照先後順序進行。字元裝置是面向流的裝置,常見的字元裝置如滑鼠、鍵盤、串列埠、控制檯、LED等。

塊裝置:是指可以從裝置的任意位置讀取一定長度的資料裝置。塊裝置如硬碟、磁碟、U盤和SD卡等儲存裝置。

網路裝置:網路裝置比較特殊,不在是對檔案進行操作,而是由專門的網路介面來實現。應用程式不能直接訪問網路裝置驅動程式。在/dev目錄下也沒有檔案來表示網路裝置。

對於字元裝置和塊裝置來說,在/dev目錄下都有對應的裝置檔案。linux使用者程式通過裝置檔案或叫做裝置節點來使用驅動程式操作字元裝置和塊裝置。

二、字元裝置和快裝置啟動與使用者控制元件訪問該裝置的程式 ,三者之間的關係。

如上圖,在linux核心中使用cdev結構體來描述字元裝置,通過其成員dev_t來定義裝置號,以確定字元裝置的唯一性。通過其成員file_operations來定義字元裝置驅動提供給VFS的介面函式,如常見的open()、read()、write()等。

在Linux字元裝置驅動中,模組載入函式通過register_chrdev_region( ) 或alloc_chrdev_region( )來靜態或者動態獲取裝置號,通過cdev_init( )建立cdev與file_operations之間的連線,通過cdev_add( )向系統新增一個cdev以完成註冊。模組解除安裝函式通過cdev_del( )來登出cdev,通過unregister_chrdev_region( )來釋放裝置號。

使用者空間訪問該裝置的程式通過Linux系統呼叫,如open( )、read( )、write( ),來“呼叫”file_operations來定義字元裝置驅動提供給VFS的介面函式。

三、字元裝置驅動模板

這張圖基本表示了字元驅動所需要的模板,只是缺少class的相關內容,class主要是用來自動建立裝置節點的,還有就是一個比較常用的ioctl()函式沒有列在上邊。

下面具體說一下每個步驟的詳細內容。

1.驅動初始化

1.1分配cdev

在2.6的核心中使用cdev結構體來描述字元裝置,在驅動中分配cdev,主要是分配一個cdev結構體與申請裝置號。

例如:

/*……*/
/* 分配cdev*/
struct cdev btn_cdev;
/*……*/
/* 1.1 申請裝置號*/
if(major){
	//靜態
	dev_id = MKDEV(major, 0);
	register_chrdev_region(dev_id, 1, "button");
} else {
	//動態
	alloc_chardev_region(&dev_id, 0, 1, "button");
	major = MAJOR(dev_id);
}
/*……*/

從上面的程式碼可以看出,申請裝置號有動靜之分,其實裝置號還有主次之分。 在Linux中以主裝置號用來標識與裝置檔案相連的驅動程式。次編號被驅動程式用來辨別操作的是哪個裝置。cdev 結構體的 dev_t 成員定義了裝置號,為 32 位,其中高 12 位為主裝置號,低20 位為次裝置號。 裝置號的獲得與生成: 獲得:主裝置號:MAJOR(dev_t dev); 次裝置號:MINOR(dev_t dev); 生成:MKDEV(int major,int minor); 裝置號申請的動靜之分: 靜態:

int register_chrdev_region(dev_t from, unsigned count, const char *name);
/*功能:申請使用從from開始的count 個裝置號(主裝置號不變,次裝置號增加)*/

靜態申請相對較簡單,但是一旦驅動被廣泛使用,這個隨機選定的主裝置號可能會導致裝置號衝突,而使驅動程式無法註冊。 動態:

int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,const char *name);
/*功能:請求核心動態分配count個裝置號,且次裝置號從baseminor開始。*/

動態申請簡單,易於驅動推廣,但是無法在安裝驅動前建立裝置檔案(因為安裝前還沒有分配到主裝置號)。

1.2.初始化cdev

1 void cdev_init(struct cdev *, struct file_operations *); 
2 cdev_init()函式用於初始化 cdev 的成員,並建立 cdev 和 file_operations 之間的連線。

1.3.註冊cdev

1 int cdev_add(struct cdev *, dev_t, unsigned);
2      cdev_add()函式向系統新增一個 cdev,完成字元裝置的註冊。

1.4.硬體初始化

硬體初始化主要是硬體資源的申請與配置,主要涉及地址對映,暫存器讀寫等相關操作,每一個開發板不同都有不同的實現方式,這裡以FS4412為例:

	/* 地址對映 */
	gpx2con = ioremap(GPX2CON, 4);
	if (gpx2con == NULL)
	{
		printk("gpx2con ioremap err\n");
		goto err3;
	}
	gpx2dat = ioremap(GPX2DAT, 4);
	if (gpx2dat == NULL)
	{
		printk("gpx2dat ioremap err\n");
		goto err4;
	}

	gpx1con = ioremap(GPX1CON, 4);
	gpx1dat = ioremap(GPX1DAT, 4);

	gpf3con = ioremap(GPF3CON, 4);
	gpf3dat = ioremap(GPF3DAT, 4);

	writel(readl(gpx2con)&(~(0xf<<28))|(0x1<<28), gpx2con);
	writel((0x1<<7), gpx2dat);
	writel(readl(gpx1con)&(~(0xf<<0))|(0x1<<0), gpx1con);
	writel((0x1<<0), gpx1dat);
	writel(readl(gpf3con)&(~(0xf<<16))|(0x1<<16), gpf3con);
	writel(readl(gpf3dat)|(0x1<<4), gpf3dat);
	writel(readl(gpf3con)&(~(0xf<<20))|(0x1<<20), gpf3con);
	writel(readl(gpf3dat)|(0x1<<5), gpf3dat);

2.實現裝置操作 使用者空間的程式以訪問檔案的形式訪問字元裝置,通常進行open、read、write、close等系統呼叫。而這些系統呼叫的最終落實則是file_operations結構體中成員函式,它們是字元裝置驅動與核心的介面。以FS4412的LED驅動為例:

struct file_operations hello_fops = {
	.owner = THIS_MODULE,
	.open = hello_open,
	.release = hello_release,
	.read = hello_read,
	.write = hello_write,
};

上面程式碼中的hello_open、hello_write、hello_read是要在驅動中自己實現的。file_operations結構體成員函式有很多個,下面就選幾個常見的來展示: 2.1. open()函式 原型:

1 int(*open)(struct inode *, struct file*); 
2 /*開啟*/

2.2. read( )函式 原型:

ssize_t(*read)(struct file *, char __user*, size_t, loff_t*); 
/*用來從裝置中讀取資料,成功時函式返回讀取的位元組數,出錯時返回一個負值*/

2.3. write( )函式 原型:

1 ssize_t(*write)(struct file *, const char__user *, size_t, loff_t*);
2 /*向裝置傳送資料,成功時該函式返回寫入的位元組數。如果此函式未被實現,
3 當用戶進行write()系統呼叫時,將得到-EINVAL返回值*/

2.4. close( )函式 原型:

1 int(*release)(struct inode *, struct file*); 
2 /*關閉*/

2.5 ioctl( )函式

原型:

int ioctl(int fd, ind cmd, …);

這裡主要說一下ioctl函式。ioctl是裝置驅動程式中對裝置的I/O通道進行管理的函式。所謂對I/O通道進行管理,就是對裝置的一些特性進行控制,例如串列埠的傳輸波特率、馬達的轉速等等。 其中fd就是使用者程式開啟裝置時使用open函式返回的檔案標示符,cmd就是使用者程式對裝置的控制命令,至於後面的省略號,那是一些補充引數,一般最多一個,有或沒有是和cmd的意義相關的。 ioctl函式是檔案結構中的一個屬性分量,就是說如果你的驅動程式提供了對ioctl的支援,使用者就可以在使用者程式中使用ioctl函式控制裝置的I/O通道。

如果不用ioctl的話,也可以實現對裝置I/O通道的控制,但那就是蠻擰了。例如,我們可以在驅動程式中實現write的時候檢查一下是否有特殊約定的資料流通過,如果有的話,那麼後面就跟著控制命令(一般在socket程式設計中常常這樣做)。但是如果這樣做的話,會導致程式碼分工不明,程式結構混亂,程式設計師自己也會頭昏眼花的。 所以,我們就使用ioctl來實現控制的功能。要記住,使用者程式所作的只是通過命令碼告訴驅動程式它想做什麼,至於怎麼解釋這些命令和怎麼實現這些命令,這都是驅動程式要做的事情。

在驅動程式中實現的ioctl函式體內,實際上是有一個switch{case}結構,每一個case對應一個命令碼,做出一些相應的操作。怎麼實現這些操作,這是每一個程式設計師自己的事情,因為裝置都是特定的,這裡也沒法說。關鍵在於怎麼樣組織命令碼,因為在ioctl中命令碼是唯一聯絡使用者程式命令和驅動程式支援的途徑。 命令碼的組織是有一些講究的,因為我們一定要做到命令和裝置是一一對應的,這樣才不會將正確的命令發給錯誤的裝置,或者是把錯誤的命令發給正確的裝置,或者是把錯誤的命令發給錯誤的裝置。這些錯誤都會導致不可預料的事情發生,而當程式設計師發現了這些奇怪的事情的時候,再來除錯程式查詢錯誤,那將是非常困難的事情。

所以在Linux核心中是這樣定義一個命令碼的:

      MAGIC: 幻數  8位的數  0 - 255    'L'        nr: 序數,用來區分同一類裝置的不同命令       #define   CMD     _IO(MAGIC, nr)  hello.h       #define   LED_MAGIC  'L'       #define   LED_ON    _IO(LED_MAGIC, 1)       #define   LED_OFF   _IO(LED_MAGIC, 2)

通過這種方式來定義cmd,並在ioctl程式中區分cmd。

2.5. 補充說明 1. 在Linux字元裝置驅動程式設計中,有3種非常重要的資料結構:struct file、struct inode、struct file_operations。 struct file 代表一個開啟的檔案。系統中每個開啟的檔案在核心空間都有一個關聯的struct file。它由核心在開啟檔案時建立, 在檔案關閉後釋放。其成員loff_t f_pos 表示檔案讀寫位置。 struct inode 用來記錄檔案的物理上的資訊。因此,它和代表開啟檔案的file結構是不同的。一個檔案可以對應多個file結構,但只有一個inode結構。其成員dev_t i_rdev表示裝置號。 struct file_operations 一個函式指標的集合,定義能在裝置上進行的操作。結構中的成員指向驅動中的函式,這些函式實現一個特別的操作, 對於不支援的操作保留為NULL。 2. 在read( )和write( )中的buff 引數是使用者空間指標。因此,它不能被核心程式碼直接引用,因為使用者空間指標在核心空間時可能根本是無效的——沒有那個地址的對映。因此,核心提供了專門的函式用於訪問使用者空間的指標:

1 unsigned long copy_from_user(void *to, const void __user *from, unsigned long count);
2 unsigned long copy_to_user(void __user *to, const void *from, unsigned long count);

3. 驅動登出 3.1. 刪除cdev 在字元裝置驅動模組解除安裝函式中通過cdev_del()函式向系統刪除一個cdev,完成字元裝置的登出。

/*原型:*/
void cdev_del(struct cdev *);
/*例:*/
cdev_del(&btn_cdev);

3.2. 釋放裝置號 在呼叫cdev_del()函式從系統登出字元裝置之後,unregister_chrdev_region()應該被呼叫以釋放原先申請的裝置號。

/*原型:*/
void unregister_chrdev_region(dev_t from, unsigned count);
/*例:*/
unregister_chrdev_region(MKDEV(major, 0), 1);

四、字元裝置驅動程式基礎: 4.1 cdev結構體

前面寫到如何向系統申請一個裝置號,裝置號就像我們的身份證號一樣,號本身並沒有什麼特殊的意義,只有把這個號和人對應才有意義,通用裝置號也需要和一個特殊的東西對於,這就是cdev, cdev是linux下抽象出來的一個用來描述一個字元裝置的結構體,在linux下定義如下:

struct cdev {
                struct kobject kobj;
                struct module *owner;
                const struct file_operations *ops;
                struct list_head list;
                dev_t dev;
                unsigned int count;
        };

結構體中有幾個成員事我們寫驅動的時候必須關心的: dev 型別是dev_t,也就是我們的裝置號 ops是一個同樣也是一個結構體並且是一個字元驅動實現的主體,字元驅動通常需要和應用程式互動,在學linux系統程式設計的時候,都會講到linux 應用程式通過系統呼叫陷入到核心空間,從而執行核心程式碼,而驅動作為核心的一部分同樣也是需要在核心空間執行的,ops也就是file_operations這個結構體就是我們的驅動為應用程式呼叫驅動而實現的一個操作的集合。後面會詳細講解。

cdev 結構體的dev_t 成員定義了裝置號,為32位,其中12位是主裝置號,20位是次裝置號,我們只需使用二個簡單的巨集就可以從dev_t 中獲取主裝置號和次裝置號: MAJOR(dev_t dev) MINOR(dev_t dev) 相反地,可以通過主次裝置號來生成dev_t: MKDEV(int major,int minor)

4.2 Linux 2.6核心提供一組函式用於操作cdev 結構體

1:void cdev_init(struct cdev*,struct file_operations *);
2:struct cdev *cdev_alloc(void);
3:int cdev_add(struct cdev *,dev_t,unsigned);
4:void cdev_del(struct cdev *);

其中(1)用於初始化cdev結構體,並建立cdev與file_operations 之間的連線。(2)用於動態分配一個cdev結構,(3)向核心註冊一個cdev結構,(4)向核心登出一個cdev結構。

cdev_add實現cdev的註冊,linux核心裡維護了一個cdev_map的表,所謂cdev的註冊就是把我們的cdev註冊到cdev_map表上,cdev_map表結構如圖:

4.3 Linux 2.6核心分配和釋放裝置號

在呼叫cdev_add()函式向系統註冊字元裝置之前,首先應向系統申請裝置號,有二種方法申請裝置號,一種是靜態申請裝置號: 5:int register_chrdev_region(dev_t from,unsigned count,const char *name) 另一種是動態申請裝置號: 6:int alloc_chrdev_region(dev_t *dev,unsigned baseminor,unsigned count,const char *name); 其中,靜態申請是已知起始裝置號的情況,如先使用cat /proc/devices 命令查得哪個裝置號未事先使用(不推薦使用靜態申請);動態申請是由系統自動分配,只需設定major = 0即可。 相反地,在呼叫cdev_del()函式從系統中登出字元裝置之後,應該向系統申請釋放原先申請的裝置號,使用: 7:void unregister_chrdev_region(dev_t from,unsigned count); 4.4 cdev結構的file_operations結構體 這個結構體是字元裝置當中最重要的結構體之一,file_operations 結構體中的成員函式指標是字元裝置驅動程式設計的主體內容,這些函式實際上在應用程式進行Linux 的 open()、read()、write()、close()、seek()、ioctl()等系統呼叫時最終被呼叫。

1 struct file_operations {
 2 
 3 /*擁有該結構的模組計數,一般為THIS_MODULE*/
 4 struct module *owner;
 5 
 6 /*用於修改檔案當前的讀寫位置*/
 7 loff_t (*llseek) (struct file *, loff_t, int);
 8 
 9 /*從裝置中同步讀取資料*/
10 ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
11 
12 /*向裝置中寫資料*/
13 ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
14 
15 
16 ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
17 ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
18 int (*readdir) (struct file *, void *, filldir_t);
19 
20 /*輪詢函式,判斷目前是否可以進行非阻塞的讀取或寫入*/
21 unsigned int (*poll) (struct file *, struct poll_table_struct *);
22 
23 /*執行裝置的I/O命令*/
24 int (*ioctl) (struct inode *, struct file *, unsigned int, unsigned long);
25 
26 
27 long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
28 long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
29 
30 /*用於請求將裝置記憶體對映到程序地址空間*/
31 int (*mmap) (struct file *, struct vm_area_struct *);
32 
33 /*開啟裝置檔案*/
34 int (*open) (struct inode *, struct file *);
35 int (*flush) (struct file *, fl_owner_t id);
36 
37 /*關閉裝置檔案*/
38 int (*release) (struct inode *, struct file *);
39 
40 
41 int (*fsync) (struct file *, struct dentry *, int datasync);
42 int (*aio_fsync) (struct kiocb *, int datasync);
43 int (*fasync) (int, struct file *, int);
44 int (*lock) (struct file *, int, struct file_lock *);
45 ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
46 unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
47 int (*check_flags)(int);
48 int (*flock) (struct file *, int, struct file_lock *);
49 ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
50 ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
51 int (*setlease)(struct file *, long, struct file_lock **);
52 };

4.5 file結構 file 結構代表一個開啟的檔案,它的特點是一個檔案可以對應多個file結構。它由核心再open時建立,並傳遞給在該檔案上操作的所有函式,直到最後close函式,在檔案的所有例項都被關閉之後,核心才釋放這個資料結構。 在核心原始碼中,指向 struct file 的指標通常比稱為filp,file結構有以下幾個重要的成員:

1 struct file{
 2 
 3 mode_t fmode; /*檔案模式,如FMODE_READ,FMODE_WRITE*/
 4 
 5 ......
 6 
 7 loff_t f_pos; /*loff_t 是一個64位的數,需要時,須強制轉換為32位*/
 8 
 9 unsigned int f_flags; /*檔案標誌,如:O_NONBLOCK*/
10 
11 struct file_operations *f_op;
12 
13 void *private_data; /*非常重要,用於存放轉換後的裝置描述結構指標*/
14 
15 .......
16 
17 };

4.6 inode 結構 核心用inode 結構在內部表示檔案,它是實實在在的表示物理硬體上的某一個檔案,且一個檔案僅有一個inode與之對應,同樣它有二個比較重要的成員:

1 struct inode{
 2 
 3 dev_t i_rdev; /*裝置編號*/
 4 
 5 struct cdev *i_cdev; /*cdev 是表示字元裝置的核心的內部結構*/
 6 
 7 };
 8 
 9 可以從inode中獲取主次裝置號,使用下面二個巨集:
10 
11 /*驅動工程師一般不關心這二個巨集*/
12 
13 unsigned int imajor(struct inode *inode);
14 
15 unsigned int iminor(struct inode *inode);

4.7字元裝置驅動模組載入與解除安裝函式 在字元裝置驅動模組載入函式中應該實現裝置號的申請和cdev 結構的註冊,而在解除安裝函式中應該實現裝置號的釋放與cdev結構的登出。 我們一般習慣將cdev內嵌到另外一個裝置相關的結構體裡面,該裝置包含所涉及的cdev、私有資料及訊號量等等資訊。常見的裝置結構體、模組載入函式、模組解除安裝函式形式如下:

1/*裝置結構體*/
 2 
 3 struct xxx_dev{
 4 
 5 struct cdev cdev;
 6 
 7 char *data;
 8 
 9 struct semaphore sem;
10 
11 ......
12 
13 };
14 
15 
16 
17 /*模組載入函式*/
18 
19 static int __init xxx_init(void)
20 
21 {
22 
23 .......
24 
25 初始化cdev結構;
26 
27 申請裝置號;
28 
29 註冊裝置號;
30 
31 
32 
33 申請分配裝置結構體的記憶體; /*非必須*/
34 
35 }
36 
37 
38 
39 /*模組解除安裝函式*/
40 
41 static void __exit xxx_exit(void)
42 
43 {
44 
45 .......
46 
47 釋放原先申請的裝置號;
48 
49 釋放原先申請的記憶體;
50 
51 登出cdev裝置;
52 
53 }
54 
55

4.8字元裝置驅動的 file_operations 結構體重成員函式

1 /*讀裝置*/
 2 
 3 ssize_t xxx_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
 4 
 5 {
 6 
 7 ......
 8 
 9 使用filp->private_data獲取裝置結構體指標;
10 
11 分析和獲取有效的長度;
12 
13 /*核心空間到使用者空間的資料傳遞*/
14 
15 copy_to_user(void __user *to, const void *from, unsigned long count);
16 
17 ......
18 
19 }
20 
21 /*寫裝置*/
22 
23 ssize_t xxx_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos)
24 
25 {
26 
27 ......
28 
29 使用filp->private_data獲取裝置結構體指標;
30 
31 分析和獲取有效的長度;
32 
33 /*使用者空間到核心空間的資料傳遞*/
34 
35 copy_from_user(void *to, const void __user *from, unsigned long count);
36 
37 ......
38 
39 }
40 
41 /*ioctl函式*/
42 
43 static int xxx_ioctl(struct inode *inode,struct file *filp,unsigned int cmd,unsigned long arg)
44 
45 {
46 
47 ......
48 
49 switch(cmd){
50 
51 case xxx_CMD1:
52 
53 ......
54 
55 break;
56 
57 case xxx_CMD2:
58 
59 .......
60 
61 break;
62 
63 default:
64 
65 return -ENOTTY; /*不能支援的命令*/
66 
67 }
68 
69 return 0;
70 
71 }

4.9、字元裝置驅動檔案操作結構體模板

1 struct file_operations xxx_fops = {
 2 
 3 .owner = THIS_MODULE,
 4 
 5 .open = xxx_open,
 6 
 7 .read = xxx_read,
 8 
 9 .write = xxx_write,
10 
11 .close = xxx_release,
12 
13 .ioctl = xxx_ioctl,
14 
15 .lseek = xxx_llseek,
16 
17 };
18 
19 上面的寫法需要注意二點,一:結構體成員之間是以逗號分開的而不是分號,結構體欄位結束時最後應加上分號。

5.自動建立裝置節點

在剛開始寫Linux裝置驅動程式的時候,很多時候都是利用mknod命令手動建立裝置節點,實際上Linux核心為我們提供了一組函式,可以用來在模組載入的時候自動在/dev目錄下建立相應裝置節點,並在解除安裝模組時刪除該節點。

在2.6.17以前,在/dev目錄下生成裝置檔案很容易, devfs_mk_bdev devfs_mk_cdev devfs_mk_symlink devfs_mk_dir devfs_remove 這幾個是純devfs的api,2.6.17以前可用,但後來devfs被sysfs+udev的形式取代,同時期sysfs檔案系統可以用的api: class_device_create_file,在2.6.26以後也不行了,現在,使用的是device_create ,從2.6.18開始可用 struct device *device_create(struct class *class, struct device *parent, dev_t devt, const char *fmt, ...) 從2.6.26起又多了一個引數drvdata: the data to be added to the device for callbacks 不會用可以給此引數賦NULL struct device *device_create(struct class *class, struct device *parent, dev_t devt, void *drvdata, const char *fmt, ...)

在驅動用加入對udev的支援主要做的就是:在驅動初始化的程式碼裡呼叫class_create(...)為該裝置建立一個class,再為每個裝置呼叫device_create(...)( 在2.6較早的核心中用class_device_create)建立對應的裝置。 核心中定義的struct class結構體,顧名思義,一個struct class結構體型別變數對應一個類,核心同時提供了class_create(…)函式,可以用它來建立一個類,這個類存放於sysfs下面,一旦建立好了這個類,再呼叫 device_create(…)函式來在/dev目錄下建立相應的裝置節點。這樣,載入模組的時候,使用者空間中的udev會自動響應 device_create(…)函式,去/sysfs下尋找對應的類從而建立裝置節點。 struct class和class_create(…) 以及device_create(…)都包含在在/include/linux/device.h中,使用的時候一定要包含這個標頭檔案,否則編譯器會報錯。

struct class定義在標頭檔案include/linux/device.h中

//device classes

struct class {
      const char       *name;
      struct module     *owner;
                         nbsp;
      struct kset        subsys;
      struct list_head        devices;
      struct list_head        interfaces;
      struct kset             class_dirs;
      struct semaphore sem;    //lockschildren, devices, interfaces 
      struct class_attribute   *class_attrs;
      struct device_attribute     *dev_attrs;

      int (*dev_uevent)(structdevice *dev, struct kobj_uevent_env *env);
      void (*class_release)(structclass *class);
      void (*dev_release)(struct device *dev);
      int (*suspend)(struct device*dev, pm_message_t state);
      int (*resume)(struct device *dev);
};

class_create(…)在/drivers/base/class.c中實現

// class_create - create a struct class structure
// @owner: pointer to the module that is to "own"this struct class
// @name: pointer to a string for the name of this class.

// This is used to create a struct class pointer that canthen be used
// in calls to device_create().

//Note, the pointer created here is to be destroyed whenfinished by
// making a call to class_destroy().

struct class *class_create(struct module *owner, const char *name)
{
      struct class *cls;
      int retval;

      cls = kzalloc(sizeof(*cls), GFP_KERNEL);
      if (!cls) {
           retval = -ENOMEM;
           goto error;
      }

      cls->name = name;
      cls->owner = owner;
      cls->class_release =class_create_release;

      retval =class_register(cls);
      if (retval)
           goto error;

      return cls;
error:
      kfree(cls);
      return ERR_PTR(retval);
}

class_destroy(...)函式

// class_destroy - destroys a struct class structure
//@cs: pointer to the struct class that is to be destroyed

//Note, the pointer to be destroyed must have been created with a call
//to class_create().

void class_destroy(struct class *cls)
{
    if((cls == NULL) || (IS_ERR(cls)))
        return;

    class_unregister(cls);
}

device_create(…)函式在/drivers/base/core.c中實現

// device_create - creates a device and registersit with sysfs
// @class: pointer to the struct class that thisdevice should be registered to
// @parent: pointer to the parent struct device ofthis new device, if any
// @devt: the dev_t for the char device to beadded
// @fmt: string for the device's name
     
// This function can be used by char deviceclasses. A struct device
// will be created in sysfs, registered to thespecified class.

// A "dev" file will be created, showingthe dev_t for the device, if
// the dev_t is not 0,0.
// If a pointer to a parent struct device ispassed in, the newly created
// struct device will be a child of that device insysfs.
// The pointer to the struct device will bereturned from the call.
// Any further sysfs files that might be requiredcan be created using this
// pointer.

// Note: the struct class passed to this functionmust have previously
// been created with a call to class_create().

struct device *device_create(struct class *class,struct device *parent,
                        dev_tdevt, const char *fmt, ...)
{
         va_list vargs;
         struct device *dev;

         va_start(vargs,fmt);
         dev =device_create_vargs(class, parent, devt, NULL, fmt, vargs);
         va_end(vargs);

         return dev;
}

第一個引數指定所要建立的裝置所從屬的類, 第二個引數是這個裝置的父裝置,如果沒有就指定為NULL, 第三個引數是裝置號, 第四個引數是裝置名稱, 第五個引數是從裝置號。

class_destroy(...),device_destroy(...)也在/drivers/base/core.c中實現

// device_destroy - removes a device that was created with device_create()
// @class: pointer to the struct class that this device was registered with
// @devt: the dev_t of the device that was previously registered

// This call unregisters and cleans up a device that was created with a
// call to device_create().

void device_destroy(struct class *class,dev_t devt)
{
    structdevice *dev = NULL;
    structdevice *dev_tmp;
 
    down(&class->sem);
    list_for_each_entry(dev_tmp,&class->devices, node) {
        if(dev_tmp->devt == devt) {
            dev= dev_tmp;
            break;
        }
    }
    up(&class->sem);
 
    if(dev)
        device_unregister(dev);
}

相比devfs,udev有很多優勢,在此就不羅嗦了,提醒一點,udev是應用層的東東,不要試圖在核心的配置選項裡找到它;加入對udev的支援很簡單,以字元裝置驅動為例,在驅動初始化的程式碼裡呼叫class_create為該裝置建立一個class,再為每個裝置呼叫 class_device_create建立對應的裝置。大致用法如下:

struct class *myclass = class_create(THIS_MODULE, “my_device_driver”);
class_device_create(myclass, NULL, MKDEV(major_num, 0), NULL, “my_device”);

這樣的module被載入時,udev daemon就會自動在/dev下建立my_device裝置檔案。

下面以一個簡單字元裝置驅動來展示如何使用這幾個函式:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
 
int HELLO_MAJOR = 0;
int HELLO_MINOR = 0;
int NUMBER_OF_DEVICES = 2;
 
struct class *my_class;
//struct cdev cdev;
//dev_t devno;
 
struct hello_dev {
struct device *dev;
dev_t chrdev;
struct cdev cdev;
};

static struct hello_dev *my_hello_dev = NULL;

struct file_operations hello_fops = {
 .owner = THIS_MODULE
};
 
static int __init hello_init (void)
{
int err = 0;
struct device *dev;

my_hello_dev = kzalloc(sizeof(struct hello_dev), GFP_KERNEL);
if (NULL == my_hello_dev) {
printk("%s kzalloc failed!\n",__func__);
return -ENOMEM;
}

devno = MKDEV(HELLO_MAJOR, HELLO_MINOR);
if (HELLO_MAJOR)
err= register_chrdev_region(my_hello_dev->chrdev, 2, "memdev");
else
{
err = alloc_chrdev_region(&my_hello_dev->chrdev, 0, 2, "memdev");
HELLO_MAJOR = MAJOR(devno);
}  
if (err) {
printk("%s alloc_chrdev_region failed!\n",__func__);
goto alloc_chrdev_err;
}
printk("MAJOR IS %d\n",HELLO_MAJOR);

cdev_init(&(my_hello_dev->cdev), &hello_fops);
my_hello_dev->cdev.owner = THIS_MODULE;
err = cdev_add(&(my_hello_dev->cdev), my_hello_dev->chrdev, 1);
if (err) {
printk("%s cdev_add failed!\n",__func__);
goto cdev_add_err;
}
printk (KERN_INFO "Character driver Registered\n");

my_class =class_create(THIS_MODULE,"hello_char_class");  //類名為hello_char_class
if(IS_ERR(my_class)) 
{
err = PTR_ERR(my_class);
printk("%s class_create failed!\n",__func__);
goto class_err;
}

dev = device_create(my_class,NULL,my_hello_dev->chrdev,NULL,"memdev%d",0);      //裝置名為memdev
if (IS_ERR(dev)) {
err = PTR_ERR(dev);
gyro_err("%s device_create failed!\n",__func__);
goto device_err;
}

printk("hello module initialization\n");
return 0;
 
device_err:
device_destroy(my_class, my_hello_dev->chrdev);
class_err:
cdev_del(my_hello_dev->chrdev);
cdev_add_err:
unregister_chrdev_region(my_hello_dev->chrdev, 1);
alloc_chrdev_err:
kfree(my_hello_dev);
return err;
}
 
static void __exit hello_exit (void)
{
cdev_del (&(my_hello_dev->cdev));
unregister_chrdev_region (my_hello_dev->chrdev,1);
device_destroy(my_class, devno);         //delete device node under /dev//必須先刪除裝置,再刪除class類
class_destroy(my_class);                 //delete class created by us
printk (KERN_INFO "char driver cleaned up\n");
}
 
module_init (hello_init);
module_exit (hello_exit);
 
MODULE_LICENSE ("GPL");

載入結果:

[[email protected] node]# insmod node.ko  
[[email protected] node]# dmesg | tail -3  
[23503.365316] create node success:  
[23503.365319]   ls -l /dev/noddev*  
[23503.365321]   ls -l /sys/class/noddev  
[[email protected] node]# ls -l /dev/noddev*  
crw------- 1 root root 66,  0 11月 26 15:02 /dev/noddev0  
crw------- 1 root root 66, 20 11月 26 15:02 /dev/noddev20  
[[email protected] node]# ls -l /sys/class/noddev  
總用量 0  
lrwxrwxrwx 1 root root 0 11月 26 15:02 noddev0 -> ../../devices/virtual/noddev/noddev0  
lrwxrwxrwx 1 root root 0 11月 26 15:02 noddev20 -> ../../devices/virtual/noddev/noddev20