Skip to content
systemcoding.dev
Networking

The Complete Guide to eBPF for Network Programmers

A full guide to eBPF for network work on Linux: programs, maps, the verifier, XDP, tc, sockets, tracing, testing, debugging and running it safely in production.

29 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and GNU logos.

For most of Linux's history, changing how the kernel treats network packets meant one of two things. You wrote a kernel module, and accepted that a bug would crash the machine and that every kernel release might break you. Or you kept your code in user space and paid to move every packet across the boundary. eBPF removes that choice. It lets you load small programs into the running kernel, at precise points in the network path, after the kernel has proven they are safe. The programs share data with ordinary processes through maps, they are compiled to native code, and they can be replaced while traffic flows. This guide is the map of the subject for network programmers, on Linux 6.12 with clang 18, libbpf 1.5 and bpftool 7.5. It explains the execution model, the toolchain, the hooks that matter for networking, how to parse packets without offending the verifier, how to get data out, how to test and debug, and how to operate eBPF programs responsibly. Every listing is written to compile as shown, and the focused posts in this cluster go deeper on each hook.

You should be comfortable with C and with the basics of IP, TCP and UDP. You do not need prior eBPF experience; each term is defined where it first appears. The guide assumes a Linux machine where you can use sudo, and ideally a virtual machine or a network namespace for experiments, since a mistake in a packet filter can cut your own connection.

Why network programmers care

A packet's trip through Linux passes dozens of decision points: the driver's receive ring, the generic receive path, traffic control, netfilter, routing, the socket layer, the transport protocols. Each is a place where you might want to look at, change, count, drop or redirect traffic, and each used to need its own mechanism, configured through its own tools: tc filters, iptables rules, socket options, kernel patches. eBPF gives you one programming model across many of those points. The same language, the same maps and the same tooling work at the driver, at the queueing layer, at the socket and on the kernel's own internal events.

The practical consequences are what make it worth learning:

  • Speed where it matters. An XDP program decides a packet's fate in the driver, before the kernel allocates the sk_buff that the rest of the stack uses. Dropping unwanted traffic there costs far less than dropping it later, because the allocation, the header parsing and the routing lookup never happen.

  • Logic the stack does not offer. Custom load balancing, flow sampling, protocol-specific filtering and per-tenant accounting become a few dozen lines of C instead of a kernel patch.

  • Visibility. Tracepoints and kernel probes show retransmits, drops, queue lengths and latencies as they happen, in production, without rebuilding anything.

  • Safety. The verifier rejects a program that could crash the kernel, loop forever or read memory it should not touch. A bug becomes a load-time error, not an outage.

None of that is free. The language is restricted, the verifier is strict and the debugging tools are younger than the ones you know. The sections below are as much about working within those limits as about the capabilities.

The execution model

An eBPF program starts as C source in a restricted dialect. You compile it with clang for the bpf target, which produces an ELF object holding bytecode, instructions for a small virtual machine with eleven 64-bit registers, a 512-byte stack and no heap. You hand that object to the kernel through the bpf(2) system call, usually via libbpf, and the kernel does four things in order.

First it creates the maps the program declares. Then it runs the verifier, a static analyzer that explores every possible execution path and rejects the program if any path could read out of bounds, dereference a null pointer, use an uninitialized value, call a helper with wrong arguments or fail to terminate. Next the JIT compiler translates the verified bytecode into native machine code for the host CPU, so the program runs at close to native speed. Finally the kernel attaches the program to a hook, a specific place where events occur, and from then on the program runs each time the event happens.

Three terms recur everywhere:

  • A program type fixes the hook, the context structure the program receives and the meaning of its return value. An XDP program receives a struct xdp_md and returns a verdict. A traffic-control program receives a struct __sk_buff.

  • A helper is a function the kernel exports to programs of certain types, for example bpf_map_lookup_elem, bpf_ktime_get_ns or bpf_redirect. A program cannot call arbitrary kernel functions; it uses the helpers its type allows. The bpf-helpers(7) man page lists them.

  • A map is kernel memory that programs and user-space processes share. It is the only place a program keeps state between runs, because its stack disappears when it returns.

The limits are worth memorizing, because they shape how you write code. The stack is 512 bytes. Programs may have loops only if the verifier can prove a bound; bounded loops have been accepted since Linux 5.3, and the bpf_loop helper from 5.17 handles larger iteration counts. The verifier gives up on a program that needs more than one million instructions' worth of analysis. Tail calls, which jump from one program to another through a program-array map, are limited to 33 in a chain. A program cannot allocate memory, take a lock it did not get through a helper, or sleep (sleepable programs are a separate, restricted class).

