Lecture 25: Memory Consistency

Section 1: Memory Consistency Models — Sequential Consistency vs. Total Store Ordering

Synchronization problems arise whenever concurrent processes share memory—even on a single uniprocessor with preemptive threads! Notice that there are two distinct classes of synchronization:

  1. Mutual Exclusion: Ensuring only one process accesses a shared resource at a time (what we built with locks in Lecture 24).
  2. Producer-Consumer: Ensuring a consumer process waits until a producer process has finished producing data.

Do we need heavyweight atomic instructions for simple Producer-Consumer coordination? Suppose initially flag = 0, and we write the following Simple Producer-Consumer code using only plain loads and stores:

Producer:                          Consumer:
  sw xdata, (xdatap)                 spin: lw xflag, (xflagp)
  li xflag, 1                              beqz xflag, spin
  sw xflag, (xflagp)                       lw xdata, (xdatap)

Is this code correct? Look carefully: the Producer writes data first and flag = 1 second; the Consumer reads flag until it sees 1, and then reads data. You might assume “Of course it’s correct—sw xdata appears before sw xflag in the program!”

Whether this code works depends entirely on the machine’s Memory Consistency Model!

Cache Coherence vs. Memory Consistency

Students very often confuse coherence and consistency. Keep the boundary razor-sharp:

Why doesn’t the sequential ISA settle this? A sequential ISA only guarantees that a single processor sees its own memory operations behave as if executed in program order (so li xflag, 1 happens before sw xflag, (xflagp) on the Producer, and lw xflag happens before beqz on the Consumer). The sequential ISA says nothing about how stores and loads to different addresses (data vs. flag) become visible to other processors!

Sequential Consistency (SC)

Leslie Lamport defined the cleanest, most intuitive memory model—Sequential Consistency (SC): > “A system is sequentially consistent if the result of any execution is the same as if the operations of all the processors were executed in some sequential order, and the operations of each individual processor appear in the order specified by the program.”

Equivalently, SC = an arbitrary order-preserving interleaving of the memory references of all sequential programs, as if all processors P connected directly to one single shared memory M with a central switch taking one load or store at a time.

Look back at our Producer-Consumer example under SC:

Why Most Real Machines Are Not SC: Store Buffers and TSO

Does SC play nicely with modern caches, store buffers, and out-of-order cores? No! Very few commercial ISAs require SC (for instance, neither IBM 370, nor x86, nor ARM, nor RISC-V are SC; the MIPS R10000 did implement SC, but needed complex hardware to speculate on out-of-order loads/stores and squash pipelines whenever cross-core ordering violations were detected).

Why did real hardware abandon SC? Because uniprocessor architects invented the Store Buffer optimization (CPU -> Store Buffer -> Shared Memory):

When uniprocessors with store buffers were bolted together into multiprocessors, the resulting hardware was no longer SC! Instead, it implemented Total Store Ordering (TSO)—used by x86 TSO, SPARC TSO (default), IBM-370 TSO, and optional RISC-V RVTSO, making TSO the strongest memory model in common commercial use.

Worked Litmus Test: SC vs. TSO

Let’s expose the exact difference between SC and TSO with a classic 2-thread litmus test (initially M[X] = M[Y] = 0):

P1:               P2:
  sw 1, X           sw 1, Y
  lw x2, Y          lw x2, X

What values of (P1.x2, P2.x2) are possible?

✎ Check Your Understanding

  1. State the difference between cache coherence and a memory consistency model. Answer: Coherence governs the legal values returned by reads and writes to a single memory address, whereas consistency governs the ordering and visibility rules across all memory addresses across multiple threads.

  2. In the litmus test (P1: sw 1, X; lw x2, Y and P2: sw 1, Y; lw x2, X with X=Y=0 initially), why can (P1.x2, P2.x2) = (0, 0) happen under TSO even though it is impossible under SC? Answer: Under TSO, each processor buffers its store (sw) locally in its store buffer and allows its subsequent load (lw) to a different address to execute early against shared memory, so both loads can read 0 before either store drains globally.


Section 2: Weak Memory Models, Fences, Release Consistency, and Multi-Copy Atomicity

Strong memory models (like SC) provide an easy ISA-level programming model, but require slower execution or complex speculative-squash hardware. Weak memory models give fewer automatic ordering guarantees—making the ISA programming model notoriously tricky, even for experts—in exchange for simpler, higher-performance hardware that exposes hardware reorderings (such as store buffers, non-blocking caches, and out-of-order loads) directly to software.

Whenever software needs a specific ordering under a weak model, it inserts explicit fence instructions. Look at how fences fix our Producer-Consumer code on any weak-memory machine:

