系统相关
首页 > 系统相关> > linux的驱动开发——设备号

linux的驱动开发——设备号

作者:互联网

1.设备号的获取

\qquad 设备号的获取方法:自动分配;指定设备号注册

2.自动分配函数

\qquad 函数:int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name)
\qquad 功能:分配设备号
\qquad 参数:第一个参数:dev_t类型定义的变量,取地址传入;第二个参数:次设备号,次设备号自己指定;第三个参数:设备个数;第四个参数:名字
\qquad 返回值:成功返回0;失败返回负数错误码

int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name)
{
	struct char_device_struct *cd;
	cd = __register_chrdev_region(0, baseminor, count, name);
	if (IS_ERR(cd))
		return PTR_ERR(cd);
	*dev = MKDEV(cd->major, cd->baseminor);
	return 0;
}

3.指定设备号注册

\qquad 函数:int register_chrdev_region(dev_t from, unsigned count, const char *name)
\qquad 功能:指定设备号注册
\qquad 参数:第一个参数:设备号(MKDEV(major,minor));第二个参数:设备个数;第三个参数:名字
\qquad 返回值:成功返回0;失败返回负数错误码

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);
}

4.注销设备号

\qquad 函数:void unregister_chrdev_region(dev_t from, unsigned count)
\qquad 功能:注销设备号
\qquad 参数:第一个参数:设备号;第二个参数:设备个数
\qquad 返回值:void

void unregister_chrdev_region(dev_t from, unsigned count)
{
	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;
		kfree(__unregister_chrdev_region(MAJOR(n), MINOR(n), next - n));
	}
}

标签:qquad,region,dev,next,chrdev,linux,驱动,cd,设备
来源: https://blog.csdn.net/zxr916/article/details/110147320