本文章主要参考Linux设备驱动开发详情这本书。
字符设备
在Linux内核中,使用cdev结构体描述一个字符设备,cdev结构体的定义如下代码清单。
struct cdev {
//字符设备对应的kobj
struct kobject kobj;
struct module *owner;
//字符设备对应的文件操作集
const struct file_operations *ops;
//节点,所有的cdev都会链在一个链表里
struct list_head list;
//设备号
dev_t dev;
//次设备号个数
unsigned int count;
};
cdev结构体的dev成员定义了设备号,为32位,其中高12位为主设备号,低20位为次设备号。使用下列宏可以从dev_t获得主设备号和次设备号。
MAJOR(dev_t dev) //获得主设备号
MINOR(dev_t dev) //获得次设备号
而使用下列宏则可以通过主设备号和次设备号生成dev_t:
MKDEV(int major, int minor)
分配和释放设备号
在建立一个字符设备之前,我们的驱动程序首先要做的事情就是申请一个或者多个设备号。完成该工作的必要函数是register_chrdev_region或alloc_chrdev_region。
int register_chrdev_region(dev_t from, unsigned count, const char *name);
int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,
const char *name);
register_chrdev_region函数用于已知起始设备的设备号的情况,而alloc_chrdev_region用于设备号未知,向系统动态申请未被占用的设备号的情况,函数调用成功之后,会把得到的设备号放入第一个参数dev中。alloc_chrdev_region相比于register_chrdev_region的优点在于它会自动避开设备号重复的冲突。
相应地,在调用cdev_del函数从系统注销字符设备之后,unregister_chrdev_region应该被调用以释放原先申请的设备号,这个函数的原型为:
void unregister_chrdev_region(dev_t from, unsigned count);
文件操作file_operations结构体
file_operations结构体中的成员函数是字符设备驱动程序设计的主体内容,这些函数实际会在应用程序进行Linux的open、write、read、close等系统调用时最终被内核调用。
结构体如下代码清单所示:
struct file_operations {
struct module *owner;
//llseek函数用来修改一个文件的当前读写位置,并将新位置返回,在出错时,这个函数返回一个负值
loff_t (*llseek) (struct file *, loff_t, int);
//read函数用来从设备中读取数据,成功时函数返回读取的字节数,出错时返回一个负值
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
//write函数向设备发送数据,成功时该函数返回写入的字节数
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
int (*iterate) (struct file *, struct dir_context *);
int (*iterate_shared) (struct file *, struct dir_context *);
/*poll函数一般用于询问设备是否可被非阻塞地立即读写
当询问的条件未触发时,用户空间进行select和poll系统调用将引起进程的阻塞*/
unsigned int (*poll) (struct file *, struct poll_table_struct *);
//unlocked_ioctl提供设备相关控制命令的实现
long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
//mmap函数将设备内存映射到进程的虚拟地址空间中
int (*mmap) (struct file *, struct vm_area_struct *);
//当用户空间调用Linux API函数open打开设备文件时,设备驱动的open函数最终被调用
int (*open) (struct inode *, struct file *);
int (*flush) (struct file *, fl_owner_t id);
int (*release) (struct inode *, struct file *);
int (*fsync) (struct file *, loff_t, loff_t, int datasync);
int (*fasync) (int, struct file *, int);
int (*lock) (struct file *, int, struct file_lock *);
ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
int (*check_flags)(int);
int (*flock) (struct file *, int, struct file_lock *);
ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
int (*setlease)(struct file *, long, struct file_lock **, void **);
long (*fallocate)(struct file *file, int mode, loff_t offset,
loff_t len);
void (*show_fdinfo)(struct seq_file *m, struct file *f);
#ifndef CONFIG_MMU
unsigned (*mmap_capabilities)(struct file *);
#endif
ssize_t (*copy_file_range)(struct file *, loff_t, struct file *,
loff_t, size_t, unsigned int);
int (*clone_file_range)(struct file *, loff_t, struct file *, loff_t,
u64);
ssize_t (*dedupe_file_range)(struct file *, u64, u64, struct file *,
u64);
};
linux字符设备驱动的组成
1.字符设备驱动模块加载与卸载函数
在字符设备驱动模块加载函数中应该实现设备号的申请和cdev的注册,而在卸载函数中应实现设备号的释放和cdev的注销。
Linux内核的编码习惯是为设备定义一个设备相关的结构体,该结构体包含设备所涉及的cdev、私有数据及锁等信息。常见的设备结构体、模块加载和卸载函数形式如下代码清单所示。
//* 设备结构体 */
struct xxx_dev_t {
struct cdev cdev;
...
} xxx_dev;
/* 设备驱动模块加载函数 */
static int _ _init xxx_init(void)
{
...
cdev_init(&xxx_dev.cdev, &xxx_fops); /* 初始化 cdev */
xxx_dev.cdev.owner = THIS_MODULE;
/* 获取字符设备号*/
if (xxx_major) {
register_chrdev_region(xxx_dev_no, 1, DEV_NAME);
} else {
alloc_chrdev_region(&xxx_dev_no, 0, 1, DEV_NAME);
}
ret = cdev_add(&xxx_dev.cdev, xxx_dev_no, 1); /* 注册设备*/
...
}
/*设备驱动模块卸载函数*/
static void _ _exit xxx_exit(void)
{
unregister_chrdev_region(xxx_dev_no, 1); /* 释放占用的设备号*/
cdev_del(&xxx_dev.cdev); /* 注销设备*/
...
}
2.字符设备驱动的file_operations结构体中的成员函数
file_operations结构体中的成员函数是字符设备驱动与内核虚拟文件系统的接口,是用户空间对Linux进行系统调用最终的落实者。大多数字符设备驱动会实现read()、write()和ioctl()函数,常见的字符设备驱动的这3个函数的形式如下代码清单所示。
/* 读设备*/
ssize_t xxx_read(struct file *filp, char __user *buf, size_t count,
loff_t*f_pos)
{
...
copy_to_user(buf, ..., ...);
...
}
/* 写设备*/
ssize_t xxx_write(struct file *filp, const char __user *buf, size_t count,
loff_t *f_pos)
{
...
copy_from_user(..., buf, ...);
...
}
/* ioctl 函数 */
int xxx_ioctl(struct inode *inode, struct file *filp, unsigned int cmd,
unsigned long arg)
{
...
switch (cmd) {
case XXX_CMD1:
...
break;
case XXX_CMD2:
...
break;
default:
/* 不能支持的命令 */
return - ENOTTY;
}
return 0;
}
设备驱动的读函数中,filp是文件结构体指针,buf是用户空间内存的地址,该地址在内核空间不能直接读写,count 是要读的字节数,f_pos 是读的位置相对于文件开头的偏移。
设备驱动的写函数中,filp是文件结构体指针,buf是用户空间内存的地址,该地址在内核空 间不能直接读写,count 是要写的字节数,f_pos 是写的位置相对于文件开头的偏移。
由于内核空间与用户空间的内存不能直接互访,因此借助了函数 copy_from_user()完成用户空间到内核空间的拷贝,以及copy_to_user()完成内核空间到用户空间的拷贝。
完成内核空间和用户空间内存拷贝的 copy_from_user()和 copy_to_user()的原型分别为:
unsigned long copy_from_user(void *to, const void _ _user *from, unsigned long count);
unsigned long copy_to_user(void _ _user *to, const void *from, unsigned long count);
上述函数均返回不能被复制的字节数,因此,如果完全复制成功,返回值为0。
在字符设备驱动中,需要定义一个file_operations 的实例,并将具体设备驱动的函数赋值给
file_operations的成员,如下代码清单所示。
struct file_operations xxx_fops = {
.owner = THIS_MODULE,
.read = xxx_read,
.write = xxx_write,
.ioctl = xxx_ioctl,
...
};
file_operations怎么跟cdev建立联系了?通过cdev_init()函数。
void cdev_init(struct cdev *cdev, const struct file_operations *fops)
{
memset(cdev, 0, sizeof *cdev);
INIT_LIST_HEAD(&cdev->list);
kobject_init(&cdev->kobj, &ktype_cdev_default);
cdev->ops = fops;
}
下图所示为字符设备驱动的结构、字符设备驱动与字符设备以及字符设备驱动与用户空间访问该设备的程序之间的关系。

