Sub topic 2
Splitting an address into tag, index and offset
A cache stores copies of blocks from main memory. When the CPU requests a byte, the cache must find out whether that byte's block is already stored. It does this by splitting the memory address into three fields: the offset, the index and the tag.
Prerequisites
This chapter assumes you can convert between binary and hexadecimal, that you know powers of two give exact bit counts, and that a block is a fixed-size group of consecutive bytes.
The three fields
- Offset: selects the byte inside a block. For a block of B bytes, the offset has log2(B) bits.
- Index: selects the set (or line) where the block may be stored. For S sets, the index has log2(S) bits.
- Tag: the remaining high bits. The cache stores the tag with each block, and a lookup compares the stored tag with the tag of the requested address.
Tag bits = address bits − index bits − offset bits.
def split_address(addr, block_size, num_sets):
offset_bits = block_size.bit_length() - 1
index_bits = num_sets.bit_length() - 1
offset = addr & (block_size - 1)
index = (addr >> offset_bits) & (num_sets - 1)
tag = addr >> (offset_bits + index_bits)
return tag, index, offset
print(split_address(0x1234, 16, 16)) # (18, 3, 4)Direct-mapped cache
A direct-mapped cache has one line per set. The index selects exactly one line, so a block can live in only that line. Two addresses with the same index and different tags compete for the same line, which causes a conflict miss.
Take a 32-bit address, 16-byte blocks and 16 lines:
| Field | Bits | Source |
|---|---|---|
| Offset | 4 | log2(16) |
| Index | 4 | log2(16 sets) |
| Tag | 24 | 32 − 4 − 4 |
Fully associative cache
A fully associative cache has one set that contains all lines. The index has zero bits, so the address holds only a tag and an offset. A block can go in any line, and the hardware compares the tag with every line.
With the same 32-bit address and 16-byte blocks, the offset is 4 bits, the index is 0 bits and the tag is 28 bits.
k-way set-associative cache
A k-way set-associative cache has S = lines / k sets, and each set holds k lines. The index selects a set, and the block can go into any of its k lines. Direct-mapped is the case k = 1, and fully associative is the case k = number of lines.
For 16 lines arranged 4-way, there are 4 sets, so the index is 2 bits, the offset is 4 bits and the tag is 26 bits.
Exercise
Exercise
A 32-bit address is used with a 256-line cache that is 2-way set-associative and has 64-byte blocks. How many bits are in the offset, index and tag fields?
Show answer
There are 256 / 2 = 128 sets, so the index is log2(128) = 7 bits. The offset is log2(64) = 6 bits. The tag is 32 − 7 − 6 = 19 bits.