新字符设备驱动

分配和释放设备号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name)
int register_chrdev_region(dev_t from, unsigned count, const char *name)
void unregister_chrdev_region(dev_t from, unsigned count)

usage:
int major;
int minor;
dev_t devid;

if(major){
devid = MKDEV(major, minor);
register_chrdev_region(devid, 1, "test");
}else{
alloc_chrdev_region(&devid, 0, 1, "test");
major = MAJOR(devid);
minor = MINOR(devid);
}

unregister_chrdev_region(devid, 1);

新字符设备注册方法

1
2
3
4
# include/linux/cdev.h
void cdev_init(struct *cdev, const struct file_operations *fops)
int cdev_add(struct cdev *p, dev_t dev, unsigned count)
void cdev_del(struct cdev *p)

自动创建设备节点

不需要使用mknod命令
udev: linux下一个应用程序,用于设备文件的创建和删除,使用busybox构建跟文件系统时,会创建一个简化版的udev—->mdev,所以在rcS文件中存在以下语句:

1
echo /sbin/mdev > /proc/sys/kernel/hotplug

自动创建设备节点需要一个class类

1
2
3
4
5
6
7
8
9
10
11
# include/linux/device.h

#define class_create(owner, name)
({
static struct lock_class_ket __key;
__class_create(owner, name, &__key);
})

struct class *__class_create(struct module *owner, const char *name, struct lock_class_key *key)

void class_destroy(struct class *cls);

创建设备

1
2
3
4
5
6
struct device *device_create(struct class *class
struct device *parent,
dev_t devt,
void *drvdata,
const char *fmt, ...)
void device_destroy(struct class *class, dev_t devt)