CPU Caches: A Scientific Explanation
CPU caches are specialized high-speed memory subsystems that bridge the performance gap between fast processors and slower main memory (RAM). They operate on fundamental principles of temporal and spatial locality to significantly reduce memory access latency.
Fundamental Principles
Memory Hierarchy
CPU caches operate within a hierarchical memory structure:
- Registers (fastest, smallest)
- Cache memory (very fast, small)
- Main memory (moderate speed, large)
- Storage (slow, very large)
Each level trades speed for capacity, with access latencies typically increasing by an order of magnitude at each step down the hierarchy.
Locality of Reference
Caches exploit two empirical observations about memory access patterns:
- Temporal locality: Recently accessed data is likely to be accessed again soon
- Spatial locality: Data near recently accessed locations is likely to be accessed soon
Cache Organization
Hierarchical Structure
Modern CPUs employ a multi-level cache hierarchy:
-
L1 Cache (Level 1)
- Size: Typically 32-64 KB per core
- Latency: 1-4 CPU cycles
- Often split into separate instruction (L1i) and data (L1d) caches
- Directly connected to the CPU core
-
L2 Cache
- Size: 256 KB-1 MB per core
- Latency: 10-20 CPU cycles
- Usually unified (contains both instructions and data)
- May be private to each core or shared
-
L3 Cache (Last Level Cache or LLC)
- Size: 4-50 MB
- Latency: 40-75 CPU cycles
- Shared among all cores on a processor die
- Acts as the final on-chip cache before accessing main memory
Mapping Techniques
Caches organize data using three primary mapping strategies:
-
Direct-Mapped
- Each memory location maps to exactly one cache location
- Simplest design but higher conflict rate
- Mapping function:
cache_index = (memory_address) mod (number_of_cache_lines)
-
Fully Associative
- Any memory block can be placed in any cache line
- Lowest conflict rate but requires complex hardware to search the entire cache
- Uses Content Addressable Memory (CAM) for lookups
-
Set-Associative (most common)
- Compromise between direct-mapped and fully associative
- Cache divided into sets, each containing multiple ways
- Memory address maps to a specific set, but can occupy any way within that set
- n-way set associative: each set contains n cache lines
Cache Operation
Cache Line Structure
The basic unit of cache management is the cache line (or block):
- Typical size: 64 or 128 bytes
- Contains:
- Data array (the actual cached memory contents)
- Tag (portion of memory address used for identification)
- Status bits (valid, dirty, etc.)
Address Decomposition
Memory addresses are logically divided into three components:
- Tag: Identifies which memory block is stored
- Index: Determines which cache set to use
- Offset: Locates specific byte within the cache line
Cache Access Process
- CPU issues memory address
- Cache controller extracts index from address to locate appropriate set
- Tags within the set are compared with the tag from the address
- If matching tag found (cache hit):
- Data is returned to CPU
- Hit latency: 1-75 cycles depending on cache level
- If no match found (cache miss):
- Data is fetched from next level in memory hierarchy
- Miss penalty: 10-300+ cycles
Cache Management Policies
Replacement Policies
When a cache is full and a new line must be added, various algorithms determine which existing line to evict:
- Least Recently Used (LRU): Evicts the line that hasn't been accessed for the longest time
- Not Recently Used (NRU): Uses a reference bit that gets cleared periodically
- Pseudo-LRU (PLRU): Approximates LRU with less overhead
- Random: Selects a victim line randomly
- First-In-First-Out (FIFO): Evicts the oldest cached line
Write Policies
Two fundamental approaches handle writing to cached data:
-
Write-Through:
- Writes are performed to both cache and main memory
- Ensures memory consistency but increases write traffic
-
Write-Back:
- Writes only update the cache
- Modified lines (marked "dirty") are written to memory only when evicted
- Reduces memory traffic but complicates coherence
Cache Coherence
In multi-core systems, multiple caches may contain copies of the same memory location. Coherence protocols ensure consistency:
-
MESI Protocol (most common):
- Modified: Line is changed and only in this cache
- Exclusive: Line is unmodified and only in this cache
- Shared: Line is unmodified and may exist in other caches
- Invalid: Line does not contain valid data
-
Snooping: Each cache monitors the system bus for memory operations
-
Directory-Based: A centralized directory tracks cache line states
Performance Considerations
Key Metrics
- Hit Rate: Percentage of memory accesses found in cache (typically >90%)
- Miss Rate: Percentage of accesses not found in cache
- Average Memory Access Time (AMAT):
AMAT = Hit Time + (Miss Rate × Miss Penalty)
Cache Optimization Techniques
- Prefetching: Proactively loading data before it's explicitly requested
- Non-blocking caches: Allow continued operation during misses
- Victim caches: Small buffers that store recently evicted lines
- Inclusive vs. Exclusive caching: Whether higher levels must contain subsets of lower levels
- Hardware speculation: Predicting and pre-loading likely needed data
Advanced Implementations
Modern processors employ sophisticated extensions:
- Translation Lookaside Buffers (TLBs): Cache virtual-to-physical address translations
- Micro-op caches: Store decoded instructions
- Specialized caches: Branch target buffers, branch prediction caches
- Partitioned caches: Allocate cache resources dynamically between cores or applications
This sophisticated memory hierarchy represents one of the most significant architectural advancements in modern computing, enabling high-performance processing despite the widening gap between CPU and memory speeds.