The Complete Guide to Memory Bandwidth, NUMA and Huge Pages
Complete guide to memory performance on Linux: measure bandwidth, place data across NUMA nodes and cut TLB misses with huge pages, with C code throughout.

A program that streams through a few gigabytes of data is not limited by how fast the processor can add numbers. It is limited by how fast memory can deliver them, and on a server with two sockets, by which socket's memory the data happens to sit in and how many pages the processor must translate to reach it. Three separate mechanisms are at work: the bandwidth of the memory channels, the distance between a core and the memory it uses, and the size of the pages that map the memory. Each can cost a factor of two or more when it is wrong, and none is visible in the source code. This guide covers all three on Linux, from measuring the machine, through placement and page size, to a worked case that puts them together. It uses C, glibc 2.41 and Linux 6.12 on x86-64, with the tools numactl 2.0.19, perf and the STREAM benchmark.
The sentence worth keeping is this one: a memory-bound loop runs at the speed of its slowest resource, and the three resources in this guide, channel bandwidth, node distance and page-table reach, are each set before the first instruction runs, by how the data was allocated and first touched. Most of the work of tuning is therefore not rewriting the loop, but deciding where its data lives.
How this guide is organized
The sections follow the order in which you should investigate. First the vocabulary and the one equation that ties latency to bandwidth. Then measurement: what your machine can deliver, so you know the ceiling. Then the cache hierarchy and access patterns, because a loop that fits in cache never reaches memory. Then NUMA: topology, first touch, policies, libnuma and the kernel's automatic balancing. Then pages: the TLB, transparent huge pages, reserved huge pages and 1 GiB pages, and how to count the misses. Then the newer topologies, sub-NUMA clustering and CXL. A worked case follows, and a boundary section says who should skip all of this. Each topic has a focused post for the detail, linked where it comes up, and this guide gives the whole picture in one place.
Two numbers that are not the same: latency and bandwidth
Memory latency is how long one access waits for its data. Memory bandwidth is how many bytes per second the memory system moves when many accesses are in flight. They are different properties, and a program can be limited by either.
A pointer chase, where each address comes from the previous load, has one request in flight at a time. Its speed is the latency of main memory, however wide the channels are. A sequential sum over a large array has addresses known in advance, so the hardware keeps many requests in flight, and its speed is the bandwidth of the channels. The two programs read the same amount of memory and run at very different speeds, because the first exposes the latency and the second hides it behind parallelism.
The equation that links them comes from queueing theory and is called Little's law. The number of bytes in flight equals bandwidth multiplied by latency. Rearranged, the bandwidth a program achieves is the bytes it keeps outstanding divided by the latency of each request. If a core can have ten cache line misses outstanding and each line is 64 bytes, then 640 bytes are in flight, and a latency of 100 nanoseconds gives at most 6.4 bytes per nanosecond for that core. These figures are an illustration of the arithmetic and not a measurement. The practical consequences are worth stating plainly. A single core usually cannot saturate the memory channels of a modern socket, so a bandwidth test needs several threads. And once the channels are saturated, extra requests queue, so latency rises with load, which is why loaded latency, not idle latency, describes a busy server. The post on latency versus bandwidth builds the same picture from first principles.
What the machine can deliver: channels and the arithmetic of peak bandwidth
Before measuring, compute the ceiling. Memory attaches to the processor through channels, and each populated channel moves a fixed number of bytes per transfer at a fixed transfer rate. The peak is the product:
peak bytes per second = transfers per second x bytes per transfer x channelsA DDR5-4800 module does 4,800 million transfers per second. A 64-bit data path moves 8 bytes per transfer, so one channel peaks at 4,800,000,000 times 8, which is 38.4 gigabytes per second. Eight channels peak at 307.2 gigabytes per second. DDR5 splits each module into two independent 32-bit subchannels, which together match the width of one DDR4 channel, so compare total data width and not the channel count in a brochure.
The ceiling is real only if the channels are populated. A server with twelve channels and six DIMMs installed in the wrong slots uses fewer than it could. Capacity is the visible reason to buy DIMMs and channel count is the invisible bandwidth reason, so an upgrade for capacity can leave bandwidth where it was. A module rated for a given speed may also run slower when a channel carries two modules, so the configured speed, not the rated speed, sets the arithmetic. Linux shows what is installed:
sudo dmidecode --type memoryEach populated slot prints its size, locator, rated Speed and Configured Memory Speed, and the rank count. An empty slot says No Module Installed. Count the populated slots per channel, compare with the platform manual's population guide, and check that the configured speed equals the rated speed. The post on channels, ranks and interleaving goes through ranks, banks and how the controller spreads addresses across them.
The controller spreads consecutive addresses over channels, a scheme called interleaving, so a sequential stream uses every channel without the program knowing. The mapping has a period. If it covers eight channels at 256 bytes each, then a stride of 2048 bytes lands on the same channel every time and uses one eighth of the hardware. The classic cause is a matrix walked by column when the row length is a power of two. Padding each row by one cache line breaks the pattern, and the fix is one line of code in the allocation.
Measure the ceiling with STREAM
Peak is arithmetic and sustained is a measurement. STREAM, written by John McCalpin, times four loops over three large arrays: Copy, Scale, Add and Triad. Each does almost no arithmetic per byte, so its time is the time memory takes to supply and absorb the data. Triad, a[i] = b[i] + s * c[i], mixes two reads and a write and resembles streaming numerical code, so it is the figure usually quoted.
The rules for a valid run are few. Each array must be at least four times the size of the largest cache, so the loops measure memory and not cache. Threads must be pinned so they do not migrate, and enough of them must run to saturate the channels. A build and run look like this, with GCC 15:
gcc -O3 -march=native -fopenmp -DSTREAM_ARRAY_SIZE=80000000 -DNTIMES=20 stream.c -o stream
OMP_NUM_THREADS=16 OMP_PROC_BIND=spread OMP_PLACES=cores ./streamEighty million double elements per array is about 610 MiB, so three arrays use roughly 1.8 GiB, well beyond any cache. The program prints the best rate of each kernel in megabytes per second, excluding the first iteration, which pays page-fault costs. Compare Triad with the computed peak. A result in the neighborhood of the peak, below it by the amount refresh, bank conflicts and read-to-write turnaround account for, means the memory system is healthy. A result far lower points to unpopulated channels, a downclocked module, all threads on one socket or a power setting. Sweep the thread count from one up to every core and note where Triad stops improving: that knee is the number of cores that saturates memory, and it is the right size for the thread pool of a bandwidth-bound job. STREAM counts only the bytes the source names, so its figure is lower than the raw bus traffic, because a write also reads the line first on most caches. Compare its numbers only with other STREAM runs. The post on the STREAM benchmark covers the output line by line.
Latency under load
Idle latency is the number on a data sheet. Loaded latency, the time of a read while other cores stream data, is what a busy server experiences, and it can be several times the idle value. Intel Memory Latency Checker measures both. The invocations that matter are --idle_latency for the best case, --latency_matrix and --bandwidth_matrix for the node-to-node costs, and --loaded_latency, which steps injected load from idle to maximum and prints latency against bandwidth. Read the loaded table from the bottom: at light load, latency sits near idle, and as the injected load grows, bandwidth rises and latency creeps up, and near saturation bandwidth flattens while latency climbs steeply. The curve tells you where to stop. Planning to run a bandwidth-hungry job at a fraction of peak, below the knee, keeps the queueing delay small for everything else on the machine. The tool needs root, the msr kernel module to switch off prefetchers during the latency tests, and huge pages so TLB misses stay out of the number. The post on loaded latency shows the full output.
Caches decide whether memory matters at all
A loop whose working set fits in cache never waits for main memory, so none of the later sections apply to it. The first diagnostic is therefore the working-set size against the cache sizes, which lscpu reports and lstopo draws. This program sweeps the working set and prints the number of bytes touched per pass so you can time each size. It does not print timings, because those belong to your machine.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
for (size_t kib = 16; kib <= 1048576; kib *= 4) {
size_t n = kib * 1024 / sizeof(uint64_t);
uint64_t *a = malloc(n * sizeof *a);
if (!a) return 1;
for (size_t i = 0; i < n; i++) a[i] = 1;
uint64_t s = 0;
for (int pass = 0; pass < 8; pass++)
for (size_t i = 0; i < n; i++) s += a[i];
printf("%8zu KiB sum=%llu\n", kib, (unsigned long long)s);
free(a);
}
return 0;
}Each size does eight passes over n elements, so the printed sum is 8 * n:
16 KiB sum=16384
64 KiB sum=65536
256 KiB sum=262144
1024 KiB sum=1048576
4096 KiB sum=4194304
16384 KiB sum=16777216
65536 KiB sum=67108864
262144 KiB sum=268435456
1048576 KiB sum=1073741824Wrap each size in a timer and compute bytes per second. The result is a staircase: high plateaus while the data fits in the L1 cache, the L2 and the last-level cache, then a drop to the memory plateau. The height of the last plateau is the sustained single-thread bandwidth, and the position of each step is a cache size. If the working set of your real loop sits on a high plateau, bandwidth is not your problem, and the loop is limited by something else.
Access patterns: what the prefetcher can see
Memory hardware is built around sequential access. Caches fetch whole 64-byte lines. The prefetcher watches the stream of addresses and fetches ahead when it sees a constant stride, so a sequential or small-stride loop has its data waiting in cache before the instruction asks. An unpredictable pattern defeats it. Three patterns cover most code.
Sequential streaming reaches the bandwidth ceiling, because every fetched byte is used and the prefetcher hides the latency. Strided access wastes bandwidth in proportion to the stride: a stride of 64 bytes or more touches one element per line, so the loop moves a whole line for every element it uses. Random access over a large region has no prefetching and takes a latency hit per access unless several independent accesses overlap.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(void) {
size_t n = 1UL << 27; /* 128 Mi doubles = 1 GiB */
double *a = malloc(n * sizeof *a);
if (!a) return 1;
for (size_t i = 0; i < n; i++) a[i] = 1.0;
for (size_t stride = 1; stride <= 16; stride *= 2) {
double s = 0.0;
size_t used = 0;
for (size_t i = 0; i < n; i += stride) { s += a[i]; used++; }
printf("stride %2zu: elements used=%zu sum=%.0f\n", stride, used, s);
}
free(a);
return 0;
}For strides of 1, 2, 4, 8 and 16 elements, the elements used are n / stride, and each element is 1.0, so the sum equals the count. A 64-byte line holds 8 doubles, so every line is fetched for strides up to 8, and only at stride 16 does the loop skip every other line.
stride 1: elements used=134217728 sum=134217728
stride 2: elements used=67108864 sum=67108864
stride 4: elements used=33554432 sum=33554432
stride 8: elements used=16777216 sum=16777216
stride 16: elements used=8388608 sum=8388608Time the five loops. The time for strides 1 through 8 stays nearly flat even though the work halves each step, because the loop is bandwidth bound and every step fetches the same number of lines. That flat region is the signature of a memory-bound loop. The lesson for data layout is that bytes fetched, not elements used, set the cost, so keep the fields a loop uses together in the same lines, which is the case for structure-of-arrays layouts over array-of-structures when a loop touches one field.
Is the loop memory-bound at all: the roofline
The roofline model answers it with arithmetic. Attainable performance is the smaller of the processor's peak floating-point rate and the arithmetic intensity of the kernel times the memory bandwidth. Arithmetic intensity is floating-point operations per byte moved to and from main memory. The ridge point is peak compute divided by bandwidth. A kernel left of the ridge is bandwidth-bound and no faster arithmetic helps. A kernel right of it is compute-bound.
Streaming kernels sit far left of any ridge. The vector add c[i] = a[i] + b[i] does one operation for 24 bytes, an intensity of about 0.04. Triad does two for 24, about 0.08. A dot product does two for 16, 0.125. For these loops vectorizing the arithmetic changes nothing, and the only levers are fewer bytes and better placement, which is what the rest of this guide is about. Dense blocked matrix multiplication, which reuses each loaded value many times, is the textbook compute-bound case. The post on the roofline shows how to measure the compute roof with a register-only fused multiply-add loop and how to dial intensity with a parameterized kernel.
NUMA: memory with a distance
Everything above assumed one pool of memory. Many servers have two or more sockets, and each socket has its own memory controllers and DIMMs. A core reads its own socket's memory directly, called local memory, and reaches the other socket's memory across an interconnect, called remote memory. The system is non-uniform: the time and bandwidth of an access depend on where the core and the data are. The kernel groups cores and memory into NUMA nodes. A remote access takes extra hops, and the interconnect has finite capacity shared by all remote traffic, so remote memory has higher latency and lower bandwidth. The relative cost is reported by firmware as a distance matrix, with 10 meaning local, and the real ratio must be measured.
Linux shows the layout under /sys/devices/system/node/, and numactl --hardware prints it:
available: 2 nodes (0-1)
node 0 cpus: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
node 0 size: 128733 MB
node 0 free: 96412 MB
node 1 cpus: 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
node 1 size: 129019 MB
node 1 free: 101278 MB
node distances:
node 0 1
0: 10 21
1: 21 10The output above is illustrative and yours will differ. Read it as a map: which logical CPUs belong to each node, how much memory each has and how much is free, and how far apart the nodes are. lstopo from hwloc adds caches, cores and which node each PCI device belongs to, using two numbering schemes: L# for hwloc's logical index and P# for the operating system's physical index, and the physical one is what numactl and taskset take. Count the nodes before tuning. More nodes than sockets means the firmware is splitting sockets, a mode covered later. The post on inspecting the topology walks through the tools and a libnuma check for scripts, and the post on what NUMA is covers the concept from the start.
Where pages land: first touch
Allocation is lazy. malloc and mmap return address space, and the kernel supplies physical memory when a page is first written. With the default policy the page comes from the node of the CPU that took the page fault. So placement is decided by which thread first writes each page, not by who allocated the buffer and not by who reads it later.
That is the source of a classic problem. A program allocates a large array, fills it in a single thread, and then processes it with threads on every socket. The fill placed the whole array on one node, so the threads on the other node read remote memory for the rest of the run, and the first node's memory controllers and link carry all the traffic. The program is correct and slower than it should be, and nothing in its output shows it.
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define N (1UL << 28) /* 2 GiB of doubles */
int main(void) {
double *a = malloc(N * sizeof *a);
if (!a) return 1;
#pragma omp parallel for schedule(static)
for (size_t i = 0; i < N; i++) /* parallel first touch */
a[i] = 1.0;
double sum = 0.0;
#pragma omp parallel for schedule(static) reduction(+:sum)
for (size_t i = 0; i < N; i++)
sum += a[i];
printf("sum=%.1f\n", sum);
free(a);
return 0;
}The fix is in the first loop: initialize with the same parallel loop and the same static schedule as the compute loop, so the thread that touches a block is the thread that reads it, and its pages sit on its own node. Threads must stay where they started, so set OMP_PROC_BIND=close or spread and OMP_PLACES=cores. The result is the same either way:
sum=268435456.0Prove it worked rather than assuming. The move_pages call from <numaif.h>, with a null destination array, writes the node of each page into a status array, and numastat -p <pid> shows per-node memory for a process. The rule has limits. Dynamic scheduling or work stealing breaks the match between toucher and user. Data that is later reshaped is read by different threads from the ones that initialized it. And calloc for large sizes returns fresh zero pages that are not touched at all, so first touch happens in your loop. Use malloc and an explicit parallel fill when placement matters. The post on first touch covers these cases with a placement checker.
Placing memory on purpose: numactl and libnuma
First touch is implicit. Two tools make placement explicit. numactl sets a policy for a whole process from outside, and libnuma sets one per allocation from inside.
The numactl flags split into a CPU half and a memory half. --cpunodebind=N restricts threads to node N's CPUs, and --membind=N restricts pages to node N's memory. Together they keep a process fully local:
numactl --cpunodebind=0 --membind=0 ./server--membind is strict, so when the node is full there is no fallback: the kernel reclaims what it can, and then the process gets ENOMEM or the out-of-memory killer. --preferred=N tries node N and falls back. --interleave=all spreads pages round-robin across nodes, which suits a large structure read by threads on every node, because it spreads bandwidth across all the controllers at the price of making half of the accesses remote. --localalloc is the default made explicit.
| Policy | Flag | Use when |
|---|---|---|
| Bind | --membind=N | The working set fits one node and you want strict locality |
| Preferred | --preferred=N | Locality matters but running out must not kill the process |
| Interleave | --interleave=all | A large shared structure is read from every node |
| Local | --localalloc | The default, stated explicitly |
Verify the result with numastat -p. A large number on the wrong node means something escaped the policy: a child that reset it, shared memory created by another process, or the page cache. A hard bind has one well-known trap, which is running the node out of memory while the other node sits idle, so check node N free before binding and size the working set to fit. The usual shape of a well-tuned NUMA deployment is one instance per node, each bound to its own node, behind a load balancer. The post on binding with numactl covers the flags and the inheritance rules.
When one process holds several kinds of data, a per-process policy is too coarse. libnuma lets the program choose per allocation. numa_alloc_onnode(size, node) puts all pages on a node, numa_alloc_local(size) uses the node of the calling thread's CPU, and numa_alloc_interleaved(size) spreads pages. They return page-aligned mmap memory, are meant for large blocks, and must be released with numa_free(ptr, size), never free. A worker pins itself with numa_run_on_node and then allocates locally:
#include <numa.h>
#include <stdio.h>
int main(void) {
if (numa_available() < 0) return 1;
numa_run_on_node(0); /* CPUs of node 0 only */
size_t len = 32UL << 20;
char *buf = numa_alloc_local(len); /* pages from node 0 */
if (!buf) return 1;
for (size_t i = 0; i < len; i += 4096) buf[i] = 1;
printf("allocated %zu MiB locally\n", len >> 20);
numa_free(buf, len);
return 0;
}allocated 32 MiB locallyPin first and allocate second, because the node that supplies local pages is the node the thread runs on at that moment. Link with -lnuma. The post on libnuma allocation shows the per-worker pattern, interleaved tables and a placement check with move_pages.
When the kernel moves things for you: automatic NUMA balancing
Linux can also correct placement on its own. Automatic NUMA balancing samples access by unmapping pages in a task's address space so the next touch takes a hinting fault, records which node the faulting CPU is on, and then migrates pages toward the CPUs that use them and tasks toward their memory. It is controlled by the sysctl kernel.numa_balancing, where 0 is off, 1 is normal balancing and 2 enables memory tiering mode.
It helps programs with poor or unknown placement and a stable access pattern: a process that allocated on one node and was later moved by the scheduler, or a service whose workers each mostly touch their own slice. It costs minor faults and migrations, so it hurts latency-sensitive code, short-lived processes, programs with memory shared by threads on every node and programs that already pin their memory. The counters in /proc/vmstat tell which case you are in: numa_hint_faults, numa_hint_faults_local and numa_pages_migrated. Take two snapshots under steady load. Rising migrations with a flat local-fault ratio mean the kernel is moving pages without improving locality. The decision is empirical: run the workload with the sysctl at 0 and at 1 and compare throughput and tail latency. The post on automatic NUMA balancing explains the mechanism and the test.
Pages and the TLB
Every memory access uses a virtual address, and the processor translates it to a physical address through page tables. Walking the tables takes several dependent memory accesses, so processors cache recent translations in the translation lookaside buffer, the TLB. It has a fixed number of entries, so the memory it can map without a miss, its reach, equals the number of entries times the page size. With 4 KiB pages the reach is small. A working set of many gigabytes, touched across many pages, misses the TLB often, and each miss starts a page-table walk.
A huge page maps far more memory per entry. On x86-64 the sizes are 4 KiB, 2 MiB and 1 GiB, which is a factor of 512 from the first to the second and a factor of 512 again to the third. The arithmetic of reach is direct: a TLB with a given number of entries covers 512 times more memory with 2 MiB pages than with 4 KiB pages. Huge pages also shorten the walk, because the mapping is found one or two levels higher in the page-table tree. The benefit appears in programs with large, randomly accessed working sets, such as in-memory databases, hypervisors and numerical codes, and it is zero for a working set that already fits the TLB.
Count the misses before and after rather than assuming. perf stat has generic events for the data TLB:
perf stat -e dTLB-loads,dTLB-load-misses,cycles ./progCompare the absolute miss count and the cycles between variants, not the rate alone, because the denominator includes every load, including those that never need a fresh translation. On Intel processors the raw page-walk events, such as dtlb_load_misses.walk_active, count cycles spent walking, which turns misses into time. These counters are often unavailable inside virtual machines, and the event names differ on other architectures. A small test shows the effect: touch one byte in each page of a 1 GiB buffer in pseudo-random order, once with 4 KiB pages and once with the buffer advised for huge pages. The program output is the same, and the miss counts differ by orders of magnitude. The post on measuring TLB misses has the test program and the report format, and the post on TLB misses as a hidden cost covers the effect conceptually.
Transparent huge pages with madvise
The least effort route to huge pages is Transparent Huge Pages, THP. The kernel assembles a 2 MiB page from contiguous free memory at fault time, or later through a background thread called khugepaged, and falls back to small pages if it cannot. No pool or special mount is needed. The system-wide policy is in /sys/kernel/mm/transparent_hugepage/enabled with three values: always, never and madvise. In madvise mode, a range uses THP only if the program asked for it:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#define HUGE (2UL << 20)
int main(void) {
size_t len = 64 * HUGE; /* 128 MiB */
void *p = aligned_alloc(HUGE, len);
if (!p) return 1;
if (madvise(p, len, MADV_HUGEPAGE) != 0) { perror("madvise"); return 1; }
memset(p, 1, len); /* fault pages in */
FILE *f = fopen("/proc/self/smaps_rollup", "r");
char line[256];
while (f && fgets(line, sizeof line, f))
if (strncmp(line, "AnonHugePages:", 14) == 0) fputs(line, stdout);
if (f) fclose(f);
free(p);
return 0;
}Two rules decide whether it works. The range must be aligned to 2 MiB, because only an aligned 2 MiB chunk inside the range can become a huge page, so allocate with aligned_alloc(2 MiB, ...) and not a bare malloc. And the call must come before the first touch, so the kernel allocates a huge page at the fault. Pages already faulted as small pages are collapsed later by khugepaged, on its own schedule. If everything worked, the rollup reports the whole range:
AnonHugePages: 131072 kBThat is 128 MiB. A lower number means fragmentation, a defrag policy that does not wait, or a missed alignment, and zero means THP did not engage. Check the hg flag and THPeligible in /proc/self/smaps. THP is best effort: it gives no guarantee, and building a huge page can cost time. The post on THP with madvise covers the details, including MADV_NOHUGEPAGE and the process-wide disable.
The cost of THP: compaction stalls
When no free 2 MiB block exists, the kernel may compact memory, moving pages to create contiguity, and a thread in direct compaction does not run your code. For a batch job the wait is invisible. For a latency-sensitive service it is a tail-latency spike with no obvious cause. The defrag setting in /sys/kernel/mm/transparent_hugepage/defrag decides whether the faulting thread waits. The values are always, which stalls until a huge page is built, defer, which falls back at once and wakes background compaction, defer+madvise, madvise, which compacts directly only in ranges marked MADV_HUGEPAGE, and never.
The evidence is in /proc/vmstat. thp_fault_alloc counts huge pages allocated at fault, thp_fault_fallback counts faults that fell back to small pages, compact_stall counts threads entering direct compaction, and compact_success and compact_fail split the outcomes. The counters accumulate from boot, so sample them twice over a window and compare the differences. A rising compact_stall with a high fallback fraction means huge pages are scarce and threads are paying to find them. Direct compaction is not exclusive to THP, so pair the counter with the fallback count before blaming it. The choice follows the workload's tolerance for waiting: always or madvise for batch work, defer or never for services where a stall is unacceptable. The post on compaction stalls has a program that prints the deltas and a workload that provokes the fallback.
Reserved huge pages with hugetlbfs and MAP_HUGETLB
THP is a service, and explicit huge pages are a contract. You reserve a pool, you map from it, and an allocation either gets a huge page or fails. The pool size is the sysctl vm.nr_hugepages, counted in pages of the default size, 2 MiB on x86-64:
sudo sysctl vm.nr_hugepages=512
grep -E 'HugePages_|Hugepagesize' /proc/meminfo512 pages of 2 MiB is 1 GiB. The kernel tries to allocate that many contiguous blocks immediately. On a machine that has been running a while it may get fewer, so read HugePages_Total back. HugePages_Free is what remains unused and HugePages_Rsvd is what is promised to mappings that have not faulted in yet. Two interfaces use the pool. An anonymous mapping with MAP_HUGETLB:
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
int main(void) {
size_t len = 8UL << 20; /* four 2 MiB pages */
void *p = mmap(NULL, len, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0);
if (p == MAP_FAILED) { perror("mmap MAP_HUGETLB"); return 1; }
memset(p, 0x5a, len);
puts("mapped and touched 8 MiB of huge pages");
munmap(p, len);
return 0;
}mapped and touched 8 MiB of huge pagesThe length must be a multiple of the huge page size. With an empty pool the call fails immediately with Cannot allocate memory, because reservation happens at map time and not at the later fault, which is the point of the contract. The second interface is hugetlbfs, a pseudo filesystem whose files are backed by huge pages, mounted with mount -t hugetlbfs -o pagesize=2M,size=512M none /mnt/huge. Files there are mapped with ordinary mmap and no flags, and a second process that maps the same path shares the pages, which anonymous MAP_HUGETLB cannot do beyond fork. On a NUMA machine the pool is spread across nodes and per-node values live under /sys/devices/system/node/nodeN/hugepages/, so a process bound to node 0 takes its huge pages from node 0's pool and fails if that pool is empty even when node 1's is not. Reserve per node when the workload is node-bound. The post on hugetlbfs and MAP_HUGETLB covers mounts, sharing and the reservation rules.
1 GiB pages at boot
A 1 GiB page needs 1 GiB of contiguous, aligned memory, which a running machine rarely has. Reserve them at boot with two kernel parameters, hugepagesz=1G and hugepages=N, after checking that the CPU lists pdpe1gb in /proc/cpuinfo:
default_hugepagesz=1G hugepagesz=1G hugepages=16The order matters: hugepagesz= must come before the hugepages= it applies to. Sixteen pages is 16 GiB removed from general use, split evenly across NUMA nodes unless you give per-node counts as hugepages=0:8,1:8. A node with too little free memory at boot reserves fewer than its share and the shortfall does not move, so check both nodes. Virtual machines often hide pdpe1gb. Map the pages with MAP_HUGETLB | MAP_HUGE_1GB, where the size flag encodes the base-2 logarithm, 30, above bit 26. One page covers 262,144 times the memory of a 4 KiB page per TLB entry, so a working set of tens of gigabytes needs only a handful of entries. The price is memory that other programs cannot use even when idle, so reserve what you will use. The post on 1 GiB pages has the GRUB steps and the verification output.
Sub-NUMA clustering and NPS modes
Not every package is uniform inside. A large processor places cores, cache slices and memory controllers on an on-die interconnect, so some cores sit nearer some controllers. Firmware can expose that structure as extra NUMA nodes: sub-NUMA clustering on Intel Xeon, and the NPS, nodes per socket, setting on AMD EPYC. With it, a socket splits into two or four nodes, each interleaving memory only over the channels nearest to it. Local latency falls, and a node-bound job reaches a fraction of the socket's peak bandwidth, because it uses a fraction of the channels.
You recognize it by finding more NUMA nodes than sockets in lscpu or numactl --hardware, with a distance matrix that has small values inside a socket and large ones across sockets. Software then has to place threads and data by node even on a single-socket machine, because the distances are real. A latency-sensitive service with a node-sized footprint gains from more nodes, with each instance pinned to one node and its memory. A job that streams a huge shared array with threads on every core prefers the single-node mode, where interleaving across all channels gives full bandwidth with no placement work. Measure STREAM and a latency test under each mode on your hardware. The setting lives in firmware and takes a reboot, so do not change it without a reason and a measurement. The post on sub-NUMA clustering and NPS has a libnuma program that groups nodes by distance.
CXL memory and tiers
Compute Express Link adds memory over PCIe-class links. A Type 3 expander gives byte-addressable, cache-coherent memory that Linux presents as a NUMA node with memory and no CPUs, at a larger distance than local DRAM. Its latency is higher than a local DIMM and its bandwidth is bounded by the link width, and both must be measured. The existing tools apply: numactl --membind or numa_alloc_onnode places cold data on it, and --preferred on the DRAM node spills overflow to it.
The kernel can manage the tier. With /sys/kernel/mm/numa/demotion_enabled set to 1, reclaim demotes cold pages to the slower node instead of swapping them, and with kernel.numa_balancing=2 it promotes hot pages back up. The pgdemote_* and pgpromote_* counters in /proc/vmstat show how much movement happens. Tiering suits skewed access, with a small hot set and a long cold tail. It does not suit a uniform random workload over the whole footprint, since half its accesses always go to the slow tier. A DRAM-based expander is volatile, and the tier should not be confused with persistent memory. The post on CXL memory covers the details.
Putting it together: a worked case
Take a numerical kernel that runs over two 8 GiB arrays on a two-socket machine with 64 hardware threads, and suppose that its throughput is well below what STREAM predicts. This is the order of investigation, with the evidence each step produces. None of the steps below quote a result, because the results are your machine's.
First, classify the loop. It performs one multiply-add per two loaded doubles, an arithmetic intensity of about 0.06 FLOP per byte, far left of any ridge. It is bandwidth-bound, so the target is STREAM Triad on the same thread count, not the processor's peak FLOP rate. Run Triad with OMP_PROC_BIND=spread and record it as the ceiling.
Second, check the topology. numactl --hardware shows two nodes and a distance of 21 against 10. No clustering is enabled. dmidecode confirms every channel is populated at the rated speed, so the ceiling is the real one.
Third, check placement. The program allocates with malloc and fills both arrays in a serial loop, so first touch put everything on node 0. numastat -p <pid> confirms it: all of the process's memory is on node 0. Half the threads read remote memory, and node 0's controllers and the interconnect carry all the traffic. The fix is the parallel first-touch loop with the same static schedule as the compute loop and pinned threads. After the change, numastat -p shows memory split across the nodes in proportion to the threads.
Fourth, check the pages. With 16 GiB of data touched in order, the TLB reach is not a big problem for a sequential kernel, but a gather in the same program is. perf stat -e dTLB-loads,dTLB-load-misses shows a high miss count for the run. Advising the arrays with MADV_HUGEPAGE after allocating with 2 MiB alignment, and before the parallel first touch, reduces the misses and can be confirmed in AnonHugePages. The order matters here: advise first, then touch in parallel, so each huge page is placed whole by the thread that touches it first.
Fifth, check the kernel. If the process was started before pinning and the scheduler moved threads, numa_hint_faults and numa_pages_migrated rise during the run. With explicit placement and pinned threads, balancing has nothing to repair, and for a latency-sensitive neighbor on the same machine its faults are a cost. Compare the run with kernel.numa_balancing at 0 and at 1.
Sixth, re-measure against the ceiling. If the kernel is now close to Triad, stop. If it is not, the next suspects are the access pattern, a stride that aliases with the channel interleave, or a thread count past the knee. Each step produced a number to compare, and the order matters because an earlier problem hides a later one: huge pages cannot help a loop that is waiting on remote memory.
The full program is a short extension of the earlier first-touch listing, and its structure is the template for most NUMA-aware kernels:
#define _GNU_SOURCE
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#define N (1UL << 30) /* 8 GiB of doubles per array */
#define HUGE (2UL << 20)
static double *alloc_huge(size_t n) {
void *p = aligned_alloc(HUGE, n * sizeof(double));
if (!p) exit(1);
madvise(p, n * sizeof(double), MADV_HUGEPAGE); /* before first touch */
return p;
}
int main(void) {
double *a = alloc_huge(N), *b = alloc_huge(N);
#pragma omp parallel for schedule(static)
for (size_t i = 0; i < N; i++) { a[i] = 1.0; b[i] = 2.0; }
double dot = 0.0;
#pragma omp parallel for schedule(static) reduction(+:dot)
for (size_t i = 0; i < N; i++) dot += a[i] * b[i];
printf("dot=%.1f\n", dot);
free(a);
free(b);
return 0;
}The sum is 2.0 for each of 1,073,741,824 elements, which a double represents exactly:
dot=2147483648.0Build with gcc -O3 -march=native -fopenmp kernel.c -o kernel and run it as OMP_NUM_THREADS=64 OMP_PROC_BIND=spread OMP_PLACES=cores ./kernel. Each of the three decisions in the file is visible in the source: allocation aligned for huge pages, advice before the touch and a first touch whose schedule matches the compute loop.
A decision table
The table maps symptoms to the next measurement and the usual fix.
| Symptom | Measure | Usual fix |
|---|---|---|
| STREAM Triad far below the computed peak | dmidecode, thread count, pinning | Populate all channels, fix configured speed, spread threads |
| Parallel run scales poorly past one socket | numastat -p, numa_maps | Parallel first touch, per-node instances, --interleave for shared data |
| Remote latency dominates a pointer-heavy loop | numactl --hardware, loaded latency | Bind threads and memory to one node, or replicate data per node |
High dTLB-load-misses with a large random working set | perf stat DTLB events | MADV_HUGEPAGE, hugetlbfs, or 1 GiB pages |
| Tail-latency spikes after enabling THP | compact_stall in /proc/vmstat | defrag to defer or never, or reserve huge pages |
| Memory moves between nodes during a run | numa_pages_migrated | Pin threads and bind memory, or turn off balancing |
| Fewer huge pages than requested | HugePages_Total, dmesg | Reserve at boot, per node, and free fragmented memory |
| Strided loop wastes bandwidth | Lines touched against elements used | Change layout so a loop's fields share cache lines, pad power-of-two strides |
Who this guide does not fit
Several readers should skip most of it, and the reasons are specific.
A single-socket desktop or laptop has one NUMA node, so the placement sections do not apply. The bandwidth and huge-page material still does, and the first-touch discussion is irrelevant. Soldered LPDDR memory in phones and many embedded boards has a fixed configuration, and the channel count is a product specification rather than something you can change.
Programs whose working sets fit in cache never reach memory, so the guide's ceiling is not their ceiling. A compute-bound kernel past the ridge of its roofline gains nothing from any of it. Check the working-set sweep and the roofline first, and stop there if the loop is on a high plateau.
Cloud and virtualized environments limit what you can do. Hypervisors may hide hardware counters, so the TLB events can be unavailable, and they may present a flat topology that is not the physical one, so NUMA effects exist and cannot be seen. Instance types that span sockets give you remote memory without a way to control it, unless the provider exposes the topology to the guest. Check what lscpu and numactl --hardware show inside the guest before assuming anything. Containers inherit the host's topology but can be restricted by cpuset limits, so a bind may fail with Invalid argument when a node is not in the cgroup's allowed set. Orchestrators such as Kubernetes expose alignment through CPU manager and topology manager policies, and not through numactl.
Latency-sensitive services need caution with the automatic features: transparent huge pages with direct compaction and NUMA balancing can both add stalls, and the right default for such a service is often to disable or defer them, and reserve what is needed explicitly. Systems with a small, unpredictable workload mix are better served by transparent huge pages and balancing than by static reservations, since a reserved pool is memory no one else can use.
GPU memory has its own model, with separate bandwidth, pages and placement, and none of this guide's tools apply to device memory. Finally, this guide describes Linux on x86-64. Other architectures and operating systems share the ideas, but the page sizes, the counters and the names differ, and the details must be checked against their own documentation.
Sources worth keeping open
The kernel documentation is the primary source for the interfaces used here: the hugetlbpage guide, the Transparent Hugepage Support guide, the NUMA memory policy document and the [sysctl reference for numa_balancing](https://docs.kernel.org/admin-guide/sysctl/kernel.html). The numa(3) man page documents libnuma. The STREAM benchmark's reference page states its rules, and Ulrich Drepper's paper What Every Programmer Should Know About Memory remains the best long treatment of the hardware behind all of it.