BTF and CO-RE: running the same binary on different kernels

Kernel internals change between versions: structures gain fields, fields move, names change. A program that reads struct sk_buff fields directly would break whenever the layout shifted. eBPF solves this with BTF, BPF Type Format, a compact description of the kernel's own types that the running kernel exposes at /sys/kernel/btf/vmlinux when built with CONFIG_DEBUG_INFO_BTF=y, and CO-RE, "compile once, run everywhere". With CO-RE, clang records which fields your program touches, and libbpf adjusts those accesses at load time to match the real layout of the running kernel. You can generate a header of all the kernel's types with:

Shell
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h

Programs that use only the stable UAPI structures, such as xdp_md and __sk_buff, do not need CO-RE for those. CO-RE matters when you read kernel-internal structures, such as in tracing programs. A prerequisite for either is a kernel with BTF; every mainstream distribution kernel from the last few years has it, and ls /sys/kernel/btf/vmlinux confirms it.

The toolchain and project layout

A small eBPF project has two halves: a kernel-side C file compiled to bytecode, and a user-space C program that loads it, attaches it and reads its maps. The tools:

  • clang with the bpf target compiles the kernel side. Use -O2; the verifier works with optimized code, and unoptimized builds often fail on stack use. Add -g so BTF debug information is emitted.

  • libbpf is the user-space library that opens objects, relocates them against the running kernel, loads them and manages maps and links. It is the supported way to write loaders in C.

  • bpftool inspects and manipulates everything: loaded programs, maps, links, BTF. It also generates skeletons, C headers that wrap your object file in a typed API.

  • iproute2 (ip, tc) can also load XDP and tc objects directly, which is convenient for experiments.

A Makefile for a project with one program looks like this:

Makefilemakefile
CLANG   ?= clang
ARCH    := $(shell uname -m | sed 's/x86_64/x86/; s/aarch64/arm64/')

guard: guard.c guard.skel.h
	$(CC) -O2 -Wall guard.c -lbpf -o guard

guard.skel.h: guard.bpf.o
	bpftool gen skeleton $< > $@

guard.bpf.o: guard.bpf.c
	$(CLANG) -O2 -g -target bpf -D__TARGET_ARCH_$(ARCH) -c $< -o $@

Run make as an ordinary user and load as root. The skeleton step is the convenience worth having: bpftool gen skeleton produces a header with a struct containing a pointer for each program and map, plus functions to open, load, attach and destroy. The loader below uses one.

A first complete program: count and drop

The program parses Ethernet, IPv4 and UDP headers, drops UDP datagrams addressed to port 9999, and counts packets passed and dropped in a per-CPU array map. Per-CPU means each CPU has its own copy of every value, so the program updates it without atomics or contention, and user space adds the copies when it reads.

guard.bpf.cc
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

#define BLOCKED_PORT 9999

enum { STAT_PASS, STAT_DROP, STAT_MAX };

struct {
    __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
    __uint(max_entries, STAT_MAX);
    __type(key, __u32);
    __type(value, __u64);
} stats SEC(".maps");

static __always_inline void bump(__u32 idx)
{
    __u64 *v = bpf_map_lookup_elem(&stats, &idx);
    if (v)
        *v += 1;
}

SEC("xdp")
int guard(struct xdp_md *ctx)
{
    void *data = (void *)(long)ctx->data;
    void *data_end = (void *)(long)ctx->data_end;

    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end)
        goto pass;
    if (eth->h_proto != bpf_htons(ETH_P_IP))
        goto pass;

    struct iphdr *ip = (void *)(eth + 1);
    if ((void *)(ip + 1) > data_end)
        goto pass;
    if (ip->protocol != IPPROTO_UDP)
        goto pass;

    __u32 ip_len = ip->ihl * 4;
    if (ip_len < sizeof(*ip))
        goto pass;

    struct udphdr *udp = (void *)ip + ip_len;
    if ((void *)(udp + 1) > data_end)
        goto pass;

    if (udp->dest == bpf_htons(BLOCKED_PORT)) {
        bump(STAT_DROP);
        return XDP_DROP;
    }

pass:
    bump(STAT_PASS);
    return XDP_PASS;
}

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

