Skip to contentSkip to conversation

ipv4/ipv6: local address lookup scaling

RFC PATCH In review [email protected] 2 participants 6 messages Mar 31 – Apr 3

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

cover ipv4/ipv6: local address lookup scaling

From: Jesper Dangaard Brouer <[email protected]>

On servers with many IPv4 addresses (e.g. Cloudflare edge nodes with ~700 addrs), __ip_dev_find() becomes visible in perf profiles on the unconnected UDP sendmsg path:

udp_sendmsg
ip_route_output_flow
ip_route_output_key_hash_rcu
__ip_dev_find <-- source address validation
inet_lookup_ifaddr_rcu <-- walks inet_addr_lst hash chain

The current inet_addr_lst is a fixed-size hlist hash table with 256 buckets (IN4_ADDR_HSIZE). At 700 addresses this gives ~2.8 entries per bucket on average. The O(N/256) lookup cost grows linearly as addresses are added, with no mechanism to resize. IPv6 has the same issue with inet6_addr_lst (IN6_ADDR_HSIZE = 256).

This series presents two approaches. The first two patches are a minimal, low-risk fix. The last two patches are a more complete but higher-complexity solution. Both are included so maintainers can evaluate the trade-off.

Approach A: compile-time CONFIG option (patches 1-2)
----------------------------------------------------

The simplest fix: add CONFIG_INET_ADDR_HASH_BUCKETS and CONFIG_INET6_ADDR_HASH_BUCKETS (default 256, range 64-16384, EXPERT) so operators can size the tables at build time.

- 2 lines of Kconfig + 1 line change each
- Zero runtime behavior change at default settings
- Immediately deployable for known workloads
- Does not help workloads that cannot rebuild their kernel
- Memory cost scales with the chosen bucket count per netns

Approach B: rhltable conversion (patches 3-4)
---------------------------------------------

Convert IPv4 inet_addr_lst from a fixed hlist to an rhltable (resizable hash linked table). The rhltable:

- Maintains O(1) lookup regardless of address count
- Automatically grows and shrinks as addresses are added/removed
- Eliminates the fixed IN4_ADDR_HSIZE compile-time limit
- Uses the rhl (resizable hash list) variant to preserve support for duplicate keys -- the same IP can exist on multiple interfaces, and the old hlist already allowed this

The rhashtable_params are tuned for this use case:

- No .hashfn set: with key_len = sizeof(__be32), the default path calls jhash2(key, 1, seed), which the compiler fully inlines since jhash2 is static inline and the length is a compile-time constant. The result is equivalent to jhash_1word().

- .obj_cmpfn provides a direct __be32 comparison, replacing the generic memcmp() call in the default rhashtable_compare(). The compiler inlines this to a single cmp instruction in the inner lookup loop.

- .min_size = 32 reduces initial memory vs the old fixed 256-bucket hlist (256 x 8 = 2048 bytes per netns). The rhltable starts at 32 x 8 = 256 bytes for buckets plus ~180 bytes of metadata, so ~440 bytes total per netns -- a 4x reduction. Most containers only have loopback, so 32 buckets is more than sufficient.

With these settings, objdump confirms that inet_lookup_ifaddr_rcu() contains zero indirect calls and zero function calls to hashfn or cmpfn -- everything is inlined by the compiler.

The check_lifetime() work function previously iterated all hash buckets directly. Since rhltable does not expose bucket iteration, this is converted to iterate via for_each_netdev + in_dev->ifa_list, which is the natural way to walk all addresses and avoids coupling the lifetime logic to the hash table internals.

Benchmarks
----------

Performance was measured using bpftrace kprobe/kretprobe on __ip_dev_find inside a virtme-ng VM (4 vCPUs, veth pair, network namespaces, CPU-isolated host). A C benchmark tool sends unconnected UDP packets in a tight loop, cycling through all source addresses to exercise the lookup path on every sendto().

