Memory Has a Location

CPU series, post 5 of 5

Memory has a location. A server can have free memory and still swap.

Jeremy Cole described it in 2010. A MySQL box had 64 GB of RAM, two quad-core CPUs and a 48 GB InnoDB buffer pool. It swapped while memory sat free. His post, The MySQL “swap insanity” problem and the effects of the NUMA architecture, traced it to NUMA. The kernel placed pages on the node of the CPU that touched them. One node filled up. The kernel then preferred to reclaim memory there, which meant swapping, over taking free pages from the other node. The fix was a change to how the process launched: numactl --interleave=all.

Five years later, Stewart Smith noted that the MySQL bug about it, filed in 2010, was still relevant. He also noted that binding a workload to fewer nodes could sometimes help, because of mutex and cache-line traffic. So interleaving is not a universal cure. This post builds Cole’s box as a model so you can see exactly what interleaving fixes and what it does not.

One limit first. The VM I test on has a single NUMA node, so I can model NUMA here but I cannot measure a remote access. Every latency in this post is cited, and every program labeled a model is a model.

How much does remote memory cost?

Here are four measurements. Treat the ratio as sturdier than any single number, because these runs come from different hardware and some do not name the model.

Platform Local Remote Source
Xeon E5-2680 v3 (Haswell), 2 sockets 77 to 78 ns about 122 ns Yunming Zhang, 2018
2-socket server, Intel MLC 3.9a 108.2 ns 195.7 ns Steve Scargall, “Linux NUMA Distances Explained”, 2022
2-socket Xeon, model not stated 81.9 ns 129.0 ns PostgreSQL list attachment
Xeon 6, across compute dies inside one socket about 131 ns (derived) 157.4 ns one hop, 181.5 ns two hops Chips and Cheese

On the two-socket rows, remote latency runs 1.6 to 1.8 times local. In the PostgreSQL attachment, remote bandwidth is about half of local, roughly 30.5 against 63.5 GB/s. The firmware also publishes a distance table, the SLIT, which you can read with numactl --hardware. In Scargall’s measurement the SLIT said 21, which reads as 2.1 times local. The measured ratio was about 1.8. The table is a hint. It is not a measurement.

Now look at the last row. That is one socket. On Intel Xeon 6, crossing a compute-die boundary to another memory controller costs about 26 ns over local, and a second crossing adds roughly 24 ns more. Post 3 said memory has a location. Here is the evidence that a socket is not the boundary any more.

Add CXL memory and the map grows a CPU-less node. Measured load latency depends on the device. One study found CXL 50% to 300% slower than local DIMMs, with ASIC devices around 200 to 300 ns and FPGA prototypes near 400 ns (arXiv 2411.02814). Another found CXL tail latency less stable than DRAM’s (arXiv 2409.14317). Treat CXL as a capacity tier, not as free bandwidth.

Who decides where a page lives?

Linux decides at the moment a page is first touched. The default policy puts it on the node of the CPU doing the touching. That is a sensible rule for a program whose threads stay put. It is a trap for a big process that one thread initializes, as Cole’s MySQL did.

Here is that box as a model. It has two nodes of 32 GB each and a 48 GB buffer pool, and it uses the Haswell latencies from the table, 78 ns local and 122 ns remote. One thread on node 0 loads the pool, and then threads on both nodes read it uniformly. Three policies decide where the pages go: strict first-touch, where a full node reclaims before it spills; first-touch that spills to the other node; and interleave. A second workload has each thread load and read its own half. The model counts swapped gigabytes, the share of reads that are remote, the average latency and how much of the pool sits on the busiest node. It places pages and multiplies latencies, nothing more.

# numa_policy.py: where do pages land, and what does each policy cost? A model of the mechanism, not a measurement.
LOCAL_NS, REMOTE_NS = 78, 122        # Xeon E5-2680 v3, two sockets (Yunming Zhang, 2018)
NODE_GB, POOL_GB = 32, 48            # Cole's box: 64 GB over two nodes, a 48 GB buffer pool

