Skip to contentSkip to conversation

tcp: clamp return value of tcp_wmem_schedule() to non-negative

PATCH Superseded Octavian Purdila 3 participants 6 messages Oct 20 – Oct 23

Subsystems (4)

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v2 cover tcp: clamp return value of tcp_wmem_schedule() to non-negative

This series fixes a bug discovered in production in tcp_wmem_schedule() where a negative sk->sk_forward_alloc under TCP memory pressure causes tcp_wmem_schedule() to return a negative copy length when sk->sk_wmem_queued already reaches or exceeds sysctl_tcp_wmem[0].

sk->sk_forward_alloc can transiently become negative when tcp_collapse() re-packs partially read or high payload-to-truesize SKBs in the receive queue and charges newly allocated SKBs via sk_mem_charge() before freeing the original SKBs. When a subsequent send hits memory pressure in sk_wmem_schedule() with sk->sk_wmem_queued >= sysctl_tcp_wmem[0], tcp_wmem_schedule() returns min(copy, sk->sk_forward_alloc) < 0. Callers such as tcp_sendmsg_locked() then pass that negative copy length to skb_copy_to_page_nocache() -> copy_from_iter_full() -> check_copy_size(), triggering WARN_ON_ONCE(bytes > INT_MAX) in production and returning -EFAULT instead of waiting for memory or returning -EAGAIN.

Patch 1 clamps the return value of tcp_wmem_schedule() to [0, copy] so a negative sk->sk_forward_alloc is treated as 0 available bytes. Patch 2 adds a packetdrill selftest that reproduces the negative sk->sk_forward_alloc condition via tcp_collapse() under memory pressure and verifies that a non-blocking write fails with EAGAIN rather than EFAULT.

Changes in v2:
- Include production warning trace in Patch 1 commit message.
- Skip the packetdrill test when PAGE_SIZE != 4096 via --define=REQUIRES_PAGESIZE="4096" in ksft_runner.sh.
- Collect Reviewed-by tags from Kuniyuki Iwashima and Eric Dumazet.

Octavian Purdila (2):
tcp: clamp return value of tcp_wmem_schedule() to non-negative
selftests: net: packetdrill: add test for negative sk_forward_alloc in
tcp_wmem_schedule()

 net/ipv4/tcp.c                                |   2 +-
 .../testing/selftests/net/packetdrill/config  |   1 +
 .../selftests/net/packetdrill/ksft_runner.sh  |   6 +
 .../tcp_wmem_schedule_negative_fwd_alloc.pkt  | 117 ++++++++++++++++++
 4 files changed, 125 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/net/packetdrill/tcp_wmem_schedule_negative_fwd_alloc.pkt
Signature · 1 line
2.56.0.212.g129ede20d9-goog
#1 lore raw

PATCH v2 1/2 tcp: clamp return value of tcp_wmem_schedule() to non-negative

When sk_wmem_schedule(sk, copy) fails under TCP memory pressure and sk->sk_wmem_queued already reaches or exceeds sysctl_tcp_wmem[0], tcp_wmem_schedule() returns min(copy, sk->sk_forward_alloc).

However, sk->sk_forward_alloc is a signed int that can transiently become negative when tcp_collapse() re-packs partially read or high payload-to-truesize SKBs in the receive queue and charges newly allocated SKBs via sk_mem_charge() before freeing the original SKB.

If tcp_wmem_schedule() returns a negative value, tcp_sendmsg_locked() passes that negative copy length to skb_copy_to_page_nocache() -> copy_from_iter_full() -> check_copy_size(), where it is converted to an unsigned size_t > INT_MAX, triggering a WARN_ON_ONCE(bytes > INT_MAX) in production and returning -EFAULT instead of waiting for memory or returning -EAGAIN:

  WARNING: CPU: 1 PID: 939331 at include/linux/thread_info.h:249 tcp_sendmsg+0x10c1/0x1530
  Call Trace:
   <TASK>
   __sys_sendmsg+0x292/0x490
   do_syscall_64+0x88/0x340
   entry_SYSCALL_64_after_hwframe+0x76/0x7e