__ip_dev_find average latency (bpftrace stats, 5 rounds x 3s):

  Addrs   rhltable (ns)   hlist (ns)   Improvement
  -----   -------------   ----------   -----------
     20           201          200          0%
    100           210          218         +4%
    500           206          234        +12%
    700           218          237         +8%
   1000           214          228         +6%
   2000           231          265        +13%
   5000           247          335        +26%

At low address counts (20) the rhltable matches the hlist. The custom obj_cmpfn (single cmp vs memcmp) and the compiler-inlined jhash2 keeps the more advanced hash table as fast as the simple hlist.

At the production use-case of ~700 addresses, the rhltable provides an 8% reduction in __ip_dev_find latency (218 ns vs 237 ns). The improvement grows with address count, reaching 26% at 5000 addresses as hlist chains lengthen while rhltable stays flat.

Note: bpftrace kprobe/kretprobe instrumentation adds constant overhead to each call, so the absolute nanosecond values are inflated. The relative improvement percentages are the meaningful comparison.

UDP sendmsg throughput (end-to-end, 10 rounds x 3s, unconnected sendto() cycling all source addresses, iptables DROP on receiver, virtme-ng VM with CPU isolation, frequency pinned to 1400 MHz):

  Addrs   rhltable (pkt/s)   hlist (pkt/s)   Improvement
  -----   ----------------   -------------   -----------
     20          385,696          389,206        -0.9%
    100          382,188          382,693        -0.1%
    500          378,509          366,216        +3.4%
    700          375,295          361,877        +3.7%
   1000          365,848          356,039        +2.8%
   2000          345,092          333,232        +3.6%
   5000          324,478          303,649        +6.9%
  10000          330,775          268,786       +23.1%

The absolute throughput is low because CPUs are deliberately down-clocked for measurement stability (CV < 2%). The relative improvement percentages are the meaningful comparison.

At the production use-case of ~700 addresses, rhltable provides a +3.7% throughput improvement, growing to +23% at 10,000 addresses as hlist O(N/256) chain walks dominate.

Summary
-------

Patches 1-2 (CONFIG option) are trivial, safe, and solve the immediate problem for operators who can rebuild their kernel. Patches 3-4 (rhltable) are a better long-term solution that works automatically for all workloads, at the cost of more complex code and a harder review.

If the rhltable approach is acceptable, patches 1-2 become unnecessary (the rhltable supersedes the fixed hash table entirely). They are included here to give maintainers the choice.

Future work: a similar rhltable conversion for IPv6 inet6_addr_lst.

Jesper Dangaard Brouer (4):
ipv4: make inet_addr_lst hash table size configurable
ipv6: make inet6_addr_lst hash table size configurable
ipv4: convert inet_addr_lst to rhltable for dynamic resizing
selftests: net: add IPv4 address lookup stress test

 include/linux/inetdevice.h                    |   3 +-
 include/net/ip.h                              |   5 -
 include/net/netns/ipv4.h                      |   4 +-
 net/ipv4/devinet.c                            | 149 ++--
 net/ipv6/Kconfig                              |  15 +
 net/ipv6/addrconf.c                           |   2 +-
 tools/testing/selftests/net/Makefile          |   3 +
 .../selftests/net/ipv4_addr_lookup_test.sh    | 804 ++++++++++++++++++
 .../net/ipv4_addr_lookup_test_virtme.sh       | 282 ++++++
 .../selftests/net/ipv4_addr_lookup_trace.bt   | 178 ++++
 .../net/ipv4_addr_lookup_udp_sender.c         | 401 +++++++++
 11 files changed, 1772 insertions(+), 74 deletions(-)
 create mode 100755 tools/testing/selftests/net/ipv4_addr_lookup_test.sh
 create mode 100755 tools/testing/selftests/net/ipv4_addr_lookup_test_virtme.sh
 create mode 100644 tools/testing/selftests/net/ipv4_addr_lookup_trace.bt
 create mode 100644 tools/testing/selftests/net/ipv4_addr_lookup_udp_sender.c
Signature · 1 line
2.43.0
#1 lore raw

RFC PATCH 1/4 ipv4: make inet_addr_lst hash table size configurable

