Skip to content

Computer Architecture 07 caches coherence

Mugundan edited this page Nov 27, 2026 · 1 revision

Caches and Coherence

Relevant source files

The following references were used as context for generating this wiki page:

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.

Purpose and Scope

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.

The Desk and Library Analogy

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

Hits, Misses and Lines

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"]
Loading

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

Where Does a Line Go?

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"]
Loading
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

Worked Example

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"]
Loading

Replacement

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.

Writes

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

Why Misses Happen: The Three Cs

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.

Average Memory Access Time

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.

Coherence: Many Copies of One Line

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!
Loading

A coherence protocol guarantees two things for every single address:

  1. Write propagation: a write eventually becomes visible to all cores.
  2. 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

The MESI Protocol

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
Loading

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 versus Directories

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
Loading

False Sharing

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

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

Key Points

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

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally