CIDR, Longest Prefix Match, and MTU: Calculate IP Routing Step by Step
CIDR, Longest Prefix Match, and MTU: Calculate IP Routing Step by Step
Search
Ask the AI

CIDR, Longest Prefix Match, and MTU: Calculate IP Routing Step by Step

Once DNS has produced an IP address, the routing table selects an exit by longest prefix match. The link limits the size of each packet through its MTU. These determine whether the packet arrives and how much it can carry.

When small requests succeed but larger responses stall, investigate a PMTU blackhole alongside loss, congestion and application delays. Traditional IPv4 PMTUD uses ICMP fragmentation-needed messages; filtering them can leave oversized packets failing. This article separates prefix matching, kernel lookup structures, path-MTU discovery and encapsulation.

1. The Mathematics and Data Structures of LPM

CIDR expresses address ranges with prefixes. Routing selects the longest matching prefix together with applicable policy rules. Distinguish the forwarding information base from control-plane BGP routes; lookup costs depend on table size and implementation.

Modern Linux kernels use an LC-Trie (Level-Compressed Trie) for the IPv4 routing table. Unlike a standard binary trie which requires \(O(W)\) lookups where \(W\) is the IP address length (32 for IPv4), an LC-trie compresses sparse branches and path nodes.

Path and level compression reduce the number of nodes visited. A node \(v\) with branching factor \(k\) changes that traversal, but route count \( n \) alone does not establish an expected-depth bound of \( O(\log n) \) for every route distribution. Child-pointer arrays do not guarantee that an entire node or lookup fits one L1/L2 cache line. The structure below is retained as a version-dependent illustration; see the implementation notes.

/* Excerpt from linux/net/ipv4/fib_trie.c */
struct key_vector {
    t_key key;
    unsigned char pos;      /* 2log(KEYLENGTH) bits needed */
    unsigned char bits;     /* 2log(KEYLENGTH) bits needed */
    unsigned char slen;
    union {
        /* This array's size is 2^bits */
        struct key_vector __rcu *tnode[0];
        struct fib_alias __rcu *leaf;
    };
};

The IPv4 fib_lookup path queries the FIB. RCU read-side critical sections allow readers to access protected structures while reducing contention with updates. They do not eliminate cache-coherence costs or establish a lock-free guarantee for the whole forwarding path.

Destination IP: 10.22.18.7 (00001010.00010110.00010010.00000111)
LC-Trie Traversal:
- Check root node, shift to branch based on `pos` and `bits`.
- Match against `10.22.16.0/20` (Winner: Specific Service Subnet)
- Exceeds `10.0.0.0/8` precision.
LC-Trie structure and LPM evaluation
Kernel FIB lookup utilizing Level-Compressed Tries to find the longest matching prefix with minimal memory access.

Visualizing Route Selection with eBPF/XDP

With native driver support, an XDP program can process packets before normal sk_buff allocation, query a FIB helper and choose redirection or stack fallback. The diagram illustrates an optional fast path, not every packet at Cloudflare or Meta. Zero-copy behavior depends on the driver, buffers and redirection path.


flowchart TD
    A[NIC Rx Ring
Dest: 10.22.18.7] --> B{XDP Hook
eBPF Program} B -->|bpf_fib_lookup| C((Kernel FIB
LC-Trie)) C -.->|Match 10.22.16.0/20| B B --> D{MTU Check} D -->|<= MTU| E[XDP_REDIRECT
Zero-Copy Forward] D -->|> MTU| F[XDP_PASS
Pushed to generic Skb stack] F --> G[ip_local_deliver / ip_forward]

2. MTU, MSS, and the Mathematics of Encapsulation

Routing selects an egress interface. Its MTU limits the layer-3 IP packet and excludes the Ethernet header. A 1500-byte Ethernet MTU is common, while other values are configurable. TCP segmentation also depends on path MTU, peer MSS, options and encapsulation.

First calculate the effective inner-IP path MTU after encapsulation, then subtract the inner IP and TCP headers. Count each encapsulation layer once; starting from an IP MTU does not require subtracting Ethernet. The formula is:

$$ MSS = PMTU_{inner}-H_{inner\_ip}-H_{tcp} $$

The original 1400-byte budget below reserves roughly 40 bytes for ESP; that is a budget assumption, not a fixed AES-GCM overhead. RFC 4106 requires accounting for the ESP header, explicit IV, padding, trailer and authentication tag, plus NAT-T UDP when present. The two IPv4-header rows represent outer and inner headers despite the original label order. VXLAN overhead, if used, is additional.

