Skip to contentSkip to conversation

tun: bound the NAPI receive queue

PATCH Applied Antonio Quartulli 5 participants 7 messages Nov 19 – Nov 25

Subsystems (5)
lore
Share & tools
lore
#0 lore raw

PATCH v7 1/1 tun: bound the NAPI receive queue

With IFF_NAPI, tun_get_user() queues every written packet for NAPI on an unbounded list. When the poll runs asynchronously (threaded NAPI or ksoftirqd) and is slower than the writer, the queue grows until the system runs out of memory. An unprivileged user can do this from its own user and network namespaces, and the queued skbs are not charged to its
memcg: in a test VM, a uid 1000 process limited to 128 MB caused a global OOM in ~6 seconds. The socket send buffer does not help: tun sets it to INT_MAX by default, the build_skb() path is only used while it is INT_MAX, and the XDP batch path never checks it.

Drop packets once more than netdev_max_backlog of them are queued, like enqueue_to_backlog() does, and count them as rx_dropped; the write still reports success, as for a full backlog. The check sits where packets are queued for NAPI, in tun_get_user() and in tun_xdp_one() for the batches vhost-net passes, so packets consumed by XDP or delivered through IFF_NAPI_FRAGS are not affected. A dropped zerocopy skb completes its buffer when freed. The check is lockless, so concurrent writers can each still add one packet.

The NAPI poll moved the whole queue out, processed up to its budget and put the rest back: while it ran, the queue looked empty to writers, so with the poll on another CPU the backlog could still grow without limit. Take at most budget packets instead: the rest stays on the queue writers check.

Dropping also schedules NAPI. vhost-net sends with MSG_MORE while it has more packets, and tun_get_user() schedules NAPI only for a packet without it or once more than NAPI_POLL_WEIGHT are queued. With a netdev_max_backlog below that, the queue fills first and the packet without MSG_MORE is dropped too: nothing would schedule NAPI, and the queued packets, with zerocopy also their buffers, would wait forever.

Reproducer, as an unprivileged user in a new user and network namespace, without kernel modifications or fault injection:
ip tuntap add t0 mode tun; ip addr add 10.11.0.1/24 dev t0 ip link add d0 type dummy; ip addr add 10.20.0.1/24 dev d0 ip link set t0 up; ip link set d0 up; sysctl net.ipv4.ip_forward=1 install ~500 iptables FORWARD rules, to slow down the poll, and a MASQUERADE rule on d0
open t0 with IFF_TUN | IFF_NO_PI | IFF_NAPI
echo 1 > /sys/class/net/t0/threaded
write() 1400-byte IPv4 packets for 10.20.0.2 in a loop

Found by code inspection while analysing the performance of the tun write path. Tested in an x86-64 VM on net, with 1 and 2 vCPUs: the reproducer causes a global OOM without the patch, while with it memory use stays flat and the forwarding rate is unchanged; the tun kselftest passes; a local vhost-net test of the batch, copy and zerocopy paths with netdev_max_backlog set to 8 passes, and fails without the patch; an XDP program on the device sees every packet while the excess is dropped.

Still open: neither the packet size nor the queued memory is bounded, and the skbs are not charged to the writer's memcg. A single write can create an skb of several hundred KB, so even one queue can hold a lot, and IFF_MULTI_QUEUE (allowed in a user namespace) and more devices multiply it. This bounds the queue as enqueue_to_backlog() bounds the per-CPU backlog; charging the skbs to the writer is left to a follow-up.

Fixes 943170998b20 ("tun: enable NAPI for TUN/TAP driver")

---
v7:
- Check where packets are queued, after XDP and not for IFF_NAPI_FRAGS (Sashiko); a dropped zerocopy skb now completes its buffer when freed
- Fix the poll comment and the commit message (Sashiko)
- Drop the vhost-net selftest (Willem, Sashiko)

v6: https://lore.kernel.org/netdev/[email protected]/
v5: https://lore.kernel.org/netdev/[email protected]/
v4: https://lore.kernel.org/netdev/[email protected]/
v3: https://lore.kernel.org/netdev/[email protected]/
v2: https://lore.kernel.org/netdev/[email protected]/

Stable: kernels before v6.9 have no net_hotdata; a backport reads netdev_max_backlog instead.

 drivers/net/tun.c | 52 +++++++++++++++++++++++++++++++++++++++--------
 1 file changed, 44 insertions(+), 8 deletions(-)