From: Jesper Dangaard Brouer <[email protected]>

On servers with many IPv4 addresses, __ip_dev_find() becomes visible in perf profiles on the unconnected UDP sendmsg path. The call chain is:

udpv6_sendmsg / udp_sendmsg
ip_route_output_flow
ip_route_output_key_hash_rcu
__ip_dev_find <-- source address validation

__ip_dev_find() calls inet_lookup_ifaddr_rcu() which walks a hash chain in inet_addr_lst. With the current fixed table size of 256 buckets, a host with ~700 IPv4 addresses averages ~2.8 entries per chain, adding unnecessary cache misses under RCU on every unconnected send.

Add CONFIG_INET_ADDR_HASH_BUCKETS (default 256, range 64-16384, EXPERT) so hosts with many addresses can size the table appropriately. The value is rounded up to the nearest power of 2 at compile time via order_base_2(). Memory cost is one hlist_head pointer per bucket per net namespace.

---
 net/ipv4/Kconfig   | 16 ++++++++++++++++
 net/ipv4/devinet.c |  2 +-
 2 files changed, 17 insertions(+), 1 deletion(-)
net/ipv4/Kconfig +16 -0
index df922f9f5289..3c5e5e74b3e4 100644
@@ -402,6 +402,22 @@ config INET_IPCOMP
 
 	  If unsure, say Y.
 
+config INET_ADDR_HASH_BUCKETS
+	int "IPv4 address hash table size" if EXPERT
+	range 64 16384
+	default 256
+	help
+	  Number of hash buckets for looking up local IPv4 addresses,
+	  e.g. during route output to validate the source address via
+	  __ip_dev_find().  Rounded up to the nearest power of 2.
+
+	  Hosts with many IPv4 addresses benefit from a larger table to reduce
+	  hash chain lengths. This is particularly relevant when sending using
+	  unconnected UDP sockets.
+
+	  The default of 256 is fine for most systems.  A value of 1024
+	  suits hosts with ~500+ addresses.
+
 config INET_TABLE_PERTURB_ORDER
 	int "INET: Source port perturbation table size (as power of 2)" if EXPERT
 	default 16
net/ipv4/devinet.c +1 -1
index 58fe7cb69545..9e3da06fb618 100644
@@ -108,7 +108,7 @@ static const struct nla_policy ifa_ipv4_policy[IFA_MAX+1] = {
 	[IFA_PROTO]		= { .type = NLA_U8 },
 };
 
-#define IN4_ADDR_HSIZE_SHIFT	8
+#define IN4_ADDR_HSIZE_SHIFT	order_base_2(CONFIG_INET_ADDR_HASH_BUCKETS)
 #define IN4_ADDR_HSIZE		(1U << IN4_ADDR_HSIZE_SHIFT)
 
 static u32 inet_addr_hash(const struct net *net, __be32 addr)
Signature · 1 line
2.43.0
#2 lore raw

RFC PATCH 2/4 ipv6: make inet6_addr_lst hash table size configurable

In reply to [email protected]

From: Jesper Dangaard Brouer <[email protected]>

Similar to the IPv4 inet_addr_lst hash table, IPv6 also uses a fixed 256-bucket hash table for address lookups. On hosts with many IPv6 addresses, this results in long hash chains walked under RCU.

The inet6_addr_lst table is used in the route lookup path when no output interface is specified (oif == 0):

udpv6_sendmsg

    ip6_sk_dst_lookup_flow
      ip6_dst_lookup_tail
        ip6_route_output -> fib6 lookup
          __rt6_device_match
            ipv6_chk_addr              <-- walks inet6_addr_lst

Add CONFIG_INET6_ADDR_HASH_BUCKETS (default 256, range 64-16384, EXPERT) so hosts with many addresses can size the table appropriately. The value is rounded up to the nearest power of 2 at compile time via order_base_2(). Memory cost is one hlist_head pointer per bucket per net namespace.

---
 net/ipv6/Kconfig    | 15 +++++++++++++++
 net/ipv6/addrconf.c |  2 +-
 2 files changed, 16 insertions(+), 1 deletion(-)
