Netdev List
 help / color / mirror / Atom feed
* [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly
@ 2026-12-04 16:27 Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 01/15] xdp: Let memory providers expose net_iovs to XDP Björn Töpel
                   ` (14 more replies)
  0 siblings, 15 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

Currently, AF_XDP zero copy fills one UMEM chunk per buffer at the
UMEM headroom, and each RX descriptor gives its chunk back. Drivers
carry a second RX path for that layout, and cannot use their own
buffer sizes or pack small packets into a page.

This series adds explicit chunk return. With XDP_UMEM_EXPLICIT_RETURN,
the device lays out buffers in chunks as in pages, so a chunk may hold
several buffers and a packet may span chunks. Each buffer reaches the
socket as an RX descriptor. A chunk comes back on a descriptor with
XDP_RX_CHUNK_RETURNED, or without one once the receiving socket is
gone. The application cannot influence where packets land, how many
share a chunk, or the headroom.

The design came out of off-list discussions with Magnus, Maciej,
Stanislav and Jakub, where Jakub proposed letting the device keep its
own buffer layout.

The chunks back the bound queue's RX page pools through an AF_XDP
memory provider, so drivers need no AF_XDP code. fbnic and mlx5 add 54
and 165 lines, to handle buffers as netmem, refuse settings that the
provider cannot take and, for mlx5, restart queues with a provider
bound. A native XDP program steers packets to the socket. The kernel
keeps nothing in the chunks, as userspace may write them at any time.

The provider takes no lock. The driver uses the queue's buffers from
one context at a time, its NAPI or an operation that runs only while
that NAPI cannot use the rings. It runs that NAPI once after the queue
starts, and passes the buffers only to the queue's socket. That
context writes every return at once, as the RX ring keeps room for
each chunk the kernel owes, so packets drop a little before the ring
is full.

This posting drops XDP_PASS and XDP_TX of these buffers. Both need a
copy, which a follow-up adds. Until then, management traffic should
use other queues. Sockets transmit in copy mode only.

Performance in Mpps with 4 KiB chunks and preferred busy polling, so
application and NAPI share one CPU. Native XDP drops each packet and
AF_XDP sockets only return it, untouched. Min-max of 3 runs, 5 for
mlx5 XDP_DROP below 300 B; * is within 2% of the offered load, ** a
PCIe limit (Gen4 x4).

MTU 1500:

                 offered  native        explicit      classic
  frame   NIC             XDP_DROP      return        zero copy
  66 B    mlx5   61.0     31.38-32.71   18.19-18.25   23.40-23.87
          fbnic  65.3     37.68-38.15   26.61-26.96   n/a
  128 B   mlx5   37.0     31.07-31.27** 18.09-18.28   23.22-23.64
          fbnic  40.5     37.99-38.21   26.81-27.14   n/a
  300 B   mlx5   19.3     17.70-17.71** 17.72-17.73** 17.72-17.73**
          fbnic  17.4     17.38-17.43*  17.41-17.52*  n/a
  1500 B  mlx5   4.10     4.10*         4.10*         4.09*
          fbnic  4.04     4.03-4.08*    4.03-4.05*    n/a

MTU 5000, where classic zero copy cannot bind on mlx5; fbnic has none:

                 offered  native        explicit      classic
  frame   NIC             XDP_DROP      return        zero copy
  300 B   mlx5   19.3     17.78**       17.21-17.48** n/a
          fbnic  17.4     17.41-17.48*  17.39-17.46*  n/a
  1500 B  mlx5   4.10     4.10*         4.10*         n/a
          fbnic  4.04     4.04-4.06*    4.03-4.04*    n/a
  3000 B  mlx5   2.07     2.07*         2.07*         n/a
          fbnic  2.02     2.02*         2.02*         n/a
  5000 B  mlx5   1.24     1.24*         1.24*         n/a
          fbnic  1.21     1.20-1.21*    1.20-1.21*    n/a

Native XDP (XDP_DROP, XDP_TX and XDP_REDIRECT), classic AF_XDP and the
kernel UDP and TCP paths run at the rate of the base on mlx5, fbnic
and bnxt, within the run-to-run spread.

This series transmits in copy mode; the full branch, with bnxt,
zero-copy TX and the follow-up optimizations, and its numbers are at
https://github.com/fb-bjorn/linux/tree/xsk-explicit-return-v2.

Dependencies:
 - "xsk: Keep the shared info of zero-copy buffers in kernel memory",
   https://lore.kernel.org/netdev/20261204142030.626820-1-bjorn@kernel.org/;
 - "eth: fbnic: Support XDP redirect",
   https://lore.kernel.org/netdev/20261203180924.3862144-1-bjorn@kernel.org/;
 - "net/mlx5e: Report a down device as -ENETDOWN to queue restarts",
   https://lore.kernel.org/netdev/20261201113925.1245805-1-bjorn@kernel.org/;
 - "ethtool: Allow the channel count that a memory provider needs",
   https://lore.kernel.org/netdev/20261201115458.1254880-1-bjorn@kernel.org/;
 - "bpf: Use the checked TCP header length in the syncookie helpers",
   https://lore.kernel.org/netdev/20261201091755.1130605-1-bjorn@kernel.org/.

v1: https://lore.kernel.org/netdev/20261124112707.118678-1-bjorn@kernel.org/

Changes since v1:
 - v1 was "xsk: Receive in the device's buffer layout". The flags are
   now XDP_UMEM_EXPLICIT_RETURN and XDP_RX_CHUNK_RETURNED, not
   XDP_UMEM_DRV_LAYOUT and XDP_RX_CHUNK_FREE, after Magnus. xsk_sink
   is now xsk_mp, and "sink" is "XDP-only" in kernel names;
 - v1 patch 2 became a net series, see Dependencies, which also moves
   the shared info of classic zero-copy buffers out of the UMEM,
   after Maciej;
 - v1 patch 9, fbnic XDP_REDIRECT, is a dependency. v1 patch 11
   is part of patch 2, and v1 patch 12 is split into patches 10 and
   11. bnxt, v1 patch 13, comes back in a follow-up, after fixes to
   its queue restarts. Patches 8, 12 and 13 are new;
 - binding also needs CAP_NET_ADMIN, and XDP_ZEROCOPY fails as
   XDP_COPY did. Classic zero copy may bind next to an XDP-only
   provider on another queue;
 - an empty head with metadata reaches the socket as a zero-length
   first descriptor with XDP_PKT_CONTD. v1 dropped such packets;
 - a returned chunk counts against no page pool, so a restart while
   bound does not starve the new queue;
 - the provider takes no lock, as the driver uses a queue's buffers
   from one context at a time. Returns go into RX ring room kept for
   them, and need_wakeup reports only an empty FILL ring;
 - the provider drops the references of a run of buffers at once, and
   mlx5 lets go of a page after its last stride, so fewer chunks need
   an extra empty descriptor;
 - the provider goes with the last socket of the queue, not with the
   receiving socket. Once the receiver is gone, the queue drops what
   it redirects and the chunks the kernel owes return. The rest
   return with the last socket, and a program detach right after that
   may briefly fail with EBUSY;
 - redirects show in the xdp_redirect_map tracepoints, and page-pool
   dumps carry a new, empty xsk nest, NETDEV_A_PAGE_POOL_XSK;
 - mlx5 takes the provider on striding RQs only. While a queue has
   one, it refuses to leave them, PTP, HTB offload and growing the
   RQs of a down device. A channel switch closes the old channels
   first;
 - xskxceiver's --drv-layout is now --explicit-return, -H checks the
   headroom, and RX_RING_FULL_RETURNS is new. The test now fits the
   reworked xsk selftests, and drivers/net/xsk.py runs its rx cases
   with explicit return on a NIC. The af_xdp.rst section
   "Device Buffer Layout" is now "Explicit Chunk Return", with a part
   for drivers;
 - many fixes from a machine review of v1, listed in each patch.

Björn Töpel (15):
  xdp: Let memory providers expose net_iovs to XDP
  net: Add memory providers that only feed XDP
  page_pool: Let memory providers take back net_iovs
  xdp: Run programs on XDP-only buffers
  xsk: Back a queue's page pools with UMEM chunks
  xsk: Deliver packets and return chunks explicitly
  xsk: Receive with explicit chunk return
  xsk: Drop references of a run of buffers at once
  eth: fbnic: Receive into XDP-only memory providers
  net/mlx5e: Handle restarts with XDP-only providers
  net/mlx5e: Receive into XDP-only memory providers
  net/mlx5e: Release XDP-only pages earlier
  net/mlx5e: Test for XDP-only pages per RQ
  selftests: net: xsk: Test explicit chunk return
  Documentation: xsk: Describe explicit chunk return

 Documentation/netlink/specs/netdev.yaml       |   8 +
 Documentation/networking/af_xdp.rst           | 244 ++++-
 drivers/net/ethernet/mellanox/mlx5/core/en.h  |   1 +
 .../net/ethernet/mellanox/mlx5/core/en_main.c | 100 +-
 .../net/ethernet/mellanox/mlx5/core/en_rx.c   |  83 +-
 .../net/ethernet/meta/fbnic/fbnic_ethtool.c   |  22 +
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c  |  41 +-
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h  |   8 +
 drivers/net/netkit.c                          |   2 +-
 include/linux/netdevice.h                     |   2 +
 include/net/netdev_queues.h                   |   1 +
 include/net/netdev_rx_queue.h                 |   5 +
 include/net/netmem.h                          |  31 +-
 include/net/page_pool/helpers.h               |   4 +-
 include/net/page_pool/memory_provider.h       |  22 +
 include/net/page_pool/types.h                 |  24 +-
 include/net/xdp.h                             | 117 ++-
 include/net/xdp_sock.h                        |   8 +
 include/net/xsk_buff_pool.h                   |   3 +
 include/uapi/linux/if_xdp.h                   |  23 +-
 include/uapi/linux/netdev.h                   |   1 +
 net/core/dev.c                                |  56 +-
 net/core/filter.c                             |  46 +-
 net/core/netdev_rx_queue.c                    |  51 +-
 net/core/page_pool.c                          |  71 +-
 net/core/xdp.c                                |  55 ++
 net/ethtool/rings.c                           |   5 +-
 net/xdp/Kconfig                               |   1 +
 net/xdp/Makefile                              |   2 +-
 net/xdp/xdp_umem.c                            |   5 +
 net/xdp/xsk.c                                 | 110 ++-
 net/xdp/xsk_buff_pool.c                       |  38 +-
 net/xdp/xsk_mp.c                              | 900 ++++++++++++++++++
 net/xdp/xsk_mp.h                              |  21 +
 tools/include/uapi/linux/if_xdp.h             |  23 +-
 tools/include/uapi/linux/netdev.h             |   1 +
 tools/testing/selftests/drivers/net/xsk.py    |  28 +-
 .../testing/selftests/net/lib/xsk/test_xsk.c  | 556 ++++++++++-
 .../testing/selftests/net/lib/xsk/test_xsk.h  |   9 +
 .../selftests/net/lib/xsk/xskxceiver.c        |  57 +-
 40 files changed, 2659 insertions(+), 126 deletions(-)
 create mode 100644 net/xdp/xsk_mp.c
 create mode 100644 net/xdp/xsk_mp.h


base-commit: e5ba10df689a988da8480e4f3e2a6cd88a506f97
-- 
2.56.1


^ permalink raw reply	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 01/15] xdp: Let memory providers expose net_iovs to XDP
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 02/15] net: Add memory providers that only feed XDP Björn Töpel
                   ` (13 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

Currently, the address helpers give NULL for net_iovs, so XDP cannot
read them. The AF_XDP provider later in this series backs net_iovs
with UMEM chunks that XDP must read. As for io_uring zcrx, these are
user pages pinned with GUP, whose struct page fields mm owns, so they
cannot be page_pool pages.

Let a net_iov area offer an XDP view, an address per net_iov that XDP
may read and write. Add xdp_netmem_address() and xdp_frag_address()
for drivers and the BPF helpers. They give NULL for a net_iov without
a view.

The stack still treats every net_iov as unreadable, so other readers
get NULL and fail closed. Such buffers must never become skb frags or
xdp_frames.

Providers still block native XDP and need header split until the next
patch adds MP_XDP_ONLY.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Rename from "xdp: Let memory providers offer XDP a view of their
      net_iovs".
    - Name the provider by what it does, AF_XDP with explicit chunk
      return, and say that MP_XDP_ONLY comes with the next patch.
    - Bring the comment on unreadable XDP frags up to date, as XDP reads
      such frags through the view of their provider (Sashiko).

 include/net/netmem.h |  8 ++++++++
 include/net/xdp.h    | 47 +++++++++++++++++++++++++++++++++++++++++---
 net/core/filter.c    |  8 ++++----
 3 files changed, 56 insertions(+), 7 deletions(-)

diff --git a/include/net/netmem.h b/include/net/netmem.h
index fb693bc1702a..4cf4ee1cd55d 100644
--- a/include/net/netmem.h
+++ b/include/net/netmem.h
@@ -104,6 +104,14 @@ struct net_iov_area {
 	/* Array of net_iovs for this area. */
 	struct net_iov *niovs;
 	size_t num_niovs;
+	/* XDP view, see xdp_netmem_address(): XDP may read and write net_iov i
+	 * at xdp_vaddr + (i << xdp_shift), xdp_vsize bytes in all. NULL if the
+	 * provider offers none. The core and the stack take every net_iov as
+	 * unreadable either way.
+	 */
+	void *xdp_vaddr;
+	size_t xdp_vsize;
+	unsigned int xdp_shift;
 };
 
 static inline struct net_iov_area *net_iov_owner(const struct net_iov *niov)
diff --git a/include/net/xdp.h b/include/net/xdp.h
index 052402766988..da4bb98fceeb 100644
--- a/include/net/xdp.h
+++ b/include/net/xdp.h
@@ -80,9 +80,10 @@ enum xdp_buff_flags {
 	XDP_FLAGS_FRAGS_PF_MEMALLOC	= BIT(1), /* xdp paged memory is under
 						   * pressure
 						   */
-	/* frags have unreadable mem, this can't be true for real XDP packets,
-	 * but drivers may use XDP helpers to construct Rx pkt state even when
-	 * XDP program is not attached.
+	/* frags have memory that the stack cannot read, as every net_iov
+	 * has. XDP reads such frags only through the XDP view of their
+	 * provider, see xdp_netmem_address(). Drivers may use XDP helpers to
+	 * construct Rx pkt state even when XDP program is not attached.
 	 */
 	XDP_FLAGS_FRAGS_UNREADABLE	= BIT(2),
 	/* The shared info lives in &xdp_rxq_info.ext_sinfo, not at the end of
@@ -175,6 +176,46 @@ xdp_init_buff(struct xdp_buff *xdp, u32 frame_sz, struct xdp_rxq_info *rxq)
 #endif
 }
 
+/* XDP view of net_iovs: a memory provider may give XDP an address for its
+ * net_iovs, see &net_iov_area.xdp_vaddr. XDP code may read and write a
+ * net_iov only through these helpers, and only if its provider offers a
+ * view; such buffers must not become skb frags or xdp_frames. For the core
+ * and the stack every net_iov stays unreadable: netmem_address() and
+ * skb_frag_address() give NULL for it. A net_iov without a view gives NULL
+ * here too, so a reader that does not use these helpers fails closed.
+ */
+static __always_inline void *xdp_net_iov_address(const struct net_iov *niov)
+{
+	const struct net_iov_area *area = net_iov_owner(niov);
+
+	if (!area->xdp_vaddr)
+		return NULL;
+	return area->xdp_vaddr +
+	       ((unsigned long)net_iov_idx(niov) << area->xdp_shift);
+}
+
+/* Address of @netmem, which a driver uses as the head of an XDP buffer */
+static __always_inline void *xdp_netmem_address(netmem_ref netmem)
+{
+	if (netmem_is_net_iov(netmem))
+		return xdp_net_iov_address(netmem_to_net_iov(netmem));
+	return __netmem_address(netmem);
+}
+
+/* Address of the bytes of @frag of an XDP buffer */
+static __always_inline void *xdp_frag_address(const skb_frag_t *frag)
+{
+	netmem_ref netmem = skb_frag_netmem(frag);
+	void *addr;
+
+	/* Only a net_iov can lack an address */
+	if (!netmem_is_net_iov(netmem))
+		return __netmem_address(netmem) + skb_frag_off(frag);
+
+	addr = xdp_net_iov_address(netmem_to_net_iov(netmem));
+	return addr ? addr + skb_frag_off(frag) : NULL;
+}
+
 static __always_inline void
 xdp_prepare_buff(struct xdp_buff *xdp, unsigned char *hard_start,
 		 int headroom, int data_len, const bool meta_valid)
diff --git a/net/core/filter.c b/net/core/filter.c
index 1ebc2fab7211..90e4bf78c689 100644
--- a/net/core/filter.c
+++ b/net/core/filter.c
@@ -4311,7 +4311,7 @@ void bpf_xdp_copy_buf(struct xdp_buff *xdp, unsigned long off,
 			break;
 
 		ptr_off += ptr_len;
-		ptr_buf = skb_frag_address(next_frag);
+		ptr_buf = xdp_frag_address(next_frag);
 		ptr_len = skb_frag_size(next_frag);
 		next_frag++;
 	}
@@ -4339,7 +4339,7 @@ void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len)
 		u32 frag_size = skb_frag_size(&sinfo->frags[i]);
 
 		if  (offset < frag_size) {
-			addr = skb_frag_address(&sinfo->frags[i]);
+			addr = xdp_frag_address(&sinfo->frags[i]);
 			size = frag_size;
 			break;
 		}
@@ -4430,7 +4430,7 @@ static int bpf_xdp_frags_increase_tail(struct xdp_buff *xdp, int offset)
 	if (unlikely(offset > tailroom))
 		return -EINVAL;
 
-	memset(skb_frag_address(frag) + skb_frag_size(frag), 0, offset);
+	memset(xdp_frag_address(frag) + skb_frag_size(frag), 0, offset);
 	skb_frag_size_add(frag, offset);
 	sinfo->xdp_frags_size += offset;
 	if (rxq->mem.type == MEM_TYPE_XSK_BUFF_POOL)
@@ -12846,7 +12846,7 @@ __bpf_kfunc int bpf_xdp_pull_data(struct xdp_md *x, u32 len)
 		skb_frag_t *frag = &sinfo->frags[i];
 		u32 shrink = min_t(u32, delta, skb_frag_size(frag));
 
-		memcpy(xdp->data_end, skb_frag_address(frag), shrink);
+		memcpy(xdp->data_end, xdp_frag_address(frag), shrink);
 
 		xdp->data_end += shrink;
 		sinfo->xdp_frags_size -= shrink;
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 02/15] net: Add memory providers that only feed XDP
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 01/15] xdp: Let memory providers expose net_iovs to XDP Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 03/15] page_pool: Let memory providers take back net_iovs Björn Töpel
                   ` (12 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

So far, the core requires header split for memory providers and
refuses native XDP next to them, as they serve payload to the stack.
The AF_XDP provider later in this series feeds only XDP.

Let a provider declare itself XDP-only with MP_XDP_ONLY, which lifts
both rules. Drivers opt in with PP_FLAG_ALLOW_XDP_ONLY_NETMEM, and the
install fails on others.

The provider takes no lock. With the flag, the driver lets one context
at a time use the queue's buffers, its NAPI or an operation that runs
only while that NAPI cannot use the rings. It runs that NAPI once
after the queue starts, so that a queue that starts with FILL empty
asks for a wakeup, and passes the buffers only to the queue's AF_XDP
socket.

Add netif_rxq_has_xdp_only_mp() for drivers that size a queue before
its page pools exist.

Until now, classic zero copy could not bind next to any provider of
the device. Refuse it only next to providers that block native XDP.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Fold in v1 patch 11, netif_rxq_has_xdp_only_mp(), which drivers
      call before the page pools of a queue exist.
    - Refuse classic zero copy, also through netkit, only next to
      providers that block native XDP, so that it binds next to an
      XDP-only provider on another queue of the device, in either order
      (Sashiko).
    - Say that the private data of such a provider starts with its
      net_iov area, and that a driver that sets the flag lets one context
      at a time use the buffers of the queue and runs its NAPI once after
      a start, as the provider takes no lock.
    - Say in a comment that the core counts an XDP-only provider as
      unreadable.

 drivers/net/netkit.c                    |  2 +-
 include/linux/netdevice.h               |  1 +
 include/net/netdev_queues.h             |  1 +
 include/net/page_pool/helpers.h         |  4 +-
 include/net/page_pool/memory_provider.h | 19 +++++++++
 include/net/page_pool/types.h           | 23 ++++++++++-
 net/core/dev.c                          | 21 +++++++++-
 net/core/netdev_rx_queue.c              | 51 +++++++++++++++++++++----
 net/core/page_pool.c                    | 16 ++++++--
 net/ethtool/rings.c                     |  5 ++-
 net/xdp/xsk_buff_pool.c                 |  2 +-
 11 files changed, 126 insertions(+), 19 deletions(-)

diff --git a/drivers/net/netkit.c b/drivers/net/netkit.c
index 82e608e733d9..b1f8e3b9292a 100644
--- a/drivers/net/netkit.c
+++ b/drivers/net/netkit.c
@@ -289,7 +289,7 @@ static int netkit_xsk(struct net_device *dev, struct netdev_bpf *xdp)
 		ret = -EOPNOTSUPP;
 		goto out;
 	}
-	if (!create || !dev_get_min_mp_channel_count(phys))
+	if (!create || !dev_mp_blocks_xdp(phys))
 		ret = phys->netdev_ops->ndo_bpf(phys, &xdp_lower);
 out:
 	netdev_unlock(phys);
diff --git a/include/linux/netdevice.h b/include/linux/netdevice.h
index 694b6d29f680..9e542d793df7 100644
--- a/include/linux/netdevice.h
+++ b/include/linux/netdevice.h
@@ -4459,6 +4459,7 @@ u8 dev_xdp_sb_prog_count(struct net_device *dev);
 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode);
 
 u32 dev_get_min_mp_channel_count(const struct net_device *dev);
+bool dev_mp_blocks_xdp(const struct net_device *dev);
 
 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb);
 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb);
diff --git a/include/net/netdev_queues.h b/include/net/netdev_queues.h
index c5335e935b7d..813388778797 100644
--- a/include/net/netdev_queues.h
+++ b/include/net/netdev_queues.h
@@ -235,6 +235,7 @@ void netdev_queue_config(struct net_device *dev, int rxq,
 			 struct netdev_queue_config *qcfg);
 
 bool netif_rxq_has_unreadable_mp(struct net_device *dev, unsigned int rxq_idx);
+bool netif_rxq_has_xdp_only_mp(struct net_device *dev, unsigned int rxq_idx);
 
 /**
  * DOC: Lockless queue stopping / waking helpers.
diff --git a/include/net/page_pool/helpers.h b/include/net/page_pool/helpers.h
index 28635ce9454e..e3cca0a8efa1 100644
--- a/include/net/page_pool/helpers.h
+++ b/include/net/page_pool/helpers.h
@@ -513,7 +513,9 @@ static inline void page_pool_nid_changed(struct page_pool *pool, int new_nid)
  * kernel. This will only be the case if user space bound a memory provider (mp)
  * which returns unreadable memory to the queue served by the page pool.
  * If %PP_FLAG_ALLOW_UNREADABLE_NETMEM was set but there is no mp bound
- * this helper will return false. See also netif_rxq_has_unreadable_mp().
+ * this helper will return false. An XDP-only mp is unreadable here too,
+ * though netif_rxq_has_unreadable_mp() leaves it out, as its queue needs
+ * no header split.
  *
  * Return: true if memory allocated by the page pool may be unreadable
  */
diff --git a/include/net/page_pool/memory_provider.h b/include/net/page_pool/memory_provider.h
index bceb5f7740e2..ae300f9504d0 100644
--- a/include/net/page_pool/memory_provider.h
+++ b/include/net/page_pool/memory_provider.h
@@ -19,6 +19,24 @@ struct sk_buff;
  * Per-provider custom logic must be delegated to memory_provider_ops rather
  * than handled directly in page_pool core code.
  */
+
+/**
+ * enum mp_flags - how a memory provider differs from the default
+ * @MP_XDP_ONLY: Only XDP consumes the buffers: they never reach the stack.
+ *	They back the RX page pools of the queue that set
+ *	%PP_FLAG_ALLOW_XDP_ONLY_NETMEM, so header split is not needed, and
+ *	native XDP may run next to them.
+ *	XDP may read them, but userspace may write them at any time,
+ *	so the kernel must keep its own data out of them.
+ *	The core finds the &net_iov_area of such a provider at the start
+ *	of &page_pool.mp_priv, which must point to a struct that begins
+ *	with one. The driver uses the buffers of the queue from one
+ *	context at a time, see %PP_FLAG_ALLOW_XDP_ONLY_NETMEM.
+ */
+enum mp_flags {
+	MP_XDP_ONLY		= BIT(0),
+};
+
 struct memory_provider_ops {
 	netmem_ref (*alloc_netmems)(struct page_pool *pool, gfp_t gfp);
 	bool (*release_netmem)(struct page_pool *pool, netmem_ref netmem);
@@ -27,6 +45,7 @@ struct memory_provider_ops {
 	int (*nl_fill)(void *mp_priv, struct sk_buff *rsp,
 		       struct netdev_rx_queue *rxq);
 	void (*uninstall)(void *mp_priv, struct netdev_rx_queue *rxq);
+	u32 flags;
 };
 
 bool net_mp_niov_set_dma_addr(struct net_iov *niov, dma_addr_t addr);
diff --git a/include/net/page_pool/types.h b/include/net/page_pool/types.h
index 5306e34105eb..c9b9b738e8ba 100644
--- a/include/net/page_pool/types.h
+++ b/include/net/page_pool/types.h
@@ -31,8 +31,27 @@
  */
 #define PP_FLAG_ALLOW_UNREADABLE_NETMEM BIT(3)
 
+/*
+ * Allow an XDP-only memory provider of the queue (%MP_XDP_ONLY) to back the
+ * pool. The driver registers the pool as the memory model of the RX queue,
+ * sets up XDP buffers with xdp_prepare_buff() at xdp_netmem_address() of
+ * their head, and puts heads back by netmem, not by address.
+ *
+ * Such a provider takes no lock, so the driver also lets one context at a
+ * time use the buffers of the queue: its NAPI, or an operation that runs
+ * only while that NAPI cannot use the rings of the queue, as a queue
+ * restart or an error recovery. It fills and drains the rings only then,
+ * runs the NAPI once after the queue starts, so that its refill can ask
+ * for a wakeup, and lets the buffers leave the driver only to the AF_XDP
+ * socket of the queue, as the core turns XDP_PASS and XDP_TX of them into
+ * drops.
+ */
+#define PP_FLAG_ALLOW_XDP_ONLY_NETMEM BIT(4)
+
 #define PP_FLAG_ALL		(PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV | \
-				 PP_FLAG_SYSTEM_POOL | PP_FLAG_ALLOW_UNREADABLE_NETMEM)
+				 PP_FLAG_SYSTEM_POOL | \
+				 PP_FLAG_ALLOW_UNREADABLE_NETMEM | \
+				 PP_FLAG_ALLOW_XDP_ONLY_NETMEM)
 
 /* Index limit to stay within PP_DMA_INDEX_BITS for DMA indices */
 #define PP_DMA_INDEX_LIMIT XA_LIMIT(1, BIT(PP_DMA_INDEX_BITS) - 1)
@@ -84,7 +103,7 @@ struct pp_alloc_cache {
  * @netdev:	netdev this pool will serve (leave as NULL if none or multiple)
  * @queue_idx:	queue idx this page_pool is being created for.
  * @flags:	PP_FLAG_DMA_MAP, PP_FLAG_DMA_SYNC_DEV, PP_FLAG_SYSTEM_POOL,
- *		PP_FLAG_ALLOW_UNREADABLE_NETMEM.
+ *		PP_FLAG_ALLOW_UNREADABLE_NETMEM, PP_FLAG_ALLOW_XDP_ONLY_NETMEM.
  */
 struct page_pool_params {
 	struct_group_tagged(page_pool_params_fast, fast,
diff --git a/net/core/dev.c b/net/core/dev.c
index b7757f91fdf9..9ca2bfedcab5 100644
--- a/net/core/dev.c
+++ b/net/core/dev.c
@@ -10666,7 +10666,7 @@ int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 			return -EBUSY;
 		}
 
-		if (dev_get_min_mp_channel_count(dev)) {
+		if (dev_mp_blocks_xdp(dev)) {
 			NL_SET_ERR_MSG(bpf->extack,
 				       "unable to propagate XDP to device using memory provider");
 			return -EBUSY;
@@ -10747,7 +10747,7 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
 				       "unable to install XDP to device using tcp-data-split");
 			return -EBUSY;
 		}
-		if (dev_get_min_mp_channel_count(dev)) {
+		if (dev_mp_blocks_xdp(dev)) {
 			NL_SET_ERR_MSG(extack,
 				       "unable to install XDP to device using memory provider");
 			return -EBUSY;
@@ -11173,6 +11173,23 @@ int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
 	return err;
 }
 
+/* Native XDP runs next to XDP-only providers only, see %MP_XDP_ONLY */
+bool dev_mp_blocks_xdp(const struct net_device *dev)
+{
+	const struct memory_provider_ops *ops;
+	unsigned int i;
+
+	netdev_assert_locked_ops_compat(dev);
+
+	for (i = 0; i < dev->real_num_rx_queues; i++) {
+		ops = dev->_rx[i].mp_params.mp_ops;
+		if (ops && !(ops->flags & MP_XDP_ONLY))
+			return true;
+	}
+
+	return false;
+}
+
 u32 dev_get_min_mp_channel_count(const struct net_device *dev)
 {
 	int i;
diff --git a/net/core/netdev_rx_queue.c b/net/core/netdev_rx_queue.c
index a7261fedd5e7..212f1b9415b3 100644
--- a/net/core/netdev_rx_queue.c
+++ b/net/core/netdev_rx_queue.c
@@ -79,15 +79,46 @@ __netif_get_rx_queue_lease(struct net_device **dev, unsigned int *rxq_idx,
 	return rxq;
 }
 
-/* See also page_pool_is_unreadable() */
+/* See also page_pool_is_unreadable(). An XDP-only provider backs the headers
+ * too, so its queue needs no header split, see %MP_XDP_ONLY.
+ */
 bool netif_rxq_has_unreadable_mp(struct net_device *dev, unsigned int rxq_idx)
 {
-	if (rxq_idx < dev->real_num_rx_queues)
-		return __netif_get_rx_queue(dev, rxq_idx)->mp_params.mp_ops;
-	return false;
+	const struct memory_provider_ops *ops;
+
+	if (rxq_idx >= dev->real_num_rx_queues)
+		return false;
+
+	ops = __netif_get_rx_queue(dev, rxq_idx)->mp_params.mp_ops;
+	return ops && !(ops->flags & MP_XDP_ONLY);
 }
 EXPORT_SYMBOL(netif_rxq_has_unreadable_mp);
 
+/**
+ * netif_rxq_has_xdp_only_mp() - whether an XDP-only provider backs an RX queue
+ * @dev: device of the queue
+ * @rxq_idx: RX queue of @dev itself, not of a lease
+ *
+ * The page pools of the queue that allow it take the provider, see
+ * %PP_FLAG_ALLOW_XDP_ONLY_NETMEM. They are created under the instance lock,
+ * which the caller holds, so they agree with the answer.
+ *
+ * Return: true if the queue has a provider with %MP_XDP_ONLY.
+ */
+bool netif_rxq_has_xdp_only_mp(struct net_device *dev, unsigned int rxq_idx)
+{
+	const struct memory_provider_ops *ops;
+
+	netdev_assert_locked(dev);
+
+	if (rxq_idx >= dev->real_num_rx_queues)
+		return false;
+
+	ops = __netif_get_rx_queue(dev, rxq_idx)->mp_params.mp_ops;
+	return ops && ops->flags & MP_XDP_ONLY;
+}
+EXPORT_SYMBOL(netif_rxq_has_xdp_only_mp);
+
 bool netif_rxq_has_mp(struct net_device *dev, unsigned int rxq_idx)
 {
 	if (rxq_idx < dev->real_num_rx_queues)
@@ -189,6 +220,7 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 			       struct netlink_ext_ack *extack)
 {
 	const struct netdev_queue_mgmt_ops *qops = dev->queue_mgmt_ops;
+	bool xdp_only = p->mp_ops->flags & MP_XDP_ONLY;
 	struct netdev_queue_config qcfg[2];
 	struct netdev_rx_queue *rxq;
 	int ret;
@@ -196,15 +228,17 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 	if (!qops)
 		return -EOPNOTSUPP;
 
-	if (dev->cfg->hds_config != ETHTOOL_TCP_DATA_SPLIT_ENABLED) {
+	/* An XDP-only provider backs headers too, and runs next to XDP */
+	if (!xdp_only &&
+	    dev->cfg->hds_config != ETHTOOL_TCP_DATA_SPLIT_ENABLED) {
 		NL_SET_ERR_MSG(extack, "tcp-data-split is disabled");
 		return -EINVAL;
 	}
-	if (dev->cfg->hds_thresh) {
+	if (!xdp_only && dev->cfg->hds_thresh) {
 		NL_SET_ERR_MSG(extack, "hds-thresh is not zero");
 		return -EINVAL;
 	}
-	if (dev_xdp_prog_count(dev)) {
+	if (!xdp_only && dev_xdp_prog_count(dev)) {
 		NL_SET_ERR_MSG(extack, "unable to custom memory provider to device with XDP program attached");
 		return -EEXIST;
 	}
@@ -219,7 +253,8 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		return -EEXIST;
 	}
 #ifdef CONFIG_XDP_SOCKETS
-	if (rxq->pool) {
+	/* Only the AF_XDP socket of the queue installs an XDP-only provider */
+	if (rxq->pool && !xdp_only) {
 		NL_SET_ERR_MSG(extack, "designated queue already in use by AF_XDP");
 		return -EBUSY;
 	}
diff --git a/net/core/page_pool.c b/net/core/page_pool.c
index d7c88c0b67e5..8a1ea21ccdcd 100644
--- a/net/core/page_pool.c
+++ b/net/core/page_pool.c
@@ -272,12 +272,22 @@ static int page_pool_init(struct page_pool *pool,
 
 	xa_init_flags(&pool->dma_mapped, XA_FLAGS_ALLOC1);
 
-	if (pool->slow.flags & PP_FLAG_ALLOW_UNREADABLE_NETMEM) {
+	if (pool->slow.flags & (PP_FLAG_ALLOW_UNREADABLE_NETMEM |
+				PP_FLAG_ALLOW_XDP_ONLY_NETMEM)) {
+		const struct memory_provider_ops *ops;
+		u32 allow;
+
 		netdev_assert_locked(pool->slow.netdev);
 		rxq = __netif_get_rx_queue(pool->slow.netdev,
 					   pool->slow.queue_idx);
-		pool->mp_priv = rxq->mp_params.mp_priv;
-		pool->mp_ops = rxq->mp_params.mp_ops;
+		ops = rxq->mp_params.mp_ops;
+		allow = ops && ops->flags & MP_XDP_ONLY ?
+			PP_FLAG_ALLOW_XDP_ONLY_NETMEM :
+			PP_FLAG_ALLOW_UNREADABLE_NETMEM;
+		if (pool->slow.flags & allow) {
+			pool->mp_priv = rxq->mp_params.mp_priv;
+			pool->mp_ops = ops;
+		}
 	}
 
 	if (pool->mp_ops) {
diff --git a/net/ethtool/rings.c b/net/ethtool/rings.c
index e3810c0320e3..84ba17412a40 100644
--- a/net/ethtool/rings.c
+++ b/net/ethtool/rings.c
@@ -258,7 +258,10 @@ ethnl_set_rings(struct ethnl_req_info *req_info, struct genl_info *info)
 		return -EINVAL;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
+	/* Providers that take the payload need header split. XDP-only
+	 * providers back whole packets: they neither need it nor block XDP.
+	 */
+	if (dev_mp_blocks_xdp(dev)) {
 		if (kernel_ringparam.tcp_data_split !=
 		    ETHTOOL_TCP_DATA_SPLIT_ENABLED) {
 			NL_SET_ERR_MSG(info->extack,
diff --git a/net/xdp/xsk_buff_pool.c b/net/xdp/xsk_buff_pool.c
index 28bdc63551bf..d707fb308001 100644
--- a/net/xdp/xsk_buff_pool.c
+++ b/net/xdp/xsk_buff_pool.c
@@ -244,7 +244,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 		goto err_unreg_pool;
 	}
 
-	if (dev_get_min_mp_channel_count(netdev)) {
+	if (dev_mp_blocks_xdp(netdev)) {
 		err = -EBUSY;
 		goto err_unreg_pool;
 	}
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 03/15] page_pool: Let memory providers take back net_iovs
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 01/15] xdp: Let memory providers expose net_iovs to XDP Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 02/15] net: Add memory providers that only feed XDP Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 04/15] xdp: Run programs on XDP-only buffers Björn Töpel
                   ` (11 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

Currently, a provider learns of the last put of a net_iov only through
its release hook, which takes the net_iov out of its page pool. The
AF_XDP provider later in this series must see that put, as it returns
a chunk to userspace only once the device is done with it too.

Let a provider mark a net_iov so that its last put goes to the
provider's new hand_off() instead of the page pool cache. It may
decline, never runs in hard IRQ context, and for an XDP-only pool runs
in the one context that uses the queue's buffers. The cached net_iovs
of a pool that goes away are unmarked and never reach the provider.

Let a provider also count net_iovs off their page pool and back on in
bulk, keeping their page pool info, so that net_iovs in userspace pin
no pool.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Let a provider count net_iovs that it took back off their page
      pool, and back on, in bulk (Sashiko).
    - Add a helper that tests the mark (Sashiko).
    - Say in the message that hand_off() may decline, that it never runs
      in hard IRQ context, and that for an XDP-only pool it runs in the
      one context that uses the buffers of the queue (Sashiko).
    - Make the mark a u8.

 include/net/netmem.h                    | 14 +++++++
 include/net/page_pool/memory_provider.h |  3 ++
 net/core/page_pool.c                    | 55 ++++++++++++++++++++++++-
 3 files changed, 70 insertions(+), 2 deletions(-)

diff --git a/include/net/netmem.h b/include/net/netmem.h
index 4cf4ee1cd55d..5d3ec8554fb0 100644
--- a/include/net/netmem.h
+++ b/include/net/netmem.h
@@ -97,6 +97,9 @@ enum net_iov_type {
 struct net_iov {
 	struct netmem_desc desc;
 	enum net_iov_type type;
+	u8 mp_hand_off;
+	/* Owned by the memory provider */
+	u8 mp_state;
 	struct net_iov_area *owner;
 };
 
@@ -132,6 +135,8 @@ static inline void net_iov_init(struct net_iov *niov,
 {
 	niov->owner = owner;
 	niov->type = type;
+	niov->mp_hand_off = 0;
+	niov->mp_state = 0;
 }
 
 /* netmem */
@@ -194,6 +199,15 @@ static inline struct net_iov *netmem_to_net_iov(netmem_ref netmem)
 	return NULL;
 }
 
+/* A provider takes the netmem back at its last put, see
+ * &memory_provider_ops.hand_off. Never true for pages.
+ */
+static inline bool netmem_mp_hand_off(netmem_ref netmem)
+{
+	return netmem_is_net_iov(netmem) &&
+	       netmem_to_net_iov(netmem)->mp_hand_off;
+}
+
 static inline netmem_ref net_iov_to_netmem(struct net_iov *niov)
 {
 	return (__force netmem_ref)((unsigned long)niov | NET_IOV);
diff --git a/include/net/page_pool/memory_provider.h b/include/net/page_pool/memory_provider.h
index ae300f9504d0..38bf292b8505 100644
--- a/include/net/page_pool/memory_provider.h
+++ b/include/net/page_pool/memory_provider.h
@@ -40,6 +40,7 @@ enum mp_flags {
 struct memory_provider_ops {
 	netmem_ref (*alloc_netmems)(struct page_pool *pool, gfp_t gfp);
 	bool (*release_netmem)(struct page_pool *pool, netmem_ref netmem);
+	bool (*hand_off)(struct page_pool *pool, netmem_ref netmem);
 	int (*init)(struct page_pool *pool);
 	void (*destroy)(struct page_pool *pool);
 	int (*nl_fill)(void *mp_priv, struct sk_buff *rsp,
@@ -51,6 +52,8 @@ struct memory_provider_ops {
 bool net_mp_niov_set_dma_addr(struct net_iov *niov, dma_addr_t addr);
 void net_mp_niov_set_page_pool(struct page_pool *pool, struct net_iov *niov);
 void net_mp_niov_clear_page_pool(struct net_iov *niov);
+void net_mp_release_page_pool(struct page_pool *pool, u32 nr);
+void net_mp_hold_page_pool(struct page_pool *pool, u32 nr);
 
 int netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		      const struct pp_memory_provider_params *p,
diff --git a/net/core/page_pool.c b/net/core/page_pool.c
index 8a1ea21ccdcd..03a03074e49c 100644
--- a/net/core/page_pool.c
+++ b/net/core/page_pool.c
@@ -840,6 +840,15 @@ static bool __page_pool_page_can_be_recycled(netmem_ref netmem)
 		!page_is_pfmemalloc(netmem_to_page(netmem)));
 }
 
+/* A memory provider takes back a free net_iov it marked, see
+ * &memory_provider_ops.hand_off
+ */
+static bool page_pool_hand_off(struct page_pool *pool, netmem_ref netmem)
+{
+	return unlikely(netmem_mp_hand_off(netmem)) &&
+	       pool->mp_ops->hand_off(pool, netmem);
+}
+
 /* If the page refcnt == 1, this will try to recycle the page.
  * If pool->dma_sync is set, we'll try to sync the DMA area for
  * the configured size min(dma_sync_size, pool->max_len).
@@ -852,6 +861,10 @@ __page_pool_put_page(struct page_pool *pool, netmem_ref netmem,
 {
 	lockdep_assert_no_hardirq();
 
+	/* The provider takes the net_iovs it marked */
+	if (page_pool_hand_off(pool, netmem))
+		return 0;
+
 	/* This allocator is optimized for the XDP mode that uses
 	 * one-frame-per-page, but have fallbacks that act like the
 	 * regular page allocator APIs.
@@ -1051,6 +1064,9 @@ static netmem_ref page_pool_drain_frag(struct page_pool *pool,
 	if (likely(page_pool_unref_netmem(netmem, drain_count)))
 		return 0;
 
+	if (page_pool_hand_off(pool, netmem))
+		return 0;
+
 	if (__page_pool_page_can_be_recycled(netmem)) {
 		page_pool_dma_sync_for_device(pool, netmem, -1);
 		return netmem;
@@ -1067,7 +1083,8 @@ static void page_pool_free_frag(struct page_pool *pool)
 
 	pool->frag_page = 0;
 
-	if (!netmem || page_pool_unref_netmem(netmem, drain_count))
+	if (!netmem || page_pool_unref_netmem(netmem, drain_count) ||
+	    page_pool_hand_off(pool, netmem))
 		return;
 
 	page_pool_return_netmem(pool, netmem);
@@ -1351,7 +1368,8 @@ bool net_mp_niov_set_dma_addr(struct net_iov *niov, dma_addr_t addr)
 }
 
 /* Associate a niov with a page pool. Should follow with a matching
- * net_mp_niov_clear_page_pool()
+ * net_mp_niov_clear_page_pool(), or net_mp_release_page_pool() for a niov
+ * that its provider takes back, see &memory_provider_ops.hand_off
  */
 void net_mp_niov_set_page_pool(struct page_pool *pool, struct net_iov *niov)
 {
@@ -1372,3 +1390,36 @@ void net_mp_niov_clear_page_pool(struct net_iov *niov)
 
 	page_pool_clear_pp_info(netmem);
 }
+
+/**
+ * net_mp_release_page_pool() - account niovs that left their page pool
+ * @pool: page pool that the niovs were taken from
+ * @nr: number of niovs
+ *
+ * Accounts @nr free niovs that only the provider holds, as a hand-off
+ * leaves them, as released from @pool, as page_pool_return_netmem() would,
+ * without calling the provider. They keep their page pool info: the
+ * provider gives them to a page pool again with net_mp_niov_set_page_pool(),
+ * or to @pool with net_mp_hold_page_pool(). Not traced per niov.
+ *
+ * @pool may go away at once, as the niovs may have been its last.
+ */
+void net_mp_release_page_pool(struct page_pool *pool, u32 nr)
+{
+	atomic_add(nr, &pool->pages_state_release_cnt);
+}
+
+/**
+ * net_mp_hold_page_pool() - account niovs that their page pool takes again
+ * @pool: page pool whose info the niovs still have
+ * @nr: number of niovs
+ *
+ * Accounts @nr niovs that net_mp_release_page_pool() released from @pool as
+ * held by @pool again, as net_mp_niov_set_page_pool() would. Called where
+ * @pool allocates, from &memory_provider_ops.alloc_netmems. Not traced per
+ * niov.
+ */
+void net_mp_hold_page_pool(struct page_pool *pool, u32 nr)
+{
+	pool->pages_state_hold_cnt += nr;
+}
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 04/15] xdp: Run programs on XDP-only buffers
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (2 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 03/15] page_pool: Let memory providers take back net_iovs Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 05/15] xsk: Back a queue's page pools with UMEM chunks Björn Töpel
                   ` (10 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

The AF_XDP provider needs native XDP to steer packets and for the RX
metadata kfuncs. XDP reads its UMEM chunks through the kernel mapping,
but userspace may write them at any time. Currently, multi-buffer
shared info, XDP_TX and redirect frames, and XDP_PASS skbs live in the
buffer.

Run programs on such XDP-only buffers, but keep kernel structures out
of them.

The core tells an XDP-only head by its address, with one range check
under a static key, so other buffers pay nothing while no provider is
bound. Such a buffer keeps its shared info in the provider.
Registering such a page pool without its RX queue fails with
-EOPNOTSUPP.

The core turns XDP_TX and XDP_PASS of these buffers into XDP_DROP, so
drivers need no checks. Frame and skb construction refuse these
buffers, so devmap and cpumap drop them.

The kernel takes bounds only from its own fields, and a helper that
reads bytes twice must check a copy.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Rename from "xdp: Run programs on buffers that must not hold kernel
      structures".
    - Keep the shared info of XDP-only buffers in the provider, with the
      queue only pointing to it. In v1 the queue owned it, which breaks
      for drivers that copy their queue info.
    - Take the frame and skb refusals of v1 patch 2. The rest of that
      patch went to net as a series of its own, which covers classic zero
      copy too (Maciej). The frame and skb paths of classic zero copy stay
      as they are.
    - XDP_PASS and XDP_TX stay drops in this posting. A follow-up adds
      them as copies (Maciej).
    - Call the buffers XDP-only rather than sink buffers, also in the
      names of their flag, test and static key.

 include/net/netmem.h          |  9 ++++-
 include/net/page_pool/types.h |  7 ++--
 include/net/xdp.h             | 70 ++++++++++++++++++++++++++++++++++-
 net/core/xdp.c                | 55 +++++++++++++++++++++++++++
 4 files changed, 135 insertions(+), 6 deletions(-)

diff --git a/include/net/netmem.h b/include/net/netmem.h
index 5d3ec8554fb0..9a3994fb12ab 100644
--- a/include/net/netmem.h
+++ b/include/net/netmem.h
@@ -68,6 +68,7 @@ DECLARE_STATIC_KEY_FALSE(page_pool_mem_providers);
 enum net_iov_type {
 	NET_IOV_DMABUF,
 	NET_IOV_IOURING,
+	NET_IOV_XSK,
 };
 
 /* A memory descriptor representing abstract networking I/O vectors.
@@ -81,7 +82,9 @@ enum net_iov_type {
  * CPU-readable or unreadable. New code must not assume net_iov implies
  * unreadable memory (check readability via netmem_address() or
  * skb_frags_readable() instead) and should, as much as possible, generalize
- * existing limitations to match the design principles.
+ * existing limitations to match the design principles. AF_XDP memory provider
+ * net_iovs (%NET_IOV_XSK) are unreadable for the core and the stack as well:
+ * only XDP reads them, through their XDP view (&net_iov_area.xdp_vaddr).
  *
  * @pp_magic:	pp field, similar to the one in struct page/struct
  *		netmem_desc.
@@ -115,6 +118,10 @@ struct net_iov_area {
 	void *xdp_vaddr;
 	size_t xdp_vsize;
 	unsigned int xdp_shift;
+	/* Shared info of the XDP buffers of an MP_XDP_ONLY provider, in its
+	 * kernel memory, see %XDP_FLAGS_SINFO_EXT
+	 */
+	struct skb_shared_info *xdp_sinfo;
 };
 
 static inline struct net_iov_area *net_iov_owner(const struct net_iov *niov)
diff --git a/include/net/page_pool/types.h b/include/net/page_pool/types.h
index c9b9b738e8ba..4172e9aee28f 100644
--- a/include/net/page_pool/types.h
+++ b/include/net/page_pool/types.h
@@ -33,9 +33,10 @@
 
 /*
  * Allow an XDP-only memory provider of the queue (%MP_XDP_ONLY) to back the
- * pool. The driver registers the pool as the memory model of the RX queue,
- * sets up XDP buffers with xdp_prepare_buff() at xdp_netmem_address() of
- * their head, and puts heads back by netmem, not by address.
+ * pool. The driver registers the pool as the memory model of the RX queue
+ * with xdp_rxq_info_reg_mem_model(), sets up XDP buffers with
+ * xdp_prepare_buff() at xdp_netmem_address() of their head, and puts heads
+ * back by netmem, not by address.
  *
  * Such a provider takes no lock, so the driver also lets one context at a
  * time use the buffers of the queue: its NAPI, or an operation that runs
diff --git a/include/net/xdp.h b/include/net/xdp.h
index da4bb98fceeb..077d4b4b2614 100644
--- a/include/net/xdp.h
+++ b/include/net/xdp.h
@@ -65,8 +65,13 @@ struct xdp_rxq_info {
 	u32 reg_state;
 	struct xdp_mem_info mem;
 	u32 frag_size;
+	/* Area of the MP_XDP_ONLY provider of the page pool, see
+	 * xdp_mark_xdp_only()
+	 */
+	struct net_iov_area *xdp_only_area;
 	/* Shared info of buffers with %XDP_FLAGS_SINFO_EXT, in the XSk buffer
-	 * pool, set by xsk_pool_set_rxq_info().
+	 * pool, set by xsk_pool_set_rxq_info(), or where an XDP-only memory
+	 * provider keeps it, set by xdp_rxq_info_reg_mem_model()
 	 */
 	struct skb_shared_info *ext_sinfo;
 } ____cacheline_aligned; /* perf critical, avoid false-sharing */
@@ -93,6 +98,15 @@ enum xdp_buff_flags {
 	 * must copy what it needs.
 	 */
 	XDP_FLAGS_SINFO_EXT		= BIT(3),
+	/* XDP-only memory, see %MP_XDP_ONLY: the buffer may only go to the
+	 * AF_XDP socket of its queue. Userspace may write it at any time,
+	 * also while the kernel reads it. So the kernel takes bounds only
+	 * from its own fields, and only the XDP program and its helpers read
+	 * the bytes. A helper that checks bytes and reads them again later
+	 * must check a copy. Nothing builds a frame or an skb in the
+	 * buffer.
+	 */
+	XDP_FLAGS_MP_XDP_ONLY		= BIT(4),
 };
 
 struct xdp_buff {
@@ -148,6 +162,14 @@ static __always_inline void xdp_buff_set_frag_unreadable(struct xdp_buff *xdp)
 	xdp->flags |= XDP_FLAGS_FRAGS_UNREADABLE;
 }
 
+static __always_inline bool xdp_buff_is_xdp_only(const struct xdp_buff *xdp)
+{
+	return !!(xdp->flags & XDP_FLAGS_MP_XDP_ONLY);
+}
+
+/* Enabled while an AF_XDP socket receives with explicit return */
+DECLARE_STATIC_KEY_FALSE(xdp_only_mp_key);
+
 static __always_inline u32 xdp_buff_get_skb_flags(const struct xdp_buff *xdp)
 {
 	return xdp->flags;
@@ -176,6 +198,26 @@ xdp_init_buff(struct xdp_buff *xdp, u32 frame_sz, struct xdp_rxq_info *rxq)
 #endif
 }
 
+/* Drivers take the address of a head buffer with xdp_netmem_address(),
+ * which for an AF_XDP memory provider lies in its XDP view, the UMEM, see
+ * &net_iov_area.xdp_vaddr. Mark such buffers before the driver adds
+ * fragments: their shared info lives in the queue, and they may only go to
+ * the AF_XDP socket of the queue.
+ */
+static __always_inline void xdp_mark_xdp_only(struct xdp_buff *xdp)
+{
+	struct net_iov_area *area = xdp->rxq->xdp_only_area;
+	unsigned long off;
+
+	off = (u8 *)xdp->data_hard_start - (u8 *)area->xdp_vaddr;
+	/* A byte-wide update would leave the next load of the flags two
+	 * stores to merge, which x86 cannot forward
+	 */
+	if (off < area->xdp_vsize)
+		WRITE_ONCE(xdp->flags, xdp->flags | XDP_FLAGS_MP_XDP_ONLY |
+				       XDP_FLAGS_SINFO_EXT);
+}
+
 /* XDP view of net_iovs: a memory provider may give XDP an address for its
  * net_iovs, see &net_iov_area.xdp_vaddr. XDP code may read and write a
  * net_iov only through these helpers, and only if its provider offers a
@@ -216,6 +258,9 @@ static __always_inline void *xdp_frag_address(const skb_frag_t *frag)
 	return addr ? addr + skb_frag_off(frag) : NULL;
 }
 
+/* Marks XDP-only buffers in @xdp->flags too: call it after
+ * xdp_init_buff(), which clears the flags
+ */
 static __always_inline void
 xdp_prepare_buff(struct xdp_buff *xdp, unsigned char *hard_start,
 		 int headroom, int data_len, const bool meta_valid)
@@ -226,6 +271,10 @@ xdp_prepare_buff(struct xdp_buff *xdp, unsigned char *hard_start,
 	xdp->data = data;
 	xdp->data_end = data + data_len;
 	xdp->data_meta = meta_valid ? data : data + 1;
+
+	if (static_branch_unlikely(&xdp_only_mp_key) && xdp->rxq &&
+	    unlikely(xdp->rxq->xdp_only_area))
+		xdp_mark_xdp_only(xdp);
 }
 
 /* Reserve memory area at end-of data area.
@@ -351,8 +400,12 @@ static inline bool xdp_buff_add_frag(struct xdp_buff *xdp, netmem_ref netmem,
 
 	if (unlikely(netmem_is_pfmemalloc(netmem)))
 		xdp_buff_set_frag_pfmemalloc(xdp);
-	if (unlikely(netmem_is_net_iov(netmem)))
+	if (unlikely(netmem_is_net_iov(netmem))) {
 		xdp_buff_set_frag_unreadable(xdp);
+		/* XDP-only memory may only go to the socket of its queue */
+		if (netmem_to_net_iov(netmem)->type == NET_IOV_XSK)
+			xdp->flags |= XDP_FLAGS_MP_XDP_ONLY;
+	}
 
 	return true;
 }
@@ -481,6 +534,13 @@ int xdp_update_frame_from_buff(const struct xdp_buff *xdp,
 		return -ENOSPC;
 	}
 
+	/* XDP-only buffers go to their AF_XDP socket, or nowhere. They
+	 * exist only while the key is on.
+	 */
+	if (static_branch_unlikely(&xdp_only_mp_key) &&
+	    xdp_buff_is_xdp_only(xdp))
+		return -EFAULT;
+
 	xdp_frame->data = xdp->data;
 	xdp_frame->len  = xdp->data_end - xdp->data;
 	xdp_frame->headroom = headroom - sizeof(*xdp_frame);
@@ -761,6 +821,12 @@ static __always_inline u32 bpf_prog_run_xdp(const struct bpf_prog *prog,
 	 */
 	u32 act = __bpf_prog_run(prog, xdp, BPF_DISPATCHER_FUNC(xdp));
 
+	/* XDP-only buffers go to the AF_XDP socket of their queue only */
+	if (static_branch_unlikely(&xdp_only_mp_key) &&
+	    xdp_buff_is_xdp_only(xdp) &&
+	    (act == XDP_PASS || act == XDP_TX))
+		act = XDP_DROP;
+
 	if (static_branch_unlikely(&bpf_master_redirect_enabled_key)) {
 		if (act == XDP_TX && netif_is_bond_slave(xdp->rxq->dev))
 			act = xdp_master_redirect(xdp);
diff --git a/net/core/xdp.c b/net/core/xdp.c
index 33a6740b411f..56b32ef795a0 100644
--- a/net/core/xdp.c
+++ b/net/core/xdp.c
@@ -15,6 +15,7 @@
 #include <linux/rhashtable.h>
 #include <linux/bug.h>
 #include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>
 
 #include <net/hotdata.h>
 #include <net/netdev_lock.h>
@@ -142,6 +143,14 @@ void xdp_rxq_info_unreg_mem_model(struct xdp_rxq_info *xdp_rxq)
 	}
 
 	xdp_unreg_mem_model(&xdp_rxq->mem);
+	/* Both belong to the provider, which may go away now. The pool of a
+	 * classic zero-copy queue owns its shared info, so leave that
+	 * pointer to xp_set_rxq_info().
+	 */
+	if (xdp_rxq->xdp_only_area) {
+		xdp_rxq->xdp_only_area = NULL;
+		xdp_rxq->ext_sinfo = NULL;
+	}
 }
 EXPORT_SYMBOL_GPL(xdp_rxq_info_unreg_mem_model);
 
@@ -332,11 +341,23 @@ static struct xdp_mem_allocator *__xdp_reg_mem_model(struct xdp_mem_info *mem,
 	return ERR_PTR(errno);
 }
 
+/* The page pool has an MP_XDP_ONLY provider */
+static bool xdp_mem_is_xdp_only(enum xdp_mem_type type, void *allocator)
+{
+	struct page_pool *pp = allocator;
+
+	return type == MEM_TYPE_PAGE_POOL && pp && pp->mp_ops &&
+	       pp->mp_ops->flags & MP_XDP_ONLY;
+}
+
 int xdp_reg_mem_model(struct xdp_mem_info *mem,
 		      enum xdp_mem_type type, void *allocator)
 {
 	struct xdp_mem_allocator *xdp_alloc;
 
+	if (xdp_mem_is_xdp_only(type, allocator))
+		return -EOPNOTSUPP;
+
 	xdp_alloc = __xdp_reg_mem_model(mem, type, allocator);
 	if (IS_ERR(xdp_alloc))
 		return PTR_ERR(xdp_alloc);
@@ -344,16 +365,30 @@ int xdp_reg_mem_model(struct xdp_mem_info *mem,
 }
 EXPORT_SYMBOL_GPL(xdp_reg_mem_model);
 
+DEFINE_STATIC_KEY_FALSE(xdp_only_mp_key);
+EXPORT_SYMBOL_GPL(xdp_only_mp_key);
+
 int xdp_rxq_info_reg_mem_model(struct xdp_rxq_info *xdp_rxq,
 			       enum xdp_mem_type type, void *allocator)
 {
 	struct xdp_mem_allocator *xdp_alloc;
+	struct net_iov_area *area = NULL;
 
 	if (xdp_rxq->reg_state != REG_STATE_REGISTERED) {
 		WARN(1, "Missing register, driver bug");
 		return -EFAULT;
 	}
 
+	/* MP_XDP_ONLY providers put their net_iov_area first in mp_priv. As
+	 * userspace may write XDP-only buffers, the provider keeps their shared
+	 * info.
+	 */
+	if (xdp_mem_is_xdp_only(type, allocator)) {
+		area = ((struct page_pool *)allocator)->mp_priv;
+		if (WARN_ON_ONCE(!area->xdp_sinfo))
+			return -EINVAL;
+	}
+
 	xdp_alloc = __xdp_reg_mem_model(&xdp_rxq->mem, type, allocator);
 	if (IS_ERR(xdp_alloc))
 		return PTR_ERR(xdp_alloc);
@@ -361,6 +396,22 @@ int xdp_rxq_info_reg_mem_model(struct xdp_rxq_info *xdp_rxq,
 	if (type == MEM_TYPE_XSK_BUFF_POOL && allocator)
 		xsk_pool_set_rxq_info(allocator, xdp_rxq);
 
+	/* The queue only points to both, which live as long as the page
+	 * pool. Copies of the queue info need no care.
+	 */
+	xdp_rxq->xdp_only_area = area;
+	if (area) {
+		xdp_rxq->ext_sinfo = area->xdp_sinfo;
+		/* The driver publishes the queue to its buffers after this,
+		 * as mlx5 does when it starts the new channel, and a reader
+		 * of a buffer takes the queue with READ_ONCE(xdp->rxq), as
+		 * xdp_get_shared_info_from_buff() does: order the shared
+		 * info of the queue before the queue reaches a buffer, the
+		 * way xp_set_rxq_info() does for classic zero copy.
+		 */
+		smp_wmb();
+	}
+
 	if (trace_mem_connect_enabled() && xdp_alloc)
 		trace_mem_connect(xdp_alloc, xdp_rxq);
 	return 0;
@@ -638,6 +689,10 @@ struct sk_buff *xdp_build_skb_from_buff(const struct xdp_buff *xdp)
 	u32 nr_frags = 0;
 	int metalen;
 
+	/* XDP-only buffers go to their AF_XDP socket, or nowhere */
+	if (unlikely(xdp_buff_is_xdp_only(xdp)))
+		return NULL;
+
 	if (unlikely(xdp_buff_has_frags(xdp))) {
 		sinfo = xdp_get_shared_info_from_buff(xdp);
 		nr_frags = sinfo->nr_frags;
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 05/15] xsk: Back a queue's page pools with UMEM chunks
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (3 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 04/15] xdp: Run programs on XDP-only buffers Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 06/15] xsk: Deliver packets and return chunks explicitly Björn Töpel
                   ` (9 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

Currently, AF_XDP zero copy fills one chunk per buffer at the UMEM
headroom, so drivers carry a second RX path and cannot use their own
buffer layout.

Add XDP_UMEM_EXPLICIT_RETURN, under which the device lays out buffers
in chunks as in pages and chunks come back explicitly. Back the bound
queue's RX page pools with the chunks through an AF_XDP memory
provider, so drivers need no AF_XDP code.

A chunk on FILL twice or outside the UMEM is an invalid entry. A chunk
counts against the page pool that took it, and against none in
userspace. FILL needs no lock, as only the queue's NAPI, or an
operation that runs only while that NAPI cannot use the rings,
refills.

Binding needs:
- a native XDP program attached through netlink (-ENOENT), which
  cannot be detached, as drivers would build skbs on the buffers;
- CAP_NET_ADMIN in the initial user namespace (-EPERM), as the
  provider changes what the program does;
- XDP_USE_NEED_WAKEUP (-EINVAL), as a queue that drained FILL needs a
  wakeup.

XDP_COPY or XDP_ZEROCOPY fails with -EOPNOTSUPP. Page pools whose ring
and cache could hold every chunk fail with -ENOSPC.

Unbind restarts the queue without the provider, or closes the device
if that fails, as the old queue may still use the UMEM.

UMEM registration accepts the flag two patches later.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Rename from "xsk: Lend UMEM chunks to the page pools of a queue".
    - Rename XDP_UMEM_DRV_LAYOUT to XDP_UMEM_EXPLICIT_RETURN, and the sink
      to the AF_XDP memory provider in xsk_mp.c, after what changes for
      the application (Magnus).
    - Require XDP_USE_NEED_WAKEUP here, where bind is added, and drop the
      tests of whether a socket uses it (Magnus).
    - Require CAP_NET_ADMIN in the initial user namespace, and fail
      XDP_ZEROCOPY with -EOPNOTSUPP, as XDP_COPY already did. The check of
      both now sits next to the checks of the classic modes (Sashiko).
    - Charge a FILL chunk to the page pool that takes it, so that a
      restart while bound no longer leaves the new queue without buffers
      (Sashiko).
    - Refuse page pools with an init callback, as a chunk that a page pool
      takes back from FILL keeps its page pool info and would miss the
      callback.
    - Add the page-pool netlink attribute xsk, an empty nest that
      page-pool dumps show for this provider (Sashiko).
    - Keep the bind checks apart from those of classic zero copy, as
      sharing them takes more lines than it saves (Magnus).
    - Take FILL without a lock: only the owner of the queue, its NAPI or
      an operation that runs only while that NAPI cannot use the rings,
      refills, which the driver agrees to with
      PP_FLAG_ALLOW_XDP_ONLY_NETMEM.

 Documentation/netlink/specs/netdev.yaml |   8 +
 include/linux/netdevice.h               |   1 +
 include/net/xsk_buff_pool.h             |   3 +
 include/uapi/linux/if_xdp.h             |   8 +
 include/uapi/linux/netdev.h             |   1 +
 net/core/dev.c                          |  32 ++
 net/xdp/Kconfig                         |   1 +
 net/xdp/Makefile                        |   2 +-
 net/xdp/xsk_buff_pool.c                 |  36 +-
 net/xdp/xsk_mp.c                        | 443 ++++++++++++++++++++++++
 net/xdp/xsk_mp.h                        |  14 +
 tools/include/uapi/linux/if_xdp.h       |   8 +
 tools/include/uapi/linux/netdev.h       |   1 +
 13 files changed, 551 insertions(+), 7 deletions(-)
 create mode 100644 net/xdp/xsk_mp.c
 create mode 100644 net/xdp/xsk_mp.h

diff --git a/Documentation/netlink/specs/netdev.yaml b/Documentation/netlink/specs/netdev.yaml
index 0de7f93f0c4c..cf07ea7f0727 100644
--- a/Documentation/netlink/specs/netdev.yaml
+++ b/Documentation/netlink/specs/netdev.yaml
@@ -206,6 +206,13 @@ attribute-sets:
         doc: io-uring memory provider information.
         type: nest
         nested-attributes: io-uring-provider-info
+      -
+        name: xsk
+        doc: |
+          The page pool takes its buffers from the UMEM of an AF_XDP
+          socket with explicit chunk return.
+        type: nest
+        nested-attributes: xsk-info
   -
     name: page-pool-info
     subset-of: page-pool
@@ -678,6 +685,7 @@ operations:
             - detach-time
             - dmabuf
             - io-uring
+            - xsk
       dump:
         request:
           attributes:
diff --git a/include/linux/netdevice.h b/include/linux/netdevice.h
index 9e542d793df7..c1fde6420940 100644
--- a/include/linux/netdevice.h
+++ b/include/linux/netdevice.h
@@ -4460,6 +4460,7 @@ u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode);
 
 u32 dev_get_min_mp_channel_count(const struct net_device *dev);
 bool dev_mp_blocks_xdp(const struct net_device *dev);
+bool dev_xdp_drv_prog_held(struct net_device *dev);
 
 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb);
 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb);
diff --git a/include/net/xsk_buff_pool.h b/include/net/xsk_buff_pool.h
index ef4bbf7f66b9..e26162f956c4 100644
--- a/include/net/xsk_buff_pool.h
+++ b/include/net/xsk_buff_pool.h
@@ -11,6 +11,7 @@
 #include <net/xdp.h>
 
 struct xsk_buff_pool;
+struct xsk_mp;
 struct xdp_rxq_info;
 struct xsk_cb_desc;
 struct xsk_queue;
@@ -54,6 +55,8 @@ struct xsk_buff_pool {
 	spinlock_t xsk_tx_list_lock;
 	refcount_t users;
 	struct xdp_umem *umem;
+	/* RX with explicit return, see net/xdp/xsk_mp.c */
+	struct xsk_mp *mp;
 	struct work_struct work;
 	/* Protects generic receive in shared and non-shared umem mode. */
 	spinlock_t rx_lock;
diff --git a/include/uapi/linux/if_xdp.h b/include/uapi/linux/if_xdp.h
index 50d67df78911..60f01759a1d4 100644
--- a/include/uapi/linux/if_xdp.h
+++ b/include/uapi/linux/if_xdp.h
@@ -45,6 +45,14 @@
  */
 #define XDP_UMEM_TX_METADATA_LEN	(1 << 2)
 
+/* With explicit return, the kernel and the driver decide where packets
+ * land in a chunk, how many share it and the headroom: userspace only
+ * supplies chunks on FILL. An RX descriptor does not give its chunk
+ * back, and a packet may span chunks. Needs aligned page-sized chunks
+ * and no headroom.
+ */
+#define XDP_UMEM_EXPLICIT_RETURN	(1 << 4)
+
 struct sockaddr_xdp {
 	__u16 sxdp_family;
 	__u16 sxdp_flags;
diff --git a/include/uapi/linux/netdev.h b/include/uapi/linux/netdev.h
index 9026e0414fbe..0e2b4cdf1ef4 100644
--- a/include/uapi/linux/netdev.h
+++ b/include/uapi/linux/netdev.h
@@ -112,6 +112,7 @@ enum {
 	NETDEV_A_PAGE_POOL_DETACH_TIME,
 	NETDEV_A_PAGE_POOL_DMABUF,
 	NETDEV_A_PAGE_POOL_IO_URING,
+	NETDEV_A_PAGE_POOL_XSK,
 
 	__NETDEV_A_PAGE_POOL_MAX,
 	NETDEV_A_PAGE_POOL_MAX = (__NETDEV_A_PAGE_POOL_MAX - 1)
diff --git a/net/core/dev.c b/net/core/dev.c
index 9ca2bfedcab5..12e852cc3855 100644
--- a/net/core/dev.c
+++ b/net/core/dev.c
@@ -10813,6 +10813,22 @@ static void dev_xdp_uninstall(struct net_device *dev)
 	dev->xdp_from_upper = 0;
 }
 
+/* A queue of @dev has an XDP-only memory provider */
+static bool dev_has_xdp_only_mp(const struct net_device *dev)
+{
+	const struct memory_provider_ops *ops;
+	unsigned int i;
+
+	netdev_assert_locked_ops(dev);
+	for (i = 0; i < dev->real_num_rx_queues; i++) {
+		ops = dev->_rx[i].mp_params.mp_ops;
+		if (ops && ops->flags & MP_XDP_ONLY)
+			return true;
+	}
+
+	return false;
+}
+
 static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
 			  struct bpf_xdp_link *link, struct bpf_prog *new_prog,
 			  struct bpf_prog *old_prog, u32 flags)
@@ -10881,6 +10897,12 @@ static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack
 		NL_SET_ERR_MSG(extack, "Active program does not match expected");
 		return -EEXIST;
 	}
+	if (cur_prog && !new_prog && !link && mode == XDP_MODE_DRV &&
+	    dev_has_xdp_only_mp(dev)) {
+		NL_SET_ERR_MSG(extack,
+			       "An XDP-only provider needs the program");
+		return -EBUSY;
+	}
 
 	/* put effective new program into new_prog */
 	if (link)
@@ -11190,6 +11212,16 @@ bool dev_mp_blocks_xdp(const struct net_device *dev)
 	return false;
 }
 