drivers/net/tun.c +44 -8
index 86fd44e10755..b7432bd4d3f0 100644
@@ -58,6 +58,7 @@
 #include <linux/nsproxy.h>
 #include <linux/virtio_net.h>
 #include <linux/rcupdate.h>
+#include <net/hotdata.h>
 #include <net/net_namespace.h>
 #include <net/netns/generic.h>
 #include <net/rtnetlink.h>
@@ -227,6 +228,16 @@ struct veth {
 static void tun_flow_init(struct tun_struct *tun);
 static void tun_flow_uninit(struct tun_struct *tun);
 
+/* In IFF_NAPI mode written packets wait in the tfile's sk_write_queue for the
+ * NAPI poll, which may run later in a kthread or ksoftirqd. Bound that queue
+ * like the per-CPU backlog.
+ */
+static bool tun_napi_queue_full(const struct sk_buff_head *queue)
+{
+	return skb_queue_len_lockless(queue) >
+	       READ_ONCE(net_hotdata.max_backlog);
+}
+
 static int tun_napi_receive(struct napi_struct *napi, int budget)
 {
 	struct tun_file *tfile = container_of(napi, struct tun_file, napi);
@@ -237,21 +248,22 @@ static int tun_napi_receive(struct napi_struct *napi, int budget)
 
 	__skb_queue_head_init(&process_queue);
 
+	/* At most budget skbs: the rest stays on the queue writers check */
 	spin_lock(&queue->lock);
-	skb_queue_splice_tail_init(queue, &process_queue);
+	if (skb_queue_len(queue) <= budget) {
+		skb_queue_splice_tail_init(queue, &process_queue);
+	} else {
+		while (skb_queue_len(&process_queue) < budget &&
+		       (skb = __skb_dequeue(queue)))
+			__skb_queue_tail(&process_queue, skb);
+	}
 	spin_unlock(&queue->lock);
 
-	while (received < budget && (skb = __skb_dequeue(&process_queue))) {
+	while ((skb = __skb_dequeue(&process_queue))) {
 		napi_gro_receive(napi, skb);
 		++received;
 	}
 
-	if (!skb_queue_empty(&process_queue)) {
-		spin_lock(&queue->lock);
-		skb_queue_splice(&process_queue, queue);
-		spin_unlock(&queue->lock);
-	}
-
 	return received;
 }
 
@@ -2043,6 +2055,19 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
 		struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
 		int queue_len;
 
+		/* Queue full: drop, and schedule NAPI, which a MSG_MORE sender
+		 * may not have done yet. Lockless: concurrent writers can each
+		 * still add one.
+		 */
+		if (unlikely(tun_napi_queue_full(queue))) {
+			local_bh_disable();
+			napi_schedule(&tfile->napi);
+			local_bh_enable();
+			rcu_read_unlock();
+			drop_reason = SKB_DROP_REASON_FULL_RING;
+			goto drop;
+		}
+
 		spin_lock_bh(&queue->lock);
 
 		if (unlikely(tfile->detached)) {
@@ -2658,6 +2683,17 @@ static int tun_xdp_one(struct tun_struct *tun,
 
 	if (tfile->napi_enabled) {
 		queue = &tfile->sk.sk_write_queue;
+
+		/* Queue full: drop, and schedule NAPI so that it drains even if
+		 * nothing in this batch gets queued.
+		 */
+		if (unlikely(tun_napi_queue_full(queue))) {
+			napi_schedule(&tfile->napi);
+			kfree_skb_reason(skb, SKB_DROP_REASON_FULL_RING);
+			dev_core_stats_rx_dropped_inc(tun->dev);
+			return 0;
+		}
+
 		spin_lock(&queue->lock);
 
 		if (unlikely(tfile->detached)) {

base-commit: ead6fa9a0ab194f02a2f36d634b193e9c5f9a1c6

Signature · 1 line
2.56.1
#1 lore raw
Sashiko has reviewed this patch and found no issues.
Quoted 19 lines

With IFF_NAPI, tun_get_user() queues every written packet for NAPI on an unbounded list. When the poll runs asynchronously (threaded NAPI or ksoftirqd) and is slower than the writer, the queue grows until the system runs out of memory. An unprivileged user can do this from its own user and network namespaces, and the queued skbs are not charged to its
memcg: in a test VM, a uid 1000 process limited to 128 MB caused a global OOM in ~6 seconds. The socket send buffer does not help: tun sets it to INT_MAX by default, the build_skb() path is only used while it is INT_MAX, and the XDP batch path never checks it.

Drop packets once more than netdev_max_backlog of them are queued, like enqueue_to_backlog() does, and count them as rx_dropped; the write still reports success, as for a full backlog. The check sits where packets are queued for NAPI, in tun_get_user() and in tun_xdp_one() for the batches vhost-net passes, so packets consumed by XDP or delivered through [ ... ]
multiply it. This bounds the queue as enqueue_to_backlog() bounds the per-CPU backlog; charging the skbs to the writer is left to a follow-up.

Quoted 2 lines
Fixes 943170998b20 ("tun: enable NAPI for TUN/TAP driver")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
maintainer Reviewed-by on v7 1/1
#2 lore raw
In reply to Antonio Quartulli
Quoted 59 lines · Antonio Quartulli

With IFF_NAPI, tun_get_user() queues every written packet for NAPI on an unbounded list. When the poll runs asynchronously (threaded NAPI or ksoftirqd) and is slower than the writer, the queue grows until the system runs out of memory. An unprivileged user can do this from its own user and network namespaces, and the queued skbs are not charged to its
memcg: in a test VM, a uid 1000 process limited to 128 MB caused a global OOM in ~6 seconds. The socket send buffer does not help: tun sets it to INT_MAX by default, the build_skb() path is only used while it is INT_MAX, and the XDP batch path never checks it.

Drop packets once more than netdev_max_backlog of them are queued, like enqueue_to_backlog() does, and count them as rx_dropped; the write still reports success, as for a full backlog. The check sits where packets are queued for NAPI, in tun_get_user() and in tun_xdp_one() for the batches vhost-net passes, so packets consumed by XDP or delivered through IFF_NAPI_FRAGS are not affected. A dropped zerocopy skb completes its buffer when freed. The check is lockless, so concurrent writers can each still add one packet.

The NAPI poll moved the whole queue out, processed up to its budget and put the rest back: while it ran, the queue looked empty to writers, so with the poll on another CPU the backlog could still grow without limit. Take at most budget packets instead: the rest stays on the queue writers check.

Dropping also schedules NAPI. vhost-net sends with MSG_MORE while it has more packets, and tun_get_user() schedules NAPI only for a packet without it or once more than NAPI_POLL_WEIGHT are queued. With a netdev_max_backlog below that, the queue fills first and the packet without MSG_MORE is dropped too: nothing would schedule NAPI, and the queued packets, with zerocopy also their buffers, would wait forever.

Reproducer, as an unprivileged user in a new user and network namespace, without kernel modifications or fault injection:
ip tuntap add t0 mode tun; ip addr add 10.11.0.1/24 dev t0 ip link add d0 type dummy; ip addr add 10.20.0.1/24 dev d0 ip link set t0 up; ip link set d0 up; sysctl net.ipv4.ip_forward=1 install ~500 iptables FORWARD rules, to slow down the poll, and a MASQUERADE rule on d0
open t0 with IFF_TUN | IFF_NO_PI | IFF_NAPI
echo 1 > /sys/class/net/t0/threaded
write() 1400-byte IPv4 packets for 10.20.0.2 in a loop

Found by code inspection while analysing the performance of the tun write path. Tested in an x86-64 VM on net, with 1 and 2 vCPUs: the reproducer causes a global OOM without the patch, while with it memory use stays flat and the forwarding rate is unchanged; the tun kselftest passes; a local vhost-net test of the batch, copy and zerocopy paths with netdev_max_backlog set to 8 passes, and fails without the patch; an XDP program on the device sees every packet while the excess is dropped.

Still open: neither the packet size nor the queued memory is bounded, and the skbs are not charged to the writer's memcg. A single write can create an skb of several hundred KB, so even one queue can hold a lot, and IFF_MULTI_QUEUE (allowed in a user namespace) and more devices multiply it. This bounds the queue as enqueue_to_backlog() bounds the per-CPU backlog; charging the skbs to the writer is left to a follow-up.

Quoted 2 lines
Fixes 943170998b20 ("tun: enable NAPI for TUN/TAP driver")
#3 lore raw
In reply to Antonio Quartulli
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

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

Critical: 0 · High: 1 · Medium: 1 · 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] Bounding the IFF_NAPI queue by packet count only (net_hotdata.max_backlog skbs per tun_file, ignoring size) does not…
- [Medium] The patch silently changes behaviour for IFF_NAPI users who set a finite send buffer with TUNSETSNDBUF, and the commit message…

--

tun: bound the NAPI receive queue

This patch caps the IFF_NAPI sk_write_queue of each tun_file at net_hotdata.max_backlog packets. Excess packets are dropped and counted as rx_dropped in tun_get_user() and tun_xdp_one(). It also changes tun_napi_receive() to take at most budget skbs from the queue, so the rest stays visible to writers.

Quoted 4 lines
drivers/net/tun.c +0 -0
index 86fd44e107550..b7432bd4d3f03 100644

[ ... ]

drivers/net/tun.c struct veth { · line 239

Quoted 13 lines
drivers/net/tun.c +9 -0
@@ -227,6 +228,16 @@ struct veth {
 static void tun_flow_init(struct tun_struct *tun);
 static void tun_flow_uninit(struct tun_struct *tun);
 
+/* In IFF_NAPI mode written packets wait in the tfile's sk_write_queue for the
+ * NAPI poll, which may run later in a kthread or ksoftirqd. Bound that queue
+ * like the per-CPU backlog.
+ */
+static bool tun_napi_queue_full(const struct sk_buff_head *queue)
+{
+	return skb_queue_len_lockless(queue) >
+	       READ_ONCE(net_hotdata.max_backlog);
+}

[Severity: High]
Is a packet count limit in tun_napi_queue_full() enough to prevent the global OOM described in the commit message?

tun_get_user() takes total_len = iov_iter_count(from) with no upper bound. tun_alloc_skb() can then build an skb with up to ~544 KB of frags plus a linear remainder:

drivers/net/tun.c:tun_alloc_skb() {
    ...
	if (len - linear > MAX_SKB_FRAGS * (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
		linear = len - MAX_SKB_FRAGS * (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER);
	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
				   &err, PAGE_ALLOC_COSTLY_ORDER);
    ...
}

tun_chr_open() sets sk_sndbuf to INT_MAX by default. With that, a single tun_file can still hold about max_backlog * truesize. That is tens of MB with 64 KB writes, and much more with multi-MB writes.

The limit is also per tun_file. With IFF_MULTI_QUEUE, tun_set_iff() allows MAX_TAP_QUEUES (256) queues per device. The only gate is ns_capable() in the user's own namespace:

	int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
		     MAX_TAP_QUEUES : 1;

Even with 1400-byte packets that is roughly 256 * 1000 * ~2.3 KB, or about 590 MB per device. A namespace can also create several devices.

The commit message lists this under "Still open". Even so, the same uid 1000 process limited to a 128 MB memcg looks able to reach a global OOM with larger writes, more queues or more devices.

Would this need a truesize based limit, or charging the queued skbs to the writer's memcg, to close the reported DoS?

[ ... ]

Quoted 6 lines
drivers/net/tun.c +2 -0
@@ -2043,6 +2055,19 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
 		struct sk_buff_head *queue = &tfile->sk.sk_write_queue;
 		int queue_len;
 
+		/* Queue full: drop, and schedule NAPI, which a MSG_MORE sender
+		 * may not have done yet. Lockless: concurrent writers can each

drivers/net/tun.c static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, · line 2069

Quoted 10 lines
drivers/net/tun.c +10 -0
+		 * still add one.
+		 */
+		if (unlikely(tun_napi_queue_full(queue))) {
+			local_bh_disable();
+			napi_schedule(&tfile->napi);
+			local_bh_enable();
+			rcu_read_unlock();
+			drop_reason = SKB_DROP_REASON_FULL_RING;
+			goto drop;
+		}

[Severity: Medium]
Is this behaviour change intended for IFF_NAPI users who set a finite send buffer with TUNSETSNDBUF?

With a finite sk_sndbuf, tun_can_build_skb() refuses the build_skb path:

	if (tfile->socket.sk->sk_sndbuf != INT_MAX)
		return false;

So every write goes through tun_alloc_skb()->sock_alloc_send_pskb(), which charges sk_wmem_alloc.

Before this patch, skbs on sk_write_queue kept their wmem charge until the NAPI poll consumed them. A slow poll made a blocking writer sleep in sock_alloc_send_pskb(), and gave a non-blocking writer or vhost-net -EAGAIN.

After this patch, this branch fires first once sndbuf is larger than about max_backlog * truesize. That is about 2.3 MB for 1400-byte packets with the default max_backlog of 1000. The skb is freed, which releases its wmem, and tun_get_user() returns total_len.

The writer then never blocks and never gets -EAGAIN. Lossless backpressure that the user configured becomes silent packet loss. The commit message only mentions sndbuf as being INT_MAX by default.

Could this be documented? Or could a full queue block or return -EAGAIN for writers on the charged path? Exempting finite-sndbuf queues alone would not be enough, since the same user could set sndbuf to INT_MAX - 1 to get around the cap.

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261119153056.353156-1-antonio%40mandelbit.com
#4 lore raw
Quoted 5 lines · On 22/11/2026 00:37, [email protected] wrote:

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

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

Quoted 8 lines

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] Bounding the IFF_NAPI queue by packet count only (net_hotdata.max_backlog skbs per tun_file, ignoring size) does not…

Right, and the commit message says so under "Still open": this bounds each queue the way enqueue_to_backlog() bounds the per-CPU backlog, but not the memory a user can queue. Closing that needs the queued skbs charged to the writer's memcg, which touches more allocation sites (one in vhost-net) and every tun user, so it will be a separate change.

Quoted 3 lines

- [Medium] The patch silently changes behaviour for IFF_NAPI users who set a finite send buffer with TUNSETSNDBUF, and the commit message…

True for a send buffer larger than about netdev_max_backlog packets:
there the queue limit now drops before the writer would block on socket memory. With a smaller send buffer the writer still blocks first. A full queue dropping instead of pushing back is also what netif_rx() does for a full backlog, regardless of the send buffer, and blocking on the NAPI queue would need a wait/wake mechanism tun does not have.
I'd rather
keep the fix minimal; netdev_max_backlog tunes the limit and be done with it.

Given the above, I am not going to respin.

Regards,

Signature · 5 lines
Antonio Quartulli

CEO and Co-Founder
Mandelbit Srl
https://www.mandelbit.com
maintainer
#5 lore raw
Quoted 40 lines · Antonio Quartulli
Quoted 5 lines · On 22/11/2026 00:37, [email protected] wrote:

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

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

Quoted 8 lines

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] Bounding the IFF_NAPI queue by packet count only (net_hotdata.max_backlog skbs per tun_file, ignoring size) does not…

Right, and the commit message says so under "Still open": this bounds each queue the way enqueue_to_backlog() bounds the per-CPU backlog, but not the memory a user can queue. Closing that needs the queued skbs charged to the writer's memcg, which touches more allocation sites (one in vhost-net) and every tun user, so it will be a separate change.

Quoted 3 lines

- [Medium] The patch silently changes behaviour for IFF_NAPI users who set a finite send buffer with TUNSETSNDBUF, and the commit message…

True for a send buffer larger than about netdev_max_backlog packets:
there the queue limit now drops before the writer would block on socket memory. With a smaller send buffer the writer still blocks first. A full queue dropping instead of pushing back is also what netif_rx() does for a full backlog, regardless of the send buffer, and blocking on the NAPI queue would need a wait/wake mechanism tun does not have. I'd rather
keep the fix minimal; netdev_max_backlog tunes the limit and be done with it.

Quoted 1 line

Given the above, I am not going to respin.

Agreed.

#6 lore raw
In reply to Antonio Quartulli
This patch was applied to netdev/net.git (main) by Willem de Bruijn <[email protected]>:

Hello:

This patch was applied to netdev/net.git (main)
by Willem de Bruijn <[email protected]>:

Quoted 11 lines · On Thu, 19 Nov 2026 16:30:55 +0100 you wrote:

With IFF_NAPI, tun_get_user() queues every written packet for NAPI on an unbounded list. When the poll runs asynchronously (threaded NAPI or ksoftirqd) and is slower than the writer, the queue grows until the system runs out of memory. An unprivileged user can do this from its own user and network namespaces, and the queued skbs are not charged to its
memcg: in a test VM, a uid 1000 process limited to 128 MB caused a global OOM in ~6 seconds. The socket send buffer does not help: tun sets it to INT_MAX by default, the build_skb() path is only used while it is INT_MAX, and the XDP batch path never checks it.

[...]

Here is the summary with links:
- [net,v7] tun: bound the NAPI receive queue

    https://git.kernel.org/netdev/net/c/cc7fe6e74173

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html