xref: /xnu-10002.41.9/doc/atomics.md (revision 699cd48037512bf4380799317ca44ca453c82f57)
1*699cd480SApple OSS DistributionsXNU use of Atomics and Memory Barriers
2*699cd480SApple OSS Distributions======================================
3*699cd480SApple OSS Distributions
4*699cd480SApple OSS DistributionsGoal
5*699cd480SApple OSS Distributions----
6*699cd480SApple OSS Distributions
7*699cd480SApple OSS DistributionsThis document discusses the use of atomics and memory barriers in XNU. It is
8*699cd480SApple OSS Distributionsmeant as a guide to best practices, and warns against a variety of possible
9*699cd480SApple OSS Distributionspitfalls in the handling of atomics in C.
10*699cd480SApple OSS Distributions
11*699cd480SApple OSS DistributionsIt is assumed that the reader has a decent understanding of
12*699cd480SApple OSS Distributionsthe [C11 memory model](https://en.cppreference.com/w/c/atomic/memory_order)
13*699cd480SApple OSS Distributionsas this document builds on it, and explains the liberties XNU takes with said
14*699cd480SApple OSS Distributionsmodel.
15*699cd480SApple OSS Distributions
16*699cd480SApple OSS DistributionsAll the interfaces discussed in this document are available through
17*699cd480SApple OSS Distributionsthe `<os/atomic_private.h>` header.
18*699cd480SApple OSS Distributions
19*699cd480SApple OSS DistributionsNote: Linux has thorough documentation around memory barriers
20*699cd480SApple OSS Distributions(Documentation/memory-barriers.txt), some of which is Linux specific,
21*699cd480SApple OSS Distributionsbut most is not and is a valuable read.
22*699cd480SApple OSS Distributions
23*699cd480SApple OSS Distributions
24*699cd480SApple OSS DistributionsVocabulary
25*699cd480SApple OSS Distributions----------
26*699cd480SApple OSS Distributions
27*699cd480SApple OSS DistributionsIn the rest of this document we'll refer to the various memory ordering defined
28*699cd480SApple OSS Distributionsby C11 as relaxed, consume, acquire, release, acq\_rel and seq\_cst.
29*699cd480SApple OSS Distributions
30*699cd480SApple OSS Distributions`os_atomic` also tries to make the distinction between compiler **barriers**
31*699cd480SApple OSS Distributions(which limit how much the compiler can reorder code), and memory **fences**.
32*699cd480SApple OSS Distributions
33*699cd480SApple OSS Distributions
34*699cd480SApple OSS DistributionsThe dangers and pitfalls of C11's `<stdatomic.h>`
35*699cd480SApple OSS Distributions-------------------------------------------------
36*699cd480SApple OSS Distributions
37*699cd480SApple OSS DistributionsWhile the C11 memory model has likely been one of the most important additions
38*699cd480SApple OSS Distributionsto modern C, in the purest C tradition, it is a sharp tool.
39*699cd480SApple OSS Distributions
40*699cd480SApple OSS DistributionsBy default, C11 comes with two variants of each atomic "operation":
41*699cd480SApple OSS Distributions
42*699cd480SApple OSS Distributions- an *explicit* variant where memory orderings can be specified,
43*699cd480SApple OSS Distributions- a regular variant which is equivalent to the former with the *seq_cst*
44*699cd480SApple OSS Distributions  memory ordering.
45*699cd480SApple OSS Distributions
46*699cd480SApple OSS DistributionsWhen an `_Atomic` qualified variable is accessed directly without using
47*699cd480SApple OSS Distributionsany `atomic_*_explicit()` operation, then the compiler will generate the
48*699cd480SApple OSS Distributionsmatching *seq_cst* atomic operations on your behalf.
49*699cd480SApple OSS Distributions
50*699cd480SApple OSS DistributionsThe sequentially consistent world is extremely safe from a lot of compiler
51*699cd480SApple OSS Distributionsand hardware reorderings and optimizations, which is great, but comes with
52*699cd480SApple OSS Distributionsa huge cost in terms of memory barriers.
53*699cd480SApple OSS Distributions
54*699cd480SApple OSS Distributions
55*699cd480SApple OSS DistributionsIt seems very tempting to use `atomic_*_explicit()` functions with explicit
56*699cd480SApple OSS Distributionsmemory orderings, however, the compiler is entitled to perform a number of
57*699cd480SApple OSS Distributionsoptimizations with relaxed atomics, that most developers will not expect.
58*699cd480SApple OSS DistributionsIndeed, the compiler is perfectly allowed to perform various optimizations it
59*699cd480SApple OSS Distributionsdoes with other plain memory accesess such as coalescing, reordering, hoisting
60*699cd480SApple OSS Distributionsout of loops, ...
61*699cd480SApple OSS Distributions
62*699cd480SApple OSS DistributionsFor example, when the compiler can know what `doit` is doing (which due to LTO
63*699cd480SApple OSS Distributionsis almost always the case for XNU), is allowed to transform this code:
64*699cd480SApple OSS Distributions
65*699cd480SApple OSS Distributions```c
66*699cd480SApple OSS Distributions    void
67*699cd480SApple OSS Distributions    perform_with_progress(int steps, long _Atomic *progress)
68*699cd480SApple OSS Distributions    {
69*699cd480SApple OSS Distributions        for (int i = 0; i < steps; i++) {
70*699cd480SApple OSS Distributions            doit(i);
71*699cd480SApple OSS Distributions            atomic_store_explicit(progress, i, memory_order_relaxed);
72*699cd480SApple OSS Distributions        }
73*699cd480SApple OSS Distributions    }
74*699cd480SApple OSS Distributions```
75*699cd480SApple OSS Distributions
76*699cd480SApple OSS DistributionsInto this, which obviously defeats the entire purpose of `progress`:
77*699cd480SApple OSS Distributions
78*699cd480SApple OSS Distributions```c
79*699cd480SApple OSS Distributions    void
80*699cd480SApple OSS Distributions    perform_with_progress(int steps, long _Atomic *progress)
81*699cd480SApple OSS Distributions    {
82*699cd480SApple OSS Distributions        for (int i = 0; i < steps; i++) {
83*699cd480SApple OSS Distributions            doit(i);
84*699cd480SApple OSS Distributions        }
85*699cd480SApple OSS Distributions        atomic_store_explicit(progress, steps, memory_order_relaxed);
86*699cd480SApple OSS Distributions    }
87*699cd480SApple OSS Distributions```
88*699cd480SApple OSS Distributions
89*699cd480SApple OSS Distributions
90*699cd480SApple OSS DistributionsHow `os_atomic_*` tries to address `<stdatomic.h>` pitfalls
91*699cd480SApple OSS Distributions-----------------------------------------------------------
92*699cd480SApple OSS Distributions
93*699cd480SApple OSS Distributions1. the memory locations passed to the various `os_atomic_*`
94*699cd480SApple OSS Distributions   functions do not need to be marked `_Atomic` or `volatile`
95*699cd480SApple OSS Distributions   (or `_Atomic volatile`), which allow for use of atomic
96*699cd480SApple OSS Distributions   operations in code written before C11 was even a thing.
97*699cd480SApple OSS Distributions
98*699cd480SApple OSS Distributions   It is however recommended in new code to use the `_Atomic`
99*699cd480SApple OSS Distributions   specifier.
100*699cd480SApple OSS Distributions
101*699cd480SApple OSS Distributions2. `os_atomic_*` cannot be coalesced by the compiler:
102*699cd480SApple OSS Distributions   all accesses are performed on the specified locations
103*699cd480SApple OSS Distributions   as if their type was `_Atomic volatile` qualified.
104*699cd480SApple OSS Distributions
105*699cd480SApple OSS Distributions3. `os_atomic_*` only comes with the explicit variants:
106*699cd480SApple OSS Distributions   orderings must be provided and can express either memory orders
107*699cd480SApple OSS Distributions   where the name is the same as in C11 without the `memory_order_` prefix,
108*699cd480SApple OSS Distributions   or a compiler barrier ordering `compiler_acquire`, `compiler_release`,
109*699cd480SApple OSS Distributions   `compiler_acq_rel`.
110*699cd480SApple OSS Distributions
111*699cd480SApple OSS Distributions4. `os_atomic_*` emits the proper compiler barriers that
112*699cd480SApple OSS Distributions   correspond to the requested memory ordering (using
113*699cd480SApple OSS Distributions   `atomic_signal_fence()`).
114*699cd480SApple OSS Distributions
115*699cd480SApple OSS Distributions
116*699cd480SApple OSS DistributionsBest practices for the use of atomics in XNU
117*699cd480SApple OSS Distributions--------------------------------------------
118*699cd480SApple OSS Distributions
119*699cd480SApple OSS DistributionsFor most generic code, the `os_atomic_*` functions from
120*699cd480SApple OSS Distributions`<os/atomic_private.h>` are the preferred interfaces.
121*699cd480SApple OSS Distributions
122*699cd480SApple OSS Distributions`__sync_*`, `__c11_*` and `__atomic_*` compiler builtins should not be used.
123*699cd480SApple OSS Distributions
124*699cd480SApple OSS Distributions`<stdatomic.h>` functions may be used if:
125*699cd480SApple OSS Distributions
126*699cd480SApple OSS Distributions- compiler coalescing / reordering is desired (refcounting
127*699cd480SApple OSS Distributions  implementations may desire this for example).
128*699cd480SApple OSS Distributions
129*699cd480SApple OSS Distributions
130*699cd480SApple OSS DistributionsQualifying atomic variables with `_Atomic` or even
131*699cd480SApple OSS Distributions`_Atomic volatile` is encouraged, however authors must
132*699cd480SApple OSS Distributionsbe aware that a direct access to this variable will
133*699cd480SApple OSS Distributionsresult in quite heavy memory barriers.
134*699cd480SApple OSS Distributions
135*699cd480SApple OSS DistributionsThe *consume* memory ordering should not be used
136*699cd480SApple OSS Distributions(See *dependency* memory order later in this documentation).
137*699cd480SApple OSS Distributions
138*699cd480SApple OSS Distributions**Note**: `<libkern/OSAtomic.h>` provides a bunch of legacy
139*699cd480SApple OSS Distributionsatomic interfaces, but this header is considered obsolete
140*699cd480SApple OSS Distributionsand these functions should not be used in new code.
141*699cd480SApple OSS Distributions
142*699cd480SApple OSS Distributions
143*699cd480SApple OSS DistributionsHigh level overview of `os_atomic_*` interfaces
144*699cd480SApple OSS Distributions-----------------------------------------------
145*699cd480SApple OSS Distributions
146*699cd480SApple OSS Distributions### Compiler barriers and memory fences
147*699cd480SApple OSS Distributions
148*699cd480SApple OSS Distributions`os_compiler_barrier(mem_order?)` provides a compiler barrier,
149*699cd480SApple OSS Distributionswith an optional barrier ordering. It is implemented with C11's
150*699cd480SApple OSS Distributions`atomic_signal_fence()`. The barrier ordering argument is optional
151*699cd480SApple OSS Distributionsand defaults to the `acq_rel` compiler barrier (which prevents the
152*699cd480SApple OSS Distributionscompiler to reorder code in any direction around this barrier).
153*699cd480SApple OSS Distributions
154*699cd480SApple OSS Distributions`os_atomic_thread_fence(mem_order)` provides a memory barrier
155*699cd480SApple OSS Distributionsaccording to the semantics of `atomic_thread_fence()`. It always
156*699cd480SApple OSS Distributionsimplies the equivalent `os_compiler_barrier()` even on UP systems.
157*699cd480SApple OSS Distributions
158*699cd480SApple OSS Distributions### Init, load and store
159*699cd480SApple OSS Distributions
160*699cd480SApple OSS Distributions`os_atomic_init`, `os_atomic_load` and `os_atomic_store` provide
161*699cd480SApple OSS Distributionsfacilities equivalent to `atomic_init`, `atomic_load_explicit`
162*699cd480SApple OSS Distributionsand `atomic_store_explicit` respectively.
163*699cd480SApple OSS Distributions
164*699cd480SApple OSS DistributionsNote that `os_atomic_load` and `os_atomic_store` promise that they will
165*699cd480SApple OSS Distributionscompile to a plain load or store. `os_atomic_load_wide` and
166*699cd480SApple OSS Distributions`os_atomic_store_wide` can be used to have access to atomic loads and store
167*699cd480SApple OSS Distributionsthat involve more costly codegen (such as compare exchange loops).
168*699cd480SApple OSS Distributions
169*699cd480SApple OSS Distributions### Basic RMW (read/modify/write) atomic operations
170*699cd480SApple OSS Distributions
171*699cd480SApple OSS DistributionsThe following basic atomic RMW operations exist:
172*699cd480SApple OSS Distributions
173*699cd480SApple OSS Distributions- `inc`: atomic increment (equivalent to an atomic add of `1`),
174*699cd480SApple OSS Distributions- `dec`: atomic decrement (equivalent to an atomic sub of `1`),
175*699cd480SApple OSS Distributions- `add`: atomic add,
176*699cd480SApple OSS Distributions- `sub`: atomic sub,
177*699cd480SApple OSS Distributions- `or`: atomic bitwise or,
178*699cd480SApple OSS Distributions- `xor`: atomic bitwise xor,
179*699cd480SApple OSS Distributions- `and`: atomic bitwise and,
180*699cd480SApple OSS Distributions- `andnot`: atomic bitwise andnot (equivalent to atomic and of ~value),
181*699cd480SApple OSS Distributions- `min`: atomic min,
182*699cd480SApple OSS Distributions- `max`: atomic max.
183*699cd480SApple OSS Distributions
184*699cd480SApple OSS DistributionsFor any such operation, two variants exist:
185*699cd480SApple OSS Distributions
186*699cd480SApple OSS Distributions- `os_atomic_${op}_orig` (for example `os_atomic_add_orig`)
187*699cd480SApple OSS Distributions  which returns the value stored at the specified location
188*699cd480SApple OSS Distributions  *before* the atomic operation took place
189*699cd480SApple OSS Distributions- `os_atomic_${op}` (for example `os_atomic_add`) which
190*699cd480SApple OSS Distributions  returns the value stored at the specified location
191*699cd480SApple OSS Distributions  *after* the atomic operation took place
192*699cd480SApple OSS Distributions
193*699cd480SApple OSS DistributionsThis convention is picked for two reasons:
194*699cd480SApple OSS Distributions
195*699cd480SApple OSS Distributions1. `os_atomic_add(p, value, ...)` is essentially equivalent to the C
196*699cd480SApple OSS Distributions   in place addition `(*p += value)` which returns the result of the
197*699cd480SApple OSS Distributions   operation and not the original value of `*p`.
198*699cd480SApple OSS Distributions
199*699cd480SApple OSS Distributions2. Most subtle atomic algorithms do actually require the original value
200*699cd480SApple OSS Distributions   stored at the location, especially for bit manipulations:
201*699cd480SApple OSS Distributions   `(os_atomic_or_orig(p, bit, relaxed) & bit)` will atomically perform
202*699cd480SApple OSS Distributions   `*p |= bit` but also tell you whether `bit` was set in the original value.
203*699cd480SApple OSS Distributions
204*699cd480SApple OSS Distributions   Making it more explicit that the original value is used is hence
205*699cd480SApple OSS Distributions   important for readers and worth the extra five keystrokes.
206*699cd480SApple OSS Distributions
207*699cd480SApple OSS DistributionsTypically:
208*699cd480SApple OSS Distributions
209*699cd480SApple OSS Distributions```c
210*699cd480SApple OSS Distributions    static int _Atomic i = 0;
211*699cd480SApple OSS Distributions
212*699cd480SApple OSS Distributions    printf("%d\n", os_atomic_inc_orig(&i)); // prints 0
213*699cd480SApple OSS Distributions    printf("%d\n", os_atomic_inc(&i)); // prints 2
214*699cd480SApple OSS Distributions```
215*699cd480SApple OSS Distributions
216*699cd480SApple OSS Distributions### Atomic swap / compare and swap
217*699cd480SApple OSS Distributions
218*699cd480SApple OSS Distributions`os_atomic_xchg` is a simple wrapper around `atomic_exchange_explicit`.
219*699cd480SApple OSS Distributions
220*699cd480SApple OSS DistributionsThere are two variants of `os_atomic_cmpxchg` which are wrappers around
221*699cd480SApple OSS Distributions`atomic_compare_exchange_strong_explicit`. Both of these variants will
222*699cd480SApple OSS Distributionsreturn false/0 if the compare exchange failed, and true/1 if the expected
223*699cd480SApple OSS Distributionsvalue was found at the specified location and the new value was stored.
224*699cd480SApple OSS Distributions
225*699cd480SApple OSS Distributions1. `os_atomic_cmpxchg(address, expected, new_value, mem_order)` which
226*699cd480SApple OSS Distributions   will atomically store `new_value` at `address` if the current value
227*699cd480SApple OSS Distributions   is equal to `expected`.
228*699cd480SApple OSS Distributions
229*699cd480SApple OSS Distributions2. `os_atomic_cmpxchgv(address, expected, new_value, orig_value, mem_order)`
230*699cd480SApple OSS Distributions   which has an extra `orig_value` argument which must be a pointer to a local
231*699cd480SApple OSS Distributions   variable and will be filled with the current value at `address` whether the
232*699cd480SApple OSS Distributions   compare exchange was successful or not. In case of success, the loaded value
233*699cd480SApple OSS Distributions   will always be `expected`, however in case of failure it will be filled with
234*699cd480SApple OSS Distributions   the current value, which is helpful to redrive compare exchange loops.
235*699cd480SApple OSS Distributions
236*699cd480SApple OSS DistributionsUnlike `atomic_compare_exchange_strong_explicit`, a single ordering is
237*699cd480SApple OSS Distributionsspecified, which only takes effect in case of a successful compare exchange.
238*699cd480SApple OSS DistributionsIn C11 speak, `os_atomic_cmpxchg*` always specifies `memory_order_relaxed`
239*699cd480SApple OSS Distributionsfor the failure case ordering, as it is what is used most of the time.
240*699cd480SApple OSS Distributions
241*699cd480SApple OSS DistributionsThere is no wrapper around `atomic_compare_exchange_weak_explicit`,
242*699cd480SApple OSS Distributionsas `os_atomic_rmw_loop` offers a much better alternative for CAS-loops.
243*699cd480SApple OSS Distributions
244*699cd480SApple OSS Distributions### `os_atomic_rmw_loop`
245*699cd480SApple OSS Distributions
246*699cd480SApple OSS DistributionsThis expressive and versatile construct allows for really terse and
247*699cd480SApple OSS Distributionsway more readable compare exchange loops. It also uses LL/SC constructs more
248*699cd480SApple OSS Distributionsefficiently than a compare exchange loop would allow.
249*699cd480SApple OSS Distributions
250*699cd480SApple OSS DistributionsInstead of a typical CAS-loop in C11:
251*699cd480SApple OSS Distributions
252*699cd480SApple OSS Distributions```c
253*699cd480SApple OSS Distributions    int _Atomic *address;
254*699cd480SApple OSS Distributions    int old_value, new_value;
255*699cd480SApple OSS Distributions    bool success = false;
256*699cd480SApple OSS Distributions
257*699cd480SApple OSS Distributions    old_value = atomic_load_explicit(address, memory_order_relaxed);
258*699cd480SApple OSS Distributions    do {
259*699cd480SApple OSS Distributions        if (!validate(old_value)) {
260*699cd480SApple OSS Distributions            break;
261*699cd480SApple OSS Distributions        }
262*699cd480SApple OSS Distributions        new_value = compute_new_value(old_value);
263*699cd480SApple OSS Distributions        success = atomic_compare_exchange_weak_explicit(address, &old_value,
264*699cd480SApple OSS Distributions                new_value, memory_order_acquire, memory_order_relaxed);
265*699cd480SApple OSS Distributions    } while (__improbable(!success));
266*699cd480SApple OSS Distributions```
267*699cd480SApple OSS Distributions
268*699cd480SApple OSS Distributions`os_atomic_rmw_loop` allows this form:
269*699cd480SApple OSS Distributions
270*699cd480SApple OSS Distributions```c
271*699cd480SApple OSS Distributions    int _Atomic *address;
272*699cd480SApple OSS Distributions    int old_value, new_value;
273*699cd480SApple OSS Distributions    bool success;
274*699cd480SApple OSS Distributions
275*699cd480SApple OSS Distributions    success = os_atomic_rmw_loop(address, old_value, new_value, acquire, {
276*699cd480SApple OSS Distributions        if (!validate(old_value)) {
277*699cd480SApple OSS Distributions            os_atomic_rmw_loop_give_up(break);
278*699cd480SApple OSS Distributions        }
279*699cd480SApple OSS Distributions        new_value = compute_new_value(old_value);
280*699cd480SApple OSS Distributions    });
281*699cd480SApple OSS Distributions```
282*699cd480SApple OSS Distributions
283*699cd480SApple OSS DistributionsUnlike the C11 variant, it lets the reader know in program order that this will
284*699cd480SApple OSS Distributionsbe a CAS loop, and exposes the ordering upfront, while for traditional CAS loops
285*699cd480SApple OSS Distributionsone has to jump to the end of the code to understand what it does.
286*699cd480SApple OSS Distributions
287*699cd480SApple OSS DistributionsAny control flow that attempts to exit its scope of the loop needs to be
288*699cd480SApple OSS Distributionswrapped with `os_atomic_rmw_loop_give_up` (so that LL/SC architectures can
289*699cd480SApple OSS Distributionsabort their opened LL/SC transaction).
290*699cd480SApple OSS Distributions
291*699cd480SApple OSS DistributionsBecause these loops are LL/SC transactions, it is undefined to perform
292*699cd480SApple OSS Distributionsany store to memory (register operations are fine) within these loops,
293*699cd480SApple OSS Distributionsas these may cause the store-conditional to always fail.
294*699cd480SApple OSS DistributionsIn particular nesting of `os_atomic_rmw_loop` is invalid.
295*699cd480SApple OSS Distributions
296*699cd480SApple OSS DistributionsUse of `continue` within an `os_atomic_rmw_loop` is also invalid, instead an
297*699cd480SApple OSS Distributions`os_atomic_rmw_loop_give_up(goto again)` jumping to an `again:` label placed
298*699cd480SApple OSS Distributionsbefore the loop should be used in this way:
299*699cd480SApple OSS Distributions
300*699cd480SApple OSS Distributions```c
301*699cd480SApple OSS Distributions    int _Atomic *address;
302*699cd480SApple OSS Distributions    int old_value, new_value;
303*699cd480SApple OSS Distributions    bool success;
304*699cd480SApple OSS Distributions
305*699cd480SApple OSS Distributionsagain:
306*699cd480SApple OSS Distributions    success = os_atomic_rmw_loop(address, old_value, new_value, acquire, {
307*699cd480SApple OSS Distributions        if (needs_some_store_that_can_thwart_the_transaction(old_value)) {
308*699cd480SApple OSS Distributions            os_atomic_rmw_loop_give_up({
309*699cd480SApple OSS Distributions                // Do whatever you need to do/store to central memory
310*699cd480SApple OSS Distributions                // that would cause the loop to always fail
311*699cd480SApple OSS Distributions                do_my_rmw_loop_breaking_store();
312*699cd480SApple OSS Distributions
313*699cd480SApple OSS Distributions                // And only then redrive.
314*699cd480SApple OSS Distributions                goto again;
315*699cd480SApple OSS Distributions            });
316*699cd480SApple OSS Distributions        }
317*699cd480SApple OSS Distributions        if (!validate(old_value)) {
318*699cd480SApple OSS Distributions            os_atomic_rmw_loop_give_up(break);
319*699cd480SApple OSS Distributions        }
320*699cd480SApple OSS Distributions        new_value = compute_new_value(old_value);
321*699cd480SApple OSS Distributions    });
322*699cd480SApple OSS Distributions```
323*699cd480SApple OSS Distributions
324*699cd480SApple OSS Distributions### the *dependency* memory order
325*699cd480SApple OSS Distributions
326*699cd480SApple OSS DistributionsBecause the C11 *consume* memory order is broken in various ways,
327*699cd480SApple OSS Distributionsmost compilers, clang included, implement it as an equivalent
328*699cd480SApple OSS Distributionsfor `memory_order_acquire`. However, its concept is useful
329*699cd480SApple OSS Distributionsfor certain algorithms.
330*699cd480SApple OSS Distributions
331*699cd480SApple OSS DistributionsAs an attempt to provide a replacement for this, `<os/atomic_private.h>`
332*699cd480SApple OSS Distributionsimplements an entirely new *dependency* memory ordering.
333*699cd480SApple OSS Distributions
334*699cd480SApple OSS DistributionsThe purpose of this ordering is to provide a relaxed load followed by an
335*699cd480SApple OSS Distributionsimplicit compiler barrier, that can be used as a root for a chain of hardware
336*699cd480SApple OSS Distributionsdependencies that would otherwise pair with store-releases done at this address,
337*699cd480SApple OSS Distributionsvery much like the *consume* memory order is intended to provide.
338*699cd480SApple OSS Distributions
339*699cd480SApple OSS DistributionsHowever, unlike the *consume* memory ordering where the compiler had to follow
340*699cd480SApple OSS Distributionsthe dependencies, the *dependency* memory ordering relies on explicit
341*699cd480SApple OSS Distributionsannotations of when the dependencies are expected:
342*699cd480SApple OSS Distributions
343*699cd480SApple OSS Distributions- loads through a pointer loaded with a *dependency* memory ordering
344*699cd480SApple OSS Distributions  will provide a hardware dependency,
345*699cd480SApple OSS Distributions
346*699cd480SApple OSS Distributions- dependencies may be injected into other loads not performed through this
347*699cd480SApple OSS Distributions  particular pointer with the `os_atomic_load_with_dependency_on` and
348*699cd480SApple OSS Distributions  `os_atomic_inject_dependency` interfaces.
349*699cd480SApple OSS Distributions
350*699cd480SApple OSS DistributionsHere is an example of how it is meant to be used:
351*699cd480SApple OSS Distributions
352*699cd480SApple OSS Distributions```c
353*699cd480SApple OSS Distributions    struct foo {
354*699cd480SApple OSS Distributions        long value;
355*699cd480SApple OSS Distributions        long _Atomic flag;
356*699cd480SApple OSS Distributions    };
357*699cd480SApple OSS Distributions
358*699cd480SApple OSS Distributions    void
359*699cd480SApple OSS Distributions    publish(struct foo *p, long value)
360*699cd480SApple OSS Distributions    {
361*699cd480SApple OSS Distributions        p->value = value;
362*699cd480SApple OSS Distributions        os_atomic_store(&p->flag, 1, release);
363*699cd480SApple OSS Distributions    }
364*699cd480SApple OSS Distributions
365*699cd480SApple OSS Distributions
366*699cd480SApple OSS Distributions    bool
367*699cd480SApple OSS Distributions    broken_read(struct foo *p, long *value)
368*699cd480SApple OSS Distributions    {
369*699cd480SApple OSS Distributions        /*
370*699cd480SApple OSS Distributions         * This isn't safe, as there's absolutely no hardware dependency involved.
371*699cd480SApple OSS Distributions         * Using an acquire barrier would of course fix it but is quite expensive...
372*699cd480SApple OSS Distributions         */
373*699cd480SApple OSS Distributions        if (os_atomic_load(&p->flag, relaxed)) {
374*699cd480SApple OSS Distributions            *value = p->value;
375*699cd480SApple OSS Distributions            return true;
376*699cd480SApple OSS Distributions        }
377*699cd480SApple OSS Distributions        return false;
378*699cd480SApple OSS Distributions    }
379*699cd480SApple OSS Distributions
380*699cd480SApple OSS Distributions    bool
381*699cd480SApple OSS Distributions    valid_read(struct foo *p, long *value)
382*699cd480SApple OSS Distributions    {
383*699cd480SApple OSS Distributions        long flag = os_atomic_load(&p->flag, dependency);
384*699cd480SApple OSS Distributions        if (flag) {
385*699cd480SApple OSS Distributions            /*
386*699cd480SApple OSS Distributions             * Further the chain of dependency to any loads through `p`
387*699cd480SApple OSS Distributions             * which properly pair with the release barrier in `publish`.
388*699cd480SApple OSS Distributions             */
389*699cd480SApple OSS Distributions            *value = os_atomic_load_with_dependency_on(&p->value, flag);
390*699cd480SApple OSS Distributions            return true;
391*699cd480SApple OSS Distributions        }
392*699cd480SApple OSS Distributions        return false;
393*699cd480SApple OSS Distributions    }
394*699cd480SApple OSS Distributions```
395*699cd480SApple OSS Distributions
396*699cd480SApple OSS DistributionsThere are 4 interfaces involved with hardware dependencies:
397*699cd480SApple OSS Distributions
398*699cd480SApple OSS Distributions1. `os_atomic_load(..., dependency)` to initiate roots of hardware dependencies,
399*699cd480SApple OSS Distributions   that should pair with a store or rmw with release semantics or stronger
400*699cd480SApple OSS Distributions   (release, acq\_rel or seq\_cst),
401*699cd480SApple OSS Distributions
402*699cd480SApple OSS Distributions2. `os_atomic_inject_dependency` can be used to inject the dependency provided
403*699cd480SApple OSS Distributions   by a *dependency* load, or any other value that has had a dependency
404*699cd480SApple OSS Distributions   injected,
405*699cd480SApple OSS Distributions
406*699cd480SApple OSS Distributions3. `os_atomic_load_with_dependency_on` to do an otherwise related relaxed load
407*699cd480SApple OSS Distributions   that still prolongs a dependency chain,
408*699cd480SApple OSS Distributions
409*699cd480SApple OSS Distributions4. `os_atomic_make_dependency` to create an opaque token out of a given
410*699cd480SApple OSS Distributions   dependency root to inject into multiple loads.
411*699cd480SApple OSS Distributions
412*699cd480SApple OSS Distributions
413*699cd480SApple OSS Distributions**Note**: this technique is NOT safe when the compiler can reason about the
414*699cd480SApple OSS Distributionspointers that you are manipulating, for example if the compiler can know that
415*699cd480SApple OSS Distributionsthe pointer can only take a couple of values and ditch all these manually
416*699cd480SApple OSS Distributionscrafted dependency chains. Hopefully there will be a future C2Y standard that
417*699cd480SApple OSS Distributionsprovides a similar construct as a language feature instead.
418