memory-barriers.txt 114 KB
Newer Older
1 2 3 4 5
			 ============================
			 LINUX KERNEL MEMORY BARRIERS
			 ============================

By: David Howells <dhowells@redhat.com>
6
    Paul E. McKenney <paulmck@linux.vnet.ibm.com>
7 8
    Will Deacon <will.deacon@arm.com>
    Peter Zijlstra <peterz@infradead.org>
9

10 11 12 13 14 15 16
==========
DISCLAIMER
==========

This document is not a specification; it is intentionally (for the sake of
brevity) and unintentionally (due to being human) incomplete. This document is
meant as a guide to using the various memory barriers provided by Linux, but
17 18 19 20 21
in case of any doubt (and there are many) please ask.  Some doubts may be
resolved by referring to the formal memory consistency model and related
documentation at tools/memory-model/.  Nevertheless, even this memory
model should be viewed as the collective opinion of its maintainers rather
than as an infallible oracle.
22 23 24 25

To repeat, this document is not a specification of what Linux expects from
hardware.

26 27 28 29 30 31 32 33
The purpose of this document is twofold:

 (1) to specify the minimum functionality that one can rely on for any
     particular barrier, and

 (2) to provide a guide as to how to use the barriers that are available.

Note that an architecture can provide more than the minimum requirement
34
for any particular barrier, but if the architecture provides less than
35 36 37 38 39 40 41
that, that architecture is incorrect.

Note also that it is possible that a barrier may be a no-op for an
architecture because the way that arch works renders an explicit barrier
unnecessary in that case.


42 43 44
========
CONTENTS
========
45 46 47 48 49 50 51 52 53 54

 (*) Abstract memory access model.

     - Device operations.
     - Guarantees.

 (*) What are memory barriers?

     - Varieties of memory barrier.
     - What may not be assumed about memory barriers?
55
     - Data dependency barriers (historical).
56 57 58
     - Control dependencies.
     - SMP barrier pairing.
     - Examples of memory barrier sequences.
59
     - Read memory barriers vs load speculation.
60
     - Multicopy atomicity.
61 62 63 64

 (*) Explicit kernel barriers.

     - Compiler barrier.
65
     - CPU memory barriers.
66 67 68 69
     - MMIO write barrier.

 (*) Implicit kernel memory barriers.

70
     - Lock acquisition functions.
71
     - Interrupt disabling functions.
72
     - Sleep and wake-up functions.
73 74
     - Miscellaneous functions.

75
 (*) Inter-CPU acquiring barrier effects.
76

77 78
     - Acquires vs memory accesses.
     - Acquires vs I/O accesses.
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

 (*) Where are memory barriers needed?

     - Interprocessor interaction.
     - Atomic operations.
     - Accessing devices.
     - Interrupts.

 (*) Kernel I/O barrier effects.

 (*) Assumed minimum execution ordering model.

 (*) The effects of the cpu cache.

     - Cache coherency.
     - Cache coherency vs DMA.
     - Cache coherency vs MMIO.

 (*) The things CPUs get up to.

     - And then there's the Alpha.
100
     - Virtual Machine Guests.
101

102 103 104 105
 (*) Example uses.

     - Circular buffers.

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
 (*) References.


============================
ABSTRACT MEMORY ACCESS MODEL
============================

Consider the following abstract model of the system:

		            :                :
		            :                :
		            :                :
		+-------+   :   +--------+   :   +-------+
		|       |   :   |        |   :   |       |
		|       |   :   |        |   :   |       |
		| CPU 1 |<----->| Memory |<----->| CPU 2 |
		|       |   :   |        |   :   |       |
		|       |   :   |        |   :   |       |
		+-------+   :   +--------+   :   +-------+
		    ^       :       ^        :       ^
		    |       :       |        :       |
		    |       :       |        :       |
		    |       :       v        :       |
		    |       :   +--------+   :       |
		    |       :   |        |   :       |
		    |       :   |        |   :       |
		    +---------->| Device |<----------+
		            :   |        |   :
		            :   |        |   :
		            :   +--------+   :
		            :                :

Each CPU executes a program that generates memory access operations.  In the
abstract CPU, memory operation ordering is very relaxed, and a CPU may actually
perform the memory operations in any order it likes, provided program causality
appears to be maintained.  Similarly, the compiler may also arrange the
instructions it emits in any order it likes, provided it doesn't affect the
apparent operation of the program.

So in the above diagram, the effects of the memory operations performed by a
CPU are perceived by the rest of the system as the operations cross the
interface between the CPU and rest of the system (the dotted lines).


For example, consider the following sequence of events:

	CPU 1		CPU 2
	===============	===============
	{ A == 1; B == 2 }
155 156
	A = 3;		x = B;
	B = 4;		y = A;
157 158 159 160

The set of accesses as seen by the memory system in the middle can be arranged
in 24 different combinations:

161 162 163 164 165 166 167
	STORE A=3,	STORE B=4,	y=LOAD A->3,	x=LOAD B->4
	STORE A=3,	STORE B=4,	x=LOAD B->4,	y=LOAD A->3
	STORE A=3,	y=LOAD A->3,	STORE B=4,	x=LOAD B->4
	STORE A=3,	y=LOAD A->3,	x=LOAD B->2,	STORE B=4
	STORE A=3,	x=LOAD B->2,	STORE B=4,	y=LOAD A->3
	STORE A=3,	x=LOAD B->2,	y=LOAD A->3,	STORE B=4
	STORE B=4,	STORE A=3,	y=LOAD A->3,	x=LOAD B->4
168 169 170 171 172
	STORE B=4, ...
	...

and can thus result in four different combinations of values:

173 174 175 176
	x == 2, y == 1
	x == 2, y == 3
	x == 4, y == 1
	x == 4, y == 3
177 178 179 180 181 182 183 184 185 186 187


Furthermore, the stores committed by a CPU to the memory system may not be
perceived by the loads made by another CPU in the same order as the stores were
committed.


As a further example, consider this sequence of events:

	CPU 1		CPU 2
	===============	===============
188
	{ A == 1, B == 2, C == 3, P == &A, Q == &C }
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
	B = 4;		Q = P;
	P = &B		D = *Q;

There is an obvious data dependency here, as the value loaded into D depends on
the address retrieved from P by CPU 2.  At the end of the sequence, any of the
following results are possible:

	(Q == &A) and (D == 1)
	(Q == &B) and (D == 2)
	(Q == &B) and (D == 4)

Note that CPU 2 will never try and load C into D because the CPU will load P
into Q before issuing the load of *Q.


DEVICE OPERATIONS
-----------------

Some devices present their control interfaces as collections of memory
locations, but the order in which the control registers are accessed is very
important.  For instance, imagine an ethernet card with a set of internal
registers that are accessed through an address port register (A) and a data
port register (D).  To read internal register 5, the following code might then
be used:

	*A = 5;
	x = *D;

but this might show up as either of the following two sequences:

	STORE *A = 5, x = LOAD *D
	x = LOAD *D, STORE *A = 5

the second of which will almost certainly result in a malfunction, since it set
the address _after_ attempting to read the register.


GUARANTEES
----------

There are some minimal guarantees that may be expected of a CPU:

 (*) On any given CPU, dependent memory accesses will be issued in order, with
     respect to itself.  This means that for:

234
	Q = READ_ONCE(P); D = READ_ONCE(*Q);
235 236 237 238 239

     the CPU will issue the following memory operations:

	Q = LOAD P, D = LOAD *Q

240 241 242 243 244 245 246 247
     and always in that order.  However, on DEC Alpha, READ_ONCE() also
     emits a memory-barrier instruction, so that a DEC Alpha CPU will
     instead issue the following memory operations:

	Q = LOAD P, MEMORY_BARRIER, D = LOAD *Q, MEMORY_BARRIER

     Whether on DEC Alpha or not, the READ_ONCE() also prevents compiler
     mischief.
248 249 250 251

 (*) Overlapping loads and stores within a particular CPU will appear to be
     ordered within that CPU.  This means that for:

252
	a = READ_ONCE(*X); WRITE_ONCE(*X, b);
253 254 255 256 257 258 259

     the CPU will only issue the following sequence of memory operations:

	a = LOAD *X, STORE *X = b

     And for:

260
	WRITE_ONCE(*X, c); d = READ_ONCE(*X);
261 262 263 264 265

     the CPU will only issue:

	STORE *X = c, d = LOAD *X

266
     (Loads and stores overlap if they are targeted at overlapping pieces of
267 268 269 270
     memory).

And there are a number of things that _must_ or _must_not_ be assumed:

