← Writing

Dropping Packets Before the Kernel Sees Them

61 min readSystemsEbpfLinuxXdpNetworkingTc
Contents

On Linux 6.1, one C function that reads a packet’s UDP destination port and decides whether to keep it ran in two places: in XDP, at the network driver, and in tc, one layer further up. Raced against iptables and nftables on one CPU of a virtual machine, the tc copy dropped 3.10 million packets a second, the best of the lot, and iptables’ INPUT chain managed 2.19 million. XDP, the hook built to be the fastest place in the kernel to drop a packet, managed 2.10 million: the worst of the six filters, and no better than having no filter at all.

That last number is not a mistake, and the reason for it is the best way into this post. On a real network card, XDP runs before the kernel has spent anything on a packet, and nothing else comes close. On the virtual interface I measured, the kernel had already spent most of it. Where that money goes, stage by stage, and which hook sees a packet after which stage, is what this part is about.

This is Part 8 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 was run on Linux 6.1, released a week ago, in a virtual machine with a Ubuntu 22.04 userland; the loaders use libbpf 1.0.1, and xdp-tools is the 1.2.9 release from Wednesday. The output is pasted from those runs. The note at the end says exactly where and how.

A packet you would rather not have

Every machine on the internet receives traffic it doesn’t want. Most of it is harmless noise, but some of it is a flood: millions of small packets a second, aimed at one port, sent to use up something. The usual answer on Linux is a firewall rule, and it works. iptables -A INPUT -p udp --dport 9 -j DROP and the packets stop reaching the application.

What the rule doesn’t do is stop the packets costing anything. By the time a packet reaches iptables’ INPUT chain, the kernel has taken it off the network card, allocated memory for it, filled in a few hundred bytes of bookkeeping, tried to merge it with others, checked its IP header, and looked up where it is going. The DROP rule throws all of that away. At a few packets a second nobody cares. At a few million a second, that work is the attack: the CPUs spend their time preparing packets for a rule that will discard them, and the traffic you do want waits behind them.

So the question for this post is not whether the kernel can drop a packet, but where: how early in its life a program can look at it and say no, and what has already been paid by then. eBPF has two answers. XDP runs a program in the network driver, on the raw bytes, before the kernel has built anything around them. tc runs a program a little later, on the kernel’s own packet structure, but before any of IP. They are the two halves of this part, and to see why they sit where they do, we need the path a packet takes in.

The receive path, stage by stage

Here is what happens to one incoming UDP packet on a Linux 6.1 machine with an ordinary network card. Each stage is a few hundred to a few thousand instructions, and the order matters more than the details.

The card and the ring. The network card has a ring of receive descriptors, each pointing at a buffer the driver gave it in advance. A frame arrives, the card copies it into the next buffer by DMA, marks the descriptor as used and, eventually, raises an interrupt. At this point the packet is a run of bytes in a page of memory, and the CPU hasn’t touched it.

NAPI. The driver’s interrupt handler does almost nothing: it masks further interrupts and schedules its NAPI poll function to run in softirq context, the kernel’s deferred-work mechanism for exactly this. The poll function then takes packets off the ring in batches of up to 64. Under load, interrupts stay off and the poll keeps draining the ring, which is how a single CPU gets through millions of packets a second.

The sk_buff. For each packet, the driver now builds a struct sk_buff, the structure every packet travels in for the rest of its life in the kernel. On this kernel it is 232 bytes, plus a separate skb_shared_info at the end of the data buffer, and it is filled in field by field: lengths, protocol, the device it came from, checksum status, hash, timestamp. It is allocated from a slab cache, and the fields are written into memory the CPU has to bring into its cache to write. This is the single most expensive thing that happens to a small packet, and everything after this point works on the sk_buff, not on the bytes.

GRO. Generic receive offload tries to merge consecutive segments of the same TCP or UDP flow into one large sk_buff, so the layers above process one 64 KiB packet instead of forty-odd small ones. For a flood of unrelated small packets it is mostly a lookup that finds nothing.

__netif_receive_skb_core. This one function, in net/core/dev.c, is where the protocol stack proper begins, and several hooks hang off it in a fixed order. In 6.1 it runs generic XDP first (we’ll come to what that is), then delivers a copy to any packet taps, which is how tcpdump and other AF_PACKET sockets see traffic, then runs the tc ingress hook, then netfilter’s ingress hook (nftables’ netdev family), and finally hands the packet to the handler registered for its protocol: ip_rcv for IPv4.

IP. ip_rcv checks the IP header: version, length, checksum. Then netfilter’s PREROUTING hook runs, in priority order: the raw table, then connection tracking if it is loaded (it looks every packet up in a hash table of flows, and creates an entry for new ones), then mangle and nat. Then the routing decision: is this packet for this machine, or to be forwarded? For a local destination, netfilter’s INPUT hook runs, and that is where most host firewalls keep their rules.

UDP and the socket. Finally UDP verifies the checksum, looks up the socket bound to the destination port, and appends the sk_buff to that socket’s receive queue, waking the process blocked in recv(). If no socket is bound to the port, the kernel counts the packet in NoPorts, may send back an ICMP “port unreachable”, and frees it.

Each hook along this path can drop the packet, and each drop saves exactly the stages after it. The figure lets you pick a hook and see which stages a packet dropped there has already been through. The rates in it are the measurements from later in this post, which, as the opening warned, need reading with care.

One packet's way in, and where each hook can stop it

Pick a hook: teal stages have already been paid for when it runs; faded ones never happen to a packet dropped there.

  1. Frame lands in the receive ring · NIC DMA; on veth, the sender's sk_buff is queued for veth1
  2. XDP offload · on the NIC's own processor
  3. Driver's NAPI poll picks it up · softirq on one CPU
  4. XDP native · in the driver, on raw bytes
  5. sk_buff allocated and filled in · 232-byte struct sk_buff + metadata
  6. GRO tries to merge it into a flow
  7. XDP generic · __netif_receive_skb_core
  8. Packet taps: tcpdump, AF_PACKET
  9. tc ingress · clsact + cls_bpf
  10. nftables ingress · netdev family
  11. IP: header checked, ip_rcv
  12. netfilter PREROUTING, raw table
  13. Connection tracking · only if loaded; not in this lab
  14. Routing decision: deliver locally or forward
  15. netfilter INPUT, filter table
  16. UDP: checksum, socket lookup
  17. No socket on the port · counted in NoPorts, dropped
  18. Socket receive queue; the reader wakes

Dropped here

hookmedian drop rate, this lab
XDP, native2.10 Mpps
XDP, generic2.60 Mpps
tc ingress, BPF3.10 Mpps
nftables ingress2.78 Mpps
iptables raw2.74 Mpps
iptables INPUT2.19 Mpps
no rule2.08 Mpps

Order of stages from the Linux 6.1 source. Rates are the median of five rounds on one CPU of a KVM guest, dropping 60-byte UDP frames over a veth pair: their order and ratios carry, their absolute values are not what a physical NIC would show.

Two consequences of that order are worth spelling out, because both surprise people. First, a packet dropped by XDP is never seen by tcpdump, because the taps come after it; a packet dropped by tc is seen, because the taps come before. If you are debugging a filter with tcpdump on the same machine, which hook it sits in decides whether you can see what it throws away. Second, the raw table exists precisely to get in before connection tracking: a DROP in raw PREROUTING doesn’t create a conntrack entry, and a DROP in INPUT does, if conntrack is loaded.

XDP: a program in the driver

XDP, the eXpress Data Path, was merged in Linux 4.8 in October 2016, with support in one driver, Mellanox’s mlx4. The idea is simple to state: call a BPF program from inside the driver’s NAPI poll, for each packet, before the sk_buff is built, and let it decide what happens next. If the answer is “drop”, the driver puts the buffer straight back on its receive ring. No allocation, no bookkeeping, nothing to free: the packet cost one descriptor read and one program run.

The program receives a struct xdp_md, and on 6.1 it has six fields:

struct xdp_md {
	__u32 data;
	__u32 data_end;
	__u32 data_meta;
	/* Below access go through struct xdp_rxq_info */
	__u32 ingress_ifindex; /* rxq->dev->ifindex */
	__u32 rx_queue_index;  /* rxq->queue_index  */

	__u32 egress_ifindex;  /* txq->dev->ifindex */
};

That is copied from include/uapi/linux/bpf.h in the 6.1 tree. data and data_end bound the packet: the program may read and write the bytes between them, and nothing else. data_meta points at a small area just before the packet where a program can leave notes for whatever handles the packet next. The rest identify where the packet came from. There is no length field, no protocol, no checksum status: at this point nobody has looked at the packet yet, so there is nothing to report. data and data_end are declared as 32-bit integers, not pointers, and the structure doesn’t exist in the kernel in this form at all: the verifier rewrites each access into a load from the kernel’s real structure, which we’ll see in a moment.

The program’s return value is the verdict, one of five:

  • XDP_DROP: recycle the buffer, the packet never existed.
  • XDP_PASS: carry on as normal. The driver builds the sk_buff and the packet goes up the path above, unaware it was looked at.
  • XDP_TX: send the packet back out of the interface it arrived on, usually after the program has rewritten it. Present from 4.8.
  • XDP_REDIRECT: send it somewhere else, chosen by a helper call: another interface, another CPU, or a user-space socket. Added in 4.14.
  • XDP_ABORTED: the program hit an error. The packet is dropped, and the xdp:xdp_exception tracepoint fires so that the error can be seen. It is value 0, so a program that returns without setting a verdict aborts.

That is the whole interface. What XDP doesn’t give you is as important: no access to the socket, the connection state, the routing table, or anything else the stack works out later, because none of it has been worked out yet. An XDP program sees bytes and must work out everything else itself.

Native, generic and offloaded

“In the driver” needs qualifying, because a driver has to be changed to call the program. There are three ways an XDP program can run, chosen when it is attached:

Native mode (XDP_FLAGS_DRV_MODE, ip link set ... xdpdrv) is the real thing: the driver calls the program from its NAPI poll on the raw buffer. The driver has to implement it, and through 2022 about thirty drivers in 6.1 have, among them Intel’s i40e, ice and ixgbe, Mellanox’s mlx4 and mlx5, Broadcom’s bnxt, Amazon’s ENA, and virtio-net and Hyper-V’s netvsc for virtual machines. The virtual Ethernet pair, veth, has had native XDP since 4.19, which matters for the lab below.

