---
title: Cache design
heading: Associativity, replacement, writes and levels of cache
eyebrow: C8 · Lesson 44 · Cache design
xp: 40
---

::: hook
Main memory takes around a hundred processor cycles to answer, so a processor that waited for it on every load would spend almost all its time waiting. Caches hide that delay by keeping recently used memory close at hand, and lesson 39 showed the basic direct-mapped kind. Real caches make more choices: how many places each address may go, which line to throw out when a new one arrives, what to do on a write, and how many levels to stack. Each choice trades a little hardware or hit time against fewer misses, and the miss rate is what decides how fast programs really run.
:::

::: play
- A program reads an array from start to end with a stride of s bytes between accesses. Each miss brings in a whole line of L bytes, so with small strides most accesses find their data already loaded.
- The curve is the miss rate against the stride. Move L: bigger lines mean fewer misses for sequential access, until the stride is larger than a line and every access misses.
- The readouts give the average memory access time for 4-byte strides (reading every int) and for 64-byte strides (one int out of every 16).
:::
:::

```sim plot
view: graph
x: s = 4..256
y: m = 0..1.1
slider: L = 16..128 step 16 = 64
slider: P = 20..200 step 10 = 100
plot: (s/L + 1 - abs(s/L - 1))/2 | label: miss rate
readout: AMAT reading every int, cycles = 1 + (4/L + 1 - abs(4/L - 1))/2*P | digits: 3
readout: AMAT at a 64-byte stride, cycles = 1 + (64/L + 1 - abs(64/L - 1))/2*P | digits: 3
```

::: predict
## A direct-mapped 4 KiB cache. A loop reads `a[i]` and then `b[i]`, and the arrays start exactly 4 KiB apart. What happens?

- [ ] Nearly every access hits, thanks to spatial locality
- [ ] Half the accesses miss
- [x] Nearly every access misses, because a[i] and b[i] map to the same line and keep evicting each other
- [ ] The cache detects the pattern and prefetches

::: reveal
Every access misses: addresses 4 KiB apart have the same index, so in a direct-mapped cache they compete for one line. A 2-way set-associative cache gives each index two lines, and both arrays fit. These are **conflict misses**.
:::
:::

::: nameit
## Associativity

An **N-way set-associative** cache groups its lines into **sets** of N. An address picks a set by its index bits and may go in any line of that set; all N tags are compared at once.

$$\text{sets} = \frac{\text{capacity}}{\text{line size} \times N}, \quad \text{index bits} = \log_2(\text{sets}), \quad \text{offset bits} = \log_2(\text{line size})$$

and the tag is the rest of the address. Direct-mapped is 1-way; **fully associative** is one set holding every line. The set an address uses is $\lfloor \text{address}/L \rfloor \bmod \text{sets}$.

## Replacement and writes

- **Replacement:** on a miss in a full set, evict the **least recently used** line (LRU), or a random one, which is cheaper and nearly as good for large sets.
- **Write-through:** every store also goes to memory (usually through a write buffer). Simple, but heavy memory traffic.
- **Write-back:** stores change only the cache and mark the line **dirty**; it's written to memory when evicted. One write for many stores to the same line.
- **Write-allocate:** on a store miss, bring the line in first (usual with write-back).

## The three Cs