271 272 273 274
 (*) It _must_not_ be assumed that the compiler will do what you want
     with memory references that are not protected by READ_ONCE() and
     WRITE_ONCE().  Without them, the compiler is within its rights to
     do all sorts of "creative" transformations, which are covered in
275
     the COMPILER BARRIER section.
276

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
 (*) It _must_not_ be assumed that independent loads and stores will be issued
     in the order given.  This means that for:

	X = *A; Y = *B; *D = Z;

     we may get any of the following sequences:

	X = LOAD *A,  Y = LOAD *B,  STORE *D = Z
	X = LOAD *A,  STORE *D = Z, Y = LOAD *B
	Y = LOAD *B,  X = LOAD *A,  STORE *D = Z
	Y = LOAD *B,  STORE *D = Z, X = LOAD *A
	STORE *D = Z, X = LOAD *A,  Y = LOAD *B
	STORE *D = Z, Y = LOAD *B,  X = LOAD *A

 (*) It _must_ be assumed that overlapping memory accesses may be merged or
     discarded.  This means that for:

	X = *A; Y = *(A + 4);

     we may get any one of the following sequences:

	X = LOAD *A; Y = LOAD *(A + 4);
	Y = LOAD *(A + 4); X = LOAD *A;
	{X, Y} = LOAD {*A, *(A + 4) };

     And for:

304
	*A = X; *(A + 4) = Y;
305

306
     we may get any of:
307

308 309 310
	STORE *A = X; STORE *(A + 4) = Y;
	STORE *(A + 4) = Y; STORE *A = X;
	STORE {*A, *(A + 4) } = {X, Y};
311

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
And there are anti-guarantees:

 (*) These guarantees do not apply to bitfields, because compilers often
     generate code to modify these using non-atomic read-modify-write
     sequences.  Do not attempt to use bitfields to synchronize parallel
     algorithms.

 (*) Even in cases where bitfields are protected by locks, all fields
     in a given bitfield must be protected by one lock.  If two fields
     in a given bitfield are protected by different locks, the compiler's
     non-atomic read-modify-write sequences can cause an update to one
     field to corrupt the value of an adjacent field.

 (*) These guarantees apply only to properly aligned and sized scalar
     variables.  "Properly sized" currently means variables that are
     the same size as "char", "short", "int" and "long".  "Properly
     aligned" means the natural alignment, thus no constraints for
     "char", two-byte alignment for "short", four-byte alignment for
     "int", and either four-byte or eight-byte alignment for "long",
     on 32-bit and 64-bit systems, respectively.  Note that these
     guarantees were introduced into the C11 standard, so beware when
     using older pre-C11 compilers (for example, gcc 4.6).  The portion
     of the standard containing this guarantee is Section 3.14, which
     defines "memory location" as follows:

     	memory location
		either an object of scalar type, or a maximal sequence
		of adjacent bit-fields all having nonzero width

		NOTE 1: Two threads of execution can update and access
		separate memory locations without interfering with
		each other.

		NOTE 2: A bit-field and an adjacent non-bit-field member
		are in separate memory locations. The same applies
		to two bit-fields, if one is declared inside a nested
		structure declaration and the other is not, or if the two
		are separated by a zero-length bit-field declaration,
		or if they are separated by a non-bit-field member
		declaration. It is not safe to concurrently update two
		bit-fields in the same structure if all members declared
		between them are also bit-fields, no matter what the
		sizes of those intervening bit-fields happen to be.

356 357 358 359 360 361 362 363 364 365 366

=========================
WHAT ARE MEMORY BARRIERS?
=========================

As can be seen above, independent memory operations are effectively performed
in random order, but this can be a problem for CPU-CPU interaction and for I/O.
What is required is some way of intervening to instruct the compiler and the
CPU to restrict the order.

Memory barriers are such interventions.  They impose a perceived partial
367 368 369
ordering over the memory operations on either side of the barrier.

Such enforcement is important because the CPUs and other devices in a system
370
can use a variety of tricks to improve performance, including reordering,
371 372 373 374
deferral and combination of memory operations; speculative loads; speculative
branch prediction and various types of caching.  Memory barriers are used to
override or suppress these tricks, allowing the code to sanely control the
interaction of multiple CPUs and/or devices.
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391


VARIETIES OF MEMORY BARRIER
---------------------------

Memory barriers come in four basic varieties:

 (1) Write (or store) memory barriers.

     A write memory barrier gives a guarantee that all the STORE operations
     specified before the barrier will appear to happen before all the STORE
     operations specified after the barrier with respect to the other
     components of the system.

     A write barrier is a partial ordering on stores only; it is not required
     to have any effect on loads.

392
     A CPU can be viewed as committing a sequence of store operations to the
393 394
     memory system as time progresses.  All stores _before_ a write barrier
     will occur _before_ all the stores after the write barrier.
395 396 397 398 399 400 401 402 403 404 405

     [!] Note that write barriers should normally be paired with read or data
     dependency barriers; see the "SMP barrier pairing" subsection.


 (2) Data dependency barriers.

     A data dependency barrier is a weaker form of read barrier.  In the case
     where two loads are performed such that the second depends on the result
     of the first (eg: the first load retrieves the address to which the second
     load will be directed), a data dependency barrier would be required to
406
     make sure that the target of the second load is updated after the address
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
     obtained by the first load is accessed.

     A data dependency barrier is a partial ordering on interdependent loads
     only; it is not required to have any effect on stores, independent loads
     or overlapping loads.

     As mentioned in (1), the other CPUs in the system can be viewed as
     committing sequences of stores to the memory system that the CPU being
     considered can then perceive.  A data dependency barrier issued by the CPU
     under consideration guarantees that for any load preceding it, if that
     load touches one of a sequence of stores from another CPU, then by the
     time the barrier completes, the effects of all the stores prior to that
     touched by the load will be perceptible to any loads issued after the data
     dependency barrier.

     See the "Examples of memory barrier sequences" subsection for diagrams
     showing the ordering constraints.

     [!] Note that the first load really has to have a _data_ dependency and
     not a control dependency.  If the address for the second load is dependent
     on the first load, but the dependency is through a conditional rather than
     actually loading the address itself, then it's a _control_ dependency and
     a full read barrier or better is required.  See the "Control dependencies"
     subsection for more information.

     [!] Note that data dependency barriers should normally be paired with
     write barriers; see the "SMP barrier pairing" subsection.


 (3) Read (or load) memory barriers.

     A read barrier is a data dependency barrier plus a guarantee that all the
     LOAD operations specified before the barrier will appear to happen before
     all the LOAD operations specified after the barrier with respect to the
     other components of the system.

     A read barrier is a partial ordering on loads only; it is not required to
     have any effect on stores.

     Read memory barriers imply data dependency barriers, and so can substitute
     for them.

     [!] Note that read barriers should normally be paired with write barriers;
     see the "SMP barrier pairing" subsection.


 (4) General memory barriers.

455 456 457 458 459 460
     A general memory barrier gives a guarantee that all the LOAD and STORE
     operations specified before the barrier will appear to happen before all
     the LOAD and STORE operations specified after the barrier with respect to
     the other components of the system.

     A general memory barrier is a partial ordering over both loads and stores.
461 462 463 464 465 466 467

     General memory barriers imply both read and write memory barriers, and so
     can substitute for either.


And a couple of implicit varieties:

468
 (5) ACQUIRE operations.
469 470

     This acts as a one-way permeable barrier.  It guarantees that all memory
471 472
     operations after the ACQUIRE operation will appear to happen after the
     ACQUIRE operation with respect to the other components of the system.
473 474 475
     ACQUIRE operations include LOCK operations and both smp_load_acquire()
     and smp_cond_acquire() operations. The later builds the necessary ACQUIRE
     semantics from relying on a control dependency and smp_rmb().
476

477 478
     Memory operations that occur before an ACQUIRE operation may appear to
     happen after it completes.
479

480 481
     An ACQUIRE operation should almost always be paired with a RELEASE
     operation.
482 483


484
 (6) RELEASE operations.
485 486

     This also acts as a one-way permeable barrier.  It guarantees that all
487 488 489 490
     memory operations before the RELEASE operation will appear to happen
     before the RELEASE operation with respect to the other components of the
     system. RELEASE operations include UNLOCK operations and
     smp_store_release() operations.
491

492
     Memory operations that occur after a RELEASE operation may appear to
493 494
     happen before it completes.

495 496 497 498 499 500 501 502 503
     The use of ACQUIRE and RELEASE operations generally precludes the need
     for other sorts of memory barrier (but note the exceptions mentioned in
     the subsection "MMIO write barrier").  In addition, a RELEASE+ACQUIRE
     pair is -not- guaranteed to act as a full memory barrier.  However, after
     an ACQUIRE on a given variable, all memory accesses preceding any prior
     RELEASE on that same variable are guaranteed to be visible.  In other
     words, within a given variable's critical section, all accesses of all
     previous critical sections for that variable are guaranteed to have
     completed.
