< Linux Kernel > Reference Counts

本文探讨了操作系统内核中引用计数机制的工作原理及其重要性。引用计数用于跟踪指向特定数据结构的指针数量,以确保当最后一个引用被释放时,该数据结构可以被正确地回收。文章还讨论了不正确使用引用计数可能导致的问题,包括内存泄漏和过早释放,以及如何通过正确的编程实践来避免这些问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

When a piece of code tries to access a data structure that has already been freed, the kernel is
not very happy, and the user is rarely happy with the kernel's reaction. To avoid those nasty
problems, and to make garbage collection mechanisms easier and more effective (see the
section "Garbage Collection" later in this chapter), most data structures keep a reference
count. Good kernel citizens increment and decrement the reference count of every data
structure every time they save and release a reference, respectively, to the structure. For any
data structure type that requires a reference count, the kernel component that owns the
structure usually exports two functions that can be used to increment and decrement the
reference count. Such functions are usually called xxx_hold and xxx_release,
respectively. Sometimes the release function is called xxx_put instead (e.g., dev_put for

net_device structures).


While we like to assume there are no bad citizens in the kernel, developers are human, and as
such they do not always write bug-free code. The use of the reference count is a simple but
effective mechanism to avoid freeing still-referenced data structures. However, it does not
always solve the problem completely. This is the consequence of forgetting to balance
increments and decrements:

• If you release a reference to a data structure but forget to call the xxx_release
function, the kernel will never allow the data structure to be freed (unless another
buggy piece of code happens to call the release function an extra time by mistake!).

This leads to gradual memory exhaustion.


• If you take a reference to a data structure but forget to call xxx_hold, and at some
later point you happen to be the only reference holder, the structure will be
prematurely freed because you are not accounted for. This case definitely can be
more catastrophic than the previous one; your next attempt to access the structure
can corrupt other data or cause a kernel panic that brings down the whole system
instantly.



When a data structure is to be removed for some reason, the reference holders can be
explicitly notified about its going away so that they can politely release their references. This
is done through notification chains. See the section "Reference Counts" in Chapter 8 for an
interesting example.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值