Path: blob/master/tools/memory-model/Documentation/litmus-tests.txt
26288 views
Linux-Kernel Memory Model Litmus Tests1======================================23This file describes the LKMM litmus-test format by example, describes4some tricks and traps, and finally outlines LKMM's limitations. Earlier5versions of this material appeared in a number of LWN articles, including:67https://lwn.net/Articles/720550/8A formal kernel memory-ordering model (part 2)9https://lwn.net/Articles/608550/10Axiomatic validation of memory barriers and atomic instructions11https://lwn.net/Articles/470681/12Validating Memory Barriers and Atomic Instructions1314This document presents information in decreasing order of applicability,15so that, where possible, the information that has proven more commonly16useful is shown near the beginning.1718For information on installing LKMM, including the underlying "herd7"19tool, please see tools/memory-model/README.202122Copy-Pasta23==========2425As with other software, it is often better (if less macho) to adapt an26existing litmus test than it is to create one from scratch. A number27of litmus tests may be found in the kernel source tree:2829tools/memory-model/litmus-tests/30Documentation/litmus-tests/3132Several thousand more example litmus tests are available on github33and kernel.org:3435https://github.com/paulmckrcu/litmus36https://git.kernel.org/pub/scm/linux/kernel/git/paulmck/perfbook.git/tree/CodeSamples/formal/herd37https://git.kernel.org/pub/scm/linux/kernel/git/paulmck/perfbook.git/tree/CodeSamples/formal/litmus3839The -l and -L arguments to "git grep" can be quite helpful in identifying40existing litmus tests that are similar to the one you need. But even if41you start with an existing litmus test, it is still helpful to have a42good understanding of the litmus-test format.434445Examples and Format46===================4748This section describes the overall format of litmus tests, starting49with a small example of the message-passing pattern and moving on to50more complex examples that illustrate explicit initialization and LKMM's51minimalistic set of flow-control statements.525354Message-Passing Example55-----------------------5657This section gives an overview of the format of a litmus test using an58example based on the common message-passing use case. This use case59appears often in the Linux kernel. For example, a flag (modeled by "y"60below) indicates that a buffer (modeled by "x" below) is now completely61filled in and ready for use. It would be very bad if the consumer saw the62flag set, but, due to memory misordering, saw old values in the buffer.6364This example asks whether smp_store_release() and smp_load_acquire()65suffices to avoid this bad outcome:66671 C MP+pooncerelease+poacquireonce682693 {}704715 P0(int *x, int *y)726 {737 WRITE_ONCE(*x, 1);748 smp_store_release(y, 1);759 }76107711 P1(int *x, int *y)7812 {7913 int r0;8014 int r1;81158216 r0 = smp_load_acquire(y);8317 r1 = READ_ONCE(*x);8418 }85198620 exists (1:r0=1 /\ 1:r1=0)8788Line 1 starts with "C", which identifies this file as being in the89LKMM C-language format (which, as we will see, is a small fragment90of the full C language). The remainder of line 1 is the name of91the test, which by convention is the filename with the ".litmus"92suffix stripped. In this case, the actual test may be found in93tools/memory-model/litmus-tests/MP+pooncerelease+poacquireonce.litmus94in the Linux-kernel source tree.9596Mechanically generated litmus tests will often have an optional97double-quoted comment string on the second line. Such strings are ignored98when running the test. Yes, you can add your own comments to litmus99tests, but this is a bit involved due to the use of multiple parsers.100For now, you can use C-language comments in the C code, and these comments101may be in either the "/* */" or the "//" style. A later section will102cover the full litmus-test commenting story.103104Line 3 is the initialization section. Because the default initialization105to zero suffices for this test, the "{}" syntax is used, which mean the106initialization section is empty. Litmus tests requiring non-default107initialization must have non-empty initialization sections, as in the108example that will be presented later in this document.109110Lines 5-9 show the first process and lines 11-18 the second process. Each111process corresponds to a Linux-kernel task (or kthread, workqueue, thread,112and so on; LKMM discussions often use these terms interchangeably).113The name of the first process is "P0" and that of the second "P1".114You can name your processes anything you like as long as the names consist115of a single "P" followed by a number, and as long as the numbers are116consecutive starting with zero. This can actually be quite helpful,117for example, a .litmus file matching "^P1(" but not matching "^P2("118must contain a two-process litmus test.119120The argument list for each function are pointers to the global variables121used by that function. Unlike normal C-language function parameters, the122names are significant. The fact that both P0() and P1() have a formal123parameter named "x" means that these two processes are working with the124same global variable, also named "x". So the "int *x, int *y" on P0()125and P1() mean that both processes are working with two shared global126variables, "x" and "y". Global variables are always passed to processes127by reference, hence "P0(int *x, int *y)", but *never* "P0(int x, int y)".128129P0() has no local variables, but P1() has two of them named "r0" and "r1".130These names may be freely chosen, but for historical reasons stemming from131other litmus-test formats, it is conventional to use names consisting of132"r" followed by a number as shown here. A common bug in litmus tests133is forgetting to add a global variable to a process's parameter list.134This will sometimes result in an error message, but can also cause the135intended global to instead be silently treated as an undeclared local136variable.137138Each process's code is similar to Linux-kernel C, as can be seen on lines1397-8 and 13-17. This code may use many of the Linux kernel's atomic140operations, some of its exclusive-lock functions, and some of its RCU141and SRCU functions. An approximate list of the currently supported142functions may be found in the linux-kernel.def file.143144The P0() process does "WRITE_ONCE(*x, 1)" on line 7. Because "x" is a145pointer in P0()'s parameter list, this does an unordered store to global146variable "x". Line 8 does "smp_store_release(y, 1)", and because "y"147is also in P0()'s parameter list, this does a release store to global148variable "y".149150The P1() process declares two local variables on lines 13 and 14.151Line 16 does "r0 = smp_load_acquire(y)" which does an acquire load152from global variable "y" into local variable "r0". Line 17 does a153"r1 = READ_ONCE(*x)", which does an unordered load from "*x" into local154variable "r1". Both "x" and "y" are in P1()'s parameter list, so both155reference the same global variables that are used by P0().156157Line 20 is the "exists" assertion expression to evaluate the final state.158This final state is evaluated after the dust has settled: both processes159have completed and all of their memory references and memory barriers160have propagated to all parts of the system. The references to the local161variables "r0" and "r1" in line 24 must be prefixed with "1:" to specify162which process they are local to.163164Note that the assertion expression is written in the litmus-test165language rather than in C. For example, single "=" is an equality166operator rather than an assignment. The "/\" character combination means167"and". Similarly, "\/" stands for "or". Both of these are ASCII-art168representations of the corresponding mathematical symbols. Finally,169"~" stands for "logical not", which is "!" in C, and not to be confused170with the C-language "~" operator which instead stands for "bitwise not".171Parentheses may be used to override precedence.172173The "exists" assertion on line 20 is satisfied if the consumer sees the174flag ("y") set but the buffer ("x") as not yet filled in, that is, if P1()175loaded a value from "x" that was equal to 1 but loaded a value from "y"176that was still equal to zero.177178This example can be checked by running the following command, which179absolutely must be run from the tools/memory-model directory and from180this directory only:181182herd7 -conf linux-kernel.cfg litmus-tests/MP+pooncerelease+poacquireonce.litmus183184The output is the result of something similar to a full state-space185search, and is as follows:1861871 Test MP+pooncerelease+poacquireonce Allowed1882 States 31893 1:r0=0; 1:r1=0;1904 1:r0=0; 1:r1=1;1915 1:r0=1; 1:r1=1;1926 No1937 Witnesses1948 Positive: 0 Negative: 31959 Condition exists (1:r0=1 /\ 1:r1=0)19610 Observation MP+pooncerelease+poacquireonce Never 0 319711 Time MP+pooncerelease+poacquireonce 0.0019812 Hash=579aaa14d8c35a39429b02e698241d09199200The most pertinent line is line 10, which contains "Never 0 3", which201indicates that the bad result flagged by the "exists" clause never202happens. This line might instead say "Sometimes" to indicate that the203bad result happened in some but not all executions, or it might say204"Always" to indicate that the bad result happened in all executions.205(The herd7 tool doesn't judge, so it is only an LKMM convention that the206"exists" clause indicates a bad result. To see this, invert the "exists"207clause's condition and run the test.) The numbers ("0 3") at the end208of this line indicate the number of end states satisfying the "exists"209clause (0) and the number not not satisfying that clause (3).210211Another important part of this output is shown in lines 2-5, repeated here:2122132 States 32143 1:r0=0; 1:r1=0;2154 1:r0=0; 1:r1=1;2165 1:r0=1; 1:r1=1;217218Line 2 gives the total number of end states, and each of lines 3-5 list219one of these states, with the first ("1:r0=0; 1:r1=0;") indicating that220both of P1()'s loads returned the value "0". As expected, given the221"Never" on line 10, the state flagged by the "exists" clause is not222listed. This full list of states can be helpful when debugging a new223litmus test.224225The rest of the output is not normally needed, either due to irrelevance226or due to being redundant with the lines discussed above. However, the227following paragraph lists them for the benefit of readers possessed of228an insatiable curiosity. Other readers should feel free to skip ahead.229230Line 1 echos the test name, along with the "Test" and "Allowed". Line 6's231"No" says that the "exists" clause was not satisfied by any execution,232and as such it has the same meaning as line 10's "Never". Line 7 is a233lead-in to line 8's "Positive: 0 Negative: 3", which lists the number234of end states satisfying and not satisfying the "exists" clause, just235like the two numbers at the end of line 10. Line 9 repeats the "exists"236clause so that you don't have to look it up in the litmus-test file.237The number at the end of line 11 (which begins with "Time") gives the238time in seconds required to analyze the litmus test. Small tests such239as this one complete in a few milliseconds, so "0.00" is quite common.240Line 12 gives a hash of the contents for the litmus-test file, and is used241by tooling that manages litmus tests and their output. This tooling is242used by people modifying LKMM itself, and among other things lets such243people know which of the several thousand relevant litmus tests were244affected by a given change to LKMM.245246247Initialization248--------------249250The previous example relied on the default zero initialization for251"x" and "y", but a similar litmus test could instead initialize them252to some other value:2532541 C MP+pooncerelease+poacquireonce25522563 {2574 x=42;2585 y=42;2596 }26072618 P0(int *x, int *y)2629 {26310 WRITE_ONCE(*x, 1);26411 smp_store_release(y, 1);26512 }2661326714 P1(int *x, int *y)26815 {26916 int r0;27017 int r1;2711827219 r0 = smp_load_acquire(y);27320 r1 = READ_ONCE(*x);27421 }2752227623 exists (1:r0=1 /\ 1:r1=42)277278Lines 3-6 now initialize both "x" and "y" to the value 42. This also279means that the "exists" clause on line 23 must change "1:r1=0" to280"1:r1=42".281282Running the test gives the same overall result as before, but with the283value 42 appearing in place of the value zero:2842851 Test MP+pooncerelease+poacquireonce Allowed2862 States 32873 1:r0=1; 1:r1=1;2884 1:r0=42; 1:r1=1;2895 1:r0=42; 1:r1=42;2906 No2917 Witnesses2928 Positive: 0 Negative: 32939 Condition exists (1:r0=1 /\ 1:r1=42)29410 Observation MP+pooncerelease+poacquireonce Never 0 329511 Time MP+pooncerelease+poacquireonce 0.0229612 Hash=ab9a9b7940a75a792266be279a980156297298It is tempting to avoid the open-coded repetitions of the value "42"299by defining another global variable "initval=42" and replacing all300occurrences of "42" with "initval". This will not, repeat *not*,301initialize "x" and "y" to 42, but instead to the address of "initval"302(try it!). See the section below on linked lists to learn more about303why this approach to initialization can be useful.304305306Control Structures307------------------308309LKMM supports the C-language "if" statement, which allows modeling of310conditional branches. In LKMM, conditional branches can affect ordering,311but only if you are *very* careful (compilers are surprisingly able312to optimize away conditional branches). The following example shows313the "load buffering" (LB) use case that is used in the Linux kernel to314synchronize between ring-buffer producers and consumers. In the example315below, P0() is one side checking to see if an operation may proceed and316P1() is the other side completing its update.3173181 C LB+fencembonceonce+ctrlonceonce31923203 {}32143225 P0(int *x, int *y)3236 {3247 int r0;32583269 r0 = READ_ONCE(*x);32710 if (r0)32811 WRITE_ONCE(*y, 1);32912 }3301333114 P1(int *x, int *y)33215 {33316 int r0;3341733518 r0 = READ_ONCE(*y);33619 smp_mb();33720 WRITE_ONCE(*x, 1);33821 }3392234023 exists (0:r0=1 /\ 1:r0=1)341342P1()'s "if" statement on line 10 works as expected, so that line 11 is343executed only if line 9 loads a non-zero value from "x". Because P1()'s344write of "1" to "x" happens only after P1()'s read from "y", one would345hope that the "exists" clause cannot be satisfied. LKMM agrees:3463471 Test LB+fencembonceonce+ctrlonceonce Allowed3482 States 23493 0:r0=0; 1:r0=0;3504 0:r0=1; 1:r0=0;3515 No3526 Witnesses3537 Positive: 0 Negative: 23548 Condition exists (0:r0=1 /\ 1:r0=1)3559 Observation LB+fencembonceonce+ctrlonceonce Never 0 235610 Time LB+fencembonceonce+ctrlonceonce 0.0035711 Hash=e5260556f6de495fd39b556d1b831c3b358359However, there is no "while" statement due to the fact that full360state-space search has some difficulty with iteration. However, there361are tricks that may be used to handle some special cases, which are362discussed below. In addition, loop-unrolling tricks may be applied,363albeit sparingly.364365366Tricks and Traps367================368369This section covers extracting debug output from herd7, emulating370spin loops, handling trivial linked lists, adding comments to litmus tests,371emulating call_rcu(), and finally tricks to improve herd7 performance372in order to better handle large litmus tests.373374375Debug Output376------------377378By default, the herd7 state output includes all variables mentioned379in the "exists" clause. But sometimes debugging efforts are greatly380aided by the values of other variables. Consider this litmus test381(tools/memory-order/litmus-tests/SB+rfionceonce-poonceonces.litmus but382slightly modified), which probes an obscure corner of hardware memory383ordering:3843851 C SB+rfionceonce-poonceonces38623873 {}38843895 P0(int *x, int *y)3906 {3917 int r1;3928 int r2;393939410 WRITE_ONCE(*x, 1);39511 r1 = READ_ONCE(*x);39612 r2 = READ_ONCE(*y);39713 }3981439915 P1(int *x, int *y)40016 {40117 int r3;40218 int r4;4031940420 WRITE_ONCE(*y, 1);40521 r3 = READ_ONCE(*y);40622 r4 = READ_ONCE(*x);40723 }4082440925 exists (0:r2=0 /\ 1:r4=0)410411The herd7 output is as follows:4124131 Test SB+rfionceonce-poonceonces Allowed4142 States 44153 0:r2=0; 1:r4=0;4164 0:r2=0; 1:r4=1;4175 0:r2=1; 1:r4=0;4186 0:r2=1; 1:r4=1;4197 Ok4208 Witnesses4219 Positive: 1 Negative: 342210 Condition exists (0:r2=0 /\ 1:r4=0)42311 Observation SB+rfionceonce-poonceonces Sometimes 1 342412 Time SB+rfionceonce-poonceonces 0.0142513 Hash=c7f30fe0faebb7d565405d55b7318ada426427(This output indicates that CPUs are permitted to "snoop their own428store buffers", which all of Linux's CPU families other than s390 will429happily do. Such snooping results in disagreement among CPUs on the430order of stores from different CPUs, which is rarely an issue.)431432But the herd7 output shows only the two variables mentioned in the433"exists" clause. Someone modifying this test might wish to know the434values of "x", "y", "0:r1", and "0:r3" as well. The "locations"435statement on line 25 shows how to cause herd7 to display additional436variables:4374381 C SB+rfionceonce-poonceonces43924403 {}44144425 P0(int *x, int *y)4436 {4447 int r1;4458 int r2;446944710 WRITE_ONCE(*x, 1);44811 r1 = READ_ONCE(*x);44912 r2 = READ_ONCE(*y);45013 }4511445215 P1(int *x, int *y)45316 {45417 int r3;45518 int r4;4561945720 WRITE_ONCE(*y, 1);45821 r3 = READ_ONCE(*y);45922 r4 = READ_ONCE(*x);46023 }4612446225 locations [0:r1; 1:r3; x; y]46326 exists (0:r2=0 /\ 1:r4=0)464465The herd7 output then displays the values of all the variables:4664671 Test SB+rfionceonce-poonceonces Allowed4682 States 44693 0:r1=1; 0:r2=0; 1:r3=1; 1:r4=0; x=1; y=1;4704 0:r1=1; 0:r2=0; 1:r3=1; 1:r4=1; x=1; y=1;4715 0:r1=1; 0:r2=1; 1:r3=1; 1:r4=0; x=1; y=1;4726 0:r1=1; 0:r2=1; 1:r3=1; 1:r4=1; x=1; y=1;4737 Ok4748 Witnesses4759 Positive: 1 Negative: 347610 Condition exists (0:r2=0 /\ 1:r4=0)47711 Observation SB+rfionceonce-poonceonces Sometimes 1 347812 Time SB+rfionceonce-poonceonces 0.0147913 Hash=40de8418c4b395388f6501cafd1ed38d480481What if you would like to know the value of a particular global variable482at some particular point in a given process's execution? One approach483is to use a READ_ONCE() to load that global variable into a new local484variable, then add that local variable to the "locations" clause.485But be careful: In some litmus tests, adding a READ_ONCE() will change486the outcome! For one example, please see the C-READ_ONCE.litmus and487C-READ_ONCE-omitted.litmus tests located here:488489https://github.com/paulmckrcu/litmus/blob/master/manual/kernel/490491492Spin Loops493----------494495The analysis carried out by herd7 explores full state space, which is496at best of exponential time complexity. Adding processes and increasing497the amount of code in a give process can greatly increase execution time.498Potentially infinite loops, such as those used to wait for locks to499become available, are clearly problematic.500501Fortunately, it is possible to avoid state-space explosion by specially502modeling such loops. For example, the following litmus tests emulates503locking using xchg_acquire(), but instead of enclosing xchg_acquire()504in a spin loop, it instead excludes executions that fail to acquire the505lock using a herd7 "filter" clause. Note that for exclusive locking, you506are better off using the spin_lock() and spin_unlock() that LKMM directly507models, if for no other reason that these are much faster. However, the508techniques illustrated in this section can be used for other purposes,509such as emulating reader-writer locking, which LKMM does not yet model.5105111 C C-SB+l-o-o-u+l-o-o-u-X51225133 {5144 }51555166 P0(int *sl, int *x0, int *x1)5177 {5188 int r2;5199 int r1;5201052111 r2 = xchg_acquire(sl, 1);52212 WRITE_ONCE(*x0, 1);52313 r1 = READ_ONCE(*x1);52414 smp_store_release(sl, 0);52515 }5261652717 P1(int *sl, int *x0, int *x1)52818 {52919 int r2;53020 int r1;5312153222 r2 = xchg_acquire(sl, 1);53323 WRITE_ONCE(*x1, 1);53424 r1 = READ_ONCE(*x0);53525 smp_store_release(sl, 0);53626 }5372753828 filter (0:r2=0 /\ 1:r2=0)53929 exists (0:r1=0 /\ 1:r1=0)540541This litmus test may be found here:542543https://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.litmus544545This test uses two global variables, "x1" and "x2", and also emulates a546single global spinlock named "sl". This spinlock is held by whichever547process changes the value of "sl" from "0" to "1", and is released when548that process sets "sl" back to "0". P0()'s lock acquisition is emulated549on line 11 using xchg_acquire(), which unconditionally stores the value550"1" to "sl" and stores either "0" or "1" to "r2", depending on whether551the lock acquisition was successful or unsuccessful (due to "sl" already552having the value "1"), respectively. P1() operates in a similar manner.553554Rather unconventionally, execution appears to proceed to the critical555section on lines 12 and 13 in either case. Line 14 then uses an556smp_store_release() to store zero to "sl", thus emulating lock release.557558The case where xchg_acquire() fails to acquire the lock is handled by559the "filter" clause on line 28, which tells herd7 to keep only those560executions in which both "0:r2" and "1:r2" are zero, that is to pay561attention only to those executions in which both locks are actually562acquired. Thus, the bogus executions that would execute the critical563sections are discarded and any effects that they might have had are564ignored. Note well that the "filter" clause keeps those executions565for which its expression is satisfied, that is, for which the expression566evaluates to true. In other words, the "filter" clause says what to567keep, not what to discard.568569The result of running this test is as follows:5705711 Test C-SB+l-o-o-u+l-o-o-u-X Allowed5722 States 25733 0:r1=0; 1:r1=1;5744 0:r1=1; 1:r1=0;5755 No5766 Witnesses5777 Positive: 0 Negative: 25788 Condition exists (0:r1=0 /\ 1:r1=0)5799 Observation C-SB+l-o-o-u+l-o-o-u-X Never 0 258010 Time C-SB+l-o-o-u+l-o-o-u-X 0.03581582The "Never" on line 9 indicates that this use of xchg_acquire() and583smp_store_release() really does correctly emulate locking.584585Why doesn't the litmus test take the simpler approach of using a spin loop586to handle failed spinlock acquisitions, like the kernel does? The key587insight behind this litmus test is that spin loops have no effect on the588possible "exists"-clause outcomes of program execution in the absence589of deadlock. In other words, given a high-quality lock-acquisition590primitive in a deadlock-free program running on high-quality hardware,591each lock acquisition will eventually succeed. Because herd7 already592explores the full state space, the length of time required to actually593acquire the lock does not matter. After all, herd7 already models all594possible durations of the xchg_acquire() statements.595596Why not just add the "filter" clause to the "exists" clause, thus597avoiding the "filter" clause entirely? This does work, but is slower.598The reason that the "filter" clause is faster is that (in the common case)599herd7 knows to abandon an execution as soon as the "filter" expression600fails to be satisfied. In contrast, the "exists" clause is evaluated601only at the end of time, thus requiring herd7 to waste time on bogus602executions in which both critical sections proceed concurrently. In603addition, some LKMM users like the separation of concerns provided by604using the both the "filter" and "exists" clauses.605606Readers lacking a pathological interest in odd corner cases should feel607free to skip the remainder of this section.608609But what if the litmus test were to temporarily set "0:r2" to a non-zero610value? Wouldn't that cause herd7 to abandon the execution prematurely611due to an early mismatch of the "filter" clause?612613Why not just try it? Line 4 of the following modified litmus test614introduces a new global variable "x2" that is initialized to "1". Line 23615of P1() reads that variable into "1:r2" to force an early mismatch with616the "filter" clause. Line 24 does a known-true "if" condition to avoid617and static analysis that herd7 might do. Finally the "exists" clause618on line 32 is updated to a condition that is alway satisfied at the end619of the test.6206211 C C-SB+l-o-o-u+l-o-o-u-X62226233 {6244 x2=1;6255 }62666277 P0(int *sl, int *x0, int *x1)6288 {6299 int r2;63010 int r1;6311163212 r2 = xchg_acquire(sl, 1);63313 WRITE_ONCE(*x0, 1);63414 r1 = READ_ONCE(*x1);63515 smp_store_release(sl, 0);63616 }6371763818 P1(int *sl, int *x0, int *x1, int *x2)63919 {64020 int r2;64121 int r1;6422264323 r2 = READ_ONCE(*x2);64424 if (r2)64525 r2 = xchg_acquire(sl, 1);64626 WRITE_ONCE(*x1, 1);64727 r1 = READ_ONCE(*x0);64828 smp_store_release(sl, 0);64929 }6503065131 filter (0:r2=0 /\ 1:r2=0)65232 exists (x1=1)653654If the "filter" clause were to check each variable at each point in the655execution, running this litmus test would display no executions because656all executions would be filtered out at line 23. However, the output657is instead as follows:6586591 Test C-SB+l-o-o-u+l-o-o-u-X Allowed6602 States 16613 x1=1;6624 Ok6635 Witnesses6646 Positive: 2 Negative: 06657 Condition exists (x1=1)6668 Observation C-SB+l-o-o-u+l-o-o-u-X Always 2 06679 Time C-SB+l-o-o-u+l-o-o-u-X 0.0466810 Hash=080bc508da7f291e122c6de76c0088e3669670Line 3 shows that there is one execution that did not get filtered out,671so the "filter" clause is evaluated only on the last assignment to672the variables that it checks. In this case, the "filter" clause is a673disjunction, so it might be evaluated twice, once at the final (and only)674assignment to "0:r2" and once at the final assignment to "1:r2".675676677Linked Lists678------------679680LKMM can handle linked lists, but only linked lists in which each node681contains nothing except a pointer to the next node in the list. This is682of course quite restrictive, but there is nevertheless quite a bit that683can be done within these confines, as can be seen in the litmus test684at tools/memory-model/litmus-tests/MP+onceassign+derefonce.litmus:6856861 C MP+onceassign+derefonce68726883 {6894 y=z;6905 z=0;6916 }69276938 P0(int *x, int **y)6949 {69510 WRITE_ONCE(*x, 1);69611 rcu_assign_pointer(*y, x);69712 }6981369914 P1(int *x, int **y)70015 {70116 int *r0;70217 int r1;7031870419 rcu_read_lock();70520 r0 = rcu_dereference(*y);70621 r1 = READ_ONCE(*r0);70722 rcu_read_unlock();70823 }7092471025 exists (1:r0=x /\ 1:r1=0)711712Line 4's "y=z" may seem odd, given that "z" has not yet been initialized.713But "y=z" does not set the value of "y" to that of "z", but instead714sets the value of "y" to the *address* of "z". Lines 4 and 5 therefore715create a simple linked list, with "y" pointing to "z" and "z" having a716NULL pointer. A much longer linked list could be created if desired,717and circular singly linked lists can also be created and manipulated.718719The "exists" clause works the same way, with the "1:r0=x" comparing P1()'s720"r0" not to the value of "x", but again to its address. This term of the721"exists" clause therefore tests whether line 20's load from "y" saw the722value stored by line 11, which is in fact what is required in this case.723724P0()'s line 10 initializes "x" to the value 1 then line 11 links to "x"725from "y", replacing "z".726727P1()'s line 20 loads a pointer from "y", and line 21 dereferences that728pointer. The RCU read-side critical section spanning lines 19-22 is just729for show in this example. Note that the address used for line 21's load730depends on (in this case, "is exactly the same as") the value loaded by731line 20. This is an example of what is called an "address dependency".732This particular address dependency extends from the load on line 20 to the733load on line 21. Address dependencies provide a weak form of ordering.734735Running this test results in the following:7367371 Test MP+onceassign+derefonce Allowed7382 States 27393 1:r0=x; 1:r1=1;7404 1:r0=z; 1:r1=0;7415 No7426 Witnesses7437 Positive: 0 Negative: 27448 Condition exists (1:r0=x /\ 1:r1=0)7459 Observation MP+onceassign+derefonce Never 0 274610 Time MP+onceassign+derefonce 0.0074711 Hash=49ef7a741563570102448a256a0c8568748749The only possible outcomes feature P1() loading a pointer to "z"750(which contains zero) on the one hand and P1() loading a pointer to "x"751(which contains the value one) on the other. This should be reassuring752because it says that RCU readers cannot see the old preinitialization753values when accessing a newly inserted list node. This undesirable754scenario is flagged by the "exists" clause, and would occur if P1()755loaded a pointer to "x", but obtained the pre-initialization value of756zero after dereferencing that pointer.757758759Comments760--------761762Different portions of a litmus test are processed by different parsers,763which has the charming effect of requiring different comment syntax in764different portions of the litmus test. The C-syntax portions use765C-language comments (either "/* */" or "//"), while the other portions766use Ocaml comments "(* *)".767768The following litmus test illustrates the comment style corresponding769to each syntactic unit of the test:7707711 C MP+onceassign+derefonce (* A *)77227733 (* B *)77447755 {7766 y=z; (* C *)7777 z=0;7788 } // D779978010 // E7811178212 P0(int *x, int **y) // F78313 {78414 WRITE_ONCE(*x, 1); // G78515 rcu_assign_pointer(*y, x);78616 }7871778818 // H7891979020 P1(int *x, int **y)79121 {79222 int *r0;79323 int r1;7942479525 rcu_read_lock();79626 r0 = rcu_dereference(*y);79727 r1 = READ_ONCE(*r0);79828 rcu_read_unlock();79929 }8003080131 // I8023280333 exists (* J *) (1:r0=x /\ (* K *) 1:r1=0) (* L *)804805In short, use C-language comments in the C code and Ocaml comments in806the rest of the litmus test.807808On the other hand, if you prefer C-style comments everywhere, the809C preprocessor is your friend.810811812Asynchronous RCU Grace Periods813------------------------------814815The following litmus test is derived from the example show in816Documentation/litmus-tests/rcu/RCU+sync+free.litmus, but converted to817emulate call_rcu():8188191 C RCU+sync+free82028213 {8224 int x = 1;8235 int *y = &x;8246 int z = 1;8257 }82688279 P0(int *x, int *z, int **y)82810 {82911 int *r0;83012 int r1;8311383214 rcu_read_lock();83315 r0 = rcu_dereference(*y);83416 r1 = READ_ONCE(*r0);83517 rcu_read_unlock();83618 }8371983820 P1(int *z, int **y, int *c)83921 {84022 rcu_assign_pointer(*y, z);84123 smp_store_release(*c, 1); // Emulate call_rcu().84224 }8432584426 P2(int *x, int *z, int **y, int *c)84527 {84628 int r0;8472984830 r0 = smp_load_acquire(*c); // Note call_rcu() request.84931 synchronize_rcu(); // Wait one grace period.85032 WRITE_ONCE(*x, 0); // Emulate the RCU callback.85133 }8523485335 filter (2:r0=1) (* Reject too-early starts. *)85436 exists (0:r0=x /\ 0:r1=0)855856Lines 4-6 initialize a linked list headed by "y" that initially contains857"x". In addition, "z" is pre-initialized to prepare for P1(), which858will replace "x" with "z" in this list.859860P0() on lines 9-18 enters an RCU read-side critical section, loads the861list header "y" and dereferences it, leaving the node in "0:r0" and862the node's value in "0:r1".863864P1() on lines 20-24 updates the list header to instead reference "z",865then emulates call_rcu() by doing a release store into "c".866867P2() on lines 27-33 emulates the behind-the-scenes effect of doing a868call_rcu(). Line 30 first does an acquire load from "c", then line 31869waits for an RCU grace period to elapse, and finally line 32 emulates870the RCU callback, which in turn emulates a call to kfree().871872Of course, it is possible for P2() to start too soon, so that the873value of "2:r0" is zero rather than the required value of "1".874The "filter" clause on line 35 handles this possibility, rejecting875all executions in which "2:r0" is not equal to the value "1".876877878Performance879-----------880881LKMM's exploration of the full state-space can be extremely helpful,882but it does not come for free. The price is exponential computational883complexity in terms of the number of processes, the average number884of statements in each process, and the total number of stores in the885litmus test.886887So it is best to start small and then work up. Where possible, break888your code down into small pieces each representing a core concurrency889requirement.890891That said, herd7 is quite fast. On an unprepossessing x86 laptop, it892was able to analyze the following 10-process RCU litmus test in about893six seconds.894895https://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.litmus896897One way to make herd7 run faster is to use the "-speedcheck true" option.898This option prevents herd7 from generating all possible end states,899instead causing it to focus solely on whether or not the "exists"900clause can be satisfied. With this option, herd7 evaluates the above901litmus test in about 300 milliseconds, for more than an order of magnitude902improvement in performance.903904Larger 16-process litmus tests that would normally consume 15 minutes905of time complete in about 40 seconds with this option. To be fair,906you do get an extra 65,535 states when you leave off the "-speedcheck907true" option.908909https://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.litmus910911Nevertheless, litmus-test analysis really is of exponential complexity,912whether with or without "-speedcheck true". Increasing by just three913processes to a 19-process litmus test requires 2 hours and 40 minutes914without, and about 8 minutes with "-speedcheck true". Each of these915results represent roughly an order of magnitude slowdown compared to the91616-process litmus test. Again, to be fair, the multi-hour run explores917no fewer than 524,287 additional states compared to the shorter one.918919https://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.litmus920921If you don't like command-line arguments, you can obtain a similar speedup922by adding a "filter" clause with exactly the same expression as your923"exists" clause.924925However, please note that seeing the full set of states can be extremely926helpful when developing and debugging litmus tests.927928929LIMITATIONS930===========931932Limitations of the Linux-kernel memory model (LKMM) include:9339341. Compiler optimizations are not accurately modeled. Of course,935the use of READ_ONCE() and WRITE_ONCE() limits the compiler's936ability to optimize, but under some circumstances it is possible937for the compiler to undermine the memory model. For more938information, see Documentation/explanation.txt (in particular,939the "THE PROGRAM ORDER RELATION: po AND po-loc" and "A WARNING"940sections).941942Note that this limitation in turn limits LKMM's ability to943accurately model address, control, and data dependencies.944For example, if the compiler can deduce the value of some variable945carrying a dependency, then the compiler can break that dependency946by substituting a constant of that value.947948Conversely, LKMM will sometimes overestimate the amount of949reordering compilers and CPUs can carry out, leading it to miss950some pretty obvious cases of ordering. A simple example is:951952r1 = READ_ONCE(x);953if (r1 == 0)954smp_mb();955WRITE_ONCE(y, 1);956957The WRITE_ONCE() does not depend on the READ_ONCE(), and as a958result, LKMM does not claim ordering. However, even though no959dependency is present, the WRITE_ONCE() will not be executed before960the READ_ONCE(). There are two reasons for this:961962The presence of the smp_mb() in one of the branches963prevents the compiler from moving the WRITE_ONCE()964up before the "if" statement, since the compiler has965to assume that r1 will sometimes be 0 (but see the966comment below);967968CPUs do not execute stores before po-earlier conditional969branches, even in cases where the store occurs after the970two arms of the branch have recombined.971972It is clear that it is not dangerous in the slightest for LKMM to973make weaker guarantees than architectures. In fact, it is974desirable, as it gives compilers room for making optimizations.975For instance, suppose that a 0 value in r1 would trigger undefined976behavior elsewhere. Then a clever compiler might deduce that r1977can never be 0 in the if condition. As a result, said clever978compiler might deem it safe to optimize away the smp_mb(),979eliminating the branch and any ordering an architecture would980guarantee otherwise.9819822. Multiple access sizes for a single variable are not supported,983and neither are misaligned or partially overlapping accesses.9849853. Exceptions and interrupts are not modeled. In some cases,986this limitation can be overcome by modeling the interrupt or987exception with an additional process.9889894. I/O such as MMIO or DMA is not supported.9909915. Self-modifying code (such as that found in the kernel's992alternatives mechanism, function tracer, Berkeley Packet Filter993JIT compiler, and module loader) is not supported.9949956. Complete modeling of all variants of atomic read-modify-write996operations, locking primitives, and RCU is not provided.997For example, call_rcu() and rcu_barrier() are not supported.998However, a substantial amount of support is provided for these999operations, as shown in the linux-kernel.def file.10001001Here are specific limitations:10021003a. When rcu_assign_pointer() is passed NULL, the Linux1004kernel provides no ordering, but LKMM models this1005case as a store release.10061007b. The "unless" RMW operations are not currently modeled:1008atomic_long_add_unless(), atomic_inc_unless_negative(),1009and atomic_dec_unless_positive(). These can be emulated1010in litmus tests, for example, by using atomic_cmpxchg().10111012One exception of this limitation is atomic_add_unless(),1013which is provided directly by herd7 (so no corresponding1014definition in linux-kernel.def). atomic_add_unless() is1015modeled by herd7 therefore it can be used in litmus tests.10161017c. The call_rcu() function is not modeled. As was shown above,1018it can be emulated in litmus tests by adding another1019process that invokes synchronize_rcu() and the body of the1020callback function, with (for example) a release-acquire1021from the site of the emulated call_rcu() to the beginning1022of the additional process.10231024d. The rcu_barrier() function is not modeled. It can be1025emulated in litmus tests emulating call_rcu() via1026(for example) a release-acquire from the end of each1027additional call_rcu() process to the site of the1028emulated rcu-barrier().10291030e. Reader-writer locking is not modeled. It can be1031emulated in litmus tests using atomic read-modify-write1032operations.10331034The fragment of the C language supported by these litmus tests is quite1035limited and in some ways non-standard:103610371. There is no automatic C-preprocessor pass. You can of course1038run it manually, if you choose.103910402. There is no way to create functions other than the Pn() functions1041that model the concurrent processes.104210433. The Pn() functions' formal parameters must be pointers to the1044global shared variables. Nothing can be passed by value into1045these functions.104610474. The only functions that can be invoked are those built directly1048into herd7 or that are defined in the linux-kernel.def file.104910505. The "switch", "do", "for", "while", and "goto" C statements are1051not supported. The "switch" statement can be emulated by the1052"if" statement. The "do", "for", and "while" statements can1053often be emulated by manually unrolling the loop, or perhaps by1054enlisting the aid of the C preprocessor to minimize the resulting1055code duplication. Some uses of "goto" can be emulated by "if",1056and some others by unrolling.105710586. Although you can use a wide variety of types in litmus-test1059variable declarations, and especially in global-variable1060declarations, the "herd7" tool understands only int and1061pointer types. There is no support for floating-point types,1062enumerations, characters, strings, arrays, or structures.106310647. Parsing of variable declarations is very loose, with almost no1065type checking.106610678. Initializers differ from their C-language counterparts.1068For example, when an initializer contains the name of a shared1069variable, that name denotes a pointer to that variable, not1070the current value of that variable. For example, "int x = y"1071is interpreted the way "int x = &y" would be in C.107210739. Dynamic memory allocation is not supported, although this can1074be worked around in some cases by supplying multiple statically1075allocated variables.10761077Some of these limitations may be overcome in the future, but others are1078more likely to be addressed by incorporating the Linux-kernel memory model1079into other tools.10801081Finally, please note that LKMM is subject to change as hardware, use cases,1082and compilers evolve.108310841085