Base MTU: 1500 bytes
IPv4 Header: 20 bytes
ESP Header + IV + Trailer + ICV: ~40 bytes
Outer IPv4 Header: 20 bytes
TCP Header: 20 bytes
Effective MSS = 1500 - 20 - 40 - 20 - 20 = 1400 Bytes

IP fragmentation differs from TCP segmentation. ip_fragment() can allocate or reference sk_buff data; its cost depends on the path and offload support. A 10Gbps+ rate alone does not establish immediate ksoftirqd saturation. Prefer sender segmentation at the effective PMTU. MSS clamping can adjust a TCP limit in suitable deployments, while TSO/GSO perform hardware/software segmentation at the selected size; neither replaces PMTU discovery.

3. Kernel-Level Debugging: `perf` and PMTUD

Traditional IPv4 PMTUD uses ICMP Fragmentation Needed; IPv6 uses Packet Too Big. Filtering these messages can cause blackholes, with the resulting stall depending on packet sizes and transport-layer probing or fallback.

The original perf/ftrace commands below require checking the actual kernel events and probeable symbols. Linux v6.12 lists icmp_send, not icmp:icmp_unreach, in its ICMP trace header. Static functions may be inlined, and a BPF helper name is not necessarily a probeable symbol. A stack counter alone does not identify the FIB error return.

# Trace ICMP Need Frag reception in the kernel
sudo perf record -e icmp:icmp_unreach -a -g

# Trace TCP MTU probing (RFC 4821) when PMTUD fails
sudo perf probe -a tcp_mtu_probing
sudo perf record -e probe:tcp_mtu_probing -aR

# Investigate XDP redirects and FIB lookup failures
sudo bpftrace -e 'kprobe:bpf_fib_lookup { @[kstack] = count(); }'

Linux sysctl net.ipv4.tcp_mtu_probing=1 enables TCP MTU probing after blackhole detection, rather than shrinking MSS immediately on every timeout. The original C shorthand below differs from v6.12 tcp_mtu_probing; retain it as historical pseudocode, not an excerpt of that implementation.

/* Excerpt from net/ipv4/tcp_timer.c handling PMTU probes */
static void tcp_mtu_probing(struct inet_connection_sock *icsk, struct sock *sk)
{
    struct tcp_sock *tp = tcp_sk(sk);
    /* Probe for larger MTU, or drop MSS if blackhole detected */
    if (tcp_mtu_probe(sk)) {
        tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
    }
}

4. XDP forwarding: scenario and evidence

The eBPF / XDP Routing Bypass

The original narrative claimed a global CDN increased from about 2Mpps to 14Mpps per core. The companion CSV contains no throughput run, hardware description or record of that deployment, so these figures remain unverified original assertions. The supported mechanism is an XDP fast path that reads an IP destination, calls bpf_fib_lookup(), rewrites MAC addresses and returns XDP_REDIRECT. It can reduce some sk_buff work from the normal ip_forward path; this does not establish interrupt-free or universally zero-copy forwarding.

An XDP forwarding path using XDP_REDIRECT must handle egress MTU. With length checking configured, the FIB helper can return a fragmentation-needed status and MTU. Inspect return codes, tracepoints and driver counters before attributing a redirect failure to a silent drop. The program can fall back to the stack or implement the appropriate IPv4/IPv6 ICMP error. A reply through XDP_TX also requires correct headers, checksums, quoted packet data, source address and rate limits; constructing an ICMP Packet Too Big frame alone does not establish complete PMTUD behavior.

5. Automated Data-Plane Validation

The original pyroute2 example below queries Netlink, but RTA_METRICS is nested and must be decoded for the installed library version. Its 1500-byte fallback is an assumption, not a measured path MTU. The value 65535 is not a universal GSO/TSO maximum. Segment-count arithmetic does not establish what a particular NIC transmitted.

from pyroute2 import IPRoute
import math

ipr = IPRoute()
destination = "10.22.18.7"

# Query Netlink socket for exact kernel routing decision
route = ipr.route('get', dst=destination)[0]
attrs = dict(route['attrs'])

egress_iface = attrs.get('RTA_OIF')
gateway = attrs.get('RTA_GATEWAY', 'Direct Connect')
mtu = attrs.get('RTA_METRICS', {}).get('RTAX_MTU', 1500)