504

505 506
     This means that ACQUIRE acts as a minimal "acquire" operation and
     RELEASE acts as a minimal "release" operation.
507

508 509 510 511 512
A subset of the atomic operations described in atomic_t.txt have ACQUIRE and
RELEASE variants in addition to fully-ordered and relaxed (no barrier
semantics) definitions.  For compound atomics performing both a load and a
store, ACQUIRE semantics apply only to the load and RELEASE semantics apply
only to the store portion of the operation.
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

Memory barriers are only required where there's a possibility of interaction
between two CPUs or between a CPU and a device.  If it can be guaranteed that
there won't be any such interaction in any particular piece of code, then
memory barriers are unnecessary in that piece of code.


Note that these are the _minimum_ guarantees.  Different architectures may give
more substantial guarantees, but they may _not_ be relied upon outside of arch
specific code.


WHAT MAY NOT BE ASSUMED ABOUT MEMORY BARRIERS?
----------------------------------------------

There are certain things that the Linux kernel memory barriers do not guarantee:

 (*) There is no guarantee that any of the memory accesses specified before a
     memory barrier will be _complete_ by the completion of a memory barrier
     instruction; the barrier can be considered to draw a line in that CPU's
     access queue that accesses of the appropriate type may not cross.

 (*) There is no guarantee that issuing a memory barrier on one CPU will have
     any direct effect on another CPU or any other hardware in the system.  The
     indirect effect will be the order in which the second CPU sees the effects
     of the first CPU's accesses occur, but see the next point:

540
 (*) There is no guarantee that a CPU will see the correct order of effects
541 542 543 544 545 546 547 548 549 550 551
     from a second CPU's accesses, even _if_ the second CPU uses a memory
     barrier, unless the first CPU _also_ uses a matching memory barrier (see
     the subsection on "SMP Barrier Pairing").

 (*) There is no guarantee that some intervening piece of off-the-CPU
     hardware[*] will not reorder the memory accesses.  CPU cache coherency
     mechanisms should propagate the indirect effects of a memory barrier
     between CPUs, but might not do so in order.

	[*] For information on bus mastering DMA and coherency please read:

552
	    Documentation/PCI/pci.txt
Paul Bolle's avatar
Paul Bolle committed
553
	    Documentation/DMA-API-HOWTO.txt
554 555 556
	    Documentation/DMA-API.txt


557 558 559 560 561 562 563 564 565
DATA DEPENDENCY BARRIERS (HISTORICAL)
-------------------------------------

As of v4.15 of the Linux kernel, an smp_read_barrier_depends() was
added to READ_ONCE(), which means that about the only people who
need to pay attention to this section are those working on DEC Alpha
architecture-specific code and those working on READ_ONCE() itself.
For those who need it, and for those who are interested in the history,
here is the story of data-dependency barriers.
566 567 568 569 570

The usage requirements of data dependency barriers are a little subtle, and
it's not always obvious that they're needed.  To illustrate, consider the
following sequence of events:

571 572
	CPU 1		      CPU 2
	===============	      ===============
573
	{ A == 1, B == 2, C == 3, P == &A, Q == &C }
574 575
	B = 4;
	<write barrier>
576 577
	WRITE_ONCE(P, &B)
			      Q = READ_ONCE(P);
578
			      D = *Q;
579 580 581 582 583 584 585

There's a clear data dependency here, and it would seem that by the end of the
sequence, Q must be either &A or &B, and that:

	(Q == &A) implies (D == 1)
	(Q == &B) implies (D == 4)

586
But!  CPU 2's perception of P may be updated _before_ its perception of B, thus
587 588 589 590 591 592 593 594
leading to the following situation:

	(Q == &B) and (D == 2) ????

Whilst this may seem like a failure of coherency or causality maintenance, it
isn't, and this behaviour can be observed on certain real CPUs (such as the DEC
Alpha).

595 596
To deal with this, a data dependency barrier or better must be inserted
between the address load and the data load:
597

598 599
	CPU 1		      CPU 2
	===============	      ===============
600
	{ A == 1, B == 2, C == 3, P == &A, Q == &C }
601 602
	B = 4;
	<write barrier>
603 604
	WRITE_ONCE(P, &B);
			      Q = READ_ONCE(P);
605 606
			      <data dependency barrier>
			      D = *Q;
607 608 609 610

This enforces the occurrence of one of the two implications, and prevents the
third possibility from arising.

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

[!] Note that this extremely counterintuitive situation arises most easily on
machines with split caches, so that, for example, one cache bank processes
even-numbered cache lines and the other bank processes odd-numbered cache
lines.  The pointer P might be stored in an odd-numbered cache line, and the
variable B might be stored in an even-numbered cache line.  Then, if the
even-numbered bank of the reading CPU's cache is extremely busy while the
odd-numbered bank is idle, one can see the new value of the pointer P (&B),
but the old value of the variable B (2).


A data-dependency barrier is not required to order dependent writes
because the CPUs that the Linux kernel supports don't do writes
until they are certain (1) that the write will actually happen, (2)
of the location of the write, and (3) of the value to be written.
But please carefully read the "CONTROL DEPENDENCIES" section and the
Documentation/RCU/rcu_dereference.txt file:  The compiler can and does
break dependencies in a great many highly creative ways.
629 630 631 632 633 634 635 636

	CPU 1		      CPU 2
	===============	      ===============
	{ A == 1, B == 2, C = 3, P == &A, Q == &C }
	B = 4;
	<write barrier>
	WRITE_ONCE(P, &B);
			      Q = READ_ONCE(P);
637
			      WRITE_ONCE(*Q, 5);
638

639 640 641
Therefore, no data-dependency barrier is required to order the read into
Q with the store into *Q.  In other words, this outcome is prohibited,
even without a data-dependency barrier:
642

643
	(Q == &B) && (B == 4)
644 645 646 647

Please note that this pattern should be rare.  After all, the whole point
of dependency ordering is to -prevent- writes to the data structure, along
with the expensive cache misses associated with those writes.  This pattern
648 649
can be used to record rare error conditions and the like, and the CPUs'
naturally occurring ordering prevents such records from being lost.
650 651


652 653 654 655 656
Note well that the ordering provided by a data dependency is local to
the CPU containing it.  See the section on "Multicopy atomicity" for
more information.


657 658 659 660 661
The data dependency barrier is very important to the RCU system,
for example.  See rcu_assign_pointer() and rcu_dereference() in
include/linux/rcupdate.h.  This permits the current target of an RCU'd
pointer to be replaced with a new modified target, without the replacement
target appearing to be incompletely initialised.
662 663 664 665 666 667 668

See also the subsection on "Cache Coherency" for a more thorough example.


CONTROL DEPENDENCIES
--------------------

669 670 671 672
Control dependencies can be a bit tricky because current compilers do
not understand them.  The purpose of this section is to help you prevent
the compiler's ignorance from breaking your code.

673 674 675
A load-load control dependency requires a full read memory barrier, not
simply a data dependency barrier to make it work correctly.  Consider the
following bit of code:
676

677
	q = READ_ONCE(a);
678 679
	if (q) {
		<data dependency barrier>  /* BUG: No data dependency!!! */
680
		p = READ_ONCE(b);
681
	}
682 683

This will not have the desired effect because there is no actual data
684 685 686 687
dependency, but rather a control dependency that the CPU may short-circuit
by attempting to predict the outcome in advance, so that other CPUs see
the load from b as having happened before the load from a.  In such a
case what's actually required is:
688

689
	q = READ_ONCE(a);
690
	if (q) {
691
		<read barrier>
692
		p = READ_ONCE(b);
693
	}
694 695

However, stores are not speculated.  This means that ordering -is- provided
696
for load-store control dependencies, as in the following example:
697

698
	q = READ_ONCE(a);
699
	if (q) {
700
		WRITE_ONCE(b, 1);
701 702
	}

703 704 705 706 707 708
Control dependencies pair normally with other types of barriers.
That said, please note that neither READ_ONCE() nor WRITE_ONCE()
are optional! Without the READ_ONCE(), the compiler might combine the
load from 'a' with other loads from 'a'.  Without the WRITE_ONCE(),
the compiler might combine the store to 'b' with other stores to 'b'.
Either can result in highly counterintuitive effects on ordering.
709 710 711 712 713 714 715

Worse yet, if the compiler is able to prove (say) that the value of
variable 'a' is always non-zero, it would be well within its rights
to optimize the original example by eliminating the "if" statement
as follows:

	q = a;