框架源码分析
在内核中,定义了一个哈希表chrdevs,该哈希表的大小为CHRDEV_MAJOR_HASH_SIZE(255),定义如下。
/* fs/char_dev.c */
#define CHRDEV_MAJOR_HASH_SIZE 255
static struct char_device_struct {
struct char_device_struct *next;
unsigned int major;
unsigned int baseminor;
int minorct;
char name[64];
struct cdev *cdev; /* will die */
} *chrdevs[CHRDEV_MAJOR_HASH_SIZE];
字符设备申请设备号,即是申请一个struct char_device_struct结构体,然后把该结构体放入chrdevs哈希表中,方便以后查找。struct char_device_struct结构体保存着主设备号、次设备号、cdev、name等信息。
下面分析一下申请设备号的alloc_chrdev_region函数:
//申请设备号,baseminor表示起始的设备号,count表示申请的个数
int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,
const char *name)
{
struct char_device_struct *cd;
//创建char_device_struct等
cd = __register_chrdev_region(0, baseminor, count, name);
if (IS_ERR(cd))
return PTR_ERR(cd);
//设置dev
*dev = MKDEV(cd->major, cd->baseminor);
return 0;
}
static struct char_device_struct *
__register_chrdev_region(unsigned int major, unsigned int baseminor,
int minorct, const char *name)
{
struct char_device_struct *cd, **cp;
int ret = 0;
int i;
//创建一个char_device_struct
cd = kzalloc(sizeof(struct char_device_struct), GFP_KERNEL);
if (cd == NULL)
return ERR_PTR(-ENOMEM);
mutex_lock(&chrdevs_lock);
/* major为0表示向系统动态申请未被占用的设备号,在chrdevs中找空闲位置*/
if (major == 0) {
for (i = ARRAY_SIZE(chrdevs)-1; i > 0; i--) {
if (chrdevs[i] == NULL)
break;
}
//系统推荐动态申请设备号的范围254-234,设备号低于动态申请的范围,警告
if (i < CHRDEV_MAJOR_DYN_END)
pr_warn("CHRDEV \"%s\" major number %d goes below the dynamic allocation range\n",
name, i);
if (i == 0) {
ret = -EBUSY;
goto out;
}
major = i;
}
//设置char_device_struct结构体,包括设备号、起始此设备号,申请设备号个数、name
cd->major = major;
cd->baseminor = baseminor;
cd->minorct = minorct;
strlcpy(cd->name, name, sizeof(cd->name));
//根据主设备号获得哈希表的索引,major%255
i = major_to_index(major);
/*在哈希表索引项的链表中寻找合适的位置进行插入
该链表是从小到大排序的,插入的时候按照这个规则
*/
for (cp = &chrdevs[i]; *cp; cp = &(*cp)->next)
if ((*cp)->major > major ||
((*cp)->major == major &&
(((*cp)->baseminor >= baseminor) ||
((*cp)->baseminor + (*cp)->minorct > baseminor))))
break;
/* 如果链表中存在有主设备号相同的char_device_struct,则判断次设备号是否有冲突 */
if (*cp && (*cp)->major == major) {
int old_min = (*cp)->baseminor;
int old_max = (*cp)->baseminor + (*cp)->minorct - 1;
int new_min = baseminor;
int new_max = baseminor + minorct - 1;
/* New driver overlaps from the left. */
if (new_max >= old_min && new_max <= old_max) {
ret = -EBUSY;
goto out;
}
/* New driver overlaps from the right. */
if (new_min <= old_max && new_min >= old_min) {
ret = -EBUSY;
goto out;
}
}
//插入链表中
cd->next = *cp;
*cp = cd;
mutex_unlock(&chrdevs_lock);
return cd;
out:
mutex_unlock(&chrdevs_lock);
kfree(cd);
return ERR_PTR(ret);
}
从代码分析上,可以得知主设备号相同的设备号,在chrdevs中的索引是相同的,区别在于次设备号,次设备的范围不能有重叠,然后通过链表串起来,从小到大排序。
在内核中,定义了一个哈希表cdev_map,定义如下所示。
//定义在drivers/base/map.c
struct kobj_map {
struct probe {
struct probe *next;
dev_t dev;
unsigned long range;
struct module *owner;
kobj_probe_t *get;
int (*lock)(dev_t, void *);
void *data;
} *probes[255];
struct mutex *lock;
};
//定义在fs/char_dev.c
static struct kobj_map *cdev_map;
cdev_map保存着注册到内核的字符设备信息。
把字符设备增添进内核,即使分配一个struct probe,然后初始化该struct probe结构体,结构体中包含有设备号、次设备号个数range,字符设备cdev,然后将该结构体插入哈希表索引项的链表中,以主设备号小到大插入,索引通过(主设备%255)算出。
//增添一个cdev到内核
int cdev_add(struct cdev *p, dev_t dev, unsigned count)
{
int error;
p->dev = dev;
p->count = count;
//核心是调用kobj_map
error = kobj_map(cdev_map, dev, count, NULL,
exact_match, exact_lock, p);
if (error)
return error;
kobject_get(p->kobj.parent);
return 0;
}
int kobj_map(struct kobj_map *domain, dev_t dev, unsigned long range,
struct module *module, kobj_probe_t *probe,
int (*lock)(dev_t, void *), void *data)
{
//表示设备号范围(dev, dev+range)中不同的主设备号的个数,通常为1
unsigned n = MAJOR(dev + range - 1) - MAJOR(dev) + 1;
unsigned index = MAJOR(dev);
unsigned i;
struct probe *p;
//若n > 255,则超出了kobj_map中probes数组的大小
if (n > 255)
n = 255;
//分配n个struct probe
p = kmalloc_array(n, sizeof(struct probe), GFP_KERNEL);
if (p == NULL)
return -ENOMEM;
//初始化probe,包括dev、此设备号数等
for (i = 0; i < n; i++, p++) {
p->owner = module;
p->get = probe; //初始化为exact_match
p->lock = lock; //初始化为exact_lock
p->dev = dev;
p->range = range;
p->data = data; //指向cdev
}
mutex_lock(domain->lock);
//将probe插入哈希表索引项的链表中
for (i = 0, p -= n; i < n; i++, p++, index++) {
struct probe **s = &domain->probes[index % 255];
while (*s && (*s)->range < range)
s = &(*s)->next;
p->next = *s;
*s = p;
}
mutex_unlock(domain->lock);
return 0;
}
字符设备的设备文件
在字符设备驱动程序中,通过调用class_create创建一个设备class,在调用device_create在这个class下创建设备,成功后会在/dev目录下生成设备文件。那么对设备文件open、read、write等,是怎么转换为调用cdev->ops的函数集的呢?
对于设备文件,其inode是通过调用init_special_inode函数进行初始化的。
const struct file_operations def_chr_fops = {
.open = chrdev_open,
.llseek = noop_llseek,
};
void init_special_inode(struct inode *inode, umode_t mode, dev_t rdev)
{
inode->i_mode = mode;
if (S_ISCHR(mode)) {
inode->i_fop = &def_chr_fops;//对于字符设备其inode的file_operations初始化为def_chr_fops
inode->i_rdev = rdev; //设备号
} else if (S_ISBLK(mode)) {
inode->i_fop = &def_blk_fops;
inode->i_rdev = rdev;
} else if (S_ISFIFO(mode))
inode->i_fop = &pipefifo_fops;
else if (S_ISSOCK(mode))
; /* leave it no_open_fops */
else
printk(KERN_DEBUG "init_special_inode: bogus i_mode (%o) for"
" inode %s:%lu\n", mode, inode->i_sb->s_id,
inode->i_ino);
}
当进程open文件,会调用file->f_op->open,而file->f_op是通过inode->i_fop初始化的。所以进程最终会调用chrdev_open函数。
static int chrdev_open(struct inode *inode, struct file *filp)
{
const struct file_operations *fops;
struct cdev *p;
struct cdev *new = NULL;
int ret = 0;
spin_lock(&cdev_lock);
p = inode->i_cdev; //i_cdev为NULL,表示还未打开过设备文件
if (!p) {
struct kobject *kobj;
int idx;
spin_unlock(&cdev_lock);
/*在cdev_map哈希表中通过设备号,找到字符设备对应的probe结构体,
通过probe结构体找到cdev结构体,返回cdev的kobj
*/
kobj = kobj_lookup(cdev_map, inode->i_rdev, &idx);
if (!kobj)
return -ENXIO;
//获得cdev
new = container_of(kobj, struct cdev, kobj);
spin_lock(&cdev_lock);
/* Check i_cdev again in case somebody beat us to it while
we dropped the lock. */
p = inode->i_cdev;
if (!p) {
inode->i_cdev = p = new; //设置inode->i_cdev,或许就不要在cdev_map查找了
list_add(&inode->i_devices, &p->list);
new = NULL;
} else if (!cdev_get(p))
ret = -ENXIO;
} else if (!cdev_get(p))
ret = -ENXIO;
spin_unlock(&cdev_lock);
cdev_put(new);
if (ret)
return ret;
ret = -ENXIO;
//得到字符设备的fops
fops = fops_get(p->ops);
if (!fops)
goto out_cdev_put;
//换掉filp的fops为字符设备的fops
replace_fops(filp, fops);
//调用字符设备fops->open
if (filp->f_op->open) {
ret = filp->f_op->open(inode, filp);
if (ret)
goto out_cdev_put;
}
return 0;
out_cdev_put:
cdev_put(p);
return ret;
}