# CS152 Lecture 6: Memory 2 ### Section 1: Measuring and Tuning Caches — AMAT, the 3 C's, Sub-Blocks, and Multilevel Hierarchies Integrating L1 Instruction and Data caches into our 5-stage RISC pipeline exposes a crucial asymmetry: on an **I-cache miss** (`hit? == 0`), we deassert `PCen` and inject a `bubble` into `IR` while Memory Control refills; on a **D-cache miss**, we must **stall the entire CPU** until the lower memory hierarchy returns the refill block. To evaluate any cache design quantitatively, we use **Average Memory Access Time (AMAT)**: $$\text{AMAT} = \text{Hit time} + \text{Miss rate} \times \text{Miss penalty}$$ Let us break down each term: * **$\text{Hit time}$:** Cycles (or nanoseconds) to look up the cache and return data on a hit. * **$\text{Miss rate}$:** Fraction of memory accesses that miss in the cache ($0 \le \text{Miss rate} \le 1$). * **$\text{Miss penalty}$:** *Extra* cycles incurred when an access misses and must fetch from the next level down. Notice what AMAT says for our 5-stage pipeline: every extra cycle of `Hit time` hurts *100% of accesses*, whereas `Miss penalty` only hurts `Miss rate` of accesses. Therefore, the best L1 cache for a classic 5-stage pipeline is **the biggest cache that doesn't increase hit time past 1 cycle**. Deeply pipelined out-of-order cores make the same trade with a longer hit time that the scheduler hides. An AMD Zen 5 core at about 5 GHz pairs a **48 KB, 12-way L1D with a 4-cycle load-to-use latency**; behind it, L2 hits take about **14 cycles** and L3 hits about **50–55 cycles**: | Level | Hit latency (Zen 5, ~5 GHz) | | :--- | :--- | | L1D (48 KB) | 4 cycles (0.8 ns) | | L2 | ~14 cycles (2.8 ns) | | L3 | ~50–55 cycles (10–11 ns) | #### The 3 C's of Cache Misses and Parameter Effects To lower `Miss rate`, we diagnose *why* misses occur using **the 3 C's**: 1. **Compulsory misses (cold-start misses):** First reference ever made to a line—would occur even in an *infinite* cache. 2. **Capacity misses:** Cache is simply too small to hold the program's working set—would occur even in a *fully associative* cache of the same size. 3. **Conflict misses:** Collisions caused by limited set associativity—would *not* occur in a fully associative cache of the same size. Inspecting empirical miss-rate curves (SPEC92 across `4 KB` to `1024 KB` caches, 1-way to 8-way) shows how the three basic parameters trade off: * **Larger cache size:** $(+)$ reduces capacity and conflict misses; $(-)$ increases hit time. (In the empirical data, moving from 4 KB to 256 KB drops total miss rate from $\sim 9.5\%$ down toward $1\%$, shifting the remaining share from capacity/conflict toward compulsory misses.) * **Higher associativity:** $(+)$ reduces conflict misses (going from 1-way to 2-way removes most conflict misses; 4-way/8-way gets diminishing returns); $(-)$ may increase hit time (extra tag comparators and data mux). * **Larger line size:** $(+)$ reduces compulsory and capacity (reload) misses; $(-)$ increases conflict misses and miss penalty. Empirical curves of miss rate vs. block size (`16 B` to `256 B`) form a U-shape for small caches (`4 KB` and `16 KB`): miss rate initially drops from `16 B` to `64 B`, then *climbs back up* at `128 B` and `256 B` because too few lines remain! #### Sub-Block Placement (Sector Caches) Suppose tag SRAM is consuming too much chip area. Making lines bigger reduces the number of tags, *but* makes `Miss penalty` huge. **Sub-block placement (a sector cache)** decouples tag granularity from transfer granularity: * One `Tag` (e.g., `100`, `300`, `204`) covers a large line divided into multiple smaller **sub-blocks** (e.g., 4 sub-blocks), each with its **own valid bit** (`1, 1, 0, 0` or `0, 1, 0, 1`). * On a miss, hardware fetches **only the missing sub-block** rather than the whole sector. * **Watch the lookup trap:** *If a tag matches, is the requested word guaranteed to be in the cache?* **No!** You must check *both* `Tag match` **and** `sub-block Valid bit == 1`! #### Multilevel Caches and Inclusion Policies Because a single memory cannot be both huge and 1-cycle fast, modern chips build a **multilevel cache hierarchy**: `CPU <-> L1$ <-> L2$ <-> (L3$) <-> DRAM`. We track three distinct miss metrics: * **Local miss rate** $= \frac{\text{misses in cache } i}{\text{accesses to cache } i}$ * **Global miss rate** $= \frac{\text{misses in cache } i}{\text{total CPU memory accesses}}$ (e.g., $\text{Global}_{L2} = \text{Miss rate}_{L1} \times \text{Local Miss rate}_{L2}$) * **Misses per instruction** $= \frac{\text{misses in cache } i}{\text{number of instructions}}$ We generalize AMAT recursively by replacing `Miss penalty L1` with the AMAT of L2: $$\text{AMAT} = \text{Hit time}_{L1} + \text{Miss rate}_{L1} \times \left(\text{Hit time}_{L2} + \text{Miss rate}_{L2} \times \text{Miss penalty}_{L2}\right)$$ Here `Miss rate L1` and `Miss rate L2` are *local* miss rates. Notice the nesting: first compute L2's expected time upon an L1 miss (`Hit time L2 + Miss rate L2 * Miss penalty L2`), then weight that entire L1 miss penalty by `Miss rate L1` and add `Hit time L1`. **Inline Worked Example:** Suppose $\text{Hit time}_{L1} = 1\text{ cycle}$, $\text{Miss rate}_{L1} = 5\%$, $\text{Hit time}_{L2} = 10\text{ cycles}$, $\text{Miss rate}_{L2} = 20\%$, and $\text{Miss penalty}_{L2} = 100\text{ cycles}$. 1. Compute L1's miss penalty (the L2 + DRAM cost): $$\text{Miss penalty}_{L1} = 10 + (0.20 \times 100) = 10 + 20 = 30\text{ cycles}$$ 2. Compute overall AMAT: $$\text{AMAT} = 1 + (0.05 \times 30) = 1 + 1.5 = 2.5\text{ cycles}$$ Notice also what the **Global L2 miss rate** is: $0.05 \times 0.20 = 0.01$ ($1\%$ of all CPU accesses go to DRAM). Because L1 filters out $95\%$ of accesses, **L2 capacity matters far more than L2 hit latency** (as confirmed by Alpha 21264 simulations showing shrinking L2 from 8 MB to 256 KB more than doubles execution time, whereas doubling L2 latency from 8 to 16 cycles barely moves execution time by a few percent!). Finally, multilevel caches choose between two **Inclusion Policies**: * **Inclusive multilevel cache:** Every line in L1 *must* also be present in L2 (and L3). External multiprocessor coherence snoops then only need to check the outer cache (L2/L3), keeping L1 undisturbed—at the cost of wasted duplicate capacity and having to back-invalidate L1 when L2 evicts a line. * **Exclusive multilevel cache:** Inner caches hold lines *not* in the outer cache; on an L1 miss that hits in L2, the two caches **swap lines** (used in AMD Athlon's 64 KB L1 + 256 KB L2 to get $320\text{ KB}$ of distinct capacity instead of $256\text{ KB}$). *[Editor Note: removed three separate historical cache-spec slides for Itanium-2, Power 7, and IBM z196.]* #### ✎ Check Your Understanding 1. **Quick computation:** An L1 cache has $\text{Hit time}_{L1} = 1\text{ cycle}$ and $\text{Miss rate}_{L1} = 4\%$. An L2 cache has $\text{Hit time}_{L2} = 12\text{ cycles}$, local $\text{Miss rate}_{L2} = 25\%$, and $\text{Miss penalty}_{L2} = 200\text{ cycles}$. Calculate AMAT and the global L2 miss rate. **Answer:** $\text{Miss penalty}_{L1} = 12 + 0.25 \times 200 = 62\text{ cycles}$; $\text{AMAT} = 1 + 0.04 \times 62 = 3.48\text{ cycles}$. Global L2 miss rate $= 0.04 \times 0.25 = 0.01$ ($1\%$). 2. **Concept check:** Why is increasing associativity from 1-way to 2-way much more impactful than going from 4-way to 8-way, and which of the 3 C's does it reduce? **Answer:** It reduces **conflict misses**; most address collisions involve just two competing blocks mapping to the same set, so 2-way associativity eliminates the vast majority of conflicts. --- ### Section 2: Handling Cache Writes — Hit Timing, Write Buffers, and Write Policies Reading a cache is easy because reading is speculative: in a direct-mapped cache, you can read the `Data` array and compare the `Tag` in the exact same clock cycle—if `HIT == 0`, you simply ignore the data you just read! **Preempting a Critical Hardware Misconception:** You might think writes work the same way—just write into the `Data` array in parallel with checking the tag! **That corrupts memory.** If you write `Data` *before* knowing whether `Tag == Address Tag` matched (`HIT == 1`), a write miss would silently overwrite someone else's valid data sitting in that cache line! Therefore, in hardware, the `Data` array's write-enable (`WE`) **must wait for `HIT`** (requiring either a 2-cycle tag-check-then-write sequence, or pipelining the write behind the previous store's tag check). #### Write Policies: Hit and Miss Choices Cache writes require two orthogonal policy decisions: 1. **On a Cache Hit:** * **Write-through:** Write *both* the cache line and lower-level memory (simpler pipeline and cache coherence, but generates high memory write traffic). * **Write-back:** Write *only* the cache line; lower-level memory is updated only when that line is later **evicted**. Adding a **dirty bit** per line avoids writing clean evicted lines back to memory. *(Tradeoff: a write-back cache must handle **0, 1, or 2** memory accesses per load/store—0 on hit, 1 on clean miss, 2 on miss that evicts a dirty line!)* 2. **On a Cache Miss:** * **No-write-allocate:** Do not allocate a cache line; just send the write straight to main memory. * **Write-allocate (fetch-on-write):** Fetch the missing block into the cache first, then perform the write. Two combinations dominate in practice: **write-through + no-write-allocate** (common in simple L1 caches where writes stream past) and **write-back + write-allocate** (dominant in modern L1/L2/L3 caches because repeated writes to the same block hit silently in SRAM). #### Write Buffers to Reduce Read Miss Penalty Whether sending *all writes* (in a write-through cache) or *evicted dirty lines* (in a write-back cache) downward to L2/DRAM, the CPU should not stall waiting for slow writes to finish. We insert a FIFO **Write Buffer** between the Data Cache and L2: * The processor drops writes into the Write Buffer at full speed and continues executing, while **read misses are allowed to bypass pending writes** to reach L2/DRAM first. * **Watch the RAW hazard in the Write Buffer!** Suppose a write to address `X` is sitting inside the Write Buffer, and the CPU suffers a read miss to `X`! If the read bypasses the Write Buffer blindly, it reads **stale data** from L2! * *Simple solution:* On any read miss, stall and wait for the Write Buffer to drain empty. * *Faster solution:* Compare the read miss address against all addresses currently in the Write Buffer—if there is **no match**, let the read miss go ahead of pending writes; if there **is a match**, return the updated value directly from the Write Buffer! #### ✎ Check Your Understanding 1. **Hardware hazard check:** Why can a direct-mapped cache read the `Data` array in parallel with comparing `Tag`, whereas a cache write cannot assert `WE` in parallel with `Tag` comparison? **Answer:** A speculative read on a miss is harmless because the CPU discards the data when `HIT = 0`, whereas writing `Data` before `HIT = 1` would corrupt another block's valid data on a write miss. 2. **Worst-case count:** Explain how a single `LW` or `SW` instruction in a **write-back, write-allocate** cache can trigger **two** main-memory block transfers. **Answer:** If the access misses and the cache line selected for eviction has its dirty bit set, the cache must first write the dirty victim block out to memory (1) and then fetch the newly requested block from memory (2).