Sub topic 17
TLB Misses and Page-Level Locality
This chapter assumes you know what a cache line is and how spatial locality works, and that you can read C. It also assumes you have seen virtual memory described at least once. The chapter covers a cost that sits next to cache misses: the cost of translating addresses.
Every address is translated
Your program uses virtual addresses. The CPU converts each one to a physical address before it can reach the caches or RAM. Memory is divided into pages for this purpose, and 4 KiB is the usual page size on x86-64 and most ARM Linux systems. The operating system keeps a page table that maps each virtual page to a physical frame.
The page table lives in memory and has several levels. On x86-64, a full lookup (a page walk) reads up to four table entries in sequence. Doing that for every load and store would make each access several times slower. The CPU avoids this with the translation lookaside buffer (TLB). The TLB is a small cache of recent virtual-to-physical page mappings.
A TLB hit costs almost nothing. A miss costs a page walk. The page-table entries are themselves cached in the data caches, so a walk may take tens of cycles, or hundreds if those entries are also cold.
TLB reach
The TLB holds few entries. Its reach is the number of entries times the page size, and it is the amount of memory you can touch without TLB misses. The numbers below are illustrative. Real CPUs differ, and lscpu, cpuid, or vendor manuals give exact values.
| Level | Typical entries | Reach with 4 KiB pages | Reach with 2 MiB pages |
|---|---|---|---|
| L1 data TLB | 64 | 256 KiB | 128 MiB |
| L2 (second-level) TLB | 1,500 to 2,000 | 6 to 8 MiB | 3 to 4 GiB |
Compare the reach to your L2 and L3 cache sizes. A 32 MiB L3 cache is larger than the 4 KiB-page reach of the L2 TLB. You can therefore have data that fits in cache and still take TLB misses on most accesses.
Page-level locality
Cache lines reward accesses that are close together within 64 bytes. TLB entries reward accesses that are close together within a page. The same habits help both:
- Sequential traversal touches a new page only once per 4096 bytes.
- A large stride, such as walking a column of a big row-major matrix, can touch a new page on every access.
- Objects scattered across the heap touch many pages, even if the total data is small.
- Objects packed into a few pages touch few pages, even if the traversal order is irregular.
The last two points explain why pointer-based structures suffer. A linked list with 100,000 small nodes may have nodes spread across thousands of pages. Each hop can cost a cache miss and a TLB miss.
Observing the effect
The program below touches the same set of cache lines in two orders. The first order visits all 64 lines of a page before moving on. The second visits one line from each of 16,384 pages (64 MiB) before returning to the first page. The offset (p + k) % 64 shifts with the page number. This keeps consecutive accesses out of the same cache set and avoids mixing in the conflict misses from the associativity chapter.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/mman.h>
#define PAGE 4096u
#define LINE 64u
#define PAGES 16384u
#define LINES_PER_PAGE (PAGE / LINE)
static double now(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (double)t.tv_sec + (double)t.tv_nsec * 1e-9;
}
int main(void) {
size_t bytes = (size_t)PAGES * PAGE;
unsigned char *buf = mmap(NULL, bytes, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (buf == MAP_FAILED) { perror("mmap"); return 1; }
for (size_t i = 0; i < bytes; i++) buf[i] = (unsigned char)i; /* prefault */
unsigned long sum = 0;
double t0 = now();
for (unsigned p = 0; p < PAGES; p++)
for (unsigned k = 0; k < LINES_PER_PAGE; k++)
sum += buf[(size_t)p * PAGE + ((p + k) % LINES_PER_PAGE) * LINE];
double t1 = now();
for (unsigned k = 0; k < LINES_PER_PAGE; k++)
for (unsigned p = 0; p < PAGES; p++)
sum += buf[(size_t)p * PAGE + ((p + k) % LINES_PER_PAGE) * LINE];
double t2 = now();
printf("page by page: %.3f s\nline by line across pages: %.3f s\n(sum=%lu)\n",
t1 - t0, t2 - t1, sum);
return 0;
}Compile with gcc -O2 tlb.c -o tlb. Both loops do the same number of loads to the same lines. The second loop usually runs noticeably slower. On Linux you can confirm the cause with perf stat -e dTLB-load-misses,dTLB-loads ./tlb. Event names vary by CPU, and perf list shows what yours supports. The counters cover the whole run, so to compare the two loops, run each in its own program or build.
Reducing TLB misses
Use huge pages
Larger pages give each TLB entry more reach. On x86-64 Linux, huge pages are 2 MiB. A 64 MiB array needs 16,384 entries with 4 KiB pages and 32 entries with 2 MiB pages. The second count fits in the L1 TLB.
Linux offers two routes. Explicit huge pages (hugetlbfs, or MAP_HUGETLB) require reserved memory. Transparent huge pages (THP) are automatic when the setting in /sys/kernel/mm/transparent_hugepage/enabled is always, or on request when it is madvise.
#define _GNU_SOURCE
#include <stdlib.h>
#include <sys/mman.h>
void *alloc_huge(size_t bytes) {
size_t huge = (size_t)2 << 20;
bytes = (bytes + huge - 1) & ~(huge - 1); /* aligned_alloc needs a multiple */
void *p = aligned_alloc(huge, bytes);
if (p == NULL) return NULL;
madvise(p, bytes, MADV_HUGEPAGE); /* a hint; the kernel may ignore it */
return p;
}Check AnonHugePages in /proc/self/smaps to see whether the hint took effect.
Huge pages have costs:
- Memory fragmentation can prevent the kernel from finding contiguous 2 MiB regions.
- Zeroing a huge page on first touch can add latency spikes.
- A sparse allocation wastes memory, because the kernel backs the whole 2 MiB.
- Some databases recommend disabling THP because of these latency effects. Measure on your workload.
Pack data into fewer pages
Changes that shrink the working set help here as well. Hot and cold splitting, compact struct layout, and contiguous arrays all reduce the page count. For pointer-based structures, allocate nodes from an arena or pool. This keeps nodes from one structure in adjacent pages instead of interleaved with unrelated allocations.
Block by page when the stride is large
Tiling works for pages the same way it works for cache lines. If a loop must touch many pages, process a group of items that share a page set before moving on. Choose tile sizes so that the tile's page count stays within the L1 TLB capacity.
Common mistakes
- Treating every slow strided loop as a cache problem. If the cache miss count is modest and dTLB misses are high, the page count is the limit.
- Assuming huge pages always help. They help large, randomly accessed working sets, and do little for small ones.
- Benchmarking without prefaulting, which mixes page-fault cost into the result.
- Hard-coding 4096. Query the page size with
sysconf(_SC_PAGESIZE)in portable code. Apple Silicon uses 16 KiB pages, for example. - Forgetting virtualization. Under a hypervisor, a TLB miss may need a two-dimensional page walk, which makes misses more expensive.
Exercise
A program scans a 256 MiB array of 8-byte values in random order, one value at a time. The L2 TLB has 1,536 entries. Estimate the TLB reach with 4 KiB pages and with 2 MiB pages, and say which configuration you expect to take fewer TLB misses and why.
Show answer
With 4 KiB pages the reach is 1,536 × 4 KiB = 6 MiB, far less than 256 MiB, so most random accesses miss the TLB. With 2 MiB pages the reach is 1,536 × 2 MiB = 3 GiB, which covers the whole array (it needs only 128 pages), so almost all lookups hit. The huge-page configuration takes far fewer TLB misses. Cache misses are unchanged, because the pages do not alter cache-line behavior.