1> 分配一个新的 char_device_struct 结构,并用 0 填充。
2> 如果申请的设备编号范围的主设备号为 0,那么表示设备驱动程序请求动态分配一个主设备号。动态分配主设备号的原则是从散列表的最后一个桶向前寻找,那个桶是空的,主设备号就是相应散列桶的序号。所以动态分配的主设备号总是小于 256,如果每个桶都有字符设备编号了,那动态分配就会失败。
3> 根据参数设置 char_device_struct 结构中的初始设备号,范围大小及设备驱动名称。
4> 计算出主设备号所对应的散列桶,为新的 char_device_struct 结构寻找正确的位置。同时,如果设备编号范围有重复的话,则出错返回。
5> 将新的 char_device_struct 结构插入散列表中,并返回 char_device_struct 结构的地址。
4.分析三个注册函数
1> register_chrdev_region()
186
187/**
188 * register_chrdev_region() - register a range of device numbers
189 * @from: the first in the desired range of device numbers; must include
190 * the major number.
191 * @count: the number of consecutive device numbers required
192 * @name: the name of the device or driver.
193 *
194 * Return value is zero on success, a negative error code on failure.
195 */
196int register_chrdev_region(dev_t from, unsigned count, const char *name)
197{
198 struct char_device_struct *cd;
199 dev_t to = from + count;
200 dev_t n, next;
201
202 for (n = from; n < to; n = next) {
203 next = MKDEV(MAJOR(n)+1, 0);
204 if (next > to)
205 next = to;
206 cd = __register_chrdev_region(MAJOR(n), MINOR(n),
207 next - n, name);
208 if (IS_ERR(cd))
209 goto fail;
210 }
211 return 0;
212fail:
213 to = n;
214 for (n = from; n < to; n = next) {
215 next = MKDEV(MAJOR(n)+1, 0);
216 kfree(__unregister_chrdev_region(MAJOR(n), MINOR(n), next - n));
217 }
218 return PTR_ERR(cd);
}
