locking.9 revision 203131
Copyright (c) 2007 Julian Elischer (julian - freebsd org )
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

$FreeBSD: head/share/man/man9/locking.9 203131 2010-01-28 21:14:12Z trasz $

.Dd January 29, 2010 .Dt LOCKING 9 .Os .Sh NAME .Nm locking .Nd kernel synchronization primitives .Sh DESCRIPTION The .Em FreeBSD kernel is written to run across multiple CPUs and as such requires several different synchronization primitives to allow the developers to safely access and manipulate the many data types required.

p These include: l -enum t Mutexes t Spin mutexes t Pool mutexes t Shared/exclusive locks t Reader/writer locks t Read-mostly locks t Counting semaphores t Condition variables t Sleep/wakeup t Giant t Lockmanager locks .El

p The primitives interact and have a number of rules regarding how they can and can not be combined. Many of these rules are checked using the .Xr witness 4 code.

p .Ss Mutexes Mutexes are the most commonly used synchronization primitive in the kernel. Thread acquires (locks) a mutex before accessing data shared with other threads (including interrupt threads), and releases (unlocks) it afterwards. If the mutex cannot be acquired, the thread requesting it will sleep. Mutexes fully support priority propagation.

p See .Xr mutex 9 for details. .Ss Spin mutexes Spin mutexes are variation of basic mutexes; the main difference between the two is that spin mutexes never sleep - instead, they spin, waiting for the thread holding the lock, which runs on another CPU, to release it. Differently from ordinary mutex, spin mutexes disable interrupts when acquired. Since disabling interrupts is expensive, they are also generally slower. Spin mutexes should only be used to protect data shared with primary (INTR_FILTER) interrupt code. You .Em must not do anything that deschedules the thread while you are holding a spin mutex. .Ss Pool mutexes With most synchronisaton primitives, such as mutexes, programmer must provide a piece of allocated memory to hold the primitive. For example, a mutex may be embedded inside the structure it protects. Pool mutex is a variant of mutex without this requirement - to lock or unlock a pool mutex, one uses address of the structure being protected with it, not the mutex itself. Pool mutexes are seldom used.

p See .Xr mtx_pool 9 for details. .Ss Reader/writer locks Reader/writer locks allow shared access to protected data by multiple threads, or exclusive access by a single thread. The threads with shared access are known as .Em readers since they should only read the protected data. A thread with exclusive access is known as a .Em writer since it may modify protected data.

p Reader/writer locks can be treated as mutexes (see above and .Xr mutex 9 ) with shared/exclusive semantics. More specifically, regular mutexes can be considered to be equivalent to a write-lock on an .Em rw_lock. The .Em rw_lock locks have priority propagation like mutexes, but priority can be propagated only to an exclusive holder. This limitation comes from the fact that shared owners are anonymous. Another important property is that shared holders of .Em rw_lock can recurse, but exclusive locks are not allowed to recurse. This ability should not be used lightly and .Em may go away.

p See .Xr rwlock 9 for details. .Ss Read-mostly locks Mostly reader locks are similar to .Em reader/writer locks but optimized for very infrequent write locking. .Em Read-mostly locks implement full priority propagation by tracking shared owners using a lock user supplied .Em tracker data structure.

p See .Xr rmlock 9 for details. .Ss Shared/exclusive locks Shared/exclusive locks are similar to reader/writer locks; the main difference between them is that shared/exclusive locks may be held during unbounded sleep (and may thus perform an unbounded sleep). They are inherently less efficient than mutexes, reader/writer locks and read-mostly locks. They don't support priority propagation. They should be considered to be closely related to .Xr sleep 9 . In fact it could in some cases be considered a conditional sleep.

p See .Xr sx 9 for details. .Ss Counting semaphores Counting semaphores provide a mechanism for synchronizing access to a pool of resources. Unlike mutexes, semaphores do not have the concept of an owner, so they can be useful in situations where one thread needs to acquire a resource, and another thread needs to release it. They are largely deprecated.

p See .Xr sema 9 for details. .Ss Condition variables Condition variables are used in conjunction with mutexes to wait for conditions to occur. A thread must hold the mutex before calling the .Fn cv_wait* , functions. When a thread waits on a condition, the mutex is atomically released before the thread is blocked, then reacquired before the function call returns.

p See .Xr condvar 9 for details. .Ss Giant Giant is an instance of a mutex, with some special characteristics: l -enum t It is recursive. t Drivers can request that Giant be locked around them, but this is going away. t You can sleep while it has recursed, but other recursive locks cannot. t Giant must be locked first before other locks. t There are places in the kernel that drop Giant and pick it back up again. Sleep locks will do this before sleeping. Parts of the network or VM code may do this as well, depending on the setting of a sysctl. This means that you cannot count on Giant keeping other code from running if your code sleeps, even if you want it to. .El .Ss Sleep/wakeup The functions .Fn tsleep , .Fn msleep , .Fn msleep_spin , .Fn pause , .Fn wakeup , and .Fn wakeup_one handle event-based thread blocking. If a thread must wait for an external event, it is put to sleep by .Fn tsleep , .Fn msleep , .Fn msleep_spin , or .Fn pause . Threads may also wait using one of the locking primitive sleep routines .Xr mtx_sleep 9 , .Xr rw_sleep 9 , or .Xr sx_sleep 9 .

