Notes
All notes

Memory Hierarchy (COA Core #4)

A 3.5 GHz core can execute an instruction every 0.29 ns. Main memory takes 60–100 ns to answer. Without a hierarchy, every load would stall the CPU for 200–350 cycles. Caches exist to make the common case look fast, and the arithmetic of hits, misses, and capacity is the core of the subject.

The levels

Level Typical size Latency Managed by
Registers 16–32 × 8 bytes 1 cycle compiler
L1 cache 32–64 KB, split I/D 4–5 cycles hardware
L2 cache 256 KB–1 MB per core 12–20 cycles hardware
L3 cache 8–32 MB shared 30–50 cycles hardware
DRAM 8–64 GB 60–100 ns OS + hardware
SSD 100 GB–4 TB 50–150 µs OS
HDD 1–20 TB 5–10 ms OS

SSD and HDD are the secondary storage levels: persistent, block-addressed, and three to six orders of magnitude slower than DRAM.

The pattern: each level is larger and slower by roughly an order of magnitude. The goal is to keep the working set in the fastest level that fits.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  l/.style={draw, thick, minimum height=0.5cm, font=\scriptsize, align=center}]
  \node[l, fill=blue!18, minimum width=2.2cm] at (0,0) {registers\\1 cycle};
  \node[l, fill=blue!12, minimum width=3.4cm] at (0,-0.6) {L1: 4–5 cycles};
  \node[l, fill=blue!8, minimum width=4.6cm] at (0,-1.2) {L2: 12–20 cycles};
  \node[l, fill=orange!15, minimum width=5.8cm] at (0,-1.8) {L3: 30–50 cycles};
  \node[l, fill=orange!25, minimum width=7.0cm] at (0,-2.4) {DRAM: 60–100 ns};
  \node[l, fill=red!15, minimum width=8.2cm] at (0,-3.0) {SSD / HDD: µs–ms};
  \node[font=\scriptsize, anchor=west] at (4.3,-0.3) {faster, smaller, costlier per byte};
\end{tikzpicture}
QQuestionWhy not make all memory as fast as L1?
ASolution

SRAM is fast but takes about six transistors per bit and a lot of area. DRAM uses one transistor and a capacitor, so it is dense and cheap but slow. The hierarchy buys speed for the common case at DRAM density for the rest.

Locality of reference

Caches work because programs do not access memory uniformly.

int sum = 0;
for (int i = 0; i < n; ++i)
    sum += a[i];        // spatial: a[i] and a[i+1] share a cache line
                        // temporal: sum and i stay in registers

A linked list has poor spatial locality: each node is elsewhere in memory, so the next access is a new cache line (and likely a miss). This is why an array traversal can be several times faster than a list traversal at the same Big-O.

QQuestionWhich locality does a hash table lookup rely on?
ASolution

Mostly temporal for repeated keys, and spatial within a bucket or cache line. A random lookup pattern has poor spatial locality, so large hash tables are memory-latency bound.

Hits, misses, and the four Cs

A hit is serviced by the cache. A miss must fetch from the next level.

\[ \text{hit rate} = \frac{\text{hits}}{\text{accesses}}, \qquad \text{miss rate} = 1 - \text{hit rate} \]

Misses are classified by cause:

Type Cause Fix
Compulsory (cold) first access to a block prefetch, larger blocks
Capacity working set exceeds cache larger cache, blocking
Conflict too many blocks map to one set higher associativity
Coherence another core wrote the line protocol tuning, padding

A fully associative cache has no conflict misses. A direct-mapped cache has the most. Capacity misses are the ones a bigger cache actually fixes.

QQuestionA loop over a 1 MB array misses every time on a 32 KB L1. Which

category is that?

ASolution

Capacity, because the array is much larger than the cache and each pass evicts data the next pass needs. Conflict misses would also occur in a low-associativity cache, but capacity dominates at this size ratio.

Average Memory Access Time

AMAT combines hit time and miss cost:

\[ \text{AMAT} = t_{\text{hit}} + \text{miss rate} \times t_{\text{miss}} \]

For two levels, the L1 miss penalty is the L2 access:

\[ \text{AMAT} = t_{L1} + m_1\big(t_{L2} + m_2 \cdot t_{\text{mem}}\big) \]

Worked example:

\[ \text{AMAT} = 1 + 0.10\,(5 + 0.50 \times 100) = 1 + 0.10 \times 55 = 6.5 \text{ ns} \]

If L1 hit time were 2 ns instead, AMAT would be 7.5 ns — hit time matters as much as the miss rate when misses are rare.

QQuestionA cache has a 95% hit rate, 1-cycle hit, and 100-cycle miss penalty.

What is AMAT in cycles?

ASolution