716
	b = 1;  /* BUG: Compiler and CPU can both reorder!!! */
717

718
So don't leave out the READ_ONCE().
719

720 721
It is tempting to try to enforce ordering on identical stores on both
branches of the "if" statement as follows:
722

723
	q = READ_ONCE(a);
724
	if (q) {
725
		barrier();
726
		WRITE_ONCE(b, 1);
727 728
		do_something();
	} else {
729
		barrier();
730
		WRITE_ONCE(b, 1);
731 732 733
		do_something_else();
	}

734 735
Unfortunately, current compilers will transform this as follows at high
optimization levels:
736

737
	q = READ_ONCE(a);
738
	barrier();
739
	WRITE_ONCE(b, 1);  /* BUG: No ordering vs. load from a!!! */
740
	if (q) {
741
		/* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
742 743
		do_something();
	} else {
744
		/* WRITE_ONCE(b, 1); -- moved up, BUG!!! */
745 746 747
		do_something_else();
	}

748 749 750 751 752 753
Now there is no conditional between the load from 'a' and the store to
'b', which means that the CPU is within its rights to reorder them:
The conditional is absolutely required, and must be present in the
assembly code even after all compiler optimizations have been applied.
Therefore, if you need ordering in this example, you need explicit
memory barriers, for example, smp_store_release():
754

755
	q = READ_ONCE(a);
756
	if (q) {
757
		smp_store_release(&b, 1);
758 759
		do_something();
	} else {
760
		smp_store_release(&b, 1);
761 762 763
		do_something_else();
	}

764 765 766
In contrast, without explicit memory barriers, two-legged-if control
ordering is guaranteed only when the stores differ, for example:

767
	q = READ_ONCE(a);
768
	if (q) {
769
		WRITE_ONCE(b, 1);
770 771
		do_something();
	} else {
772
		WRITE_ONCE(b, 2);
773 774 775
		do_something_else();
	}

776 777
The initial READ_ONCE() is still required to prevent the compiler from
proving the value of 'a'.
778 779 780 781 782

In addition, you need to be careful what you do with the local variable 'q',
otherwise the compiler might be able to guess the value and again remove
the needed conditional.  For example:

783
	q = READ_ONCE(a);
784
	if (q % MAX) {
785
		WRITE_ONCE(b, 1);
786 787
		do_something();
	} else {
788
		WRITE_ONCE(b, 2);
789 790 791 792 793 794 795
		do_something_else();
	}

If MAX is defined to be 1, then the compiler knows that (q % MAX) is
equal to zero, in which case the compiler is within its rights to
transform the above code into the following:

796
	q = READ_ONCE(a);
797
	WRITE_ONCE(b, 2);
798 799
	do_something_else();

800 801 802 803 804 805
Given this transformation, the CPU is not required to respect the ordering
between the load from variable 'a' and the store to variable 'b'.  It is
tempting to add a barrier(), but this does not help.  The conditional
is gone, and the barrier won't bring it back.  Therefore, if you are
relying on this ordering, you should make sure that MAX is greater than
one, perhaps as follows:
806

807
	q = READ_ONCE(a);
808 809
	BUILD_BUG_ON(MAX <= 1); /* Order load from a with store to b. */
	if (q % MAX) {
810
		WRITE_ONCE(b, 1);
811 812
		do_something();
	} else {
813
		WRITE_ONCE(b, 2);
814 815 816
		do_something_else();
	}

817 818 819 820
Please note once again that the stores to 'b' differ.  If they were
identical, as noted earlier, the compiler could pull this store outside
of the 'if' statement.

821 822 823
You must also be careful not to rely too much on boolean short-circuit
evaluation.  Consider this example:

824
	q = READ_ONCE(a);
825
	if (q || 1 > 0)
826
		WRITE_ONCE(b, 1);
827

828 829 830
Because the first condition cannot fault and the second condition is
always true, the compiler can transform this example as following,
defeating control dependency:
831

832
	q = READ_ONCE(a);
833
	WRITE_ONCE(b, 1);
834 835

This example underscores the need to ensure that the compiler cannot
836
out-guess your code.  More generally, although READ_ONCE() does force
837 838 839
the compiler to actually emit code for a given load, it does not force
the compiler to use the results.

840 841 842 843 844 845
In addition, control dependencies apply only to the then-clause and
else-clause of the if-statement in question.  In particular, it does
not necessarily apply to code following the if-statement:

	q = READ_ONCE(a);
	if (q) {
846
		WRITE_ONCE(b, 1);
847
	} else {
848
		WRITE_ONCE(b, 2);
849
	}
850
	WRITE_ONCE(c, 1);  /* BUG: No ordering against the read from 'a'. */
851 852 853

It is tempting to argue that there in fact is ordering because the
compiler cannot reorder volatile accesses and also cannot reorder
854 855
the writes to 'b' with the condition.  Unfortunately for this line
of reasoning, the compiler might compile the two writes to 'b' as
856 857 858 859 860
conditional-move instructions, as in this fanciful pseudo-assembly
language:

	ld r1,a
	cmp r1,$0
861 862
	cmov,ne r4,$1
	cmov,eq r4,$2
863 864 865 866
	st r4,b
	st $1,c

A weakly ordered CPU would have no dependency of any sort between the load
867
from 'a' and the store to 'c'.  The control dependencies would extend
868 869 870 871 872
only to the pair of cmov instructions and the store depending on them.
In short, control dependencies apply only to the stores in the then-clause
and else-clause of the if-statement in question (including functions
invoked by those two clauses), not to code following that if-statement.

873

874 875 876
Note well that the ordering provided by a control dependency is local
to the CPU containing it.  See the section on "Multicopy atomicity"
for more information.
877 878 879 880 881 882 883 884


In summary:

  (*) Control dependencies can order prior loads against later stores.
      However, they do -not- guarantee any other sort of ordering:
      Not prior loads against later loads, nor prior stores against
      later anything.  If you need these other forms of ordering,
885
      use smp_rmb(), smp_wmb(), or, in the case of prior stores and
886 887
      later loads, smp_mb().

888 889 890 891
  (*) If both legs of the "if" statement begin with identical stores to
      the same variable, then those stores must be ordered, either by
      preceding both of them with smp_mb() or by using smp_store_release()
      to carry out the stores.  Please note that it is -not- sufficient
892 893 894 895
      to use barrier() at beginning of each leg of the "if" statement
      because, as shown by the example above, optimizing compilers can
      destroy the control dependency while respecting the letter of the
      barrier() law.
896

897
  (*) Control dependencies require at least one run-time conditional
898
      between the prior load and the subsequent store, and this
899 900
      conditional must involve the prior load.  If the compiler is able
      to optimize the conditional away, it will have also optimized
901 902
      away the ordering.  Careful use of READ_ONCE() and WRITE_ONCE()
      can help to preserve the needed conditional.
903 904

  (*) Control dependencies require that the compiler avoid reordering the
905 906
      dependency into nonexistence.  Careful use of READ_ONCE() or
      atomic{,64}_read() can help to preserve your control dependency.
907
      Please see the COMPILER BARRIER section for more information.
908

909 910 911 912 913 914
  (*) Control dependencies apply only to the then-clause and else-clause
      of the if-statement containing the control dependency, including
      any functions that these two clauses call.  Control dependencies
      do -not- apply to code following the if-statement containing the
      control dependency.

915 916
  (*) Control dependencies pair normally with other types of barriers.

917 918
  (*) Control dependencies do -not- provide multicopy atomicity.  If you
      need all the CPUs to see a given store at the same time, use smp_mb().
919

920 921 922
  (*) Compilers do not understand control dependencies.  It is therefore
      your job to ensure that they do not break your code.

923 924 925 926 927 928 929

SMP BARRIER PAIRING
-------------------

When dealing with CPU-CPU interactions, certain types of memory barrier should
always be paired.  A lack of appropriate pairing is almost certainly an error.

930
General barriers pair with each other, though they also pair with most
931 932 933 934 935 936 937 938
other types of barriers, albeit without multicopy atomicity.  An acquire
barrier pairs with a release barrier, but both may also pair with other
barriers, including of course general barriers.  A write barrier pairs
with a data dependency barrier, a control dependency, an acquire barrier,
a release barrier, a read barrier, or a general barrier.  Similarly a
read barrier, control dependency, or a data dependency barrier pairs
with a write barrier, an acquire barrier, a release barrier, or a
general barrier:
939

940 941
	CPU 1		      CPU 2
	===============	      ===============
942
	WRITE_ONCE(a, 1);
943
	<write barrier>
944
	WRITE_ONCE(b, 2);     x = READ_ONCE(b);
