< Linux Kernel > Reference Counts

来源:互联网 发布:淘宝主图尺寸高度 编辑:程序博客网 时间:2024/05/01 15:03
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.

原创粉丝点击