tcp: fix false exhaustion of odd-sized bind port ranges

Started by Florin Badita-Nistor on Nov 5, 2026 · 5 messages from 2 authors · Last reply Nov 5, 2026

Series

2 patches, 2 files

Subsystems (4)

Show 1 more

Maintainers (8)

Show 4 more
COLD16d SUPERSEDED

Status: Superseded by v2 (posted 2026-11-06). [go to v2]

Revision v1 (2 revisions archived).

Revisions (2)
  1. v1 current
  2. v2 [diff against previous]

open the first message on its own page

  1. [PATCH net 1/2] tcp: avoid false bind exhaustion with odd-sized port ranges
    Revisions and related patches
    Revisions (2)
    1. v1 current
    2. v2 [diff against previous]
  2. [PATCH net 2/2] selftests/net: cover odd-sized local port ranges with one free port
    Revisions and related patches
    Revisions (2)
    1. v1 current
    2. v2 [diff against previous]
Message details and related content
TCP and MPTCP can reject an automatic bind with EADDRINUSE while an
eligible port is still free in an odd-sized local port range. For a
three-port range with its first two ports occupied, automatic binding
always fails although explicitly binding the final port succeeds.

Patch 1 keeps the complete range length in inet_csk_find_open_port().
Patch 2 adds regression coverage for each free-port position in three-
and five-port ranges, with both lower-bound parities and all existing
protocol/IP fixture variants.

The issue was triggered while extending port-range tests with Codex
assistance, then isolated using userspace reproducers on unmodified
kernels. No kernel instrumentation or fault injection was used.
Codex assisted with analysis, reproducers, patch/test code and commit
messages. The task was to find a small networking contribution relevant
to high-concurrency workloads; the missed-port case emerged during that
investigation. An independent model review found no correctness blocker.

Built and booted the exact net base below and that base with the fix in
separate x86-64 KVM guests using the same configuration and binaries:

  New regression test: 4 failures before, 0 afterwards (8 cases).
  Full port-range suite: 4 failures before, 0 afterwards (80 cases).
  Two existing SCTP late_bind XPASS outcomes are unchanged.
  Go net.Listen with a three-port namespace range and two listeners:
    IPv4: 100/100 failures before, 0/100 afterwards.
    IPv6: 100/100 failures before, 0/100 afterwards.
  Explicitly listening on the free final port succeeds in both kernels.

Even-sized candidate sequences are unchanged. This is a correctness fix
for odd-sized ranges, without a general throughput claim.

The userspace selftests were compiled with -Wall. The boot-tested kernel
builds used W=1. The changed allocator object also compiled with W=1
under allyesconfig and allmodconfig (object builds, not full builds of
those two configurations). The baseline W=1 build emitted an existing
Synaptics input-driver format warning outside these changes; the changed
allocator object compiled without diagnostics. Both emails were sent
through a self-only transport test,
read back as raw messages and applied with git am, reproducing the exact

14 more lines

[PATCH net 1/2] tcp: avoid false bind exhaustion with odd-sized port ranges

Message details and related content
inet_csk_find_open_port() rounds the range length down to an even
number but keeps the original exclusive upper bound for wrapping.
For an odd-sized range, the two scans can therefore miss a valid port
and return EADDRINUSE while an eligible port remains free.

For example, restrict a TCP socket to IP_LOCAL_PORT_RANGE [40000, 40002]
and hold explicit binds on 40000 and 40001. bind(..., 0) always fails,
although an explicit bind to 40002 succeeds. Both IPv4 and IPv6 TCP and
MPTCP are affected. A namespace-wide odd-sized ip_local_port_range can
also trigger the failure without a per-socket range setting.

Keep the full length for the scan bound and wrapping. The two scans
then cover every candidate in an odd-sized range, with at most one
repeated candidate when exhausted. Even-sized candidate sequences
remain unchanged.

The issue was triggered while developing port-range selftests with
Codex assistance, then confirmed using userspace reproducers on
unmodified kernels. No kernel instrumentation or fault injection was
needed. Booted x86-64 KVM kernels were tested against the regression
selftest, the full ip_local_port_range suite, and a Go net.Listen
reproducer. The Go reproducer fails 100/100 times per IP version before
the fix and 0/100 afterwards with a three-port namespace range and two
listeners occupying its first two ports.

