[PATCH] doc: memory-barriers: reStructure Text

From: afzal mohammed
Date: Wed Jan 03 2018 - 04:35:40 EST


Let PDF & HTML's be created out of memory-barriers Text by
reStructuring.

reStructuring done were,
1. Section headers modification, lower header case except start
2. Removal of manual index(contents section), since it now gets created
automatically for html/pdf
3. Internal cross reference for easy navigation
4. Alignment adjustments
5. Strong emphasis made wherever there was emphasis earlier (through
other ways), strong was chosen as normal emphasis showed in italics,
which was felt to be not enough & strong showed it in bold
6. ASCII text & code snippets in literal blocks
7. Backquotes for inline instances in the paragraph's where they are
expressed not in English, but in C, pseudo-code, file path etc.
8. Notes section created out of the earlier notes
9. Manual numbering replaced by auto-numbering
10.Bibliography (References section) made such that it can be
cross-linked

Signed-off-by: afzal mohammed <afzal.mohd.ma@xxxxxxxxx>
---

Hi,

With this change, pdf & html could be generated. There certainly are
improvements to be made, but thought of first knowing whether migrating
memory-barriers from txt to rst is welcome.

The location chosen is "Documentation/kernel-hacking", i was unsure
where this should reside & there was no .rst file in top-level directory
"Documentation", so put it into one of the existing folder that seemed
to me as not that unsuitable.

Other files refer to memory-barrier.txt, those also needs to be
adjusted based on where .rst can reside.

afzal


Documentation/kernel-hacking/index.rst | 1 +
.../memory-barriers.rst} | 1707 ++++++++++----------
2 files changed, 837 insertions(+), 871 deletions(-)
rename Documentation/{memory-barriers.txt => kernel-hacking/memory-barriers.rst} (63%)

diff --git a/Documentation/kernel-hacking/index.rst b/Documentation/kernel-hacking/index.rst
index fcb0eda3cca3..20eb56d02ea5 100644
--- a/Documentation/kernel-hacking/index.rst
+++ b/Documentation/kernel-hacking/index.rst
@@ -7,3 +7,4 @@ Kernel Hacking Guides

hacking
locking
+ memory-barriers
diff --git a/Documentation/memory-barriers.txt b/Documentation/kernel-hacking/memory-barriers.rst
similarity index 63%
rename from Documentation/memory-barriers.txt
rename to Documentation/kernel-hacking/memory-barriers.rst
index 479ecec80593..60b6a8be8a09 100644
--- a/Documentation/memory-barriers.txt
+++ b/Documentation/kernel-hacking/memory-barriers.rst
@@ -1,14 +1,13 @@
- ============================
- LINUX KERNEL MEMORY BARRIERS
- ============================
+============================
+Linux kernel memory barriers
+============================

-By: David Howells <dhowells@xxxxxxxxxx>
- Paul E. McKenney <paulmck@xxxxxxxxxxxxxxxxxx>
- Will Deacon <will.deacon@xxxxxxx>
- Peter Zijlstra <peterz@xxxxxxxxxxxxx>
+:Authors: David Howells <dhowells@xxxxxxxxxx>,
+ Paul E. McKenney <paulmck@xxxxxxxxxxxxxxxxxx>,
+ Will Deacon <will.deacon@xxxxxxx>,
+ Peter Zijlstra <peterz@xxxxxxxxxxxxx>

-==========
-DISCLAIMER
+Disclaimer
==========