print(f"Destination: {destination}")
print(f"Egress Interface Index: {egress_iface}")
print(f"Gateway: {gateway}")
print(f"Path MTU: {mtu} bytes")

# Hardware Segmentation Math (TSO)
ip_tcp_headers = 40
payload_size = 65535 # Max GSO Super-frame
segments = math.ceil(payload_size / (mtu - ip_tcp_headers))
print(f"NIC TSO will slice super-frame into {segments} hardware segments.")

The companion cidr-mtu-results.csv contains a fixed calculation: 10.22.18.7 matches 10.22.16.0/20; a 1500-byte MTU, 40-byte headers and 3600-byte payload give 3 segments with 680 bytes in the last. The pure-arithmetic correction below reproduces those values. The CSV contains no DPDK/XDP throughput or packet-loss measurement.

# Arithmetic example: effective IP MTU already accounts for tunnel overhead.
import math
effective_ip_mtu = 1500
ip_tcp_headers = 40  # IPv4 + TCP, without options
payload_bytes = 3600
capacity = effective_ip_mtu - ip_tcp_headers
segments = math.ceil(payload_bytes / capacity)
last_payload = payload_bytes - capacity * (segments - 1)
assert (capacity, segments, last_payload) == (1460, 3, 680)

The original figure and animation captions are retained. The companion source plots prefix lengths and segmentation arithmetic; it does not trace kernel LC-Trie traversal, DPDK/XDP zero-copy or NIC TSO behavior.

6. Animated Walkthrough

The animation illustrates an LC-Trie lookup resolving the LPM, followed by zero-copy DPDK/XDP redirection, segmenting packets to strictly adhere to the egress MTU.

7. Engineering Heuristics & Anti-Patterns

  • Host Routes: Many /32 entries enlarge the table; measure lookup and cache costs for the actual distribution and implementation. Aggregate only when next hops and route attributes permit it, preserving routing semantics.
  • PMTU ICMP: Permit necessary ICMP Type 3 Code 4 and IPv6 Packet Too Big under the network policy, validate messages, and check transport probing and fallback.
  • Jumbo Frames: A 9000-byte MTU is an option for storage networks with end-to-end support. Check links, tunnels and devices, then measure throughput and CPU use. A 1500-byte setting alone does not establish server saturation.
  • TSO/GSO and captures: When tcpdump shows 65KB packets, check the capture point and offload state. Transmit TSO, software GSO or receive GRO can expose aggregate data on the host. Packet size alone does not establish NIC hardware segmentation or an on-wire MTU violation.

8. Routing and MTU Evidence Matrix

For routing or MTU failures, record route selection, next hop, egress MTU, ICMP reachability, and hardware offload state. The matrix below uses that evidence to distinguish longest-prefix matching, PMTUD blackholes, overlay encapsulation, and packet-capture artifacts.

Symptom Layer to inspect first Evidence to preserve Decision boundary
Destination leaves through the wrong interface FIB/LPM ip route get, Netlink result, matched prefix, and next hop. Confirm whether a longer prefix overrides the default route instead of blaming DNS.
Small packets work but large transfers time out Path MTU DF ping, tracepath, ICMP Packet Too Big, and interface MTU. If ICMP is blocked, check PLPMTUD and MSS fallback behavior.
Overlay tunnel stalls intermittently Encapsulation overhead GRE/IPsec/WireGuard header overhead, effective MSS, and retransmission events. Encapsulation reduces payload space; the physical NIC MTU is not the whole story.
Packet capture shows 65KB packets TSO/GSO offload ethtool -k, capture point, offload flags, and actual wire frames. A pre-NIC super-frame does not mean the wire violated MTU.

FAQ

Why doesn’t the kernel just use a Hash Table for routing?

Hash tables commonly provide average-case \(O(1)\) exact-key lookup. LPM additionally identifies the matching prefix length. Tries support hierarchical prefixes, but hash-based LPM designs also exist, and kernel hash structures are not limited to Conntrack.

How does MTU affect BGP?

BGP uses a TCP byte stream. A PMTU blackhole can allow a small OPEN message while larger TCP segments carrying UPDATE data retransmit or stall, potentially expiring a session timer. TCP segments BGP messages according to MSS; the full routing table is not one oversized IP packet, and flapping is not an inevitable outcome.

References

The next article examines how the TCP state machine responds to congestion signals from these networks.

Leave a Reply

Scroll down