+/* A native program is attached, and dev_xdp_attach() keeps it while an
+ * AF_XDP socket receives with explicit return on @dev. A BPF link could go
+ * without asking, and so could a program that an upper device propagated.
+ */
+bool dev_xdp_drv_prog_held(struct net_device *dev)
+{
+	return dev_xdp_prog_id(dev, XDP_MODE_DRV) &&
+	       !dev_xdp_link(dev, XDP_MODE_DRV) && !dev->xdp_from_upper;
+}
+
 u32 dev_get_min_mp_channel_count(const struct net_device *dev)
 {
 	int i;
diff --git a/net/xdp/Kconfig b/net/xdp/Kconfig
index 71af2febe72a..c9c68d3b3712 100644
--- a/net/xdp/Kconfig
+++ b/net/xdp/Kconfig
@@ -2,6 +2,7 @@
 config XDP_SOCKETS
 	bool "XDP sockets"
 	depends on BPF_SYSCALL
+	select PAGE_POOL
 	default n
 	help
 	  XDP sockets allows a channel between XDP programs and
diff --git a/net/xdp/Makefile b/net/xdp/Makefile
index 30cdc4315f42..add6c7a7dec4 100644
--- a/net/xdp/Makefile
+++ b/net/xdp/Makefile
@@ -1,4 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0-only
 obj-$(CONFIG_XDP_SOCKETS) += xsk.o xdp_umem.o xsk_queue.o xskmap.o
-obj-$(CONFIG_XDP_SOCKETS) += xsk_buff_pool.o
+obj-$(CONFIG_XDP_SOCKETS) += xsk_buff_pool.o xsk_mp.o
 obj-$(CONFIG_XDP_SOCKETS_DIAG) += xsk_diag.o
diff --git a/net/xdp/xsk_buff_pool.c b/net/xdp/xsk_buff_pool.c
index d707fb308001..2cfe069e9959 100644
--- a/net/xdp/xsk_buff_pool.c
+++ b/net/xdp/xsk_buff_pool.c
@@ -7,6 +7,7 @@
 #include <net/xdp_sock_drv.h>
 
 #include "xsk_queue.h"
+#include "xsk_mp.h"
 #include "xdp_umem.h"
 #include "xsk.h"
 
@@ -69,9 +70,14 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
 	if (!pool)
 		goto out;
 
-	pool->heads = kvzalloc_objs(*pool->heads, umem->chunks);
-	if (!pool->heads)
-		goto out;
+	/* Receiving with explicit return and copy TX take none */
+	if (!(umem->flags & XDP_UMEM_EXPLICIT_RETURN)) {
+		pool->heads = kvzalloc_objs(*pool->heads, umem->chunks);
+		if (!pool->heads)
+			goto out;
+		pool->heads_cnt = umem->chunks;
+		pool->free_heads_cnt = umem->chunks;
+	}
 
 	if (xs->tx)
 		if (xp_alloc_tx_descs(pool, xs, max_segs))
@@ -79,8 +85,6 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
 
 	pool->chunk_mask = ~((u64)umem->chunk_size - 1);
 	pool->addrs_cnt = umem->size;
-	pool->heads_cnt = umem->chunks;
-	pool->free_heads_cnt = umem->chunks;
 	pool->headroom = umem->headroom;
 	pool->chunk_size = umem->chunk_size;
 	pool->chunk_shift = ffs(umem->chunk_size) - 1;
@@ -189,6 +193,12 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 	if (force_zc && force_copy)
 		return -EINVAL;
 
+	/* Explicit return lets the kernel place the packets, which is
+	 * neither of the classic modes
+	 */
+	if (umem_flags & XDP_UMEM_EXPLICIT_RETURN && (force_zc || force_copy))
+		return -EOPNOTSUPP;
+
 	if (pool->tx_sw_csum && (netdev->priv_flags & IFF_TX_SKB_NO_LINEAR))
 		return -EOPNOTSUPP;
 
@@ -219,6 +229,13 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 	 */
 	hlist_add_head(&pool->dev_node, &netdev->xsk_pools);
 
+	if (pool->umem->flags & XDP_UMEM_EXPLICIT_RETURN) {
+		err = xsk_mp_bind(pool, netdev, queue_id, flags);
+		if (err)
+			goto err_unbind;
+		return 0;
+	}
+
 	if (force_copy)
 		/* For copy-mode, we are done. */
 		return 0;
@@ -271,6 +288,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 err_unreg_pool:
 	if (!force_zc)
 		err = 0; /* fallback to copy mode */
+err_unbind:
 	if (err) {
 		pool->umem->flags = umem_flags;
 		xsk_clear_pool_at_qid(netdev, queue_id);
@@ -288,6 +306,9 @@ int xp_assign_dev_shared(struct xsk_buff_pool *pool, struct xdp_sock *umem_xs,
 	struct xdp_umem *umem = umem_xs->umem;
 
 	flags = umem->zc ? XDP_ZEROCOPY : XDP_COPY;
+	/* Explicit return has no copy mode */
+	if (umem->flags & XDP_UMEM_EXPLICIT_RETURN)
+		flags = 0;
 
 	if (umem->flags & XDP_UMEM_SG_FLAG)
 		flags |= XDP_USE_SG;
@@ -303,7 +324,10 @@ static void __xp_clear_dev(struct xsk_buff_pool *pool)
 	struct net_device *netdev = pool->netdev;
 
 	netdev_assert_locked_ops_compat(netdev);
-	xp_disable_drv_zc(pool);
+	if (pool->mp)
+		xsk_mp_unbind(pool);
+	else
+		xp_disable_drv_zc(pool);
 	xsk_clear_pool_at_qid(netdev, pool->queue_id);
 	hlist_del(&pool->dev_node);
 	pool->netdev = NULL;
diff --git a/net/xdp/xsk_mp.c b/net/xdp/xsk_mp.c
new file mode 100644
index 000000000000..0e33fd4d9fd5
--- /dev/null
+++ b/net/xdp/xsk_mp.c
@@ -0,0 +1,443 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP RX with explicit return
+ *
+ * Userspace hands page-sized UMEM chunks to the kernel through the FILL
+ * ring, and only XDP_RX_CHUNK_RETURNED gives them back. Each chunk
+ * becomes a net_iov of a page pool memory provider, and the device splits it
+ * as it splits pages: a chunk may hold several RX buffers, and a packet may
+ * span chunks.
+ *
+ * One context at a time owns the provider state of a queue: the queue's
+ * NAPI, in softirq, busy polling or its thread, or a driver operation that
+ * runs only while that NAPI cannot use the rings, as a queue restart or an
+ * error recovery does. A driver that lets the provider in agrees, see
+ * PP_FLAG_ALLOW_XDP_ONLY_NETMEM. It fills and drains its rings only while
+ * the queue's NAPI cannot use them, so the owner reads FILL and changes the
+ * chunk states without a lock. The exception is a page pool that goes
+ * away: it releases the chunks it never handed out from any context, onto
+ * a lock-free list.
+ *
+ * The kernel maps the chunks through the UMEM mapping, so XDP programs read
+ * and write the packets in place. The kernel stores none of its own data in
+ * the chunks: the shared info of a packet lives in the buffer pool, see
+ * %XDP_FLAGS_SINFO_EXT, and the core turns every verdict that would build an
+ * skb or a frame in the buffers into a drop.
+ */
+
+#include <linux/nospec.h>
+#include <net/netdev_queues.h>
+#include <net/netdev_rx_queue.h>
+#include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
+
+#include "../core/dev.h"
+#include "xsk_queue.h"
+#include "xsk_mp.h"
+
+#define XSK_MP_DMA_ATTR (DMA_ATTR_WEAK_ORDERING | DMA_ATTR_SKIP_CPU_SYNC)
+/* Chunks a refill tops up to with released ones */
+#define XSK_MP_RESERVE	32
+
+/* &net_iov.mp_state: whether userspace or the kernel has the chunk */
+enum {
+	XSK_MP_USER,
+	XSK_MP_LENT,
+};
+
+struct xsk_mp {
+	struct net_iov_area area;
+	struct device *dev;
+	struct xsk_buff_pool *pool;
+	/* NULL once no queue uses the provider */
+	struct netdev_rx_queue *rxq;
+	refcount_t refs;
+	/* NULL once no queue refills from the provider. Its consumer is the
+	 * owner of the queue, see the top of this file.
+	 */
+	struct xsk_queue *fq;
+	/* One node per chunk: chunks that page pools released, from any
+	 * context
+	 */
+	struct llist_node *nodes;
+	struct llist_head released;
+};
+
+static void xsk_mp_free(struct xsk_mp *mp)
+{
+	kvfree(mp->nodes);
+	kvfree(mp->area.niovs);
+	kfree(mp);
+}
+
+static void xsk_mp_put(struct xsk_mp *mp)
+{
+	if (refcount_dec_and_test(&mp->refs))
+		xsk_mp_free(mp);
+}
+
+static int xsk_mp_init(struct page_pool *pp)
+{
+	struct xsk_mp *mp = pp->mp_priv;
+
+	/* Each net_iov is one chunk, mapped for one device */
+	if (pp->p.order)
+		return -E2BIG;
+	if (pp->p.dev != mp->dev || pp->p.offset + pp->p.max_len > PAGE_SIZE)
+		return -EINVAL;
+	/* A chunk that its page pool takes back from FILL keeps the page
+	 * pool info, see xsk_mp_take_fill(), and would miss the callback
+	 */
+	if (pp->slow.init_callback)
+		return -EOPNOTSUPP;
+	/* Rings that keep every chunk posted leave none to replace the ones
+	 * the device filled: mlx5 posts about 16K pages per queue at MTU
+	 * 9000.
+	 */
+	if (pp->p.pool_size + PP_ALLOC_CACHE_SIZE >= mp->area.num_niovs)
+		return -ENOSPC;
+
+	refcount_inc(&mp->refs);
+	return 0;
+}
+
+static void xsk_mp_destroy(struct page_pool *pp)
+{
+	xsk_mp_put(pp->mp_priv);
+}
+
+/* Takes the chunks of FILL entries into the cache of @pp, which holds them
+ * from now on: a chunk that userspace has counts against no page pool. It
+ * keeps the info of the page pool it went back from, which takes it back
+ * cheaply. Returns the number of chunks taken. The owner of the queue is
+ * the only consumer of FILL.
+ */
+static u32 xsk_mp_take_fill(struct xsk_mp *mp, struct page_pool *pp,
+			    struct xsk_queue *fq)
+{
+	u32 i, entries, cons, mask, nr, n = 0, held = 0;
+	struct net_iov *niov, *niovs = mp->area.niovs;
+	struct xdp_umem_ring *ring;
+	netmem_ref netmem;
+	bool lent;
+	u64 addr;
+
+	/* One cache worth, bounding NAPI work */
+	entries = fq ? xskq_cons_nb_entries(fq, PP_ALLOC_CACHE_SIZE) : 0;
+	if (!entries)
+		return 0;
+
+	nr = mp->area.num_niovs;
+	ring = (struct xdp_umem_ring *)fq->ring;
+	mask = fq->ring_mask;
+	cons = fq->cached_cons;
+	for (i = 0; i < entries; i++) {
+		addr = ring->desc[(cons + i) & mask];
+		niov = &niovs[array_index_nospec((u32)(addr >> PAGE_SHIFT),
+						 nr)];
+		/* A chunk on FILL twice would be in two places at once. This
+		 * pairs with the release that gave it to userspace.
+		 */
+		lent = smp_load_acquire(&niov->mp_state) != XSK_MP_USER;
+		if (unlikely(addr >= (u64)nr << PAGE_SHIFT || lent)) {
+			fq->invalid_descs++;
+			continue;
+		}
+
+		WRITE_ONCE(niov->mp_state, XSK_MP_LENT);
+		netmem = net_iov_to_netmem(niov);
+		if (netmem_get_pp(netmem) == pp)
+			held++;
+		else
+			net_mp_niov_set_page_pool(pp, niov);
+		pp->alloc.cache[n++] = netmem;
+	}
+	net_mp_hold_page_pool(pp, held);
+
+	xskq_cons_release_n(fq, entries);
+	__xskq_cons_release(fq);
+	return n;
+}
+
+/* Tops up the cache of @pp, which holds @n chunks, with chunks that page
+ * pools released. A reserve, not a source. Each chunk it adds stays in
+ * circulation, so take only what FILL could not give. The owner of the
+ * queue is the only consumer of the list, as llist_del_first() needs.
+ */
+static u32 xsk_mp_take_released(struct xsk_mp *mp, struct page_pool *pp,
+				u32 n)
+{
+	struct llist_node *node;
+	struct net_iov *niov;
+
+	/* The page pool cache has 8 entries with 64K pages */
+	while (n < min(XSK_MP_RESERVE, PP_ALLOC_CACHE_SIZE)) {
+		node = llist_del_first(&mp->released);
+		if (!node)
+			break;
+		niov = &mp->area.niovs[node - mp->nodes];
+		net_mp_niov_set_page_pool(pp, niov);
+		pp->alloc.cache[n++] = net_iov_to_netmem(niov);
+	}
+	return n;
+}
+
+static netmem_ref xsk_mp_alloc_netmems(struct page_pool *pp, gfp_t gfp)
+{
+	struct xsk_mp *mp = pp->mp_priv;
+	/* The NAPI owns the need_wakeup flags */
+	bool napi = in_softirq() && !in_hardirq();
+	struct xsk_queue *fq;
+	dma_addr_t dma;
+	u32 i, n;
+
+	/* An owner outside the NAPI holds the instance lock. The pool keeps
+	 * its device for as long as the provider, while stop clears @rxq.
+	 */
+	lockdep_assert_once(napi || lockdep_is_held(&mp->pool->netdev->lock));
+
+	/* See xsk_mp_stop() */
+	fq = READ_ONCE(mp->fq);
+	/* The page pool asks only once its cache is empty */
+	n = xsk_mp_take_fill(mp, pp, fq);
+	n = xsk_mp_take_released(mp, pp, n);
+	/* Ask for a wakeup only while FILL runs dry, as zero copy drivers do:
+	 * a wakeup schedules the NAPI, which a busy poller would rather run
+	 * itself. Process context refills new queues only and leaves the
+	 * flag to bind and to their NAPI, which the driver runs once after a
+	 * start.
+	 */
+	if (napi && fq) {
+		if (n)
+			xsk_clear_rx_need_wakeup(mp->pool);
+		else
+			xsk_set_rx_need_wakeup(mp->pool);
+	}
+	if (fq && !n)
+		fq->queue_empty_descs++;
+	if (!n)
+		return 0;
+
+	for (i = 0; i < n; i++) {
+		dma = page_pool_get_dma_addr_netmem(pp->alloc.cache[i]);
+		dma_sync_single_range_for_device(pp->p.dev, dma, pp->p.offset,
+						 pp->p.max_len, pp->p.dma_dir);
+	}
+
+	pp->alloc.count = n - 1;
+	return pp->alloc.cache[n - 1];
+}
+
+static bool xsk_mp_release_netmem(struct page_pool *pp, netmem_ref netmem)
+{
+	struct net_iov *niov = netmem_to_net_iov(netmem);
+	struct xsk_mp *mp = pp->mp_priv;
+
+	net_mp_niov_clear_page_pool(niov);
+	llist_add(&mp->nodes[net_iov_idx(niov)], &mp->released);
+	return false;
+}
+
+static int xsk_mp_nl_fill(void *mp_priv, struct sk_buff *rsp,
+			  struct netdev_rx_queue *rxq)
+{
+	/* Queue dumps show NETDEV_A_QUEUE_XSK through the queue's pool */
+	if (rxq)
+		return 0;
+	return nla_put_empty_nest(rsp, NETDEV_A_PAGE_POOL_XSK);
+}
+
+/* No queue DMAs to the UMEM any longer: the queue restarted without the
+ * provider, or the device went away, so nothing refills from it
+ */
+static void xsk_mp_stop(struct xsk_mp *mp)
+{
+	struct xsk_queue *fq = mp->fq;
+
+	WRITE_ONCE(mp->rxq, NULL);
+	WRITE_ONCE(mp->fq, NULL);
+	/* Wait for wakeups that found the provider or the queue */
+	synchronize_net();
+	if (fq)
+		xp_dma_unmap(mp->pool, XSK_MP_DMA_ATTR);
+}
+
+/* Device unregister, after the queue stopped */
+static void xsk_mp_uninstall(void *mp_priv, struct netdev_rx_queue *rxq)
+{
+	memset(&rxq->mp_params, 0, sizeof(rxq->mp_params));
+	xsk_mp_stop(mp_priv);
+}
+
+static const struct memory_provider_ops xsk_mp_ops = {
+	.alloc_netmems	= xsk_mp_alloc_netmems,
+	.release_netmem	= xsk_mp_release_netmem,
+	.init		= xsk_mp_init,
+	.destroy	= xsk_mp_destroy,
+	.nl_fill	= xsk_mp_nl_fill,
+	.uninstall	= xsk_mp_uninstall,
+	.flags		= MP_XDP_ONLY,
+};
+
+static struct xsk_mp *xsk_mp_create(struct xsk_buff_pool *pool,
+				    struct device *dev)
+{
+	u32 i, nr = pool->umem->chunks;
+	struct net_iov *niov;
+	struct xsk_mp *mp;
+	dma_addr_t dma;
+
+	mp = kzalloc_obj(*mp, GFP_KERNEL_ACCOUNT);
+	if (!mp)
+		return ERR_PTR(-ENOMEM);
+
+	/* See &xdp_rxq_info.xdp_only_area */
+	BUILD_BUG_ON(offsetof(struct xsk_mp, area));
+
+	mp->area.niovs = kvcalloc(nr, sizeof(*niov), GFP_KERNEL_ACCOUNT);
+	mp->nodes = kvcalloc(nr, sizeof(*mp->nodes), GFP_KERNEL_ACCOUNT);
+	if (!mp->area.niovs || !mp->nodes) {
+		xsk_mp_free(mp);
+		return ERR_PTR(-ENOMEM);
+	}
+
+	mp->area.num_niovs = nr;
+	/* Chunks are pages, see XDP_UMEM_EXPLICIT_RETURN */
+	mp->area.xdp_vaddr = pool->addrs;
+	mp->area.xdp_vsize = (size_t)nr << PAGE_SHIFT;
+	mp->area.xdp_shift = PAGE_SHIFT;
+	/* XDP runs on the queue only while the pool is bound, see
+	 * xsk_mp_unbind()
+	 */
+	mp->area.xdp_sinfo = &pool->sinfo;
+	mp->dev = dev;
+	mp->pool = pool;
+	mp->fq = pool->fq;
+	init_llist_head(&mp->released);
+	refcount_set(&mp->refs, 1);
+
+	/* Chunks are pages, see XDP_UMEM_EXPLICIT_RETURN */
+	for (i = 0; i < nr; i++) {
+		niov = &mp->area.niovs[i];
+		dma = pool->dma_pages[i] & ~XSK_NEXT_PG_CONTIG_MASK;
+		net_iov_init(niov, &mp->area, NET_IOV_XSK);
+		if (net_mp_niov_set_dma_addr(niov, dma)) {
+			xsk_mp_free(mp);
+			return ERR_PTR(-ERANGE);
+		}
+	}
+
+	return mp;
+}
+
+/* Sockets sharing the pool find no provider after the grace period of
+ * xsk_mp_stop(), see xsk_wakeup()
+ */
+static void xsk_mp_detach(struct xsk_buff_pool *pool)
+{
+	struct xsk_mp *mp = pool->mp;
+
+	WRITE_ONCE(pool->mp, NULL);
+	xsk_mp_stop(mp);
+	xsk_mp_put(mp);
+	static_branch_dec(&xdp_only_mp_key);
+}
+
+/**
+ * xsk_mp_bind - install the UMEM of @pool as the provider of an RX queue
+ * @pool: buffer pool with an XDP_UMEM_EXPLICIT_RETURN UMEM
+ * @dev: device of the queue
+ * @queue_id: RX queue
+ * @flags: bind flags
+ *
+ * Context: RTNL and the instance lock of @dev.
+ * Return: 0 on success. No copy mode takes over on error.
+ */
+int xsk_mp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+		u16 queue_id, u16 flags)
+{
+	struct pp_memory_provider_params p = { .mp_ops = &xsk_mp_ops };
+	u32 needed = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT;
+	struct device *dma_dev;
+	struct xsk_mp *mp;
+	int err;
+
+	/* The provider changes what the program of the queue does to every
+	 * packet, and keeps the program from going
+	 */
+	if (!capable(CAP_NET_ADMIN))
+		return -EPERM;
+
+	/* Without a wakeup, a queue that used up the FILL ring stays dry */
+	if (!(flags & XDP_USE_NEED_WAKEUP))
+		return -EINVAL;
+
+	if (flags & XDP_USE_SG)
+		needed |= NETDEV_XDP_ACT_RX_SG;
+	/* The queue must receive, and the device must take the queue back
+	 * and run programs on what it gives the socket
+	 */
+	if (!dev->queue_mgmt_ops || (dev->xdp_features & needed) != needed ||
+	    queue_id >= dev->real_num_rx_queues)
+		return -EOPNOTSUPP;
+
+	/* The program of another device would see a leased queue's packets */
+	if (netif_rxq_is_leased(dev, queue_id))
+		return -EOPNOTSUPP;
+
+	/* The device of the queue's page pools, which may differ per queue */
+	dma_dev = netdev_queue_get_dma_dev(dev, queue_id, NETDEV_QUEUE_TYPE_RX);
+	if (!dma_dev)
+		return -EOPNOTSUPP;
+
+	/* Without a program, drivers would build skbs from the buffers */
+	if (!dev_xdp_drv_prog_held(dev))
+		return -ENOENT;
+
+	err = xp_dma_map(pool, dma_dev, XSK_MP_DMA_ATTR, pool->umem->pgs,
+			 pool->umem->npgs);
+	if (err)
+		return err;
+
+	mp = xsk_mp_create(pool, dma_dev);
+	if (IS_ERR(mp)) {
+		xp_dma_unmap(pool, XSK_MP_DMA_ATTR);
+		return PTR_ERR(mp);
+	}
+
+	/* Until the first refill of the NAPI: the queue may need FILL to
+	 * start. Set before the NAPI runs, which owns the flags after that.
+	 */
+	xsk_set_rx_need_wakeup(pool);
+
+	/* The core keeps XDP-only buffers to the socket once the queue runs */
+	static_branch_inc(&xdp_only_mp_key);
+	mp->rxq = __netif_get_rx_queue(dev, queue_id);
+	pool->mp = mp;
+	p.mp_priv = mp;
+	err = netif_mp_open_rxq(dev, queue_id, &p, NULL);
+	if (err) {
+		xsk_mp_detach(pool);
+		return err;
+	}
+
+	return 0;
+}
+
+/* Context: RTNL and the instance lock of the device */
+void xsk_mp_unbind(struct xsk_buff_pool *pool)
+{
+	struct pp_memory_provider_params p = {
+		.mp_ops = &xsk_mp_ops,
+		.mp_priv = pool->mp,
+	};
+	struct xsk_mp *mp = pool->mp;
+
+	/* Unregister may have uninstalled the provider already. A queue that
+	 * cannot restart without it may still use the UMEM: stop the device.
+	 */
+	if (READ_ONCE(mp->rxq) &&
+	    netif_mp_close_rxq(pool->netdev, pool->queue_id, &p))
+		netif_close(pool->netdev);
+	xsk_mp_detach(pool);
+}
diff --git a/net/xdp/xsk_mp.h b/net/xdp/xsk_mp.h
new file mode 100644
index 000000000000..e6c965bd3b2c
--- /dev/null
+++ b/net/xdp/xsk_mp.h
@@ -0,0 +1,14 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* AF_XDP RX with explicit return, see xsk_mp.c */
+
+#ifndef XSK_MP_H_
+#define XSK_MP_H_
+
+struct net_device;
+struct xsk_buff_pool;
+
+int xsk_mp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+		u16 queue_id, u16 flags);
+void xsk_mp_unbind(struct xsk_buff_pool *pool);
+
+#endif /* XSK_MP_H_ */
diff --git a/tools/include/uapi/linux/if_xdp.h b/tools/include/uapi/linux/if_xdp.h
index 50d67df78911..60f01759a1d4 100644
--- a/tools/include/uapi/linux/if_xdp.h
+++ b/tools/include/uapi/linux/if_xdp.h
@@ -45,6 +45,14 @@
  */
 #define XDP_UMEM_TX_METADATA_LEN	(1 << 2)
 
+/* With explicit return, the kernel and the driver decide where packets
+ * land in a chunk, how many share it and the headroom: userspace only
+ * supplies chunks on FILL. An RX descriptor does not give its chunk
+ * back, and a packet may span chunks. Needs aligned page-sized chunks
+ * and no headroom.
+ */
+#define XDP_UMEM_EXPLICIT_RETURN	(1 << 4)
+
 struct sockaddr_xdp {
 	__u16 sxdp_family;
 	__u16 sxdp_flags;
diff --git a/tools/include/uapi/linux/netdev.h b/tools/include/uapi/linux/netdev.h
index 9026e0414fbe..0e2b4cdf1ef4 100644
--- a/tools/include/uapi/linux/netdev.h
+++ b/tools/include/uapi/linux/netdev.h
@@ -112,6 +112,7 @@ enum {
 	NETDEV_A_PAGE_POOL_DETACH_TIME,
 	NETDEV_A_PAGE_POOL_DMABUF,
 	NETDEV_A_PAGE_POOL_IO_URING,
+	NETDEV_A_PAGE_POOL_XSK,
 
 	__NETDEV_A_PAGE_POOL_MAX,
 	NETDEV_A_PAGE_POOL_MAX = (__NETDEV_A_PAGE_POOL_MAX - 1)
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 06/15] xsk: Deliver packets and return chunks explicitly
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (4 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 05/15] xsk: Back a queue's page pools with UMEM chunks Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 07/15] xsk: Receive with explicit chunk return Björn Töpel
                   ` (8 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

Once a chunk holds several buffers, an RX descriptor can no longer
give its chunk back.

Deliver redirected XDP-only buffers to the queue's receiving socket,
the first bound socket with an RX ring.

Each buffer becomes one RX descriptor where the device put it, chained
with XDP_PKT_CONTD, with the program's metadata in front of the head.
An empty head becomes a zero-length descriptor only if it carries
metadata. The socket drops and counts packets that do not fit its
UMEM, XDP_USE_SG setting or RX ring. Redirects, traced by the
xdp_redirect_map tracepoints, fail with -EOPNOTSUPP outside an XSKMAP
and with -EINVAL to another socket.

Once the kernel is done with a chunk whose buffer reached the socket,
the new XDP_RX_CHUNK_RETURNED marks the descriptor of the buffer that
freed it, or an empty descriptor if the device let go later. The RX
ring keeps a slot for each chunk owed, so returns never wait, and
packets drop that much earlier under overload. Returned chunks count
against no page pool, so they pin none after a restart.

The provider takes no lock, as the socket drops its references in the
queue's NAPI. So the NAPI, or an operation that runs only while that
NAPI cannot use the rings, makes every last put of a chunk and every
RX ring write.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Rename from "xsk: Deliver to the socket in the device's buffer
      layout".
    - Rename XDP_RX_CHUNK_FREE to XDP_RX_CHUNK_RETURNED (Magnus).
    - Deliver an empty head with metadata as a zero-length first
      descriptor with XDP_PKT_CONTD. v1 dropped such packets (Sashiko).
    - Say in the uAPI comment of XDP_PKT_CONTD that single-buffer packets
      never set it, as the options of their descriptor may carry
      XDP_RX_CHUNK_RETURNED.
    - Trace redirects and their errors in the xdp_redirect_map
      tracepoints, at no cost while they are off (Sashiko).
    - Stop counting a chunk that goes back to userspace against its page
      pool, once per poll, so that chunks that userspace keeps hold no old
      page pool alive after a restart (Sashiko).
    - A hand-off writes the return descriptor itself, and the RX ring
      keeps room for the chunks that the device still holds, replacing the
      list that the next poll posted (Sashiko).

 include/net/xdp_sock.h            |   8 +
 include/uapi/linux/if_xdp.h       |  21 +-
 net/core/filter.c                 |  38 ++++
 net/xdp/xsk.c                     |  28 ++-
 net/xdp/xsk_mp.c                  | 365 +++++++++++++++++++++++++++++-
 net/xdp/xsk_mp.h                  |   5 +
 tools/include/uapi/linux/if_xdp.h |  21 +-
 7 files changed, 463 insertions(+), 23 deletions(-)

diff --git a/include/net/xdp_sock.h b/include/net/xdp_sock.h
index 6e70b320b399..f56cacd5c343 100644
--- a/include/net/xdp_sock.h
+++ b/include/net/xdp_sock.h
@@ -126,6 +126,8 @@ struct xsk_tx_metadata_ops {
 int xsk_generic_rcv(struct xdp_sock *xs, struct xdp_buff *xdp);
 int __xsk_map_redirect(struct xdp_sock *xs, struct xdp_buff *xdp);
 void __xsk_map_flush(struct list_head *flush_list);
+int xsk_mp_redirect(struct xdp_buff *xdp, enum bpf_map_type map_type,
+		    void *fwd);
 INDIRECT_CALLABLE_DECLARE(void xsk_destruct_skb(struct sk_buff *));
 
 /**
@@ -182,6 +184,12 @@ static inline int xsk_generic_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 	return -ENOTSUPP;
 }
 
+static inline int xsk_mp_redirect(struct xdp_buff *xdp,
+				  enum bpf_map_type map_type, void *fwd)
+{
+	return -EOPNOTSUPP;
+}
+
 static inline int __xsk_map_redirect(struct xdp_sock *xs, struct xdp_buff *xdp)
 {
 	return -EOPNOTSUPP;
diff --git a/include/uapi/linux/if_xdp.h b/include/uapi/linux/if_xdp.h
index 60f01759a1d4..a319e8d83a97 100644
--- a/include/uapi/linux/if_xdp.h
+++ b/include/uapi/linux/if_xdp.h
@@ -47,9 +47,12 @@
 
 /* With explicit return, the kernel and the driver decide where packets
  * land in a chunk, how many share it and the headroom: userspace only
- * supplies chunks on FILL. An RX descriptor does not give its chunk
- * back, and a packet may span chunks. Needs aligned page-sized chunks
- * and no headroom.
+ * supplies chunks on FILL, and a packet may span chunks. Receiving a
+ * buffer does not give its chunk back. A chunk is userspace's again
+ * once an RX descriptor carries XDP_RX_CHUNK_RETURNED for it, or,
+ * without a descriptor, when the receiving socket closes or the UMEM
+ * stops backing the queue. Needs aligned page-sized chunks and no
+ * headroom.
  */
 #define XDP_UMEM_EXPLICIT_RETURN	(1 << 4)
 
@@ -182,12 +185,20 @@ struct xdp_desc {
 
 /* Flag indicating that the packet continues with the buffer pointed out by the
  * next frame in the ring. The end of the packet is signalled by setting this
- * bit to zero. For single buffer packets, every descriptor has 'options' set
- * to 0 and this maintains backward compatibility.
+ * bit to zero. Single buffer packets never set it, and this maintains
+ * backward compatibility.
  */
 #define XDP_PKT_CONTD (1 << 0)
 
 /* TX packet carries valid metadata. */
 #define XDP_TX_METADATA (1 << 1)
 
+/* Flag on an RX descriptor of an XDP_UMEM_EXPLICIT_RETURN UMEM: the
+ * kernel is done with the UMEM chunk of the descriptor, and puts nothing
+ * more in it. The chunk is userspace's again. An empty descriptor at the
+ * chunk carries only this flag, when the device let go of the chunk after
+ * its last buffer.
+ */
+#define XDP_RX_CHUNK_RETURNED (1 << 2)
+
 #endif /* _UAPI_LINUX_IF_XDP_H */
diff --git a/net/core/filter.c b/net/core/filter.c
index 90e4bf78c689..71a4f93c2b20 100644
--- a/net/core/filter.c
+++ b/net/core/filter.c
@@ -4770,12 +4770,50 @@ __xdp_do_redirect_frame(struct bpf_redirect_info *ri, struct net_device *dev,
 	return err;
 }
 
+static noinline int xdp_redirect_xdp_only_traced(const struct net_device *dev,
+						 struct xdp_buff *xdp,
+						 const struct bpf_prog *prog,
+						 struct bpf_redirect_info *ri)
+{
+	enum bpf_map_type map_type = ri->map_type;
+	void *fwd = ri->tgt_value;
+	u32 index = ri->tgt_index;
+	u32 map_id = ri->map_id;
+	int err;
+
+	ri->map_id = 0;
+	ri->map_type = BPF_MAP_TYPE_UNSPEC;
+	err = xsk_mp_redirect(xdp, map_type, fwd);
+	if (err)
+		_trace_xdp_redirect_map_err(dev, prog, fwd, map_type, map_id,
+					    index, err);
+	else
+		_trace_xdp_redirect_map(dev, prog, fwd, map_type, map_id,
+					index);
+	return err;
+}
+
 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
 		    const struct bpf_prog *xdp_prog)
 {
 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
 	enum bpf_map_type map_type = ri->map_type;
 
+	if (static_branch_unlikely(&xdp_only_mp_key) &&
+	    xdp_buff_is_xdp_only(xdp)) {
+		void *fwd;
+
+		if (trace_xdp_redirect_enabled() ||
+		    trace_xdp_redirect_err_enabled())
+			return xdp_redirect_xdp_only_traced(dev, xdp, xdp_prog,
+							    ri);
+
+		fwd = ri->tgt_value;
+		ri->map_id = 0;
+		ri->map_type = BPF_MAP_TYPE_UNSPEC;
+		return xsk_mp_redirect(xdp, map_type, fwd);
+	}
+
 	if (map_type == BPF_MAP_TYPE_XSKMAP)
 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
 
diff --git a/net/xdp/xsk.c b/net/xdp/xsk.c
index 48a835e53518..482bb2cd94bf 100644
--- a/net/xdp/xsk.c
+++ b/net/xdp/xsk.c
@@ -35,6 +35,7 @@
 #include "../core/dev.h"
 
 #include "xsk_queue.h"
+#include "xsk_mp.h"
 #include "xdp_umem.h"
 #include "xsk.h"
 
@@ -437,6 +438,12 @@ static bool xsk_dev_queue_valid(const struct xdp_sock *xs,
 	return false;
 }
 
+/* The pool receives with explicit return, or did */
+static bool xsk_explicit_return(const struct xdp_sock *xs)
+{
+	return xs->pool->umem->flags & XDP_UMEM_EXPLICIT_RETURN;
+}
+
 static int xsk_rcv_check(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len)
 {
 	if (!xsk_is_bound(xs))
@@ -454,8 +461,14 @@ static int xsk_rcv_check(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len)
 
 static void xsk_flush(struct xdp_sock *xs)
 {
+	struct xsk_mp *mp = xs->pool->mp;
+
+	if (mp)
+		xsk_mp_flush(mp);
 	xskq_prod_submit(xs->rx);
-	__xskq_cons_release(xs->pool->fq);
+	/* The provider releases FILL as it takes it, see xsk_mp_take_fill() */
+	if (!mp)
+		__xskq_cons_release(xs->pool->fq);
 	sock_def_readable(&xs->sk);
 }
 
@@ -465,6 +478,11 @@ int xsk_generic_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 	int err;
 
 	err = xsk_rcv_check(xs, xdp, len);
+	/* A socket with explicit return takes buffers of its provider only */
+	if (!err && xsk_explicit_return(xs)) {
+		xs->rx_dropped++;
+		err = -EOPNOTSUPP;
+	}
 	if (!err) {
 		spin_lock_bh(&xs->pool->rx_lock);
 		err = __xsk_rcv(xs, xdp, len);
@@ -489,6 +507,14 @@ static int xsk_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 		return xsk_rcv_zc(xs, xdp, len);
 	}
 
+	/* XDP-only buffers take xsk_mp_redirect(); others cannot go to a
+	 * socket with explicit return
+	 */
+	if (xsk_explicit_return(xs)) {
+		xs->rx_dropped++;
+		return -EOPNOTSUPP;
+	}
+
 	err = __xsk_rcv(xs, xdp, len);
 	if (!err)
 		xdp_return_buff(xdp);
diff --git a/net/xdp/xsk_mp.c b/net/xdp/xsk_mp.c
index 0e33fd4d9fd5..f7db0d6f788a 100644
--- a/net/xdp/xsk_mp.c
+++ b/net/xdp/xsk_mp.c
@@ -5,23 +5,48 @@
  * ring, and only XDP_RX_CHUNK_RETURNED gives them back. Each chunk
  * becomes a net_iov of a page pool memory provider, and the device splits it
  * as it splits pages: a chunk may hold several RX buffers, and a packet may
- * span chunks.
+ * span chunks. Each buffer of a packet that XDP redirects to the socket
+ * becomes one RX descriptor, at the address the device chose.
+ *
+ * The socket drops the page pool reference of each buffer it takes. A chunk
+ * goes back to userspace once nothing in the kernel uses it, if a buffer of
+ * it reached the socket: the descriptor of the buffer that freed it carries
+ * XDP_RX_CHUNK_RETURNED, or, when the device lets go of the chunk later, an
+ * empty descriptor at the chunk does:
+ *
+ *   FILL 0x7000
+ *   RX {0x7100, A}
+ *   RX {0x7900, B, XDP_RX_CHUNK_RETURNED}
+ * or
+ *   RX {0x7000, 0, XDP_RX_CHUNK_RETURNED}
+ *
+ * Such a chunk no longer counts against its page pool, so that chunks that
+ * userspace keeps hold no page pool alive, and the page pool that takes it
+ * from FILL counts it again. Chunks whose buffers all stayed in the kernel, as
+ * for dropped packets, stay in the kernel.
  *
  * One context at a time owns the provider state of a queue: the queue's
  * NAPI, in softirq, busy polling or its thread, or a driver operation that
  * runs only while that NAPI cannot use the rings, as a queue restart or an
  * error recovery does. A driver that lets the provider in agrees, see
  * PP_FLAG_ALLOW_XDP_ONLY_NETMEM. It fills and drains its rings only while
- * the queue's NAPI cannot use them, so the owner reads FILL and changes the
- * chunk states without a lock. The exception is a page pool that goes
- * away: it releases the chunks it never handed out from any context, onto
- * a lock-free list.
+ * the queue's NAPI cannot use them, and the buffers leave it only to the
+ * queue's socket, which drops its references in that NAPI. So the owner
+ * makes every last put of a chunk, and reads FILL, writes the RX ring and
+ * changes the chunk states and counts below without a lock. The exception
+ * is a page pool that goes away: it releases the chunks it never handed
+ * out from any context, onto a lock-free list.
+ *
+ * The RX ring keeps room for one descriptor per chunk that the kernel owes
+ * back, so a return never waits for room: a packet that would leave less is
+ * dropped.
  *
  * The kernel maps the chunks through the UMEM mapping, so XDP programs read
- * and write the packets in place. The kernel stores none of its own data in
- * the chunks: the shared info of a packet lives in the buffer pool, see
- * %XDP_FLAGS_SINFO_EXT, and the core turns every verdict that would build an
- * skb or a frame in the buffers into a drop.
+ * and write the packets in place, and their metadata lands in front of the
+ * first buffer. The kernel stores none of its own data in the chunks: the
+ * shared info of a packet lives in the buffer pool, see %XDP_FLAGS_SINFO_EXT,
+ * and the core turns every verdict that would build an skb or a frame in the
+ * buffers into a drop.
  */
 
 #include <linux/nospec.h>
@@ -39,9 +64,11 @@
 /* Chunks a refill tops up to with released ones */
 #define XSK_MP_RESERVE	32
 
-/* &net_iov.mp_state: whether userspace or the kernel has the chunk */
+/* &net_iov.mp_state */
 enum {
+	/* Userspace has the chunk */
 	XSK_MP_USER,
+	/* The kernel has it */
 	XSK_MP_LENT,
 };
 
@@ -52,10 +79,22 @@ struct xsk_mp {
 	/* NULL once no queue uses the provider */
 	struct netdev_rx_queue *rxq;
 	refcount_t refs;
-	/* NULL once no queue refills from the provider. Its consumer is the
-	 * owner of the queue, see the top of this file.
+	/* NULL once no queue refills from the provider. This and the fields
+	 * up to @owed belong to the owner of the queue, see the top of this
+	 * file.
 	 */
 	struct xsk_queue *fq;
+	/* Page pool of the chunks that went back to userspace and still count
+	 * against it, and their number, see xsk_mp_returned()
+	 */
+	struct page_pool *ret_pp;
+	u32 ret_nr;
+	/* Chunks marked mp_hand_off, whose returns the RX ring keeps room
+	 * for, see xsk_mp_rcv()
+	 */
+	u32 owed;
+	/* Set once: see xsk_mp_add_sock() */
+	struct xdp_sock *xs;
 	/* One node per chunk: chunks that page pools released, from any
 	 * context
 	 */
@@ -182,6 +221,104 @@ static u32 xsk_mp_take_released(struct xsk_mp *mp, struct page_pool *pp,
 	return n;
 }
 
+/* Counts the returned chunks off their page pool, before the RX ring shows
+ * them and before the owner lets go of the queue, so the batch is empty
+ * outside a NAPI poll. The page pool, and with it the provider, may go
+ * once its chunks no longer count against it, so touch neither after that.
+ */
+static void xsk_mp_flush_returned(struct xsk_mp *mp)
+{
+	struct page_pool *pp = mp->ret_pp;
+	u32 nr = mp->ret_nr;
+
+	if (!nr)
+		return;
+	mp->ret_pp = NULL;
+	mp->ret_nr = 0;
+	net_mp_release_page_pool(pp, nr);
+}
+
+/* A chunk that goes back to userspace no longer counts against its page
+ * pool, so that chunks that userspace keeps hold no old page pool of a
+ * restarted queue alive. It keeps the page pool info, see
+ * xsk_mp_take_fill(). Returns count off their page pool in batches, see
+ * xsk_mp_flush_returned().
+ */
+static void xsk_mp_returned(struct xsk_mp *mp, struct net_iov *niov)
+{
+	struct page_pool *pp = netmem_get_pp(net_iov_to_netmem(niov));
+
+	if (pp != mp->ret_pp) {
+		xsk_mp_flush_returned(mp);
+		mp->ret_pp = pp;
+	}
+	mp->ret_nr++;
+}
+
+/* Gives @niov back on an empty RX descriptor. The device let go of it after
+ * the socket dropped its references, so this comes after the descriptors
+ * of its buffers, and the room that the receive path keeps for it is there,
+ * unless userspace moved the consumer back, which costs it only its own
+ * descriptors.
+ */
+static void xsk_mp_return(struct xsk_mp *mp, struct xdp_sock *xs,
+			  struct net_iov *niov)
+{
+	xsk_mp_returned(mp, niov);
+	mp->owed--;
+	/* Pairs with xsk_mp_take_fill() */
+	smp_store_release(&niov->mp_state, XSK_MP_USER);
+	__xskq_prod_reserve_desc(xs->rx, (u64)net_iov_idx(niov) << PAGE_SHIFT,
+				 0, XDP_RX_CHUNK_RETURNED);
+}
+
+/* Shows what the owner put on the RX ring outside the flush of a poll */
+static void xsk_mp_publish(struct xsk_mp *mp, struct xdp_sock *xs)
+{
+	xsk_mp_flush_returned(mp);
+	xskq_prod_submit(xs->rx);
+	xs->sk.sk_data_ready(&xs->sk);
+}
+
+/* Drops the reference of the buffer of @niov that the socket took at the
+ * last RX descriptor. Only the owner of the queue changes the count of a
+ * chunk that delivers to the socket, so this needs no atomic.
+ */
+static void xsk_mp_drop_buf(struct xsk_mp *mp, struct xdp_sock *xs,
+			    struct net_iov *niov)
+{
+	struct xdp_rxtx_ring *ring;
+	atomic_long_t *count;
+	long left;
+
+	count = netmem_get_pp_ref_count_ref(net_iov_to_netmem(niov));
+	left = atomic_long_read(count) - 1;
+	if (left > 0) {
+		/* The device still uses it: its last put hands it off, onto
+		 * a descriptor that the RX ring keeps room for
+		 */
+		atomic_long_set(count, left);
+		if (!niov->mp_hand_off) {
+			niov->mp_hand_off = 1;
+			mp->owed++;
+		}
+		return;
+	}
+
+	/* Free: back to userspace with this descriptor, with the count of a
+	 * free netmem
+	 */
+	atomic_long_set(count, 1);
+	mp->owed -= niov->mp_hand_off;
+	niov->mp_hand_off = 0;
+	xsk_mp_returned(mp, niov);
+	/* Pairs with xsk_mp_take_fill() */
+	smp_store_release(&niov->mp_state, XSK_MP_USER);
+	ring = (struct xdp_rxtx_ring *)xs->rx->ring;
+	ring->desc[(xs->rx->cached_prod - 1) & xs->rx->ring_mask].options |=
+		XDP_RX_CHUNK_RETURNED;
+}
+
 static netmem_ref xsk_mp_alloc_netmems(struct page_pool *pp, gfp_t gfp)
 {
 	struct xsk_mp *mp = pp->mp_priv;
@@ -238,6 +375,23 @@ static bool xsk_mp_release_netmem(struct page_pool *pp, netmem_ref netmem)
 	return false;
 }
 
+/* The last put of a chunk with a buffer in userspace, by the owner of the
+ * queue: the chunk goes back to userspace
+ */
+static bool xsk_mp_hand_off(struct page_pool *pp, netmem_ref netmem)
+{
+	struct net_iov *niov = netmem_to_net_iov(netmem);
+	struct xsk_mp *mp = pp->mp_priv;
+	struct xdp_sock *xs;
+
+	niov->mp_hand_off = 0;
+	/* A buffer of the chunk reached the socket, which stays */
+	xs = READ_ONCE(mp->xs);
+	xsk_mp_return(mp, xs, niov);
+	xsk_mp_publish(mp, xs);
+	return true;
+}
+
 static int xsk_mp_nl_fill(void *mp_priv, struct sk_buff *rsp,
 			  struct netdev_rx_queue *rxq)
 {
@@ -272,6 +426,7 @@ static void xsk_mp_uninstall(void *mp_priv, struct netdev_rx_queue *rxq)
 static const struct memory_provider_ops xsk_mp_ops = {
 	.alloc_netmems	= xsk_mp_alloc_netmems,
 	.release_netmem	= xsk_mp_release_netmem,
+	.hand_off	= xsk_mp_hand_off,
 	.init		= xsk_mp_init,
 	.destroy	= xsk_mp_destroy,
 	.nl_fill	= xsk_mp_nl_fill,
@@ -424,6 +579,27 @@ int xsk_mp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
 	return 0;
 }
 
+/* The first socket with an RX ring receives; others sharing the pool,
+ * such as TX-only sockets, do not.
+ *
+ * Context: RTNL and the instance lock of the device
+ */
+void xsk_mp_add_sock(struct xsk_mp *mp, struct xdp_sock *xs)
+{
+	if (xs->rx && !mp->xs) {
+		/* The NAPI acquires the socket once it is set up */
+		smp_store_release(&mp->xs, xs);
+	}
+}
+
+/* The receiving socket, if any.
+ * Context: RTNL and the instance lock of the device
+ */
+struct xdp_sock *xsk_mp_sock(struct xsk_mp *mp)
+{
+	return mp->xs;
+}
+
 /* Context: RTNL and the instance lock of the device */
 void xsk_mp_unbind(struct xsk_buff_pool *pool)
 {
@@ -441,3 +617,168 @@ void xsk_mp_unbind(struct xsk_buff_pool *pool)
 		netif_close(pool->netdev);
 	xsk_mp_detach(pool);
 }
+
+/* The net_iov of @netmem if it is one of ours; tells by its address */
+static struct net_iov *xsk_mp_niov(struct xsk_mp *mp, netmem_ref netmem)
+{
+	struct net_iov *niov;
+
+	if (!netmem_is_net_iov(netmem))
+		return NULL;
+	niov = netmem_to_net_iov(netmem);
+	if ((unsigned long)(niov - mp->area.niovs) >= mp->area.num_niovs)
+		return NULL;
+	return niov;
+}
+
+/* Puts the buffers of a packet on the RX ring, one descriptor each, with
+ * the metadata of the program in front of the first. Returns 0 if the socket
+ * took them.
+ */
+static int xsk_mp_rcv(struct xsk_mp *mp, struct xdp_sock *xs,
+		      struct xdp_buff *xdp)
+{
+	u32 i, n, k, len, hlen, nr_frags = 0, headroom;
+	struct skb_shared_info *sinfo;
+	struct net_iov *niov, *hniov;
+	const skb_frag_t *frag;
+	netmem_ref netmem;
+	u32 metalen = 0;
+	bool head_desc;
+	u64 addr, off;
+
+	sinfo = xdp_get_shared_info_from_buff(xdp);
+	if (xdp_buff_has_frags(xdp))
+		nr_frags = sinfo->nr_frags;
+
+	/* The head sits in the UMEM mapping. It is empty when the device
+	 * puts every byte in fragments, as mlx5 does for a nonlinear RQ.
+	 */
+	off = (u8 *)xdp->data - (u8 *)mp->area.xdp_vaddr;
+	if (off >= (u64)mp->area.num_niovs << PAGE_SHIFT)
+		goto drop;
+	hniov = &mp->area.niovs[off >> PAGE_SHIFT];
+	hlen = xdp->data_end - xdp->data;
+	if ((off & ~PAGE_MASK) + hlen > PAGE_SIZE)
+		goto drop;
+	headroom = min_t(u64, off & ~PAGE_MASK,
+			 xdp->data - xdp->data_hard_start);
+
+	if (!hlen && !nr_frags)
+		goto drop;
+
+	/* The program put metadata in front of the head, which must be the
+	 * first buffer, within its chunk
+	 */
+	if (!xdp_data_meta_unsupported(xdp))
+		metalen = xdp->data - xdp->data_meta;
+	if (metalen > headroom)
+		goto drop;
+
+	/* An empty head reaches the socket only with metadata in front of
+	 * it, as a descriptor of length zero that XDP_PKT_CONTD chains to
+	 * the data. Without metadata it holds nothing the socket wants.
+	 */
+	head_desc = hlen || metalen;
+	n = nr_frags + head_desc;
+	if (n > 1 && !xs->sg)
+		goto drop;
+
+	for (i = 0; i < nr_frags; i++)
+		if (!xsk_mp_niov(mp, skb_frag_netmem(&sinfo->frags[i])))
+			goto drop;
+
+	/* Room for the packet, and for a return of every chunk that the
+	 * kernel owes after it, so returns never wait: those it owes, and one
+	 * per buffer, as the device may keep the chunk of each
+	 */
+	k = 2 * n + mp->owed;
+	if (xskq_prod_nb_free(xs->rx, k) < k) {
+		xs->rx_queue_full++;
+		return -ENOBUFS;
+	}
+
+	/* Puts nothing, so no return lands between the descriptors */
+	for (i = 0; i < n; i++) {
+		if (head_desc && !i) {
+			niov = hniov;
+			addr = off;
+			len = hlen;
+		} else {
+			frag = &sinfo->frags[i - head_desc];
+			niov = netmem_to_net_iov(skb_frag_netmem(frag));
+			addr = ((u64)(niov - mp->area.niovs) << PAGE_SHIFT) +
+			       skb_frag_off(frag);
+			len = skb_frag_size(frag);
+		}
+		__xskq_prod_reserve_desc(xs->rx, addr, len,
+					 i + 1 < n ? XDP_PKT_CONTD : 0);
+		xsk_mp_drop_buf(mp, xs, niov);
+	}
+
+	if (!head_desc) {
+		netmem = net_iov_to_netmem(hniov);
+		page_pool_put_netmem(netmem_get_pp(netmem), netmem, -1, false);
+	}
+	return 0;
+
+drop:
+	xs->rx_dropped++;
+	return -EINVAL;
+}
+
+/**
+ * xsk_mp_flush - give back chunks at the end of a NAPI poll
+ * @mp: provider of a socket that received in this poll
+ *
+ * Context: the queue NAPI, from xdp_do_flush(), before the RX ring is
+ * submitted.
+ */
+void xsk_mp_flush(struct xsk_mp *mp)
+{
+	xsk_mp_flush_returned(mp);
+}
+
+/**
+ * xsk_mp_redirect - deliver an XDP-only buffer to a socket of its queue
+ * @xdp: XDP-only buffer, see xdp_buff_is_xdp_only()
+ * @map_type: map of the redirect
+ * @fwd: target of the redirect
+ *
+ * The target must be the receiving socket of the queue in an XSKMAP.
+ * Other maps cannot take XDP-only buffers.
+ *
+ * Context: the queue NAPI, from xdp_do_redirect().
+ * Return: 0 if the socket took the buffer.
+ */
+int xsk_mp_redirect(struct xdp_buff *xdp, enum bpf_map_type map_type,
+		    void *fwd)
+{
+	struct net_iov_area *area = xdp->rxq->xdp_only_area;
+	struct xdp_sock *xs;
+	struct xsk_mp *mp;
+	int err;
+
+	/* Set for every queue with an AF_XDP memory provider, see
+	 * PP_FLAG_ALLOW_XDP_ONLY_NETMEM
+	 */
+	if (unlikely(!area))
+		return -EINVAL;
+	mp = container_of(area, struct xsk_mp, area);
+
+	if (map_type != BPF_MAP_TYPE_XSKMAP)
+		return -EOPNOTSUPP;
+
+	/* Pairs with xsk_mp_add_sock() */
+	xs = smp_load_acquire(&mp->xs);
+	if (unlikely(!xs || xs != fwd))
+		return -EINVAL;
+
+	err = xsk_mp_rcv(mp, xs, xdp);
+	if (err)
+		return err;
+
+	if (!xs->flush_node.prev)
+		list_add(&xs->flush_node, bpf_net_ctx_get_xskmap_flush_list());
+	return 0;
+}
diff --git a/net/xdp/xsk_mp.h b/net/xdp/xsk_mp.h
index e6c965bd3b2c..46d73fdb40a1 100644
--- a/net/xdp/xsk_mp.h
+++ b/net/xdp/xsk_mp.h
@@ -5,10 +5,15 @@
 #define XSK_MP_H_
 
 struct net_device;
+struct xdp_sock;
 struct xsk_buff_pool;
+struct xsk_mp;
 
 int xsk_mp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
 		u16 queue_id, u16 flags);
 void xsk_mp_unbind(struct xsk_buff_pool *pool);
+void xsk_mp_flush(struct xsk_mp *mp);
+void xsk_mp_add_sock(struct xsk_mp *mp, struct xdp_sock *xs);
+struct xdp_sock *xsk_mp_sock(struct xsk_mp *mp);
 
 #endif /* XSK_MP_H_ */
diff --git a/tools/include/uapi/linux/if_xdp.h b/tools/include/uapi/linux/if_xdp.h
index 60f01759a1d4..a319e8d83a97 100644
--- a/tools/include/uapi/linux/if_xdp.h
+++ b/tools/include/uapi/linux/if_xdp.h
@@ -47,9 +47,12 @@
 
 /* With explicit return, the kernel and the driver decide where packets
  * land in a chunk, how many share it and the headroom: userspace only
- * supplies chunks on FILL. An RX descriptor does not give its chunk
- * back, and a packet may span chunks. Needs aligned page-sized chunks
- * and no headroom.
+ * supplies chunks on FILL, and a packet may span chunks. Receiving a
+ * buffer does not give its chunk back. A chunk is userspace's again
+ * once an RX descriptor carries XDP_RX_CHUNK_RETURNED for it, or,
+ * without a descriptor, when the receiving socket closes or the UMEM
+ * stops backing the queue. Needs aligned page-sized chunks and no
+ * headroom.
  */
 #define XDP_UMEM_EXPLICIT_RETURN	(1 << 4)
 
@@ -182,12 +185,20 @@ struct xdp_desc {
 
 /* Flag indicating that the packet continues with the buffer pointed out by the
  * next frame in the ring. The end of the packet is signalled by setting this
- * bit to zero. For single buffer packets, every descriptor has 'options' set
- * to 0 and this maintains backward compatibility.
+ * bit to zero. Single buffer packets never set it, and this maintains
+ * backward compatibility.
  */
 #define XDP_PKT_CONTD (1 << 0)
 
 /* TX packet carries valid metadata. */
 #define XDP_TX_METADATA (1 << 1)
 
+/* Flag on an RX descriptor of an XDP_UMEM_EXPLICIT_RETURN UMEM: the
+ * kernel is done with the UMEM chunk of the descriptor, and puts nothing
+ * more in it. The chunk is userspace's again. An empty descriptor at the
+ * chunk carries only this flag, when the device let go of the chunk after
+ * its last buffer.
+ */
+#define XDP_RX_CHUNK_RETURNED (1 << 2)
+
 #endif /* _UAPI_LINUX_IF_XDP_H */
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 07/15] xsk: Receive with explicit chunk return
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (5 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 06/15] xsk: Deliver packets and return chunks explicitly Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 08/15] xsk: Drop references of a run of buffers at once Björn Töpel
                   ` (7 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

UMEM registration still refuses XDP_UMEM_EXPLICIT_RETURN.

Accept it with aligned page-sized chunks and no headroom, and install
the provider when a socket with such a UMEM binds. A bind that cannot
install it fails rather than fall back.

Only the first socket with an RX ring receives, and later ones get
-EBUSY until the provider goes, so the NAPI never sees the receiver
replaced. Sockets sharing the UMEM may transmit, in copy mode.

The provider goes with the queue's last socket, from the freezable
buffer pool teardown, so unbind never restarts the queue of a
suspended device. Until then, a queue without a receiver drops what it
redirects.

Returns need no wakeup, so recvmsg and poll wake the NAPI only for an
empty FILL ring. A wakeup fails with -ENETDOWN once the provider or
NAPI is gone.

Once its fd is closed and its rings unmapped, the receiving socket
waits out the NAPI polls and hand-offs that may write to its RX ring.
Later hand-offs return chunks without descriptors.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Rename from "xsk: Receive in the device's buffer layout".
    - Move the XDP_USE_NEED_WAKEUP requirement to patch 5 (Magnus).
    - Let the provider go with the last socket of the queue, from the
      deferred teardown of the buffer pool on a freezable workqueue, so
      that unbind never restarts the queue of a suspended device. v1 let
      it go with the receiving socket, but a queue that only TX-only
      sockets used kept it until its pool went (Sashiko). A program detach
      right after the last close may now fail with EBUSY for a short time.
    - Hand-offs and wakeups follow the single owner of a queue, see patch
      6; need_wakeup reports only an empty FILL ring. Read the NAPI of the
      queue under RCU, and mark its writes (Sashiko).
    - Once the receiving socket closes, give the chunks that the kernel
      owes it back to the application without descriptors, and drop what
      the queue redirects until the provider goes (Sashiko).

 include/net/netdev_rx_queue.h |  5 +++
 net/core/dev.c                |  3 +-
 net/xdp/xdp_umem.c            |  5 +++
 net/xdp/xsk.c                 | 82 ++++++++++++++++++++++++++++-----
 net/xdp/xsk_mp.c              | 85 ++++++++++++++++++++++++++++++++---
 net/xdp/xsk_mp.h              |  4 +-
 6 files changed, 163 insertions(+), 21 deletions(-)

diff --git a/include/net/netdev_rx_queue.h b/include/net/netdev_rx_queue.h
index 9415a94d333d..c5cc9d10f0c2 100644
--- a/include/net/netdev_rx_queue.h
+++ b/include/net/netdev_rx_queue.h
@@ -28,6 +28,11 @@ struct netdev_rx_queue {
 #ifdef CONFIG_XDP_SOCKETS
 	struct xsk_buff_pool            *pool;
 #endif
+	/* Readers without the instance lock, such as AF_XDP wakeups, use
+	 * READ_ONCE() under RCU. Drivers clear it before netif_napi_del(),
+	 * and wait for a grace period before they free the NAPI, as they
+	 * already must for napi_by_id(), so the NAPI stays valid for them.
+	 */
 	struct napi_struct		*napi;
 	struct netdev_queue_config	qcfg;
 	struct pp_memory_provider_params mp_params;
diff --git a/net/core/dev.c b/net/core/dev.c
index 12e852cc3855..42ed8e2514d2 100644
--- a/net/core/dev.c
+++ b/net/core/dev.c
@@ -7631,7 +7631,8 @@ void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index,
 	switch (type) {
 	case NETDEV_QUEUE_TYPE_RX:
 		rxq = __netif_get_rx_queue(dev, queue_index);
-		rxq->napi = napi;
+		/* See &netdev_rx_queue.napi */
+		WRITE_ONCE(rxq->napi, napi);
 		return;
 	case NETDEV_QUEUE_TYPE_TX:
 		txq = netdev_get_tx_queue(dev, queue_index);
diff --git a/net/xdp/xdp_umem.c b/net/xdp/xdp_umem.c
index de8a2747ac9f..84caa001ff6a 100644
--- a/net/xdp/xdp_umem.c
+++ b/net/xdp/xdp_umem.c
@@ -145,6 +145,7 @@ static int xdp_umem_account_pages(struct xdp_umem *umem)
 		XDP_UMEM_UNALIGNED_CHUNK_FLAG | \
 		XDP_UMEM_TX_SW_CSUM | \
 		XDP_UMEM_TX_METADATA_LEN | \
+		XDP_UMEM_EXPLICIT_RETURN | \
 	0)
 
 static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)
@@ -198,6 +199,10 @@ static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)
 	if (headroom > chunk_size - XDP_PACKET_HEADROOM - 128)
 		return -EINVAL;
 
+	if (mr->flags & XDP_UMEM_EXPLICIT_RETURN &&
+	    (unaligned_chunks || chunk_size != PAGE_SIZE || headroom))
+		return -EINVAL;
+
 	if (mr->flags & XDP_UMEM_TX_METADATA_LEN) {
 		if (mr->tx_metadata_len >= 256 || mr->tx_metadata_len % 8)
 			return -EINVAL;
diff --git a/net/xdp/xsk.c b/net/xdp/xsk.c
index 482bb2cd94bf..33d4cbee658d 100644
--- a/net/xdp/xsk.c
+++ b/net/xdp/xsk.c
@@ -55,7 +55,8 @@ void xsk_set_rx_need_wakeup(struct xsk_buff_pool *pool)
 		return;
 
 	pool->fq->ring->flags |= XDP_RING_NEED_WAKEUP;
-	pool->cached_need_wakeup |= XDP_WAKEUP_RX;
+	WRITE_ONCE(pool->cached_need_wakeup,
+		   pool->cached_need_wakeup | XDP_WAKEUP_RX);
 }
 EXPORT_SYMBOL(xsk_set_rx_need_wakeup);
 
@@ -72,7 +73,8 @@ void xsk_set_tx_need_wakeup(struct xsk_buff_pool *pool)
 	}
 	rcu_read_unlock();
 
-	pool->cached_need_wakeup |= XDP_WAKEUP_TX;
+	WRITE_ONCE(pool->cached_need_wakeup,
+		   pool->cached_need_wakeup | XDP_WAKEUP_TX);
 }
 EXPORT_SYMBOL(xsk_set_tx_need_wakeup);
 