Several habits in that file recur in every network program. Each header's end is compared with data_end before the header is read, because the verifier requires proof that the access stays inside the packet. Anything the program does not understand takes the pass label, so it never drops traffic it was not meant to touch. Ports in headers are in network byte order, so the comparison uses bpf_htons. And the helper that bumps a counter is static __always_inline, so the verifier sees one flat program instead of a function call.

The loader uses the generated skeleton:

guard.cc
#include <bpf/libbpf.h>
#include <net/if.h>
#include <stdio.h>
#include <unistd.h>
#include "guard.skel.h"

static __u64 sum(int fd, __u32 key, int ncpu)
{
    __u64 vals[ncpu];
    __u64 total = 0;

    if (bpf_map_lookup_elem(fd, &key, vals))
        return 0;
    for (int i = 0; i < ncpu; i++)
        total += vals[i];
    return total;
}

int main(int argc, char **argv)
{
    int ifindex = if_nametoindex(argc > 1 ? argv[1] : "eth0");
    if (!ifindex) {
        perror("if_nametoindex");
        return 1;
    }

    struct guard_bpf *skel = guard_bpf__open_and_load();
    if (!skel) {
        fprintf(stderr, "load failed\n");
        return 1;
    }

    struct bpf_link *link = bpf_program__attach_xdp(skel->progs.guard, ifindex);
    if (!link) {
        fprintf(stderr, "attach failed\n");
        guard_bpf__destroy(skel);
        return 1;
    }

    int fd = bpf_map__fd(skel->maps.stats);
    int ncpu = libbpf_num_possible_cpus();

    for (int i = 0; i < 3; i++) {
        sleep(1);
        printf("pass=%llu drop=%llu\n",
               (unsigned long long)sum(fd, 0, ncpu),
               (unsigned long long)sum(fd, 1, ncpu));
    }

    bpf_link__destroy(link);
    guard_bpf__destroy(skel);
    return 0;
}
Shell
make
sudo ./guard eth0
Text
pass=18 drop=0
pass=41 drop=3
pass=77 drop=5

The numbers depend on your traffic, and the drops appear when something sends UDP to port 9999. The loader holds the program alive through the link: when the process exits or bpf_link__destroy runs, the program detaches automatically, which is the safe default for experiments, because a forgotten program cannot keep dropping traffic after your tool is gone.

Maps in depth

Maps are where eBPF programs keep their memory, and choosing the right type is half of the design. The types you will meet most in networking:

TypeShapeTypical use
BPF_MAP_TYPE_ARRAYFixed array, integer keysConfiguration, small tables
BPF_MAP_TYPE_PERCPU_ARRAYOne copy per CPUCounters without contention
BPF_MAP_TYPE_HASHHash table, any fixed-size keyPer-flow or per-address state
BPF_MAP_TYPE_LRU_HASHHash that evicts the least recently used entryUnbounded key sets such as client addresses
BPF_MAP_TYPE_LPM_TRIELongest-prefix matchRouting tables, CIDR allow and deny lists
BPF_MAP_TYPE_DEVMAPInterface indexesXDP_REDIRECT targets
BPF_MAP_TYPE_XSKMAPAF_XDP socketsRedirect to user space
BPF_MAP_TYPE_SOCKHASHSockets by keySocket-to-socket redirection
BPF_MAP_TYPE_RINGBUFEvent streamSending records to user space

Three rules keep map code correct. First, always check lookup results for null: a lookup returns a pointer or nothing, and the verifier refuses to let you dereference it unchecked. Second, sizes are fixed at creation: a full hash map rejects new keys, so a program must decide what a failed insertion means, and an attacker who can create unbounded keys can fill the table; the LRU type is the usual defense. Third, updates race: two CPUs may see a miss and try to insert the same key, so use the BPF_NOEXIST flag on insertion and look the key up again if it fails, and update values in place with atomic operations or per-CPU maps.

Maps are shared by name or by file descriptor between programs, and they can be pinned in the BPF filesystem at /sys/fs/bpf so they outlive the process that created them. Pinning lets an agent restart without losing its counters, and lets a second tool read them. Memory for maps is charged to the creating cgroup on current kernels, so a large map can fail to create inside a constrained container even where it works on the host.

Parsing packets without upsetting the verifier

Every network program parses, and parsing is where the verifier's rules bite. The pattern is the same at each layer: take the pointer from the end of the previous header, compare its end with data_end, return early on failure, and only then read fields. The proof the verifier needs is a comparison between a pointer derived from data and data_end, on the path where the read happens.

