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:
- Mutual Exclusion: Ensuring only one process accesses a shared resource at a time (what we built with locks in Lecture 24).
- 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:
- Coherence describes the legal values a single memory address should return (for instance, all cores agree on the order of writes to
flagalone). - Consistency describes ordering properties across all memory addresses (
flaganddata!). A Memory Consistency Model specifies what values can be returned by load instructions across multiple hardware threads—in other words, what final program states are legal.
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:
- The sequential ISA gives us
li xflag, 1 -> sw xflagandlw xflag -> beqz. - SC adds two cross-address guarantees:
sw xdata -> sw xflagon the Producer, andlw xflag -> lw xdataon the Consumer. Under SC, our Producer-Consumer code is 100% correct!
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):
- A core puts stores into its local Store Buffer while waiting for cache misses or bus access, allowing the CPU to keep running.
- Load optimizations: Later loads can bypass ahead of older buffered stores if they access a different address, and can forward/bypass the value from an earlier buffered store if they access the same address.
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?
(0, 1):P1runs completely beforeP2\implies Yes in SC, Yes in TSO.(1, 0):P2runs completely beforeP1\implies Yes in SC, Yes in TSO.(1, 1): Bothswhappen before bothlw\implies Yes in SC, Yes in TSO.(0, 0):- Under SC: NO (
N)! In any order-preserving global interleaving, eithersw 1, Xorsw 1, Ymust appear first; whichever appears first guarantees the other processor’s subsequentlwsees1! - Under TSO: YES (
Y)!P1putssw 1, XintoP1’s local store buffer and immediately executeslw x2, Yahead of it, readingM[Y] = 0. Meanwhile,P2putssw 1, YintoP2’s local store buffer and immediately executeslw x2, X, readingM[X] = 0! Only afterward do both store buffers drain to shared memory!
- Under SC: NO (
✎ Check Your Understanding
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.
In the litmus test (
P1: sw 1, X; lw x2, YandP2: sw 1, Y; lw x2, XwithX=Y=0initially), 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 read0before 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”:
- Sequential Consistency (SC) enforces all four pairs: R \to R, \qquad R \to W, \qquad W \to R, \qquad W \to W
- Relaxed memory models simply drop a subset of those four rules, using synchronization/fences to restore the illusion of SC when needed!
Let’s formalize TSO using this notation:
- TSO relaxes W \to R (subsequent reads do not have to wait for earlier writes in the store buffer to become globally visible).
- TSO enforces R \to R, R \to W, and W \to W. Look what that immediately tells us about our original un-fenced Producer-Consumer example (
sw xdata; sw xflagandlw xflag; lw xdata): it only ever needed W \to W and R \to R! Therefore, our simple Producer-Consumer code already works without any fences on TSO (such as x86)!
Other hardware models relax progressively more rules:
- PSO (Partial Store Ordering): Relaxes W \to R and W \to W (allows writes in the store buffer to merge/complete out of order).
- WO / Alpha / RMO / PowerPC: Relax W \to R, W \to W, and R \to RW (R \to R and R \to W).
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:
- 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.)
- 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:
- Reorders instructions (
*flagp = 1moved before slowx / y, or loading*datapinto a register before thewhileloop!). - Register-allocates
*flagp: loads*flagponce into a register before the loop and never checks memory again, turningwhile (!*flagp)into an infinite loop!
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:
- 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).
- 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 MemorywhileCPU 3, CPU 4 -> Intermediate Buffer B -> Shared Memory). IfCPU 2is allowed to readCPU 1’s write out ofIntermediate Buffer Abefore it drains to Shared Memory,CPU 2sees the write beforeCPU 3orCPU 4can! 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
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 xdatabeforesw xflag) and the Consumer only requires R \to R (lw xflagbeforelw xdata), TSO preserves correctness without fences.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.