Repository navigation
Computer Architecture 07 caches coherence
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: CPU cache
- Wikipedia: Memory hierarchy
- Wikipedia: Cache coherence
- Wikipedia: MESI protocol
- Wikipedia: False sharing
- Arm: Learn the architecture: Memory Systems, Ordering, and Barriers (document 102336)
- Book: Patterson and Hennessy, Computer Organization and Design (Arm edition), chapter 5
Main memory is about a hundred times slower than the processor. A cache is a small, fast memory next to the core that keeps copies of recently used data, so most loads never have to go all the way to main memory. With several cores, each with its own cache, a second problem appears: several copies of the same data must stay in agreement. That is cache coherence.
Sizes, latencies and examples on this page are typical, illustrative values, not the figures of a particular chip.
This page covers locality, cache lines, hits and misses, how an address finds its place in a cache (direct-mapped, set-associative), replacement, write policies, the three kinds of miss, average access time, coherence with the MESI protocol, snooping versus directories, and false sharing. The ordering of accesses to different addresses is on Memory and Ordering.
| Library | Computer |
|---|---|
| Your desk (holds a few books) | L1 cache |
| The shelf behind you | L2 cache |
| The library down the hall | Main memory |
| You fetch a whole book, not one page | The cache fetches a whole line (typically 64 bytes), not one byte |
| You keep the books you are using on the desk | Temporal locality: recently used data is likely to be used again |
| The page you want next is in the same book | Spatial locality: nearby data is likely to be used soon |
flowchart TD
L["Core issues a load"] --> C{"Is the line in L1?"}
C -->|"Hit (most of the time)"| H["Return data in a few cycles"]
C -->|"Miss"| L2{"In L2?"}
L2 -->|"Hit"| H2["Copy line into L1, return data<br/>(~10-15 cycles)"]
L2 -->|"Miss"| MEM["Fetch line from main memory<br/>(hundreds of cycles)"]
MEM --> FILL["Fill L2 and L1, return data"]
Memory moves between levels in fixed-size blocks called cache lines. A load of one 4-byte integer brings in the whole 64-byte line around it, which is why walking an array in order is fast: the next 15 integers are already there.
| Access pattern | Locality | Cache behaviour |
|---|---|---|
for (i...) sum += a[i]; |
Spatial and temporal | Excellent: 1 miss per 16 ints |
| Walking a linked list scattered in memory | Poor spatial | Often a miss per node |
a[i][j] with j in the outer loop (column order in C) |
Poor spatial | A miss on almost every access |
Sources: Wikipedia: CPU cache
The cache splits each address into three fields:
flowchart LR
A["Address"] --> T["Tag<br/>which line is it?"]
A --> I["Index<br/>which set to look in"]
A --> O["Offset<br/>which byte in the line"]
| Organisation | A line can go in | Pros / cons |
|---|---|---|
| Direct-mapped | Exactly one place | Simple and fast; two hot addresses that map to the same place keep evicting each other |
| N-way set-associative | Any of N places in one set | The common choice (L1 is often 4- to 8-way) |
| Fully associative | Anywhere | No conflicts, but checking every tag is expensive; used for small structures such as TLBs |
A 32 KB, 4-way set-associative cache with 64-byte lines:
Lines = 32 KB / 64 B = 512 lines
Sets = 512 lines / 4 ways = 128 sets
Offset bits = log2(64) = 6 (bits 0-5)
Index bits = log2(128) = 7 (bits 6-12)
Tag bits = the rest (bits 13 and up)
Address 0x0001_2345: offset = 0x05, index = (0x12345 >> 6) & 0x7F = 0x0D (set 13), tag = 0x12345 >> 13 = 0x9. The cache looks in set 13, compares tag 0x9 with the tags of its 4 ways, and reports a hit if one matches and is valid.
flowchart TD
S["Set 13"] --> W0["Way 0: tag 0x4, valid"]
S --> W1["Way 1: tag 0x9, valid ✔ hit"]
S --> W2["Way 2: tag 0x1F, valid"]
S --> W3["Way 3: empty"]
On a miss in a full set, one line must be evicted. LRU (least recently used) evicts the line untouched for longest; real caches use cheaper approximations such as pseudo-LRU or random.
| Policy | On a store | Trade-off |
|---|---|---|
| Write-through | Update the cache and the next level immediately | Simple; uses a lot of bandwidth |
| Write-back | Update the cache only; mark the line dirty; write it out when evicted | Less traffic; the usual choice for L1/L2 |
| Write-allocate | On a store miss, bring the line in first | Pairs with write-back |
| No-write-allocate | On a store miss, write straight to the next level | Pairs with write-through |
| Kind | Cause | Remedy |
|---|---|---|
| Compulsory (cold) | First ever access to a line | Bigger lines, prefetching (the hardware guesses the next lines and fetches them early) |
| Capacity | The working set is bigger than the cache | Bigger cache, or restructure the loop (blocking/tiling) |
| Conflict | Too many hot lines map to the same set | More associativity |
With several cores there is a fourth kind, coherence misses, explained below.
AMAT = Hit time + Miss rate × Miss penalty
Worked example: L1 hit 4 cycles, L1 miss rate 5%, L2 hit 12 cycles, L2 miss rate (of L1 misses) 20%, memory 200 cycles.
L2 miss penalty seen by L1 = 12 + 0.20 × 200 = 52 cycles
AMAT = 4 + 0.05 × 52 = 6.6 cycles
Halving the L1 miss rate to 2.5% gives 4 + 0.025 × 52 = 5.3 cycles. Small changes in miss rate matter a lot.
Each core has a private L1 (and often L2). If two cores read the same address, both caches hold a copy. If one core then writes, the other copy is stale.
sequenceDiagram
participant C0 as Core 0 cache
participant C1 as Core 1 cache
participant M as Memory
C0->>M: read X
M-->>C0: X = 0
C1->>M: read X
M-->>C1: X = 0
C0->>C0: write X = 5 (in its cache only)
C1->>C1: read X -> 0 ?? stale!
A coherence protocol guarantees two things for every single address:
- Write propagation: a write eventually becomes visible to all cores.
- Write serialization: all cores see writes to the same address in the same order.
The usual rule that delivers this is single writer, multiple readers: at any moment a line is either writable by one cache, or readable by many, never both.
Sources: Wikipedia: Cache coherence
Each line in each cache is in one of four states:
| State | Meaning | Can read? | Can write without asking? | Same as memory? |
|---|---|---|---|---|
| M Modified | Only copy, has been written | Yes | Yes | No (dirty) |
| E Exclusive | Only copy, not written | Yes | Yes (moves to M silently) | Yes |
| S Shared | Other caches may also have it | Yes | No: must invalidate others first | Yes |
| I Invalid | Not present / stale | No | No | n/a |
stateDiagram-v2
[*] --> I
I --> E: local read, no other copy
I --> S: local read, others have it
I --> M: local write (invalidate others)
E --> M: local write (silent)
E --> S: another core reads
S --> M: local write (invalidate others)
M --> S: another core reads (write back data)
M --> I: another core writes
S --> I: another core writes
E --> I: another core writes
Replaying the stale-read example with MESI:
| Step | Core 0 line | Core 1 line | Message |
|---|---|---|---|
| Core 0 reads X | E | I | read from memory |
| Core 1 reads X | S | S | Core 0 sees the read and downgrades |
| Core 0 writes X = 5 | M | I | invalidate sent; Core 1 drops its copy |
| Core 1 reads X | S | S | Core 0 supplies 5 (and writes back) |
Core 1 now reads 5. Its second read was a coherence miss. Real systems add states (MOESI adds Owned, so a dirty line can be shared without writing memory first; Arm's AMBA CHI interconnect uses a MOESI-style set of states).
Sources: Wikipedia: MESI protocol
| Snooping | Directory | |
|---|---|---|
| How caches find out | Every request is broadcast; every cache "snoops" | A directory records which caches hold each line; messages go only to them |
| Scales to | A handful of cores | Many cores |
| Used in | Small clusters | Large server chips, many-core systems |
flowchart LR
subgraph Snoop["Snooping"]
A0["Core 0"] --- BUS["Shared bus / broadcast"]
A1["Core 1"] --- BUS
A2["Core 2"] --- BUS
end
subgraph Dir["Directory"]
D["Directory<br/>line X: cores 1, 3"]
B0["Core 0"] -->|"write X?"| D
D -->|"invalidate"| B1["Core 1"]
D -->|"invalidate"| B3["Core 3"]
end
Coherence works on whole lines, not variables. Two cores updating different variables that happen to sit in the same 64-byte line keep stealing the line from each other:
// illustrative
struct { long count0; long count1; } c; // both in one cache line
// thread on core 0: for (...) c.count0++;
// thread on core 1: for (...) c.count1++;sequenceDiagram
participant C0 as Core 0
participant C1 as Core 1
C0->>C0: write count0 (line in M)
C1->>C0: want line to write count1
C0-->>C1: line moves, Core 0 invalidated
C0->>C1: want line back to write count0
C1-->>C0: line moves again...
The program is correct but can run many times slower. The fix is to put each hot variable on its own line, for example with alignas(64) padding.
Sources: Wikipedia: False sharing
- Caches exploit locality and move data in 64-byte lines; an address splits into tag, index and offset.
- AMAT = hit time + miss rate × miss penalty; compulsory, capacity and conflict misses have different remedies.
- Coherence (e.g. MESI) keeps one writer or many readers per line; false sharing is coherence traffic between unrelated variables in one line.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look