A few rules prevent most verifier failures:

  • Use the same pointer variable for the check and the access. A recomputed pointer is, to the verifier, a different value.

  • Bound variable offsets from both sides before using them in pointer arithmetic. The IPv4 header length ihl * 4 is between 20 and 60 once you reject values below 20.

  • After any helper that changes the packet, such as bpf_xdp_adjust_head, forget every packet pointer and reload data and data_end from the context.

  • Keep parsing in static __always_inline helpers. A non-inlined function is verified separately, and a bounds proof does not carry across the call in the way you might expect.

  • Do not index into the packet with an unchecked value read from the packet itself.

When a load fails, the log names the problem. The classic message is invalid access to packet, off=36 size=2, R1(id=0,off=36,r=0), which says the program read two bytes at offset 36 while only r bytes were proven in range. The access is valid only when off + size <= r. Compile with -g and ask libbpf for a larger log, and the log annotates each instruction with its source line, which turns a wall of text into a pointer at the guilty statement.

XDP: the earliest hook

XDP runs in the network driver's receive path, before the kernel builds an sk_buff. The program sees the raw frame and returns one of five verdicts: XDP_PASS to continue into the stack, XDP_DROP to discard the frame, XDP_TX to send it back out the interface it arrived on, XDP_REDIRECT to send it to another interface, a CPU or a socket, and XDP_ABORTED for an error path that also fires a tracepoint.

It attaches in three modes. Native (driver) mode runs inside the driver and is the fast one; it needs driver support, which many common server drivers have. Generic mode runs after the skb exists, works on any interface and is meant for development. Offload mode runs on a smart NIC. With iproute2 you request a mode explicitly, which is the safe choice because it fails loudly when native mode is unavailable instead of falling back to the slow path:

Shell
sudo ip link set dev eth0 xdpdrv obj guard.bpf.o sec xdp
sudo ip link show dev eth0
sudo ip link set dev eth0 xdp off

XDP's strengths are also its limits. It sees only ingress, has no socket or connection-tracking context because none exists yet, and must keep per-packet work short because it runs in the receive softirq on the CPU handling that queue: a slow program there causes drops in the card's ring. The earlier posts on what XDP is and on writing your first program cover the details.

Three XDP techniques deserve a place in your toolbox. Redirect with bpf_redirect_map and a devmap forwards frames between interfaces inside the driver, batching per target; the Ethernet addresses are the program's job because XDP does no neighbor resolution. XDP_TX with header rewriting underlies stateless load balancers: a program hashes the flow, wraps the packet in an outer IP header addressed to a backend using bpf_xdp_adjust_head, and sends it back out, with replies returning directly from the backend. AF_XDP redirects selected frames into an XSKMAP so a user-space process receives them from shared-memory rings without a copy in zero-copy mode, which lets you write logic in ordinary C or Rust for flows that do not fit in a verifier-sized program.

Traffic control: the hook with the skb

Traffic control (tc) runs after the driver has built the sk_buff. A program there gets a struct __sk_buff, a stable view of the skb with fields such as protocol, mark, len and ifindex, and it can attach on egress as well as ingress, which XDP cannot. The program type is BPF_PROG_TYPE_SCHED_CLS, placed in a section named tc, and it returns TC_ACT_OK to continue or TC_ACT_SHOT to drop.

The classic attachment uses a clsact qdisc, which exists only to provide ingress and egress attachment points:

Shell
sudo tc qdisc add dev eth0 clsact
sudo tc filter add dev eth0 ingress bpf da obj icmp_drop.bpf.o sec tc
sudo tc filter show dev eth0 ingress

The da flag selects direct action, which makes the program's return value the verdict. Linux 6.6 added tcx, a dedicated attachment with defined ordering and BPF links that detach automatically when the owner exits, attached from libbpf with bpf_program__attach_tcx. Prefer it on kernels that have it, because priority-based filters from different tools can overwrite each other. tc programs are the right home for logic that needs skb metadata, for egress policy, and for packet rewriting with helpers such as bpf_skb_store_bytes and bpf_l3_csum_replace, which fix checksums incrementally. After any such helper the packet pointers are invalid and must be reloaded, just as after bpf_xdp_adjust_head.

Sockets and cgroups: policy at the application boundary