945
			      <read barrier>
946
			      y = READ_ONCE(a);
947 948 949

Or:

950 951
	CPU 1		      CPU 2
	===============	      ===============================
952 953
	a = 1;
	<write barrier>
954
	WRITE_ONCE(b, &a);    x = READ_ONCE(b);
955 956
			      <data dependency barrier>
			      y = *x;
957

958 959 960 961
Or even:

	CPU 1		      CPU 2
	===============	      ===============================
962
	r1 = READ_ONCE(y);
963
	<general barrier>
964
	WRITE_ONCE(x, 1);     if (r2 = READ_ONCE(x)) {
965
			         <implicit control dependency>
966
			         WRITE_ONCE(y, 1);
967 968 969 970
			      }

	assert(r1 == 0 || r2 == 0);

971 972 973
Basically, the read barrier always has to be there, even though it can be of
the "weaker" type.

974
[!] Note that the stores before the write barrier would normally be expected to
975
match the loads after the read barrier or the data dependency barrier, and vice
976 977
versa:

978 979
	CPU 1                               CPU 2
	===================                 ===================
980 981
	WRITE_ONCE(a, 1);    }----   --->{  v = READ_ONCE(c);
	WRITE_ONCE(b, 2);    }    \ /    {  w = READ_ONCE(d);
982
	<write barrier>            \        <read barrier>
983 984
	WRITE_ONCE(c, 3);    }    / \    {  x = READ_ONCE(a);
	WRITE_ONCE(d, 4);    }----   --->{  y = READ_ONCE(b);
985

986 987 988 989

EXAMPLES OF MEMORY BARRIER SEQUENCES
------------------------------------

990
Firstly, write barriers act as partial orderings on store operations.
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
Consider the following sequence of events:

	CPU 1
	=======================
	STORE A = 1
	STORE B = 2
	STORE C = 3
	<write barrier>
	STORE D = 4
	STORE E = 5

This sequence of events is committed to the memory coherence system in an order
that the rest of the system might perceive as the unordered set of { STORE A,
1004
STORE B, STORE C } all occurring before the unordered set of { STORE D, STORE E
1005 1006 1007 1008 1009
}:

	+-------+       :      :
	|       |       +------+
	|       |------>| C=3  |     }     /\
1010 1011
	|       |  :    +------+     }-----  \  -----> Events perceptible to
	|       |  :    | A=1  |     }        \/       the rest of the system
1012 1013 1014 1015 1016 1017
	|       |  :    +------+     }
	| CPU 1 |  :    | B=2  |     }
	|       |       +------+     }
	|       |   wwwwwwwwwwwwwwww }   <--- At this point the write barrier
	|       |       +------+     }        requires all stores prior to the
	|       |  :    | E=5  |     }        barrier to be committed before
1018
	|       |  :    +------+     }        further stores may take place
1019 1020 1021 1022
	|       |------>| D=4  |     }
	|       |       +------+
	+-------+       :      :
	                   |
1023 1024
	                   | Sequence in which stores are committed to the
	                   | memory system by CPU 1
1025 1026 1027
	                   V


1028
Secondly, data dependency barriers act as partial orderings on data-dependent
1029 1030 1031 1032
loads.  Consider the following sequence of events:

	CPU 1			CPU 2
	=======================	=======================
1033
		{ B = 7; X = 9; Y = 8; C = &Y }
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
	STORE A = 1
	STORE B = 2
	<write barrier>
	STORE C = &B		LOAD X
	STORE D = 4		LOAD C (gets &B)
				LOAD *C (reads B)

Without intervention, CPU 2 may perceive the events on CPU 1 in some
effectively random order, despite the write barrier issued by CPU 1:

	+-------+       :      :                :       :
	|       |       +------+                +-------+  | Sequence of update
	|       |------>| B=2  |-----       --->| Y->8  |  | of perception on
	|       |  :    +------+     \          +-------+  | CPU 2
	| CPU 1 |  :    | A=1  |      \     --->| C->&Y |  V
	|       |       +------+       |        +-------+
	|       |   wwwwwwwwwwwwwwww   |        :       :
	|       |       +------+       |        :       :
	|       |  :    | C=&B |---    |        :       :       +-------+
	|       |  :    +------+   \   |        +-------+       |       |
	|       |------>| D=4  |    ----------->| C->&B |------>|       |
	|       |       +------+       |        +-------+       |       |
	+-------+       :      :       |        :       :       |       |
	                               |        :       :       |       |
	                               |        :       :       | CPU 2 |
	                               |        +-------+       |       |
	    Apparently incorrect --->  |        | B->7  |------>|       |
	    perception of B (!)        |        +-------+       |       |
	                               |        :       :       |       |
	                               |        +-------+       |       |
	    The load of X holds --->    \       | X->9  |------>|       |
	    up the maintenance           \      +-------+       |       |
	    of coherence of B             ----->| B->2  |       +-------+
	                                        +-------+
	                                        :       :


In the above example, CPU 2 perceives that B is 7, despite the load of *C
1072
(which would be B) coming after the LOAD of C.
1073 1074

If, however, a data dependency barrier were to be placed between the load of C
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
and the load of *C (ie: B) on CPU 2:

	CPU 1			CPU 2
	=======================	=======================
		{ B = 7; X = 9; Y = 8; C = &Y }
	STORE A = 1
	STORE B = 2
	<write barrier>
	STORE C = &B		LOAD X
	STORE D = 4		LOAD C (gets &B)
				<data dependency barrier>
				LOAD *C (reads B)

then the following will occur:
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| B=2  |-----       --->| Y->8  |
	|       |  :    +------+     \          +-------+
	| CPU 1 |  :    | A=1  |      \     --->| C->&Y |
	|       |       +------+       |        +-------+
	|       |   wwwwwwwwwwwwwwww   |        :       :
	|       |       +------+       |        :       :
	|       |  :    | C=&B |---    |        :       :       +-------+
	|       |  :    +------+   \   |        +-------+       |       |
	|       |------>| D=4  |    ----------->| C->&B |------>|       |
	|       |       +------+       |        +-------+       |       |
	+-------+       :      :       |        :       :       |       |
	                               |        :       :       |       |
	                               |        :       :       | CPU 2 |
	                               |        +-------+       |       |
1106 1107 1108 1109 1110 1111
	                               |        | X->9  |------>|       |
	                               |        +-------+       |       |
	  Makes sure all effects --->   \   ddddddddddddddddd   |       |
	  prior to the store of C        \      +-------+       |       |
	  are perceptible to              ----->| B->2  |------>|       |
	  subsequent loads                      +-------+       |       |
1112 1113 1114 1115 1116 1117 1118 1119
	                                        :       :       +-------+


And thirdly, a read barrier acts as a partial order on loads.  Consider the
following sequence of events:

	CPU 1			CPU 2
	=======================	=======================
1120
		{ A = 0, B = 9 }
1121 1122
	STORE A=1
	<write barrier>
1123
	STORE B=2
1124
				LOAD B
1125
				LOAD A
1126 1127 1128 1129

Without intervention, CPU 2 may then choose to perceive the events on CPU 1 in
some effectively random order, despite the write barrier issued by CPU 1:

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       | A->0  |------>|       |
	                                |       +-------+       |       |
	                                |       :       :       +-------+
	                                 \      :       :
	                                  \     +-------+
	                                   ---->| A->1  |
	                                        +-------+
	                                        :       :
1149

1150

1151
If, however, a read barrier were to be placed between the load of B and the
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
load of A on CPU 2:

	CPU 1			CPU 2
	=======================	=======================
		{ A = 0, B = 9 }
	STORE A=1
	<write barrier>
	STORE B=2
				LOAD B
				<read barrier>
				LOAD A

then the partial ordering imposed by CPU 1 will be perceived correctly by CPU
2:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       :       :       |       |
	                                |       :       :       |       |
	  At this point the read ---->   \  rrrrrrrrrrrrrrrrr   |       |
	  barrier causes all effects      \     +-------+       |       |
	  prior to the storage of B        ---->| A->1  |------>|       |
	  to be perceptible to CPU 2            +-------+       |       |
	                                        :       :       +-------+


To illustrate this more completely, consider what could happen if the code
contained a load of A either side of the read barrier:

	CPU 1			CPU 2
	=======================	=======================
		{ A = 0, B = 9 }
	STORE A=1
	<write barrier>
	STORE B=2
				LOAD B
				LOAD A [first load of A]
				<read barrier>
				LOAD A [second load of A]

