XDP Packet Processing

Packet Rewriting and Load Balancing

Packet modification and L4 load balancing - the real power of XDP.

Packet Rewriting

xdp-tutorial: packet02-rewriting/

What you will learn:

  • MAC address swap (required for XDP_TX)
  • IP address swap (NAT)
  • bpf_xdp_adjust_head / bpf_xdp_adjust_tail - modify packet size
  • Checksum recalculation - update IP and L4 checksums

MAC Swap Pattern

static __always_inline void swap_mac(struct ethhdr *eth) {
    __u8 tmp[ETH_ALEN];
    __builtin_memcpy(tmp, eth->h_source, ETH_ALEN);
    __builtin_memcpy(eth->h_source, eth->h_dest, ETH_ALEN);
    __builtin_memcpy(eth->h_dest, tmp, ETH_ALEN);
}

Redirect and L4 Load Balancing

Lab: XDP Load Balancer

What you will learn in this lab:

  • NAT (Network Address Translation) concept
  • Connection tracking (5-tuple: src_ip, dst_ip, src_port, dst_port, protocol)
  • Backend selection via hashing
  • bpf_fib_lookup helper - resolve MAC/interface from the routing table
  • IP/MAC rewriting
  • XDP_REDIRECT - redirect to another interface

Load Balancer Flow

Client -> XDP Program -> Backend Server
  1. Parse: src/dst IP, port
  2. Lookup: Connection table (if exists -> existing backend)
  3. Select: Hash(5-tuple) % backend_count (if not -> new backend)
  4. Rewrite: dst_ip = backend_ip, dst_mac = backend_mac
  5. Redirect: Send to backend interface via XDP_REDIRECT

xdp-tutorial equivalent: packet03-redirecting/

Reading: Unimog - Cloudflare’s Edge Load Balancer - production XDP/L4 LB architecture.