This document is not a specification; it is intentionally (for the sake of
@@ -21,10 +20,9 @@ hardware.

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.
+* to specify the minimum functionality that one can rely on for any
+ particular barrier
+* 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
for any particular barrier, but if the architecture provides less than
@@ -35,78 +33,10 @@ architecture because the way that arch works renders an explicit barrier
unnecessary in that case.


-========
-CONTENTS
-========
-
- (*) Abstract memory access model.
-
- - Device operations.
- - Guarantees.
-
- (*) What are memory barriers?
-
- - Varieties of memory barrier.
- - What may not be assumed about memory barriers?
- - Data dependency barriers.
- - Control dependencies.
- - SMP barrier pairing.
- - Examples of memory barrier sequences.
- - Read memory barriers vs load speculation.
- - Multicopy atomicity.
-
- (*) Explicit kernel barriers.
-
- - Compiler barrier.
- - CPU memory barriers.
- - MMIO write barrier.
-
- (*) Implicit kernel memory barriers.
-
- - Lock acquisition functions.
- - Interrupt disabling functions.
- - Sleep and wake-up functions.
- - Miscellaneous functions.
-
- (*) Inter-CPU acquiring barrier effects.
-
- - Acquires vs memory accesses.
- - Acquires vs I/O accesses.
-
- (*) 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.
- - Virtual Machine Guests.
-
- (*) Example uses.
-
- - Circular buffers.
-
- (*) References.
-
-
-============================
-ABSTRACT MEMORY ACCESS MODEL
+Abstract memory access model
============================

-Consider the following abstract model of the system:
+Consider the following abstract model of the system::

: :
: :
@@ -143,7 +73,7 @@ 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:
+For example, consider the following sequence of events::

CPU 1 CPU 2
=============== ===============
@@ -152,7 +82,7 @@ interface between the CPU and rest of the system (the dotted lines).
B = 4; y = A;

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

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
@@ -164,7 +94,7 @@ The set of accesses as seen by the memory system in the middle can be arranged
STORE B=4, ...
...

-and can thus result in four different combinations of values:
+and can thus result in four different combinations of values::

x == 2, y == 1
x == 2, y == 3
@@ -177,7 +107,7 @@ 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:
+As a further example, consider this sequence of events::

CPU 1 CPU 2
=============== ===============
@@ -187,17 +117,17 @@ committed.

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:
+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.
+into Q before issuing the load of \*Q.


-DEVICE OPERATIONS
+Device operations
-----------------

Some devices present their control interfaces as collections of memory
@@ -205,74 +135,76 @@ 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:
+be used::

*A = 5;
x = *D;

-but this might show up as either of the following two sequences:
+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.
+the address **after** attempting to read the register.


-GUARANTEES
+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:
+* On any given CPU, dependent memory accesses will be issued in order, with
+ respect to itself. This means that for::

Q = READ_ONCE(P); smp_read_barrier_depends(); D = READ_ONCE(*Q);

- the CPU will issue the following memory operations:
+ the CPU will issue the following memory operations::

Q = LOAD P, D = LOAD *Q

- and always in that order. On most systems, smp_read_barrier_depends()
- does nothing, but it is required for DEC Alpha. The READ_ONCE()
- is required to prevent compiler mischief. Please note that you
- should normally use something like rcu_dereference() instead of
- open-coding smp_read_barrier_depends().
+ and always in that order. On most systems, ``smp_read_barrier_depends()``
+ does nothing, but it is required for DEC Alpha. The ``READ_ONCE()``
+ is required to prevent compiler mischief. Please note that you
+ should normally use something like ``rcu_dereference()`` instead of
+ open-coding ``smp_read_barrier_depends()``.

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

a = READ_ONCE(*X); WRITE_ONCE(*X, b);

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

a = LOAD *X, STORE *X = b

- And for:
+ And for::

WRITE_ONCE(*X, c); d = READ_ONCE(*X);

- the CPU will only issue:
+ the CPU will only issue::

STORE *X = c, d = LOAD *X

- (Loads and stores overlap if they are targeted at overlapping pieces of
- memory).
+ .. note::

-And there are a number of things that _must_ or _must_not_ be assumed:
+ Loads and stores overlap if they are targeted at overlapping pieces
+ of memory.

- (*) 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
- the COMPILER BARRIER section.
+And there are a number of things that **must** or **must not** be assumed:

- (*) It _must_not_ be assumed that independent loads and stores will be issued
- in the order given. This means that for:
+* 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
+ the :ref:`compiler-barrier` section.
+
+* 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:
+ 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
@@ -281,22 +213,22 @@ GUARANTEES
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:
+* 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:
+ 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:
+ And for::

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

- we may get any of:
+ we may get any of::

STORE *A = X; STORE *(A + 4) = Y;
STORE *(A + 4) = Y; STORE *A = X;
@@ -304,28 +236,28 @@ GUARANTEES

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:
+* 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
@@ -347,8 +279,7 @@ GUARANTEES
sizes of those intervening bit-fields happen to be.


-=========================
-WHAT ARE MEMORY BARRIERS?
+What are memory barriers?
=========================

As can be seen above, independent memory operations are effectively performed
@@ -367,138 +298,146 @@ override or suppress these tricks, allowing the code to sanely control the
interaction of multiple CPUs and/or devices.


-VARIETIES OF MEMORY BARRIER
+Varieties of memory barrier
---------------------------

Memory barriers come in four basic varieties:

- (1) Write (or store) memory barriers.
+#. 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.
+
+ A CPU can be viewed as committing a sequence of store operations to the
+ memory system as time progresses. All stores **before** a write barrier
+ will occur **before** all the stores after the write barrier.
+
+ .. note::

- 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.
+ write barriers should normally be paired with read or data
+ dependency barriers; see :ref:`smp-barrier-pairing`.

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

- A CPU can be viewed as committing a sequence of store operations to the
- memory system as time progresses. All stores _before_ a write barrier
- will occur _before_ all the stores after the write barrier.
+#. Data dependency barriers

- [!] Note that write barriers should normally be paired with read or data
- dependency barriers; see the "SMP barrier pairing" subsection.
+ 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
+ make sure that the target of the second load is updated before the address
+ 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.

- (2) Data dependency barriers.
+ 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.

- 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
- make sure that the target of the second load is updated before the address
- obtained by the first load is accessed.
+ See :ref:`examples-of-memory--barrier-sequences` for diagrams showing the
+ ordering constraints.

- 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.
+ .. note::

- 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.
+ 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
+ :ref:`control-dependencies` for more information.

- See the "Examples of memory barrier sequences" subsection for diagrams
- showing the ordering constraints.
+ .. note::

- [!] 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.
+ data dependency barriers should normally be paired with write
+ barriers; see :ref:`smp-barrier-pairing`.

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

+#. Read (or load) memory barriers

- (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 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.

- 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.

- Read memory barriers imply data dependency barriers, and so can substitute
- for them.
+ .. note::

- [!] Note that read barriers should normally be paired with write barriers;
- see the "SMP barrier pairing" subsection.
+ read barriers should normally be paired with write barriers; see
+ :ref:`smp-barrier-pairing`.


- (4) General memory barriers.
+#. General memory barriers

- 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 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.
+ A general memory barrier is a partial ordering over both loads and stores.

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


And a couple of implicit varieties:

- (5) ACQUIRE operations.
+#. ACQUIRE operations

- This acts as a one-way permeable barrier. It guarantees that all memory
- operations after the ACQUIRE operation will appear to happen after the
- ACQUIRE operation with respect to the other components of the system.
- 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().
+ This acts as a one-way permeable barrier. It guarantees that all memory
+ operations after the ACQUIRE operation will appear to happen after the
+ ACQUIRE operation with respect to the other components of the system.
+ 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()``.

- Memory operations that occur before an ACQUIRE operation may appear to
- happen after it completes.
+ Memory operations that occur before an ACQUIRE operation may appear to
+ happen after it completes.

- An ACQUIRE operation should almost always be paired with a RELEASE
- operation.
+ An ACQUIRE operation should almost always be paired with a RELEASE
+ operation.


- (6) RELEASE operations.
+#. RELEASE operations

- This also acts as a one-way permeable barrier. It guarantees that all
- 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.
+ This also acts as a one-way permeable barrier. It guarantees that all
+ 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.

- Memory operations that occur after a RELEASE operation may appear to
- happen before it completes.
+ Memory operations that occur after a RELEASE operation may appear to
+ happen before it completes.

- 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.
+ 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 :ref:`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.

- This means that ACQUIRE acts as a minimal "acquire" operation and
- RELEASE acts as a minimal "release" operation.
+ This means that ACQUIRE acts as a minimal "acquire" operation and
+ RELEASE acts as a minimal "release" operation.

-A subset of the atomic operations described in atomic_t.txt have ACQUIRE and
+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
@@ -509,50 +448,47 @@ 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.

-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?
+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:
+* 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 a CPU will see the correct order of effects
- 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 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:

- (*) 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.
+* There is no guarantee that a CPU will see the correct order of effects
+ 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
+ :ref:`smp-barrier-pairing`).

- [*] For information on bus mastering DMA and coherency please read:
+* 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.

- Documentation/PCI/pci.txt
- Documentation/DMA-API-HOWTO.txt
- Documentation/DMA-API.txt
+ .. [#] For bus mastering DMA and coherency details, please read
+ ``Documentation/PCI/pci.txt``, ``Documentation/DMA-API-HOWTO.txt``,
+ and ``Documentation/DMA-API.txt``


-DATA DEPENDENCY BARRIERS
+Data dependency barriers
------------------------

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:
+following sequence of events::

CPU 1 CPU 2
=============== ===============
@@ -564,13 +500,13 @@ it's not always obvious that they're needed. To illustrate, consider the
D = *Q;

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:
+sequence, Q must be either &A or &B, and that::

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

But! CPU 2's perception of P may be updated _before_ its perception of B, thus
-leading to the following situation:
+leading to the following situation::

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

@@ -579,7 +515,7 @@ isn't, and this behaviour can be observed on certain real CPUs (such as the DEC
Alpha).

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

CPU 1 CPU 2
=============== ===============
@@ -594,25 +530,28 @@ To deal with this, a data dependency barrier or better must be inserted
This enforces the occurrence of one of the two implications, and prevents the
third possibility from arising.

+.. note::

-[!] 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).
+ 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
+But please carefully read :ref:`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.

+::
+
CPU 1 CPU 2
=============== ===============
{ A == 1, B == 2, C = 3, P == &A, Q == &C }
@@ -623,8 +562,8 @@ break dependencies in a great many highly creative ways.
WRITE_ONCE(*Q, 5);

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:
+Q with the store into \*Q. In other words, this outcome is prohibited,
+even without a data-dependency barrier::

(Q == &B) && (B == 4)

@@ -641,15 +580,17 @@ more information.


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
+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.

-See also the subsection on "Cache Coherency" for a more thorough example.
+See also :ref:`cache-coherency` for a more thorough example.`


-CONTROL DEPENDENCIES
+.. _control-dependencies:
+
+Control dependencies
--------------------

Control dependencies can be a bit tricky because current compilers do
@@ -658,7 +599,7 @@ the compiler's ignorance from breaking your code.

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:
+following bit of code::

q = READ_ONCE(a);
if (q) {
@@ -670,7 +611,7 @@ This will not have the desired effect because there is no actual data
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:
+case what's actually required is::

q = READ_ONCE(a);
if (q) {
@@ -679,7 +620,7 @@ the load from b as having happened before the load from a. In such a
}

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

q = READ_ONCE(a);
if (q) {
@@ -687,24 +628,24 @@ However, stores are not speculated. This means that ordering -is- provided
}

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(),
+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.

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:
+as follows::

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

-So don't leave out the READ_ONCE().
+So don't leave out the ``READ_ONCE()``.

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

q = READ_ONCE(a);
if (q) {
@@ -718,7 +659,7 @@ It is tempting to try to enforce ordering on identical stores on both
}

Unfortunately, current compilers will transform this as follows at high
-optimization levels:
+optimization levels::

q = READ_ONCE(a);
barrier();
@@ -736,7 +677,7 @@ Now there is no conditional between the load from 'a' and the store to
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():
+memory barriers, for example, ``smp_store_release()``::

q = READ_ONCE(a);
if (q) {
@@ -748,7 +689,7 @@ Therefore, if you need ordering in this example, you need explicit
}

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

q = READ_ONCE(a);
if (q) {
@@ -759,12 +700,12 @@ In contrast, without explicit memory barriers, two-legged-if control
do_something_else();
}

-The initial READ_ONCE() is still required to prevent the compiler from
+The initial ``READ_ONCE()`` is still required to prevent the compiler from
proving the value of 'a'.

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:
+the needed conditional. For example::

q = READ_ONCE(a);
if (q % MAX) {
@@ -777,7 +718,7 @@ otherwise the compiler might be able to guess the value and again remove

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:
+transform the above code into the following::

q = READ_ONCE(a);
WRITE_ONCE(b, 2);
@@ -785,10 +726,10 @@ equal to zero, in which case the compiler is within its rights to

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
+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:
+one, perhaps as follows::

q = READ_ONCE(a);
BUILD_BUG_ON(MAX <= 1); /* Order load from a with store to b. */
@@ -805,7 +746,7 @@ identical, as noted earlier, the compiler could pull this store outside
of the 'if' statement.

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

q = READ_ONCE(a);
if (q || 1 > 0)
@@ -813,19 +754,19 @@ You must also be careful not to rely too much on boolean short-circuit

Because the first condition cannot fault and the second condition is
always true, the compiler can transform this example as following,
-defeating control dependency:
+defeating control dependency::

q = READ_ONCE(a);
WRITE_ONCE(b, 1);

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

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:
+not necessarily apply to code following the if-statement::

q = READ_ONCE(a);
if (q) {
@@ -840,7 +781,7 @@ compiler cannot reorder volatile accesses and also cannot reorder
the writes to 'b' with the condition. Unfortunately for this line
of reasoning, the compiler might compile the two writes to 'b' as
conditional-move instructions, as in this fanciful pseudo-assembly
-language:
+language::

ld r1,a
cmp r1,$0
@@ -858,56 +799,56 @@ invoked by those two clauses), not to code following that if-statement.


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.
+to the CPU containing it. See :ref:`multicopy-atomicity` for more information.


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,
- use smp_rmb(), smp_wmb(), or, in the case of prior stores and
- later loads, smp_mb().
-
- (*) 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
- 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.
-
- (*) Control dependencies require at least one run-time conditional
- between the prior load and the subsequent store, and this
- conditional must involve the prior load. If the compiler is able
- to optimize the conditional away, it will have also optimized
- away the ordering. Careful use of READ_ONCE() and WRITE_ONCE()
- can help to preserve the needed conditional.
-
- (*) Control dependencies require that the compiler avoid reordering the
- dependency into nonexistence. Careful use of READ_ONCE() or
- atomic{,64}_read() can help to preserve your control dependency.
- Please see the COMPILER BARRIER section for more information.
-
- (*) 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.
-
- (*) Control dependencies pair normally with other types of barriers.
-
- (*) 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().
-
- (*) Compilers do not understand control dependencies. It is therefore
- your job to ensure that they do not break your code.
-
-
-SMP BARRIER PAIRING
+* 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,
+ use ``smp_rmb()``, ``smp_wmb()``, or, in the case of prior stores
+ and later loads, ``smp_mb()``.
+
+* 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
+ 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.
+
+* Control dependencies require at least one run-time conditional
+ between the prior load and the subsequent store, and this
+ conditional must involve the prior load. If the compiler is able
+ to optimize the conditional away, it will have also optimized
+ away the ordering. Careful use of ``READ_ONCE()`` and ``WRITE_ONCE()``
+ can help to preserve the needed conditional.
+
+* Control dependencies require that the compiler avoid reordering the
+ dependency into nonexistence. Careful use of ``READ_ONCE()`` or
+ ``atomic{,64}_read()`` can help to preserve your control dependency.
+ Please see :ref:`compiler-barrier` section for more information.
+
+* 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.
+
+* Control dependencies pair normally with other types of barriers.
+
+* 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()``.
+
+* Compilers do not understand control dependencies. It is therefore
+ your job to ensure that they do not break your code.
+
+.. _smp-barrier-pairing:
+
+SMP barrier pairing
-------------------

When dealing with CPU-CPU interactions, certain types of memory barrier should
@@ -921,7 +862,7 @@ 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:
+general barrier::

CPU 1 CPU 2
=============== ===============
@@ -931,7 +872,7 @@ with a write barrier, an acquire barrier, a release barrier, or a
<read barrier>
y = READ_ONCE(a);

-Or:
+Or::

CPU 1 CPU 2
=============== ===============================
@@ -941,7 +882,7 @@ with a write barrier, an acquire barrier, a release barrier, or a
<data dependency barrier>
y = *x;

-Or even:
+Or even::

CPU 1 CPU 2
=============== ===============================
@@ -957,9 +898,11 @@ with a write barrier, an acquire barrier, a release barrier, or a
Basically, the read barrier always has to be there, even though it can be of
the "weaker" type.

-[!] Note that the stores before the write barrier would normally be expected to
-match the loads after the read barrier or the data dependency barrier, and vice
-versa:
+.. note::
+
+ The stores before the write barrier would normally be expected to
+ match the loads after the read barrier or the data dependency barrier,
+ and vice versa::

CPU 1 CPU 2
=================== ===================
@@ -969,12 +912,13 @@ match the loads after the read barrier or the data dependency barrier, and vice
WRITE_ONCE(c, 3); } / \ { x = READ_ONCE(a);
WRITE_ONCE(d, 4); }---- --->{ y = READ_ONCE(b);

+.. _examples-of-memory--barrier-sequences:

-EXAMPLES OF MEMORY BARRIER SEQUENCES
+Examples of memory barrier sequences
------------------------------------

Firstly, write barriers act as partial orderings on store operations.
-Consider the following sequence of events:
+Consider the following sequence of events::

CPU 1
=======================
@@ -988,7 +932,7 @@ Firstly, write barriers act as partial orderings on store operations.
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,
STORE B, STORE C } all occurring before the unordered set of { STORE D, STORE E
-}:
+}::

+-------+ : :
| | +------+
@@ -1012,7 +956,7 @@ STORE B, STORE C } all occurring before the unordered set of { STORE D, STORE E


Secondly, data dependency barriers act as partial orderings on data-dependent
-loads. Consider the following sequence of events:
+loads. Consider the following sequence of events::

CPU 1 CPU 2
======================= =======================
@@ -1025,7 +969,7 @@ Secondly, data dependency barriers act as partial orderings on data-dependent
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:
+effectively random order, despite the write barrier issued by CPU 1::

+-------+ : : : :
| | +------+ +-------+ | Sequence of update
@@ -1054,11 +998,11 @@ Without intervention, CPU 2 may perceive the events on CPU 1 in some
: :


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

If, however, a data dependency barrier were to be placed between the load of C
-and the load of *C (ie: B) on CPU 2:
+and the load of \*C (ie: B) on CPU 2::

CPU 1 CPU 2
======================= =======================
@@ -1071,7 +1015,7 @@ If, however, a data dependency barrier were to be placed between the load of C
<data dependency barrier>
LOAD *C (reads B)

-then the following will occur:
+then the following will occur::

+-------+ : : : :
| | +------+ +-------+
@@ -1099,7 +1043,7 @@ If, however, a data dependency barrier were to be placed between the load of C


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

CPU 1 CPU 2
======================= =======================
@@ -1111,7 +1055,7 @@ And thirdly, a read barrier acts as a partial order on loads. Consider the
LOAD A

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:
+some effectively random order, despite the write barrier issued by CPU 1::

+-------+ : : : :
| | +------+ +-------+
@@ -1135,7 +1079,7 @@ Without intervention, CPU 2 may then choose to perceive the events on CPU 1 in


If, however, a read barrier were to be placed between the load of B and the
-load of A on CPU 2:
+load of A on CPU 2::

CPU 1 CPU 2
======================= =======================
@@ -1148,7 +1092,7 @@ If, however, a read barrier were to be placed between the load of B and the
LOAD A

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

+-------+ : : : :
| | +------+ +-------+
@@ -1171,7 +1115,7 @@ then the partial ordering imposed by CPU 1 will be perceived correctly by CPU


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

CPU 1 CPU 2
======================= =======================
@@ -1185,7 +1129,7 @@ To illustrate this more completely, consider what could happen if the code
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:
+come up with different values::

+-------+ : : : :
| | +------+ +-------+
@@ -1211,7 +1155,7 @@ Even though the two loads of A both occur after the load of B, they may both


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

+-------+ : : : :
| | +------+ +-------+
@@ -1241,7 +1185,7 @@ 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
+Read memory barriers vs load speculation
----------------------------------------

Many CPUs speculate with loads: that is they see that they will need to load an
@@ -1255,7 +1199,7 @@ 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:
+Consider::

CPU 1 CPU 2
======================= =======================
@@ -1264,7 +1208,7 @@ cache it for later use.
DIVIDE } take a long time to perform
LOAD A

-Which might appear as this:
+Which might appear as this::

: : +-------+
+-------+ | |
@@ -1283,7 +1227,7 @@ cache it for later use.


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

CPU 1 CPU 2
======================= =======================
@@ -1295,7 +1239,7 @@ Placing a read barrier or a data dependency barrier just before the second

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:
+speculated memory location, then the speculated value will just be used::

: : +-------+
+-------+ | |
@@ -1317,7 +1261,7 @@ dependent on the type of barrier used. If there was no change made to the


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

: : +-------+
+-------+ | |
@@ -1337,8 +1281,9 @@ but if there was an update or an invalidation from another CPU pending, then
and an updated value is +-------+ | |
retrieved : : +-------+

+.. _multicopy-atomicity:

-MULTICOPY ATOMICITY
+Multicopy atomicity
--------------------

Multicopy atomicity is a deeply intuitive notion about ordering that is
@@ -1346,12 +1291,12 @@ not always provided by real computer systems, namely that a given store
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''
+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''.
+time to all **other** CPUs. The remainder of this document discusses this
+weaker form, but for brevity will call it simply ``multicopy atomicity``.

-The following example demonstrates multicopy atomicity:
+The following example demonstrates multicopy atomicity::

CPU 1 CPU 2 CPU 3
======================= ======================= =======================
@@ -1384,7 +1329,7 @@ from X must indeed also return 1.
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:
+only the data dependency shown below::

CPU 1 CPU 2 CPU 3
======================= ======================= =======================
@@ -1410,7 +1355,7 @@ 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:
+in deference to the ghost of Herman Hollerith::

int u, v, x, y, z;

@@ -1442,42 +1387,42 @@ on the combined order of the accesses. For example, switching to C code
r3 = READ_ONCE(u);
}

-Because cpu0(), cpu1(), and cpu2() participate in a chain of
-smp_store_release()/smp_load_acquire() pairs, the following outcome
-is prohibited:
+Because ``cpu0()``, ``cpu1()``, and ``cpu2()`` participate in a chain of
+``smp_store_release()``/``smp_load_acquire()`` pairs, the following outcome
+is prohibited::

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:
+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

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:
+to the CPUs participating in that chain and does not apply to ``cpu3()``,
+at least aside from stores. Therefore, the following outcome is possible::

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

-As an aside, the following outcome is also possible:
+As an aside, the following outcome is also possible::

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

-Although cpu0(), cpu1(), and cpu2() will see their respective reads and
-writes in order, CPUs not involved in the release-acquire chain might
+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
+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.
+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:
+following outcome is possible::

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

@@ -1488,58 +1433,58 @@ To reiterate, if your code requires full ordering of all operations,
use general barriers throughout.


-========================
-EXPLICIT KERNEL BARRIERS
+Explicit kernel barriers
========================

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

- (*) Compiler barrier.
+* Compiler barrier.

- (*) CPU memory barriers.
+* CPU memory barriers.

- (*) MMIO write barrier.
+* MMIO write barrier.

+.. _compiler-barrier:

-COMPILER 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:
+compiler from moving the memory accesses either side of it to the other side::

barrier();

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().
+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()``.

-The barrier() function has the following effects:
+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.
+* 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.
+* Within a loop, forces the compiler to load the variables used
+ in that loop's conditional on each pass through that loop.

-The READ_ONCE() and WRITE_ONCE() functions can prevent any number of
+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:

- (*) 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:
+* 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:
+ 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::

a[0] = READ_ONCE(x);
a[1] = READ_ONCE(x);
@@ -1547,115 +1492,115 @@ be fatal in concurrent code. Here are some examples of these sorts
In short, READ_ONCE() and WRITE_ONCE() provide cache coherence for
accesses from multiple CPUs to a single variable.

- (*) 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:
+* 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:
+ 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);

- Use READ_ONCE() to prevent the compiler from doing this to you:
+ Use ``READ_ONCE()`` to prevent the compiler from doing this to you::

while (tmp = READ_ONCE(a))
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:
+* 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:
+ 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().
+ 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()``.

- Again, use READ_ONCE() to prevent the compiler from doing this:
+ Again, use ``READ_ONCE()`` to prevent the compiler from doing this::

while (tmp = READ_ONCE(a))
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.
+ 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:
+* 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:
+ Into this::

do { } while (0);

- 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:
+ 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::

while (tmp = READ_ONCE(a))
do_something_with(tmp);

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

while ((tmp = READ_ONCE(a)) % MAX)
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'.)
+ 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:
+* 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;
... Code that does not store to variable a ...
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.
+ 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.

- Use WRITE_ONCE() to prevent the compiler from making this sort of
- wrong guess:
+ Use ``WRITE_ONCE()`` to prevent the compiler from making this sort of
+ wrong guess::

WRITE_ONCE(a, 0);
... Code that does not store to variable a ...
WRITE_ONCE(a, 0);

- (*) 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:
+* 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)
{
@@ -1669,9 +1614,9 @@ be fatal in concurrent code. Here are some examples of these sorts
process_message(msg);
}

- There is nothing to prevent the compiler from transforming
- process_level() to the following, in fact, this might well be a
- win for single-threaded code:
+ There is nothing to prevent the compiler from transforming
+ ``process_level()`` to the following, in fact, this might well be a
+ win for single-threaded code::

void process_level(void)
{
@@ -1679,9 +1624,9 @@ be fatal in concurrent code. Here are some examples of these sorts
msg = get_message();
}

- If the interrupt occurs between these two statement, then
- interrupt_handler() might be passed a garbled msg. Use WRITE_ONCE()
- to prevent this as follows:
+ If the interrupt occurs between these two statement, then
+ ``interrupt_handler()`` might be passed a garbled msg. Use ``WRITE_ONCE()``
+ to prevent this as follows::

void process_level(void)
{
@@ -1695,81 +1640,81 @@ be fatal in concurrent code. Here are some examples of these sorts
process_message(READ_ONCE(msg));
}

- 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.
-
- (*) The compiler is within its rights to invent stores to a variable,
- as in the following example:
+ 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.
+
+* 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:
+ 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'.
- Use WRITE_ONCE() to prevent this as follows:
+ 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``.
+ Use ``WRITE_ONCE()`` to prevent this as follows::

if (a)
WRITE_ONCE(b, a);
else
WRITE_ONCE(b, 42);

- The compiler can also invent loads. These are usually less
- damaging, but they can result in cache-line bouncing and thus in
- poor performance and scalability. Use READ_ONCE() to prevent
- invented loads.
+ The compiler can also invent loads. These are usually less
+ damaging, but they can result in cache-line bouncing and thus in
+ poor performance and scalability. Use ``READ_ONCE()`` to prevent
+ 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:
+* 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,
- use of WRITE_ONCE() prevents store tearing in the following example:
+ 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,
+ use of ``WRITE_ONCE()`` prevents store tearing in the following example::

WRITE_ONCE(p, 0x00010002);

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

struct __attribute__((__packed__)) foo {
short a;
@@ -1783,32 +1728,32 @@ be fatal in concurrent code. Here are some examples of these sorts
foo2.b = foo1.b;
foo2.c = foo1.c;

- 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:
+ 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::

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

-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
+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.

Please note that these compiler barriers have no direct effect on the CPU,
which may then reorder things however it wishes.


-CPU MEMORY BARRIERS
+CPU memory barriers
-------------------

-The Linux kernel has eight basic CPU memory barriers:
+The Linux kernel has eight basic CPU memory barriers::

TYPE MANDATORY SMP CONDITIONAL
=============== ======================= ===========================
@@ -1822,23 +1767,25 @@ All memory barriers except the data dependency barriers imply a compiler
barrier. Data dependencies do not impose any additional compiler ordering.

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)
-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
-has not yet been reached about these problems, however the READ_ONCE()
-macro is a good place to start looking.
+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)
+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 has not yet been reached about these problems, however the
+``READ_ONCE()`` macro is a good place to start looking.

SMP memory barriers are reduced to compiler barriers on uniprocessor compiled
systems because it is assumed that a CPU will appear to be self-consistent,
and will order overlapping accesses correctly with respect to itself.
-However, see the subsection on "Virtual Machine Guests" below.
+However, see :ref:`virtual-machine-guests`.
+
+.. note::

-[!] 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.
+ 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
barriers impose unnecessary overhead on both SMP and UP systems. They may,
@@ -1850,47 +1797,47 @@ compiler and the CPU from reordering them.

There are some more advanced barrier functions:

- (*) smp_store_mb(var, value)
+* smp_store_mb(var, value)

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


- (*) smp_mb__before_atomic();
- (*) smp_mb__after_atomic();
+* smp_mb__before_atomic();
+* smp_mb__after_atomic();

- 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 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).
+ These are also used for atomic bitop functions that do not return a
+ value (such as set_bit and clear_bit).

- As an example, consider a piece of code that marks an object as being dead
- and then decrements the object's reference count:
+ 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;
smp_mb__before_atomic();
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.
+ This makes sure that the death mark on the object is perceived to be set
+ **before** the reference counter is decremented.

- See Documentation/atomic_{t,bitops}.txt for more information.
+ See ``Documentation/atomic_{t,bitops}.txt`` for more information.


- (*) dma_wmb();
- (*) dma_rmb();
+* 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.
+ 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:
+ 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 */
@@ -1913,21 +1860,23 @@ compiler and the CPU from reordering them.
writel(DESC_NOTIFY, doorbell);
}

- The dma_rmb() allows us guarantee the device has released ownership
- before we read the data from the descriptor, and the dma_wmb() allows
- us to guarantee the data is written to the descriptor before the device
- can see it now has ownership. The wmb() is needed to guarantee that the
- cache coherent memory writes have completed before attempting a write to
- the cache incoherent MMIO region.
+ The ``dma_rmb()`` allows us guarantee the device has released ownership
+ before we read the data from the descriptor, and the ``dma_wmb()`` allows
+ us to guarantee the data is written to the descriptor before the device
+ can see it now has ownership. The ``wmb()`` is needed to guarantee that the
+ cache coherent memory writes have completed before attempting a write to
+ the cache incoherent MMIO region.

- See Documentation/DMA-API.txt for more information on consistent memory.
+ See ``Documentation/DMA-API.txt`` for more information on consistent memory.


-MMIO WRITE BARRIER
+.. _mmio-write-barrier:
+
+MMIO write barrier
------------------

The Linux kernel also has a special barrier for use with memory-mapped I/O
-writes:
+writes::

mmiowb();

@@ -1935,83 +1884,84 @@ This is a variation on the mandatory write barrier that causes writes to weakly
ordered I/O regions to be partially ordered. Its effects may go beyond the
CPU->Hardware interface and actually affect the hardware at some level.

-See the subsection "Acquires vs I/O accesses" for more information.
+See :ref:`acquires-vs-io-accesses` for more information.


-===============================
-IMPLICIT KERNEL MEMORY BARRIERS
+Implicit kernel memory barriers
===============================

Some of the other functions in the linux kernel imply memory barriers, amongst
which are locking and scheduling functions.

-This specification is a _minimum_ guarantee; any particular architecture may
+This specification is a **minimum** guarantee; any particular architecture may
provide more substantial guarantees, but these may not be relied upon outside
of arch specific code.


-LOCK ACQUISITION FUNCTIONS
+Lock acquisition functions
--------------------------

The Linux kernel has a number of locking constructs:

- (*) spin locks
- (*) R/W spin locks
- (*) mutexes
- (*) semaphores
- (*) R/W semaphores
+* spin locks
+* R/W spin locks
+* mutexes
+* semaphores
+* R/W semaphores

In all cases there are variants on "ACQUIRE" operations and "RELEASE" operations
for each construct. These operations all imply certain barriers:

- (1) ACQUIRE operation implication:
+#. ACQUIRE operation implication:

- Memory operations issued after the ACQUIRE will be completed after the
- ACQUIRE operation has completed.
+ Memory operations issued after the ACQUIRE will be completed after the
+ ACQUIRE operation has completed.

- Memory operations issued before the ACQUIRE may be completed after
- the ACQUIRE operation has completed.
+ Memory operations issued before the ACQUIRE may be completed after
+ the ACQUIRE operation has completed.

- (2) RELEASE operation implication:
+#. RELEASE operation implication:

- Memory operations issued before the RELEASE will be completed before the
- RELEASE operation has completed.
+ Memory operations issued before the RELEASE will be completed before the
+ RELEASE operation has completed.

- Memory operations issued after the RELEASE may be completed before the
- RELEASE operation has completed.
+ Memory operations issued after the RELEASE may be completed before the
+ RELEASE operation has completed.

- (3) ACQUIRE vs ACQUIRE implication:
+#. ACQUIRE vs ACQUIRE implication:

- All ACQUIRE operations issued before another ACQUIRE operation will be
- completed before that ACQUIRE operation.
+ All ACQUIRE operations issued before another ACQUIRE operation will be
+ completed before that ACQUIRE operation.

- (4) ACQUIRE vs RELEASE implication:
+#. ACQUIRE vs RELEASE implication:

- All ACQUIRE operations issued before a RELEASE operation will be
- completed before the RELEASE operation.
+ All ACQUIRE operations issued before a RELEASE operation will be
+ completed before the RELEASE operation.

- (5) Failed conditional ACQUIRE implication:
+#. Failed conditional ACQUIRE implication:

- Certain locking variants of the ACQUIRE operation may fail, either due to
- being unable to get the lock immediately, or due to receiving an unblocked
- signal whilst asleep waiting for the lock to become available. Failed
- locks do not imply any sort of barrier.
+ Certain locking variants of the ACQUIRE operation may fail, either due to
+ being unable to get the lock immediately, or due to receiving an unblocked
+ signal whilst asleep waiting for the lock to become available. Failed
+ locks do not imply any sort of barrier.

-[!] Note: one of the consequences of lock ACQUIREs and RELEASEs being only
-one-way barriers is that the effects of instructions outside of a critical
-section may seep into the inside of the critical section.
+.. note::
+
+ One of the consequences of lock ACQUIREs and RELEASEs being only
+ one-way barriers is that the effects of instructions outside of a critical
+ section may seep into the inside of the critical section.

An ACQUIRE followed by a RELEASE may not be assumed to be full memory barrier
because it is possible for an access preceding the ACQUIRE to happen after the
ACQUIRE, and an access following the RELEASE to happen before the RELEASE, and
-the two accesses can themselves then cross:
+the two accesses can themselves then cross::

*A = a;
ACQUIRE M
RELEASE M
*B = b;

-may occur as:
+may occur as::

ACQUIRE M, STORE *B, STORE *A, RELEASE M

@@ -2019,19 +1969,19 @@ When the ACQUIRE and RELEASE are a lock acquisition and release,
respectively, this same reordering can occur if the lock's ACQUIRE and
RELEASE are to the same lock variable, but only from the perspective of
another CPU not holding that lock. In short, a ACQUIRE followed by an
-RELEASE may -not- be assumed to be a full memory barrier.
+RELEASE may **not** be assumed to be a full memory barrier.

Similarly, the reverse case of a RELEASE followed by an ACQUIRE does
not imply a full memory barrier. Therefore, the CPU's execution of the
critical sections corresponding to the RELEASE and the ACQUIRE can cross,
-so that:
+so that::

*A = a;
RELEASE M
ACQUIRE N
*B = b;

-could occur as:
+could occur as::

ACQUIRE N, STORE *B, STORE *A, RELEASE M

@@ -2044,7 +1994,7 @@ the RELEASE would simply complete, thereby avoiding the deadlock.
One key point is that we are only talking about the CPU doing
the reordering, not the compiler. If the compiler (or, for
that matter, the developer) switched the operations, deadlock
- -could- occur.
+ **could** occur.

But suppose the CPU reordered the operations. In this case,
the unlock precedes the lock in the assembly code. The CPU
@@ -2067,10 +2017,10 @@ systems, and so cannot be counted on in such a situation to actually achieve
anything at all - especially with respect to I/O accesses - unless combined
with interrupt disabling operations.

-See also the section on "Inter-CPU acquiring barrier effects".
+See also :ref:`inter-cpu-acquiring-barrier-effects`.


-As an example, consider the following:
+As an example, consider the following::

*A = a;
*B = b;
@@ -2081,13 +2031,15 @@ See also the section on "Inter-CPU acquiring barrier effects".
*E = e;
*F = f;

-The following sequence of events is acceptable:
+The following sequence of events is acceptable::

ACQUIRE, {*F,*A}, *E, {*C,*D}, *B, RELEASE

- [+] Note that {*F,*A} indicates a combined access.
+.. note::
+
+ {\*F,\*A} indicates a combined access.

-But none of the following are:
+But none of the following are::

{*F,*A}, *B, ACQUIRE, *C, *D, RELEASE, *E
*A, *B, *C, ACQUIRE, *D, RELEASE, *E, *F
@@ -2096,7 +2048,7 @@ See also the section on "Inter-CPU acquiring barrier effects".



-INTERRUPT DISABLING FUNCTIONS
+Interrupt disabling functions
-----------------------------

Functions that disable interrupts (ACQUIRE equivalent) and enable interrupts
@@ -2105,7 +2057,7 @@ barriers are required in such a situation, they must be provided from some
other means.


-SLEEP AND WAKE-UP FUNCTIONS
+Sleep and wake-up functions
---------------------------

Sleeping and waking on an event flagged in global data can be viewed as an
@@ -2115,7 +2067,7 @@ these appear to happen in the right order, the primitives to begin the process
of going to sleep, and the primitives to initiate a wake up imply certain
barriers.

-Firstly, the sleeper normally follows something like this sequence of events:
+Firstly, the sleeper normally follows something like this sequence of events::

for (;;) {
set_current_state(TASK_UNINTERRUPTIBLE);
@@ -2124,8 +2076,8 @@ barriers.
schedule();
}

-A general memory barrier is interpolated automatically by set_current_state()
-after it has altered the task state:
+A general memory barrier is interpolated automatically by ``set_current_state()``
+after it has altered the task state::

CPU 1
===============================
@@ -2135,14 +2087,14 @@ A general memory barrier is interpolated automatically by set_current_state()
<general barrier>
LOAD event_indicated

-set_current_state() may be wrapped by:
+``set_current_state()`` may be wrapped by::

prepare_to_wait();
prepare_to_wait_exclusive();

which therefore also imply a general memory barrier after setting the state.
The whole sequence above is available in various canned forms, all of which
-interpolate the memory barrier in the right place:
+interpolate the memory barrier in the right place::

wait_event();
wait_event_interruptible();
@@ -2154,19 +2106,19 @@ The whole sequence above is available in various canned forms, all of which
wait_on_bit_lock();


-Secondly, code that performs a wake up normally follows something like this:
+Secondly, code that performs a wake up normally follows something like this::

event_indicated = 1;
wake_up(&event_wait_queue);

-or:
+or::

event_indicated = 1;
wake_up_process(event_daemon);

-A write memory barrier is implied by wake_up() and co. if and only if they
+A write memory barrier is implied by ``wake_up()`` and co. if and only if they
wake something up. The barrier occurs before the task state is cleared, and so
-sits between the STORE to indicate the event and the STORE to set TASK_RUNNING:
+sits between the STORE to indicate the event and the STORE to set TASK_RUNNING::

CPU 1 CPU 2
=============================== ===============================
@@ -2178,7 +2130,7 @@ wake something up. The barrier occurs before the task state is cleared, and so

To repeat, this write memory barrier is present if and only if something
is actually awakened. To see this, consider the following sequence of
-events, where X and Y are both initially zero:
+events, where X and Y are both initially zero::

CPU 1 CPU 2
=============================== ===============================
@@ -2191,7 +2143,7 @@ is actually awakened. To see this, consider the following sequence of
In contrast, if a wakeup does occur, CPU 2's load from X would be guaranteed
to see 1.

-The available waker functions include:
+The available waker functions include::

complete();
wake_up();
@@ -2210,10 +2162,10 @@ to see 1.
wake_up_process();


-[!] Note that the memory barriers implied by the sleeper and the waker do _not_
+Note that the memory barriers implied by the sleeper and the waker do **not**
order multiple stores before the wake-up with respect to loads of those stored
values after the sleeper has called set_current_state(). For instance, if the
-sleeper does:
+sleeper does::

set_current_state(TASK_INTERRUPTIBLE);
if (event_indicated)
@@ -2221,7 +2173,7 @@ values after the sleeper has called set_current_state(). For instance, if the
__set_current_state(TASK_RUNNING);
do_something(my_data);

-and the waker does:
+and the waker does::

my_data = value;
event_indicated = 1;
@@ -2230,7 +2182,7 @@ values after the sleeper has called set_current_state(). For instance, if the
there's no guarantee that the change to event_indicated will be perceived by
the sleeper as coming after the change to my_data. In such a circumstance, the
code on both sides must interpolate its own memory barriers between the
-separate data accesses. Thus the above sleeper ought to do:
+separate data accesses. Thus the above sleeper ought to do::

set_current_state(TASK_INTERRUPTIBLE);
if (event_indicated) {
@@ -2238,7 +2190,7 @@ code on both sides must interpolate its own memory barriers between the
do_something(my_data);
}

-and the waker should do:
+and the waker should do::

my_data = value;
smp_wmb();
@@ -2246,16 +2198,16 @@ code on both sides must interpolate its own memory barriers between the
wake_up(&event_wait_queue);


-MISCELLANEOUS FUNCTIONS
+Miscellaneous functions
-----------------------

Other functions that imply barriers:

- (*) schedule() and similar imply full memory barriers.
+* schedule() and similar imply full memory barriers

+.. _inter-cpu-acquiring-barrier-effects:

-===================================
-INTER-CPU ACQUIRING BARRIER EFFECTS
+Inter-CPU acquiring barrier effects
===================================

On SMP systems locking primitives give a more substantial form of barrier: one
@@ -2263,11 +2215,11 @@ that does affect memory access ordering on other CPUs, within the context of
conflict on any particular lock.


-ACQUIRES VS MEMORY ACCESSES
+Acquires vs memory accesses
---------------------------

Consider the following: the system has a pair of spinlocks (M) and (Q), and
-three CPUs; then should the following sequence of events occur:
+three CPUs; then should the following sequence of events occur::

CPU 1 CPU 2
=============================== ===============================
@@ -2278,13 +2230,13 @@ Consider the following: the system has a pair of spinlocks (M) and (Q), and
RELEASE M RELEASE Q
WRITE_ONCE(*D, d); WRITE_ONCE(*H, h);

-Then there is no guarantee as to what order CPU 3 will see the accesses to *A
-through *H occur in, other than the constraints imposed by the separate locks
-on the separate CPUs. It might, for example, see:
+Then there is no guarantee as to what order CPU 3 will see the accesses to \*A
+through \*H occur in, other than the constraints imposed by the separate locks
+on the separate CPUs. It might, for example, see::

*E, ACQUIRE M, ACQUIRE Q, *G, *C, *F, *A, *B, RELEASE Q, *D, *H, RELEASE M

-But it won't see any of:
+But it won't see any of::

*B, *C or *D preceding ACQUIRE M
*A, *B or *C following RELEASE M
@@ -2292,8 +2244,9 @@ through *H occur in, other than the constraints imposed by the separate locks
*E, *F or *G following RELEASE Q


+.. _acquires-vs-io-accesses:

-ACQUIRES VS I/O ACCESSES
+Acquires vs I/O accesses
------------------------

Under certain circumstances (especially involving NUMA), I/O accesses within
@@ -2302,7 +2255,7 @@ PCI bridge, because the PCI bridge does not necessarily participate in the
cache-coherence protocol, and is therefore incapable of issuing the required
read memory barriers.

-For example:
+For example::

CPU 1 CPU 2
=============================== ===============================
@@ -2315,15 +2268,15 @@ read memory barriers.
writel(5, DATA);
spin_unlock(Q);

-may be seen by the PCI bridge as follows:
+may be seen by the PCI bridge as follows::

STORE *ADDR = 0, STORE *ADDR = 4, STORE *DATA = 1, STORE *DATA = 5

which would probably cause the hardware to malfunction.


-What is necessary here is to intervene with an mmiowb() before dropping the
-spinlock, for example:
+What is necessary here is to intervene with an ``mmiowb()`` before dropping the
+spinlock, for example::

CPU 1 CPU 2
=============================== ===============================
@@ -2343,8 +2296,8 @@ before either of the stores issued on CPU 2.


Furthermore, following a store by a load from the same device obviates the need
-for the mmiowb(), because the load forces the store to complete before the load
-is performed:
+for the ``mmiowb()``, because the load forces the store to complete before the
+load is performed::

CPU 1 CPU 2
=============================== ===============================
@@ -2358,28 +2311,27 @@ for the mmiowb(), because the load forces the store to complete before the load
spin_unlock(Q);


-See Documentation/driver-api/device-io.rst for more information.
+See ``Documentation/driver-api/device-io.rst`` for more information.


-=================================
-WHERE ARE MEMORY BARRIERS NEEDED?
+Where are memory barriers needed?
=================================

Under normal operation, memory operation reordering is generally not going to
be a problem as a single-threaded linear piece of code will still appear to
work correctly, even if it's in an SMP kernel. There are, however, four
-circumstances in which reordering definitely _could_ be a problem:
+circumstances in which reordering definitely **could** be a problem:

- (*) Interprocessor interaction.
+* Interprocessor interaction

- (*) Atomic operations.
+* Atomic operations

- (*) Accessing devices.
+* Accessing devices

- (*) Interrupts.
+* Interrupts


-INTERPROCESSOR INTERACTION
+Interprocessor interaction
--------------------------

When there's a system with more than one processor, more than one CPU in the
@@ -2392,7 +2344,7 @@ a malfunction.

Consider, for example, the R/W semaphore slow path. Here a waiting process is
queued on the semaphore, by virtue of it having a piece of its stack linked to
-the semaphore's list of waiting processes:
+the semaphore's list of waiting processes::

struct rw_semaphore {
...
@@ -2405,20 +2357,21 @@ queued on the semaphore, by virtue of it having a piece of its stack linked to
struct task_struct *task;
};

-To wake up a particular waiter, the up_read() or up_write() functions have to:
+To wake up a particular waiter, the ``up_read()`` or ``up_write()`` functions
+have to:

- (1) read the next pointer from this waiter's record to know as to where the
- next waiter record is;
+#. read the next pointer from this waiter's record to know as to where the
+ next waiter record is;

- (2) read the pointer to the waiter's task structure;
+#. read the pointer to the waiter's task structure;

- (3) clear the task pointer to tell the waiter it has been given the semaphore;
+#. clear the task pointer to tell the waiter it has been given the semaphore;

- (4) call wake_up_process() on the task; and
+#. call wake_up_process() on the task; and

- (5) release the reference held on the waiter's task struct.
+#. release the reference held on the waiter's task struct.

-In other words, it has to perform this sequence of events:
+In other words, it has to perform this sequence of events::

LOAD waiter->list.next;
LOAD waiter->task;
@@ -2436,7 +2389,7 @@ if the task pointer is cleared _before_ the next pointer in the list is read,
another CPU might start processing the waiter and might clobber the waiter's
stack before the up*() function has a chance to read the next pointer.

-Consider then what might happen to the above sequence of events:
+Consider then what might happen to the above sequence of events::

CPU 1 CPU 2
=============================== ===============================
@@ -2456,10 +2409,10 @@ stack before the up*() function has a chance to read the next pointer.
LOAD waiter->list.next;
--- OOPS ---

-This could be dealt with using the semaphore lock, but then the down_xxx()
+This could be dealt with using the semaphore lock, but then the ``down_xxx()``
function has to needlessly get the spinlock again after being woken up.

-The way to deal with this is to insert a general SMP memory barrier:
+The way to deal with this is to insert a general SMP memory barrier::

LOAD waiter->list.next;
LOAD waiter->task;
@@ -2474,13 +2427,13 @@ with respect to the other CPUs on the system. It does _not_ guarantee that all
the memory accesses before the barrier will be complete by the time the barrier
instruction itself is complete.

-On a UP system - where this wouldn't be a problem - the smp_mb() is just a
+On a UP system - where this wouldn't be a problem - the ``smp_mb()`` is just a
compiler barrier, thus making sure the compiler emits the instructions in the
right order without actually intervening in the CPU. Since there's only one
CPU, that CPU's dependency ordering logic will take care of everything else.


-ATOMIC OPERATIONS
+Atomic operations
-----------------

Whilst they are technically interprocessor interaction considerations, atomic
@@ -2488,10 +2441,10 @@ operations are noted specially as some of them imply full memory barriers and
some don't, but they're very heavily relied on as a group throughout the
kernel.

-See Documentation/atomic_t.txt for more information.
+See ``Documentation/atomic_t.txt`` for more information.


-ACCESSING DEVICES
+Accessing devices
-----------------

Many devices can be memory mapped, and so appear to the CPU as if they're just
@@ -2505,23 +2458,23 @@ efficient to reorder, combine or merge accesses - something that would cause
the device to malfunction.

Inside of the Linux kernel, I/O should be done through the appropriate accessor
-routines - such as inb() or writel() - which know how to make such accesses
-appropriately sequential. Whilst this, for the most part, renders the explicit
-use of memory barriers unnecessary, there are a couple of situations where they
-might be needed:
+routines - such as ``inb()`` or ``writel()`` - which know how to make such
+accesses appropriately sequential. Whilst this, for the most part, renders the
+explicit use of memory barriers unnecessary, there are a couple of situations
+where they might be needed:

- (1) On some systems, I/O stores are not strongly ordered across all CPUs, and
- so for _all_ general drivers locks should be used and mmiowb() must be
- issued prior to unlocking the critical section.
+#. On some systems, I/O stores are not strongly ordered across all CPUs, and
+ so for _all_ general drivers locks should be used and mmiowb() must be
+ issued prior to unlocking the critical section.

- (2) If the accessor functions are used to refer to an I/O memory window with
- relaxed memory access properties, then _mandatory_ memory barriers are
- required to enforce ordering.
+#. If the accessor functions are used to refer to an I/O memory window with
+ relaxed memory access properties, then _mandatory_ memory barriers are
+ required to enforce ordering.

-See Documentation/driver-api/device-io.rst for more information.
+See ``Documentation/driver-api/device-io.rst`` for more information.


-INTERRUPTS
+Interrupts
----------

A driver may be interrupted by its own interrupt service routine, and thus the
@@ -2537,7 +2490,7 @@ handled, thus the interrupt handler does not need to lock against that.

However, consider a driver that was talking to an ethernet card that sports an
address register and a data register. If that driver's core talks to the card
-under interrupt-disablement and then the driver's interrupt handler is invoked:
+under interrupt-disablement and then the driver's interrupt handler is invoked::

LOCAL IRQ DISABLE
writew(ADDR, 3);
@@ -2549,7 +2502,7 @@ address register and a data register. If that driver's core talks to the card
</interrupt>

The store to the data register might happen after the second store to the
-address register if ordering rules are sufficiently relaxed:
+address register if ordering rules are sufficiently relaxed::

STORE *ADDR = 3, STORE *ADDR = 4, STORE *DATA = y, q = LOAD *DATA

@@ -2562,7 +2515,7 @@ explicit barriers are used.
Normally this won't be a problem because the I/O accesses done inside such
sections will include synchronous load operations on strictly ordered I/O
registers that form implicit I/O barriers. If this isn't sufficient then an
-mmiowb() may need to be used explicitly.
+``mmiowb()`` may need to be used explicitly.


A similar situation may occur between an interrupt routine and two routines
@@ -2570,14 +2523,13 @@ running on separate CPUs that communicate with each other. If such a case is
likely, then interrupt-disabling locks should be used to guarantee ordering.


-==========================
-KERNEL I/O BARRIER EFFECTS
+Kernel I/O barrier effects
==========================

When accessing I/O memory, drivers should use the appropriate accessor
functions:

- (*) inX(), outX():
+* inX(), outX():

These are intended to talk to I/O space rather than memory space, but
that's primarily a CPU-specific concept. The i386 and x86_64 processors
@@ -2599,7 +2551,7 @@ When accessing I/O memory, drivers should use the appropriate accessor
They are not guaranteed to be fully ordered with respect to other types of
memory and I/O operation.

- (*) readX(), writeX():
+* readX(), writeX():

Whether these are guaranteed to be fully ordered and uncombined with
respect to each other on the issuing CPU depends on the characteristics
@@ -2612,12 +2564,12 @@ When accessing I/O memory, drivers should use the appropriate accessor

However, intermediary hardware (such as a PCI bridge) may indulge in
deferral if it so wishes; to flush a store, a load from the same location
- is preferred[*], but a load from the same device or from configuration
+ is preferred [#]_, but a load from the same device or from configuration
space should suffice for PCI.

- [*] NOTE! attempting to load from the same location as was written to may
- cause a malfunction - consider the 16550 Rx/Tx serial registers for
- example.
+ .. [#] Attempting to load from the same location as was written to may
+ cause a malfunction - consider the 16550 Rx/Tx serial registers for
+ example.

Used with prefetchable I/O memory, an mmiowb() barrier may be required to
force stores to be ordered.
@@ -2625,24 +2577,23 @@ When accessing I/O memory, drivers should use the appropriate accessor
Please refer to the PCI specification for more information on interactions
between PCI transactions.

- (*) readX_relaxed(), writeX_relaxed()
+* readX_relaxed(), writeX_relaxed()

- These are similar to readX() and writeX(), but provide weaker memory
- ordering guarantees. Specifically, they do not guarantee ordering with
- respect to normal memory accesses (e.g. DMA buffers) nor do they guarantee
- ordering with respect to LOCK or UNLOCK operations. If the latter is
- required, an mmiowb() barrier can be used. Note that relaxed accesses to
- the same peripheral are guaranteed to be ordered with respect to each
- other.
+ These are similar to ``readX()`` and ``writeX()``, but provide weaker
+ memory ordering guarantees. Specifically, they do not guarantee ordering
+ with respect to normal memory accesses (e.g. DMA buffers) nor do they
+ guarantee ordering with respect to LOCK or UNLOCK operations. If the
+ latter is required, an ``mmiowb()`` barrier can be used. Note that
+ relaxed accesses to the same peripheral are guaranteed to be ordered with
+ respect to each other.

- (*) ioreadX(), iowriteX()
+* ioreadX(), iowriteX()

These will perform appropriately for the type of access they're actually
- doing, be it inX()/outX() or readX()/writeX().
+ doing, be it ``inX()``/``outX()`` or ``readX()``/``writeX()``.


-========================================
-ASSUMED MINIMUM EXECUTION ORDERING MODEL
+Assumed minimum execution ordering model
========================================

It has to be assumed that the conceptual CPU is weakly-ordered but that it will
@@ -2652,15 +2603,15 @@ frv), and so the most relaxed case (namely DEC Alpha) must be assumed outside
of arch-specific code.

This means that it must be considered that the CPU will execute its instruction
-stream in any order it feels like - or even in parallel - provided that if an
+stream in any order it feels like **or even in parallel** provided that if an
instruction in the stream depends on an earlier instruction, then that
-earlier instruction must be sufficiently complete[*] before the later
+earlier instruction must be sufficiently complete [#]_ before the later
instruction may proceed; in other words: provided that the appearance of
causality is maintained.

- [*] Some instructions have more than one effect - such as changing the
- condition codes, changing registers or changing memory - and different
- instructions may depend on different effects.
+.. [#] Some instructions have more than one effect - such as changing the
+ condition codes, changing registers or changing memory - and different
+ instructions may depend on different effects.

A CPU may also discard any instruction sequence that winds up having no
ultimate effect. For example, if two adjacent instructions both load an
@@ -2672,8 +2623,7 @@ stream in any way it sees fit, again provided the appearance of causality is
maintained.


-============================
-THE EFFECTS OF THE CPU CACHE
+The effects of the cpu cache
============================

The way cached memory operations are perceived across the system is affected to
@@ -2683,7 +2633,7 @@ memory coherence system that maintains the consistency of state in the system.
As far as the way a CPU interacts with another part of the system through the
caches goes, the memory system has to include the CPU's caches, and memory
barriers for the most part act at the interface between the CPU and its cache
-(memory barriers logically act on the dotted line in the following diagram):
+(memory barriers logically act on the dotted line in the following diagram)::

<--- CPU ---> : <----------- Memory ----------->
:
@@ -2725,15 +2675,21 @@ accesses cross from the CPU side of things to the memory side of things, and
the order in which the effects are perceived to happen by the other observers
in the system.

-[!] Memory barriers are _not_ needed within a given CPU, as CPUs always see
-their own loads and stores as if they had happened in program order.
+.. note::
+
+ Memory barriers are _not_ needed within a given CPU, as CPUs always see
+ their own loads and stores as if they had happened in program order.

-[!] MMIO or other device accesses may bypass the cache system. This depends on
-the properties of the memory window through which devices are accessed and/or
-the use of any special device communication instructions the CPU may have.
+.. note::

+ MMIO or other device accesses may bypass the cache system. This depends on
+ the properties of the memory window through which devices are accessed
+ and/or the use of any special device communication instructions the CPU may
+ have.

-CACHE COHERENCY
+.. _cache-coherency:
+
+Cache coherency
---------------

Life isn't quite as simple as it may appear above, however: for while the
@@ -2744,7 +2700,7 @@ become apparent in the same order on those other CPUs.


Consider dealing with a system that has a pair of CPUs (1 & 2), each of which
-has a pair of parallel data caches (CPU 1 has A/B, and CPU 2 has C/D):
+has a pair of parallel data caches (CPU 1 has A/B, and CPU 2 has C/D)::

:
: +--------+
@@ -2768,26 +2724,26 @@ Consider dealing with a system that has a pair of CPUs (1 & 2), each of which

Imagine the system has the following properties:

- (*) an odd-numbered cache line may be in cache A, cache C or it may still be
- resident in memory;
+* an odd-numbered cache line may be in cache A, cache C or it may still be
+ resident in memory;

- (*) an even-numbered cache line may be in cache B, cache D or it may still be
- resident in memory;
+* an even-numbered cache line may be in cache B, cache D or it may still be
+ resident in memory;

- (*) whilst the CPU core is interrogating one cache, the other cache may be
- making use of the bus to access the rest of the system - perhaps to
- displace a dirty cacheline or to do a speculative load;
+* whilst the CPU core is interrogating one cache, the other cache may be
+ making use of the bus to access the rest of the system - perhaps to
+ displace a dirty cacheline or to do a speculative load;

- (*) each cache has a queue of operations that need to be applied to that cache
- to maintain coherency with the rest of the system;
+* each cache has a queue of operations that need to be applied to that cache
+ to maintain coherency with the rest of the system;

- (*) the coherency queue is not flushed by normal loads to lines already
- present in the cache, even though the contents of the queue may
- potentially affect those loads.
+* the coherency queue is not flushed by normal loads to lines already
+ present in the cache, even though the contents of the queue may
+ potentially affect those loads.

Imagine, then, that two writes are made on the first CPU, with a write barrier
between them to guarantee that they will appear to reach that CPU's caches in
-the requisite order:
+the requisite order::

CPU 1 CPU 2 COMMENT
=============== =============== =======================================
@@ -2801,7 +2757,7 @@ between them to guarantee that they will appear to reach that CPU's caches in

The write memory barrier forces the other CPUs in the system to perceive that
the local CPU's caches have apparently been updated in the correct order. But
-now imagine that the second CPU wants to read those values:
+now imagine that the second CPU wants to read those values::

CPU 1 CPU 2 COMMENT
=============== =============== =======================================
@@ -2811,8 +2767,8 @@ the local CPU's caches have apparently been updated in the correct order. But

The above pair of reads may then fail to happen in the expected order, as the
cacheline holding p may get updated in one of the second CPU's caches whilst
-the update to the cacheline holding v is delayed in the other of the second
-CPU's caches by some other cache event:
+the update to the cacheline holding ``v`` is delayed in the other of the second
+CPU's caches by some other cache event::

CPU 1 CPU 2 COMMENT
=============== =============== =======================================
@@ -2837,7 +2793,7 @@ as that committed on CPU 1.

To intervene, we need to interpolate a data dependency barrier or a read
barrier between the loads. This will force the cache to commit its coherency
-queue before processing any further requests:
+queue before processing any further requests::

CPU 1 CPU 2 COMMENT
=============== =============== =======================================
@@ -2867,7 +2823,7 @@ cachelets for normal memory accesses. The semantics of the Alpha removes the
need for coordination in the absence of memory barriers.


-CACHE COHERENCY VS DMA
+Cache coherency vs DMA
----------------------

Not all systems maintain cache coherency with respect to devices doing DMA. In
@@ -2885,10 +2841,10 @@ is discarded from the CPU's cache and reloaded. To deal with this, the
appropriate part of the kernel must invalidate the overlapping bits of the
cache on each CPU.

-See Documentation/cachetlb.txt for more information on cache management.
+See ``Documentation/cachetlb.txt`` for more information on cache management.


-CACHE COHERENCY VS MMIO
+Cache coherency VS MMIO
-----------------------

Memory mapped I/O usually takes place through memory locations that are part of
@@ -2903,13 +2859,12 @@ flushed between the cached memory write and the MMIO access if the two are in
any way dependent.


-=========================
-THE THINGS CPUS GET UP TO
+The things cpus get up to
=========================

A programmer might take it for granted that the CPU will perform memory
operations in exactly the order specified, so that if the CPU is, for example,
-given the following piece of code to execute:
+given the following piece of code to execute::

a = READ_ONCE(*A);
WRITE_ONCE(*B, b);
@@ -2919,7 +2874,7 @@ operations in exactly the order specified, so that if the CPU is, for example,

they would then expect that the CPU will complete the memory operation for each
instruction before moving on to the next one, leading to a definite sequence of
-operations as seen by external observers in the system:
+operations as seen by external observers in the system::

LOAD *A, STORE *B, LOAD *C, LOAD *D, STORE *E.

@@ -2927,31 +2882,31 @@ instruction before moving on to the next one, leading to a definite sequence of
Reality is, of course, much messier. With many CPUs and compilers, the above
assumption doesn't hold because:

- (*) loads are more likely to need to be completed immediately to permit
- execution progress, whereas stores can often be deferred without a
- problem;
+* loads are more likely to need to be completed immediately to permit
+ execution progress, whereas stores can often be deferred without a
+ problem;

- (*) loads may be done speculatively, and the result discarded should it prove
- to have been unnecessary;
+* loads may be done speculatively, and the result discarded should it prove
+ to have been unnecessary;

- (*) loads may be done speculatively, leading to the result having been fetched
- at the wrong time in the expected sequence of events;
+* loads may be done speculatively, leading to the result having been fetched
+ at the wrong time in the expected sequence of events;

- (*) the order of the memory accesses may be rearranged to promote better use
- of the CPU buses and caches;
+* the order of the memory accesses may be rearranged to promote better use
+ of the CPU buses and caches;

- (*) loads and stores may be combined to improve performance when talking to
- memory or I/O hardware that can do batched accesses of adjacent locations,
- thus cutting down on transaction setup costs (memory and PCI devices may
- both be able to do this); and
+* loads and stores may be combined to improve performance when talking to
+ memory or I/O hardware that can do batched accesses of adjacent locations,
+ thus cutting down on transaction setup costs (memory and PCI devices may
+ both be able to do this); and

- (*) the CPU's data cache may affect the ordering, and whilst cache-coherency
- mechanisms may alleviate this - once the store has actually hit the cache
- - there's no guarantee that the coherency management will be propagated in
- order to other CPUs.
+* the CPU's data cache may affect the ordering, and whilst cache-coherency
+ mechanisms may alleviate this - once the store has actually hit the cache
+ - there's no guarantee that the coherency management will be propagated in
+ order to other CPUs.

So what another CPU, say, might actually observe from the above piece of code
-is:
+is::

LOAD *A, ..., LOAD {*C,*D}, STORE *E, STORE *B

@@ -2959,8 +2914,8 @@ So what another CPU, say, might actually observe from the above piece of code


However, it is guaranteed that a CPU will be self-consistent: it will see its
-_own_ accesses appear to be correctly ordered, without the need for a memory
-barrier. For instance with the following code:
+**own** accesses appear to be correctly ordered, without the need for a memory
+barrier. For instance with the following code::

U = READ_ONCE(*A);
WRITE_ONCE(*A, V);
@@ -2970,7 +2925,7 @@ _own_ accesses appear to be correctly ordered, without the need for a memory
Z = READ_ONCE(*A);

and assuming no intervention by an external influence, it can be assumed that
-the final result will appear to be:
+the final result will appear to be::

U == the original value of *A
X == W
@@ -2978,40 +2933,41 @@ and assuming no intervention by an external influence, it can be assumed that
*A == Y

The code above may cause the CPU to generate the full sequence of memory
-accesses:
+accesses::

U=LOAD *A, STORE *A=V, STORE *A=W, X=LOAD *A, STORE *A=Y, Z=LOAD *A

in that order, but, without intervention, the sequence may have almost any
combination of elements combined or discarded, provided the program's view
-of the world remains consistent. Note that READ_ONCE() and WRITE_ONCE()
-are -not- optional in the above example, as there are architectures
+of the world remains consistent. Note that ``READ_ONCE()`` and ``WRITE_ONCE()``
+are **not** optional in the above example, as there are architectures
where a given CPU might reorder successive loads to the same location.
-On such architectures, READ_ONCE() and WRITE_ONCE() do whatever is
+On such architectures, ``READ_ONCE()`` and ``WRITE_ONCE()`` do whatever is
necessary to prevent this, for example, on Itanium the volatile casts
-used by READ_ONCE() and WRITE_ONCE() cause GCC to emit the special ld.acq
-and st.rel instructions (respectively) that prevent such reordering.
+used by ``READ_ONCE()`` and ``WRITE_ONCE()`` cause GCC to emit the special
+``ld.acq`` and ``st.rel`` instructions (respectively) that prevent such
+reordering.

The compiler may also combine, discard or defer elements of the sequence before
the CPU even sees them.

-For instance:
+For instance::

*A = V;
*A = W;

-may be reduced to:
+may be reduced to::

*A = W;

-since, without either a write barrier or an WRITE_ONCE(), it can be
-assumed that the effect of the storage of V to *A is lost. Similarly:
+since, without either a write barrier or an ``WRITE_ONCE()``, it can be
+assumed that the effect of the storage of V to \*A is lost. Similarly::

*A = Y;
Z = *A;

may, without a memory barrier or an READ_ONCE() and WRITE_ONCE(), be
-reduced to:
+reduced to::

*A = Y;
Z = Y;
@@ -3019,7 +2975,7 @@ may, without a memory barrier or an READ_ONCE() and WRITE_ONCE(), be
and the LOAD operation never appear outside of the CPU.


-AND THEN THERE'S THE ALPHA
+And then there's the ALPHA
--------------------------

The DEC Alpha CPU is one of the most relaxed CPUs there is. Not only that,
@@ -3031,10 +2987,11 @@ changes vs new data occur in the right order.

The Alpha defines the Linux kernel's memory barrier model.

-See the subsection on "Cache Coherency" above.
+See :ref:`cache-coherency`

+.. _virtual-machine-guests:

-VIRTUAL MACHINE GUESTS
+Virtual machine guests
----------------------

Guests running within virtual machines might be affected by SMP effects even if
@@ -3042,89 +2999,97 @@ the guest itself is compiled without SMP support. This is an artifact of
interfacing with an SMP host while running an UP kernel. Using mandatory
barriers for this use-case would be possible but is often suboptimal.

-To handle this case optimally, low-level virt_mb() etc macros are available.
-These have the same effect as smp_mb() etc when SMP is enabled, but generate
+To handle this case optimally, low-level ``virt_mb()`` etc macros are available.
+These have the same effect as ``smp_mb()`` etc when SMP is enabled, but generate
identical code for SMP and non-SMP systems. For example, virtual machine guests
-should use virt_mb() rather than smp_mb() when synchronizing against a
+should use ``virt_mb()`` rather than ``smp_mb()`` when synchronizing against a
(possibly SMP) host.

-These are equivalent to smp_mb() etc counterparts in all other respects,
-in particular, they do not control MMIO effects: to control
-MMIO effects, use mandatory barriers.
+These are equivalent to ``smp_mb()`` etc counterparts in all other respects,
+in particular, they do not control MMIO effects: to control MMIO effects, use
+mandatory barriers.


-============
-EXAMPLE USES
+Example uses
============

-CIRCULAR BUFFERS
+Circular buffers
----------------

Memory barriers can be used to implement circular buffering without the need
-of a lock to serialise the producer with the consumer. See:
+of a lock to serialise the producer with the consumer. See
+``Documentation/circular-buffers.txt`` for details.

- Documentation/circular-buffers.txt

-for details.
+References
+==========

+.. [ALPHA] Alpha AXP Architecture Reference Manual, Second Edition (Sites &
+ Witek, Digital Press)

-==========
-REFERENCES
-==========
+ | Chapter 5.2: Physical Address Space Characteristics
+ | Chapter 5.4: Caches and Write Buffers
+ | Chapter 5.5: Data Sharing
+ | Chapter 5.6: Read/Write Ordering
+
+.. [AMD64] AMD64 Architecture Programmer's Manual Volume 2: System Programming
+
+ | Chapter 7.1: Memory-Access Ordering
+ | Chapter 7.4: Buffering and Combining Memory Writes
+
+.. [ARMV8] ARM Architecture Reference Manual (ARMv8, for ARMv8-A architecture
+ profile)
+
+ Chapter B2: The AArch64 Application Level Memory Model
+
+.. [IA32] IA-32 Intel Architecture Software Developer's Manual, Volume 3:
+ System Programming Guide
+
+ | Chapter 7.1: Locked Atomic Operations
+ | Chapter 7.2: Memory Ordering
+ | Chapter 7.4: Serializing Instructions
+
+.. [SPARC1] The SPARC Architecture Manual, Version 9
+
+ | Chapter 8: Memory Models
+ | Appendix D: Formal Specification of the Memory Models
+ | Appendix J: Programming with the Memory Models
+
+.. [PPC] Storage in the PowerPC (Stone and Fitzgerald)
+
+.. [USPARC2] UltraSPARC Programmer Reference Manual
+
+ | Chapter 5: Memory Accesses and Cacheability
+ | Chapter 15: Sparc-V9 Memory Models

-Alpha AXP Architecture Reference Manual, Second Edition (Sites & Witek,
-Digital Press)
- Chapter 5.2: Physical Address Space Characteristics
- Chapter 5.4: Caches and Write Buffers
- Chapter 5.5: Data Sharing
- Chapter 5.6: Read/Write Ordering
+.. [USPARC3] UltraSPARC III Cu User's Manual

-AMD64 Architecture Programmer's Manual Volume 2: System Programming
- Chapter 7.1: Memory-Access Ordering
- Chapter 7.4: Buffering and Combining Memory Writes
+ Chapter 9: Memory Models

-ARM Architecture Reference Manual (ARMv8, for ARMv8-A architecture profile)
- Chapter B2: The AArch64 Application Level Memory Model
+.. [USPARC4] UltraSPARC IIIi Processor User's Manual

-IA-32 Intel Architecture Software Developer's Manual, Volume 3:
-System Programming Guide
- Chapter 7.1: Locked Atomic Operations
- Chapter 7.2: Memory Ordering
- Chapter 7.4: Serializing Instructions
+ Chapter 8: Memory Models

-The SPARC Architecture Manual, Version 9
- Chapter 8: Memory Models
- Appendix D: Formal Specification of the Memory Models
- Appendix J: Programming with the Memory Models
+.. [USPARC5] UltraSPARC Architecture 2005

-Storage in the PowerPC (Stone and Fitzgerald)
+ | Chapter 9: Memory
+ | Appendix D: Formal Specifications of the Memory Models

-UltraSPARC Programmer Reference Manual
- Chapter 5: Memory Accesses and Cacheability
- Chapter 15: Sparc-V9 Memory Models
+.. [UPSARC6] UltraSPARC T1 Supplement to the UltraSPARC Architecture 2005

-UltraSPARC III Cu User's Manual
- Chapter 9: Memory Models
+ | Chapter 8: Memory Models
+ | Appendix F: Caches and Cache Coherency

-UltraSPARC IIIi Processor User's Manual
- Chapter 8: Memory Models
+.. [SOLARIS] Solaris Internals, Core Kernel Architecture, p63-68:

-UltraSPARC Architecture 2005
- Chapter 9: Memory
- Appendix D: Formal Specifications of the Memory Models
+ Chapter 3.3: Hardware Considerations for Locks and Synchronization

-UltraSPARC T1 Supplement to the UltraSPARC Architecture 2005
- Chapter 8: Memory Models
- Appendix F: Caches and Cache Coherency
+.. [UNIX] Unix Systems for Modern Architectures, Symmetric Multiprocessing
+ and Caching for Kernel Programmers:

-Solaris Internals, Core Kernel Architecture, p63-68:
- Chapter 3.3: Hardware Considerations for Locks and
- Synchronization
+ Chapter 13: Other Memory Models

-Unix Systems for Modern Architectures, Symmetric Multiprocessing and Caching
-for Kernel Programmers:
- Chapter 13: Other Memory Models
+.. [ITANIUM] Intel Itanium Architecture Software Developer's Manual: Volume 1:

-Intel Itanium Architecture Software Developer's Manual: Volume 1:
- Section 2.6: Speculation
- Section 4.4: Memory Access
+ | Section 2.6: Speculation
+ | Section 4.4: Memory Access
--
2.15.1