Even though the two loads of A both occur after the load of B, they may both
come up with different values:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       :       :       |       |
	                                |       :       :       |       |
	                                |       +-------+       |       |
	                                |       | A->0  |------>| 1st   |
	                                |       +-------+       |       |
	  At this point the read ---->   \  rrrrrrrrrrrrrrrrr   |       |
	  barrier causes all effects      \     +-------+       |       |
	  prior to the storage of B        ---->| A->1  |------>| 2nd   |
	  to be perceptible to CPU 2            +-------+       |       |
	                                        :       :       +-------+


But it may be that the update to A from CPU 1 becomes perceptible to CPU 2
before the read barrier completes anyway:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       :       :       |       |
	                                 \      :       :       |       |
	                                  \     +-------+       |       |
	                                   ---->| A->1  |------>| 1st   |
	                                        +-------+       |       |
	                                    rrrrrrrrrrrrrrrrr   |       |
	                                        +-------+       |       |
	                                        | A->1  |------>| 2nd   |
	                                        +-------+       |       |
	                                        :       :       +-------+


The guarantee is that the second load will always come up with A == 1 if the
load of B came up with B == 2.  No such guarantee exists for the first load of
A; that may come up with either A == 0 or A == 1.


READ MEMORY BARRIERS VS LOAD SPECULATION
----------------------------------------

Many CPUs speculate with loads: that is they see that they will need to load an
item from memory, and they find a time where they're not using the bus for any
other loads, and so do the load in advance - even though they haven't actually
got to that point in the instruction execution flow yet.  This permits the
actual load instruction to potentially complete immediately because the CPU
already has the value to hand.

It may turn out that the CPU didn't actually need the value - perhaps because a
branch circumvented the load - in which case it can discard the value or just
cache it for later use.

Consider:

1274
	CPU 1			CPU 2
1275
	=======================	=======================
1276 1277 1278 1279
				LOAD B
				DIVIDE		} Divide instructions generally
				DIVIDE		} take a long time to perform
				LOAD A
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301

Which might appear as this:

	                                        :       :       +-------+
	                                        +-------+       |       |
	                                    --->| B->2  |------>|       |
	                                        +-------+       | CPU 2 |
	                                        :       :DIVIDE |       |
	                                        +-------+       |       |
	The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
	division speculates on the              +-------+   ~   |       |
	LOAD of A                               :       :   ~   |       |
	                                        :       :DIVIDE |       |
	                                        :       :   ~   |       |
	Once the divisions are complete -->     :       :   ~-->|       |
	the CPU can then perform the            :       :       |       |
	LOAD with immediate effect              :       :       +-------+


Placing a read barrier or a data dependency barrier just before the second
load:

1302
	CPU 1			CPU 2
1303
	=======================	=======================
1304 1305 1306
				LOAD B
				DIVIDE
				DIVIDE
1307
				<read barrier>
1308
				LOAD A
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352

will force any value speculatively obtained to be reconsidered to an extent
dependent on the type of barrier used.  If there was no change made to the
speculated memory location, then the speculated value will just be used:

	                                        :       :       +-------+
	                                        +-------+       |       |
	                                    --->| B->2  |------>|       |
	                                        +-------+       | CPU 2 |
	                                        :       :DIVIDE |       |
	                                        +-------+       |       |
	The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
	division speculates on the              +-------+   ~   |       |
	LOAD of A                               :       :   ~   |       |
	                                        :       :DIVIDE |       |
	                                        :       :   ~   |       |
	                                        :       :   ~   |       |
	                                    rrrrrrrrrrrrrrrr~   |       |
	                                        :       :   ~   |       |
	                                        :       :   ~-->|       |
	                                        :       :       |       |
	                                        :       :       +-------+


but if there was an update or an invalidation from another CPU pending, then
the speculation will be cancelled and the value reloaded:

	                                        :       :       +-------+
	                                        +-------+       |       |
	                                    --->| B->2  |------>|       |
	                                        +-------+       | CPU 2 |
	                                        :       :DIVIDE |       |
	                                        +-------+       |       |
	The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
	division speculates on the              +-------+   ~   |       |
	LOAD of A                               :       :   ~   |       |
	                                        :       :DIVIDE |       |
	                                        :       :   ~   |       |
	                                        :       :   ~   |       |
	                                    rrrrrrrrrrrrrrrrr   |       |
	                                        +-------+       |       |
	The speculation is discarded --->   --->| A->1  |------>|       |
	and an updated value is                 +-------+       |       |
	retrieved                               :       :       +-------+
1353 1354


1355 1356 1357 1358 1359
MULTICOPY ATOMICITY
--------------------

Multicopy atomicity is a deeply intuitive notion about ordering that is
not always provided by real computer systems, namely that a given store
1360 1361 1362 1363 1364 1365 1366
becomes visible at the same time to all CPUs, or, alternatively, that all
CPUs agree on the order in which all stores become visible.  However,
support of full multicopy atomicity would rule out valuable hardware
optimizations, so a weaker form called ``other multicopy atomicity''
instead guarantees only that a given store becomes visible at the same
time to all -other- CPUs.  The remainder of this document discusses this
weaker form, but for brevity will call it simply ``multicopy atomicity''.
1367

1368
The following example demonstrates multicopy atomicity:
1369 1370 1371 1372

	CPU 1			CPU 2			CPU 3
	=======================	=======================	=======================
		{ X = 0, Y = 0 }
1373 1374 1375
	STORE X=1		r1=LOAD X (reads 1)	LOAD Y (reads 1)
				<general barrier>	<read barrier>
				STORE Y=r1		LOAD X
1376

1377 1378 1379 1380 1381 1382
Suppose that CPU 2's load from X returns 1, which it then stores to Y,
and CPU 3's load from Y returns 1.  This indicates that CPU 1's store
to X precedes CPU 2's load from X and that CPU 2's store to Y precedes
CPU 3's load from Y.  In addition, the memory barriers guarantee that
CPU 2 executes its load before its store, and CPU 3 loads from Y before
it loads from X.  The question is then "Can CPU 3's load from X return 0?"
1383

1384
Because CPU 3's load from X in some sense comes after CPU 2's load, it
1385
is natural to expect that CPU 3's load from X must therefore return 1.
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
This expectation follows from multicopy atomicity: if a load executing
on CPU B follows a load from the same variable executing on CPU A (and
CPU A did not originally store the value which it read), then on
multicopy-atomic systems, CPU B's load must return either the same value
that CPU A's load did or some later value.  However, the Linux kernel
does not require systems to be multicopy atomic.

The use of a general memory barrier in the example above compensates
for any lack of multicopy atomicity.  In the example, if CPU 2's load
from X returns 1 and CPU 3's load from Y returns 1, then CPU 3's load
from X must indeed also return 1.
1397 1398 1399 1400 1401

However, dependencies, read barriers, and write barriers are not always
able to compensate for non-multicopy atomicity.  For example, suppose
that CPU 2's general barrier is removed from the above example, leaving
only the data dependency shown below:
1402 1403 1404 1405

	CPU 1			CPU 2			CPU 3
	=======================	=======================	=======================
		{ X = 0, Y = 0 }
1406 1407 1408 1409 1410 1411 1412 1413 1414
	STORE X=1		r1=LOAD X (reads 1)	LOAD Y (reads 1)
				<data dependency>	<read barrier>
				STORE Y=r1		LOAD X (reads 0)

This substitution allows non-multicopy atomicity to run rampant: in
this example, it is perfectly legal for CPU 2's load from X to return 1,
CPU 3's load from Y to return 1, and its load from X to return 0.

The key point is that although CPU 2's data dependency orders its load
1415 1416 1417 1418 1419
and store, it does not guarantee to order CPU 1's store.  Thus, if this
example runs on a non-multicopy-atomic system where CPUs 1 and 2 share a
store buffer or a level of cache, CPU 2 might have early access to CPU 1's
writes.  General barriers are therefore required to ensure that all CPUs
agree on the combined order of multiple accesses.
1420 1421 1422 1423 1424 1425 1426 1427

General barriers can compensate not only for non-multicopy atomicity,
but can also generate additional ordering that can ensure that -all-
CPUs will perceive the same order of -all- operations.  In contrast, a
chain of release-acquire pairs do not provide this additional ordering,
which means that only those CPUs on the chain are guaranteed to agree
on the combined order of the accesses.  For example, switching to C code
in deference to the ghost of Herman Hollerith:
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458

	int u, v, x, y, z;

	void cpu0(void)
	{
		r0 = smp_load_acquire(&x);
		WRITE_ONCE(u, 1);
		smp_store_release(&y, 1);
	}

	void cpu1(void)
	{
		r1 = smp_load_acquire(&y);
		r4 = READ_ONCE(v);
		r5 = READ_ONCE(u);
		smp_store_release(&z, 1);
	}

	void cpu2(void)
	{
		r2 = smp_load_acquire(&z);
		smp_store_release(&x, 1);
	}

	void cpu3(void)
	{
		WRITE_ONCE(v, 1);
		smp_mb();
		r3 = READ_ONCE(u);
	}

