Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> 學習 Linux

Linux 核心 char_dev.c 逐段中文注解

Linux 核心 char_dev.c 逐段中文注解

字元裝置是 Linux 裝置模型裡最基礎的一塊,而 fs/char_dev.c 正是管理字元主號、次號與 cdev 結構的核心檔案。以下是我為這份原始碼加上注解的版本,內容僅代表個人理解,歡迎指正。

閱讀時可以先掌握幾個關鍵:主號(major)透過 major_to_index() 映射成 chrdevs 陣列的索引,同一索引底下以鏈表串起所有主號相同的註冊項;cdev_map 則是 kobj_map,負責在開啟裝置檔案時把 inode 的 rdev 對應回正確的 cdev;而 cdev 的釋放行為由 ktype 決定,動態配置的叫 ktype_cdev_dynamic(會 kfree),靜態初始化的叫 ktype_cdev_default(不釋放記憶體)。

 1 /*
 2 * linux/fs/char_dev.c
 3 *
 4 * Copyright (C) 1991, 1992 Linus Torvalds
 5 */
 6
 7 #include <linux/init.h>
 8 #include <linux/fs.h>
 9 #include <linux/kdev_t.h>
10 #include <linux/slab.h>
11 #include <linux/string.h>
12
13 #include <linux/major.h>
14 #include <linux/errno.h>
15 #include <linux/module.h>
16 #include <linux/smp_lock.h>
17 #include <linux/seq_file.h>
18
19 #include <linux/kobject.h>
20 #include <linux/kobj_map.h>
21 #include <linux/cdev.h>
22 #include <linux/mutex.h>
23 #include <linux/backing-dev.h>
24
25 #ifdef CONFIG_KMOD
26 #include <linux/kmod.h>
27 #endif
28 #include "internal.h"
29
30 /*
31 * capabilities for /dev/mem, /dev/kmem and similar directly mappable character
32 * devices
33 * - permits shared-mmap for read, write and/or exec
34 * - does not permit private mmap in NOMMU mode (can't do COW)
35 * - no readahead or I/O queue unplugging required
36 */
37
38 struct backing_dev_info directly_mappable_cdev_bdi = {
39   .capabilities = (
40 #ifdef CONFIG_MMU
41   /* permit private copies of the data to be taken */
42   BDI_CAP_MAP_COPY |
43 #endif
44   /* permit direct mmap, for read, write or exec */
45   BDI_CAP_MAP_DIRECT | BDI_CAP_READ_MAP | BDI_CAP_WRITE_MAP | BDI_CAP_EXEC_MAP),
46 };
47
48 static struct kobj_map *cdev_map;
49
50 static DEFINE_MUTEX(chrdevs_lock);
51
52 static struct char_device_struct {
53   struct char_device_struct *next;
54   unsigned int major;
55   unsigned int baseminor;
56   int minorct;
57   char name[64];
58   struct file_operations *fops;
59   struct cdev *cdev;
60   /* will die */
61 } *chrdevs[CHRDEV_MAJOR_HASH_SIZE];
62
63 /* index in the above */
64 static inline int major_to_index(int major)
65 {
66   /* [CGW]: 根據主設備號,轉換成對應的索引
67    * 即主設備號就是索引號
68    */
69   return major % CHRDEV_MAJOR_HASH_SIZE;
70 }
71
72 #ifdef CONFIG_PROC_FS
73
74 void chrdev_show(struct seq_file *f, off_t offset)
75 {
76   struct char_device_struct *cd;
77   /* [CGW]: 根據offset (相當於索引),找到對應設備 */
78   if (offset < CHRDEV_MAJOR_HASH_SIZE) {
79     /* [CGW]: 上鎖 */
80     mutex_lock(&chrdevs_lock);
81     /* [CGW]: 打印該設備項下鏈表中所有節點的主設備號,和設備名 */
82     for (cd = chrdevs[offset]; cd; cd = cd->next)
83       seq_printf(f, "%3d %s\n", cd->major, cd->name);
84     /* [CGW]: 解鎖 */
85     mutex_unlock(&chrdevs_lock);
86   }
87 }
88
89 #endif /* CONFIG_PROC_FS */
90
91 /*
92  * Register a single major with a specified minor range.
93  *
94  * If major == 0 this functions will dynamically allocate a major and return
95  * its number.
96  *
97  * If major > 0 this function will attempt to reserve the passed range of
98  * minors and will return zero on success.
99  *
100  * Returns a -ve errno on failure.
101  */
102
103 static struct char_device_struct *
104 __register_chrdev_region(unsigned int major, unsigned int baseminor,
105        int minorct, const char *name)
106
107 {
108   struct char_device_struct *cd, **cp;
109   int ret = 0;
110   int i;
111
112   /* [cgw]: 分配一塊char_device_struct大小的內存塊 */
113   cd = kzalloc(sizeof(struct char_device_struct), GFP_KERNEL);
114   /* [cgw]: 分配失敗 */
115   if (cd == NULL)
116     return ERR_PTR(-ENOMEM);
117   /*[cgw]: 上鎖,進入臨界區*/
118   mutex_lock(&chrdevs_lock);
119   /* temporary */
120   /*[cgw]: 如果主設備號為0,則從最大的設備號開始,往下查找第一個未被
121    * 注冊的設備
122    */
123   if (major == 0) {
124     /*[cgw]: 從大到小開始查找*/
125     for (i = ARRAY_SIZE(chrdevs)-1; i > 0; i--) {
126       /* [cgw]: 找到第一個未被注冊的設備 */
127       if (chrdevs[i] == NULL)
128         break;
129     }
130     /* [cgw]:未找到空位 */
131     if (i == 0) {
132       ret = -EBUSY;
133       goto out;
134     }
135     /* [cgw]: 以該空位的序號為主設備號 */
136     major = i;
137     ret = major;
138   }
139
140   /* [cgw]: 手工分配一個主設備號,和次設備號基址 */
141   cd->major = major;
142   /* [cgw]: 手工分配次設備號基址 */
143   cd->baseminor = baseminor;
144   /* [cgw]: 分配minorct個次設備號 */
145   cd->minorct = minorct;
146   /* [cgw]: 分配設備名 */
147   strncpy(cd->name,name, 64);
148   /* [cgw]: 找到主設備號在設備列表中的索引 */
149   i = major_to_index(major);
150   /* [cgw]: 當前分配的設備號比較設備列表,判斷該設備號是否
151    * 合法
152    */
153   for (cp = &chrdevs[i]; *cp; cp = &(*cp)->next)
154     /* [cgw]: 當前分配的主設備號,小於該主設備號索引對應的,設備列表
155      * 中的主設備號,合法
156      * 這個裡有點不解,從i = major_to_index(major);看出,主設備號和該主
157      * 設備號對應的索引是相等的,為什麼(*cp)->major > major是合法呢
158      */
159     if ((*cp)->major > major ||
160       /* [cgw]: 當前分配的主設備號,等於該主設備號索引對應的,設備列表
161        * 中的主設備號,並且符合以下條件之一,當前分配的次設備號,等於
162        * 小於該主設備號索引對應的,設備列表中的次設備號。或者,當前分
163        * 配的次設備號,小於該主設備號索引對應的,設備列表中的次設備基
164        * 址以後minorct個次設備號
165        */
166       ((*cp)->major == major &&
167       (((*cp)->baseminor >= baseminor) ||
168       ((*cp)->baseminor + (*cp)->minorct > baseminor))))
169     break;
170   /* Check for overlapping minor ranges. */
171   /* [cgw]: 當前分配的主設備號,等於該主設備號索引對應的,設備列表
172    * 中的主設備號,判斷次設備號是否在范圍內
173    */
174   if (*cp && (*cp)->major == major) {
175     int old_min = (*cp)->baseminor;
176     int old_max = (*cp)->baseminor + (*cp)->minorct - 1;
177     int new_min = baseminor;
178     int new_max = baseminor + minorct - 1;
179
180     /* New driver overlaps from the left. */
181     if (new_max >= old_min && new_max <= old_max) {
182       ret = -EBUSY;
183       goto out;
184     }
185
186     /* New driver overlaps from the right. */
187     if (new_min <= old_max && new_min >= old_min) {
188       ret = -EBUSY;
189       goto out;
190     }
191   }
192
193   /* [cgw]: 新加入的設備, 添加到該主設備號鏈表 */
194   cd->next = *cp;
195   /* [cgw]: 設備列表指針指向新加入設備*/
196   *cp = cd;
197   /* [cgw]: 解鎖,退出臨界區*/
198   mutex_unlock(&chrdevs_lock);
199   return cd;
200 out:
201
202   /* [cgw]: 解鎖,退出臨界區*/
203   mutex_unlock(&chrdevs_lock);
204   /* [cgw]: 釋放為新設備創建的內存*/
205   kfree(cd);
206   return ERR_PTR(ret);
207 }
208
209 static struct char_device_struct *
210 __unregister_chrdev_region(unsigned major, unsigned baseminor, int minorct)
211 {
212   struct char_device_struct *cd = NULL, **cp;
213   /* [CGW]: 根據主設備號,找出該主設備號所在列表中的索引*/
214   int i = major_to_index(major);
215   /* [CGW]: 上鎖,進入臨界區 */
216   mutex_lock(&chrdevs_lock);
217   /* [CGW]: 根據索引,找出該主設備號所在列表項 */
218   for (cp = &chrdevs[i]; *cp; cp = &(*cp)->next)
219     /* [CGW]:主設備號所在列表項中, 在主設備號對應的鏈表中,查找判斷該主設備號,
220      * 次設備號基址,次設備號個數是否已經被注冊
221      */
222     if ((*cp)->major == major &&
223       (*cp)->baseminor == baseminor &&
224       (*cp)->minorct == minorct)
225       /* [CGW]: 已經被注冊,停止查找 */
226       break;
227   /* [CGW]: 主設備號所在鏈表中的節點
228    * (注意: 設備列表中,每個設備號都對應一個鏈表,該鏈表用於存放此設備號)
229    */
230   if (*cp) {
231     /* [CGW]: 取出該節點 */
232     cd = *cp;
233     /* [CGW]: 更新cp,指向下一個節點*/
234     *cp = cd->next;
235   }
236
237   /* [CGW]: 解鎖,退出臨界區 */
238   mutex_unlock(&chrdevs_lock);
239   /* [CGW]: 返回該設備(節點) */
240   return cd;
241 }
242
243 /**
244  * register_chrdev_region() - register a range of device numbers
245  * @from: the first in the desired range of device numbers; must include
246  * the major number.
247  * @count: the number of consecutive device numbers required
248  * @name: the name of the device or driver.
249  *
250  * Return value is zero on success, a negative error code on failure.
251  */
252
253 int register_chrdev_region(dev_t from, unsigned count, const char *name)
254 {
255   struct char_device_struct *cd;
256   dev_t to = from + count;
257   dev_t n, next;
258   /* [CGW]: 分配count個連續的設備 */
259   for (n = from; n < to; n = next) {
260     /* [CGW]: 主設備號+1遞增 */
261     next = MKDEV(MAJOR(n)+1, 0);
262     if (next > to)
263       next = to;
264     /* [CGW]: 根據主、次設備號基址,分配next - n個連續次設備號的設備,
265      * 並根據主設備號分配設備名
266      * 如果MINOR(n)為0,next-n的值應恆為256,未驗證!!!
267      */
268     cd = __register_chrdev_region(MAJOR(n), MINOR(n), next - n, name);
269     /* [CGW]: 分配失敗 */
270     if (IS_ERR(cd))
271       goto fail;
272   }
273   return 0;
274
275 fail:
276   /* [CGW]: 當前分配到了第n個設備就失敗了*/
277   to = n;
278   /* [CGW]: 注銷剛剛分配的所有設備 */
279   for (n = from; n < to; n = next) {
280     next = MKDEV(MAJOR(n)+1, 0);
281     /* [CGW]: 對應的內存空間 */
282     kfree(__unregister_chrdev_region(MAJOR(n), MINOR(n), next - n));
283   }
284   /* [CGW]: 返回這個分配失敗的設備指針 */
285   return PTR_ERR(cd);
286 }
287
288 /**
289  * alloc_chrdev_region() - register a range of char device numbers
290  * @dev: output parameter for first assigned number
291  * @baseminor: first of the requested range of minor numbers
292  * @count: the number of minor numbers required
293  * @name: the name of the associated device or driver
294  *
295  * Allocates a range of char device numbers. The major number will be
296  * chosen dynamically, and returned (along with the first minor number)
297  * in @dev. Returns zero or a negative error code.
298  */
299 int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,
300 const char *name)
301 {
302   struct char_device_struct *cd;
303   /* [CGW]: 自動分配一個設備,因為主設備號為0
304    * 以baseminor為基址,分配count個次設備號
305    */
306   cd = __register_chrdev_region(0, baseminor, count, name);
307   /* [CGW]: 分配失敗 */
308   if (IS_ERR(cd))
309     return PTR_ERR(cd);
310   /* [CGW]: 返回設備號 */
311   *dev = MKDEV(cd->major, cd->baseminor);
312   return 0;
313 }
314
315 /**
316  * register_chrdev() - Register a major number for character devices.
317  * @major: major device number or 0 for dynamic allocation
318  * @name: name of this range of devices
319  * @fops: file operations associated with this devices
320  *
321  * If @major == 0 this functions will dynamically allocate a major and return
322  * its number.
323  *
324  * If @major > 0 this function will attempt to reserve a device with the given
325  * major number and will return zero on success.
326  *
327  * Returns a -ve errno on failure.
328  *
329  * The name of this device has nothing to do with the name of the device in
330  * /dev. It only helps to keep track of the different owners of devices. If
331  * your module name has only one type of devices it's ok to use e.g. the name
332  * of the module here.
333  *
334  * This function registers a range of 256 minor numbers. The first minor number
335  * is 0.
336  */
337
338 int register_chrdev(unsigned int major, const char *name,
339 const struct file_operations *fops)
340 {
341   struct char_device_struct *cd;
342   struct cdev *cdev;
343   char *s;
344   int err = -ENOMEM;
345
346   /* [cgw]: 分配一個設備,次設備號為0~255 */
347   cd = __register_chrdev_region(major, 0, 256, name);
348   if (IS_ERR(cd))
349     return PTR_ERR(cd);
350   /* [cgw]:分配一個cdev結構體 */
351   cdev = cdev_alloc();
352   if (!cdev)
353     goto out2;
354
355   cdev->owner = fops->owner;
356   cdev->ops = fops;
357
358   /* [cgw]: 設置kobject的名字 */
359   kobject_set_name(&cdev->kobj, "%s", name);
360   /* [cgw]: 把kobject的名字kobj->name中的'/'替換成'!' */
361   for (s = strchr(kobject_name(&cdev->kobj),'/'); s; s = strchr(s, '/'))
362     *s = '!';
363
364   /* [cgw]: 添加一個字符設備到系統*/
365   err = cdev_add(cdev, MKDEV(cd->major, 0), 256);
366   if (err)
367     goto out;
368
369   /* [cgw]: 設置char_device_struct中的cdev指針 */
370   cd->cdev = cdev;
371
372   return major ? 0 : cd->major;
373
374 out:
375   /* [cgw]: kobect 引用計數-1 */
376   kobject_put(&cdev->kobj);
377
378 out2:
379   /* [cgw]: 釋放剛注冊的設備 */
380   kfree(__unregister_chrdev_region(cd->major, 0, 256));
381   return err;
382 }
383
384 /**
385  * unregister_chrdev_region() - return a range of device numbers
386  * @from: the first in the range of numbers to unregister
387  * @count: the number of device numbers to unregister
388  *
389  * This function will unregister a range of @count device numbers,
390  * starting with @from. The caller should normally be the one who
391  * allocated those numbers in the first place...
392  */
393
394 void unregister_chrdev_region(dev_t from, unsigned count)
395 {
396   dev_t to = from + count;
397   dev_t n, next;
398
399   /* [CGW]: 注銷所有從from到to的count個設備 */
400   for (n = from; n < to; n = next) {
401     /* [CGW]: 查找下一設備號*/
402     next = MKDEV(MAJOR(n)+1, 0);
403     if (next > to)
404       next = to;
405     /* [CGW]: 注銷所有剛才注冊的設備 */
406     kfree(__unregister_chrdev_region(MAJOR(n), MINOR(n), next - n));
407   }
408 }
409
410 int unregister_chrdev(unsigned int major, const char *name)
411 {
412   struct char_device_struct *cd;
413   /* [CGW]: 根據主設備號,找到對應設備列表項 */
414   cd = __unregister_chrdev_region(major, 0, 256);
415   /* [CGW]: 該設備項有效,並且被注冊 */
416   if (cd && cd->cdev)
417     /* [CGW]: 注銷該設備 */
418     cdev_del(cd->cdev);
419   /* [CGW]: 釋放該設備占用的內存空間 */
420   kfree(cd);
421
422   return 0;
423 }
424
425 static DEFINE_SPINLOCK(cdev_lock);
426
427 static struct kobject *cdev_get(struct cdev *p)
428 {
429   struct module *owner = p->owner;
430   struct kobject *kobj;
431
432   /* [cgw]:cdev_get uses try_module_get to attempt to increment that module's
433    * usage count. If that operation succeeds, kobject_get is used to increment
434    * the kobject's reference count as well---<Linux Device Drivers>
435    * try_module_get(owner)增加owner (THIS_MODULE)引用計數
436    */
437   /* [cgw]: module使用計數+1 */
438   if (owner && !try_module_get(owner))
439     return NULL;
440   /* [cgw]: kobj引用計數+1 */
441   kobj = kobject_get(&p->kobj);
442   /* [cgw]: kobj指針返回失敗 */
443   if (!kobj)
444     /* [cgw]: module使用計數-1 */
445     module_put(owner);
446
447   return kobj;
448 }
449
450 void cdev_put(struct cdev *p)
451 {
452   /* [cgw]: cdev指針不為空 */
453   if (p) {
454     /* [cgw]: 獲得模塊指針 */
455     struct module *owner = p->owner;
456     /* [cgw]: kobj引用計數-1 */
457     kobject_put(&p->kobj);
458     /* [cgw]: module使用計數-1 */
459     module_put(owner);
460   }
461 }
462
463 /*
464  * Called every time a character special file is opened
465  */
466 int chrdev_open(struct inode * inode, struct file * filp)
467 {
468   struct cdev *p;
469   struct cdev *new = NULL;
470   int ret = 0;
471
472   /* [cgw]: 進入臨界區 */
473   spin_lock(&cdev_lock);
474   /* [cgw]: 從inode中得到一個字符設備cdev指針 */
475   p = inode->i_cdev;
476   /* [cgw]: struct cdev指針為空 */
477   if (!p) {
478     struct kobject *kobj;
479     int idx;
480     /* [cgw]: 進入臨界區 */
481     spin_unlock(&cdev_lock);
482     /* [cgw]: 看看cdev_map的probes[inode->i_rdev]鏈表是否有inode->i_rdev這個設備
483      * 並返回這個設備的kobj
484      */
485     kobj = kobj_lookup(cdev_map, inode->i_rdev, &idx);
486     /* [cgw]: kobj為空,錯誤 */
487     if (!kobj)
488       return -ENXIO;
489     /* [cgw]: 根據返回的kobj,找出包含這個kobj的struct cdev指針 */
490     new = container_of(kobj, struct cdev, kobj);
491     /* [cgw]: 進入臨界區 */
492     spin_lock(&cdev_lock);
493     /* [cgw]: 從inode中得到一個字符設備cdev指針 */
494     p = inode->i_cdev;
495     /* [cgw]: struct cdev指針為空 */
496     if (!p) {
497       /* [cgw]: 把這個struct cdev指針填裝到inode->i_cdev */
498       inode->i_cdev = p = new;
499       /* [cgw]: 記錄對應的索引 */
500       inode->i_cindex = idx;
501       /* [cgw]: 把inode->i_devices插入到p->list */
502       list_add(&inode->i_devices, &p->list);
503       /* [cgw]: 清除new指針 */
504       new = NULL;
505       /* [cgw]: 返回cdev中kobj指針為空,錯誤 */
506     } else if (!cdev_get(p))
507       ret = -ENXIO;
508   /* [cgw]: 返回cdev中kobj指針為空,錯誤 */
509   } else if (!cdev_get(p))
510     ret = -ENXIO;
511   /* [cgw]: 退出臨界區 */
512   spin_unlock(&cdev_lock);
513   /* [cgw]: 實際上是cdev->kobj引用計數-1,module使用計數-1 */
514   cdev_put(new);
515   if (ret)
516     return ret;
517   /* [cgw]: module使用計數+1,並返回cdev->ops指針 */
518   filp->f_op = fops_get(p->ops);
519   /* [cgw]: filp->f_op指針為空,失敗 */
520   if (!filp->f_op) {
521     /* [cgw]: 實際上是cdev->kobj引用計數-1,module使用計數-1 */
522     cdev_put(p);
523     return -ENXIO;
524   }
525   /* [cgw]: 調用filp->f_op->open,打開的是用戶驅動程序中定義的
526    * file_operations中的open函數
527    */
528   if (filp->f_op->open) {
529     /* [cgw]: 上鎖 */
530     lock_kernel();
531     /* [cgw]: 調用filp->f_op->open */
532     ret = filp->f_op->open(inode,filp);
533     /* [cgw]: 解鎖 */
534     unlock_kernel();
535   }
536   /* [cgw]: 調用filp->f_op->open失敗 */
537   if (ret)
538     /* [cgw]: 實際上是cdev->kobj引用計數-1,module使用計數-1 */
539     cdev_put(p);
540
541   return ret;
542 }
543
544 void cd_forget(struct inode *inode)
545 {
546   /* [cgw]: 進入臨界區 */
547   spin_lock(&cdev_lock);
548   /* [cgw]: 從鏈表刪除一個inode->i_devices節點,
549    * 並重新初始化這個鏈表
550    */
551   list_del_init(&inode->i_devices);
552   /* [cgw]: inode->i_cdev指針清0 */
553   inode->i_cdev = NULL;
554   /* [cgw]: 退出臨界區 */
555   spin_unlock(&cdev_lock);
556 }
557
558 static void cdev_purge(struct cdev *cdev)
559 {
560   /* [cgw]: 進入臨界區 */
561   spin_lock(&cdev_lock);
562   /* [cgw]: 測試cdev->list這個鏈表是否為空 */
563   while (!list_empty(&cdev->list)) {
564     struct inode *inode;
565     /* [cgw]: 找出包含cdev->list的struct inode結構體的指針 */
566     inode = container_of(cdev->list.next, struct inode, i_devices);
567     /* [cgw]: 從鏈表刪除一個inode->i_devices節點,
568      * 並重新初始化這個鏈表
569      */
570     list_del_init(&inode->i_devices);
571     /* [cgw]: inode->i_cdev指針清0 */
572     inode->i_cdev = NULL;
573   }
574   /* [cgw]: 退出臨界區 */
575   spin_unlock(&cdev_lock);
576 }
577
578 /*
579  * Dummy default file-operations: the only thing this does
580  * is contain the open that then fills in the correct operations
581  * depending on the special file...
582  */
583
584 const struct file_operations def_chr_fops = {
585   .open = chrdev_open,
586 };
587
588 static struct kobject *exact_match(dev_t dev, int *part, void *data)
589 {
590   struct cdev *p = data;
591   /* [cgw]: 返回cdev中kobj成員指針 */
592   return &p->kobj;
593 }
594
595 static int exact_lock(dev_t dev, void *data)
596 {
597   struct cdev *p = data;
598   /* [cgw]: data中kobj引用計數+1,並返回kobj指針 */
599   return cdev_get(p) ? 0 : -1;
600 }
601
602 /**
603  * cdev_add() - add a char device to the system
604  * @p: the cdev structure for the device
605  * @dev: the first device number for which this device is responsible
606  * @count: the number of consecutive minor numbers corresponding to this
607  * device
608  *
609  * cdev_add() adds the device represented by @p to the system, making it
610  * live immediately. A negative error code is returned on failure.
611  */
612
613 int cdev_add(struct cdev *p, dev_t dev, unsigned count)
614 {
615   /* [cgw]: 分配一個dev設備號給p->dev */
616   p->dev = dev;
617   /* [cgw]: 分配count個連續的次設備號
618    * 這裡實際是分配count設備,只是次設備號不一樣,主設備號都一樣
619    */
620   p->count = count;
621   /* [cgw]: 把新加入的設備填裝到一個probe結構,並把這個probe插入到
622    * 對應probes[MAJOR(dev)]鏈表,即probes[]中每一個元素都是一個鏈表
623    */
624   return kobj_map(cdev_map, dev, count, NULL, exact_match, exact_lock, p);
625 }
626
627 static void cdev_unmap(dev_t dev, unsigned count)
628 {
629   /* [cgw]: 從probes[MAJOR(dev)]鏈表中刪除一個節點(probe) */
630   kobj_unmap(cdev_map, dev, count);
631 }
632
633 /**
634  * cdev_del() - remove a cdev from the system
635  * @p: the cdev structure to be removed
636  *
637  * cdev_del() removes @p from the system, possibly freeing the structure
638  * itself.
639  */
640
641 void cdev_del(struct cdev *p)
642 {
643   /* [cgw]: 從probes[MAJOR(p->dev)]鏈表中刪除一個節點(probe) */
644   cdev_unmap(p->dev, p->count);
645   /* [cgw]: kobj引用計數-1 */
646   kobject_put(&p->kobj);
647 }
648
649 static void cdev_default_release(struct kobject *kobj)
650 {
651   /* [cgw]: 找到包含kobj的結構體struct cdev的指針 */
652   struct cdev *p = container_of(kobj, struct cdev, kobj);
653   /* [cgw]: 從cdev->list鏈表中刪除cdev */
654   cdev_purge(p);
655 }
656
657 static void cdev_dynamic_release(struct kobject *kobj)
658 {
659   /* [cgw]: 找到包含kobj的結構體struct cdev的指針 */
660   struct cdev *p = container_of(kobj, struct cdev, kobj);
661   /* [cgw]: 從cdev->list鏈表中刪除cdev */
662   cdev_purge(p);
663   /* [cgw]: 釋放這個cdev的內存空間 */
664   kfree(p);
665 }
666
667 static struct kobj_type ktype_cdev_default = {
668   .release = cdev_default_release,
669 };
670
671 static struct kobj_type ktype_cdev_dynamic = {
672   .release = cdev_dynamic_release,
673 };
674
675 /**
676  * cdev_alloc() - allocate a cdev structure
677  *
678  * Allocates and returns a cdev structure, or NULL on failure.
679  */
680
681 struct cdev *cdev_alloc(void)
682 {
683   /* [cgw]: 分配一個cdev結構體 */
684   struct cdev *p = kzalloc(sizeof(struct cdev), GFP_KERNEL);
685
686   /* [cgw]: 分配cdev結構體成功 */
687   if (p) {
688     /* [cgw]: 分配一個kobj.ktype結構體,指向&ktype_cdev_dynamic
689      * 為這個驅動制定一個統一的行為,提供釋放kobj的方法
690      */
691     p->kobj.ktype = &ktype_cdev_dynamic;
692     /* [cgw]: 初始化鏈表,把這個cdev插入鏈表頭 */
693     INIT_LIST_HEAD(&p->list);
694     /* [cgw]: 初始化kobject,每個對象都有一個kobject */
695     kobject_init(&p->kobj);
696   }
697   return p;
698 }
699
700 /**
701  * cdev_init() - initialize a cdev structure
702  * @cdev: the structure to initialize
703  * @fops: the file_operations for this device
704  *
705  * Initializes @cdev, remembering @fops, making it ready to add to the
706  * system with cdev_add().
707  */
708
709 void cdev_init(struct cdev *cdev, const struct file_operations *fops)
710 {
711   /* [cgw]: cdev結構體清零 */
712   memset(cdev, 0, sizeof *cdev);
713   /* [cgw]: 初始化鏈表,把這個cdev插入鏈表頭 */
714   INIT_LIST_HEAD(&cdev->list);
715   /* [cgw]: 分配一個kobj.ktype結構體,指向&ktype_cdev_default
716    * 為這個驅動制定一個默認的統一的行為,提供恢復默認kobj的方法
717    * 沒有釋放kobj內存空間
718    */
719   cdev->kobj.ktype = &ktype_cdev_default;
720   /* [cgw]: 初始化kobject,每個對象都有一個kobject */
721   kobject_init(&cdev->kobj);
722   /* [cgw]: cdev->ops指向驅動程序中的file_operations結構體 */
723   cdev->ops = fops;
724 }
725
726 static struct kobject *base_probe(dev_t dev, int *part, void *data)
727 {
728   if (request_module("char-major-%d-%d", MAJOR(dev), MINOR(dev)) > 0)
729     /* Make old-style 2.4 aliases work */
730     request_module("char-major-%d", MAJOR(dev));
731   return NULL;
732 }
733
734 void __init chrdev_init(void)
735 {
736   /*[cgw]: 初始化cdev_map變量 */
737   cdev_map = kobj_map_init(base_probe, &chrdevs_lock);
738 }
739
740 /* Let modules do char dev stuff */
741 EXPORT_SYMBOL(register_chrdev_region);
742 EXPORT_SYMBOL(unregister_chrdev_region);
743 EXPORT_SYMBOL(alloc_chrdev_region);
744 EXPORT_SYMBOL(cdev_init);
745 EXPORT_SYMBOL(cdev_alloc);
746 EXPORT_SYMBOL(cdev_del);
747 EXPORT_SYMBOL(cdev_add);
748 EXPORT_SYMBOL(register_chrdev);
749 EXPORT_SYMBOL(unregister_chrdev);
750 EXPORT_SYMBOL(directly_mappable_cdev_bdi);

讀完這份程式碼,可以發現整個字元裝置架構其實就三件事:用 chrdevs 陣列管理主號的註冊與回收、用 cdev_map 做 rdev 到 cdev 的快速查找、用引用計數(kobject 與 module 各一層)確保裝置被開啟時驅動不會被卸載。理解這三點,再看 chrdev_open() 那段看似繁瑣的雙重檢查,就順了。

Copyright © Linux教程網 All Rights Reserved