Generic mode (XDP_FLAGS_SKB_MODE, xdpgeneric), added in 4.12, works on any interface at all, because it doesn’t involve the driver. The kernel runs the program in __netif_receive_skb_core, after the sk_buff has been built, by pointing data and data_end at the sk_buff’s buffer. It exists so that XDP programs can be written and tested anywhere, and it gives them the same semantics, but none of the speed: by the time it runs, the expensive part has happened. It costs a little extra, too: XDP promises programs 256 bytes of headroom in front of the packet and a linear buffer, so generic mode reallocates the sk_buff’s head when it doesn’t have them.

Offload (XDP_FLAGS_HW_MODE, xdpoffload), whose flag arrived in 4.13, runs the program on the network card’s own processor, so a dropped packet never crosses the PCIe bus at all. Netronome’s SmartNICs, through the nfp driver, are the only cards in 6.1 that implement it (the other driver that does is netdevsim, the kernel’s simulated device for testing), and only for a subset of helpers and maps. I don’t have one, so this post mentions it and moves on.

If you attach without asking for a mode, the kernel uses native when the driver supports it and falls back to generic when it doesn’t.

Reading a packet the verifier will accept

An XDP program’s input is untrusted bytes from the network, and it reads them through raw pointers. That would be the most dangerous thing a BPF program could do, if the verifier let it. The rule is the one from Part 1, applied to packets: every access through a packet pointer must be proven, on every path, to lie between data and data_end. The verifier knows neither value; packets differ in length. So the program has to compare, and the verifier learns from the comparison.

The idiom looks like this, and every XDP program is mostly made of it:

struct ethhdr *eth = data;
if ((void *)(eth + 1) > data_end)
	return XDP_PASS;
/* from here on, the 14 bytes of *eth are readable */

The verifier tracks a packet pointer as an offset from data plus a range: the number of bytes past that pointer that some earlier comparison has proven to exist. After data + 14 > data_end has been taken as false, every pointer derived from data carries r=14, and loads of up to 14 bytes from offset 0 are allowed. Without the comparison, the range is 0 and the load is refused.

Here is the verifier’s own account of our program’s first check, from its log on 6.1. r8 holds data, r7 holds data_end:

5: (bf) r1 = r8                       ; R1_w=pkt(off=0,r=0,imm=0) R8_w=pkt(off=0,r=0,imm=0)
6: (07) r1 += 14                      ; R1_w=pkt(off=14,r=0,imm=0)
7: (2d) if r1 > r7 goto pc+42         ; R1_w=pkt(off=14,r=14,imm=0) R7_w=pkt_end(off=0,imm=0)
8: (71) r2 = *(u8 *)(r8 +13)          ; R2_w=scalar(umax=255,var_off=(0x0; 0xff)) R8_w=pkt(off=0,r=14,imm=0)

Read pkt(off=14,r=14) as “a pointer 14 bytes into the packet, through which 14 bytes are proven readable”. Before instruction 7 the range is 0; after the fall-through of the comparison it is 14, and instruction 8 may read byte 13. Then the same three steps again for the IP header, proving 34 bytes, and again for the UDP header. The UDP header is the interesting one, because its position depends on the packet: an IP header is ihl × 4 bytes, anywhere from 20 to 60. The program computes it, and the verifier follows:

21: (2d) if r3 > r2 goto pc+28        ; R2_w=scalar(umin=5,umax=15,var_off=(0x0; 0xf)) R3_w=5
22: (67) r2 <<= 2                     ; R2_w=scalar(umin=20,umax=60,var_off=(0x0; 0x3c))
23: (0f) r1 += r2
24: R1_w=pkt(id=1,off=14,r=0,umin=20,umax=60,var_off=(0x0; 0x3c),s32_min=0) ...
26: (2d) if r2 > r7 goto pc+23        ; R2=pkt(id=1,off=22,r=22,umin=20,umax=60,var_off=(0x0; 0x3c),s32_min=0) R7=pkt_end(off=0,imm=0)

The ihl field is the low four bits of a byte, so after & 15 the verifier knows it is at most 15, and after the program’s own ihl < 5 test, at least 5. Times four, 20 to 60. Adding that to a packet pointer gives a pointer with a variable offset, which the verifier keeps as a range (umin=20,umax=60) and a fresh id, with nothing yet proven readable (r=0). One more comparison and eight bytes past it are proven, wherever it lands. The stepper walks a real packet through all of it: one datagram my test sent to port 9, byte by byte, with the log lines for each check.

What the verifier lets the program read, one check at a time

The 60 bytes of one real datagram to UDP port 9, and the verifier's log for the XDP program parsing it.

proven readableread by this steprefusednot yet proven

The program starts: data in r8, data_end in r7

0: (61) r7 = *(u32 *)(r1 +4)  ; R1=ctx(off=0,imm=0) R7_w=pkt_end(off=0,imm=0)
1: (61) r8 = *(u32 *)(r1 +0)  ; R1=ctx(off=0,imm=0) R8_w=pkt(off=0,r=0,imm=0)

Two loads from the context. The verifier types them at once: pkt for the start of the packet and pkt_end for its end. r=0: nothing is proven readable yet, so not one byte of the packet may be touched.

Check 1: is there room for an Ethernet header?

5: (bf) r1 = r8  ; R1_w=pkt(off=0,r=0,imm=0) R8_w=pkt(off=0,r=0,imm=0)
6: (07) r1 += 14  ; R1_w=pkt(off=14,r=0,imm=0)
7: (2d) if r1 > r7 goto pc+42  ; R1_w=pkt(off=14,r=14,imm=0) R7_w=pkt_end(off=0,imm=0)

data + 14 > data_end jumps away to return 0. On the fall-through the verifier knows the packet has at least 14 bytes, and every pointer derived from data now carries r=14.

Read the EtherType, bytes 12 and 13

8: (71) r2 = *(u8 *)(r8 +13)  ; R2_w=scalar(umax=255,var_off=(0x0; 0xff)) R8_w=pkt(off=0,r=14,imm=0)
9: (67) r2 <<= 8  ; R2_w=scalar(umax=65280,var_off=(0x0; 0xff00))
10: (71) r3 = *(u8 *)(r8 +12)  ; R3_w=scalar(umax=255,var_off=(0x0; 0xff)) R8_w=pkt(off=0,r=14,imm=0)
11: (4f) r2 |= r3  ; R2_w=scalar() R3_w=scalar(umax=255,var_off=(0x0; 0xff))
12: (55) if r2 != 0x8 goto pc+37  ; R2_w=8

08 00: IPv4. Two one-byte loads, not one two-byte load, because struct ethhdr is packed and clang can't assume h_proto is aligned. The comparison is against 0x8 because the bytes 08 00, loaded little-endian, are 0x0008.

Check 2: is there room for an IP header?

13: (bf) r2 = r8  ; R2_w=pkt(off=0,r=14,imm=0) R8_w=pkt(off=0,r=14,imm=0)
14: (07) r2 += 34  ; R2=pkt(off=34,r=14,imm=0)
15: (2d) if r2 > r7 goto pc+34  ; R2=pkt(off=34,r=34,imm=0) R7=pkt_end(off=0,imm=0)

The same three steps, 34 bytes out: 14 of Ethernet plus the 20 of a minimal IPv4 header. Range proven: r=34.

Read the protocol, byte 23

16: (71) r2 = *(u8 *)(r8 +23)  ; R2_w=scalar(umax=255,var_off=(0x0; 0xff)) R8=pkt(off=0,r=34,imm=0)
17: (55) if r2 != 0x11 goto pc+32  ; R2_w=17

11 is 17, UDP. Anything else returns 0 and goes on up the stack.

Read the header length, the low half of byte 14

18: (71) r2 = *(u8 *)(r1 +0)  ; R1=pkt(off=14,r=34,imm=0) R2_w=scalar(umax=255,var_off=(0x0; 0xff))
19: (57) r2 &= 15  ; R2_w=scalar(umax=15,var_off=(0x0; 0xf))
20: (b7) r3 = 5  ; R3_w=5
21: (2d) if r3 > r2 goto pc+28  ; R2_w=scalar(umin=5,umax=15,var_off=(0x0; 0xf)) R3_w=5
22: (67) r2 <<= 2  ; R2_w=scalar(umin=20,umax=60,var_off=(0x0; 0x3c))

45: version 4, header length 5 words. After & 15 the verifier knows 0 to 15; after the program's own ihl < 5 test, 5 to 15; after the shift, 20 to 60 bytes.

Point at the UDP header: a variable offset

23: (0f) r1 += r2
24: R1_w=pkt(id=1,off=14,r=0,umin=20,umax=60,var_off=(0x0; 0x3c),s32_min=0) R2_w=Pscalar(umin=20,umax=60,var_off=(0x0; 0x3c))

udp = ip + ihl * 4. The verifier can't know where that lands, so it keeps the pointer as an offset range, umin=20,umax=60 past the IP header, gives it a new id, and resets its proven range to r=0. Nothing through it is readable yet, wherever it points.

Check 3: is there room for a UDP header?

24: (bf) r2 = r1  ; R1_w=pkt(id=1,off=14,r=0,umin=20,umax=60,var_off=(0x0; 0x3c),s32_min=0) R2_w=pkt(id=1,off=14,r=0,umin=20,umax=60,var_off=(0x0; 0x3c),s32_min=0)
25: (07) r2 += 8  ; R2=pkt(id=1,off=22,r=0,umin=20,umax=60,var_off=(0x0; 0x3c),s32_min=0)
26: (2d) if r2 > r7 goto pc+23  ; R2=pkt(id=1,off=22,r=22,umin=20,umax=60,var_off=(0x0; 0x3c),s32_min=0) R7=pkt_end(off=0,imm=0)

udp + 8 > data_end, and on the fall-through r=22: 8 bytes proven past the UDP pointer, whichever of its possible positions it has. On this packet ihl is 5, so the UDP header is bytes 34 to 41.

Read the destination port, bytes 36 and 37

