Linux Kernel Architecture

(Jacob Rumans) #1

Chapter 5: Locking and Interprocess Communication


5.2.2 Spinlocks


Spinlocksare used to protect short code sections that comprise just a few C statements and are therefore
quickly executed and exited. Most kernel data structures have their own spinlock that must be acquired
when critical elements in the structure are processed. Although spinlocks are omnipresent in the kernel
sources, I omit them in most pieces of code shown in this book. They do not provide any valuable insight
into how the kernel functions but make the code more difficult to read, as explained above. Nevertheless,
it is important that codeisequipped with appropriate locks!

Data Structures and Usage


Spinlocks are implemented by means of thespinlock_tdata structure, which is manipulated essentially
usingspin_lockandspin_unlock. There are a few other spinlock operations:spin_lock_irqsave
not only acquires the spinlock but also disables the interrupts on the local CPU, andspin_lock_bh
also disables softIRQs (see Chapter 14). Spinlocksacquired with these operations must be released
by means of their counterpart;spin_unlock_bhandspin_unlock_irqsave, respectively. Once again,
implementation is almost fully in (strongly architecture-dependent) assembly language and is therefore
not discussed here.

Spinlocks are used as follows:

spinlock_t lock = SPIN_LOCK_UNLOCKED;
...
spin_lock(&lock);
/* Critical section */
spin_unlock(&lock);

SPIN_LOCK_UNLOCKEDmust be used in its unlocked state to initialize the spinlock.spin_locktakes
account of two situations:


  1. Iflockis not yet acquired from another place in the kernel, it is reserved for the current
    processor. Other processors may no longer enter the following area.

  2. Iflockis already acquired by another processor,spin_lockgoes into an endless loop to
    repeatedly check whetherlockhas been released byspin_unlock(thus the namespinlock).
    Once this is the case,lockis acquired, and the critical section of code is entered.


spin_lockis defined as an atomic operation to prevent race conditions arising when spinlocks are
acquired.

Additionally, the kernel provides the two methodsspin_trylockandspin_trylock_bh.Theytryto
obtain a lock, but will not block if it cannot be immediately acquired. When the locking operation has
succeeded, they return a nonzero value (and the code is protected by the spinlock), but otherwise they
return 0. In this case, the code isnotprotected by the lock.

Two points must be noted when using spinlocks:


  1. If a lock is acquired but no longer released, the system is rendered unusable. All
    processors — including the one that acquired the lock — sooner or later arrive at a point
    where they must enter the critical region. They go into the endless loop to wait for lock
    release, but this never happens. This produces adeadlock, and the grim name suggests that
    it’s something that should be avoided.

Free download pdf