ByteGuideHub
Systems & Kernel Engineering • • 13 min read

Self-Hosted eBPF-Based Kernel Memory Tiering with CXL: A Practical Guide to Page Migration and Hot/Cold Data Placement

Implement CXL memory tiering on Linux using eBPF for page access profiling. Step-by-step guide to demotion/promotion policies and NUMA-aware hot/cold data placement for memory-hungry workloads.

Sponsored / Ad Space

Self-Hosted eBPF-Based Kernel Memory Tiering with CXL: A Practical Guide to Page Migration and Hot/Cold Data Placement

Quick Summary (TL;DR)

  • Goal: Build a self-hosted memory tiering controller that keeps hot pages on local DRAM and cold pages on slower, cheaper CXL-attached memory.
  • Mechanism: Use eBPF tracepoints/kprobes to profile per-page access frequency and recency, aggregate a “heat score” in BPF maps, and hand decisions to a user-space controller.
  • Migration: Move pages between NUMA nodes (DRAM ↔ CXL) with move_pages() / migrate_pages(), applying hysteresis to avoid thrashing.
  • Requirements: Linux 6.1+ (CXL + tiering maturity), CONFIG_CXL_*, CONFIG_NUMA, CONFIG_BPF_SYSCALL, a CXL memory device (or numa=fake= for testing).
  • Watch out for: Migration thrashing, CPU overhead from sampling, and incorrect NUMA node masks.

Introduction: Why CXL Memory Tiering Matters

Memory-hungry workloads — in-memory databases, JVMs, ML feature stores, Redis clusters — are increasingly capacity-bound, not compute-bound. DRAM is expensive and physically constrained by DIMM slots. CXL (Compute Express Link) changes the economics: CXL-attached memory lets you add terabytes of capacity that the CPU can address coherently, at lower cost and higher latency than local DRAM.

The catch: CXL memory is typically ~1.5–3× slower than local DRAM for latency-sensitive access. Naively placing all data on CXL memory tanks performance. The answer is tiering — treat DRAM and CXL memory as tiers, and continuously place hot pages on DRAM while cold pages live on CXL.

Traditional kernel tiering (e.g., DAMON, the memory tiering NUMA demotion paths) is powerful but rigid. eBPF gives you programmable, low-overhead instrumentation to define your own hot/cold policy — without patching the kernel. This guide walks you through building a production-ready eBPF-based tiering controller from the ground up.

Prerequisites and System Requirements

Before you start, verify your platform supports the full stack.

ComponentMinimumRecommendedNotes
Kernel5.16 (basic CXL)6.1+6.1+ has stable CXL region + tiering support
eBPF5.46.1+BTF + CO-RE recommended (CONFIG_DEBUG_INFO_BTF=y)
CXL device1 memory device2+ devices / interleaveRoot port + memory device via cxl CLI
Toolchainclang 12, libbpfclang 15+, libbpf 1.xFor CO-RE eBPF programs
NUMACONFIG_NUMA=yCONFIG_NUMA_BALANCING optionalCXL appears as a NUMA node

Required kernel configs (verify with grep CONFIG_X /boot/config-$(uname -r)):

CONFIG_CXL_BUS=y
CONFIG_CXL_PCI=y
CONFIG_CXL_MEM=y
CONFIG_CXL_REGION=y
CONFIG_NUMA=y
CONFIG_BPF_SYSCALL=y
CONFIG_BPF_EVENTS=y
CONFIG_DEBUG_INFO_BTF=y

Install the toolchain (Debian/Ubuntu example):

sudo apt install -y clang llvm libbpf-dev linux-tools-common \
    bpftool libelf-dev zlib1g-dev pkg-config

If you don’t yet have CXL hardware, you can simulate a tier using a fake NUMA node — invaluable for testing the controller logic:

# Boot with a fake 4GB NUMA node (testing only)
# Add to kernel cmdline:
numa=fake=4G

Understanding CXL Memory Topology on Linux

Linux exposes CXL memory as one or more NUMA nodes with no CPUs attached. Local DRAM is typically node 0; CXL memory appears as node N with higher access latency. Confirm the topology:

# List NUMA nodes and their memory
numactl -H

# Inspect CXL devices and regions
cxl list -M -R

