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