def place(policy):
    """GB resident on node 0, node 1, and swapped, when one thread on node 0 touches the whole pool first."""
    first = min(POOL_GB, NODE_GB)
    if policy == "first-touch, strict":      # node 0 fills, then the kernel reclaims instead of spilling
        return [first, 0], POOL_GB - first
    if policy == "first-touch, spill":       # node 0 fills, the rest goes to node 1
        return [first, POOL_GB - first], 0
    return [POOL_GB / 2, POOL_GB / 2], 0     # interleave: alternate pages across nodes

def row(workload, policy, resident, swapped, remote):
    avg = (1 - remote) * LOCAL_NS + remote * REMOTE_NS
    busiest = 100 * max(resident) / sum(resident)
    print(f"{workload:26} {policy:22} {swapped:5.0f} GB {100 * remote:7.0f}% {avg:7.0f} ns {busiest:12.0f}%")

print(f"{'workload':26} {'policy':22} {'swapped':>8} {'remote':>8} {'avg':>10} {'busiest node':>13}")

# Workload 1: one thread loads the pool, then threads on both nodes read it uniformly.
for policy in ("first-touch, strict", "first-touch, spill", "interleave"):
    res, swp = place(policy)
    local = sum(0.5 * r / sum(res) for r in res)     # half the readers sit on each node
    row("one loader, all read", policy, res, swp, 1 - local)

# Workload 2: each thread loads and reads its own half, so first touch puts each half next to its owner.
row("each thread, own half", "first-touch", [POOL_GB / 2, POOL_GB / 2], 0, 0.0)
row("each thread, own half", "interleave", [POOL_GB / 2, POOL_GB / 2], 0, 0.5)
workload                   policy                  swapped   remote        avg  busiest node
one loader, all read       first-touch, strict       16 GB      50%     100 ns          100%
one loader, all read       first-touch, spill         0 GB      50%     100 ns           67%
one loader, all read       interleave                 0 GB      50%     100 ns           50%
each thread, own half      first-touch                0 GB       0%      78 ns           50%
each thread, own half      interleave                 0 GB      50%     100 ns           50%

Look at the first row. Strict first-touch swaps 16 GB while all of node 1 sits empty, and it puts 100% of the pool on one node. That is Cole’s failure. The model charges nothing for reading the swapped 16 GB, which flatters that row. Look at the next two rows. Spilling to node 1 removes the swap and balances the pool to 67 and 33, and interleave balances it to 50 and 50. Neither changes the remote fraction. In all three rows, half the reads are remote and the average read costs 100 ns, because the readers sit evenly on both nodes and the pool is shared.

So interleave fixes the swap and the imbalance. It does not fix locality, and the model says why: when every thread reads everything, there is no placement that makes reads local. Now the last two rows. When each thread works on its own half, first-touch puts each half next to its owner, remote reads drop to zero and the average falls to 78 ns. Interleave on that workload throws locality away and costs 100 ns. The same policy is a cure in one workload and a loss in the other. That is Smith’s point, in a table.

Is the 22 ns difference worth a policy? Per access, no. At millions of accesses per second per thread it adds up to whole cores, and in the model it is a 28% increase over local. These are Haswell numbers on a toy workload, so read the shape, not the figure.

You can override the default. numactl offers bind, preferred, interleave and weighted-interleave policies, and the numa(7) page documents the underlying calls and the /proc/<pid>/numa_maps format. The kernel also runs automatic NUMA balancing, which samples access patterns and moves pages or tasks toward where they get used. It helps many workloads and can hurt a few.

How do you check what your own machine believes? This script reads sysfs, with nothing to install: the node list, each node’s CPUs and memory, the distance row, and whether automatic balancing is on.

# topology.py: read the NUMA map your kernel believes in. Works on any Linux box, no tools to install.
import glob, os, re

def node_id(path):
    return int(path.rsplit("node", 1)[1])

nodes = sorted(glob.glob("/sys/devices/system/node/node[0-9]*"), key=node_id)
print(f"NUMA nodes: {len(nodes)}")
for n in nodes:
    cpus = open(f"{n}/cpulist").read().strip()
    mem_kb = int(re.search(r"MemTotal:\s+(\d+)", open(f"{n}/meminfo").read()).group(1))
    dist = open(f"{n}/distance").read().split()
    kind = "memory-only (no CPUs)" if not cpus else "cpus + memory"
    print(f"  {os.path.basename(n)}: cpus [{cpus or 'none'}], {mem_kb / 1048576:.1f} GiB, distance row {dist}, {kind}")

