新的字符设备驱动

(1)分配设备号 

  使用register_chrdev注册字符设备需要事先给定主设备号,因此我们需要先确定哪些主设备号没有使用,并且分配一个主设备号将会使用下面所有的2^20的次设备号。alloc_chrdev_region 和register_chrdev_region提供一种自动分配设备号的方式。

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)

使用unregister_chrdev_region()函数进行释放设备号

 

(2)注册字符设备

字符设备结构在include/linux/cdev.h 文件

struct cdev {
    struct kobject kobj;
    struct module *owner;
    const struct file_operations *ops;
    struct list_head list;
    dev_t dev;
    unsigned int count;
};

定义一个字符设备

struct cdev my_cdev;

使用cdev_init 函数对其进行初始化

void cdev_init(struct cdev *cdev, const struct file_operations *fops)
int cdev_add(struct cdev *p, dev_t dev, unsigned count)

使用 cdev_add 函数添加字符设备,cdev_del 函数从 Linux 内核中删除相应的字符设备。

void cdev_del(struct cdev *p)

cdev_del unregister_chrdev_region 这两个函数合起来的功能相当于 unregister_chrdev 函数。

(3)自动创建设备节点

在modprobe或者insmod加载驱动程序后,还需要使用mknod手动创建设备节点,可以通过mdev来实现自动创建设备节点。
  (a)创建类

struct class *class_create (struct module *owner, const char *name)

  class_create 一共有两个参数,参数 owner 一般为 THIS_MODULE,参数 name 是类名字。返回值是个指向结构体 class 的指针,也就是创建的类。
  删除类

void class_destroy(struct class *cls);

  (b)创建设备

  device_create 函数在类下面创建设备。

struct device *device_create(struct class *class, struct device parent, dev_t devt, void *drvdata, const char *fmt, ...)

device_create 是个可变参数函数,参数 class 就是设备要创建哪个类下面;参数 parent 是父设备,一般为 NULL,也就是没有父设备;参数 devt 是设备号;参数 drvdata 是设备可能会使用的一些数据,一般为 NULL;参数 fmt 是设备名字,如果设置 fmt=xxx 的话,就会生成/dev/xxx这个设备文件。返回值就是创建好的设备。
  删除设备

void device_destroy(struct class *class, dev_t devt)

 




 

posted @ 2020-12-08 13:16  11YS  阅读(93)  评论(0)    收藏  举报