\(1 + 0.05 \times 100 = 6\) cycles. The 5% of misses dominates: the average access is six times the hit time.

Cache lines

A cache line (block) is the unit transferred between levels, typically 64 bytes on x86 and ARM. A line holds 16 ints or 8 doubles.

Larger lines exploit spatial locality but cost more to transfer and reduce the number of lines for a fixed capacity, which can increase conflict misses. Smaller lines reduce wasted bandwidth on scattered accesses.

The address splits into three fields:

\[ \underbrace{\text{tag}}_{\text{rest}} \;\; \underbrace{\text{index}}_{\log_2(\text{sets})} \;\; \underbrace{\text{offset}}_{\log_2(\text{line size})} \]

The offset selects a byte within the line; the index selects the set; the tag identifies which block occupies the line.

QQuestionHow many ints fit in a 64-byte cache line?
ASolution

16, because each int is 4 bytes and \(64/4 = 16\).

Capacity, associativity, and mapping

\[ \text{capacity} = \text{sets} \times \text{ways} \times \text{line size} \]

Address decomposition on a 32-bit machine with 64-byte lines:

Cache Sets Offset bits Index bits Tag bits
32 KB direct (512 lines) 512 6 9 17
32 KB 4-way (128 sets) 128 6 7 19
32 KB fully associative 1 6 0 26

Higher associativity reduces conflict misses at the cost of more comparators and a more complex replacement policy.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum height=0.5cm, font=\scriptsize\ttfamily}]
  \node[c, fill=blue!12, minimum width=2.2cm] (t) at (0,0) {tag (17)};
  \node[c, fill=orange!18, minimum width=1.3cm] (i) at (1.75,0) {index (9)};
  \node[c, fill=green!15, minimum width=0.9cm] (o) at (2.85,0) {off (6)};
  \node[font=\scriptsize, anchor=north] at (2.85,-0.4) {byte in line};
  \node[font=\scriptsize, anchor=north] at (1.75,-0.85) {selects the set};
  \node[font=\scriptsize, anchor=north] at (0,-1.3) {compared against the stored tag};
\end{tikzpicture}
QQuestionWhy does a direct-mapped cache need only one tag comparison?
ASolution

The index determines exactly one line. In an \(N\)-way set, all \(N\) tags in the set must be compared in parallel.

Replacement policies

When a set is full and a new block arrives, one line must go:

Hand simulation, 2-way set, LRU, accesses A B C A:

Access Contents Result
A A miss
B A B miss
C B C miss, evict A
A C A miss, evict B

With A B A C A: A miss, B miss, A hit, C miss (evict B), A hit → 2 hits.

Direct-mapped, 4 lines indexed by addr mod 4, accesses 0 1 2 3 0 4 0:

Access Index Result
0 0 miss
1 1 miss
2 2 miss
3 3 miss
0 0 hit
4 0 miss, evicts 0
0 0 miss

One hit out of seven. The 0,4,0 pattern is a conflict miss: both blocks map to set 0.

QQuestionWhy can LRU be worse than random on some patterns?
ASolution

LRU assumes recency predicts the future. A cyclic scan larger than the cache makes every line “least recently used” just before it is needed again, so LRU evicts exactly what the next access wants.

Write policies

Two independent decisions:

When to write to the next level:

What to do on a write miss:

Combination Behaviour Typical use
Write-back + write-allocate cache it, dirty it, flush later L1/L2/L3 on CPUs
Write-through + no-write-allocate memory always current simple caches, some GPUs
Write-through + write-allocate cache it and write memory rare

Dirty lines complicate coherence: another core reading the line must get the modified data, not stale memory. That is the job of the coherence protocol (Ch. 6).

QQuestionWhy does write-back reduce memory bandwidth?
ASolution

Multiple writes to the same line collapse into one writeback when the line is evicted, instead of one memory write per store.

Worked cache problem

A 16 KB direct-mapped cache with 32-byte lines, 32-bit addresses:

The address 0x12345678 splits as:

Two addresses map to the same set if their index bits match; they hit only if the tags also match.

QQuestionTwo addresses differ by 16 KB in a 16 KB direct-mapped cache. Do they

conflict?

ASolution

Yes. They have the same index but different tags, so they map to the same line and evict each other on alternating accesses.

Bugs and edge cases

QQuestionA stride-4096 loop misses almost every access on a 32 KB 8-way

cache with 64-byte lines. Why?

ASolution

4096 bytes is 64 lines; with 64 sets, the stride maps every access to the same set. Eight ways fill and then evict each other — a conflict miss pattern, not a capacity problem.

Next: TLB and Virtual Memory Hardware (COA Core #5) — translating addresses at speed, and simulating an LRU TLB by hand.