net/ipv6/Kconfig +15 -0
index b8f9a8c0302e..963fa0e1a014 100644
@@ -238,6 +238,21 @@ config IPV6_FOU_TUNNEL
 	default NET_FOU_IP_TUNNELS && IPV6_FOU
 	select IPV6_TUNNEL
 
+config INET6_ADDR_HASH_BUCKETS
+	int "IPv6 address hash table size" if EXPERT
+	range 64 16384
+	default 256
+	help
+	  Number of hash buckets for looking up local IPv6 addresses,
+	  e.g. in ipv6_chk_addr() and related callers.  Rounded up to
+	  the nearest power of 2.
+
+	  Hosts with many IPv6 addresses benefit from a larger table to
+	  reduce hash chain lengths.
+
+	  The default of 256 is fine for most systems.  A value of 1024
+	  suits hosts with ~500+ addresses.
+
 config IPV6_MULTIPLE_TABLES
 	bool "IPv6: Multiple Routing Tables"
 	select FIB_RULES
net/ipv6/addrconf.c +1 -1
index 0e55f139e05d..dad08f0733ef 100644
@@ -144,7 +144,7 @@ static int ipv6_generate_stable_address(struct in6_addr *addr,
 					u8 dad_count,
 					const struct inet6_dev *idev);
 
-#define IN6_ADDR_HSIZE_SHIFT	8
+#define IN6_ADDR_HSIZE_SHIFT	order_base_2(CONFIG_INET6_ADDR_HASH_BUCKETS)
 #define IN6_ADDR_HSIZE		(1 << IN6_ADDR_HSIZE_SHIFT)
 
 static void addrconf_verify(struct net *net);
Signature · 1 line
2.43.0
#3 lore raw

RFC PATCH 3/4 ipv4: convert inet_addr_lst to rhltable for dynamic resizing

In reply to [email protected]

From: Jesper Dangaard Brouer <[email protected]>

The per-netns IPv4 local address hash table (inet_addr_lst) is a fixed-size hlist with 256 buckets (IN4_ADDR_HSIZE). On hosts with many addresses -- e.g. ~700 on Cloudflare edge nodes -- the average chain length reaches ~2.8, making inet_lookup_ifaddr_rcu() visible in perf profiles on the unconnected UDP sendmsg path via __ip_dev_find().

Replace the fixed hlist with an rhltable (resizable hash linked table) that grows and shrinks automatically as addresses are added or removed.

The rhl variant is needed because the same IP can exist on multiple interfaces. A plain rhashtable would reject the second insert with -EEXIST, and removing one interface's address would silently drop the other from the table. All current callers only need first-match semantics, which rhltable_lookup() provides.

The rhashtable_params are tuned for this use case:

- No explicit .hashfn: with key_len = sizeof(__be32), the default path calls jhash2(key, 1, seed) which the compiler fully inlines.

- .obj_cmpfn: a direct __be32 comparison replacing the generic memcmp() in the default rhashtable_compare(). The compiler inlines this to a single cmp instruction.

- .min_size = 32: most network namespaces only have loopback, so 32 buckets (256 bytes) is sufficient and saves memory compared to the old fixed 256-bucket table (2048 bytes per netns).

With these settings, objdump confirms zero indirect calls and zero function calls to hashfn or cmpfn in the lookup path.

The check_lifetime() work function previously iterated all hash buckets directly. Convert it to walk for_each_netdev -> in_dev->ifa_list, which is the natural way to enumerate all addresses and avoids coupling the lifetime logic to hash table internals.

The rhltable serves as a lookup cache for __ip_dev_find(). If rhltable_insert() fails (e.g. -ENOMEM during table resize), the address remains on in_dev->ifa_list and lookups fall back to the slower but always-correct fib_table_lookup() path. A pr_warn is emitted on insert failure for diagnostics. On remove, -ENOENT is tolerated since the preceding insert may have failed.