p The parameter .Fa chan is an arbitrary address that uniquely identifies the event on which the thread is being put to sleep. All threads sleeping on a single .Fa chan are woken up later by .Fn wakeup , often called from inside an interrupt routine, to indicate that the resource the thread was blocking on is available now.

p Several of the sleep functions including .Fn msleep , .Fn msleep_spin , and the locking primitive sleep routines specify an additional lock parameter. The lock will be released before sleeping and reacquired before the sleep routine returns. If .Fa priority includes the .Dv PDROP flag, then the lock will not be reacquired before returning. The lock is used to ensure that a condition can be checked atomically, and that the current thread can be suspended without missing a change to the condition, or an associated wakeup. In addition, all of the sleep routines will fully drop the .Va Giant mutex (even if recursed) while the thread is suspended and will reacquire the .Va Giant mutex before the function returns.

p See .Xr sleep 9 for details.

p .Ss Lockmanager locks Shared/exclusive locks, used mostly in .Xr VFS 9 , in particular as a .Xr vnode 9 lock. They have features other lock types don't have, such as sleep timeout, writer starvation avoidance, draining, and interlock mutex, but this makes them complicated to implement; for this reason, they are deprecated.

p See .Xr lock 9 for details. .Sh INTERACTIONS .Ss Bounded vs. unbounded sleep The following primitives perform bounded sleep: mutexes, pool mutexes, reader/writer locks and read-mostly locks.

p The following primitives block (perform unbounded sleep): shared/exclusive locks, counting semaphores, condition variables, sleep/wakeup and lockmanager locks.

p It is an error to do any operation that could result in any kind of sleep while holding spin mutex.

p As a general rule, it is an error to do any operation that could result in unbounded sleep while holding any primitive from the 'bounded sleep' group. For example, it is an error to try to acquire shared/exclusive lock while holding mutex, or to try to allocate memory with M_WAITOK while holding read-write lock.

p As a special case, it is possible to call .Fn sleep 9 or .Fn mtx_sleep 9 while holding a mutex. It will atomically drop the mutex and reacquire it as part of waking up. This is often however a bad idea because it generally relies on you having such a good knowledge of all the call graph above you and what assumptions it is making that there are a lot of ways to make hard-to-find mistakes. For example you must re-test all the assumptions you made before, all the way up the call graph to where you got the lock. You can not just assume that mtx_sleep can be inserted anywhere. If any caller above you has any mutex or rwlock, your sleep, will cause a panic. If the sleep only happens rarely it may be years before the bad code path is found. .Ss Interaction table The following table shows what you can and can not do if you hold one of the synchronization primitives discussed here: (someone who knows what they are talking about should write this table) l -column ".Ic xxxxxxxxxxxxxxxxxxx" ".Xr XXXXXXXXX" ".Xr XXXXXXX" ".Xr XXXXXXX" ".Xr XXXXXXX" ".Xr XXXXXX" -offset indent t Xo .Em "You have: You want:" Ta spin mtx Ta mutex Ta sx Ta rwlock Ta rmlock Ta sleep .Xc t Ic spin mtx Ta ok-1 Ta no Ta no Ta no Ta no Ta no-3 t Ic mutex Ta ok Ta ok-1 Ta no Ta ok Ta ok Ta no-3 t Ic sx Ta ok Ta ok Ta ok-2 Ta ok Ta ok Ta ok-4 t Ic rwlock Ta ok Ta ok Ta no Ta ok-2 Ta ok Ta no-3 t Ic rmlock Ta ok Ta ok Ta no Ta ok Ta ok-2 Ta no .El

p .Em *1 Recursion is defined per lock. Lock order is important.

p .Em *2 readers can recurse though writers can not. Lock order is important.

p .Em *3 There are calls atomically release this primitive when going to sleep and reacquire it on wakeup (e.g. .Fn mtx_sleep , .Fn rw_sleep and .Fn msleep_spin ).

p .Em *4 Though one can sleep holding an sx lock, one can also use .Fn sx_sleep which atomically release this primitive when going to sleep and reacquire it on wakeup. .Ss Context mode table The next table shows what can be used in different contexts. At this time this is a rather easy to remember table. l -column ".Ic Xxxxxxxxxxxxxxxxxxx" ".Xr XXXXXXXXX" ".Xr XXXXXXX" ".Xr XXXXXXX" ".Xr XXXXXXX" ".Xr XXXXXX" -offset indent t Xo .Em "Context:" Ta spin mtx Ta mutex Ta sx Ta rwlock Ta rmlock Ta sleep .Xc t interrupt: Ta ok Ta no Ta no Ta no Ta no Ta no t idle: Ta ok Ta no Ta no Ta no Ta no Ta no .El .Sh SEE ALSO .Xr condvar 9 , .Xr lock 9 , .Xr mtx_pool 9 , .Xr mutex 9 , .Xr rmlock 9 , .Xr rwlock 9 , .Xr sema 9 , .Xr sleep 9 , .Xr sx 9 , .Xr witness 9 , .Xr LOCK_PROFILING 9 .Sh HISTORY These functions appeared in sx 4.1 through .Fx 7.0 .Sh BUGS There are too many locking primitives to choose from.