Below the packet hooks sit hooks that see sockets. A socket filter program, attached with setsockopt(SO_ATTACH_BPF), decides how many bytes of each incoming packet one socket receives, which is how capture tools discard unwanted frames before copying them. Socket filters cannot use direct packet access and read with bpf_skb_load_bytes.

Cgroup hooks attach to a control group and apply to every process in it. BPF_CGROUP_INET4_CONNECT and its siblings run when a process calls connect, and can rewrite the destination address, which is how a service mesh redirects traffic transparently. BPF_PROG_TYPE_CGROUP_SKB filters packets entering and leaving the group's sockets, a per-container firewall. sockops programs react to TCP events such as a connection becoming established, and combined with a BPF_MAP_TYPE_SOCKHASH and an sk_msg program they can move data between two local sockets directly, skipping the loopback path. These hooks need a cgroup file descriptor; attach to a narrow cgroup while testing, not the root.

Seeing inside the stack: tracing programs

Not every network program changes traffic. Many only observe. Tracepoints are stable, documented hooks the kernel developers maintain, such as tcp:tcp_retransmit_skb, skb:kfree_skb and sock:inet_sock_set_state. kprobes attach to almost any kernel function by name, which is flexible and fragile, since functions are renamed and inlined between releases. fentry and fexit probes use BTF to attach with lower overhead and typed arguments.

Here is the shape of a tracepoint program that counts TCP retransmits per remote address, using the BTF-generated vmlinux.h:

retrans.bpf.cc
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>

struct key {
    __u32 daddr;
    __u16 dport;
    __u16 pad;
};

struct {
    __uint(type, BPF_MAP_TYPE_LRU_HASH);
    __uint(max_entries, 8192);
    __type(key, struct key);
    __type(value, __u64);
} retrans SEC(".maps");

SEC("tp/tcp/tcp_retransmit_skb")
int on_retransmit(struct trace_event_raw_tcp_event_sk_skb *ctx)
{
    if (ctx->family != 2)
        return 0;

    struct key k = { .pad = 0 };
    __builtin_memcpy(&k.daddr, ctx->daddr, sizeof(k.daddr));
    k.dport = ctx->dport;

    __u64 one = 1;
    __u64 *v = bpf_map_lookup_elem(&retrans, &k);
    if (v)
        __sync_fetch_and_add(v, 1);
    else
        bpf_map_update_elem(&retrans, &k, &one, BPF_NOEXIST);
    return 0;
}

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

Aggregating inside the kernel, as here, keeps the cost per event constant and the map bounded. The quickest way to try an idea is bpftrace, which compiles one-liners such as tracepoint:tcp:tcp_retransmit_skb { @[ntop(args->daddr)] = count(); }. Use it to explore, then move to a compiled libbpf program for anything that runs unattended.

Getting data out

A program has three ways to deliver results. Polling a map is the simplest: the program aggregates, user space reads on an interval. It suits counters and tables. Streaming events suits records that matter individually, such as a connection attempt or a drop with its reason. The tool for that is the ring buffer, BPF_MAP_TYPE_RINGBUF, added in Linux 5.8: one buffer shared by all CPUs, with a reserve-then-submit API that writes the record in place with no extra copy. The older per-CPU perf buffer remains for kernels before 5.8. A third option is **bpf_printk**, which writes to the kernel trace pipe; use it only for debugging, since it is slow and shared.

events.bpf.cc
struct event {
    __u32 saddr;
    __u16 dport;
    __u16 pad;
    __u64 ts_ns;
};

struct {
    __uint(type, BPF_MAP_TYPE_RINGBUF);
    __uint(max_entries, 256 * 1024);
} events SEC(".maps");

static __always_inline void emit(__u32 saddr, __u16 dport)
{
    struct event *e = bpf_ringbuf_reserve(&events, sizeof(*e), 0);
    if (!e)
        return;                       /* ring full: the event is lost */
    e->saddr = saddr;
    e->dport = dport;
    e->pad = 0;
    e->ts_ns = bpf_ktime_get_ns();
    bpf_ringbuf_submit(e, 0);
}

Every reserved record must be submitted or discarded on every path, or the verifier rejects the program. The map's max_entries is the ring size in bytes and must be a power of two multiple of the page size. User space drains it with ring_buffer__new and ring_buffer__poll. A full ring returns null from reserve, so keep a per-CPU counter of lost events and report it beside the data; otherwise a quiet stretch in the output could mean either no traffic or an overloaded reader.

Testing programs before they see traffic