@@ -82,7 +84,8 @@ void xsk_clear_rx_need_wakeup(struct xsk_buff_pool *pool)
 		return;
 
 	pool->fq->ring->flags &= ~XDP_RING_NEED_WAKEUP;
-	pool->cached_need_wakeup &= ~XDP_WAKEUP_RX;
+	WRITE_ONCE(pool->cached_need_wakeup,
+		   pool->cached_need_wakeup & ~XDP_WAKEUP_RX);
 }
 EXPORT_SYMBOL(xsk_clear_rx_need_wakeup);
 
@@ -99,7 +102,8 @@ void xsk_clear_tx_need_wakeup(struct xsk_buff_pool *pool)
 	}
 	rcu_read_unlock();
 
-	pool->cached_need_wakeup &= ~XDP_WAKEUP_TX;
+	WRITE_ONCE(pool->cached_need_wakeup,
+		   pool->cached_need_wakeup & ~XDP_WAKEUP_TX);
 }
 EXPORT_SYMBOL(xsk_clear_tx_need_wakeup);
 
@@ -800,9 +804,16 @@ u32 xsk_tx_peek_release_desc_batch(struct xsk_buff_pool *pool, u32 nb_pkts)
 }
 EXPORT_SYMBOL(xsk_tx_peek_release_desc_batch);
 
