这里只需要了解一直知识点 引用计数器kref
文章目录
参考资料
什么是引用计数器
引用计数器实验
kobject释放实例分析实验
迅为设备模型偏
在线查看Linux 系统源码:Linux Kernel Cross Reference (LXR)
一、基础知识
什么是引用计数器。
引用计数器(reference counting)是一种内存管理技术,用于跟踪对象或资源的引用数量。它通过在对象被引用时增加计数值,并在引用被释放时减少计数值,以确定何时可以安全地释放对象或资源。
引用计数器的基本原理如下:
对象或资源被创建时,引用计数器初始化为 1。
当有新的引用指向对象或资源时,引用计数器增加。
当引用不再指向对象或资源时(引用被删除、超出作用域等),引用计数器减少。
当引用计数器的值为 0 时,表示没有任何引用指向对象或资源,可以安全地释放对象或资
源,并进行相关的清理操作。
引用计数器 kref 介绍
kref 是 Linux 内核中提供的一种引用计数器实现,它是一种轻量级的引用计数技术,用于管理内核中的对象的引用计数。
在 Linux 系统中,引用计数器用结构体 kref 来表示。struct kref 定义在 include/linux/kref.h头文件当中,本质是一个 int 型变量。
直接看kref 结构体:
struct kref {
refcount_t refcount;
};
对象是refcount_t,如下:
/**
* struct refcount_t - variant of atomic_t specialized for reference counts
* @refs: atomic_t counter field
*
* The counter saturates at UINT_MAX and will not move once
* there. This avoids wrapping the counter and causing 'spurious'
* use-after-free bugs.
*/
typedef struct refcount_struct {
atomic_t refs;
} refcount_t;
继续看对象属性 atomic_t结构体,如下:
typedef struct {
int counter;
} atomic_t;
对象是一个 int 类型的counter.
在使用引用计数器时,通常会将结构体 kref 嵌入到其他结构体中,例如 struct kobject,以实现引用计数的管理。如
1、kobject 结构体里面嵌套了kref 结构体:
struct kobject {
const char *name;
struct list_head entry;
struct kobject *parent;
struct kset *kset;
struct kobj_type *ktype;
struct kernfs_node *sd; /* sysfs directory entry */
struct kref kref;
#ifdef CONFIG_DEBUG_KOBJECT_RELEASE
struct delayed_work release;
#endif
unsigned int state_initialized:1;
unsigned int state_in_sysfs:1;
unsigned int state_add_uevent_sent:1;
unsigned int state_remove_uevent_sent:1;
unsigned int uevent_suppress:1;
ANDROID_KABI_RESERVE(1);
ANDROID_KABI_RESERVE(2);
ANDROID_KABI_RESERVE(3);
ANDROID_KABI_RESERVE(4);
};
2、我们刚了解过的ConfigFS 中的 config_item 结构体里面也是嵌套的kref 结构体。
struct config_item {
char *ci_name;
char ci_namebuf[CONFIGFS_ITEM_NAME_LEN];
struct kref ci_kref;
struct list_head ci_entry;
struct config_item *ci_parent;
struct config_group *ci_group;
const struct config_item_type *ci_type;
struct dentry *ci_dentry;
};

最低0.47元/天 解锁文章
452

被折叠的 条评论
为什么被折叠?



