char_dev.c里的中文注释,仅代表个人理解,仅供参考。如有错误之处,请指出,谢谢!

 /*
* linux/fs/char_dev.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/ #include <linux/init.h>
#include <linux/fs.h>
#include <linux/kdev_t.h>
#include <linux/slab.h>
#include <linux/string.h> #include <linux/major.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/smp_lock.h>
#include <linux/seq_file.h> #include <linux/kobject.h>
#include <linux/kobj_map.h>
#include <linux/cdev.h>
#include <linux/mutex.h>
#include <linux/backing-dev.h> #ifdef CONFIG_KMOD
#include <linux/kmod.h>
#endif
#include "internal.h" /*
* capabilities for /dev/mem, /dev/kmem and similar directly mappable character
* devices
* - permits shared-mmap for read, write and/or exec
* - does not permit private mmap in NOMMU mode (can't do COW)
* - no readahead or I/O queue unplugging required
*/ struct backing_dev_info directly_mappable_cdev_bdi = {
.capabilities = (
#ifdef CONFIG_MMU
/* permit private copies of the data to be taken */
BDI_CAP_MAP_COPY |
#endif
/* permit direct mmap, for read, write or exec */
BDI_CAP_MAP_DIRECT |
BDI_CAP_READ_MAP | BDI_CAP_WRITE_MAP | BDI_CAP_EXEC_MAP),
}; static struct kobj_map *cdev_map; static DEFINE_MUTEX(chrdevs_lock); static struct char_device_struct {
struct char_device_struct *next;
unsigned int major;
unsigned int baseminor;
int minorct;
char name[];
struct file_operations *fops;
struct cdev *cdev;
/* will die */
} *chrdevs[CHRDEV_MAJOR_HASH_SIZE]; /* index in the above */
static inline int major_to_index(int major)
{
/* [CGW]: 根据主设备号,转换成对应的索引
* 即主设备号就是索引号
*/
return major % CHRDEV_MAJOR_HASH_SIZE;
} #ifdef CONFIG_PROC_FS void chrdev_show(struct seq_file *f, off_t offset)
{
struct char_device_struct *cd;
/* [CGW]: 根据offset (相当于索引),找到对应设备 */
if (offset < CHRDEV_MAJOR_HASH_SIZE) {
/* [CGW]: 上锁 */
mutex_lock(&chrdevs_lock);
/* [CGW]: 打印该设备项下链表中所有节点的主设备号,和设备名 */
for (cd = chrdevs[offset]; cd; cd = cd->next)
seq_printf(f, "%3d %s\n", cd->major, cd->name);
/* [CGW]: 解锁 */
mutex_unlock(&chrdevs_lock);
}
} #endif /* CONFIG_PROC_FS */ /*
* Register a single major with a specified minor range.
*
* If major == 0 this functions will dynamically allocate a major and return
* its number.
*
* If major > 0 this function will attempt to reserve the passed range of
* minors and will return zero on success.
*
* Returns a -ve errno on failure.
*/ 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 = ;
int i; /* [cgw]: 分配一块char_device_struct大小的内存块 */
cd = kzalloc(sizeof(struct char_device_struct), GFP_KERNEL);
/* [cgw]: 分配失败 */
if (cd == NULL)
return ERR_PTR(-ENOMEM);
/*[cgw]: 上锁,进入临界区*/
mutex_lock(&chrdevs_lock);
/* temporary */
/*[cgw]: 如果主设备号为0,则从最大的设备号开始,往下查找第一个未被
*注册的设备
*/
if (major == ) {
/*[cgw]: 从大到小开始查找*/
for (i = ARRAY_SIZE(chrdevs)-; i > ; i--) {
/* [cgw]: 找到第一个未被注册的设备 */
if (chrdevs[i] == NULL)
break;
}
/* [cgw]:未找到空位 */
if (i == ) {
ret = -EBUSY;
goto out;
}
/* [cgw]: 以该空位的序号为主设备号 */
major = i;
ret = major;
} /* [cgw]: 手工分配一个主设备号,和次设备号基址 */
cd->major = major;
/* [cgw]: 手工分配次设备号基址 */
cd->baseminor = baseminor;
/* [cgw]: 分配minorct个次设备号 */
cd->minorct = minorct;
/* [cgw]: 分配设备名 */
strncpy(cd->name,name, );
/* [cgw]: 找到主设备号在设备列表中的索引 */
i = major_to_index(major);
/* [cgw]: 当前分配的设备号比较设备列表,判断该设备号是否
* 合法
*/
for (cp = &chrdevs[i]; *cp; cp = &(*cp)->next)
/* [cgw]: 当前分配的主设备号,小于该主设备号索引对应的,设备列表
* 中的主设备号,合法
* 这个里有点不解,从i = major_to_index(major);看出,主设备号和该主
* 设备号对应的索引是相等的,为什么(*cp)->major > major是合法呢
*/
if ((*cp)->major > major ||
/* [cgw]: 当前分配的主设备号,等于该主设备号索引对应的,设备列表
* 中的主设备号,并且符合以下条件之一,当前分配的次设备号,等于
* 小于该主设备号索引对应的,设备列表中的次设备号。或者,当前分
* 配的次设备号,小于该主设备号索引对应的,设备列表中的次设备基
* 址以后minorct个次设备号
*/
((*cp)->major == major &&
(((*cp)->baseminor >= baseminor) ||
((*cp)->baseminor + (*cp)->minorct > baseminor))))
break;
/* Check for overlapping minor ranges. */
/* [cgw]: 当前分配的主设备号,等于该主设备号索引对应的,设备列表
* 中的主设备号,判断次设备号是否在范围内
*/
if (*cp && (*cp)->major == major) {
int old_min = (*cp)->baseminor;
int old_max = (*cp)->baseminor + (*cp)->minorct - ;
int new_min = baseminor;
int new_max = baseminor + minorct - ; /* 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;
}
} /* [cgw]: 新加入的设备, 添加到该主设备号链表 */
cd->next = *cp;
/* [cgw]: 设备列表指针指向新加入设备*/
*cp = cd;
/* [cgw]: 解锁,退出临界区*/
mutex_unlock(&chrdevs_lock);
return cd;
out: /* [cgw]: 解锁,退出临界区*/
mutex_unlock(&chrdevs_lock);
/* [cgw]: 释放为新设备创建的内存*/
kfree(cd);
return ERR_PTR(ret);
} static struct char_device_struct *
__unregister_chrdev_region(unsigned major, unsigned baseminor, int minorct) {
struct char_device_struct *cd = NULL, **cp;
/* [CGW]: 根据主设备号,找出该主设备号所在列表中的索引*/
int i = major_to_index(major);
/* [CGW]: 上锁,进入临界区 */
mutex_lock(&chrdevs_lock);
/* [CGW]: 根据索引,找出该主设备号所在列表项 */
for (cp = &chrdevs[i]; *cp; cp = &(*cp)->next)
/* [CGW]:主设备号所在列表项中, 在主设备号对应的链表中,查找判断该主设备号,
* 次设备号基址,次设备号个数是否已经被注册
*/
if ((*cp)->major == major &&
(*cp)->baseminor == baseminor &&
(*cp)->minorct == minorct)
/* [CGW]: 已经被注册,停止查找 */
break;
/* [CGW]: 主设备号所在链表中的节点
* (注意: 设备列表中,每个设备号都对应一个链表,该链表用于存放此设备号)
*/
if (*cp) {
/* [CGW]: 取出该节点 */
cd = *cp;
/* [CGW]: 更新cp,指向下一个节点*/
*cp = cd->next;
} /* [CGW]: 解锁,退出临界区 */
mutex_unlock(&chrdevs_lock);
/* [CGW]: 返回该设备(节点) */
return cd; } /**
* register_chrdev_region() - register a range of device numbers
* @from: the first in the desired range of device numbers; must include
* the major number.
* @count: the number of consecutive device numbers required
* @name: the name of the device or driver.
*
* Return value is zero on success, a negative error code on failure.
*/ int register_chrdev_region(dev_t from, unsigned count, const char *name) {
struct char_device_struct *cd;
dev_t to = from + count;
dev_t n, next;
/* [CGW]: 分配count个连续的设备 */
for (n = from; n < to; n = next) {
/* [CGW]: 主设备号+1递增 */
next = MKDEV(MAJOR(n)+, );
if (next > to)
next = to; /* [CGW]: 根据主、次设备号基址,分配next - n个连续次设备号的设备,
* 并根据主设备号分配设备名
* 如果MINOR(n)为0,next-n的值应恒为256,未验证!!!
*/
cd = __register_chrdev_region(MAJOR(n), MINOR(n),
next - n, name);
/* [CGW]: 分配失败 */
if (IS_ERR(cd))
goto fail;
}
return ; fail: /* [CGW]: 当前分配到了第n个设备就失败了*/
to = n;
/* [CGW]: 注销刚刚分配的所有设备 */
for (n = from; n < to; n = next) {
next = MKDEV(MAJOR(n)+, );
/* [CGW]: 对应的内存空间 */
kfree(__unregister_chrdev_region(MAJOR(n), MINOR(n), next - n));
} /* [CGW]: 返回这个分配失败的设备指针 */
return PTR_ERR(cd);
} /**
* alloc_chrdev_region() - register a range of char device numbers
* @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
*
* Allocates a range of char device numbers. The major number will be
* chosen dynamically, and returned (along with the first minor number)
* in @dev. Returns zero or a negative error code.
*/
int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,
const char *name) {
struct char_device_struct *cd;
/* [CGW]: 自动分配一个设备,因为主设备号为0
* 以baseminor为基址,分配count个次设备号
*/
cd = __register_chrdev_region(, baseminor, count, name);
/* [CGW]: 分配失败 */
if (IS_ERR(cd))
return PTR_ERR(cd);
/* [CGW]: 返回设备号 */
*dev = MKDEV(cd->major, cd->baseminor);
return ;
} /**
* register_chrdev() - Register a major number for character devices.
* @major: major device number or 0 for dynamic allocation
* @name: name of this range of devices
* @fops: file operations associated with this devices
*
* If @major == 0 this functions will dynamically allocate a major and return
* its number.
*
* If @major > 0 this function will attempt to reserve a device with the given
* major number and will return zero on success.
*
* Returns a -ve errno on failure.
*
* The name of this device has nothing to do with the name of the device in
* /dev. It only helps to keep track of the different owners of devices. If
* your module name has only one type of devices it's ok to use e.g. the name
* of the module here.
*
* This function registers a range of 256 minor numbers. The first minor number
* is 0.
*/ int register_chrdev(unsigned int major, const char *name,
const struct file_operations *fops) {
struct char_device_struct *cd;
struct cdev *cdev;
char *s;
int err = -ENOMEM; /* [cgw]: 分配一个设备,次设备号为0~255 */
cd = __register_chrdev_region(major, , , name);
if (IS_ERR(cd))
return PTR_ERR(cd);
/* [cgw]:分配一个cdev结构体 */
cdev = cdev_alloc();
if (!cdev)
goto out2; cdev->owner = fops->owner;
cdev->ops = fops; /* [cgw]: 设置kobject的名字 */
kobject_set_name(&cdev->kobj, "%s", name);
/* [cgw]: 把kobject的名字kobj->name中的'/'替换成'!' */
for (s = strchr(kobject_name(&cdev->kobj),'/'); s; s = strchr(s, '/'))
*s = '!'; /* [cgw]: 添加一个字符设备到系统*/
err = cdev_add(cdev, MKDEV(cd->major, ), );
if (err)
goto out; /* [cgw]: 设置char_device_struct中的cdev指针 */
cd->cdev = cdev; return major ? : cd->major; out:
/* [cgw]: kobect 引用计数-1 */
kobject_put(&cdev->kobj); out2:
/* [cgw]: 释放刚注册的设备 */
kfree(__unregister_chrdev_region(cd->major, , ));
return err;
} /**
* unregister_chrdev_region() - return a range of device numbers
* @from: the first in the range of numbers to unregister
* @count: the number of device numbers to unregister
*
* This function will unregister a range of @count device numbers,
* starting with @from. The caller should normally be the one who
* allocated those numbers in the first place...
*/ void unregister_chrdev_region(dev_t from, unsigned count)
{
dev_t to = from + count;
dev_t n, next; /* [CGW]: 注销所有从from到to的count个设备 */
for (n = from; n < to; n = next) {
/* [CGW]: 查找下一设备号*/
next = MKDEV(MAJOR(n)+, );
if (next > to)
next = to;
/* [CGW]: 注销所有刚才注册的设备 */
kfree(__unregister_chrdev_region(MAJOR(n), MINOR(n), next - n));
}
} int unregister_chrdev(unsigned int major, const char *name)
{
struct char_device_struct *cd;
/* [CGW]: 根据主设备号,找到对应设备列表项 */
cd = __unregister_chrdev_region(major, , );
/* [CGW]: 该设备项有效,并且被注册 */
if (cd && cd->cdev)
/* [CGW]: 注销该设备 */
cdev_del(cd->cdev);
/* [CGW]: 释放该设备占用的内存空间 */
kfree(cd); return ;
} static DEFINE_SPINLOCK(cdev_lock); static struct kobject *cdev_get(struct cdev *p)
{
struct module *owner = p->owner;
struct kobject *kobj;
/* [cgw]:cdev_get uses try_module_get to attempt to increment that module's
* usage count. If that operation succeeds, kobject_get is used to increment the
* kobject's reference count as well---<Linux Device Drivers>
* try_module_get(owner)增加owner (THIS_MODULE)引用计数
*/
/* [cgw]: module使用计数+1 */
if (owner && !try_module_get(owner))
return NULL;
/* [cgw]: kobj引用计数+1 */
kobj = kobject_get(&p->kobj);
/* [cgw]: kobj指针返回失败 */
if (!kobj)
/* [cgw]: module使用计数-1 */
module_put(owner); return kobj;
} void cdev_put(struct cdev *p)
{
/* [cgw]: cdev指针不为空 */
if (p) {
/* [cgw]: 获得模块指针 */
struct module *owner = p->owner;
/* [cgw]: kobj引用计数-1 */
kobject_put(&p->kobj);
/* [cgw]: module使用计数-1 */
module_put(owner);
}
} /*
* Called every time a character special file is opened
*/
int chrdev_open(struct inode * inode, struct file * filp)
{
struct cdev *p;
struct cdev *new = NULL;
int ret = ; /* [cgw]: 进入临界区 */
spin_lock(&cdev_lock);
/* [cgw]: 从inode中得到一个字符设备cdev指针 */
p = inode->i_cdev;
/* [cgw]: struct cdev指针为空 */
if (!p) {
struct kobject *kobj;
int idx;
/* [cgw]: 进入临界区 */
spin_unlock(&cdev_lock);
/* [cgw]: 看看cdev_map的probes[inode->i_rdev]链表是否有inode->i_rdev这个设备
* 并返回这个设备的kobj
*/
kobj = kobj_lookup(cdev_map, inode->i_rdev, &idx);
/* [cgw]: kobj为空,错误 */
if (!kobj)
return -ENXIO;
/* [cgw]: 根据返回的kobj,找出包含这个kobj的struct cdev指针 */
new = container_of(kobj, struct cdev, kobj);
/* [cgw]: 进入临界区 */
spin_lock(&cdev_lock);
/* [cgw]: 从inode中得到一个字符设备cdev指针 */
p = inode->i_cdev;
/* [cgw]: struct cdev指针为空 */
if (!p) {
/* [cgw]: 把这个struct cdev指针填装到inode->i_cdev */
inode->i_cdev = p = new;
/* [cgw]: 记录对应的索引 */
inode->i_cindex = idx;
/* [cgw]: 把inode->i_devices插入到p->list */
list_add(&inode->i_devices, &p->list);
/* [cgw]: 清除new指针 */
new = NULL;
/* [cgw]: 返回cdev中kobj指针为空,错误 */
} else if (!cdev_get(p))
ret = -ENXIO;
/* [cgw]: 返回cdev中kobj指针为空,错误 */
} else if (!cdev_get(p))
ret = -ENXIO;
/* [cgw]: 退出临界区 */
spin_unlock(&cdev_lock);
/* [cgw]: 实际上是cdev->kobj引用计数-1,module使用计数-1 */
cdev_put(new);
if (ret)
return ret;
/* [cgw]: module使用计数+1,并返回cdev->ops指针 */
filp->f_op = fops_get(p->ops);
/* [cgw]: filp->f_op指针为空,失败 */
if (!filp->f_op) {
/* [cgw]: 实际上是cdev->kobj引用计数-1,module使用计数-1 */
cdev_put(p);
return -ENXIO;
}
/* [cgw]: 调用filp->f_op->open,打开的是用户驱动程序中定义的
* file_operations中的open函数
*/
if (filp->f_op->open) {
/* [cgw]: 上锁 */
lock_kernel();
/* [cgw]: 调用filp->f_op->open */
ret = filp->f_op->open(inode,filp);
/* [cgw]: 解锁 */
unlock_kernel();
}
/* [cgw]: 调用filp->f_op->open失败 */
if (ret)
/* [cgw]: 实际上是cdev->kobj引用计数-1,module使用计数-1 */
cdev_put(p); return ret;
} void cd_forget(struct inode *inode)
{
/* [cgw]: 进入临界区 */
spin_lock(&cdev_lock);
/* [cgw]: 从链表删除一个inode->i_devices节点,
* 并重新初始化这个链表
*/
list_del_init(&inode->i_devices);
/* [cgw]: inode->i_cdev指针清0 */
inode->i_cdev = NULL;
/* [cgw]: 退出临界区 */
spin_unlock(&cdev_lock);
} static void cdev_purge(struct cdev *cdev)
{
/* [cgw]: 进入临界区 */
spin_lock(&cdev_lock);
/* [cgw]: 测试cdev->list这个链表是否为空
*
*/
while (!list_empty(&cdev->list)) {
struct inode *inode;
/* [cgw]: 找出包含cdev->list的struct inode结构体的指针 */
inode = container_of(cdev->list.next, struct inode, i_devices);
/* [cgw]: 从链表删除一个inode->i_devices节点,
* 并重新初始化这个链表
*/
list_del_init(&inode->i_devices);
/* [cgw]: inode->i_cdev指针清0 */
inode->i_cdev = NULL;
}
/* [cgw]: 退出临界区 */
spin_unlock(&cdev_lock);
} /*
* Dummy default file-operations: the only thing this does
* is contain the open that then fills in the correct operations
* depending on the special file...
*/ const struct file_operations def_chr_fops = {
.open = chrdev_open,
};
static struct kobject *exact_match(dev_t dev, int *part, void *data)
{
struct cdev *p = data;
/* [cgw]: 返回cdev中kobj成员指针 */
return &p->kobj;
} static int exact_lock(dev_t dev, void *data)
{
struct cdev *p = data;
/* [cgw]: data中kobj引用计数+1,并返回kobj指针 */
return cdev_get(p) ? : -;
} /**
* cdev_add() - add a char device to the system
* @p: the cdev structure for the device
* @dev: the first device number for which this device is responsible
* @count: the number of consecutive minor numbers corresponding to this
* device
*
* cdev_add() adds the device represented by @p to the system, making it
* live immediately. A negative error code is returned on failure.
*/ int cdev_add(struct cdev *p, dev_t dev, unsigned count)
{
/* [cgw]: 分配一个dev设备号给p->dev */
p->dev = dev;
/* [cgw]: 分配count个连续的次设备号
* 这里实际是分配count设备,只是次设备号不一样,主设备号都一样
*/
p->count = count;
/* [cgw]: 把新加入的设备填装到一个probe结构,并把这个probe插入到
* 对应probes[MAJOR(dev)]链表,即probes[]中每一个元素都是一个链表
*/
return kobj_map(cdev_map, dev, count, NULL, exact_match, exact_lock, p);
} static void cdev_unmap(dev_t dev, unsigned count)
{
/* [cgw]: 从probes[MAJOR(dev)]链表中删除一个节点(probe) */
kobj_unmap(cdev_map, dev, count);
} /**
* cdev_del() - remove a cdev from the system
* @p: the cdev structure to be removed
*
* cdev_del() removes @p from the system, possibly freeing the structure
* itself.
*/ void cdev_del(struct cdev *p)
{
/* [cgw]: 从probes[MAJOR(p->dev)]链表中删除一个节点(probe)
*
*/
cdev_unmap(p->dev, p->count);
/* [cgw]: kobj引用计数-1 */
kobject_put(&p->kobj);
} static void cdev_default_release(struct kobject *kobj)
{
/* [cgw]: 找到包含kobj的结构体struct cdev的指针 */
struct cdev *p = container_of(kobj, struct cdev, kobj);
/* [cgw]: 从cdev->list链表中删除cdev */
cdev_purge(p);
} static void cdev_dynamic_release(struct kobject *kobj)
{
/* [cgw]: 找到包含kobj的结构体struct cdev的指针 */
struct cdev *p = container_of(kobj, struct cdev, kobj);
/* [cgw]: 从cdev->list链表中删除cdev */
cdev_purge(p);
/* [cgw]: 释放这个cdev的内存空间 */
kfree(p);
} static struct kobj_type ktype_cdev_default = {
.release = cdev_default_release,
}; static struct kobj_type ktype_cdev_dynamic = {
.release = cdev_dynamic_release,
}; /**
* cdev_alloc() - allocate a cdev structure
*
* Allocates and returns a cdev structure, or NULL on failure.
*/
struct cdev *cdev_alloc(void)
{
/* [cgw]: 分配一个cdev结构体 */
struct cdev *p = kzalloc(sizeof(struct cdev), GFP_KERNEL); /* [cgw]: 分配cdev结构体成功 */
if (p) {
/* [cgw]: 分配一个kobj.ktype结构体,指向&ktype_cdev_dynamic
* 为这个驱动制定一个统一的行为,提供释放kobj的方法
*/
p->kobj.ktype = &ktype_cdev_dynamic;
/* [cgw]: 初始化链表,把这个cdev插入链表头 */
INIT_LIST_HEAD(&p->list);
/* [cgw]: 初始化kobject,每个对象都有一个kobject */
kobject_init(&p->kobj);
}
return p;
} /**
* 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)
{
/* [cgw]: cdev结构体清零 */
memset(cdev, , sizeof *cdev);
/* [cgw]: 初始化链表,把这个cdev插入链表头 */
INIT_LIST_HEAD(&cdev->list);
/* [cgw]: 分配一个kobj.ktype结构体,指向&ktype_cdev_default
* 为这个驱动制定一个默认的统一的行为,提供恢复默认kobj的方法
* 没有释放kobj内存空间
*/
cdev->kobj.ktype = &ktype_cdev_default;
/* [cgw]: 初始化kobject,每个对象都有一个kobject */
kobject_init(&cdev->kobj);
/* [cgw]: cdev->ops指向驱动程序中的file_operations结构体 */
cdev->ops = fops;
} static struct kobject *base_probe(dev_t dev, int *part, void *data)
{
if (request_module("char-major-%d-%d", MAJOR(dev), MINOR(dev)) > )
/* Make old-style 2.4 aliases work */
request_module("char-major-%d", MAJOR(dev));
return NULL;
} void __init chrdev_init(void)
{
/*[cgw]: 初始化cdev_map变量 */
cdev_map = kobj_map_init(base_probe, &chrdevs_lock);
} /* Let modules do char dev stuff */
EXPORT_SYMBOL(register_chrdev_region);
EXPORT_SYMBOL(unregister_chrdev_region);
EXPORT_SYMBOL(alloc_chrdev_region);
EXPORT_SYMBOL(cdev_init);
EXPORT_SYMBOL(cdev_alloc);
EXPORT_SYMBOL(cdev_del);
EXPORT_SYMBOL(cdev_add);
EXPORT_SYMBOL(register_chrdev);
EXPORT_SYMBOL(unregister_chrdev);
EXPORT_SYMBOL(directly_mappable_cdev_bdi);
04-20 15:55