register_chrdev_region函数解析

来源:互联网 发布:产品经理数据分析手册 编辑:程序博客网 时间:2024/09/21 08:15
int register_chrdev_region(dev_t from, unsigned count, const char *name);
此函数主要是进行手动分配设备号
参数1:from为设备号,包含已经存在的主设备号和次设备号
参数2:count为要申请设备号的个数

参数3:name为驱动的名称

/** * register_chrdev_region() - register a range of device numbers * @from: the first in the desired range of device numbers; must include *        the major number. * @count: the number of consecutive device numbers required * @name: the name of the device or driver. * * Return value is zero on success, a negative error code on failure. */int register_chrdev_region(dev_t from, unsigned count, const char *name){struct char_device_struct *cd;dev_t to = from + count;dev_t n, next;for (n = from; n < to; n = next) {next = MKDEV(MAJOR(n)+1, 0);if (next > to)next = to;cd = __register_chrdev_region(MAJOR(n), MINOR(n),next - n, name);if (IS_ERR(cd))goto fail;}return 0;fail:to = n;for (n = from; n < to; n = next) {next = MKDEV(MAJOR(n)+1, 0);kfree(__unregister_chrdev_region(MAJOR(n), MINOR(n), next - n));}return PTR_ERR(cd);}


第一行:定义了一个struct char_device_struct类型的结构体,内容如下:

static struct char_device_struct {struct char_device_struct *next;/*指向下一个此类型的指针*/unsigned int major;/*主设备号*/unsigned int baseminor;/*次设备号*/int minorct; /*申请设备号的个数*/char name[64];/*驱动名称*/struct cdev *cdev;/* 字符驱动结构体 */}

第二行:dev_t为32位的,前12位保存主设备号,后20位保存次设备号,to保存为"当前设备号 + 次设备个数 = 总设备号"
第三行:定义n,作为整个函数使用过程的中间变量,next也为中间变量,但同时也作为设备号的下一设备号
第四行:一个for循环,循环的每个状态为设备号,并且循环开始的第一个设备号为from
第五行:MAJOR是获取主设备,MKDEV是组合成设备号,下一个设备号状态 = ((当前主设备号+1),次设备号0)的组合
第六行:if语句,判断下一状态是否大于最后的末状态
第七行:如果下一状态大于最后的末状态,则将末状态变为下一状态
第八行:申请设备号,参数1为主设备号,参数2为次设备号,参数3为要申请次设备的个数,参数4为设备名称
第九行:如果申请失败
第十行:跳转到fail
fail:
第一行:将当前的设备号赋值给to
第二行:for循环,从from->n
第三行:下一设备号的组合
第四行:把申请的设备号全部销了

最后返回一个值


(注:在手动分配设备号时,需要传入from这个32位数,因为是手动分配,就有可能会出现重复的错误,所以,我觉的在手动分配之前,需要知道确切的初始值,不然感觉会很容易出错)

原创粉丝点击