ATOMIC(9)
Bestie, welcome to ATOMIC(9) from the Kernel Developer's Manual โ the FreeBSD page about atomic operations. ๐ This is part 1, so we're going in.
โจ NAME โจ
atomic_add, atomic_clear, atomic_cmpset, atomic_fcmpset, atomic_fetchadd, atomic_load, atomic_readandclear, atomic_set, atomic_subtract, atomic_store, atomic_thread_fence โ atomic operations. Periodt. ๐
๐ฆ SYNOPSIS ๐ฆ
#include <sys/types.h>
#include <machine/atomic.h>
void
atomic_add_[acq_|rel_]<type>(volatile <type> *p, <type> v);
void
atomic_clear_[acq_|rel_]<type>(volatile <type> *p, <type> v);
int
atomic_cmpset_[acq_|rel_]<type>(volatile <type> *dst, <type> old,
<type> new);
int
atomic_fcmpset_[acq_|rel_]<type>(volatile <type> *dst, <type> *old,
<type> new);
<type>
atomic_fetchadd_<type>(volatile <type> *p, <type> v);
<type>
atomic_load_[acq_]<type>(volatile <type> *p);
<type>
atomic_readandclear_<type>(volatile <type> *p);
void
atomic_set_[acq_|rel_]<type>(volatile <type> *p, <type> v);
void
atomic_subtract_[acq_|rel_]<type>(volatile <type> *p, <type> v);
void
atomic_store_[rel_]<type>(volatile <type> *p, <type> v);
<type>
atomic_swap_<type>(volatile <type> *p, <type> v);
int
atomic_testandclear_<type>(volatile <type> *p, u_int v);
int
atomic_testandset_<type>(volatile <type> *p, u_int v);
void
atomic_thread_fence_[acq|acq_rel|rel|seq_cst](void);
๐ซ DESCRIPTION ๐ซ
Atomic operations are commonly used to implement reference counts and as building blocks for synchronization primitives, such as mutexes. So like, they're the besties behind refcounts and the little LEGO bricks for mutexes and friends. ๐
All of these operations are performed atomically across multiple threads and in the presence of interrupts. That means from the perspective of concurrently running threads and interrupt handlers, they happen in an indivisible way. No half-finished vibes, no peek-a-boo partial updates. โจ
On all architectures supported by FreeBSD, ordinary loads and stores of integers in cache-coherent memory are inherently atomic if the integer is naturally aligned and its size does not exceed the processor's word size. But here's the catch: those ordinary loads and stores may be elided from the program by the compiler, whereas atomic operations are always performed. So atomic ops don't ghost you. ๐
When atomic operations are performed on cache-coherent memory, all operations on the same location are totally ordered. Like, there's a line, and everyone respects it. ๐
When an atomic load is performed on a location in cache-coherent memory, it reads the entire value that was defined by the last atomic store to each byte of the location. An atomic load will never return a value out of thin air. When an atomic store is performed on a location, no other thread or interrupt handler will observe a torn write, or partial modification of the location. Basically: no phantom values, no torn writes. ๐ซ๐ป
Except as noted below, the semantics of these operations are almost identical to the semantics of similarly named C11 atomic operations. Sibling energy, fr fr. ๐ซถ
๐ฎ Types ๐ฎ
Most atomic operations act upon a specific type. That type is indicated in the function name. In contrast to C11 atomic operations, FreeBSD's atomic operations are performed on ordinary integer types. The available types are:
intโ unsigned integerlongโ unsigned long integerptrโ unsigned integer the size of a pointer32โ unsigned 32-bit integer64โ unsigned 64-bit integer
For example, the function to atomically add two integers is called atomic_add_int().
Certain architectures also provide operations for types smaller than int. Those are:
charโ unsigned charactershortโ unsigned short integer8โ unsigned 8-bit integer16โ unsigned 16-bit integer
๐จ These types must not be used in machine-independent code. Keep them architecture-specific, bestie.
๐ Acquire and Release Operations ๐
By default, a thread's accesses to different memory locations might not be performed in program order โ that is, the order in which the accesses appear in the source code. To optimize the program's execution, both the compiler and processor might reorder the thread's accesses. However, both ensure that their reordering of the accesses is not visible to the thread. Otherwise, the traditional memory model that is expected by single-threaded programs would be violated. Nonetheless, other threads in a multithreaded program, such as the FreeBSD kernel, might observe the reordering. Moreover, in some cases, such as the implementation of synchronization between threads, arbitrary reordering might result in the incorrect execution of the program. To constrain the reordering that both the compiler and processor might perform on a thread's accesses, a programmer can use atomic operations with acquire and release semantics. Slay. ๐ฅ
Atomic operations on memory have up to three variants. The first, or relaxed variant, performs the operation without imposing any ordering constraints on accesses to other memory locations. This variant is the default. The second variant has acquire semantics, and the third variant has release semantics. Three flavors, one iconic lineup. ๐
When an atomic operation has acquire semantics, the operation must have completed before any subsequent load or store (by program order) is performed. Conversely, acquire semantics do not require that prior loads or stores have completed before the atomic operation is performed. An atomic operation can only have acquire semantics if it performs a load from memory. To denote acquire semantics, the suffix _acq is inserted into the function name immediately prior to the _โจtypeโฉ suffix. For example, to subtract two integers ensuring that the subtraction is completed before any subsequent loads and stores are performed, use atomic_subtract_acq_int(). ๐
When an atomic operation has release semantics, all prior loads or stores (by program order) must have completed before the operation is performed. Conversely, release semantics do not require that the atomic operation must have completed before any subsequent load or store is performed. An atomic operation can only have release semantics if it performs a store to memory. To denote release semantics, the suffix _rel is inserted into the function name immediately prior to the _โจtypeโฉ suffix. For example, to add two long integers ensuring that all prior loads and stores are completed before the addition is performed, use atomic_add_rel_long(). ๐
When a release operation by one thread synchronizes with an acquire operation by another thread, usually meaning that the acquire operation reads the value written by the release operation, then the effects of all prior stores by the releasing thread must become visible to subsequent loads by the acquiring thread. Moreover, the effects of all stores (by other threads) that were visible to the releasing thread must also become visible to the acquiring thread. These rules only apply to the synchronizing threads. Other threads might observe these stores in a different order. No cap. ๐ง
In effect, atomic operations with acquire and release semantics establish one-way barriers to reordering that enable the implementations of synchronization primitives to express their ordering requirements without also imposing unnecessary ordering. For example, for a critical section guarded by a mutex, an acquire operation when the mutex is locked and a release operation when the mutex is unlocked will prevent any loads or stores from moving outside of the critical section. However, they will not prevent the compiler or processor from moving loads or stores into the critical section, which does not violate the semantics of a mutex. It's giving efficient. ๐ฅ
๐ง Thread Fence Operations ๐ง
Alternatively, a programmer can use atomic thread fence operations to constrain the reordering of accesses. In contrast to other atomic operations, fences do not, themselves, access memory. They're just out here enforcing order, not touching the memory. ๐
When a fence has acquire semantics, all prior loads (by program order) must have completed before any subsequent load or store is performed. Thus, an acquire fence is a two-way barrier for load operations. To denote acquire semantics, the suffix _acq is appended to the function name, for example, atomic_thread_fence_acq(). โจ
When a fence has release semantics, all prior loads or stores (by program order) must have completed before any subsequent store operation is performed. Thus, a release fence is a two-way barrier for store operations. To denote release semantics, the suffix _rel is appended to the function name, for example, atomic_thread_fence_rel(). ๐
Although atomic_thread_fence_acq_rel() implements both acquire and release semantics, it is not a full barrier. For example, a store prior to the fence (in program order) may be completed after a load subsequent to the fence. In contrast, atomic_thread_fence_seq_cst() implements a full barrier. Neither loads nor stores may cross this barrier in either direction. It's giving "you shall not pass" in both directions. ๐
In C11, a release fence by one thread synchronizes with an acquire fence by another thread when an atomic load that is prior to the acquire fence (by program order) reads the value written by an atomic store that is subsequent to the release fence. In contrast, in FreeBSD, because of the atomicity of ordinary, naturally aligned loads and stores, fences can also be synchronized by ordinary loads and stores. This simplifies the implementation and use of some synchronization primitives in FreeBSD. ๐ซถ
Since neither a compiler nor a processor can foresee which (atomic) load will read the value written by an (atomic) store, the ordering constraints imposed by fences must be more restrictive than acquire loads and release stores. Essentially, this is why fences are two-way barriers. It's just math, bestie. ๐ฅ
Although fences impose more restrictive ordering than acquire loads and release stores, by separating access from ordering, they can sometimes facilitate more efficient implementations of synchronization primitives. For example, they can be used to avoid executing a memory barrier until a memory access shows that some condition is satisfied. Efficiency icon behavior. ๐
๐ Multiple Processors ๐
In multiprocessor systems, the atomicity of the atomic operations on memory depends on support for cache coherence in the underlying architecture. In general, cache coherence on the default memory type, VM_MEMATTR_DEFAULT, is guaranteed by all architectures that are supported by FreeBSD. For example, cache coherence is guaranteed on write-back memory by the amd64 and i386 architectures. However, on some architectures, cache coherence might not be enabled on all memory types. To determine if cache coherence is enabled for a non-default memory type, consult the architecture's documentation. So yeah, check your architecture's docs if you're not on default memory type. ๐
๐ Semantics ๐
This section describes the semantics of each operation using a C like notation.
atomic_add(p, v)
*p += v;
atomic_clear(p, v)
*p &= ~v;
atomic_cmpset(dst, old, new)
if (*dst == old) {
*dst = new;
return (1);
} else
return (0);
Some architectures straight up do not implement the atomic_cmpset() functions for the types โcharโ, โshortโ, โ8โ, and โ16โ. ๐ not every platform got the memo, bestie.
โจ the atomic_fcmpset() tea โจ
atomic_fcmpset(dst, *old, new)
On architectures that implement the Compare And Swap operation in hardware, the functionality can be described as
if (*dst == *old) {
*dst = new;
return (1);
} else {
*old = *dst;
return (0);
}
On architectures which provide the Load Linked/Store Conditional primitive, the write to *dst might also fail for several reasons, most important of which is a parallel write to the *dst cache line by another CPU. ๐ In this case the atomic_fcmpset() function also returns false, despite
*old == *dst.
Like, it looked equal but the vibes were off. It's giving "he's literally right there but the timing said no." ๐ญ
And again, some architectures don't implement the atomic_fcmpset() functions for the types โcharโ, โshortโ, โ8โ, and โ16โ. ๐
๐ the rest of the operations, one by one ๐
atomic_fetchadd(p, v)
tmp = *p;
*p += v;
return (tmp);
The atomic_fetchadd() functions are only implemented for the types โintโ, โlongโ and โ32โ, and do not have any variants with memory barriers at this time. that's it, that's the list. ๐ซถ
atomic_load(p)
return (*p);
atomic_readandclear(p)
tmp = *p;
*p = 0;
return (tmp);
The atomic_readandclear() functions are not implemented for the types โcharโ, โshortโ, โptrโ, โ8โ, and โ16โ, and do not have any variants with memory barriers at this time. ๐
atomic_set(p, v)
*p |= v;
atomic_subtract(p, v)
*p -= v;
atomic_store(p, v)
*p = v;
atomic_swap(p, v)
tmp = *p;
*p = v;
return (tmp);
The atomic_swap() functions are not implemented for the types โcharโ, โshortโ, โptrโ, โ8โ, and โ16โ, and do not have any variants with memory barriers at this time. ๐
โโ๏ธ
atomic_testandclear(p, v)
bit = 1 << (v % (sizeof(*p) * NBBY));
tmp = (*p & bit) != 0;
*p &= ~bit;
return (tmp);
atomic_testandset(p, v)
bit = 1 << (v % (sizeof(*p) * NBBY));
tmp = (*p & bit) != 0;
*p |= bit;
return (tmp);
The atomic_testandset() and atomic_testandclear() functions are only implemented for the types โintโ, โlongโ and โ32โ, and do not have any variants with memory barriers at this time. ๐ธ
heads up bestie: the typeโ64โis currently not implemented for some of the atomic operations on thearm,i386, andpowerpcarchitectures. so like. check before you ship. ๐
๐ RETURN VALUES ๐
Okay so what do you actually get back? ๐
- The
atomic_cmpset()function returns the result of the compare operation. - The
atomic_fcmpset()function returns true if the operation succeeded. Otherwise it returns false and sets*oldto the found value. (yes, it hands you the receipts. ๐งพ) - The
atomic_fetchadd(),atomic_load(),atomic_readandclear(), andatomic_swap()functions return the value at the specified address. - The
atomic_testandset()andatomic_testandclear()function returns the result of the test operation.
๐ฆ EXAMPLES ๐ฆ
This example uses the atomic_cmpset_acq_ptr() and atomic_set_ptr() functions to obtain a sleep mutex and handle recursion. Since the mtx_lock member of a struct mtx is a pointer, the โptrโ type is used. โจ
/* Try to obtain mtx_lock once. */
#define _obtain_lock(mp, tid) \
atomic_cmpset_acq_ptr(&(mp)->mtx_lock, MTX_UNOWNED, (tid))
/* Get a sleep lock, deal with recursion inline. */
#define _get_sleep_lock(mp, tid, opts, file, line) do { \
uintptr_t _tid = (uintptr_t)(tid); \
\
if (!_obtain_lock(mp, tid)) { \
if (((mp)->mtx_lock & MTX_FLAGMASK) != _tid) \
_mtx_lock_sleep((mp), _tid, (opts), (file), (line));\
else { \
atomic_set_ptr(&(mp)->mtx_lock, MTX_RECURSE); \
(mp)->mtx_recurse++; \
} \
} \
} while (0)
ate. no crumbs. the macro is eating. ๐
๐ HISTORY ๐
the lore drop, fr fr:
- The
atomic_add(),atomic_clear(),atomic_set(), andatomic_subtract()operations were introduced in FreeBSD 3.0. Initially, these operations were defined on the typesโcharโ,โshortโ,โintโ, andโlongโ. - The
atomic_cmpset(),atomic_load_acq(),atomic_readandclear(), andatomic_store_rel()operations were added in FreeBSD 5.0. Simultaneously, the acquire and release variants were introduced, and support was added for operation on the typesโ8โ,โ16โ,โ32โ,โ64โ, andโptrโ. glow up era. โจ - The
atomic_fetchadd()operation was added in FreeBSD 6.0. - The
atomic_swap()andatomic_testandset()operations were added in FreeBSD 10.0. - The
atomic_testandclear()andatomic_thread_fence()operations were added in FreeBSD 11.0. - The relaxed variants of
atomic_load()andatomic_store()were added in FreeBSD 12.0.
and that's the whole page bestie ๐ this one came from the Debian crew, dated August 18, 2019, and it lives under ATOMIC(9). go be atomic, stay safe, and remember: if it's not atomic, it's not the moment. ๐
๐ซถ
๐ฆ where this page comes from
- debian bookworm: freebsd-manpages 12.2-1 ยท BSD-2-Clause-FreeBSD AND BSD-4-Clause
- debian trixie: freebsd-manpages 12.2-2 ยท BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu jammy: freebsd-manpages 12.2-1 ยท BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu noble: freebsd-manpages 12.2-1 ยท BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu questing: freebsd-manpages 12.2-2
- ubuntu resolute: freebsd-manpages 12.2-2build1 ยท BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu stonking: freebsd-manpages 12.2-2build1 ยท BSD-2-Clause-FreeBSD AND BSD-4-Clause
- Copyright (c) 2000-2001 John H. Baldwin <jhb@FreeBSD.org>
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms