# CS152 Lecture 5: Memory 1 ### Section 1: Physical Memory Technologies — From Core to SRAM and 1-T DRAM In our pipelined RISC-V processor, both `Instruction Fetch` and `Memory` stages assumed that `Instruction Cache` and `Data Cache` return words effortlessly in a single short clock cycle. In reality, building memory that is simultaneously **large, fast, and cheap** is one of the hardest physical problems in computer engineering. Every memory technology forces a tradeoff among density, speed, volatility, and cost. In the 1950s and 1960s, after early experimental storage like Williams CRT tubes and mercury delay lines proved fragile or non-random-access, **Magnetic Core Memory** (invented by Jay Forrester at MIT for the Whirlwind project) became the first large-scale reliable main memory. Each bit was stored as the magnetic polarity of a tiny ferrite ring threaded onto a 2D grid of `X` and `Y` copper wires. Coincident half-current pulses on an `X` and `Y` wire flipped the core at their intersection, while a sense wire detected the induced voltage pulse—meaning **reads were destructive** (reading a bit erased it, so the hardware had to immediately write it back). Core memory was non-volatile and rugged, but threading cores onto wires limited access times to roughly **$1\text{ }\mu\text{s}$** ($1,000\text{ ns}$). In the early 1970s, **semiconductor memory** built on silicon wafers rapidly replaced magnetic cores in two distinct forms: * **Static RAM (SRAM):** Each bit cell acts like a digital latch made of **cross-coupled inverters** plus two access transistors (`4 to 6 transistors per cell`), connected to a **`Word line`** and differential **`Bit line`** / **`~Bit line`**. Think of an SRAM cell as a **faucet** connected to power rails: as long as power is on, the cross-coupled inverters actively hold the voltage at `0` or `1`. Because the inverters actively drive the bit lines, **reads are non-destructive**, **no refresh is required**, and SRAM uses **separate row/column address pins**—it is **optimized for speed, then density**. * **Dynamic RAM (DRAM):** Invented by Robert Dennard at IBM (and first commercialized in the 1-Kbit Intel 1103), a **1-T DRAM cell** collapses storage down to **1 access transistor and 1 storage capacitor** connected between a **`Word line`**, a **`Bit line`**, and a reference plate $V_{REF}$. Think of a DRAM cell as a **leaky bucket**: charge leaks off the tiny capacitor over milliseconds, so **DRAM must be refreshed every few milliseconds**. Moreover, turning on the access transistor shares the tiny cell capacitor's charge with the huge capacitance of the bit line, making **reads destructive** (every read must immediately rewrite the cell). To save chip pins and maximize chip density, DRAM uses **time-multiplexed address pins** and vertical 3D trench or stacked cylindrical capacitors—it is **optimized for density, then speed**. Because a 1-T DRAM cell uses 1 transistor and a vertical capacitor whereas a 6-T SRAM cell uses 6 planar transistors, **DRAM is roughly $10\times$ denser than SRAM** in the same process generation (for instance, in a $0.5\text{ }\mu\text{m}$ process, a standard DRAM cell measures $3.2\text{ }\mu\text{m}^2$ versus $43\text{ }\mu\text{m}^2$ for a standard 6-T SRAM cell). #### DRAM Array Architecture Whether inside an SRAM or DRAM chip, bits are organized hierarchically from system board down to silicon cell: $$\text{DIMM} \longrightarrow \text{Rank} \longrightarrow \text{Chip} \longrightarrow \text{Bank} \longrightarrow \text{Array} \longrightarrow \text{Cell}$$ The **Bank** is the "atomic unit" that gets independently activated on a memory access (modern DRAM chips contain roughly 4–8 logical banks, each physically subdivided into smaller arrays to keep wire capacitances manageable). Inside a single 2D memory array storing $2^{N+M}$ bits: * An $(N+M)$-bit address splits into **$N$ row bits** and **$M$ column bits**. * The **`Row Address Decoder`** drives one of $2^N$ horizontal **`word lines`**, turning on all $2^M$ cells across that row simultaneously. * All $2^M$ vertical **`bit lines`** feed the **`Column Decoder & Sense Amplifiers`**, which amplify the tiny voltage swings, latch the entire row, and select $D$ **`Data`** bits to send off-chip. Because DRAM relies on tiny stored charges and destructive reads, we cannot simply store all memory in fast SRAM—nor can we run a modern CPU directly out of dense DRAM without hitting a massive performance wall. *[Editor Note: removed duplicate slides of 18th–19th-century punched cards/Babbage wheels/Williams tubes covered in earlier lectures, Core Memory space-shuttle/production trivia, Gate-Array SRAM table rows, and the Chip War book slide.]* #### ✎ Check Your Understanding 1. **Comparison check:** Give two physical reasons why a 1-T DRAM cell is slower and requires more control overhead than a 6-T SRAM cell, even though both are built from silicon CMOS. **Answer:** DRAM reads are destructive (charge sharing drains the storage capacitor, requiring sense amplifiers to restore it), and capacitor charge leaks over time, forcing periodic refresh cycles every few milliseconds (plus DRAM multiplexes row and column address pins). 2. **Array calculation:** A single DRAM array has $N = 10$ row address bits and $M = 10$ column address bits, outputting $D = 1$ bit at a time. How many memory cells sit on a single horizontal word line, and how many total bits does the array store? **Answer:** Each word line enables $2^{10} = 1,024$ cells (columns), and the array stores $2^{10+10} = 2^{20} = 1\text{ Mebibit}$ ($1,048,576$ bits). --- ### Section 2: The CPU–Memory Bottleneck, DRAM Operation, and Packaging for Bandwidth High-speed processors are almost always bottlenecked by memory **latency**, **bandwidth**, and **occupancy**: * **Latency** (time for a single access): Memory access time is orders of magnitude longer than a processor cycle time. From 1980 to 2000, microprocessor performance grew roughly **$60\%/\text{year}$** while DRAM latency improved only **$7\%/\text{year}$**, opening a **Processor–DRAM performance gap growing at $50\%/\text{year}$**. A modern 4-issue $3\text{ GHz}$ superscalar core accessing $100\text{ ns}$ DRAM could execute **$1,200$ instructions** during the time required for *one* DRAM access! * **Bandwidth** (accesses per unit time): Even on a single-issue RISC-V pipeline targeting $\text{CPI} = 1$, *every* instruction needs an instruction fetch (`1`), and if fraction $m$ of instructions are loads/stores, the CPU generates **$1 + m$ memory references per instruction** (so $\text{CPI} = 1$ demands **$1 + m$ memory references per clock cycle**!). * **Occupancy** (time a memory bank stays busy servicing one request). Why can't we just make one giant memory that is also fast? Physics dictates that **physical size hurts latency**: in a big memory compared to a small memory, electrical signals must travel across longer RC wires and fan out to far more bit/word-line locations. #### How DRAM Accesses Work (RAS, CAS, Precharge) and DDR Accessing a single DRAM bank proceeds in three sequential steps, each taking roughly **$15\text{–}20\text{ ns}$** in modern DRAMs: 1. **Row access (`RAS` / `ACT`):** Decode the row address and activate one word line (often several kilobits wide). Cell capacitors share charge with bit lines; sense amplifiers detect the tiny voltage shift, latch the entire row of bits, and drive the bit lines full-rail to recharge (restore) the storage cells. 2. **Column access (`CAS` / `READ` or `WRITE`):** Decode the column address to select $4, 8, 16,$ or $32$ bits from the sense-amplifier latches and drive them to the chip pins (or overwrite the latches on a write). Crucially, once a row is open in the sense amplifiers, the controller can issue **multiple column accesses on that same row without another row access**—called **burst mode**. 3. **Precharge (`PRE`):** Equalize and recharge the bit lines back to the mid-rail reference voltage before the next row can be activated. Notice how **Double-Data Rate (DDR) DRAM** doubles pin data rate without speeding up internal array physics: while commands clock on one edge, `DQ` data pins transfer on **both the rising and falling edges** of the clock (e.g., a $200\text{ MHz}$ clock yields a **$400\text{ Mb/s}$** per-pin data rate). #### Packaging Memory for Higher Bandwidth Since single DRAM chips only have narrow data buses ($4, 8, 16,$ or $32$ bits), architects scale memory bandwidth through packaging: * **DIMM (Dual Inline Memory Module):** Connects multiple DRAM chips in parallel to shared clock, control, and multiplexed row/column address lines (~7 control + ~12 address pins), while combining their data pins into a wide bus (e.g., $16 \times 4\text{-bit}$ chips form a **64-bit data bus**). * **On-Package DRAM (Apple M1, 2020):** Places two DRAM chips directly on the same package substrate next to the system SoC, shortening wires to achieve a **128-bit bus** at $4.2\text{ Gb/s/pin}$: $$\text{Bandwidth} = \frac{128\text{ bits} \times 4.2\text{ Gb/s}}{8\text{ bits/byte}} = 67.2\text{ GB/s} \approx 68\text{ GB/s}$$ * **High-Bandwidth Memory (2.5D HBM2, NEC SX-Aurora):** Stacks DRAM dies vertically and mounts up to 6 HBM2 stacks alongside the processor on a **silicon interposer** with ultra-dense micro-wires. With $6$ channels $\times 1,024$ bits/channel at $1.6\text{ Gb/s/pin}$: $$\text{Bandwidth} = \frac{6 \times 1,024 \times 1.6\text{ Gb/s}}{8\text{ bits/byte}} = 1.2288\text{ TB/s} \approx 1.2\text{ TB/s}$$ For scale, the HBM interface on an NVIDIA Blackwell B300 GPU is **7,680 bits** wide, against $6 \times 1{,}024 = 6{,}144$ bits for the SX-Aurora's six HBM2 stacks. Yet even $1.2\text{ TB/s}$ of bandwidth does not shrink the $\sim 50\text{–}100\text{ ns}$ raw latency of opening a DRAM row. To bridge that latency gap, we must exploit how real programs actually access memory. *[Editor Note: removed NEC SX-Aurora marketing package dimensions/stiffener details while keeping the HBM2 2.5D interposer bandwidth math.]* #### ✎ Check Your Understanding 1. **Quick computation:** In a RISC-V program where $30\%$ of all instructions are loads or stores ($m = 0.30$), how many memory references per cycle must the memory system sustain to achieve $\text{CPI} = 1$? **Answer:** $1 + m = 1 + 0.30 = 1.3$ memory references per cycle ($1$ instruction fetch plus $0.3$ data accesses on average). 2. **Mechanism check:** Why can a DRAM controller serve a burst of sequential column reads faster than random reads scattered across different rows? **Answer:** Once a row access (`RAS`) latches an entire multi-kilobit row into the sense amplifiers, subsequent column accesses (`CAS`) to that same open row skip both `Precharge` and `RAS`. --- ### Section 3: Memory Reference Patterns, Locality, and Cache Organization If programs accessed memory uniformly at random, hiding a 100-ns DRAM latency would be hopeless. Fortunately, plotting real program execution traces (Memory Address on the vertical axis vs. Time on the horizontal axis, one dot per access—such as Hatfield and Gerald's classic 1971 study) reveals striking structure: * **Instruction fetches** march upward across loop bodies and repeat in tight sawtooth bands over $n$ iterations. * **Stack accesses** climb on subroutine calls, hover horizontally at a fixed frame region for arguments, and step back down on returns. * **Data accesses** sweep diagonally across vectors (`vector access`) or hammer fixed addresses (`scalar accesses`). These patterns express two fundamental, predictable properties of programs: * **Temporal Locality:** If a memory location is referenced, it is likely to be referenced *again* in the near future (visible as flat horizontal bands over time on the reference plot—like loop code and scalar variables). * **Spatial Locality:** If a memory location is referenced, locations *near* it in address space are likely to be referenced in the near future (visible as tight vertical clusters or diagonal sweeps—like sequential instructions and array elements). #### The Memory Hierarchy and Caches To exploit both locality properties, we arrange memory as a **small/fast $\rightarrow$ big/slow pyramid**: $$\text{CPU} \Longleftrightarrow \text{Small, Fast Memory (Register File, SRAM)} \Longleftrightarrow \text{Big, Slow Memory (DRAM)}$$ Across this hierarchy: * **Capacity:** $\text{Register} \ll \text{SRAM} \ll \text{DRAM}$ * **Latency:** $\text{Register} \ll \text{SRAM} \ll \text{DRAM}$ * **Bandwidth:** $\text{on-chip} \gg \text{off-chip}$ On every memory access: if $\text{data} \in \text{fast memory}$, the CPU gets a **low-latency SRAM access**; if $\text{data} \notin \text{fast memory}$, it suffers a **high-latency DRAM access** (and brings the data into the fast memory). A **Cache** is a hardware-managed SRAM structure sitting between the CPU and main memory that is **completely invisible to software** (unlike registers, the programmer does not name cache locations in the ISA): * It exploits **temporal locality** by keeping recently accessed lines in fast SRAM. * It exploits **spatial locality** by fetching contiguous multi-byte **blocks (lines)** around each accessed location. #### Anatomy of a Cache and Basic Read Flow Inside a cache, each **Line** stores two things: an **`Address Tag`** (identifying which main-memory address currently occupies this slot, e.g., `100`, `304`, `6848`, `416`) and a **`Data Block`** holding multiple contiguous data bytes (e.g., copies of main memory locations `100`, `101`, ...). On a processor read: 1. Look at the processor address and search the relevant cache tag(s) for a match. 2. **HIT (found in cache):** Return the requested copy of data directly from fast SRAM. 3. **MISS (not in cache):** Read the full block of data from lower-level memory (Wait...), return the requested data to the CPU, and install the block into the cache—which raises an immediate design question: *where in the cache can an incoming block be placed, and which existing line should it replace?* #### ✎ Check Your Understanding 1. **Locality classification:** Accessing elements `A[0], A[1], A[2], A[3]` sequentially in a loop primarily exhibits which type of locality, and why? **Answer:** Spatial locality, because accessing `A[i]` is immediately followed by accessing nearby memory addresses `A[i+1]`. 2. **Concept check:** Why are caches considered microarchitectural rather than architectural? **Answer:** Because caches are invisible to software—the programmer cannot address them directly in the ISA, and changing cache size or layout does not alter program correctness. --- ### Section 4: Cache Lookup, Placement Policies, and the Hash-Table Analogy When Main Memory holds many blocks (say, blocks `0` through `31`) and our Cache holds only `8` blocks, **Placement Policy** determines where a given memory block—say **Block `12`**—is allowed to live: 1. **Fully Associative:** Block `12` can be placed **anywhere** among all `8` cache blocks (`1` set of `8` ways). 2. **Set Associative (e.g., 2-way):** The `8` blocks are grouped into `4` sets (`Set 0..3`) of `2` blocks each. Block `12` maps to Set $12 \bmod 4 = 0$, and can sit in **either slot inside Set 0**. 3. **Direct Mapped:** Block `12` maps to **only Block `4`** ($12 \bmod 8 = 4$). #### Cache = Hardware-Optimized Hash Table A helpful mental model is to view a cache as a **hardware-optimized hash table**: * **`Bin` $\equiv$ Set**, and **`Slots` $\equiv$ Ways** (`1` Bin $\rightarrow$ fully associative; `1` Slot/Bin $\rightarrow$ direct-mapped; `M` Slots / `N` Bins $\rightarrow$ $M$-way set-associative). * A 32-bit address splits from MSB to LSB into **`Tag (T) | Index (I) | Offset (O)`**, where `(Tag, Index)` is the block's **`Key`**. * Instead of an expensive cryptographic hash, hardware uses a zero-logic **hash function**: simply take the **`Index` bits** of the address to pick one `Bin` (Set)! * Unlike software hash tables with linked lists, a cache has a **fixed number of `Slots` per `Bin`**, reads all slots in the selected bin **in parallel**, and stores `Key` (`Tag`) and `Value` (`Data`) in separate SRAM arrays. #### Hardware Walkthrough: Direct-Mapped, 2-Way, and Fully Associative 1. **Direct-Mapped Cache:** * Address bits split into `Tag (t bits) | Index (k bits) | Block Offset (b bits)`. * The `k`-bit `Index` selects `1` out of $2^k$ cache lines. * That line outputs its Valid bit `V`, its stored `t`-bit `Tag`, and its `Data Block`. * An `=` comparator checks `Stored Tag == Address Tag`, ANDed with `V == 1`, producing **`HIT`**. Meanwhile, the `b`-bit `Block Offset` drives a multiplexer across the words/bytes in `Data Block` to select the exact **`Data Word or Byte`**. * **Preempting a Critical Addressing Misconception:** You might think we could put `Index` in the *highest-order* bits (`[31 : 32-k]`) and `Tag` in the middle! **That breaks spatial locality horribly.** If `Index` used the top bits, every contiguous address in a typical program (which shares the same upper address bits!) would hash into the exact same cache line and constantly evict each other, leaving the rest of the cache empty. Placing `Index` in the **lower-order block-address bits** just above `Block Offset` guarantees consecutive memory blocks spread cleanly across different cache lines! **Inline Worked Example — Address Bit Slicing:** Suppose we have a **16 KB Direct-Mapped Cache** with **64-byte blocks** on a **32-bit byte-addressed CPU**: * Block size $= 64\text{ bytes} = 2^6 \implies \mathbf{b = 6}$ bits (`[5:0]` = `Block Offset`). * Number of lines $= \frac{16\text{ KB}}{64\text{ B}} = \frac{16,384}{64} = 256 = 2^8 \implies \mathbf{k = 8}$ bits (`[13:6]` = `Index`). * Remaining upper bits $= 32 - 8 - 6 = \mathbf{t = 18}$ bits (`[31:14]` = `Tag`). 2. **2-Way Set-Associative Cache:** * Now `256` total blocks with 2 ways means $256 / 2 = 128 = 2^7$ sets ($\mathbf{k = 7}$ `Index` bits, $\mathbf{t = 19}$ `Tag` bits, $\mathbf{b = 6}$ `Offset` bits). * The `k`-bit `Index` reads *both* ways in parallel. Two separate `=` comparators + `V` AND gates check both stored tags against `Address Tag`. Each way drives a tri-state buffer onto a shared data mux bus, and an **OR gate** combines the two way-hit signals into **`HIT`**. 3. **Fully Associative Cache:** * There is **zero `Index`** ($k = 0$); the entire upper `32 - b` bits form the `Tag`. Every line in the cache has its own `=` comparator checking `Address Tag` in parallel, feeding a wide OR gate for `HIT`. (Fast for small tables, too power-hungry and area-expensive for large caches!) #### Replacement Policy (and Pseudo-LRU) In an associative cache, when a set is full and a miss arrives, which way gets evicted? * **Random:** Simple, zero tracking state. * **Least-Recently Used (LRU):** Evicts the block untouched for the longest time. Exact LRU requires updating state on *every* access and is only practical for small associativities (e.g., 2-way, which needs just 1 bit pointing to the other way). * **Pseudo-LRU Binary Tree (for 4-way or 8-way):** For a 4-way cache (`Way 3, Way 2, Way 1, Way 0`), we store **3 bits** in a 2-level binary tree (`root` chooses left pair `1` vs right pair `0`; left child chooses `Way 3 (1)` vs `Way 2 (0)`; right child chooses `Way 1 (1)` vs `Way 0 (0)`). * **Inline Example:** Suppose all 3 bits start at `0, 0, 0` (pointing `right -> Way 0`). On a **hit to `Way 2`** (which is in the `left` half, `0` branch), we walk the path from root to `Way 2` and **flip every bit along that path to point to the *other* half**: root flips to **`0`** (away from left half), left-node flips to **`1`** (away from `Way 2`, toward `Way 3`). On a later **miss**, we simply follow the tree pointers (`0` $\rightarrow$ right child `0` $\rightarrow$ evict `Way 0`)! * **FIFO / Round-Robin** (used in highly associative caches) and **NMRU (Not-Most-Recently Used)** (FIFO with an exception sparing the most-recently used block). Notice that replacement policy is a **second-order effect** because eviction choices are only exercised on *misses*. #### Block Size Tradeoffs Recall that a block (line) of size $2^b$ bytes splits the 32-bit address into `block address (32-b bits) | offset (b bits)`. Making $b$ larger has clear hardware advantages: **less tag overhead** (fewer tags per KB of data) and **exploiting fast DRAM bursts and wide buses**. However, for a fixed total cache size, larger blocks mean **fewer total lines in the cache**, which causes **more conflict misses** and can **waste memory bandwidth** if the CPU only reads 4 bytes out of a 256-byte block! #### ✎ Check Your Understanding 1. **Quick address split:** A **32 KB, 4-way set-associative cache** has **32-byte blocks** on a 32-bit byte-addressed machine. Compute the bit widths of `Block Offset (b)`, `Index (k)`, and `Tag (t)`. **Answer:** Block size $= 32\text{ B} = 2^5 \implies b = 5$ bits. Total lines $= 32\text{ KB} / 32\text{ B} = 1,024$; with 4 ways, sets $= 1,024 / 4 = 256 = 2^8 \implies k = 8$ bits. Thus $t = 32 - 8 - 5 = 19$ bits. 2. **Design check:** Why must a direct-mapped cache use *lower-order* block-address bits (immediately above `Block Offset`) for `Index` instead of the highest-order bits `[31 : 32-k]`? **Answer:** Sequential addresses share the same highest-order bits; using them as `Index` would force consecutive blocks of an array or loop to collide in the exact same cache line, destroying spatial locality.