Linux驱动程序字符设备注册我一直采用的是register_chrdev,但是最近在学校设备驱动开发详解的时候,看那里面的字符设备注册都是采用register_chrdev_region,好像是比较新的用法,之前没用过,现在学习到了,也就换了试试。
下面将字符设备注册用到的相关知识进行归纳:
cdev结构体
struct cdev {
struct kobject kobj;
struct module *owner;
const struct file_operations -*ops;
struct list_head list;
dev_t dev; //设备号
unsigned int count;
};
dev_t成员定义了设备号,用MAJOR(dev_t dev)、MINOR(dev_t dev)分别获得主设备号和从设备号。使用MKDEV(int major,int minor)生成dev_t。
相关函数:
1、cdev_alloc():动态申请一个cdev内存。
/**
* cdev_alloc() - allocate a cdev structure
*
* Allocates and returns a cdev structure, or NULL on failure.
*/
struct cdev *cdev_alloc(void)
{
struct cdev *p = kzalloc(sizeof(struct cdev), GFP_KERNEL);
if (p) {
p->kobj.ktype = &ktype_cdev_dynamic;
INIT_LIST_HEAD(&p->list);
kobject_init(&p->kobj);
}
}
2、cdev_init()初始化cdev成员,建立cdevhe file_operation间的连接。
/**
* cdev_init() - initialize a cdev structure
* @cdev: the structure to initialize
* @fops: the file_operations for this device
*
* Initializes @cdev, remembering @fops, making it ready to add to the
* system with cdev_add().
*/
void cdev_init(struct cdev *cdev, const struct file_operations *fops)
{
memset(cdev, 0, sizeof *cdev);
INIT_LIST_HEAD(&cdev->list);
cdev->kobj.ktype = &ktype_cdev_default;
kobject_init(&cdev->kobj);
cdev->ops = fops;
}
3、cdev_add():向系统添加一个cdev
4、cdev_del():向系统删除一个cdev
5、int register_chrdev_region(dev_t devno,unsigned count,const char *name);
分配设备号,即向系统注册注册一个字符设备。
int alloc_chrdev_region(dev_t *dev,unsigned baseminor,unsigned count,const char *name);自动分配设备号。
6、void unregister_chrdev_region(dev_t devno,unsigned count);释放设备号。
阅读(3038) | 评论(0) | 转发(0) |