|
在用 cdev_init() 函数对 cdev 结构体初始化后以及手动初始化了 cdev中的 owner 域和 file_operations 指针 ops 域后,就可以使用 cdev_add() 函数来将字符设备加入到内核中。
cdev_add() 函数的原型如下:
#include <linux/cdev.h>
int cdev_add(struct cdev *p, dev_t dev, unsigned count);
第 1 个参数为 cdev 结构体指针;
第 2 个参数为 dev_t 类型表达的设备号(dev_t 类型表达的设备号用 MKDEV(int major, int minor) 宏来实现) ;
第 3 个参数是设备号的数目。
一般的,count 的值为 1,但是有些情形也可能是大于 1 的数。比如 SCSI 磁带机,它通过给每个物理设备安排多个此设备号来允许用户在应用程序里选择操作模式(比如密度)。
cdev_add 如果失败了,那么返回一个负值,表明驱动无法加载到系统中。然而它一般情况下都会成功,一旦 cdev_add 返回,设备也就 “活” 了起来,于是所对应的操作方法(file_operations 结构里所定义的各种函数)也就能为内核所调用。
cdev_add() 函数的实现代码为:
/**
* cdev_add() - add a char device to the system
* @p: the cdev structure for the device
* @dev: the first device number for which this device is responsible
* @count: the number of consecutive minor numbers corresponding to this
* device
*
* cdev_add() adds the device represented by @p to the system, making it
* live immediately. A negative error code is returned on failure.
*/
int cdev_add(struct cdev *p, dev_t dev, unsigned count)
{
p->dev = dev;
p->count = count;
return kobj_map(cdev_map, dev, count, NULL, exact_match, exact_lock, p);
}
|
|