---
 include/linux/inetdevice.h |   3 +-
 include/net/ip.h           |   5 --
 include/net/netns/ipv4.h   |   4 +-
 net/ipv4/Kconfig           |  16 ----
 net/ipv4/devinet.c         | 149 +++++++++++++++++++++----------------
 5 files changed, 88 insertions(+), 89 deletions(-)
include/linux/inetdevice.h +2 -1
index dccbeb25f701..e2f7a2f721c9 100644
@@ -13,6 +13,7 @@
 #include <linux/sysctl.h>
 #include <linux/rtnetlink.h>
 #include <linux/refcount.h>
+#include <linux/rhashtable-types.h>
 
 struct ipv4_devconf {
 	void	*sysctl;
@@ -141,7 +142,7 @@ static inline void ipv4_devconf_setall(struct in_device *in_dev)
 							  ARP_EVICT_NOCARRIER)
 
 struct in_ifaddr {
-	struct hlist_node	addr_lst;
+	struct rhlist_head	addr_lst;
 	struct in_ifaddr	__rcu *ifa_next;
 	struct in_device	*ifa_dev;
 	struct rcu_head		rcu_head;
include/net/ip.h +0 -5
index f39a3787fedd..03932ec93d67 100644
@@ -705,11 +705,6 @@ static inline unsigned int ipv4_addr_hash(__be32 ip)
 	return (__force unsigned int) ip;
 }
 
-static inline u32 __ipv4_addr_hash(const __be32 ip, const u32 initval)
-{
-	return jhash_1word((__force u32)ip, initval);
-}
-
 static inline u32 ipv4_portaddr_hash(const struct net *net,
 				     __be32 saddr,
 				     unsigned int port)
include/net/netns/ipv4.h +2 -2
index 80ccd4dda8e0..f956ea1b23ca 100644
@@ -11,11 +11,11 @@
 #include <linux/rcupdate.h>
 #include <linux/seqlock.h>
 #include <linux/siphash.h>
+#include <linux/rhashtable-types.h>
 
 struct ctl_table_header;
 struct ipv4_devconf;
 struct fib_rules_ops;