Clamp the return value of tcp_wmem_schedule() to [0, copy] so callers treat negative sk_forward_alloc as 0 available bytes.

Fixes 849b425cd091 ("tcp: fix possible freeze in tx path under memory pressure")
Assisted-by LLM

---
v2:
- Add production warning trace to the commit message.

 net/ipv4/tcp.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/ipv4/tcp.c +1 -1
index 87ef6d5cbfeba..0e062fcd94a6c 100644
@@ -1037,7 +1037,7 @@ int tcp_wmem_schedule(struct sock *sk, int copy)
 	left = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[0]) - sk->sk_wmem_queued;
 	if (left > 0)
 		sk_forced_mem_schedule(sk, min(left, copy));
-	return min(copy, sk->sk_forward_alloc);
+	return clamp(sk->sk_forward_alloc, 0, copy);
 }
 
 void tcp_free_fastopen_req(struct tcp_sock *tp)
Signature · 1 line
2.56.0.212.g129ede20d9-goog
#2 lore raw

PATCH v2 2/2 selftests: net: packetdrill: add test for negative sk_forward_alloc in tcp_wmem_schedule()

In reply to Octavian Purdila

Add a packetdrill test that drives sk->sk_forward_alloc negative via tcp_collapse() on the receive queue while sk->sk_wmem_queued exceeds sysctl_tcp_wmem[0], and verifies that a subsequent non-blocking write() under TCP memory pressure fails with EAGAIN rather than returning a negative copy length from tcp_wmem_schedule() and failing with EFAULT.

---
v2:
- Skip the test when PAGE_SIZE != 4096 via --define=REQUIRES_PAGESIZE="4096" in ksft_runner.sh (Eric Dumazet).

 .../testing/selftests/net/packetdrill/config  |   1 +
 .../selftests/net/packetdrill/ksft_runner.sh  |   6 +
 .../tcp_wmem_schedule_negative_fwd_alloc.pkt  | 117 ++++++++++++++++++
 3 files changed, 124 insertions(+)
 create mode 100644 tools/testing/selftests/net/packetdrill/tcp_wmem_schedule_negative_fwd_alloc.pkt
tools/testing/selftests/net/packetdrill/config +1 -0
index b7df8bf309200..dc3cd72a8da8c 100644
@@ -1,6 +1,7 @@
 CONFIG_HZ=1000
 CONFIG_HZ_1000=y
 CONFIG_IPV6=y
+CONFIG_MEMCG=y
 CONFIG_NET_NS=y
 CONFIG_NET_SCH_FIFO=y
 CONFIG_NET_SCH_FQ=y
tools/testing/selftests/net/packetdrill/ksft_runner.sh +6 -0
index 0a97d5ae34699..dcda2b93c76e0 100755
@@ -52,6 +52,12 @@ if [[ -n "${KSFT_MACHINE_SLOW}" ]]; then
 	failfunc=ktap_test_xfail
 fi
 
+pagesize=$(grep -E '^--define=REQUIRES_PAGESIZE=' $script | cut -d '=' -f 3 | tr -d '"')
+if [[ -n "$pagesize" && "$(getconf PAGESIZE)" != "$pagesize" ]]; then
+	ktap_skip_all "requires ${pagesize}B PAGE_SIZE"
+	exit "$KSFT_SKIP"
+fi
+
 ip_versions=$(grep -E '^--ip_version=' $script | cut -d '=' -f 2)
 if [[ -z $ip_versions ]]; then
 	ip_versions="ipv4 ipv6 ipv4-mapped-ipv6"
tools/testing/selftests/net/packetdrill/tcp_wmem_schedule_negative_fwd_alloc.pkt new file +117 -0

117 lines not on this page · raw message

