ebpfbased distributed tracing in Linux Kernel 6.8

The 03:14 AM Panic

My phone buzzed against the nightstand at 03:14 AM. The alert was blunt: node us-east-1a-app-worker-09f was unresponsive, the kernel log was flooding with RCU stall detected on CPU, and packet loss on the primary interface had crossed ninety-eight percent. By the time I SSH’d into the serial console, the system was unresponsive to anything short of an IPMI reset. The culprit wasn’t a runaway database query or a saturating TCP exhaustion attack. It was a shiny new observability agent utilizing ebpfbased distributed tracing that had quietly chewed through all available kernel memory over four days of production traffic, eventually exhausting the ring buffer allocations and triggering a cascading failure down the tracing subsystem.

We installed the tooling to get visibility into microservice latency, but instead, we bought ourselves a ticket to kernel-panic town. Kernel 6.8 brought some welcome performance additions to the BPF subsystem, but it also made it easier than ever to shoot yourself in the foot with unbounded memory allocations and poorly tracked map references. If you are pushing over 100,000 packets per second through your ingress paths and blindly attaching tracing programs without understanding the actual overhead, you are playing Russian roulette with your uptime.

The Hidden Tax of Context Switches and Tracepoints

Marketing slide decks love to tell you that eBPF runs safely inside the kernel with zero overhead. They omit the part about context switching penalties, instruction cache misses, and the sheer cost of hitting traditional tracepoints under heavy I/O loads.

Tracepoints vs. Fentry/Fexit Overheads

Traditional tracepoints rely on static registration points embedded throughout the kernel source tree. When your program triggers a tracepoint, the kernel executes a registration stub that marshals arguments, calls a probe function, and hands data off to a perf buffer or ring buffer. This path involves significant register saving and restoring, not to mention the memory barrier overhead.

Kernel 6.8 improves upon fentry and fexit attachments, which compile directly to direct function calls using BPF trampoline generation. Instead of navigating the generic tracepoint infrastructure, the JIT compiler patches the target kernel function prologue directly to jump straight into your BPF bytecode.

/* Example of a low-overhead fentry program targeting tcp_connect in Kernel 6.8 */
#include <vmlinux.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

SEC("fentry/tcp_connect")
int BPF_PROG(tcp_connect_trace, struct sock *sk)
{
    __u16 family = BPF_CORE_READ(sk, __sk_common.skc_family);
    if (family != AF_INET)
        return 0;

    // Direct telemetry collection without tracepoint argument marshaling overhead
    return 0;
}

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

Instruction Cache Thrashing in High-Throughput Paths

Even with trampolines, attaching hooks to high-frequency functions like __netif_receive_skb on an interface handling 150k RPS will destroy your CPU cache. Every time a packet arrives, your BPF instructions are loaded into the L1/L2 instruction cache, evicting vital networking stack code. We measured a consistent 4.2 percent CPU regression on our networking workers simply by attaching a poorly optimized tracing program that walked the socket lookup tables on every incoming segment.

To measure the actual CPU cycles consumed by your ebpfbased distributed tracing daemon, you need to rely on bpftool and perf rather than guessing based on user-space telemetry:

# Check runtime stats and instruction counts for loaded BPF programs
bpftool prog show id 4892
# Output will display run_time_ns and run_cnt, allowing you to calculate cost per execution

Memory Leak Anatomy in BPF Maps

Writing a BPF program that loads successfully is easy. Writing one that doesn’t leak memory over a two-week lifecycle is apparently an art form. The most common silent killer in production environments is the unmanaged map lifecycle, particularly when dealing with dynamic socket tracking or distributed tracing context propagation maps.

Orphaned File Descriptors and Pinned Maps

When a user-space daemon initializes its tracing pipeline, it creates maps via syscalls, populates them, and pins them to the BPF virtual filesystem (/sys/fs/bpf/). If the user-space process crashes, gets killed by the OOM killer, or terminates without properly cleaning up, the maps remain allocated in kernel memory as long as a reference exists or they remain pinned. Worse, if the daemon spawns worker threads that create maps without setting appropriate `max_entries` caps, you will watch kernel slab memory vanish into the ether.

/* Defining a hash map with strict sizing to prevent unbounded allocation */
struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 1048576); // Hard cap at 1 million entries
    __type(key, __u64);
    __type(value, struct trace_context);
} active_traces SEC(".maps");

Map-in-Map Reference Count Traps

Kernel 6.8 supports complex map-in-map structures for efficient per-CPU routing and fast context switching. However, if your inner maps are dynamically replaced while outer map entries still point to them, the inner maps can be orphaned without their reference counts hitting zero correctly. You end up with dangling pointers in the kernel address space that cannot be freed until the entire outer map is destroyed.

Inspect your current map allocations and pin states manually to verify you aren’t leaking resources:

# List all active BPF maps and their current memory consumption
bpftool map show
# Inspect specific map definitions and pin locations
bpftool map pin id 304 /sys/fs/bpf/my_pinned_map

Ring Buffers vs. Perf Buffers Under Extreme Pressure

Older kernel versions forced you to use BPF_MAP_TYPE_PERF_EVENT_ARRAY, which was notorious for dropping events, causing user-space CPU spikes due to constant polling, and wasting memory on pre-allocated per-CPU buffers that sat idle on quiet cores while busy cores dropped data.

Kernel 6.8 Ring Buffer Accounting Improvements