Fixes: ea8add2b1903 ("tcp/dccp: better use of ephemeral ports in bind()")
Cc: <redacted>
Signed-off-by: Florin Badita-Nistor <redacted>
---
 net/ipv4/inet_connection_sock.c | 2 --
 1 file changed, 2 deletions(-)
diff --git a/net/ipv4/inet_connection_sock.c b/net/ipv4/inet_connection_sock.c
index e56beec43..755fcea35 100644
--- a/net/ipv4/inet_connection_sock.c
+++ b/net/ipv4/inet_connection_sock.c
@@ -343,8 +343,6 @@ inet_csk_find_open_port(const struct sock *sk,
struct inet_bind_bucket **tb_ret,
 			low = half;
 	}
 	remaining = high - low;
-	if (likely(remaining > 1))
-		remaining &= ~1U;

 	offset = get_random_u32_below(remaining);
 	/* __inet_hash_connect() favors ports having @low parity

base-commit: c6b41de4dd9f2d6856d8d8d292348f7961034152
-- 
2.51.0

[PATCH net 2/2] selftests/net: cover odd-sized local port ranges with one free port

Message details and related content
Leave each port in three- and five-port socket-local ranges as the only
available candidate and verify that bind(..., 0) can allocate it. Cover
both lower-bound parities and repeat allocation to vary the random
starting offset. Use the existing IPv4/IPv6 TCP, UDP, SCTP and MPTCP
fixture variants.

This catches the false EADDRINUSE caused by rounding an odd-sized range
down during TCP port allocation. Without the preceding fix, the TCP
and MPTCP variants fail on both IP versions when the last port in a
three-port range is the only free one. With the fix, all eight variants
pass.

Allow the loopback bind helper to take a port so the test can hold
explicit binds on every other candidate. Retain the existing helper for
automatic binding and run under the existing isolated-network-namespace
wrapper.

The regression test was developed with Codex assistance and exercised
on booted x86-64 KVM kernels before and after the fix.

Signed-off-by: Florin Badita-Nistor <redacted>
---
 .../selftests/net/ip_local_port_range.c       | 67 ++++++++++++++++++-
 1 file changed, 64 insertions(+), 3 deletions(-)
diff --git a/tools/testing/selftests/net/ip_local_port_range.c
b/tools/testing/selftests/net/ip_local_port_range.c
index 3d32b33cb..c17d95045 100644
--- a/tools/testing/selftests/net/ip_local_port_range.c
+++ b/tools/testing/selftests/net/ip_local_port_range.c
@@ -44,7 +44,7 @@ static int get_so_domain(int fd)
 	return domain;
 }

-static int bind_to_loopback_any_port(int fd)
+static int bind_to_loopback_port(int fd, __u16 port)
 {
 	union {
 		struct sockaddr sa;
@@ -57,13 +57,13 @@ static int bind_to_loopback_any_port(int fd)
 	switch (get_so_domain(fd)) {
 	case AF_INET:
 		addr.v4.sin_family = AF_INET;
-		addr.v4.sin_port = htons(0);
+		addr.v4.sin_port = htons(port);
 		addr.v4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
 		addr_len = sizeof(addr.v4);
 		break;
 	case AF_INET6:
 		addr.v6.sin6_family = AF_INET6;
-		addr.v6.sin6_port = htons(0);
+		addr.v6.sin6_port = htons(port);
 		addr.v6.sin6_addr = in6addr_loopback;
 		addr_len = sizeof(addr.v6);
 		break;
@@ -74,6 +74,11 @@ static int bind_to_loopback_any_port(int fd)
 	return bind(fd, &addr.sa, addr_len);
 }

+static int bind_to_loopback_any_port(int fd)
+{
+	return bind_to_loopback_port(fd, 0);
+}
+
 static int get_sock_port(int fd)
 {
 	union {
@@ -301,6 +306,62 @@ TEST_F(ip_local_port_range, single_port_range)
 	}
 }

+/* Leave each port in turn as the only available one. An odd-sized range
+ * must not report exhaustion while a port at either end is still free.
+ */
+TEST_F(ip_local_port_range, odd_port_range)
+{
+	const struct {
+		__u16 low;
+		__u16 high;
+	} ranges[] = {
+		{ 40000, 40002 },
+		{ 40001, 40003 },
+		{ 40000, 40004 },
+		{ 40001, 40005 },
+	};
+	int i, j, port, free_port, fd, err;
+	__u32 range;
+	int fds[5];
+
+	for (i = 0; i < ARRAY_SIZE(ranges); i++) {
+		range = pack_port_range(ranges[i].low, ranges[i].high);
+		for (free_port = ranges[i].low; free_port <= ranges[i].high; free_port++) {
+			for (port = ranges[i].low; port <= ranges[i].high; port++) {
+				j = port - ranges[i].low;
+				fds[j] = -1;
+				if (port == free_port)
+					continue;
+				fd = socket(variant->so_domain, variant->so_type,
+					    variant->so_protocol);
+				ASSERT_GE(fd, 0) TH_LOG("socket failed");
+				fds[j] = fd;
+				err = bind_to_loopback_port(fd, port);
+				ASSERT_EQ(err, 0) TH_LOG("bind(%d) failed", port);
+			}
+
+			/* Exercise different random starting offsets. */
+			for (j = 0; j < 16; j++) {
+				fd = socket(variant->so_domain, variant->so_type,
+					    variant->so_protocol);
+				ASSERT_GE(fd, 0) TH_LOG("socket failed");
+				err = setsockopt(fd, SOL_IP, IP_LOCAL_PORT_RANGE,
+						 &range, sizeof(range));
+				ASSERT_EQ(err, 0) TH_LOG("setsockopt(IP_LOCAL_PORT_RANGE) failed");
+				err = bind_to_loopback_any_port(fd);
+				ASSERT_EQ(err, 0) TH_LOG("range %d-%d, free port %d",
+						       ranges[i].low, ranges[i].high, free_port);
+				ASSERT_EQ(get_sock_port(fd), free_port);
+				ASSERT_EQ(close(fd), 0);
+			}
+
+			for (j = 0; j <= ranges[i].high - ranges[i].low; j++)
+				if (fds[j] >= 0)
+					ASSERT_EQ(close(fds[j]), 0);
+		}
+	}
+}
+
 #define REUSEADDR	0x1
 #define REUSEPORT	0x2