Signature · 1 line
2.56.0.212.g129ede20d9-goog
maintainer
#3 lore raw

Re: [PATCH net v2 2/2] selftests: net: packetdrill: add test for negative sk_forward_alloc in tcp_wmem_schedule()

Quoted 5 lines · On Tue, 20 Oct 2026 16:38:35 +0000 Octavian Purdila wrote:

Add a packetdrill test that drives sk->sk_forward_alloc negative via tcp_collapse() on the receive queue while sk->sk_wmem_queued exceeds sysctl_tcp_wmem[0], and verifies that a subsequent non-blocking write() under TCP memory pressure fails with EAGAIN rather than returning a negative copy length from tcp_wmem_schedule() and failing with EFAULT.

This is failing in our CI, it doesn't need any packetdrill updates, right?

Here's the AI report about the failure:

The new packetdrill test tcp_wmem_schedule_negative_fwd_alloc.pkt is failing in our CI (both the regular and debug kernel configs, all three address-family sub-tests: ipv4, ipv6, ipv4-mapped-ipv6):

tcp_wmem_schedule_negative_fwd_alloc.pkt:105: runtime error in write call:
Expected result -1 but got 3680 with errno 22 (Invalid argument)

Instead of the non-blocking write() failing with EAGAIN as the test expects, it succeeds and returns 3680 bytes. The kernel log for the run also shows the test's memory cgroup repeatedly entering the OOM-killer path (try_charge_memcg() -> mem_cgroup_out_of_memory(), "Out of memory and no killable processes...") from inside tcp_wmem_schedule(), rather than the write() being throttled and returning -EAGAIN as intended.