27: (69) r1 = *(u16 *)(r1 +2)  ; R1_w=scalar(umax=65535,var_off=(0x0; 0xffff))
28: (dc) r1 = be16 r1  ; R1_w=scalar()

00 09, network byte order: port 9. be16 is bpf_ntohs, one instruction. Every packet read the program does is now behind us; the rest uses only the stack and the maps.

Count it, look it up, decide

29: (6b) *(u16 *)(r10 -18) = r1  ; R1_w=scalar() R10=fp0 fp-24=mm??????
30: (bf) r2 = r10  ; R2_w=fp0 R10=fp0
31: (07) r2 += -18  ; R2_w=fp-18
32: (18) r1 = 0xffffa036c30fe800  ; R1_w=map_ptr(off=0,ks=2,vs=16,imm=0)
34: (85) call bpf_map_lookup_elem#1  ; R0=map_value_or_null(id=2,off=0,ks=2,vs=16,imm=0)
35: (55) if r0 != 0x0 goto pc+15  ; R0=0

The port goes on the stack as the key, and the per-CPU seen map is looked up. Port 9 is in blocked, so this packet's verdict is XDP_DROP. Its UDP checksum, 14 2e, is only the pseudo-header sum: the sender left the rest to veth's checksum offload, which matters later.

Without check 1: refused

; if (eth->h_proto != bpf_htons(ETH_P_IP))
5: (71) r1 = *(u8 *)(r8 +13)
invalid access to packet, off=13 size=1, R8(id=0,off=13,r=0)
R8 offset is outside of the packet

Delete the first bounds check and load the object again. The first packet read, byte 13, is through a pointer with r=0, and the verifier rejects the whole program before it ever runs.

Log lines are the verifier's, trimmed to the instructions of each step. pkt(off=N,r=R) is a pointer N bytes into the packet through which R bytes have been proven readable; pkt_end is data_end. Bytes: one datagram udpsend.py sent to 10.0.0.2:9, captured on veth1 with tcpdump -xx: 14 bytes of Ethernet, 20 of IPv4, 8 of UDP, 18 of payload (the letter x).

Leave out the first check and the program is refused before it runs. This is the same object with the two lines of the Ethernet check deleted, loaded with bpftool:

; if (eth->h_proto != bpf_htons(ETH_P_IP))
5: (71) r1 = *(u8 *)(r8 +13)
invalid access to packet, off=13 size=1, R8(id=0,off=13,r=0)
R8 offset is outside of the packet
processed 6 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

off=13 size=1, r=0: a one-byte read at offset 13, through a pointer with nothing proven. The packet that arrives might be shorter than 14 bytes, and the verifier won’t assume it isn’t. Two other details in that log are worth noticing. The load is one byte, not two: struct ethhdr is declared packed, so clang can’t assume the 16-bit h_proto is aligned and reads it a byte at a time. And the verifier rejects the program at the first bad access it finds, on the first path it walks; Part 4 is about how that walk works, and how much worse the messages get.

One filter, two hooks

Here is the worked example of this part: a UDP port filter. It drops packets to ports listed in one map, counts packets and bytes per destination port in another, and lets everything else through. It is written once, as a function over two pointers, and called from two programs: one for XDP, one for tc.

// udpfilter.bpf.c — one UDP port filter, built for two hooks: XDP and tc
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/pkt_cls.h>
#include <linux/udp.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

struct counter {
	__u64 packets;
	__u64 bytes;
};

struct {
	__uint(type, BPF_MAP_TYPE_HASH);
	__uint(max_entries, 64);
	__type(key, __u16);			/* UDP destination port */
	__type(value, __u8);
} blocked SEC(".maps");

struct {
	__uint(type, BPF_MAP_TYPE_PERCPU_HASH);
	__uint(max_entries, 1024);
	__type(key, __u16);
	__type(value, struct counter);
} seen SEC(".maps");

/* Returns 1 to drop, 0 to let the packet go on. */
static __always_inline int udp_verdict(void *data, void *data_end, __u64 len)
{
	struct ethhdr *eth = data;
	struct iphdr *ip;
	struct udphdr *udp;
	struct counter *c, zero = {};
	__u16 port;

	if ((void *)(eth + 1) > data_end)
		return 0;
	if (eth->h_proto != bpf_htons(ETH_P_IP))
		return 0;

	ip = (void *)(eth + 1);
	if ((void *)(ip + 1) > data_end)
		return 0;
	if (ip->protocol != IPPROTO_UDP || ip->ihl < 5)
		return 0;

	udp = (void *)ip + ip->ihl * 4;
	if ((void *)(udp + 1) > data_end)
		return 0;

	port = bpf_ntohs(udp->dest);
	c = bpf_map_lookup_elem(&seen, &port);
	if (!c) {
		bpf_map_update_elem(&seen, &port, &zero, BPF_NOEXIST);
		c = bpf_map_lookup_elem(&seen, &port);
		if (!c)
			return 0;
	}
	c->packets++;
	c->bytes += len;

	return bpf_map_lookup_elem(&blocked, &port) != NULL;
}

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

	return udp_verdict(data, data_end, data_end - data) ? XDP_DROP : XDP_PASS;
}

SEC("tc")
int tc_filter(struct __sk_buff *skb)
{
	void *data = (void *)(long)skb->data;
	void *data_end = (void *)(long)skb->data_end;

	return udp_verdict(data, data_end, skb->len) ? TC_ACT_SHOT : TC_ACT_OK;
}

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

Taking it from the top:

  • The headers are the kernel’s user-space API headers, not vmlinux.h. Networking programs usually work this way: they need the wire formats (ethhdr, iphdr, udphdr) and the constants (ETH_P_IP, IPPROTO_UDP, TC_ACT_SHOT), which are stable UAPI and #defines that vmlinux.h doesn’t carry. Nothing here reads a kernel-internal structure, so there is nothing for CO-RE to relocate.
  • blocked is a hash map from port to a byte; a port is blocked if it is present. User space fills it.
  • seen is a per-CPU hash: every CPU has its own copy of each value, so the increments later need no atomic instructions and never contend. User space adds the copies up when it reads. On a machine taking millions of packets a second across many CPUs, a shared counter would be the slowest thing in the program.
  • udp_verdict is static __always_inline, so each program gets its own copy and there is no call. It does the three bounds checks walked through above, in order, each one before the first read it protects. ip->ihl < 5 is there for correctness, not safety: a header claiming fewer than 20 bytes is malformed, and the verifier is satisfied either way. Every failed check returns 0, “not mine, pass it on”: a filter that drops what it can’t parse would drop ARP, IPv6, and everything else that isn’t IPv4 UDP.
  • The count inserts a zero entry the first time a port is seen, then increments in place. BPF_NOEXIST makes a racing second insert fail harmlessly; with per-CPU values, two CPUs never share the slot they write anyway.
  • The verdict is whether the port is in blocked.
  • xdp_filter gets its packet from ctx->data and ctx->data_end, measures the length as the distance between them, and turns the verdict into XDP_DROP or XDP_PASS.
  • tc_filter gets the same two pointers from an __sk_buff, takes the length from skb->len, and returns TC_ACT_SHOT or TC_ACT_OK. That the same parsing works on both is not an accident: at tc ingress the kernel points skb->data at the Ethernet header before it runs the program (cls_bpf_classify pushes the MAC header back on for exactly this), so both programs see a frame that starts with the destination MAC.

SEC("xdp") and SEC("tc") tell libbpf the program types, BPF_PROG_TYPE_XDP and BPF_PROG_TYPE_SCHED_CLS. Loaded, each program is 70 instructions, and the verifier processed 87 and 86 instructions respectively to prove them, walking both sides of every branch it couldn’t decide.

tc, and why it’s still worth having

tc is Linux’s traffic-control subsystem, the thing that shapes, queues and prioritises traffic, configured with the tc command from iproute2. Its classifiers decide which class a packet belongs to and its actions decide what to do with it. BPF arrived there early. A classifier running classic BPF, cls_bpf, came in 3.13; it took eBPF programs in 4.1, the same release as kprobes. Two later changes made it what it is now:

  • Direct-action (da), in 4.4. Originally a classifier returned a class, and you attached separate actions to do things. With direct-action, the program’s return value is the action: TC_ACT_OK to let the packet through, TC_ACT_SHOT to drop it, TC_ACT_REDIRECT to send it elsewhere. One program, one decision, no tc rule language in between.
  • The clsact qdisc, in 4.5. A qdisc is the queueing discipline attached to an interface. clsact isn’t really one: it queues nothing and exists only to provide two attachment points, ingress and egress, where classifiers run. Before it, BPF on egress meant attaching to a real queueing qdisc’s classes.

That egress hook is the first thing tc has that XDP doesn’t. XDP is receive-only; there is no “XDP on transmit”. tc can see every packet a machine sends, after the stack has built it and before the driver gets it, which is where you enforce what a container may send, or rewrite outgoing headers.

The second difference is the context. A tc program gets a struct __sk_buff, a 192-byte view of the real sk_buff, and the stack has filled it in: len, protocol, mark, priority, ifindex, hash, VLAN fields, a pointer to the sending socket on egress, and more. It has helpers XDP lacks: bpf_skb_store_bytes with checksum fixups, bpf_skb_change_head to add room for encapsulation, bpf_redirect to another interface’s ingress or egress. And it runs after GRO, so on a busy TCP connection it sees fewer, larger packets.

Both contexts are fiction, in the same way: neither struct exists in the kernel as declared. The verifier rewrites every context access into a load from the real structure. Here are the first instructions of the two programs as the kernel holds them:

int xdp_filter(struct xdp_md * ctx):
; void *data_end = (void *)(long)ctx->data_end;
   0: (79) r7 = *(u64 *)(r1 +8)
; void *data = (void *)(long)ctx->data;
   1: (79) r8 = *(u64 *)(r1 +0)
int tc_filter(struct __sk_buff * skb):
; return udp_verdict(data, data_end, skb->len) ? TC_ACT_SHOT : TC_ACT_OK;
   0: (61) r7 = *(u32 *)(r1 +112)
; void *data_end = (void *)(long)skb->data_end;
   1: (79) r2 = *(u64 *)(r1 +80)
; void *data = (void *)(long)skb->data;
   2: (79) r3 = *(u64 *)(r1 +208)

