COA/Lesson 5 of 6/8 min read
Memory Hierarchy and Cache
The memory hierarchy, locality, cache mapping (direct, fully and set associative), replacement and write policies, AMAT and cache coherence.
On this page
Memory Hierarchy
Fast memory is expensive and small; cheap memory is slow and large. The hierarchy combines them so the system looks almost as fast as the top and almost as big as the bottom.
| Level | Typical size | Typical latency | Technology |
|---|---|---|---|
| Registers | Under 1 KB | Under 1 ns (0 cycles) | Flip-flops |
| L1 cache | 32 to 64 KB per core | About 1 ns (4 cycles) | SRAM |
| L2 cache | 256 KB to 2 MB per core | About 4 ns (12 cycles) | SRAM |
| L3 cache | 8 to 64 MB shared | About 10 to 20 ns | SRAM |
| Main memory | 8 to 128 GB | About 60 to 100 ns | DRAM |
| SSD | TBs | About 100 us | Flash |
| HDD | TBs | About 5 to 10 ms | Magnetic |
Moving down: larger, cheaper per byte, slower. Each level caches the level below it.
SRAM
Static RAM stores each bit in a 6-transistor flip-flop. Fast, no refresh needed, but large and expensive. Used for caches and registers.
DRAM
Dynamic RAM stores each bit as charge in a capacitor with one transistor. Dense and cheap, but the charge leaks, so it must be refreshed every few milliseconds, and reads are slower. Used for main memory.
| SRAM | DRAM | |
|---|---|---|
| Cell | 6 transistors | 1 transistor + capacitor |
| Speed | Fast | Slower |
| Refresh | No | Yes |
| Density and cost | Low density, expensive | High density, cheap |
| Use | Cache | Main memory |
Locality of Reference
Caches work because programs do not access memory randomly.
- Temporal locality: recently used data is likely to be used again soon (loop counters, hot variables).
- Spatial locality: data near recently used data is likely to be used soon (array traversal, sequential instructions).
// Good spatial locality: row-major traversal of a C array
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
sum += a[i][j];
// Poor: column-major traversal jumps N * 4 bytes each access
for (j = 0; j < N; j++)
for (i = 0; i < N; i++)
sum += a[i][j];The second loop can be several times slower for large N purely because of cache misses.
Cache Memory
A small, fast SRAM between the CPU and main memory that holds copies of recently used blocks.
Cache Hit
The requested data is in the cache. A miss means it must be fetched from the next level.
Hit rate = hits / total accesses
Miss rate = 1 - hit rateThe three Cs of misses
| Miss type | Cause | Reduce with |
|---|---|---|
| Compulsory (cold) | First access to a block | Larger blocks, prefetching |
| Capacity | Cache too small for the working set | Bigger cache |
| Conflict | Too many blocks map to the same set | Higher associativity |
A fourth C for multiprocessors: coherence misses.
Cache Line
The unit of transfer between cache and memory, also called a block, typically 64 bytes. On a miss, the whole line is loaded, which is how spatial locality is exploited.
A memory address is split into fields:
| Tag | Index | Block offset |- Block offset: byte within the line;
log2(line size)bits. - Index: which set;
log2(number of sets)bits. - Tag: remaining high bits; identifies which memory block is stored.
Each line also stores a valid bit and, for write-back caches, a dirty bit.
Cache mapping
Direct Mapping
Each memory block maps to exactly one cache line: line = block number mod number of lines.
- Simple, fast, cheap (one tag comparison).
- Suffers conflict misses when two hot blocks map to the same line and keep evicting each other (thrashing between them).
Fully Associative
A block can go in any line. Every tag must be compared in parallel. No conflict misses, but expensive hardware; used only for small caches.
Set Associative
The cache is divided into sets of k lines (k-way). A block maps to one set and can occupy any line within it. The practical compromise: L1 caches are often 8-way, L3 12 to 16-way.
| Mapping | Placement | Comparators | Conflict misses |
|---|---|---|---|
| Direct mapped | One line | 1 | Most |
| k-way set associative | Any of k lines in one set | k | Fewer |
| Fully associative | Any line | All lines | None |
Direct mapped is 1-way set associative; fully associative is a single set.
Worked example
32 KB cache, 64-byte lines, 4-way set associative, 32-bit addresses.
Lines = 32 KB / 64 B = 512
Sets = 512 / 4 = 128
Offset = log2(64) = 6 bits
Index = log2(128) = 7 bits
Tag = 32 - 7 - 6 = 19 bitsCache Replacement Policy
On a miss in a full set, which line to evict?
| Policy | Idea | Notes |
|---|---|---|
| LRU | Evict least recently used | Good, expensive for high associativity |
| Pseudo-LRU | Tree bits approximate LRU | Common in hardware |
| FIFO | Evict oldest loaded | Simple, ignores use |
| Random | Pick randomly | Cheap, surprisingly decent |
| Optimal (Belady) | Evict the one used furthest in future | Theoretical benchmark only |
Write policies
Write-Through
Every write updates both the cache and main memory. Simple and memory is always up to date, but generates heavy memory traffic. Usually paired with a write buffer.
Write-Back
Writes update only the cache and set the dirty bit. The line is written to memory only when evicted. Less traffic, faster, but more complex and memory can be stale.
On a write miss:
- Write-allocate: load the line into the cache, then write (pairs with write-back).
- No-write-allocate: write directly to memory (pairs with write-through).
AMAT
Average Memory Access Time:
AMAT = Hit time + Miss rate * Miss penaltyExample: hit time 1 ns, miss rate 5%, miss penalty 100 ns. AMAT = 1 + 0.05 * 100 = 6 ns.
Multi-level:
AMAT = HitL1 + MissL1 * (HitL2 + MissL2 * PenaltyL2)With L1 1 ns and 5% miss, L2 10 ns and 20% local miss, memory 100 ns: 1 + 0.05 * (10 + 0.2 * 100) = 2.5 ns. Adding L2 more than halves AMAT.
Ways to improve: lower hit time (small, simple L1), lower miss rate (bigger, more associative, prefetching), lower miss penalty (multi-level caches, critical word first).
Cache Coherence
In a multicore CPU, each core has its own L1 and L2. If two cores cache the same address and one writes, the other's copy becomes stale. Coherence protocols keep copies consistent.
- Snooping: caches watch (snoop) a shared bus for writes. Works for a small number of cores.
- Directory-based: a directory tracks which caches hold each line. Scales to many cores.
MESI
The common snooping protocol. Each cache line is in one of four states:
| State | Meaning |
|---|---|
| Modified | Only this cache has it; dirty |
| Exclusive | Only this cache has it; clean |
| Shared | Several caches may have it; clean |
| Invalid | Not valid |
A write to a Shared line broadcasts an invalidate so other copies become Invalid.
False sharing: two threads write different variables that happen to sit on the same cache line. The line ping-pongs between cores and performance collapses. Fix: pad or align hot per-thread data to separate 64-byte lines.
For how the OS layers virtual addresses on top of this, see virtual memory.
Quick revision
- Hierarchy: registers, L1, L2, L3 (SRAM), DRAM, SSD, HDD; faster and smaller at the top.
- Temporal and spatial locality make caches effective; traverse arrays in memory order.
- Address = tag, index, offset; 64-byte lines are typical.
- Direct mapped: one place, conflict misses. Fully associative: anywhere, expensive. Set associative: compromise.
- Three Cs: compulsory, capacity, conflict.
- Write-through updates memory every write; write-back uses a dirty bit and writes on eviction.
AMAT = hit time + miss rate * miss penalty.- MESI keeps multicore caches coherent; watch out for false sharing.