This suggests the test's reproduction recipe (tcp_collapse() driving sk_forward_alloc negative while sk_wmem_queued exceeds sysctl_tcp_wmem[0]) isn't landing the socket in the TCP memory-pressure path in our test environment, but instead in the memcg hard-limit/OOM path, which the companion fix (clamping tcp_wmem_schedule()'s return value) does not need to handle the same way.

Could you take a look at why the test's preconditions (buffer sizes, cgroup memory limit, write() size) aren't reliably reproducing the negative-forward-alloc + EAGAIN scenario in our VM environment? It's possible the memory cgroup limit used by the test is too tight relative to the data pushed through write(), causing it to hit the generic memcg OOM path before/instead of the TCP memory-pressure check.

#4 lore raw

Re: [PATCH net v2 2/2] selftests: net: packetdrill: add test for negative sk_forward_alloc in tcp_wmem_schedule()

Quoted 11 lines · Jakub Kicinski
Quoted 5 lines · On Tue, 20 Oct 2026 16:38:35 +0000 Octavian Purdila wrote:

Add a packetdrill test that drives sk->sk_forward_alloc negative via tcp_collapse() on the receive queue while sk->sk_wmem_queued exceeds sysctl_tcp_wmem[0], and verifies that a subsequent non-blocking write() under TCP memory pressure fails with EAGAIN rather than returning a negative copy length from tcp_wmem_schedule() and failing with EFAULT.

This is failing in our CI, it doesn't need any packetdrill updates, right?

Hi Jakub,

Correct, no packetdrill updates are needed.

Quoted 17 lines

Here's the AI report about the failure:

The new packetdrill test tcp_wmem_schedule_negative_fwd_alloc.pkt is failing in our CI (both the regular and debug kernel configs, all three address-family sub-tests: ipv4, ipv6, ipv4-mapped-ipv6):

tcp_wmem_schedule_negative_fwd_alloc.pkt:105: runtime error in write call:
Expected result -1 but got 3680 with errno 22 (Invalid argument)

Instead of the non-blocking write() failing with EAGAIN as the test expects, it succeeds and returns 3680 bytes. The kernel log for the run also shows the test's memory cgroup repeatedly entering the OOM-killer path (try_charge_memcg() -> mem_cgroup_out_of_memory(), "Out of memory and no killable processes...") from inside tcp_wmem_schedule(), rather than the write() being throttled and returning -EAGAIN as intended.

Quoted 7 lines

This suggests the test's reproduction recipe (tcp_collapse() driving sk_forward_alloc negative while sk_wmem_queued exceeds sysctl_tcp_wmem[0]) isn't landing the socket in the TCP memory-pressure path in our test environment, but instead in the memcg hard-limit/OOM path, which the companion fix (clamping tcp_wmem_schedule()'s return value) does not need to handle the same way.

Thanks for the report!

Quoted 6 lines

Could you take a look at why the test's preconditions (buffer sizes, cgroup memory limit, write() size) aren't reliably reproducing the negative-forward-alloc + EAGAIN scenario in our VM environment? It's possible the memory cgroup limit used by the test is too tight relative to the data pushed through write(), causing it to hit the generic memcg OOM path before/instead of the TCP memory-pressure check.

Ah, looks like my local .config was the issue (CONFIG_MAX_SKB_FRAGS=45). With the netdev CI .config I got the same error and OOM as you are seeing. I'll fix the script in v3 to work with both 45 and 17 skb frags.

#5 lore raw

Re: [PATCH net v2 2/2] selftests: net: packetdrill: add test for negative sk_forward_alloc in tcp_wmem_schedule()

In reply to Octavian Purdila
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 2

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [Medium] In tools/testing/selftests/net/packetdrill/tcp_wmem_schedule_n egative_fwd_alloc.pkt, the new test reports FAIL instead of SKIP when…
- [Low] The packetdrill config fragment (tools/testing/selftests/net/packetdrill/config line 4) adds…
- [Low] The init command writes echo +memory > "${cgroot}/cgroup.subtree_control" (line 17) on the root of the…

--

selftests: net: packetdrill: add test for negative sk_forward_alloc in tcp_wmem_schedule()

This patch adds a packetdrill test. The test drives sk->sk_forward_alloc negative through tcp_collapse() while sk_wmem_queued is above tcp_wmem[0]. It then checks that a non-blocking write() under memcg pressure fails with EAGAIN, not EFAULT. The runner can now also skip any test whose REQUIRES_PAGESIZE does not match the host.

tools/testing/selftests/net/packetdrill/config line 4

Quoted 9 lines
tools/testing/selftests/net/packetdrill/config +1 -0
index b7df8bf309200..dc3cd72a8da8c 100644
@@ -1,6 +1,7 @@
 CONFIG_HZ=1000
 CONFIG_HZ_1000=y
 CONFIG_IPV6=y
+CONFIG_MEMCG=y

[Severity: Low]
Should this fragment also add CONFIG_CGROUPS=y?

In init/Kconfig, config MEMCG sits inside the "if CGROUPS" block, and menuconfig CGROUPS has no default. If this fragment is merged onto a base config with CGROUPS=n, merge_config only prints a warning and MEMCG stays off.

In that case the new test fails in its init command and never gets to run. For comparison, tools/testing/selftests/cgroup/config lists CONFIG_CGROUPS=y next to CONFIG_MEMCG=y.

Quoted 3 lines
tools/testing/selftests/net/packetdrill/config +0 -0
 CONFIG_NET_NS=y
 CONFIG_NET_SCH_FIFO=y
 CONFIG_NET_SCH_FQ=y

[ ... ]

Quoted 6 lines
tools/testing/selftests/net/packetdrill/tcp_wmem_schedule_negative_fwd_alloc.pkt new file +0 -0
new file mode 100644
index 0000000000000..96a5d60a52cb1
@@ -0,0 +1,117 @@

[ ... ]

tools/testing/selftests/net/packetdrill/tcp_wmem_schedule_negative_fwd_alloc.pkt line 17

Quoted 8 lines

+`set -e
+./defaults.sh

tools/testing/selftests/net/packetdrill/tcp_wmem_schedule_negative_fwd_alloc.pkt new file +6 -0
+ip link set dev tun0 mtu 65535
+sysctl -q net.ipv4.tcp_rmem="4096 131072 6291456"
+sysctl -q net.ipv4.tcp_wmem="4096 16384 4194304"
+cgroot=$(mount -t cgroup2 | head -1 | awk '{print $3}')
+[ -n "$cgroot" ]
+echo +memory > "${cgroot}/cgroup.subtree_control"

[Severity: Medium]
Will this give a failure instead of a skip when cgroup v2 or the memory controller can't be used?

The init command runs under set -e. It aborts, and packetdrill exits non-zero, in any of these cases:

- there is no cgroup2 mount
- on hybrid v1/v2 hosts, the first cgroup2 mount is the controller-less /sys/fs/cgroup/unified
- the kernel was booted with cgroup_disable=memory
- the cgroupfs is read-only or delegated inside a container
- the cgroup namespace root already holds processes (EBUSY)

ksft_runner.sh only looks at packetdrill's exit status:

	unshare -n packetdrill ${ip_args[$ip_version]} ${optargs[@]} $script > /dev/null \
		&& ktap_test_pass $ip_version || $failfunc $ip_version

So any of these cases gives three FAIL results, one for each default IP version.

The same patch adds a skip gate for REQUIRES_PAGESIZE. The cleanup command already handles a missing mount with:

  [ -n "$cgroot" ] || exit 0

There is no equivalent check for the cgroup prerequisite, though. Documentation/dev-tools/kselftest.rst says a test should not make the top-level "make run_tests" fail when its feature is unconfigured.

This is also the first .pkt in this directory to use cgroups, so none of the other packetdrill tests had this requirement before.

Could the runner or the test detect this case and skip instead?

Quoted 3 lines
tools/testing/selftests/net/packetdrill/tcp_wmem_schedule_negative_fwd_alloc.pkt new file +3 -0
+mkdir -p "${cgroot}/pkt_${PPID}"
+echo $PPID > "${cgroot}/pkt_${PPID}/cgroup.procs"
+`

[ ... ]

tools/testing/selftests/net/packetdrill/tcp_wmem_schedule_negative_fwd_alloc.pkt line 117

Quoted 8 lines
tools/testing/selftests/net/packetdrill/tcp_wmem_schedule_negative_fwd_alloc.pkt new file +8 -0
+// Untimed cleanup command executed by packetdrill on both pass and early failure.
+`cgroot=$(mount -t cgroup2 | head -1 | awk '{print $3}')
+[ -n "$cgroot" ] || exit 0
+runner_pid=$(awk '/^PPid:/ {print $2}' /proc/$PPID/status)
+orig_cg=$(sed -n 's/^0:://p' /proc/$runner_pid/cgroup)
+echo $PPID > "${cgroot}${orig_cg}/cgroup.procs" 2>/dev/null || true
+echo $$ > "${cgroot}${orig_cg}/cgroup.procs" 2>/dev/null || true
+rmdir "${cgroot}/pkt_${PPID}"`

[Severity: Low]
Does this leave the memory controller enabled in the host's root cgroup.subtree_control?

The init command does:

  echo +memory > "${cgroot}/cgroup.subtree_control"

ksft_runner.sh runs the test under "unshare -n" only. That creates a new network namespace, but not a new cgroup or mount namespace, so cgroot points at the host's real cgroup2 root.

The tcp_rmem and tcp_wmem sysctls are per-netns and go away with the netns. The subtree_control change applies to the whole host.

The cleanup moves the processes back and removes pkt_${PPID}. It never writes -memory or restores the earlier state.

On systems where memory was not already enabled at the root, such as minimal virtme-ng or CI VMs without systemd, memcg would stay enabled for all child cgroups after the test exits.

Should the previous subtree_control state be saved and restored here?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261020163835.4076594-1-tavip%40google.com