Course: Computer Architectures · Lecture: Lecture 08 - Cache Memories
1. The problem: the CPU needs data quickly
Main memory holds far more data than the processor can keep close to its execution units, but accessing it takes time. A cache is a smaller, faster memory that keeps copies of selected blocks from a lower level of the memory hierarchy. When the processor needs data, the cache checks whether its copy is already available.
Imagine studying at a desk while most books are on a bookshelf. A book on the desk is quick to reach; one still on the shelf takes longer. The desk is small, so it cannot hold every book. In a real cache, data is copied, not removed from memory.
A hit means the requested block is present and valid. A miss means it is absent or invalid, so a lower memory level must provide it. Caching helps when many accesses hit; the first access to an absent block cannot be a hit.
Why would recently copied data be useful?
Programs often show locality:
- Temporal locality: data used recently may be used again soon. A loop can repeatedly read the same variable.
- Spatial locality: after accessing one address, a program may access nearby addresses. An array loop often reads consecutive elements.
The cache takes advantage of spatial locality by fetching a whole block of adjacent bytes, even when the CPU initially asks for only one part of it. Larger blocks may provide useful neighbours, but they also use more space and bandwidth if those neighbours are never accessed.
Trace: the first miss can prepare later hits
For this added teaching example, assume a block holds four array elements, A[0] starts a block, the cache is initially empty, and the block is not evicted.
| Access | Result | Why? |
|---|---|---|
A[0] | Miss | Fetch the block containing A[0]–A[3]. |
A[1], A[2], A[3] | Three hits | They arrived in the same block. |
A[0] again | Hit | The earlier block is still there. |
By contrast, A[0], A[4], A[8], A[12] accesses four different blocks, so all four first accesses miss. The block size in bytes is a design choice: four 4-byte elements occupy 16 bytes; four 8-byte elements occupy 32 bytes. A block is not inherently four elements.
2. Blocks, lines, sets and ways
Keep the data separate from the slot holding it:
| Term | Meaning | Hotel analogy |
|---|---|---|
| Memory block | A fixed-size chunk of consecutive memory bytes | A group of guests travelling together |
| Cache line | A slot that can hold one block plus identifying/control information | One room |
| Set | A group of cache lines where a particular block is allowed to go | A group of rooms |
| Way | One line position within a set | One room within that group |
This analogy is illustrative: unlike the guests, the data remains in main memory when copied into the cache.
Consider four lines arranged as two sets of two ways:
Set 0: [way 0: one line] [way 1: one line]
Set 1: [way 0: one line] [way 1: one line]Each line holds one block. The cache has four lines in total, not four per set. If three blocks all map to set 0, the first two can occupy its two lines. The third must replace one of them, even if set 1 has empty lines. The mapping rule determines where a block may go; the replacement policy chooses which allowed line to reuse when necessary.
3. Mapping: which set may hold the block?
Under the simple power-of-two mapping used in the slides:
set number = memory block number modulo number of sets
Modulo gives the remainder after division. The block number is found from the byte address and block size: floor(byte address / block size).
| Organization | Structure | Allowed placement |
|---|---|---|
| Direct mapped | One line per set | Exactly one line |
| W-way set associative | W lines per set | Any of W lines in one set |
| Fully associative | One set containing all lines | Any line |
Trace: why associativity helps
A four-line direct-mapped cache has four sets of one line. Blocks 0 and 4 both have remainder 0 modulo 4, so both must use line 0. Start empty and read 0 → 4 → 0 → 4: each access misses and replaces the previous block. These are conflict misses, despite other lines being empty.
Now organize the same four lines as two sets with two ways each. Both blocks map to set 0 because 0 mod 2 = 0 and 4 mod 2 = 0. They can occupy its two lines together: the same access sequence gives miss → miss → hit → hit. Capacity has not increased; placement became more flexible. A third block mapping to that full set can still cause replacement.
4. Reading an address: set, block identity, byte
For a byte-addressed, conventional cache with power-of-two sizes, the address can be viewed as:
| tag | set index | block offset |- Index: selects one set.
- Tag: compare the requested tag with the stored tag of each valid line in that set. A match identifies the cached block.
- Offset: selects the requested byte within that block.
The valid bit says whether the line contains a usable block. A matching tag in an invalid line is not a hit. On a miss, the lower level supplies the block; the cache stores it in an allowed line, together with its tag and valid state.
Why no separate address bits for the way?
Suppose set 7 has four ways and the requested tag is A:
way 0: tag B way 1: tag C way 2: tag A way 3: invalidThe cache checks the four tags and finds the block in way 2. Two bits can represent four ways, but the memory address does not specify which one to use. The hardware may create an internal two-bit way-selection signal after the tag comparison. If the same block later occupies way 1, its memory address stays the same.
Think of the set as a group of rooms and the tag as the guest’s name: the name tells you whom to find, not which room they occupy. The offset then selects the requested byte within the block. See Branch Prediction Fundamentals for a related use of tags in a branch-target buffer.
5. Address-sizing recipe
For a byte-addressed cache, power-of-two sizes and the usual set indexing:
- Lines = data capacity in bytes ÷ block size in bytes.
- Sets = lines ÷ ways per set.
- Offset bits = log₂(block size in bytes).
- Index bits = log₂(number of sets).
- Tag bits = address width − index bits − offset bits.
Each extra bit doubles the number of choices: 5 bits select 32 choices, 6 select 64. These calculations describe data capacity; tags, valid bits and other metadata require extra storage.
Worked example: the same cache, 2 ways then 4 ways
Given 4 KiB = 4,096 bytes of data, 32-byte blocks and 32-bit byte addresses:
| Step | Two-way | Four-way |
|---|---|---|
| Lines: 4,096 ÷ 32 | 128 | 128 |
| Sets: lines ÷ ways | 128 ÷ 2 = 64 | 128 ÷ 4 = 32 |
| Offset: choose one of 32 bytes | 5 bits | 5 bits |
| Index: choose a set | 6 bits | 5 bits |
| Tag: remaining address bits | 32 − 6 − 5 = 21 | 32 − 5 − 5 = 22 |
For four ways the cache has 32 sets, each with four lines. The address is 22-bit tag | 5-bit set index | 5-bit byte offset. Increasing associativity here keeps capacity, lines and offset unchanged; it reduces the set count and moves one bit from index to tag.
6. Replacing a block
If all allowed lines are occupied, the cache needs a victim:
| Policy | Victim | Key distinction |
|---|---|---|
| LRU: least recently used | Block whose latest access was longest ago | A hit updates recency. |
| FIFO: first in, first out | Block inserted earliest | A hit does not change arrival order. |
| LFU: least frequently used | Block accessed least often, according to its counts | Frequency is not the same as recency. |
| Random | A line chosen randomly | Simple; results vary. |
For a two-way set, start empty and access A → B → A → C. The second A is a hit. When C arrives, LRU evicts B (A was just used), while FIFO evicts A (A arrived first). For A → B → C → A → B → D in a three-way set, LRU evicts C and FIFO evicts A.
Tree pseudo-LRU: less bookkeeping, approximate order
A four-way tree stores one direction bit at each of three internal nodes. To find a victim, follow arrows from the root. After accessing a way, set the arrows along that path to point away from the accessed way. These bits do not retain the exact order of all accesses, so pseudo-LRU can differ from true LRU.
root
/ \
left right
/ \ / \
W0 W1 W2 W3If all arrows start left, access W0, then W2. W0 makes the left node point toward W1; W2 makes the root point left. The replacement path is left, then right → W1. Accessing W2 did not change the arrow inside the left half.
7. Writes, dirty data and coherence
When the processor changes a cached value, the lower level must eventually receive the change.
| Policy | On a write | On eviction |
|---|---|---|
| Write-through | Update the cache and send the write to the lower level. | No deferred write-back for that update. |
| Write-back | Update the cache and mark the line dirty. | Write back a dirty victim before discarding it. |
With write-back, loading or reading a block does not make it dirty. If X was loaded as 5 and changed to 9, the cache can hold 9 while lower memory still holds 5. A dirty bit records that the change must be propagated before the block is discarded. A clean victim can be discarded without a write-back. A valid bit answers a different question: is this line usable at all?
Why write-through alone does not ensure coherence
Two cores may each cache X = 5. Core 1 writes X = 9 and sends the update to shared memory. Core 2 could still hit on its own valid cached X = 5 without checking memory. A coherence protocol coordinates copies, for example by invalidating Core 2’s copy. Its next access then misses and obtains the current value, possibly from another cache. A valid bit is useful to mark the copy invalid but is not a complete coherence protocol.
8. Several cache levels and access time
A common hierarchy is CPU → L1 → L2 → L3 → main memory. L1 is generally smaller and faster; later levels tend to be larger and slower. An L1 miss can still hit in L2, avoiding a main-memory access. Exact organization varies. Some designs split L1 into instruction and data caches, permitting simultaneous access; lower memory can still be unified. Instructions can be modified in some systems, with appropriate synchronization.
For a simple one-level model, let h be the hit fraction, C the time for a hit and M the total time for a miss:
average access time = h × C + (1 − h) × M.
Example: h = 0.9, C = 1 ns, M = 51 ns gives 0.9 × 1 + 0.1 × 51 = 6 ns. If instead a problem defines a 50 ns additional miss penalty, use C + (1 − h) × penalty = 1 + 0.1 × 50 = 6 ns. Always check which meaning the given time has.
9. Review without notes
- A cache has 64 lines and four ways. How many sets are there? Can two blocks in different sets evict one another directly?
- A block moves from way 0 to way 3 in the same set. Which address fields change? Why?
- Trace
A, B, C, A, B, Din one three-way set using both LRU and FIFO. - Explain why a clean write-back line needs no write on eviction, but a dirty one does.
- Why can a second core read a stale cached value even after a write-through update reaches shared memory?
Answers: 1. 16 sets; no, replacement chooses a line in the incoming block’s set. 2. None; the cache discovers the way by tag comparison. 3. LRU removes C, FIFO removes A. 4. Only the dirty copy has changes that must be propagated. 5. The second core can hit in its own cache; coherence must coordinate its copy.