Exercise: Huge Pages and TLB Coverage
In our lecture, we argue that paging eliminates external fragmentation and helps support full virtual memory. TLB makes paging a feasible memory management approach in practice. TLB hit ratio is critical to access latency to the main memory. Since a system has only limited size of TLB, it can be argued that the page size is one of the most consequential parameters in a memory system. The theoretical claim is simple: a 2 MB huge page multiplies the TLB’s coverage by 512 times (2 MB / 4 KB = 512) compared with a 4 KB page, so a workload whose working set overflows the 4 KB TLB coverage should run faster with huge pages, due to elevated TLB hit ratio. In practice, the benefit is often hard to observe, because other bottlenecks (cache misses, memory bandwidth, page-walk caches) can dominate and typical workloads often do not yield sufficiently high effective cache hit ratios.
This challenging exercise asks you to construct two contrasting workloads, measure them with and without huge pages, and explain what you observe, including the cases where the theory does not show up in the measurement. The objectives are:
- to be able to estimate theoretical memory access latency for simple paging systems,
- to be able to apply the estimation in reasoning the effect of page sizes in the configuration parameters of an operating system, and
- to be able to carry out system experiments, explain the results, and develop hypothesis to contrast observations and theoretical reasoning.
Background
Page Table and TLB
Modern CPUs can support multiple page sizes. For instance, the x86-64 architecture actually uses a 4-level hierarchical page table.
- 4 KB page: The CPU walks all four levels (PML4 → PDP → PD → PT) and uses a PTE (entry of PT) at the bottom to find the physical frame.
- 2 MB page: The CPU walks only three levels (PML4 → PDP → PD). The PDE (entry of PD) itself points directly to a 2 MB physical region, and the PT level is skipped entirely.
- 1 GB page: For a 1 GB page, the walk stops at the PDPTE: the CPU reads the PML4E to find the PDPT, then reads the PDPTE; if its PS bit is set, the PDPTE is the leaf. The PD and PT levels are not read.
A TLB entry holds one-page translation. If a L2 TLB has about 1,536 entries, then with 4 KB pages it covers about 6 MB of memory, and with 2 MB pages it covers about 3 GB. A workload whose working set fits inside 6 MB can have every page cached in the TLB; a workload whose working set is 1 GB cannot, unless the pages are huge. This leads to a hypothesis that large page size should offer lower memory access latency. (Specifically, the hypothesis applies to Workload A in Part 2, whose working set overflows the 4 KB TLB coverage. For Workload B, whose working set fits, the hypothesis predicts no difference between 4 KB and 2 MB pages.)
However, the TLB miss rate is not the same as the runtime. In addition, x86-64’s translation is a three-level hierarchy, TLB, paging-structure caches, page tables, where each level caches the results of the next, so the common case is answered at the fastest level and the slow path is only taken when all three levels miss. If the paging-structure caches already hold the relevant entries, a TLB miss costs much less than a full four-level walk. This is one reason huge pages often produce a smaller speedup than the coverage arithmetic suggests.
TLB and Context Switch
The lesson assumes a simple scenario in which the TLB caches translations for one process at a time. What happens during a context switch? For x86-64 family CPUs, there are two scenarios:
- Without PCID, a context switch flushes the TLB, forcing the new process to warm it up from scratch.
- With PCID, the TLB is tagged by address space, so the new process simply ignores the old process’s entries, and the old process’s TLB state can survive a switch, which is one reason why modern context switches are cheaper than the classic model suggests.
Nonetheless, context switches can affect the TLB’s effectiveness, and the experiment design should account for this.
Part 1: Determine Your TLB Geometry
Before designing the workloads, find the TLB sizes on your machine:
lscpu | grep -i tlb
sudo apt-get install -y cpuid
cpuid | grep -i tlb
Record the number of entries for the L1 data TLB and the L2 TLB. Compute:
- the coverage of the 4 KB TLB:
entries × 4 KB, - the coverage of the 2 MB TLB:
entries × 2 MB.
These two numbers determine which working-set sizes are interesting.
Part 2: Build the Two Workloads
You will write (or adapt) two programs that access a large array in different ways. Both should accept the array size and the page-size mode as command-line arguments, so you can run the same program in both modes.
Workload A: TLB Thrashing
- Working set: 1 GB (or as large as the machine comfortably allows).
- Access pattern: random. Use a simple linear congruential random number generator or a fixed permutation to visit indices in a scattered order.
- Why: with 4 KB pages, a 1 GB working set requires 262,144 TLB entries, far more than the TLB can hold. With 2 MB pages, it requires 512 entries, which fit comfortably. The contrast should be visible.
Workload B: TLB-Friendly (Control)
- Working set: 2 MB.
- Access pattern: random or sequential; the footprint is small enough that either works.
- Why: with 4 KB pages, a 2 MB working set requires 512 entries, which fit in the TLB. With 2 MB pages, it requires 1 entry. Both should have a near-zero TLB miss rate, so the runtime should be similar in both modes. This is the control: it shows that any speedup in Workload A comes from TLB coverage, not from huge pages in general.
In both workloads, do all I/O at the beginning and the end of the program, not inside the measurement loop in order to reduce context switches.
Sample Programs
The following two programs are starting points. They are deliberately small; adapt them as needed for your measurement.
tlbwork.c — a single program that allocates an array of a given
size and accesses it in a given pattern.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <time.h>
static volatile unsigned long sink;
static unsigned long lcg(unsigned long *seed) {
*seed = *seed * 6364136223846793005UL + 1442695040888963407UL;
return *seed;
}
int main(int argc, char **argv) {
if (argc < 4) {
fprintf(stderr, "usage: %s <size_mb> <random|seq> <huge|normal>\n",
argv[0]);
return 1;
}
size_t size = (size_t)atoi(argv[1]) << 20;
int random = strcmp(argv[2], "random") == 0;
int huge = strcmp(argv[3], "huge") == 0;
char *p = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED) {
perror("mmap");
return 1;
}
if (huge) {
if (madvise(p, size, MADV_HUGEPAGE) != 0) {
perror("madvise");
return 1;
}
}
memset(p, 1, size);
size_t n = size / sizeof(unsigned long);
unsigned long *q = (unsigned long *)p;
unsigned long seed = 42;
struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
const long iters = 10000000;
for (long i = 0; i < iters; i++) {
size_t idx = random ? (lcg(&seed) % n) : (i % n);
sink += q[idx];
}
clock_gettime(CLOCK_MONOTONIC, &t1);
double sec = (t1.tv_sec - t0.tv_sec)
+ (t1.tv_nsec - t0.tv_nsec) / 1e9;
printf("size=%zu MB pattern=%s page=%s time=%.3f s sink=%lu\n",
size >> 20, argv[2], argv[3], sec, sink);
munmap(p, size);
return 0;
}
checkpages.sh — a helper that reports whether the kernel actually
backed the allocation with huge pages.
#!/bin/sh
# Run before and after the workload; compare AnonHugePages.
grep -E 'AnonHugePages|HugePages_Total' /proc/meminfo
Run the workloads:
# Workload A: 1 GB, random, 4 KB vs. 2 MB
./tlbwork 1024 random normal
./tlbwork 1024 random huge
# Workload B: 2 MB, random, 4 KB vs. 2 MB
./tlbwork 2 random normal
./tlbwork 2 random huge
If Transparent Huge Pages (THP) is enabled in always mode on your
system, the normal run may also use huge pages, which would defeat
the comparison. Check:
cat /sys/kernel/mm/transparent_hugepage/enabled
If it says [always], either switch it to madvise for the duration
of the experiment (echo madvise | sudo tee ...) or use explicit
hugetlbfs allocation (mmap with MAP_HUGETLB) for the huge
mode, so that the normal mode is genuinely 4 KB.
Part 3: Measure
For each (workload, page mode) combination, run the program under
perf stat:
perf stat -e dTLB-loads,dTLB-load-misses ./tlbwork 1024 random normal
perf stat -e dTLB-loads,dTLB-load-misses ./tlbwork 1024 random huge
If perf stat reports “Permission denied,” run it with sudo, or check
kernel.perf_event_paranoid with sysctl kernel.perf_event_paranoid.
Record:
- runtime (from the program’s own output),
dTLB-load-missesanddTLB-loads,- TLB miss rate =
dTLB-load-misses / dTLB-loads.
where dTLB-loads counts the data loads that went through the TLB;
dTLB-load-misses counts the subset that missed and required a
page-table walk. The ratio is the TLB miss rate.
Repeat each configuration at least 5 times and report the median (the perf
stat output varies from run to run). If dTLB-load-misses is not available on
your CPU, use perf stat -e cycles as a coarser comparison, and report the
runtime from the program’s output.
Optional. Run the same workload with a background process that forces frequent
context switches (e.g., a yes loop pinned to the same core, like taskset -c 0
yes > /dev/null &). Does the huge-page benefit change? Why?
Part 4: Report and Deliverable
Prepare a short oral report with slides answering the following:
- The TLB geometry. What are the TLB sizes on your machine, and what coverage do they give with 4 KB and 2 MB pages?
- The prediction. For each workload, does the working set exceed the 4 KB coverage? Based on that, would you predict a speedup from huge pages?
- The measurement. A table of workload, page mode, runtime, TLB misses, and TLB miss rate.
- The comparison. Did the TLB miss rate drop with huge pages in Workload A? Did the runtime drop? If the miss rate dropped but the runtime did not, explain why (cache misses? memory bandwidth? page-walk caches?). If neither dropped, explain why the theory did not apply to your workload.
- The control. Did Workload B show a difference between 4 KB and 2 MB? If not, what does that tell you about the source of any difference in Workload A?
- The lesson. Explain what this exercise shows about the relationship between a mechanism (the TLB) and its observable effect (runtime).
- Experiment design. Your reasoning about the experiment design and design considerations, e.g., why do we write our own pseudo random number generator instead of using the library function?
Further Reading
- The TLB and paging material from the main-memory lecture.
man 2 madvise— theMADV_HUGEPAGEflag.man 2 mmap— theMAP_HUGETLBflag.- The kernel documentation on Transparent Huge Pages: https://docs.kernel.org/admin-guide/mm/transhuge.html — how THP decides when to back an allocation with huge pages, and the madvise / always / never modes.
perf statdocumentation: https://perfwiki.github.io/main/man perf-stat— the manual page for theperf statcommand, which documents the counters and the output format.