+/* Context: RCU read side, see xsk_mp_unbind() for a provider */
 static int xsk_wakeup(struct xdp_sock *xs, u8 flags)
 {
 	struct net_device *dev = xs->dev;
+	struct xsk_mp *mp;
+
+	if (xsk_explicit_return(xs)) {
+		mp = READ_ONCE(xs->pool->mp);
+		return mp ? xsk_mp_wakeup(mp) : -ENETDOWN;
+	}
 
 	return dev->netdev_ops->ndo_xsk_wakeup(dev, xs->queue_id, flags);
 }
@@ -1404,7 +1415,7 @@ static int __xsk_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len
 		return 0;
 
 	pool = xs->pool;
-	if (pool->cached_need_wakeup & XDP_WAKEUP_TX) {
+	if (READ_ONCE(pool->cached_need_wakeup) & XDP_WAKEUP_TX) {
 		if (xs->zc)
 			return xsk_wakeup(xs, XDP_WAKEUP_TX);
 		return xsk_generic_xmit(sk);
@@ -1444,7 +1455,9 @@ static int __xsk_recvmsg(struct socket *sock, struct msghdr *m, size_t len, int
 	if (xsk_no_wakeup(sk))
 		return 0;
 
-	if (xs->pool->cached_need_wakeup & XDP_WAKEUP_RX && xs->zc)
+	/* A socket with explicit return receives without driver zero copy */
+	if (READ_ONCE(xs->pool->cached_need_wakeup) & XDP_WAKEUP_RX &&
+	    (xs->zc || xsk_explicit_return(xs)))
 		return xsk_wakeup(xs, XDP_WAKEUP_RX);
 	return 0;
 }
@@ -1467,6 +1480,7 @@ static __poll_t xsk_poll(struct file *file, struct socket *sock,
 	struct sock *sk = sock->sk;
 	struct xdp_sock *xs = xdp_sk(sk);
 	struct xsk_buff_pool *pool;
+	u8 need_wakeup;
 
 	sock_poll_wait(file, sock, wait);
 
@@ -1475,13 +1489,20 @@ static __poll_t xsk_poll(struct file *file, struct socket *sock,
 		goto out;
 
 	pool = xs->pool;
+	/* Drivers change it from their NAPI */
+	need_wakeup = READ_ONCE(pool->cached_need_wakeup);
 
-	if (pool->cached_need_wakeup) {
-		if (xs->zc)
-			xsk_wakeup(xs, pool->cached_need_wakeup);
-		else if (xs->tx)
-			/* Poll needs to drive Tx also in copy mode */
-			xsk_generic_xmit(sk);
+	if (need_wakeup) {
+		if (xs->zc) {
+			xsk_wakeup(xs, need_wakeup);
+		} else {
+			if (xsk_explicit_return(xs) &&
+			    need_wakeup & XDP_WAKEUP_RX)
+				xsk_wakeup(xs, XDP_WAKEUP_RX);
+			if (xs->tx)
+				/* Poll needs to drive Tx also in copy mode */
+				xsk_generic_xmit(sk);
+		}
 	}
 
 	if (xs->rx && !xskq_prod_is_empty(xs->rx))
@@ -1571,6 +1592,28 @@ static void xsk_delete_from_maps(struct xdp_sock *xs)
 	}
 }
 
+/* The pool, and with it the provider, may outlive the socket, see
+ * xp_put_pool()
+ */
+static void xsk_mp_release(struct xdp_sock *xs)
+{
+	struct xsk_buff_pool *pool = READ_ONCE(xs->pool);
+	struct net_device *dev;
+
+	if (!pool || !READ_ONCE(pool->mp))
+		return;
+
+	rtnl_lock();
+	dev = pool->netdev;
+	if (dev) {
+		netdev_lock_ops(dev);
+		if (pool->mp)
+			xsk_mp_del_sock(pool->mp, xs);
+		netdev_unlock_ops(dev);
+	}
+	rtnl_unlock();
+}
+
 static int xsk_release(struct socket *sock)
 {
 	struct sock *sk = sock->sk;
@@ -1592,6 +1635,7 @@ static int xsk_release(struct socket *sock)
 	sock_prot_inuse_add(net, sk->sk_prot, -1);
 
 	xsk_delete_from_maps(xs);
+	xsk_mp_release(xs);
 	mutex_lock(&xs->mutex);
 	xsk_unbind_dev(xs);
 	mutex_unlock(&xs->mutex);
@@ -1744,6 +1788,18 @@ static int xsk_bind(struct socket *sock, struct sockaddr_unsized *addr, int addr
 				goto out_unlock;
 			}
 
+			/* A queue with explicit return has one
+			 * receiving socket, and none once that one went
+			 */
+			if (xs->rx &&
+			    umem_xs->umem->flags & XDP_UMEM_EXPLICIT_RETURN &&
+			    (!umem_xs->pool->mp ||
+			     xsk_mp_rx_taken(umem_xs->pool->mp))) {
+				err = -EBUSY;
+				sockfd_put(sock);
+				goto out_unlock;
+			}
+
 			xp_get_pool(umem_xs->pool);
 			xs->pool = umem_xs->pool;
 
@@ -1796,6 +1852,8 @@ static int xsk_bind(struct socket *sock, struct sockaddr_unsized *addr, int addr
 	xs->sg = !!(xs->umem->flags & XDP_UMEM_SG_FLAG);
 	xs->queue_id = qid;
 	xp_add_xsk(xs->pool, xs);
+	if (xs->pool->mp)
+		xsk_mp_add_sock(xs->pool->mp, xs);
 
 	if (qid < dev->real_num_rx_queues) {
 		struct netdev_rx_queue *rxq;
diff --git a/net/xdp/xsk_mp.c b/net/xdp/xsk_mp.c
index f7db0d6f788a..fa5e715233ad 100644
--- a/net/xdp/xsk_mp.c
+++ b/net/xdp/xsk_mp.c
@@ -93,8 +93,10 @@ struct xsk_mp {
 	 * for, see xsk_mp_rcv()
 	 */
 	u32 owed;
-	/* Set once: see xsk_mp_add_sock() */
+	/* The receiving socket, see xsk_mp_add_sock() */
 	struct xdp_sock *xs;
+	/* A socket received on the queue, so no other may */
+	u8 rx_taken;
 	/* One node per chunk: chunks that page pools released, from any
 	 * context
 	 */
@@ -385,10 +387,27 @@ static bool xsk_mp_hand_off(struct page_pool *pp, netmem_ref netmem)
 	struct xdp_sock *xs;
 
 	niov->mp_hand_off = 0;
-	/* A buffer of the chunk reached the socket, which stays */
+	/* An owner outside the NAPI, as a queue restart or an RX error
+	 * recovery, runs in process context. The read section keeps the
+	 * socket and its RX ring until this is done, see xsk_mp_del_sock().
+	 */
+	rcu_read_lock();
 	xs = READ_ONCE(mp->xs);
+	if (!xs) {
+		/* Without a receiver the chunk is the application's again,
+		 * and counts against @pp no longer. @pp, and with it the
+		 * provider, may go once it does, so touch neither after that.
+		 */
+		/* Pairs with xsk_mp_take_fill() */
+		smp_store_release(&niov->mp_state, XSK_MP_USER);
+		net_mp_release_page_pool(pp, 1);
+		rcu_read_unlock();
+		return true;
+	}
+
 	xsk_mp_return(mp, xs, niov);
 	xsk_mp_publish(mp, xs);
+	rcu_read_unlock();
 	return true;
 }
 
@@ -410,7 +429,14 @@ static void xsk_mp_stop(struct xsk_mp *mp)
 
 	WRITE_ONCE(mp->rxq, NULL);
 	WRITE_ONCE(mp->fq, NULL);
-	/* Wait for wakeups that found the provider or the queue */
+	/* Later hand-offs return chunks without descriptors, also if the
+	 * receiving socket closes after its device went away and finds no
+	 * provider to leave, see xsk_mp_release()
+	 */
+	WRITE_ONCE(mp->xs, NULL);
+	/* Wait for wakeups that found the provider or the queue, and for
+	 * hand-offs that found the socket
+	 */
 	synchronize_net();
 	if (fq)
 		xp_dma_unmap(mp->pool, XSK_MP_DMA_ATTR);
@@ -586,18 +612,39 @@ int xsk_mp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
  */
 void xsk_mp_add_sock(struct xsk_mp *mp, struct xdp_sock *xs)
 {
-	if (xs->rx && !mp->xs) {
+	if (xs->rx && !mp->rx_taken) {
+		mp->rx_taken = 1;
 		/* The NAPI acquires the socket once it is set up */
 		smp_store_release(&mp->xs, xs);
 	}
 }
 
-/* The receiving socket, if any.
+/* Whether a socket received on the queue.
  * Context: RTNL and the instance lock of the device
  */
-struct xdp_sock *xsk_mp_sock(struct xsk_mp *mp)
+bool xsk_mp_rx_taken(struct xsk_mp *mp)
 {
-	return mp->xs;
+	return mp->rx_taken;
+}
+
+/* The provider stays until the pool goes, see xp_release_deferred(), so
+ * that the queue restarts from a freezable workqueue. A receiving socket
+ * that goes before leaves the queue to drop what it redirects, and
+ * xsk_unbind_dev() waits for the NAPI before its RX ring goes.
+ *
+ * Context: RTNL and the instance lock of the device
+ */
+void xsk_mp_del_sock(struct xsk_mp *mp, struct xdp_sock *xs)
+{
+	if (mp->xs != xs)
+		return;
+	WRITE_ONCE(mp->xs, NULL);
+	/* Waits for the NAPI polls and the hand-offs that may still write to
+	 * the RX ring of the socket. Later hand-offs give chunks back without
+	 * a descriptor, so the kernel owes the socket nothing.
+	 */
+	synchronize_net();
+	mp->owed = 0;
 }
 
 /* Context: RTNL and the instance lock of the device */
@@ -618,6 +665,30 @@ void xsk_mp_unbind(struct xsk_buff_pool *pool)
 	xsk_mp_detach(pool);
 }
 
+/* Schedules the queue NAPI, which refills from FILL. If the NAPI runs,
+ * NAPI_STATE_MISSED makes it poll again. Returned chunks need no wakeup, as
+ * their owner posts them as it lets go of them.
+ *
+ * Return: 0, or -ENETDOWN without a NAPI.
+ */
+int xsk_mp_wakeup(struct xsk_mp *mp)
+{
+	struct netdev_rx_queue *rxq;
+	struct napi_struct *napi;
+
+	/* See &netdev_rx_queue.napi */
+	rcu_read_lock();
+	rxq = READ_ONCE(mp->rxq);
+	napi = rxq ? READ_ONCE(rxq->napi) : NULL;
+	if (napi) {
+		local_bh_disable();
+		napi_schedule(napi);
+		local_bh_enable();
+	}
+	rcu_read_unlock();
+	return napi ? 0 : -ENETDOWN;
+}
+
 /* The net_iov of @netmem if it is one of ours; tells by its address */
 static struct net_iov *xsk_mp_niov(struct xsk_mp *mp, netmem_ref netmem)
 {
diff --git a/net/xdp/xsk_mp.h b/net/xdp/xsk_mp.h
index 46d73fdb40a1..b2e3909f282f 100644
--- a/net/xdp/xsk_mp.h
+++ b/net/xdp/xsk_mp.h
@@ -12,8 +12,10 @@ struct xsk_mp;
 int xsk_mp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
 		u16 queue_id, u16 flags);
 void xsk_mp_unbind(struct xsk_buff_pool *pool);
+int xsk_mp_wakeup(struct xsk_mp *mp);
 void xsk_mp_flush(struct xsk_mp *mp);
 void xsk_mp_add_sock(struct xsk_mp *mp, struct xdp_sock *xs);
-struct xdp_sock *xsk_mp_sock(struct xsk_mp *mp);
+void xsk_mp_del_sock(struct xsk_mp *mp, struct xdp_sock *xs);
+bool xsk_mp_rx_taken(struct xsk_mp *mp);
 
 #endif /* XSK_MP_H_ */
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 08/15] xsk: Drop references of a run of buffers at once
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (6 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 07/15] xsk: Receive with explicit chunk return Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 09/15] eth: fbnic: Receive into XDP-only memory providers Björn Töpel
                   ` (6 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

Currently, the AF_XDP provider drops the page pool reference of a
buffer inside the redirect, before the driver drops its own. A driver
that lets go of a page after its last buffer still holds the chunk
then, so the chunk returns later, on an extra empty descriptor. A
return in the middle of a poll also shows the RX ring and wakes the
reader.

Drop the references of a run of buffers from one chunk together, when
a buffer comes from another chunk or at the NAPI flush. A chunk that
this frees returns on the descriptor of the last buffer of the run. A
return while a run is pending ends the run first. Returns wait for the
flush of a poll that delivered to the socket, and go out at once
otherwise.

Only the queue NAPI delivers, so a run needs no lock and never
outlives its poll. A receiver that goes during the poll still gets its
run dropped before its RX ring goes.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - New in v2, reworked from "xsk: Drop the references of a run of
      buffers at once" of the v1 full series. The socket dropped its
      reference to a buffer inside the redirect, before the driver was
      done with the page, so a chunk that the driver lets go of after its
      last buffer still came back on an extra empty descriptor. A return
      while a run is pending ends the run first, so the run's last
      descriptor is the last one reserved, and returns of a poll that
      delivered to the socket wait for its flush.

 net/xdp/xsk.c    |  2 +-
 net/xdp/xsk_mp.c | 81 +++++++++++++++++++++++++++++++++++++-----------
 net/xdp/xsk_mp.h |  2 +-
 3 files changed, 65 insertions(+), 20 deletions(-)

diff --git a/net/xdp/xsk.c b/net/xdp/xsk.c
index 33d4cbee658d..2e37f3b2f82f 100644
--- a/net/xdp/xsk.c
+++ b/net/xdp/xsk.c
@@ -468,7 +468,7 @@ static void xsk_flush(struct xdp_sock *xs)
 	struct xsk_mp *mp = xs->pool->mp;
 
 	if (mp)
-		xsk_mp_flush(mp);
+		xsk_mp_flush(mp, xs);
 	xskq_prod_submit(xs->rx);
 	/* The provider releases FILL as it takes it, see xsk_mp_take_fill() */
 	if (!mp)
diff --git a/net/xdp/xsk_mp.c b/net/xdp/xsk_mp.c
index fa5e715233ad..4cf205fbe2e6 100644
--- a/net/xdp/xsk_mp.c
+++ b/net/xdp/xsk_mp.c
@@ -8,9 +8,11 @@
  * span chunks. Each buffer of a packet that XDP redirects to the socket
  * becomes one RX descriptor, at the address the device chose.
  *
- * The socket drops the page pool reference of each buffer it takes. A chunk
- * goes back to userspace once nothing in the kernel uses it, if a buffer of
- * it reached the socket: the descriptor of the buffer that freed it carries
+ * The socket drops the page pool references of the buffers it takes, those
+ * of a run of buffers of one chunk together, once a buffer of another chunk
+ * comes or the NAPI poll ends. A chunk goes back to userspace once nothing
+ * in the kernel uses it, if a buffer of it reached the socket: the last
+ * descriptor of the run that freed it carries
  * XDP_RX_CHUNK_RETURNED, or, when the device lets go of the chunk later, an
  * empty descriptor at the chunk does:
  *
@@ -84,6 +86,13 @@ struct xsk_mp {
 	 * file.
 	 */
 	struct xsk_queue *fq;
+	/* Chunk of the last buffers the socket took in this NAPI poll, and
+	 * their number. Their references are dropped together, see
+	 * xsk_mp_drop_pend(). Set only from the socket taking a buffer until
+	 * the flush of that poll, or a return in between.
+	 */
+	struct net_iov *pend;
+	u32 pend_nr;
 	/* Page pool of the chunks that went back to userspace and still count
 	 * against it, and their number, see xsk_mp_returned()
 	 */
@@ -282,19 +291,24 @@ static void xsk_mp_publish(struct xsk_mp *mp, struct xdp_sock *xs)
 	xs->sk.sk_data_ready(&xs->sk);
 }
 
-/* Drops the reference of the buffer of @niov that the socket took at the
- * last RX descriptor. Only the owner of the queue changes the count of a
- * chunk that delivers to the socket, so this needs no atomic.
+/* Drops the references of the buffers the socket took from one chunk. Only
+ * the owner of the queue changes the count of a chunk that delivers to the
+ * socket, so this needs no atomic.
  */
-static void xsk_mp_drop_buf(struct xsk_mp *mp, struct xdp_sock *xs,
-			    struct net_iov *niov)
+static void xsk_mp_drop_pend(struct xsk_mp *mp, struct xdp_sock *xs)
 {
+	struct net_iov *niov = mp->pend;
 	struct xdp_rxtx_ring *ring;
 	atomic_long_t *count;
 	long left;
 
+	if (!niov)
+		return;
+
+	mp->pend = NULL;
 	count = netmem_get_pp_ref_count_ref(net_iov_to_netmem(niov));
-	left = atomic_long_read(count) - 1;
+	left = atomic_long_read(count) - mp->pend_nr;
+	mp->pend_nr = 0;
 	if (left > 0) {
 		/* The device still uses it: its last put hands it off, onto
 		 * a descriptor that the RX ring keeps room for
@@ -307,8 +321,9 @@ static void xsk_mp_drop_buf(struct xsk_mp *mp, struct xdp_sock *xs,
 		return;
 	}
 
-	/* Free: back to userspace with this descriptor, with the count of a
-	 * free netmem
+	/* Free: back to userspace with the last descriptor of the run, with
+	 * the count of a free netmem. No return comes between a run and its
+	 * end, see xsk_mp_hand_off(), so that is the last one reserved.
 	 */
 	atomic_long_set(count, 1);
 	mp->owed -= niov->mp_hand_off;
@@ -321,6 +336,17 @@ static void xsk_mp_drop_buf(struct xsk_mp *mp, struct xdp_sock *xs,
 		XDP_RX_CHUNK_RETURNED;
 }
 
+/* The socket takes a buffer of @niov at the next RX descriptor */
+static void xsk_mp_take_buf(struct xsk_mp *mp, struct xdp_sock *xs,
+			    struct net_iov *niov)
+{
+	if (mp->pend != niov) {
+		xsk_mp_drop_pend(mp, xs);
+		mp->pend = niov;
+	}
+	mp->pend_nr++;
+}
+
 static netmem_ref xsk_mp_alloc_netmems(struct page_pool *pp, gfp_t gfp)
 {
 	struct xsk_mp *mp = pp->mp_priv;
@@ -384,6 +410,7 @@ static bool xsk_mp_hand_off(struct page_pool *pp, netmem_ref netmem)
 {
 	struct net_iov *niov = netmem_to_net_iov(netmem);
 	struct xsk_mp *mp = pp->mp_priv;
+	struct net_iov *pending;
 	struct xdp_sock *xs;
 
 	niov->mp_hand_off = 0;
@@ -405,8 +432,19 @@ static bool xsk_mp_hand_off(struct page_pool *pp, netmem_ref netmem)
 		return true;
 	}
 
+	/* A NAPI poll that delivered to the socket shows the descriptor with
+	 * its flush, as when fbnic cleans its rings after its packets or a
+	 * program drops a packet. A pending run ends first, so that its last
+	 * descriptor stays the last of the run. A NAPI after its flush, as
+	 * mlx5 when it reposts, shows the descriptor at once, and so does an
+	 * owner outside the NAPI, which runs only while the NAPI cannot.
+	 * Only the NAPI of the queue puts the socket on its flush list.
+	 */
+	pending = mp->pend;
+	xsk_mp_drop_pend(mp, xs);
 	xsk_mp_return(mp, xs, niov);
-	xsk_mp_publish(mp, xs);
+	if (!pending && !xs->flush_node.prev)
+		xsk_mp_publish(mp, xs);
 	rcu_read_unlock();
 	return true;
 }
@@ -760,10 +798,11 @@ static int xsk_mp_rcv(struct xsk_mp *mp, struct xdp_sock *xs,
 			goto drop;
 
 	/* Room for the packet, and for a return of every chunk that the
-	 * kernel owes after it, so returns never wait: those it owes, and one
-	 * per buffer, as the device may keep the chunk of each
+	 * kernel owes after it, so returns never wait: those it owes, the
+	 * pending one, and one per buffer, as each may start a run whose
+	 * chunk the device keeps
 	 */
-	k = 2 * n + mp->owed;
+	k = 2 * n + 1 + mp->owed;
 	if (xskq_prod_nb_free(xs->rx, k) < k) {
 		xs->rx_queue_full++;
 		return -ENOBUFS;
@@ -782,9 +821,9 @@ static int xsk_mp_rcv(struct xsk_mp *mp, struct xdp_sock *xs,
 			       skb_frag_off(frag);
 			len = skb_frag_size(frag);
 		}
+		xsk_mp_take_buf(mp, xs, niov);
 		__xskq_prod_reserve_desc(xs->rx, addr, len,
 					 i + 1 < n ? XDP_PKT_CONTD : 0);
-		xsk_mp_drop_buf(mp, xs, niov);
 	}
 
 	if (!head_desc) {
@@ -800,13 +839,19 @@ static int xsk_mp_rcv(struct xsk_mp *mp, struct xdp_sock *xs,
 
 /**
  * xsk_mp_flush - give back chunks at the end of a NAPI poll
- * @mp: provider of a socket that received in this poll
+ * @mp: provider of @xs
+ * @xs: socket that received in this poll
+ *
+ * @xs comes from the flush list, as the provider may have dropped it as
+ * its receiving socket during the poll, see xsk_mp_del_sock(). Its RX
+ * ring stays until the poll ends.
  *
  * Context: the queue NAPI, from xdp_do_flush(), before the RX ring is
  * submitted.
  */
-void xsk_mp_flush(struct xsk_mp *mp)
+void xsk_mp_flush(struct xsk_mp *mp, struct xdp_sock *xs)
 {
+	xsk_mp_drop_pend(mp, xs);
 	xsk_mp_flush_returned(mp);
 }
 
diff --git a/net/xdp/xsk_mp.h b/net/xdp/xsk_mp.h
index b2e3909f282f..3a83b615396b 100644
--- a/net/xdp/xsk_mp.h
+++ b/net/xdp/xsk_mp.h
@@ -13,7 +13,7 @@ int xsk_mp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
 		u16 queue_id, u16 flags);
 void xsk_mp_unbind(struct xsk_buff_pool *pool);
 int xsk_mp_wakeup(struct xsk_mp *mp);
-void xsk_mp_flush(struct xsk_mp *mp);
+void xsk_mp_flush(struct xsk_mp *mp, struct xdp_sock *xs);
 void xsk_mp_add_sock(struct xsk_mp *mp, struct xdp_sock *xs);
 void xsk_mp_del_sock(struct xsk_mp *mp, struct xdp_sock *xs);
 bool xsk_mp_rx_taken(struct xsk_mp *mp);
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 09/15] eth: fbnic: Receive into XDP-only memory providers
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (7 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 08/15] xsk: Drop references of a run of buffers at once Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 10/15] net/mlx5e: Handle restarts with XDP-only providers Björn Töpel
                   ` (5 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

fbnic still handles RX heads by page address, so an XDP-only provider
cannot back its RX pool.

Let the header page pool take an XDP-only provider, and handle heads
as netmem. The payload ring shares that pool, so both rings fill from
the provider, and header-split packets reach the program as
multi-buffer packets. Skip the prefetch of XDP-only heads, which may
cost a page walk.

Size the page pool of such a queue in the pages that the rings may
post, as the provider checks that size against its chunks. A device
that is down creates no page pool on ring changes, so refuse to grow
its BDQs with -EBUSY while a queue has such a provider, rather than
fail the next open. On a running device, the provider checks the new
pool first.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - v1 patch 9, "eth: fbnic: Support XDP redirect", was posted to
      net-next on its own and is a dependency.
    - Refuse to grow the BDQs while the device is down and a queue has
      such a provider, as nothing checks them before the next open, and
      size the page pool for the provider in the pages that the BDQs
      post (Sashiko).
    - The message now says that the payload ring shares the header page
      pool, so both rings fill from the provider.

 .../net/ethernet/meta/fbnic/fbnic_ethtool.c   | 22 ++++++++++
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c  | 41 +++++++++++--------
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h  |  8 ++++
 3 files changed, 54 insertions(+), 17 deletions(-)

diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c b/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c
index 9714a89977fa..3355aadeb8ff 100644
--- a/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c
+++ b/drivers/net/ethernet/meta/fbnic/fbnic_ethtool.c
@@ -6,6 +6,7 @@
 #include <linux/netdevice.h>
 #include <linux/pci.h>
 #include <net/ipv6.h>
+#include <net/netdev_queues.h>
 
 #include "fbnic.h"
 #include "fbnic_netdev.h"
@@ -341,6 +342,16 @@ static void fbnic_set_rings(struct fbnic_net *fbn,
 	fbn->hds_thresh = kernel_ring->hds_thresh;
 }
 
+static bool fbnic_has_xdp_only_mp(struct net_device *netdev)
+{
+	unsigned int i;
+
+	for (i = 0; i < netdev->real_num_rx_queues; i++)
+		if (netif_rxq_has_xdp_only_mp(netdev, i))
+			return true;
+	return false;
+}
+
 static int
 fbnic_set_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring,
 		    struct kernel_ethtool_ringparam *kernel_ring,
@@ -386,6 +397,17 @@ fbnic_set_ringparam(struct net_device *netdev, struct ethtool_ringparam *ring,
 	}
 
 	if (!netif_running(netdev)) {
+		/* No page pool lets the provider check larger rings before
+		 * the device opens, which would then fail
+		 */
+		if (fbnic_bdq_pages(ring->rx_mini_pending,
+				    ring->rx_jumbo_pending) >
+		    fbnic_bdq_pages(fbn->hpq_size, fbn->ppq_size) &&
+		    fbnic_has_xdp_only_mp(netdev)) {
+			NL_SET_ERR_MSG_MOD(extack,
+					   "Cannot grow the BDQs while the device is down and a queue has an XDP-only memory provider");
+			return -EBUSY;
+		}
 		fbnic_set_rings(fbn, ring, kernel_ring);
 		return 0;
 	}
diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c
index 9525ad2f7e14..22e9fa5f8f15 100644
--- a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c
+++ b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c
@@ -765,15 +765,14 @@ static void fbnic_page_pool_init(struct fbnic_ring *ring, unsigned int idx,
 	rx_buf->netmem = netmem;
 }
 
-static struct page *
+static netmem_ref
 fbnic_page_pool_get_head(struct fbnic_q_triad *qt, unsigned int idx)
 {
 	struct fbnic_rx_buf *rx_buf = &qt->sub0.rx_buf[idx];
 
 	rx_buf->pagecnt_bias--;
 
-	/* sub0 is always fed system pages, from the NAPI-level page_pool */
-	return netmem_to_page(rx_buf->netmem);
+	return rx_buf->netmem;
 }
 
 static netmem_ref
@@ -1001,13 +1000,12 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 	unsigned int len = FIELD_GET(FBNIC_RCD_AL_BUFF_LEN_MASK, rcd);
 	unsigned int hdr_pg_idx = fbnic_rcd_bd_idx(&qt->sub0, rcd);
 	unsigned int frame_sz, hdr_pg_start, hdr_pg_end, headroom;
-	unsigned char *hdr_start;
-	struct page *page;
+	netmem_ref netmem;
 
 	/* data_hard_start should always be NULL when this is called */
 	WARN_ON_ONCE(pkt->buff.data_hard_start);
 
-	page = fbnic_page_pool_get_head(qt, hdr_pg_idx);
+	netmem = fbnic_page_pool_get_head(qt, hdr_pg_idx);
 
 	/* Short-cut the end calculation if we know page is fully consumed */
 	hdr_pg_end = FIELD_GET(FBNIC_RCD_AL_PAGE_FIN, rcd) ?
@@ -1020,15 +1018,20 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 	hdr_pg_start += fbnic_rcd_bd_page_offset(&qt->sub0, rcd);
 
 	/* Sync DMA buffer */
-	dma_sync_single_range_for_cpu(nv->dev, page_pool_get_dma_addr(page),
+	dma_sync_single_range_for_cpu(nv->dev,
+				      page_pool_get_dma_addr_netmem(netmem),
 				      hdr_pg_start, frame_sz,
 				      DMA_BIDIRECTIONAL);
 
 	/* Build frame around buffer */
-	hdr_start = page_address(page) + hdr_pg_start;
-	net_prefetch(hdr_start + headroom);
-	xdp_prepare_buff(&pkt->buff, hdr_start, headroom,
-			 len - FBNIC_RX_PAD, true);
+	xdp_prepare_buff(&pkt->buff, xdp_netmem_address(netmem) + hdr_pg_start,
+			 headroom, len - FBNIC_RX_PAD, true);
+	pkt->head = netmem;
+	/* The kernel reads an XDP-only head only if the program does, and a
+	 * prefetch may cost a page walk
+	 */
+	if (!netmem_is_net_iov(netmem))
+		net_prefetch(pkt->buff.data);
 
 	pkt->hwtstamp = 0;
 	pkt->add_frag_failed = false;
@@ -1072,8 +1075,6 @@ static void fbnic_add_rx_frag(struct fbnic_napi_vector *nv, u64 rcd,
 static void fbnic_put_pkt_buff(struct fbnic_q_triad *qt,
 			       struct fbnic_pkt_buff *pkt, int budget)
 {
-	struct page *page;
-
 	if (!pkt->buff.data_hard_start)
 		return;
 
@@ -1092,8 +1093,7 @@ static void fbnic_put_pkt_buff(struct fbnic_q_triad *qt,
 		}
 	}
 
-	page = virt_to_page(pkt->buff.data_hard_start);
-	page_pool_put_full_page(qt->sub0.page_pool, page, !!budget);
+	page_pool_put_full_netmem(qt->sub0.page_pool, pkt->head, !!budget);
 }
 
 static struct sk_buff *fbnic_build_skb(struct fbnic_napi_vector *nv,
@@ -1612,7 +1612,8 @@ fbnic_alloc_qt_page_pools(struct fbnic_net *fbn, struct fbnic_q_triad *qt,
 	struct page_pool_params pp_params = {
 		.order = 0,
 		.flags = PP_FLAG_DMA_MAP |
-			 PP_FLAG_DMA_SYNC_DEV,
+			 PP_FLAG_DMA_SYNC_DEV |
+			 PP_FLAG_ALLOW_XDP_ONLY_NETMEM,
 		.pool_size = fbn->hpq_size + fbn->ppq_size,
 		.nid = NUMA_NO_NODE,
 		.dev = fbn->netdev->dev.parent,
@@ -1632,8 +1633,14 @@ fbnic_alloc_qt_page_pools(struct fbnic_net *fbn, struct fbnic_q_triad *qt,
 	 * NAPI_POLL_WEIGHT possibly make more sense? The question is how
 	 * may pages do we need to hold in reserve to get the best return
 	 * without hogging too much system memory.
+	 *
+	 * An XDP-only provider checks the size against its chunks, so it
+	 * must see every page that the rings may post.
 	 */
-	if (pp_params.pool_size > 32768)
+	if (netif_rxq_has_xdp_only_mp(fbn->netdev, rxq_idx))
+		pp_params.pool_size = fbnic_bdq_pages(fbn->hpq_size,
+						      fbn->ppq_size);
+	else if (pp_params.pool_size > 32768)
 		pp_params.pool_size = 32768;
 
 	pp = page_pool_create(&pp_params);
diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.h b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.h
index a61ac2df7c03..03b668ff8a42 100644
--- a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.h
+++ b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.h
@@ -81,6 +81,7 @@ struct fbnic_net;
 
 struct fbnic_pkt_buff {
 	struct xdp_buff buff;
+	netmem_ref head;
 	ktime_t hwtstamp;
 	bool add_frag_failed;
 };
@@ -185,6 +186,13 @@ static inline u16 fbnic_bd_page_count(const struct fbnic_ring *bdq)
 	return 1U << bdq->bd_page_shift;
 }
 
+static inline u32 fbnic_bdq_pages(u32 hpq_size, u32 ppq_size)
+{
+	u32 shift = ilog2(PAGE_SIZE / FBNIC_BD_PAGE_SIZE);
+
+	return (hpq_size >> shift) + (ppq_size >> shift);
+}
+
 netdev_tx_t fbnic_xmit_frame(struct sk_buff *skb, struct net_device *dev);
 netdev_features_t
 fbnic_features_check(struct sk_buff *skb, struct net_device *dev,
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 10/15] net/mlx5e: Handle restarts with XDP-only providers
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (8 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 09/15] eth: fbnic: Receive into XDP-only memory providers Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 11/15] net/mlx5e: Receive into XDP-only memory providers Björn Töpel
                   ` (4 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

An XDP-only provider backs an RQ with UMEM chunks that come back only
through that queue. Currently, mlx5 assumes that an RQ can always get
more pages, which does not hold across a channel restart.

While a queue has such a provider:
- skip its RQ, as the XSK RQ already is, in the wait for posted WQEs
  on activation. FILL may stay empty, so the wait would time out and
  the health reporter could turn off the ICOSQ;
- close the old channels of a switch before the new ones run, as the
  old RQs hold the buffers that the new ones need, and their last puts
  must not overlap the new NAPIs.

A channel switch, as for an MTU change, then stops traffic on every
channel while it runs, as without tis_tir_td_order.

Nothing installs such a provider on mlx5 before the next patch.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Split out of v1 patch 12, which skipped the wait for the minimum of
      posted WQEs.
    - Close the old channels of a switch before the new ones run
      (Sashiko).
    - The message says that every channel stops while a switch runs, and
      that closing the old channels first also keeps the last puts of the
      old buffers off the NAPIs of the new ones.

 .../net/ethernet/mellanox/mlx5/core/en_main.c | 36 ++++++++++++++++---
 1 file changed, 32 insertions(+), 4 deletions(-)

diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c
index 54f4f5a097c8..a76ba297c9a9 100644
--- a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c
+++ b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c
@@ -3102,6 +3102,14 @@ static int mlx5e_wait_channels_min_rx_wqes(struct mlx5e_channels *chs)
 		if (test_bit(MLX5E_CHANNEL_STATE_XSK, c->state))
 			continue;
 
+		/* An RQ that an XDP-only provider backs fills from the FILL
+		 * ring of its socket, which stays empty until the socket
+		 * gets its chunks back, so a queue that restarts under a
+		 * slow reader would never meet the bound.
+		 */
+		if (netif_rxq_has_xdp_only_mp(c->netdev, c->ix))
+			continue;
+
 		err |= mlx5e_wait_for_min_rx_wqes(&c->rq, timeout);
 
 		/* Don't wait on the XSK RQ, because the newer xdpsock sample
@@ -3528,11 +3536,29 @@ static void mlx5e_close_channels_xsk(struct mlx5e_channels *chs)
 	}
 }
 
+static bool mlx5e_has_xdp_only_mp(struct mlx5e_priv *priv, unsigned int n)
+{
+	unsigned int i;
+
+	for (i = 0; i < n; i++)
+		if (netif_rxq_has_xdp_only_mp(priv->netdev, i))
+			return true;
+	return false;
+}
+
+static bool mlx5e_close_old_first(struct mlx5e_priv *priv,
+				  struct mlx5e_channels *chs)
+{
+	if (mlx5e_has_xdp_only_mp(priv, priv->netdev->real_num_rx_queues))
+		return true;
+	return !MLX5_CAP_GEN(priv->mdev, tis_tir_td_order);
+}
+
 static int mlx5e_switch_priv_channels(struct mlx5e_priv *priv,
 				      struct mlx5e_channels *old_chs,
 				      struct mlx5e_channels *new_chs,
 				      mlx5e_fp_preactivate preactivate,
-				      void *context)
+				      void *context, bool old_first)
 {
 	struct net_device *netdev = priv->netdev;
 	int carrier_ok;
@@ -3557,7 +3583,7 @@ static int mlx5e_switch_priv_channels(struct mlx5e_priv *priv,
 	}
 
 	mlx5e_set_xdp_feature(priv);
-	if (!MLX5_CAP_GEN(priv->mdev, tis_tir_td_order))
+	if (old_first)
 		mlx5e_close_channels(old_chs);
 	else
 		mlx5e_close_channels_xsk(old_chs);
@@ -3580,6 +3606,7 @@ int mlx5e_safe_switch_params(struct mlx5e_priv *priv,
 			     void *context, bool reset)
 {
 	struct mlx5e_channels *old_chs, *new_chs;
+	bool old_first;
 	int err;
 
 	reset &= test_bit(MLX5E_STATE_OPENED, &priv->state);
@@ -3602,13 +3629,14 @@ int mlx5e_safe_switch_params(struct mlx5e_priv *priv,
 		goto err_cancel_selq;
 
 	*old_chs = priv->channels;
+	old_first = mlx5e_close_old_first(priv, old_chs);
 
 	err = mlx5e_switch_priv_channels(priv, old_chs, new_chs,
-					 preactivate, context);
+					 preactivate, context, old_first);
 	if (err)
 		goto err_close;
 
-	if (MLX5_CAP_GEN(priv->mdev, tis_tir_td_order))
+	if (!old_first)
 		mlx5e_close_channels(old_chs);
 
 	kfree(new_chs);
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 11/15] net/mlx5e: Receive into XDP-only memory providers
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (9 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 10/15] net/mlx5e: Handle restarts with XDP-only providers Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 12/15] net/mlx5e: Release XDP-only pages earlier Björn Töpel
                   ` (3 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

mlx5 still refuses queue restarts with an XDP program, and its page
pools take no provider next to XDP.

Let striding RQs with a program take XDP-only providers, and accept
queue restarts with one, as other providers refuse XDP. Binds on the
cyclic RQ fail, as it would spin on a short FILL ring.

While a queue has such a provider, refuse with -EBUSY:
- a switch to the cyclic RQ;
- PTP RX, TX port timestamps and HTB offload, as queue restarts clone
  no channel under them, so unbind would fail and binds fail with
  -EOPNOTSUPP;
- growing the RQs of a device that is down, which would fail the next
  open.

A devlink eswitch mode change bypasses these checks, leaving the queue
on system pages that the socket drops.

At MTU 1500, the linear RQ puts one packet per 4 KiB chunk. The
nonlinear RQ puts every byte in fragments, so its head reaches the
socket only with metadata. A bind or unbind pauses all channels
briefly.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Move the skip of the wait for posted WQEs to patch 10, and use the
      net/mlx5e prefix.
    - Let only striding RQs take XDP-only providers. The cyclic RQ posts
      whole bulks only, and would spin on a short FILL ring (Sashiko).
    - Refuse a switch from the striding RQ to the cyclic one, PTP RX, TX
      port timestamps and HTB offload while a queue has such a provider,
      and growing the RQs while the device is down (Sashiko).
    - The message covers the nonlinear RQ and its empty heads (Sashiko),
      and says what users see.

 .../net/ethernet/mellanox/mlx5/core/en_main.c | 62 ++++++++++++++++++-
 .../net/ethernet/mellanox/mlx5/core/en_rx.c   | 10 +--
 2 files changed, 64 insertions(+), 8 deletions(-)

diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c
index a76ba297c9a9..74a2ae37a587 100644
--- a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c
+++ b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c
@@ -1012,6 +1012,13 @@ static int mlx5e_alloc_rq(struct mlx5e_params *params,
 
 		pp_params.order     = pool_order;
 		pp_params.flags     = PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV;
+		/* Trap and PTP RQs use queue 0 too, without a program. A
+		 * cyclic RQ posts whole bulks only, and would spin in NAPI
+		 * on a short FILL ring.
+		 */
+		if (params->xdp_prog &&
+		    rq->wq_type == MLX5_WQ_TYPE_LINKED_LIST_STRIDING_RQ)
+			pp_params.flags |= PP_FLAG_ALLOW_XDP_ONLY_NETMEM;
 		pp_params.pool_size = pool_size;
 		pp_params.nid       = node;
 		pp_params.dev       = rq->pdev;
@@ -3609,6 +3616,46 @@ int mlx5e_safe_switch_params(struct mlx5e_priv *priv,
 	bool old_first;
 	int err;
 
+	/* An XDP-only memory provider takes a striding RQ, and the socket
+	 * that installed it would lose its queue without a word, also when
+	 * the device opens later
+	 */
+	if (priv->channels.params.rq_wq_type ==
+	    MLX5_WQ_TYPE_LINKED_LIST_STRIDING_RQ &&
+	    params->rq_wq_type != MLX5_WQ_TYPE_LINKED_LIST_STRIDING_RQ &&
+	    mlx5e_has_xdp_only_mp(priv, priv->netdev->real_num_rx_queues)) {
+		netdev_warn(priv->netdev,
+			    "Cannot leave the striding RQ while a queue has an XDP-only memory provider\n");
+		return -EBUSY;
+	}
+
+	/* mlx5e_queue_mem_alloc() clones no channel while PTP is on, so the
+	 * provider of any queue could not go: its unbind restarts the queue
+	 */
+	if (((params->ptp_rx && !priv->channels.params.ptp_rx) ||
+	     (MLX5E_GET_PFLAG(params, MLX5E_PFLAG_TX_PORT_TS) &&
+	      !MLX5E_GET_PFLAG(&priv->channels.params,
+			       MLX5E_PFLAG_TX_PORT_TS))) &&
+	    mlx5e_has_xdp_only_mp(priv, priv->netdev->real_num_rx_queues)) {
+		netdev_warn(priv->netdev,
+			    "Cannot turn on PTP while a queue has an XDP-only memory provider\n");
+		return -EBUSY;
+	}
+
+	/* Closed channels open no RQ that would let the provider check a
+	 * larger page pool, so the device would fail to open later
+	 */
+	if (!test_bit(MLX5E_STATE_OPENED, &priv->state) &&
+	    params->rq_wq_type == MLX5_WQ_TYPE_LINKED_LIST_STRIDING_RQ &&
+	    mlx5e_mpwqe_get_log_rq_size(priv->mdev, params, NULL) >
+	    mlx5e_mpwqe_get_log_rq_size(priv->mdev, &priv->channels.params,
+					NULL) &&
+	    mlx5e_has_xdp_only_mp(priv, priv->netdev->real_num_rx_queues)) {
+		netdev_warn(priv->netdev,
+			    "Cannot grow the RQs while the device is down and a queue has an XDP-only memory provider\n");
+		return -EBUSY;
+	}
+
 	reset &= test_bit(MLX5E_STATE_OPENED, &priv->state);
 	if (!reset)
 		return mlx5e_switch_priv_params(priv, params, preactivate, context);
@@ -4166,11 +4213,21 @@ static int mlx5e_setup_tc(struct net_device *dev, enum tc_setup_type type,
 		err = mlx5e_setup_tc_mqprio(priv, type_data);
 		mutex_unlock(&priv->state_lock);
 		return err;
-	case TC_SETUP_QDISC_HTB:
+	case TC_SETUP_QDISC_HTB: {
+		struct tc_htb_qopt_offload *htb_qopt = type_data;
+
+		/* As for PTP, see mlx5e_safe_switch_params() */
+		if (htb_qopt->command == TC_HTB_CREATE &&
+		    mlx5e_has_xdp_only_mp(priv, dev->real_num_rx_queues)) {
+			NL_SET_ERR_MSG_MOD(htb_qopt->extack,
+					   "Cannot offload HTB while a queue has an XDP-only memory provider");
+			return -EBUSY;
+		}
 		mutex_lock(&priv->state_lock);
 		err = mlx5e_htb_setup_tc(priv, type_data);
 		mutex_unlock(&priv->state_lock);
 		return err;
+	}
 	default:
 		return -EOPNOTSUPP;
 	}
@@ -5872,10 +5929,9 @@ static int mlx5e_queue_mem_alloc(struct net_device *dev,
 
 	if (MLX5E_GET_PFLAG(&chs->params, MLX5E_PFLAG_TX_PORT_TS) ||
 	    chs->params.ptp_rx   ||
-	    chs->params.xdp_prog ||
 	    priv->htb) {
 		netdev_err(priv->netdev,
-			   "Cloning channels with Port/rx PTP, XDP or HTB is not supported\n");
+			   "Cloning channels with Port/rx PTP or HTB is not supported\n");
 		err = -EOPNOTSUPP;
 		goto unlock;
 	}
diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c
index 1586cb2404c0..43a382fcd3ad 100644
--- a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c
+++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c
@@ -327,7 +327,7 @@ static void *mlx5e_mpwqe_get_linear_page_frag(struct mlx5e_rq *rq)
 	frag_offset = li->frag_page.frags << MLX5E_XDP_LOG_MAX_LINEAR_SZ;
 	WARN_ON(frag_offset >= BIT(rq->mpwqe.page_shift));
 
-	return netmem_address(li->frag_page.netmem) + frag_offset;
+	return xdp_netmem_address(li->frag_page.netmem) + frag_offset;
 }
 
 static inline int mlx5e_get_rx_frag(struct mlx5e_rq *rq,
@@ -1585,7 +1585,7 @@ mlx5e_skb_from_cqe_linear(struct mlx5e_rq *rq, struct mlx5e_wqe_frag_info *wi,
 	dma_addr_t addr;
 	u32 frag_size;
 
-	va             = netmem_address(frag_page->netmem) + wi->offset;
+	va             = xdp_netmem_address(frag_page->netmem) + wi->offset;
 	data           = va + rx_headroom;
 	frag_size      = MLX5_SKB_FRAG_SZ(rx_headroom + cqe_bcnt);
 
@@ -1640,7 +1640,7 @@ mlx5e_skb_from_cqe_nonlinear(struct mlx5e_rq *rq, struct mlx5e_wqe_frag_info *wi
 
 	frag_page = wi->frag_page;
 
-	va = netmem_address(frag_page->netmem) + wi->offset;
+	va = xdp_netmem_address(frag_page->netmem) + wi->offset;
 	frag_consumed_bytes = min_t(u32, frag_info->frag_size, cqe_bcnt);
 
 	addr = page_pool_get_dma_addr_netmem(frag_page->netmem);
@@ -1940,7 +1940,7 @@ mlx5e_skb_from_cqe_mpwrq_nonlinear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *w
 
 	prog = rcu_dereference(rq->xdp_prog);
 
-	head_addr = netmem_address(head_page->netmem) + head_offset;
+	head_addr = xdp_netmem_address(head_page->netmem) + head_offset;
 
 	if (prog) {
 		/* area for bpf_xdp_[store|load]_bytes */
@@ -2114,7 +2114,7 @@ mlx5e_skb_from_cqe_mpwrq_linear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
 		return NULL;
 	}
 
-	va             = netmem_address(frag_page->netmem) + head_offset;
+	va             = xdp_netmem_address(frag_page->netmem) + head_offset;
 	data           = va + rx_headroom;
 	frag_size      = MLX5_SKB_FRAG_SZ(rx_headroom + cqe_bcnt);
 
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 12/15] net/mlx5e: Release XDP-only pages earlier
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (10 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 11/15] net/mlx5e: Receive into XDP-only memory providers Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 13/15] net/mlx5e: Test for XDP-only pages per RQ Björn Töpel
                   ` (2 subsequent siblings)
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

Before this patch, a striding RQ released pages only when reposting
their WQE, so a provider page returned its chunk late, on an extra
empty descriptor. The chunks come back without this patch; it only
saves that descriptor.

On the linear path, release a provider page once XDP took the buffer
in its last stride, and let the WQE skip it, also at close. The chunk
then comes back on the packet's descriptor, as the socket drops its
references last. The device writes nothing to a page after its last
stride, so this cannot race with DMA.

Also skip the head and xdp_frame prefetches of XDP-only pages. Only
the program reads them, and after the early release each packet lands
in an untouched page, where a prefetch may cost a page walk.

On ConnectX-7, one core, 66-byte frames offered at 61 Mpps, a program
that parses headers and an application that reads the payload, this
and the batched reference drops took a 4 KiB-chunk queue from
12.40-12.66 to 15.65-15.92 Mpps.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - New in v2, from "eth: mlx5e: Let go of XDP-only pages after their
      last stride" and "eth: mlx5e: Skip head prefetches for XDP-only
      buffers" of the v1 full series. A striding RQ let go of a page only
      when it reposted its WQE, so its chunk came back on an extra empty
      descriptor, and the head prefetch of a page that the CPU had not
      touched cost a page walk. The message has the numbers.

 .../net/ethernet/mellanox/mlx5/core/en_rx.c   | 23 +++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)

diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c
index 43a382fcd3ad..a93eefa581c0 100644
--- a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c
+++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c
@@ -2107,6 +2107,7 @@ mlx5e_skb_from_cqe_mpwrq_linear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
 	void *va, *data;
 	dma_addr_t addr;
 	u32 frag_size;
+	bool xdp_only;
 
 	/* Check packet size. Note LRO doesn't use linear SKB */
 	if (unlikely(cqe_bcnt > rq->hw_mtu)) {
@@ -2121,18 +2122,36 @@ mlx5e_skb_from_cqe_mpwrq_linear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
 	addr = page_pool_get_dma_addr_netmem(frag_page->netmem);
 	dma_sync_single_range_for_cpu(rq->pdev, addr, head_offset,
 				      frag_size, rq->buff.map_dir);
-	net_prefetch(data);
+	/* The kernel reads an XDP-only head only if the program does, and a
+	 * prefetch may cost a page walk
+	 */
+	xdp_only = netmem_is_net_iov(frag_page->netmem);
+	if (!xdp_only)
+		net_prefetch(data);
 
 	prog = rcu_dereference(rq->xdp_prog);
 	if (prog) {
 		struct mlx5e_xdp_buff *mxbuf = &rq->mxbuf;
 
-		net_prefetchw(va); /* xdp_frame data area */
+		if (!xdp_only)
+			net_prefetchw(va); /* xdp_frame data area */
 		mlx5e_fill_mxbuf(rq, cqe, va, rx_headroom, rq->buff.frame0_sz,
 				 cqe_bcnt, mxbuf);
 		if (mlx5e_xdp_handle(rq, prog, mxbuf)) {
 			if (__test_and_clear_bit(MLX5E_RQ_FLAG_XDP_XMIT, rq->flags))
 				frag_page->frags++;
+			/* The device is done with a provider page after its
+			 * last stride. Letting go of it now, before the socket
+			 * drops its references, gives the chunk back on the
+			 * packet's descriptor rather than an empty one.
+			 */
+			if (xdp_only &&
+			    head_offset + BIT(rq->mpwqe.log_stride_sz) >=
+			    BIT(rq->mpwqe.page_shift)) {
+				mlx5e_page_release_fragmented(rq->page_pool,
+							      frag_page);
+				__set_bit(page_idx, wi->skip_release_bitmap);
+			}
 			return NULL; /* page/packet was consumed by XDP */
 		}
 
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 13/15] net/mlx5e: Test for XDP-only pages per RQ
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (11 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 12/15] net/mlx5e: Release XDP-only pages earlier Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 14/15] selftests: net: xsk: Test explicit chunk return Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 15/15] Documentation: xsk: Describe " Björn Töpel
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

Before this patch, the linear striding RQ handler tested every page
for a net_iov, to skip the prefetches of XDP-only pages and to release
them after their last stride. RQs of system pages never get a net_iov,
yet the test, and the values it keeps live across the program call,
cost native XDP 7 instructions per packet on every RQ.

An RQ gets an XDP-only provider only through a queue restart, which
allocates new RQs, so whether an RQ receives into net_iovs is fixed
when its page pool is created. Make the choice once per RQ. Build the
linear handler in two variants and give an RQ the XDP-only one when
its pool has such a provider. RQs of system pages then run the code
they ran before XDP-only providers existed, and provider RQs skip the
test as well.

Binding or unbinding a provider restarts the queue and so picks the
handler again. Swapping the program keeps the RQs, and a provider
needs a program throughout.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - New in v2.

 drivers/net/ethernet/mellanox/mlx5/core/en.h  |  1 +
 .../net/ethernet/mellanox/mlx5/core/en_main.c |  2 +
 .../net/ethernet/mellanox/mlx5/core/en_rx.c   | 54 ++++++++++++++++---
 3 files changed, 50 insertions(+), 7 deletions(-)

diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en.h b/drivers/net/ethernet/mellanox/mlx5/core/en.h
index 657a7d59c845..05d2216ab981 100644
--- a/drivers/net/ethernet/mellanox/mlx5/core/en.h
+++ b/drivers/net/ethernet/mellanox/mlx5/core/en.h
@@ -618,6 +618,7 @@ typedef void (*mlx5e_fp_dealloc_wqe)(struct mlx5e_rq*, u16);
 typedef void (*mlx5e_fp_shampo_dealloc_hd)(struct mlx5e_rq*, u16, u16, bool);
 
 int mlx5e_rq_set_handlers(struct mlx5e_rq *rq, struct mlx5e_params *params, bool xsk);
+void mlx5e_rq_set_xdp_only(struct mlx5e_rq *rq);
 void mlx5e_rq_set_trap_handlers(struct mlx5e_rq *rq, struct mlx5e_params *params);
 
 enum mlx5e_rq_flag {
diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c
index 74a2ae37a587..8fdd78f74f38 100644
--- a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c
+++ b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c
@@ -1050,6 +1050,8 @@ static int mlx5e_alloc_rq(struct mlx5e_params *params,
 							 MEM_TYPE_PAGE_POOL, rq->page_pool);
 			if (err)
 				goto err_destroy_page_pool;
+			if (rq->xdp_rxq.xdp_only_area)
+				mlx5e_rq_set_xdp_only(rq);
 		}
 	}
 
diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c
index a93eefa581c0..3845c71c5680 100644
--- a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c
+++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c
@@ -70,6 +70,11 @@ static struct sk_buff *
 mlx5e_skb_from_cqe_mpwrq_nonlinear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
 				   struct mlx5_cqe64 *cqe, u16 cqe_bcnt, u32 head_offset,
 				   u32 page_idx);
+static struct sk_buff *
+mlx5e_skb_from_cqe_mpwrq_linear_xo(struct mlx5e_rq *rq,
+				   struct mlx5e_mpw_info *wi,
+				   struct mlx5_cqe64 *cqe, u16 cqe_bcnt,
+				   u32 head_offset, u32 page_idx);
 static void mlx5e_handle_rx_cqe(struct mlx5e_rq *rq, struct mlx5_cqe64 *cqe);
 static void mlx5e_handle_rx_cqe_mpwrq(struct mlx5e_rq *rq, struct mlx5_cqe64 *cqe);
 static void mlx5e_handle_rx_cqe_mpwrq_shampo(struct mlx5e_rq *rq, struct mlx5_cqe64 *cqe);
@@ -2094,10 +2099,17 @@ mlx5e_skb_from_cqe_mpwrq_nonlinear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *w
 	return skb;
 }
 
-static struct sk_buff *
-mlx5e_skb_from_cqe_mpwrq_linear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
-				struct mlx5_cqe64 *cqe, u16 cqe_bcnt, u32 head_offset,
-				u32 page_idx)
+/* An RQ of an XDP-only memory provider has only its net_iovs, see
+ * mlx5e_rq_set_xdp_only(). A constant @xdp_only keeps the test out of RQs
+ * of system pages.
+ */
+/* Inlined into each handler below, so xdp_only is a compile-time constant */
+static __always_inline struct sk_buff *
+__mlx5e_skb_from_cqe_mpwrq_linear(struct mlx5e_rq *rq,
+				  struct mlx5e_mpw_info *wi,
+				  struct mlx5_cqe64 *cqe, u16 cqe_bcnt,
+				  u32 head_offset, u32 page_idx,
+				  const bool xdp_only)
 {
 	struct mlx5e_frag_page *frag_page = &wi->alloc_units.frag_pages[page_idx];
 	u16 rx_headroom = rq->buff.headroom;
@@ -2107,7 +2119,6 @@ mlx5e_skb_from_cqe_mpwrq_linear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
 	void *va, *data;
 	dma_addr_t addr;
 	u32 frag_size;
-	bool xdp_only;
 
 	/* Check packet size. Note LRO doesn't use linear SKB */
 	if (unlikely(cqe_bcnt > rq->hw_mtu)) {
@@ -2125,7 +2136,6 @@ mlx5e_skb_from_cqe_mpwrq_linear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
 	/* The kernel reads an XDP-only head only if the program does, and a
 	 * prefetch may cost a page walk
 	 */
-	xdp_only = netmem_is_net_iov(frag_page->netmem);
 	if (!xdp_only)
 		net_prefetch(data);
 
@@ -2171,6 +2181,35 @@ mlx5e_skb_from_cqe_mpwrq_linear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
 	return skb;
 }
 
+static struct sk_buff *
+mlx5e_skb_from_cqe_mpwrq_linear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
+				struct mlx5_cqe64 *cqe, u16 cqe_bcnt,
+				u32 head_offset, u32 page_idx)
+{
+	return __mlx5e_skb_from_cqe_mpwrq_linear(rq, wi, cqe, cqe_bcnt,
+						 head_offset, page_idx, false);
+}
+
+static struct sk_buff *
+mlx5e_skb_from_cqe_mpwrq_linear_xo(struct mlx5e_rq *rq,
+				   struct mlx5e_mpw_info *wi,
+				   struct mlx5_cqe64 *cqe, u16 cqe_bcnt,
+				   u32 head_offset, u32 page_idx)
+{
+	return __mlx5e_skb_from_cqe_mpwrq_linear(rq, wi, cqe, cqe_bcnt,
+						 head_offset, page_idx, true);
+}
+
+/* An XDP-only memory provider backs the page pool of @rq, which then
+ * receives into its net_iovs only
+ */
+void mlx5e_rq_set_xdp_only(struct mlx5e_rq *rq)
+{
+	if (rq->mpwqe.skb_from_cqe_mpwrq == mlx5e_skb_from_cqe_mpwrq_linear)
+		rq->mpwqe.skb_from_cqe_mpwrq =
+			mlx5e_skb_from_cqe_mpwrq_linear_xo;
+}
+
 static struct sk_buff *
 mlx5e_skb_from_cqe_shampo(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
 			  struct mlx5_cqe64 *cqe, u16 header_index)
@@ -2398,10 +2437,11 @@ static void mlx5e_handle_rx_cqe_mpwrq(struct mlx5e_rq *rq, struct mlx5_cqe64 *cq
 
 	cqe_bcnt = mpwrq_get_cqe_byte_cnt(cqe);
 
-	skb = INDIRECT_CALL_3(rq->mpwqe.skb_from_cqe_mpwrq,
+	skb = INDIRECT_CALL_4(rq->mpwqe.skb_from_cqe_mpwrq,
 			      mlx5e_skb_from_cqe_mpwrq_linear,
 			      mlx5e_skb_from_cqe_mpwrq_nonlinear,
 			      mlx5e_xsk_skb_from_cqe_mpwrq_linear,
+			      mlx5e_skb_from_cqe_mpwrq_linear_xo,
 			      rq, wi, cqe, cqe_bcnt, head_offset,
 			      page_idx);
 	if (!skb)
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 14/15] selftests: net: xsk: Test explicit chunk return
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (12 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 13/15] net/mlx5e: Test for XDP-only pages per RQ Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  2026-12-04 16:27 ` [PATCH net-next v2 15/15] Documentation: xsk: Describe " Björn Töpel
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

xskxceiver cannot test explicit chunk return yet, as it expects one
chunk per packet at the UMEM headroom.

Add -D (--explicit-return). The RX endpoint, in drv mode, registers its
UMEM with XDP_UMEM_EXPLICIT_RETURN, checks bytes by packet offset, and
refills a chunk only on XDP_RX_CHUNK_RETURNED. The TX endpoint takes -D
too, as it keeps fewer packets in flight to such a receiver. -H BYTES
(--headroom) fails a run in which a packet starts less than BYTES into
its chunk. Cases that cannot run skip and say why. Run STAT_RX_FULL
under -D too, and add RX_RING_FULL_RETURNS.

With NETIF, xsk.py runs each case that tests the rx role once more with
explicit return, e.g. test_xsk.er_SEND_RECEIVE.

Also stop the cleanup of a UMEM that failed to register from unmapping
address zero.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Rename from "selftests: net: xsk: Test the device's RX buffer
      layout".
    - Rename --drv-layout (-D) to --explicit-return, and add -H BYTES
      (--headroom), a headroom check that needs -D.
    - Port to the reworked xsk selftests in net-next: one case per
      invocation, with -D on both endpoints, as the sender paces for an
      explicit-return receiver. drivers/net/xsk.py runs the rx-role cases
      with explicit return on NETIF (er_ variants), in place of the
      test_xsk.sh options. RX_RING_FULL_RETURNS lists the rx role.
    - Reserve FILL slots only for chunks that came back, so that the
      receive loop cannot spin (Sashiko).
    - Register only the receiving UMEM with the flag, with page-sized
      chunks also on 16K and 64K pages, and bind with XDP_USE_SG only
      where the device takes multi-buffer XDP (Sashiko).
    - Skip what the mode cannot run, and say why, among them
      STAT_FILL_EMPTY and HW_SW_MIN_RING_SIZE (Sashiko). A kernel or
      device without the mode, or a UMEM with too few chunks for the
      device, skips instead of failing or hanging.
    - Check empty heads with metadata, and count a packet only once it
      completes (Sashiko).
    - Check the sequence number of the last payload word unless the tail
      grew (Sashiko).
    - Clean up a UMEM that failed to register without unmapping address
      zero.
    - Size the too-large packets of the invalid-descriptor tests by the
      chunk, and let INVALID_DESC straddle a chunk on pages larger than 4K
      (Sashiko).
    - Skip -D on a device without native XDP (Sashiko).
    - Run STAT_RX_FULL under -D: the RX ring fills while the reader waits,
      and each return must come outside a packet, after data of its chunk.
    - Add RX_RING_FULL_RETURNS, a slow reader on a small RX ring.

 tools/testing/selftests/drivers/net/xsk.py    |  28 +-
 .../testing/selftests/net/lib/xsk/test_xsk.c  | 556 +++++++++++++++++-
 .../testing/selftests/net/lib/xsk/test_xsk.h  |   9 +
 .../selftests/net/lib/xsk/xskxceiver.c        |  57 +-
 4 files changed, 617 insertions(+), 33 deletions(-)

diff --git a/tools/testing/selftests/drivers/net/xsk.py b/tools/testing/selftests/drivers/net/xsk.py
index ebde81fa5140..6c296e6bd257 100755
--- a/tools/testing/selftests/drivers/net/xsk.py
+++ b/tools/testing/selftests/drivers/net/xsk.py
@@ -34,6 +34,12 @@ them for IPv6, the case runs over IPv4. NETIF thus needs RSS, and both hosts
 ntuple filters. The cases in RING_SIZES set the rings that they test with
 ethtool -G.
 
+With NETIF, each case that tests the rx role also runs with the local
+endpoint receiving in drv mode with explicit chunk return
+(XDP_UMEM_EXPLICIT_RETURN), e.g. test_xsk.er_SEND_RECEIVE. Both endpoints
+take -D, as the sender paces for it. They skip the case if NETIF cannot back
+the queue with an XDP-only memory provider.
+
 The UNALIGNED cases need 32 huge pages of 2 MiB on both hosts, and are
 expected failures without them.
 """
@@ -74,8 +80,10 @@ HUGEPAGES = "/sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages"
 MAX_SKB_FRAGS = "/proc/sys/net/core/max_skb_frags"
 # What xskxceiver takes when it cannot read MAX_SKB_FRAGS.
 DEFAULT_SKB_FRAGS = 17
-# The ip link option that detaches the XDP program of an endpoint mode.
-XDP_OFF = {"skb": "xdpgeneric off", "drv": "xdpdrv off", "zc": "xdpdrv off"}
+# The ip link option that detaches the XDP program of an endpoint mode, er
+# being drv mode with explicit chunk return.
+XDP_OFF = {"skb": "xdpgeneric off", "drv": "xdpdrv off", "zc": "xdpdrv off",
+           "er": "xdpdrv off"}
 # Why a case cannot pass over veth, by the mode, None for any, and the name.
 VETH_XFAIL = {
     # Generic XDP leaves no room to grow the tail, so the RX endpoint skips.
@@ -134,6 +142,9 @@ def _get_cases(cfg):
         for direction in roles.split():
             case = Case("zc", direction, int(test_id), name)
             ret.append(KsftNamedVariant(f"{direction}_{name}", case))
+        if "rx" in roles.split():
+            case = Case("er", "rx", int(test_id), name)
+            ret.append(KsftNamedVariant(f"er_{name}", case))
     return ret
 
 
@@ -228,12 +239,14 @@ def _steer(cfg, queue, udp_port, ctrl_port):
     raise KsftSkipEx("the hosts reject the ntuple rules of the test")
 
 
-def _setup_nic(cfg, udp_port, ctrl_port):
+def _setup_nic(cfg, case, udp_port, ctrl_port):
     """Take the last queue with both an RX and a TX ring out of RSS and steer
     the flows of a case until it ends. Return the queue and the frags per
     packet that the DUT takes in zero-copy mode."""
     dev = cfg.netnl.dev_get({"ifindex": cfg.ifindex})
-    if "xsk-zerocopy" not in dev["xdp-features"]:
+    # Explicit return needs no zero-copy support; xskxceiver skips if the
+    # bind fails.
+    if case.mode == "zc" and "xsk-zerocopy" not in dev["xdp-features"]:
         raise KsftSkipEx(f"{cfg.ifname} does not support AF_XDP zero-copy")
 
     req = {"header": {"dev-index": cfg.ifindex}}
@@ -361,7 +374,7 @@ def _test(cfg, case, busy_poll):
         queue, max_frags = 0, _setup_veth(case)
     else:
         timeout, xsk_timeout = NIC_CASE_TIMEOUT, NIC_XSK_TIMEOUT
-        queue, max_frags = _setup_nic(cfg, udp_port, ctrl_port)
+        queue, max_frags = _setup_nic(cfg, case, udp_port, ctrl_port)
 
     if busy_poll:
         # So that SO_PREFER_BUSY_POLL of xskxceiver -b keeps the IRQs masked.
@@ -392,12 +405,13 @@ def _test(cfg, case, busy_poll):
             "-t", str(case.test_id),
             "--udp-port", str(udp_port),
             "--max-frags", str(max_frags),
-            "--timeout", str(xsk_timeout)]
+            "--timeout", str(xsk_timeout),
+            *(["-D"] if case.mode == "er" else [])]
     local = ["timeout", "-k", "5", str(timeout), str(cfg.bin_local),
              "-i", cfg.ifname,
              "--queue", str(queue),
              "--listen",
-             "-m", case.mode,
+             "-m", "drv" if case.mode == "er" else case.mode,
              "-e", case.direction,
              *(["-b"] if busy_poll else []),
              "--src-ip", cfg.addr,
diff --git a/tools/testing/selftests/net/lib/xsk/test_xsk.c b/tools/testing/selftests/net/lib/xsk/test_xsk.c
index 2aadb95c61fa..8da7de41edf9 100644
--- a/tools/testing/selftests/net/lib/xsk/test_xsk.c
+++ b/tools/testing/selftests/net/lib/xsk/test_xsk.c
@@ -24,6 +24,8 @@
 #include "xsk_xdp_progs.skel.h"
 
 #define DEFAULT_BATCH_SIZE		64
+/* Descriptors of an RX batch that count_drv_shared() compares */
+#define DRV_SHARE_WINDOW		64
 /* Payload of the smallest packet, which is 64 bytes over IPv4 */
 #define MIN_PAYLOAD_SIZE		20
 #define MAX_ETH_JUMBO_SIZE		9000
@@ -53,6 +55,14 @@ static u32 thread_tmout = THREAD_TMOUT;
 
 bool opt_verbose;
 int min_pkt_size;
+bool opt_explicit_return;
+/* RX descriptors, and those whose chunk an earlier one of the batch holds */
+u64 drv_rx_descs, drv_rx_shared, drv_rx_empty_heads;
+u64 drv_rx_empty_heads_freed;
+/* Least headroom seen in front of a packet, and what the device leaves */
+u32 drv_rx_headroom = UINT_MAX, opt_headroom;
+/* An explicit-return bind of a receiving socket worked in this run */
+static bool explicit_return_bound;
 
 int pkts_in_flight;
 static struct xsk_peer *ctrl_peer;
@@ -262,6 +272,9 @@ int xsk_configure_umem(struct ifobject *ifobj, struct xsk_umem_info *umem, void
 
 	if (umem->unaligned_mode)
 		cfg.flags |= XDP_UMEM_UNALIGNED_CHUNK_FLAG;
+	/* Only the receiving UMEM has explicit return */
+	if (opt_explicit_return && ifobj->rx_on)
+		cfg.flags |= XDP_UMEM_EXPLICIT_RETURN;
 
 	ret = xsk_umem__create(&umem->umem, buffer, size,
 			       &umem->fq, &umem->cq, &cfg);
@@ -325,7 +338,11 @@ int xsk_configure_socket(struct xsk_socket_info *xsk, struct xsk_umem_info *umem
 	cfg.bind_flags = ifobject->bind_flags;
 	if (shared)
 		cfg.bind_flags |= XDP_SHARED_UMEM;
-	if (ifobject->mtu > MAX_ETH_PKT_SIZE)
+	/* A device with multi-buffer XDP may split any frame, see
+	 * XDP_UMEM_EXPLICIT_RETURN
+	 */
+	if (ifobject->mtu > MAX_ETH_PKT_SIZE ||
+	    (opt_explicit_return && ifobj_has_cap(ifobject, XSK_CAP_MBUF)))
 		cfg.bind_flags |= XDP_USE_SG;
 	if (umem->comp_size)
 		cfg.tx_size = umem->comp_size;
@@ -385,6 +402,9 @@ static void __test_spec_init(struct test_spec *test, struct ifobject *ifobj_tx,
 
 		ifobj->xsk->umem->num_frames = DEFAULT_UMEM_BUFFERS;
 		ifobj->xsk->umem->frame_size = XSK_UMEM__DEFAULT_FRAME_SIZE;
+		/* Explicit return takes page-sized chunks */
+		if (opt_explicit_return)
+			ifobj->xsk->umem->frame_size = getpagesize();
 	}
 
 	test->ifobj_tx = ifobj_tx;
@@ -394,6 +414,7 @@ static void __test_spec_init(struct test_spec *test, struct ifobject *ifobj_tx,
 	test->nb_sockets = 1;
 	test->adjust_tail = false;
 	test->adjust_tail_support = false;
+	test->adjust_grow = 0;
 	test->mtu = ETH_DATA_LEN;
 	test->xdp_prog_rx = ifobj_rx->xdp_progs->progs.xsk_def_prog;
 	test->xskmap_rx = ifobj_rx->xdp_progs->maps.xsk;
@@ -419,9 +440,12 @@ void test_init(struct test_spec *test, struct ifobject *ifobj_tx,
 		struct ifobject *ifobj = i ? ifobj_rx : ifobj_tx;
 
 		ifobj->bind_flags = XDP_USE_NEED_WAKEUP;
+		/* Explicit return is neither of the classic modes, and only the
+		 * receiving socket has it
+		 */
 		if (mode == TEST_MODE_ZC)
 			ifobj->bind_flags |= XDP_ZEROCOPY;
-		else
+		else if (!opt_explicit_return || ifobj == ifobj_tx)
 			ifobj->bind_flags |= XDP_COPY;
 	}
 
@@ -605,6 +629,15 @@ static u32 pkt_total_len(struct pkt_stream *pkt_stream, struct pkt *pkt, u32 nb_
 	return len;
 }
 
+/* A packet that no chunk of @umem holds, and that is longer than any MTU */
+static u32 invalid_pkt_len(struct xsk_umem_info *umem)
+{
+	u32 len = umem->frame_size + 1;
+
+	return len > XSK_UMEM__INVALID_FRAME_SIZE ?
+	       len : XSK_UMEM__INVALID_FRAME_SIZE;
+}
+
 static bool set_pkt_valid(int offset, u32 len)
 {
 	return len <= MAX_ETH_JUMBO_SIZE;
@@ -1028,6 +1061,82 @@ static bool is_frag_valid(struct xsk_umem_info *umem, u64 addr, u32 len, u32 exp
 	return false;
 }
 
+/* Explicit return: a buffer may start and end anywhere in the packet, and
+ * anywhere in its chunk. Check its bytes against the generated pattern by
+ * packet offset. XDP_ADJUST_TAIL_GROW zeroes the last @grow bytes and
+ * writes the sequence number of the last word, so that word only needs the
+ * right sequence number, and the bytes before it may be zero.
+ */
+static bool is_frag_valid_drv(struct xsk_umem_info *umem, u64 addr, u32 len,
+			      u32 expected_pkt_nb, u32 bytes_processed,
+			      u32 pkt_len, u32 grow)
+{
+	u32 payload_end = PKT_HDR_SIZE + ((pkt_len - PKT_HDR_SIZE) & ~3U);
+	u8 *bytes = xsk_umem__get_data(umem->buffer, addr);
+	u64 umem_sz = umem_size(umem);
+	u32 i, off, word;
+	bool last;
+
+	if (addr >= umem_sz || addr + len > umem_sz ||
+	    addr % umem->frame_size + len > umem->frame_size) {
+		ksft_print_msg("Frag invalid addr: %llx len: %u\n",
+			       (unsigned long long)addr, len);
+		return false;
+	}
+
+	for (i = 0; i < len; i++) {
+		off = bytes_processed + i;
+		if (off < PKT_HDR_SIZE || off >= payload_end)
+			continue;
+
+		/* The last word lies in the grown tail, but must carry its
+		 * sequence number, so it takes no zero exemption
+		 */
+		last = grow && (off - PKT_HDR_SIZE) / 4 ==
+			       (payload_end - PKT_HDR_SIZE) / 4 - 1;
+		if (!last && off >= pkt_len - grow && !bytes[i])
+			continue;
+
+		off -= PKT_HDR_SIZE;
+		word = htonl(expected_pkt_nb << 16 | (off / 4));
+		if (last && off % 4 < 2)
+			continue;
+		if (bytes[i] == ((u8 *)&word)[off % 4])
+			continue;
+
+		ksft_print_msg("[%s] pkt %u byte %u (off %u): %#x, not %#x\n",
+			       __func__, expected_pkt_nb, i,
+			       (u32)(off + PKT_HDR_SIZE), bytes[i],
+			       ((u8 *)&word)[off % 4]);
+		return false;
+	}
+
+	return true;
+}
+
+/* Explicit return: count descriptors whose chunk an earlier descriptor of the
+ * same RX batch holds, that is, chunks the device split. Only the first
+ * DRV_SHARE_WINDOW descriptors of a batch are compared.
+ */
+static void count_drv_shared(struct xsk_umem_info *umem, u64 *chunks, u32 n,
+			     u64 addr)
+{
+	u64 chunk = addr / umem->frame_size;
+	u32 i;
+
+	drv_rx_descs++;
+	if (n >= DRV_SHARE_WINDOW)
+		return;
+
+	for (i = 0; i < n; i++) {
+		if (chunks[i] != chunk)
+			continue;
+		drv_rx_shared++;
+		break;
+	}
+	chunks[n] = chunk;
+}
+
 static bool is_pkt_valid(struct pkt *pkt, void *buffer, u64 addr, u32 frag_len, u32 len)
 {
 	if (pkt->len != len) {
@@ -1130,16 +1239,36 @@ static int complete_pkts(struct xsk_socket_info *xsk, int batch_size)
 	return TEST_PASS;
 }
 
+/* Explicit return: the descriptors of an RX batch that give a chunk back */
+static u32 count_chunk_free(struct xsk_socket_info *xsk, u32 idx, u32 rcvd)
+{
+	u32 i, n = 0;
+
+	for (i = 0; i < rcvd; i++)
+		if (xsk_ring_cons__rx_desc(&xsk->rx, idx + i)->options &
+		    XDP_RX_CHUNK_RETURNED)
+			n++;
+	return n;
+}
+
 static int __receive_pkts(struct test_spec *test, struct xsk_socket_info *xsk)
 {
 	u32 frags_processed = 0, nb_frags = 0, pkt_len = 0, first_len = 0;
 	u32 idx_rx = 0, idx_fq = 0, rcvd, pkts_sent = 0;
+	/* Explicit return: the statistics as they were before the packet */
+	u64 descs = 0, shared = 0, heads = 0, heads_freed = 0;
+	/* Explicit return: FILL entries written, those of a partial packet */
+	u32 fills = 0, pkt_fills = 0;
 	struct pkt_stream *pkt_stream = xsk->pkt_stream;
 	struct ifobject *ifobj = test->ifobj_rx;
 	struct xsk_umem_info *umem = xsk->umem;
 	struct pollfd fds = { };
+	u64 batch_chunks[DRV_SHARE_WINDOW];
+	/* Entries of batch_chunks[]: data descriptors only */
+	u32 batch_n = 0;
 	struct pkt *pkt;
 	u64 first_addr = 0;
+	u32 nb_fq;
 	int ret;
 
 	fds.fd = xsk_socket__fd(xsk->xsk);
@@ -1173,15 +1302,22 @@ static int __receive_pkts(struct test_spec *test, struct xsk_socket_info *xsk)
 	if (!rcvd)
 		return TEST_CONTINUE;
 
+	/* Explicit return: only a descriptor with XDP_RX_CHUNK_RETURNED gives a
+	 * chunk back, and a chunk may hold more buffers than FILL has free
+	 * slots
+	 */
+	nb_fq = rcvd;
+	if (opt_explicit_return)
+		nb_fq = count_chunk_free(xsk, idx_rx, rcvd);
 	if (ifobj->use_fill_ring) {
-		ret = xsk_ring_prod__reserve(&umem->fq, rcvd, &idx_fq);
-		while (ret != rcvd) {
+		ret = xsk_ring_prod__reserve(&umem->fq, nb_fq, &idx_fq);
+		while (ret != nb_fq) {
 			if (xsk_ring_prod__needs_wakeup(&umem->fq)) {
 				ret = poll(&fds, 1, POLL_TMOUT);
 				if (ret < 0)
 					return TEST_FAILURE;
 			}
-			ret = xsk_ring_prod__reserve(&umem->fq, rcvd, &idx_fq);
+			ret = xsk_ring_prod__reserve(&umem->fq, nb_fq, &idx_fq);
 		}
 	}
 
@@ -1192,6 +1328,47 @@ static int __receive_pkts(struct test_spec *test, struct xsk_socket_info *xsk)
 		orig = xsk_umem__extract_addr(addr);
 		addr = xsk_umem__add_offset_to_addr(addr);
 
+		if (!nb_frags) {
+			descs = drv_rx_descs;
+			shared = drv_rx_shared;
+			heads = drv_rx_empty_heads;
+			heads_freed = drv_rx_empty_heads_freed;
+		}
+
+		/* Explicit return: a descriptor without data gives a chunk
+		 * back, and one with XDP_PKT_CONTD is the head of a packet
+		 * whose data follows, which carries the metadata.
+		 */
+		if (opt_explicit_return && !desc->len &&
+		    (desc->options & XDP_PKT_CONTD)) {
+			if (nb_frags) {
+				ksft_print_msg("[%s] nested empty head %llx\n",
+					       __func__,
+					       (unsigned long long)addr);
+				return TEST_FAILURE;
+			}
+			drv_rx_empty_heads++;
+			/* The chunk of an empty head may come back with it */
+			if (desc->options & XDP_RX_CHUNK_RETURNED)
+				drv_rx_empty_heads_freed++;
+		} else if (opt_explicit_return && !desc->len) {
+			if (nb_frags ||
+			    !(desc->options & XDP_RX_CHUNK_RETURNED)) {
+				ksft_print_msg("[%s] empty %llx, options %u\n",
+					       __func__,
+					       (unsigned long long)addr,
+					       desc->options);
+				return TEST_FAILURE;
+			}
+			if (ifobj->use_fill_ring) {
+				*xsk_ring_prod__fill_addr(&umem->fq, idx_fq++) =
+					orig - orig % umem->frame_size;
+				fills++;
+			}
+			frags_processed++;
+			continue;
+		}
+
 		if (!nb_frags) {
 			pkt = pkt_stream_get_next_rx_pkt(pkt_stream, &pkts_sent);
 			if (!pkt) {
@@ -1204,48 +1381,108 @@ static int __receive_pkts(struct test_spec *test, struct xsk_socket_info *xsk)
 		print_verbose("Rx: addr: %lx len: %u options: %u pkt_nb: %u valid: %u\n",
 			      addr, desc->len, desc->options, pkt->pkt_nb, pkt->valid);
 
-		if (!is_frag_valid(umem, addr, desc->len, pkt->pkt_nb, pkt_len) ||
-		    !is_offset_correct(umem, pkt, addr) || (ifobj->use_metadata &&
-		    !is_metadata_correct(pkt, umem->buffer, addr)))
+		if (opt_explicit_return) {
+			/* The device picks offsets; metadata precedes the
+			 * head
+			 */
+			if (!is_frag_valid_drv(umem, addr, desc->len,
+					       pkt->pkt_nb, pkt_len,
+					       pkt->len, test->adjust_grow) ||
+			    (ifobj->use_metadata && !nb_frags &&
+			     !is_metadata_correct(pkt, umem->buffer, addr)))
+				return TEST_FAILURE;
+			/* Empty heads are counted on their own */
+			if (desc->len)
+				count_drv_shared(umem, batch_chunks, batch_n++,
+						 addr);
+		} else if (!is_frag_valid(umem, addr, desc->len, pkt->pkt_nb,
+					  pkt_len) ||
+			   !is_offset_correct(umem, pkt, addr) ||
+			   (ifobj->use_metadata &&
+			    !is_metadata_correct(pkt, umem->buffer, addr))) {
 			return TEST_FAILURE;
+		}
 
-		if (!nb_frags++) {
+		if (!nb_frags) {
+			u32 headroom = addr % umem->frame_size;
+
+			/* The first buffer keeps the headroom of the
+			 * device, as native XDP has it. Its offset in the
+			 * chunk bounds that headroom from above: userspace
+			 * cannot see where the device starts a buffer.
+			 */
+			if (opt_explicit_return) {
+				if (headroom < drv_rx_headroom)
+					drv_rx_headroom = headroom;
+				if (headroom < opt_headroom) {
+					ksft_print_msg("[%s] headroom %u < %u at %llx\n",
+						       __func__, headroom,
+						       opt_headroom,
+						       (unsigned long long)addr);
+					return TEST_FAILURE;
+				}
+			}
 			first_addr = addr;
 			first_len = desc->len;
 		}
+		nb_frags++;
 		frags_processed++;
 		pkt_len += desc->len;
-		if (ifobj->use_fill_ring)
+		if (ifobj->use_fill_ring && !opt_explicit_return) {
 			*xsk_ring_prod__fill_addr(&umem->fq, idx_fq++) = orig;
+		} else if (ifobj->use_fill_ring &&
+			   desc->options & XDP_RX_CHUNK_RETURNED) {
+			/* Only a returned chunk goes back to FILL */
+			*xsk_ring_prod__fill_addr(&umem->fq, idx_fq++) =
+				orig - orig % umem->frame_size;
+			fills++;
+			pkt_fills++;
+		}
 
 		if (pkt_continues(desc->options))
 			continue;
 
-		/* The complete packet has been received */
+		/* The complete packet has been received. With explicit
+		 * return, the first buffer may hold only part of the header.
+		 */
+		if (opt_explicit_return && first_len < PKT_HDR_SIZE)
+			first_len = PKT_HDR_SIZE;
 		if (!is_pkt_valid(pkt, umem->buffer, first_addr, first_len, pkt_len) ||
-		    !is_offset_correct(umem, pkt, addr))
+		    (!opt_explicit_return &&
+		     !is_offset_correct(umem, pkt, addr)))
 			return TEST_FAILURE;
 
 		pkt_stream->nb_rx_pkts++;
 		nb_frags = 0;
 		pkt_len = 0;
+		pkt_fills = 0;
 	}
 
 	if (nb_frags) {
 		/* In the middle of a packet. Start over from beginning of packet. */
 		idx_rx -= nb_frags;
 		xsk_ring_cons__cancel(&xsk->rx, nb_frags);
-		if (ifobj->use_fill_ring) {
+		if (ifobj->use_fill_ring && !opt_explicit_return) {
 			idx_fq -= nb_frags;
 			xsk_ring_prod__cancel(&umem->fq, nb_frags);
 		}
 		frags_processed -= nb_frags;
+		fills -= pkt_fills;
+		/* Its descriptors count once it completes */
+		drv_rx_descs = descs;
+		drv_rx_shared = shared;
+		drv_rx_empty_heads = heads;
+		drv_rx_empty_heads_freed = heads_freed;
 		pkt_stream_cancel(pkt_stream);
 		pkts_sent--;
 	}
 
-	if (ifobj->use_fill_ring)
+	if (ifobj->use_fill_ring && opt_explicit_return) {
+		xsk_ring_prod__cancel(&umem->fq, nb_fq - fills);
+		xsk_ring_prod__submit(&umem->fq, fills);
+	} else if (ifobj->use_fill_ring) {
 		xsk_ring_prod__submit(&umem->fq, frags_processed);
+	}
 	if (ifobj->release_rx)
 		xsk_ring_cons__release(&xsk->rx, frags_processed);
 
@@ -1316,22 +1553,32 @@ static int receive_pkts(struct test_spec *test)
 }
 
 static int __send_pkts(struct ifobject *ifobject, struct xsk_socket_info *xsk,
-		       bool test_timeout)
+		       bool test_timeout, bool drv_rx)
 {
 	u32 i, idx = 0, valid_pkts = 0, valid_frags = 0, buffer_len;
 	struct xsk_umem_info *umem = ifobject->xsk_arr[0].umem;
 	struct pkt_stream *pkt_stream = xsk->pkt_stream;
 	bool use_poll = ifobject->use_poll;
 	struct pollfd fds = { };
-	int ret;
+	int ret, max_in_flight;
 
 	buffer_len = pkt_get_buffer_len(umem, pkt_stream->max_pkt_len);
 	if (pacing_tx_sync())
 		return TEST_FAILURE;
 
+	max_in_flight = (umem_size(umem) - xsk->batch_size * buffer_len) /
+			buffer_len;
+	/* A receiver with explicit return needs more: its queue
+	 * also holds chunks without packets, posted on rings that the
+	 * traffic does not fill, such as a header ring, and in the page
+	 * pool cache. And a packet takes an RX descriptor per buffer, and
+	 * empty ones that give chunks back. Keep a quarter of the frames in
+	 * flight to such a receiver.
+	 */
+	if (drv_rx)
+		max_in_flight /= 4;
 	/* pkts_in_flight might be negative if many invalid packets are sent */
-	if (pkts_in_flight >= (int)((umem_size(umem) - xsk->batch_size * buffer_len) /
-	    buffer_len) && !test_timeout) {
+	if (pkts_in_flight >= max_in_flight && !test_timeout) {
 		/* Only RX progress reports can lower pkts_in_flight. */
 		if (xsk_peer_skipped(ctrl_peer)) {
 			ksft_print_msg("RX skipped the case with %d packets in flight\n",
@@ -1484,6 +1731,7 @@ bool all_packets_sent(struct test_spec *test, unsigned long *bitmap)
 
 static int send_pkts(struct test_spec *test, struct ifobject *ifobject)
 {
+	bool drv_rx = opt_explicit_return && test->ifobj_rx->use_fill_ring;
 	DECLARE_BITMAP(bitmap, test->nb_sockets);
 	u32 i, ret;
 
@@ -1498,7 +1746,8 @@ static int send_pkts(struct test_spec *test, struct ifobject *ifobject)
 				__set_bit(i, bitmap);
 				continue;
 			}
-			ret = __send_pkts(ifobject, &ifobject->xsk_arr[i], test->poll_tmout);
+			ret = __send_pkts(ifobject, &ifobject->xsk_arr[i],
+					  test->poll_tmout, drv_rx);
 			if (ret != TEST_CONTINUE)
 				return ret;
 
@@ -1611,6 +1860,124 @@ static int validate_rx_full(struct ifobject *ifobject)
 	return wait_rx_stat(ifobject, false);
 }
 
+/* Explicit return: packets that find the RX ring full are dropped, never a
+ * return, as the ring keeps room for them. Waits @rx_full_wait_us, and then
+ * drains one batch every @rx_full_step_us until the ring stays empty. Each
+ * return must come outside a packet and after a data descriptor of its
+ * chunk, and every chunk with data must come back, but for the few that the
+ * device still fills. Those come back only once the device lets go of them,
+ * or without a descriptor once the queue leaves the UMEM, which the test
+ * cannot see.
+ */
+static u32 rx_full_wait_us, rx_full_step_us;
+#define RX_FULL_IDLE_POLLS	100
+#define RX_FULL_SLACK		16
+
+static int validate_rx_full_returns(struct ifobject *ifobject)
+{
+	u32 i, idx, idx_fq = 0, rcvd, nb_fq, idle = 0, chunk, fills, tries;
+	struct xsk_socket_info *xsk = ifobject->xsk;
+	struct xsk_umem_info *umem = xsk->umem;
+	u32 returns = 0, outstanding = 0, nr;
+	bool in_pkt = false, ret_only;
+	const struct xdp_desc *desc;
+	struct xdp_statistics stats;
+	int ret = TEST_FAILURE;
+	struct pollfd fds = {
+		.fd = xsk_socket__fd(xsk->xsk),
+		.events = POLLIN,
+	};
+	__u64 *fill;
+	u64 addr;
+	u8 *seen;
+
+	nr = umem->num_frames;
+	seen = calloc(nr, sizeof(*seen));
+	if (!seen)
+		return TEST_FAILURE;
+
+	usleep(rx_full_wait_us);
+	while (idle < RX_FULL_IDLE_POLLS) {
+		if (kick_rx(xsk))
+			goto out;
+		rcvd = xsk_ring_cons__peek(&xsk->rx, xsk->batch_size, &idx);
+		if (!rcvd) {
+			idle++;
+			usleep(1000);
+			continue;
+		}
+		idle = 0;
+
+		nb_fq = count_chunk_free(xsk, idx, rcvd);
+		tries = 0;
+		while (xsk_ring_prod__reserve(&umem->fq, nb_fq, &idx_fq) !=
+		       nb_fq) {
+			if (++tries > RX_FULL_IDLE_POLLS) {
+				ksft_print_msg("[%s] FILL stays full\n",
+					       __func__);
+				goto out;
+			}
+			if (xsk_ring_prod__needs_wakeup(&umem->fq) &&
+			    poll(&fds, 1, POLL_TMOUT) < 0)
+				goto out;
+			usleep(1000);
+		}
+
+		fills = 0;
+		for (i = 0; i < rcvd; i++) {
+			desc = xsk_ring_cons__rx_desc(&xsk->rx, idx + i);
+			addr = xsk_umem__extract_addr(desc->addr);
+			if (addr >= umem_size(umem)) {
+				ksft_print_msg("[%s] %llx outside the UMEM\n",
+					       __func__, desc->addr);
+				goto out;
+			}
+			chunk = addr / umem->frame_size;
+			ret_only = !desc->len &&
+				   !(desc->options & XDP_PKT_CONTD);
+			if (ret_only && (in_pkt || !seen[chunk])) {
+				ksft_print_msg("[%s] misplaced return of %u\n",
+					       __func__, chunk);
+				goto out;
+			}
+			returns += ret_only;
+			if (!ret_only)
+				seen[chunk] = 1;
+			if (desc->options & XDP_RX_CHUNK_RETURNED) {
+				seen[chunk] = 0;
+				fill = xsk_ring_prod__fill_addr(&umem->fq,
+								idx_fq++);
+				*fill = addr - addr % umem->frame_size;
+				fills++;
+			}
+			in_pkt = desc->options & XDP_PKT_CONTD;
+		}
+		xsk_ring_prod__submit(&umem->fq, fills);
+		xsk_ring_cons__release(&xsk->rx, rcvd);
+		usleep(rx_full_step_us);
+	}
+
+	if (get_xsk_stats(xsk->xsk, &stats))
+		goto out;
+	for (i = 0; i < nr; i++)
+		outstanding += seen[i];
+	print_verbose("rx_ring_full %llu returns %u outstanding %u\n",
+		      stats.rx_ring_full, returns, outstanding);
+	if (!stats.rx_ring_full) {
+		ksft_print_msg("[%s] the RX ring never filled\n", __func__);
+		goto out;
+	}
+	if (outstanding > RX_FULL_SLACK) {
+		ksft_print_msg("[%s] %u chunks with data did not come back\n",
+			       __func__, outstanding);
+		goto out;
+	}
+	ret = TEST_PASS;
+out:
+	free(seen);
+	return ret;
+}
+
 static int validate_fill_empty(struct ifobject *ifobject)
 {
 	return wait_rx_stat(ifobject, true);
@@ -1754,8 +2121,16 @@ static int thread_common_ops(struct test_spec *test, struct ifobject *ifobject)
 	umem->mmap_size = mmap_sz;
 
 	ret = xsk_configure_umem(ifobject, umem, bufs, umem_sz);
-	if (ret)
+	if (ret) {
+		munmap(bufs, mmap_sz);
+		/* A kernel without explicit return refuses the UMEM flag */
+		if (ret == -EINVAL && opt_explicit_return &&
+		    ifobject->rx_on && !explicit_return_bound) {
+			ksft_print_msg("No explicit return in the kernel?\n");
+			return TEST_SKIP;
+		}
 		return ret;
+	}
 
 	ifobject->xsk = &ifobject->xsk_arr[0];
 
@@ -1771,8 +2146,24 @@ static int thread_common_ops(struct test_spec *test, struct ifobject *ifobject)
 	}
 
 	ret = xsk_configure(test, ifobject, umem);
+	/* The queue's page pool may need more chunks than the UMEM has */
+	if (ret == -ENOSPC && opt_explicit_return && ifobject->rx_on) {
+		ksft_print_msg("%llu chunks are too few for the device\n",
+			       (unsigned long long)umem_sz / umem->frame_size);
+		return TEST_SKIP;
+	}
+	/* Without CAP_NET_ADMIN, or on a device that cannot take it. Once a
+	 * receiving bind worked, the device can, and a refusal is a failure.
+	 */
+	if ((ret == -EOPNOTSUPP || ret == -EPERM) && opt_explicit_return &&
+	    ifobject->rx_on && !explicit_return_bound) {
+		ksft_print_msg("Bind failed: %s\n", strerror(-ret));
+		return TEST_SKIP;
+	}
 	if (ret)
 		return ret;
+	if (opt_explicit_return && ifobject->rx_on)
+		explicit_return_bound = true;
 
 	if (!ifobject->rx_on)
 		return 0;
@@ -1915,6 +2306,11 @@ int worker_testapp_validate_rx(struct test_spec *test)
 	int err;
 
 	err = testapp_prepare_rx_endpoint(test, ifobject);
+	/* A bind the device cannot take is a skip, which main() tells the
+	 * peer of
+	 */
+	if (err == TEST_SKIP)
+		return err;
 	if (err) {
 		ksft_print_msg("RX endpoint setup failed at step %u: %d\n",
 			       test->current_step, err);
@@ -1940,7 +2336,13 @@ static void testapp_clean_xsk_umem(struct ifobject *ifobj)
 	struct xsk_umem_info *umem = ifobj->xsk->umem;
 
 	xsk_umem__delete(umem->umem);
-	munmap(umem->buffer, umem->mmap_size);
+	umem->umem = NULL;
+	/* No buffer if registration failed: munmap(NULL) would unmap the
+	 * program
+	 */
+	if (umem->buffer)
+		munmap(umem->buffer, umem->mmap_size);
+	umem->buffer = NULL;
 }
 
 static bool xdp_prog_changed_rx(struct test_spec *test)
@@ -2038,12 +2440,40 @@ static void clean_umem(struct test_spec *test, struct ifobject *ifobj1, struct i
 		testapp_clean_xsk_umem(ifobj2);
 }
 
+/* Explicit return takes one receiving socket per queue */
+static bool skip_second_receiver(void)
+{
+	if (!opt_explicit_return)
+		return false;
+	ksft_print_msg("One socket receives per queue with explicit return\n");
+	return true;
+}
+
+/* UMEM with explicit return: page chunks, no headroom */
+static bool explicit_return_umem_ok(struct ifobject *ifobj)
+{
+	struct xsk_umem_info *umem = ifobj->xsk->umem;
+
+	/* A TX UMEM of its own has no explicit return */
+	if (!ifobj->rx_on)
+		return true;
+	return umem->frame_size == getpagesize() && !umem->frame_headroom &&
+	       !umem->unaligned_mode;
+}
+
 static int __testapp_validate_traffic(struct test_spec *test, struct ifobject *ifobj1,
 				      struct ifobject *ifobj2)
 {
 	u32 mbuf_cap;
 	int err;
 
+	if (opt_explicit_return &&
+	    (!explicit_return_umem_ok(ifobj1) ||
+	     (ifobj2 && !explicit_return_umem_ok(ifobj2)))) {
+		ksft_print_msg("-D needs page chunks without headroom\n");
+		return TEST_SKIP;
+	}
+
 	if (test->mtu <= MAX_ETH_PKT_SIZE)
 		goto skip_mbuf_check;
 
@@ -2147,6 +2577,14 @@ int testapp_bidirectional(struct test_spec *test)
 {
 	int res;
 
+	/* The sending side binds in copy mode, and on one netdev it would
+	 * also receive on the queue of the other
+	 */
+	if (opt_explicit_return) {
+		ksft_print_msg("-D: no copy mode, one receiver per queue\n");
+		return TEST_SKIP;
+	}
+
 	test->ifobj_tx->rx_on = true;
 	test->ifobj_rx->tx_on = true;
 	test->total_steps = 2;
@@ -2187,6 +2625,9 @@ int testapp_xdp_prog_cleanup(struct test_spec *test)
 {
 	int ret;
 
+	if (skip_second_receiver())
+		return TEST_SKIP;
+
 	test->total_steps = 2;
 	test->nb_sockets = 2;
 	ret = testapp_validate_traffic(test);
@@ -2231,16 +2672,50 @@ int testapp_stats_rx_dropped(struct test_spec *test)
 
 int testapp_stats_tx_invalid_descs(struct test_spec *test)
 {
-	if (pkt_stream_replace_half(test, XSK_UMEM__INVALID_FRAME_SIZE, 0))
+	u32 len = invalid_pkt_len(test->ifobj_tx->xsk->umem);
+
+	if (pkt_stream_replace_half(test, len, 0))
 		return TEST_FAILURE;
 	test->ifobj_tx->validation_func = validate_tx_invalid_descs;
 	return testapp_validate_traffic(test);
 }
 
+/* With explicit return, returns take RX slots too, so the number of
+ * packets that fit is not known: the receive loop takes none, and the
+ * validation drains the ring, see validate_rx_full_returns(). The sender
+ * keeps fewer packets in flight than it may.
+ */
+static int testapp_rx_full_returns(struct test_spec *test, u32 rxqsize,
+				   u32 wait_us, u32 step_us)
+{
+	struct pkt_stream *tmp;
+
+	tmp = pkt_stream_generate(DEFAULT_UMEM_BUFFERS / 8, MIN_PKT_SIZE);
+	if (!tmp)
+		return TEST_FAILURE;
+	test->ifobj_tx->xsk->pkt_stream = tmp;
+
+	tmp = pkt_stream_generate(DEFAULT_UMEM_BUFFERS / 8, MIN_PKT_SIZE);
+	if (!tmp)
+		return TEST_FAILURE;
+	tmp->nb_valid_entries = 0;
+	test->ifobj_rx->xsk->pkt_stream = tmp;
+
+	rx_full_wait_us = wait_us;
+	rx_full_step_us = step_us;
+	test->ifobj_rx->xsk->rxqsize = rxqsize;
+	test->ifobj_rx->validation_func = validate_rx_full_returns;
+	return testapp_validate_traffic(test);
+}
+
 int testapp_stats_rx_full(struct test_spec *test)
 {
 	struct pkt_stream *tmp;
 
+	if (opt_explicit_return)
+		return testapp_rx_full_returns(test, DEFAULT_BATCH_SIZE,
+					       200 * 1000, 0);
+
 	tmp = pkt_stream_generate(DEFAULT_UMEM_BUFFERS + DEFAULT_UMEM_BUFFERS / 2, MIN_PKT_SIZE);
 	if (!tmp)
 		return TEST_FAILURE;
@@ -2257,10 +2732,29 @@ int testapp_stats_rx_full(struct test_spec *test)
 	return testapp_validate_traffic(test);
 }
 
+/* A small RX ring that a slow reader drains one batch at a time */
+int testapp_rx_ring_full_returns(struct test_spec *test)
+{
+	if (!opt_explicit_return) {
+		ksft_print_msg("Returns take RX slots only with -D\n");
+		return TEST_SKIP;
+	}
+
+	test->ifobj_rx->xsk->batch_size = DEFAULT_BATCH_SIZE / 4;
+	return testapp_rx_full_returns(test, DEFAULT_BATCH_SIZE / 4,
+				       50 * 1000, 2000);
+}
+
 int testapp_stats_fill_empty(struct test_spec *test)
 {
 	struct pkt_stream *tmp;
 
+	/* Several packets may share a chunk, so FILL runs dry later */
+	if (opt_explicit_return) {
+		ksft_print_msg("FILL entries are not packets with -D\n");
+		return TEST_SKIP;
+	}
+
 	tmp = pkt_stream_generate(DEFAULT_UMEM_BUFFERS + DEFAULT_UMEM_BUFFERS / 2, MIN_PKT_SIZE);
 	if (!tmp)
 		return TEST_FAILURE;
@@ -2350,6 +2844,8 @@ int testapp_invalid_desc_mb(struct test_spec *test)
 		pkts[15].valid = true;
 		pkts[16].valid = true;
 	}
+	/* Too large for a chunk, also for chunks larger than an MTU */
+	pkts[8].len = invalid_pkt_len(umem);
 
 	test->mtu = MAX_ETH_JUMBO_SIZE;
 	if (pkt_stream_generate_custom(test, pkts, ARRAY_SIZE(pkts)))
@@ -2391,6 +2887,12 @@ int testapp_invalid_desc(struct test_spec *test)
 		/* Crossing a 2K frame size boundary not allowed */
 		pkts[8].valid = false;
 	}
+	if (!umem->unaligned_mode && umem->frame_size > 0x1000) {
+		/* Page-sized chunks larger than 4K: straddle a chunk instead */
+		pkts[7].offset = umem->frame_size - MIN_PKT_SIZE / 2;
+	}
+	/* Too large for a chunk, also for chunks larger than an MTU */
+	pkts[3].len = invalid_pkt_len(umem);
 
 	if (pkt_stream_generate_custom(test, pkts, ARRAY_SIZE(pkts)))
 		return TEST_FAILURE;
@@ -2431,6 +2933,9 @@ int testapp_xdp_shared_umem(struct test_spec *test)
 	struct xsk_xdp_progs *skel_tx = test->ifobj_tx->xdp_progs;
 	int ret;
 
+	if (skip_second_receiver())
+		return TEST_SKIP;
+
 	test->total_steps = 1;
 	test->nb_sockets = 2;
 
@@ -2701,6 +3206,11 @@ int testapp_hw_sw_min_ring_size(struct test_spec *test)
 		ksft_print_msg("HW ring sizes not supported.\n");
 		return TEST_SKIP;
 	}
+	/* A batch of one never completes a packet of several descriptors */
+	if (opt_explicit_return) {
+		ksft_print_msg("A packet may span descriptors with -D\n");
+		return TEST_SKIP;
+	}
 
 	test->total_steps = 2;
 	test->ifobj_tx->xsk->batch_size = 1;
@@ -2789,6 +3299,8 @@ static int testapp_adjust_tail(struct test_spec *test, u32 value, u32 pkt_len)
 
 	test->adjust_tail_support = true;
 	test->adjust_tail = true;
+	/* A negative value shrinks */
+	test->adjust_grow = (int)value > 0 ? value : 0;
 	test->total_steps = 1;
 
 	ret = pkt_stream_replace_ifobject(test->ifobj_tx, DEFAULT_BATCH_SIZE, pkt_len);
diff --git a/tools/testing/selftests/net/lib/xsk/test_xsk.h b/tools/testing/selftests/net/lib/xsk/test_xsk.h
index 872e15206b48..7d73df25e819 100644
--- a/tools/testing/selftests/net/lib/xsk/test_xsk.h
+++ b/tools/testing/selftests/net/lib/xsk/test_xsk.h
@@ -36,6 +36,11 @@
 extern bool opt_verbose;
 /* The smallest test packet, set by xsk_set_flow() */
 extern int min_pkt_size;
+/* XDP_UMEM_EXPLICIT_RETURN: the device lays out RX buffers in UMEM chunks */
+extern bool opt_explicit_return;
+extern u64 drv_rx_descs, drv_rx_shared, drv_rx_empty_heads;
+extern u64 drv_rx_empty_heads_freed;
+extern u32 drv_rx_headroom, opt_headroom;
 #define print_verbose(x...) do { if (opt_verbose) ksft_print_msg(x); } while (0)
 
 
@@ -234,6 +239,7 @@ struct test_spec {
 	struct bpf_map *xskmap_tx;
 	test_func_t test_func;
 	int mtu;
+	u32 adjust_grow;
 	u16 total_steps;
 	u16 current_step;
 	u16 nb_sockets;
@@ -288,6 +294,7 @@ int testapp_stats_fill_empty(struct test_spec *test);
 int testapp_stats_rx_dropped(struct test_spec *test);
 int testapp_stats_tx_invalid_descs(struct test_spec *test);
 int testapp_stats_rx_full(struct test_spec *test);
+int testapp_rx_ring_full_returns(struct test_spec *test);
 int testapp_teardown(struct test_spec *test);
 int testapp_too_many_frags(struct test_spec *test);
 int testapp_tx_queue_consumer(struct test_spec *test);
@@ -336,6 +343,8 @@ static const struct test_spec hw_rx_tests[] = {
 	{.name = "XDP_ADJUST_TAIL_SHRINK_MULTI_BUFF", .test_func = testapp_adjust_tail_shrink_mb},
 	{.name = "XDP_ADJUST_TAIL_GROW", .test_func = testapp_adjust_tail_grow},
 	{.name = "XDP_ADJUST_TAIL_GROW_MULTI_BUFF", .test_func = testapp_adjust_tail_grow_mb},
+	{.name = "RX_RING_FULL_RETURNS",
+	 .test_func = testapp_rx_ring_full_returns},
 };
 
 static const struct test_spec hw_tx_tests[] = {
diff --git a/tools/testing/selftests/net/lib/xsk/xskxceiver.c b/tools/testing/selftests/net/lib/xsk/xskxceiver.c
index bc92de5e8323..db58df137b64 100644
--- a/tools/testing/selftests/net/lib/xsk/xskxceiver.c
+++ b/tools/testing/selftests/net/lib/xsk/xskxceiver.c
@@ -158,6 +158,8 @@ static struct option long_options[] = {
 	{"queue", required_argument, 0, OPT_QUEUE},
 	{"max-frags", required_argument, 0, OPT_MAX_FRAGS},
 	{"timeout", required_argument, 0, OPT_TIMEOUT},
+	{"explicit-return", no_argument, 0, 'D'},
+	{"headroom", required_argument, 0, 'H'},
 	{"help", no_argument, 0, 'h'},
 	{0, 0, 0, 0}
 };
@@ -186,6 +188,10 @@ static void print_usage(char **argv)
 		"      --queue N        AF_XDP queue to bind (default 0)\n"
 		"      --max-frags N    Fragment limit for TOO_MANY_FRAGS (default by mode)\n"
 		"      --timeout SEC    Traffic, link and bind timeout (default 3)\n"
+		"  -D, --explicit-return The RX endpoint returns chunks explicitly (drv\n"
+		"                       mode); both endpoints take it\n"
+		"  -H, --headroom BYTES Least headroom the device leaves in front of a\n"
+		"                       packet, with -D\n"
 		"  -h, --help           Display this help and exit\n";
 
 	ksft_print_msg(str, basename(argv[0]));
@@ -247,6 +253,7 @@ static const struct test_spec *find_test(u32 id)
 static void parse_command_line(struct ifobject *ifobj_tx, struct ifobject *ifobj_rx, int argc,
 			       char **argv)
 {
+	bool headroom = false;
 	int option_index, c;
 	unsigned long val;
 	char *end;
@@ -254,7 +261,8 @@ static void parse_command_line(struct ifobject *ifobj_tx, struct ifobject *ifobj
 	opterr = 0;
 
 	for (;;) {
-		c = getopt_long(argc, argv, "i:vbm:lt:e:p:P:", long_options, &option_index);
+		c = getopt_long(argc, argv, "i:vbm:lt:e:p:P:DH:", long_options,
+				&option_index);
 		if (c == -1)
 			break;
 
@@ -347,6 +355,19 @@ static void parse_command_line(struct ifobject *ifobj_tx, struct ifobject *ifobj
 				print_usage(argv);
 			opt_timeout = val;
 			break;
+		case 'D':
+			opt_explicit_return = true;
+			break;
+		case 'H':
+			errno = 0;
+			val = strtoul(optarg, &end, 0);
+			/* Headroom lies within a page-sized chunk */
+			if (errno || end == optarg || *end ||
+			    val >= (unsigned long)getpagesize())
+				print_usage(argv);
+			opt_headroom = val;
+			headroom = true;
+			break;
 		case 'h':
 		default:
 			print_usage(argv);
@@ -358,6 +379,16 @@ static void parse_command_line(struct ifobject *ifobj_tx, struct ifobject *ifobj
 	    opt_mode == TEST_MODE_ALL || !opt_src_ip || !opt_dst_ip || !opt_dst_mac ||
 	    !opt_udp_port)
 		print_usage(argv);
+
+	/* Only explicit chunk return leaves the device the headroom */
+	if (headroom && !opt_explicit_return)
+		print_usage(argv);
+	/* Explicit return is a drv mode feature of the receiving endpoint.
+	 * The sending endpoint takes -D to send as the case needs it.
+	 */
+	if (opt_explicit_return && opt_endpoint_role == XSK_ENDPOINT_RX &&
+	    opt_mode != TEST_MODE_DRV)
+		print_usage(argv);
 }
 
 static void xsk_unload_xdp_programs(struct ifobject *ifobj)
@@ -370,6 +401,14 @@ static int run_pkt_test(struct test_spec *test)
 	int ret;
 
 	ret = test->test_func(test);
+	if (opt_explicit_return && opt_endpoint_role == XSK_ENDPOINT_RX)
+		ksft_print_msg("explicit return: rx descs %llu, in a chunk shared within an RX batch %llu, empty heads %llu (%llu freed), least headroom %u\n",
+			       (unsigned long long)drv_rx_descs,
+			       (unsigned long long)drv_rx_shared,
+			       (unsigned long long)drv_rx_empty_heads,
+			       (unsigned long long)drv_rx_empty_heads_freed,
+			       drv_rx_headroom == UINT_MAX ? 0 :
+			       drv_rx_headroom);
 	pkt_stream_restore_default(test);
 	return ret;
 }
@@ -468,9 +507,19 @@ static int cleanup_iface(struct ifobject *ifobj)
 	if (!ifobj_is_local(ifobj))
 		goto unload;
 
-	if (ifobj->xdp_prog)
-		xsk_detach_xdp_program(ifobj->ifindex,
-				       mode_to_xdp_flags(ifobj->mode));
+	/* With explicit return, the queue keeps its program (EBUSY) until the
+	 * kernel has released the pool of the closed socket from a work item
+	 */
+	if (ifobj->xdp_prog) {
+		int wait_ms = opt_timeout * 1000;
+
+		while (bpf_xdp_detach(ifobj->ifindex,
+				      mode_to_xdp_flags(ifobj->mode),
+				      NULL) == -EBUSY && wait_ms > 0) {
+			usleep(10 * 1000);
+			wait_ms -= 10;
+		}
+	}
 	/* After the detach, as an attached program can cap the MTU. A driver
 	 * can also refuse it while it holds the pool of a closed socket, which
 	 * the kernel releases from a work item.
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

* [PATCH net-next v2 15/15] Documentation: xsk: Describe explicit chunk return
  2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
                   ` (13 preceding siblings ...)
  2026-12-04 16:27 ` [PATCH net-next v2 14/15] selftests: net: xsk: Test explicit chunk return Björn Töpel
@ 2026-12-04 16:27 ` Björn Töpel
  14 siblings, 0 replies; 16+ messages in thread
From: Björn Töpel @ 2026-12-04 16:27 UTC (permalink / raw)
  To: David S. Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
	Willem de Bruijn, Alexei Starovoitov, Daniel Borkmann,
	Jesper Dangaard Brouer, John Fastabend, Andrii Nakryiko,
	Eduard Zingerman, Kumar Kartikeya Dwivedi, Nikolay Aleksandrov,
	Andrew Lunn, Ilias Apalodimas, Magnus Karlsson,
	Maciej Fijalkowski, Donald Hunter, Alexander Duyck,
	Saeed Mahameed, Tariq Toukan, Mark Bloch, Leon Romanovsky,
	Shuah Khan, Jonathan Corbet, netdev, bpf
  Cc: Björn Töpel, Simon Horman, Stanislav Fomichev,
	Martin KaFai Lau, Song Liu, Yonghong Song, Jiri Olsa,
	Emil Tsalapatis, Ihor Solodrai, David Wei, Tao Cui, linux-kernel,
	kernel-team, Mike Marciniszyn (Meta), linux-rdma, linux-kselftest,
	Shuah Khan, Randy Dunlap, linux-doc

XDP_UMEM_EXPLICIT_RETURN changes who owns a chunk and when, what the
program may do, and how chunks come back. None of it is documented.

Describe the setup and its errors, the program, receive and chunk
return, need_wakeup, DMA syncs, TX of received buffers, and the driver
rule.

Signed-off-by: Björn Töpel <bjorn@kernel.org>
---

Notes (v2changes):
    Changes in v2:
    - Rename from "Documentation: networking: Describe AF_XDP RX in the
      device's layout", and the section from "Device Buffer Layout" to
      "Explicit Chunk Return". Say that the application cannot influence
      where packets land, how many share a chunk, or the headroom.
    - Describe the bind requirements and their errors: CAP_NET_ADMIN in
      the initial user namespace and XDP_ZEROCOPY (Sashiko), the other
      EOPNOTSUPP cases, the UMEM size, and binds with XDP_SHARED_UMEM.
    - Describe empty heads on RX, the headroom, and when need_wakeup is
      set and cleared, with a table that tells descriptors apart.
    - Describe what TX may do with received buffers, and when a chunk is
      the application's again.
    - Say that the UMEM stops backing the queue once the last socket of
      the queue is gone, and that a tool that detaches the program right
      after closing its sockets should retry on EBUSY.
    - Say that only netlink can replace the program while the UMEM backs
      the queue.
    - Give the page pool cache size per range of page sizes, EBUSY for a
      queue that the device leases to another one, and ENODATA for page
      pools that do not take the provider (Sashiko).
    - Say that the RX ring keeps room for the chunks the kernel owes, so
      returns never wait and need no wakeup, and that the chunks a queue
      did not return are the application's once it goes or its receiving
      socket closes (Sashiko).
    - Say that the kernel does not check a chunk on the FILL rings of two
      queues, which can only corrupt the application's own data (Sashiko).
    - Say that a socket whose fd is closed while its rings stay mapped is
      still bound.
    - Add a "Drivers" paragraph on the context rule that a driver agrees
      to with PP_FLAG_ALLOW_XDP_ONLY_NETMEM, and on running the NAPI once
      after a queue start.

 Documentation/networking/af_xdp.rst | 244 +++++++++++++++++++++++++++-
 1 file changed, 243 insertions(+), 1 deletion(-)

diff --git a/Documentation/networking/af_xdp.rst b/Documentation/networking/af_xdp.rst
index 538e71adb759..073eab1da103 100644
--- a/Documentation/networking/af_xdp.rst
+++ b/Documentation/networking/af_xdp.rst
@@ -429,7 +429,9 @@ There is also an option to set the headroom of each single buffer in
 the UMEM. If you set this to N bytes, it means that the packet will
 start N bytes into the buffer leaving the first N bytes for the
 application to use. The final option is the flags field, but it will
-be dealt with in separate sections for each UMEM flag.
+be dealt with in separate sections for each UMEM flag. With the
+XDP_UMEM_EXPLICIT_RETURN flag, chunks are pages that the device fills in
+its own layout, see the "Explicit Chunk Return" section.
 
 SO_BINDTODEVICE setsockopt
 --------------------------
@@ -761,6 +763,246 @@ processing. Note that the Tx batch API guarantees that it will provide
 a batch of Tx descriptors that ends with full packet at the end. This
 to facilitate extending a zero-copy driver with multi-buffer support.
 
+Explicit Chunk Return
+=====================
+
+In the classic zero-copy mode, the driver fills one UMEM frame per
+buffer, at the UMEM headroom, and each RX descriptor gives its frame
+back to the application. The driver needs a receive path of its own
+for AF_XDP.
+
+With the XDP_UMEM_EXPLICIT_RETURN UMEM flag, an RX descriptor does not
+give its chunk back. The device places buffers in UMEM chunks as it
+places them in the pages of its page pool: several buffers may share a
+chunk, a packet may span chunks, and the device picks the offsets. A
+chunk comes back only when an RX descriptor carries
+XDP_RX_CHUNK_RETURNED, and the application must not reuse it before.
+The XDP program reads and writes packets in place, in the UMEM, but
+the kernel stores none of its own structures in the chunks.
+
+The application cannot influence the layout. The kernel and the driver
+decide where packets land, how many share a chunk, and the headroom in
+front of a packet. The application only puts chunks on the FILL ring
+and takes back the chunks that XDP_RX_CHUNK_RETURNED returns.
+
+The UMEM backs the page pools of the bound queue through a memory
+provider, so the driver needs no AF_XDP code. A driver supports the
+mode if it runs native XDP with XDP_REDIRECT, takes its receive
+buffers from a page pool of netmem that allows such providers, and
+can restart a queue.
+
+Setting up
+----------
+
+* Register the UMEM with XDP_UMEM_EXPLICIT_RETURN, aligned chunks of
+  PAGE_SIZE, and no headroom. The UMEM must hold more chunks than the
+  size of each page pool of the queue plus its cache, or the bind
+  fails with ENOSPC. The driver sizes its page pools from the ring
+  size and the MTU. The cache holds PP_ALLOC_CACHE_SIZE chunks: 128
+  with pages smaller than 16K, 32 with pages from 16K to below 64K,
+  and 8 with pages of 64K or larger.
+
+* Attach a native XDP program to the device itself through netlink, not
+  through a BPF link or an upper device such as a bond, before the bind.
+  The bind fails with ENOENT without one. While the UMEM backs the
+  queue, the program cannot be detached (EBUSY), and only netlink can
+  replace it, not a BPF link, so the queue always runs a program until
+  the UMEM no longer backs the queue. That happens shortly after the
+  last socket of the queue is gone, its fd closed and its rings
+  unmapped: a tool that detaches the program right after closing its
+  sockets should retry on EBUSY.
+
+* Put chunks on the FILL ring before the bind. The bind starts the
+  queue with the chunks it finds there, and the queue drops packets
+  while it has none. A queue that finds the FILL ring empty sets the
+  need_wakeup flag of the FILL ring, and takes chunks again at the
+  wakeup that follows, see below.
+
+* Bind with XDP_USE_NEED_WAKEUP: a queue that used up the FILL ring
+  takes chunks again only after a wakeup. A bind without it fails with
+  EINVAL. Bind with XDP_USE_SG to receive packets that the device
+  splits over more than one buffer.
+
+* The bind needs CAP_NET_ADMIN in the initial user namespace, as
+  io_uring zero-copy receive does, because the queue's program then
+  drops every packet that it does not redirect to the socket, and
+  cannot be detached. Without it, the bind fails with EPERM, also for
+  a process that has CAP_NET_ADMIN only in a user namespace of its
+  own.
+
+* XDP_COPY and XDP_ZEROCOPY fail with EOPNOTSUPP. Both ask for a
+  classic mode, a copy or the driver's own zero-copy path, and this
+  mode is neither. The bind also fails with EOPNOTSUPP on a device
+  without native XDP_REDIRECT or queue management, with XDP_USE_SG on
+  a device without multi-buffer RX (NETDEV_XDP_ACT_RX_SG), on a queue
+  that the device leases from another device, on a queue without a DMA
+  device, and on a queue that has no RX queue, such as a TX-only
+  queue. A queue that the device leases to another device fails with
+  EBUSY. A queue whose page pools do not take the provider, as on mlx5
+  without a striding RQ, fails with ENODATA.
+  A queue id beyond both the RX and the TX queues fails with EINVAL, as
+  in the classic modes.
+
+* These requirements apply to the bind that sets up the queue. A
+  socket that binds with XDP_SHARED_UMEM to the same queue takes the
+  setup of the first, and passes no flags of its own.
+
+* One socket per queue receives: the first one with an RX ring, also
+  when it binds with XDP_SHARED_UMEM. Another socket with an RX ring
+  gets EBUSY, and so does any socket with an RX ring once the receiving
+  socket is gone. Sockets that share the UMEM with XDP_SHARED_UMEM may
+  transmit. A queue without a receiving socket drops every packet that
+  its program redirects. The UMEM stops backing the queue shortly after
+  the last socket of the queue closes, when the kernel tears down its
+  buffer pool from a workqueue, as with classic zero copy.
+
+The XDP program
+---------------
+
+The program works on the packet in place, in the UMEM: direct packet
+access, bpf_xdp_load_bytes(), bpf_xdp_store_bytes(), dynptrs,
+bpf_xdp_adjust_head(), bpf_xdp_adjust_tail(), bpf_xdp_adjust_meta()
+and the RX metadata kfuncs work as with pages, on every buffer of the
+packet. What the program writes is in the UMEM for the application to
+see. The kernel keeps its own data, such as the fragment list of a
+packet that spans buffers, in kernel memory, so the application cannot
+change what the kernel relies on. The application may still change
+the packet at any time, also while the program runs: two reads of the
+same bytes may differ.
+
+Buffers of the bound queue may only go to its receiving socket. Every
+verdict but XDP_REDIRECT drops the packet, XDP_PASS included, and
+redirects to anything but the receiving socket fail.
+
+Redirect through an XSKMAP entry that holds the receiving socket.
+
+Receiving
+---------
+
+A FILL entry hands a whole chunk to the kernel, by its address, as
+in the classic modes. Each buffer of a packet becomes one RX
+descriptor that points at the data, anywhere in a chunk, and
+XDP_PKT_CONTD chains the buffers of a packet as described in the
+multi-buffer section. In front of the first buffer
+the device leaves the headroom that native XDP has on it, so a program
+may grow a header as it does without a socket. Metadata that the program
+wrote is in front of the first buffer, where the program put it. A
+packet whose metadata does not fit in front of its first buffer, in
+the same chunk, is dropped.
+
+The kernel gives a chunk back with XDP_RX_CHUNK_RETURNED in the options
+of an RX descriptor:
+
+* On a descriptor of a packet, the flag means that the kernel is done
+  with the chunk of that descriptor. The application owns the whole
+  chunk again. An empty head carries the flag like any other
+  descriptor of the packet.
+
+* A descriptor with length zero and without XDP_PKT_CONTD, at the
+  address of a chunk, only gives that chunk back. The kernel posts one
+  when the device lets go of the chunk after its last buffer reached the
+  socket, after the descriptors of its buffers. Such a descriptor is
+  never part of a packet, and it always carries XDP_RX_CHUNK_RETURNED.
+
+A first descriptor of length zero with XDP_PKT_CONTD is an empty head:
+it carries no bytes, and its address anchors the metadata in front of
+it. The data of the packet sits in the descriptors that follow. The
+kernel posts one when the device put every byte of a packet in
+fragments, as some devices do for frames larger than a page, and the
+program wrote metadata. Such a head reaches the socket only on a
+socket bound with XDP_USE_SG, as the packet then takes more than one
+descriptor.
+
+XDP_PKT_CONTD tells the two apart, never XDP_RX_CHUNK_RETURNED. The
+table assumes that the device puts no fragment of length zero in a
+packet, which no driver of this mode does:
+
+=========  ==============  ======================  ==========================
+Length     XDP_PKT_CONTD   XDP_RX_CHUNK_RETURNED   The descriptor
+=========  ==============  ======================  ==========================
+non-zero   either          either                  carries data of a packet;
+                                                   with the flag, its chunk
+                                                   came back
+zero       set             either                  is an empty head; with the
+                                                   flag, its chunk came back
+zero       clear           always set              only gives a chunk back
+=========  ==============  ======================  ==========================
+
+XDP_RX_CHUNK_RETURNED belongs to RX, and a TX descriptor that carries
+it is invalid.
+
+A chunk may go on the FILL ring again once it came back and the
+application is done with all its buffers. The kernel never gives back
+single buffers, so a packet that the application holds keeps its
+chunk. Chunks whose buffers all stayed in the kernel, as for dropped
+packets, stay with the kernel. Once the UMEM stops backing the queue,
+every chunk that the queue had not returned is the application's
+again, without a descriptor. So is every chunk that the kernel still
+owes when the receiving socket goes. A socket goes once its fd is
+closed and its rings are unmapped, as usual for AF_XDP: a socket whose
+fd is closed while its rings stay mapped is still bound.
+
+The kernel keeps room in the RX ring for one descriptor per chunk that
+it still owes back, so a return never waits for room. A packet that
+would leave less room is dropped and counted in rx_ring_full, so under
+overload packets drop a little earlier than the ring is full. A queue
+restart returns the chunks of the old queue as it stops it.
+
+Within a queue, a FILL entry of a chunk that the kernel still holds is
+invalid, and the kernel skips it. Across queues that share a UMEM, the
+kernel does not check: as with classic zero copy, a chunk on the FILL
+rings of two queues at once may be written by both devices. That
+corrupts only the application's data, as the kernel keeps nothing in
+the chunks.
+
+The kernel sets the need_wakeup flag of the FILL ring at bind and when
+the queue finds no chunks to take, and clears it once the queue took
+chunks, from the FILL ring or from those it kept, as in the classic
+zero-copy mode. Check the flag, not the FILL ring: recvmsg() or poll()
+then schedules the queue's NAPI. Returns need no wakeup, as the kernel
+posts each one as the device lets go of its chunk. With preferred busy
+polling, the application's poll runs the queue's NAPI.
+
+Devices that need DMA syncs work as they do with page pools: the
+kernel syncs a chunk for the device when it takes the chunk from the
+FILL ring, and the driver syncs each buffer for the CPU before the
+program runs.
+
+Drivers
+-------
+
+The provider takes no lock. A driver that lets it back a page pool,
+with PP_FLAG_ALLOW_XDP_ONLY_NETMEM, keeps one context at a time on the
+buffers of the queue: its NAPI, or an operation that runs only while
+that NAPI cannot use the rings, as when the driver restarts the queue,
+changes its configuration or recovers from an error. It fills and
+drains the rings only then, and runs the NAPI once after the queue
+starts, so that a queue that starts with FILL empty asks for a wakeup.
+The buffers leave the driver only to the AF_XDP socket of the queue,
+which drops its references in that NAPI.
+
+Transmitting
+------------
+
+Sockets in this mode transmit in copy mode only. A buffer that the
+application received may go on the TX ring, within these limits:
+
+* TX takes no descriptor of length zero. A forwarder skips the empty
+  head of a received packet and starts the packet at the next
+  descriptor.
+
+* With XDP_UMEM_TX_METADATA_LEN, every TX descriptor needs that much
+  room in front of it, in its chunk. Forwarded buffers cannot carry TX
+  metadata: a buffer that RX delivered may start anywhere in a chunk,
+  and in a chunk that it shares, the room in front of it may hold the
+  packet before it, which the metadata would overwrite.
+
+* A TX completion returns the address of the descriptor, not its
+  chunk. A chunk is the application's again only once an RX
+  descriptor returned it with XDP_RX_CHUNK_RETURNED and every TX
+  descriptor that points into it is on the COMPLETION ring. Only then
+  may it go on the FILL ring.
+
 Sample application
 ==================
 There is a xdpsock benchmarking/test application that can be found at
-- 
2.56.1


^ permalink raw reply related	[flat|nested] 16+ messages in thread

end of thread, other threads:[~2026-12-04 16:29 UTC | newest]

Thread overview: 16+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-04 16:27 [PATCH net-next v2 00/15] xsk: Return UMEM chunks explicitly Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 01/15] xdp: Let memory providers expose net_iovs to XDP Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 02/15] net: Add memory providers that only feed XDP Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 03/15] page_pool: Let memory providers take back net_iovs Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 04/15] xdp: Run programs on XDP-only buffers Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 05/15] xsk: Back a queue's page pools with UMEM chunks Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 06/15] xsk: Deliver packets and return chunks explicitly Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 07/15] xsk: Receive with explicit chunk return Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 08/15] xsk: Drop references of a run of buffers at once Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 09/15] eth: fbnic: Receive into XDP-only memory providers Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 10/15] net/mlx5e: Handle restarts with XDP-only providers Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 11/15] net/mlx5e: Receive into XDP-only memory providers Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 12/15] net/mlx5e: Release XDP-only pages earlier Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 13/15] net/mlx5e: Test for XDP-only pages per RQ Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 14/15] selftests: net: xsk: Test explicit chunk return Björn Töpel
2026-12-04 16:27 ` [PATCH net-next v2 15/15] Documentation: xsk: Describe " Björn Töpel

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