balancing = open("/proc/sys/kernel/numa_balancing").read().strip()
print(f"automatic NUMA balancing (kernel.numa_balancing): {balancing}")
NUMA nodes: 1
  node0: cpus [0-1], 4.0 GiB, distance row ['10'], cpus + memory
automatic NUMA balancing (kernel.numa_balancing): 0

On this VM the answer is one node holding both CPUs and 4 GiB, a distance row of just 10, and balancing off. A VM that reports one node cannot show a NUMA effect, which is exactly the point of the next section. Run it on your own server and expect at least two nodes, perhaps with a CPU-less CXL node among them.

Latency matrix of a two-node machine and the firmware distance table
Figure 5.1. Local and remote latency on a two-node machine, and why the firmware table is only a hint.

What breaks inside a VM

A VM with all its vCPUs on node 0 and half its memory on node 1 pays remote prices on half its accesses, and nothing on the host will look like a CPU problem. Red Hat’s tuning guide says to configure vCPU pinning, NUMA memory binding and emulator-thread pinning together, and its worked example maps vCPUs to nodes one to one. Pin the vCPUs alone and you can make things worse, because the memory stays wherever it landed.

So the first rule is to fit the VM inside one node. If it cannot fit, expose the topology. libvirt lets you define guest NUMA cells with <numa>, so the guest kernel can place its own memory and threads sensibly. A guest that thinks it runs on a flat machine will make flat-machine decisions on a machine that is not flat. The model above is the reason. A guest that sees one flat node has no way to keep a thread near its memory.

Placing a VM on a NUMA host: fit in one node, or expose the cells
Figure 5.2. Placing a VM on a NUMA host: fit it in one node, or expose the cells.

Huge pages join the list for a reason that comes straight from architecture. With nested paging, a TLB miss walks the guest’s page tables and then the host’s. With four levels in each, one miss can take up to 24 memory references (Intel SDM Volume 3C covers EPT). Huge pages of 2 MB or 1 GB shrink both walks, and they stay resident, so the guest’s memory does not wander. Allocate them per node, so they land where the vCPUs run. The guest backed the 512 MiB array in Post 3 with huge pages for the same reason, though I cannot see from inside whether the host did.

The sibling thread is a seat at your table

Now switch the threat model. SMT siblings share a core’s execution resources, including the L1 data cache, execution ports and internal buffers. In 2018 and 2019, L1TF and MDS showed that a thread on one sibling could read data belonging to the other. On a host that mixes tenants, the sibling thread is the attacker’s seat, and the blast radius is whoever shares the core.

The kernel’s core scheduling document says the only full mitigation for cross-thread attacks is to disable SMT. Core scheduling offers a middle path. A task gets a cookie through prctl(PR_SCHED_CORE), children inherit it across fork and exec, and the scheduler only co-schedules tasks with matching cookies on one core’s siblings. It landed in Linux 5.14 (LWN). The same document lists what it does not solve, including MDS between a user-mode sibling and a kernel-mode one, and an L1TF attacker inside a guest.

What does it cost? The model below is one core with two SMT siblings. Tenants are groups of runnable tasks, each with its own cookie. SMT off gives 1.0. SMT on gives a gain whenever two tasks are runnable. Core scheduling picks a task, and its sibling may only run a task from the same tenant, so a tenant with a single runnable task gets no partner. The gain of 1.25 is an assumption I made, not a measurement, so change the constant and see how the table moves.

# core_sched.py: what a cookie match costs. One core with two SMT siblings, tasks grouped by tenant. A toy model.
SMT_GAIN = 1.25      # ASSUMPTION: two busy siblings do 1.25x the work of one thread alone. Measure yours.

