Back to home page

OSCL-LXR

 
 

    


0001 Linux-Kernel Memory Model Litmus Tests
0002 ======================================
0003 
0004 This file describes the LKMM litmus-test format by example, describes
0005 some tricks and traps, and finally outlines LKMM's limitations.  Earlier
0006 versions of this material appeared in a number of LWN articles, including:
0007 
0008 https://lwn.net/Articles/720550/
0009         A formal kernel memory-ordering model (part 2)
0010 https://lwn.net/Articles/608550/
0011         Axiomatic validation of memory barriers and atomic instructions
0012 https://lwn.net/Articles/470681/
0013         Validating Memory Barriers and Atomic Instructions
0014 
0015 This document presents information in decreasing order of applicability,
0016 so that, where possible, the information that has proven more commonly
0017 useful is shown near the beginning.
0018 
0019 For information on installing LKMM, including the underlying "herd7"
0020 tool, please see tools/memory-model/README.
0021 
0022 
0023 Copy-Pasta
0024 ==========
0025 
0026 As with other software, it is often better (if less macho) to adapt an
0027 existing litmus test than it is to create one from scratch.  A number
0028 of litmus tests may be found in the kernel source tree:
0029 
0030         tools/memory-model/litmus-tests/
0031         Documentation/litmus-tests/
0032 
0033 Several thousand more example litmus tests are available on github
0034 and kernel.org:
0035 
0036         https://github.com/paulmckrcu/litmus
0037         https://git.kernel.org/pub/scm/linux/kernel/git/paulmck/perfbook.git/tree/CodeSamples/formal/herd
0038         https://git.kernel.org/pub/scm/linux/kernel/git/paulmck/perfbook.git/tree/CodeSamples/formal/litmus
0039 
0040 The -l and -L arguments to "git grep" can be quite helpful in identifying
0041 existing litmus tests that are similar to the one you need.  But even if
0042 you start with an existing litmus test, it is still helpful to have a
0043 good understanding of the litmus-test format.
0044 
0045 
0046 Examples and Format
0047 ===================
0048 
0049 This section describes the overall format of litmus tests, starting
0050 with a small example of the message-passing pattern and moving on to
0051 more complex examples that illustrate explicit initialization and LKMM's
0052 minimalistic set of flow-control statements.
0053 
0054 
0055 Message-Passing Example
0056 -----------------------
0057 
0058 This section gives an overview of the format of a litmus test using an
0059 example based on the common message-passing use case.  This use case
0060 appears often in the Linux kernel.  For example, a flag (modeled by "y"
0061 below) indicates that a buffer (modeled by "x" below) is now completely
0062 filled in and ready for use.  It would be very bad if the consumer saw the
0063 flag set, but, due to memory misordering, saw old values in the buffer.
0064 
0065 This example asks whether smp_store_release() and smp_load_acquire()
0066 suffices to avoid this bad outcome:
0067 
0068  1 C MP+pooncerelease+poacquireonce
0069  2
0070  3 {}
0071  4
0072  5 P0(int *x, int *y)
0073  6 {
0074  7   WRITE_ONCE(*x, 1);
0075  8   smp_store_release(y, 1);
0076  9 }
0077 10
0078 11 P1(int *x, int *y)
0079 12 {
0080 13   int r0;
0081 14   int r1;
0082 15
0083 16   r0 = smp_load_acquire(y);
0084 17   r1 = READ_ONCE(*x);
0085 18 }
0086 19
0087 20 exists (1:r0=1 /\ 1:r1=0)
0088 
0089 Line 1 starts with "C", which identifies this file as being in the
0090 LKMM C-language format (which, as we will see, is a small fragment
0091 of the full C language).  The remainder of line 1 is the name of
0092 the test, which by convention is the filename with the ".litmus"
0093 suffix stripped.  In this case, the actual test may be found in
0094 tools/memory-model/litmus-tests/MP+pooncerelease+poacquireonce.litmus
0095 in the Linux-kernel source tree.
0096 
0097 Mechanically generated litmus tests will often have an optional
0098 double-quoted comment string on the second line.  Such strings are ignored
0099 when running the test.  Yes, you can add your own comments to litmus
0100 tests, but this is a bit involved due to the use of multiple parsers.
0101 For now, you can use C-language comments in the C code, and these comments
0102 may be in either the "/* */" or the "//" style.  A later section will
0103 cover the full litmus-test commenting story.
0104 
0105 Line 3 is the initialization section.  Because the default initialization
0106 to zero suffices for this test, the "{}" syntax is used, which mean the
0107 initialization section is empty.  Litmus tests requiring non-default
0108 initialization must have non-empty initialization sections, as in the
0109 example that will be presented later in this document.
0110 
0111 Lines 5-9 show the first process and lines 11-18 the second process.  Each
0112 process corresponds to a Linux-kernel task (or kthread, workqueue, thread,
0113 and so on; LKMM discussions often use these terms interchangeably).
0114 The name of the first process is "P0" and that of the second "P1".
0115 You can name your processes anything you like as long as the names consist
0116 of a single "P" followed by a number, and as long as the numbers are
0117 consecutive starting with zero.  This can actually be quite helpful,
0118 for example, a .litmus file matching "^P1(" but not matching "^P2("
0119 must contain a two-process litmus test.
0120 
0121 The argument list for each function are pointers to the global variables
0122 used by that function.  Unlike normal C-language function parameters, the
0123 names are significant.  The fact that both P0() and P1() have a formal
0124 parameter named "x" means that these two processes are working with the
0125 same global variable, also named "x".  So the "int *x, int *y" on P0()
0126 and P1() mean that both processes are working with two shared global
0127 variables, "x" and "y".  Global variables are always passed to processes
0128 by reference, hence "P0(int *x, int *y)", but *never* "P0(int x, int y)".
0129 
0130 P0() has no local variables, but P1() has two of them named "r0" and "r1".
0131 These names may be freely chosen, but for historical reasons stemming from
0132 other litmus-test formats, it is conventional to use names consisting of
0133 "r" followed by a number as shown here.  A common bug in litmus tests
0134 is forgetting to add a global variable to a process's parameter list.
0135 This will sometimes result in an error message, but can also cause the
0136 intended global to instead be silently treated as an undeclared local
0137 variable.
0138 
0139 Each process's code is similar to Linux-kernel C, as can be seen on lines
0140 7-8 and 13-17.  This code may use many of the Linux kernel's atomic
0141 operations, some of its exclusive-lock functions, and some of its RCU
0142 and SRCU functions.  An approximate list of the currently supported
0143 functions may be found in the linux-kernel.def file.
0144 
0145 The P0() process does "WRITE_ONCE(*x, 1)" on line 7.  Because "x" is a
0146 pointer in P0()'s parameter list, this does an unordered store to global
0147 variable "x".  Line 8 does "smp_store_release(y, 1)", and because "y"
0148 is also in P0()'s parameter list, this does a release store to global
0149 variable "y".
0150 
0151 The P1() process declares two local variables on lines 13 and 14.
0152 Line 16 does "r0 = smp_load_acquire(y)" which does an acquire load
0153 from global variable "y" into local variable "r0".  Line 17 does a
0154 "r1 = READ_ONCE(*x)", which does an unordered load from "*x" into local
0155 variable "r1".  Both "x" and "y" are in P1()'s parameter list, so both
0156 reference the same global variables that are used by P0().
0157 
0158 Line 20 is the "exists" assertion expression to evaluate the final state.
0159 This final state is evaluated after the dust has settled: both processes
0160 have completed and all of their memory references and memory barriers
0161 have propagated to all parts of the system.  The references to the local
0162 variables "r0" and "r1" in line 24 must be prefixed with "1:" to specify
0163 which process they are local to.
0164 
0165 Note that the assertion expression is written in the litmus-test
0166 language rather than in C.  For example, single "=" is an equality
0167 operator rather than an assignment.  The "/\" character combination means
0168 "and".  Similarly, "\/" stands for "or".  Both of these are ASCII-art
0169 representations of the corresponding mathematical symbols.  Finally,
0170 "~" stands for "logical not", which is "!" in C, and not to be confused
0171 with the C-language "~" operator which instead stands for "bitwise not".
0172 Parentheses may be used to override precedence.
0173 
0174 The "exists" assertion on line 20 is satisfied if the consumer sees the
0175 flag ("y") set but the buffer ("x") as not yet filled in, that is, if P1()
0176 loaded a value from "x" that was equal to 1 but loaded a value from "y"
0177 that was still equal to zero.
0178 
0179 This example can be checked by running the following command, which
0180 absolutely must be run from the tools/memory-model directory and from
0181 this directory only:
0182 
0183 herd7 -conf linux-kernel.cfg litmus-tests/MP+pooncerelease+poacquireonce.litmus
0184 
0185 The output is the result of something similar to a full state-space
0186 search, and is as follows:
0187 
0188  1 Test MP+pooncerelease+poacquireonce Allowed
0189  2 States 3
0190  3 1:r0=0; 1:r1=0;
0191  4 1:r0=0; 1:r1=1;
0192  5 1:r0=1; 1:r1=1;
0193  6 No
0194  7 Witnesses
0195  8 Positive: 0 Negative: 3
0196  9 Condition exists (1:r0=1 /\ 1:r1=0)
0197 10 Observation MP+pooncerelease+poacquireonce Never 0 3
0198 11 Time MP+pooncerelease+poacquireonce 0.00
0199 12 Hash=579aaa14d8c35a39429b02e698241d09
0200 
0201 The most pertinent line is line 10, which contains "Never 0 3", which
0202 indicates that the bad result flagged by the "exists" clause never
0203 happens.  This line might instead say "Sometimes" to indicate that the
0204 bad result happened in some but not all executions, or it might say
0205 "Always" to indicate that the bad result happened in all executions.
0206 (The herd7 tool doesn't judge, so it is only an LKMM convention that the
0207 "exists" clause indicates a bad result.  To see this, invert the "exists"
0208 clause's condition and run the test.)  The numbers ("0 3") at the end
0209 of this line indicate the number of end states satisfying the "exists"
0210 clause (0) and the number not not satisfying that clause (3).
0211 
0212 Another important part of this output is shown in lines 2-5, repeated here:
0213 
0214  2 States 3
0215  3 1:r0=0; 1:r1=0;
0216  4 1:r0=0; 1:r1=1;
0217  5 1:r0=1; 1:r1=1;
0218 
0219 Line 2 gives the total number of end states, and each of lines 3-5 list
0220 one of these states, with the first ("1:r0=0; 1:r1=0;") indicating that
0221 both of P1()'s loads returned the value "0".  As expected, given the
0222 "Never" on line 10, the state flagged by the "exists" clause is not
0223 listed.  This full list of states can be helpful when debugging a new
0224 litmus test.
0225 
0226 The rest of the output is not normally needed, either due to irrelevance
0227 or due to being redundant with the lines discussed above.  However, the
0228 following paragraph lists them for the benefit of readers possessed of
0229 an insatiable curiosity.  Other readers should feel free to skip ahead.
0230 
0231 Line 1 echos the test name, along with the "Test" and "Allowed".  Line 6's
0232 "No" says that the "exists" clause was not satisfied by any execution,
0233 and as such it has the same meaning as line 10's "Never".  Line 7 is a
0234 lead-in to line 8's "Positive: 0 Negative: 3", which lists the number
0235 of end states satisfying and not satisfying the "exists" clause, just
0236 like the two numbers at the end of line 10.  Line 9 repeats the "exists"
0237 clause so that you don't have to look it up in the litmus-test file.
0238 The number at the end of line 11 (which begins with "Time") gives the
0239 time in seconds required to analyze the litmus test.  Small tests such
0240 as this one complete in a few milliseconds, so "0.00" is quite common.
0241 Line 12 gives a hash of the contents for the litmus-test file, and is used
0242 by tooling that manages litmus tests and their output.  This tooling is
0243 used by people modifying LKMM itself, and among other things lets such
0244 people know which of the several thousand relevant litmus tests were
0245 affected by a given change to LKMM.
0246 
0247 
0248 Initialization
0249 --------------
0250 
0251 The previous example relied on the default zero initialization for
0252 "x" and "y", but a similar litmus test could instead initialize them
0253 to some other value:
0254 
0255  1 C MP+pooncerelease+poacquireonce
0256  2
0257  3 {
0258  4   x=42;
0259  5   y=42;
0260  6 }
0261  7
0262  8 P0(int *x, int *y)
0263  9 {
0264 10   WRITE_ONCE(*x, 1);
0265 11   smp_store_release(y, 1);
0266 12 }
0267 13
0268 14 P1(int *x, int *y)
0269 15 {
0270 16   int r0;
0271 17   int r1;
0272 18
0273 19   r0 = smp_load_acquire(y);
0274 20   r1 = READ_ONCE(*x);
0275 21 }
0276 22
0277 23 exists (1:r0=1 /\ 1:r1=42)
0278 
0279 Lines 3-6 now initialize both "x" and "y" to the value 42.  This also
0280 means that the "exists" clause on line 23 must change "1:r1=0" to
0281 "1:r1=42".
0282 
0283 Running the test gives the same overall result as before, but with the
0284 value 42 appearing in place of the value zero:
0285 
0286  1 Test MP+pooncerelease+poacquireonce Allowed
0287  2 States 3
0288  3 1:r0=1; 1:r1=1;
0289  4 1:r0=42; 1:r1=1;
0290  5 1:r0=42; 1:r1=42;
0291  6 No
0292  7 Witnesses
0293  8 Positive: 0 Negative: 3
0294  9 Condition exists (1:r0=1 /\ 1:r1=42)
0295 10 Observation MP+pooncerelease+poacquireonce Never 0 3
0296 11 Time MP+pooncerelease+poacquireonce 0.02
0297 12 Hash=ab9a9b7940a75a792266be279a980156
0298 
0299 It is tempting to avoid the open-coded repetitions of the value "42"
0300 by defining another global variable "initval=42" and replacing all
0301 occurrences of "42" with "initval".  This will not, repeat *not*,
0302 initialize "x" and "y" to 42, but instead to the address of "initval"
0303 (try it!).  See the section below on linked lists to learn more about
0304 why this approach to initialization can be useful.
0305 
0306 
0307 Control Structures
0308 ------------------
0309 
0310 LKMM supports the C-language "if" statement, which allows modeling of
0311 conditional branches.  In LKMM, conditional branches can affect ordering,
0312 but only if you are *very* careful (compilers are surprisingly able
0313 to optimize away conditional branches).  The following example shows
0314 the "load buffering" (LB) use case that is used in the Linux kernel to
0315 synchronize between ring-buffer producers and consumers.  In the example
0316 below, P0() is one side checking to see if an operation may proceed and
0317 P1() is the other side completing its update.
0318 
0319  1 C LB+fencembonceonce+ctrlonceonce
0320  2
0321  3 {}
0322  4
0323  5 P0(int *x, int *y)
0324  6 {
0325  7   int r0;
0326  8
0327  9   r0 = READ_ONCE(*x);
0328 10   if (r0)
0329 11     WRITE_ONCE(*y, 1);
0330 12 }
0331 13
0332 14 P1(int *x, int *y)
0333 15 {
0334 16   int r0;
0335 17
0336 18   r0 = READ_ONCE(*y);
0337 19   smp_mb();
0338 20   WRITE_ONCE(*x, 1);
0339 21 }
0340 22
0341 23 exists (0:r0=1 /\ 1:r0=1)
0342 
0343 P1()'s "if" statement on line 10 works as expected, so that line 11 is
0344 executed only if line 9 loads a non-zero value from "x".  Because P1()'s
0345 write of "1" to "x" happens only after P1()'s read from "y", one would
0346 hope that the "exists" clause cannot be satisfied.  LKMM agrees:
0347 
0348  1 Test LB+fencembonceonce+ctrlonceonce Allowed
0349  2 States 2
0350  3 0:r0=0; 1:r0=0;
0351  4 0:r0=1; 1:r0=0;
0352  5 No
0353  6 Witnesses
0354  7 Positive: 0 Negative: 2
0355  8 Condition exists (0:r0=1 /\ 1:r0=1)
0356  9 Observation LB+fencembonceonce+ctrlonceonce Never 0 2
0357 10 Time LB+fencembonceonce+ctrlonceonce 0.00
0358 11 Hash=e5260556f6de495fd39b556d1b831c3b
0359 
0360 However, there is no "while" statement due to the fact that full
0361 state-space search has some difficulty with iteration.  However, there
0362 are tricks that may be used to handle some special cases, which are
0363 discussed below.  In addition, loop-unrolling tricks may be applied,
0364 albeit sparingly.
0365 
0366 
0367 Tricks and Traps
0368 ================
0369 
0370 This section covers extracting debug output from herd7, emulating
0371 spin loops, handling trivial linked lists, adding comments to litmus tests,
0372 emulating call_rcu(), and finally tricks to improve herd7 performance
0373 in order to better handle large litmus tests.
0374 
0375 
0376 Debug Output
0377 ------------
0378 
0379 By default, the herd7 state output includes all variables mentioned
0380 in the "exists" clause.  But sometimes debugging efforts are greatly
0381 aided by the values of other variables.  Consider this litmus test
0382 (tools/memory-order/litmus-tests/SB+rfionceonce-poonceonces.litmus but
0383 slightly modified), which probes an obscure corner of hardware memory
0384 ordering:
0385 
0386  1 C SB+rfionceonce-poonceonces
0387  2
0388  3 {}
0389  4
0390  5 P0(int *x, int *y)
0391  6 {
0392  7   int r1;
0393  8   int r2;
0394  9
0395 10   WRITE_ONCE(*x, 1);
0396 11   r1 = READ_ONCE(*x);
0397 12   r2 = READ_ONCE(*y);
0398 13 }
0399 14
0400 15 P1(int *x, int *y)
0401 16 {
0402 17   int r3;
0403 18   int r4;
0404 19
0405 20   WRITE_ONCE(*y, 1);
0406 21   r3 = READ_ONCE(*y);
0407 22   r4 = READ_ONCE(*x);
0408 23 }
0409 24
0410 25 exists (0:r2=0 /\ 1:r4=0)
0411 
0412 The herd7 output is as follows:
0413 
0414  1 Test SB+rfionceonce-poonceonces Allowed
0415  2 States 4
0416  3 0:r2=0; 1:r4=0;
0417  4 0:r2=0; 1:r4=1;
0418  5 0:r2=1; 1:r4=0;
0419  6 0:r2=1; 1:r4=1;
0420  7 Ok
0421  8 Witnesses
0422  9 Positive: 1 Negative: 3
0423 10 Condition exists (0:r2=0 /\ 1:r4=0)
0424 11 Observation SB+rfionceonce-poonceonces Sometimes 1 3
0425 12 Time SB+rfionceonce-poonceonces 0.01
0426 13 Hash=c7f30fe0faebb7d565405d55b7318ada
0427 
0428 (This output indicates that CPUs are permitted to "snoop their own
0429 store buffers", which all of Linux's CPU families other than s390 will
0430 happily do.  Such snooping results in disagreement among CPUs on the
0431 order of stores from different CPUs, which is rarely an issue.)
0432 
0433 But the herd7 output shows only the two variables mentioned in the
0434 "exists" clause.  Someone modifying this test might wish to know the
0435 values of "x", "y", "0:r1", and "0:r3" as well.  The "locations"
0436 statement on line 25 shows how to cause herd7 to display additional
0437 variables:
0438 
0439  1 C SB+rfionceonce-poonceonces
0440  2
0441  3 {}
0442  4
0443  5 P0(int *x, int *y)
0444  6 {
0445  7   int r1;
0446  8   int r2;
0447  9
0448 10   WRITE_ONCE(*x, 1);
0449 11   r1 = READ_ONCE(*x);
0450 12   r2 = READ_ONCE(*y);
0451 13 }
0452 14
0453 15 P1(int *x, int *y)
0454 16 {
0455 17   int r3;
0456 18   int r4;
0457 19
0458 20   WRITE_ONCE(*y, 1);
0459 21   r3 = READ_ONCE(*y);
0460 22   r4 = READ_ONCE(*x);
0461 23 }
0462 24
0463 25 locations [0:r1; 1:r3; x; y]
0464 26 exists (0:r2=0 /\ 1:r4=0)
0465 
0466 The herd7 output then displays the values of all the variables:
0467 
0468  1 Test SB+rfionceonce-poonceonces Allowed
0469  2 States 4
0470  3 0:r1=1; 0:r2=0; 1:r3=1; 1:r4=0; x=1; y=1;
0471  4 0:r1=1; 0:r2=0; 1:r3=1; 1:r4=1; x=1; y=1;
0472  5 0:r1=1; 0:r2=1; 1:r3=1; 1:r4=0; x=1; y=1;
0473  6 0:r1=1; 0:r2=1; 1:r3=1; 1:r4=1; x=1; y=1;
0474  7 Ok
0475  8 Witnesses
0476  9 Positive: 1 Negative: 3
0477 10 Condition exists (0:r2=0 /\ 1:r4=0)
0478 11 Observation SB+rfionceonce-poonceonces Sometimes 1 3
0479 12 Time SB+rfionceonce-poonceonces 0.01
0480 13 Hash=40de8418c4b395388f6501cafd1ed38d
0481 
0482 What if you would like to know the value of a particular global variable
0483 at some particular point in a given process's execution?  One approach
0484 is to use a READ_ONCE() to load that global variable into a new local
0485 variable, then add that local variable to the "locations" clause.
0486 But be careful:  In some litmus tests, adding a READ_ONCE() will change
0487 the outcome!  For one example, please see the C-READ_ONCE.litmus and
0488 C-READ_ONCE-omitted.litmus tests located here:
0489 
0490         https://github.com/paulmckrcu/litmus/blob/master/manual/kernel/
0491 
0492 
0493 Spin Loops
0494 ----------
0495 
0496 The analysis carried out by herd7 explores full state space, which is
0497 at best of exponential time complexity.  Adding processes and increasing
0498 the amount of code in a give process can greatly increase execution time.
0499 Potentially infinite loops, such as those used to wait for locks to
0500 become available, are clearly problematic.
0501 
0502 Fortunately, it is possible to avoid state-space explosion by specially
0503 modeling such loops.  For example, the following litmus tests emulates
0504 locking using xchg_acquire(), but instead of enclosing xchg_acquire()
0505 in a spin loop, it instead excludes executions that fail to acquire the
0506 lock using a herd7 "filter" clause.  Note that for exclusive locking, you
0507 are better off using the spin_lock() and spin_unlock() that LKMM directly
0508 models, if for no other reason that these are much faster.  However, the
0509 techniques illustrated in this section can be used for other purposes,
0510 such as emulating reader-writer locking, which LKMM does not yet model.
0511 
0512  1 C C-SB+l-o-o-u+l-o-o-u-X
0513  2
0514  3 {
0515  4 }
0516  5
0517  6 P0(int *sl, int *x0, int *x1)
0518  7 {
0519  8   int r2;
0520  9   int r1;
0521 10
0522 11   r2 = xchg_acquire(sl, 1);
0523 12   WRITE_ONCE(*x0, 1);
0524 13   r1 = READ_ONCE(*x1);
0525 14   smp_store_release(sl, 0);
0526 15 }
0527 16
0528 17 P1(int *sl, int *x0, int *x1)
0529 18 {
0530 19   int r2;
0531 20   int r1;
0532 21
0533 22   r2 = xchg_acquire(sl, 1);
0534 23   WRITE_ONCE(*x1, 1);
0535 24   r1 = READ_ONCE(*x0);
0536 25   smp_store_release(sl, 0);
0537 26 }
0538 27
0539 28 filter (0:r2=0 /\ 1:r2=0)
0540 29 exists (0:r1=0 /\ 1:r1=0)
0541 
0542 This litmus test may be found here:
0543 
0544 https://git.kernel.org/pub/scm/linux/kernel/git/paulmck/perfbook.git/tree/CodeSamples/formal/herd/C-SB+l-o-o-u+l-o-o-u-X.litmus
0545 
0546 This test uses two global variables, "x1" and "x2", and also emulates a
0547 single global spinlock named "sl".  This spinlock is held by whichever
0548 process changes the value of "sl" from "0" to "1", and is released when
0549 that process sets "sl" back to "0".  P0()'s lock acquisition is emulated
0550 on line 11 using xchg_acquire(), which unconditionally stores the value
0551 "1" to "sl" and stores either "0" or "1" to "r2", depending on whether
0552 the lock acquisition was successful or unsuccessful (due to "sl" already
0553 having the value "1"), respectively.  P1() operates in a similar manner.
0554 
0555 Rather unconventionally, execution appears to proceed to the critical
0556 section on lines 12 and 13 in either case.  Line 14 then uses an
0557 smp_store_release() to store zero to "sl", thus emulating lock release.
0558 
0559 The case where xchg_acquire() fails to acquire the lock is handled by
0560 the "filter" clause on line 28, which tells herd7 to keep only those
0561 executions in which both "0:r2" and "1:r2" are zero, that is to pay
0562 attention only to those executions in which both locks are actually
0563 acquired.  Thus, the bogus executions that would execute the critical
0564 sections are discarded and any effects that they might have had are
0565 ignored.  Note well that the "filter" clause keeps those executions
0566 for which its expression is satisfied, that is, for which the expression
0567 evaluates to true.  In other words, the "filter" clause says what to
0568 keep, not what to discard.
0569 
0570 The result of running this test is as follows:
0571 
0572  1 Test C-SB+l-o-o-u+l-o-o-u-X Allowed
0573  2 States 2
0574  3 0:r1=0; 1:r1=1;
0575  4 0:r1=1; 1:r1=0;
0576  5 No
0577  6 Witnesses
0578  7 Positive: 0 Negative: 2
0579  8 Condition exists (0:r1=0 /\ 1:r1=0)
0580  9 Observation C-SB+l-o-o-u+l-o-o-u-X Never 0 2
0581 10 Time C-SB+l-o-o-u+l-o-o-u-X 0.03
0582 
0583 The "Never" on line 9 indicates that this use of xchg_acquire() and
0584 smp_store_release() really does correctly emulate locking.
0585 
0586 Why doesn't the litmus test take the simpler approach of using a spin loop
0587 to handle failed spinlock acquisitions, like the kernel does?  The key
0588 insight behind this litmus test is that spin loops have no effect on the
0589 possible "exists"-clause outcomes of program execution in the absence
0590 of deadlock.  In other words, given a high-quality lock-acquisition
0591 primitive in a deadlock-free program running on high-quality hardware,
0592 each lock acquisition will eventually succeed.  Because herd7 already
0593 explores the full state space, the length of time required to actually
0594 acquire the lock does not matter.  After all, herd7 already models all
0595 possible durations of the xchg_acquire() statements.
0596 
0597 Why not just add the "filter" clause to the "exists" clause, thus
0598 avoiding the "filter" clause entirely?  This does work, but is slower.
0599 The reason that the "filter" clause is faster is that (in the common case)
0600 herd7 knows to abandon an execution as soon as the "filter" expression
0601 fails to be satisfied.  In contrast, the "exists" clause is evaluated
0602 only at the end of time, thus requiring herd7 to waste time on bogus
0603 executions in which both critical sections proceed concurrently.  In
0604 addition, some LKMM users like the separation of concerns provided by
0605 using the both the "filter" and "exists" clauses.
0606 
0607 Readers lacking a pathological interest in odd corner cases should feel
0608 free to skip the remainder of this section.
0609 
0610 But what if the litmus test were to temporarily set "0:r2" to a non-zero
0611 value?  Wouldn't that cause herd7 to abandon the execution prematurely
0612 due to an early mismatch of the "filter" clause?
0613 
0614 Why not just try it?  Line 4 of the following modified litmus test
0615 introduces a new global variable "x2" that is initialized to "1".  Line 23
0616 of P1() reads that variable into "1:r2" to force an early mismatch with
0617 the "filter" clause.  Line 24 does a known-true "if" condition to avoid
0618 and static analysis that herd7 might do.  Finally the "exists" clause
0619 on line 32 is updated to a condition that is alway satisfied at the end
0620 of the test.
0621 
0622  1 C C-SB+l-o-o-u+l-o-o-u-X
0623  2
0624  3 {
0625  4   x2=1;
0626  5 }
0627  6
0628  7 P0(int *sl, int *x0, int *x1)
0629  8 {
0630  9   int r2;
0631 10   int r1;
0632 11
0633 12   r2 = xchg_acquire(sl, 1);
0634 13   WRITE_ONCE(*x0, 1);
0635 14   r1 = READ_ONCE(*x1);
0636 15   smp_store_release(sl, 0);
0637 16 }
0638 17
0639 18 P1(int *sl, int *x0, int *x1, int *x2)
0640 19 {
0641 20   int r2;
0642 21   int r1;
0643 22
0644 23   r2 = READ_ONCE(*x2);
0645 24   if (r2)
0646 25     r2 = xchg_acquire(sl, 1);
0647 26   WRITE_ONCE(*x1, 1);
0648 27   r1 = READ_ONCE(*x0);
0649 28   smp_store_release(sl, 0);
0650 29 }
0651 30
0652 31 filter (0:r2=0 /\ 1:r2=0)
0653 32 exists (x1=1)
0654 
0655 If the "filter" clause were to check each variable at each point in the
0656 execution, running this litmus test would display no executions because
0657 all executions would be filtered out at line 23.  However, the output
0658 is instead as follows:
0659 
0660  1 Test C-SB+l-o-o-u+l-o-o-u-X Allowed
0661  2 States 1
0662  3 x1=1;
0663  4 Ok
0664  5 Witnesses
0665  6 Positive: 2 Negative: 0
0666  7 Condition exists (x1=1)
0667  8 Observation C-SB+l-o-o-u+l-o-o-u-X Always 2 0
0668  9 Time C-SB+l-o-o-u+l-o-o-u-X 0.04
0669 10 Hash=080bc508da7f291e122c6de76c0088e3
0670 
0671 Line 3 shows that there is one execution that did not get filtered out,
0672 so the "filter" clause is evaluated only on the last assignment to
0673 the variables that it checks.  In this case, the "filter" clause is a
0674 disjunction, so it might be evaluated twice, once at the final (and only)
0675 assignment to "0:r2" and once at the final assignment to "1:r2".
0676 
0677 
0678 Linked Lists
0679 ------------
0680 
0681 LKMM can handle linked lists, but only linked lists in which each node
0682 contains nothing except a pointer to the next node in the list.  This is
0683 of course quite restrictive, but there is nevertheless quite a bit that
0684 can be done within these confines, as can be seen in the litmus test
0685 at tools/memory-model/litmus-tests/MP+onceassign+derefonce.litmus:
0686 
0687  1 C MP+onceassign+derefonce
0688  2
0689  3 {
0690  4 y=z;
0691  5 z=0;
0692  6 }
0693  7
0694  8 P0(int *x, int **y)
0695  9 {
0696 10   WRITE_ONCE(*x, 1);
0697 11   rcu_assign_pointer(*y, x);
0698 12 }
0699 13
0700 14 P1(int *x, int **y)
0701 15 {
0702 16   int *r0;
0703 17   int r1;
0704 18
0705 19   rcu_read_lock();
0706 20   r0 = rcu_dereference(*y);
0707 21   r1 = READ_ONCE(*r0);
0708 22   rcu_read_unlock();
0709 23 }
0710 24
0711 25 exists (1:r0=x /\ 1:r1=0)
0712 
0713 Line 4's "y=z" may seem odd, given that "z" has not yet been initialized.
0714 But "y=z" does not set the value of "y" to that of "z", but instead
0715 sets the value of "y" to the *address* of "z".  Lines 4 and 5 therefore
0716 create a simple linked list, with "y" pointing to "z" and "z" having a
0717 NULL pointer.  A much longer linked list could be created if desired,
0718 and circular singly linked lists can also be created and manipulated.
0719 
0720 The "exists" clause works the same way, with the "1:r0=x" comparing P1()'s
0721 "r0" not to the value of "x", but again to its address.  This term of the
0722 "exists" clause therefore tests whether line 20's load from "y" saw the
0723 value stored by line 11, which is in fact what is required in this case.
0724 
0725 P0()'s line 10 initializes "x" to the value 1 then line 11 links to "x"
0726 from "y", replacing "z".
0727 
0728 P1()'s line 20 loads a pointer from "y", and line 21 dereferences that
0729 pointer.  The RCU read-side critical section spanning lines 19-22 is just
0730 for show in this example.  Note that the address used for line 21's load
0731 depends on (in this case, "is exactly the same as") the value loaded by
0732 line 20.  This is an example of what is called an "address dependency".
0733 This particular address dependency extends from the load on line 20 to the
0734 load on line 21.  Address dependencies provide a weak form of ordering.
0735 
0736 Running this test results in the following:
0737 
0738  1 Test MP+onceassign+derefonce Allowed
0739  2 States 2
0740  3 1:r0=x; 1:r1=1;
0741  4 1:r0=z; 1:r1=0;
0742  5 No
0743  6 Witnesses
0744  7 Positive: 0 Negative: 2
0745  8 Condition exists (1:r0=x /\ 1:r1=0)
0746  9 Observation MP+onceassign+derefonce Never 0 2
0747 10 Time MP+onceassign+derefonce 0.00
0748 11 Hash=49ef7a741563570102448a256a0c8568
0749 
0750 The only possible outcomes feature P1() loading a pointer to "z"
0751 (which contains zero) on the one hand and P1() loading a pointer to "x"
0752 (which contains the value one) on the other.  This should be reassuring
0753 because it says that RCU readers cannot see the old preinitialization
0754 values when accessing a newly inserted list node.  This undesirable
0755 scenario is flagged by the "exists" clause, and would occur if P1()
0756 loaded a pointer to "x", but obtained the pre-initialization value of
0757 zero after dereferencing that pointer.
0758 
0759 
0760 Comments
0761 --------
0762 
0763 Different portions of a litmus test are processed by different parsers,
0764 which has the charming effect of requiring different comment syntax in
0765 different portions of the litmus test.  The C-syntax portions use
0766 C-language comments (either "/* */" or "//"), while the other portions
0767 use Ocaml comments "(* *)".
0768 
0769 The following litmus test illustrates the comment style corresponding
0770 to each syntactic unit of the test:
0771 
0772  1 C MP+onceassign+derefonce (* A *)
0773  2
0774  3 (* B *)
0775  4
0776  5 {
0777  6 y=z; (* C *)
0778  7 z=0;
0779  8 } // D
0780  9
0781 10 // E
0782 11
0783 12 P0(int *x, int **y) // F
0784 13 {
0785 14   WRITE_ONCE(*x, 1);  // G
0786 15   rcu_assign_pointer(*y, x);
0787 16 }
0788 17
0789 18 // H
0790 19
0791 20 P1(int *x, int **y)
0792 21 {
0793 22   int *r0;
0794 23   int r1;
0795 24
0796 25   rcu_read_lock();
0797 26   r0 = rcu_dereference(*y);
0798 27   r1 = READ_ONCE(*r0);
0799 28   rcu_read_unlock();
0800 29 }
0801 30
0802 31 // I
0803 32
0804 33 exists (* J *) (1:r0=x /\ (* K *) 1:r1=0) (* L *)
0805 
0806 In short, use C-language comments in the C code and Ocaml comments in
0807 the rest of the litmus test.
0808 
0809 On the other hand, if you prefer C-style comments everywhere, the
0810 C preprocessor is your friend.
0811 
0812 
0813 Asynchronous RCU Grace Periods
0814 ------------------------------
0815 
0816 The following litmus test is derived from the example show in
0817 Documentation/litmus-tests/rcu/RCU+sync+free.litmus, but converted to
0818 emulate call_rcu():
0819 
0820  1 C RCU+sync+free
0821  2
0822  3 {
0823  4 int x = 1;
0824  5 int *y = &x;
0825  6 int z = 1;
0826  7 }
0827  8
0828  9 P0(int *x, int *z, int **y)
0829 10 {
0830 11   int *r0;
0831 12   int r1;
0832 13
0833 14   rcu_read_lock();
0834 15   r0 = rcu_dereference(*y);
0835 16   r1 = READ_ONCE(*r0);
0836 17   rcu_read_unlock();
0837 18 }
0838 19
0839 20 P1(int *z, int **y, int *c)
0840 21 {
0841 22   rcu_assign_pointer(*y, z);
0842 23   smp_store_release(*c, 1); // Emulate call_rcu().
0843 24 }
0844 25
0845 26 P2(int *x, int *z, int **y, int *c)
0846 27 {
0847 28   int r0;
0848 29
0849 30   r0 = smp_load_acquire(*c); // Note call_rcu() request.
0850 31   synchronize_rcu(); // Wait one grace period.
0851 32   WRITE_ONCE(*x, 0); // Emulate the RCU callback.
0852 33 }
0853 34
0854 35 filter (2:r0=1) (* Reject too-early starts. *)
0855 36 exists (0:r0=x /\ 0:r1=0)
0856 
0857 Lines 4-6 initialize a linked list headed by "y" that initially contains
0858 "x".  In addition, "z" is pre-initialized to prepare for P1(), which
0859 will replace "x" with "z" in this list.
0860 
0861 P0() on lines 9-18 enters an RCU read-side critical section, loads the
0862 list header "y" and dereferences it, leaving the node in "0:r0" and
0863 the node's value in "0:r1".
0864 
0865 P1() on lines 20-24 updates the list header to instead reference "z",
0866 then emulates call_rcu() by doing a release store into "c".
0867 
0868 P2() on lines 27-33 emulates the behind-the-scenes effect of doing a
0869 call_rcu().  Line 30 first does an acquire load from "c", then line 31
0870 waits for an RCU grace period to elapse, and finally line 32 emulates
0871 the RCU callback, which in turn emulates a call to kfree().
0872 
0873 Of course, it is possible for P2() to start too soon, so that the
0874 value of "2:r0" is zero rather than the required value of "1".
0875 The "filter" clause on line 35 handles this possibility, rejecting
0876 all executions in which "2:r0" is not equal to the value "1".
0877 
0878 
0879 Performance
0880 -----------
0881 
0882 LKMM's exploration of the full state-space can be extremely helpful,
0883 but it does not come for free.  The price is exponential computational
0884 complexity in terms of the number of processes, the average number
0885 of statements in each process, and the total number of stores in the
0886 litmus test.
0887 
0888 So it is best to start small and then work up.  Where possible, break
0889 your code down into small pieces each representing a core concurrency
0890 requirement.
0891 
0892 That said, herd7 is quite fast.  On an unprepossessing x86 laptop, it
0893 was able to analyze the following 10-process RCU litmus test in about
0894 six seconds.
0895 
0896 https://github.com/paulmckrcu/litmus/blob/master/auto/C-RW-R+RW-R+RW-G+RW-G+RW-G+RW-G+RW-R+RW-R+RW-R+RW-R.litmus
0897 
0898 One way to make herd7 run faster is to use the "-speedcheck true" option.
0899 This option prevents herd7 from generating all possible end states,
0900 instead causing it to focus solely on whether or not the "exists"
0901 clause can be satisfied.  With this option, herd7 evaluates the above
0902 litmus test in about 300 milliseconds, for more than an order of magnitude
0903 improvement in performance.
0904 
0905 Larger 16-process litmus tests that would normally consume 15 minutes
0906 of time complete in about 40 seconds with this option.  To be fair,
0907 you do get an extra 65,535 states when you leave off the "-speedcheck
0908 true" option.
0909 
0910 https://github.com/paulmckrcu/litmus/blob/master/auto/C-RW-R+RW-R+RW-G+RW-G+RW-G+RW-G+RW-R+RW-R+RW-R+RW-R+RW-G+RW-G+RW-G+RW-G+RW-R+RW-R.litmus
0911 
0912 Nevertheless, litmus-test analysis really is of exponential complexity,
0913 whether with or without "-speedcheck true".  Increasing by just three
0914 processes to a 19-process litmus test requires 2 hours and 40 minutes
0915 without, and about 8 minutes with "-speedcheck true".  Each of these
0916 results represent roughly an order of magnitude slowdown compared to the
0917 16-process litmus test.  Again, to be fair, the multi-hour run explores
0918 no fewer than 524,287 additional states compared to the shorter one.
0919 
0920 https://github.com/paulmckrcu/litmus/blob/master/auto/C-RW-R+RW-R+RW-G+RW-G+RW-G+RW-G+RW-R+RW-R+RW-R+RW-R+RW-R+RW-R+RW-G+RW-G+RW-G+RW-G+RW-R+RW-R+RW-R.litmus
0921 
0922 If you don't like command-line arguments, you can obtain a similar speedup
0923 by adding a "filter" clause with exactly the same expression as your
0924 "exists" clause.
0925 
0926 However, please note that seeing the full set of states can be extremely
0927 helpful when developing and debugging litmus tests.
0928 
0929 
0930 LIMITATIONS
0931 ===========
0932 
0933 Limitations of the Linux-kernel memory model (LKMM) include:
0934 
0935 1.      Compiler optimizations are not accurately modeled.  Of course,
0936         the use of READ_ONCE() and WRITE_ONCE() limits the compiler's
0937         ability to optimize, but under some circumstances it is possible
0938         for the compiler to undermine the memory model.  For more
0939         information, see Documentation/explanation.txt (in particular,
0940         the "THE PROGRAM ORDER RELATION: po AND po-loc" and "A WARNING"
0941         sections).
0942 
0943         Note that this limitation in turn limits LKMM's ability to
0944         accurately model address, control, and data dependencies.
0945         For example, if the compiler can deduce the value of some variable
0946         carrying a dependency, then the compiler can break that dependency
0947         by substituting a constant of that value.
0948 
0949         Conversely, LKMM sometimes doesn't recognize that a particular
0950         optimization is not allowed, and as a result, thinks that a
0951         dependency is not present (because the optimization would break it).
0952         The memory model misses some pretty obvious control dependencies
0953         because of this limitation.  A simple example is:
0954 
0955                 r1 = READ_ONCE(x);
0956                 if (r1 == 0)
0957                         smp_mb();
0958                 WRITE_ONCE(y, 1);
0959 
0960         There is a control dependency from the READ_ONCE to the WRITE_ONCE,
0961         even when r1 is nonzero, but LKMM doesn't realize this and thinks
0962         that the write may execute before the read if r1 != 0.  (Yes, that
0963         doesn't make sense if you think about it, but the memory model's
0964         intelligence is limited.)
0965 
0966 2.      Multiple access sizes for a single variable are not supported,
0967         and neither are misaligned or partially overlapping accesses.
0968 
0969 3.      Exceptions and interrupts are not modeled.  In some cases,
0970         this limitation can be overcome by modeling the interrupt or
0971         exception with an additional process.
0972 
0973 4.      I/O such as MMIO or DMA is not supported.
0974 
0975 5.      Self-modifying code (such as that found in the kernel's
0976         alternatives mechanism, function tracer, Berkeley Packet Filter
0977         JIT compiler, and module loader) is not supported.
0978 
0979 6.      Complete modeling of all variants of atomic read-modify-write
0980         operations, locking primitives, and RCU is not provided.
0981         For example, call_rcu() and rcu_barrier() are not supported.
0982         However, a substantial amount of support is provided for these
0983         operations, as shown in the linux-kernel.def file.
0984 
0985         Here are specific limitations:
0986 
0987         a.      When rcu_assign_pointer() is passed NULL, the Linux
0988                 kernel provides no ordering, but LKMM models this
0989                 case as a store release.
0990 
0991         b.      The "unless" RMW operations are not currently modeled:
0992                 atomic_long_add_unless(), atomic_inc_unless_negative(),
0993                 and atomic_dec_unless_positive().  These can be emulated
0994                 in litmus tests, for example, by using atomic_cmpxchg().
0995 
0996                 One exception of this limitation is atomic_add_unless(),
0997                 which is provided directly by herd7 (so no corresponding
0998                 definition in linux-kernel.def).  atomic_add_unless() is
0999                 modeled by herd7 therefore it can be used in litmus tests.
1000 
1001         c.      The call_rcu() function is not modeled.  As was shown above,
1002                 it can be emulated in litmus tests by adding another
1003                 process that invokes synchronize_rcu() and the body of the
1004                 callback function, with (for example) a release-acquire
1005                 from the site of the emulated call_rcu() to the beginning
1006                 of the additional process.
1007 
1008         d.      The rcu_barrier() function is not modeled.  It can be
1009                 emulated in litmus tests emulating call_rcu() via
1010                 (for example) a release-acquire from the end of each
1011                 additional call_rcu() process to the site of the
1012                 emulated rcu-barrier().
1013 
1014         e.      Although sleepable RCU (SRCU) is now modeled, there
1015                 are some subtle differences between its semantics and
1016                 those in the Linux kernel.  For example, the kernel
1017                 might interpret the following sequence as two partially
1018                 overlapping SRCU read-side critical sections:
1019 
1020                          1  r1 = srcu_read_lock(&my_srcu);
1021                          2  do_something_1();
1022                          3  r2 = srcu_read_lock(&my_srcu);
1023                          4  do_something_2();
1024                          5  srcu_read_unlock(&my_srcu, r1);
1025                          6  do_something_3();
1026                          7  srcu_read_unlock(&my_srcu, r2);
1027 
1028                 In contrast, LKMM will interpret this as a nested pair of
1029                 SRCU read-side critical sections, with the outer critical
1030                 section spanning lines 1-7 and the inner critical section
1031                 spanning lines 3-5.
1032 
1033                 This difference would be more of a concern had anyone
1034                 identified a reasonable use case for partially overlapping
1035                 SRCU read-side critical sections.  For more information
1036                 on the trickiness of such overlapping, please see:
1037                 https://paulmck.livejournal.com/40593.html
1038 
1039         f.      Reader-writer locking is not modeled.  It can be
1040                 emulated in litmus tests using atomic read-modify-write
1041                 operations.
1042 
1043 The fragment of the C language supported by these litmus tests is quite
1044 limited and in some ways non-standard:
1045 
1046 1.      There is no automatic C-preprocessor pass.  You can of course
1047         run it manually, if you choose.
1048 
1049 2.      There is no way to create functions other than the Pn() functions
1050         that model the concurrent processes.
1051 
1052 3.      The Pn() functions' formal parameters must be pointers to the
1053         global shared variables.  Nothing can be passed by value into
1054         these functions.
1055 
1056 4.      The only functions that can be invoked are those built directly
1057         into herd7 or that are defined in the linux-kernel.def file.
1058 
1059 5.      The "switch", "do", "for", "while", and "goto" C statements are
1060         not supported.  The "switch" statement can be emulated by the
1061         "if" statement.  The "do", "for", and "while" statements can
1062         often be emulated by manually unrolling the loop, or perhaps by
1063         enlisting the aid of the C preprocessor to minimize the resulting
1064         code duplication.  Some uses of "goto" can be emulated by "if",
1065         and some others by unrolling.
1066 
1067 6.      Although you can use a wide variety of types in litmus-test
1068         variable declarations, and especially in global-variable
1069         declarations, the "herd7" tool understands only int and
1070         pointer types.  There is no support for floating-point types,
1071         enumerations, characters, strings, arrays, or structures.
1072 
1073 7.      Parsing of variable declarations is very loose, with almost no
1074         type checking.
1075 
1076 8.      Initializers differ from their C-language counterparts.
1077         For example, when an initializer contains the name of a shared
1078         variable, that name denotes a pointer to that variable, not
1079         the current value of that variable.  For example, "int x = y"
1080         is interpreted the way "int x = &y" would be in C.
1081 
1082 9.      Dynamic memory allocation is not supported, although this can
1083         be worked around in some cases by supplying multiple statically
1084         allocated variables.
1085 
1086 Some of these limitations may be overcome in the future, but others are
1087 more likely to be addressed by incorporating the Linux-kernel memory model
1088 into other tools.
1089 
1090 Finally, please note that LKMM is subject to change as hardware, use cases,
1091 and compilers evolve.