From e0be6bc2f4762ba8c090aef0f8b85a47a4243356 Mon Sep 17 00:00:00 2001 From: David Gibson Date: Tue, 27 Aug 2024 16:04:46 +1000 Subject: [PATCH] udp: Use dual stack sockets for port forwarding when possible Platforms like Linux allow IPv6 sockets to listen for IPv4 connections as well as native IPv6 connections. By doing this we halve the number of listening sockets we need (assuming passt/pasta is listening on the same ports for IPv4 and IPv6). When forwarding many ports (e.g. -u all) this can significantly reduce the amount of kernel memory that passt consumes. We've used such dual stack sockets for TCP since 8e914238b "tcp: Use dual stack sockets for port forwarding when possible". Add similar support for UDP "listening" sockets. Since UDP sockets don't use as much kernel memory as TCP sockets this isn't as big a saving, but it's still significant. When forwarding all TCP and UDP ports for both IPv4 & IPv6 (-t all -u all), this reduces kernel memory usage from ~522 MiB to ~380MiB (kernel version 6.10.6 on Fedora 40, x86_64). Signed-off-by: David Gibson Signed-off-by: Stefano Brivio --- udp.c | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/udp.c b/udp.c index 41a6247..bd9051e 100644 --- a/udp.c +++ b/udp.c @@ -723,6 +723,25 @@ int udp_sock_init(const struct ctx *c, int ns, sa_family_t af, else uref.pif = PIF_HOST; + if (af == AF_UNSPEC && c->ifi4 && c->ifi6) { + int s; + + /* Attempt to get a dual stack socket */ + if (!ns) { + s = sock_l4(c, AF_UNSPEC, EPOLL_TYPE_UDP_LISTEN, + addr, ifname, port, uref.u32); + udp_splice_init[V4][port] = s < 0 ? -1 : s; + udp_splice_init[V6][port] = s < 0 ? -1 : s; + } else { + s = sock_l4(c, AF_UNSPEC, EPOLL_TYPE_UDP_LISTEN, + &in4addr_loopback, ifname, port, uref.u32); + udp_splice_ns[V4][port] = s < 0 ? -1 : s; + udp_splice_ns[V6][port] = s < 0 ? -1 : s; + } + if (IN_INTERVAL(0, FD_REF_MAX, s)) + return 0; + } + if ((af == AF_INET || af == AF_UNSPEC) && c->ifi4) { if (!ns) { r4 = sock_l4(c, AF_INET, EPOLL_TYPE_UDP_LISTEN,