Specifications
Multithreading a Device Drive
r
11-5
Spin Locks 11
Spin locks are low-level, busy waiting synchronization primitives. They coordinate access
to data structures and coordinate the activities of an interrupt stream on one processor with
execution streams on other processors. They also guard critical regions that are very short
in duration (that is, less than the time that it takes to perform two context switches).
Spin locks have no mechanism for queueing waiters on a critical section. The spin lock is
simply a test and set instruction that is performed on a lock bit. If an LWP attempts to lock
a spin lock that is already locked, then the LWP does not block; instead it spins, attempting
to set the lock. Because the LWP does not block, this type of lock can be locked at interrupt
level. Obviously, it is undesirable to keep a spin lock locked for a very long period of time.
Spin locks held for long periods of time cause other lockers to consume CPU time by spin-
ning while they are waiting for the lock to become free. In general, a spin lock should not
be held for more than 20 or 30 lines of code.
Process-level code that uses spin locks must take care to raise the IPL high enough to
block all interrupt-level code that also uses the spin lock; otherwise, a processor can
deadlock itself.
NOTE
While a spin lock is held, be sure that there is no possibility that
any of the code attempts to block, causing a context switch.
Switching away from an LWP that holds a spin lock causes that
spin lock to be held for a very long time.
Spin locks are of two types: basic locks and read/write locks. The data structures associ-
ated with each type are defined in sys/ksynch.h. Each of these types is described in
the sections that follow.
First, prior to using a basic lock or a read/write lock, you must define its associated lock
information structure, which is of type lkinfo_t. This is done using the
LKINFO_DECL(D5) kernel macro:
#include <sys/ksynch.h>
#include <sys/ddi.h>
LKINFO_DECL(var, name, flags)
where:
var is the name of the lock information structure of type lkinfo_t. The name
chosen should be a unique driver prefix to distinguish it from other lock name iden-
tifiers.
name is a character string defining a name that identifies the lock. This name should
begin with the driver prefix; it identifies the lock for the purpose of gathering statis-
tics.
flags should always be 0.