A typical output shows DRAM on node 0 (e.g., 64GB) and CXL memory on node 1 (e.g., 256GB). The key insight: Linux already knows the latency hierarchy via node distances.

cat /sys/devices/system/node/node*/distance
# node 0: 0 10 20
# node 1: 10 0 20   <- node 1 is CXL, distance 10 from DRAM

The following diagram shows the flow from page access to tier decision:

flowchart TD
    A[Workload page access] --> B[eBPF tracepoint / kprobe<br/>handle_mm_fault]
    B --> C[Aggregate heat score<br/>in BPF hash map]
    C --> D{User-space controller<br/>reads map periodically}
    D -->|Heat >= promote_threshold| E[Promote: migrate to DRAM node 0]
    D -->|Heat <= demote_threshold| F[Demote: migrate to CXL node 1]
    D -->|Between thresholds| G[Hold - hysteresis band]
    E --> H[move_pages syscall]
    F --> H
    G --> D
    H --> A

Profiling Page Access with eBPF

We need two signals per page: frequency (how often it’s touched) and recency (when it was last touched). The cleanest low-overhead source is the handle_mm_fault function (faults on first touch / eviction) combined with periodic sampling. For a production system, sample rather than trace every access.

Here’s a minimal eBPF program that records a fault timestamp and count per virtual page, keyed by (pid, page-aligned addr):

// profile.bpf.c
#include <vmlinux.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

struct page_key {
    __u32 pid;
    __u64 vaddr;   // page-aligned
};

struct page_stats {
    __u64 last_access_ns;
    __u64 access_count;
};

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1048576);
    __type(key, struct page_key);
    __type(value, struct page_stats);
} page_map SEC(".maps");

SEC("kprobe/handle_mm_fault")
int BPF_KPROBE(handle_fault, struct vm_area_struct *vma, unsigned long addr)
{
    struct page_key key = {};
    key.pid = bpf_get_current_pid_tgid() >> 32;
    key.vaddr = addr & ~0xFFFULL;   // align to 4KB page

    struct page_stats *st = bpf_map_lookup_elem(&page_map, &key);
    __u64 now = bpf_ktime_get_ns();
    if (st) {
        st->access_count++;
        st->last_access_ns = now;
    } else {
        struct page_stats init = { .last_access_ns = now, .access_count = 1 };
        bpf_map_update_elem(&page_map, &key, &init, BPF_NOEXIST);
    }
    return 0;
}

char LICENSE[] SEC("license") = "GPL";

Compile with CO-RE and load it. The user-space controller reads page_map every interval (e.g., 1s) via bpf_map_lookup_and_delete_batch or iteration, computes a heat score, and decides migrations.

Performance note: Attaching to handle_mm_fault is cheap for most workloads but can be heavy for fault-storm workloads (e.g., first-touch of large mmaps). Consider sampling (attach to a fraction of faults using bpf_get_prandom_u32()) or use perf_event sampling on PERF_COUNT_SW_PAGE_FAULTS for high-throughput systems.

Designing Demotion and Promotion Policies

The heart of tiering is the policy — when to move a page up or down. Use a heat score that blends frequency and recency:

heat = w_freq * log2(access_count + 1) + w_recency * exp(-age_seconds / tau)

Where tau is a decay constant (e.g., 30s). The controller compares heat against two thresholds with a hysteresis band to prevent thrashing:

Policy ParameterTypical ValuePurpose
promote_threshold0.75Move to DRAM when heat exceeds this
demote_threshold0.25Move to CXL when heat drops below this
hysteresis_gap0.5Gap between thresholds prevents flapping
scan_interval1–5sController loop period
max_migrations_per_cycle500–2000Rate-limit migrations
tau (decay)30sRecency weighting

Demotion (DRAM → CXL) should be aggressive but rate-limited: when DRAM is under pressure, demote the coldest pages. Promotion (CXL → DRAM) should be conservative: only promote pages that have proven hot across multiple intervals, because promotion competes for scarce DRAM.

sequenceDiagram
    participant W as Workload
    participant K as Kernel (eBPF)
    participant C as Controller
    participant M as Migration Engine
    W->>K: page fault on vaddr
    K->>K: update heat in BPF map
    loop every scan_interval
        C->>K: read page_map batch
        K-->>C: (pid, vaddr, count, last_access)
        C->>C: compute heat, classify
        alt heat >= promote_threshold
            C->>M: promote(vaddr -> node0)
        else heat <= demote_threshold
            C->>M: demote(vaddr -> node1)
        end
        M->>W: page now on target tier
    end