Misses are **compulsory** (first touch of a line), **capacity** (the working set doesn't fit) or **conflict** (too many lines map to one set). Bigger caches cut capacity misses, more ways cut conflict misses, longer lines cut compulsory misses for sequential data.

## Levels

A small, fast L1 backed by a larger L2 (and often L3):

$$\text{AMAT} = t_{L1} + m_{L1}(t_{L2} + m_{L2} \cdot t_\text{mem})$$

where $m_{L2}$ is the L2's **local** miss rate, the fraction of L1 misses that also miss in L2. The effect on CPI is the memory accesses per instruction × miss rate × penalty, added to the base CPI.
:::

::: example
## Split a 32-bit address for a 32 KiB, 4-way cache with 64-byte lines.

::: solution
1. **Lines and sets.** 32 KiB of 64-byte lines is 512 lines, in 128 sets of 4.
2. **Offset.** $\log_2 64 = 6$ bits.
3. **Index.** $\log_2 128 = 7$ bits.
4. **Tag.** The rest:
   $$32 - 7 - 6 = 19\ \text{bits}$$

**Answer:** a 19-bit tag, a 7-bit index and a 6-bit offset.
:::
:::

::: example
## L1 hits in 1 cycle and misses 5% of the time; L2 hits in 10 cycles and misses 20% of the accesses that reach it; memory takes 100 cycles. What is the AMAT, with and without the L2?

::: solution
1. **With the L2.**
   $$\begin{aligned} t &= 1 + 0.05(10 + 0.2 \times 100) \\ &= 1 + 0.05 \times 30 \\ &= 2.5\ \text{cycles} \end{aligned}$$
2. **Without it.**
   $$\begin{aligned} t &= 1 + 0.05 \times 100 \\ &= 6\ \text{cycles} \end{aligned}$$
3. **Compare.** The L2 more than halves the average.

**Answer:** an AMAT of 2.5 cycles with the L2 and 6 cycles without it.
:::
:::

::: example
## Two arrays are exactly 8 KiB apart, and a loop alternates between them. What happens in an 8 KiB direct-mapped cache with 32-byte lines, and in a 2-way cache of the same size?

::: solution
1. **Split the address.** The direct-mapped cache has 256 lines: 5 offset bits and 8 index bits.
2. **Compare the two arrays.** Addresses 8 KiB apart have the same index and different tags.
3. **Direct-mapped.** Each access evicts the line the other just loaded: every access misses, although the cache has room for both. That's a conflict miss.
4. **2-way.** Both lines live in the same set, and after the first two misses every access hits.

**Answer:** in the direct-mapped cache every access misses, a conflict miss each time; in the 2-way cache every access hits after the first two.
:::
:::

::: check
kind: parts
given: C = 8 | 32 | 256; L = 32 | 64; N = 2 | 4 | 8; let sets = C*1024/(L*N)

## A {C} KiB, {N}-way set-associative cache has {L}-byte lines; addresses are 32 bits.

::: part
answer: sets
tolerance: 0

### How many sets?

::: misses
- [C*1024/L] That's the number of lines; each set holds {N}.
- [any] Not yet. capacity / (line × ways).
:::
:::

::: part
answer: log(sets)/log(2)
tolerance: 0.5%

### How many index bits?

::: misses
- [any] $\log_2$ of the number of sets.
:::
:::

::: part
answer: 32 - log(sets)/log(2) - log(L)/log(2)
tolerance: 0.5%

### How many tag bits?

::: misses
- [any] 32 − index − offset.
:::
:::
:::

::: check
kind: parts
given: t1 = 1 | 2; m1 = 0.03 | 0.08; t2 = 8 | 15; m2 = 0.1 | 0.4; P = 80 | 200

## L1 hits in {t1} cycles and misses {m1} of the time; L2 hits in {t2} cycles and misses {m2} of the accesses that reach it; memory takes {P} cycles.

::: part
answer: t1 + m1*(t2 + m2*P)
unit: cycles
tolerance: 0.5%

### What is the AMAT?

::: misses
- [t1 + m1*t2 + m2*P] The L2's misses happen only on L1 misses: multiply by {m1} too.
- [any] Not yet. $t_1 + m_1(t_2 + m_2 P)$.
:::
:::

::: part
answer: (t1 + m1*P)/(t1 + m1*(t2 + m2*P))
tolerance: 0.5%

### How many times better is that than L1 alone with memory behind it?

::: misses
- [any] AMAT without L2 over AMAT with it.
:::
:::
:::

::: check
kind: parts
given: n = 1000 | 4096; e = 1 | 4 | 8; L = 32 | 64

## A loop reads every element of an array of {n} elements of {e} bytes, aligned to a line, once, through a cache with {L}-byte lines that starts empty.

::: part
answer: n*e/L
tolerance: 0.5%

### How many misses?

::: misses
- [n] Each miss brings in a whole line, holding {L}/{e} elements.
- [any] Not yet. Bytes read over line size.
:::
:::

::: part
answer: e/L*100
unit: %
tolerance: 0.5%

### What is the miss rate?

::: misses
- [any] One miss per line's worth of elements.
:::
:::
:::

::: check
kind: parts
given: A = 40000 | 74565 | 1000000; L = 16 | 64; S = 64 | 256

## A cache has {S} sets of {L}-byte lines. Which set does address {A} map to, and at what offset?

::: part
answer: floor(A/L) - S*floor(A/(L*S))
tolerance: 0

### Which set?

::: misses
- [floor(A/L)] That's the line number in memory; take it modulo the number of sets.
- [any] Not yet. ⌊A/L⌋ mod S.
:::
:::

::: part
answer: A - L*floor(A/L)
tolerance: 0

### What offset within the line?

::: misses
- [any] A mod L.
:::
:::
:::

::: check
kind: parts
given: k = 10 | 100 | 1000

## A loop stores to the same word {k} times, and the line is evicted afterward.

::: part
answer: k
tolerance: 0

### How many memory writes does a write-through cache make?

::: misses
- [1] Write-through sends every store on to memory.
- [any] Not yet. One per store.
:::
:::

::: part
answer: 1
tolerance: 0

### How many line write-backs does a write-back cache make?

::: misses
- [k] Write-back only writes the dirty line when it's evicted.
- [any] Not yet. Once, at eviction.
:::
:::
:::

::: check
answer: 5
tolerance: 0

## One set of a 2-way LRU cache starts empty. Lines A, B, A, C, B, A are accessed in that order, all mapping to this set. How many misses?

::: right
Right. A and B miss, A hits, C evicts B, B evicts A, A evicts C: 5 misses.
:::

::: misses
- [3] With only two ways, C pushes out the least recently used line, B, which is wanted again next.
- [4] Track which line is least recently used after each access.
- [any] Not yet. Keep the two most recently used lines.
:::
:::

::: check
kind: choice

## A program's misses fall sharply when the cache goes from direct-mapped to 2-way at the same size. What kind of misses were they?

- [ ] Compulsory
- [ ] Capacity
- [x] Conflict
- [ ] Coherence

::: misses
- [1] A first touch misses however the cache is organized.
- [2] The size didn't change, so the data fits no better.
- [4] Coherence misses come from other cores writing shared data.
:::
:::

::: check
kind: parts
given: m1 = 3 | 5 | 8; t2 = 8 | 12; m2 = 10 | 25 | 40; M = 80 | 150

## L1 hits in 1 cycle and misses {m1}%; L2 takes {t2} cycles and misses {m2}% of what reaches it; memory takes {M}.

::: part
answer: 1 + m1/100*(t2 + m2/100*M)
tolerance: 0.5%

### What's the AMAT in cycles?

::: misses
- [any] $1 + m_1(t_2 + m_2M)$.
:::
:::

::: part
answer: m1*m2/100
unit: %
tolerance: 0.5%

### What fraction of all accesses go to memory?

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

::: check
kind: parts
given: C = 16 | 32 | 64; w = 2 | 4 | 8; L = 32 | 64

## A {C} KiB, {w}-way cache has {L}-byte lines and 32-bit addresses.

::: part
answer: round(log(C*1024/(L*w))/log(2))
tolerance: 0

### How many index bits?

::: misses
- [log(C*1024/L)/log(2)] Index the sets, not the lines.
- [any] $\log_2$ of the number of sets.
:::
:::

::: part
answer: round(32 - log(C*1024/(L*w))/log(2) - log(L)/log(2))
tolerance: 0

### How many tag bits?

::: misses
- [any] 32 less the index and offset bits.
:::
:::
:::

::: explain
## Why does a write-back cache need a dirty bit on each line?

::: model
In a write-back cache, a store changes only the cached copy, so for a while the line in the cache is newer than memory. When that line is evicted, its contents must be written back or the stores are lost. But most lines are never written at all, and writing every evicted line back would waste memory bandwidth. The dirty bit, set by the first store to the line, records whether the cached copy differs from memory, so only lines that were actually changed get written back.
:::
:::

::: practice

::: check
given: C = 16 | 64; L = 32 | 64; N = 1 | 4
answer: log(C*1024/(L*N))/log(2)
tolerance: 0.5%

## How many index bits does a {C} KiB, {N}-way cache with {L}-byte lines use?

::: misses
- [any] $\log_2$ of the number of sets.
:::
:::

::: check
given: t1 = 1 | 3; m1 = 0.04 | 0.1; t2 = 12 | 20; m2 = 0.25 | 0.5; P = 100 | 150
answer: t1 + m1*(t2 + m2*P)
unit: cycles
tolerance: 0.5%

## L1: {t1} cycles, {m1} misses; L2: {t2} cycles, {m2} local misses; memory {P} cycles. What is the AMAT?

::: misses
- [any] $t_1 + m_1(t_2 + m_2P)$.
:::
:::

::: check
given: n = 512 | 2048; e = 2 | 4; L = 32 | 64
answer: n*e/L
tolerance: 0.5%

## How many misses does reading {n} elements of {e} bytes once, sequentially and line-aligned, cause with {L}-byte lines?

::: misses
- [any] Bytes over line size.
:::
:::
:::