Our C read ctx->data_end as a 32-bit field at offset 4 of xdp_md; the kernel runs a 64-bit load from offset 8 of its struct xdp_buff. For tc, skb->data is offset 76 of __sk_buff in our C and offset 208 of the real struct sk_buff in the kernel, and skb->data_end lives in a scratch area at offset 80 that the kernel fills in before each run. The programs are the same size in translation, 560 bytes, and JIT to 341 and 338 bytes of x86-64.

So which to use? If the job is to drop or redirect as early as possible on receive, and the NIC’s driver supports native XDP, XDP. If you need egress, need the stack’s view of the packet, need to modify it in ways XDP’s helpers don’t cover, or are on an interface without native XDP, tc. Real systems use both: Cilium attaches tc programs to every container’s interface and, for its XDP acceleration, an XDP program to the host’s physical one.

Attaching it: the libbpf way

The user-space half loads the object, fills blocked from the command line, attaches one program to the hook asked for, waits, then detaches and prints the per-port counts:

// udpfilter.c — attach udpfilter at one hook, block some ports, print what it saw
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <linux/if_link.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "udpfilter.skel.h"

struct counter {
	__u64 packets, bytes;
};

static volatile sig_atomic_t stop;
static void on_signal(int sig) { stop = 1; }

int main(int argc, char **argv)
{
	struct udpfilter_bpf *skel;
	struct counter *vals;
	unsigned int ifindex;
	int seconds, xdp_flags = 0, tc = 0, made_qdisc = 0, ncpu, err, i, seen_fd, blocked_fd;
	__u16 key, next, *prev = NULL;
	__u8 one = 1;

	if (argc < 4) {
		fprintf(stderr, "usage: %s IFACE xdp|xdpgeneric|tc-in|tc-out SECONDS [PORT...]\n",
			argv[0]);
		return 1;
	}
	ifindex = if_nametoindex(argv[1]);
	seconds = atoi(argv[3]);
	if (!ifindex) {
		perror(argv[1]);
		return 1;
	}
	if (!strcmp(argv[2], "xdp"))
		xdp_flags = XDP_FLAGS_DRV_MODE;		/* native: in the driver */
	else if (!strcmp(argv[2], "xdpgeneric"))
		xdp_flags = XDP_FLAGS_SKB_MODE;		/* generic: after the sk_buff */
	else if (!strcmp(argv[2], "tc-in"))
		tc = BPF_TC_INGRESS;
	else if (!strcmp(argv[2], "tc-out"))
		tc = BPF_TC_EGRESS;
	else {
		fprintf(stderr, "unknown hook %s\n", argv[2]);
		return 1;
	}

	skel = udpfilter_bpf__open();
	if (!skel)
		return 1;
	/* One object, two programs: load only the one this hook takes. */
	bpf_program__set_autoload(tc ? skel->progs.xdp_filter : skel->progs.tc_filter, false);
	if (udpfilter_bpf__load(skel)) {
		udpfilter_bpf__destroy(skel);
		return 1;
	}
	seen_fd = bpf_map__fd(skel->maps.seen);
	blocked_fd = bpf_map__fd(skel->maps.blocked);
	for (i = 4; i < argc; i++) {
		key = atoi(argv[i]);
		bpf_map_update_elem(blocked_fd, &key, &one, BPF_ANY);
	}

	LIBBPF_OPTS(bpf_tc_hook, hook, .ifindex = ifindex, .attach_point = tc);
	LIBBPF_OPTS(bpf_tc_opts, opts, .prog_fd = bpf_program__fd(skel->progs.tc_filter));
	if (tc) {
		err = bpf_tc_hook_create(&hook);	/* the clsact qdisc */
		made_qdisc = !err;
		if (!err || err == -EEXIST)
			err = bpf_tc_attach(&hook, &opts);	/* cls_bpf, direct-action */
	} else {
		err = bpf_xdp_attach(ifindex, bpf_program__fd(skel->progs.xdp_filter),
				     xdp_flags, NULL);
	}
	if (err) {
		fprintf(stderr, "attach to %s failed: %s\n", argv[1], strerror(-err));
		udpfilter_bpf__destroy(skel);
		return 1;
	}

	signal(SIGINT, on_signal);
	signal(SIGTERM, on_signal);
	printf("%s: %s attached, %d port(s) blocked, for %d s\n",
	       argv[1], argv[2], argc - 4, seconds);
	fflush(stdout);
	while (seconds-- > 0 && !stop)
		sleep(1);

	/* Detach before reading, so the numbers below are final. */
	if (tc) {
		opts.prog_fd = opts.prog_id = opts.flags = 0;
		bpf_tc_detach(&hook, &opts);
		if (made_qdisc) {	/* leave the device as we found it */
			hook.attach_point = BPF_TC_INGRESS | BPF_TC_EGRESS;
			bpf_tc_hook_destroy(&hook);
		}
	} else {
		bpf_xdp_detach(ifindex, xdp_flags, NULL);
	}

	ncpu = libbpf_num_possible_cpus();
	vals = calloc(ncpu, sizeof(*vals));
	printf("%-6s %12s %14s  %s\n", "port", "packets", "bytes", "verdict");
	while (vals && bpf_map_get_next_key(seen_fd, prev, &next) == 0) {
		__u64 packets = 0, bytes = 0;

		bpf_map_lookup_elem(seen_fd, &next, vals);	/* one value per CPU */
		for (i = 0; i < ncpu; i++) {
			packets += vals[i].packets;
			bytes += vals[i].bytes;
		}
		printf("%-6u %12llu %14llu  %s\n", next, (unsigned long long)packets,
		       (unsigned long long)bytes,
		       bpf_map_lookup_elem(blocked_fd, &next, &one) == 0 ? "drop" : "pass");
		key = next;
		prev = &key;
	}
	free(vals);
	udpfilter_bpf__destroy(skel);
	return 0;
}

The parts that are new since earlier parts of the series:

  • bpf_program__set_autoload(..., false). The object has two programs; a skeleton loads every program in it by default. Turning off the one we won’t attach means the kernel never sees it.
  • bpf_xdp_attach(ifindex, fd, flags, NULL) attaches through netlink, the same interface ip link uses, with the mode in flags. libbpf also has bpf_program__attach_xdp, which makes a bpf_link (XDP has had links since 5.9, as Part 3 described for other hooks), but it doesn’t take a mode, so to compare native and generic on purpose the netlink call is the one to use. The price is that the attachment outlives the process: if the loader is killed before bpf_xdp_detach, the program stays on the interface. A link would go with the process.
  • bpf_tc_hook_create adds the clsact qdisc (and returns -EEXIST if it is already there), and bpf_tc_attach adds a cls_bpf filter with our program, always in direct-action mode. At the end the program comes off with bpf_tc_detach, and if this loader created the qdisc it removes that too, which also removes anyone else’s filters on it: fine for a lab, rude on a shared machine.

The build is the usual three commands, with libbpf 1.0.1’s headers and static library from where I installed them:

clang -g -O2 -target bpf -I/opt/libbpf-1.0/include -c udpfilter.bpf.c -o udpfilter.bpf.o
bpftool gen skeleton udpfilter.bpf.o > udpfilter.skel.h
cc -g -O2 -Wall -I/opt/libbpf-1.0/include udpfilter.c /opt/libbpf-1.0/lib64/libbpf.a -lelf -lz -o udpfilter

The lab

The test bed is a KVM virtual machine with four vCPUs, running Linux 6.1. There is no physical network card in it, so the network is a pair of virtual Ethernet devices: veth0 lives in a network namespace called gen, with address 10.0.0.1, and its peer veth1 lives in the root namespace with 10.0.0.2. Anything sent out of one end arrives at the other, and the root namespace plays the server. The filter always sits on veth1:

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 lo up
ip -n gen link set veth0 up

Two small Python scripts make the traffic and count what arrives:

# udpsend.py — send COUNT datagrams of SIZE bytes to HOST, to each PORT given
import socket, sys

host, count, size, ports = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4:]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for port in ports:
    for _ in range(count):
        s.sendto(b"x" * size, (host, int(port)))
# udprecv.py — count the datagrams that reach a socket on PORT for SECONDS
import socket, sys, time