Implementing NUMA-Aware Hot/Cold Data Placement

Migration uses the move_pages(2) syscall, which moves pages belonging to a process to specified NUMA nodes. You must translate the vaddr from the BPF map into a page index in the target process’s address space. The controller runs as a privileged helper and operates on the target PID:

// Migration core (user-space)
#include <numaif.h>

int migrate_page(pid_t pid, unsigned long vaddr, int target_node) {
    void *pages[1] = { (void *)vaddr };
    int status[1];
    int nodes[1] = { target_node };

    long rc = move_pages(pid, 1, pages, nodes, status, MPOL_MF_MOVE);
    if (rc < 0) {
        perror("move_pages");
        return -1;
    }
    if (status[0] != 0) {
        // status[0] is the errno for that page (e.g., -ENOENT if not resident)
        return status[0];
    }
    return 0;
}

Critical NUMA considerations:

  1. Verify page residency first. move_pages(pid, count, pages, NULL, status, 0) returns the current node of each page without moving it. Skip pages already on the target node.
  2. Respect the workload’s mempolicy. If the target process has an explicit set_mempolicy binding, your migrations may be overridden. Coordinate with the workload owner or use MPOL_MF_MOVE_ALL carefully.
  3. Batch aggressively. move_pages accepts an array — move hundreds of pages per syscall to amortize overhead.
  4. Never migrate kernel pages, hugepages-in-use, or pinned pages — the syscall returns -EBUSY or -EACCES; log and skip.

A simple placement helper for workloads that don’t set policy explicitly:

# Bind the workload to DRAM node 0 preferentially, allowing CXL fallback
numactl --cpunodebind=0 --membind=0,1 ./my_workload

Step-by-Step: Building and Deploying the Tiering Controller

Step 1 — Build the eBPF object:

clang -O2 -g -target bpf -D__TARGET_ARCH_x86 \
    -c profile.bpf.c -o profile.bpf.o
bpftool gen skeleton profile.bpf.o > profile.skel.h

Step 2 — Write the controller loop (pseudocode):

// controller.c (abridged)
while (running) {
    sleep(scan_interval);
    // 1. Read and clear page_map in batches
    // 2. For each (pid, vaddr, stats):
    //      heat = score(stats, now)
    //      if (heat >= promote_threshold && current_node == CXL_NODE)
    //          queue_promotion(pid, vaddr, DRAM_NODE);
    //      else if (heat <= demote_threshold && current_node == DRAM_NODE)
    //          queue_demotion(pid, vaddr, CXL_NODE);
    // 3. Apply rate limit, then batch move_pages()
}

Step 3 — Deploy as a systemd service with the capabilities it needs:

# /etc/systemd/system/cxl-tierd.service
[Unit]
Description=CXL eBPF Memory Tiering Controller
After=cxl.service

[Service]
ExecStart=/usr/local/bin/cxl-tierd --scan-interval=2 \
    --promote-threshold=0.75 --demote-threshold=0.25 \
    --max-migrations=1000
Restart=on-failure
# CAP_SYS_NICE + CAP_BPF + CAP_SYS_ADMIN for move_pages on other PIDs
AmbientCapabilities=CAP_BPF CAP_SYS_ADMIN CAP_SYS_NICE
CapabilityBoundingSet=CAP_BPF CAP_SYS_ADMIN CAP_SYS_NICE

[Install]
WantedBy=multi-user.target

Step 4 — Validate the deployment:

sudo systemctl start cxl-tierd
sudo bpftool prog list | grep handle_fault   # confirm attach
sudo numastat -p $(pgrep my_workload)         # verify distribution

Monitoring and Tuning the Tiering System

You cannot tune what you don’t measure. Track these signals continuously:

MetricSourceHealthy Signal
Pages on DRAM vs CXLnumastat -p <pid>Hot set stays on DRAM
Migration rateController logsBelow max_migrations
Migration latency (p99)move_pages timing< 100µs/page batch
eBPF overheadbpftool prog profile< 2% CPU
Thrash ratePromote+demote of same pageNear zero
Workload p99 latencyApp metricsImproves vs. no-tiering

