The FreeBSD syncronization primitives set is based on the idea to supply a rather huge number of different primitives in a way that the better one can be used for every particular, appropriate situation. To an high level point of view you can consider three kinds of syncronization primitives in the FreeBSD kernel: - atomic operations / memory barriers - locks - scheduling barriers Below there are descriptions for the 4 families. For every lock, you should really check the linked manpage (where possible) for more detailed explanatories. * Atomic operations / memory barriers Atomic operations are implemented through a set of functions performing simple aritmetics on memory operands in an atomic way respect external events (interrupts, preemption, etc). Atomic operations can guarantee atomicity just on small data types (in the magnitude order of the 'long' architecture C data type), so should be rarely used in end-level code directly, if not only for very simple operations (like flag setting in a bitmap, for example). Infact, it is rather simple and common to write down a wrong semantic just based on atomic operations (usually referred as lock-less). FreeBSD kernel offers a way to perform atomic operations in conjuction with a memory barrier. The memory barriers will guarantee that an atomic operation will happen following some specified ordering respect other memory accesses. For example, if we need that an atomic operation happens just after all other pending writes (in terms of instructions reordering buffers activities) are completed, we need to explicitly use a memory barrier in conjuction to this atomic operation. So it is simple to understand why memory barriers play a key role for higher-level locks building (just as refcounts, mutexes, etc.). XXX: adding discussion on aligned memory atomic operations & volatile For a detailed explanatory on atomic operations, please refer to atomic(9). It is far, however, noting that atomic operations (and memory barriers too) should, ideally, only be used for building front-ending locks (as mutexes). * Refcounts Refcounts are interfaces for handling reference counters. They are implemented through atomic operations and are intended to be used just for cases where the reference counter is the only one thing to be protected, so even something like a spin-mutex is deprecated. Using the refcount interface for structures where a mutex is alredy used is often wrong since we should probabilly close the reference counter in some alredy protected paths. A manpage discussing refcount doesn't exist currently, just check sys/refcount.h for an overview of the existing API. * Locks FreeBSD kernel has an huge class of locks. Every lock is defined by some peculiar properties, but probabilly the most important is the event linked to contesting holders (or, in other terms, the behaviour of threads unable to acquire the lock). FreeBSD locking scheme presents 3 different behaviours for contenders: 0. spinning 1. blocking 2. sleeping (NOTE: numbers are not casual) - Spinning Spin locks let waiters to spin until they can't acquire the lock. An important matter do deal with is that when a thread contests on a spin lock it is not descheduled. Since FreeBSD kernel is preemptive, this exposes spin lock at the risk of deadlocks that can be solved just disabling interrupts while they are acquired. For this and other reasons (like lack of priority propagation support, poorness in load balancing schemes between CPUs, etc.), spin locks are intended to protect very small paths of code, or ideally to not be used at all if not explicitly requested (explained later). - Blocking Block locks let waiters to be descheduled and blocked until the lock owner doesn't drop it and wakes up one or more contenders. In order to avoid starvation issues, blocking locks do priority propagation from the waiters to the owner. Block locks must be implemented through the turnstile interface and are intended to be the most used kind of locks in the kernel, if no particular conditions are met. - Sleeping Sleep locks let waiters to be descheduled and fall asleep until the lock holder doesn't drop it and wakes up one or more waiters. Since sleep locks are intended to protect large paths of code and to cater asyncronous events, they don't do any form of priority propagation. They must be implemented through the sleepqueue(9) interface. The order used to acquire locks is very important, not only for the possibility to deadlock due at lock order reversals, but even beacause lock acquisition should follow specific rules linked to locks natures. If you give a look at the table above, the practical rule is that if a thread holds a lock of level n (where the level is the number listed close to the kind of lock) it isn't allowed to acquire a lock of superior levels, since this would break the specified semantic for a path. For example, if a thread holds a block lock (level 1), it is allowed to acquire a spin lock (level 0) but not a sleep lock (level 2), since block locks are intended to protect smaller paths than sleep lock (these rules aren't about atomic operations or scheduling barriers, however). This is a list of lock with their respective behaviours: - spin mutex - spinning - mutex(9) - sleep mutex - blocking - mutex(9) - pool mutex - blocking - mtx_pool(9) - sleep family - sleeping - sleep(9) pause tsleep msleep msleep_spin msleep_rw msleep_sx - condvar - sleeping - condvar(9) - rwlock - blocking - rwlock(9) - sxlock - sleeping - sx(9) - lockmgr - sleeping - lockmgr(9) - semaphores - sleeping - sema(9) Among these locks only mutexes, sxlocks, rwlocks and lockmgrs are intended to handle recursion, but currently recursion is only supported by mutexes and lockmgrs. XXX: Put in evidence that WITNESS is used in order to detect applied locking strategies. * Scheduling barriers Scheduling barriers are intended to be used in order to drive scheduling of threading using it. They consist mainly of 3 different stubs: - critical sections (and preemption) - sched_bind - sched_pin Generally, these should be used only in particular context and even if they can often replace locks, they should be avoided beacause don't let diagnose simply eventual problems with locking debugging tools (as WITNESS). - Critical sections FreeBSD kernel has been made preemptive basically in order to deal with interrupt threads. Infact, in order to avoid a too high interrupt latency, time-sharing priority threads can be preempted by interrpt threads (that, in this way, don't need to wait to be scheduled as the normal path previews). Preemption, however, introduces new racing points that need to be handled as well. Often, in order to deal with preemption, the simplest thing to do is to completely disable it. A critical section, so, defines a piece of code (broderlined by the pair of functions critical_enter()/critical_exit()) where preemption is guaranteed to not happen (until the protected code is fully executed). This can often replace a lock effectively but should be used carefully in order to not lose the whole advantage that preemption brings. * sched_pin/sched_unpin Another way to deal with preemption is the sched_pin() interface. If a piece of code is closed in the sched_pin()/sched_unpin() pair of functions it is guaranteed that the respective thread, even if it can be still preempted, will always be executed on the same CPU. Pinning results very effective in the particular case we have to access at per-cpu datas and we assume other threads won't change those datas. The not-changing condition, will determine a critical section as a too strong condition for our code. * sched_bind/sched_unbind sched_bind is an API used in order to bind a thread to a particular CPU for all the time it is executed the code, until a sched_unbind() function call doesn't unbind it. This feature has a key role in situations where you can't trust about the current state of CPUs (as, for example, very early stages of boot), as you want to avoid your thread to migrate on inactive CPUs. Since sched_bind/sched_unbind manipulate internal scheduler structures, they need to be enclosed in sched_lock acquisition/releasing when used. XXX: APPENDIX A: Why we have to use spin locks in fast interrupt handlers or this should be merged in the spin-lock section?