# CS152 Lecture 19: Multithreading ### Section 1: Thread-Level Parallelism (TLP) and Vertical Multithreading Earlier we saw that extracting instruction-level parallelism (ILP) from a single sequential thread hits a harsh scaling wall: out-of-order superscalar control logic grows roughly as $W^3$, while VLIW compilers cannot predict variable cache misses or irregular branches. When squeezing more parallelism out of *one* thread becomes too expensive, an alternative is **Thread-Level Parallelism (TLP)**—executing multiple independent instruction streams in parallel. Workloads naturally supply TLP in two ways: - **Multiprogramming:** Running completely independent sequential jobs at the same time (for example, a compiler alongside a web browser). - **Multithreaded applications:** Splitting a single job into parallel cooperating threads to finish faster. **Multithreading** uses TLP to improve the utilization of a *single* processor core by interleaving instructions from multiple hardware threads onto one shared execution pipeline. #### Hardware Interleaving on a Non-Bypassed Pipeline Consider a fundamental hardware question: *How can we guarantee there are no data dependencies between adjacent instructions in a 5-stage pipeline (`F D X M W`) without building forwarding/bypass networks or stall interlocks?* The answer is **fine-grained multithreading**: interleave instructions from $N$ different threads on consecutive clock cycles! Suppose we interleave **4 threads (`T1`–`T4`)** on a **non-bypassed 5-stage pipeline**: - Cycle `t0`: `T1: LD x1, 0(x2)` enters `F` (`t1`: `D`, `t2`: `X`, `t3`: `M`, `t4`: **`W`**) - Cycle `t1`: `T2: ADD x7, x1, x4` enters `F` - Cycle `t2`: `T3: XORI x5, x4, 12` enters `F` - Cycle `t3`: `T4: SD 0(x7), x5` enters `F` - Cycle `t4`: `T1: LD x5, 12(x1)` enters `F` $\to$ at Cycle **`t5`**, it enters `D` and reads `x1` from the register file! Look closely at the timing: `T1`'s first instruction completed Writeback (`W`) at `t4`, one cycle *before* `T1`'s second instruction reads the register file in Decode (`D`) at `t5`! Because the prior instruction in any thread *always* finishes write-back before the next instruction from that same thread reads the register file, this design: 1. **Simplifies hardware:** Zero bypassing paths and zero RAW hazard interlocks are needed! 2. **Hides long-latency operations:** Even if one thread stalls on a cache miss, the remaining threads keep the pipeline filled. To build this **Simple Multithreaded Pipeline**, hardware replicates the `PC` (say 4 `PC` registers for 4 threads) and the General-Purpose Register File (`4` copies of `GPR`). A 2-bit **`Thread select`** counter (`+1` each cycle) picks which `PC` fetches from `I$` and travels down the pipeline registers (`IR`, `X/Y`, `D$`) alongside the instruction so every stage reads and writes the correct thread's state. To the OS and software, this single physical pipeline appears as **four independent, albeit slower, CPUs**. #### The Costs of Multithreading Multithreading is not free; every active hardware thread carries hardware and system costs: - **Per-thread user state:** Dedicated `PC` and `GPR`s (and FP registers). - **Per-thread system state:** Dedicated virtual-memory page-table-base register (`satp`) and exception-handling registers. - **Shared resource overheads:** Competing threads cause additional cache and TLB conflicts (requiring larger caches/TLBs), and the OS pays scheduling overhead to manage more threads. #### Thread Scheduling Policies and Fine-Grained Machines Hardware designers have used three policies to decide *which* thread enters the pipeline each cycle: 1. **Fixed interleave** (used in the **CDC 6600 Peripheral Processors, 1964**—the first multithreaded hardware): Each of $N$ threads executes 1 instruction every $N$ cycles. On the CDC 6600, 10 "virtual" I/O processors shared one `100 ns` pipeline using an accumulator-based ISA to minimize per-thread state, giving each virtual processor one instruction every `1000 ns`. If a thread is not ready in its assigned slot, hardware simply inserts a pipeline bubble. 2. **Software-controlled interleave** (used in **TI ASC PPUs, 1971**): The OS allocates $S$ pipeline slots among $N$ threads (allowing higher-priority threads to receive more slots), and hardware cycles rigidly over the $S$ slots. 3. **Hardware-controlled thread scheduling** (used in the **Denelcor HEP, 1982**): Hardware tracks which threads are actually ready to execute and picks the next thread dynamically using a priority scheme. The **Denelcor HEP** (120 threads per processor, up to 8 processors) evolved into the **Tera/Cray MTA (1990–2015)**, a supercomputer with up to 256 processors and **128 active threads per processor** connected across a sparse 3D torus to a flat, shared main memory with **no data cache**. Why no data cache? Tera MTA targeted supercomputing workloads with giant datasets and low locality; instead of trying to cache data, each processor kept 128 threads in flight so that even a hundred-cycle trip to main memory was completely hidden, sustaining one main memory access per cycle per processor. #### Coarse-Grain Multithreading and Throughput Server Cores Most general-purpose applications *are* cache-friendly: if the cache hits 98% of the time, cycling blindly across 100 threads slows down single-thread performance needlessly. That motivates **Coarse-Grain Multithreading**: run one thread at full pipeline speed, and **swap threads only on expensive events like cache misses**: - **MIT Alewife (1990):** Modified SPARC chips using SPARC register windows to hold up to 4 thread contexts, switching on a local cache miss. - **IBM PowerPC RS64-IV (2000):** A quad-issue, in-order 5-stage pipeline supporting 2 virtual CPUs. On an L2 cache miss, hardware **flushes the pipeline** and switches to the second thread; the short 5-stage pipeline keeps the flush penalty to just 4 cycles (negligible compared to DRAM latency) while greatly simplifying exception handling. Datacenter servers running web servers and databases handle thousands of independent concurrent requests, making them ideal for throughput-oriented multithreading. The **Oracle/Sun Niagara** family (`Niagara-1` through `M6`, 2004–2013) packed many simple multithreaded cores onto one chip (e.g., 8–16 cores with 4–8 hardware threads per core, later evolving in the `SPARC S3` core to dual-issue out-of-order with 1–8 dynamically threaded strands and shared L2/L3 crossbars), trading lower single-thread performance for much higher throughput per watt. *[Editor Note: removed title slide, previous-lecture recap slide, and detailed prototype wattage/commercial discontinuance trivia.]* #### ✎ Check Your Understanding 1. Suppose we build a non-bypassed 6-stage pipeline (`F D R X M W`, where register read happens in `R` and register writeback happens in `W`). What is the minimum number of hardware threads needed under fixed round-robin interleaving so two consecutive instructions from the same thread never have a RAW hazard? **Answer:** An instruction writes its result in stage 6 (`W`), and the next instruction from that thread reads registers in stage 3 (`R`), which is $6 - 3 = 3$ stages earlier. To ensure `W` finishes before the next instruction reaches `R`, at least **4 threads** must be interleaved (`t0` writes at `t5`, and its next instruction enters `F` at `t4` and `R` at `t6`). 2. How does Coarse-Grain Multithreading differ from Fine-Grain (cycle-by-cycle) Multithreading, and why is a short pipeline helpful for coarse-grain thread switching? **Answer:** Fine-grain multithreading switches threads every clock cycle, whereas coarse-grain multithreading executes a single thread continuously until a long-latency stall (like an L2 cache miss) triggers a switch. A short pipeline minimizes the number of cycles lost if the pipeline is flushed during the switch. --- ### Section 2: Simultaneous Multithreading (SMT) for Out-of-Order Superscalars Every multithreading technique we just examined—fixed interleaving, hardware-scheduled fine-grain, and coarse-grain—is **vertical multithreading**: on any single clock cycle, **only one thread** occupies a given pipeline stage. Now look at what happens inside a wide **8-way out-of-order (OoO) superscalar** processor running typical single-threaded programs (as measured by Tullsen, Eggers, and Levy, 1995): **most execution units lie idle most of the time!** Across benchmark suites, the processor is actively busy only ~15–30% of the time; the remaining 70–85% of issue slots are lost to D-cache misses, load delays, branch mispredictions, control hazards, and long floating-point latencies. To visualize why, imagine an execution grid where columns represent **Issue Width** (say, 4 slots wide) and rows represent **Time** (cycles): - **Vertical waste:** Completely idle cycles where zero instructions issue across all 4 slots (e.g., waiting on a cache miss). - **Horizontal waste:** Partially filled cycles where IPC $< 4$ (e.g., only 1 or 2 instructions from the thread have their RAW hazards satisfied in that cycle). Look at how different architectures attack these two kinds of waste: - **Vertical Multithreading:** Interleaving threads cycle-by-cycle eliminates *vertical waste* (idle cycles), **but leaves *horizontal waste*** because any single thread still rarely fills all 4 issue slots on a given cycle. - **Chip Multiprocessing (CMP):** Splitting a 4-wide core into two 2-wide cores reduces *horizontal waste*, **but leaves some *vertical waste*** on each core and **caps the peak throughput of any single thread at 2 instructions/cycle**. #### Out-of-Order Simultaneous Multithreading (SMT) **Simultaneous Multithreading (SMT)** (Tullsen et al., 1995/1996) eliminates *both* vertical and horizontal waste: **allow instructions from multiple threads to enter execution on the exact same clock cycle!** Why is SMT so natural to build on top of an out-of-order superscalar? Recall from our study of OoO pipelines that the **OoO instruction window (issue queue) and physical register file already have almost all the circuitry required to rename, track dependencies, and issue independent instructions**! Once instructions are renamed into unique physical registers, the execution backend does not care whether two ready instructions came from Thread 1 or Thread 2. All we need to add to convert an OoO superscalar into an SMT processor are: - Multiple per-thread architectural contexts (`PC`, branch history/RAS, committed rename map, instruction fetch buffers, and commit pointers). - Fetch and decode support for multiple threads. Crucially, SMT **adapts dynamically to the type of parallelism available**: - When **TLP is high**, all threads share the entire machine width simultaneously, packing every horizontal and vertical slot. - When **TLP is low** (only one active thread), **that single thread can utilize the entire wide machine** for ILP—avoiding the rigid throughput cap of CMP! #### Commercial SMT: Pentium 4 Hyperthreading and IBM Power 4 $\to$ Power 5 - **Intel Pentium 4 Hyperthreading (2002):** The first commercial 2-way SMT design. Two logical processors shared nearly all physical resources (caches, execution units, branch predictors) at a cost of only **~5% die area overhead**. When one logical thread stalled, the other made progress (though neither thread could monopolize all queue entries while both were active), and a single active thread ran at roughly the same speed with or without Hyperthreading. *(Note: Intel used "Hyperthreading" as marketing for both SMT on OoO cores and 2-way vertical multithreading on the original in-order Atom.)* - **IBM Power 4 $\to$ Power 5:** The single-threaded Power 4 had 8 execution units fed by a single fetch/decode/commit path. Power 5 converted this design to **2-way SMT** simply by duplicating the front and back ends—**2 fetch PCs, 2 instruction buffers / initial decodes, and 2 commit units (architected register sets)**—while sharing the rename mappers, issue queues, register files, and all 8 execution units (`LSU0/1`, `FXU0/1`, `FPU0/1`, `BXU`, `CRL`). **Why did Power 5 stop at 2 threads instead of 4?** Because with 4 active threads, shared structures (physical registers, cache capacity, memory bandwidth) would thrash and bottleneck! #### SMT Performance, Thread Interactions, and the `Icount` Fetch Policy In practice, pairing two threads on 2-way SMT yields solid throughput gains: Power 5 achieved `1.23×` on `SPECint_rate` and `1.16×` on `SPECfp_rate`, while pairing all $26^2$ combinations of SPEC benchmarks on Pentium 4 yielded speedups from `0.90×` (slight slowdown!) up to `1.58×`, averaging **`1.20×`**. Why do some pairs speed up by 58% while others slow down by 10%? Because threads **compete for shared caches and queues**: - A memory-bound benchmark (like `181.mcf`) gets $>30\%$ speedup alongside almost any compute-bound partner—*so long as the partner isn't hammering the L2 cache too!* - Cache-thrashing partners "don't play nice," and sensitive floating-point codes (like `172.mgrid`) suffer when paired with another L2-heavy program. How should the frontend decide which thread to fetch from each cycle so one stalled thread doesn't starve the others? The standard solution is the **`Icount` Choosing Policy**: **fetch from the thread with the *fewest* instructions currently in flight** (inside the decode and issue queues). Why does `Icount` boost throughput? When a thread stalls on a cache miss, its instructions back up in the shared issue queues without draining. If the frontend kept fetching that stalled thread, it would fill every shared ROB and issue-queue slot with blocked instructions, starving healthy threads! By feeding the thread with the *lowest* in-flight count, `Icount` automatically prioritizes threads that are draining cleanly through the execution units. #### SMT and Hardware Security Sharing fine-grained per-core hardware resources between co-resident threads introduces a serious modern vulnerability: **side-channel attacks**. While multi-core processors already share outer L3 caches and DRAM row buffers, **SMT gives an attacker thread high-bandwidth access to previously private core structures**, enabling attacks on: - **TLBs** (e.g., *TLBleed*), - **L1 caches** (e.g., *CacheBleed*), and - **Functional unit execution ports** (e.g., *PortSmash*). Because timing contention on these shared resources leaks secret control flow or cryptographic keys across threads, security-hardened systems (such as OpenBSD 6.4) chose to disable SMT/Hyperthreading by default. #### Comparing All Five Execution Categories Consider a 4-slot-wide processor over 12 cycles executing up to 5 threads (`Thread 1..5`): 1. **Superscalar (no MT):** Only `Thread 1` runs; many cycles are completely empty (vertical waste) and busy cycles only fill 1–3 slots (horizontal waste). 2. **Fine-Grained MT:** Every cycle switches threads (`T1`, `T2`, `T3`, `T4`, `T5`, ...); vertical waste disappears, but horizontal waste remains on every cycle. 3. **Coarse-Grained MT:** `Thread 1` runs across consecutive cycles until it stalls, then switches to a burst of `Thread 2`, then `Thread 3`, etc.; reduces switch overhead, still suffers horizontal waste and short stall bubbles. 4. **Multiprocessing (CMP):** Splits the 4-wide machine into two 2-wide cores (`T1` on left, `T2` on right); reduces horizontal waste, caps single-thread IPC at 2, still leaves idle vertical gaps on each core. 5. **Simultaneous Multithreading (SMT):** Mixes `T1..T5` freely across the 4 slots *within the same cycle*, filling both vertical and horizontal gaps for maximum utilization. *[Editor Note: removed course-specific lab benchmark reference and acknowledgements slide.]* #### ✎ Check Your Understanding 1. What is the difference between *vertical waste* and *horizontal waste* in a 4-way superscalar processor, and which of the two does vertical multithreading fail to eliminate? **Answer:** **Vertical waste** is a cycle in which zero instructions issue; **horizontal waste** is a cycle in which some, but fewer than 4, issue slots are filled. Vertical multithreading eliminates vertical waste by switching threads every cycle, **but fails to eliminate horizontal waste** because only one thread can issue per cycle. 2. Why does the `Icount` SMT fetch policy prioritize the thread with the *fewest* instructions currently in flight? **Answer:** A stalled thread accumulates instructions in the shared decode/issue queues without retiring them; fetching from the thread with the fewest instructions in flight prevents a stalled thread from clogging the shared queues and starving fast-moving threads.