* [PATCH net v2 0/2] kcm: bound message memory by send buffer
@ 2026-12-01 6:37 Zihan Xi
2026-12-01 6:38 ` [PATCH net v2 1/2] net: kcm: account retained message memory Zihan Xi
2026-12-01 6:38 ` [PATCH net v2 2/2] net: kcm: document transmit memory budget Zihan Xi
0 siblings, 2 replies; 5+ messages in thread
From: Zihan Xi @ 2026-12-01 6:37 UTC (permalink / raw)
To: netdev, linux-doc
Cc: davem, edumazet, pabeni, willemb, horms, rjethwani, zirajs7,
leitao, brauner, jiayuan.chen, runyu.xiao, tom, corbet, skhan,
rdunlap, vega, zihanx
Hi Linux kernel maintainers,
We found that AF_KCM message construction in net/kcm/kcmsock.c can
under-account memory retained by fragmented messages. A non-root process
can reach it without a TCP attachment or BPF program. The final v2 source
built successfully, and targeted tests completed under KVM; results follow.
An LLM was used to help create this patch.
This bug is tracked at: https://bugtracker.nebusec.ai/f/12034 (12034)
Bug details:
kcm_sendmsg() accounts message data, but fragmented messages also retain
page backing and skb metadata. Small fragments can therefore make a socket
retain more memory than the message-data charge accounts for.
The patch charges retained folios and skb metadata to the per-socket send
budget and releases the charge when messages are sent or discarded. It
also handles SO_SNDBUF changes while a message is open, rechecks space
after pushing queued messages, and lets splice coalesce at the skb fragment
limit before allocating another skb.
Page backing is charged conservatively by folio size, even when fragments
may share a folio. A message can consequently hit EMSGSIZE before its
payload alone reaches SO_SNDBUF. This is per-socket accounting; it does not
add KCM-wide aggregate or memcg accounting.
Reproducer:
Run the PoC as guest `test_user` (UID 1001) in the default user and network
namespaces, on an unpatched baseline and on the final v2 kernel. On the
unpatched baseline, with requested SO_SNDBUF=4096 (effective 8192), the
64 MiB DGRAM send succeeded; the following one-byte send returned EAGAIN.
On the final v2 kernel, both sends returned EMSGSIZE. No KASAN, BUG, Oops,
or kernel panic messages were found in the post-test dmesg.
In a 2-vCPU, 2-GB x86 QEMU guest with CONFIG_AF_KCM enabled, save the
inline PoC as `/tmp/kcm-mini-poc.c`. From a root shell, switch to
`test_user` (UID 1001):
```
su -s /bin/sh test_user
```
Then, in the `test_user` shell, compile and run:
```
cd /tmp
id -u
gcc -O2 -Wall -Wextra -o kcm-mini-poc kcm-mini-poc.c
./kcm-mini-poc
```
`id -u` should print `1001`.
Unpatched-baseline output:
```
requested_sndbuf=4096 actual_sndbuf=8192 payload=67108864 first_send=67108864
second_send=-1 (Resource temporarily unavailable)
```
Final v2 output:
```
requested_sndbuf=4096 actual_sndbuf=8192 payload=67108864 first_send=-1 (Message too long)
second_send=-1 (Message too long)
```
The same PoC was also run on the final source with larger requested
SO_SNDBUF values. At 8192 and 16384, both sends returned EMSGSIZE. At
32768 (effective 65536), the 64 MiB send returned EMSGSIZE and the one-byte
follow-up succeeded. Follow-up results varied across the tested buffer
values; these observations do not establish the underlying mechanism. The
4096-byte run did not have a successful follow-up. Results:
```
requested actual first send follow-up
4096 8192 EMSGSIZE EMSGSIZE
8192 16384 EMSGSIZE EMSGSIZE
16384 32768 EMSGSIZE EMSGSIZE
32768 65536 EMSGSIZE 1
```
The matrix ran as UID 1001 on the final source kernel under KVM. In a
`test_user` shell, compile the parameterized source and run these requested
buffer sizes:
```
gcc -O2 -Wall -Wextra -o kcm-mini-poc-sndbuf kcm-mini-poc-sndbuf.c
for sndbuf in 4096 8192 16384 32768; do
./kcm-mini-poc-sndbuf "$sndbuf"
done
```
The parameterized source is included below.
------BEGIN kcm-mini-poc-sndbuf.c------
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <unistd.h>
#ifndef AF_KCM
#define AF_KCM 41
#endif
#ifndef KCMPROTO_CONNECTED
#define KCMPROTO_CONNECTED 0
#endif
int main(int argc, char **argv)
{
const size_t size = 64 * 1024 * 1024;
int sndbuf = argc > 1 ? atoi(argv[1]) : 4096;
int actual, fd;
char byte = 'x';
char *buf;
ssize_t sent;
fd = socket(AF_KCM, SOCK_DGRAM, KCMPROTO_CONNECTED);
if (fd < 0) {
perror("socket(AF_KCM)");
return 1;
}
if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf))) {
perror("setsockopt(SO_SNDBUF)");
return 1;
}
if (getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &actual,
&(socklen_t){ sizeof(actual) })) {
perror("getsockopt(SO_SNDBUF)");
return 1;
}
buf = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (buf == MAP_FAILED) {
perror("mmap");
return 1;
}
memset(buf, 'x', size);
sent = send(fd, buf, size, MSG_DONTWAIT);
printf("requested_sndbuf=%d actual_sndbuf=%d payload=%zu first_send=%zd",
sndbuf, actual, size, sent);
if (sent < 0)
printf(" (%s)", strerror(errno));
putchar('\n');
errno = 0;
sent = send(fd, &byte, sizeof(byte), MSG_DONTWAIT);
printf("second_send=%zd", sent);
if (sent < 0)
printf(" (%s)", strerror(errno));
putchar('\n');
close(fd);
munmap(buf, size);
return 0;
}
------END kcm-mini-poc-sndbuf.c------
------BEGIN PoC------
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <unistd.h>
#ifndef AF_KCM
#define AF_KCM 41
#endif
#ifndef KCMPROTO_CONNECTED
#define KCMPROTO_CONNECTED 0
#endif
int main(void)
{
const size_t size = 64 * 1024 * 1024;
int sndbuf = 4096, actual, fd;
char byte = 'x';
char *buf;
ssize_t sent;
fd = socket(AF_KCM, SOCK_DGRAM, KCMPROTO_CONNECTED);
if (fd < 0) {
perror("socket(AF_KCM)");
return 1;
}
if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf))) {
perror("setsockopt(SO_SNDBUF)");
return 1;
}
if (getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &actual,
&(socklen_t){ sizeof(actual) })) {
perror("getsockopt(SO_SNDBUF)");
return 1;
}
buf = mmap(NULL, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (buf == MAP_FAILED) {
perror("mmap");
return 1;
}
memset(buf, 'x', size);
sent = send(fd, buf, size, MSG_DONTWAIT);
printf("requested_sndbuf=%d actual_sndbuf=%d payload=%zu first_send=%zd",
sndbuf, actual, size, sent);
if (sent < 0)
printf(" (%s)", strerror(errno));
putchar('\n');
errno = 0;
sent = send(fd, &byte, sizeof(byte), MSG_DONTWAIT);
printf("second_send=%zd", sent);
if (sent < 0)
printf(" (%s)", strerror(errno));
putchar('\n');
close(fd);
munmap(buf, size);
return 0;
}
------END PoC--------
Additional test results:
The final v2 source passed a full bzImage build and was tested under KVM in
a 2-vCPU, 2-GB guest. For the splice-boundary sweep, root set
`net.core.max_skb_frags=1`; the probe ran as UID 1001. It vmspliced two
adjacent bytes from one page into a pipe, then issued two one-byte KCM
DGRAM splice calls, with `SPLICE_F_MORE` on the first. Requested
SO_SNDBUF values from 2200 through 3200 were tested in steps of 8. At
2528, the first splice returned 1 and the second returned EMSGSIZE. At
2536 and above, both returned 1. Representative output:
```
sndbuf_request=2528 first=1 first_errno=0 second=-1 second_errno=90
sndbuf_request=2536 first=1 first_errno=0 second=1 second_errno=0
sndbuf_request=3200 first=1 first_errno=0 second=1 second_errno=0
```
A focused before/after comparison used the same single-shot binary and
configuration on pre-coalescing source commit `3e6450cdf004` and final KCM
code commit `c3949ece3d30`. Both builds used config SHA-256
`8c874562f1ce0eb8a79c2c8304c8cbec798f02d73e6ebe3da6d7d9bb35505011`;
root set `max_skb_frags=1`, and the probe ran as UID 1001. At requested
SO_SNDBUF 2672, the first splice returned 1 on both kernels. The second
returned EMSGSIZE before the fix and 1 on the final source:
```
pre_fix: first=1 errno=0 (ok); second=-1 errno=90 (Message too long)
final: first=1 errno=0 (ok); second=1 errno=0 (ok)
```
The probe source was compiled once and run on both kernels. The sweep and
focused comparison sources are included below. Neither post-test dmesg
contained KASAN, BUG, Oops, or kernel-panic messages. These return-value
tests did not generate a crash.
Sweep probe setup: set this guest-only sysctl as root:
```
echo 1 > /proc/sys/net/core/max_skb_frags
```
Then switch to `test_user` and run:
```
su -s /bin/sh test_user
```
In that shell:
```
gcc -static -O2 -Wall -Wextra -o coalesce-boundary-poc-unprivileged \
coalesce-boundary-poc-unprivileged.c
./coalesce-boundary-poc-unprivileged
```
Focused comparison probe: after setting the same sysctl as root, switch to
`test_user` and compile once in each guest:
```
su -s /bin/sh test_user
```
In that shell, compile and run on each guest:
```
gcc -static -O2 -Wall -Wextra -o coalesce-boundary-single \
coalesce-boundary-single.c
./coalesce-boundary-single
```
------BEGIN coalesce-boundary-poc-unprivileged.c------
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <linux/kcm.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <unistd.h>
#ifndef AF_KCM
#define AF_KCM 41
#endif
#ifndef KCMPROTO_CONNECTED
#define KCMPROTO_CONNECTED 0
#endif
static void try_budget(char *page, int sndbuf)
{
struct iovec iov = { .iov_base = page, .iov_len = 2 };
int p[2] = { -1, -1 }, fd = -1;
ssize_t vm, first = -1, second = -1;
int first_errno = 0, second_errno = 0;
if (pipe(p))
goto out;
vm = vmsplice(p[1], &iov, 1, 0);
if (vm != 2)
goto out;
fd = socket(AF_KCM, SOCK_DGRAM, KCMPROTO_CONNECTED);
if (fd < 0 || setsockopt(fd, SOL_SOCKET, SO_SNDBUF,
&sndbuf, sizeof(sndbuf)))
goto out;
errno = 0;
first = splice(p[0], NULL, fd, NULL, 1, SPLICE_F_MORE);
first_errno = errno;
if (first == 1) {
errno = 0;
second = splice(p[0], NULL, fd, NULL, 1, 0);
second_errno = errno;
}
printf("sndbuf_request=%d first=%zd first_errno=%d second=%zd second_errno=%d\n",
sndbuf, first, first_errno, second, second_errno);
out:
if (fd >= 0)
close(fd);
if (p[0] >= 0)
close(p[0]);
if (p[1] >= 0)
close(p[1]);
}
int main(void)
{
char *page = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
int sndbuf;
if (page == MAP_FAILED) {
perror("mmap");
return 1;
}
memset(page, 0x5a, 4096);
for (sndbuf = 2200; sndbuf <= 3200; sndbuf += 8)
try_budget(page, sndbuf);
munmap(page, 4096);
return 0;
}
------END coalesce-boundary-poc-unprivileged.c------
------BEGIN coalesce-boundary-single.c------
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <linux/kcm.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <unistd.h>
#ifndef AF_KCM
#define AF_KCM 41
#endif
#ifndef KCMPROTO_CONNECTED
#define KCMPROTO_CONNECTED 0
#endif
int main(void)
{
char *page = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
struct iovec iov;
int p[2], fd, sndbuf = 2672;
ssize_t n, first, second;
int first_errno, second_errno;
if (page == MAP_FAILED || pipe(p))
return 1;
memset(page, 0x5a, 4096);
iov.iov_base = page;
iov.iov_len = 2;
n = vmsplice(p[1], &iov, 1, 0);
if (n != 2)
return 2;
fd = socket(AF_KCM, SOCK_DGRAM, KCMPROTO_CONNECTED);
if (fd < 0 || setsockopt(fd, SOL_SOCKET, SO_SNDBUF,
&sndbuf, sizeof(sndbuf)))
return 3;
errno = 0;
first = splice(p[0], NULL, fd, NULL, 1, SPLICE_F_MORE);
first_errno = errno;
printf("first=%zd errno=%d (%s)\n", first, first_errno,
first < 0 ? strerror(first_errno) : "ok");
fflush(stdout);
if (first == 1) {
errno = 0;
second = splice(p[0], NULL, fd, NULL, 1, 0);
second_errno = errno;
printf("second=%zd errno=%d (%s)\n", second, second_errno,
second < 0 ? strerror(second_errno) : "ok");
}
close(fd);
close(p[0]);
close(p[1]);
return 0;
}
------END coalesce-boundary-single.c------
Changes in v2:
Link: https://lore.kernel.org/all/cover.1795676623.git.zihanx@nebusec.ai/
- Account retained folio backing and skb metadata in addition to
message data, and pair the ledger across send, rollback, and close.
- Use head->len for payload length, handle SO_SNDBUF shrink and
recheck space after kcm_push().
- Let splice coalesce at the frag limit before allocating a child skb.
- Document the transmit-side SO_SNDBUF budget and EMSGSIZE behavior.
Best regards,
Zihan Xi
Zihan Xi (2):
net: kcm: account retained message memory
net: kcm: document transmit memory budget
Documentation/networking/kcm.rst | 8 +
include/net/kcm.h | 3 +
net/kcm/kcmsock.c | 494 +++++++++++++++++++++++++++----
3 files changed, 453 insertions(+), 52 deletions(-)
base-commit: e9e45fcb6d39bee9325e6a7dca72bd14e82760f3
--
2.43.0
^ permalink raw reply [flat|nested] 5+ messages in thread* [PATCH net v2 1/2] net: kcm: account retained message memory
2026-12-01 6:37 [PATCH net v2 0/2] kcm: bound message memory by send buffer Zihan Xi
@ 2026-12-01 6:38 ` Zihan Xi
2026-12-05 3:39 ` netdev-bot+sashiko
2026-12-01 6:38 ` [PATCH net v2 2/2] net: kcm: document transmit memory budget Zihan Xi
1 sibling, 1 reply; 5+ messages in thread
From: Zihan Xi @ 2026-12-01 6:38 UTC (permalink / raw)
To: netdev, linux-doc
Cc: davem, edumazet, pabeni, willemb, horms, rjethwani, zirajs7,
leitao, brauner, jiayuan.chen, runyu.xiao, tom, corbet, skhan,
rdunlap, vega, zihanx
kcm_sendmsg() charges copied payload bytes, but fragmented messages
also retain page backing and skb metadata. A message made from small
fragments can therefore consume substantially more memory than its
payload charge while staying within sk_sndbuf.
Charge each retained folio and skb to the per-socket write-memory
budget, and release the message charge when it is sent or discarded.
Recheck space after pushing queued messages and preserve pending
message semantics when sk_sndbuf changes. Let splice coalesce with a
full skb fragment array before charging a new skb.
Fixes: ab7ac4eb9832 ("kcm: Kernel Connection Multiplexor module")
Cc: stable@vger.kernel.org
Reported-by: Vega <vega@nebusec.ai>
Link: https://bugtracker.nebusec.ai/f/12034
Signed-off-by: Zihan Xi <zihanx@nebusec.ai>
---
include/net/kcm.h | 3 +
net/kcm/kcmsock.c | 494 +++++++++++++++++++++++++++++++++++++++++-----
2 files changed, 445 insertions(+), 52 deletions(-)
diff --git a/include/net/kcm.h b/include/net/kcm.h
index d9c35e71ecea..3f34a117426f 100644
--- a/include/net/kcm.h
+++ b/include/net/kcm.h
@@ -49,6 +49,9 @@ struct kcm_tx_msg {
unsigned int sent;
unsigned int frag_offset;
unsigned int msg_flags;
+ unsigned int sndbuf;
+ /* Payload, skb metadata and conservative page backing charge. */
+ int wmem_charge;
bool started_tx;
struct sk_buff *frag_skb;
struct sk_buff *last_skb;
diff --git a/net/kcm/kcmsock.c b/net/kcm/kcmsock.c
index ca789812124e..d97db8adb31d 100644
--- a/net/kcm/kcmsock.c
+++ b/net/kcm/kcmsock.c
@@ -13,10 +13,12 @@
#include <linux/filter.h>
#include <linux/in.h>
#include <linux/kernel.h>
+#include <linux/mm.h>
#include <linux/module.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/poll.h>
+#include <linux/random.h>
#include <linux/rculist.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
@@ -28,6 +30,7 @@
#include <linux/uio.h>
#include <net/kcm.h>
+#include <net/hotdata.h>
#include <net/netns/generic.h>
#include <net/sock.h>
#include <net/tcp.h>
@@ -50,6 +53,129 @@ static inline struct kcm_tx_msg *kcm_tx_msg(struct sk_buff *skb)
return (struct kcm_tx_msg *)skb->cb;
}
+static bool kcm_wmem_charge(struct sock *sk, struct kcm_tx_msg *txm,
+ int charge)
+{
+ if (charge > sk_stream_wspace(sk) ||
+ txm->wmem_charge > txm->sndbuf ||
+ charge > txm->sndbuf - txm->wmem_charge ||
+ !sk_wmem_schedule(sk, charge))
+ return false;
+
+ sk_wmem_queued_add(sk, charge);
+ sk_mem_charge(sk, charge);
+ txm->wmem_charge += charge;
+ return true;
+}
+
+static void kcm_wmem_uncharge(struct sock *sk, struct kcm_tx_msg *txm,
+ int charge)
+{
+ sk_wmem_queued_add(sk, -charge);
+ sk_mem_uncharge(sk, charge);
+ txm->wmem_charge -= charge;
+}
+
+static void kcm_wmem_uncharge_msg(struct sock *sk, struct sk_buff *head)
+{
+ struct kcm_tx_msg *txm = kcm_tx_msg(head);
+
+ kcm_wmem_uncharge(sk, txm, txm->wmem_charge);
+}
+
+static bool kcm_alloc_frag_skb(struct sock *sk, struct sk_buff *head,
+ struct sk_buff **skb,
+ struct sk_buff **frag_prev)
+{
+ struct sk_buff *tskb;
+
+ tskb = alloc_skb(0, sk->sk_allocation);
+ if (!tskb)
+ return false;
+ if (!kcm_wmem_charge(sk, kcm_tx_msg(head), tskb->truesize)) {
+ kfree_skb(tskb);
+ return false;
+ }
+
+ if (head == *skb)
+ skb_shinfo(head)->frag_list = tskb;
+ else
+ (*skb)->next = tskb;
+
+ *frag_prev = *skb;
+ *skb = tskb;
+ tskb->ip_summed = CHECKSUM_UNNECESSARY;
+
+ return true;
+}
+
+static ssize_t kcm_splice_from_iter(struct sock *sk, struct kcm_tx_msg *txm,
+ struct sk_buff *skb,
+ struct iov_iter *iter, size_t maxsize,
+ size_t *min_space)
+{
+ struct page *page, **pages = &page;
+ unsigned int frag_limit = READ_ONCE(net_hotdata.sysctl_max_skb_frags);
+ bool pin = iov_iter_extract_will_pin(iter);
+ size_t off, charge, part;
+ ssize_t len;
+ int i, err;
+
+ len = iov_iter_extract_pages(iter, &pages, maxsize, 1, 0, &off);
+ if (len <= 0)
+ return len ?: -EIO;
+
+ if (WARN_ON_ONCE(!sendpage_ok(page))) {
+ err = -EIO;
+ goto revert;
+ }
+
+ part = min_t(size_t, PAGE_SIZE - off, len);
+ i = skb_shinfo(skb)->nr_frags;
+ charge = part;
+ if (!skb_can_coalesce(skb, i, page, off)) {
+ if (i >= frag_limit) {
+ err = -E2BIG;
+ goto revert;
+ }
+ charge = folio_size(page_folio(page));
+ }
+
+ if (txm->wmem_charge > txm->sndbuf ||
+ charge > txm->sndbuf - txm->wmem_charge) {
+ err = -EMSGSIZE;
+ goto revert;
+ }
+ if (charge > sk_stream_wspace(sk)) {
+ *min_space = charge;
+ err = -EAGAIN;
+ goto revert;
+ }
+ if (!kcm_wmem_charge(sk, txm, charge)) {
+ err = -ENOMEM;
+ goto revert;
+ }
+
+ err = skb_append_pagefrags(skb, page, off, part, frag_limit);
+ if (err < 0) {
+ kcm_wmem_uncharge(sk, txm, charge);
+ if (err == -EMSGSIZE)
+ err = -E2BIG;
+ goto revert;
+ }
+
+ skb_len_add(skb, part);
+ if (pin)
+ unpin_user_page(page);
+ return part;
+
+revert:
+ if (pin)
+ unpin_user_page(page);
+ iov_iter_revert(iter, len);
+ return err;
+}
+
static void report_csk_error(struct sock *csk, int err)
{
csk->sk_err = EPIPE;
@@ -694,7 +820,7 @@ static int kcm_write_msgs(struct kcm_sock *kcm)
}
/* Successfully sent the whole packet, account for it. */
- sk->sk_wmem_queued -= txm->sent;
+ kcm_wmem_uncharge_msg(sk, head);
total_sent += txm->sent;
skb_dequeue(&sk->sk_write_queue);
kfree_skb(head);
@@ -750,12 +876,94 @@ static void kcm_push(struct kcm_sock *kcm)
kcm_write_msgs(kcm);
}
+/* Wait for space without sleeping forever if sndbuf shrinks below head. */
+static int kcm_wait_memory(struct sock *sk, long *timeo_p,
+ struct sk_buff *head)
+{
+ int ret, err = 0;
+ long vm_wait = 0;
+ long current_timeo = *timeo_p;
+ DEFINE_WAIT_FUNC(wait, woken_wake_function);
+
+ if (!head || !kcm_tx_msg(head)->wmem_charge)
+ return sk_stream_wait_memory(sk, timeo_p);
+
+ if (sk_stream_memory_free(sk)) {
+ current_timeo = get_random_u32_below(HZ / 5) + 2;
+ vm_wait = current_timeo;
+ }
+
+ add_wait_queue(sk_sleep(sk), &wait);
+ while (1) {
+ sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
+
+ if (READ_ONCE(sk->sk_err) || (sk->sk_shutdown & SEND_SHUTDOWN))
+ goto do_error;
+ if (!*timeo_p)
+ goto do_eagain;
+ if (signal_pending(current))
+ goto do_interrupted;
+ sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
+ if (sk_stream_memory_free(sk) && !vm_wait)
+ break;
+ if (kcm_tx_msg(head)->wmem_charge >= READ_ONCE(sk->sk_sndbuf)) {
+ err = -EMSGSIZE;
+ break;
+ }
+
+ sk_set_nospace(sk);
+ sk->sk_write_pending++;
+ ret = sk_wait_event(sk, ¤t_timeo,
+ READ_ONCE(sk->sk_err) ||
+ (READ_ONCE(sk->sk_shutdown) & SEND_SHUTDOWN) ||
+ (sk_stream_memory_free(sk) && !vm_wait) ||
+ kcm_tx_msg(head)->wmem_charge >=
+ READ_ONCE(sk->sk_sndbuf),
+ &wait);
+ sk->sk_write_pending--;
+ if (ret < 0 || sock_flag(sk, SOCK_DEAD))
+ goto do_error;
+ if (kcm_tx_msg(head)->wmem_charge >= READ_ONCE(sk->sk_sndbuf)) {
+ err = -EMSGSIZE;
+ break;
+ }
+
+ if (vm_wait) {
+ vm_wait -= current_timeo;
+ current_timeo = *timeo_p;
+ if (current_timeo != MAX_SCHEDULE_TIMEOUT) {
+ current_timeo -= vm_wait;
+ if (current_timeo < 0)
+ current_timeo = 0;
+ }
+ vm_wait = 0;
+ }
+ *timeo_p = current_timeo;
+ }
+ goto out;
+
+do_error:
+ err = -EPIPE;
+ goto out;
+do_eagain:
+ sk_set_nospace(sk);
+ err = -EAGAIN;
+ goto out;
+do_interrupted:
+ err = sock_intr_errno(*timeo_p);
+out:
+ if (!sock_flag(sk, SOCK_DEAD))
+ remove_wait_queue(sk_sleep(sk), &wait);
+ return err;
+}
+
static int kcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct kcm_sock *kcm = kcm_sk(sk);
struct sk_buff *skb = NULL, *head = NULL, *frag_prev = NULL;
- size_t copy, copied = 0;
+ size_t copy, copied = 0, sndbuf, skb_charge;
+ int wmem_queued;
long timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
int eor = (sock->type == SOCK_DGRAM) ?
!(msg->msg_flags & MSG_MORE) : !!(msg->msg_flags & MSG_EOR);
@@ -767,38 +975,88 @@ static int kcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
/* Per tcp_sendmsg this should be in poll */
sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
- if (sk->sk_err)
- goto out_error;
-
if (kcm->seq_skb) {
/* Previously opened message */
head = kcm->seq_skb;
skb = kcm_tx_msg(head)->last_skb;
- goto start;
+ sndbuf = kcm_tx_msg(head)->sndbuf;
}
- /* Call the sk_stream functions to manage the sndbuf mem. */
- if (!sk_stream_memory_free(sk)) {
- kcm_push(kcm);
- sk_set_nospace(sk);
- err = sk_stream_wait_memory(sk, &timeo);
- if (err)
+ if (sk->sk_err)
+ goto out_error;
+
+ if (head) {
+ struct kcm_tx_msg *txm = kcm_tx_msg(head);
+
+ /* Do not let a message grow beyond its original sndbuf limit. */
+ if (msg_data_left(msg) &&
+ (txm->wmem_charge > sndbuf ||
+ msg_data_left(msg) > sndbuf - txm->wmem_charge)) {
+ err = -EMSGSIZE;
goto out_error;
+ }
+ goto start;
+ }
+
+ sndbuf = READ_ONCE(sk->sk_sndbuf);
+ skb_charge = SKB_TRUESIZE(0);
+ /* Account for the head skb before admitting the message payload. */
+ if (msg_data_left(msg) &&
+ (msg_data_left(msg) > sndbuf ||
+ skb_charge > sndbuf - msg_data_left(msg))) {
+ err = -EMSGSIZE;
+ goto out_error;
}
if (msg_data_left(msg)) {
+ while (skb_charge > sk_stream_wspace(sk)) {
+ kcm_push(kcm);
+ if (skb_charge <= sk_stream_wspace(sk))
+ break;
+ sk_set_nospace(sk);
+ err = sk_stream_wait_memory(sk, &timeo);
+ if (err)
+ goto out_error;
+
+ sndbuf = READ_ONCE(sk->sk_sndbuf);
+ if (msg_data_left(msg) > sndbuf ||
+ skb_charge > sndbuf - msg_data_left(msg)) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+ }
+
/* New message, alloc head skb */
head = alloc_skb(0, sk->sk_allocation);
while (!head) {
+ wmem_queued = READ_ONCE(sk->sk_wmem_queued);
kcm_push(kcm);
+ if (wmem_queued > READ_ONCE(sk->sk_wmem_queued)) {
+ head = alloc_skb(0, sk->sk_allocation);
+ continue;
+ }
err = sk_stream_wait_memory(sk, &timeo);
if (err)
goto out_error;
+ sndbuf = READ_ONCE(sk->sk_sndbuf);
+ if (msg_data_left(msg) > sndbuf ||
+ skb_charge > sndbuf - msg_data_left(msg)) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
head = alloc_skb(0, sk->sk_allocation);
}
skb = head;
+ kcm_tx_msg(head)->sndbuf = sndbuf;
+ kcm_tx_msg(head)->wmem_charge = 0;
+ if (!kcm_wmem_charge(sk, kcm_tx_msg(head), head->truesize)) {
+ kfree_skb(head);
+ head = NULL;
+ err = -ENOMEM;
+ goto out_error;
+ }
/* Set ip_summed to CHECKSUM_UNNECESSARY to avoid calling
* csum_and_copy_from_iter from skb_do_copy_data_nocache.
@@ -809,65 +1067,144 @@ static int kcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
start:
while (msg_data_left(msg)) {
bool merge = true;
+ bool splice = msg->msg_flags & MSG_SPLICE_PAGES;
int i = skb_shinfo(skb)->nr_frags;
- struct page_frag *pfrag = sk_page_frag(sk);
+ struct page_frag *pfrag = NULL;
+ struct kcm_tx_msg *txm = kcm_tx_msg(head);
+ int space, msg_space;
+ size_t min_space = 1;
+ unsigned int frag_limit = MAX_SKB_FRAGS;
- if (!sk_page_frag_refill(sk, pfrag))
- goto wait_for_memory;
+ if (txm->wmem_charge >= txm->sndbuf ||
+ txm->wmem_charge >= READ_ONCE(sk->sk_sndbuf)) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+ space = sk_stream_wspace(sk);
+ if (space <= 0)
+ goto wait_for_space;
+ msg_space = txm->sndbuf - txm->wmem_charge;
+
+ if (splice) {
+ frag_limit = READ_ONCE(net_hotdata.sysctl_max_skb_frags);
+ if (!frag_limit) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+ } else {
+ pfrag = sk_page_frag(sk);
- if (!skb_can_coalesce(skb, i, pfrag->page,
- pfrag->offset)) {
- if (i == MAX_SKB_FRAGS) {
- struct sk_buff *tskb;
+ if (!sk_page_frag_refill(sk, pfrag))
+ goto wait_for_memory;
- tskb = alloc_skb(0, sk->sk_allocation);
- if (!tskb)
- goto wait_for_memory;
+ /* Refill may have moderated sk_sndbuf. */
+ space = sk_stream_wspace(sk);
+ if (space <= 0)
+ goto wait_for_space;
+ if (txm->wmem_charge >= READ_ONCE(sk->sk_sndbuf)) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+ msg_space = txm->sndbuf - txm->wmem_charge;
+
+ merge = skb_can_coalesce(skb, i, pfrag->page,
+ pfrag->offset);
+ }
- if (head == skb)
- skb_shinfo(head)->frag_list = tskb;
- else
- skb->next = tskb;
+ if (!splice && !merge && i == MAX_SKB_FRAGS) {
+ size_t tskb_charge = SKB_TRUESIZE(0);
- frag_prev = skb;
- skb = tskb;
- skb->ip_summed = CHECKSUM_UNNECESSARY;
- continue;
+ if (kcm_tx_msg(head)->wmem_charge >
+ kcm_tx_msg(head)->sndbuf ||
+ tskb_charge > kcm_tx_msg(head)->sndbuf -
+ kcm_tx_msg(head)->wmem_charge) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+ if (tskb_charge > sk_stream_wspace(sk)) {
+ min_space = tskb_charge;
+ goto wait_for_space;
}
- merge = false;
- }
- if (msg->msg_flags & MSG_SPLICE_PAGES) {
- copy = msg_data_left(msg);
- if (!sk_wmem_schedule(sk, copy))
+ if (!kcm_alloc_frag_skb(sk, head, &skb, &frag_prev))
goto wait_for_memory;
+ continue;
+ }
- err = skb_splice_from_iter(skb, &msg->msg_iter, copy);
- if (err < 0) {
- if (err == -EMSGSIZE)
+ if (splice) {
+ size_t budget = min_t(size_t, space, msg_space);
+
+ copy = min(msg_data_left(msg), budget);
+ err = kcm_splice_from_iter(sk, txm, skb,
+ &msg->msg_iter, copy,
+ &min_space);
+ if (err == -E2BIG) {
+ size_t tskb_charge = SKB_TRUESIZE(0);
+
+ if (txm->wmem_charge > txm->sndbuf ||
+ tskb_charge > txm->sndbuf - txm->wmem_charge) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+ if (tskb_charge > sk_stream_wspace(sk)) {
+ min_space = tskb_charge;
+ goto wait_for_space;
+ }
+ if (!kcm_alloc_frag_skb(sk, head, &skb, &frag_prev))
goto wait_for_memory;
- goto out_error;
+ continue;
}
+ if (err == -EAGAIN)
+ goto wait_for_space;
+ if (err == -ENOMEM)
+ goto wait_for_memory;
+ if (err < 0)
+ goto out_error;
copy = err;
skb_shinfo(skb)->flags |= SKBFL_SHARED_FRAG;
- sk_wmem_queued_add(sk, copy);
- sk_mem_charge(sk, copy);
if (head != skb)
head->truesize += copy;
} else {
- copy = min_t(int, msg_data_left(msg),
+ size_t budget = min_t(size_t, space, msg_space);
+ size_t padding = 0;
+
+ copy = min_t(size_t, msg_data_left(msg),
pfrag->size - pfrag->offset);
- if (!sk_wmem_schedule(sk, copy))
+ copy = min_t(size_t, copy, budget);
+ if (!merge) {
+ if (pfrag->size > msg_space) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+ if (pfrag->size > space) {
+ min_space = pfrag->size;
+ goto wait_for_space;
+ }
+ copy = min_t(size_t, msg_data_left(msg),
+ pfrag->size - pfrag->offset);
+ padding = pfrag->size - copy;
+ if (padding &&
+ !kcm_wmem_charge(sk, txm, padding))
+ goto wait_for_memory;
+ }
+ if (!sk_wmem_schedule(sk, copy)) {
+ if (padding)
+ kcm_wmem_uncharge(sk, txm, padding);
goto wait_for_memory;
+ }
err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb,
pfrag->page,
pfrag->offset,
copy);
- if (err)
+ if (err) {
+ if (padding)
+ kcm_wmem_uncharge(sk, txm, padding);
goto out_error;
+ }
+ txm->wmem_charge += copy;
/* Update the skb. */
if (merge) {
@@ -890,9 +1227,48 @@ static int kcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
continue;
+wait_for_space:
+ kcm_push(kcm);
+ space = sk_stream_wspace(sk);
+ if (space > 0 && (size_t)space >= min_space)
+ goto start;
+ if (min_space > kcm_tx_msg(head)->sndbuf -
+ kcm_tx_msg(head)->wmem_charge) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+ if (head &&
+ READ_ONCE(sk->sk_wmem_queued) <=
+ kcm_tx_msg(head)->wmem_charge) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+
+ /* The unfinished message cannot make its own space available. */
+ if (head && msg_data_left(msg) &&
+ kcm_tx_msg(head)->wmem_charge >= READ_ONCE(sk->sk_sndbuf)) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+ err = kcm_wait_memory(sk, &timeo, head);
+ if (err)
+ goto out_error;
+ goto start;
+
wait_for_memory:
+ wmem_queued = READ_ONCE(sk->sk_wmem_queued);
kcm_push(kcm);
- err = sk_stream_wait_memory(sk, &timeo);
+ /* A synchronous push may have already restored write space. */
+ if (wmem_queued > READ_ONCE(sk->sk_wmem_queued))
+ goto start;
+
+ /* sndbuf can shrink while page-frag allocation moderates it. */
+ if (head && msg_data_left(msg) &&
+ kcm_tx_msg(head)->wmem_charge >= READ_ONCE(sk->sk_sndbuf)) {
+ err = -EMSGSIZE;
+ goto out_error;
+ }
+ err = kcm_wait_memory(sk, &timeo, head);
if (err)
goto out_error;
}
@@ -939,10 +1315,10 @@ static int kcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
out_error:
kcm_push(kcm);
- /* When MAX_SKB_FRAGS was reached, a new skb was allocated and
- * linked into the frag_list before data copy. If the copy
- * subsequently failed, this skb has zero frags. Remove it from
- * the frag_list to prevent kcm_write_msgs from later hitting
+ /* When the skb fragment limit was reached, a new skb was allocated
+ * and linked into the frag_list before copying or splicing data. If
+ * that operation failed, the skb has zero frags. Remove it from the
+ * frag_list to prevent kcm_write_msgs from later hitting
* WARN_ON(!skb_shinfo(skb)->nr_frags).
*/
if (frag_prev && !skb_shinfo(skb)->nr_frags) {
@@ -950,6 +1326,7 @@ static int kcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
skb_shinfo(head)->frag_list = NULL;
else
frag_prev->next = NULL;
+ kcm_wmem_uncharge(sk, kcm_tx_msg(head), skb->truesize);
kfree_skb(skb);
/* Update skb as it may be saved in partial_message via goto */
skb = frag_prev;
@@ -961,9 +1338,14 @@ static int kcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
*/
if (copied)
goto partial_message;
- if (head != kcm->seq_skb)
+ if (head != kcm->seq_skb) {
+ if (head)
+ kcm_wmem_uncharge_msg(sk, head);
kfree_skb(head);
+ }
} else {
+ if (head)
+ kcm_wmem_uncharge_msg(sk, head);
kfree_skb(head);
kcm->seq_skb = NULL;
}
@@ -1696,6 +2078,7 @@ static int kcm_release(struct socket *sock)
struct kcm_sock *kcm;
struct kcm_mux *mux;
struct kcm_psock *psock;
+ struct sk_buff *skb;
if (!sk)
return 0;
@@ -1705,13 +2088,20 @@ static int kcm_release(struct socket *sock)
lock_sock(sk);
sock_orphan(sk);
- kfree_skb(kcm->seq_skb);
+ if (kcm->seq_skb) {
+ kcm_wmem_uncharge_msg(sk, kcm->seq_skb);
+ kfree_skb(kcm->seq_skb);
+ kcm->seq_skb = NULL;
+ }
/* Purge queue under lock to avoid race condition with tx_work trying
* to act when queue is nonempty. If tx_work runs after this point
* it will just return.
*/
- __skb_queue_purge(&sk->sk_write_queue);
+ while ((skb = __skb_dequeue(&sk->sk_write_queue))) {
+ kcm_wmem_uncharge_msg(sk, skb);
+ kfree_skb(skb);
+ }
release_sock(sk);
--
2.43.0
^ permalink raw reply related [flat|nested] 5+ messages in thread* Re: [PATCH net v2 1/2] net: kcm: account retained message memory
2026-12-01 6:38 ` [PATCH net v2 1/2] net: kcm: account retained message memory Zihan Xi
@ 2026-12-05 3:39 ` netdev-bot+sashiko
0 siblings, 0 replies; 5+ messages in thread
From: netdev-bot+sashiko @ 2026-12-05 3:39 UTC (permalink / raw)
To: zihanx
Cc: netdev, linux-doc, davem, edumazet, pabeni, willemb, horms,
rjethwani, zirajs7, leitao, brauner, jiayuan.chen, runyu.xiao,
tom, corbet, skhan, rdunlap, vega, kuba
Thank you for your contribution! Sashiko AI review found 6 potential
issue(s) to consider.
Critical: 0 · High: 2 · Medium: 4 · Low: 0
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).
- [High] The non-splice path in kcm_sendmsg() (net/kcm/kcmsock.c) charges
every new page-frag fragment the whole pfrag->size: `padding =…
- [High] kcm_splice_from_iter() (net/kcm/kcmsock.c) sets `charge =
folio_size(page_folio(page))` for each page that does not coalesce.
- [Medium] The patch carries 'Cc: stable@vger.kernel.org' but is about
500 lines (445 insertions, 52 deletions).
- [Medium] kcm_sendmsg() checks for space using SKB_TRUESIZE(0), as
`skb_charge` for the head skb (line 1002) and `tskb_charge` for…
- [Medium] In kcm_sendmsg(), `skb_charge` is declared `size_t` (line
965).
- [Medium] net: kcm: missing min_space check in kcm_wait_memory() and
wait_for_space
--
net: kcm: account retained message memory
This commit makes kcm_sendmsg() charge per-message skb truesize and a
conservative page backing amount (a whole pfrag or a whole folio) to
sk_wmem_queued. The charge is tracked in kcm_tx_msg->wmem_charge and
released when the message is sent or discarded. It also adds the
kcm_splice_from_iter() and kcm_wait_memory() helpers, plus new -EMSGSIZE
exits when a message would grow past the sndbuf recorded for it.
Link: https://bugtracker.nebusec.ai/f/12034
> kcm_sendmsg() charges copied payload bytes, but fragmented messages
> also retain page backing and skb metadata. A message made from small
> fragments can therefore consume substantially more memory than its
> payload charge while staying within sk_sndbuf.
[ ... ]
> Cc: stable@vger.kernel.org
[Severity: Medium]
This is tagged for stable, but it is roughly 500 lines (445 insertions,
52 deletions). Documentation/process/stable-kernel-rules.rst says a stable
patch cannot be bigger than 100 lines with context, and must be obviously
correct.
The patch also makes several user-visible changes:
- it forks sk_stream_wait_memory() into kcm_wait_memory() with new
-EMSGSIZE exits
- it replaces skb_splice_from_iter() with kcm_splice_from_iter()
- it adds a per-message sndbuf cap
- it adds full pfrag and folio-size charging
Together these turn sends that used to succeed into -EMSGSIZE. The commit
message doesn't mention any of them.
The follow-up commit "net: kcm: document transmit memory budget" documents
the new EMSGSIZE semantics. It is not tagged for stable, so stable trees
would get the behaviour change without the documentation.
Is "while staying within sk_sndbuf" accurate for the old behaviour? Before
this patch, sk_stream_memory_free() was only checked before the head skb
was allocated. A single message's payload was never limited by
sk_sndbuf.
> diff --git a/net/kcm/kcmsock.c b/net/kcm/kcmsock.c
> index ca789812124e8..d97db8adb31d4 100644
> --- a/net/kcm/kcmsock.c
> +++ b/net/kcm/kcmsock.c
[ ... ]
> @@ -50,6 +53,129 @@ static inline struct kcm_tx_msg *kcm_tx_msg(struct sk_buff *skb)
[ ... ]
> +static ssize_t kcm_splice_from_iter(struct sock *sk, struct kcm_tx_msg *txm,
> + struct sk_buff *skb,
> + struct iov_iter *iter, size_t maxsize,
> + size_t *min_space)
> +{
[ ... ]
> + len = iov_iter_extract_pages(iter, &pages, maxsize, 1, 0, &off);
> + if (len <= 0)
> + return len ?: -EIO;
[ ... ]
> + part = min_t(size_t, PAGE_SIZE - off, len);
> + i = skb_shinfo(skb)->nr_frags;
> + charge = part;
> + if (!skb_can_coalesce(skb, i, page, off)) {
> + if (i >= frag_limit) {
> + err = -E2BIG;
> + goto revert;
> + }
> + charge = folio_size(page_folio(page));
> + }
> +
> + if (txm->wmem_charge > txm->sndbuf ||
> + charge > txm->sndbuf - txm->wmem_charge) {
> + err = -EMSGSIZE;
> + goto revert;
> + }
[Severity: High]
When the source is a large folio, is the whole folio charged once for
every page?
iov_iter_extract_pages() is called with maxpages=1, so each call returns
a single struct page. skb_can_coalesce() only merges when the frag uses
the same struct page and the offset is contiguous:
include/linux/skbuff.h:skb_can_coalesce_netmem() {
...
return netmem == skb_frag_netmem(frag) &&
off == skb_frag_off(frag) + skb_frag_size(frag);
}
So page N+1 of a large folio never coalesces with page N, and each 4K page
is charged folio_size(). A 64 KiB folio is then charged 16 * 64 KiB =
1 MiB for 64 KiB of data. With the default sndbuf, a spliced message
larger than about 12 KiB fails with -EMSGSIZE.
For a 2 MiB THP in the page cache (tmpfs huge=, XFS or ext4 large folios),
the first page alone exceeds any unprivileged sndbuf (wmem_max defaults to
212992):
sendfile()
splice_to_socket()
sock_sendmsg(MSG_SPLICE_PAGES)
kcm_sendmsg()
kcm_splice_from_iter()
charge = folio_size(page_folio(page));
-> -EMSGSIZE
Before this patch, these paths went through skb_splice_from_iter() and
succeeded.
[ ... ]
> @@ -750,12 +876,94 @@ static void kcm_push(struct kcm_sock *kcm)
[ ... ]
> static int kcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
> {
> struct sock *sk = sock->sk;
> struct kcm_sock *kcm = kcm_sk(sk);
> struct sk_buff *skb = NULL, *head = NULL, *frag_prev = NULL;
> - size_t copy, copied = 0;
> + size_t copy, copied = 0, sndbuf, skb_charge;
> + int wmem_queued;
[ ... ]
> + sndbuf = READ_ONCE(sk->sk_sndbuf);
> + skb_charge = SKB_TRUESIZE(0);
> + /* Account for the head skb before admitting the message payload. */
> + if (msg_data_left(msg) &&
> + (msg_data_left(msg) > sndbuf ||
> + skb_charge > sndbuf - msg_data_left(msg))) {
> + err = -EMSGSIZE;
> + goto out_error;
> }
>
> if (msg_data_left(msg)) {
> + while (skb_charge > sk_stream_wspace(sk)) {
> + kcm_push(kcm);
> + if (skb_charge <= sk_stream_wspace(sk))
> + break;
[Severity: Medium]
skb_charge is a size_t, but sk_stream_wspace() returns an int
(sk_sndbuf - sk_wmem_queued). That value goes negative when sk_sndbuf
drops below sk_wmem_queued. Two ways this can happen:
- setsockopt(SO_SNDBUF) lowers it while MSG_BATCH messages are queued
- sk_page_frag_refill() fails and sk_stream_moderate_sndbuf() shrinks it
Wouldn't the negative int be converted to a huge unsigned value here? That
would skip the wait loop exactly when there is no space.
kcm_wmem_charge() then does a signed comparison:
if (charge > sk_stream_wspace(sk) ||
That check fails, and the head charge below returns -ENOMEM. Blocking
callers get -ENOMEM instead of waiting, and non-blocking callers get
-ENOMEM instead of -EAGAIN. The old !sk_stream_memory_free() check pushed
and waited in this case.
[ ... ]
> skb = head;
> + kcm_tx_msg(head)->sndbuf = sndbuf;
> + kcm_tx_msg(head)->wmem_charge = 0;
> + if (!kcm_wmem_charge(sk, kcm_tx_msg(head), head->truesize)) {
> + kfree_skb(head);
> + head = NULL;
> + err = -ENOMEM;
> + goto out_error;
> + }
[Severity: Medium]
kcm_wait_memory() is not told how much space the caller needs.
wait_for_space is reached with min_space set to pfrag->size (32 KiB
on 4K page systems), to folio_size() from kcm_splice_from_iter(), or
to SKB_TRUESIZE(0) for a new frag_list skb. If sk_stream_wspace(sk)
is positive but below min_space, sk_stream_memory_free() is already
true on entry, so kcm_wait_memory() takes the vm_wait branch:
- it sleeps for a random 2..HZ/5+1 jiffies, or until the next wakeup
- it then sees sk_stream_memory_free() && !vm_wait and returns 0
Nothing checks that min_space bytes are actually free. kcm_sendmsg()
goes back to start, hits the same shortfall and lands in
wait_for_space again. With the default MAX_SCHEDULE_TIMEOUT the
timeout never decreases. A blocking sender therefore polls on a
timer instead of sleeping until enough space is released, and it
holds kcm->tx_mutex the whole time. The head skb loop has the same
pattern with sk_stream_wait_memory() when sk_stream_wspace(sk) is
positive but below skb_charge.
The sndbuf checks don't account for min_space either. wait_for_space
compares min_space against the txm->sndbuf snapshot. Both
wait_for_space and kcm_wait_memory() only compare the live sk_sndbuf
against txm->wmem_charge.
Suppose SO_SNDBUF or sk_stream_moderate_sndbuf() leaves sk_sndbuf
between wmem_charge and wmem_charge + min_space while other messages
are still queued. The request can no longer be satisfied, but the
sender keeps polling until the queue drains completely. Only then
does the sk_wmem_queued <= wmem_charge check return -EMSGSIZE. If
the psock peer stops reading, the queue never drains.
Should kcm_wait_memory() take min_space and wait until
sk_stream_wspace(sk) is at least min_space, rather than for
sk_stream_memory_free()? It could then return -EMSGSIZE as soon as
min_space exceeds the live sk_sndbuf minus wmem_charge.
[Severity: Medium]
The admission checks above use skb_charge = SKB_TRUESIZE(0), but the
charge here is head->truesize from alloc_skb(0). alloc_skb(0) goes through
kmalloc_reserve(), which sets *size = SKB_SMALL_HEAD_CACHE_SIZE.
__finalize_skb_around() then does:
size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
skb->truesize = SKB_TRUESIZE(size);
The result is a few hundred bytes larger than SKB_TRUESIZE(0). If the free
space falls inside that gap, the pre-check passes and kcm_wmem_charge()
fails.
Is a hard -ENOMEM intended here, for a sender that would have waited
before?
The frag_list skb has the same mismatch. The non-splice MAX_SKB_FRAGS path
and the splice -E2BIG path both check tskb_charge = SKB_TRUESIZE(0). Then
kcm_alloc_frag_skb() charges tskb->truesize and fails the same way. That
failure goes to wait_for_memory:
wait_for_memory:
wmem_queued = READ_ONCE(sk->sk_wmem_queued);
kcm_push(kcm);
...
err = kcm_wait_memory(sk, &timeo, head);
if (err)
goto out_error;
Unlike wait_for_space, this path has no sk_wmem_queued <= wmem_charge
exit. Suppose the unfinished message is the only charged object:
- kcm_push() frees nothing
- kcm_wait_memory() sees sk_stream_memory_free() true
- it sleeps a random vm_wait of up to about HZ/5 and returns 0
- with the default MAX_SCHEDULE_TIMEOUT, the timeout never decreases
Can this loop forever? Each pass, the SKB_TRUESIZE(0) pre-check passes,
the real charge fails, and the code goes back to wait_for_memory. The
sendmsg() or sendfile() call would spin until a signal arrives. It holds
kcm->tx_mutex the whole time, so other senders on the same socket sit in
uninterruptible mutex_lock().
[ ... ]
> @@ -809,65 +1067,144 @@ static int kcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
[ ... ]
> } else {
> - copy = min_t(int, msg_data_left(msg),
> + size_t budget = min_t(size_t, space, msg_space);
> + size_t padding = 0;
> +
> + copy = min_t(size_t, msg_data_left(msg),
> pfrag->size - pfrag->offset);
> - if (!sk_wmem_schedule(sk, copy))
> + copy = min_t(size_t, copy, budget);
> + if (!merge) {
> + if (pfrag->size > msg_space) {
> + err = -EMSGSIZE;
> + goto out_error;
> + }
> + if (pfrag->size > space) {
> + min_space = pfrag->size;
> + goto wait_for_space;
> + }
> + copy = min_t(size_t, msg_data_left(msg),
> + pfrag->size - pfrag->offset);
> + padding = pfrag->size - copy;
> + if (padding &&
> + !kcm_wmem_charge(sk, txm, padding))
> + goto wait_for_memory;
> + }
[Severity: High]
Doesn't this charge every message at least one full pfrag, even for a
1 byte payload?
The first fragment of a new message never merges, because
skb_can_coalesce() returns false for i == 0. So this block always runs for
it. skb_page_frag_refill() sets:
pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER;
That is 32 KiB on 4K page systems and 64 KiB on 64K page systems, whatever
sk_sndbuf is.
padding is pfrag->size - copy even when pfrag->offset > 0 and earlier
messages on the same page were already charged for it. The same page is
then counted once per message.
Some consequences:
With setsockopt(SO_SNDBUF, 16384), sk_sndbuf becomes 32768. msg_space is
then 32768 - head->truesize, which is smaller than pfrag->size. Every
non-splice sendmsg() returns -EMSGSIZE, where it used to succeed.
Without SOCK_SNDBUF_LOCK, a failed sk_page_frag_refill() calls
sk_stream_moderate_sndbuf(), which shrinks sk_sndbuf toward
SOCK_MIN_SNDBUF. Nothing in net/kcm/ grows it back. Later sends keep
failing the wmem_charge >= sk_sndbuf and pfrag->size > msg_space checks.
With the default 212992 byte sndbuf, only about 6 messages fit in the
queue (about 3 on 64K page systems). Before, roughly sndbuf bytes of
payload could be queued.
The new comment in struct kcm_tx_msg calls this a "conservative page
backing charge". Since shared pfrag pages are counted once per message,
isn't this double counting rather than retained memory?
The documentation patch in this series only says the maximum payload can
be smaller than SO_SNDBUF. It doesn't mention that a small SO_SNDBUF
leaves the socket unable to send at all.
[ ... ]
--
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796043121.git.zihanx%40nebusec.ai
^ permalink raw reply [flat|nested] 5+ messages in thread
* [PATCH net v2 2/2] net: kcm: document transmit memory budget
2026-12-01 6:37 [PATCH net v2 0/2] kcm: bound message memory by send buffer Zihan Xi
2026-12-01 6:38 ` [PATCH net v2 1/2] net: kcm: account retained message memory Zihan Xi
@ 2026-12-01 6:38 ` Zihan Xi
2026-12-05 3:39 ` netdev-bot+sashiko
1 sibling, 1 reply; 5+ messages in thread
From: Zihan Xi @ 2026-12-01 6:38 UTC (permalink / raw)
To: netdev, linux-doc
Cc: davem, edumazet, pabeni, willemb, horms, rjethwani, zirajs7,
leitao, brauner, jiayuan.chen, runyu.xiao, tom, corbet, skhan,
rdunlap, vega, zihanx
Document KCM's per-message SO_SNDBUF budget, including retained page and
skb memory, EMSGSIZE behavior, and the limit captured when message
construction starts.
Signed-off-by: Zihan Xi <zihanx@nebusec.ai>
---
Documentation/networking/kcm.rst | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/Documentation/networking/kcm.rst b/Documentation/networking/kcm.rst
index 07778f29211c..e64fd3c35773 100644
--- a/Documentation/networking/kcm.rst
+++ b/Documentation/networking/kcm.rst
@@ -102,6 +102,14 @@ greater than this limit a corresponding error (EMSGSIZE) is posted on the TCP
socket. The BPF program may also enforce a maximum messages size and report an
error when it is exceeded.
+On transmit, the KCM socket's SO_SNDBUF also limits the memory used to build
+and queue a message. This budget includes the message data, skb metadata and
+the backing pages retained by page fragments, so the maximum payload can be
+smaller than SO_SNDBUF. A send that would exceed the per-socket budget fails
+with EMSGSIZE. The limit for a message is taken when message construction
+starts; changing SO_SNDBUF does not enlarge an already started message. Set
+SO_SNDBUF before sending messages that require a larger budget.
+
A timeout may be set for assembling messages on a receive socket. The timeout
value is taken from the receive timeout of the attached TCP socket (this is set
by SO_RCVTIMEO). If the timer expires before assembly is complete an error
--
2.43.0
^ permalink raw reply related [flat|nested] 5+ messages in thread
* Re: [PATCH net v2 2/2] net: kcm: document transmit memory budget
2026-12-01 6:38 ` [PATCH net v2 2/2] net: kcm: document transmit memory budget Zihan Xi
@ 2026-12-05 3:39 ` netdev-bot+sashiko
0 siblings, 0 replies; 5+ messages in thread
From: netdev-bot+sashiko @ 2026-12-05 3:39 UTC (permalink / raw)
To: zihanx
Cc: netdev, linux-doc, davem, edumazet, pabeni, willemb, horms,
rjethwani, zirajs7, leitao, brauner, jiayuan.chen, runyu.xiao,
tom, corbet, skhan, rdunlap, vega, kuba
Thank you for your contribution! Sashiko AI review found 5 potential
issue(s) to consider.
Critical: 0 · High: 0 · Medium: 4 · Low: 1
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] The new kcm.rst paragraph (lines 105-108) says the transmit
budget covers the message data, skb metadata and the backing pages…
- [Medium] kcm.rst (lines 109-110) says the limit for a message "is taken
when message construction starts", and mentions only that a later…
- [Medium] net: kcm: broken partial-wspace wait logic in
kcm_wait_memory()
- [Medium] net: kcm: signed/unsigned sk_stream_wspace() comparison in
kcm_sendmsg()
- [Low] kcm.rst (lines 108-109) says "A send that would exceed the per-
socket budget fails with EMSGSIZE." Two parts of the code disagree…
--
net: kcm: document transmit memory budget
This commit adds a paragraph to Documentation/networking/kcm.rst about the
SO_SNDBUF budget that KCM applies on transmit. The paragraph covers which
memory is charged, when EMSGSIZE is returned, and when the limit for a
message is captured.
> diff --git a/Documentation/networking/kcm.rst b/Documentation/networking/kcm.rst
> index 07778f29211c4..e64fd3c357730 100644
> --- a/Documentation/networking/kcm.rst
> +++ b/Documentation/networking/kcm.rst
> @@ -102,6 +102,14 @@ greater than this limit a corresponding error (EMSGSIZE) is posted on the TCP
> socket. The BPF program may also enforce a maximum messages size and report an
> error when it is exceeded.
>
> +On transmit, the KCM socket's SO_SNDBUF also limits the memory used to build
> +and queue a message. This budget includes the message data, skb metadata and
> +the backing pages retained by page fragments, so the maximum payload can be
> +smaller than SO_SNDBUF. A send that would exceed the per-socket budget fails
[Severity: Medium]
Does this match the accounting in kcm_sendmsg()? For each copy that does not
coalesce, the whole page_frag has to fit in the message budget. The whole
page_frag is charged whatever pfrag->offset is:
net/kcm/kcmsock.c:kcm_sendmsg() {
...
if (!merge) {
if (pfrag->size > msg_space) {
err = -EMSGSIZE;
goto out_error;
}
...
padding = pfrag->size - copy;
if (padding &&
!kcm_wmem_charge(sk, txm, padding))
goto wait_for_memory;
}
...
txm->wmem_charge += copy;
...
}
skb_page_frag_refill() normally hands out a 32 KiB page
(PAGE_SIZE << SKB_FRAG_PAGE_ORDER). Take SO_SNDBUF=16384, which gives
sk_sndbuf=32768. Then pfrag->size is larger than msg_space
(32768 - head->truesize). Wouldn't even a 1-byte send fail with EMSGSIZE?
In that case the maximum payload is zero, not just "smaller than
SO_SNDBUF".
sk_page_frag() can also return current->task_frag. Earlier bytes of that
page may belong to other sockets, but they are still billed to this
message.
On the merge path (MSG_MORE on DGRAM, or no MSG_EOR on SEQPACKET), padding
is 0, but txm->wmem_charge += copy still runs. The earlier padding charge
already covered those bytes, so they get charged twice. That is not in the
list of what the budget includes.
The splice path charges the whole folio for each page that does not
coalesce:
net/kcm/kcmsock.c:kcm_splice_from_iter() {
...
if (!skb_can_coalesce(skb, i, page, off)) {
...
charge = folio_size(page_folio(page));
}
...
}
skb_can_coalesce() needs the same struct page, so each subpage of a large
folio can be charged the full folio size. Can spliced sends from
large-folio page cache hit EMSGSIZE at the default sndbuf?
The accounting itself comes from the preceding commit "net: kcm: account
retained message memory". This paragraph seems to understate it.
> +with EMSGSIZE. The limit for a message is taken when message construction
[Severity: Medium]
This is outside the documentation change itself, but it decides whether
the EMSGSIZE and blocking behaviour described here actually holds. What
does kcm_wait_memory() do when wait_for_space is entered with some write
space left, but less than min_space?
kcm_proto has no .stream_memory_free, so sk_stream_memory_free() is true
whenever sk->sk_wmem_queued < sk->sk_sndbuf. kcm_wait_memory() then
takes the vm_wait backoff path:
net/kcm/kcmsock.c:kcm_wait_memory() {
...
if (sk_stream_memory_free(sk)) {
current_timeo = get_random_u32_below(HZ / 5) + 2;
vm_wait = current_timeo;
}
...
}
That path looks meant for a failed page allocation while socket space
is available. Here the socket space is the problem. wait_for_space in
kcm_sendmsg() needs sk_stream_wspace(sk) >= min_space, and min_space is
pfrag->size, the folio size or SKB_TRUESIZE(0). The wake condition
(sk_stream_memory_free(sk) && !vm_wait) stays false until vm_wait
expires, so sk_write_space() from kcm_write_msgs() can't wake the
sender. Once vm_wait is cleared, the loop exits with err = 0 even
though wspace is still below min_space:
if (sk_stream_memory_free(sk) && !vm_wait)
break;
kcm_sendmsg() then goes back to start, lands in wait_for_space again
and repeats. With a 32 KiB page_frag that covers any wspace from 1 to
32767 bytes. Doesn't this turn into a poll loop with sleeps of up to
about HZ / 5, rather than a wait for write space?
The shrink case looks worse. Suppose sk_sndbuf was lowered so that
txm->wmem_charge < sk->sk_sndbuf < txm->wmem_charge + min_space, and
another message is still on sk_write_queue. wait_for_space only checks
min_space against the captured limit:
if (min_space > kcm_tx_msg(head)->sndbuf -
kcm_tx_msg(head)->wmem_charge) {
kcm_wait_memory() only aborts when txm->wmem_charge >= sk->sk_sndbuf.
Neither check fires. The sender keeps looping even though min_space
can never fit in the current sk_sndbuf, and it does not get the
EMSGSIZE this paragraph promises.
Should kcm_wait_memory() be given min_space, wait until
sk_stream_wspace(sk) >= min_space, and check min_space against the live
sk_sndbuf as well as txm->sndbuf? That fix would presumably belong in
the preceding "net: kcm: account retained message memory" commit
rather than here.
[Severity: Low]
Is "per-socket budget" the right term here? The commit message calls it a
"per-message SO_SNDBUF budget". EMSGSIZE seems to come back only when the
message's own charge would go past txm->sndbuf - txm->wmem_charge, or when
the message is the only thing queued.
When socket-wide write space runs short, kcm_sendmsg() goes to
wait_for_space. It then blocks in kcm_wait_memory(), or returns EAGAIN with
MSG_DONTWAIT. kcm_splice_from_iter() also returns EAGAIN in that case:
if (charge > sk_stream_wspace(sk)) {
*min_space = charge;
err = -EAGAIN;
goto revert;
}
SOCK_SEQPACKET behaves differently again. If the budget is hit after some
bytes were already copied in the current call, out_error returns a short
count with no error:
if (copied)
goto partial_message;
EMSGSIZE then only shows up on the next call. Should the paragraph mention
this?
> +starts; changing SO_SNDBUF does not enlarge an already started message. Set
[Severity: Medium]
Is this accurate for kcm_sendmsg()? The limit is captured when the head is
allocated:
kcm_tx_msg(head)->sndbuf = sndbuf;
The accumulated charge is also checked against the live sk->sk_sndbuf in
several places: at the top of the copy loop, after sk_page_frag_refill(),
in wait_for_space, in wait_for_memory, and in kcm_wait_memory(). For
example:
if (txm->wmem_charge >= txm->sndbuf ||
txm->wmem_charge >= READ_ONCE(sk->sk_sndbuf)) {
err = -EMSGSIZE;
goto out_error;
}
So the effective limit looks like min(captured sndbuf, current
sk_sndbuf), and a started message is aborted if sk_sndbuf shrinks.
Two things can shrink it. A user can lower SO_SNDBUF. The kernel can also
lower it: when sk_page_frag_refill() fails, it calls
sk_stream_moderate_sndbuf() on sockets without SOCK_SNDBUF_LOCK. The code
comments say as much:
/* sndbuf can shrink while page-frag allocation moderates it. */
For DGRAM sockets, out_error then throws away the whole partly built
message:
} else {
if (head)
kcm_wmem_uncharge_msg(sk, head);
kfree_skb(head);
kcm->seq_skb = NULL;
}
That includes bytes that earlier MSG_MORE sendmsg() calls reported as
sent. Should the documentation cover the shrink case and this loss of the
pending message?
[ ... ]
> @@ -102,6 +102,14 @@ greater than this limit a corresponding error (EMSGSIZE) is posted on the TCP
> socket. The BPF program may also enforce a maximum messages size and report an
> error when it is exceeded.
>
> +On transmit, the KCM socket's SO_SNDBUF also limits the memory used to build
> +and queue a message. This budget includes the message data, skb metadata and
> +the backing pages retained by page fragments, so the maximum payload can be
> +smaller than SO_SNDBUF. A send that would exceed the per-socket budget fails
> +with EMSGSIZE. The limit for a message is taken when message construction
> +starts; changing SO_SNDBUF does not enlarge an already started message. Set
> +SO_SNDBUF before sending messages that require a larger budget.
> +
> A timeout may be set for assembling messages on a receive socket. The timeout
> value is taken from the receive timeout of the attached TCP socket (this is set
> by SO_RCVTIMEO). If the timer expires before assembly is complete an error
[Severity: Medium]
Does starting a new message work when sk->sk_wmem_queued is already
above sk->sk_sndbuf? That is the state after SO_SNDBUF is lowered with
messages still queued, or after sk_page_frag_refill() moderates
sk_sndbuf. This sentence gives advice about exactly that situation.
sk_stream_wspace() returns an int, which is negative here, but
skb_charge in kcm_sendmsg() is a size_t:
net/kcm/kcmsock.c:kcm_sendmsg() {
size_t copy, copied = 0, sndbuf, skb_charge;
...
while (skb_charge > sk_stream_wspace(sk)) {
kcm_push(kcm);
if (skb_charge <= sk_stream_wspace(sk))
break;
...
}
The negative int is converted to a huge size_t, so the loop condition
is false. Both kcm_push() and sk_stream_wait_memory() are skipped.
head is then allocated and charged with kcm_wmem_charge(sk,
kcm_tx_msg(head), head->truesize). kcm_wmem_charge() takes an int
charge, so there charge > sk_stream_wspace(sk) is true and the charge
fails:
err = -ENOMEM;
goto out_error;
A blocking sender therefore gets ENOMEM straight away instead of
waiting for the queue to drain, and the already queued messages are not
pushed first. The new paragraph does not mention ENOMEM either. Should
skb_charge be compared as a signed value, or should a negative
sk_stream_wspace() be handled explicitly before the loop?
--
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/cover.1796043121.git.zihanx%40nebusec.ai
^ permalink raw reply [flat|nested] 5+ messages in thread
end of thread, other threads:[~2026-12-05 3:39 UTC | newest]
Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-01 6:37 [PATCH net v2 0/2] kcm: bound message memory by send buffer Zihan Xi
2026-12-01 6:38 ` [PATCH net v2 1/2] net: kcm: account retained message memory Zihan Xi
2026-12-05 3:39 ` netdev-bot+sashiko
2026-12-01 6:38 ` [PATCH net v2 2/2] net: kcm: document transmit memory budget Zihan Xi
2026-12-05 3:39 ` netdev-bot+sashiko
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.