Producer:                          Consumer:
  sw    xdata, (xdatap)              spin: lw    xflag, (xflagp)
  li    xflag, 1                           beqz  xflag, spin
  fence w, w    // Write-write fence       fence r, r    // Read-read fence
  sw    xflag, (xflagp)                    lw    xdata, (xdatap)

The fence w, w forces sw xdata to become globally visible before sw xflag is issued; the fence r, r forces lw xflag to complete before lw xdata is read.

Formalizing Weak Memory Models with Ordering Rules

We can formalize memory models cleanly using reordering rules, where X \to Y means “operation X must be globally visible before operation Y is visible”:

Let’s formalize TSO using this notation:

Other hardware models relax progressively more rules:

Release Consistency (RC)

Release Consistency (RC)—used as the conceptual foundation for ARM and RISC-V weak memory models—relaxes all four ordinary orderings (R \to R, R \to W, W \to R, W \to W) and introduces explicit synchronization markers: acquire (S_A) and release (S_R)!

RC enforces two groups of rules:

  1. Synchronization boundaries (one-way barriers!): S_A \to R, \qquad S_A \to W, \qquad R \to S_R, \qquad W \to S_R (All accesses after an acquire stay after it; all accesses before a release finish before it.)
  2. Synchronizations ordered with each other: S_A \to S_A, \qquad S_R \to S_R, \qquad S_A \to S_R, \qquad S_R \to S_A

Look closely at what is not enforced in Release Consistency: R \to S_A, W \to S_A (operations before an acquire can slip past it into the critical section) and S_R \to R, S_R \to W (operations after a release can start early before the release finishes). That asymmetry formalizes one-way memory fences (such as RISC-V’s fence r, rw and fence rw, w).

Compilers Reorder Too! Language-Level Memory Models

Even if you bought a CPU with strict SC hardware, your C/C++ compiler can still break your lock-free code! Consider our Producer-Consumer loop written in C:

// Producer                // Consumer
*datap = x / y;            while (!*flagp) ;
*flagp = 1;                d = *datap;

An optimizing compiler routinely:

Because prohibiting all compiler optimizations would ruin single-thread performance, programming languages (like C/C++11 and Java) define Language-Level Memory Models—most adopting Release Consistency—that hide ISA details underneath the language standard. The language specifies which compiler optimizations are legal and maps portable atomic operations directly onto hardware fences—for example, in C11/C++11: atomic_load(memory_order_seq_cst) \longmapsto RISC-V fence rw,rw; lw; fence r,rw.

Multi-Copy Atomic vs. Non-Multi-Copy Atomic Models

Finally, weak models split into two classes regarding how different cores observe a third core’s stores:

  1. Multi-Copy Atomic Models (SC, TSO, revised ARM v8, and RISC-V RVWMO): Each hardware thread sees its own buffered writes early, but once a local store crosses the “Point of global visibility” and becomes visible to one other hardware thread, all other hardware threads must also be able to observe it (all cores see another core’s writes in the same order).
  2. Non-Multi-Copy Atomic Models (ARM v7, original ARM v8, IBM POWER, Digital Alpha): Large systems sometimes place shared intermediate buffers between clusters of CPUs (CPU 1, CPU 2 -> Intermediate Buffer A -> Shared Memory while CPU 3, CPU 4 -> Intermediate Buffer B -> Shared Memory). If CPU 2 is allowed to read CPU 1’s write out of Intermediate Buffer A before it drains to Shared Memory, CPU 2 sees the write before CPU 3 or CPU 4 can! Recent industry consensus (e.g., ARM’s revision from original ARMv8 to revised ARMv8, and RISC-V’s RVWMO) is that non-multi-copy-atomic models are simply too weak and error-prone for general-purpose processors.

[Editor Note: removed blank scratch slide and acknowledgements slide.]

✎ Check Your Understanding

  1. Using the ordering notation (R \to R, R \to W, W \to R, W \to W), which ordering rule does TSO relax compared to SC, and why does a simple Producer-Consumer flag/data handshake still work without fences under TSO? Answer: TSO relaxes only W \to R while still enforcing R \to R, R \to W, and W \to W. Because the Producer only requires W \to W (sw xdata before sw xflag) and the Consumer only requires R \to R (lw xflag before lw xdata), TSO preserves correctness without fences.

  2. What distinguishes a multi-copy atomic memory model from a non-multi-copy atomic memory model? Answer: In a multi-copy atomic model, once a store becomes visible to any other thread, it becomes visible to all other threads simultaneously; in a non-multi-copy atomic model (e.g., with shared cluster write buffers), one remote core can observe a store before other remote cores can.