xref: /freebsd/share/man/man9/atomic.9 (revision 608da65de9552d5678c1000776ed69da04a45983)
1.\" Copyright (c) 2000-2001 John H. Baldwin <jhb@FreeBSD.org>
2.\"
3.\" Redistribution and use in source and binary forms, with or without
4.\" modification, are permitted provided that the following conditions
5.\" are met:
6.\" 1. Redistributions of source code must retain the above copyright
7.\"    notice, this list of conditions and the following disclaimer.
8.\" 2. Redistributions in binary form must reproduce the above copyright
9.\"    notice, this list of conditions and the following disclaimer in the
10.\"    documentation and/or other materials provided with the distribution.
11.\"
12.\" THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY EXPRESS OR
13.\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
14.\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
15.\" IN NO EVENT SHALL THE DEVELOPERS BE LIABLE FOR ANY DIRECT, INDIRECT,
16.\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
17.\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
18.\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
19.\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
20.\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
21.\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22.\"
23.Dd January 16, 2023
24.Dt ATOMIC 9
25.Os
26.Sh NAME
27.Nm atomic_add ,
28.Nm atomic_clear ,
29.Nm atomic_cmpset ,
30.Nm atomic_fcmpset ,
31.Nm atomic_fetchadd ,
32.Nm atomic_interrupt_fence ,
33.Nm atomic_load ,
34.Nm atomic_readandclear ,
35.Nm atomic_set ,
36.Nm atomic_subtract ,
37.Nm atomic_store ,
38.Nm atomic_thread_fence
39.Nd atomic operations
40.Sh SYNOPSIS
41.In machine/atomic.h
42.Ft void
43.Fn atomic_add_[acq_|rel_]<type> "volatile <type> *p" "<type> v"
44.Ft void
45.Fn atomic_clear_[acq_|rel_]<type> "volatile <type> *p" "<type> v"
46.Ft int
47.Fo atomic_cmpset_[acq_|rel_]<type>
48.Fa "volatile <type> *dst"
49.Fa "<type> old"
50.Fa "<type> new"
51.Fc
52.Ft int
53.Fo atomic_fcmpset_[acq_|rel_]<type>
54.Fa "volatile <type> *dst"
55.Fa "<type> *old"
56.Fa "<type> new"
57.Fc
58.Ft <type>
59.Fn atomic_fetchadd_<type> "volatile <type> *p" "<type> v"
60.Ft void
61.Fn atomic_interrupt_fence "void"
62.Ft <type>
63.Fn atomic_load_[acq_]<type> "volatile <type> *p"
64.Ft <type>
65.Fn atomic_readandclear_<type> "volatile <type> *p"
66.Ft void
67.Fn atomic_set_[acq_|rel_]<type> "volatile <type> *p" "<type> v"
68.Ft void
69.Fn atomic_subtract_[acq_|rel_]<type> "volatile <type> *p" "<type> v"
70.Ft void
71.Fn atomic_store_[rel_]<type> "volatile <type> *p" "<type> v"
72.Ft <type>
73.Fn atomic_swap_<type> "volatile <type> *p" "<type> v"
74.Ft int
75.Fn atomic_testandclear_<type> "volatile <type> *p" "u_int v"
76.Ft int
77.Fn atomic_testandset_<type> "volatile <type> *p" "u_int v"
78.Ft void
79.Fn atomic_thread_fence_[acq|acq_rel|rel|seq_cst] "void"
80.Sh DESCRIPTION
81Atomic operations are commonly used to implement reference counts and as
82building blocks for synchronization primitives, such as mutexes.
83.Pp
84All of these operations are performed
85.Em atomically
86across multiple threads and in the presence of interrupts, meaning that they
87are performed in an indivisible manner from the perspective of concurrently
88running threads and interrupt handlers.
89.Pp
90On all architectures supported by
91.Fx ,
92ordinary loads and stores of integers in cache-coherent memory are
93inherently atomic if the integer is naturally aligned and its size does not
94exceed the processor's word size.
95However, such loads and stores may be elided from the program by
96the compiler, whereas atomic operations are always performed.
97.Pp
98When atomic operations are performed on cache-coherent memory, all
99operations on the same location are totally ordered.
100.Pp
101When an atomic load is performed on a location in cache-coherent memory,
102it reads the entire value that was defined by the last atomic store to
103each byte of the location.
104An atomic load will never return a value out of thin air.
105When an atomic store is performed on a location, no other thread or
106interrupt handler will observe a
107.Em torn write ,
108or partial modification of the location.
109.Pp
110Except as noted below, the semantics of these operations are almost
111identical to the semantics of similarly named C11 atomic operations.
112.Ss Types
113Most atomic operations act upon a specific
114.Fa type .
115That type is indicated in the function name.
116In contrast to C11 atomic operations,
117.Fx Ns 's
118atomic operations are performed on ordinary integer types.
119The available types are:
120.Pp
121.Bl -tag -offset indent -width short -compact
122.It Li int
123unsigned integer
124.It Li long
125unsigned long integer
126.It Li ptr
127unsigned integer the size of a pointer
128.It Li 32
129unsigned 32-bit integer
130.It Li 64
131unsigned 64-bit integer
132.El
133.Pp
134For example, the function to atomically add two integers is called
135.Fn atomic_add_int .
136.Pp
137Certain architectures also provide operations for types smaller than
138.Dq Li int .
139.Pp
140.Bl -tag -offset indent -width short -compact
141.It Li char
142unsigned character
143.It Li short
144unsigned short integer
145.It Li 8
146unsigned 8-bit integer
147.It Li 16
148unsigned 16-bit integer
149.El
150.Pp
151These types must not be used in machine-independent code.
152.Ss Acquire and Release Operations
153By default, a thread's accesses to different memory locations might not be
154performed in
155.Em program order ,
156that is, the order in which the accesses appear in the source code.
157To optimize the program's execution, both the compiler and processor might
158reorder the thread's accesses.
159However, both ensure that their reordering of the accesses is not visible to
160the thread.
161Otherwise, the traditional memory model that is expected by single-threaded
162programs would be violated.
163Nonetheless, other threads in a multithreaded program, such as the
164.Fx
165kernel, might observe the reordering.
166Moreover, in some cases, such as the implementation of synchronization between
167threads, arbitrary reordering might result in the incorrect execution of the
168program.
169To constrain the reordering that both the compiler and processor might perform
170on a thread's accesses, a programmer can use atomic operations with
171.Em acquire
172and
173.Em release
174semantics.
175.Pp
176Atomic operations on memory have up to three variants.
177The first, or
178.Em relaxed
179variant, performs the operation without imposing any ordering constraints on
180accesses to other memory locations.
181This variant is the default.
182The second variant has acquire semantics, and the third variant has release
183semantics.
184.Pp
185When an atomic operation has acquire semantics, the operation must have
186completed before any subsequent load or store (by program order) is
187performed.
188Conversely, acquire semantics do not require that prior loads or stores have
189completed before the atomic operation is performed.
190An atomic operation can only have acquire semantics if it performs a load
191from memory.
192To denote acquire semantics, the suffix
193.Dq Li _acq
194is inserted into the function name immediately prior to the
195.Dq Li _ Ns Aq Fa type
196suffix.
197For example, to subtract two integers ensuring that the subtraction is
198completed before any subsequent loads and stores are performed, use
199.Fn atomic_subtract_acq_int .
200.Pp
201When an atomic operation has release semantics, all prior loads or stores
202(by program order) must have completed before the operation is performed.
203Conversely, release semantics do not require that the atomic operation must
204have completed before any subsequent load or store is performed.
205An atomic operation can only have release semantics if it performs a store
206to memory.
207To denote release semantics, the suffix
208.Dq Li _rel
209is inserted into the function name immediately prior to the
210.Dq Li _ Ns Aq Fa type
211suffix.
212For example, to add two long integers ensuring that all prior loads and
213stores are completed before the addition is performed, use
214.Fn atomic_add_rel_long .
215.Pp
216When a release operation by one thread
217.Em synchronizes with
218an acquire operation by another thread, usually meaning that the acquire
219operation reads the value written by the release operation, then the effects
220of all prior stores by the releasing thread must become visible to
221subsequent loads by the acquiring thread.
222Moreover, the effects of all stores (by other threads) that were visible to
223the releasing thread must also become visible to the acquiring thread.
224These rules only apply to the synchronizing threads.
225Other threads might observe these stores in a different order.
226.Pp
227In effect, atomic operations with acquire and release semantics establish
228one-way barriers to reordering that enable the implementations of
229synchronization primitives to express their ordering requirements without
230also imposing unnecessary ordering.
231For example, for a critical section guarded by a mutex, an acquire operation
232when the mutex is locked and a release operation when the mutex is unlocked
233will prevent any loads or stores from moving outside of the critical
234section.
235However, they will not prevent the compiler or processor from moving loads
236or stores into the critical section, which does not violate the semantics of
237a mutex.
238.Ss Thread Fence Operations
239Alternatively, a programmer can use atomic thread fence operations to
240constrain the reordering of accesses.
241In contrast to other atomic operations, fences do not, themselves, access
242memory.
243.Pp
244When a fence has acquire semantics, all prior loads (by program order) must
245have completed before any subsequent load or store is performed.
246Thus, an acquire fence is a two-way barrier for load operations.
247To denote acquire semantics, the suffix
248.Dq Li _acq
249is appended to the function name, for example,
250.Fn atomic_thread_fence_acq .
251.Pp
252When a fence has release semantics, all prior loads or stores (by program
253order) must have completed before any subsequent store operation is
254performed.
255Thus, a release fence is a two-way barrier for store operations.
256To denote release semantics, the suffix
257.Dq Li _rel
258is appended to the function name, for example,
259.Fn atomic_thread_fence_rel .
260.Pp
261Although
262.Fn atomic_thread_fence_acq_rel
263implements both acquire and release semantics, it is not a full barrier.
264For example, a store prior to the fence (in program order) may be completed
265after a load subsequent to the fence.
266In contrast,
267.Fn atomic_thread_fence_seq_cst
268implements a full barrier.
269Neither loads nor stores may cross this barrier in either direction.
270.Pp
271In C11, a release fence by one thread synchronizes with an acquire fence by
272another thread when an atomic load that is prior to the acquire fence (by
273program order) reads the value written by an atomic store that is subsequent
274to the release fence.
275In constrast, in
276.Fx ,
277because of the atomicity of ordinary, naturally
278aligned loads and stores, fences can also be synchronized by ordinary loads
279and stores.
280This simplifies the implementation and use of some synchronization
281primitives in
282.Fx .
283.Pp
284Since neither a compiler nor a processor can foresee which (atomic) load
285will read the value written by an (atomic) store, the ordering constraints
286imposed by fences must be more restrictive than acquire loads and release
287stores.
288Essentially, this is why fences are two-way barriers.
289.Pp
290Although fences impose more restrictive ordering than acquire loads and
291release stores, by separating access from ordering, they can sometimes
292facilitate more efficient implementations of synchronization primitives.
293For example, they can be used to avoid executing a memory barrier until a
294memory access shows that some condition is satisfied.
295.Ss Interrupt Fence Operations
296The
297.Fn atomic_interrupt_fence
298function establishes ordering between its call location and any interrupt
299handler executing on the same CPU.
300It is modeled after the similar C11 function
301.Fn atomic_signal_fence ,
302and adapted for the kernel environment.
303.Ss Multiple Processors
304In multiprocessor systems, the atomicity of the atomic operations on memory
305depends on support for cache coherence in the underlying architecture.
306In general, cache coherence on the default memory type,
307.Dv VM_MEMATTR_DEFAULT ,
308is guaranteed by all architectures that are supported by
309.Fx .
310For example, cache coherence is guaranteed on write-back memory by the
311.Tn amd64
312and
313.Tn i386
314architectures.
315However, on some architectures, cache coherence might not be enabled on all
316memory types.
317To determine if cache coherence is enabled for a non-default memory type,
318consult the architecture's documentation.
319.Ss Semantics
320This section describes the semantics of each operation using a C like notation.
321.Bl -hang
322.It Fn atomic_add p v
323.Bd -literal -compact
324*p += v;
325.Ed
326.It Fn atomic_clear p v
327.Bd -literal -compact
328*p &= ~v;
329.Ed
330.It Fn atomic_cmpset dst old new
331.Bd -literal -compact
332if (*dst == old) {
333	*dst = new;
334	return (1);
335} else
336	return (0);
337.Ed
338.El
339.Pp
340Some architectures do not implement the
341.Fn atomic_cmpset
342functions for the types
343.Dq Li char ,
344.Dq Li short ,
345.Dq Li 8 ,
346and
347.Dq Li 16 .
348.Bl -hang
349.It Fn atomic_fcmpset dst *old new
350.El
351.Pp
352On architectures implementing
353.Em Compare And Swap
354operation in hardware, the functionality can be described as
355.Bd -literal -offset indent -compact
356if (*dst == *old) {
357	*dst = new;
358	return (1);
359} else {
360	*old = *dst;
361	return (0);
362}
363.Ed
364On architectures which provide
365.Em Load Linked/Store Conditional
366primitive, the write to
367.Dv *dst
368might also fail for several reasons, most important of which
369is a parallel write to
370.Dv *dst
371cache line by other CPU.
372In this case
373.Fn atomic_fcmpset
374function also returns
375.Dv false ,
376despite
377.Dl *old == *dst .
378.Pp
379Some architectures do not implement the
380.Fn atomic_fcmpset
381functions for the types
382.Dq Li char ,
383.Dq Li short ,
384.Dq Li 8 ,
385and
386.Dq Li 16 .
387.Bl -hang
388.It Fn atomic_fetchadd p v
389.Bd -literal -compact
390tmp = *p;
391*p += v;
392return (tmp);
393.Ed
394.El
395.Pp
396The
397.Fn atomic_fetchadd
398functions are only implemented for the types
399.Dq Li int ,
400.Dq Li long
401and
402.Dq Li 32
403and do not have any variants with memory barriers at this time.
404.Bl -hang
405.It Fn atomic_load p
406.Bd -literal -compact
407return (*p);
408.Ed
409.It Fn atomic_readandclear p
410.Bd -literal -compact
411tmp = *p;
412*p = 0;
413return (tmp);
414.Ed
415.El
416.Pp
417The
418.Fn atomic_readandclear
419functions are not implemented for the types
420.Dq Li char ,
421.Dq Li short ,
422.Dq Li ptr ,
423.Dq Li 8 ,
424and
425.Dq Li 16
426and do not have any variants with memory barriers at this time.
427.Bl -hang
428.It Fn atomic_set p v
429.Bd -literal -compact
430*p |= v;
431.Ed
432.It Fn atomic_subtract p v
433.Bd -literal -compact
434*p -= v;
435.Ed
436.It Fn atomic_store p v
437.Bd -literal -compact
438*p = v;
439.Ed
440.It Fn atomic_swap p v
441.Bd -literal -compact
442tmp = *p;
443*p = v;
444return (tmp);
445.Ed
446.El
447.Pp
448The
449.Fn atomic_swap
450functions are not implemented for the types
451.Dq Li char ,
452.Dq Li short ,
453.Dq Li ptr ,
454.Dq Li 8 ,
455and
456.Dq Li 16
457and do not have any variants with memory barriers at this time.
458.Bl -hang
459.It Fn atomic_testandclear p v
460.Bd -literal -compact
461bit = 1 << (v % (sizeof(*p) * NBBY));
462tmp = (*p & bit) != 0;
463*p &= ~bit;
464return (tmp);
465.Ed
466.El
467.Bl -hang
468.It Fn atomic_testandset p v
469.Bd -literal -compact
470bit = 1 << (v % (sizeof(*p) * NBBY));
471tmp = (*p & bit) != 0;
472*p |= bit;
473return (tmp);
474.Ed
475.El
476.Pp
477The
478.Fn atomic_testandset
479and
480.Fn atomic_testandclear
481functions are only implemented for the types
482.Dq Li int ,
483.Dq Li long
484and
485.Dq Li 32
486and do not have any variants with memory barriers at this time.
487.Pp
488The type
489.Dq Li 64
490is currently not implemented for some of the atomic operations on the
491.Tn arm ,
492.Tn i386 ,
493and
494.Tn powerpc
495architectures.
496.Sh RETURN VALUES
497The
498.Fn atomic_cmpset
499function returns the result of the compare operation.
500The
501.Fn atomic_fcmpset
502function returns
503.Dv true
504if the operation succeeded.
505Otherwise it returns
506.Dv false
507and sets
508.Va *old
509to the found value.
510The
511.Fn atomic_fetchadd ,
512.Fn atomic_load ,
513.Fn atomic_readandclear ,
514and
515.Fn atomic_swap
516functions return the value at the specified address.
517The
518.Fn atomic_testandset
519and
520.Fn atomic_testandclear
521function returns the result of the test operation.
522.Sh EXAMPLES
523This example uses the
524.Fn atomic_cmpset_acq_ptr
525and
526.Fn atomic_set_ptr
527functions to obtain a sleep mutex and handle recursion.
528Since the
529.Va mtx_lock
530member of a
531.Vt "struct mtx"
532is a pointer, the
533.Dq Li ptr
534type is used.
535.Bd -literal
536/* Try to obtain mtx_lock once. */
537#define _obtain_lock(mp, tid)						\\
538	atomic_cmpset_acq_ptr(&(mp)->mtx_lock, MTX_UNOWNED, (tid))
539
540/* Get a sleep lock, deal with recursion inline. */
541#define _get_sleep_lock(mp, tid, opts, file, line) do {			\\
542	uintptr_t _tid = (uintptr_t)(tid);				\\
543									\\
544	if (!_obtain_lock(mp, tid)) {					\\
545		if (((mp)->mtx_lock & MTX_FLAGMASK) != _tid)		\\
546			_mtx_lock_sleep((mp), _tid, (opts), (file), (line));\\
547		else {							\\
548			atomic_set_ptr(&(mp)->mtx_lock, MTX_RECURSE);	\\
549			(mp)->mtx_recurse++;				\\
550		}							\\
551	}								\\
552} while (0)
553.Ed
554.Sh HISTORY
555The
556.Fn atomic_add ,
557.Fn atomic_clear ,
558.Fn atomic_set ,
559and
560.Fn atomic_subtract
561operations were introduced in
562.Fx 3.0 .
563Initially, these operations were defined on the types
564.Dq Li char ,
565.Dq Li short ,
566.Dq Li int ,
567and
568.Dq Li long .
569.Pp
570The
571.Fn atomic_cmpset ,
572.Fn atomic_load_acq ,
573.Fn atomic_readandclear ,
574and
575.Fn atomic_store_rel
576operations were added in
577.Fx 5.0 .
578Simultaneously, the acquire and release variants were introduced, and
579support was added for operation on the types
580.Dq Li 8 ,
581.Dq Li 16 ,
582.Dq Li 32 ,
583.Dq Li 64 ,
584and
585.Dq Li ptr .
586.Pp
587The
588.Fn atomic_fetchadd
589operation was added in
590.Fx 6.0 .
591.Pp
592The
593.Fn atomic_swap
594and
595.Fn atomic_testandset
596operations were added in
597.Fx 10.0 .
598.Pp
599The
600.Fn atomic_testandclear
601and
602.Fn atomic_thread_fence
603operations were added in
604.Fx 11.0 .
605.Pp
606The relaxed variants of
607.Fn atomic_load
608and
609.Fn atomic_store
610were added in
611.Fx 12.0 .
612.Pp
613The
614.Fn atomic_interrupt_fence
615operation was added in
616.Fx 13.0 .
617