-- 
2.51.0

Re: [PATCH net 1/2] tcp: avoid false bind exhaustion with odd-sized port ranges

Message details and related content
Le jeu. 5 nov. 2026 à 12:04, Florin Badita-Nistor
[off-list ref] a écrit :
inet_csk_find_open_port() rounds the range length down to an even
number but keeps the original exclusive upper bound for wrapping.
For an odd-sized range, the two scans can therefore miss a valid port
and return EADDRINUSE while an eligible port remains free.

For example, restrict a TCP socket to IP_LOCAL_PORT_RANGE [40000, 40002]
and hold explicit binds on 40000 and 40001. bind(..., 0) always fails,
although an explicit bind to 40002 succeeds. Both IPv4 and IPv6 TCP and
MPTCP are affected. A namespace-wide odd-sized ip_local_port_range can
also trigger the failure without a per-socket range setting.

Keep the full length for the scan bound and wrapping. The two scans
then cover every candidate in an odd-sized range, with at most one
repeated candidate when exhausted. Even-sized candidate sequences
remain unchanged.
Please mention the side effect: with an odd @remaining, the wrap
(port -= remaining) flips parity, so the first scan is no longer
restricted to odd offsets. For odd-sized ranges, bind() will now pick
ports of the parity __inet_hash_connect() prefers.

I think this is fine: same-parity netns ranges already trigger
"ip_local_port_range: prefer different parity for start/end values",
and __inet_hash_connect() ignores parity (step == 1) for per-socket
IP_LOCAL_PORT_RANGE. But the changelog should say so.

Also note that __inet_hash_connect() has the same rounding for
netns-wide ranges, so connect() still misses a port there. This is
fine since the sysctl already warns about this setup, but the
changelog should not suggest netns-wide odd ranges are now fully
handled.

The issue was triggered while developing port-range selftests with
Codex assistance, then confirmed using userspace reproducers on
unmodified kernels. No kernel instrumentation or fault injection was
needed. Booted x86-64 KVM kernels were tested against the regression
selftest, the full ip_local_port_range suite, and a Go net.Listen
reproducer. The Go reproducer fails 100/100 times per IP version before
the fix and 0/100 afterwards with a three-port namespace range and two
listeners occupying its first two ports.

