# CS152 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: - **Coherence** describes the legal values a **single memory address** should return (for instance, all cores agree on the order of writes to `flag` alone). - **Consistency** describes ordering properties **across *all* memory addresses** (`flag` *and* `data`!). 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 xflag` and `lw xflag -> beqz`. - **SC adds two cross-address guarantees:** `sw xdata -> sw xflag` on the Producer, and `lw xflag -> lw xdata` on 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)`: `P1` runs completely before `P2` $\implies$ **Yes** in SC, **Yes** in TSO. - `(1, 0)`: `P2` runs completely before `P1` $\implies$ **Yes** in SC, **Yes** in TSO. - `(1, 1)`: Both `sw` happen before both `lw` $\implies$ **Yes** in SC, **Yes** in TSO. - **`(0, 0)`**: - **Under SC: NO (`N`)!** In any order-preserving global interleaving, either `sw 1, X` or `sw 1, Y` must appear first; whichever appears first guarantees the *other* processor's subsequent `lw` sees `1`! - **Under TSO: YES (`Y`)!** `P1` puts `sw 1, X` into `P1`'s local store buffer and immediately executes `lw x2, Y` ahead of it, reading `M[Y] = 0`. Meanwhile, `P2` puts `sw 1, Y` into `P2`'s local store buffer and immediately executes `lw x2, X`, reading `M[X] = 0`! Only afterward do both store buffers drain to shared memory! #### ✎ 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"*: - **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 xflag` and `lw 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: 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: ```c // Producer // Consumer *datap = x / y; while (!*flagp) ; *flagp = 1; d = *datap; ``` An optimizing compiler routinely: - Reorders instructions (`*flagp = 1` moved before slow `x / y`, or loading `*datap` into a register *before* the `while` loop!). - **Register-allocates `*flagp`**: loads `*flagp` once into a register before the loop and never checks memory again, turning `while (!*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: 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.