Sub topic 6
Splitting an Address into Tag, Index and Offset
Assume you know binary and hexadecimal numbers, powers of two, byte-addressable memory, and the basic idea of cache blocks and cache lines. This chapter shows how a cache divides a physical address so it can locate data quickly.
The three address fields
A cache stores memory in fixed-size blocks. A block may contain several consecutive bytes. When the CPU requests a byte, the cache uses three parts of the address:
- Block offset: selects a byte inside the block.
- Index: selects a cache line or set.
- Tag: identifies which memory block currently occupies that line or set.
For an address with \(A\) bits:
\[ A = \text{tag bits} + \text{index bits} + \text{offset bits} \]
If the block size is \(B\) bytes, the offset needs:
\[ \log_2(B) \]
bits. If the cache has \(S\) sets, the index needs:
\[ \log_2(S) \]
bits. The remaining bits form the tag:
\[ \text{tag bits} = A - \log2(S) - \log2(B) \]
Both the block size and the number of sets must normally be powers of two.
Worked example
Consider a 32-bit physical address and a cache with:
- 16-byte blocks
- 16 sets
- One or more ways per set
The block offset has:
\[ \log_2(16) = 4 \]
bits. The index has:
\[ \log_2(16) = 4 \]
bits. Therefore, the tag has:
\[ 32 - 4 - 4 = 24 \]
bits.
The address layout is:
| Field | Bits | Purpose |
|---|---|---|
| Tag | 24 | Identifies the memory block |
| Index | 4 | Selects one of 16 sets |
| Offset | 4 | Selects one of 16 bytes |
For address 0x1234, the low four bits are the offset. The next four bits are the index. The remaining high bits are the tag.
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), or tag=0x12, index=3, offset=4The offset is 4, so the CPU wants the fifth byte in the block. The index is 3, so the cache checks set 3. The tag is 0x12, so the cache compares that tag with the tag stored in the selected set.
A cache hit occurs only when the stored tag matches and the entry is valid. The offset is not compared with the tag. It selects the requested byte after the correct block has been found.
Mapping consequences
In a direct-mapped cache, each set has one line. The index selects exactly one possible line.
In a set-associative cache, the index selects a set, and the tag is compared with every way in that set.
In a fully associative cache, there is no index field. The cache compares the tag against all lines, so all address bits except the offset belong to the tag.
Exercise
A 16-bit address uses 8-byte blocks and a cache with 8 sets. How many tag, index, and offset bits does the address contain?
Show answer
The offset uses log2(8) = 3 bits. The index uses log2(8) = 3 bits. The tag uses 16 - 3 - 3 = 10 bits.