Loading an untested packet filter on a live interface is how people lock themselves out of servers. eBPF has a better way: BPF_PROG_TEST_RUN, which runs a loaded program once or many times on packet bytes you supply and returns the verdict, without attaching it anywhere. libbpf wraps it as bpf_prog_test_run_opts. The test below feeds the guard program two hand-built packets and checks the verdicts:

guard_test.cc
#include <bpf/bpf.h>
#include <bpf/libbpf.h>
#include <linux/bpf.h>
#include <stdio.h>
#include <string.h>
#include "guard.skel.h"

static int run(int prog_fd, unsigned dport_hi, unsigned dport_lo)
{
    unsigned char pkt[47] = {
        0x02,0x00,0x00,0x00,0x00,0x02, 0x02,0x00,0x00,0x00,0x00,0x01, 0x08,0x00,
        0x45,0x00,0x00,0x21, 0x00,0x00,0x40,0x00, 0x40,0x11,0x00,0x00,
        0xc0,0x00,0x02,0x01, 0xc0,0x00,0x02,0x0a,
        0x9c,0x40, 0,0, 0x00,0x0d, 0x00,0x00,
        'h','e','l','l','o'
    };
    pkt[36] = (unsigned char)dport_hi;
    pkt[37] = (unsigned char)dport_lo;

    unsigned char out[128];
    LIBBPF_OPTS(bpf_test_run_opts, opts,
        .data_in = pkt, .data_size_in = sizeof(pkt),
        .data_out = out, .data_size_out = sizeof(out),
        .repeat = 1);

    if (bpf_prog_test_run_opts(prog_fd, &opts))
        return -1;
    return (int)opts.retval;
}

int main(void)
{
    struct guard_bpf *skel = guard_bpf__open_and_load();
    if (!skel)
        return 1;
    int fd = bpf_program__fd(skel->progs.guard);

    printf("port 9999: retval=%d (XDP_DROP is %d)\n", run(fd, 0x27, 0x0f), XDP_DROP);
    printf("port 9998: retval=%d (XDP_PASS is %d)\n", run(fd, 0x27, 0x0e), XDP_PASS);

    guard_bpf__destroy(skel);
    return 0;
}
Text
port 9999: retval=1 (XDP_DROP is 1)
port 9998: retval=2 (XDP_PASS is 2)

The packet is 47 bytes: 14 of Ethernet, 20 of IPv4 with a total length of 33, 8 of UDP and 5 of payload, with the destination port at offsets 36 and 37. The test needs no network card, no traffic and no risk, and it fits in a continuous-integration job on any kernel with the feature. Add cases for short frames, other EtherTypes, IP options and fragments, since those are the inputs that break filters in production. For a program that updates maps, read the maps after the run to check the side effects too.

Debugging and inspecting

Four tools cover most debugging. bpftool lists what is loaded (bpftool prog show, bpftool map show, bpftool net show for attachments), dumps maps (bpftool map dump name stats), and prints the translated or JIT-compiled instructions (bpftool prog dump xlated name guard, ... jited ...). **bpf_printk** and bpftool prog tracelog give you printf-style output from inside a program, slowly and for development only. Verifier logs, enabled with a higher log level in libbpf or bpftool -d prog load, show the state of every register at every instruction and are the only way to understand a rejection. Kernel statistics, enabled with sysctl -w kernel.bpf_stats_enabled=1, make bpftool prog show report each program's run count and total run time, which answers whether a program is hot, though it costs a little on every run and should be switched off when you finish.

Common verifier rejections, and what they mean:

Message fragmentMeaningUsual fix
invalid access to packetRead beyond the proven rangeAdd or move the data_end check
R0 invalid mem access 'map_value_or_null'Lookup result used without a null checkif (v) before use
back-edge from insn ... to ...Loop the verifier cannot boundUse a constant bound, unroll or bpf_loop
invalid indirect read from stackReading stack bytes never initializedZero the struct before use
math between pkt pointer and register with unbounded min valueVariable offset with no lower boundCompare the offset against a minimum
BPF program is too large or complexity limitToo many instructions or statesSplit with inline helpers or tail calls
unknown func ... or helper call is not allowedHelper not available for this program typeCheck the helper list for the type

When the log is long, read it from the failing instruction upward and find the last place the relevant register's type or range was set. Most of the time the fix is a missing comparison, written once and then used consistently.

Reasoning about performance

This guide gives no throughput numbers, because they depend on the CPU, the driver, the offloads and the work each packet needs, and a figure from someone else's machine says nothing about yours. Reason about cost from mechanism instead, and measure your own.

