Linux Documentation
 help / color / mirror / Atom feed
* [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; 3+ 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] 3+ 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-01  6:38 ` [PATCH net v2 2/2] net: kcm: document transmit memory budget Zihan Xi
  1 sibling, 0 replies; 3+ 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, &current_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] 3+ 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
  1 sibling, 0 replies; 3+ 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] 3+ messages in thread

end of thread, other threads:[~2026-12-01  6:38 UTC | newest]

Thread overview: 3+ 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-01  6:38 ` [PATCH net v2 2/2] net: kcm: document transmit memory budget Zihan Xi

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox