---
title: Writes, coherence and DMA
heading: What happens to stores, and who else might be looking at memory
eyebrow: C8 · Lesson 45 · Writes, coherence and DMA
xp: 40
---

::: hook
A cache is easy to reason about while the processor only reads: the cached copy and memory always agree. Stores break that. A write-back cache holds data newer than memory, and a DMA controller or a second core reading memory directly sees the old values. Going the other way, a DMA controller that writes fresh data into memory leaves stale copies in the cache. Getting writes right is about traffic and speed, and also about correctness whenever anything besides the one core touches memory.
:::

::: play
- Each line of the cache is filled from scratch by a loop that stores to a fraction x of its words, k times each, before the line is evicted.
- Write-through sends every store to memory: k · x · L bytes per line. Write-back with write-allocate first reads the whole line in, then writes the whole line back once: 2L bytes, however many stores there were.
- With a single pass over every word (k = 1, x = 1), write-back moves twice as much data. From k = 2 on it wins, and the more often each word is rewritten, the more it wins.
:::

```sim plot
view: graph
x: k = 1..10
y: B = 0..1000 bytes
slider: x = 0.1..1 step 0.05 = 1
slider: L = 16..128 step 16 = 64
plot: k*x*L | label: write-through
plot: 2*L | label: write-back, allocate
readout: break-even stores per word = 2/x | digits: 3
```

::: predict
## A loop writes 4000 bytes into a fresh array, each word once, through a write-back, write-allocate cache with 64-byte lines. About how many bytes cross the memory bus?

- [ ] 4000
- [x] 8000
- [ ] 64
- [ ] 256,000

::: reveal
About 8000. Each of the 63 lines is read in on its first store miss (write-allocate), then written back when it's evicted: 4000 bytes in and 4000 out. A write-through cache, or a write-back cache that doesn't allocate on a store miss, would send just the 4000 bytes being written. That's why processors offer streaming stores and "zero this line" instructions for code that fills memory.
:::
:::

::: nameit
## On a store miss: allocate or not

- **Write-allocate** brings the line into the cache, then writes it. It pays a line read for each store miss, which wins when the line will be read or written again soon.
- **No-write-allocate** (write-around) sends the store to memory and leaves the cache alone. It wins for data written once and not read back, such as an output buffer.

Write-back caches usually allocate; write-through caches usually don't.

## Write buffers

A write-through cache would make the processor wait for memory on every store. A **write buffer**, a small queue of pending stores, lets it continue while memory catches up. It only hides the delay on average: if stores arrive faster than memory accepts them, the buffer fills and the processor stalls. With a store fraction f, one instruction a cycle and memory taking m cycles per write, the buffer keeps up only while $f \cdot m < 1$.

## Dirty evictions lengthen misses

In a write-back cache, a miss that evicts a dirty line has to write it back before (or while) the new line comes in. If a fraction d of evicted lines are dirty and each transfer takes P,

$$\text{average miss penalty} \approx P(1 + d)$$

unless a buffer lets the write-back happen later.

## Coherence with DMA

A DMA controller reads and writes memory directly, bypassing the cache. Two operations keep the cache honest:

- **Clean** (write back) the lines of a buffer before a DMA controller *reads* it, so memory holds what the processor wrote.
- **Invalidate** the lines of a buffer after a DMA controller *writes* it, so the processor's next loads miss and fetch the new data.

DMA buffers should start on a line boundary and fill whole lines. Invalidating a line that also holds an unrelated variable would throw away that variable's newest value. Some systems instead mark DMA buffers as uncacheable, or have hardware that snoops DMA traffic.

## Coherence between cores

With several cores, each with its own cache, a **coherence protocol** keeps their copies consistent. The usual rule is **write-invalidate**: before a core writes a line, every other cached copy is invalidated, so there's only ever one writer and readers get the newest value on their next miss. Each line is in a state such as Modified (dirty, only copy), Shared (clean, maybe in several caches) or Invalid. Course S4 goes into the protocols.
:::

::: example
## A store-heavy loop is 12% stores at one instruction a cycle, through a write-through cache whose write buffer drains one store every 10 cycles. What happens?

::: solution
1. **Compare the rates.** Stores arrive at 0.12 per cycle, but memory accepts only 0.1.
2. **The buffer fills.** However deep the buffer, it eventually fills, and from then on the processor can only issue a store when one drains.
3. **The throughput.** At most 0.1 stores a cycle means at most
   $$\frac{0.1}{0.12} = 0.83$$
   instructions a cycle, a CPI of 1.2 instead of 1.
4. **Write-back.** A write-back cache would absorb most of those stores, since loops tend to write the same lines repeatedly.

**Answer:** the write buffer fills, and the processor slows to 0.83 instructions a cycle, a CPI of 1.2.
:::
:::

::: example
## A cache misses 5% of the time with a 100-cycle penalty, and 30% of evicted lines are dirty. What's the average access time, with a 1-cycle hit, if write-backs aren't buffered?

::: solution
1. **The average miss.** Every miss fetches a line, and 30% also write one back first:
   $$100(1 + 0.3) = 130\ \text{cycles}$$
2. **AMAT.**
   $$\begin{aligned} \text{AMAT} &= 1 + 0.05 \times 130 \\ &= 7.5\ \text{cycles} \end{aligned}$$
   against 6 if no line were ever dirty.
3. **A victim buffer.** A victim buffer that holds the dirty line while the new one is fetched recovers most of the difference.

**Answer:** 7.5 cycles, against 6 if no line were ever dirty.
:::
:::

::: example
## A network controller writes a 1500-byte frame by DMA into a buffer, with 64-byte cache lines. How many lines must the driver invalidate, and what goes wrong if the buffer starts 20 bytes into a line?

::: solution
1. **Aligned.** The frame covers
   $$\left\lceil \frac{1500}{64} \right\rceil = 24\ \text{lines}$$
2. **Starting 20 bytes in.** It covers $\lceil 1520/64 \rceil$ = 24 lines too, but the first one also holds 20 bytes of something else.
3. **What goes wrong.** If the processor had written to those 20 bytes and the line was dirty, invalidating it discards the processor's write; cleaning it first would instead overwrite the start of the frame in memory.
4. **The cure.** Neither is right, which is why DMA buffers are aligned to lines and padded to whole lines.

**Answer:** 24 lines; starting 20 bytes in, the first line also holds other data, so invalidating it loses the processor's write and cleaning it overwrites the frame.
:::
:::

::: check
kind: parts
given: N = 1000 | 4096 | 16384; L = 32 | 64

## A loop stores {N} words (4 bytes each) into a fresh array, once each, with {L}-byte lines.

::: part
answer: 4*N
unit: bytes
tolerance: 0.5%

### How many bytes reach memory through a write-through, no-allocate cache?

::: misses
- [any] Every byte stored, once.
:::
:::

::: part
answer: 8*N
unit: bytes
tolerance: 0.5%

### And through a write-back, write-allocate cache?

::: misses
- [4*N] Each line is also read in before the first store to it.
- [any] Read every line in, then write every line back.
:::
:::
:::

::: check
kind: parts
given: f = 15 | 20 | 25; m = 8 | 10 | 12

## A program is {f}% stores; memory accepts one write every {m} cycles through a write buffer.

::: part
answer: f/100
tolerance: 0.5%

### How many stores per cycle would it issue at one instruction a cycle?

::: misses
- [any] The store fraction.
:::
:::

::: part
answer: f*m/100
tolerance: 0.5%

### What's the lowest CPI the memory allows once the buffer is full?

::: misses
- [any] Memory caps stores at $1/m$ a cycle, so instructions at $1/(fm)$.
:::
:::
:::

::: check
kind: parts
given: P = 50 | 100; d = 20 | 40; m = 2 | 5

## A write-back cache misses {m}% of the time with a {P}-cycle penalty, and {d}% of evicted lines are dirty. Hits take 1 cycle.

::: part
answer: P*(1 + d/100)
tolerance: 0.5%

### What's the average miss penalty without a write buffer?

::: misses
- [P] Dirty lines have to be written back too.
- [any] $P(1 + d)$.
:::
:::

::: part
answer: 1 + m/100*P*(1 + d/100)
tolerance: 0.5%

### What's the AMAT?

::: misses
- [any] $1 + m \cdot P(1 + d)$.
:::
:::
:::

