Cache coherence and the MESI protocol

Advanced

Introduction

A multicore chip gives each core its own fast L1 cache. That is good for speed and bad for agreement: if core 0 changes a variable that core 1 has cached, core 1 would read an old value unless the hardware does something. The set of rules the hardware follows is cache coherence. It works silently, millions of times a second, and it decides how well shared-memory programs perform. This lesson explains the most common protocol, MESI, and a performance trap that comes from it, false sharing.

How it works

Coherence means that all cores see one value for each memory location, and that a write is eventually seen by everyone. Most chips use a write-invalidate protocol: before a core writes a block, it makes every other cache drop its copy. Caches watch the shared bus (or ask a directory) to find out what the others do.

In the MESI protocol every block in a cache is in one of four states:

  • Modified (M): this cache has the only copy, and it differs from memory. It must be written back before anyone else reads the block.
  • Exclusive (E): this cache has the only copy, and it matches memory. It can be written without telling anyone.
  • Shared (S): several caches may hold the block, and it matches memory. A write needs an invalidate first.
  • Invalid (I): the cache holds nothing useful.

The rules for one block: a read miss gives Exclusive if no other cache has the block, and Shared if some do (a Modified owner first writes the block back and becomes Shared). A write makes this cache Modified and every other copy Invalid. A read hit changes nothing.

states = ["I", "I", "I"]            # the state of one memory block in each of 3 cores

def read(core):
    if states[core] == "I":
        others = [i for i in range(3) if i != core and states[i] != "I"]
        for i in others:
            states[i] = "S"
        states[core] = "S" if others else "E"

def write(core):
    for i in range(3):
        states[i] = "I"
    states[core] = "M"

for op, core in [("R", 0), ("R", 1), ("W", 1), ("R", 0), ("W", 2)]:
    read(core) if op == "R" else write(core)
    print(op, "by core", core, "->", " ".join(states))
Open in compiler

False sharing is a performance bug that coherence causes. Cache blocks are 64 bytes. If two cores keep their own counters in two variables that sit next to each other, both counters are in one block, and every write by one core invalidates the other core's copy, even though they never touch the same variable. The block bounces between the caches and both cores crawl. The fix is padding: put each core's data in a separate block.

BLOCK = 64
addresses = {"counter_a": 0, "counter_b": 8, "counter_c": 64}
names = list(addresses)
for i in range(len(names)):
    for j in range(i + 1, len(names)):
        same = addresses[names[i]] // BLOCK == addresses[names[j]] // BLOCK
        print(names[i], names[j], "share a block" if same else "are in different blocks")
Open in compiler

Coherence is not the whole story. Memory consistency says in which order the writes of one core may be seen by others. Modern processors reorder memory operations for speed, so programs that share data must use locks or atomic operations and memory barriers, which stop the reordering where it matters.

Example

Three cores read and write the same block. The program keeps the MESI state of the block in each core and prints all three after every operation.

states = ["I", "I", "I"]            # the state of one memory block in each of 3 cores

def read(core):
    if states[core] == "I":
        others = [i for i in range(3) if i != core and states[i] != "I"]
        for i in others:
            states[i] = "S"
        states[core] = "S" if others else "E"

def write(core):
    for i in range(3):
        states[i] = "I"
    states[core] = "M"

for op, core in [("R", 0), ("R", 1), ("W", 1), ("R", 0), ("W", 2)]:
    read(core) if op == "R" else write(core)
    print(op, "by core", core, "->", " ".join(states))
Open in compiler

Line by line

  1. states holds the state of the block in core 0, 1 and 2; all start Invalid.
  2. read does nothing on a hit. On a miss it looks at who else has the block: those copies become Shared, and the reader becomes Shared too, or Exclusive if it is alone.
  3. write invalidates every copy and makes the writer Modified.
  4. The loop runs five operations. The third, a write by core 1, leaves core 1 Modified and the others Invalid; the fourth, a read by core 0, makes both Shared.

Expected result

R by core 0 -> E I I
R by core 1 -> S S I
W by core 1 -> I M I
R by core 0 -> S S I
W by core 2 -> I I M

In the real world

Every shared-memory program on a multicore chip depends on coherence, from a database to a game. Performance engineers look for false sharing with profilers that count cache-to-cache transfers, and library authors add padding to counters and queue indexes to keep them in separate blocks. Large servers have several chips, and some use directory protocols that remember who has each block, instead of every cache listening on one bus. Lock-free data structures rely on atomic instructions that the coherence hardware makes possible.

Common mistakes

  • Thinking a write updates the copies in other caches: with write-invalidate it removes them.
  • Forgetting that a read of a block held Modified by another core makes that core write it back first.
  • Thinking false sharing is a bug in the program's results: the answers are right, only slow.
  • Treating coherence as ordering: it says nothing about the order of writes to different locations.

Best practices

  • Give each thread its own data, and combine results at the end, instead of updating one shared counter.
  • Pad or align hot per-thread variables to the cache block size.
  • Use locks, atomics and barriers for shared data; never rely on the hardware's reordering.

Summary

Private caches would give stale data, so hardware keeps them coherent, mostly by invalidating other copies on a write. In MESI a block is Modified, Exclusive, Shared or Invalid. False sharing makes cores slow when unrelated variables share a block, and memory consistency is the separate question of the order in which writes become visible.

Quick check

1. In MESI, core 0 reads a block that no other cache has. Which state does it get?
2. Core 1 holds a block Modified. Core 0 reads it. What happens first?
3. What is false sharing?
4. A core writes a Shared block. What happens to other copies?

Key takeaways

  • Every core has a private cache, so the hardware must stop stale copies from being read.
  • In MESI each cached block is Modified, Exclusive, Shared or Invalid, and a write invalidates all other copies.
  • Variables that different cores write should not share a cache block.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.