Fixes: ea8add2b1903 ("tcp/dccp: better use of ephemeral ports in bind()")
Cc: <redacted>
This has been there since 2016 and needs an odd-sized range, I would
target net-next and drop the stable Cc.
quoted hunk
Signed-off-by: Florin Badita-Nistor <redacted>
---
 net/ipv4/inet_connection_sock.c | 2 --
 1 file changed, 2 deletions(-)
diff --git a/net/ipv4/inet_connection_sock.c b/net/ipv4/inet_connection_sock.c
index e56beec43..755fcea35 100644
--- a/net/ipv4/inet_connection_sock.c
+++ b/net/ipv4/inet_connection_sock.c
@@ -343,8 +343,6 @@ inet_csk_find_open_port(const struct sock *sk,
struct inet_bind_bucket **tb_ret,
Both patches are mangled by your mailer (wrapped hunk header here,
wrapped diff --git line in 2/2), they do not apply. Please use
git send-email for v2.

Also, please trim the cover letter to the problem and the test
results.

The code change itself looks good to me.

pw-bot:cr

Re: [PATCH net 1/2] tcp: avoid false bind exhaustion with odd-sized port ranges

Message details and related content
Hi Eric,
Please mention the side effect: with an odd @remaining, the wrap
(port -= remaining) flips parity, so the first scan is no longer
restricted to odd offsets.
Agreed. I will state that wrapping an odd-sized range can select ports
of the parity preferred by __inet_hash_connect(), while even-sized
candidate sequences remain unchanged.
Also note that __inet_hash_connect() has the same rounding for
netns-wide ranges, so connect() still misses a port there.
Understood. I will make the scope explicitly bind() allocation only.
The netns-wide connect() behavior remains unchanged; I will not suggest
that odd-sized namespace ranges are fully handled.
This has been there since 2016 and needs an odd-sized range, I would
target net-next and drop the stable Cc.
I will retarget both patches to net-next and remove the stable Cc.
Both patches are mangled by your mailer [...] Please use
git send-email for v2.

Also, please trim the cover letter to the problem and the test
results.
Sorry for the malformed patches. The raw Sent copies applied locally,
but that did not establish that the copies received by the list were
intact. I will use git send-email for v2 and verify the received copies.
I will also shorten the cover letter to the problem and test results.

I will allow at least 24 hours from v1 for further feedback before
posting v2 as a new thread, with a link to v1.

Thanks for reviewing the change.

Florin


On Thu, 05 Nov 2026 12:17:56 +0100, Eric Dumazet [off-list ref] wrote:
Le jeu. 5 nov. 2026 à 12:04, Florin Badita-Nistor
[off-list ref] a écrit :
quoted
inet_csk_find_open_port() rounds the range length down to an even
number but keeps the original exclusive upper bound for wrapping.
For an odd-sized range, the two scans can therefore miss a valid port
and return EADDRINUSE while an eligible port remains free.

For example, restrict a TCP socket to IP_LOCAL_PORT_RANGE [40000, 40002]
and hold explicit binds on 40000 and 40001. bind(..., 0) always fails,
although an explicit bind to 40002 succeeds. Both IPv4 and IPv6 TCP and
MPTCP are affected. A namespace-wide odd-sized ip_local_port_range can
also trigger the failure without a per-socket range setting.

Keep the full length for the scan bound and wrapping. The two scans
then cover every candidate in an odd-sized range, with at most one
repeated candidate when exhausted. Even-sized candidate sequences
remain unchanged.
Please mention the side effect: with an odd @remaining, the wrap
(port -= remaining) flips parity, so the first scan is no longer
restricted to odd offsets. For odd-sized ranges, bind() will now pick
ports of the parity __inet_hash_connect() prefers.

I think this is fine: same-parity netns ranges already trigger
"ip_local_port_range: prefer different parity for start/end values",
and __inet_hash_connect() ignores parity (step == 1) for per-socket
IP_LOCAL_PORT_RANGE. But the changelog should say so.

Also note that __inet_hash_connect() has the same rounding for
netns-wide ranges, so connect() still misses a port there. This is
fine since the sysctl already warns about this setup, but the
changelog should not suggest netns-wide odd ranges are now fully
handled.

quoted
The issue was triggered while developing port-range selftests with
Codex assistance, then confirmed using userspace reproducers on
unmodified kernels. No kernel instrumentation or fault injection was

34 more quoted lines

Keyboard shortcuts
hback out one level
jnext message in thread / next series-diff position
kprevious message in thread / previous series-diff position
ldrill in
Escclose help / fold thread tree
?toggle this help