1459 1460 1461
Because cpu0(), cpu1(), and cpu2() participate in a chain of
smp_store_release()/smp_load_acquire() pairs, the following outcome
is prohibited:
1462 1463 1464 1465 1466 1467 1468 1469 1470

	r0 == 1 && r1 == 1 && r2 == 1

Furthermore, because of the release-acquire relationship between cpu0()
and cpu1(), cpu1() must see cpu0()'s writes, so that the following
outcome is prohibited:

	r1 == 1 && r5 == 0

1471 1472 1473
However, the ordering provided by a release-acquire chain is local
to the CPUs participating in that chain and does not apply to cpu3(),
at least aside from stores.  Therefore, the following outcome is possible:
1474 1475 1476

	r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0

1477 1478 1479 1480
As an aside, the following outcome is also possible:

	r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0 && r5 == 1

1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
Although cpu0(), cpu1(), and cpu2() will see their respective reads and
writes in order, CPUs not involved in the release-acquire chain might
well disagree on the order.  This disagreement stems from the fact that
the weak memory-barrier instructions used to implement smp_load_acquire()
and smp_store_release() are not required to order prior stores against
subsequent loads in all cases.  This means that cpu3() can see cpu0()'s
store to u as happening -after- cpu1()'s load from v, even though
both cpu0() and cpu1() agree that these two operations occurred in the
intended order.

However, please keep in mind that smp_load_acquire() is not magic.
In particular, it simply reads from its argument with ordering.  It does
-not- ensure that any particular value will be read.  Therefore, the
following outcome is possible:

	r0 == 0 && r1 == 0 && r2 == 0 && r5 == 0

Note that this outcome can happen even on a mythical sequentially
consistent system where nothing is ever reordered.

1501 1502
To reiterate, if your code requires full ordering of all operations,
use general barriers throughout.
1503 1504


1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
========================
EXPLICIT KERNEL BARRIERS
========================

The Linux kernel has a variety of different barriers that act at different
levels:

  (*) Compiler barrier.

  (*) CPU memory barriers.

  (*) MMIO write barrier.


COMPILER BARRIER
----------------

The Linux kernel has an explicit compiler barrier function that prevents the
compiler from moving the memory accesses either side of it to the other side:

	barrier();

1527 1528 1529 1530
This is a general barrier -- there are no read-read or write-write
variants of barrier().  However, READ_ONCE() and WRITE_ONCE() can be
thought of as weak forms of barrier() that affect only the specific
accesses flagged by the READ_ONCE() or WRITE_ONCE().
1531

1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
The barrier() function has the following effects:

 (*) Prevents the compiler from reordering accesses following the
     barrier() to precede any accesses preceding the barrier().
     One example use for this property is to ease communication between
     interrupt-handler code and the code that was interrupted.

 (*) Within a loop, forces the compiler to load the variables used
     in that loop's conditional on each pass through that loop.

1542 1543 1544 1545
The READ_ONCE() and WRITE_ONCE() functions can prevent any number of
optimizations that, while perfectly safe in single-threaded code, can
be fatal in concurrent code.  Here are some examples of these sorts
of optimizations:
1546

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
 (*) The compiler is within its rights to reorder loads and stores
     to the same variable, and in some cases, the CPU is within its
     rights to reorder loads to the same variable.  This means that
     the following code:

	a[0] = x;
	a[1] = x;

     Might result in an older value of x stored in a[1] than in a[0].
     Prevent both the compiler and the CPU from doing this as follows:

1558 1559
	a[0] = READ_ONCE(x);
	a[1] = READ_ONCE(x);
1560

1561 1562
     In short, READ_ONCE() and WRITE_ONCE() provide cache coherence for
     accesses from multiple CPUs to a single variable.
1563

1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
 (*) The compiler is within its rights to merge successive loads from
     the same variable.  Such merging can cause the compiler to "optimize"
     the following code:

	while (tmp = a)
		do_something_with(tmp);

     into the following code, which, although in some sense legitimate
     for single-threaded code, is almost certainly not what the developer
     intended:

	if (tmp = a)
		for (;;)
			do_something_with(tmp);

1579
     Use READ_ONCE() to prevent the compiler from doing this to you:
1580

1581
	while (tmp = READ_ONCE(a))
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
		do_something_with(tmp);

 (*) The compiler is within its rights to reload a variable, for example,
     in cases where high register pressure prevents the compiler from
     keeping all data of interest in registers.  The compiler might
     therefore optimize the variable 'tmp' out of our previous example:

	while (tmp = a)
		do_something_with(tmp);

     This could result in the following code, which is perfectly safe in
     single-threaded code, but can be fatal in concurrent code:

	while (a)
		do_something_with(a);

     For example, the optimized version of this code could result in
     passing a zero to do_something_with() in the case where the variable
     a was modified by some other CPU between the "while" statement and
     the call to do_something_with().

1603
     Again, use READ_ONCE() to prevent the compiler from doing this:
1604

1605
	while (tmp = READ_ONCE(a))
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
		do_something_with(tmp);

     Note that if the compiler runs short of registers, it might save
     tmp onto the stack.  The overhead of this saving and later restoring
     is why compilers reload variables.  Doing so is perfectly safe for
     single-threaded code, so you need to tell the compiler about cases
     where it is not safe.

 (*) The compiler is within its rights to omit a load entirely if it knows
     what the value will be.  For example, if the compiler can prove that
     the value of variable 'a' is always zero, it can optimize this code:

	while (tmp = a)
		do_something_with(tmp);

     Into this:

	do { } while (0);

1625 1626 1627 1628 1629 1630
     This transformation is a win for single-threaded code because it
     gets rid of a load and a branch.  The problem is that the compiler
     will carry out its proof assuming that the current CPU is the only
     one updating variable 'a'.  If variable 'a' is shared, then the
     compiler's proof will be erroneous.  Use READ_ONCE() to tell the
     compiler that it doesn't know as much as it thinks it does:
1631

1632
	while (tmp = READ_ONCE(a))
1633 1634 1635
		do_something_with(tmp);

     But please note that the compiler is also closely watching what you
1636
     do with the value after the READ_ONCE().  For example, suppose you
1637 1638
     do the following and MAX is a preprocessor macro with the value 1:

1639
	while ((tmp = READ_ONCE(a)) % MAX)
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
		do_something_with(tmp);

     Then the compiler knows that the result of the "%" operator applied
     to MAX will always be zero, again allowing the compiler to optimize
     the code into near-nonexistence.  (It will still load from the
     variable 'a'.)

 (*) Similarly, the compiler is within its rights to omit a store entirely
     if it knows that the variable already has the value being stored.
     Again, the compiler assumes that the current CPU is the only one
     storing into the variable, which can cause the compiler to do the
     wrong thing for shared variables.  For example, suppose you have
     the following:

	a = 0;
1655
	... Code that does not store to variable a ...
1656 1657 1658 1659 1660 1661 1662
	a = 0;

     The compiler sees that the value of variable 'a' is already zero, so
     it might well omit the second store.  This would come as a fatal
     surprise if some other CPU might have stored to variable 'a' in the
     meantime.

1663
     Use WRITE_ONCE() to prevent the compiler from making this sort of
1664 1665
     wrong guess:

1666
	WRITE_ONCE(a, 0);
1667
	... Code that does not store to variable a ...
1668
	WRITE_ONCE(a, 0);
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685

 (*) The compiler is within its rights to reorder memory accesses unless
     you tell it not to.  For example, consider the following interaction
     between process-level code and an interrupt handler:

	void process_level(void)
	{
		msg = get_message();
		flag = true;
	}

	void interrupt_handler(void)
	{
		if (flag)
			process_message(msg);
	}

Masanari Iida's avatar
Masanari Iida committed
1686
     There is nothing to prevent the compiler from transforming
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
     process_level() to the following, in fact, this might well be a
     win for single-threaded code:

	void process_level(void)
	{
		flag = true;
		msg = get_message();
	}

     If the interrupt occurs between these two statement, then
1697
     interrupt_handler() might be passed a garbled msg.  Use WRITE_ONCE()
1698 1699 1700 1701
     to prevent this as follows:

	void process_level(void)
	{
1702 1703
		WRITE_ONCE(msg, get_message());
		WRITE_ONCE(flag, true);
1704 1705 1706 1707
	}

	void interrupt_handler(void)
	{
1708 1709
		if (READ_ONCE(flag))
			process_message(READ_ONCE(msg));
1710 1711
	}

