标准字符驱动程序初始化步骤
1.通过alloc_chrdev_region()函数分配主/次设备号
2.使用cdev_init() 和cdev_add() 注册为字符设备驱动 (核心函数)
3. 使用class_create () 和device_create() 创建/sys 和/dev目录下的节点
详解:
1 .int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,
const char *name)
传入参数:
* @dev: output parameter for first assigned number
//传入的是指针,输出的是的一个分配到的主设备号
* @baseminor: first of the requested range of minor numbers
//第一个需要分配的次设备号
* @count: the number of minor numbers required
//需要分配多少个次设备号
* @name: the name of the associated device or driver
//设备名称(并不是创建在/dev目录下的名称,这里只是注册用的)
2.void cdev_init(struct cdev *cdev, const struct file_operations *fops)
功能:
初始化一个cdev 结构体(就是将一个cdev结构体和 文件操作集合联系)
传入参数:
struct cdev *cdev cdev结构体指针
const struct file_operations *fops 文件操作集合
PS: 第一个参数 可以由 cdev_alloc()获取
3.int cdev_add(struct cdev *p, dev_t dev, unsigned count)
功能 :添加一个字符设备到系统中(但是没有在/dev 创建节点 需要手动创建)
传入参数: struct cdev *p 需要添加的struct cdev (字符设备结构体指针)
dev_t dev : 设备号(就是第一个函数动态分配的)
unsigned count :需要添加的数目
4. class_create(owner, name)
功能 ; 创建一个struct class结构体
参数 :owner 这个结构体
作用 1.为这个设备在sys/提供接口
2.同时需要有struct class结构体 的指针才能调用device_create函数在/dev下面创建节点
5.struct device *device_create(struct class *class, struct device *parent,
dev_t devt, void *drvdata, const char *fmt, ...)
函数功能 : 这个函数能通过设备号 和struct class 在/dev下创建节点
传入的参数:struct class *class : class_create创建的class
struct device* parent : 设备的父节点
dev_t devt : 设备号
void *drvdata : 设备驱动数据
const char *fmt, ... :这个不定参数格式就是创建出来节点的名字