The Network Plumbing Grows Up

Contents
Three tools shared one network device’s ingress hook through classic tc. One of them stopped seeing packets the moment another arrived, and nobody told it. A third replaced the second’s program without the second finding out, and when the second shut down and cleaned up after itself, it deleted everyone’s programs. On Linux 6.7, four tools sharing the same hook through tcx kept a list the kernel will show to anyone who asks, could not remove each other’s programs, and got ESTALE instead of a silent overwrite when two of them raced. In the same virtual machine, a pod plugged in with netkit, the new device meant to replace veth,
pushed 1.21 million small packets a second out of the node against 1.14 million
for a veth pod running the same BPF program, and two local processes completed a one-byte TCP round trip
in 2.50 µs instead of 3.44 once a sockmap program carried the bytes from
one socket to the other.
None of that is new BPF in the sense of new instructions or new maps. It is the plumbing: where a networking program attaches, who owns the attachment, and which of the kernel’s queues a packet has to sit in on the way. This post is about the plumbing that changed in the last two kernel releases, and the older socket-level plumbing it now sits beside.
This is Part 11 of a series on eBPF, written for C programmers who know what a process, a system call and a socket are, and nothing about kernel internals. Everything here ran on Linux 6.7, released on 7 January, in Ubuntu’s mainline build, with an Ubuntu 23.04 userland: clang 15, and libbpf 1.3 and bpftool 7.3 built from their release tags, because 23.04 ships libbpf 1.1, which predates both new hooks. The output is pasted from those runs, not reconstructed. The note at the end says exactly where and how.
Where the packets were left
Part 8
put programs on the two network hooks most BPF networking is built on. XDP runs in the driver,
before the kernel has built an sk_buff for the packet, and can drop, pass, bounce or redirect it at
almost no cost. tc runs a little later, on the sk_buff itself, on the way in or out of any device:
a BPF_PROG_TYPE_SCHED_CLS program attached as a filter (cls_bpf) to the clsact pseudo-qdisc,
in direct-action mode, so that the program’s return value is the verdict. Everything in that part
was attached the way it had been attached since 2016.
Two things have happened to that picture since. The first is tcx, merged for Linux 6.6 in October: a new way to attach programs at the same ingress and egress points that does not go through tc’s qdisc and filter machinery at all, and the generic multi-program API (“mprog”) it is built on. The second is netkit, merged for 6.7 two weeks ago: a new kind of virtual network device, meant to replace the veth pair that connects nearly every container to its host, whose whole job is to run BPF programs. tcx is Daniel Borkmann’s, netkit Borkmann’s and Nikolay Aleksandrov’s, and both files carry the copyright of Isovalent, the company behind Cilium. Both were written with Cilium’s datapath in mind, and both are too new for any released Cilium to use.
The other half of this post is older and lives one layer up, at sockets. sockmap (4.14) and
sk_msg programs (4.17) can carry bytes from one local socket straight to another. sk_lookup
(5.9) decides which listening socket a new connection belongs to. The cgroup socket-address
hooks (connect4 in 4.17, more since) rewrite the address an application passes to connect(),
which is how a Kubernetes service can be load-balanced without translating a single packet. They are
the parts of BPF networking that never touch a packet header, and the last section shows where all
of it sits in Cilium as of this month.
A hook with no owner
Start with what was wrong. The classic tc model has three objects. A qdisc hangs off the device;
for BPF it is clsact, added in 4.5, which does no queueing at all and exists only to provide an
ingress and an egress attach point. Filters hang off the qdisc, each with a priority (lower
runs first) and a handle, and a cls_bpf filter holds one BPF program. When a packet arrives
the kernel walks the filters in priority order, and in direct-action mode each program’s return
value either decides (TC_ACT_OK to accept, TC_ACT_SHOT to drop, TC_ACT_REDIRECT) or, with
TC_ACT_UNSPEC, says “not mine, ask the next one”.
That was a reasonable design for a classifier inside a traffic-control framework, which is what
cls_bpf was when it arrived in 3.13 running classic BPF. It is a poor design for what tc BPF
became: the attach point of choice for a dozen unrelated tools that each assume the device is
theirs. A CNI plugin, a network policy agent, an observability agent and a service mesh may all want
the same device’s ingress, and nothing in the model knows they are different tools:
- the order is decided by priority numbers each tool picks on its own, with no way to say “run before that program”;
- a filter belongs to the device, not to whoever attached it, so anyone can replace or delete it;
- and the qdisc is shared too, so deleting it, which is the obvious way to clean up, deletes every filter on it.
To make that concrete, here are stand-ins for real tools, built into one object: three programs for classic tc and four for tcx. They do nothing but return a verdict, which is all the experiment needs:
// gate.bpf.c — stand-ins for several tools that all want the same device's ingress hook
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#define TC_ACT_UNSPEC (-1) /* classic tc: "not my decision, ask the next filter" */
#define TC_ACT_OK 0 /* classic tc: "accept, stop here" */
/* Classic tc (cls_bpf in direct-action mode), attached with bpf_tc_attach(). */
SEC("tc")
int watch_old(struct __sk_buff *skb) /* a monitoring agent: looks, never decides */
{
return TC_ACT_UNSPEC;
}
SEC("tc")
int guard_old(struct __sk_buff *skb) /* a firewall: allowed traffic is accepted at once */
{
return TC_ACT_OK;
}
SEC("tc")
int count_old(struct __sk_buff *skb) /* an accounting tool: looks, never decides */
{
return TC_ACT_UNSPEC;
}
/* tcx (Linux 6.6), attached with bpf_program__attach_tcx(). */
SEC("tcx/ingress")
int watch(struct __sk_buff *skb)
{
return TCX_NEXT;
}
SEC("tcx/ingress")
int guard(struct __sk_buff *skb)
{
return TCX_NEXT; /* allowed: let the programs after me see it too */
}
SEC("tcx/ingress")
int audit(struct __sk_buff *skb)
{
return TCX_NEXT;
}
SEC("tcx/ingress")
int meter(struct __sk_buff *skb)
{
return TCX_NEXT;
}
char LICENSE[] SEC("license") = "GPL";
The classic-tc programs use the plain SEC("tc") section and the TC_ACT_* codes. The tcx ones
come later. The loader plays three tools in turn, using libbpf’s bpf_tc_* API (libbpf 0.4, 2021),
the C equivalent of tc qdisc add and tc filter add. It counts how often each program ran with
the kernel’s own statistics (kernel.bpf_stats_enabled, as in Part 1), across ten pings sent into
veth1 from another namespace:
// tcold.c — three tools share one device's ingress through classic tc
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <net/if.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "gate.skel.h"
static struct gate_bpf *skel;
static unsigned long long runs(struct bpf_program *p)
{
struct bpf_prog_info info = {};
__u32 len = sizeof(info);
bpf_prog_get_info_by_fd(bpf_program__fd(p), &info, &len);
return info.run_cnt; /* needs kernel.bpf_stats_enabled=1 */
}
/* Ten pings in from the other namespace, then how often each program ran. */
static void ping10(void)
{
unsigned long long w = runs(skel->progs.watch_old), g = runs(skel->progs.guard_old);
system("ip netns exec gen ping -q -c 10 -i 0.01 10.0.0.2 > /dev/null");
printf(" 10 pings: watch_old ran %llu times, guard_old %llu\n",
runs(skel->progs.watch_old) - w, runs(skel->progs.guard_old) - g);
}
static void filters(void)
{
system("tc filter show dev veth1 ingress | grep -o 'pref [0-9]* bpf.*handle [^ ]* [a-z_]*'"
" | sed 's/^/ tc: /'; echo ' tc: --'");
}
int main(void)
{
int ifindex = if_nametoindex("veth1"), err;
setvbuf(stdout, NULL, _IOLBF, 0); /* keep our lines in order with libbpf's */
skel = gate_bpf__open_and_load();
if (!skel)
return 1;
LIBBPF_OPTS(bpf_tc_hook, hook, .ifindex = ifindex, .attach_point = BPF_TC_INGRESS);
LIBBPF_OPTS(bpf_tc_opts, a, .handle = 1, .priority = 2,
.prog_fd = bpf_program__fd(skel->progs.watch_old));
LIBBPF_OPTS(bpf_tc_opts, b, .handle = 1, .priority = 1,
.prog_fd = bpf_program__fd(skel->progs.guard_old));
LIBBPF_OPTS(bpf_tc_opts, c, .handle = 1, .priority = 1,
.prog_fd = bpf_program__fd(skel->progs.count_old));
puts("A, a monitor, creates clsact and attaches watch_old at priority 2");
bpf_tc_hook_create(&hook);
err = bpf_tc_attach(&hook, &a);
printf(" bpf_tc_attach: %s\n", strerror(-err));
ping10();
puts("B, a firewall, wants to run first, so it picks priority 1");
err = bpf_tc_attach(&hook, &b);
printf(" bpf_tc_attach: %s\n", strerror(-err));
ping10();
filters();
puts("C, an accounting tool, happens to pick the same priority and handle as B");
err = bpf_tc_attach(&hook, &c);
printf(" bpf_tc_attach: %s\n", strerror(-err));
puts("C retries with BPF_TC_F_REPLACE");
c.flags = BPF_TC_F_REPLACE;
err = bpf_tc_attach(&hook, &c);
printf(" bpf_tc_attach: %s\n", strerror(-err));
filters();
puts("B shuts down and cleans up the way its library makes easy: bpf_tc_hook_destroy()");
err = bpf_tc_hook_destroy(&hook);
printf(" bpf_tc_hook_destroy: %s\n", strerror(-err));
filters();
ping10();
gate_bpf__destroy(skel);
return 0;
}
The test bed is one veth pair: veth1 in the root namespace, veth0 in a namespace called gen
that sends the pings.
# gen.sh — veth1 here, veth0 in namespace "gen", which sends the pings; and run-time statistics on
ip netns add gen
ip link add veth1 type veth peer name veth0 netns gen
ip addr add 10.0.0.2/24 dev veth1 && ip link set veth1 up
ip -n gen addr add 10.0.0.1/24 dev veth0 && ip -n gen link set veth0 up
sysctl -qw kernel.bpf_stats_enabled=1
Everything in this post builds with one script. vmlinux.h comes from the running 6.7 kernel’s
BTF, the BPF objects are compiled with clang 15 against libbpf 1.3’s headers (installed under
/usr/local, ahead of 23.04’s libbpf 1.1), and the user-space programs link against libbpf 1.3:
# build.sh — Ubuntu 23.04 userland, libbpf 1.3 and bpftool 7.3 built from their tags into /usr/local
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h
for p in gate podnet sockredir steer lb; do
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -I/usr/local/include -c $p.bpf.c -o $p.bpf.o
done
for p in gate podnet steer; do bpftool gen skeleton $p.bpf.o > $p.skel.h; done
UAPI=/opt/src/libbpf/include/uapi # 23.04's kernel headers are 6.2's; these are 6.7's
for p in tcold tcxnew podnet steer; do
cc -g -O2 -Wall -I$UAPI $p.c -L/usr/local/lib -lbpf -lelf -lz -o $p
done
cc -O2 -Wall -I$UAPI nkadd.c -o nkadd
cc -O2 -Wall pp.c -o pp
Then the classic-tc run:
$ sudo ./tcold
A, a monitor, creates clsact and attaches watch_old at priority 2
bpf_tc_attach: Success
10 pings: watch_old ran 11 times, guard_old 0
B, a firewall, wants to run first, so it picks priority 1
bpf_tc_attach: Success
10 pings: watch_old ran 0 times, guard_old 10
tc: pref 1 bpf chain 0 handle 0x1 guard_old
tc: pref 2 bpf chain 0 handle 0x1 watch_old
tc: --
C, an accounting tool, happens to pick the same priority and handle as B
libbpf: Kernel error message: Filter already exists
bpf_tc_attach: File exists
C retries with BPF_TC_F_REPLACE
bpf_tc_attach: Success
tc: pref 1 bpf chain 0 handle 0x1 count_old
tc: pref 2 bpf chain 0 handle 0x1 watch_old
tc: --
B shuts down and cleans up the way its library makes easy: bpf_tc_hook_destroy()
bpf_tc_hook_destroy: Success
tc: --
10 pings: watch_old ran 0 times, guard_old 0
Read it as three tools, each doing something locally sensible:
- A attaches at priority 2 and sees the traffic: ten pings, plus one ARP packet.
- B wants to run first, picks priority 1, and returns
TC_ACT_OKfor traffic it allows, as a firewall naturally would. From then on A’s program ran zero times. It is still attached, the listing still shows it, and A has no way to find out, short of noticing that its counters stopped. - C happens to pick the same priority and handle as B, gets
EEXIST, and does what the library offers: retries withBPF_TC_F_REPLACE. B’s firewall is gone. B is still running. - B shuts down and calls
bpf_tc_hook_destroy(), the natural counterpart of thebpf_tc_hook_create()it called at start-up. That deletes theclsactqdisc, and with it A’s and C’s programs. A is still running, still believes it is attached, and counts nothing.
None of these is a bug in tc. Every step is the documented behaviour. The problem is that the
attachment has no owner: it is a property of the device, and any process with CAP_NET_ADMIN can
rewrite the device’s properties. The usual response has been convention. Tools picked “their”
priority numbers and hoped, and tc filter del dev eth0 ingress in a runbook could take out a
cluster’s network policy without leaving a trace in any of the tools that installed it.
tcx: one list per hook, with an owner for every entry
tcx, merged for 6.6, puts BPF programs directly on the device. Each net device gets two
bpf_mprog entries, one for ingress and one for egress, and the receive path runs them before it
looks at any qdisc. From sch_handle_ingress() in 6.7’s net/core/dev.c, abridged:
entry = rcu_dereference_bh(skb->dev->tcx_ingress);
...
if (static_branch_unlikely(&tcx_needed_key)) {
sch_ret = tcx_run(entry, skb, true); /* the tcx programs, in order */
if (sch_ret != TC_ACT_UNSPEC)
goto ingress_verdict;
}
sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason); /* then classic tc, if any */
Two things follow from that. tcx and classic tc can coexist on one device, and tcx always goes
first: classic cls_bpf filters only see a packet that every tcx program passed on. And there is no
qdisc, no priority and no handle. There is a list, at most 64 programs long, run in order, and each
program’s return value is one of four:
TCX_NEXT(−1): not my decision, run the next program. If every program says so, the packet carries on as if nothing were attached.TCX_PASS(0): accept now; programs after this one do not run.TCX_DROP(2): drop it.TCX_REDIRECT(7): send it where a redirect helper said.
The numbers are those of TC_ACT_UNSPEC, TC_ACT_OK, TC_ACT_SHOT and TC_ACT_REDIRECT, so a
program written for classic tc returns the right thing in tcx too. What changed is that TCX_NEXT
is now the documented default, the code a program returns when it has no opinion, which is why the
tcx stand-ins in gate.bpf.c all return it.
The list is managed by the multi-program API, bpf_mprog, which tcx was the first user of
(netkit is the second). Every attachment is either a link or, for compatibility, a bare program,
and three ideas make it safe to share:
Placement is relative. An attach request can carry BPF_F_BEFORE or BPF_F_AFTER, plus a
reference to a program or link already in the list (by fd, or by ID with BPF_F_ID). “After the
firewall” is something you can say. With no reference, BPF_F_BEFORE means the front and
BPF_F_AFTER the back.
Every change bumps a revision. Each list starts at revision 1 and every attach, detach or
replace increments it. A query returns the programs, their links and the revision, and an attach can
pass expected_revision: if the list has changed since you read it, the kernel refuses with
ESTALE instead of applying your change to a list you never saw. It is compare-and-swap for
attachment order.
A link is the only handle that can remove its program. Detaching a link-attached program by
program fd fails with EBUSY. When the process holding the link exits, the kernel closes the fd and
the program goes away, so nothing is left behind by a crashed agent unless it pinned the link on
purpose.
libbpf 1.3, released in November, has all of this: SEC("tcx/ingress") and SEC("tcx/egress"),
bpf_program__attach_tcx() with a bpf_tcx_opts carrying the flags, the relative fd or ID and the
expected revision, and bpf_prog_query_opts() returning the revision. It also relabels SEC("tc")
as legacy in its own source. Here are the same tools again, now on tcx, plus a fourth:
// tcxnew.c — the same tools sharing the same hook through tcx links (Linux 6.6+, libbpf 1.3)
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "gate.skel.h"
static int ifindex;
/* Ask the kernel for the device's tcx ingress list: revision, then programs in run order. */
static __u64 show(void)
{
__u32 prog_ids[64], link_ids[64];
LIBBPF_OPTS(bpf_prog_query_opts, q, .prog_ids = prog_ids, .link_ids = link_ids, .count = 64);
bpf_prog_query_opts(ifindex, BPF_TCX_INGRESS, &q);
printf(" revision %llu:", (unsigned long long)q.revision);
for (__u32 i = 0; i < q.count; i++) {
struct bpf_prog_info info = {};
__u32 len = sizeof(info);
int fd = bpf_prog_get_fd_by_id(prog_ids[i]);
bpf_prog_get_info_by_fd(fd, &info, &len);
close(fd);
printf(" %s(link %u)", info.name, link_ids[i]);
}
printf("\n");
return q.revision;
}
static void report(const char *what, struct bpf_link *l)
{
printf(" %s: %s\n", what, l ? "ok" : strerror(errno));
}
int main(void)
{
struct bpf_link *la, *lb, *lc, *ld;
__u64 rev;
int err;
setvbuf(stdout, NULL, _IOLBF, 0); /* keep our lines in order with libbpf's */
ifindex = if_nametoindex("veth1");
struct gate_bpf *skel = gate_bpf__open_and_load();
if (!skel)
return 1;
puts("A attaches watch: no qdisc, no priority, no handle");
la = bpf_program__attach_tcx(skel->progs.watch, ifindex, NULL);
report("attach", la);
show();
puts("B attaches guard and asks to run before everything already there");
LIBBPF_OPTS(bpf_tcx_opts, ob, .flags = BPF_F_BEFORE);
lb = bpf_program__attach_tcx(skel->progs.guard, ifindex, &ob);
report("attach", lb);
rev = show();
puts("C and D both read revision and both want a place right after guard");
LIBBPF_OPTS(bpf_tcx_opts, oc, .flags = BPF_F_AFTER, .expected_revision = rev,
.relative_fd = bpf_program__fd(skel->progs.guard));
LIBBPF_OPTS(bpf_tcx_opts, od, .flags = BPF_F_AFTER, .expected_revision = rev,
.relative_fd = bpf_program__fd(skel->progs.guard));
lc = bpf_program__attach_tcx(skel->progs.audit, ifindex, &oc);
report("C attach, expected revision matches", lc);
ld = bpf_program__attach_tcx(skel->progs.meter, ifindex, &od);
report("D attach, same expected revision", ld);
puts("D reads the list again and retries against the new revision");
od.expected_revision = show();
ld = bpf_program__attach_tcx(skel->progs.meter, ifindex, &od);
report("D attach", ld);
show();
puts("someone with the program's fd but not its link tries to detach watch");
err = bpf_prog_detach_opts(bpf_program__fd(skel->progs.watch), ifindex,
BPF_TCX_INGRESS, NULL);
printf(" bpf_prog_detach_opts: %s\n", strerror(-err));
puts("an operator runs the tc commands that used to wipe a device clean");
system("tc filter del dev veth1 ingress 2>&1 | sed 's/^/ tc: /';"
"tc qdisc del dev veth1 clsact 2>&1 | sed 's/^/ tc: /'");
show();
system("bpftool net show dev veth1 | sed 's/^/ /'");
puts("B shuts down: it destroys its own link, and only that");
bpf_link__destroy(lb);
show();
puts("A, C and D exit without cleaning up");
return 0; /* the kernel closes their link fds, which detaches them */
}
$ sudo ./tcxnew
A attaches watch: no qdisc, no priority, no handle
attach: ok
revision 2: watch(link 2)
B attaches guard and asks to run before everything already there
attach: ok
revision 3: guard(link 3) watch(link 2)
C and D both read revision and both want a place right after guard
C attach, expected revision matches: ok
libbpf: prog 'meter': failed to attach to tcx: Stale file handle
D attach, same expected revision: Stale file handle
D reads the list again and retries against the new revision
revision 4: guard(link 3) audit(link 4) watch(link 2)
D attach: ok
revision 5: guard(link 3) meter(link 6) audit(link 4) watch(link 2)
someone with the program's fd but not its link tries to detach watch
bpf_prog_detach_opts: Device or resource busy
an operator runs the tc commands that used to wipe a device clean
revision 5: guard(link 3) meter(link 6) audit(link 4) watch(link 2)
xdp:
tc:
veth1(2) tcx/ingress guard prog_id 20 link_id 3
veth1(2) tcx/ingress meter prog_id 22 link_id 6
veth1(2) tcx/ingress audit prog_id 21 link_id 4
veth1(2) tcx/ingress watch prog_id 19 link_id 2
flow_dissector:
netfilter:
B shuts down: it destroys its own link, and only that
revision 6: meter(link 6) audit(link 4) watch(link 2)
A, C and D exit without cleaning up
Each line of that maps onto one of the three ideas:
- A attached with no flags and landed in an empty list: revision 2.
- B asked for
BPF_F_BEFOREwith no anchor and went to the front. Its program returnsTCX_NEXTfor traffic it allows, so A still sees every packet. - C and D both read revision 3 and both asked for a place after
guard. C’s request reached the kernel first and moved the list to revision 4; D’s carriedexpected_revision = 3and was refused withESTALE(“Stale file handle”), with the list unchanged. D read the list again, saw where C had gone, and tried again against revision 4. The line from libbpf above it is libbpf reporting the same refusal. - A process holding
watch’s program fd, which any root process can get from its ID, tried to detach it the old way and gotEBUSY. It takes the link, not the program, to remove A’s program. tc filter delandtc qdisc deldon’t see tcx at all: there is no qdisc to delete. The list was still at revision 5.- B destroyed its own link and only its own program left. A, C and D exited without cleaning up,
and the device was empty afterwards, which
bpftool net showconfirms:
$ sudo bpftool net show dev veth1
xdp:
tc:
flow_dissector:
netfilter:
The link IDs tell one more small story. There is no link 5: the kernel creates the link object, with its ID, before it asks the mprog layer to insert it, so D’s refused attempt used up an ID.
Several tools, one ingress hook
The same sequence of events under classic tc and under tcx, step by step, from the two runs in this post.
classic tc: clsact qdisc, cls_bpf filters, priority and handle
A, a monitor, creates the clsact qdisc and attaches
watch_oldat priority 2.bpf_tc_attach: Success · 10 pings: watch_old ran 11 times
veth1 ingresswatch_old pref 2B, a firewall that wants to run first, picks priority 1. Its program accepts what it allows.
bpf_tc_attach: Success · 10 pings: watch_old ran 0 times, guard_old 10
veth1 ingressguard_old pref 1→watch_old pref 2Nobody told A. Its program is attached and never runs.
C, an accounting tool, happens to pick B's priority and handle.
bpf_tc_attach: File exists
veth1 ingressguard_old pref 1→watch_old pref 2C retries with
BPF_TC_F_REPLACE.bpf_tc_attach: Success
veth1 ingresscount_old pref 1→watch_old pref 2B's firewall is gone. B is still running and was not told.
B shuts down and cleans up with
bpf_tc_hook_destroy().bpf_tc_hook_destroy: Success · 10 pings: watch_old ran 0 times
veth1 ingress(no qdisc, no filters)Destroying the qdisc took A's and C's programs with it.
tcx: one ordered list per device, links, a revision number
A attaches
watch. No qdisc, no priority, no handle.attach: ok · revision 2
rev 2watch link 2B attaches
guardwithBPF_F_BEFOREand no anchor: the front of the list.attach: ok · revision 3
rev 3guard link 3→watch link 2C attaches
auditafterguard, expecting revision 3.attach: ok · revision 4
rev 4guard link 3→audit link 4→watch link 2D read the list at the same time as C and also expects revision 3.
attach: Stale file handle (ESTALE)
rev 4guard link 3→audit link 4→watch link 2Nothing changed. D's plan was made against a list that no longer exists.
D reads the list again and retries against revision 4.
attach: ok · revision 5
rev 5guard link 3→meter link 6→audit link 4→watch link 2Someone holding
watch's program fd, but not A's link, tries to detach it.bpf_prog_detach_opts: Device or resource busy (EBUSY)
rev 5guard→meter→audit→watchAn operator runs
tc filter delandtc qdisc del … clsact.tc: Cannot find specified qdisc on specified device.
rev 5guard→meter→audit→watchB shuts down by destroying its own link.
revision 6
rev 6meter link 6→audit link 4→watch link 2A, C and D exit without cleaning up.
the kernel closes their link fds
veth1(nothing attached)
Link 5 is missing from the tcx track because D's failed attach was given an id before the
kernel checked the revision. Pings are counted with kernel.bpf_stats_enabled.
None of this makes two tools agree on an order. It makes the order visible, makes changes to it atomic, and makes it impossible for one tool to remove another’s program by accident, which is what was missing. Libraries now have the primitives to build policies on top: Cilium, for instance, could insert its programs relative to its own previous ones and leave everybody else’s alone.
netkit: a veth that runs your program before it queues anything
How a container is plugged in today
A container lives in its own network namespace, which has its own devices, addresses and routing
table. The standard way to connect it to the host is a veth pair: two virtual Ethernet devices,
one end in the container (usually called eth0), the other in the host’s namespace, so that
whatever is transmitted on one end is received on the other. Docker does it, and every common
Kubernetes network plugin does it, Cilium included.
What “received on the other” means is the important part. Here is the heart of veth_xmit() in
6.7, by way of veth_forward_skb():
return __dev_forward_skb(dev, skb) ?: xdp ?
veth_xdp_rx(rq, skb) :
__netif_rx(skb);
Without XDP on the veth, the packet goes to __netif_rx(), which puts it on the current CPU’s
backlog, a per-CPU input queue, and raises the network softirq. The transmit call returns, the
softirq runs (on the same CPU, typically as soon as the sender’s code re-enables bottom halves), and
process_backlog() takes the packet off the queue and runs the whole receive path for it on the
host side: tc ingress, then routing or bridging, then transmission out of the real NIC. One trip
through an extra queue and a second receive-path traversal, per packet, per direction. For years
that was simply the cost of a container.
Cilium already cut part of that. Its programs on the host side of each veth, and on the physical
device, use two helpers merged for 5.10: bpf_redirect_neigh() sends a packet out of another device
with the neighbour subsystem filling in the MAC addresses, and bpf_redirect_peer() hands a packet
arriving on the physical device directly to the container end of a veth, switching namespaces inside
the same receive call, with no backlog. That fixes the inbound direction. The outbound
direction can’t be fixed from the host side, because the host side only sees the packet after it
has been through the backlog: the hop happens inside veth_xmit(), before any program runs.
What netkit changes
netkit moves the program into the transmit call. A netkit pair looks like a veth pair from the
outside, one end in the host and one in the pod, but its transmit function, netkit_xmit(), runs
the device’s BPF programs first and acts on their verdict immediately. Abridged from
drivers/net/netkit.c in 6.7:
enum netkit_action ret = READ_ONCE(nk->policy);
...
entry = rcu_dereference(nk->active);
if (entry)
ret = netkit_run(entry, skb, ret); /* the programs, in mprog order */
switch (ret) {
case NETKIT_NEXT:
case NETKIT_PASS:
...
__netif_rx(skb); /* hand it to the peer, through the backlog */
break;
case NETKIT_REDIRECT:
skb_do_redirect(skb); /* go where the program said, right now */
break;
case NETKIT_DROP:
default:
kfree_skb(skb);
...
A program that knows where the packet should go returns NETKIT_REDIRECT and the packet goes there
directly from the pod’s own sendmsg(): out of the physical device with bpf_redirect_neigh(), or
to another device. Only a packet that is passed through to the host side still takes the backlog.
The commit that added netkit puts the goal plainly: when a program decides that a packet must leave
the node, “a redirect to the physical device can take place directly without going through per-CPU
backlog queue”, which “helps to shift processing for such traffic from softirq to process context”.
The work is done by, and accounted to, the task that sent the packet. The rest of the design follows
from who is meant to control it:
- Primary and peer. The end created in the host’s namespace is the primary, the end moved into
the pod is the peer. Programs are attached with the
BPF_NETKIT_PRIMARYattach type (they run when the primary transmits, that is on traffic going into the pod) orBPF_NETKIT_PEER(they run when the pod transmits). Both are attached through the primary’s ifindex: asking for the peer’s returnsEACCES, and link settings can only be changed through the primary. From inside the pod, its own device offers no way to attach, detach or change the programs that police it. - A default policy. Each end has a policy,
NETKIT_PASSorNETKIT_DROP, that applies when no program is attached. A plugin can create the pair with the peer’s policy set to drop, so the pod has no connectivity at all until its program is in place, rather than briefly having unpoliced connectivity. Once a program is attached, the policy no longer applies: a program returningNETKIT_NEXTlets the packet through. - L3 by default. In the default
NETKIT_L3mode the devices have no MAC addresses and do no ARP (IFF_NOARP); the pod routes everything out of its one device.NETKIT_L2exists for setups that need Ethernet semantics. - The same multi-program API as tcx, so netkit programs are links with revisions and relative
ordering, and the return codes are the tcx codes under new names (the driver checks at build time
that
NETKIT_PASS == TCX_PASSand so on).
One packet between a pod and the network
Where the packet is queued for later on the way, and where a BPF program gets to send it straight on.
pod → network
network → pod
backlog is __netif_rx(): the packet is put on this CPU's input
queue and picked up again by the network softirq, a second pass through the receive path.
Inbound, bpf_redirect_peer() (Linux 5.10) already skips it for veth and netkit alike.
Outbound, only netkit can, because only netkit runs the program inside the pod's transmit. The
wire hop is the lab's stand-in for a NIC and is the same in every lane.
Making a netkit device in January 2024
The obvious way to create a pair would be ip link add ... type netkit. iproute2 6.7.0, released on
8 January, does not know the type yet: support for it was committed to iproute2’s development
branch in November and hasn’t reached a release. So the lab creates the pair the way ip would, with
one RTM_NEWLINK message over rtnetlink. That is also the clearest way to see what a netkit device
is:
// nkadd.c — create a netkit pair over rtnetlink: nkadd <primary> <peer> <netns-path> [pass|drop]
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <linux/rtnetlink.h>
#include <linux/if_link.h> /* IFLA_NETKIT_*, from libbpf 1.3's copy of the 6.7 uapi */
static char buf[1024];
static struct nlmsghdr *nh = (struct nlmsghdr *)buf;
/* Append one attribute at the end of the message; return it so it can be nested into. */
static struct rtattr *put(int type, const void *data, int len)
{
struct rtattr *rta = (struct rtattr *)(buf + NLMSG_ALIGN(nh->nlmsg_len));
rta->rta_type = type;
rta->rta_len = RTA_LENGTH(len);
if (len)
memcpy(RTA_DATA(rta), data, len);
nh->nlmsg_len = NLMSG_ALIGN(nh->nlmsg_len) + RTA_ALIGN(rta->rta_len);
return rta;
}
static void end(struct rtattr *nest) /* close a nested attribute */
{
nest->rta_len = buf + nh->nlmsg_len - (char *)nest;
}
int main(int argc, char **argv)
{
struct ifinfomsg ifi = { .ifi_family = AF_UNSPEC };
__u32 mode = NETKIT_L3, peer_policy = NETKIT_PASS;
int nsfd, fd;
if (argc < 4)
return fprintf(stderr, "usage: nkadd primary peer netns [pass|drop]\n"), 2;
if (argc > 4 && !strcmp(argv[4], "drop"))
peer_policy = NETKIT_DROP;
nsfd = open(argv[3], O_RDONLY);
nh->nlmsg_len = NLMSG_LENGTH(sizeof(ifi));
nh->nlmsg_type = RTM_NEWLINK;
nh->nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL | NLM_F_ACK;
memcpy(NLMSG_DATA(nh), &ifi, sizeof(ifi));
put(IFLA_IFNAME, argv[1], strlen(argv[1]) + 1);
struct rtattr *linkinfo = put(IFLA_LINKINFO, NULL, 0);
put(IFLA_INFO_KIND, "netkit", 7);
struct rtattr *data = put(IFLA_INFO_DATA, NULL, 0);
put(IFLA_NETKIT_MODE, &mode, sizeof(mode));
put(IFLA_NETKIT_PEER_POLICY, &peer_policy, sizeof(peer_policy));
struct rtattr *peer = put(IFLA_NETKIT_PEER_INFO, &ifi, sizeof(ifi));
put(IFLA_IFNAME, argv[2], strlen(argv[2]) + 1);
put(IFLA_NET_NS_FD, &nsfd, sizeof(nsfd));
end(peer);
end(data);
end(linkinfo);
fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
send(fd, buf, nh->nlmsg_len, 0);
recv(fd, buf, sizeof(buf), 0); /* the ACK: an NLMSG_ERROR carrying 0 or -errno */
int err = ((struct nlmsgerr *)NLMSG_DATA(nh))->error;
printf("RTM_NEWLINK netkit %s <-> %s: %s\n", argv[1], argv[2], err ? strerror(-err) : "ok");
return err ? 1 : 0;
}
The request is an ordinary “new link” with a nested IFLA_LINKINFO naming the kind, netkit, and
a nested IFLA_INFO_DATA with netkit’s own attributes: the mode, the peer’s policy, and
IFLA_NETKIT_PEER_INFO, which holds a whole second ifinfomsg for the peer, with the peer’s name
and the namespace to create it in. The constants come from 6.7’s linux/if_link.h; Ubuntu 23.04’s
headers are 6.2’s and don’t have them, so the build points at the copy of the 6.7 UAPI headers that
ships inside libbpf 1.3’s source.
The lab is one VM standing in for a Kubernetes node. A namespace called remote sits at the far end
of a veth pair called wire, which stands in for the node’s NIC and the network beyond it. Three pods
hang off the node: pod-rt on a veth routed by the kernel, the way a plain bridge-less setup would
do it; pod-veth on a veth whose traffic BPF will route; and pod-nk on netkit, created with the
pod side’s policy set to drop.
# podlab.sh — this namespace is the node; "remote" sits behind a wire; three pods
set -e
for ns in remote pod-rt pod-veth pod-nk; do ip netns add $ns; ip -n $ns link set lo up; done
# the wire: stands in for the node's NIC and the network beyond it
ip link add wire type veth peer name eth0 netns remote
ip addr add 192.168.50.1/24 dev wire
ip link set wire up
ip -n remote addr add 192.168.50.2/24 dev eth0
ip -n remote link set eth0 up
ip -n remote route add 10.0.0.0/24 via 192.168.50.1
sysctl -qw net.ipv4.ip_forward=1
# two veth pods: pod-rt is routed by the kernel, pod-veth will be routed by BPF
for p in rt:10.0.0.10 veth:10.0.0.11; do
name=${p%%:*} addr=${p#*:}
ip link add h-$name type veth peer name eth0 netns pod-$name
sysctl -qw net.ipv4.conf.h-$name.proxy_arp=1 # answer the pod's ARP for the world
ip link set h-$name up
ip route add $addr/32 dev h-$name
ip -n pod-$name addr add $addr/32 dev eth0
ip -n pod-$name link set eth0 up
ip -n pod-$name route add default dev eth0
done
# the netkit pod: L3 mode (no ARP, no MACs), and its side drops everything until a
# program is attached
./nkadd h-nk eth0 /run/netns/pod-nk drop
ip link set h-nk up
ip route add 10.0.0.12/32 dev h-nk
ip -n pod-nk addr add 10.0.0.12/32 dev eth0
ip -n pod-nk link set eth0 up
ip -n pod-nk route add default dev eth0
$ sudo sh podlab.sh
RTM_NEWLINK netkit h-nk <-> eth0: ok
$ ip -d link show h-nk
6: h-nk@if2: <BROADCAST,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP ...
link/ether 00:00:00:00:00:00 brd ff:ff:ff:ff:ff:ff link-netns pod-nk ...
netkit addrgenmode eui64 ...
$ sudo ip netns exec pod-nk ping -c 2 -W 1 192.168.50.2
PING 192.168.50.2 (192.168.50.2) 56(84) bytes of data.
ping: sendmsg: No buffer space available
ping: sendmsg: No buffer space available
--- 192.168.50.2 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 2001ms
ip -d link shows the new kind and the missing MAC address, and the policy is doing its job: until a
program is attached, everything pod-nk transmits is dropped inside netkit_xmit(), which ping
sees as ENOBUFS from sendmsg().
The datapath is two programs’ worth of code. Outbound, every IPv4 packet a pod sends goes straight
out of the wire with bpf_redirect_neigh(). Inbound, a program on the wire’s tcx ingress looks the
destination up in a map of pod addresses and hands the packet to the pod with bpf_redirect_peer().
The outbound code runs at two different hooks: tcx ingress on the host end of pod-veth’s pair,
which is after the backlog hop, and the netkit peer hook of pod-nk, which is inside the pod’s own
transmit, before it:
// podnet.bpf.c — a two-program pod datapath: pod -> wire, and wire -> pod
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
#define ETH_P_IP 0x0800
const volatile __u32 wire_ifindex; /* set by the loader before load */
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 256);
__type(key, __u32); /* pod IPv4 address, network byte order */
__type(value, __u32); /* ifindex of the pod's host-side device */
} pods SEC(".maps");
/* What a pod sends: IPv4 goes straight out of the wire device, and the neighbour
* subsystem fills in the MAC addresses. ARP and the rest go to the stack. */
static __always_inline int to_wire(struct __sk_buff *skb)
{
if (skb->protocol != bpf_htons(ETH_P_IP))
return TCX_NEXT;
return bpf_redirect_neigh(wire_ifindex, NULL, 0, 0);
}
/* The same code at two hooks. libbpf takes the attach type from the section name,
* so each hook gets its own entry point. */
SEC("tcx/ingress")
int veth_out(struct __sk_buff *skb) /* host side of a veth: after the backlog hop */
{
return to_wire(skb);
}
SEC("netkit/peer")
int netkit_out(struct __sk_buff *skb) /* inside the pod's own transmit: no hop */
{
return to_wire(skb);
}
/* Runs at tcx ingress of the wire: traffic for a pod jumps straight into the pod's
* namespace, without a second trip through a backlog queue. */
SEC("tcx/ingress")
int from_wire(struct __sk_buff *skb)
{
void *data = (void *)(long)skb->data, *end = (void *)(long)skb->data_end;
struct ethhdr *eth = data;
struct iphdr *ip = data + sizeof(*eth);
__u32 *ifindex;
if ((void *)(ip + 1) > end || eth->h_proto != bpf_htons(ETH_P_IP))
return TCX_NEXT;
ifindex = bpf_map_lookup_elem(&pods, &ip->daddr);
if (!ifindex)
return TCX_NEXT; /* not a pod we manage: ordinary routing */
return bpf_redirect_peer(*ifindex, 0);
}
char LICENSE[] SEC("license") = "GPL";
One wrinkle is visible in the two thin wrappers. libbpf derives the attach type from the section
name and attaches with the program’s own expected attach type, so a SEC("tc") program handed to
bpf_program__attach_tcx() is refused with EINVAL. A program meant for two hooks gets one entry
point per hook. The loader attaches all three and pins the links in bpffs, so that the datapath
belongs to the filesystem rather than to a process:
// podnet.c — attach podnet.bpf.o: podnet <wire> <veth-host> <veth-pod-ip> <netkit-primary> <netkit-pod-ip>
#include <stdio.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "podnet.skel.h"
static int pin(struct bpf_link *l, const char *path)
{
if (l && !bpf_link__pin(l, path)) {
printf("pinned %s\n", path);
return 0;
}
fprintf(stderr, "attach or pin failed: %s\n", path);
return 1;
}
int main(int argc, char **argv)
{
if (argc != 6)
return fprintf(stderr, "usage: podnet wire veth-host veth-pod-ip nk-primary nk-pod-ip\n"), 2;
int wire = if_nametoindex(argv[1]), veth = if_nametoindex(argv[2]), nk = if_nametoindex(argv[4]);
__u32 vip, nip;
inet_pton(AF_INET, argv[3], &vip);
inet_pton(AF_INET, argv[5], &nip);
struct podnet_bpf *skel = podnet_bpf__open();
skel->rodata->wire_ifindex = wire;
if (podnet_bpf__load(skel))
return 1;
bpf_map__update_elem(skel->maps.pods, &vip, 4, &veth, 4, BPF_ANY);
bpf_map__update_elem(skel->maps.pods, &nip, 4, &nk, 4, BPF_ANY);
/* netkit programs attach through the primary device; the pod's side is not addressable */
return pin(bpf_program__attach_tcx(skel->progs.veth_out, veth, NULL), "/sys/fs/bpf/pod-veth") |
pin(bpf_program__attach_netkit(skel->progs.netkit_out, nk, NULL), "/sys/fs/bpf/pod-netkit") |
pin(bpf_program__attach_tcx(skel->progs.from_wire, wire, NULL), "/sys/fs/bpf/wire-in");
}
$ sudo ./podnet wire h-veth 10.0.0.11 h-nk 10.0.0.12
pinned /sys/fs/bpf/pod-veth
pinned /sys/fs/bpf/pod-netkit
pinned /sys/fs/bpf/wire-in
$ sudo bpftool net show
...
tc:
wire(3) tcx/ingress from_wire prog_id 29 link_id 9
h-veth(5) tcx/ingress veth_out prog_id 27 link_id 7
h-nk(6) netkit/peer netkit_out prog_id 30 link_id 8
...
$ sudo ip netns exec pod-nk ping -c 2 -W 1 192.168.50.2
PING 192.168.50.2 (192.168.50.2) 56(84) bytes of data.
64 bytes from 192.168.50.2: icmp_seq=1 ttl=64 time=0.042 ms
64 bytes from 192.168.50.2: icmp_seq=2 ttl=64 time=0.038 ms
--- 192.168.50.2 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1026ms
rtt min/avg/max/mdev = 0.038/0.040/0.042/0.002 ms
The netkit link is listed against h-nk, the primary, though the program runs when the pod
transmits. Ask bpftool link show about the same link, though, and it says something else:
$ sudo bpftool link show
...
8: netkit prog 30
ifindex veth1(2) attach_type netkit_peer
...
The kernel reports the ifindex of the device the program is installed on, which for a peer program
is the pod’s eth0: index 2 in the pod’s namespace. bpftool translates the number in its own
namespace, where index 2 is veth1, a device that has nothing to do with netkit. A small
trap in brand-new code.
What it costs, measured
The question netkit answers is “how close can a pod get to the network performance of the host
itself?” So the experiment measures four clients talking to the same server in remote, through the
same wire, the only difference being how the client is plugged in: host, a process in the
node’s own namespace with no pod plumbing at all; veth, routed; veth + BPF; and netkit +
BPF.
Three measurements. Latency is a TCP ping-pong, one byte each way, timed per round trip with
clock_gettime(): 20,000 timed round trips after 2,000 untimed ones, reporting the median and the
99th percentile. Packet rate is iperf3 3.12 sending 64-byte UDP datagrams as fast as one thread
can for three seconds: the receiver can’t keep up and drops nearly all of them, which doesn’t matter,
because what is being measured is how many packets per second the pod can push out, and every
packet’s whole trip from sendto() to the wire is paid for on the sender’s CPU. Throughput is
one iperf3 TCP stream for three seconds. The ping-pong tool is short enough to show:
The VM has four virtual CPUs. The client is pinned to CPU 1 and the servers to CPU 2, except that for latency I also ran a server on CPU 1, the same CPU as the client. All four configurations were measured in each of 9 rounds, in rotated order, in one boot, and BPF’s run-time statistics were switched off so that the BPF configurations didn’t pay for the bookkeeping.
| configuration | round trip, same vCPU, median µs (range) | same vCPU, p99 µs | round trip, across vCPUs, median µs (range) | 64-byte UDP, thousand packets/s (range) | one TCP stream, Gbit/s (range) |
|---|---|---|---|---|---|
| host namespace, no pod | 3.43 (3.40–3.49) | 4.48 | 25.71 (25.48–26.51) | 1,467 (1,358–1,483) | 95.5 (91.6–96.9) |
| netkit + BPF | 3.67 (3.66–3.70) | 4.77 | 26.20 (25.66–26.63) | 1,208 (1,164–1,231) | 90.1 (87.9–93.5) |
| veth + BPF | 3.68 (3.65–3.82) | 4.71 | 26.08 (25.65–26.61) | 1,137 (1,105–1,150) | 89.0 (86.3–90.5) |
| veth, kernel routing | 3.95 (3.91–4.00) | 6.44 | 26.61 (26.37–26.96) | 1,091 (1,032–1,107) | 86.2 (80.5–90.6) |
What the plumbing costs, round by round
9 interleaved rounds in one boot. Each dot is one round; the tick is the median.
Pod → remote, round trip, same vCPU (µs)
| configuration | median | min | max |
|---|---|---|---|
| host namespace, no pod | 3.43 | 3.4 | 3.49 |
| netkit + BPF | 3.67 | 3.66 | 3.7 |
| veth + BPF | 3.68 | 3.65 | 3.82 |
| veth, kernel routing | 3.95 | 3.91 | 4 |
Pod → remote, round trip, across vCPUs (µs)
| configuration | median | min | max |
|---|---|---|---|
| host namespace, no pod | 25.71 | 25.48 | 26.51 |
| netkit + BPF | 26.2 | 25.66 | 26.63 |
| veth + BPF | 26.08 | 25.65 | 26.61 |
| veth, kernel routing | 26.61 | 26.37 | 26.96 |
Pod → remote, 64-byte UDP sent (k pkt/s)
| configuration | median | min | max |
|---|---|---|---|
| host namespace, no pod | 1467.4 | 1357.6 | 1482.7 |
| netkit + BPF | 1207.9 | 1163.9 | 1230.7 |
| veth + BPF | 1137.1 | 1105.4 | 1150.2 |
| veth, kernel routing | 1091 | 1032 | 1107.1 |
Pod → remote, one TCP stream (Gbit/s)
| configuration | median | min | max |
|---|---|---|---|
| host namespace, no pod | 95.5 | 91.58 | 96.87 |
| netkit + BPF | 90.13 | 87.9 | 93.5 |
| veth + BPF | 88.97 | 86.33 | 90.49 |
| veth, kernel routing | 86.17 | 80.49 | 90.57 |
Local TCP, round trip, same vCPU (µs)
| configuration | median | min | max |
|---|---|---|---|
| sockmap redirect | 2.5 | 2.48 | 2.53 |
| plain TCP | 3.44 | 3.39 | 3.51 |
Local TCP, round trip, across vCPUs (µs)
| configuration | median | min | max |
|---|---|---|---|
| sockmap redirect | 23.92 | 18.07 | 24.4 |
| plain TCP | 25.83 | 25.48 | 26.21 |
Local TCP, one stream (Gbit/s)
| configuration | median | min | max |
|---|---|---|---|
| sockmap redirect | 59.56 | 53.47 | 61.84 |
| plain TCP | 96.28 | 93.89 | 98.12 |
Linux 6.7 in a 4-vCPU KVM guest that itself runs inside another hypervisor. Round trips: one byte each way over TCP, median of 20,000 per dot. UDP: 64-byte datagrams sent by one thread for 3 s. Streams: iperf3, one TCP stream, 3 s. The axis is fitted to the data and does not start at zero.
Across CPUs, the plumbing doesn’t show. With client and server on different virtual CPUs, every configuration took between 25.7 and 26.6 µs per round trip. That number is not the network stack. It is the cost of one virtual CPU waking another twice per round trip, an inter-processor interrupt, which in a KVM guest running inside another hypervisor is several exits deep. It hides nearly everything else; only the kernel-routed veth, with two extra hops and IP forwarding, stands out, at 0.6 µs above the rest.
On one CPU, the path shows, a little. With both ends on CPU 1, the wakeups are cheap and what is left is the software path: the host at 3.43 µs, netkit at 3.67, veth with BPF at 3.68, and veth routed by the kernel at 3.95. Two gaps are clear in every round. Routing a pod’s traffic with BPF instead of the kernel’s forwarding saved 0.27 µs per round trip, and being in a pod at all cost about 0.24 µs over a process in the node’s own namespace. The gap netkit was built to close, between netkit and a BPF-routed veth, was 0.01 µs: netkit was ahead in five of the 9 rounds, and the ranges overlap. In a round trip the backlog hop is cheap, because the softirq that drains the backlog runs on the same CPU as soon as the sender’s transmit path re-enables bottom halves: “queued for later” means later by a fraction of a microsecond.
Pushing packets out, it is measurable. The UDP sender is where a per-packet cost on the way out
of the pod should show, and it did: 1,208 thousand packets a second through netkit against
1,137 thousand through the BPF-routed veth, 6.2% more, with netkit ahead in
nine of the 9 rounds. Turned into time per packet, that is about
52 ns, which on this path is everything the veth does that netkit doesn’t: put the packet on
the backlog, take it off again and start the receive path on the host side of the pair, before the
same program sends it on. Small, but it is per packet, on every packet a pod sends. The kernel-routed veth
managed 1,091 thousand. And the host’s own socket did 1,467 thousand: a pod on
netkit still pays for a second device transmit and for the route and neighbour lookup inside
bpf_redirect_neigh(), which a socket in the node’s namespace does as part of its ordinary output.
netkit removes the queue, not the pod.
Throughput barely moves. One TCP stream did 95.5 Gbit/s for the host namespace, 90.1 Gbit/s for netkit, 89.0 Gbit/s for veth with BPF, 86.2 Gbit/s for routed veth (medians; individual rounds ranged from 80.5 to 96.9). The order is the same, but the spread between rounds is as large as the gaps. TCP over these virtual devices moves 64 KiB segments, so a per-packet cost is spread over a lot of bytes, and a single stream in a VM is limited by other things. The gain netkit’s authors report is in CPU per packet and scheduling on real NICs at high packet rates, with many pods, which one VM cannot reproduce. I didn’t see a throughput difference that rose above the round-to-round spread, and I am not claiming one.
Skipping TCP between two local sockets
The rest of this post moves up a layer, to sockets, where BPF can change what happens to data and connections without looking at a single packet.
sockmap and sk_msg
Two processes on one machine that talk over TCP, an application and its sidecar proxy, say, send every
message down through TCP and IP, through the loopback device, and back up the receive path into the
other socket’s queue. Since 4.14, BPF has had a map
that holds sockets rather than the data of
Part 5, BPF_MAP_TYPE_SOCKMAP (and since 4.18, the hash-keyed
BPF_MAP_TYPE_SOCKHASH), and since 4.17 an sk_msg program type that runs on every sendmsg() by
a socket in such a map and can redirect the message to another socket in it. Redirected with
BPF_F_INGRESS, the data lands directly on the other socket’s receive queue. TCP never carries it.
It takes two programs. A sock_ops program (4.13), attached to a cgroup, is called on TCP events for sockets in that cgroup; on “connection established”, from either end, it adds the socket to a sockhash keyed by its 4-tuple. The sk_msg program, attached to the map itself, looks up the socket whose key is its own 4-tuple turned around, which is the other end of the same connection:
// sockredir.bpf.c — between two local TCP sockets, hand the bytes over directly
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
#define AF_INET 2
struct sock_key { /* one TCP socket, by its own view of the connection */
__u32 local_ip, remote_ip;
__u32 local_port, remote_port; /* both host byte order */
};
struct {
__uint(type, BPF_MAP_TYPE_SOCKHASH);
__uint(max_entries, 65536);
__type(key, struct sock_key);
__type(value, __u64);
} socks SEC(".maps");
/* sock_ops, attached to a cgroup: every TCP socket in it that reaches ESTABLISHED,
* from either end, goes into the map. */
SEC("sockops")
int add_established(struct bpf_sock_ops *ops)
{
if (ops->family != AF_INET)
return 0;
if (ops->op != BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB &&
ops->op != BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB)
return 0;
struct sock_key k = {
.local_ip = ops->local_ip4,
.remote_ip = ops->remote_ip4,
.local_port = ops->local_port,
.remote_port = bpf_ntohl(ops->remote_port), /* big-endian, in the top 16 bits */
};
bpf_sock_hash_update(ops, &socks, &k, BPF_ANY);
return 0;
}
/* sk_msg, attached to the map: runs on every sendmsg() by a socket in it. The other
* end of the connection is the socket whose key is ours turned around. */
SEC("sk_msg")
int redirect(struct sk_msg_md *msg)
{
struct sock_key peer = {
.local_ip = msg->remote_ip4,
.remote_ip = msg->local_ip4,
.local_port = bpf_ntohl(msg->remote_port),
.remote_port = msg->local_port,
};
/* Found: the data goes onto the peer's receive queue, and TCP never carries it.
* Not found (the helper says SK_DROP): ignore that and pass, so a connection to
* anything outside the map still works the ordinary way. */
bpf_msg_redirect_hash(msg, &socks, &peer, BPF_F_INGRESS);
return SK_PASS;
}
char LICENSE[] SEC("license") = "GPL";
Two details are worth slowing down for. The port fields don’t share a byte order: local_port is in
host order, remote_port in network order, and on a little-endian machine the kernel puts that
16-bit network-order port in the upper half of the 32-bit field, so bpf_ntohl() is the right
conversion and bpf_ntohs() is not. And bpf_msg_redirect_hash() returns SK_DROP when the key is
not in the map; returning that as the verdict would drop data on every connection whose other end
isn’t local, so the program ignores the return value and always returns SK_PASS, which means
“redirect if a target was set, deliver normally if not”.
No loader is needed; bpftool can do it all, and a three-line wrapper puts a command into a cgroup:
# sockmap.sh — load both programs; sk_msg goes on the map, sock_ops on a cgroup called "fast"
bpftool prog loadall sockredir.bpf.o /sys/fs/bpf/sr pinmaps /sys/fs/bpf/sr
bpftool prog attach pinned /sys/fs/bpf/sr/redirect msg_verdict pinned /sys/fs/bpf/sr/socks
mkdir -p /sys/fs/cgroup/fast /sys/fs/cgroup/plain
bpftool cgroup attach /sys/fs/cgroup/fast sock_ops pinned /sys/fs/bpf/sr/add_established
# incg — run a command inside a cgroup: incg <cgroup> <command...>
echo $$ > /sys/fs/cgroup/$1/cgroup.procs
shift
exec "$@"
The quickest proof that the redirect happens is to count the loopback device’s packets around 20,000 ping-pongs, in a cgroup with the programs and in one without:
# lo-count.sh — the same ping-pong in both cgroups, counting the loopback device's packets
./incg fast ./pp -s 6001 &
./incg plain ./pp -s 6002 &
sleep 0.5
for run in fast:6001 plain:6002; do
cg=${run%:*} port=${run#*:}
before=$(cat /sys/class/net/lo/statistics/tx_packets)
./incg $cg ./pp 127.0.0.1 $port 20000
after=$(cat /sys/class/net/lo/statistics/tx_packets)
echo "$cg: $((after - before)) packets on lo"
done
$ sudo sh sockmap.sh && sudo bash lo-count.sh
n=20000 p50=25.05 p90=26.64 p99=67.88 mean=26.63 us
fast: 6 packets on lo
n=20000 p50=26.54 p90=27.95 p99=55.08 mean=27.27 us
plain: 44008 packets on lo
The tool does 22,000 round trips (2,000 untimed, then 20,000), so 44,000 one-byte messages. Without
the programs that was 44,008 loopback packets, one per message plus the connection’s opening and
closing. With them it was six: the handshake and the closing exchange, which still go through TCP
because a socket only enters the map once it is established. Every byte in between went from one
socket’s sendmsg() to the other’s receive queue.
What that buys, measured in the same rounds as the pods, client on CPU 1:
| configuration | same vCPU, median µs (range) | across vCPUs, median µs (range) | one stream, Gbit/s (range) | loopback packets per stream |
|---|---|---|---|---|
| sockmap redirect | 2.50 (2.48–2.53) | 23.92 (18.07–24.40) | 59.6 (53.5–61.8) | 12 |
| plain TCP | 3.44 (3.39–3.51) | 25.83 (25.48–26.21) | 96.3 (93.9–98.1) | 1,112,304 |
Small messages got faster: a median round trip of 2.50 µs against 3.44 µs, 27% less, with both ends on one CPU, and 23.92 against 25.83 µs
across CPUs. Bulk throughput got slower: 59.6 Gbit/s with the redirect against 96.3 without, 38% less. That is not a measurement
error, and it repeated in every round. I didn’t profile why, but the sk_msg path is not where the
kernel’s bulk-transfer work has gone: loopback TCP moves 64 KiB segments and never computes a
checksum, while a redirected socket runs the program on every sendmsg() and moves the data through
its own message queue. The trick wins for chatty request-response traffic and loses for streams.
It is also a trick that has had a hard time in production. Cilium shipped exactly this, sock_ops
plus sk_msg between local pods, behind a --sockops-enable flag for several releases, deprecated it in 1.13
and removed it in 1.14 last July; the issue that removed it says simply that it was not being
maintained. The mechanism is still in the kernel and still works, as above; what it asks of whoever
deploys it is to know both ends of every connection it touches, and to accept that anything which
expects to see those bytes as packets, from a packet capture to a network policy, no longer will.
sk_lookup: one socket for a whole address range
When a SYN arrives, the kernel finds the listening socket for it by destination address and port.
That lookup has a hard rule: a socket listens on one port, on one address or on all of them. A
service that must answer on every port from 7000 to 7999 of 65,536 addresses has no way to say so
with bind(), short of 65 million sockets.
BPF_PROG_TYPE_SK_LOOKUP, contributed by Cloudflare’s Jakub Sitnicki and merged for 5.9, puts a
program in front of that lookup, per network namespace. It sees the connection’s addresses, ports
and protocol, and can pick a socket out of a sockmap with bpf_sk_assign(); the chosen socket then
receives the connection as if it had matched normally. If the program doesn’t pick, the normal lookup
runs. Here it is steering a /16 and a thousand ports to one listener that is bound to neither:
// steer.bpf.c — any TCP connection to 10.1.0.0/16, ports 7000-7999, goes to one socket
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
#define IPPROTO_TCP 6
struct {
__uint(type, BPF_MAP_TYPE_SOCKMAP);
__uint(max_entries, 1);
__type(key, __u32);
__type(value, __u64); /* user space stores a socket fd; we get the socket */
} target SEC(".maps");
SEC("sk_lookup")
int steer(struct bpf_sk_lookup *ctx)
{
__u32 zero = 0;
struct bpf_sock *sk;
long err;
if (ctx->protocol != IPPROTO_TCP)
return SK_PASS;
if ((bpf_ntohl(ctx->local_ip4) >> 16) != (10 << 8 | 1)) /* 10.1.x.x */
return SK_PASS;
if (ctx->local_port < 7000 || ctx->local_port > 7999)
return SK_PASS;
sk = bpf_map_lookup_elem(&target, &zero);
if (!sk)
return SK_PASS; /* nobody to steer to: normal lookup */
err = bpf_sk_assign(ctx, sk, 0);
bpf_sk_release(sk);
return err ? SK_DROP : SK_PASS;
}
char LICENSE[] SEC("license") = "GPL";
// steer.c — one listening socket, steered to by steer.bpf.o; serves N connections and exits
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "steer.skel.h"
static const char *str(struct sockaddr_in *a)
{
static char s[32];
snprintf(s, sizeof(s), "%s:%u", inet_ntoa(a->sin_addr), ntohs(a->sin_port));
return s;
}
int main(int argc, char **argv)
{
struct sockaddr_in sa = { .sin_family = AF_INET, .sin_port = htons(1234) };
int n = argc > 1 ? atoi(argv[1]) : 3, zero = 0;
/* An ordinary listener on 127.0.0.1:1234. It is not bound to 10.1.x.x at all. */
int lfd = socket(AF_INET, SOCK_STREAM, 0);
inet_pton(AF_INET, "127.0.0.1", &sa.sin_addr);
if (bind(lfd, (void *)&sa, sizeof(sa)) || listen(lfd, 64))
return perror("bind/listen"), 1;
struct steer_bpf *skel = steer_bpf__open_and_load();
if (!skel)
return 1;
__u64 v = lfd;
bpf_map__update_elem(skel->maps.target, &zero, 4, &v, 8, BPF_ANY);
int netns = open("/proc/self/ns/net", O_RDONLY);
struct bpf_link *link = bpf_program__attach_netns(skel->progs.steer, netns);
if (!link)
return perror("attach"), 1;
printf("listening on %s, steering 10.1.0.0/16 ports 7000-7999 to it\n", str(&sa));
fflush(stdout);
while (n--) {
struct sockaddr_in local, peer;
socklen_t l1 = sizeof(local), l2 = sizeof(peer);
char line[128];
int c = accept(lfd, (void *)&peer, &l2);
getsockname(c, (void *)&local, &l1); /* the address the client dialled */
int k = snprintf(line, sizeof(line), "fd %d answered %s", lfd, str(&local));
k += snprintf(line + k, sizeof(line) - k, " for %s\n", str(&peer));
write(c, line, k);
close(c);
}
bpf_link__destroy(link);
return 0;
}
To make the addresses local in the first place, a route marks the whole /16 as local, a trick that predates BPF: any address in it is accepted by this host, and without a matching listener it is refused like any other closed port.
# steer.sh — make 10.1.0.0/16 local, start the server, dial four addresses, then one more
ip route add local 10.1.0.0/16 dev lo
./steer 3 &
sleep 0.5
for a in 10.1.0.1/7000 10.1.42.42/7123 10.1.255.254/7999 10.1.0.1/8000; do
cat < /dev/tcp/${a%/*}/${a#*/}
done
wait # the server has served its three and exited
cat < /dev/tcp/10.1.0.1/7000
$ sudo bash steer.sh
listening on 127.0.0.1:1234, steering 10.1.0.0/16 ports 7000-7999 to it
fd 3 answered 10.1.0.1:7000 for 10.1.0.1:48354
fd 3 answered 10.1.42.42:7123 for 10.1.42.42:39558
fd 3 answered 10.1.255.254:7999 for 10.1.255.254:50402
steer.sh: connect: Connection refused
steer.sh: line 6: /dev/tcp/10.1.0.1/8000: Connection refused
steer.sh: connect: Connection refused
steer.sh: line 9: /dev/tcp/10.1.0.1/7000: Connection refused
The socket listening on 127.0.0.1:1234 answered connections to three addresses it never bound,
and getsockname() on each accepted connection reports the address the client dialled, so the
application can still tell them apart. Port 8000 is outside the program’s range and was refused as
usual. After the server exited and its link with it, port 7000 was refused too: with no program
attached, the lookup is the ordinary one.
cgroup sock_addr: a service address no packet carries
The last hook doesn’t steer packets or connections. It changes the arguments of the system call.
BPF_PROG_TYPE_CGROUP_SOCK_ADDR programs (4.17) run inside connect(), bind(), sendmsg()
(4.18) and recvmsg() (5.2), and since 5.8 inside getpeername() and getsockname(), for sockets
in the cgroup they are attached to, and they can rewrite the address. 6.7 extended them to Unix
sockets.
That is enough to build a load balancer that never translates a packet. Kubernetes gives each service
a virtual IP; kube-proxy traditionally implements it with iptables or IPVS rules that translate
every packet’s destination. A connect4 program can instead rewrite the destination once, in
connect(), to a real backend. The socket is then an ordinary connection to that backend, and every
packet carries the backend’s address from the start:
// lb.bpf.c — a service address that no packet ever carries: 10.96.0.10:80
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
#define VIP 0x0a60000a /* 10.96.0.10 */
#define VPORT 80
#define BACKEND 0x7f000001 /* two backends, 127.0.0.1:8081 and 127.0.0.1:8082 */
struct orig {
__u32 ip;
__u32 port;
};
struct { /* socket cookie -> the address the app asked for */
__uint(type, BPF_MAP_TYPE_LRU_HASH);
__uint(max_entries, 65536);
__type(key, __u64);
__type(value, struct orig);
} rev SEC(".maps");
SEC("cgroup/connect4")
int lb_connect(struct bpf_sock_addr *ctx)
{
if (ctx->user_ip4 != bpf_htonl(VIP) || ctx->user_port != bpf_htons(VPORT))
return 1; /* not the service: connect as asked */
struct orig o = { ctx->user_ip4, ctx->user_port };
__u64 cookie = bpf_get_socket_cookie(ctx);
bpf_map_update_elem(&rev, &cookie, &o, BPF_ANY);
ctx->user_ip4 = bpf_htonl(BACKEND);
ctx->user_port = bpf_htons(bpf_get_prandom_u32() & 1 ? 8082 : 8081);
return 1; /* 1 = allow the (rewritten) connect */
}
SEC("cgroup/getpeername4")
int lb_peer(struct bpf_sock_addr *ctx)
{
__u64 cookie = bpf_get_socket_cookie(ctx);
struct orig *o = bpf_map_lookup_elem(&rev, &cookie);
if (o) { /* tell the app the address it thinks it is talking to */
ctx->user_ip4 = o->ip;
ctx->user_port = o->port;
}
return 1;
}
char LICENSE[] SEC("license") = "GPL";
The getpeername4 program is the other half: it puts the service address back when the application
asks whom it is connected to, using the socket cookie, a unique 64-bit ID for every socket, to
remember what each socket originally asked for. Two backends, the programs attached to the root
cgroup, and a client:
# lb.sh — two backends on 127.0.0.1, the client once without the programs and once with
mkdir -p /tmp/b1 /tmp/b2
echo "backend 8081" > /tmp/b1/index.html
echo "backend 8082" > /tmp/b2/index.html
python3 -m http.server 8081 --bind 127.0.0.1 --directory /tmp/b1 > /dev/null 2>&1 &
python3 -m http.server 8082 --bind 127.0.0.1 --directory /tmp/b2 > /dev/null 2>&1 &
sleep 1
python3 vipget.py 2>&1 | tail -1
bpftool prog loadall lb.bpf.o /sys/fs/bpf/lb
bpftool cgroup attach /sys/fs/cgroup connect4 pinned /sys/fs/bpf/lb/lb_connect
bpftool cgroup attach /sys/fs/cgroup getpeername4 pinned /sys/fs/bpf/lb/lb_peer
python3 vipget.py
# vipget.py — six connections to the service address, as an application sees them
import os, socket
for i in range(6):
s = socket.create_connection(("10.96.0.10", 80))
if i == 0: # the kernel's own view of the same connection
os.system("ss -tnH state established '( dport = 8081 or dport = 8082 )'")
s.sendall(b"GET / HTTP/1.0\r\n\r\n")
reply = b"".join(iter(lambda: s.recv(4096), b"")).decode()
print("getpeername() says", s.getpeername(), "-", reply.split("\r\n\r\n")[1].strip())
s.close()
$ sudo bash lb.sh
OSError: [Errno 101] Network is unreachable
0 0 127.0.0.1:55644 127.0.0.1:8082
getpeername() says ('10.96.0.10', 80) - backend 8082
getpeername() says ('10.96.0.10', 80) - backend 8082
getpeername() says ('10.96.0.10', 80) - backend 8082
getpeername() says ('10.96.0.10', 80) - backend 8081
getpeername() says ('10.96.0.10', 80) - backend 8081
getpeername() says ('10.96.0.10', 80) - backend 8081
Before the programs were attached, 10.96.0.10 was simply unroutable: there is no such host, no
route to it, and nothing on the machine answers to it. Afterwards, six connect()s to it reached the
two backends at random, the application’s getpeername() kept saying 10.96.0.10:80, and ss,
which reads the kernel’s socket table directly rather than calling getpeername(), shows the truth:
a connection to 127.0.0.1:8082. Nothing was translated, so there is no connection-tracking entry,
no per-packet cost and nothing to reverse on the reply.
Cilium’s datapath in January 2024
All of this is easiest to see in context, and the context for BPF networking is Cilium. It graduated in the CNCF in October; its release is 1.14, from last July; Tetragon, its sibling project for security observability (the subject of Part 10), reached 1.0 in November. Reading the BPF sources of the 1.14.0 tag, the datapath is assembled from exactly the hooks in this series:
bpf_lxc.c, attached at tc ingress on the host side of each pod’s veth (cil_from_container), handles everything a pod sends: policy, connection tracking, service translation for traffic that didn’t go through a socket hook, and the routing decision, which with “BPF host routing” ends inbpf_redirect_neigh()rather than in the host’s stack.bpf_host.c, attached at tc on the node’s physical devices (cil_from_netdev), handles traffic arriving for pods and, with BPF host routing on, delivers it withbpf_redirect_peer(). The helper that chooses,redirect_ep(), explains itself in a comment: going “via CPU backlog queue” is only needed when a fast ingress-to-ingress switch is impossible.bpf_xdp.caccelerates NodePort services and drops at XDP, as in Part 8.bpf_sock.cis the socket-level load balancer:cgroup/connect4,sendmsg4,recvmsg4,getpeername4,bind4andpost_bind4, with the IPv6 twins. It is the core of Cilium’s kube-proxy replacement, which it has offered since 1.6 in 2019, and the reason a pod connecting to a ClusterIP is connected to a backend before its first packet exists.
What 1.14 doesn’t have is anything from the first half of this post. Its tc programs are attached as
classic cls_bpf filters, and its pods are plugged in with veth, because tcx and netkit are newer
than the release. The plan is no secret, though: the commit that added netkit says that its authors
“plan to use netkit devices in Cilium as the main device type for connecting Pods”, in L3 mode, with
the peer in drop mode “so that no traffic is leaving between the time when a Pod is brought up by
the CNI plugin and programs attached by the agent”, tcx programs on the physical devices using
bpf_redirect_peer() on the way in and bpf_redirect_neigh() from the netkit peer on the way out.
That is, almost line for line, the lab in this post.
What we covered
- Classic tc attachments belong to the device, not to whoever made them: in one run, a monitor was silently starved by a firewall that picked a lower priority, the firewall was silently replaced by a tool that picked the same handle, and the firewall’s clean-up deleted everyone’s programs.
- tcx (6.6) puts an ordered list of up to 64 programs on each device’s ingress and egress,
ahead of classic tc. The mprog API behind it places programs relative to each other
(
BPF_F_BEFORE/AFTER), versions the list with a revision (ESTALEon a staleexpected_revision), and makes the link the only handle that can detach (EBUSYotherwise).tccan’t see or delete any of it. - netkit (6.7) is a veth-like pair whose transmit runs BPF programs and can redirect immediately, so a pod’s outbound traffic can leave the node without the backlog hop and second receive pass that veth imposes. Programs attach only through the host-side primary; the peer can be created with a drop policy. iproute2 6.7.0 can’t create one yet, so this post did it with one rtnetlink message.
- Measured in one VM, a netkit pod sent 6.2% more small packets per second than a veth pod running the same program, about 52 ns per packet, while round trips on one CPU separated netkit from that veth by only 0.01 µs, within the spread. The clear gains were BPF routing over kernel routing, and the clearest limit was that a pod still costs more than the host’s own namespace.
- sockmap + sk_msg carried every byte of 22,000 ping-pongs between two local sockets with six loopback packets instead of 44,008, cut the one-CPU round trip from 3.44 to 2.50 µs and made one bulk stream 38% slower; Cilium dropped its version of the trick in 1.14.
- sk_lookup (5.9) let one listener on
127.0.0.1:1234accept connections for a /16 and a thousand ports. - cgroup sock_addr programs rewrote
connect()from a service address to a backend andgetpeername()back again: load balancing with no per-packet work, as Cilium’s socket LB does.
Part 12 goes back to eBPF for Windows, two years after the first look at it in Part 7.
A note on the evidence
What I ran, and where. Every listing in this post is pasted from a real run, and every C file,
script and command block was extracted from this page and run as shown, in one boot. The machine
was a KVM virtual machine with 4 virtual CPUs and 4 GiB of memory, itself running nested inside
another hypervisor, booting Ubuntu’s mainline build of Linux 6.7 (6.7.0-060700-generic #202401072033, built from the v6.7 tag on release day; CONFIG_NETKIT=y, veth, sch_ingress and
cls_bpf as modules) on a minimal Ubuntu 23.04 userland built from the release archive only:
clang 15.0.7, iproute2 6.1.0, iperf3 3.12 and Python 3.11.2. Ubuntu 23.04 ships libbpf 1.1, which
has neither tcx nor netkit, so I built libbpf v1.3.0 and bpftool v7.3.0 (with its libbpf submodule
at the same libbpf commit) from their release tags inside that userland and installed them under
/usr/local. I checked iproute2’s tags for netkit support: there is none in v6.7.0 (8 January), and
the commit that adds it (e4956e7f, dated 22 November) is not in any release yet, so I did not
build iproute2 and created the netkit pair with nkadd.c instead.
The timings. All of them come from one run. That run was meant to have the host to itself, but for about a minute near its start another test virtual machine was still running beside it, so I repeated the whole run, unchanged, with nothing else running. The repeat agreed on every conclusion: netkit sent 5.6% more small packets than veth with BPF (1,214.9 against 1,150.9 thousand a second, ahead in 8 of 9 rounds, against 6.2% and 9 of 9 above), its round trip was 3.63 against 3.71 µs (ahead in all 9 rounds, where the first run had them tied), and sockmap’s round trip was 2.50 against 3.41 µs. The tables keep the first run’s numbers. In each of 9 rounds every configuration was measured once, in an order rotated from round to round for the pods and alternated for the sockets; BPF run-time statistics were off. The tables give the median of the rounds and the range from the lowest round to the highest; each round’s latency figure is itself the median of 20,000 timed round trips. The client was pinned to virtual CPU 1 and the servers to CPU 1 or CPU 2 as stated. The UDP figure is the sending rate iperf3 reports for the client, not what arrived: the receiver lost nearly everything, which does not matter for a measure of the sender’s per-packet cost. A nested VM inflates anything that crosses CPUs (above all the cross-CPU round trips, which are dominated by waking another virtual CPU) and makes absolute numbers non-transferable to hardware. The comparisons within a run are what I rely on, and where two configurations’ ranges overlap I have said so rather than reported a winner.
What I trimmed. bpftool net show and bpftool link show listings are cut to the lines about
the devices in question, marked ...; the ip -d link lines are cut after the first few fields,
also marked. Program, map and link IDs, ifindexes, ephemeral ports and random backend choices are as
printed in that run. Nothing that carries the time of the run is shown.
What I cited rather than ran. The kernel versions for each hook, which I checked by asking which
release tag first contains the commit that introduced it: tcx e420bed02507 and mprog 053c8e1f235d
(6.6), netkit 35dfaad7188c (6.7), bpf_redirect_neigh() b4ab31414970 and bpf_redirect_peer()
9aa1206e8f48 (5.10), sockmap 174a79ff9515 (4.14), sockhash 81110384441a (4.18), sk_msg
4f738adba30a (4.17), sock_ops 40304b2a1567 (4.13), sk_lookup e9ddbb7707ff (5.9),
bpf_sk_assign() cf7fbe660f2d (5.7), connect4 d74bad4e74ee (4.17), sendmsg4 1cedee13d25a
(4.18), recvmsg4 983695fa6765 (5.2), getpeername4 1b66d253610c (5.8), the Unix-socket hooks
859051dd165e (6.7), clsact 1f211a1b929c (4.5). The quotations about netkit’s purpose and
Cilium’s plans are from the commit message of 35dfaad7188c. The kernel code excerpts are from the
6.7 source. The Cilium paragraph comes from reading the bpf/ directory of the v1.14.0 tag, and the
removal of its sockops acceleration from Cilium commit 87c8746e25 and issue 23556. Release dates
are from the projects’ release pages.
What I’d still change. One VM cannot show what netkit is for at its best: many pods, real NICs and packet rates high enough for softirq scheduling to matter. I measured the mechanism, one sender at a time, and the difference it makes there is small. A two-machine test with a physical NIC, and a look at CPU time per packet rather than round trips, would say more. The sockmap comparison is one client and one server on loopback; the trade-off between request-response and bulk traffic is clear, but where it crosses over depends on message sizes I didn’t sweep.
The Network Plumbing Grows Up