Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

Automate memory-barriers.txt; provide Linux-kernel memory model

There is some reason to believe that Documentation/memory-barriers.txt
could use some help, and a major purpose of this patch is to provide
that help in the form of a design-time tool that can produce all valid
executions of a small fragment of concurrent Linux-kernel code, which is
called a "litmus test". This tool's functionality is roughly similar to
a full state-space search. Please note that this is a design-time tool,
not useful for regression testing. However, we hope that the underlying
Linux-kernel memory model will be incorporated into other tools capable
of analyzing large bodies of code for regression-testing purposes.

The main tool is herd7, together with the linux-kernel.bell,
linux-kernel.cat, linux-kernel.cfg, linux-kernel.def, and lock.cat files
added by this patch. The herd7 executable takes the other files as input,
and all of these files collectively define the Linux-kernel memory memory
model. A brief description of each of these other files is provided
in the README file. Although this tool does have its limitations,
which are documented in the README file, it does improve on the version
reported on in the LWN series (https://lwn.net/Articles/718628/ and
https://lwn.net/Articles/720550/) by supporting locking and arithmetic,
including a much wider variety of read-modify-write atomic operations.
Please note that herd7 is not part of this submission, but is freely
available from http://diy.inria.fr/sources/index.html (and via "git"
at https://github.com/herd/herdtools7).

A second tool is klitmus7, which converts litmus tests to loadable
kernel modules for direct testing. As with herd7, the klitmus7
code is freely available from http://diy.inria.fr/sources/index.html
(and via "git" at https://github.com/herd/herdtools7).

Of course, litmus tests are not always the best way to fully understand a
memory model, so this patch also includes Documentation/explanation.txt,
which describes the memory model in detail. In addition,
Documentation/recipes.txt provides example known-good and known-bad use
cases for those who prefer working by example.

This patch also includes a few sample litmus tests, and a great many
more litmus tests are available at https://github.com/paulmckrcu/litmus.

This patch was the result of a most excellent collaboration founded
by Jade Alglave and also including Alan Stern, Andrea Parri, and Luc
Maranget. For more details on the history of this collaboration, please
refer to the Linux-kernel memory model presentations at 2016 LinuxCon EU,
2016 Kernel Summit, 2016 Linux Plumbers Conference, 2017 linux.conf.au,
or 2017 Linux Plumbers Conference microconference. However, one aspect
of the history does bear repeating due to weak copyright tracking earlier
in this project, which extends back to early 2015. This weakness came
to light in late 2017 after an LKMM presentation by Paul in which an
audience member noted the similarity of some LKMM code to code in early
published papers. This prompted a copyright review.

From Alan Stern:

To say that the model was mine is not entirely accurate.
Pieces of it (especially the Scpv and Atomic axioms) were taken
directly from Jade's models. And of course the Happens-before
and Propagation relations and axioms were heavily based on
Jade and Luc's work, even though they weren't identical to the
earlier versions. Only the RCU portion was completely original.

. . .

One can make a much better case that I wrote the bulk of lock.cat.
However, it was inspired by Luc's earlier version (and still
shares some elements in common), and of course it benefited from
feedback and testing from all members of our group.

The model prior to Alan's was Luc Maranget's. From Luc:

I totally agree on Alan Stern's account of the linux kernel model
genesis. I thank him for his acknowledgments of my participation
to previous model drafts. I'd like to complete Alan Stern's
statement: any bell cat code I have written has its roots in
discussions with Jade Alglave and Paul McKenney. Moreover I
have borrowed cat and bell code written by Jade Alglave freely.

This copyright review therefore resulted in late adds to the copyright
statements of several files.

Discussion of v1 has raised several issues, which we do not believe should
block acceptance given that this level of change will be ongoing, just
as it has been with memory-barriers.txt:

o Under what conditions should ordering provided by pure locking
be seen by CPUs not holding the relevant lock(s)? In particular,
should the message-passing pattern be forbidden?

o Should examples involving C11 release sequences be forbidden?
Note that this C11 is still a moving target for this issue:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0735r0.html

o Some details of the handling of internal dependencies for atomic
read-modify-write atomic operations are still subject to debate.

o Changes recently accepted into mainline greatly reduce the need
to handle DEC Alpha as a special case. These changes add an
smp_read_barrier_depends() to READ_ONCE(), thus causing Alpha
to respect ordering of dependent reads. If these changes stick,
the memory model can be simplified accordingly.

o Will changes be required to accommodate RISC-V?

Differences from v1:
(http://lkml.kernel.org/r/20171113184031.GA26302@linux.vnet.ibm.com)

o Add SPDX notations to .bell and .cat files, replacing
textual license statements.

o Add reference to upcoming ASPLOS paper to .bell and .cat files.

o Updated identifier names in .bell and .cat files to match those
used in the ASPLOS paper.

o Updates to READMEs and other documentation based on review
feedback.

o Added a memory-ordering cheatsheet.

o Update sigs to new Co-Developed-by and add acks and
reviewed-bys.

o Simplify rules detecting nested RCU read-side critical sections.

o Update copyright statements as noted above.

Co-Developed-by: Alan Stern <stern@rowland.harvard.edu>
Co-Developed-by: Andrea Parri <parri.andrea@gmail.com>
Co-Developed-by: Jade Alglave <j.alglave@ucl.ac.uk>
Co-Developed-by: Luc Maranget <luc.maranget@inria.fr>
Co-Developed-by: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com>
Signed-off-by: Alan Stern <stern@rowland.harvard.edu>
Signed-off-by: Andrea Parri <parri.andrea@gmail.com>
Signed-off-by: Jade Alglave <j.alglave@ucl.ac.uk>
Signed-off-by: Luc Maranget <luc.maranget@inria.fr>
Signed-off-by: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Acked-by: Will Deacon <will.deacon@arm.com>
Acked-by: Peter Zijlstra <peterz@infradead.org>
Acked-by: Nicholas Piggin <npiggin@gmail.com>
Acked-by: David Howells <dhowells@redhat.com>
Acked-by: "Reshetova, Elena" <elena.reshetova@intel.com>
Acked-by: Michal Hocko <mhocko@suse.com>
Acked-by: Akira Yokosawa <akiyks@gmail.com>
Cc: <linux-arch@vger.kernel.org>

+3973
+30
tools/memory-model/Documentation/cheatsheet.txt
··· 1 + Prior Operation Subsequent Operation 2 + --------------- --------------------------- 3 + C Self R W RWM Self R W DR DW RMW SV 4 + __ ---- - - --- ---- - - -- -- --- -- 5 + 6 + Store, e.g., WRITE_ONCE() Y Y 7 + Load, e.g., READ_ONCE() Y Y Y 8 + Unsuccessful RMW operation Y Y Y 9 + smp_read_barrier_depends() Y Y Y 10 + *_dereference() Y Y Y Y 11 + Successful *_acquire() R Y Y Y Y Y Y 12 + Successful *_release() C Y Y Y W Y 13 + smp_rmb() Y R Y Y R 14 + smp_wmb() Y W Y Y W 15 + smp_mb() & synchronize_rcu() CP Y Y Y Y Y Y Y Y 16 + Successful full non-void RMW CP Y Y Y Y Y Y Y Y Y Y Y 17 + smp_mb__before_atomic() CP Y Y Y a a a a Y 18 + smp_mb__after_atomic() CP a a Y Y Y Y Y 19 + 20 + 21 + Key: C: Ordering is cumulative 22 + P: Ordering propagates 23 + R: Read, for example, READ_ONCE(), or read portion of RMW 24 + W: Write, for example, WRITE_ONCE(), or write portion of RMW 25 + Y: Provides ordering 26 + a: Provides ordering given intervening RMW atomic operation 27 + DR: Dependent read (address dependency) 28 + DW: Dependent write (address, data, or control dependency) 29 + RMW: Atomic read-modify-write operation 30 + SV Same-variable access
+1840
tools/memory-model/Documentation/explanation.txt
··· 1 + Explanation of the Linux-Kernel Memory 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: link, gp-link, rscs-link, and rcu-path 31 + 23. ODDS AND ENDS 32 + 33 + 34 + 35 + INTRODUCTION 36 + ------------ 37 + 38 + The Linux-kernel memory model (LKMM) is rather complex and obscure. 39 + This is particularly evident if you read through the linux-kernel.bell 40 + and linux-kernel.cat files that make up the formal version of the 41 + memory model; they are extremely terse and their meanings are far from 42 + clear. 43 + 44 + This document describes the ideas underlying the LKMM. It is meant 45 + for people who want to understand how the memory model was designed. 46 + It does not go into the details of the code in the .bell and .cat 47 + files; rather, it explains in English what the code expresses 48 + symbolically. 49 + 50 + Sections 2 (BACKGROUND) through 5 (ORDERING AND CYCLES) are aimed 51 + toward beginners; they explain what memory models are and the basic 52 + notions shared by all such models. People already familiar with these 53 + concepts can skim or skip over them. Sections 6 (EVENTS) through 12 54 + (THE FROM_READS RELATION) describe the fundamental relations used in 55 + many memory models. Starting in Section 13 (AN OPERATIONAL MODEL), 56 + the workings of the LKMM itself are covered. 57 + 58 + Warning: The code examples in this document are not written in the 59 + proper format for litmus tests. They don't include a header line, the 60 + initializations are not enclosed in braces, the global variables are 61 + not passed by pointers, and they don't have an "exists" clause at the 62 + end. Converting them to the right format is left as an exercise for 63 + the reader. 64 + 65 + 66 + BACKGROUND 67 + ---------- 68 + 69 + A memory consistency model (or just memory model, for short) is 70 + something which predicts, given a piece of computer code running on a 71 + particular kind of system, what values may be obtained by the code's 72 + load instructions. The LKMM makes these predictions for code running 73 + as part of the Linux kernel. 74 + 75 + In practice, people tend to use memory models the other way around. 76 + That is, given a piece of code and a collection of values specified 77 + for the loads, the model will predict whether it is possible for the 78 + code to run in such a way that the loads will indeed obtain the 79 + specified values. Of course, this is just another way of expressing 80 + the same idea. 81 + 82 + For code running on a uniprocessor system, the predictions are easy: 83 + Each load instruction must obtain the value written by the most recent 84 + store instruction accessing the same location (we ignore complicating 85 + factors such as DMA and mixed-size accesses.) But on multiprocessor 86 + systems, with multiple CPUs making concurrent accesses to shared 87 + memory locations, things aren't so simple. 88 + 89 + Different architectures have differing memory models, and the Linux 90 + kernel supports a variety of architectures. The LKMM has to be fairly 91 + permissive, in the sense that any behavior allowed by one of these 92 + architectures also has to be allowed by the LKMM. 93 + 94 + 95 + A SIMPLE EXAMPLE 96 + ---------------- 97 + 98 + Here is a simple example to illustrate the basic concepts. Consider 99 + some code running as part of a device driver for an input device. The 100 + driver might contain an interrupt handler which collects data from the 101 + device, stores it in a buffer, and sets a flag to indicate the buffer 102 + is full. Running concurrently on a different CPU might be a part of 103 + the driver code being executed by a process in the midst of a read(2) 104 + system call. This code tests the flag to see whether the buffer is 105 + ready, and if it is, copies the data back to userspace. The buffer 106 + and the flag are memory locations shared between the two CPUs. 107 + 108 + We can abstract out the important pieces of the driver code as follows 109 + (the reason for using WRITE_ONCE() and READ_ONCE() instead of simple 110 + assignment statements is discussed later): 111 + 112 + int buf = 0, flag = 0; 113 + 114 + P0() 115 + { 116 + WRITE_ONCE(buf, 1); 117 + WRITE_ONCE(flag, 1); 118 + } 119 + 120 + P1() 121 + { 122 + int r1; 123 + int r2 = 0; 124 + 125 + r1 = READ_ONCE(flag); 126 + if (r1) 127 + r2 = READ_ONCE(buf); 128 + } 129 + 130 + Here the P0() function represents the interrupt handler running on one 131 + CPU and P1() represents the read() routine running on another. The 132 + value 1 stored in buf represents input data collected from the device. 133 + Thus, P0 stores the data in buf and then sets flag. Meanwhile, P1 134 + reads flag into the private variable r1, and if it is set, reads the 135 + data from buf into a second private variable r2 for copying to 136 + userspace. (Presumably if flag is not set then the driver will wait a 137 + while and try again.) 138 + 139 + This pattern of memory accesses, where one CPU stores values to two 140 + shared memory locations and another CPU loads from those locations in 141 + the opposite order, is widely known as the "Message Passing" or MP 142 + pattern. It is typical of memory access patterns in the kernel. 143 + 144 + Please note that this example code is a simplified abstraction. Real 145 + buffers are usually larger than a single integer, real device drivers 146 + usually use sleep and wakeup mechanisms rather than polling for I/O 147 + completion, and real code generally doesn't bother to copy values into 148 + private variables before using them. All that is beside the point; 149 + the idea here is simply to illustrate the overall pattern of memory 150 + accesses by the CPUs. 151 + 152 + A memory model will predict what values P1 might obtain for its loads 153 + from flag and buf, or equivalently, what values r1 and r2 might end up 154 + with after the code has finished running. 155 + 156 + Some predictions are trivial. For instance, no sane memory model would 157 + predict that r1 = 42 or r2 = -7, because neither of those values ever 158 + gets stored in flag or buf. 159 + 160 + Some nontrivial predictions are nonetheless quite simple. For 161 + instance, P1 might run entirely before P0 begins, in which case r1 and 162 + r2 will both be 0 at the end. Or P0 might run entirely before P1 163 + begins, in which case r1 and r2 will both be 1. 164 + 165 + The interesting predictions concern what might happen when the two 166 + routines run concurrently. One possibility is that P1 runs after P0's 167 + store to buf but before the store to flag. In this case, r1 and r2 168 + will again both be 0. (If P1 had been designed to read buf 169 + unconditionally then we would instead have r1 = 0 and r2 = 1.) 170 + 171 + However, the most interesting possibility is where r1 = 1 and r2 = 0. 172 + If this were to occur it would mean the driver contains a bug, because 173 + incorrect data would get sent to the user: 0 instead of 1. As it 174 + happens, the LKMM does predict this outcome can occur, and the example 175 + driver code shown above is indeed buggy. 176 + 177 + 178 + A SELECTION OF MEMORY MODELS 179 + ---------------------------- 180 + 181 + The first widely cited memory model, and the simplest to understand, 182 + is Sequential Consistency. According to this model, systems behave as 183 + if each CPU executed its instructions in order but with unspecified 184 + timing. In other words, the instructions from the various CPUs get 185 + interleaved in a nondeterministic way, always according to some single 186 + global order that agrees with the order of the instructions in the 187 + program source for each CPU. The model says that the value obtained 188 + by each load is simply the value written by the most recently executed 189 + store to the same memory location, from any CPU. 190 + 191 + For the MP example code shown above, Sequential Consistency predicts 192 + that the undesired result r1 = 1, r2 = 0 cannot occur. The reasoning 193 + goes like this: 194 + 195 + Since r1 = 1, P0 must store 1 to flag before P1 loads 1 from 196 + it, as loads can obtain values only from earlier stores. 197 + 198 + P1 loads from flag before loading from buf, since CPUs execute 199 + their instructions in order. 200 + 201 + P1 must load 0 from buf before P0 stores 1 to it; otherwise r2 202 + would be 1 since a load obtains its value from the most recent 203 + store to the same address. 204 + 205 + P0 stores 1 to buf before storing 1 to flag, since it executes 206 + its instructions in order. 207 + 208 + Since an instruction (in this case, P1's store to flag) cannot 209 + execute before itself, the specified outcome is impossible. 210 + 211 + However, real computer hardware almost never follows the Sequential 212 + Consistency memory model; doing so would rule out too many valuable 213 + performance optimizations. On ARM and PowerPC architectures, for 214 + instance, the MP example code really does sometimes yield r1 = 1 and 215 + r2 = 0. 216 + 217 + x86 and SPARC follow yet a different memory model: TSO (Total Store 218 + Ordering). This model predicts that the undesired outcome for the MP 219 + pattern cannot occur, but in other respects it differs from Sequential 220 + Consistency. One example is the Store Buffer (SB) pattern, in which 221 + each CPU stores to its own shared location and then loads from the 222 + other CPU's location: 223 + 224 + int x = 0, y = 0; 225 + 226 + P0() 227 + { 228 + int r0; 229 + 230 + WRITE_ONCE(x, 1); 231 + r0 = READ_ONCE(y); 232 + } 233 + 234 + P1() 235 + { 236 + int r1; 237 + 238 + WRITE_ONCE(y, 1); 239 + r1 = READ_ONCE(x); 240 + } 241 + 242 + Sequential Consistency predicts that the outcome r0 = 0, r1 = 0 is 243 + impossible. (Exercise: Figure out the reasoning.) But TSO allows 244 + this outcome to occur, and in fact it does sometimes occur on x86 and 245 + SPARC systems. 246 + 247 + The LKMM was inspired by the memory models followed by PowerPC, ARM, 248 + x86, Alpha, and other architectures. However, it is different in 249 + detail from each of them. 250 + 251 + 252 + ORDERING AND CYCLES 253 + ------------------- 254 + 255 + Memory models are all about ordering. Often this is temporal ordering 256 + (i.e., the order in which certain events occur) but it doesn't have to 257 + be; consider for example the order of instructions in a program's 258 + source code. We saw above that Sequential Consistency makes an 259 + important assumption that CPUs execute instructions in the same order 260 + as those instructions occur in the code, and there are many other 261 + instances of ordering playing central roles in memory models. 262 + 263 + The counterpart to ordering is a cycle. Ordering rules out cycles: 264 + It's not possible to have X ordered before Y, Y ordered before Z, and 265 + Z ordered before X, because this would mean that X is ordered before 266 + itself. The analysis of the MP example under Sequential Consistency 267 + involved just such an impossible cycle: 268 + 269 + W: P0 stores 1 to flag executes before 270 + X: P1 loads 1 from flag executes before 271 + Y: P1 loads 0 from buf executes before 272 + Z: P0 stores 1 to buf executes before 273 + W: P0 stores 1 to flag. 274 + 275 + In short, if a memory model requires certain accesses to be ordered, 276 + and a certain outcome for the loads in a piece of code can happen only 277 + if those accesses would form a cycle, then the memory model predicts 278 + that outcome cannot occur. 279 + 280 + The LKMM is defined largely in terms of cycles, as we will see. 281 + 282 + 283 + EVENTS 284 + ------ 285 + 286 + The LKMM does not work directly with the C statements that make up 287 + kernel source code. Instead it considers the effects of those 288 + statements in a more abstract form, namely, events. The model 289 + includes three types of events: 290 + 291 + Read events correspond to loads from shared memory, such as 292 + calls to READ_ONCE(), smp_load_acquire(), or 293 + rcu_dereference(). 294 + 295 + Write events correspond to stores to shared memory, such as 296 + calls to WRITE_ONCE(), smp_store_release(), or atomic_set(). 297 + 298 + Fence events correspond to memory barriers (also known as 299 + fences), such as calls to smp_rmb() or rcu_read_lock(). 300 + 301 + These categories are not exclusive; a read or write event can also be 302 + a fence. This happens with functions like smp_load_acquire() or 303 + spin_lock(). However, no single event can be both a read and a write. 304 + Atomic read-modify-write accesses, such as atomic_inc() or xchg(), 305 + correspond to a pair of events: a read followed by a write. (The 306 + write event is omitted for executions where it doesn't occur, such as 307 + a cmpxchg() where the comparison fails.) 308 + 309 + Other parts of the code, those which do not involve interaction with 310 + shared memory, do not give rise to events. Thus, arithmetic and 311 + logical computations, control-flow instructions, or accesses to 312 + private memory or CPU registers are not of central interest to the 313 + memory model. They only affect the model's predictions indirectly. 314 + For example, an arithmetic computation might determine the value that 315 + gets stored to a shared memory location (or in the case of an array 316 + index, the address where the value gets stored), but the memory model 317 + is concerned only with the store itself -- its value and its address 318 + -- not the computation leading up to it. 319 + 320 + Events in the LKMM can be linked by various relations, which we will 321 + describe in the following sections. The memory model requires certain 322 + of these relations to be orderings, that is, it requires them not to 323 + have any cycles. 324 + 325 + 326 + THE PROGRAM ORDER RELATION: po AND po-loc 327 + ----------------------------------------- 328 + 329 + The most important relation between events is program order (po). You 330 + can think of it as the order in which statements occur in the source 331 + code after branches are taken into account and loops have been 332 + unrolled. A better description might be the order in which 333 + instructions are presented to a CPU's execution unit. Thus, we say 334 + that X is po-before Y (written as "X ->po Y" in formulas) if X occurs 335 + before Y in the instruction stream. 336 + 337 + This is inherently a single-CPU relation; two instructions executing 338 + on different CPUs are never linked by po. Also, it is by definition 339 + an ordering so it cannot have any cycles. 340 + 341 + po-loc is a sub-relation of po. It links two memory accesses when the 342 + first comes before the second in program order and they access the 343 + same memory location (the "-loc" suffix). 344 + 345 + Although this may seem straightforward, there is one subtle aspect to 346 + program order we need to explain. The LKMM was inspired by low-level 347 + architectural memory models which describe the behavior of machine 348 + code, and it retains their outlook to a considerable extent. The 349 + read, write, and fence events used by the model are close in spirit to 350 + individual machine instructions. Nevertheless, the LKMM describes 351 + kernel code written in C, and the mapping from C to machine code can 352 + be extremely complex. 353 + 354 + Optimizing compilers have great freedom in the way they translate 355 + source code to object code. They are allowed to apply transformations 356 + that add memory accesses, eliminate accesses, combine them, split them 357 + into pieces, or move them around. Faced with all these possibilities, 358 + the LKMM basically gives up. It insists that the code it analyzes 359 + must contain no ordinary accesses to shared memory; all accesses must 360 + be performed using READ_ONCE(), WRITE_ONCE(), or one of the other 361 + atomic or synchronization primitives. These primitives prevent a 362 + large number of compiler optimizations. In particular, it is 363 + guaranteed that the compiler will not remove such accesses from the 364 + generated code (unless it can prove the accesses will never be 365 + executed), it will not change the order in which they occur in the 366 + code (within limits imposed by the C standard), and it will not 367 + introduce extraneous accesses. 368 + 369 + This explains why the MP and SB examples above used READ_ONCE() and 370 + WRITE_ONCE() rather than ordinary memory accesses. Thanks to this 371 + usage, we can be certain that in the MP example, P0's write event to 372 + buf really is po-before its write event to flag, and similarly for the 373 + other shared memory accesses in the examples. 374 + 375 + Private variables are not subject to this restriction. Since they are 376 + not shared between CPUs, they can be accessed normally without 377 + READ_ONCE() or WRITE_ONCE(), and there will be no ill effects. In 378 + fact, they need not even be stored in normal memory at all -- in 379 + principle a private variable could be stored in a CPU register (hence 380 + the convention that these variables have names starting with the 381 + letter 'r'). 382 + 383 + 384 + A WARNING 385 + --------- 386 + 387 + The protections provided by READ_ONCE(), WRITE_ONCE(), and others are 388 + not perfect; and under some circumstances it is possible for the 389 + compiler to undermine the memory model. Here is an example. Suppose 390 + both branches of an "if" statement store the same value to the same 391 + location: 392 + 393 + r1 = READ_ONCE(x); 394 + if (r1) { 395 + WRITE_ONCE(y, 2); 396 + ... /* do something */ 397 + } else { 398 + WRITE_ONCE(y, 2); 399 + ... /* do something else */ 400 + } 401 + 402 + For this code, the LKMM predicts that the load from x will always be 403 + executed before either of the stores to y. However, a compiler could 404 + lift the stores out of the conditional, transforming the code into 405 + something resembling: 406 + 407 + r1 = READ_ONCE(x); 408 + WRITE_ONCE(y, 2); 409 + if (r1) { 410 + ... /* do something */ 411 + } else { 412 + ... /* do something else */ 413 + } 414 + 415 + Given this version of the code, the LKMM would predict that the load 416 + from x could be executed after the store to y. Thus, the memory 417 + model's original prediction could be invalidated by the compiler. 418 + 419 + Another issue arises from the fact that in C, arguments to many 420 + operators and function calls can be evaluated in any order. For 421 + example: 422 + 423 + r1 = f(5) + g(6); 424 + 425 + The object code might call f(5) either before or after g(6); the 426 + memory model cannot assume there is a fixed program order relation 427 + between them. (In fact, if the functions are inlined then the 428 + compiler might even interleave their object code.) 429 + 430 + 431 + DEPENDENCY RELATIONS: data, addr, and ctrl 432 + ------------------------------------------ 433 + 434 + We say that two events are linked by a dependency relation when the 435 + execution of the second event depends in some way on a value obtained 436 + from memory by the first. The first event must be a read, and the 437 + value it obtains must somehow affect what the second event does. 438 + There are three kinds of dependencies: data, address (addr), and 439 + control (ctrl). 440 + 441 + A read and a write event are linked by a data dependency if the value 442 + obtained by the read affects the value stored by the write. As a very 443 + simple example: 444 + 445 + int x, y; 446 + 447 + r1 = READ_ONCE(x); 448 + WRITE_ONCE(y, r1 + 5); 449 + 450 + The value stored by the WRITE_ONCE obviously depends on the value 451 + loaded by the READ_ONCE. Such dependencies can wind through 452 + arbitrarily complicated computations, and a write can depend on the 453 + values of multiple reads. 454 + 455 + A read event and another memory access event are linked by an address 456 + dependency if the value obtained by the read affects the location 457 + accessed by the other event. The second event can be either a read or 458 + a write. Here's another simple example: 459 + 460 + int a[20]; 461 + int i; 462 + 463 + r1 = READ_ONCE(i); 464 + r2 = READ_ONCE(a[r1]); 465 + 466 + Here the location accessed by the second READ_ONCE() depends on the 467 + index value loaded by the first. Pointer indirection also gives rise 468 + to address dependencies, since the address of a location accessed 469 + through a pointer will depend on the value read earlier from that 470 + pointer. 471 + 472 + Finally, a read event and another memory access event are linked by a 473 + control dependency if the value obtained by the read affects whether 474 + the second event is executed at all. Simple example: 475 + 476 + int x, y; 477 + 478 + r1 = READ_ONCE(x); 479 + if (r1) 480 + WRITE_ONCE(y, 1984); 481 + 482 + Execution of the WRITE_ONCE() is controlled by a conditional expression 483 + which depends on the value obtained by the READ_ONCE(); hence there is 484 + a control dependency from the load to the store. 485 + 486 + It should be pretty obvious that events can only depend on reads that 487 + come earlier in program order. Symbolically, if we have R ->data X, 488 + R ->addr X, or R ->ctrl X (where R is a read event), then we must also 489 + have R ->po X. It wouldn't make sense for a computation to depend 490 + somehow on a value that doesn't get loaded from shared memory until 491 + later in the code! 492 + 493 + 494 + THE READS-FROM RELATION: rf, rfi, and rfe 495 + ----------------------------------------- 496 + 497 + The reads-from relation (rf) links a write event to a read event when 498 + the value loaded by the read is the value that was stored by the 499 + write. In colloquial terms, the load "reads from" the store. We 500 + write W ->rf R to indicate that the load R reads from the store W. We 501 + further distinguish the cases where the load and the store occur on 502 + the same CPU (internal reads-from, or rfi) and where they occur on 503 + different CPUs (external reads-from, or rfe). 504 + 505 + For our purposes, a memory location's initial value is treated as 506 + though it had been written there by an imaginary initial store that 507 + executes on a separate CPU before the program runs. 508 + 509 + Usage of the rf relation implicitly assumes that loads will always 510 + read from a single store. It doesn't apply properly in the presence 511 + of load-tearing, where a load obtains some of its bits from one store 512 + and some of them from another store. Fortunately, use of READ_ONCE() 513 + and WRITE_ONCE() will prevent load-tearing; it's not possible to have: 514 + 515 + int x = 0; 516 + 517 + P0() 518 + { 519 + WRITE_ONCE(x, 0x1234); 520 + } 521 + 522 + P1() 523 + { 524 + int r1; 525 + 526 + r1 = READ_ONCE(x); 527 + } 528 + 529 + and end up with r1 = 0x1200 (partly from x's initial value and partly 530 + from the value stored by P0). 531 + 532 + On the other hand, load-tearing is unavoidable when mixed-size 533 + accesses are used. Consider this example: 534 + 535 + union { 536 + u32 w; 537 + u16 h[2]; 538 + } x; 539 + 540 + P0() 541 + { 542 + WRITE_ONCE(x.h[0], 0x1234); 543 + WRITE_ONCE(x.h[1], 0x5678); 544 + } 545 + 546 + P1() 547 + { 548 + int r1; 549 + 550 + r1 = READ_ONCE(x.w); 551 + } 552 + 553 + If r1 = 0x56781234 (little-endian!) at the end, then P1 must have read 554 + from both of P0's stores. It is possible to handle mixed-size and 555 + unaligned accesses in a memory model, but the LKMM currently does not 556 + attempt to do so. It requires all accesses to be properly aligned and 557 + of the location's actual size. 558 + 559 + 560 + CACHE COHERENCE AND THE COHERENCE ORDER RELATION: co, coi, and coe 561 + ------------------------------------------------------------------ 562 + 563 + Cache coherence is a general principle requiring that in a 564 + multi-processor system, the CPUs must share a consistent view of the 565 + memory contents. Specifically, it requires that for each location in 566 + shared memory, the stores to that location must form a single global 567 + ordering which all the CPUs agree on (the coherence order), and this 568 + ordering must be consistent with the program order for accesses to 569 + that location. 570 + 571 + To put it another way, for any variable x, the coherence order (co) of 572 + the stores to x is simply the order in which the stores overwrite one 573 + another. The imaginary store which establishes x's initial value 574 + comes first in the coherence order; the store which directly 575 + overwrites the initial value comes second; the store which overwrites 576 + that value comes third, and so on. 577 + 578 + You can think of the coherence order as being the order in which the 579 + stores reach x's location in memory (or if you prefer a more 580 + hardware-centric view, the order in which the stores get written to 581 + x's cache line). We write W ->co W' if W comes before W' in the 582 + coherence order, that is, if the value stored by W gets overwritten, 583 + directly or indirectly, by the value stored by W'. 584 + 585 + Coherence order is required to be consistent with program order. This 586 + requirement takes the form of four coherency rules: 587 + 588 + Write-write coherence: If W ->po-loc W' (i.e., W comes before 589 + W' in program order and they access the same location), where W 590 + and W' are two stores, then W ->co W'. 591 + 592 + Write-read coherence: If W ->po-loc R, where W is a store and R 593 + is a load, then R must read from W or from some other store 594 + which comes after W in the coherence order. 595 + 596 + Read-write coherence: If R ->po-loc W, where R is a load and W 597 + is a store, then the store which R reads from must come before 598 + W in the coherence order. 599 + 600 + Read-read coherence: If R ->po-loc R', where R and R' are two 601 + loads, then either they read from the same store or else the 602 + store read by R comes before the store read by R' in the 603 + coherence order. 604 + 605 + This is sometimes referred to as sequential consistency per variable, 606 + because it means that the accesses to any single memory location obey 607 + the rules of the Sequential Consistency memory model. (According to 608 + Wikipedia, sequential consistency per variable and cache coherence 609 + mean the same thing except that cache coherence includes an extra 610 + requirement that every store eventually becomes visible to every CPU.) 611 + 612 + Any reasonable memory model will include cache coherence. Indeed, our 613 + expectation of cache coherence is so deeply ingrained that violations 614 + of its requirements look more like hardware bugs than programming 615 + errors: 616 + 617 + int x; 618 + 619 + P0() 620 + { 621 + WRITE_ONCE(x, 17); 622 + WRITE_ONCE(x, 23); 623 + } 624 + 625 + If the final value stored in x after this code ran was 17, you would 626 + think your computer was broken. It would be a violation of the 627 + write-write coherence rule: Since the store of 23 comes later in 628 + program order, it must also come later in x's coherence order and 629 + thus must overwrite the store of 17. 630 + 631 + int x = 0; 632 + 633 + P0() 634 + { 635 + int r1; 636 + 637 + r1 = READ_ONCE(x); 638 + WRITE_ONCE(x, 666); 639 + } 640 + 641 + If r1 = 666 at the end, this would violate the read-write coherence 642 + rule: The READ_ONCE() load comes before the WRITE_ONCE() store in 643 + program order, so it must not read from that store but rather from one 644 + coming earlier in the coherence order (in this case, x's initial 645 + value). 646 + 647 + int x = 0; 648 + 649 + P0() 650 + { 651 + WRITE_ONCE(x, 5); 652 + } 653 + 654 + P1() 655 + { 656 + int r1, r2; 657 + 658 + r1 = READ_ONCE(x); 659 + r2 = READ_ONCE(x); 660 + } 661 + 662 + If r1 = 5 (reading from P0's store) and r2 = 0 (reading from the 663 + imaginary store which establishes x's initial value) at the end, this 664 + would violate the read-read coherence rule: The r1 load comes before 665 + the r2 load in program order, so it must not read from a store that 666 + comes later in the coherence order. 667 + 668 + (As a minor curiosity, if this code had used normal loads instead of 669 + READ_ONCE() in P1, on Itanium it sometimes could end up with r1 = 5 670 + and r2 = 0! This results from parallel execution of the operations 671 + encoded in Itanium's Very-Long-Instruction-Word format, and it is yet 672 + another motivation for using READ_ONCE() when accessing shared memory 673 + locations.) 674 + 675 + Just like the po relation, co is inherently an ordering -- it is not 676 + possible for a store to directly or indirectly overwrite itself! And 677 + just like with the rf relation, we distinguish between stores that 678 + occur on the same CPU (internal coherence order, or coi) and stores 679 + that occur on different CPUs (external coherence order, or coe). 680 + 681 + On the other hand, stores to different memory locations are never 682 + related by co, just as instructions on different CPUs are never 683 + related by po. Coherence order is strictly per-location, or if you 684 + prefer, each location has its own independent coherence order. 685 + 686 + 687 + THE FROM-READS RELATION: fr, fri, and fre 688 + ----------------------------------------- 689 + 690 + The from-reads relation (fr) can be a little difficult for people to 691 + grok. It describes the situation where a load reads a value that gets 692 + overwritten by a store. In other words, we have R ->fr W when the 693 + value that R reads is overwritten (directly or indirectly) by W, or 694 + equivalently, when R reads from a store which comes earlier than W in 695 + the coherence order. 696 + 697 + For example: 698 + 699 + int x = 0; 700 + 701 + P0() 702 + { 703 + int r1; 704 + 705 + r1 = READ_ONCE(x); 706 + WRITE_ONCE(x, 2); 707 + } 708 + 709 + The value loaded from x will be 0 (assuming cache coherence!), and it 710 + gets overwritten by the value 2. Thus there is an fr link from the 711 + READ_ONCE() to the WRITE_ONCE(). If the code contained any later 712 + stores to x, there would also be fr links from the READ_ONCE() to 713 + them. 714 + 715 + As with rf, rfi, and rfe, we subdivide the fr relation into fri (when 716 + the load and the store are on the same CPU) and fre (when they are on 717 + different CPUs). 718 + 719 + Note that the fr relation is determined entirely by the rf and co 720 + relations; it is not independent. Given a read event R and a write 721 + event W for the same location, we will have R ->fr W if and only if 722 + the write which R reads from is co-before W. In symbols, 723 + 724 + (R ->fr W) := (there exists W' with W' ->rf R and W' ->co W). 725 + 726 + 727 + AN OPERATIONAL MODEL 728 + -------------------- 729 + 730 + The LKMM is based on various operational memory models, meaning that 731 + the models arise from an abstract view of how a computer system 732 + operates. Here are the main ideas, as incorporated into the LKMM. 733 + 734 + The system as a whole is divided into the CPUs and a memory subsystem. 735 + The CPUs are responsible for executing instructions (not necessarily 736 + in program order), and they communicate with the memory subsystem. 737 + For the most part, executing an instruction requires a CPU to perform 738 + only internal operations. However, loads, stores, and fences involve 739 + more. 740 + 741 + When CPU C executes a store instruction, it tells the memory subsystem 742 + to store a certain value at a certain location. The memory subsystem 743 + propagates the store to all the other CPUs as well as to RAM. (As a 744 + special case, we say that the store propagates to its own CPU at the 745 + time it is executed.) The memory subsystem also determines where the 746 + store falls in the location's coherence order. In particular, it must 747 + arrange for the store to be co-later than (i.e., to overwrite) any 748 + other store to the same location which has already propagated to CPU C. 749 + 750 + When a CPU executes a load instruction R, it first checks to see 751 + whether there are any as-yet unexecuted store instructions, for the 752 + same location, that come before R in program order. If there are, it 753 + uses the value of the po-latest such store as the value obtained by R, 754 + and we say that the store's value is forwarded to R. Otherwise, the 755 + CPU asks the memory subsystem for the value to load and we say that R 756 + is satisfied from memory. The memory subsystem hands back the value 757 + of the co-latest store to the location in question which has already 758 + propagated to that CPU. 759 + 760 + (In fact, the picture needs to be a little more complicated than this. 761 + CPUs have local caches, and propagating a store to a CPU really means 762 + propagating it to the CPU's local cache. A local cache can take some 763 + time to process the stores that it receives, and a store can't be used 764 + to satisfy one of the CPU's loads until it has been processed. On 765 + most architectures, the local caches process stores in 766 + First-In-First-Out order, and consequently the processing delay 767 + doesn't matter for the memory model. But on Alpha, the local caches 768 + have a partitioned design that results in non-FIFO behavior. We will 769 + discuss this in more detail later.) 770 + 771 + Note that load instructions may be executed speculatively and may be 772 + restarted under certain circumstances. The memory model ignores these 773 + premature executions; we simply say that the load executes at the 774 + final time it is forwarded or satisfied. 775 + 776 + Executing a fence (or memory barrier) instruction doesn't require a 777 + CPU to do anything special other than informing the memory subsystem 778 + about the fence. However, fences do constrain the way CPUs and the 779 + memory subsystem handle other instructions, in two respects. 780 + 781 + First, a fence forces the CPU to execute various instructions in 782 + program order. Exactly which instructions are ordered depends on the 783 + type of fence: 784 + 785 + Strong fences, including smp_mb() and synchronize_rcu(), force 786 + the CPU to execute all po-earlier instructions before any 787 + po-later instructions; 788 + 789 + smp_rmb() forces the CPU to execute all po-earlier loads 790 + before any po-later loads; 791 + 792 + smp_wmb() forces the CPU to execute all po-earlier stores 793 + before any po-later stores; 794 + 795 + Acquire fences, such as smp_load_acquire(), force the CPU to 796 + execute the load associated with the fence (e.g., the load 797 + part of an smp_load_acquire()) before any po-later 798 + instructions; 799 + 800 + Release fences, such as smp_store_release(), force the CPU to 801 + execute all po-earlier instructions before the store 802 + associated with the fence (e.g., the store part of an 803 + smp_store_release()). 804 + 805 + Second, some types of fence affect the way the memory subsystem 806 + propagates stores. When a fence instruction is executed on CPU C: 807 + 808 + For each other CPU C', smb_wmb() forces all po-earlier stores 809 + on C to propagate to C' before any po-later stores do. 810 + 811 + For each other CPU C', any store which propagates to C before 812 + a release fence is executed (including all po-earlier 813 + stores executed on C) is forced to propagate to C' before the 814 + store associated with the release fence does. 815 + 816 + Any store which propagates to C before a strong fence is 817 + executed (including all po-earlier stores on C) is forced to 818 + propagate to all other CPUs before any instructions po-after 819 + the strong fence are executed on C. 820 + 821 + The propagation ordering enforced by release fences and strong fences 822 + affects stores from other CPUs that propagate to CPU C before the 823 + fence is executed, as well as stores that are executed on C before the 824 + fence. We describe this property by saying that release fences and 825 + strong fences are A-cumulative. By contrast, smp_wmb() fences are not 826 + A-cumulative; they only affect the propagation of stores that are 827 + executed on C before the fence (i.e., those which precede the fence in 828 + program order). 829 + 830 + smp_read_barrier_depends(), rcu_read_lock(), rcu_read_unlock(), and 831 + synchronize_rcu() fences have other properties which we discuss later. 832 + 833 + 834 + PROPAGATION ORDER RELATION: cumul-fence 835 + --------------------------------------- 836 + 837 + The fences which affect propagation order (i.e., strong, release, and 838 + smp_wmb() fences) are collectively referred to as cumul-fences, even 839 + though smp_wmb() isn't A-cumulative. The cumul-fence relation is 840 + defined to link memory access events E and F whenever: 841 + 842 + E and F are both stores on the same CPU and an smp_wmb() fence 843 + event occurs between them in program order; or 844 + 845 + F is a release fence and some X comes before F in program order, 846 + where either X = E or else E ->rf X; or 847 + 848 + A strong fence event occurs between some X and F in program 849 + order, where either X = E or else E ->rf X. 850 + 851 + The operational model requires that whenever W and W' are both stores 852 + and W ->cumul-fence W', then W must propagate to any given CPU 853 + before W' does. However, for different CPUs C and C', it does not 854 + require W to propagate to C before W' propagates to C'. 855 + 856 + 857 + DERIVATION OF THE LKMM FROM THE OPERATIONAL MODEL 858 + ------------------------------------------------- 859 + 860 + The LKMM is derived from the restrictions imposed by the design 861 + outlined above. These restrictions involve the necessity of 862 + maintaining cache coherence and the fact that a CPU can't operate on a 863 + value before it knows what that value is, among other things. 864 + 865 + The formal version of the LKMM is defined by five requirements, or 866 + axioms: 867 + 868 + Sequential consistency per variable: This requires that the 869 + system obey the four coherency rules. 870 + 871 + Atomicity: This requires that atomic read-modify-write 872 + operations really are atomic, that is, no other stores can 873 + sneak into the middle of such an update. 874 + 875 + Happens-before: This requires that certain instructions are 876 + executed in a specific order. 877 + 878 + Propagation: This requires that certain stores propagate to 879 + CPUs and to RAM in a specific order. 880 + 881 + Rcu: This requires that RCU read-side critical sections and 882 + grace periods obey the rules of RCU, in particular, the 883 + Grace-Period Guarantee. 884 + 885 + The first and second are quite common; they can be found in many 886 + memory models (such as those for C11/C++11). The "happens-before" and 887 + "propagation" axioms have analogs in other memory models as well. The 888 + "rcu" axiom is specific to the LKMM. 889 + 890 + Each of these axioms is discussed below. 891 + 892 + 893 + SEQUENTIAL CONSISTENCY PER VARIABLE 894 + ----------------------------------- 895 + 896 + According to the principle of cache coherence, the stores to any fixed 897 + shared location in memory form a global ordering. We can imagine 898 + inserting the loads from that location into this ordering, by placing 899 + each load between the store that it reads from and the following 900 + store. This leaves the relative positions of loads that read from the 901 + same store unspecified; let's say they are inserted in program order, 902 + first for CPU 0, then CPU 1, etc. 903 + 904 + You can check that the four coherency rules imply that the rf, co, fr, 905 + and po-loc relations agree with this global ordering; in other words, 906 + whenever we have X ->rf Y or X ->co Y or X ->fr Y or X ->po-loc Y, the 907 + X event comes before the Y event in the global ordering. The LKMM's 908 + "coherence" axiom expresses this by requiring the union of these 909 + relations not to have any cycles. This means it must not be possible 910 + to find events 911 + 912 + X0 -> X1 -> X2 -> ... -> Xn -> X0, 913 + 914 + where each of the links is either rf, co, fr, or po-loc. This has to 915 + hold if the accesses to the fixed memory location can be ordered as 916 + cache coherence demands. 917 + 918 + Although it is not obvious, it can be shown that the converse is also 919 + true: This LKMM axiom implies that the four coherency rules are 920 + obeyed. 921 + 922 + 923 + ATOMIC UPDATES: rmw 924 + ------------------- 925 + 926 + What does it mean to say that a read-modify-write (rmw) update, such 927 + as atomic_inc(&x), is atomic? It means that the memory location (x in 928 + this case) does not get altered between the read and the write events 929 + making up the atomic operation. In particular, if two CPUs perform 930 + atomic_inc(&x) concurrently, it must be guaranteed that the final 931 + value of x will be the initial value plus two. We should never have 932 + the following sequence of events: 933 + 934 + CPU 0 loads x obtaining 13; 935 + CPU 1 loads x obtaining 13; 936 + CPU 0 stores 14 to x; 937 + CPU 1 stores 14 to x; 938 + 939 + where the final value of x is wrong (14 rather than 15). 940 + 941 + In this example, CPU 0's increment effectively gets lost because it 942 + occurs in between CPU 1's load and store. To put it another way, the 943 + problem is that the position of CPU 0's store in x's coherence order 944 + is between the store that CPU 1 reads from and the store that CPU 1 945 + performs. 946 + 947 + The same analysis applies to all atomic update operations. Therefore, 948 + to enforce atomicity the LKMM requires that atomic updates follow this 949 + rule: Whenever R and W are the read and write events composing an 950 + atomic read-modify-write and W' is the write event which R reads from, 951 + there must not be any stores coming between W' and W in the coherence 952 + order. Equivalently, 953 + 954 + (R ->rmw W) implies (there is no X with R ->fr X and X ->co W), 955 + 956 + where the rmw relation links the read and write events making up each 957 + atomic update. This is what the LKMM's "atomic" axiom says. 958 + 959 + 960 + THE PRESERVED PROGRAM ORDER RELATION: ppo 961 + ----------------------------------------- 962 + 963 + There are many situations where a CPU is obligated to execute two 964 + instructions in program order. We amalgamate them into the ppo (for 965 + "preserved program order") relation, which links the po-earlier 966 + instruction to the po-later instruction and is thus a sub-relation of 967 + po. 968 + 969 + The operational model already includes a description of one such 970 + situation: Fences are a source of ppo links. Suppose X and Y are 971 + memory accesses with X ->po Y; then the CPU must execute X before Y if 972 + any of the following hold: 973 + 974 + A strong (smp_mb() or synchronize_rcu()) fence occurs between 975 + X and Y; 976 + 977 + X and Y are both stores and an smp_wmb() fence occurs between 978 + them; 979 + 980 + X and Y are both loads and an smp_rmb() fence occurs between 981 + them; 982 + 983 + X is also an acquire fence, such as smp_load_acquire(); 984 + 985 + Y is also a release fence, such as smp_store_release(). 986 + 987 + Another possibility, not mentioned earlier but discussed in the next 988 + section, is: 989 + 990 + X and Y are both loads, X ->addr Y (i.e., there is an address 991 + dependency from X to Y), and an smp_read_barrier_depends() 992 + fence occurs between them. 993 + 994 + Dependencies can also cause instructions to be executed in program 995 + order. This is uncontroversial when the second instruction is a 996 + store; either a data, address, or control dependency from a load R to 997 + a store W will force the CPU to execute R before W. This is very 998 + simply because the CPU cannot tell the memory subsystem about W's 999 + store before it knows what value should be stored (in the case of a 1000 + data dependency), what location it should be stored into (in the case 1001 + of an address dependency), or whether the store should actually take 1002 + place (in the case of a control dependency). 1003 + 1004 + Dependencies to load instructions are more problematic. To begin with, 1005 + there is no such thing as a data dependency to a load. Next, a CPU 1006 + has no reason to respect a control dependency to a load, because it 1007 + can always satisfy the second load speculatively before the first, and 1008 + then ignore the result if it turns out that the second load shouldn't 1009 + be executed after all. And lastly, the real difficulties begin when 1010 + we consider address dependencies to loads. 1011 + 1012 + To be fair about it, all Linux-supported architectures do execute 1013 + loads in program order if there is an address dependency between them. 1014 + After all, a CPU cannot ask the memory subsystem to load a value from 1015 + a particular location before it knows what that location is. However, 1016 + the split-cache design used by Alpha can cause it to behave in a way 1017 + that looks as if the loads were executed out of order (see the next 1018 + section for more details). For this reason, the LKMM does not include 1019 + address dependencies between read events in the ppo relation unless an 1020 + smp_read_barrier_depends() fence is present. 1021 + 1022 + On the other hand, dependencies can indirectly affect the ordering of 1023 + two loads. This happens when there is a dependency from a load to a 1024 + store and a second, po-later load reads from that store: 1025 + 1026 + R ->dep W ->rfi R', 1027 + 1028 + where the dep link can be either an address or a data dependency. In 1029 + this situation we know it is possible for the CPU to execute R' before 1030 + W, because it can forward the value that W will store to R'. But it 1031 + cannot execute R' before R, because it cannot forward the value before 1032 + it knows what that value is, or that W and R' do access the same 1033 + location. However, if there is merely a control dependency between R 1034 + and W then the CPU can speculatively forward W to R' before executing 1035 + R; if the speculation turns out to be wrong then the CPU merely has to 1036 + restart or abandon R'. 1037 + 1038 + (In theory, a CPU might forward a store to a load when it runs across 1039 + an address dependency like this: 1040 + 1041 + r1 = READ_ONCE(ptr); 1042 + WRITE_ONCE(*r1, 17); 1043 + r2 = READ_ONCE(*r1); 1044 + 1045 + because it could tell that the store and the second load access the 1046 + same location even before it knows what the location's address is. 1047 + However, none of the architectures supported by the Linux kernel do 1048 + this.) 1049 + 1050 + Two memory accesses of the same location must always be executed in 1051 + program order if the second access is a store. Thus, if we have 1052 + 1053 + R ->po-loc W 1054 + 1055 + (the po-loc link says that R comes before W in program order and they 1056 + access the same location), the CPU is obliged to execute W after R. 1057 + If it executed W first then the memory subsystem would respond to R's 1058 + read request with the value stored by W (or an even later store), in 1059 + violation of the read-write coherence rule. Similarly, if we had 1060 + 1061 + W ->po-loc W' 1062 + 1063 + and the CPU executed W' before W, then the memory subsystem would put 1064 + W' before W in the coherence order. It would effectively cause W to 1065 + overwrite W', in violation of the write-write coherence rule. 1066 + (Interestingly, an early ARMv8 memory model, now obsolete, proposed 1067 + allowing out-of-order writes like this to occur. The model avoided 1068 + violating the write-write coherence rule by requiring the CPU not to 1069 + send the W write to the memory subsystem at all!) 1070 + 1071 + There is one last example of preserved program order in the LKMM: when 1072 + a load-acquire reads from an earlier store-release. For example: 1073 + 1074 + smp_store_release(&x, 123); 1075 + r1 = smp_load_acquire(&x); 1076 + 1077 + If the smp_load_acquire() ends up obtaining the 123 value that was 1078 + stored by the smp_store_release(), the LKMM says that the load must be 1079 + executed after the store; the store cannot be forwarded to the load. 1080 + This requirement does not arise from the operational model, but it 1081 + yields correct predictions on all architectures supported by the Linux 1082 + kernel, although for differing reasons. 1083 + 1084 + On some architectures, including x86 and ARMv8, it is true that the 1085 + store cannot be forwarded to the load. On others, including PowerPC 1086 + and ARMv7, smp_store_release() generates object code that starts with 1087 + a fence and smp_load_acquire() generates object code that ends with a 1088 + fence. The upshot is that even though the store may be forwarded to 1089 + the load, it is still true that any instruction preceding the store 1090 + will be executed before the load or any following instructions, and 1091 + the store will be executed before any instruction following the load. 1092 + 1093 + 1094 + AND THEN THERE WAS ALPHA 1095 + ------------------------ 1096 + 1097 + As mentioned above, the Alpha architecture is unique in that it does 1098 + not appear to respect address dependencies to loads. This means that 1099 + code such as the following: 1100 + 1101 + int x = 0; 1102 + int y = -1; 1103 + int *ptr = &y; 1104 + 1105 + P0() 1106 + { 1107 + WRITE_ONCE(x, 1); 1108 + smp_wmb(); 1109 + WRITE_ONCE(ptr, &x); 1110 + } 1111 + 1112 + P1() 1113 + { 1114 + int *r1; 1115 + int r2; 1116 + 1117 + r1 = READ_ONCE(ptr); 1118 + r2 = READ_ONCE(*r1); 1119 + } 1120 + 1121 + can malfunction on Alpha systems. 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. In constrast, other architectures 1142 + maintain at least the appearance of FIFO order. 1143 + 1144 + In practice, this difficulty is solved by inserting an 1145 + smp_read_barrier_depends() fence between P1's two loads. The effect 1146 + of this fence is to cause the CPU not to execute any po-later 1147 + instructions until after the local cache has finished processing all 1148 + the stores it has already received. Thus, if the code was changed to: 1149 + 1150 + P1() 1151 + { 1152 + int *r1; 1153 + int r2; 1154 + 1155 + r1 = READ_ONCE(ptr); 1156 + smp_read_barrier_depends(); 1157 + r2 = READ_ONCE(*r1); 1158 + } 1159 + 1160 + then we would never get r1 = &x and r2 = 0. By the time P1 executed 1161 + its second load, the x = 1 store would already be fully processed by 1162 + the local cache and available for satisfying the read request. 1163 + 1164 + The LKMM requires that smp_rmb(), acquire fences, and strong fences 1165 + share this property with smp_read_barrier_depends(): They do not allow 1166 + the CPU to execute any po-later instructions (or po-later loads in the 1167 + case of smp_rmb()) until all outstanding stores have been processed by 1168 + the local cache. In the case of a strong fence, the CPU first has to 1169 + wait for all of its po-earlier stores to propagate to every other CPU 1170 + in the system; then it has to wait for the local cache to process all 1171 + the stores received as of that time -- not just the stores received 1172 + when the strong fence began. 1173 + 1174 + And of course, none of this matters for any architecture other than 1175 + Alpha. 1176 + 1177 + 1178 + THE HAPPENS-BEFORE RELATION: hb 1179 + ------------------------------- 1180 + 1181 + The happens-before relation (hb) links memory accesses that have to 1182 + execute in a certain order. hb includes the ppo relation and two 1183 + others, one of which is rfe. 1184 + 1185 + W ->rfe R implies that W and R are on different CPUs. It also means 1186 + that W's store must have propagated to R's CPU before R executed; 1187 + otherwise R could not have read the value stored by W. Therefore W 1188 + must have executed before R, and so we have W ->hb R. 1189 + 1190 + The equivalent fact need not hold if W ->rfi R (i.e., W and R are on 1191 + the same CPU). As we have already seen, the operational model allows 1192 + W's value to be forwarded to R in such cases, meaning that R may well 1193 + execute before W does. 1194 + 1195 + It's important to understand that neither coe nor fre is included in 1196 + hb, despite their similarities to rfe. For example, suppose we have 1197 + W ->coe W'. This means that W and W' are stores to the same location, 1198 + they execute on different CPUs, and W comes before W' in the coherence 1199 + order (i.e., W' overwrites W). Nevertheless, it is possible for W' to 1200 + execute before W, because the decision as to which store overwrites 1201 + the other is made later by the memory subsystem. When the stores are 1202 + nearly simultaneous, either one can come out on top. Similarly, 1203 + R ->fre W means that W overwrites the value which R reads, but it 1204 + doesn't mean that W has to execute after R. All that's necessary is 1205 + for the memory subsystem not to propagate W to R's CPU until after R 1206 + has executed, which is possible if W executes shortly before R. 1207 + 1208 + The third relation included in hb is like ppo, in that it only links 1209 + events that are on the same CPU. However it is more difficult to 1210 + explain, because it arises only indirectly from the requirement of 1211 + cache coherence. The relation is called prop, and it links two events 1212 + on CPU C in situations where a store from some other CPU comes after 1213 + the first event in the coherence order and propagates to C before the 1214 + second event executes. 1215 + 1216 + This is best explained with some examples. The simplest case looks 1217 + like this: 1218 + 1219 + int x; 1220 + 1221 + P0() 1222 + { 1223 + int r1; 1224 + 1225 + WRITE_ONCE(x, 1); 1226 + r1 = READ_ONCE(x); 1227 + } 1228 + 1229 + P1() 1230 + { 1231 + WRITE_ONCE(x, 8); 1232 + } 1233 + 1234 + If r1 = 8 at the end then P0's accesses must have executed in program 1235 + order. We can deduce this from the operational model; if P0's load 1236 + had executed before its store then the value of the store would have 1237 + been forwarded to the load, so r1 would have ended up equal to 1, not 1238 + 8. In this case there is a prop link from P0's write event to its read 1239 + event, because P1's store came after P0's store in x's coherence 1240 + order, and P1's store propagated to P0 before P0's load executed. 1241 + 1242 + An equally simple case involves two loads of the same location that 1243 + read from different stores: 1244 + 1245 + int x = 0; 1246 + 1247 + P0() 1248 + { 1249 + int r1, r2; 1250 + 1251 + r1 = READ_ONCE(x); 1252 + r2 = READ_ONCE(x); 1253 + } 1254 + 1255 + P1() 1256 + { 1257 + WRITE_ONCE(x, 9); 1258 + } 1259 + 1260 + If r1 = 0 and r2 = 9 at the end then P0's accesses must have executed 1261 + in program order. If the second load had executed before the first 1262 + then the x = 9 store must have been propagated to P0 before the first 1263 + load executed, and so r1 would have been 9 rather than 0. In this 1264 + case there is a prop link from P0's first read event to its second, 1265 + because P1's store overwrote the value read by P0's first load, and 1266 + P1's store propagated to P0 before P0's second load executed. 1267 + 1268 + Less trivial examples of prop all involve fences. Unlike the simple 1269 + examples above, they can require that some instructions are executed 1270 + out of program order. This next one should look familiar: 1271 + 1272 + int buf = 0, flag = 0; 1273 + 1274 + P0() 1275 + { 1276 + WRITE_ONCE(buf, 1); 1277 + smp_wmb(); 1278 + WRITE_ONCE(flag, 1); 1279 + } 1280 + 1281 + P1() 1282 + { 1283 + int r1; 1284 + int r2; 1285 + 1286 + r1 = READ_ONCE(flag); 1287 + r2 = READ_ONCE(buf); 1288 + } 1289 + 1290 + This is the MP pattern again, with an smp_wmb() fence between the two 1291 + stores. If r1 = 1 and r2 = 0 at the end then there is a prop link 1292 + from P1's second load to its first (backwards!). The reason is 1293 + similar to the previous examples: The value P1 loads from buf gets 1294 + overwritten by P0's store to buf, the fence guarantees that the store 1295 + to buf will propagate to P1 before the store to flag does, and the 1296 + store to flag propagates to P1 before P1 reads flag. 1297 + 1298 + The prop link says that in order to obtain the r1 = 1, r2 = 0 result, 1299 + P1 must execute its second load before the first. Indeed, if the load 1300 + from flag were executed first, then the buf = 1 store would already 1301 + have propagated to P1 by the time P1's load from buf executed, so r2 1302 + would have been 1 at the end, not 0. (The reasoning holds even for 1303 + Alpha, although the details are more complicated and we will not go 1304 + into them.) 1305 + 1306 + But what if we put an smp_rmb() fence between P1's loads? The fence 1307 + would force the two loads to be executed in program order, and it 1308 + would generate a cycle in the hb relation: The fence would create a ppo 1309 + link (hence an hb link) from the first load to the second, and the 1310 + prop relation would give an hb link from the second load to the first. 1311 + Since an instruction can't execute before itself, we are forced to 1312 + conclude that if an smp_rmb() fence is added, the r1 = 1, r2 = 0 1313 + outcome is impossible -- as it should be. 1314 + 1315 + The formal definition of the prop relation involves a coe or fre link, 1316 + followed by an arbitrary number of cumul-fence links, ending with an 1317 + rfe link. You can concoct more exotic examples, containing more than 1318 + one fence, although this quickly leads to diminishing returns in terms 1319 + of complexity. For instance, here's an example containing a coe link 1320 + followed by two fences and an rfe link, utilizing the fact that 1321 + release fences are A-cumulative: 1322 + 1323 + int x, y, z; 1324 + 1325 + P0() 1326 + { 1327 + int r0; 1328 + 1329 + WRITE_ONCE(x, 1); 1330 + r0 = READ_ONCE(z); 1331 + } 1332 + 1333 + P1() 1334 + { 1335 + WRITE_ONCE(x, 2); 1336 + smp_wmb(); 1337 + WRITE_ONCE(y, 1); 1338 + } 1339 + 1340 + P2() 1341 + { 1342 + int r2; 1343 + 1344 + r2 = READ_ONCE(y); 1345 + smp_store_release(&z, 1); 1346 + } 1347 + 1348 + If x = 2, r0 = 1, and r2 = 1 after this code runs then there is a prop 1349 + link from P0's store to its load. This is because P0's store gets 1350 + overwritten by P1's store since x = 2 at the end (a coe link), the 1351 + smp_wmb() ensures that P1's store to x propagates to P2 before the 1352 + store to y does (the first fence), the store to y propagates to P2 1353 + before P2's load and store execute, P2's smp_store_release() 1354 + guarantees that the stores to x and y both propagate to P0 before the 1355 + store to z does (the second fence), and P0's load executes after the 1356 + store to z has propagated to P0 (an rfe link). 1357 + 1358 + In summary, the fact that the hb relation links memory access events 1359 + in the order they execute means that it must not have cycles. This 1360 + requirement is the content of the LKMM's "happens-before" axiom. 1361 + 1362 + The LKMM defines yet another relation connected to times of 1363 + instruction execution, but it is not included in hb. It relies on the 1364 + particular properties of strong fences, which we cover in the next 1365 + section. 1366 + 1367 + 1368 + THE PROPAGATES-BEFORE RELATION: pb 1369 + ---------------------------------- 1370 + 1371 + The propagates-before (pb) relation capitalizes on the special 1372 + features of strong fences. It links two events E and F whenever some 1373 + store is coherence-later than E and propagates to every CPU and to RAM 1374 + before F executes. The formal definition requires that E be linked to 1375 + F via a coe or fre link, an arbitrary number of cumul-fences, an 1376 + optional rfe link, a strong fence, and an arbitrary number of hb 1377 + links. Let's see how this definition works out. 1378 + 1379 + Consider first the case where E is a store (implying that the sequence 1380 + of links begins with coe). Then there are events W, X, Y, and Z such 1381 + that: 1382 + 1383 + E ->coe W ->cumul-fence* X ->rfe? Y ->strong-fence Z ->hb* F, 1384 + 1385 + where the * suffix indicates an arbitrary number of links of the 1386 + specified type, and the ? suffix indicates the link is optional (Y may 1387 + be equal to X). Because of the cumul-fence links, we know that W will 1388 + propagate to Y's CPU before X does, hence before Y executes and hence 1389 + before the strong fence executes. Because this fence is strong, we 1390 + know that W will propagate to every CPU and to RAM before Z executes. 1391 + And because of the hb links, we know that Z will execute before F. 1392 + Thus W, which comes later than E in the coherence order, will 1393 + propagate to every CPU and to RAM before F executes. 1394 + 1395 + The case where E is a load is exactly the same, except that the first 1396 + link in the sequence is fre instead of coe. 1397 + 1398 + The existence of a pb link from E to F implies that E must execute 1399 + before F. To see why, suppose that F executed first. Then W would 1400 + have propagated to E's CPU before E executed. If E was a store, the 1401 + memory subsystem would then be forced to make E come after W in the 1402 + coherence order, contradicting the fact that E ->coe W. If E was a 1403 + load, the memory subsystem would then be forced to satisfy E's read 1404 + request with the value stored by W or an even later store, 1405 + contradicting the fact that E ->fre W. 1406 + 1407 + A good example illustrating how pb works is the SB pattern with strong 1408 + fences: 1409 + 1410 + int x = 0, y = 0; 1411 + 1412 + P0() 1413 + { 1414 + int r0; 1415 + 1416 + WRITE_ONCE(x, 1); 1417 + smp_mb(); 1418 + r0 = READ_ONCE(y); 1419 + } 1420 + 1421 + P1() 1422 + { 1423 + int r1; 1424 + 1425 + WRITE_ONCE(y, 1); 1426 + smp_mb(); 1427 + r1 = READ_ONCE(x); 1428 + } 1429 + 1430 + If r0 = 0 at the end then there is a pb link from P0's load to P1's 1431 + load: an fre link from P0's load to P1's store (which overwrites the 1432 + value read by P0), and a strong fence between P1's store and its load. 1433 + In this example, the sequences of cumul-fence and hb links are empty. 1434 + Note that this pb link is not included in hb as an instance of prop, 1435 + because it does not start and end on the same CPU. 1436 + 1437 + Similarly, if r1 = 0 at the end then there is a pb link from P1's load 1438 + to P0's. This means that if both r1 and r2 were 0 there would be a 1439 + cycle in pb, which is not possible since an instruction cannot execute 1440 + before itself. Thus, adding smp_mb() fences to the SB pattern 1441 + prevents the r0 = 0, r1 = 0 outcome. 1442 + 1443 + In summary, the fact that the pb relation links events in the order 1444 + they execute means that it cannot have cycles. This requirement is 1445 + the content of the LKMM's "propagation" axiom. 1446 + 1447 + 1448 + RCU RELATIONS: link, gp-link, rscs-link, and rcu-path 1449 + ----------------------------------------------------- 1450 + 1451 + RCU (Read-Copy-Update) is a powerful synchronization mechanism. It 1452 + rests on two concepts: grace periods and read-side critical sections. 1453 + 1454 + A grace period is the span of time occupied by a call to 1455 + synchronize_rcu(). A read-side critical section (or just critical 1456 + section, for short) is a region of code delimited by rcu_read_lock() 1457 + at the start and rcu_read_unlock() at the end. Critical sections can 1458 + be nested, although we won't make use of this fact. 1459 + 1460 + As far as memory models are concerned, RCU's main feature is its 1461 + Grace-Period Guarantee, which states that a critical section can never 1462 + span a full grace period. In more detail, the Guarantee says: 1463 + 1464 + If a critical section starts before a grace period then it 1465 + must end before the grace period does. In addition, every 1466 + store that propagates to the critical section's CPU before the 1467 + end of the critical section must propagate to every CPU before 1468 + the end of the grace period. 1469 + 1470 + If a critical section ends after a grace period ends then it 1471 + must start after the grace period does. In addition, every 1472 + store that propagates to the grace period's CPU before the 1473 + start of the grace period must propagate to every CPU before 1474 + the start of the critical section. 1475 + 1476 + Here is a simple example of RCU in action: 1477 + 1478 + int x, y; 1479 + 1480 + P0() 1481 + { 1482 + rcu_read_lock(); 1483 + WRITE_ONCE(x, 1); 1484 + WRITE_ONCE(y, 1); 1485 + rcu_read_unlock(); 1486 + } 1487 + 1488 + P1() 1489 + { 1490 + int r1, r2; 1491 + 1492 + r1 = READ_ONCE(x); 1493 + synchronize_rcu(); 1494 + r2 = READ_ONCE(y); 1495 + } 1496 + 1497 + The Grace Period Guarantee tells us that when this code runs, it will 1498 + never end with r1 = 1 and r2 = 0. The reasoning is as follows. r1 = 1 1499 + means that P0's store to x propagated to P1 before P1 called 1500 + synchronize_rcu(), so P0's critical section must have started before 1501 + P1's grace period. On the other hand, r2 = 0 means that P0's store to 1502 + y, which occurs before the end of the critical section, did not 1503 + propagate to P1 before the end of the grace period, violating the 1504 + Guarantee. 1505 + 1506 + In the kernel's implementations of RCU, the business about stores 1507 + propagating to every CPU is realized by placing strong fences at 1508 + suitable places in the RCU-related code. Thus, if a critical section 1509 + starts before a grace period does then the critical section's CPU will 1510 + execute an smp_mb() fence after the end of the critical section and 1511 + some time before the grace period's synchronize_rcu() call returns. 1512 + And if a critical section ends after a grace period does then the 1513 + synchronize_rcu() routine will execute an smp_mb() fence at its start 1514 + and some time before the critical section's opening rcu_read_lock() 1515 + executes. 1516 + 1517 + What exactly do we mean by saying that a critical section "starts 1518 + before" or "ends after" a grace period? Some aspects of the meaning 1519 + are pretty obvious, as in the example above, but the details aren't 1520 + entirely clear. The LKMM formalizes this notion by means of a 1521 + relation with the unfortunately generic name "link". It is a very 1522 + general relation; among other things, X ->link Z includes cases where 1523 + X happens-before or is equal to some event Y which is equal to or 1524 + comes before Z in the coherence order. Taking Y = Z, this says that 1525 + X ->rfe Z implies X ->link Z, and taking Y = X, it says that X ->fr Z 1526 + and X ->co Z each imply X ->link Z. 1527 + 1528 + The formal definition of the link relation is more than a little 1529 + obscure, and we won't give it here. It is closely related to the pb 1530 + relation, and the details don't matter unless you want to comb through 1531 + a somewhat lengthy formal proof. Pretty much all you need to know 1532 + about link is the information in the preceding paragraph. 1533 + 1534 + The LKMM goes on to define the gp-link and rscs-link relations. They 1535 + bring grace periods and read-side critical sections into the picture, 1536 + in the following way: 1537 + 1538 + E ->gp-link F means there is a synchronize_rcu() fence event S 1539 + and an event X such that E ->po S, either S ->po X or S = X, 1540 + and X ->link F. In other words, E and F are connected by a 1541 + grace period followed by an instance of link. 1542 + 1543 + E ->rscs-link F means there is a critical section delimited by 1544 + an rcu_read_lock() fence L and an rcu_read_unlock() fence U, 1545 + and an event X such that E ->po U, either L ->po X or L = X, 1546 + and X ->link F. Roughly speaking, this says that some event 1547 + in the same critical section as E is connected by link to F. 1548 + 1549 + If we think of the link relation as standing for an extended "before", 1550 + then E ->gp-link F says that E executes before a grace period which 1551 + ends before F executes. (In fact it says more than this, because it 1552 + includes cases where E executes before a grace period and some store 1553 + propagates to F's CPU before F executes and doesn't propagate to some 1554 + other CPU until after the grace period ends.) Similarly, 1555 + E ->rscs-link F says that E is part of (or before the start of) a 1556 + critical section which starts before F executes. 1557 + 1558 + Putting this all together, the LKMM expresses the Grace Period 1559 + Guarantee by requiring that there are no cycles consisting of gp-link 1560 + and rscs-link connections in which the number of gp-link instances is 1561 + >= the number of rscs-link instances. It does this by defining the 1562 + rcu-path relation to link events E and F whenever it is possible to 1563 + pass from E to F by a sequence of gp-link and rscs-link connections 1564 + with at least as many of the former as the latter. The LKMM's "rcu" 1565 + axiom then says that there are no events E such that E ->rcu-path E. 1566 + 1567 + Justifying this axiom takes some intellectual effort, but it is in 1568 + fact a valid formalization of the Grace Period Guarantee. We won't 1569 + attempt to go through the detailed argument, but the following 1570 + analysis gives a taste of what is involved. Suppose we have a 1571 + violation of the first part of the Guarantee: A critical section 1572 + starts before a grace period, and some store propagates to the 1573 + critical section's CPU before the end of the critical section but 1574 + doesn't propagate to some other CPU until after the end of the grace 1575 + period. 1576 + 1577 + Putting symbols to these ideas, let L and U be the rcu_read_lock() and 1578 + rcu_read_unlock() fence events delimiting the critical section in 1579 + question, and let S be the synchronize_rcu() fence event for the grace 1580 + period. Saying that the critical section starts before S means there 1581 + are events E and F where E is po-after L (which marks the start of the 1582 + critical section), E is "before" F in the sense of the link relation, 1583 + and F is po-before the grace period S: 1584 + 1585 + L ->po E ->link F ->po S. 1586 + 1587 + Let W be the store mentioned above, let Z come before the end of the 1588 + critical section and witness that W propagates to the critical 1589 + section's CPU by reading from W, and let Y on some arbitrary CPU be a 1590 + witness that W has not propagated to that CPU, where Y happens after 1591 + some event X which is po-after S. Symbolically, this amounts to: 1592 + 1593 + S ->po X ->hb* Y ->fr W ->rf Z ->po U. 1594 + 1595 + The fr link from Y to W indicates that W has not propagated to Y's CPU 1596 + at the time that Y executes. From this, it can be shown (see the 1597 + discussion of the link relation earlier) that X and Z are connected by 1598 + link, yielding: 1599 + 1600 + S ->po X ->link Z ->po U. 1601 + 1602 + These formulas say that S is po-between F and X, hence F ->gp-link Z 1603 + via X. They also say that Z comes before the end of the critical 1604 + section and E comes after its start, hence Z ->rscs-link F via E. But 1605 + now we have a forbidden cycle: F ->gp-link Z ->rscs-link F. Thus the 1606 + "rcu" axiom rules out this violation of the Grace Period Guarantee. 1607 + 1608 + For something a little more down-to-earth, let's see how the axiom 1609 + works out in practice. Consider the RCU code example from above, this 1610 + time with statement labels added to the memory access instructions: 1611 + 1612 + int x, y; 1613 + 1614 + P0() 1615 + { 1616 + rcu_read_lock(); 1617 + W: WRITE_ONCE(x, 1); 1618 + X: WRITE_ONCE(y, 1); 1619 + rcu_read_unlock(); 1620 + } 1621 + 1622 + P1() 1623 + { 1624 + int r1, r2; 1625 + 1626 + Y: r1 = READ_ONCE(x); 1627 + synchronize_rcu(); 1628 + Z: r2 = READ_ONCE(y); 1629 + } 1630 + 1631 + 1632 + If r2 = 0 at the end then P0's store at X overwrites the value 1633 + that P1's load at Z reads from, so we have Z ->fre X and thus 1634 + Z ->link X. In addition, there is a synchronize_rcu() between Y and 1635 + Z, so therefore we have Y ->gp-link X. 1636 + 1637 + If r1 = 1 at the end then P1's load at Y reads from P0's store at W, 1638 + so we have W ->link Y. In addition, W and X are in the same critical 1639 + section, so therefore we have X ->rscs-link Y. 1640 + 1641 + This gives us a cycle, Y ->gp-link X ->rscs-link Y, with one gp-link 1642 + and one rscs-link, violating the "rcu" axiom. Hence the outcome is 1643 + not allowed by the LKMM, as we would expect. 1644 + 1645 + For contrast, let's see what can happen in a more complicated example: 1646 + 1647 + int x, y, z; 1648 + 1649 + P0() 1650 + { 1651 + int r0; 1652 + 1653 + rcu_read_lock(); 1654 + W: r0 = READ_ONCE(x); 1655 + X: WRITE_ONCE(y, 1); 1656 + rcu_read_unlock(); 1657 + } 1658 + 1659 + P1() 1660 + { 1661 + int r1; 1662 + 1663 + Y: r1 = READ_ONCE(y); 1664 + synchronize_rcu(); 1665 + Z: WRITE_ONCE(z, 1); 1666 + } 1667 + 1668 + P2() 1669 + { 1670 + int r2; 1671 + 1672 + rcu_read_lock(); 1673 + U: r2 = READ_ONCE(z); 1674 + V: WRITE_ONCE(x, 1); 1675 + rcu_read_unlock(); 1676 + } 1677 + 1678 + If r0 = r1 = r2 = 1 at the end, then similar reasoning to before shows 1679 + that W ->rscs-link Y via X, Y ->gp-link U via Z, and U ->rscs-link W 1680 + via V. And just as before, this gives a cycle: 1681 + 1682 + W ->rscs-link Y ->gp-link U ->rscs-link W. 1683 + 1684 + However, this cycle has fewer gp-link instances than rscs-link 1685 + instances, and consequently the outcome is not forbidden by the LKMM. 1686 + The following instruction timing diagram shows how it might actually 1687 + occur: 1688 + 1689 + P0 P1 P2 1690 + -------------------- -------------------- -------------------- 1691 + rcu_read_lock() 1692 + X: WRITE_ONCE(y, 1) 1693 + Y: r1 = READ_ONCE(y) 1694 + synchronize_rcu() starts 1695 + . rcu_read_lock() 1696 + . V: WRITE_ONCE(x, 1) 1697 + W: r0 = READ_ONCE(x) . 1698 + rcu_read_unlock() . 1699 + synchronize_rcu() ends 1700 + Z: WRITE_ONCE(z, 1) 1701 + U: r2 = READ_ONCE(z) 1702 + rcu_read_unlock() 1703 + 1704 + This requires P0 and P2 to execute their loads and stores out of 1705 + program order, but of course they are allowed to do so. And as you 1706 + can see, the Grace Period Guarantee is not violated: The critical 1707 + section in P0 both starts before P1's grace period does and ends 1708 + before it does, and the critical section in P2 both starts after P1's 1709 + grace period does and ends after it does. 1710 + 1711 + 1712 + ODDS AND ENDS 1713 + ------------- 1714 + 1715 + This section covers material that didn't quite fit anywhere in the 1716 + earlier sections. 1717 + 1718 + The descriptions in this document don't always match the formal 1719 + version of the LKMM exactly. For example, the actual formal 1720 + definition of the prop relation makes the initial coe or fre part 1721 + optional, and it doesn't require the events linked by the relation to 1722 + be on the same CPU. These differences are very unimportant; indeed, 1723 + instances where the coe/fre part of prop is missing are of no interest 1724 + because all the other parts (fences and rfe) are already included in 1725 + hb anyway, and where the formal model adds prop into hb, it includes 1726 + an explicit requirement that the events being linked are on the same 1727 + CPU. 1728 + 1729 + Another minor difference has to do with events that are both memory 1730 + accesses and fences, such as those corresponding to smp_load_acquire() 1731 + calls. In the formal model, these events aren't actually both reads 1732 + and fences; rather, they are read events with an annotation marking 1733 + them as acquires. (Or write events annotated as releases, in the case 1734 + smp_store_release().) The final effect is the same. 1735 + 1736 + Although we didn't mention it above, the instruction execution 1737 + ordering provided by the smp_rmb() fence doesn't apply to read events 1738 + that are part of a non-value-returning atomic update. For instance, 1739 + given: 1740 + 1741 + atomic_inc(&x); 1742 + smp_rmb(); 1743 + r1 = READ_ONCE(y); 1744 + 1745 + it is not guaranteed that the load from y will execute after the 1746 + update to x. This is because the ARMv8 architecture allows 1747 + non-value-returning atomic operations effectively to be executed off 1748 + the CPU. Basically, the CPU tells the memory subsystem to increment 1749 + x, and then the increment is carried out by the memory hardware with 1750 + no further involvement from the CPU. Since the CPU doesn't ever read 1751 + the value of x, there is nothing for the smp_rmb() fence to act on. 1752 + 1753 + The LKMM defines a few extra synchronization operations in terms of 1754 + things we have already covered. In particular, rcu_dereference() and 1755 + lockless_dereference() are both treated as a READ_ONCE() followed by 1756 + smp_read_barrier_depends() -- which also happens to be how they are 1757 + defined in include/linux/rcupdate.h and include/linux/compiler.h, 1758 + respectively. 1759 + 1760 + There are a few oddball fences which need special treatment: 1761 + smp_mb__before_atomic(), smp_mb__after_atomic(), and 1762 + smp_mb__after_spinlock(). The LKMM uses fence events with special 1763 + annotations for them; they act as strong fences just like smp_mb() 1764 + except for the sets of events that they order. Instead of ordering 1765 + all po-earlier events against all po-later events, as smp_mb() does, 1766 + they behave as follows: 1767 + 1768 + smp_mb__before_atomic() orders all po-earlier events against 1769 + po-later atomic updates and the events following them; 1770 + 1771 + smp_mb__after_atomic() orders po-earlier atomic updates and 1772 + the events preceding them against all po-later events; 1773 + 1774 + smp_mb_after_spinlock() orders po-earlier lock acquisition 1775 + events and the events preceding them against all po-later 1776 + events. 1777 + 1778 + The LKMM includes locking. In fact, there is special code for locking 1779 + in the formal model, added in order to make tools run faster. 1780 + However, this special code is intended to be exactly equivalent to 1781 + concepts we have already covered. A spinlock_t variable is treated 1782 + the same as an int, and spin_lock(&s) is treated the same as: 1783 + 1784 + while (cmpxchg_acquire(&s, 0, 1) != 0) 1785 + cpu_relax(); 1786 + 1787 + which waits until s is equal to 0 and then atomically sets it to 1, 1788 + and where the read part of the atomic update is also an acquire fence. 1789 + An alternate way to express the same thing would be: 1790 + 1791 + r = xchg_acquire(&s, 1); 1792 + 1793 + along with a requirement that at the end, r = 0. spin_unlock(&s) is 1794 + treated the same as: 1795 + 1796 + smp_store_release(&s, 0); 1797 + 1798 + Interestingly, RCU and locking each introduce the possibility of 1799 + deadlock. When faced with code sequences such as: 1800 + 1801 + spin_lock(&s); 1802 + spin_lock(&s); 1803 + spin_unlock(&s); 1804 + spin_unlock(&s); 1805 + 1806 + or: 1807 + 1808 + rcu_read_lock(); 1809 + synchronize_rcu(); 1810 + rcu_read_unlock(); 1811 + 1812 + what does the LKMM have to say? Answer: It says there are no allowed 1813 + executions at all, which makes sense. But this can also lead to 1814 + misleading results, because if a piece of code has multiple possible 1815 + executions, some of which deadlock, the model will report only on the 1816 + non-deadlocking executions. For example: 1817 + 1818 + int x, y; 1819 + 1820 + P0() 1821 + { 1822 + int r0; 1823 + 1824 + WRITE_ONCE(x, 1); 1825 + r0 = READ_ONCE(y); 1826 + } 1827 + 1828 + P1() 1829 + { 1830 + rcu_read_lock(); 1831 + if (READ_ONCE(x) > 0) { 1832 + WRITE_ONCE(y, 36); 1833 + synchronize_rcu(); 1834 + } 1835 + rcu_read_unlock(); 1836 + } 1837 + 1838 + Is it possible to end up with r0 = 36 at the end? The LKMM will tell 1839 + you it is not, but the model won't mention that this is because P1 1840 + will self-deadlock in the executions where it stores 36 in y.
+570
tools/memory-model/Documentation/recipes.txt
··· 1 + This document provides "recipes", that is, litmus tests for commonly 2 + occurring situations, as well as a few that illustrate subtly broken but 3 + attractive nuisances. Many of these recipes include example code from 4 + v4.13 of the Linux kernel. 5 + 6 + The first section covers simple special cases, the second section 7 + takes off the training wheels to cover more involved examples, 8 + and the third section provides a few rules of thumb. 9 + 10 + 11 + Simple special cases 12 + ==================== 13 + 14 + This section presents two simple special cases, the first being where 15 + there is only one CPU or only one memory location is accessed, and the 16 + second being use of that old concurrency workhorse, locking. 17 + 18 + 19 + Single CPU or single memory location 20 + ------------------------------------ 21 + 22 + If there is only one CPU on the one hand or only one variable 23 + on the other, the code will execute in order. There are (as 24 + usual) some things to be careful of: 25 + 26 + 1. Some aspects of the C language are unordered. For example, 27 + in the expression "f(x) + g(y)", the order in which f and g are 28 + called is not defined; the object code is allowed to use either 29 + order or even to interleave the computations. 30 + 31 + 2. Compilers are permitted to use the "as-if" rule. That is, a 32 + compiler can emit whatever code it likes for normal accesses, 33 + as long as the results of a single-threaded execution appear 34 + just as if the compiler had followed all the relevant rules. 35 + To see this, compile with a high level of optimization and run 36 + the debugger on the resulting binary. 37 + 38 + 3. If there is only one variable but multiple CPUs, that variable 39 + must be properly aligned and all accesses to that variable must 40 + be full sized. Variables that straddle cachelines or pages void 41 + your full-ordering warranty, as do undersized accesses that load 42 + from or store to only part of the variable. 43 + 44 + 4. If there are multiple CPUs, accesses to shared variables should 45 + use READ_ONCE() and WRITE_ONCE() or stronger to prevent load/store 46 + tearing, load/store fusing, and invented loads and stores. 47 + There are exceptions to this rule, including: 48 + 49 + i. When there is no possibility of a given shared variable 50 + being updated by some other CPU, for example, while 51 + holding the update-side lock, reads from that variable 52 + need not use READ_ONCE(). 53 + 54 + ii. When there is no possibility of a given shared variable 55 + being either read or updated by other CPUs, for example, 56 + when running during early boot, reads from that variable 57 + need not use READ_ONCE() and writes to that variable 58 + need not use WRITE_ONCE(). 59 + 60 + 61 + Locking 62 + ------- 63 + 64 + Locking is well-known and straightforward, at least if you don't think 65 + about it too hard. And the basic rule is indeed quite simple: Any CPU that 66 + has acquired a given lock sees any changes previously seen or made by any 67 + CPU before it released that same lock. Note that this statement is a bit 68 + stronger than "Any CPU holding a given lock sees all changes made by any 69 + CPU during the time that CPU was holding this same lock". For example, 70 + consider the following pair of code fragments: 71 + 72 + /* See MP+polocks.litmus. */ 73 + void CPU0(void) 74 + { 75 + WRITE_ONCE(x, 1); 76 + spin_lock(&mylock); 77 + WRITE_ONCE(y, 1); 78 + spin_unlock(&mylock); 79 + } 80 + 81 + void CPU1(void) 82 + { 83 + spin_lock(&mylock); 84 + r0 = READ_ONCE(y); 85 + spin_unlock(&mylock); 86 + r1 = READ_ONCE(x); 87 + } 88 + 89 + The basic rule guarantees that if CPU0() acquires mylock before CPU1(), 90 + then both r0 and r1 must be set to the value 1. This also has the 91 + consequence that if the final value of r0 is equal to 1, then the final 92 + value of r1 must also be equal to 1. In contrast, the weaker rule would 93 + say nothing about the final value of r1. 94 + 95 + The converse to the basic rule also holds, as illustrated by the 96 + following litmus test: 97 + 98 + /* See MP+porevlocks.litmus. */ 99 + void CPU0(void) 100 + { 101 + r0 = READ_ONCE(y); 102 + spin_lock(&mylock); 103 + r1 = READ_ONCE(x); 104 + spin_unlock(&mylock); 105 + } 106 + 107 + void CPU1(void) 108 + { 109 + spin_lock(&mylock); 110 + WRITE_ONCE(x, 1); 111 + spin_unlock(&mylock); 112 + WRITE_ONCE(y, 1); 113 + } 114 + 115 + This converse to the basic rule guarantees that if CPU0() acquires 116 + mylock before CPU1(), then both r0 and r1 must be set to the value 0. 117 + This also has the consequence that if the final value of r1 is equal 118 + to 0, then the final value of r0 must also be equal to 0. In contrast, 119 + the weaker rule would say nothing about the final value of r0. 120 + 121 + These examples show only a single pair of CPUs, but the effects of the 122 + locking basic rule extend across multiple acquisitions of a given lock 123 + across multiple CPUs. 124 + 125 + However, it is not necessarily the case that accesses ordered by 126 + locking will be seen as ordered by CPUs not holding that lock. 127 + Consider this example: 128 + 129 + /* See Z6.0+pooncelock+pooncelock+pombonce.litmus. */ 130 + void CPU0(void) 131 + { 132 + spin_lock(&mylock); 133 + WRITE_ONCE(x, 1); 134 + WRITE_ONCE(y, 1); 135 + spin_unlock(&mylock); 136 + } 137 + 138 + void CPU1(void) 139 + { 140 + spin_lock(&mylock); 141 + r0 = READ_ONCE(y); 142 + WRITE_ONCE(z, 1); 143 + spin_unlock(&mylock); 144 + } 145 + 146 + void CPU2(void) 147 + { 148 + WRITE_ONCE(z, 2); 149 + smp_mb(); 150 + r1 = READ_ONCE(x); 151 + } 152 + 153 + Counter-intuitive though it might be, it is quite possible to have 154 + the final value of r0 be 1, the final value of z be 2, and the final 155 + value of r1 be 0. The reason for this surprising outcome is that 156 + CPU2() never acquired the lock, and thus did not benefit from the 157 + lock's ordering properties. 158 + 159 + Ordering can be extended to CPUs not holding the lock by careful use 160 + of smp_mb__after_spinlock(): 161 + 162 + /* See Z6.0+pooncelock+poonceLock+pombonce.litmus. */ 163 + void CPU0(void) 164 + { 165 + spin_lock(&mylock); 166 + WRITE_ONCE(x, 1); 167 + WRITE_ONCE(y, 1); 168 + spin_unlock(&mylock); 169 + } 170 + 171 + void CPU1(void) 172 + { 173 + spin_lock(&mylock); 174 + smp_mb__after_spinlock(); 175 + r0 = READ_ONCE(y); 176 + WRITE_ONCE(z, 1); 177 + spin_unlock(&mylock); 178 + } 179 + 180 + void CPU2(void) 181 + { 182 + WRITE_ONCE(z, 2); 183 + smp_mb(); 184 + r1 = READ_ONCE(x); 185 + } 186 + 187 + This addition of smp_mb__after_spinlock() strengthens the lock acquisition 188 + sufficiently to rule out the counter-intuitive outcome. 189 + 190 + 191 + Taking off the training wheels 192 + ============================== 193 + 194 + This section looks at more complex examples, including message passing, 195 + load buffering, release-acquire chains, store buffering. 196 + Many classes of litmus tests have abbreviated names, which may be found 197 + here: https://www.cl.cam.ac.uk/~pes20/ppc-supplemental/test6.pdf 198 + 199 + 200 + Message passing (MP) 201 + -------------------- 202 + 203 + The MP pattern has one CPU execute a pair of stores to a pair of variables 204 + and another CPU execute a pair of loads from this same pair of variables, 205 + but in the opposite order. The goal is to avoid the counter-intuitive 206 + outcome in which the first load sees the value written by the second store 207 + but the second load does not see the value written by the first store. 208 + In the absence of any ordering, this goal may not be met, as can be seen 209 + in the MP+poonceonces.litmus litmus test. This section therefore looks at 210 + a number of ways of meeting this goal. 211 + 212 + 213 + Release and acquire 214 + ~~~~~~~~~~~~~~~~~~~ 215 + 216 + Use of smp_store_release() and smp_load_acquire() is one way to force 217 + the desired MP ordering. The general approach is shown below: 218 + 219 + /* See MP+pooncerelease+poacquireonce.litmus. */ 220 + void CPU0(void) 221 + { 222 + WRITE_ONCE(x, 1); 223 + smp_store_release(&y, 1); 224 + } 225 + 226 + void CPU1(void) 227 + { 228 + r0 = smp_load_acquire(&y); 229 + r1 = READ_ONCE(x); 230 + } 231 + 232 + The smp_store_release() macro orders any prior accesses against the 233 + store, while the smp_load_acquire macro orders the load against any 234 + subsequent accesses. Therefore, if the final value of r0 is the value 1, 235 + the final value of r1 must also be the value 1. 236 + 237 + The init_stack_slab() function in lib/stackdepot.c uses release-acquire 238 + in this way to safely initialize of a slab of the stack. Working out 239 + the mutual-exclusion design is left as an exercise for the reader. 240 + 241 + 242 + Assign and dereference 243 + ~~~~~~~~~~~~~~~~~~~~~~ 244 + 245 + Use of rcu_assign_pointer() and rcu_dereference() is quite similar to the 246 + use of smp_store_release() and smp_load_acquire(), except that both 247 + rcu_assign_pointer() and rcu_dereference() operate on RCU-protected 248 + pointers. The general approach is shown below: 249 + 250 + /* See MP+onceassign+derefonce.litmus. */ 251 + int z; 252 + int *y = &z; 253 + int x; 254 + 255 + void CPU0(void) 256 + { 257 + WRITE_ONCE(x, 1); 258 + rcu_assign_pointer(y, &x); 259 + } 260 + 261 + void CPU1(void) 262 + { 263 + rcu_read_lock(); 264 + r0 = rcu_dereference(y); 265 + r1 = READ_ONCE(*r0); 266 + rcu_read_unlock(); 267 + } 268 + 269 + In this example, if the final value of r0 is &x then the final value of 270 + r1 must be 1. 271 + 272 + The rcu_assign_pointer() macro has the same ordering properties as does 273 + smp_store_release(), but the rcu_dereference() macro orders the load only 274 + against later accesses that depend on the value loaded. A dependency 275 + is present if the value loaded determines the address of a later access 276 + (address dependency, as shown above), the value written by a later store 277 + (data dependency), or whether or not a later store is executed in the 278 + first place (control dependency). Note that the term "data dependency" 279 + is sometimes casually used to cover both address and data dependencies. 280 + 281 + In lib/prime_numbers.c, the expand_to_next_prime() function invokes 282 + rcu_assign_pointer(), and the next_prime_number() function invokes 283 + rcu_dereference(). This combination mediates access to a bit vector 284 + that is expanded as additional primes are needed. 285 + 286 + 287 + Write and read memory barriers 288 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 289 + 290 + It is usually better to use smp_store_release() instead of smp_wmb() 291 + and to use smp_load_acquire() instead of smp_rmb(). However, the older 292 + smp_wmb() and smp_rmb() APIs are still heavily used, so it is important 293 + to understand their use cases. The general approach is shown below: 294 + 295 + /* See MP+wmbonceonce+rmbonceonce.litmus. */ 296 + void CPU0(void) 297 + { 298 + WRITE_ONCE(x, 1); 299 + smp_wmb(); 300 + WRITE_ONCE(y, 1); 301 + } 302 + 303 + void CPU1(void) 304 + { 305 + r0 = READ_ONCE(y); 306 + smp_rmb(); 307 + r1 = READ_ONCE(x); 308 + } 309 + 310 + The smp_wmb() macro orders prior stores against later stores, and the 311 + smp_rmb() macro orders prior loads against later loads. Therefore, if 312 + the final value of r0 is 1, the final value of r1 must also be 1. 313 + 314 + The the xlog_state_switch_iclogs() function in fs/xfs/xfs_log.c contains 315 + the following write-side code fragment: 316 + 317 + log->l_curr_block -= log->l_logBBsize; 318 + ASSERT(log->l_curr_block >= 0); 319 + smp_wmb(); 320 + log->l_curr_cycle++; 321 + 322 + And the xlog_valid_lsn() function in fs/xfs/xfs_log_priv.h contains 323 + the corresponding read-side code fragment: 324 + 325 + cur_cycle = ACCESS_ONCE(log->l_curr_cycle); 326 + smp_rmb(); 327 + cur_block = ACCESS_ONCE(log->l_curr_block); 328 + 329 + Alternatively, consider the following comment in function 330 + perf_output_put_handle() in kernel/events/ring_buffer.c: 331 + 332 + * kernel user 333 + * 334 + * if (LOAD ->data_tail) { LOAD ->data_head 335 + * (A) smp_rmb() (C) 336 + * STORE $data LOAD $data 337 + * smp_wmb() (B) smp_mb() (D) 338 + * STORE ->data_head STORE ->data_tail 339 + * } 340 + 341 + The B/C pairing is an example of the MP pattern using smp_wmb() on the 342 + write side and smp_rmb() on the read side. 343 + 344 + Of course, given that smp_mb() is strictly stronger than either smp_wmb() 345 + or smp_rmb(), any code fragment that would work with smp_rmb() and 346 + smp_wmb() would also work with smp_mb() replacing either or both of the 347 + weaker barriers. 348 + 349 + 350 + Load buffering (LB) 351 + ------------------- 352 + 353 + The LB pattern has one CPU load from one variable and then store to a 354 + second, while another CPU loads from the second variable and then stores 355 + to the first. The goal is to avoid the counter-intuitive situation where 356 + each load reads the value written by the other CPU's store. In the 357 + absence of any ordering it is quite possible that this may happen, as 358 + can be seen in the LB+poonceonces.litmus litmus test. 359 + 360 + One way of avoiding the counter-intuitive outcome is through the use of a 361 + control dependency paired with a full memory barrier: 362 + 363 + /* See LB+ctrlonceonce+mbonceonce.litmus. */ 364 + void CPU0(void) 365 + { 366 + r0 = READ_ONCE(x); 367 + if (r0) 368 + WRITE_ONCE(y, 1); 369 + } 370 + 371 + void CPU1(void) 372 + { 373 + r1 = READ_ONCE(y); 374 + smp_mb(); 375 + WRITE_ONCE(x, 1); 376 + } 377 + 378 + This pairing of a control dependency in CPU0() with a full memory 379 + barrier in CPU1() prevents r0 and r1 from both ending up equal to 1. 380 + 381 + The A/D pairing from the ring-buffer use case shown earlier also 382 + illustrates LB. Here is a repeat of the comment in 383 + perf_output_put_handle() in kernel/events/ring_buffer.c, showing a 384 + control dependency on the kernel side and a full memory barrier on 385 + the user side: 386 + 387 + * kernel user 388 + * 389 + * if (LOAD ->data_tail) { LOAD ->data_head 390 + * (A) smp_rmb() (C) 391 + * STORE $data LOAD $data 392 + * smp_wmb() (B) smp_mb() (D) 393 + * STORE ->data_head STORE ->data_tail 394 + * } 395 + * 396 + * Where A pairs with D, and B pairs with C. 397 + 398 + The kernel's control dependency between the load from ->data_tail 399 + and the store to data combined with the user's full memory barrier 400 + between the load from data and the store to ->data_tail prevents 401 + the counter-intuitive outcome where the kernel overwrites the data 402 + before the user gets done loading it. 403 + 404 + 405 + Release-acquire chains 406 + ---------------------- 407 + 408 + Release-acquire chains are a low-overhead, flexible, and easy-to-use 409 + method of maintaining order. However, they do have some limitations that 410 + need to be fully understood. Here is an example that maintains order: 411 + 412 + /* See ISA2+pooncerelease+poacquirerelease+poacquireonce.litmus. */ 413 + void CPU0(void) 414 + { 415 + WRITE_ONCE(x, 1); 416 + smp_store_release(&y, 1); 417 + } 418 + 419 + void CPU1(void) 420 + { 421 + r0 = smp_load_acquire(y); 422 + smp_store_release(&z, 1); 423 + } 424 + 425 + void CPU2(void) 426 + { 427 + r1 = smp_load_acquire(z); 428 + r2 = READ_ONCE(x); 429 + } 430 + 431 + In this case, if r0 and r1 both have final values of 1, then r2 must 432 + also have a final value of 1. 433 + 434 + The ordering in this example is stronger than it needs to be. For 435 + example, ordering would still be preserved if CPU1()'s smp_load_acquire() 436 + invocation was replaced with READ_ONCE(). 437 + 438 + It is tempting to assume that CPU0()'s store to x is globally ordered 439 + before CPU1()'s store to z, but this is not the case: 440 + 441 + /* See Z6.0+pooncerelease+poacquirerelease+mbonceonce.litmus. */ 442 + void CPU0(void) 443 + { 444 + WRITE_ONCE(x, 1); 445 + smp_store_release(&y, 1); 446 + } 447 + 448 + void CPU1(void) 449 + { 450 + r0 = smp_load_acquire(y); 451 + smp_store_release(&z, 1); 452 + } 453 + 454 + void CPU2(void) 455 + { 456 + WRITE_ONCE(z, 2); 457 + smp_mb(); 458 + r1 = READ_ONCE(x); 459 + } 460 + 461 + One might hope that if the final value of r0 is 1 and the final value 462 + of z is 2, then the final value of r1 must also be 1, but it really is 463 + possible for r1 to have the final value of 0. The reason, of course, 464 + is that in this version, CPU2() is not part of the release-acquire chain. 465 + This situation is accounted for in the rules of thumb below. 466 + 467 + Despite this limitation, release-acquire chains are low-overhead as 468 + well as simple and powerful, at least as memory-ordering mechanisms go. 469 + 470 + 471 + Store buffering 472 + --------------- 473 + 474 + Store buffering can be thought of as upside-down load buffering, so 475 + that one CPU first stores to one variable and then loads from a second, 476 + while another CPU stores to the second variable and then loads from the 477 + first. Preserving order requires nothing less than full barriers: 478 + 479 + /* See SB+mbonceonces.litmus. */ 480 + void CPU0(void) 481 + { 482 + WRITE_ONCE(x, 1); 483 + smp_mb(); 484 + r0 = READ_ONCE(y); 485 + } 486 + 487 + void CPU1(void) 488 + { 489 + WRITE_ONCE(y, 1); 490 + smp_mb(); 491 + r1 = READ_ONCE(x); 492 + } 493 + 494 + Omitting either smp_mb() will allow both r0 and r1 to have final 495 + values of 0, but providing both full barriers as shown above prevents 496 + this counter-intuitive outcome. 497 + 498 + This pattern most famously appears as part of Dekker's locking 499 + algorithm, but it has a much more practical use within the Linux kernel 500 + of ordering wakeups. The following comment taken from waitqueue_active() 501 + in include/linux/wait.h shows the canonical pattern: 502 + 503 + * CPU0 - waker CPU1 - waiter 504 + * 505 + * for (;;) { 506 + * @cond = true; prepare_to_wait(&wq_head, &wait, state); 507 + * smp_mb(); // smp_mb() from set_current_state() 508 + * if (waitqueue_active(wq_head)) if (@cond) 509 + * wake_up(wq_head); break; 510 + * schedule(); 511 + * } 512 + * finish_wait(&wq_head, &wait); 513 + 514 + On CPU0, the store is to @cond and the load is in waitqueue_active(). 515 + On CPU1, prepare_to_wait() contains both a store to wq_head and a call 516 + to set_current_state(), which contains an smp_mb() barrier; the load is 517 + "if (@cond)". The full barriers prevent the undesirable outcome where 518 + CPU1 puts the waiting task to sleep and CPU0 fails to wake it up. 519 + 520 + Note that use of locking can greatly simplify this pattern. 521 + 522 + 523 + Rules of thumb 524 + ============== 525 + 526 + There might seem to be no pattern governing what ordering primitives are 527 + needed in which situations, but this is not the case. There is a pattern 528 + based on the relation between the accesses linking successive CPUs in a 529 + given litmus test. There are three types of linkage: 530 + 531 + 1. Write-to-read, where the next CPU reads the value that the 532 + previous CPU wrote. The LB litmus-test patterns contain only 533 + this type of relation. In formal memory-modeling texts, this 534 + relation is called "reads-from" and is usually abbreviated "rf". 535 + 536 + 2. Read-to-write, where the next CPU overwrites the value that the 537 + previous CPU read. The SB litmus test contains only this type 538 + of relation. In formal memory-modeling texts, this relation is 539 + often called "from-reads" and is sometimes abbreviated "fr". 540 + 541 + 3. Write-to-write, where the next CPU overwrites the value written 542 + by the previous CPU. The Z6.0 litmus test pattern contains a 543 + write-to-write relation between the last access of CPU1() and 544 + the first access of CPU2(). In formal memory-modeling texts, 545 + this relation is often called "coherence order" and is sometimes 546 + abbreviated "co". In the C++ standard, it is instead called 547 + "modification order" and often abbreviated "mo". 548 + 549 + The strength of memory ordering required for a given litmus test to 550 + avoid a counter-intuitive outcome depends on the types of relations 551 + linking the memory accesses for the outcome in question: 552 + 553 + o If all links are write-to-read links, then the weakest 554 + possible ordering within each CPU suffices. For example, in 555 + the LB litmus test, a control dependency was enough to do the 556 + job. 557 + 558 + o If all but one of the links are write-to-read links, then a 559 + release-acquire chain suffices. Both the MP and the ISA2 560 + litmus tests illustrate this case. 561 + 562 + o If more than one of the links are something other than 563 + write-to-read links, then a full memory barrier is required 564 + between each successive pair of non-write-to-read links. This 565 + case is illustrated by the Z6.0 litmus tests, both in the 566 + locking and in the release-acquire sections. 567 + 568 + However, if you find yourself having to stretch these rules of thumb 569 + to fit your situation, you should consider creating a litmus test and 570 + running it on the model.
+107
tools/memory-model/Documentation/references.txt
··· 1 + This document provides background reading for memory models and related 2 + tools. These documents are aimed at kernel hackers who are interested 3 + in memory models. 4 + 5 + 6 + Hardware manuals and models 7 + =========================== 8 + 9 + o SPARC International Inc. (Ed.). 1994. "The SPARC Architecture 10 + Reference Manual Version 9". SPARC International Inc. 11 + 12 + o Compaq Computer Corporation (Ed.). 2002. "Alpha Architecture 13 + Reference Manual". Compaq Computer Corporation. 14 + 15 + o Intel Corporation (Ed.). 2002. "A Formal Specification of Intel 16 + Itanium Processor Family Memory Ordering". Intel Corporation. 17 + 18 + o Intel Corporation (Ed.). 2002. "Intel 64 and IA-32 Architectures 19 + Software Developer’s Manual". Intel Corporation. 20 + 21 + o Peter Sewell, Susmit Sarkar, Scott Owens, Francesco Zappa Nardelli, 22 + and Magnus O. Myreen. 2010. "x86-TSO: A Rigorous and Usable 23 + Programmer's Model for x86 Multiprocessors". Commun. ACM 53, 7 24 + (July, 2010), 89-97. http://doi.acm.org/10.1145/1785414.1785443 25 + 26 + o IBM Corporation (Ed.). 2009. "Power ISA Version 2.06". IBM 27 + Corporation. 28 + 29 + o ARM Ltd. (Ed.). 2009. "ARM Barrier Litmus Tests and Cookbook". 30 + ARM Ltd. 31 + 32 + o Susmit Sarkar, Peter Sewell, Jade Alglave, Luc Maranget, and 33 + Derek Williams. 2011. "Understanding POWER Multiprocessors". In 34 + Proceedings of the 32Nd ACM SIGPLAN Conference on Programming 35 + Language Design and Implementation (PLDI ’11). ACM, New York, 36 + NY, USA, 175–186. 37 + 38 + o Susmit Sarkar, Kayvan Memarian, Scott Owens, Mark Batty, 39 + Peter Sewell, Luc Maranget, Jade Alglave, and Derek Williams. 40 + 2012. "Synchronising C/C++ and POWER". In Proceedings of the 33rd 41 + ACM SIGPLAN Conference on Programming Language Design and 42 + Implementation (PLDI '12). ACM, New York, NY, USA, 311-322. 43 + 44 + o ARM Ltd. (Ed.). 2014. "ARM Architecture Reference Manual (ARMv8, 45 + for ARMv8-A architecture profile)". ARM Ltd. 46 + 47 + o Imagination Technologies, LTD. 2015. "MIPS(R) Architecture 48 + For Programmers, Volume II-A: The MIPS64(R) Instruction, 49 + Set Reference Manual". Imagination Technologies, 50 + LTD. https://imgtec.com/?do-download=4302. 51 + 52 + o Shaked Flur, Kathryn E. Gray, Christopher Pulte, Susmit 53 + Sarkar, Ali Sezgin, Luc Maranget, Will Deacon, and Peter 54 + Sewell. 2016. "Modelling the ARMv8 Architecture, Operationally: 55 + Concurrency and ISA". In Proceedings of the 43rd Annual ACM 56 + SIGPLAN-SIGACT Symposium on Principles of Programming Languages 57 + (POPL ’16). ACM, New York, NY, USA, 608–621. 58 + 59 + o Shaked Flur, Susmit Sarkar, Christopher Pulte, Kyndylan Nienhuis, 60 + Luc Maranget, Kathryn E. Gray, Ali Sezgin, Mark Batty, and Peter 61 + Sewell. 2017. "Mixed-size Concurrency: ARM, POWER, C/C++11, 62 + and SC". In Proceedings of the 44th ACM SIGPLAN Symposium on 63 + Principles of Programming Languages (POPL 2017). ACM, New York, 64 + NY, USA, 429–442. 65 + 66 + 67 + Linux-kernel memory model 68 + ========================= 69 + 70 + o Andrea Parri, Alan Stern, Luc Maranget, Paul E. McKenney, 71 + and Jade Alglave. 2017. "A formal model of 72 + Linux-kernel memory ordering - companion webpage". 73 + http://moscova.inria.fr/∼maranget/cats7/linux/. (2017). [Online; 74 + accessed 30-January-2017]. 75 + 76 + o Jade Alglave, Luc Maranget, Paul E. McKenney, Andrea Parri, and 77 + Alan Stern. 2017. "A formal kernel memory-ordering model (part 1)" 78 + Linux Weekly News. https://lwn.net/Articles/718628/ 79 + 80 + o Jade Alglave, Luc Maranget, Paul E. McKenney, Andrea Parri, and 81 + Alan Stern. 2017. "A formal kernel memory-ordering model (part 2)" 82 + Linux Weekly News. https://lwn.net/Articles/720550/ 83 + 84 + 85 + Memory-model tooling 86 + ==================== 87 + 88 + o Daniel Jackson. 2002. "Alloy: A Lightweight Object Modelling 89 + Notation". ACM Trans. Softw. Eng. Methodol. 11, 2 (April 2002), 90 + 256–290. http://doi.acm.org/10.1145/505145.505149 91 + 92 + o Jade Alglave, Luc Maranget, and Michael Tautschnig. 2014. "Herding 93 + Cats: Modelling, Simulation, Testing, and Data Mining for Weak 94 + Memory". ACM Trans. Program. Lang. Syst. 36, 2, Article 7 (July 95 + 2014), 7:1–7:74 pages. 96 + 97 + o Jade Alglave, Patrick Cousot, and Luc Maranget. 2016. "Syntax and 98 + semantics of the weak consistency model specification language 99 + cat". CoRR abs/1608.07531 (2016). http://arxiv.org/abs/1608.07531 100 + 101 + 102 + Memory-model comparisons 103 + ======================== 104 + 105 + o Paul E. McKenney, Ulrich Weigand, Andrea Parri, and Boqun 106 + Feng. 2016. "Linux-Kernel Memory Model". (6 June 2016). 107 + http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/p0124r2.html.
+15
tools/memory-model/MAINTAINERS
··· 1 + LINUX KERNEL MEMORY MODEL 2 + M: Alan Stern <stern@rowland.harvard.edu> 3 + M: Andrea Parri <parri.andrea@gmail.com> 4 + M: Will Deacon <will.deacon@arm.com> 5 + M: Peter Zijlstra <peterz@infradead.org> 6 + M: Boqun Feng <boqun.feng@gmail.com> 7 + M: Nicholas Piggin <npiggin@gmail.com> 8 + M: David Howells <dhowells@redhat.com> 9 + M: Jade Alglave <j.alglave@ucl.ac.uk> 10 + M: Luc Maranget <luc.maranget@inria.fr> 11 + M: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com> 12 + L: linux-kernel@vger.kernel.org 13 + S: Supported 14 + T: git git://git.kernel.org/pub/scm/linux/kernel/git/paulmck/linux-rcu.git 15 + F: tools/memory-model/
+220
tools/memory-model/README
··· 1 + ========================= 2 + LINUX KERNEL MEMORY MODEL 3 + ========================= 4 + 5 + ============ 6 + INTRODUCTION 7 + ============ 8 + 9 + This directory contains the memory model of the Linux kernel, written 10 + in the "cat" language and executable by the (externally provided) 11 + "herd7" simulator, which exhaustively explores the state space of 12 + small litmus tests. 13 + 14 + In addition, the "klitmus7" tool (also externally provided) may be used 15 + to convert a litmus test to a Linux kernel module, which in turn allows 16 + that litmus test to be exercised within the Linux kernel. 17 + 18 + 19 + ============ 20 + REQUIREMENTS 21 + ============ 22 + 23 + The "herd7" and "klitmus7" tools must be downloaded separately: 24 + 25 + https://github.com/herd/herdtools7 26 + 27 + See "herdtools7/INSTALL.md" for installation instructions. 28 + 29 + Alternatively, Abhishek Bhardwaj has kindly provided a Docker image 30 + of these tools at "abhishek40/memory-model". Abhishek suggests the 31 + following commands to install and use this image: 32 + 33 + - Users should install Docker for their distribution. 34 + - docker run -itd abhishek40/memory-model 35 + - docker attach <id-emitted-from-the-previous-command> 36 + 37 + Gentoo users might wish to make use of Patrick McLean's package: 38 + 39 + https://gitweb.gentoo.org/repo/gentoo.git/tree/dev-util/herdtools7 40 + 41 + These packages may not be up-to-date with respect to the GitHub 42 + repository. 43 + 44 + 45 + ================== 46 + BASIC USAGE: HERD7 47 + ================== 48 + 49 + The memory model is used, in conjunction with "herd7", to exhaustively 50 + explore the state space of small litmus tests. 51 + 52 + For example, to run SB+mbonceonces.litmus against the memory model: 53 + 54 + $ herd7 -conf linux-kernel.cfg litmus-tests/SB+mbonceonces.litmus 55 + 56 + Here is the corresponding output: 57 + 58 + Test SB+mbonceonces Allowed 59 + States 3 60 + 0:r0=0; 1:r0=1; 61 + 0:r0=1; 1:r0=0; 62 + 0:r0=1; 1:r0=1; 63 + No 64 + Witnesses 65 + Positive: 0 Negative: 3 66 + Condition exists (0:r0=0 /\ 1:r0=0) 67 + Observation SB+mbonceonces Never 0 3 68 + Time SB+mbonceonces 0.01 69 + Hash=d66d99523e2cac6b06e66f4c995ebb48 70 + 71 + The "Positive: 0 Negative: 3" and the "Never 0 3" each indicate that 72 + this litmus test's "exists" clause can not be satisfied. 73 + 74 + See "herd7 -help" or "herdtools7/doc/" for more information. 75 + 76 + 77 + ===================== 78 + BASIC USAGE: KLITMUS7 79 + ===================== 80 + 81 + The "klitmus7" tool converts a litmus test into a Linux kernel module, 82 + which may then be loaded and run. 83 + 84 + For example, to run SB+mbonceonces.litmus against hardware: 85 + 86 + $ mkdir mymodules 87 + $ klitmus7 -o mymodules litmus-tests/SB+mbonceonces.litmus 88 + $ cd mymodules ; make 89 + $ sudo sh run.sh 90 + 91 + The corresponding output includes: 92 + 93 + Test SB+mbonceonces Allowed 94 + Histogram (3 states) 95 + 644580 :>0:r0=1; 1:r0=0; 96 + 644328 :>0:r0=0; 1:r0=1; 97 + 711092 :>0:r0=1; 1:r0=1; 98 + No 99 + Witnesses 100 + Positive: 0, Negative: 2000000 101 + Condition exists (0:r0=0 /\ 1:r0=0) is NOT validated 102 + Hash=d66d99523e2cac6b06e66f4c995ebb48 103 + Observation SB+mbonceonces Never 0 2000000 104 + Time SB+mbonceonces 0.16 105 + 106 + The "Positive: 0 Negative: 2000000" and the "Never 0 2000000" indicate 107 + that during two million trials, the state specified in this litmus 108 + test's "exists" clause was not reached. 109 + 110 + And, as with "herd7", please see "klitmus7 -help" or "herdtools7/doc/" 111 + for more information. 112 + 113 + 114 + ==================== 115 + DESCRIPTION OF FILES 116 + ==================== 117 + 118 + Documentation/cheatsheet.txt 119 + Quick-reference guide to the Linux-kernel memory model. 120 + 121 + Documentation/explanation.txt 122 + Describes the memory model in detail. 123 + 124 + Documentation/recipes.txt 125 + Lists common memory-ordering patterns. 126 + 127 + Documentation/references.txt 128 + Provides background reading. 129 + 130 + linux-kernel.bell 131 + Categorizes the relevant instructions, including memory 132 + references, memory barriers, atomic read-modify-write operations, 133 + lock acquisition/release, and RCU operations. 134 + 135 + More formally, this file (1) lists the subtypes of the various 136 + event types used by the memory model and (2) performs RCU 137 + read-side critical section nesting analysis. 138 + 139 + linux-kernel.cat 140 + Specifies what reorderings are forbidden by memory references, 141 + memory barriers, atomic read-modify-write operations, and RCU. 142 + 143 + More formally, this file specifies what executions are forbidden 144 + by the memory model. Allowed executions are those which 145 + satisfy the model's "coherence", "atomic", "happens-before", 146 + "propagation", and "rcu" axioms, which are defined in the file. 147 + 148 + linux-kernel.cfg 149 + Convenience file that gathers the common-case herd7 command-line 150 + arguments. 151 + 152 + linux-kernel.def 153 + Maps from C-like syntax to herd7's internal litmus-test 154 + instruction-set architecture. 155 + 156 + litmus-tests 157 + Directory containing a few representative litmus tests, which 158 + are listed in litmus-tests/README. A great deal more litmus 159 + tests are available at https://github.com/paulmckrcu/litmus. 160 + 161 + lock.cat 162 + Provides a front-end analysis of lock acquisition and release, 163 + for example, associating a lock acquisition with the preceding 164 + and following releases and checking for self-deadlock. 165 + 166 + More formally, this file defines a performance-enhanced scheme 167 + for generation of the possible reads-from and coherence order 168 + relations on the locking primitives. 169 + 170 + README 171 + This file. 172 + 173 + 174 + =========== 175 + LIMITATIONS 176 + =========== 177 + 178 + The Linux-kernel memory model has the following limitations: 179 + 180 + 1. Compiler optimizations are not modeled. Of course, the use 181 + of READ_ONCE() and WRITE_ONCE() limits the compiler's ability 182 + to optimize, but there is Linux-kernel code that uses bare C 183 + memory accesses. Handling this code is on the to-do list. 184 + For more information, see Documentation/explanation.txt (in 185 + particular, the "THE PROGRAM ORDER RELATION: po AND po-loc" 186 + and "A WARNING" sections). 187 + 188 + 2. Multiple access sizes for a single variable are not supported, 189 + and neither are misaligned or partially overlapping accesses. 190 + 191 + 3. Exceptions and interrupts are not modeled. In some cases, 192 + this limitation can be overcome by modeling the interrupt or 193 + exception with an additional process. 194 + 195 + 4. I/O such as MMIO or DMA is not supported. 196 + 197 + 5. Self-modifying code (such as that found in the kernel's 198 + alternatives mechanism, function tracer, Berkeley Packet Filter 199 + JIT compiler, and module loader) is not supported. 200 + 201 + 6. Complete modeling of all variants of atomic read-modify-write 202 + operations, locking primitives, and RCU is not provided. 203 + For example, call_rcu() and rcu_barrier() are not supported. 204 + However, a substantial amount of support is provided for these 205 + operations, as shown in the linux-kernel.def file. 206 + 207 + The "herd7" tool has some additional limitations of its own, apart from 208 + the memory model: 209 + 210 + 1. Non-trivial data structures such as arrays or structures are 211 + not supported. However, pointers are supported, allowing trivial 212 + linked lists to be constructed. 213 + 214 + 2. Dynamic memory allocation is not supported, although this can 215 + be worked around in some cases by supplying multiple statically 216 + allocated variables. 217 + 218 + Some of these limitations may be overcome in the future, but others are 219 + more likely to be addressed by incorporating the Linux-kernel memory model 220 + into other tools.
+53
tools/memory-model/linux-kernel.bell
··· 1 + // SPDX-License-Identifier: GPL-2.0+ 2 + (* 3 + * Copyright (C) 2015 Jade Alglave <j.alglave@ucl.ac.uk>, 4 + * Copyright (C) 2016 Luc Maranget <luc.maranget@inria.fr> for Inria 5 + * Copyright (C) 2017 Alan Stern <stern@rowland.harvard.edu>, 6 + * Andrea Parri <parri.andrea@gmail.com> 7 + * 8 + * An earlier version of this file appears in the companion webpage for 9 + * "Frightening small children and disconcerting grown-ups: Concurrency 10 + * in the Linux kernel" by Alglave, Maranget, McKenney, Parri, and Stern, 11 + * which is to appear in ASPLOS 2018. 12 + *) 13 + 14 + "Linux kernel memory model" 15 + 16 + enum Accesses = 'once (*READ_ONCE,WRITE_ONCE,ACCESS_ONCE*) || 17 + 'release (*smp_store_release*) || 18 + 'acquire (*smp_load_acquire*) || 19 + 'noreturn (* R of non-return RMW *) 20 + instructions R[{'once,'acquire,'noreturn}] 21 + instructions W[{'once,'release}] 22 + instructions RMW[{'once,'acquire,'release}] 23 + 24 + enum Barriers = 'wmb (*smp_wmb*) || 25 + 'rmb (*smp_rmb*) || 26 + 'mb (*smp_mb*) || 27 + 'rb_dep (*smp_read_barrier_depends*) || 28 + 'rcu-lock (*rcu_read_lock*) || 29 + 'rcu-unlock (*rcu_read_unlock*) || 30 + 'sync-rcu (*synchronize_rcu*) || 31 + 'before_atomic (*smp_mb__before_atomic*) || 32 + 'after_atomic (*smp_mb__after_atomic*) || 33 + 'after_spinlock (*smp_mb__after_spinlock*) 34 + instructions F[Barriers] 35 + 36 + (* Compute matching pairs of nested Rcu-lock and Rcu-unlock *) 37 + let matched = let rec 38 + unmatched-locks = Rcu-lock \ domain(matched) 39 + and unmatched-unlocks = Rcu-unlock \ range(matched) 40 + and unmatched = unmatched-locks | unmatched-unlocks 41 + and unmatched-po = [unmatched] ; po ; [unmatched] 42 + and unmatched-locks-to-unlocks = 43 + [unmatched-locks] ; po ; [unmatched-unlocks] 44 + and matched = matched | (unmatched-locks-to-unlocks \ 45 + (unmatched-po ; unmatched-po)) 46 + in matched 47 + 48 + (* Validate nesting *) 49 + flag ~empty Rcu-lock \ domain(matched) as unbalanced-rcu-locking 50 + flag ~empty Rcu-unlock \ range(matched) as unbalanced-rcu-locking 51 + 52 + (* Outermost level of nesting only *) 53 + let crit = matched \ (po^-1 ; matched ; po^-1)
+124
tools/memory-model/linux-kernel.cat
··· 1 + // SPDX-License-Identifier: GPL-2.0+ 2 + (* 3 + * Copyright (C) 2015 Jade Alglave <j.alglave@ucl.ac.uk>, 4 + * Copyright (C) 2016 Luc Maranget <luc.maranget@inria.fr> for Inria 5 + * Copyright (C) 2017 Alan Stern <stern@rowland.harvard.edu>, 6 + * Andrea Parri <parri.andrea@gmail.com> 7 + * 8 + * An earlier version of this file appears in the companion webpage for 9 + * "Frightening small children and disconcerting grown-ups: Concurrency 10 + * in the Linux kernel" by Alglave, Maranget, McKenney, Parri, and Stern, 11 + * which is to appear in ASPLOS 2018. 12 + *) 13 + 14 + "Linux kernel memory model" 15 + 16 + (* 17 + * File "lock.cat" handles locks and is experimental. 18 + * It can be replaced by include "cos.cat" for tests that do not use locks. 19 + *) 20 + 21 + include "lock.cat" 22 + 23 + (*******************) 24 + (* Basic relations *) 25 + (*******************) 26 + 27 + (* Fences *) 28 + let rb-dep = [R] ; fencerel(Rb_dep) ; [R] 29 + let rmb = [R \ Noreturn] ; fencerel(Rmb) ; [R \ Noreturn] 30 + let wmb = [W] ; fencerel(Wmb) ; [W] 31 + let mb = ([M] ; fencerel(Mb) ; [M]) | 32 + ([M] ; fencerel(Before_atomic) ; [RMW] ; po? ; [M]) | 33 + ([M] ; po? ; [RMW] ; fencerel(After_atomic) ; [M]) | 34 + ([M] ; po? ; [LKW] ; fencerel(After_spinlock) ; [M]) 35 + let gp = po ; [Sync-rcu] ; po? 36 + 37 + let strong-fence = mb | gp 38 + 39 + (* Release Acquire *) 40 + let acq-po = [Acquire] ; po ; [M] 41 + let po-rel = [M] ; po ; [Release] 42 + let rfi-rel-acq = [Release] ; rfi ; [Acquire] 43 + 44 + (**********************************) 45 + (* Fundamental coherence ordering *) 46 + (**********************************) 47 + 48 + (* Sequential Consistency Per Variable *) 49 + let com = rf | co | fr 50 + acyclic po-loc | com as coherence 51 + 52 + (* Atomic Read-Modify-Write *) 53 + empty rmw & (fre ; coe) as atomic 54 + 55 + (**********************************) 56 + (* Instruction execution ordering *) 57 + (**********************************) 58 + 59 + (* Preserved Program Order *) 60 + let dep = addr | data 61 + let rwdep = (dep | ctrl) ; [W] 62 + let overwrite = co | fr 63 + let to-w = rwdep | (overwrite & int) 64 + let rrdep = addr | (dep ; rfi) 65 + let strong-rrdep = rrdep+ & rb-dep 66 + let to-r = strong-rrdep | rfi-rel-acq 67 + let fence = strong-fence | wmb | po-rel | rmb | acq-po 68 + let ppo = rrdep* ; (to-r | to-w | fence) 69 + 70 + (* Propagation: Ordering from release operations and strong fences. *) 71 + let A-cumul(r) = rfe? ; r 72 + let cumul-fence = A-cumul(strong-fence | po-rel) | wmb 73 + let prop = (overwrite & ext)? ; cumul-fence* ; rfe? 74 + 75 + (* 76 + * Happens Before: Ordering from the passage of time. 77 + * No fences needed here for prop because relation confined to one process. 78 + *) 79 + let hb = ppo | rfe | ((prop \ id) & int) 80 + acyclic hb as happens-before 81 + 82 + (****************************************) 83 + (* Write and fence propagation ordering *) 84 + (****************************************) 85 + 86 + (* Propagation: Each non-rf link needs a strong fence. *) 87 + let pb = prop ; strong-fence ; hb* 88 + acyclic pb as propagation 89 + 90 + (*******) 91 + (* RCU *) 92 + (*******) 93 + 94 + (* 95 + * Effect of read-side critical section proceeds from the rcu_read_lock() 96 + * onward on the one hand and from the rcu_read_unlock() backwards on the 97 + * other hand. 98 + *) 99 + let rscs = po ; crit^-1 ; po? 100 + 101 + (* 102 + * The synchronize_rcu() strong fence is special in that it can order not 103 + * one but two non-rf relations, but only in conjunction with an RCU 104 + * read-side critical section. 105 + *) 106 + let link = hb* ; pb* ; prop 107 + 108 + (* Chains that affect the RCU grace-period guarantee *) 109 + let gp-link = gp ; link 110 + let rscs-link = rscs ; link 111 + 112 + (* 113 + * A cycle containing at least as many grace periods as RCU read-side 114 + * critical sections is forbidden. 115 + *) 116 + let rec rcu-path = 117 + gp-link | 118 + (gp-link ; rscs-link) | 119 + (rscs-link ; gp-link) | 120 + (rcu-path ; rcu-path) | 121 + (gp-link ; rcu-path ; rscs-link) | 122 + (rscs-link ; rcu-path ; gp-link) 123 + 124 + irreflexive rcu-path as rcu
+21
tools/memory-model/linux-kernel.cfg
··· 1 + macros linux-kernel.def 2 + bell linux-kernel.bell 3 + model linux-kernel.cat 4 + graph columns 5 + squished true 6 + showevents noregs 7 + movelabel true 8 + fontsize 8 9 + xscale 2.0 10 + yscale 1.5 11 + arrowsize 0.8 12 + showinitrf false 13 + showfinalrf false 14 + showinitwrites false 15 + splines spline 16 + pad 0.1 17 + edgeattr hb,color,indigo 18 + edgeattr co,color,blue 19 + edgeattr mb,color,darkgreen 20 + edgeattr wmb,color,darkgreen 21 + edgeattr rmb,color,darkgreen
+108
tools/memory-model/linux-kernel.def
··· 1 + // SPDX-License-Identifier: GPL-2.0+ 2 + // 3 + // An earlier version of this file appears in the companion webpage for 4 + // "Frightening small children and disconcerting grown-ups: Concurrency 5 + // in the Linux kernel" by Alglave, Maranget, McKenney, Parri, and Stern, 6 + // which is to appear in ASPLOS 2018. 7 + 8 + // ONCE 9 + READ_ONCE(X) __load{once}(X) 10 + WRITE_ONCE(X,V) { __store{once}(X,V); } 11 + 12 + // Release Acquire and friends 13 + smp_store_release(X,V) { __store{release}(*X,V); } 14 + smp_load_acquire(X) __load{acquire}(*X) 15 + rcu_assign_pointer(X,V) { __store{release}(X,V); } 16 + lockless_dereference(X) __load{lderef}(X) 17 + rcu_dereference(X) __load{deref}(X) 18 + 19 + // Fences 20 + smp_mb() { __fence{mb} ; } 21 + smp_rmb() { __fence{rmb} ; } 22 + smp_wmb() { __fence{wmb} ; } 23 + smp_read_barrier_depends() { __fence{rb_dep}; } 24 + smp_mb__before_atomic() { __fence{before_atomic} ; } 25 + smp_mb__after_atomic() { __fence{after_atomic} ; } 26 + smp_mb__after_spinlock() { __fence{after_spinlock} ; } 27 + 28 + // Exchange 29 + xchg(X,V) __xchg{mb}(X,V) 30 + xchg_relaxed(X,V) __xchg{once}(X,V) 31 + xchg_release(X,V) __xchg{release}(X,V) 32 + xchg_acquire(X,V) __xchg{acquire}(X,V) 33 + cmpxchg(X,V,W) __cmpxchg{mb}(X,V,W) 34 + cmpxchg_relaxed(X,V,W) __cmpxchg{once}(X,V,W) 35 + cmpxchg_acquire(X,V,W) __cmpxchg{acquire}(X,V,W) 36 + cmpxchg_release(X,V,W) __cmpxchg{release}(X,V,W) 37 + 38 + // Spinlocks 39 + spin_lock(X) { __lock(X) ; } 40 + spin_unlock(X) { __unlock(X) ; } 41 + spin_trylock(X) __trylock(X) 42 + 43 + // RCU 44 + rcu_read_lock() { __fence{rcu-lock}; } 45 + rcu_read_unlock() { __fence{rcu-unlock};} 46 + synchronize_rcu() { __fence{sync-rcu}; } 47 + synchronize_rcu_expedited() { __fence{sync-rcu}; } 48 + 49 + // Atomic 50 + atomic_read(X) READ_ONCE(*X) 51 + atomic_set(X,V) { WRITE_ONCE(*X,V) ; } 52 + atomic_read_acquire(X) smp_load_acquire(X) 53 + atomic_set_release(X,V) { smp_store_release(X,V); } 54 + 55 + atomic_add(V,X) { __atomic_op(X,+,V) ; } 56 + atomic_sub(V,X) { __atomic_op(X,-,V) ; } 57 + atomic_inc(X) { __atomic_op(X,+,1) ; } 58 + atomic_dec(X) { __atomic_op(X,-,1) ; } 59 + 60 + atomic_add_return(V,X) __atomic_op_return{mb}(X,+,V) 61 + atomic_add_return_relaxed(V,X) __atomic_op_return{once}(X,+,V) 62 + atomic_add_return_acquire(V,X) __atomic_op_return{acquire}(X,+,V) 63 + atomic_add_return_release(V,X) __atomic_op_return{release}(X,+,V) 64 + atomic_fetch_add(V,X) __atomic_fetch_op{mb}(X,+,V) 65 + atomic_fetch_add_relaxed(V,X) __atomic_fetch_op{once}(X,+,V) 66 + atomic_fetch_add_acquire(V,X) __atomic_fetch_op{acquire}(X,+,V) 67 + atomic_fetch_add_release(V,X) __atomic_fetch_op{release}(X,+,V) 68 + 69 + atomic_inc_return(X) __atomic_op_return{mb}(X,+,1) 70 + atomic_inc_return_relaxed(X) __atomic_op_return{once}(X,+,1) 71 + atomic_inc_return_acquire(X) __atomic_op_return{acquire}(X,+,1) 72 + atomic_inc_return_release(X) __atomic_op_return{release}(X,+,1) 73 + atomic_fetch_inc(X) __atomic_fetch_op{mb}(X,+,1) 74 + atomic_fetch_inc_relaxed(X) __atomic_fetch_op{once}(X,+,1) 75 + atomic_fetch_inc_acquire(X) __atomic_fetch_op{acquire}(X,+,1) 76 + atomic_fetch_inc_release(X) __atomic_fetch_op{release}(X,+,1) 77 + 78 + atomic_sub_return(V,X) __atomic_op_return{mb}(X,-,V) 79 + atomic_sub_return_relaxed(V,X) __atomic_op_return{once}(X,-,V) 80 + atomic_sub_return_acquire(V,X) __atomic_op_return{acquire}(X,-,V) 81 + atomic_sub_return_release(V,X) __atomic_op_return{release}(X,-,V) 82 + atomic_fetch_sub(V,X) __atomic_fetch_op{mb}(X,-,V) 83 + atomic_fetch_sub_relaxed(V,X) __atomic_fetch_op{once}(X,-,V) 84 + atomic_fetch_sub_acquire(V,X) __atomic_fetch_op{acquire}(X,-,V) 85 + atomic_fetch_sub_release(V,X) __atomic_fetch_op{release}(X,-,V) 86 + 87 + atomic_dec_return(X) __atomic_op_return{mb}(X,-,1) 88 + atomic_dec_return_relaxed(X) __atomic_op_return{once}(X,-,1) 89 + atomic_dec_return_acquire(X) __atomic_op_return{acquire}(X,-,1) 90 + atomic_dec_return_release(X) __atomic_op_return{release}(X,-,1) 91 + atomic_fetch_dec(X) __atomic_fetch_op{mb}(X,-,1) 92 + atomic_fetch_dec_relaxed(X) __atomic_fetch_op{once}(X,-,1) 93 + atomic_fetch_dec_acquire(X) __atomic_fetch_op{acquire}(X,-,1) 94 + atomic_fetch_dec_release(X) __atomic_fetch_op{release}(X,-,1) 95 + 96 + atomic_xchg(X,V) __xchg{mb}(X,V) 97 + atomic_xchg_relaxed(X,V) __xchg{once}(X,V) 98 + atomic_xchg_release(X,V) __xchg{release}(X,V) 99 + atomic_xchg_acquire(X,V) __xchg{acquire}(X,V) 100 + atomic_cmpxchg(X,V,W) __cmpxchg{mb}(X,V,W) 101 + atomic_cmpxchg_relaxed(X,V,W) __cmpxchg{once}(X,V,W) 102 + atomic_cmpxchg_acquire(X,V,W) __cmpxchg{acquire}(X,V,W) 103 + atomic_cmpxchg_release(X,V,W) __cmpxchg{release}(X,V,W) 104 + 105 + atomic_sub_and_test(V,X) __atomic_op_return{mb}(X,-,V) == 0 106 + atomic_dec_and_test(X) __atomic_op_return{mb}(X,-,1) == 0 107 + atomic_inc_and_test(X) __atomic_op_return{mb}(X,+,1) == 0 108 + atomic_add_negative(V,X) __atomic_op_return{mb}(X,+,V) < 0
+19
tools/memory-model/litmus-tests/CoRR+poonceonce+Once.litmus
··· 1 + C CoRR+poonceonce+Once 2 + 3 + {} 4 + 5 + P0(int *x) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + } 9 + 10 + P1(int *x) 11 + { 12 + int r0; 13 + int r1; 14 + 15 + r0 = READ_ONCE(*x); 16 + r1 = READ_ONCE(*x); 17 + } 18 + 19 + exists (1:r0=1 /\ 1:r1=0)
+18
tools/memory-model/litmus-tests/CoRW+poonceonce+Once.litmus
··· 1 + C CoRW+poonceonce+Once 2 + 3 + {} 4 + 5 + P0(int *x) 6 + { 7 + int r0; 8 + 9 + r0 = READ_ONCE(*x); 10 + WRITE_ONCE(*x, 1); 11 + } 12 + 13 + P1(int *x) 14 + { 15 + WRITE_ONCE(*x, 2); 16 + } 17 + 18 + exists (x=2 /\ 0:r0=2)
+18
tools/memory-model/litmus-tests/CoWR+poonceonce+Once.litmus
··· 1 + C CoWR+poonceonce+Once 2 + 3 + {} 4 + 5 + P0(int *x) 6 + { 7 + int r0; 8 + 9 + WRITE_ONCE(*x, 1); 10 + r0 = READ_ONCE(*x); 11 + } 12 + 13 + P1(int *x) 14 + { 15 + WRITE_ONCE(*x, 2); 16 + } 17 + 18 + exists (x=1 /\ 0:r0=2)
+11
tools/memory-model/litmus-tests/CoWW+poonceonce.litmus
··· 1 + C CoWW+poonceonce 2 + 3 + {} 4 + 5 + P0(int *x) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + WRITE_ONCE(*x, 2); 9 + } 10 + 11 + exists (x=1)
+35
tools/memory-model/litmus-tests/IRIW+mbonceonces+OnceOnce.litmus
··· 1 + C IRIW+mbonceonces+OnceOnce 2 + 3 + {} 4 + 5 + P0(int *x) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + } 9 + 10 + P1(int *x, int *y) 11 + { 12 + int r0; 13 + int r1; 14 + 15 + r0 = READ_ONCE(*x); 16 + smp_mb(); 17 + r1 = READ_ONCE(*y); 18 + } 19 + 20 + P2(int *y) 21 + { 22 + WRITE_ONCE(*y, 1); 23 + } 24 + 25 + P3(int *x, int *y) 26 + { 27 + int r0; 28 + int r1; 29 + 30 + r0 = READ_ONCE(*y); 31 + smp_mb(); 32 + r1 = READ_ONCE(*x); 33 + } 34 + 35 + exists (1:r0=1 /\ 1:r1=0 /\ 3:r0=1 /\ 3:r1=0)
+33
tools/memory-model/litmus-tests/IRIW+poonceonces+OnceOnce.litmus
··· 1 + C IRIW+poonceonces+OnceOnce 2 + 3 + {} 4 + 5 + P0(int *x) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + } 9 + 10 + P1(int *x, int *y) 11 + { 12 + int r0; 13 + int r1; 14 + 15 + r0 = READ_ONCE(*x); 16 + r1 = READ_ONCE(*y); 17 + } 18 + 19 + P2(int *y) 20 + { 21 + WRITE_ONCE(*y, 1); 22 + } 23 + 24 + P3(int *x, int *y) 25 + { 26 + int r0; 27 + int r1; 28 + 29 + r0 = READ_ONCE(*y); 30 + r1 = READ_ONCE(*x); 31 + } 32 + 33 + exists (1:r0=1 /\ 1:r1=0 /\ 3:r0=1 /\ 3:r1=0)
+28
tools/memory-model/litmus-tests/ISA2+poonceonces.litmus
··· 1 + C ISA2+poonceonces 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + WRITE_ONCE(*y, 1); 9 + } 10 + 11 + P1(int *y, int *z) 12 + { 13 + int r0; 14 + 15 + r0 = READ_ONCE(*y); 16 + WRITE_ONCE(*z, 1); 17 + } 18 + 19 + P2(int *x, int *z) 20 + { 21 + int r0; 22 + int r1; 23 + 24 + r0 = READ_ONCE(*z); 25 + r1 = READ_ONCE(*x); 26 + } 27 + 28 + exists (1:r0=1 /\ 2:r0=1 /\ 2:r1=0)
+28
tools/memory-model/litmus-tests/ISA2+pooncerelease+poacquirerelease+poacquireonce.litmus
··· 1 + C ISA2+pooncerelease+poacquirerelease+poacquireonce 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + smp_store_release(y, 1); 9 + } 10 + 11 + P1(int *y, int *z) 12 + { 13 + int r0; 14 + 15 + r0 = smp_load_acquire(y); 16 + smp_store_release(z, 1); 17 + } 18 + 19 + P2(int *x, int *z) 20 + { 21 + int r0; 22 + int r1; 23 + 24 + r0 = smp_load_acquire(z); 25 + r1 = READ_ONCE(*x); 26 + } 27 + 28 + exists (1:r0=1 /\ 2:r0=1 /\ 2:r1=0)
+23
tools/memory-model/litmus-tests/LB+ctrlonceonce+mbonceonce.litmus
··· 1 + C LB+ctrlonceonce+mbonceonce 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + int r0; 8 + 9 + r0 = READ_ONCE(*x); 10 + if (r0) 11 + WRITE_ONCE(*y, 1); 12 + } 13 + 14 + P1(int *x, int *y) 15 + { 16 + int r0; 17 + 18 + r0 = READ_ONCE(*y); 19 + smp_mb(); 20 + WRITE_ONCE(*x, 1); 21 + } 22 + 23 + exists (0:r0=1 /\ 1:r0=1)
+21
tools/memory-model/litmus-tests/LB+poacquireonce+pooncerelease.litmus
··· 1 + C LB+poacquireonce+pooncerelease 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + int r0; 8 + 9 + r0 = READ_ONCE(*x); 10 + smp_store_release(y, 1); 11 + } 12 + 13 + P1(int *x, int *y) 14 + { 15 + int r0; 16 + 17 + r0 = smp_load_acquire(y); 18 + WRITE_ONCE(*x, 1); 19 + } 20 + 21 + exists (0:r0=1 /\ 1:r0=1)
+21
tools/memory-model/litmus-tests/LB+poonceonces.litmus
··· 1 + C LB+poonceonces 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + int r0; 8 + 9 + r0 = READ_ONCE(*x); 10 + WRITE_ONCE(*y, 1); 11 + } 12 + 13 + P1(int *x, int *y) 14 + { 15 + int r0; 16 + 17 + r0 = READ_ONCE(*y); 18 + WRITE_ONCE(*x, 1); 19 + } 20 + 21 + exists (0:r0=1 /\ 1:r0=1)
+25
tools/memory-model/litmus-tests/MP+onceassign+derefonce.litmus
··· 1 + C MP+onceassign+derefonce.litmus 2 + 3 + { 4 + y=z; 5 + z=0; 6 + } 7 + 8 + P0(int *x, int **y) 9 + { 10 + WRITE_ONCE(*x, 1); 11 + rcu_assign_pointer(*y, x); 12 + } 13 + 14 + P1(int *x, int **y) 15 + { 16 + int *r0; 17 + int r1; 18 + 19 + rcu_read_lock(); 20 + r0 = rcu_dereference(*y); 21 + r1 = READ_ONCE(*r0); 22 + rcu_read_unlock(); 23 + } 24 + 25 + exists (1:r0=x /\ 1:r1=0)
+24
tools/memory-model/litmus-tests/MP+polocks.litmus
··· 1 + C MP+polocks 2 + 3 + {} 4 + 5 + P0(int *x, int *y, spinlock_t *mylock) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + spin_lock(mylock); 9 + WRITE_ONCE(*y, 1); 10 + spin_unlock(mylock); 11 + } 12 + 13 + P1(int *x, int *y, spinlock_t *mylock) 14 + { 15 + int r0; 16 + int r1; 17 + 18 + spin_lock(mylock); 19 + r0 = READ_ONCE(*y); 20 + spin_unlock(mylock); 21 + r1 = READ_ONCE(*x); 22 + } 23 + 24 + exists (1:r0=1 /\ 1:r1=0)
+20
tools/memory-model/litmus-tests/MP+poonceonces.litmus
··· 1 + C MP+poonceonces 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + WRITE_ONCE(*y, 1); 9 + } 10 + 11 + P1(int *x, int *y) 12 + { 13 + int r0; 14 + int r1; 15 + 16 + r0 = READ_ONCE(*y); 17 + r1 = READ_ONCE(*x); 18 + } 19 + 20 + exists (1:r0=1 /\ 1:r1=0)
+20
tools/memory-model/litmus-tests/MP+pooncerelease+poacquireonce.litmus
··· 1 + C MP+pooncerelease+poacquireonce 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + smp_store_release(y, 1); 9 + } 10 + 11 + P1(int *x, int *y) 12 + { 13 + int r0; 14 + int r1; 15 + 16 + r0 = smp_load_acquire(y); 17 + r1 = READ_ONCE(*x); 18 + } 19 + 20 + exists (1:r0=1 /\ 1:r1=0)
+24
tools/memory-model/litmus-tests/MP+porevlocks.litmus
··· 1 + C MP+porevlocks 2 + 3 + {} 4 + 5 + P0(int *x, int *y, spinlock_t *mylock) 6 + { 7 + int r0; 8 + int r1; 9 + 10 + r0 = READ_ONCE(*y); 11 + spin_lock(mylock); 12 + r1 = READ_ONCE(*x); 13 + spin_unlock(mylock); 14 + } 15 + 16 + P1(int *x, int *y, spinlock_t *mylock) 17 + { 18 + spin_lock(mylock); 19 + WRITE_ONCE(*x, 1); 20 + spin_unlock(mylock); 21 + WRITE_ONCE(*y, 1); 22 + } 23 + 24 + exists (0:r0=1 /\ 0:r1=0)
+22
tools/memory-model/litmus-tests/MP+wmbonceonce+rmbonceonce.litmus
··· 1 + C MP+wmbonceonce+rmbonceonce 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + smp_wmb(); 9 + WRITE_ONCE(*y, 1); 10 + } 11 + 12 + P1(int *x, int *y) 13 + { 14 + int r0; 15 + int r1; 16 + 17 + r0 = READ_ONCE(*y); 18 + smp_rmb(); 19 + r1 = READ_ONCE(*x); 20 + } 21 + 22 + exists (1:r0=1 /\ 1:r1=0)
+21
tools/memory-model/litmus-tests/R+mbonceonces.litmus
··· 1 + C R+mbonceonces 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + smp_mb(); 9 + WRITE_ONCE(*y, 1); 10 + } 11 + 12 + P1(int *x, int *y) 13 + { 14 + int r0; 15 + 16 + WRITE_ONCE(*y, 2); 17 + smp_mb(); 18 + r0 = READ_ONCE(*x); 19 + } 20 + 21 + exists (y=2 /\ 1:r0=0)
+19
tools/memory-model/litmus-tests/R+poonceonces.litmus
··· 1 + C R+poonceonces 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + WRITE_ONCE(*y, 1); 9 + } 10 + 11 + P1(int *x, int *y) 12 + { 13 + int r0; 14 + 15 + WRITE_ONCE(*y, 2); 16 + r0 = READ_ONCE(*x); 17 + } 18 + 19 + exists (y=2 /\ 1:r0=0)
+125
tools/memory-model/litmus-tests/README
··· 1 + This directory contains the following litmus tests: 2 + 3 + CoRR+poonceonce+Once.litmus 4 + Test of read-read coherence, that is, whether or not two 5 + successive reads from the same variable are ordered. 6 + 7 + CoRW+poonceonce+Once.litmus 8 + Test of read-write coherence, that is, whether or not a read 9 + from a given variable followed by a write to that same variable 10 + are ordered. 11 + 12 + CoWR+poonceonce+Once.litmus 13 + Test of write-read coherence, that is, whether or not a write 14 + to a given variable followed by a read from that same variable 15 + are ordered. 16 + 17 + CoWW+poonceonce.litmus 18 + Test of write-write coherence, that is, whether or not two 19 + successive writes to the same variable are ordered. 20 + 21 + IRIW+mbonceonces+OnceOnce.litmus 22 + Test of independent reads from independent writes with smp_mb() 23 + between each pairs of reads. In other words, is smp_mb() 24 + sufficient to cause two different reading processes to agree on 25 + the order of a pair of writes, where each write is to a different 26 + variable by a different process. 27 + 28 + IRIW+poonceonces+OnceOnce.litmus 29 + Test of independent reads from independent writes with nothing 30 + between each pairs of reads. In other words, is anything at all 31 + needed to cause two different reading processes to agree on the 32 + order of a pair of writes, where each write is to a different 33 + variable by a different process. 34 + 35 + ISA2+poonceonces.litmus 36 + As below, but with store-release replaced with WRITE_ONCE() 37 + and load-acquire replaced with READ_ONCE(). 38 + 39 + ISA2+pooncerelease+poacquirerelease+poacquireonce.litmus 40 + Can a release-acquire chain order a prior store against 41 + a later load? 42 + 43 + LB+ctrlonceonce+mbonceonce.litmus 44 + Does a control dependency and an smp_mb() suffice for the 45 + load-buffering litmus test, where each process reads from one 46 + of two variables then writes to the other? 47 + 48 + LB+poacquireonce+pooncerelease.litmus 49 + Does a release-acquire pair suffice for the load-buffering 50 + litmus test, where each process reads from one of two variables then 51 + writes to the other? 52 + 53 + LB+poonceonces.litmus 54 + As above, but with store-release replaced with WRITE_ONCE() 55 + and load-acquire replaced with READ_ONCE(). 56 + 57 + MP+onceassign+derefonce.litmus 58 + As below, but with rcu_assign_pointer() and an rcu_dereference(). 59 + 60 + MP+polocks.litmus 61 + As below, but with the second access of the writer process 62 + and the first access of reader process protected by a lock. 63 + 64 + MP+poonceonces.litmus 65 + As below, but without the smp_rmb() and smp_wmb(). 66 + 67 + MP+pooncerelease+poacquireonce.litmus 68 + As below, but with a release-acquire chain. 69 + 70 + MP+porevlocks.litmus 71 + As below, but with the first access of the writer process 72 + and the second access of reader process protected by a lock. 73 + 74 + MP+wmbonceonce+rmbonceonce.litmus 75 + Does a smp_wmb() (between the stores) and an smp_rmb() (between 76 + the loads) suffice for the message-passing litmus test, where one 77 + process writes data and then a flag, and the other process reads 78 + the flag and then the data. (This is similar to the ISA2 tests, 79 + but with two processes instead of three.) 80 + 81 + R+mbonceonces.litmus 82 + This is the fully ordered (via smp_mb()) version of one of 83 + the classic counterintuitive litmus tests that illustrates the 84 + effects of store propagation delays. 85 + 86 + R+poonceonces.litmus 87 + As above, but without the smp_mb() invocations. 88 + 89 + SB+mbonceonces.litmus 90 + This is the fully ordered (again, via smp_mb() version of store 91 + buffering, which forms the core of Dekker's mutual-exclusion 92 + algorithm. 93 + 94 + SB+poonceonces.litmus 95 + As above, but without the smp_mb() invocations. 96 + 97 + S+poonceonces.litmus 98 + As below, but without the smp_wmb() and acquire load. 99 + 100 + S+wmbonceonce+poacquireonce.litmus 101 + Can a smp_wmb(), instead of a release, and an acquire order 102 + a prior store against a subsequent store? 103 + 104 + WRC+poonceonces+Once.litmus 105 + WRC+pooncerelease+rmbonceonce+Once.litmus 106 + These two are members of an extension of the MP litmus-test class 107 + in which the first write is moved to a separate process. 108 + 109 + Z6.0+pooncelock+pooncelock+pombonce.litmus 110 + Is the ordering provided by a spin_unlock() and a subsequent 111 + spin_lock() sufficient to make ordering apparent to accesses 112 + by a process not holding the lock? 113 + 114 + Z6.0+pooncelock+poonceLock+pombonce.litmus 115 + As above, but with smp_mb__after_spinlock() immediately 116 + following the spin_lock(). 117 + 118 + Z6.0+pooncerelease+poacquirerelease+mbonceonce.litmus 119 + Is the ordering provided by a release-acquire chain sufficient 120 + to make ordering apparent to accesses by a process that does 121 + not participate in that release-acquire chain? 122 + 123 + A great many more litmus tests are available here: 124 + 125 + https://github.com/paulmckrcu/litmus
+19
tools/memory-model/litmus-tests/S+poonceonces.litmus
··· 1 + C S+poonceonces 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + WRITE_ONCE(*x, 2); 8 + WRITE_ONCE(*y, 1); 9 + } 10 + 11 + P1(int *x, int *y) 12 + { 13 + int r0; 14 + 15 + r0 = READ_ONCE(*y); 16 + WRITE_ONCE(*x, 1); 17 + } 18 + 19 + exists (x=2 /\ 1:r0=1)
+20
tools/memory-model/litmus-tests/S+wmbonceonce+poacquireonce.litmus
··· 1 + C S+wmbonceonce+poacquireonce 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + WRITE_ONCE(*x, 2); 8 + smp_wmb(); 9 + WRITE_ONCE(*y, 1); 10 + } 11 + 12 + P1(int *x, int *y) 13 + { 14 + int r0; 15 + 16 + r0 = smp_load_acquire(y); 17 + WRITE_ONCE(*x, 1); 18 + } 19 + 20 + exists (x=2 /\ 1:r0=1)
+23
tools/memory-model/litmus-tests/SB+mbonceonces.litmus
··· 1 + C SB+mbonceonces 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + int r0; 8 + 9 + WRITE_ONCE(*x, 1); 10 + smp_mb(); 11 + r0 = READ_ONCE(*y); 12 + } 13 + 14 + P1(int *x, int *y) 15 + { 16 + int r0; 17 + 18 + WRITE_ONCE(*y, 1); 19 + smp_mb(); 20 + r0 = READ_ONCE(*x); 21 + } 22 + 23 + exists (0:r0=0 /\ 1:r0=0)
+21
tools/memory-model/litmus-tests/SB+poonceonces.litmus
··· 1 + C SB+poonceonces 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + int r0; 8 + 9 + WRITE_ONCE(*x, 1); 10 + r0 = READ_ONCE(*y); 11 + } 12 + 13 + P1(int *x, int *y) 14 + { 15 + int r0; 16 + 17 + WRITE_ONCE(*y, 1); 18 + r0 = READ_ONCE(*x); 19 + } 20 + 21 + exists (0:r0=0 /\ 1:r0=0)
+27
tools/memory-model/litmus-tests/WRC+poonceonces+Once.litmus
··· 1 + C WRC+poonceonces+Once 2 + 3 + {} 4 + 5 + P0(int *x) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + } 9 + 10 + P1(int *x, int *y) 11 + { 12 + int r0; 13 + 14 + r0 = READ_ONCE(*x); 15 + WRITE_ONCE(*y, 1); 16 + } 17 + 18 + P2(int *x, int *y) 19 + { 20 + int r0; 21 + int r1; 22 + 23 + r0 = READ_ONCE(*y); 24 + r1 = READ_ONCE(*x); 25 + } 26 + 27 + exists (1:r0=1 /\ 2:r0=1 /\ 2:r1=0)
+28
tools/memory-model/litmus-tests/WRC+pooncerelease+rmbonceonce+Once.litmus
··· 1 + C WRC+pooncerelease+rmbonceonce+Once 2 + 3 + {} 4 + 5 + P0(int *x) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + } 9 + 10 + P1(int *x, int *y) 11 + { 12 + int r0; 13 + 14 + r0 = READ_ONCE(*x); 15 + smp_store_release(y, 1); 16 + } 17 + 18 + P2(int *x, int *y) 19 + { 20 + int r0; 21 + int r1; 22 + 23 + r0 = READ_ONCE(*y); 24 + smp_rmb(); 25 + r1 = READ_ONCE(*x); 26 + } 27 + 28 + exists (1:r0=1 /\ 2:r0=1 /\ 2:r1=0)
+33
tools/memory-model/litmus-tests/Z6.0+pooncelock+poonceLock+pombonce.litmus
··· 1 + C Z6.0+pooncelock+poonceLock+pombonce 2 + 3 + {} 4 + 5 + P0(int *x, int *y, spinlock_t *mylock) 6 + { 7 + spin_lock(mylock); 8 + WRITE_ONCE(*x, 1); 9 + WRITE_ONCE(*y, 1); 10 + spin_unlock(mylock); 11 + } 12 + 13 + P1(int *y, int *z, spinlock_t *mylock) 14 + { 15 + int r0; 16 + 17 + spin_lock(mylock); 18 + smp_mb__after_spinlock(); 19 + r0 = READ_ONCE(*y); 20 + WRITE_ONCE(*z, 1); 21 + spin_unlock(mylock); 22 + } 23 + 24 + P2(int *x, int *z) 25 + { 26 + int r1; 27 + 28 + WRITE_ONCE(*z, 2); 29 + smp_mb(); 30 + r1 = READ_ONCE(*x); 31 + } 32 + 33 + exists (1:r0=1 /\ z=2 /\ 2:r1=0)
+32
tools/memory-model/litmus-tests/Z6.0+pooncelock+pooncelock+pombonce.litmus
··· 1 + C Z6.0+pooncelock+pooncelock+pombonce 2 + 3 + {} 4 + 5 + P0(int *x, int *y, spinlock_t *mylock) 6 + { 7 + spin_lock(mylock); 8 + WRITE_ONCE(*x, 1); 9 + WRITE_ONCE(*y, 1); 10 + spin_unlock(mylock); 11 + } 12 + 13 + P1(int *y, int *z, spinlock_t *mylock) 14 + { 15 + int r0; 16 + 17 + spin_lock(mylock); 18 + r0 = READ_ONCE(*y); 19 + WRITE_ONCE(*z, 1); 20 + spin_unlock(mylock); 21 + } 22 + 23 + P2(int *x, int *z) 24 + { 25 + int r1; 26 + 27 + WRITE_ONCE(*z, 2); 28 + smp_mb(); 29 + r1 = READ_ONCE(*x); 30 + } 31 + 32 + exists (1:r0=1 /\ z=2 /\ 2:r1=0)
+28
tools/memory-model/litmus-tests/Z6.0+pooncerelease+poacquirerelease+mbonceonce.litmus
··· 1 + C Z6.0+pooncerelease+poacquirerelease+mbonceonce 2 + 3 + {} 4 + 5 + P0(int *x, int *y) 6 + { 7 + WRITE_ONCE(*x, 1); 8 + smp_store_release(y, 1); 9 + } 10 + 11 + P1(int *y, int *z) 12 + { 13 + int r0; 14 + 15 + r0 = smp_load_acquire(y); 16 + smp_store_release(z, 1); 17 + } 18 + 19 + P2(int *x, int *z) 20 + { 21 + int r1; 22 + 23 + WRITE_ONCE(*z, 2); 24 + smp_mb(); 25 + r1 = READ_ONCE(*x); 26 + } 27 + 28 + exists (1:r0=1 /\ z=2 /\ 2:r1=0)
+99
tools/memory-model/lock.cat
··· 1 + // SPDX-License-Identifier: GPL-2.0+ 2 + (* 3 + * Copyright (C) 2016 Luc Maranget <luc.maranget@inria.fr> for Inria 4 + * Copyright (C) 2017 Alan Stern <stern@rowland.harvard.edu> 5 + *) 6 + 7 + (* Generate coherence orders and handle lock operations *) 8 + 9 + include "cross.cat" 10 + 11 + (* From lock reads to their partner lock writes *) 12 + let lk-rmw = ([LKR] ; po-loc ; [LKW]) \ (po ; po) 13 + let rmw = rmw | lk-rmw 14 + 15 + (* 16 + * A paired LKR must always see an unlocked value; spin_lock() calls nested 17 + * inside a critical section (for the same lock) always deadlock. 18 + *) 19 + empty ([LKW] ; po-loc ; [domain(lk-rmw)]) \ (po-loc ; [UL] ; po-loc) 20 + as lock-nest 21 + 22 + (* The litmus test is invalid if an LKW event is not part of an RMW pair *) 23 + flag ~empty LKW \ range(lk-rmw) as unpaired-LKW 24 + 25 + (* This will be allowed if we implement spin_is_locked() *) 26 + flag ~empty LKR \ domain(lk-rmw) as unpaired-LKR 27 + 28 + (* There should be no R or W accesses to spinlocks *) 29 + let ALL-LOCKS = LKR | LKW | UL | LF 30 + flag ~empty [M \ IW] ; loc ; [ALL-LOCKS] as mixed-lock-accesses 31 + 32 + (* The final value of a spinlock should not be tested *) 33 + flag ~empty [FW] ; loc ; [ALL-LOCKS] as lock-final 34 + 35 + 36 + (* 37 + * Put lock operations in their appropriate classes, but leave UL out of W 38 + * until after the co relation has been generated. 39 + *) 40 + let R = R | LKR | LF 41 + let W = W | LKW 42 + 43 + let Release = Release | UL 44 + let Acquire = Acquire | LKR 45 + 46 + 47 + (* Match LKW events to their corresponding UL events *) 48 + let critical = ([LKW] ; po-loc ; [UL]) \ (po-loc ; [LKW | UL] ; po-loc) 49 + 50 + flag ~empty UL \ range(critical) as unmatched-unlock 51 + 52 + (* Allow up to one unmatched LKW per location; more must deadlock *) 53 + let UNMATCHED-LKW = LKW \ domain(critical) 54 + empty ([UNMATCHED-LKW] ; loc ; [UNMATCHED-LKW]) \ id as unmatched-locks 55 + 56 + 57 + (* rfi for LF events: link each LKW to the LF events in its critical section *) 58 + let rfi-lf = ([LKW] ; po-loc ; [LF]) \ ([LKW] ; po-loc ; [UL] ; po-loc) 59 + 60 + (* rfe for LF events *) 61 + let all-possible-rfe-lf = 62 + (* 63 + * Given an LF event r, compute the possible rfe edges for that event 64 + * (all those starting from LKW events in other threads), 65 + * and then convert that relation to a set of single-edge relations. 66 + *) 67 + let possible-rfe-lf r = 68 + let pair-to-relation p = p ++ 0 69 + in map pair-to-relation ((LKW * {r}) & loc & ext) 70 + (* Do this for each LF event r that isn't in rfi-lf *) 71 + in map possible-rfe-lf (LF \ range(rfi-lf)) 72 + 73 + (* Generate all rf relations for LF events *) 74 + with rfe-lf from cross(all-possible-rfe-lf) 75 + let rf = rf | rfi-lf | rfe-lf 76 + 77 + 78 + (* Generate all co relations, including LKW events but not UL *) 79 + let co0 = co0 | ([IW] ; loc ; [LKW]) | 80 + (([LKW] ; loc ; [UNMATCHED-LKW]) \ [UNMATCHED-LKW]) 81 + include "cos-opt.cat" 82 + let W = W | UL 83 + let M = R | W 84 + 85 + (* Merge UL events into co *) 86 + let co = (co | critical | (critical^-1 ; co))+ 87 + let coe = co & ext 88 + let coi = co & int 89 + 90 + (* Merge LKR events into rf *) 91 + let rf = rf | ([IW | UL] ; singlestep(co) ; lk-rmw^-1) 92 + let rfe = rf & ext 93 + let rfi = rf & int 94 + 95 + let fr = rf^-1 ; co 96 + let fre = fr & ext 97 + let fri = fr & int 98 + 99 + show co,rf,fr