1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
     Note that the READ_ONCE() and WRITE_ONCE() wrappers in
     interrupt_handler() are needed if this interrupt handler can itself
     be interrupted by something that also accesses 'flag' and 'msg',
     for example, a nested interrupt or an NMI.  Otherwise, READ_ONCE()
     and WRITE_ONCE() are not needed in interrupt_handler() other than
     for documentation purposes.  (Note also that nested interrupts
     do not typically occur in modern Linux kernels, in fact, if an
     interrupt handler returns with interrupts enabled, you will get a
     WARN_ONCE() splat.)

     You should assume that the compiler can move READ_ONCE() and
     WRITE_ONCE() past code not containing READ_ONCE(), WRITE_ONCE(),
     barrier(), or similar primitives.

     This effect could also be achieved using barrier(), but READ_ONCE()
     and WRITE_ONCE() are more selective:  With READ_ONCE() and
     WRITE_ONCE(), the compiler need only forget the contents of the
     indicated memory locations, while with barrier() the compiler must
     discard the value of all memory locations that it has currented
     cached in any machine registers.  Of course, the compiler must also
     respect the order in which the READ_ONCE()s and WRITE_ONCE()s occur,
     though the CPU of course need not do so.
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752

 (*) The compiler is within its rights to invent stores to a variable,
     as in the following example:

	if (a)
		b = a;
	else
		b = 42;

     The compiler might save a branch by optimizing this as follows:

	b = 42;
	if (a)
		b = a;

     In single-threaded code, this is not only safe, but also saves
     a branch.  Unfortunately, in concurrent code, this optimization
     could cause some other CPU to see a spurious value of 42 -- even
     if variable 'a' was never zero -- when loading variable 'b'.
1753
     Use WRITE_ONCE() to prevent this as follows:
1754 1755

	if (a)
1756
		WRITE_ONCE(b, a);
1757
	else
1758
		WRITE_ONCE(b, 42);
1759 1760 1761

     The compiler can also invent loads.  These are usually less
     damaging, but they can result in cache-line bouncing and thus in
1762
     poor performance and scalability.  Use READ_ONCE() to prevent
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
     invented loads.

 (*) For aligned memory locations whose size allows them to be accessed
     with a single memory-reference instruction, prevents "load tearing"
     and "store tearing," in which a single large access is replaced by
     multiple smaller accesses.  For example, given an architecture having
     16-bit store instructions with 7-bit immediate fields, the compiler
     might be tempted to use two 16-bit store-immediate instructions to
     implement the following 32-bit store:

	p = 0x00010002;

     Please note that GCC really does use this sort of optimization,
     which is not surprising given that it would likely take more
     than two instructions to build the constant and then store it.
     This optimization can therefore be a win in single-threaded code.
     In fact, a recent bug (since fixed) caused GCC to incorrectly use
     this optimization in a volatile store.  In the absence of such bugs,
1781
     use of WRITE_ONCE() prevents store tearing in the following example:
1782

1783
	WRITE_ONCE(p, 0x00010002);
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799

     Use of packed structures can also result in load and store tearing,
     as in this example:

	struct __attribute__((__packed__)) foo {
		short a;
		int b;
		short c;
	};
	struct foo foo1, foo2;
	...

	foo2.a = foo1.a;
	foo2.b = foo1.b;
	foo2.c = foo1.c;

1800 1801 1802 1803 1804 1805
     Because there are no READ_ONCE() or WRITE_ONCE() wrappers and no
     volatile markings, the compiler would be well within its rights to
     implement these three assignment statements as a pair of 32-bit
     loads followed by a pair of 32-bit stores.  This would result in
     load tearing on 'foo1.b' and store tearing on 'foo2.b'.  READ_ONCE()
     and WRITE_ONCE() again prevent tearing in this example:
1806 1807

	foo2.a = foo1.a;
1808
	WRITE_ONCE(foo2.b, READ_ONCE(foo1.b));
1809 1810
	foo2.c = foo1.c;

1811 1812 1813 1814 1815 1816
All that aside, it is never necessary to use READ_ONCE() and
WRITE_ONCE() on a variable that has been marked volatile.  For example,
because 'jiffies' is marked volatile, it is never necessary to
say READ_ONCE(jiffies).  The reason for this is that READ_ONCE() and
WRITE_ONCE() are implemented as volatile casts, which has no effect when
its argument is already marked volatile.
1817 1818 1819

Please note that these compiler barriers have no direct effect on the CPU,
which may then reorder things however it wishes.
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831


CPU MEMORY BARRIERS
-------------------

The Linux kernel has eight basic CPU memory barriers:

	TYPE		MANDATORY		SMP CONDITIONAL
	===============	=======================	===========================
	GENERAL		mb()			smp_mb()
	WRITE		wmb()			smp_wmb()
	READ		rmb()			smp_rmb()
1832
	DATA DEPENDENCY				READ_ONCE()
1833 1834


1835
All memory barriers except the data dependency barriers imply a compiler
1836
barrier.  Data dependencies do not impose any additional compiler ordering.
1837

1838 1839 1840 1841 1842
Aside: In the case of data dependencies, the compiler would be expected
to issue the loads in the correct order (eg. `a[b]` would have to load
the value of b before loading a[b]), however there is no guarantee in
the C specification that the compiler may not speculate the value of b
(eg. is equal to 1) and load a before b (eg. tmp = a[1]; if (b != 1)
1843 1844
tmp = a[b]; ).  There is also the problem of a compiler reloading b after
having loaded a[b], thus having a newer copy of b than a[b].  A consensus
1845 1846
has not yet been reached about these problems, however the READ_ONCE()
macro is a good place to start looking.
1847 1848

SMP memory barriers are reduced to compiler barriers on uniprocessor compiled
1849
systems because it is assumed that a CPU will appear to be self-consistent,
1850
and will order overlapping accesses correctly with respect to itself.
1851
However, see the subsection on "Virtual Machine Guests" below.
1852 1853 1854 1855 1856 1857

[!] Note that SMP memory barriers _must_ be used to control the ordering of
references to shared memory on SMP systems, though the use of locking instead
is sufficient.

Mandatory barriers should not be used to control SMP effects, since mandatory
1858 1859 1860 1861 1862
barriers impose unnecessary overhead on both SMP and UP systems. They may,
however, be used to control MMIO effects on accesses through relaxed memory I/O
windows.  These barriers are required even on non-SMP systems as they affect
the order in which memory operations appear to a device by prohibiting both the
compiler and the CPU from reordering them.
1863 1864 1865 1866


There are some more advanced barrier functions:

1867
 (*) smp_store_mb(var, value)
1868

1869
     This assigns the value to the variable and then inserts a full memory
1870 1871
     barrier after it.  It isn't guaranteed to insert anything more than a
     compiler barrier in a UP compilation.
1872 1873


1874 1875
 (*) smp_mb__before_atomic();
 (*) smp_mb__after_atomic();
1876

1877 1878 1879 1880 1881 1882
     These are for use with atomic (such as add, subtract, increment and
     decrement) functions that don't return a value, especially when used for
     reference counting.  These functions do not imply memory barriers.

     These are also used for atomic bitop functions that do not return a
     value (such as set_bit and clear_bit).
1883 1884 1885 1886 1887

     As an example, consider a piece of code that marks an object as being dead
     and then decrements the object's reference count:

	obj->dead = 1;
1888
	smp_mb__before_atomic();
1889 1890 1891 1892 1893
	atomic_dec(&obj->ref_count);

     This makes sure that the death mark on the object is perceived to be set
     *before* the reference counter is decremented.

1894
     See Documentation/atomic_{t,bitops}.txt for more information.
1895 1896


1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
 (*) dma_wmb();
 (*) dma_rmb();

     These are for use with consistent memory to guarantee the ordering
     of writes or reads of shared memory accessible to both the CPU and a
     DMA capable device.

     For example, consider a device driver that shares memory with a device
     and uses a descriptor status value to indicate if the descriptor belongs
     to the device or the CPU, and a doorbell to notify it when new
     descriptors are available:

	if (desc->status != DEVICE_OWN) {
		/* do not read data until we own descriptor */
		dma_rmb();

		/* read/modify data */
		read_data = desc->data;
		desc->data = write_data;

		/* flush modifications before status update */
		dma_wmb();

		/* assign ownership */
		desc->status = DEVICE_OWN;

		/* force memory to sync before notifying device via MMIO */
		wmb();

		/* notify device of new descriptors */
		writel(DESC_NOTIFY, doorbell);
	}

     The dma_rmb() allows us guarantee the device has released ownership
1931
     before we read the data from the descriptor, and the dma_wmb() allows