xref: /linux/tools/memory-model/Documentation/explanation.txt (revision e9f0878c4b2004ac19581274c1ae4c61ae3ca70e)
1Explanation of the Linux-Kernel Memory Consistency Model
2~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3
4:Author: Alan Stern <stern@rowland.harvard.edu>
5:Created: October 2017
6
7.. Contents
8
9  1. INTRODUCTION
10  2. BACKGROUND
11  3. A SIMPLE EXAMPLE
12  4. A SELECTION OF MEMORY MODELS
13  5. ORDERING AND CYCLES
14  6. EVENTS
15  7. THE PROGRAM ORDER RELATION: po AND po-loc
16  8. A WARNING
17  9. DEPENDENCY RELATIONS: data, addr, and ctrl
18  10. THE READS-FROM RELATION: rf, rfi, and rfe
19  11. CACHE COHERENCE AND THE COHERENCE ORDER RELATION: co, coi, and coe
20  12. THE FROM-READS RELATION: fr, fri, and fre
21  13. AN OPERATIONAL MODEL
22  14. PROPAGATION ORDER RELATION: cumul-fence
23  15. DERIVATION OF THE LKMM FROM THE OPERATIONAL MODEL
24  16. SEQUENTIAL CONSISTENCY PER VARIABLE
25  17. ATOMIC UPDATES: rmw
26  18. THE PRESERVED PROGRAM ORDER RELATION: ppo
27  19. AND THEN THERE WAS ALPHA
28  20. THE HAPPENS-BEFORE RELATION: hb
29  21. THE PROPAGATES-BEFORE RELATION: pb
30  22. RCU RELATIONS: rcu-link, gp, rscs, rcu-fence, and rb
31  23. ODDS AND ENDS
32
33
34
35INTRODUCTION
36------------
37
38The Linux-kernel memory consistency model (LKMM) is rather complex and
39obscure.  This is particularly evident if you read through the
40linux-kernel.bell and linux-kernel.cat files that make up the formal
41version of the model; they are extremely terse and their meanings are
42far from clear.
43
44This document describes the ideas underlying the LKMM.  It is meant
45for people who want to understand how the model was designed.  It does
46not go into the details of the code in the .bell and .cat files;
47rather, it explains in English what the code expresses symbolically.
48
49Sections 2 (BACKGROUND) through 5 (ORDERING AND CYCLES) are aimed
50toward beginners; they explain what memory consistency models are and
51the basic notions shared by all such models.  People already familiar
52with these concepts can skim or skip over them.  Sections 6 (EVENTS)
53through 12 (THE FROM_READS RELATION) describe the fundamental
54relations used in many models.  Starting in Section 13 (AN OPERATIONAL
55MODEL), the workings of the LKMM itself are covered.
56
57Warning: The code examples in this document are not written in the
58proper format for litmus tests.  They don't include a header line, the
59initializations are not enclosed in braces, the global variables are
60not passed by pointers, and they don't have an "exists" clause at the
61end.  Converting them to the right format is left as an exercise for
62the reader.
63
64
65BACKGROUND
66----------
67
68A memory consistency model (or just memory model, for short) is
69something which predicts, given a piece of computer code running on a
70particular kind of system, what values may be obtained by the code's
71load instructions.  The LKMM makes these predictions for code running
72as part of the Linux kernel.
73
74In practice, people tend to use memory models the other way around.
75That is, given a piece of code and a collection of values specified
76for the loads, the model will predict whether it is possible for the
77code to run in such a way that the loads will indeed obtain the
78specified values.  Of course, this is just another way of expressing
79the same idea.
80
81For code running on a uniprocessor system, the predictions are easy:
82Each load instruction must obtain the value written by the most recent
83store instruction accessing the same location (we ignore complicating
84factors such as DMA and mixed-size accesses.)  But on multiprocessor
85systems, with multiple CPUs making concurrent accesses to shared
86memory locations, things aren't so simple.
87
88Different architectures have differing memory models, and the Linux
89kernel supports a variety of architectures.  The LKMM has to be fairly
90permissive, in the sense that any behavior allowed by one of these
91architectures also has to be allowed by the LKMM.
92
93
94A SIMPLE EXAMPLE
95----------------
96
97Here is a simple example to illustrate the basic concepts.  Consider
98some code running as part of a device driver for an input device.  The
99driver might contain an interrupt handler which collects data from the
100device, stores it in a buffer, and sets a flag to indicate the buffer
101is full.  Running concurrently on a different CPU might be a part of
102the driver code being executed by a process in the midst of a read(2)
103system call.  This code tests the flag to see whether the buffer is
104ready, and if it is, copies the data back to userspace.  The buffer
105and the flag are memory locations shared between the two CPUs.
106
107We can abstract out the important pieces of the driver code as follows
108(the reason for using WRITE_ONCE() and READ_ONCE() instead of simple
109assignment statements is discussed later):
110
111	int buf = 0, flag = 0;
112
113	P0()
114	{
115		WRITE_ONCE(buf, 1);
116		WRITE_ONCE(flag, 1);
117	}
118
119	P1()
120	{
121		int r1;
122		int r2 = 0;
123
124		r1 = READ_ONCE(flag);
125		if (r1)
126			r2 = READ_ONCE(buf);
127	}
128
129Here the P0() function represents the interrupt handler running on one
130CPU and P1() represents the read() routine running on another.  The
131value 1 stored in buf represents input data collected from the device.
132Thus, P0 stores the data in buf and then sets flag.  Meanwhile, P1
133reads flag into the private variable r1, and if it is set, reads the
134data from buf into a second private variable r2 for copying to
135userspace.  (Presumably if flag is not set then the driver will wait a
136while and try again.)
137
138This pattern of memory accesses, where one CPU stores values to two
139shared memory locations and another CPU loads from those locations in
140the opposite order, is widely known as the "Message Passing" or MP
141pattern.  It is typical of memory access patterns in the kernel.
142
143Please note that this example code is a simplified abstraction.  Real
144buffers are usually larger than a single integer, real device drivers
145usually use sleep and wakeup mechanisms rather than polling for I/O
146completion, and real code generally doesn't bother to copy values into
147private variables before using them.  All that is beside the point;
148the idea here is simply to illustrate the overall pattern of memory
149accesses by the CPUs.
150
151A memory model will predict what values P1 might obtain for its loads
152from flag and buf, or equivalently, what values r1 and r2 might end up
153with after the code has finished running.
154
155Some predictions are trivial.  For instance, no sane memory model would
156predict that r1 = 42 or r2 = -7, because neither of those values ever
157gets stored in flag or buf.
158
159Some nontrivial predictions are nonetheless quite simple.  For
160instance, P1 might run entirely before P0 begins, in which case r1 and
161r2 will both be 0 at the end.  Or P0 might run entirely before P1
162begins, in which case r1 and r2 will both be 1.
163
164The interesting predictions concern what might happen when the two
165routines run concurrently.  One possibility is that P1 runs after P0's
166store to buf but before the store to flag.  In this case, r1 and r2
167will again both be 0.  (If P1 had been designed to read buf
168unconditionally then we would instead have r1 = 0 and r2 = 1.)
169
170However, the most interesting possibility is where r1 = 1 and r2 = 0.
171If this were to occur it would mean the driver contains a bug, because
172incorrect data would get sent to the user: 0 instead of 1.  As it
173happens, the LKMM does predict this outcome can occur, and the example
174driver code shown above is indeed buggy.
175
176
177A SELECTION OF MEMORY MODELS
178----------------------------
179
180The first widely cited memory model, and the simplest to understand,
181is Sequential Consistency.  According to this model, systems behave as
182if each CPU executed its instructions in order but with unspecified
183timing.  In other words, the instructions from the various CPUs get
184interleaved in a nondeterministic way, always according to some single
185global order that agrees with the order of the instructions in the
186program source for each CPU.  The model says that the value obtained
187by each load is simply the value written by the most recently executed
188store to the same memory location, from any CPU.
189
190For the MP example code shown above, Sequential Consistency predicts
191that the undesired result r1 = 1, r2 = 0 cannot occur.  The reasoning
192goes like this:
193
194	Since r1 = 1, P0 must store 1 to flag before P1 loads 1 from
195	it, as loads can obtain values only from earlier stores.
196
197	P1 loads from flag before loading from buf, since CPUs execute
198	their instructions in order.
199
200	P1 must load 0 from buf before P0 stores 1 to it; otherwise r2
201	would be 1 since a load obtains its value from the most recent
202	store to the same address.
203
204	P0 stores 1 to buf before storing 1 to flag, since it executes
205	its instructions in order.
206
207	Since an instruction (in this case, P1's store to flag) cannot
208	execute before itself, the specified outcome is impossible.
209
210However, real computer hardware almost never follows the Sequential
211Consistency memory model; doing so would rule out too many valuable
212performance optimizations.  On ARM and PowerPC architectures, for
213instance, the MP example code really does sometimes yield r1 = 1 and
214r2 = 0.
215
216x86 and SPARC follow yet a different memory model: TSO (Total Store
217Ordering).  This model predicts that the undesired outcome for the MP
218pattern cannot occur, but in other respects it differs from Sequential
219Consistency.  One example is the Store Buffer (SB) pattern, in which
220each CPU stores to its own shared location and then loads from the
221other CPU's location:
222
223	int x = 0, y = 0;
224
225	P0()
226	{
227		int r0;
228
229		WRITE_ONCE(x, 1);
230		r0 = READ_ONCE(y);
231	}
232
233	P1()
234	{
235		int r1;
236
237		WRITE_ONCE(y, 1);
238		r1 = READ_ONCE(x);
239	}
240
241Sequential Consistency predicts that the outcome r0 = 0, r1 = 0 is
242impossible.  (Exercise: Figure out the reasoning.)  But TSO allows
243this outcome to occur, and in fact it does sometimes occur on x86 and
244SPARC systems.
245
246The LKMM was inspired by the memory models followed by PowerPC, ARM,
247x86, Alpha, and other architectures.  However, it is different in
248detail from each of them.
249
250
251ORDERING AND CYCLES
252-------------------
253
254Memory models are all about ordering.  Often this is temporal ordering
255(i.e., the order in which certain events occur) but it doesn't have to
256be; consider for example the order of instructions in a program's
257source code.  We saw above that Sequential Consistency makes an
258important assumption that CPUs execute instructions in the same order
259as those instructions occur in the code, and there are many other
260instances of ordering playing central roles in memory models.
261
262The counterpart to ordering is a cycle.  Ordering rules out cycles:
263It's not possible to have X ordered before Y, Y ordered before Z, and
264Z ordered before X, because this would mean that X is ordered before
265itself.  The analysis of the MP example under Sequential Consistency
266involved just such an impossible cycle:
267
268	W: P0 stores 1 to flag   executes before
269	X: P1 loads 1 from flag  executes before
270	Y: P1 loads 0 from buf   executes before
271	Z: P0 stores 1 to buf    executes before
272	W: P0 stores 1 to flag.
273
274In short, if a memory model requires certain accesses to be ordered,
275and a certain outcome for the loads in a piece of code can happen only
276if those accesses would form a cycle, then the memory model predicts
277that outcome cannot occur.
278
279The LKMM is defined largely in terms of cycles, as we will see.
280
281
282EVENTS
283------
284
285The LKMM does not work directly with the C statements that make up
286kernel source code.  Instead it considers the effects of those
287statements in a more abstract form, namely, events.  The model
288includes three types of events:
289
290	Read events correspond to loads from shared memory, such as
291	calls to READ_ONCE(), smp_load_acquire(), or
292	rcu_dereference().
293
294	Write events correspond to stores to shared memory, such as
295	calls to WRITE_ONCE(), smp_store_release(), or atomic_set().
296
297	Fence events correspond to memory barriers (also known as
298	fences), such as calls to smp_rmb() or rcu_read_lock().
299
300These categories are not exclusive; a read or write event can also be
301a fence.  This happens with functions like smp_load_acquire() or
302spin_lock().  However, no single event can be both a read and a write.
303Atomic read-modify-write accesses, such as atomic_inc() or xchg(),
304correspond to a pair of events: a read followed by a write.  (The
305write event is omitted for executions where it doesn't occur, such as
306a cmpxchg() where the comparison fails.)
307
308Other parts of the code, those which do not involve interaction with
309shared memory, do not give rise to events.  Thus, arithmetic and
310logical computations, control-flow instructions, or accesses to
311private memory or CPU registers are not of central interest to the
312memory model.  They only affect the model's predictions indirectly.
313For example, an arithmetic computation might determine the value that
314gets stored to a shared memory location (or in the case of an array
315index, the address where the value gets stored), but the memory model
316is concerned only with the store itself -- its value and its address
317-- not the computation leading up to it.
318
319Events in the LKMM can be linked by various relations, which we will
320describe in the following sections.  The memory model requires certain
321of these relations to be orderings, that is, it requires them not to
322have any cycles.
323
324
325THE PROGRAM ORDER RELATION: po AND po-loc
326-----------------------------------------
327
328The most important relation between events is program order (po).  You
329can think of it as the order in which statements occur in the source
330code after branches are taken into account and loops have been
331unrolled.  A better description might be the order in which
332instructions are presented to a CPU's execution unit.  Thus, we say
333that X is po-before Y (written as "X ->po Y" in formulas) if X occurs
334before Y in the instruction stream.
335
336This is inherently a single-CPU relation; two instructions executing
337on different CPUs are never linked by po.  Also, it is by definition
338an ordering so it cannot have any cycles.
339
340po-loc is a sub-relation of po.  It links two memory accesses when the
341first comes before the second in program order and they access the
342same memory location (the "-loc" suffix).
343
344Although this may seem straightforward, there is one subtle aspect to
345program order we need to explain.  The LKMM was inspired by low-level
346architectural memory models which describe the behavior of machine
347code, and it retains their outlook to a considerable extent.  The
348read, write, and fence events used by the model are close in spirit to
349individual machine instructions.  Nevertheless, the LKMM describes
350kernel code written in C, and the mapping from C to machine code can
351be extremely complex.
352
353Optimizing compilers have great freedom in the way they translate
354source code to object code.  They are allowed to apply transformations
355that add memory accesses, eliminate accesses, combine them, split them
356into pieces, or move them around.  Faced with all these possibilities,
357the LKMM basically gives up.  It insists that the code it analyzes
358must contain no ordinary accesses to shared memory; all accesses must
359be performed using READ_ONCE(), WRITE_ONCE(), or one of the other
360atomic or synchronization primitives.  These primitives prevent a
361large number of compiler optimizations.  In particular, it is
362guaranteed that the compiler will not remove such accesses from the
363generated code (unless it can prove the accesses will never be
364executed), it will not change the order in which they occur in the
365code (within limits imposed by the C standard), and it will not
366introduce extraneous accesses.
367
368This explains why the MP and SB examples above used READ_ONCE() and
369WRITE_ONCE() rather than ordinary memory accesses.  Thanks to this
370usage, we can be certain that in the MP example, P0's write event to
371buf really is po-before its write event to flag, and similarly for the
372other shared memory accesses in the examples.
373
374Private variables are not subject to this restriction.  Since they are
375not shared between CPUs, they can be accessed normally without
376READ_ONCE() or WRITE_ONCE(), and there will be no ill effects.  In
377fact, they need not even be stored in normal memory at all -- in
378principle a private variable could be stored in a CPU register (hence
379the convention that these variables have names starting with the
380letter 'r').
381
382
383A WARNING
384---------
385
386The protections provided by READ_ONCE(), WRITE_ONCE(), and others are
387not perfect; and under some circumstances it is possible for the
388compiler to undermine the memory model.  Here is an example.  Suppose
389both branches of an "if" statement store the same value to the same
390location:
391
392	r1 = READ_ONCE(x);
393	if (r1) {
394		WRITE_ONCE(y, 2);
395		...  /* do something */
396	} else {
397		WRITE_ONCE(y, 2);
398		...  /* do something else */
399	}
400
401For this code, the LKMM predicts that the load from x will always be
402executed before either of the stores to y.  However, a compiler could
403lift the stores out of the conditional, transforming the code into
404something resembling:
405
406	r1 = READ_ONCE(x);
407	WRITE_ONCE(y, 2);
408	if (r1) {
409		...  /* do something */
410	} else {
411		...  /* do something else */
412	}
413
414Given this version of the code, the LKMM would predict that the load
415from x could be executed after the store to y.  Thus, the memory
416model's original prediction could be invalidated by the compiler.
417
418Another issue arises from the fact that in C, arguments to many
419operators and function calls can be evaluated in any order.  For
420example:
421
422	r1 = f(5) + g(6);
423
424The object code might call f(5) either before or after g(6); the
425memory model cannot assume there is a fixed program order relation
426between them.  (In fact, if the functions are inlined then the
427compiler might even interleave their object code.)
428
429
430DEPENDENCY RELATIONS: data, addr, and ctrl
431------------------------------------------
432
433We say that two events are linked by a dependency relation when the
434execution of the second event depends in some way on a value obtained
435from memory by the first.  The first event must be a read, and the
436value it obtains must somehow affect what the second event does.
437There are three kinds of dependencies: data, address (addr), and
438control (ctrl).
439
440A read and a write event are linked by a data dependency if the value
441obtained by the read affects the value stored by the write.  As a very
442simple example:
443
444	int x, y;
445
446	r1 = READ_ONCE(x);
447	WRITE_ONCE(y, r1 + 5);
448
449The value stored by the WRITE_ONCE obviously depends on the value
450loaded by the READ_ONCE.  Such dependencies can wind through
451arbitrarily complicated computations, and a write can depend on the
452values of multiple reads.
453
454A read event and another memory access event are linked by an address
455dependency if the value obtained by the read affects the location
456accessed by the other event.  The second event can be either a read or
457a write.  Here's another simple example:
458
459	int a[20];
460	int i;
461
462	r1 = READ_ONCE(i);
463	r2 = READ_ONCE(a[r1]);
464
465Here the location accessed by the second READ_ONCE() depends on the
466index value loaded by the first.  Pointer indirection also gives rise
467to address dependencies, since the address of a location accessed
468through a pointer will depend on the value read earlier from that
469pointer.
470
471Finally, a read event and another memory access event are linked by a
472control dependency if the value obtained by the read affects whether
473the second event is executed at all.  Simple example:
474
475	int x, y;
476
477	r1 = READ_ONCE(x);
478	if (r1)
479		WRITE_ONCE(y, 1984);
480
481Execution of the WRITE_ONCE() is controlled by a conditional expression
482which depends on the value obtained by the READ_ONCE(); hence there is
483a control dependency from the load to the store.
484
485It should be pretty obvious that events can only depend on reads that
486come earlier in program order.  Symbolically, if we have R ->data X,
487R ->addr X, or R ->ctrl X (where R is a read event), then we must also
488have R ->po X.  It wouldn't make sense for a computation to depend
489somehow on a value that doesn't get loaded from shared memory until
490later in the code!
491
492
493THE READS-FROM RELATION: rf, rfi, and rfe
494-----------------------------------------
495
496The reads-from relation (rf) links a write event to a read event when
497the value loaded by the read is the value that was stored by the
498write.  In colloquial terms, the load "reads from" the store.  We
499write W ->rf R to indicate that the load R reads from the store W.  We
500further distinguish the cases where the load and the store occur on
501the same CPU (internal reads-from, or rfi) and where they occur on
502different CPUs (external reads-from, or rfe).
503
504For our purposes, a memory location's initial value is treated as
505though it had been written there by an imaginary initial store that
506executes on a separate CPU before the program runs.
507
508Usage of the rf relation implicitly assumes that loads will always
509read from a single store.  It doesn't apply properly in the presence
510of load-tearing, where a load obtains some of its bits from one store
511and some of them from another store.  Fortunately, use of READ_ONCE()
512and WRITE_ONCE() will prevent load-tearing; it's not possible to have:
513
514	int x = 0;
515
516	P0()
517	{
518		WRITE_ONCE(x, 0x1234);
519	}
520
521	P1()
522	{
523		int r1;
524
525		r1 = READ_ONCE(x);
526	}
527
528and end up with r1 = 0x1200 (partly from x's initial value and partly
529from the value stored by P0).
530
531On the other hand, load-tearing is unavoidable when mixed-size
532accesses are used.  Consider this example:
533
534	union {
535		u32	w;
536		u16	h[2];
537	} x;
538
539	P0()
540	{
541		WRITE_ONCE(x.h[0], 0x1234);
542		WRITE_ONCE(x.h[1], 0x5678);
543	}
544
545	P1()
546	{
547		int r1;
548
549		r1 = READ_ONCE(x.w);
550	}
551
552If r1 = 0x56781234 (little-endian!) at the end, then P1 must have read
553from both of P0's stores.  It is possible to handle mixed-size and
554unaligned accesses in a memory model, but the LKMM currently does not
555attempt to do so.  It requires all accesses to be properly aligned and
556of the location's actual size.
557
558
559CACHE COHERENCE AND THE COHERENCE ORDER RELATION: co, coi, and coe
560------------------------------------------------------------------
561
562Cache coherence is a general principle requiring that in a
563multi-processor system, the CPUs must share a consistent view of the
564memory contents.  Specifically, it requires that for each location in
565shared memory, the stores to that location must form a single global
566ordering which all the CPUs agree on (the coherence order), and this
567ordering must be consistent with the program order for accesses to
568that location.
569
570To put it another way, for any variable x, the coherence order (co) of
571the stores to x is simply the order in which the stores overwrite one
572another.  The imaginary store which establishes x's initial value
573comes first in the coherence order; the store which directly
574overwrites the initial value comes second; the store which overwrites
575that value comes third, and so on.
576
577You can think of the coherence order as being the order in which the
578stores reach x's location in memory (or if you prefer a more
579hardware-centric view, the order in which the stores get written to
580x's cache line).  We write W ->co W' if W comes before W' in the
581coherence order, that is, if the value stored by W gets overwritten,
582directly or indirectly, by the value stored by W'.
583
584Coherence order is required to be consistent with program order.  This
585requirement takes the form of four coherency rules:
586
587	Write-write coherence: If W ->po-loc W' (i.e., W comes before
588	W' in program order and they access the same location), where W
589	and W' are two stores, then W ->co W'.
590
591	Write-read coherence: If W ->po-loc R, where W is a store and R
592	is a load, then R must read from W or from some other store
593	which comes after W in the coherence order.
594
595	Read-write coherence: If R ->po-loc W, where R is a load and W
596	is a store, then the store which R reads from must come before
597	W in the coherence order.
598
599	Read-read coherence: If R ->po-loc R', where R and R' are two
600	loads, then either they read from the same store or else the
601	store read by R comes before the store read by R' in the
602	coherence order.
603
604This is sometimes referred to as sequential consistency per variable,
605because it means that the accesses to any single memory location obey
606the rules of the Sequential Consistency memory model.  (According to
607Wikipedia, sequential consistency per variable and cache coherence
608mean the same thing except that cache coherence includes an extra
609requirement that every store eventually becomes visible to every CPU.)
610
611Any reasonable memory model will include cache coherence.  Indeed, our
612expectation of cache coherence is so deeply ingrained that violations
613of its requirements look more like hardware bugs than programming
614errors:
615
616	int x;
617
618	P0()
619	{
620		WRITE_ONCE(x, 17);
621		WRITE_ONCE(x, 23);
622	}
623
624If the final value stored in x after this code ran was 17, you would
625think your computer was broken.  It would be a violation of the
626write-write coherence rule: Since the store of 23 comes later in
627program order, it must also come later in x's coherence order and
628thus must overwrite the store of 17.
629
630	int x = 0;
631
632	P0()
633	{
634		int r1;
635
636		r1 = READ_ONCE(x);
637		WRITE_ONCE(x, 666);
638	}
639
640If r1 = 666 at the end, this would violate the read-write coherence
641rule: The READ_ONCE() load comes before the WRITE_ONCE() store in
642program order, so it must not read from that store but rather from one
643coming earlier in the coherence order (in this case, x's initial
644value).
645
646	int x = 0;
647
648	P0()
649	{
650		WRITE_ONCE(x, 5);
651	}
652
653	P1()
654	{
655		int r1, r2;
656
657		r1 = READ_ONCE(x);
658		r2 = READ_ONCE(x);
659	}
660
661If r1 = 5 (reading from P0's store) and r2 = 0 (reading from the
662imaginary store which establishes x's initial value) at the end, this
663would violate the read-read coherence rule: The r1 load comes before
664the r2 load in program order, so it must not read from a store that
665comes later in the coherence order.
666
667(As a minor curiosity, if this code had used normal loads instead of
668READ_ONCE() in P1, on Itanium it sometimes could end up with r1 = 5
669and r2 = 0!  This results from parallel execution of the operations
670encoded in Itanium's Very-Long-Instruction-Word format, and it is yet
671another motivation for using READ_ONCE() when accessing shared memory
672locations.)
673
674Just like the po relation, co is inherently an ordering -- it is not
675possible for a store to directly or indirectly overwrite itself!  And
676just like with the rf relation, we distinguish between stores that
677occur on the same CPU (internal coherence order, or coi) and stores
678that occur on different CPUs (external coherence order, or coe).
679
680On the other hand, stores to different memory locations are never
681related by co, just as instructions on different CPUs are never
682related by po.  Coherence order is strictly per-location, or if you
683prefer, each location has its own independent coherence order.
684
685
686THE FROM-READS RELATION: fr, fri, and fre
687-----------------------------------------
688
689The from-reads relation (fr) can be a little difficult for people to
690grok.  It describes the situation where a load reads a value that gets
691overwritten by a store.  In other words, we have R ->fr W when the
692value that R reads is overwritten (directly or indirectly) by W, or
693equivalently, when R reads from a store which comes earlier than W in
694the coherence order.
695
696For example:
697
698	int x = 0;
699
700	P0()
701	{
702		int r1;
703
704		r1 = READ_ONCE(x);
705		WRITE_ONCE(x, 2);
706	}
707
708The value loaded from x will be 0 (assuming cache coherence!), and it
709gets overwritten by the value 2.  Thus there is an fr link from the
710READ_ONCE() to the WRITE_ONCE().  If the code contained any later
711stores to x, there would also be fr links from the READ_ONCE() to
712them.
713
714As with rf, rfi, and rfe, we subdivide the fr relation into fri (when
715the load and the store are on the same CPU) and fre (when they are on
716different CPUs).
717
718Note that the fr relation is determined entirely by the rf and co
719relations; it is not independent.  Given a read event R and a write
720event W for the same location, we will have R ->fr W if and only if
721the write which R reads from is co-before W.  In symbols,
722
723	(R ->fr W) := (there exists W' with W' ->rf R and W' ->co W).
724
725
726AN OPERATIONAL MODEL
727--------------------
728
729The LKMM is based on various operational memory models, meaning that
730the models arise from an abstract view of how a computer system
731operates.  Here are the main ideas, as incorporated into the LKMM.
732
733The system as a whole is divided into the CPUs and a memory subsystem.
734The CPUs are responsible for executing instructions (not necessarily
735in program order), and they communicate with the memory subsystem.
736For the most part, executing an instruction requires a CPU to perform
737only internal operations.  However, loads, stores, and fences involve
738more.
739
740When CPU C executes a store instruction, it tells the memory subsystem
741to store a certain value at a certain location.  The memory subsystem
742propagates the store to all the other CPUs as well as to RAM.  (As a
743special case, we say that the store propagates to its own CPU at the
744time it is executed.)  The memory subsystem also determines where the
745store falls in the location's coherence order.  In particular, it must
746arrange for the store to be co-later than (i.e., to overwrite) any
747other store to the same location which has already propagated to CPU C.
748
749When a CPU executes a load instruction R, it first checks to see
750whether there are any as-yet unexecuted store instructions, for the
751same location, that come before R in program order.  If there are, it
752uses the value of the po-latest such store as the value obtained by R,
753and we say that the store's value is forwarded to R.  Otherwise, the
754CPU asks the memory subsystem for the value to load and we say that R
755is satisfied from memory.  The memory subsystem hands back the value
756of the co-latest store to the location in question which has already
757propagated to that CPU.
758
759(In fact, the picture needs to be a little more complicated than this.
760CPUs have local caches, and propagating a store to a CPU really means
761propagating it to the CPU's local cache.  A local cache can take some
762time to process the stores that it receives, and a store can't be used
763to satisfy one of the CPU's loads until it has been processed.  On
764most architectures, the local caches process stores in
765First-In-First-Out order, and consequently the processing delay
766doesn't matter for the memory model.  But on Alpha, the local caches
767have a partitioned design that results in non-FIFO behavior.  We will
768discuss this in more detail later.)
769
770Note that load instructions may be executed speculatively and may be
771restarted under certain circumstances.  The memory model ignores these
772premature executions; we simply say that the load executes at the
773final time it is forwarded or satisfied.
774
775Executing a fence (or memory barrier) instruction doesn't require a
776CPU to do anything special other than informing the memory subsystem
777about the fence.  However, fences do constrain the way CPUs and the
778memory subsystem handle other instructions, in two respects.
779
780First, a fence forces the CPU to execute various instructions in
781program order.  Exactly which instructions are ordered depends on the
782type of fence:
783
784	Strong fences, including smp_mb() and synchronize_rcu(), force
785	the CPU to execute all po-earlier instructions before any
786	po-later instructions;
787
788	smp_rmb() forces the CPU to execute all po-earlier loads
789	before any po-later loads;
790
791	smp_wmb() forces the CPU to execute all po-earlier stores
792	before any po-later stores;
793
794	Acquire fences, such as smp_load_acquire(), force the CPU to
795	execute the load associated with the fence (e.g., the load
796	part of an smp_load_acquire()) before any po-later
797	instructions;
798
799	Release fences, such as smp_store_release(), force the CPU to
800	execute all po-earlier instructions before the store
801	associated with the fence (e.g., the store part of an
802	smp_store_release()).
803
804Second, some types of fence affect the way the memory subsystem
805propagates stores.  When a fence instruction is executed on CPU C:
806
807	For each other CPU C', smp_wmb() forces all po-earlier stores
808	on C to propagate to C' before any po-later stores do.
809
810	For each other CPU C', any store which propagates to C before
811	a release fence is executed (including all po-earlier
812	stores executed on C) is forced to propagate to C' before the
813	store associated with the release fence does.
814
815	Any store which propagates to C before a strong fence is
816	executed (including all po-earlier stores on C) is forced to
817	propagate to all other CPUs before any instructions po-after
818	the strong fence are executed on C.
819
820The propagation ordering enforced by release fences and strong fences
821affects stores from other CPUs that propagate to CPU C before the
822fence is executed, as well as stores that are executed on C before the
823fence.  We describe this property by saying that release fences and
824strong fences are A-cumulative.  By contrast, smp_wmb() fences are not
825A-cumulative; they only affect the propagation of stores that are
826executed on C before the fence (i.e., those which precede the fence in
827program order).
828
829rcu_read_lock(), rcu_read_unlock(), and synchronize_rcu() fences have
830other properties which we discuss later.
831
832
833PROPAGATION ORDER RELATION: cumul-fence
834---------------------------------------
835
836The fences which affect propagation order (i.e., strong, release, and
837smp_wmb() fences) are collectively referred to as cumul-fences, even
838though smp_wmb() isn't A-cumulative.  The cumul-fence relation is
839defined to link memory access events E and F whenever:
840
841	E and F are both stores on the same CPU and an smp_wmb() fence
842	event occurs between them in program order; or
843
844	F is a release fence and some X comes before F in program order,
845	where either X = E or else E ->rf X; or
846
847	A strong fence event occurs between some X and F in program
848	order, where either X = E or else E ->rf X.
849
850The operational model requires that whenever W and W' are both stores
851and W ->cumul-fence W', then W must propagate to any given CPU
852before W' does.  However, for different CPUs C and C', it does not
853require W to propagate to C before W' propagates to C'.
854
855
856DERIVATION OF THE LKMM FROM THE OPERATIONAL MODEL
857-------------------------------------------------
858
859The LKMM is derived from the restrictions imposed by the design
860outlined above.  These restrictions involve the necessity of
861maintaining cache coherence and the fact that a CPU can't operate on a
862value before it knows what that value is, among other things.
863
864The formal version of the LKMM is defined by five requirements, or
865axioms:
866
867	Sequential consistency per variable: This requires that the
868	system obey the four coherency rules.
869
870	Atomicity: This requires that atomic read-modify-write
871	operations really are atomic, that is, no other stores can
872	sneak into the middle of such an update.
873
874	Happens-before: This requires that certain instructions are
875	executed in a specific order.
876
877	Propagation: This requires that certain stores propagate to
878	CPUs and to RAM in a specific order.
879
880	Rcu: This requires that RCU read-side critical sections and
881	grace periods obey the rules of RCU, in particular, the
882	Grace-Period Guarantee.
883
884The first and second are quite common; they can be found in many
885memory models (such as those for C11/C++11).  The "happens-before" and
886"propagation" axioms have analogs in other memory models as well.  The
887"rcu" axiom is specific to the LKMM.
888
889Each of these axioms is discussed below.
890
891
892SEQUENTIAL CONSISTENCY PER VARIABLE
893-----------------------------------
894
895According to the principle of cache coherence, the stores to any fixed
896shared location in memory form a global ordering.  We can imagine
897inserting the loads from that location into this ordering, by placing
898each load between the store that it reads from and the following
899store.  This leaves the relative positions of loads that read from the
900same store unspecified; let's say they are inserted in program order,
901first for CPU 0, then CPU 1, etc.
902
903You can check that the four coherency rules imply that the rf, co, fr,
904and po-loc relations agree with this global ordering; in other words,
905whenever we have X ->rf Y or X ->co Y or X ->fr Y or X ->po-loc Y, the
906X event comes before the Y event in the global ordering.  The LKMM's
907"coherence" axiom expresses this by requiring the union of these
908relations not to have any cycles.  This means it must not be possible
909to find events
910
911	X0 -> X1 -> X2 -> ... -> Xn -> X0,
912
913where each of the links is either rf, co, fr, or po-loc.  This has to
914hold if the accesses to the fixed memory location can be ordered as
915cache coherence demands.
916
917Although it is not obvious, it can be shown that the converse is also
918true: This LKMM axiom implies that the four coherency rules are
919obeyed.
920
921
922ATOMIC UPDATES: rmw
923-------------------
924
925What does it mean to say that a read-modify-write (rmw) update, such
926as atomic_inc(&x), is atomic?  It means that the memory location (x in
927this case) does not get altered between the read and the write events
928making up the atomic operation.  In particular, if two CPUs perform
929atomic_inc(&x) concurrently, it must be guaranteed that the final
930value of x will be the initial value plus two.  We should never have
931the following sequence of events:
932
933	CPU 0 loads x obtaining 13;
934					CPU 1 loads x obtaining 13;
935	CPU 0 stores 14 to x;
936					CPU 1 stores 14 to x;
937
938where the final value of x is wrong (14 rather than 15).
939
940In this example, CPU 0's increment effectively gets lost because it
941occurs in between CPU 1's load and store.  To put it another way, the
942problem is that the position of CPU 0's store in x's coherence order
943is between the store that CPU 1 reads from and the store that CPU 1
944performs.
945
946The same analysis applies to all atomic update operations.  Therefore,
947to enforce atomicity the LKMM requires that atomic updates follow this
948rule: Whenever R and W are the read and write events composing an
949atomic read-modify-write and W' is the write event which R reads from,
950there must not be any stores coming between W' and W in the coherence
951order.  Equivalently,
952
953	(R ->rmw W) implies (there is no X with R ->fr X and X ->co W),
954
955where the rmw relation links the read and write events making up each
956atomic update.  This is what the LKMM's "atomic" axiom says.
957
958
959THE PRESERVED PROGRAM ORDER RELATION: ppo
960-----------------------------------------
961
962There are many situations where a CPU is obligated to execute two
963instructions in program order.  We amalgamate them into the ppo (for
964"preserved program order") relation, which links the po-earlier
965instruction to the po-later instruction and is thus a sub-relation of
966po.
967
968The operational model already includes a description of one such
969situation: Fences are a source of ppo links.  Suppose X and Y are
970memory accesses with X ->po Y; then the CPU must execute X before Y if
971any of the following hold:
972
973	A strong (smp_mb() or synchronize_rcu()) fence occurs between
974	X and Y;
975
976	X and Y are both stores and an smp_wmb() fence occurs between
977	them;
978
979	X and Y are both loads and an smp_rmb() fence occurs between
980	them;
981
982	X is also an acquire fence, such as smp_load_acquire();
983
984	Y is also a release fence, such as smp_store_release().
985
986Another possibility, not mentioned earlier but discussed in the next
987section, is:
988
989	X and Y are both loads, X ->addr Y (i.e., there is an address
990	dependency from X to Y), and X is a READ_ONCE() or an atomic
991	access.
992
993Dependencies can also cause instructions to be executed in program
994order.  This is uncontroversial when the second instruction is a
995store; either a data, address, or control dependency from a load R to
996a store W will force the CPU to execute R before W.  This is very
997simply because the CPU cannot tell the memory subsystem about W's
998store before it knows what value should be stored (in the case of a
999data dependency), what location it should be stored into (in the case
1000of an address dependency), or whether the store should actually take
1001place (in the case of a control dependency).
1002
1003Dependencies to load instructions are more problematic.  To begin with,
1004there is no such thing as a data dependency to a load.  Next, a CPU
1005has no reason to respect a control dependency to a load, because it
1006can always satisfy the second load speculatively before the first, and
1007then ignore the result if it turns out that the second load shouldn't
1008be executed after all.  And lastly, the real difficulties begin when
1009we consider address dependencies to loads.
1010
1011To be fair about it, all Linux-supported architectures do execute
1012loads in program order if there is an address dependency between them.
1013After all, a CPU cannot ask the memory subsystem to load a value from
1014a particular location before it knows what that location is.  However,
1015the split-cache design used by Alpha can cause it to behave in a way
1016that looks as if the loads were executed out of order (see the next
1017section for more details).  The kernel includes a workaround for this
1018problem when the loads come from READ_ONCE(), and therefore the LKMM
1019includes address dependencies to loads in the ppo relation.
1020
1021On the other hand, dependencies can indirectly affect the ordering of
1022two loads.  This happens when there is a dependency from a load to a
1023store and a second, po-later load reads from that store:
1024
1025	R ->dep W ->rfi R',
1026
1027where the dep link can be either an address or a data dependency.  In
1028this situation we know it is possible for the CPU to execute R' before
1029W, because it can forward the value that W will store to R'.  But it
1030cannot execute R' before R, because it cannot forward the value before
1031it knows what that value is, or that W and R' do access the same
1032location.  However, if there is merely a control dependency between R
1033and W then the CPU can speculatively forward W to R' before executing
1034R; if the speculation turns out to be wrong then the CPU merely has to
1035restart or abandon R'.
1036
1037(In theory, a CPU might forward a store to a load when it runs across
1038an address dependency like this:
1039
1040	r1 = READ_ONCE(ptr);
1041	WRITE_ONCE(*r1, 17);
1042	r2 = READ_ONCE(*r1);
1043
1044because it could tell that the store and the second load access the
1045same location even before it knows what the location's address is.
1046However, none of the architectures supported by the Linux kernel do
1047this.)
1048
1049Two memory accesses of the same location must always be executed in
1050program order if the second access is a store.  Thus, if we have
1051
1052	R ->po-loc W
1053
1054(the po-loc link says that R comes before W in program order and they
1055access the same location), the CPU is obliged to execute W after R.
1056If it executed W first then the memory subsystem would respond to R's
1057read request with the value stored by W (or an even later store), in
1058violation of the read-write coherence rule.  Similarly, if we had
1059
1060	W ->po-loc W'
1061
1062and the CPU executed W' before W, then the memory subsystem would put
1063W' before W in the coherence order.  It would effectively cause W to
1064overwrite W', in violation of the write-write coherence rule.
1065(Interestingly, an early ARMv8 memory model, now obsolete, proposed
1066allowing out-of-order writes like this to occur.  The model avoided
1067violating the write-write coherence rule by requiring the CPU not to
1068send the W write to the memory subsystem at all!)
1069
1070There is one last example of preserved program order in the LKMM: when
1071a load-acquire reads from an earlier store-release.  For example:
1072
1073	smp_store_release(&x, 123);
1074	r1 = smp_load_acquire(&x);
1075
1076If the smp_load_acquire() ends up obtaining the 123 value that was
1077stored by the smp_store_release(), the LKMM says that the load must be
1078executed after the store; the store cannot be forwarded to the load.
1079This requirement does not arise from the operational model, but it
1080yields correct predictions on all architectures supported by the Linux
1081kernel, although for differing reasons.
1082
1083On some architectures, including x86 and ARMv8, it is true that the
1084store cannot be forwarded to the load.  On others, including PowerPC
1085and ARMv7, smp_store_release() generates object code that starts with
1086a fence and smp_load_acquire() generates object code that ends with a
1087fence.  The upshot is that even though the store may be forwarded to
1088the load, it is still true that any instruction preceding the store
1089will be executed before the load or any following instructions, and
1090the store will be executed before any instruction following the load.
1091
1092
1093AND THEN THERE WAS ALPHA
1094------------------------
1095
1096As mentioned above, the Alpha architecture is unique in that it does
1097not appear to respect address dependencies to loads.  This means that
1098code such as the following:
1099
1100	int x = 0;
1101	int y = -1;
1102	int *ptr = &y;
1103
1104	P0()
1105	{
1106		WRITE_ONCE(x, 1);
1107		smp_wmb();
1108		WRITE_ONCE(ptr, &x);
1109	}
1110
1111	P1()
1112	{
1113		int *r1;
1114		int r2;
1115
1116		r1 = ptr;
1117		r2 = READ_ONCE(*r1);
1118	}
1119
1120can malfunction on Alpha systems (notice that P1 uses an ordinary load
1121to read ptr instead of READ_ONCE()).  It is quite possible that r1 = &x
1122and r2 = 0 at the end, in spite of the address dependency.
1123
1124At first glance this doesn't seem to make sense.  We know that the
1125smp_wmb() forces P0's store to x to propagate to P1 before the store
1126to ptr does.  And since P1 can't execute its second load
1127until it knows what location to load from, i.e., after executing its
1128first load, the value x = 1 must have propagated to P1 before the
1129second load executed.  So why doesn't r2 end up equal to 1?
1130
1131The answer lies in the Alpha's split local caches.  Although the two
1132stores do reach P1's local cache in the proper order, it can happen
1133that the first store is processed by a busy part of the cache while
1134the second store is processed by an idle part.  As a result, the x = 1
1135value may not become available for P1's CPU to read until after the
1136ptr = &x value does, leading to the undesirable result above.  The
1137final effect is that even though the two loads really are executed in
1138program order, it appears that they aren't.
1139
1140This could not have happened if the local cache had processed the
1141incoming stores in FIFO order.  By contrast, other architectures
1142maintain at least the appearance of FIFO order.
1143
1144In practice, this difficulty is solved by inserting a special fence
1145between P1's two loads when the kernel is compiled for the Alpha
1146architecture.  In fact, as of version 4.15, the kernel automatically
1147adds this fence (called smp_read_barrier_depends() and defined as
1148nothing at all on non-Alpha builds) after every READ_ONCE() and atomic
1149load.  The effect of the fence is to cause the CPU not to execute any
1150po-later instructions until after the local cache has finished
1151processing all the stores it has already received.  Thus, if the code
1152was changed to:
1153
1154	P1()
1155	{
1156		int *r1;
1157		int r2;
1158
1159		r1 = READ_ONCE(ptr);
1160		r2 = READ_ONCE(*r1);
1161	}
1162
1163then we would never get r1 = &x and r2 = 0.  By the time P1 executed
1164its second load, the x = 1 store would already be fully processed by
1165the local cache and available for satisfying the read request.  Thus
1166we have yet another reason why shared data should always be read with
1167READ_ONCE() or another synchronization primitive rather than accessed
1168directly.
1169
1170The LKMM requires that smp_rmb(), acquire fences, and strong fences
1171share this property with smp_read_barrier_depends(): They do not allow
1172the CPU to execute any po-later instructions (or po-later loads in the
1173case of smp_rmb()) until all outstanding stores have been processed by
1174the local cache.  In the case of a strong fence, the CPU first has to
1175wait for all of its po-earlier stores to propagate to every other CPU
1176in the system; then it has to wait for the local cache to process all
1177the stores received as of that time -- not just the stores received
1178when the strong fence began.
1179
1180And of course, none of this matters for any architecture other than
1181Alpha.
1182
1183
1184THE HAPPENS-BEFORE RELATION: hb
1185-------------------------------
1186
1187The happens-before relation (hb) links memory accesses that have to
1188execute in a certain order.  hb includes the ppo relation and two
1189others, one of which is rfe.
1190
1191W ->rfe R implies that W and R are on different CPUs.  It also means
1192that W's store must have propagated to R's CPU before R executed;
1193otherwise R could not have read the value stored by W.  Therefore W
1194must have executed before R, and so we have W ->hb R.
1195
1196The equivalent fact need not hold if W ->rfi R (i.e., W and R are on
1197the same CPU).  As we have already seen, the operational model allows
1198W's value to be forwarded to R in such cases, meaning that R may well
1199execute before W does.
1200
1201It's important to understand that neither coe nor fre is included in
1202hb, despite their similarities to rfe.  For example, suppose we have
1203W ->coe W'.  This means that W and W' are stores to the same location,
1204they execute on different CPUs, and W comes before W' in the coherence
1205order (i.e., W' overwrites W).  Nevertheless, it is possible for W' to
1206execute before W, because the decision as to which store overwrites
1207the other is made later by the memory subsystem.  When the stores are
1208nearly simultaneous, either one can come out on top.  Similarly,
1209R ->fre W means that W overwrites the value which R reads, but it
1210doesn't mean that W has to execute after R.  All that's necessary is
1211for the memory subsystem not to propagate W to R's CPU until after R
1212has executed, which is possible if W executes shortly before R.
1213
1214The third relation included in hb is like ppo, in that it only links
1215events that are on the same CPU.  However it is more difficult to
1216explain, because it arises only indirectly from the requirement of
1217cache coherence.  The relation is called prop, and it links two events
1218on CPU C in situations where a store from some other CPU comes after
1219the first event in the coherence order and propagates to C before the
1220second event executes.
1221
1222This is best explained with some examples.  The simplest case looks
1223like this:
1224
1225	int x;
1226
1227	P0()
1228	{
1229		int r1;
1230
1231		WRITE_ONCE(x, 1);
1232		r1 = READ_ONCE(x);
1233	}
1234
1235	P1()
1236	{
1237		WRITE_ONCE(x, 8);
1238	}
1239
1240If r1 = 8 at the end then P0's accesses must have executed in program
1241order.  We can deduce this from the operational model; if P0's load
1242had executed before its store then the value of the store would have
1243been forwarded to the load, so r1 would have ended up equal to 1, not
12448.  In this case there is a prop link from P0's write event to its read
1245event, because P1's store came after P0's store in x's coherence
1246order, and P1's store propagated to P0 before P0's load executed.
1247
1248An equally simple case involves two loads of the same location that
1249read from different stores:
1250
1251	int x = 0;
1252
1253	P0()
1254	{
1255		int r1, r2;
1256
1257		r1 = READ_ONCE(x);
1258		r2 = READ_ONCE(x);
1259	}
1260
1261	P1()
1262	{
1263		WRITE_ONCE(x, 9);
1264	}
1265
1266If r1 = 0 and r2 = 9 at the end then P0's accesses must have executed
1267in program order.  If the second load had executed before the first
1268then the x = 9 store must have been propagated to P0 before the first
1269load executed, and so r1 would have been 9 rather than 0.  In this
1270case there is a prop link from P0's first read event to its second,
1271because P1's store overwrote the value read by P0's first load, and
1272P1's store propagated to P0 before P0's second load executed.
1273
1274Less trivial examples of prop all involve fences.  Unlike the simple
1275examples above, they can require that some instructions are executed
1276out of program order.  This next one should look familiar:
1277
1278	int buf = 0, flag = 0;
1279
1280	P0()
1281	{
1282		WRITE_ONCE(buf, 1);
1283		smp_wmb();
1284		WRITE_ONCE(flag, 1);
1285	}
1286
1287	P1()
1288	{
1289		int r1;
1290		int r2;
1291
1292		r1 = READ_ONCE(flag);
1293		r2 = READ_ONCE(buf);
1294	}
1295
1296This is the MP pattern again, with an smp_wmb() fence between the two
1297stores.  If r1 = 1 and r2 = 0 at the end then there is a prop link
1298from P1's second load to its first (backwards!).  The reason is
1299similar to the previous examples: The value P1 loads from buf gets
1300overwritten by P0's store to buf, the fence guarantees that the store
1301to buf will propagate to P1 before the store to flag does, and the
1302store to flag propagates to P1 before P1 reads flag.
1303
1304The prop link says that in order to obtain the r1 = 1, r2 = 0 result,
1305P1 must execute its second load before the first.  Indeed, if the load
1306from flag were executed first, then the buf = 1 store would already
1307have propagated to P1 by the time P1's load from buf executed, so r2
1308would have been 1 at the end, not 0.  (The reasoning holds even for
1309Alpha, although the details are more complicated and we will not go
1310into them.)
1311
1312But what if we put an smp_rmb() fence between P1's loads?  The fence
1313would force the two loads to be executed in program order, and it
1314would generate a cycle in the hb relation: The fence would create a ppo
1315link (hence an hb link) from the first load to the second, and the
1316prop relation would give an hb link from the second load to the first.
1317Since an instruction can't execute before itself, we are forced to
1318conclude that if an smp_rmb() fence is added, the r1 = 1, r2 = 0
1319outcome is impossible -- as it should be.
1320
1321The formal definition of the prop relation involves a coe or fre link,
1322followed by an arbitrary number of cumul-fence links, ending with an
1323rfe link.  You can concoct more exotic examples, containing more than
1324one fence, although this quickly leads to diminishing returns in terms
1325of complexity.  For instance, here's an example containing a coe link
1326followed by two fences and an rfe link, utilizing the fact that
1327release fences are A-cumulative:
1328
1329	int x, y, z;
1330
1331	P0()
1332	{
1333		int r0;
1334
1335		WRITE_ONCE(x, 1);
1336		r0 = READ_ONCE(z);
1337	}
1338
1339	P1()
1340	{
1341		WRITE_ONCE(x, 2);
1342		smp_wmb();
1343		WRITE_ONCE(y, 1);
1344	}
1345
1346	P2()
1347	{
1348		int r2;
1349
1350		r2 = READ_ONCE(y);
1351		smp_store_release(&z, 1);
1352	}
1353
1354If x = 2, r0 = 1, and r2 = 1 after this code runs then there is a prop
1355link from P0's store to its load.  This is because P0's store gets
1356overwritten by P1's store since x = 2 at the end (a coe link), the
1357smp_wmb() ensures that P1's store to x propagates to P2 before the
1358store to y does (the first fence), the store to y propagates to P2
1359before P2's load and store execute, P2's smp_store_release()
1360guarantees that the stores to x and y both propagate to P0 before the
1361store to z does (the second fence), and P0's load executes after the
1362store to z has propagated to P0 (an rfe link).
1363
1364In summary, the fact that the hb relation links memory access events
1365in the order they execute means that it must not have cycles.  This
1366requirement is the content of the LKMM's "happens-before" axiom.
1367
1368The LKMM defines yet another relation connected to times of
1369instruction execution, but it is not included in hb.  It relies on the
1370particular properties of strong fences, which we cover in the next
1371section.
1372
1373
1374THE PROPAGATES-BEFORE RELATION: pb
1375----------------------------------
1376
1377The propagates-before (pb) relation capitalizes on the special
1378features of strong fences.  It links two events E and F whenever some
1379store is coherence-later than E and propagates to every CPU and to RAM
1380before F executes.  The formal definition requires that E be linked to
1381F via a coe or fre link, an arbitrary number of cumul-fences, an
1382optional rfe link, a strong fence, and an arbitrary number of hb
1383links.  Let's see how this definition works out.
1384
1385Consider first the case where E is a store (implying that the sequence
1386of links begins with coe).  Then there are events W, X, Y, and Z such
1387that:
1388
1389	E ->coe W ->cumul-fence* X ->rfe? Y ->strong-fence Z ->hb* F,
1390
1391where the * suffix indicates an arbitrary number of links of the
1392specified type, and the ? suffix indicates the link is optional (Y may
1393be equal to X).  Because of the cumul-fence links, we know that W will
1394propagate to Y's CPU before X does, hence before Y executes and hence
1395before the strong fence executes.  Because this fence is strong, we
1396know that W will propagate to every CPU and to RAM before Z executes.
1397And because of the hb links, we know that Z will execute before F.
1398Thus W, which comes later than E in the coherence order, will
1399propagate to every CPU and to RAM before F executes.
1400
1401The case where E is a load is exactly the same, except that the first
1402link in the sequence is fre instead of coe.
1403
1404The existence of a pb link from E to F implies that E must execute
1405before F.  To see why, suppose that F executed first.  Then W would
1406have propagated to E's CPU before E executed.  If E was a store, the
1407memory subsystem would then be forced to make E come after W in the
1408coherence order, contradicting the fact that E ->coe W.  If E was a
1409load, the memory subsystem would then be forced to satisfy E's read
1410request with the value stored by W or an even later store,
1411contradicting the fact that E ->fre W.
1412
1413A good example illustrating how pb works is the SB pattern with strong
1414fences:
1415
1416	int x = 0, y = 0;
1417
1418	P0()
1419	{
1420		int r0;
1421
1422		WRITE_ONCE(x, 1);
1423		smp_mb();
1424		r0 = READ_ONCE(y);
1425	}
1426
1427	P1()
1428	{
1429		int r1;
1430
1431		WRITE_ONCE(y, 1);
1432		smp_mb();
1433		r1 = READ_ONCE(x);
1434	}
1435
1436If r0 = 0 at the end then there is a pb link from P0's load to P1's
1437load: an fre link from P0's load to P1's store (which overwrites the
1438value read by P0), and a strong fence between P1's store and its load.
1439In this example, the sequences of cumul-fence and hb links are empty.
1440Note that this pb link is not included in hb as an instance of prop,
1441because it does not start and end on the same CPU.
1442
1443Similarly, if r1 = 0 at the end then there is a pb link from P1's load
1444to P0's.  This means that if both r1 and r2 were 0 there would be a
1445cycle in pb, which is not possible since an instruction cannot execute
1446before itself.  Thus, adding smp_mb() fences to the SB pattern
1447prevents the r0 = 0, r1 = 0 outcome.
1448
1449In summary, the fact that the pb relation links events in the order
1450they execute means that it cannot have cycles.  This requirement is
1451the content of the LKMM's "propagation" axiom.
1452
1453
1454RCU RELATIONS: rcu-link, gp, rscs, rcu-fence, and rb
1455----------------------------------------------------
1456
1457RCU (Read-Copy-Update) is a powerful synchronization mechanism.  It
1458rests on two concepts: grace periods and read-side critical sections.
1459
1460A grace period is the span of time occupied by a call to
1461synchronize_rcu().  A read-side critical section (or just critical
1462section, for short) is a region of code delimited by rcu_read_lock()
1463at the start and rcu_read_unlock() at the end.  Critical sections can
1464be nested, although we won't make use of this fact.
1465
1466As far as memory models are concerned, RCU's main feature is its
1467Grace-Period Guarantee, which states that a critical section can never
1468span a full grace period.  In more detail, the Guarantee says:
1469
1470	If a critical section starts before a grace period then it
1471	must end before the grace period does.  In addition, every
1472	store that propagates to the critical section's CPU before the
1473	end of the critical section must propagate to every CPU before
1474	the end of the grace period.
1475
1476	If a critical section ends after a grace period ends then it
1477	must start after the grace period does.  In addition, every
1478	store that propagates to the grace period's CPU before the
1479	start of the grace period must propagate to every CPU before
1480	the start of the critical section.
1481
1482Here is a simple example of RCU in action:
1483
1484	int x, y;
1485
1486	P0()
1487	{
1488		rcu_read_lock();
1489		WRITE_ONCE(x, 1);
1490		WRITE_ONCE(y, 1);
1491		rcu_read_unlock();
1492	}
1493
1494	P1()
1495	{
1496		int r1, r2;
1497
1498		r1 = READ_ONCE(x);
1499		synchronize_rcu();
1500		r2 = READ_ONCE(y);
1501	}
1502
1503The Grace Period Guarantee tells us that when this code runs, it will
1504never end with r1 = 1 and r2 = 0.  The reasoning is as follows.  r1 = 1
1505means that P0's store to x propagated to P1 before P1 called
1506synchronize_rcu(), so P0's critical section must have started before
1507P1's grace period.  On the other hand, r2 = 0 means that P0's store to
1508y, which occurs before the end of the critical section, did not
1509propagate to P1 before the end of the grace period, violating the
1510Guarantee.
1511
1512In the kernel's implementations of RCU, the requirements for stores
1513to propagate to every CPU are fulfilled by placing strong fences at
1514suitable places in the RCU-related code.  Thus, if a critical section
1515starts before a grace period does then the critical section's CPU will
1516execute an smp_mb() fence after the end of the critical section and
1517some time before the grace period's synchronize_rcu() call returns.
1518And if a critical section ends after a grace period does then the
1519synchronize_rcu() routine will execute an smp_mb() fence at its start
1520and some time before the critical section's opening rcu_read_lock()
1521executes.
1522
1523What exactly do we mean by saying that a critical section "starts
1524before" or "ends after" a grace period?  Some aspects of the meaning
1525are pretty obvious, as in the example above, but the details aren't
1526entirely clear.  The LKMM formalizes this notion by means of the
1527rcu-link relation.  rcu-link encompasses a very general notion of
1528"before": Among other things, X ->rcu-link Z includes cases where X
1529happens-before or is equal to some event Y which is equal to or comes
1530before Z in the coherence order.  When Y = Z this says that X ->rfe Z
1531implies X ->rcu-link Z.  In addition, when Y = X it says that X ->fr Z
1532and X ->co Z each imply X ->rcu-link Z.
1533
1534The formal definition of the rcu-link relation is more than a little
1535obscure, and we won't give it here.  It is closely related to the pb
1536relation, and the details don't matter unless you want to comb through
1537a somewhat lengthy formal proof.  Pretty much all you need to know
1538about rcu-link is the information in the preceding paragraph.
1539
1540The LKMM also defines the gp and rscs relations.  They bring grace
1541periods and read-side critical sections into the picture, in the
1542following way:
1543
1544	E ->gp F means there is a synchronize_rcu() fence event S such
1545	that E ->po S and either S ->po F or S = F.  In simple terms,
1546	there is a grace period po-between E and F.
1547
1548	E ->rscs F means there is a critical section delimited by an
1549	rcu_read_lock() fence L and an rcu_read_unlock() fence U, such
1550	that E ->po U and either L ->po F or L = F.  You can think of
1551	this as saying that E and F are in the same critical section
1552	(in fact, it also allows E to be po-before the start of the
1553	critical section and F to be po-after the end).
1554
1555If we think of the rcu-link relation as standing for an extended
1556"before", then X ->gp Y ->rcu-link Z says that X executes before a
1557grace period which ends before Z executes.  (In fact it covers more
1558than this, because it also includes cases where X executes before a
1559grace period and some store propagates to Z's CPU before Z executes
1560but doesn't propagate to some other CPU until after the grace period
1561ends.)  Similarly, X ->rscs Y ->rcu-link Z says that X is part of (or
1562before the start of) a critical section which starts before Z
1563executes.
1564
1565The LKMM goes on to define the rcu-fence relation as a sequence of gp
1566and rscs links separated by rcu-link links, in which the number of gp
1567links is >= the number of rscs links.  For example:
1568
1569	X ->gp Y ->rcu-link Z ->rscs T ->rcu-link U ->gp V
1570
1571would imply that X ->rcu-fence V, because this sequence contains two
1572gp links and only one rscs link.  (It also implies that X ->rcu-fence T
1573and Z ->rcu-fence V.)  On the other hand:
1574
1575	X ->rscs Y ->rcu-link Z ->rscs T ->rcu-link U ->gp V
1576
1577does not imply X ->rcu-fence V, because the sequence contains only
1578one gp link but two rscs links.
1579
1580The rcu-fence relation is important because the Grace Period Guarantee
1581means that rcu-fence acts kind of like a strong fence.  In particular,
1582if W is a write and we have W ->rcu-fence Z, the Guarantee says that W
1583will propagate to every CPU before Z executes.
1584
1585To prove this in full generality requires some intellectual effort.
1586We'll consider just a very simple case:
1587
1588	W ->gp X ->rcu-link Y ->rscs Z.
1589
1590This formula means that there is a grace period G and a critical
1591section C such that:
1592
1593	1. W is po-before G;
1594
1595	2. X is equal to or po-after G;
1596
1597	3. X comes "before" Y in some sense;
1598
1599	4. Y is po-before the end of C;
1600
1601	5. Z is equal to or po-after the start of C.
1602
1603From 2 - 4 we deduce that the grace period G ends before the critical
1604section C.  Then the second part of the Grace Period Guarantee says
1605not only that G starts before C does, but also that W (which executes
1606on G's CPU before G starts) must propagate to every CPU before C
1607starts.  In particular, W propagates to every CPU before Z executes
1608(or finishes executing, in the case where Z is equal to the
1609rcu_read_lock() fence event which starts C.)  This sort of reasoning
1610can be expanded to handle all the situations covered by rcu-fence.
1611
1612Finally, the LKMM defines the RCU-before (rb) relation in terms of
1613rcu-fence.  This is done in essentially the same way as the pb
1614relation was defined in terms of strong-fence.  We will omit the
1615details; the end result is that E ->rb F implies E must execute before
1616F, just as E ->pb F does (and for much the same reasons).
1617
1618Putting this all together, the LKMM expresses the Grace Period
1619Guarantee by requiring that the rb relation does not contain a cycle.
1620Equivalently, this "rcu" axiom requires that there are no events E and
1621F with E ->rcu-link F ->rcu-fence E.  Or to put it a third way, the
1622axiom requires that there are no cycles consisting of gp and rscs
1623alternating with rcu-link, where the number of gp links is >= the
1624number of rscs links.
1625
1626Justifying the axiom isn't easy, but it is in fact a valid
1627formalization of the Grace Period Guarantee.  We won't attempt to go
1628through the detailed argument, but the following analysis gives a
1629taste of what is involved.  Suppose we have a violation of the first
1630part of the Guarantee: A critical section starts before a grace
1631period, and some store propagates to the critical section's CPU before
1632the end of the critical section but doesn't propagate to some other
1633CPU until after the end of the grace period.
1634
1635Putting symbols to these ideas, let L and U be the rcu_read_lock() and
1636rcu_read_unlock() fence events delimiting the critical section in
1637question, and let S be the synchronize_rcu() fence event for the grace
1638period.  Saying that the critical section starts before S means there
1639are events E and F where E is po-after L (which marks the start of the
1640critical section), E is "before" F in the sense of the rcu-link
1641relation, and F is po-before the grace period S:
1642
1643	L ->po E ->rcu-link F ->po S.
1644
1645Let W be the store mentioned above, let Z come before the end of the
1646critical section and witness that W propagates to the critical
1647section's CPU by reading from W, and let Y on some arbitrary CPU be a
1648witness that W has not propagated to that CPU, where Y happens after
1649some event X which is po-after S.  Symbolically, this amounts to:
1650
1651	S ->po X ->hb* Y ->fr W ->rf Z ->po U.
1652
1653The fr link from Y to W indicates that W has not propagated to Y's CPU
1654at the time that Y executes.  From this, it can be shown (see the
1655discussion of the rcu-link relation earlier) that X and Z are related
1656by rcu-link, yielding:
1657
1658	S ->po X ->rcu-link Z ->po U.
1659
1660The formulas say that S is po-between F and X, hence F ->gp X.  They
1661also say that Z comes before the end of the critical section and E
1662comes after its start, hence Z ->rscs E.  From all this we obtain:
1663
1664	F ->gp X ->rcu-link Z ->rscs E ->rcu-link F,
1665
1666a forbidden cycle.  Thus the "rcu" axiom rules out this violation of
1667the Grace Period Guarantee.
1668
1669For something a little more down-to-earth, let's see how the axiom
1670works out in practice.  Consider the RCU code example from above, this
1671time with statement labels added to the memory access instructions:
1672
1673	int x, y;
1674
1675	P0()
1676	{
1677		rcu_read_lock();
1678		W: WRITE_ONCE(x, 1);
1679		X: WRITE_ONCE(y, 1);
1680		rcu_read_unlock();
1681	}
1682
1683	P1()
1684	{
1685		int r1, r2;
1686
1687		Y: r1 = READ_ONCE(x);
1688		synchronize_rcu();
1689		Z: r2 = READ_ONCE(y);
1690	}
1691
1692
1693If r2 = 0 at the end then P0's store at X overwrites the value that
1694P1's load at Z reads from, so we have Z ->fre X and thus Z ->rcu-link X.
1695In addition, there is a synchronize_rcu() between Y and Z, so therefore
1696we have Y ->gp Z.
1697
1698If r1 = 1 at the end then P1's load at Y reads from P0's store at W,
1699so we have W ->rcu-link Y.  In addition, W and X are in the same critical
1700section, so therefore we have X ->rscs W.
1701
1702Then X ->rscs W ->rcu-link Y ->gp Z ->rcu-link X is a forbidden cycle,
1703violating the "rcu" axiom.  Hence the outcome is not allowed by the
1704LKMM, as we would expect.
1705
1706For contrast, let's see what can happen in a more complicated example:
1707
1708	int x, y, z;
1709
1710	P0()
1711	{
1712		int r0;
1713
1714		rcu_read_lock();
1715		W: r0 = READ_ONCE(x);
1716		X: WRITE_ONCE(y, 1);
1717		rcu_read_unlock();
1718	}
1719
1720	P1()
1721	{
1722		int r1;
1723
1724		Y: r1 = READ_ONCE(y);
1725		synchronize_rcu();
1726		Z: WRITE_ONCE(z, 1);
1727	}
1728
1729	P2()
1730	{
1731		int r2;
1732
1733		rcu_read_lock();
1734		U: r2 = READ_ONCE(z);
1735		V: WRITE_ONCE(x, 1);
1736		rcu_read_unlock();
1737	}
1738
1739If r0 = r1 = r2 = 1 at the end, then similar reasoning to before shows
1740that W ->rscs X ->rcu-link Y ->gp Z ->rcu-link U ->rscs V ->rcu-link W.
1741However this cycle is not forbidden, because the sequence of relations
1742contains fewer instances of gp (one) than of rscs (two).  Consequently
1743the outcome is allowed by the LKMM.  The following instruction timing
1744diagram shows how it might actually occur:
1745
1746P0			P1			P2
1747--------------------	--------------------	--------------------
1748rcu_read_lock()
1749X: WRITE_ONCE(y, 1)
1750			Y: r1 = READ_ONCE(y)
1751			synchronize_rcu() starts
1752			.			rcu_read_lock()
1753			.			V: WRITE_ONCE(x, 1)
1754W: r0 = READ_ONCE(x)	.
1755rcu_read_unlock()	.
1756			synchronize_rcu() ends
1757			Z: WRITE_ONCE(z, 1)
1758						U: r2 = READ_ONCE(z)
1759						rcu_read_unlock()
1760
1761This requires P0 and P2 to execute their loads and stores out of
1762program order, but of course they are allowed to do so.  And as you
1763can see, the Grace Period Guarantee is not violated: The critical
1764section in P0 both starts before P1's grace period does and ends
1765before it does, and the critical section in P2 both starts after P1's
1766grace period does and ends after it does.
1767
1768
1769ODDS AND ENDS
1770-------------
1771
1772This section covers material that didn't quite fit anywhere in the
1773earlier sections.
1774
1775The descriptions in this document don't always match the formal
1776version of the LKMM exactly.  For example, the actual formal
1777definition of the prop relation makes the initial coe or fre part
1778optional, and it doesn't require the events linked by the relation to
1779be on the same CPU.  These differences are very unimportant; indeed,
1780instances where the coe/fre part of prop is missing are of no interest
1781because all the other parts (fences and rfe) are already included in
1782hb anyway, and where the formal model adds prop into hb, it includes
1783an explicit requirement that the events being linked are on the same
1784CPU.
1785
1786Another minor difference has to do with events that are both memory
1787accesses and fences, such as those corresponding to smp_load_acquire()
1788calls.  In the formal model, these events aren't actually both reads
1789and fences; rather, they are read events with an annotation marking
1790them as acquires.  (Or write events annotated as releases, in the case
1791smp_store_release().)  The final effect is the same.
1792
1793Although we didn't mention it above, the instruction execution
1794ordering provided by the smp_rmb() fence doesn't apply to read events
1795that are part of a non-value-returning atomic update.  For instance,
1796given:
1797
1798	atomic_inc(&x);
1799	smp_rmb();
1800	r1 = READ_ONCE(y);
1801
1802it is not guaranteed that the load from y will execute after the
1803update to x.  This is because the ARMv8 architecture allows
1804non-value-returning atomic operations effectively to be executed off
1805the CPU.  Basically, the CPU tells the memory subsystem to increment
1806x, and then the increment is carried out by the memory hardware with
1807no further involvement from the CPU.  Since the CPU doesn't ever read
1808the value of x, there is nothing for the smp_rmb() fence to act on.
1809
1810The LKMM defines a few extra synchronization operations in terms of
1811things we have already covered.  In particular, rcu_dereference() is
1812treated as READ_ONCE() and rcu_assign_pointer() is treated as
1813smp_store_release() -- which is basically how the Linux kernel treats
1814them.
1815
1816There are a few oddball fences which need special treatment:
1817smp_mb__before_atomic(), smp_mb__after_atomic(), and
1818smp_mb__after_spinlock().  The LKMM uses fence events with special
1819annotations for them; they act as strong fences just like smp_mb()
1820except for the sets of events that they order.  Instead of ordering
1821all po-earlier events against all po-later events, as smp_mb() does,
1822they behave as follows:
1823
1824	smp_mb__before_atomic() orders all po-earlier events against
1825	po-later atomic updates and the events following them;
1826
1827	smp_mb__after_atomic() orders po-earlier atomic updates and
1828	the events preceding them against all po-later events;
1829
1830	smp_mb_after_spinlock() orders po-earlier lock acquisition
1831	events and the events preceding them against all po-later
1832	events.
1833
1834The LKMM includes locking.  In fact, there is special code for locking
1835in the formal model, added in order to make tools run faster.
1836However, this special code is intended to be exactly equivalent to
1837concepts we have already covered.  A spinlock_t variable is treated
1838the same as an int, and spin_lock(&s) is treated the same as:
1839
1840	while (cmpxchg_acquire(&s, 0, 1) != 0)
1841		cpu_relax();
1842
1843which waits until s is equal to 0 and then atomically sets it to 1,
1844and where the read part of the atomic update is also an acquire fence.
1845An alternate way to express the same thing would be:
1846
1847	r = xchg_acquire(&s, 1);
1848
1849along with a requirement that at the end, r = 0.  spin_unlock(&s) is
1850treated the same as:
1851
1852	smp_store_release(&s, 0);
1853
1854Interestingly, RCU and locking each introduce the possibility of
1855deadlock.  When faced with code sequences such as:
1856
1857	spin_lock(&s);
1858	spin_lock(&s);
1859	spin_unlock(&s);
1860	spin_unlock(&s);
1861
1862or:
1863
1864	rcu_read_lock();
1865	synchronize_rcu();
1866	rcu_read_unlock();
1867
1868what does the LKMM have to say?  Answer: It says there are no allowed
1869executions at all, which makes sense.  But this can also lead to
1870misleading results, because if a piece of code has multiple possible
1871executions, some of which deadlock, the model will report only on the
1872non-deadlocking executions.  For example:
1873
1874	int x, y;
1875
1876	P0()
1877	{
1878		int r0;
1879
1880		WRITE_ONCE(x, 1);
1881		r0 = READ_ONCE(y);
1882	}
1883
1884	P1()
1885	{
1886		rcu_read_lock();
1887		if (READ_ONCE(x) > 0) {
1888			WRITE_ONCE(y, 36);
1889			synchronize_rcu();
1890		}
1891		rcu_read_unlock();
1892	}
1893
1894Is it possible to end up with r0 = 36 at the end?  The LKMM will tell
1895you it is not, but the model won't mention that this is because P1
1896will self-deadlock in the executions where it stores 36 in y.
1897