Tuning loop: Start with conservative thresholds (promote=0.8, demote=0.2) and long scan intervals (5s). If DRAM pressure is high but promotions are rare, lower promote_threshold. If you see pages bouncing back and forth, widen the hysteresis gap and increase tau.

# Quick health check
sudo numastat -p $(pgrep -f my_workload)
# Look for: fewer pages on node 1 (CXL) than total working set

Comparison of Tiering Approaches

ApproachControlOverheadKernel Req.Best For
eBPF controller (this guide)Full, programmableLow–moderate6.1+Custom policies, heterogeneous workloads
DAMONTunable, kernel-nativeVery low5.15+Set-and-forget, minimal ops
NUMA balancing (auto)AutomaticLow3.x+General workloads, no CXL tuning
Manual numactlStaticNoneAnyPredictable, small working sets
Cgroup memory tieringPer-cgroupLow6.1+Containerized multi-tenant

Choose eBPF when you need workload-specific heat scoring, integration with your own observability, or rapid policy iteration. Choose DAMON when you want a battle-tested kernel subsystem with minimal ops overhead. They are not mutually exclusive — a hybrid (DAMON for coarse demotion, eBPF for fine promotion) is a legitimate production pattern.

Conclusion and Best Practices

CXL memory tiering turns a latency penalty into a capacity win — if you place pages intelligently. eBPF gives you the instrumentation and policy flexibility to do exactly that, without forking the kernel.

Best practices to carry into production:

  • Start with simulation. Validate the controller against numa=fake= before touching real CXL hardware.
  • Design for hysteresis from day one. Thrashing is the #1 failure mode; wide thresholds and decay constants prevent it.
  • Rate-limit migrations. A runaway controller can saturate memory bandwidth; cap max_migrations_per_cycle.
  • Measure eBPF overhead. Sample, don’t trace every fault, on high-throughput workloads.
  • Coordinate with NUMA policy. Respect explicit set_mempolicy bindings; never fight the workload owner.
  • Observe continuously. numastat, bpftool prog profile, and app latency are your feedback loop.
  • Keep the controller restartable. Stateless decision-making (recompute heat each cycle) makes recovery trivial.

With these in place, you get a self-hosted, programmable tiering layer that keeps your hot data fast and your cold data cheap — exactly the promise CXL was built to deliver.


FAQ

Q: What is CXL memory tiering and why use eBPF for it? CXL memory tiering uses CXL-attached memory as a slower, cheaper tier alongside DRAM. eBPF provides low-overhead, programmable kernel instrumentation to profile page accesses and drive migration decisions without modifying kernel code.

Q: Which Linux kernel version is required? You need Linux 5.16+ for basic CXL support and 6.1+ for mature memory tiering. For eBPF profiling, 5.4+ is sufficient, but we recommend 6.1+ for full functionality.

Q: How does eBPF collect page access information? eBPF programs attach to tracepoints or kprobes such as handle_mm_fault, or use the perf subsystem to sample page faults, tracking access patterns per virtual address in BPF maps.

Q: What are the key metrics for hot/cold classification? Access frequency (faults per page per interval), recency (time since last access), and access type (read/write). These aggregate into a heat score used for tier decisions.

Q: How do I ensure NUMA-aware placement when migrating pages? Use move_pages() or migrate_pages() with node masks targeting the correct NUMA node. Confirm the CXL node is in the memory tier hierarchy and respect workload set_mempolicy bindings.

Q: Can I use DAMON instead of eBPF? Yes — DAMON is a kernel-native data access monitor suitable for set-and-forget tiering. eBPF offers more flexibility for custom policies and user-space integration; a hybrid of both is a valid production pattern.

Q: What are the risks of aggressive page migration? Thrashing (pages bouncing between tiers), increased latency, and CPU/bandwidth overhead. Mitigate with hysteresis bands, rate limits, and conservative promotion thresholds.

Q: How can I verify tiering is working? Use numastat, perf, and custom eBPF scripts to track migrations and memory distribution. Confirm hot pages reside on DRAM, cold pages on CXL, and workload performance improves.

Sponsored / Ad Space