::: check
kind: parts
given: B = 256 | 1500 | 4096; L = 32 | 64; o = 8 | 20

## A DMA controller fills a {B}-byte receive buffer, and the cache has {L}-byte lines.

::: part
answer: ceil(B/L)
tolerance: 0

### How many lines must be invalidated if the buffer starts on a line boundary?

::: misses
- [any] $\lceil B/L \rceil$.
:::
:::

::: part
answer: ceil((o + B)/L)
tolerance: 0

### And if it starts {o} bytes into a line?

::: misses
- [any] The buffer now spans from the line's start to {o} + {B}.
:::
:::
:::

::: check
kind: choice

## A DMA controller has just written new samples into a buffer the processor read earlier. What must the driver do before the processor reads it?

- [ ] Clean the buffer's lines
- [x] Invalidate the buffer's lines
- [ ] Nothing: caches always see memory writes
- [ ] Turn off interrupts

::: misses
- [1] Cleaning writes the cache's old copy over the new data in memory.
- [3] DMA bypasses the cache, so the cached copies are stale.
- [4] Interrupts aren't involved; the cache still holds stale lines.
:::
:::

::: check
kind: choice

## The processor has filled a transmit buffer through a write-back cache and is about to start a DMA transfer that reads it. What must it do first?

- [x] Clean the buffer's lines, so memory holds the new data
- [ ] Invalidate the buffer's lines
- [ ] Read the buffer back once
- [ ] Nothing

::: misses
- [2] Invalidating would throw the new data away before it reached memory.
- [3] Reading hits in the cache and changes nothing in memory.
- [4] The newest data may still be only in the cache, so DMA would send old bytes.
:::
:::

::: check
kind: choice

## Cores 1 and 2 both have line X cached. Core 1 stores to X. Under a write-invalidate protocol, what happens?

- [ ] Core 2's copy is updated with the new value
- [x] Core 2's copy is invalidated, and its next load of X misses and gets the new value
- [ ] Nothing until X is evicted from core 1
- [ ] Core 1's store waits until core 2 evicts X

::: misses
- [1] That's write-update, a different and less common protocol.
- [3] Then core 2 could read the old value indefinitely.
- [4] The invalidation is sent at once; nobody waits for an eviction.
:::
:::

::: check
kind: derivation
vars: k = 1..100, x = 0.01..1, L = 16..256

## Before eviction, a loop stores k times to each of a fraction x of a freshly allocated line's words; the line is L bytes.

::: step
answer: k*x*L

### How many bytes does write-through send?
:::

::: step
answer: 2*L

### How many does write-back with allocation move?
:::

::: step
answer: 2/x

### Above what k does write-back move less?
:::

::: right
Right. Rewriting the same words is where write-back pays.
:::
:::

::: explain
## Why must a driver invalidate a DMA receive buffer's cache lines, and why should the buffer be aligned to whole lines?

::: model
The DMA controller writes straight to memory, so any copy of the buffer already in the cache still holds the old bytes, and the processor's loads would hit on that stale copy. Invalidating the lines forces those loads to miss and fetch what the controller wrote. But invalidation works on whole lines. If the buffer shares a line with another variable, invalidating it can discard a newer value of that variable that existed only in the cache, and cleaning it instead would write stale buffer bytes over the new data in memory. Aligning the buffer to line boundaries and padding it to whole lines means every line it touches belongs to the buffer alone.
:::
:::

::: practice
::: check
given: N = 1000 | 2000 | 4000 | 5000 | 8000 | 16000
answer: 8*N
unit: bytes
tolerance: 0.5%

## {N} words stored once through a write-back, write-allocate cache. Bytes moved?

::: misses
- [any] Each line is read in, then written back.
:::
:::

::: check
given: f = 12 | 18; m = 10 | 15
answer: f*m/100
tolerance: 0.5%

## {f}% stores, {m} cycles per memory write. Lowest CPI once the buffer fills?

::: misses
- [any] $fm$.
:::
:::

::: check
given: B = 512 | 2048; L = 32 | 64
answer: ceil(B/L)
tolerance: 0

## How many {L}-byte lines does an aligned {B}-byte DMA buffer cover?

::: misses
- [any] $\lceil B/L \rceil$.
:::
:::
:::
