Reference

Quick Reference and Resources

A consolidated reference for BPF primitives, helper functions, and additional learning resources. Use this page when you need to quickly look up how to accomplish a specific task in BPF.

Quick Reference

NeedSolutionNotes
Block IPs from a listBPF_MAP_TYPE_HASH with IP keysUsed in DDoS engine and IP blocklist
Count packets per sourceBPF_MAP_TYPE_PERCPU_HASH or BPF_MAP_TYPE_LRU_HASHPer-CPU variant avoids lock contention
Rate limitingBPF_MAP_TYPE_HASH + token bucket in BPFStore timestamp and token count per key
Round-robin backend selectionBPF_MAP_TYPE_ARRAY + atomic counterIndex into backend array with __sync_fetch_and_add
Consistent hashingHash 5-tuple, mod N backendsUse jhash or similar; see Katran for reference
DNS query inspectionParse UDP payload after L3/L4 headersMatch on QNAME field in DNS wire format
Pass packet to kernel stackReturn XDP_PASSDefault when no action needed
Drop packetReturn XDP_DROPFastest discard path in the kernel
Redirect to another interfacebpf_redirect() + return XDP_REDIRECTNeeded for load balancer forwarding
Rewrite MAC addressesDirect header modification via xdp_md->dataRequired after redirect to set correct L2 header
Share state between XDP and user spaceBPF_MAP_TYPE_HASH or BPF_MAP_TYPE_ARRAYPin maps to BPFFS for persistence across program reloads
Tail call to another BPF programBPF_MAP_TYPE_PROG_ARRAY + bpf_tail_call()Used in Katran’s xdp_root.c for program chaining
IP blocklist (CIDR ranges)BPF_MAP_TYPE_LPM_TRIELongest prefix match for subnet-level blocking
DNS query logBPF_MAP_TYPE_RINGBUF + Go consumerStream events to userspace without polling
Debug outputbpf_printk() + bpftool prog traceKernel trace pipe; use only during development
Routing lookupbpf_fib_lookup()Resolve next-hop MAC and interface from kernel FIB
String comparisonbpf_strncmp()Compare variable string against a constant
Substring searchbpf_strstr() (kernel 6.x+)Find a needle in a haystack buffer
Read kernel memorybpf_probe_read_kernel_str()Safe read from kernel address space
Read user memorybpf_probe_read_user_str()Safe read from user address space
Get process namebpf_get_current_comm()Returns the comm (name) of the running task
Convert port (network to host)bpf_ntohs()16-bit network byte order to host byte order
Convert IP (network to host)bpf_ntohl()32-bit network byte order to host byte order

Reading Materials

SourceReferenced In
Computer Networking FundamentalsStruct, Memory Layout and Byte Order
XDP PaperXDP Fundamentals
Cilium BPF ArchitectureProgram Types and Deep Dive
Cilium Network ConceptsProgram Types and Deep Dive
Unimog BlogPacket Rewriting and Load Balancing
Facebook BPF FirewallRate Limiting and IP Blocklist
Cilium Performance TuningObservability

Additional Resources