Cost comes from five sources. Work in the driver path is paid per packet on a single CPU for each receive queue, so spread flows across queues with receive-side scaling. Helper calls have a fixed price; a map lookup computes a hash and may take a bucket lock, so one lookup per packet is normal and ten is a design smell. Contended maps serialize CPUs; per-CPU maps and per-CPU counters remove the contention. Memory access patterns matter: a large hash map misses the CPU cache on every lookup. And verifier-forced code shape, bounds checks and early returns, is usually negligible compared with the memory costs.

To measure, run the real program on the real hardware with real traffic, with kernel.bpf_stats_enabled=1 for per-program run time, and compare total CPU use with and without the program. Watch drops at every layer: ethtool -S for the card's ring, the XDP statistics, and your own counters. An idle CPU with rising card drops points to receive queue imbalance; all CPUs busy means you are out of capacity.

Operating eBPF programs safely

An eBPF program in production is code running inside the kernel on every packet, and it deserves the care of a kernel component.

Privilege. Loading needs capabilities: CAP_BPF for loading programs and creating maps (Linux 5.8 and later), plus CAP_NET_ADMIN for XDP and tc attachment and CAP_PERFMON for tracing. The sysctl kernel.unprivileged_bpf_disabled controls whether unprivileged users may load programs, and hardened systems set it to 1 or 2. Give your agent exactly the capabilities it needs, not root.

Lifetime. Decide whether a program should die with its loader or outlive it. Links, as in the loader above, detach on exit, which is safe. Pinned programs and links in /sys/fs/bpf persist, which suits long-lived filters, and means you must have a removal procedure. Record how to detach in your runbook before deploying: ip link set dev eth0 xdp off, tc filter del, rm of a pinned link.

Failure behavior. Decide what the program does when it cannot decide. The guard program passes anything it does not understand. A firewall might choose the opposite, but that choice must be explicit, because a bug in a drop-by-default program takes the host off the network.

Compatibility. Rely on CO-RE and BTF for kernel-internal access, test on every kernel version you deploy, and check feature availability at load time with libbpf_probe_bpf_prog_type and related probes instead of assuming. Prefer stable hooks, tracepoints over kprobes, wherever you have the choice.

Observability of the programs themselves. Export counters for passes, drops, errors and lost events, and alert on a program that stops being invoked or on a map near capacity. A filter that silently stopped matching is invisible without them.

Upgrades. Replace programs atomically rather than detaching and re-attaching: libbpf links support bpf_link__update_program, and BPF_F_REPLACE serves the same purpose for older attachment types, so traffic never sees a window with no program.

Checking that the machine can run it

Before you write a line, confirm the host has what eBPF needs, because the failures from a missing prerequisite are unhelpful. Three checks cover almost everything. First, the kernel must have been built with the BPF system call and a JIT, and distribution kernels are. You can confirm the system call exists by running bpftool prog show, which fails with a clear message when it does not. Second, BTF must be present for CO-RE programs, so check that /sys/kernel/btf/vmlinux exists. Third, check the sysctls that control access: kernel.unprivileged_bpf_disabled decides whether unprivileged users may load programs, and net.core.bpf_jit_enable should be 1 so programs are compiled to native code instead of interpreted.

For features that vary by kernel version, probe at run time instead of parsing the version string, because distributions backport features into older numbered kernels and the number lies. libbpf offers libbpf_probe_bpf_prog_type and libbpf_probe_bpf_map_type, and bpftool feature probe prints everything the running kernel supports, including which program types, map types and helpers are available to the current user. A loader that probes for the ring buffer and falls back to the perf buffer when it is missing works across a wider range of machines than one that hard-codes a minimum version, and it fails with a clear message when no fallback exists.

A worked scenario: protecting a UDP service

To see how the pieces combine, follow the design of a small defense for a UDP service on port 9999 that is being flooded with garbage from many source addresses. The goal is to drop the flood before it reaches the application while letting legitimate clients through, and to know what is happening.

The first layer is the XDP program in this guide, extended with a hash map of allowed client addresses, filled by the application itself when a client completes a handshake. Packets to port 9999 from addresses not in the map are dropped in the driver; the application never sees them. The map is an LRU hash, so a flood of spoofed sources cannot fill it and lock out real clients, because new entries evict old idle ones, and entries are only created by the user-space process after validation, never by the XDP program itself, so the attacker cannot influence what is allowed.