def throughput(policy, tenants):
    """Expected work per slice on one core. tenants: runnable task count per tenant (one cookie each)."""
    total = sum(tenants)
    if policy == "SMT off":
        return 1.0
    if policy == "SMT on":                       # any two runnable tasks may share the core
        return SMT_GAIN if total >= 2 else 1.0
    # core scheduling: the core picks a task, and its sibling may only run a task with the same cookie
    return sum(n / total * (SMT_GAIN if n >= 2 else 1.0) for n in tenants)

print(f"relative work per core-slice, assuming SMT_GAIN = {SMT_GAIN}")
print(f"{'runnable tasks per tenant':28} {'SMT off':>8} {'SMT on':>8} {'core sched':>11}")
for mix in ([8], [4, 4], [2, 2, 2, 2], [3, 1], [1, 1, 1, 1], [1] * 8):
    label = " + ".join(map(str, mix)) if len(mix) <= 4 else "1 x 8 tenants"
    print(f"{label:28} {throughput('SMT off', mix):8.2f} {throughput('SMT on', mix):8.2f} {throughput('core sched', mix):11.2f}")
relative work per core-slice, assuming SMT_GAIN = 1.25
runnable tasks per tenant     SMT off   SMT on  core sched
8                                1.00     1.25        1.25
4 + 4                            1.00     1.25        1.25
2 + 2 + 2 + 2                    1.00     1.25        1.25
3 + 1                            1.00     1.25        1.19
1 + 1 + 1 + 1                    1.00     1.25        1.00
1 x 8 tenants                    1.00     1.25        1.00

The shape is what matters. When tenants bring several runnable tasks each, core scheduling keeps the whole 1.25. When one tenant is split 3 and 1, a quarter of the picks have no partner and the gain falls to 1.19. When every tenant has one task, core scheduling falls to 1.00, the same as SMT off, and you carry the complexity for nothing. The cost depends on how many runnable tasks each trust group brings per core, which is why the kernel document tells you to measure your own workload.

Real numbers exist from before the merge. Patch-set benchmarks measured a TPC-C drop of 42.65%, or 65.51% with kernel protection on, and a uperf case where core scheduling ran 28.2% slower than SMT turned off. LWN notes that early versions were sometimes worse than disabling SMT outright. Those are development numbers from before the merge, so do not quote them as today’s cost.

Can you even run it? Check the kernel, not the documentation:

$ zcat /proc/config.gz | grep SCHED_CORE
# CONFIG_SCHED_CORE is not set

This VM’s kernel was built without CONFIG_SCHED_CORE, so the prctl would fail here. The feature is a build option, and a distribution that omits it gives you nothing to turn on. Look before you plan around it.

The shelf of things to read next

A few topics did not fit, and each connects back to something earlier. Interrupts have destinations, as Post 1 implied. A network card’s interrupts land on whichever CPU the kernel picked, and if that CPU sits on the wrong socket, every packet pays the remote toll. Look into IRQ affinity. PCIe devices attach to one socket’s root complex, so the same logic applies to NICs and NVMe drives. Deep CPU sleep states save power and add wake latency, which matters for the tail latencies Post 4 measured. For the strictest isolation, libvirt’s real-time guest guide partitions host CPUs and runs with SMT off. And the scheduler itself is changing. sched_ext, merged in Linux 6.12, lets you load a scheduler as a BPF program.

What to carry forward

Memory has a location. So does a vCPU, an interrupt, a drive and the thread that shares your core. Five posts, one chain. Gates built a loop. A timer took the loop back. A scheduler divided one core among many threads. More cores and more channels exposed every serial assumption. A hypervisor stacked a second scheduler on top. NUMA is the bill for all of it, written in nanoseconds per access.

Takeaways

  1. Remote memory costs roughly 1.6 to 1.8 times local latency on two-socket servers and can halve bandwidth; trust ratios over single numbers.
  2. Linux places a page on the node that first touches it, so a full node can swap while another has free memory.
  3. Interleave fixes capacity and balance, not locality; locality needs each page next to its owner.
  4. In a VM, pin vCPUs, bind memory and pin emulator threads together, or size the VM to fit one node.
  5. Core scheduling needs CONFIG_SCHED_CORE, and its cost depends on runnable tasks per trust group.
  6. Run numastat, lstopo and the topology script before you change a policy.

Published November 22, 2026