Kernel 6.8 features refined memory accounting for the newer `BPF_MAP_TYPE_RINGBUF`. Unlike perf buffers, ring buffers share memory between kernel and user space via a single mmap region, reducing memory overhead and eliminating the need to copy events per CPU. However, if your user-space consumer thread gets blocked or scheduled out by the CFS scheduler, the ring buffer fills up instantly.

When a ring buffer fills up, the kernel drops incoming tracing events by default. If your tracing program attempts to force allocations using bpf_ringbuf_output with BPF_RB_NO_WAKEUP flags incorrectly, you can trigger soft lockups as the kernel spins trying to find free space.

/* Safe ring buffer submission with error checking */
struct trace_event *e;
e = bpf_ringbuf_reserve(&rb_map, sizeof(*e), 0);
if (!e) {
    // Drop gracefully or increment an internal dropped-packet counter
    __sync_fetch_and_add(&dropped_events_total, 1);
    return 0;
}

e->timestamp = bpf_ktime_get_ns();
e->pid = bpf_get_current_pid_tgid() >> 32;

bpf_ringbuf_submit(e, 0);

Tuning Ring Buffer Memory Limits

Never leave ring buffer sizes at default values when deploying ebpfbased distributed tracing across multi-socket systems. You must size them based on the maximum burst rate of your application layer, keeping memory consumption strictly bounded.

struct {
    __uint(type, BPF_MAP_TYPE_RINGBUF);
    __uint(max_entries, 16 * 1024 * 1024); // Exactly 16MB shared buffer
} rb_map SEC(".maps");

User-Space Tail Calls vs. Kernel-Side Execution Paths

Architectural decisions made during the design of your tracing agent dictate whether your system survives a traffic spike or grinds to a halt. The debate between handling logic entirely inside kernel-side BPF programs versus delegating parsing and aggregation to user space via tail calls determines your failure domain.

The Danger of Excessive Tail Calls

Kernel 6.8 allows up to 33 nested tail calls within a single execution path. While this sounds like a feature that enables modular, clean BPF code, each tail call introduces function pointer lookups in the program array map. If you chain tail calls across multiple parsing layers for complex protocol inspection on every packet, you blow past your instruction budgets and risk triggering the verifier’s worst-case path analysis limits.

More importantly, passing massive context structures between tail calls using stack memory will trigger verifier rejections or stack overflow warnings in the kernel log:

Bpf program is too large. Processed 1048576 insn

Kernel-Side Aggregation vs. User-Space Streaming

If your tracing agent streams every single span and packet trace directly to user space via ring buffers, you are shifting the CPU burden from the kernel to the user-space daemon, which must deserialize, parse, and aggregate the raw telemetry. Under high loads, the user-space consumer falls behind, the ring buffer fills up, and your tracing drops critical data precisely when you need it during an incident.

The correct approach for ebpfbased distributed tracing in production environments is aggressive in-kernel aggregation using per-CPU hash maps, passing only summarized metrics to user space every few seconds.

/* In-kernel aggregation example using per-CPU hash maps */
struct {
    __uint(type, BPF_MAP_TYPE_PERCPU_HASH);
    __uint(max_entries, 8192);
    __type(key, __u32);   // Service ID or port
    __type(value, __u64); // Cumulative latency or request count
} latency_aggregates SEC(".maps");

SEC("fentry/ip_rcv")
int aggregate_latency(struct sk_buff *skb)
{
    __u32 key = 8443;
    __u64 *val, delta = 100; // Calculated latency delta

    val = bpf_map_lookup_elem(&latency_aggregates, &key);
    if (val) {
        __sync_fetch_and_add(val, delta);
    } else {
        bpf_map_update_elem(&latency_aggregates, &key, &delta, BPF_ANY);
    }
    return 0;
}

Production Mitigations and Verification Checklist

If you manage infrastructure running Kernel 6.8, you cannot rely on defaults. You need an enforced operational checklist to prevent tracing agents from taking down your production clusters.

Enforcing Strict Resource Limits

Before loading any BPF object file into the kernel, your loader application must verify memory allocations and lock limits. Unprivileged BPF should be disabled entirely across your fleet via sysctl configurations.

# Disable unprivileged BPF to prevent unauthorized loading
sysctl -w net.core.bpf_jit_enable=1
sysctl -w kernel.unprivileged_bpf_disable=1

Automated Validation and Monitoring Script

Run a cron job or sidecar daemon that queries the kernel for active BPF memory usage and alerts your on-call rotation before allocations spiral out of control. Never assume a daemon will clean up after itself.

#!/usr/bin/env bash
set -euo pipefail

# Check total pinned BPF maps and compare against safety thresholds
MAX_PINNED_MAPS=50
CURRENT_MAPS=$(bpftool map show | grep -c "id")

if [ "$CURRENT_MAPS" -gt "$MAX_PINNED_MAPS" ]; then
    echo "CRITICAL: BPF map count ($CURRENT_MAPS) exceeds safety threshold!"
    exit 2
fi

echo "OK: BPF map count is within nominal operating parameters."
exit 0

Observability is not free. Every byte of telemetry extracted from the kernel carries a cost in CPU cycles, memory allocations, and stability risks. Treat your tracing code with the same rigorous review process you apply to your core kernel modules, or prepare for another 03:14 AM page.

Related Articles

Explore more insights and best practices:

Leave a Comment