Linux Kernel Architecture

(Jacob Rumans) #1

Chapter 5: Locking and Interprocess Communication


❑ down_trylockattempts to acquire a semaphore. If it fails, the process does not go to sleep to wait
for the semaphore but continues execution normally. If the semaphore is acquired, the function
returns a false value, otherwise a true value.

In addition to mutex variables that can be used in the kernel only, Linux also features so-calledfutexes(fast
userspace mutex) that consist of a combination of kernel and user mode. These provide mutex functionality
for userspace processes. However, it must be ensured that they are used and manipulated as quickly
and efficiently as possible. For reasons of space, I dispense with a description of their implementation,
particularly as they are not especially important for the kernel itself. See the manual pagefutex(2)for
more information.

5.2.4 The Read-Copy-Update Mechanism


Read-copy-update (RCU) is a rather new synchronization mechanism that was added during the devel-
opment of kernel 2.5, but has been very favorably accepted by the kernel community. It is by now used
in numerous places all over the kernel. RCU performs very well in terms of performance impact, if at a
slight cost in memory requirements, which is, however, mostly negligible. This is a good thing, but good
things are always accompanied by a number of not-so-good things. This time, it’s the constraints that
RCU places on potential users:

❑ Accesses to the shared resource should be Read Only most of the time, and writes should be
correspondingly rare.
❑ The kernel cannot go to sleep within a region protected by RCU.
❑ The protected resource must be accessed via a pointer.

The principle of RCU is simple: The mechanism keeps track of all users of the pointer to the shared
data structure. When the structure is supposed to change, a copy (or a new instance that is filled in
appropriately, this does not make any difference) is first created and the change is performed there. After
all previous readers have finished their reading work on the old copy, the pointer can be replaced by a
pointer to the new, modified copy. Notice that this allows read access to happen concurrently with write
updates!

Core API


Suppose that a pointerptrpoints to a data structure that is protected by RCU. It is forbidden to simply
de-reference the pointer, butrcu_dereference(ptr)must be invoked before and theresultbe de-
referenced. Additionally, the code that de-references the pointer and uses the result needs to be embraced
by calls torcu_read_lockandrcu_read_unlock:

rcu_read_lock();

p = rcu_dereference(ptr);
if (p != NULL) {
awesome_function(p);
}

rcu_read_unlock();

The de-referenced pointer may not be used outside the region protected by
rcu_read_lock() ... rcu_read_unlock(), nor may it be used for write access!
Free download pdf