port, seconds = int(sys.argv[1]), float(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", port))
s.settimeout(0.2)
n, end = 0, time.time() + seconds
while time.time() < end:
    try:
        s.recv(2048)
        n += 1
    except socket.timeout:
        pass
print("port %d: %d datagrams reached the socket" % (port, n))

For each hook, I ran the filter blocking ports 9 and 53, put a socket on port 5353 in the root namespace, and sent 100 datagrams of 18 bytes to each of 9, 53, 5353 and 7777 from gen:

./udpfilter veth1 xdp 5 9 53 &
sleep 1
python3 udprecv.py 5353 2.5 &
sleep 0.3
ip netns exec gen python3 udpsend.py 10.0.0.2 100 18 9 53 5353 7777
port 5353: 100 datagrams reached the socket
veth1: xdp attached, 2 port(s) blocked, for 5 s
port        packets          bytes  verdict
7777            100           6000  pass
5353            100           6000  pass
53              100           6000  drop
9               100           6000  drop

Four ports, a hundred packets each, 60 bytes a packet: 14 of Ethernet, 20 of IP, 8 of UDP and 18 of payload. Ports 9 and 53 were dropped. 5353 reached its socket, all hundred. 7777 was passed and, with no socket there, discarded by UDP further up. While it was attached, ip link and bpftool showed where:

$ ip link show dev veth1
2: veth1@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 xdp qdisc noqueue state UP mode DEFAULT group default qlen 1000
    link/ether 5a:52:5d:35:93:d0 brd ff:ff:ff:ff:ff:ff link-netns gen
    prog/xdp id 17 tag 06f82af79d0adbd4 jited
$ bpftool net show dev veth1
xdp:
veth1(2) driver id 17

tc:

flow_dissector:

xdp in the ip link flags and driver in bpftool’s output both say native mode. Run as xdpgeneric, the same lines read xdpgeneric and generic id 22; as tc-in, the XDP slot is empty and bpftool lists veth1(2) clsact/ingress tc_filter:[26] id 26. The counts were the same all three times, as they should be: the same function, judging the same four hundred packets.

Egress is where tc earns its place, so the last run put the filter on veth1’s outgoing side, blocking port 9, and sent 50 datagrams each to ports 9 and 5353 from the root namespace, with a socket waiting on both ports in gen:

port 9: 0 datagrams reached the socket
port 5353: 50 datagrams reached the socket
veth1: tc-out attached, 1 port(s) blocked, for 4 s
port        packets          bytes  verdict
5353             50           3000  pass
9                50           3000  drop

The same program, unchanged, judging packets on their way out. On egress skb->data already points at the Ethernet header the stack has just written, so the parse is the same. Nothing about XDP could have done this.

Attaching it without writing a loader

A loader of your own is what a real tool needs, but the object file can be attached without one, three ways. iproute2 can do both hooks. On jammy, ip and tc are iproute2 5.15, built with libbpf 0.5, and they read BTF-defined maps from the object:

$ ip link set dev veth1 xdpgeneric obj udpfilter.bpf.o sec xdp
$ ip link show dev veth1
2: veth1@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 xdpgeneric qdisc noqueue state UP mode DEFAULT group default qlen 1000
    link/ether 5a:52:5d:35:93:d0 brd ff:ff:ff:ff:ff:ff link-netns gen
    prog/xdp id 34 tag 06f82af79d0adbd4 jited
$ bpftool map update name blocked key 9 0 value 1

Nothing fills blocked when ip loads the object, so bpftool does: key 9 0 is port 9 as two bytes in the machine’s byte order. Ten datagrams to each of ports 9 and 53 later, the per-CPU map shows all twenty arrived on CPU 1 (trimmed to that CPU):

$ bpftool map dump name seen
[{
        "key": 53,
        "values": [{
                "cpu": 1,
                "value": {
                    "packets": 10,
                    "bytes": 600
                }
            }
        ]
    },{
        "key": 9,
        "values": [{
                "cpu": 1,
                "value": {
                    "packets": 10,
                    "bytes": 600
                }
            }
        ]
    }
]
$ ip link set dev veth1 xdpgeneric off

For tc, the qdisc first, then the filter, with direct-action spelled out:

$ tc qdisc add dev veth1 clsact
$ tc filter add dev veth1 ingress bpf direct-action obj udpfilter.bpf.o sec tc
$ tc filter show dev veth1 ingress
filter protocol all pref 49152 bpf chain 0
filter protocol all pref 49152 bpf chain 0 handle 0x1 udpfilter.bpf.o:[tc] direct-action not_in_hw id 38 tag 8baf759635fed954 jited
$ tc qdisc del dev veth1 clsact

The third way is xdp-loader, from the XDP project’s xdp-tools, whose 1.2.9 release came out on Wednesday. Jammy doesn’t package it, so I built it from the release tarball. It solves a problem the others don’t: an interface has exactly one XDP slot, and two programs that both want it (a DDoS filter and a load balancer, say) can’t share it. xdp-loader goes through libxdp, which attaches a small dispatcher program to the interface and links the real programs into it as extensions, called in order of priority. Ours is one of possibly several:

$ xdp-loader load -m native -s xdp veth1 udpfilter.bpf.o
$ xdp-loader status veth1
CURRENT XDP PROGRAM STATUS:

Interface        Prio  Program name      Mode     ID   Tag               Chain actions
--------------------------------------------------------------------------------------
veth1                  xdp_dispatcher    native   43   94d5f00c20184d17
 =>              50     xdp_filter                50   06f82af79d0adbd4  XDP_PASS

$ ip link show dev veth1
2: veth1@if2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 xdp qdisc noqueue state UP mode DEFAULT group default qlen 1000
    link/ether 5a:52:5d:35:93:d0 brd ff:ff:ff:ff:ff:ff link-netns gen
    prog/xdp id 43 tag 94d5f00c20184d17 jited
$ xdp-loader unload veth1 --all

The interface now runs program 43, the dispatcher, not ours; ours is program 50, run by the dispatcher at priority 50 (the default), and the “chain actions” column says which of its verdicts pass control to the next program in the chain. The tag of xdp_filter, 06f82af79d0adbd4, is the same one every other loader produced: the same instructions, by four different routes into the kernel.

Sending packets back out

XDP_DROP is the verdict this post is named after, but the two forwarding verdicts are what XDP load balancers are built from. The smallest program that uses XDP_TX answers UDP port 7, the old echo service, from inside the driver:

// reflect.bpf.c — answer UDP port 7 from the driver: swap the addresses, XDP_TX
#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>

SEC("xdp")
int xdp_reflect(struct xdp_md *ctx)
{
	void *data = (void *)(long)ctx->data;
	void *data_end = (void *)(long)ctx->data_end;
	struct ethhdr *eth = data;
	struct iphdr *ip = (void *)(eth + 1);
	struct udphdr *udp = (void *)(ip + 1);
	unsigned char mac[ETH_ALEN];
	__be32 addr;
	__be16 port;

	if ((void *)(udp + 1) > data_end)	/* one check covers all 42 bytes */
		return XDP_PASS;
	if (eth->h_proto != bpf_htons(ETH_P_IP) || ip->ihl != 5 ||
	    ip->protocol != IPPROTO_UDP || udp->dest != bpf_htons(7))
		return XDP_PASS;

	__builtin_memcpy(mac, eth->h_dest, ETH_ALEN);
	__builtin_memcpy(eth->h_dest, eth->h_source, ETH_ALEN);
	__builtin_memcpy(eth->h_source, mac, ETH_ALEN);
	addr = ip->saddr;
	ip->saddr = ip->daddr;
	ip->daddr = addr;
	port = udp->source;
	udp->source = udp->dest;
	udp->dest = port;
	return XDP_TX;
}

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

It swaps the MAC addresses, the IP addresses and the UDP ports, and returns XDP_TX: the driver puts the same buffer on its transmit ring, and the packet leaves by the interface it came in on, never having been seen by the stack. Two details make it small. One bounds check covers all three headers, because the program only accepts ihl == 5, so the UDP header is at a fixed offset. And no checksum needs fixing: the IP checksum covers the two addresses, the UDP checksum covers both addresses and both ports, and a ones’-complement sum doesn’t care what order its terms come in. Swapping them changes nothing.

The test is a client in gen that sends one datagram to 10.0.0.2 port 7 and waits a second for an answer:

# echo.py — send one datagram to HOST port 7, wait a second for an answer
import socket, sys

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(1.0)
s.sendto(b"anyone there?", (sys.argv[1], 7))
try:
    data, addr = s.recvfrom(2048)
    print("reply from %s:%d: %r" % (addr[0], addr[1], data))
except socket.timeout:
    print("no reply")

Nothing in the root namespace listens on port 7, so any reply came from XDP. On veth it took three attempts to get one, and both failures are worth knowing:

$ ip link set dev veth1 xdpdrv obj reflect.bpf.o sec xdp
$ ip netns exec gen python3 echo.py 10.0.0.2
no reply
     rx_queue_0_xdp_tx: 0
     rx_queue_0_xdp_tx_errors: 1
$ ip netns exec gen ip link set dev veth0 xdpdrv obj reflect.bpf.o sec xdp
$ ip netns exec gen python3 echo.py 10.0.0.2
no reply
     rx_queue_0_xdp_tx: 1
     rx_queue_0_xdp_tx_errors: 1
$ ip netns exec gen nstat -az UdpInDatagrams UdpInCsumErrors
#kernel
UdpInDatagrams                  50                 0.0
UdpInCsumErrors                 1                  0.0
$ ip netns exec gen ethtool -K veth0 tx off
$ ip netns exec gen python3 echo.py 10.0.0.2
reply from 10.0.0.2:7: b'anyone there?'

(The two counter lines after each attempt are from ethtool -S veth1; the 50 datagrams already in UdpInDatagrams are the egress test’s.)

First failure: the peer has to be ready to receive XDP frames. XDP_TX on veth1 means “transmit to veth0”, and veth delivers an XDP frame by putting it on the peer’s own XDP receive ring, which only exists when the peer runs in its NAPI mode. In 6.1 the transmit path checks for that and fails without it, which is the xdp_tx_errors: 1. Since 5.13 enabling GRO on the peer turns the NAPI mode on, but in 6.1 the code that kicks the peer after an XDP_TX still checks for an XDP program there, not for NAPI, so the frame sits on the ring unprocessed. What works is to load an XDP program on the peer too. Ours passes everything not addressed to port 7, so loading the reflector on veth0 as well does nothing else.

Second failure: the checksum was never finished. With that, xdp_tx counted one, the reply crossed back, and UDP in gen threw it away: UdpInCsumErrors 1. The client’s datagram left veth0 with checksum offload: veth advertises that it will finish checksums the way real hardware does, so the stack writes only the pseudo-header part into the UDP checksum field and marks the sk_buff as “the device will complete this”. veth never needs to, because the sk_buff crosses to the peer with that mark intact and the receiver trusts it. XDP doesn’t carry the mark. It saw bytes, returned bytes, and the bytes had a half-done checksum, which the receiver checked and rejected. With offload switched off on veth0 the checksum is complete when it leaves, swapping preserves it, and the echo comes back. A real NIC computes the checksum on the wire, so this one is a veth artefact. It is also exactly the kind of thing that makes XDP feel different from the rest of the stack: there is no metadata, only bytes, so anything the stack would normally take care of is the program’s job.

XDP_REDIRECT generalises XDP_TX. The program calls bpf_redirect_map(&map, key, flags) and returns its result, and the map decides where the packet goes. Each kind of target has its own map type, added in the same burst of work: a BPF_MAP_TYPE_DEVMAP (4.14) holds network interfaces, so the packet goes out of another NIC, which is how an XDP router or load balancer forwards; a BPF_MAP_TYPE_CPUMAP (4.15) holds CPUs, and the packet is queued to a kernel thread on that CPU which builds the sk_buff there and passes it up the stack, spreading receive work across cores for traffic the NIC’s own hashing would put on one; an XSKMAP holds AF_XDP sockets, which are the last section of this post. The redirect is batched: frames are collected per destination during a NAPI poll and flushed together at the end, which is a large part of why it is fast. I didn’t build a redirect example for this part: the veth caveats above apply to it equally, and the measurements below had more to teach.

How fast does each drop point drop?

Now the race from the opening. Seven conditions, each dropping every UDP packet to port 9 arriving on veth1, at a different point in the path:

conditiondrop point
no ruleUDP finds no socket on port 9 (NoPorts)
iptables INPUTiptables -A INPUT -p udp --dport 9 -j DROP
iptables rawiptables -t raw -A PREROUTING -p udp --dport 9 -j DROP
nftables ingressa netdev table with an ingress chain on veth1: udp dport 9 counter drop
tcudpfilter veth1 tc-in 120 9
XDP genericudpfilter veth1 xdpgeneric 120 9
XDP nativeudpfilter veth1 xdp 120 9

Jammy’s iptables is iptables 1.8.7 on the nf_tables backend, so the two iptables rows are nftables underneath, running the old match code through its compatibility layer. There is no connection tracking in this lab: nothing loaded it. On a host with stateful rules, everything after the raw table would also pay for a conntrack lookup.

The sender. The obvious tool is pktgen, the kernel’s own packet generator: a kernel module you configure by writing to files in /proc/net/pktgen, which builds packets in a kernel thread and hands them straight to the driver. This is how I set it up in gen:

# pktgen.sh — run inside netns gen: one kernel thread sends 64-byte UDP to 10.0.0.2:9
DMAC=$1                                 # veth1's MAC address
PG=/proc/net/pktgen
echo "rem_device_all"   > $PG/kpktgend_0
echo "add_device veth0" > $PG/kpktgend_0
echo "count 0"          > $PG/veth0     # until told to stop
echo "clone_skb 0"      > $PG/veth0     # a fresh sk_buff for every packet
echo "pkt_size 60"      > $PG/veth0     # 64 bytes on the wire, with the FCS
echo "dst 10.0.0.2"     > $PG/veth0
echo "dst_mac $DMAC"    > $PG/veth0
echo "udp_dst_min 9"    > $PG/veth0
echo "udp_dst_max 9"    > $PG/veth0
echo "start"            > $PG/pgctrl    # returns when someone writes "stop"

It is fast, and in a trial pass it ran the first five conditions without trouble. With the filter attached as generic XDP, it took the virtual machine down at once:

kernel BUG at net/core/skbuff.c:1824!
invalid opcode: 0000 [#1] PREEMPT SMP NOPTI
RIP: 0010:pskb_expand_head+0x2af/0x380
Call Trace:
 <IRQ>
 netif_receive_generic_xdp+0x9f/0x1a0
 do_xdp_generic+0x4b/0xd0
 __netif_receive_skb_core.constprop.0+0x2ac/0xd20
 __netif_receive_skb_one_core+0x3e/0xa0
 __netif_receive_skb+0x15/0x60
 process_backlog+0x8e/0x150
 __napi_poll+0x30/0x1a0
 net_rx_action+0x180/0x2d0
 __do_softirq+0xd6/0x346
 do_softirq.part.0+0x7d/0xa0
 </IRQ>
 <TASK>
 __local_bh_enable_ip+0x72/0x80
 pktgen_xmit+0x1b2/0x530 [pktgen]
Kernel panic - not syncing: Fatal exception in interrupt

Line 1824 of skbuff.c in 6.1 is BUG_ON(skb_shared(skb)), the first thing pskb_expand_head checks. pktgen keeps its own reference on every sk_buff it transmits (refcount_add(burst, &pkt_dev->skb->users) in pktgen_xmit), so the packet arriving at veth1 is shared. Generic XDP wants 256 bytes of headroom, the packet has less, so netif_receive_generic_xdp asks pskb_expand_head to make room, and pskb_expand_head refuses, fatally, to reallocate a buffer someone else still holds. Native XDP on veth checks for a shared sk_buff and copies it instead; generic XDP in 6.1 doesn’t. pktgen is a testing tool that takes liberties normal senders don’t, and this is one it can’t take here.

So the sender for every condition is a small program of my own instead: one AF_PACKET socket that sends a prebuilt 60-byte frame out of veth0, 64 frames per sendmmsg call, skipping the queueing discipline:

// flood.c — send one 60-byte UDP frame out of IFACE, over and over, for SECONDS
#define _GNU_SOURCE			/* for sendmmsg() */
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>

#define BATCH 64

static void read_mac(const char *s, unsigned char *mac)
{
	sscanf(s, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
	       &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
}

int main(int argc, char **argv)
{
	unsigned char frame[60] = { 0 };
	struct ether_header *eth = (void *)frame;
	struct iphdr *ip = (void *)(eth + 1);
	struct udphdr *udp = (void *)(ip + 1);
	struct sockaddr_ll to = { .sll_family = AF_PACKET, .sll_halen = ETH_ALEN };
	struct iovec iov = { frame, sizeof(frame) };
	struct mmsghdr msgs[BATCH];
	unsigned long long sent = 0;
	unsigned int sum = 0;
	char path[64], mac[32];
	int fd, one = 1, i;
	time_t end;
	FILE *f;

	if (argc < 7) {
		fprintf(stderr, "usage: %s IFACE DST_MAC SRC_IP DST_IP DST_PORT SECONDS\n", argv[0]);
		return 1;
	}
	snprintf(path, sizeof(path), "/sys/class/net/%s/address", argv[1]);
	if (!(f = fopen(path, "r")) || !fgets(mac, sizeof(mac), f))
		return 1;
	read_mac(mac, eth->ether_shost);
	read_mac(argv[2], eth->ether_dhost);
	eth->ether_type = htons(ETHERTYPE_IP);

	ip->version = 4;
	ip->ihl = 5;
	ip->tot_len = htons(sizeof(frame) - sizeof(*eth));
	ip->ttl = 64;
	ip->protocol = IPPROTO_UDP;
	ip->saddr = inet_addr(argv[3]);
	ip->daddr = inet_addr(argv[4]);
	for (i = 0; i < 10; i++)		/* the IP header checksum */
		sum += ((unsigned short *)ip)[i];
	while (sum >> 16)
		sum = (sum & 0xffff) + (sum >> 16);
	ip->check = ~sum;

	udp->source = htons(9999);
	udp->dest = htons(atoi(argv[5]));
	udp->len = htons(sizeof(frame) - sizeof(*eth) - sizeof(*ip));
	udp->check = 0;			/* "no checksum", which UDP over IPv4 allows */

	/* A packet socket that only sends, straight to the driver, no qdisc. */
	fd = socket(AF_PACKET, SOCK_RAW, 0);
	if (fd < 0 || setsockopt(fd, SOL_PACKET, PACKET_QDISC_BYPASS, &one, sizeof(one))) {
		perror("socket");
		return 1;
	}
	to.sll_ifindex = if_nametoindex(argv[1]);
	memset(msgs, 0, sizeof(msgs));
	for (i = 0; i < BATCH; i++) {
		msgs[i].msg_hdr.msg_name = &to;
		msgs[i].msg_hdr.msg_namelen = sizeof(to);
		msgs[i].msg_hdr.msg_iov = &iov;
		msgs[i].msg_hdr.msg_iovlen = 1;
	}

	end = time(NULL) + atoi(argv[6]);
	while (time(NULL) < end) {
		int n = sendmmsg(fd, msgs, BATCH, 0);	/* 64 frames per system call */

		if (n > 0)
			sent += n;
	}
	printf("%llu frames sent\n", sent);
	return 0;
}

One CPU, by construction. On veth, the receive side runs on the sender’s CPU: veth0’s transmit function queues the packet for veth1, and the softirq that processes it runs on the same CPU as soon as the sending system call re-enables softirqs. Pinning the sender to CPU 0 with taskset therefore puts both halves of every packet’s life on CPU 0, and the rate a condition reaches is one CPU’s worth of sending plus receiving plus dropping. The sender’s share is the same in every condition, so the differences between conditions are differences in the receive side.

The run. For each condition the script installed the drop point, started the sender for six seconds, waited one second, read the drop point’s own counter (the NoPorts counter, the iptables or nftables rule’s packet count, or the BPF program’s seen map), waited three seconds, and read it again. Seven conditions make a round; I ran five rounds, rotating the order by one each round, in one vrun-alone session, so no other test machine shared the host. The figure shows the median of the five rounds and the spread between the lowest and highest.

Packets dropped per second, by where they are dropped

60-byte UDP frames, one sending program on one vCPU of a KVM guest, over veth, Linux 6.1. Ordered from the driver up.

XDP, nativein veth1's NAPI poll
2.10 Mpps · 476 ns
XDP, generic__netif_receive_skb_core
2.60 Mpps · 384 ns
tc ingress, BPFclsact + cls_bpf, direct-action
3.10 Mpps · 323 ns
nftables ingressnetdev family, ingress hook
2.78 Mpps · 360 ns
iptables rawPREROUTING, before conntrack
2.74 Mpps · 365 ns
iptables INPUTafter routing
2.19 Mpps · 458 ns
no ruleUDP finds no socket on port 9
2.08 Mpps · 480 ns
00.511.522.53
drop pointmedian Mppsmin–maxns/packet
XDP, native2.102.07–2.16476
XDP, generic2.602.55–2.67384
tc ingress, BPF3.103.06–3.10323
nftables ingress2.782.75–2.81360
iptables raw2.742.71–2.78365
iptables INPUT2.192.17–2.35458
no rule2.082.06–2.45480

Bar: median of five interleaved rounds, in millions of packets per second (axis). Line: lowest to highest round. ns is one second divided by the median rate: the full cost of a packet on that CPU, sending included. A VM and a veth pair, not a NIC: read the order and the ratios, not the absolute numbers.

Start with the five drop points that don’t involve XDP, because they behave the way the path says they should. With no rule at all, the packet climbs all the way to UDP and dies there for want of a socket: 2.08 million packets a second, 480 ns per packet with the sending included. An iptables DROP in INPUT is barely better, 2.19 million and 458 ns: by the time INPUT runs, IP has checked the header and routing has made its decision, which is most of what the rule was meant to save. The same rule in the raw table, before routing, reaches 2.74 million; that is 92 ns less per packet, a fifth of the total, for moving one rule to another table. nftables’ ingress hook, before IP altogether, 2.78 million. And at tc ingress, the same point in the path as nftables’, our BPF program drops 3.10 million a second at 323 ns a packet, 37 ns less than nftables’ rule engine does at the same spot. Each hook earlier in the path drops faster, and between tc and INPUT the same CPU drops 42% more packets.

Then XDP, which breaks the pattern: generic mode 2.60 million, slower than tc although it runs earlier in the same function, and native mode 2.10 million, the slowest of the six filters and level with having no filter at all. The spreads are narrow (the figure’s whiskers; the two wider ones, “no rule” and INPUT, come from round 1, the first two conditions of the whole run), so this is not noise. And it isn’t the program: with kernel.bpf_stats_enabled on, the kernel timed it at 27.4 ns per run at tc, 27.5 ns in generic XDP and 28.1 ns in native XDP. The same instructions do the same work wherever they are attached. The difference is in what the kernel does around them.

To see what that is, I counted calls to a few kernel functions with bpftrace while the sender ran for two seconds under each hook (a separate, untimed run: probes slow everything down). Every count below was equal, to the packet, to the number the program dropped, so each is a cost paid once per packet:

per dropped packettcXDP genericXDP native
__alloc_skb (the sender’s sk_buff)111
pskb_expand_head1
alloc_pages, skb_copy_bits, build_skb1 each
__napi_schedule, veth_poll, napi_complete_done1 each
skb_release_data112

The first row is the whole story in one line: on veth there is no receive ring of empty buffers. The “packet” arriving at veth1 is the sk_buff the sender’s socket allocated on the other side, so every hook, XDP included, starts from a packet the kernel has already paid for. The XDP modes then pay more, to give the program what XDP promises it:

  • Generic XDP needs 256 bytes of headroom in front of the packet, so the program can grow headers with bpf_xdp_adjust_head. The packet socket left far less, so netif_receive_generic_xdp calls pskb_expand_head, which allocates a new, bigger head and copies the packet into it. Once per packet: 61 ns more than tc.
  • Native XDP on veth runs in veth’s own NAPI poll, so every packet first schedules and runs a poll (__napi_schedule, veth_poll). Then veth needs the packet in memory XDP may write to and hand on as a page. A head allocated by kmalloc, as a packet socket’s is, fails the kernel’s skb_head_is_locked test, so veth allocates a fresh page, copies the packet into it, builds a second sk_buff around it and frees the first: hence two skb_release_data per packet. 153 ns more than tc.

None of that happens on a network card. There, native XDP’s per-packet work is reading a descriptor, running the program and handing the buffer back to the ring, and there is no sk_buff before it to reallocate or copy. That is the result Cloudflare measured on a real NIC in 2018: tc 1.8 million packets a second, XDP 10.1 million. This lab can’t show it, and it would be wrong to read the chart’s XDP rows as a measurement of XDP. What carries from it is the order and the size of the gaps among the sk_buff hooks, which Cloudflare’s numbers share (INPUT, then raw and nftables ingress, then tc, each faster), and one practical lesson: on veth, which is how containers are usually wired, tc is the faster place for a BPF filter, and XDP there is a tool for testing XDP programs, not for speed.

AF_XDP: the packet goes to user space instead

The last thing XDP can do with a packet is give it away. AF_XDP, merged in 4.18, is a socket family whose sockets receive packets straight from an XDP program, through XDP_REDIRECT into an XSKMAP, without the stack ever building an sk_buff. It is how DPDK-style applications, which want every packet in user space at line rate, can get that on Linux without taking the NIC away from the kernel: the XDP program chooses which packets go to user space, and everything else carries on as usual.

The design is all shared memory. User space allocates a region, the UMEM, divided into equal frames, and registers it with the socket. Four single-producer, single-consumer rings, also in memory both sides map, pass frame addresses back and forth: the fill ring (user space gives the kernel empty frames to receive into), the RX ring (the kernel says which frames now hold a packet, and how long), and the TX and completion rings, the same pair for sending. In copy mode the kernel copies each packet into a UMEM frame. In zero-copy mode, the driver DMAs packets straight into UMEM, so the bytes user space reads are the bytes the NIC wrote; that needs driver support, which arrived in 4.20 with Intel’s i40e and has spread since. veth has no zero-copy mode.

The socket API moved house this year. libbpf carried the AF_XDP helpers (xsk.h) until 1.0, which removed them; they live on in libxdp, from the same xdp-tools as xdp-loader. This program sets up one socket on queue 0 of veth1 in copy mode, receives for a few seconds, hands each frame back to the fill ring as soon as it has looked at it, and prints the first packet’s bytes:

// xskcount.c — take packets from one queue of IFACE through an AF_XDP socket
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <linux/if_xdp.h>
#include <xdp/xsk.h>

#define NUM_FRAMES 4096
#define FRAME_SIZE XSK_UMEM__DEFAULT_FRAME_SIZE	/* 4096 bytes */
#define BATCH 64

int main(int argc, char **argv)
{
	struct xsk_ring_prod fill;
	struct xsk_ring_cons comp, rx;
	struct xsk_umem *umem;
	struct xsk_socket *xsk;
	struct xsk_socket_config cfg = {
		.rx_size = XSK_RING_CONS__DEFAULT_NUM_DESCS,
		.tx_size = XSK_RING_PROD__DEFAULT_NUM_DESCS,
		.bind_flags = XDP_COPY,		/* veth has no zero-copy mode */
	};
	unsigned long long packets = 0, bytes = 0;
	__u32 idx, fidx, i, n;
	void *area;
	time_t end;
	int err;

	if (argc < 3) {
		fprintf(stderr, "usage: %s IFACE SECONDS\n", argv[0]);
		return 1;
	}
	if (posix_memalign(&area, getpagesize(), NUM_FRAMES * FRAME_SIZE))
		return 1;

	/* The UMEM: one area of memory, shared by us and the kernel. */
	err = xsk_umem__create(&umem, area, NUM_FRAMES * FRAME_SIZE, &fill, &comp, NULL);
	if (!err)
		err = xsk_socket__create(&xsk, argv[1], 0, umem, &rx, NULL, &cfg);
	if (err) {
		fprintf(stderr, "AF_XDP setup failed: %s\n", strerror(-err));
		return 1;
	}

	/* Give the kernel half the frames to write packets into. */
	n = xsk_ring_prod__reserve(&fill, NUM_FRAMES / 2, &idx);
	for (i = 0; i < n; i++)
		*xsk_ring_prod__fill_addr(&fill, idx + i) = (__u64)i * FRAME_SIZE;
	xsk_ring_prod__submit(&fill, n);

	printf("AF_XDP socket on %s queue 0: %d frames of %d bytes\n",
	       argv[1], NUM_FRAMES, FRAME_SIZE);
	fflush(stdout);
	end = time(NULL) + atoi(argv[2]);
	while (time(NULL) < end) {
		struct pollfd pfd = { .fd = xsk_socket__fd(xsk), .events = POLLIN };

		if (poll(&pfd, 1, 100) <= 0)
			continue;
		n = xsk_ring_cons__peek(&rx, BATCH, &idx);
		if (!n)
			continue;
		while (xsk_ring_prod__reserve(&fill, n, &fidx) != n)
			;	/* we hold n frames, so there is room for n */
		for (i = 0; i < n; i++) {
			const struct xdp_desc *d = xsk_ring_cons__rx_desc(&rx, idx + i);
			unsigned char *pkt = xsk_umem__get_data(area, d->addr);

			if (packets == 0) {
				printf("first packet, %u bytes, at umem offset %llu:\n",
				       d->len, (unsigned long long)d->addr);
				for (__u32 b = 0; b < d->len && b < 64; b++)
					printf("%02x%s", pkt[b], b % 16 == 15 ? "\n" : " ");
				printf("\n");
			}
			packets++;
			bytes += d->len;
			/* the frame goes back on the fill ring */
			*xsk_ring_prod__fill_addr(&fill, fidx + i) = d->addr & ~(__u64)(FRAME_SIZE - 1);
		}
		xsk_ring_prod__submit(&fill, n);
		xsk_ring_cons__release(&rx, n);
	}
	printf("%llu packets, %llu bytes through the socket\n", packets, bytes);
	xsk_socket__delete(xsk);
	xsk_umem__delete(umem);
	return 0;
}

xsk_socket__create does more than it says. With no program of our own on the interface, libxdp loads its default one, xsk_def_prog, through the same dispatcher xdp-loader used, and puts our socket in its XSKMAP at index 0. The default program redirects everything arriving on queue 0 to the socket. I built it against libxdp, sent five datagrams to port 9 and two pings from gen, and printed the program list while it ran:

$ xdp-loader status veth1
CURRENT XDP PROGRAM STATUS:

Interface        Prio  Program name      Mode     ID   Tag               Chain actions
--------------------------------------------------------------------------------------
veth1                  xdp_dispatcher    native   65   94d5f00c20184d17
 =>              20     xsk_def_prog              72   03b13f331978c78c  XDP_PASS

$ ip netns exec gen ping -c 2 -W 1 10.0.0.2
PING 10.0.0.2 (10.0.0.2) 56(84) bytes of data.

--- 10.0.0.2 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms

And from the program, minus four lines in which libxdp’s bundled libbpf complains about ELF sections it doesn’t recognise:

AF_XDP socket on veth1 queue 0: 4096 frames of 4096 bytes
first packet, 90 bytes, at umem offset 256:
33 33 00 00 00 16 12 10 98 d0 00 a2 86 dd 60 00
00 00 00 24 00 01 fe 80 00 00 00 00 00 00 10 10
98 ff fe d0 00 a2 ff 02 00 00 00 00 00 00 00 00
00 00 00 00 00 16 3a 00 05 02 00 00 01 00 8f 00

8 packets, 586 bytes through the socket

Eight packets: the five datagrams, the two pings, and the first one, which neither of us sent. It begins 33 33 00 00 00 16, an IPv6 multicast MAC, and 86 dd is IPv6: it is veth0’s own multicast listener report, the kind of background chatter every IPv6 interface makes. The default program took that too, and the pings, which is why ping got no answers: the kernel never saw the echo requests. That is the lesson of the default program, and the reason real AF_XDP applications ship their own XDP program that redirects only the traffic they want. The frame offset, 256, is the XDP headroom again: in copy mode the kernel writes the packet 256 bytes into the frame.

In two earlier runs the same program counted nothing. In one of them, the xdp:xdp_redirect_err tracepoint showed the redirects failing with -ENOMEM, which is what the kernel returns when the socket’s fill ring has no frame to copy into. My best explanation is that those packets arrived after xsk_socket__create had put the socket in the map but before the program had stocked the fill ring; the run above waits for the program’s first line before sending anything. I didn’t pin it down further.

Who runs this, at the end of 2022

The early-drop argument from the start of this post is not academic. Three of the best-known uses of XDP are exactly it, at scale:

Katran. Facebook open-sourced Katran, its layer-4 load balancer, in May 2018. It forwards with an XDP program: packets for a service’s virtual IP arrive at the load balancer’s NIC, the program picks a backend for the flow, wraps the packet in IP-in-IP and sends it on, with one interface carrying traffic both ways, and the backend answers the client directly. Because XDP leaves the rest of the kernel alone, Facebook runs Katran alongside the backend servers themselves, which a kernel-bypass load balancer that takes over the NIC could not do.

Cloudflare. Cloudflare has written more about this than anyone. In July 2018, How to drop 10 million packets per second ran nearly this post’s experiment on a real 10 Gb/s Intel NIC, with one CPU taking all the traffic: iptables INPUT dropped 608 thousand packets a second, iptables in raw PREROUTING 1.688 million, nftables at ingress about 1.53 million, tc 1.8 million, and XDP 10.1 million. In November 2018 they described L4Drop, which compiles their DDoS mitigation rules into XDP programs, deployed on all their servers, and in September 2020 Unimog, their edge load balancer, which forwards with XDP too.

Cilium. Cilium’s datapath is BPF throughout: tc programs on every pod’s interface implement policy and service load balancing, and since 1.6 (August 2019) it can replace kube-proxy’s iptables rules entirely. Cilium 1.8, in June 2020, added XDP acceleration of that service handling for NodePort, LoadBalancer and external IPs on the node’s physical interface, so traffic for a Kubernetes service can be load-balanced, or dropped, at the driver. Cilium 1.12, in July this year, is the current release.

And in Part 7 we saw that eBPF for Windows has a hook it calls XDP, attached through the Windows Filtering Platform at its MAC-frame layer. By the time a WFP layer runs, the Windows driver stack has already built its own packet structure around the bytes, so in the vocabulary of this post it is nearer to generic XDP than to native: the same programming model, without the reason the Linux hook was built.

What we covered

  • A received packet’s path through Linux 6.1: DMA into a ring; the driver’s NAPI poll; a 232-byte sk_buff; GRO; __netif_receive_skb_core, where generic XDP, the packet taps, tc ingress and netfilter ingress run in that order; ip_rcv and PREROUTING (raw before conntrack); routing; INPUT; UDP and the socket. Each hook can only save what comes after it.
  • XDP runs in the driver on raw bytes, with a six-field xdp_md and five verdicts: DROP, PASS, TX, REDIRECT, ABORTED. Native mode needs driver support (veth since 4.19); generic mode (4.12) runs anywhere, after the sk_buff exists; offload (4.13) runs on the NIC, on Netronome cards only.
  • Every packet access must be proven in bounds. The verifier tracks packet pointers as an offset and a proven range, pkt(off=14,r=14); a comparison against data_end is what grows the range, and without it the load is refused: invalid access to packet, off=13 size=1.
  • tc with cls_bpf in direct-action mode (4.4) on a clsact qdisc (4.5) sees the stack’s __sk_buff, has richer helpers, and runs on egress as well as ingress. Both contexts are rewritten by the verifier into loads from the kernel’s real structures.
  • One function, called from an XDP program and a tc program, filtered real traffic between two namespaces: attached with libbpf natively, generically and at tc ingress and egress; with ip and tc; and through libxdp’s dispatcher with xdp-loader.
  • XDP_TX on veth needs an XDP program on the peer, and veth’s checksum offload leaves half-done checksums that XDP passes through untouched. XDP_REDIRECT with DEVMAP and CPUMAP forwards to other interfaces and CPUs.
  • pktgen crashes a 6.1 kernel under generic XDP on veth (BUG_ON(skb_shared(skb)) in pskb_expand_head), so the race used a sender of its own.
  • Dropping 60-byte UDP frames on one CPU over veth: tc 3.10 Mpps, nftables ingress 2.78, iptables raw 2.74, iptables INPUT 2.19, no rule 2.08. XDP generic 2.60 and native 2.10, because on veth XDP starts from the sender’s sk_buff and then reallocates (generic) or copies (native) it; the program itself costs 27 to 28 ns in all three hooks. On a NIC, native XDP skips the sk_buff altogether.
  • AF_XDP (4.18) hands packets to user space through a shared UMEM and four rings; libbpf 1.0 moved its helpers to libxdp; libxdp’s default program takes every packet on the queue.
  • Katran, Cloudflare’s L4Drop and Unimog, and Cilium all drop or forward at XDP in production.

Kernel networking hooks keep multiplying after tc and XDP: sockets, cgroups and the socket lookup itself can all be programmed, and a later part follows them up the stack.

A note on the evidence

What I ran, and where. Every listing is pasted from a real run. The machine was a KVM virtual machine with 4 virtual CPUs and 4 GiB of memory on an Intel Core Ultra 9 285K host, booted with virtme-ng into Ubuntu’s mainline build of Linux 6.1 (6.1.0-060100-generic, the v6.1 release tag, with its modules), on a minimal Ubuntu 22.04 userland built from the release archive only: clang 14.0.0-1ubuntu1, iproute2 5.15.0 (built with libbpf 0.5.0), iptables 1.8.7 on nf_tables, nftables 1.0.2, ethtool 5.16, bpftrace 0.14.0, Python 3.10. Three tools came from source at their release tags, built inside that userland: libbpf v1.0.1 (the newest 1.0 release; 1.1 is not out), bpftool v7.0.0 (built against the same libbpf, so it reports “using libbpf v1.0”), and xdp-tools v1.2.9 from its release tarball, which bundles libbpf 0.8.0 for libxdp and xdp-loader. Building xdp-tools needed jammy’s gcc-multilib for the asm/types.h that clang’s BPF target looks for. The C, Python and shell in this post were extracted from the page and run as shown: udpfilter, reflect, xskcount and flood built with the commands given, the tests driven by a lab script that set up the namespaces as described.

What I trimmed. Run-time timestamps: loaded_at lines, and the times and dates in kernel messages. The kernel BUG report is cut to the message, the faulting instruction and the call trace, without the register dump, the build-stamp and hardware lines, and the boot-time offsets; the full console log is in my lab notes. The per-CPU map dump is cut to the one CPU that had non-zero values (the other three printed zeros). The verifier log excerpts are the lines for the instructions discussed, from one load with bpftool’s -d (log level 7); the full log for xdp_filter is 156 lines. ethtool -S is cut to the two xdp_tx counters. The libxdp warnings about unrecognised ELF sections are removed from the AF_XDP output, as noted there. MAC addresses are random per boot and are as printed in that boot. Program and map IDs are as printed.

The measurement. Seven conditions, five rounds, rotated, in one vrun-alone session: 1 s of warm-up, then the drop point’s own counter read twice, 3 s apart (NoPorts from /proc/net/snmp, the iptables or nftables rule’s packet counter, or the sum of the seen map over the four CPUs), with the two reads timed by the script itself. The sender was flood.c, pinned to CPU 0 in namespace gen; on veth the receive processing runs on the sending CPU, so each rate is one CPU’s worth of sending, receiving and dropping, and /proc/net/softnet_stat showed no backlog drops in any round. The medians and their ranges, in millions of packets a second: tc 3.10 (3.06–3.10), nftables ingress 2.78 (2.75–2.81), iptables raw 2.74 (2.71–2.78), XDP generic 2.60 (2.55–2.67), iptables INPUT 2.19 (2.17–2.35), XDP native 2.10 (2.07–2.16), no rule 2.08 (2.06–2.45); every round is in data/ebpf_part08.json. The two high values in the INPUT and no-rule ranges are both from round 1, the first two conditions of the session. The per-run program costs come from a separate pass with kernel.bpf_stats_enabled=1, which itself adds the cost of reading the clock twice per run, and the per-packet call counts from a third, untimed run with bpftrace 0.14 kprobes. pktgen ran the first five conditions of a trial pass before the generic-XDP crash ended it; those numbers are not reported, since they came from a different sender. For the first XDP_TX failure: an earlier run with GRO switched on for veth0 and its checksum offload off, but no XDP program on it, got no reply, with xdp_tx: 1 on veth1 and every counter on veth0’s XDP ring still at zero: the frame was sent and never received.

What I cited rather than ran. The kernel versions in which each feature arrived (XDP 4.8, XDP_TX 4.8, generic XDP 4.12, the offload flag 4.13, XDP_REDIRECT, bpf_redirect_map and DEVMAP 4.14, CPUMAP 4.15, AF_XDP 4.18, veth’s native XDP 4.19, i40e’s AF_XDP zero-copy 4.20, cls_bpf 3.13 and 4.1, direct-action 4.4, clsact 4.5, veth NAPI without XDP 5.13), each checked as the first release tag containing the commit that introduced it. The receive-path order, the veth behaviour behind both XDP_TX failures, the shared-sk_buff check in veth and its absence in generic XDP, and pktgen’s extra reference are read from the 6.1 source; the BUG I saw, the rest I read. Cloudflare’s numbers are from their posts of July 2018, November 2018 and September 2020, Katran’s from Facebook’s of May 2018, and Cilium’s from the release announcements of 1.6, 1.8 and 1.12. Offload mode and zero-copy AF_XDP I did not run: there is no hardware for either here.

What I’d still change. The race measures veth, where both XDP modes start from an sk_buff the sender has already built; it says nothing about how XDP compares on a NIC, which is the comparison that matters and the one Cloudflare’s 2018 numbers show. A physical NIC with native XDP, a separate machine sending, and the receive side spread over several queues and CPUs is the experiment to do next. A redirect example through a DEVMAP between two veth pairs would also have been worth building, with the same peer-program caveat as XDP_TX.

More