-struct hlist_head;
 struct fib_table;
 struct sock;
 struct local_ports {
@@ -296,7 +296,7 @@ struct netns_ipv4 {
 
 	atomic_t	rt_genid;
 	siphash_key_t	ip_id_key;
-	struct hlist_head	*inet_addr_lst;
+	struct rhltable		inet_addr_lst;
 	struct delayed_work	addr_chk_work;
 };
 
net/ipv4/Kconfig +0 -16
index 3c5e5e74b3e4..df922f9f5289 100644
@@ -402,22 +402,6 @@ config INET_IPCOMP
 
 	  If unsure, say Y.
 
-config INET_ADDR_HASH_BUCKETS
-	int "IPv4 address hash table size" if EXPERT
-	range 64 16384
-	default 256
-	help
-	  Number of hash buckets for looking up local IPv4 addresses,
-	  e.g. during route output to validate the source address via
-	  __ip_dev_find().  Rounded up to the nearest power of 2.
-
-	  Hosts with many IPv4 addresses benefit from a larger table to reduce
-	  hash chain lengths. This is particularly relevant when sending using
-	  unconnected UDP sockets.
-
-	  The default of 256 is fine for most systems.  A value of 1024
-	  suits hosts with ~500+ addresses.
-
 config INET_TABLE_PERTURB_ORDER
 	int "INET: Source port perturbation table size (as power of 2)" if EXPERT
 	default 16
net/ipv4/devinet.c +84 -65

250 lines not on this page · raw message

Signature · 1 line
2.43.0
#4 lore raw

RFC PATCH 4/4 selftests: net: add IPv4 address lookup stress test

In reply to [email protected]

From: Jesper Dangaard Brouer <[email protected]>

Add a test that exercises the IPv4 local address hash table (inet_addr_lst) insert, lookup, and remove paths under load:

- Add/remove 1000 addresses to trigger rhltable growth and shrinking
- Unconnected UDP sendmsg stress to exercise the __ip_dev_find() lookup hot path (each sendto triggers a hash table lookup)
- Duplicate key test: same IP on two different interfaces
- Address lifetime expiry via check_lifetime() work function
- Ping-based lookup verification from sampled addresses

The test uses network namespaces and veth pairs to avoid polluting the host. A C helper (ipv4_addr_lookup_udp_sender) pre-creates sockets during setup for low-noise measurement with per-round statistics.

Optional bpftrace integration (--bpftrace, --bpftrace-debug) provides latency histograms and resize event tracing for A/B kernel comparison. A virtme-ng wrapper script is included for isolated VM testing.

---
 tools/testing/selftests/net/Makefile          |   4 +
 .../selftests/net/ipv4_addr_lookup_test.sh    | 804 ++++++++++++++++++
 .../net/ipv4_addr_lookup_test_virtme.sh       | 282 ++++++
 .../selftests/net/ipv4_addr_lookup_trace.bt   | 178 ++++
 .../net/ipv4_addr_lookup_udp_sender.c         | 401 +++++++++
 5 files changed, 1669 insertions(+)
 create mode 100755 tools/testing/selftests/net/ipv4_addr_lookup_test.sh
 create mode 100755 tools/testing/selftests/net/ipv4_addr_lookup_test_virtme.sh
 create mode 100644 tools/testing/selftests/net/ipv4_addr_lookup_trace.bt
 create mode 100644 tools/testing/selftests/net/ipv4_addr_lookup_udp_sender.c
tools/testing/selftests/net/Makefile +4 -0
index 6bced3ed798b..1724d1478020 100644
@@ -42,6 +42,7 @@ TEST_PROGS := \
 	gre_ipv6_lladdr.sh \
 	icmp.sh \
 	icmp_redirect.sh \
+	ipv4_addr_lookup_test.sh \
 	io_uring_zerocopy_tx.sh \
 	ioam6.sh \
 	ip6_gre_headroom.sh \
@@ -127,6 +128,8 @@ TEST_PROGS := \
 # end of TEST_PROGS
 
 TEST_PROGS_EXTENDED := \
+	ipv4_addr_lookup_test_virtme.sh \
+	ipv4_addr_lookup_trace.bt \
 	xfrm_policy_add_speed.sh \
 # end of TEST_PROGS_EXTENDED
 
@@ -135,6 +138,7 @@ TEST_GEN_FILES := \
 	cmsg_sender \
 	fin_ack_lat \
 	hwtstamp_config \
+	ipv4_addr_lookup_udp_sender \
 	io_uring_zerocopy_tx \
 	ioam6_parser \
 	ip_defrag \
tools/testing/selftests/net/ipv4_addr_lookup_test.sh new file +804 -0

804 lines not on this page · raw message

tools/testing/selftests/net/ipv4_addr_lookup_test_virtme.sh new file +282 -0

282 lines not on this page · raw message

tools/testing/selftests/net/ipv4_addr_lookup_trace.bt new file +178 -0

178 lines not on this page · raw message

tools/testing/selftests/net/ipv4_addr_lookup_udp_sender.c new file +401 -0

401 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#5 lore raw
In reply to [email protected]
Quoted 9 lines · On 3/31/26 3:07 PM, [email protected] wrote:

Benchmarks
----------

Performance was measured using bpftrace kprobe/kretprobe on __ip_dev_find inside a virtme-ng VM (4 vCPUs, veth pair, network namespaces, CPU-isolated host). A C benchmark tool sends unconnected UDP packets in a tight loop, cycling through all source addresses to exercise the lookup path on every sendto().

Quoted 5 lines

__ip_dev_find average latency (bpftrace stats, 5 rounds x 3s):

  Addrs   rhltable (ns)   hlist (ns)   Improvement
  -----   -------------   ----------   -----------

20 201 200 0%

why 20 as the low end? 1 ipv4, 2 ipv6 would be most common use case. All of the benchmarking numbers should start there.

Quoted 7 lines
    100           210          218         +4%
    500           206          234        +12%
    700           218          237         +8%
   1000           214          228         +6%
   2000           231          265        +13%
   5000           247          335        +26%