The second layer is observability. The program keeps per-CPU counters for allowed, dropped and malformed packets, and sends one sampled event per thousand drops through a ring buffer, carrying the source address and a timestamp, so an operator can see who is flooding without drowning in events. A counter of failed ring reservations tells the operator when the sample is incomplete.

The third layer is safe operation. The program is attached with a link and a documented removal command. It fails open for anything it does not understand, because the service is more important than the filter. A test suite runs the program through BPF_PROG_TEST_RUN with packets from allowed and unknown sources, IP options, fragments and truncated frames, and runs on every kernel the fleet uses. And a rollout starts on one host, comparing the application's receive counts with the XDP counters, before it spreads.

Notice what the design does not do. It does not try to track connections or reassemble anything; that stays in the application and the stack. It does not rely on the kernel version beyond features it probes for. And it does not try to be clever: three counters, one map and one verdict are enough to turn an outage into a graph. Most useful eBPF networking programs look like this, small and boring, with the care in the testing and the operating procedure.

A note on terminology you will meet

Documentation and conversations about eBPF mix several names that mean different things, and knowing them saves confusion. BPF originally meant the classic packet filter, and cBPF is the shorthand for it; the instruction set used by tcpdump -d and SO_ATTACH_FILTER is cBPF, and the kernel translates it internally. eBPF is the extended machine this guide covers, and most people now say plain BPF for it. A program is one function in one section of an object; an object is the compiled ELF file containing programs and map definitions; a link is the kernel object that represents an attachment of a program to a hook. Helpers are kernel-exported functions, kfuncs are a newer, less stable class of kernel functions that programs may call, declared through BTF, and you will see them in recent code for tasks that helpers never covered. A skeleton is the generated header wrapping an object. Verifier logs show register states, written like R1=pkt(id=0,off=0,r=14), where the type, offset and verified range describe what the verifier knows about each register at that point.

Reading those register annotations is a skill worth practicing early. pkt means a pointer into the packet, pkt_end is the end pointer, map_value and map_value_or_null describe pointers returned from map lookups, scalar is a plain number with optional known bounds, and ctx is the program's context pointer. When a log says a register is a scalar where you expected a pointer, an earlier arithmetic operation lost the type, and the fix is almost always to restructure the code so the pointer is derived once and then only compared and dereferenced.

Choosing eBPF or something else

You want to...Reach forWhy
Drop or steer packets as early as possibleXDPRuns before skb allocation
Apply policy on egress or use skb metadatatc or tcxHas the skb and both directions
Filter what one socket receivesSocket filterKernel discards before copying
Rewrite connect destinations per containerCgroup connect hooksApplies to every process in the group
Move data between local socketssockmap with sk_msgSkips the loopback path
Observe retransmits, drops, state changesTracepointsStable and cheap
Receive selected frames in user spaceAF_XDPZero-copy rings, kernel keeps the NIC
Own the whole NIC in user spaceDPDKKernel bypass, separate stack
Stateful firewalling and NATnftablesConnection tracking, mature tooling
Capture for analysisAF_PACKET or libpcapPortable, no verifier

eBPF is not a replacement for the whole stack. The netfilter and conntrack machinery does stateful work that is awkward to rebuild in maps, and a user-space process is the right home for logic too large for the verifier or too complex to test in a restricted language. The best designs split the work: eBPF for the fast, early, simple decisions and counters, user space for policy, management and anything heavy.

Limits and where to go next

Know what eBPF will not do for you. Programs cannot sleep, allocate or run unbounded work. The programming model differs between kernel versions, so a feature you read about may need a newer kernel than you run; every post in this cluster states the version where a feature appeared. Packet processing at the XDP level handles single frames, and anything needing reassembly, TLS or application state belongs elsewhere. Debugging remains harder than in user space, which is why testing with BPF_PROG_TEST_RUN and keeping programs small are not optional habits.

The natural path from here follows the cluster. Start with what eBPF and XDP are, then write a first XDP program and count packets per address with a hash map. Learn to read verifier errors, because you will meet them constantly. Add tc for egress, then ring buffers for events, then redirect and AF_XDP when you need to leave the kernel. Sockets and sockmaps come after that, and the verifier's internals last, since by then you will have met every rule it enforces. At each step keep the discipline that this guide repeats: write the smallest program, test it on crafted packets, load it on a namespace interface, watch it with bpftool, and only then trust it with real traffic.

Also inKernels
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.