Skip to contentSkip to conversation

xsk: Zero copy through page-pool memory providers

PATCH In review Björn Töpel 10 participants 97 messages Nov 10 – Nov 22 Page 1 of 2

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

cover xsk: Zero copy through page-pool memory providers

Hi!

AF_XDP zero copy needs a second RX allocator in every driver. This series makes UMEM a page-pool memory provider instead: a page_pool driver opts in, and keeps its refill, recycling and DMA sync code. fbnic is the first user. Patches 1-7 are core, 8-11 fbnic.

Since the RFC [RFC], net_iov is a first class netmem, the core owns AF_XDP setup, and a refill contract replaces the NAPI kicks. The fixes are out.

Changes since the RFC:

- A readable net_iov has an address. netmem_address() and skb_frag_address() find it through struct net_iov_area, which now holds niov_shift. xdp_frag_address() is gone. (Mina, Stanislav)
- PP_FLAG_ALLOW_UNREADABLE_NETMEM keeps its meaning. A pool takes a readable provider only with the new PP_FLAG_MEM_PROVIDER. (Mina)
- The core installs the provider at bind, through the queue API, as for devmem and io_uring. A driver sets netdev_queue_mgmt_ops.xsk_page_pool, and checks chunk size, headroom and multi-buffer mode in XDP_VALIDATE_XSK_POOL. MTU and XDP program changes of a bound device get the same check. (Stanislav)
- No NAPI kicks. Drivers report the end of each refill with page_pool_refill_done(), and the core publishes the queue's NAPI for provider and socket wakeups, so no ndo_xsk_wakeup. (Mina)
- Page pools declare the RX buffers they supply, header or payload. A per-queue generation tells new pools from old ones in the restart check.
- MP_CAP_RETAIN says whether the stack may keep provider buffers. The stack copies the others on XDP_PASS, frame conversion and non-XSKMAP redirects. Frame copies are linear, so multi-buffer frames to devmap and cpumap are dropped.
- xdp_buff does not grow. The head netmem and shared info live in driver memory, reached through a union with txq.
- The buffer pool allocates xdp_buff_xsk only for copy mode and driver zero copy: 128 bytes less per chunk. (Stanislav)
- With XDP_USE_NEED_WAKEUP the FILL flag stays set. Setting it only when starved races with userspace.
- fbnic is split in four: XDP redirect, netmem heads and XDP_TX, unsplittable buffers, zero copy.
- The RFC's fixes are out. The fbnic one is upstream, and the skb head sizing is Clement's fix [1]. Other fixes found on the way go to net separately. (Stanislav, Maciej)

Unchanged: aligned chunks only (4 KiB on fbnic), and generic XDP and CPUMAP cannot feed a provider socket.

fbnic, one queue, 66-byte packets: XSK RX 21.2 Mpps (17.0 with epoll), XSK TX 28.9 Mpps, XDP_DROP costs 1.9%, 30 instructions per packet, against net-next. Tested on fbnic hardware and the fbnic QEMU model.

Still open from the RFC: how should userspace learn the chunk constraints before bind?

netkit queue leases and bnxt come later.

Björn

[RFC] https://lore.kernel.org/netdev/[email protected]/
[1] https://lore.kernel.org/bpf/[email protected]/

Björn Töpel (11):
net: Get skb fragment addresses through netmem
net: Add memory provider capabilities
xdp: Copy buffers with restricted lifetime
xsk: Allocate UMEM chunks through page_pool
xsk: Install UMEM page pool providers in the core
page_pool: Coordinate refill with memory providers
xsk: Deliver provider chunks without copying
eth: fbnic: Support XDP redirect
eth: fbnic: Use netmem for RX headers and XDP_TX
eth: fbnic: Support RX buffers it cannot split
eth: fbnic: Support AF_XDP page pool zero copy

 Documentation/networking/af_xdp.rst           |  64 +-
 Documentation/networking/netmem.rst           |  15 +
 Documentation/networking/xsk-tx-metadata.rst  |   3 +-
 .../net/ethernet/meta/fbnic/fbnic_netdev.c    |  22 +-
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c  | 601 ++++++++++++---
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h  |  28 +
 drivers/net/netkit.c                          |   3 +-
 include/linux/netdevice.h                     |   8 +
 include/linux/skbuff.h                        |  22 +-
 include/net/netdev_queues.h                   |  12 +
 include/net/netdev_rx_queue.h                 |   8 +
 include/net/netmem.h                          |  41 +-
 include/net/page_pool/helpers.h               |  38 +-
 include/net/page_pool/memory_provider.h       |  21 +
 include/net/page_pool/types.h                 |  33 +-
 include/net/xdp.h                             |  94 ++-
 include/net/xdp_sock.h                        |   4 +
 include/net/xdp_sock_drv.h                    |  45 ++
 include/net/xsk_buff_pool.h                   |   3 +
 io_uring/zcrx.c                               |   2 +
 net/core/dev.c                                |  30 +-
 net/core/dev.h                                |   8 +
 net/core/devmem.c                             |   9 +-
 net/core/devmem.h                             |   4 +-
 net/core/filter.c                             |  20 +-
 net/core/netdev_config.c                      |   2 +
 net/core/netdev_rx_queue.c                    | 143 +++-
 net/core/page_pool.c                          | 100 ++-
 net/core/page_pool_user.c                     |  25 +-
 net/core/xdp.c                                |  78 +-
 net/ethtool/rings.c                           |   7 +-
 net/xdp/Kconfig                               |   1 +
 net/xdp/Makefile                              |   2 +-
 net/xdp/xsk.c                                 |  86 ++-
 net/xdp/xsk.h                                 |  15 +
 net/xdp/xsk_buff_pool.c                       |  72 +-
 net/xdp/xsk_pp.c                              | 697 ++++++++++++++++++
 net/xdp/xsk_queue.h                           |  18 +-
 38 files changed, 2159 insertions(+), 225 deletions(-)
 create mode 100644 net/xdp/xsk_pp.c

base-commit: 2d916a8c307c31b433318509bf0311d52d509f09

Signature · 1 line
2.56.0
#1 lore raw

PATCH 1/11 net: Get skb fragment addresses through netmem

skb_frag_address() goes through struct page, so a net_iov never has an address. Only unreadable memory should lack one: XDP and BPF read fragments through this helper, and AF_XDP UMEM will back readable net_iovs. netmem_address() also returns NULL, not a bogus pointer, for an unmapped highmem page.

Generic code needs the size of a net_iov to find its address, so keep it in struct net_iov_area instead of the devmem binding.

---
 include/linux/skbuff.h | 21 +++++++++------------
 include/net/netmem.h   |  6 ++++--
 io_uring/zcrx.c        |  1 +
 net/core/devmem.c      |  8 ++++----
 net/core/devmem.h      |  4 +---
 5 files changed, 19 insertions(+), 21 deletions(-)
include/linux/skbuff.h +9 -12
index 73365c5de6f9..8b0039d49905 100644
@@ -3759,33 +3759,30 @@ int skb_cow_data_for_xdp(struct page_pool *pool, struct sk_buff **pskb,
  * skb_frag_address - gets the address of the data contained in a paged fragment
  * @frag: the paged fragment buffer
  *
- * Returns: the address of the data within @frag. The page must already
- * be mapped.
+ * Returns: the address of the data within @frag, or %NULL if the CPU cannot
+ * read it.
  */
 static inline void *skb_frag_address(const skb_frag_t *frag)
 {
-	if (!skb_frag_page(frag))
+	void *ptr = netmem_address(skb_frag_netmem(frag));
+
+	if (!ptr)
 		return NULL;
 
-	return page_address(skb_frag_page(frag)) + skb_frag_off(frag);
+	return ptr + skb_frag_off(frag);
 }
 
 /**
  * skb_frag_address_safe - gets the address of the data contained in a paged fragment
  * @frag: the paged fragment buffer
  *
- * Returns: the address of the data within @frag. Checks that the page
- * is mapped and returns %NULL otherwise.
+ * Returns: the address of the data within @frag. Checks that the memory
+ * is mapped and readable and returns %NULL otherwise.
  */
 static inline void *skb_frag_address_safe(const skb_frag_t *frag)
 {
-	struct page *page = skb_frag_page(frag);
-	void *ptr;
+	void *ptr = netmem_address(skb_frag_netmem(frag));
 
-	if (!page)
-		return NULL;
-
-	ptr = page_address(page);
 	if (unlikely(!ptr))
 		return NULL;
 
include/net/netmem.h +4 -2
index fb693bc1702a..f196b014184c 100644
@@ -72,8 +72,8 @@ enum net_iov_type {
 
 /* A memory descriptor representing abstract networking I/O vectors.
  *
- * net_iovs are allocated and used by networking code, and the size of
- * the chunk is PAGE_SIZE.
+ * net_iovs are allocated and used by networking code. Their area sets the
+ * size of a chunk, see net_iov_area.niov_shift.
  *
  * Examples include imported dmabuf memory and imported io_uring memory. See
  * net_iov_type for all the supported types. While current net_iov types are
@@ -104,6 +104,8 @@ struct net_iov_area {
 	/* Array of net_iovs for this area. */
 	struct net_iov *niovs;
 	size_t num_niovs;
+	/* Each net_iov covers 1 << niov_shift bytes. */
+	unsigned int niov_shift;
 };
 
 static inline struct net_iov_area *net_iov_owner(const struct net_iov *niov)
io_uring/zcrx.c +1 -0
index 6d7abb1636e7..555f27e6c1ba 100644
@@ -542,6 +542,7 @@ static int __zcrx_create_area(struct io_zcrx_ifq *ifq,
 	ifq->niov_shift = buf_size_shift;
 	nr_iovs = area->mem.size >> ifq->niov_shift;
 	area->nia.num_niovs = nr_iovs;
+	area->nia.niov_shift = buf_size_shift;
 
 	ret = -ENOMEM;
 	area->nia.niovs = kvmalloc_objs(area->nia.niovs[0], nr_iovs,
net/core/devmem.c +4 -4
index 5c7d9640e9d1..b9146b1f294a 100644
@@ -287,8 +287,8 @@ int net_devmem_bind_dmabuf_to_queue(struct net_device *dev, u32 rxq_idx,
 	u32 xa_idx;
 	int err;
 
-	if (binding->niov_shift != PAGE_SHIFT)
-		mp_params.rx_page_size = 1U << binding->niov_shift;
+	if (binding->area.niov_shift != PAGE_SHIFT)
+		mp_params.rx_page_size = 1U << binding->area.niov_shift;
 
 	rxq = __netif_get_rx_queue(dev, rxq_idx);
 	err = xa_alloc(&binding->bound_rxqs, &xa_idx, rxq, xa_limit_32b,
@@ -342,7 +342,7 @@ net_devmem_bind_dmabuf(struct net_device *dev, void *vdev,
 	binding->vdev = vdev;
 	write_pnet(&binding->net, sock_net(nl_sk));
 	binding->uid = sk_uid(nl_sk);
-	binding->niov_shift = niov_shift;
+	binding->area.niov_shift = niov_shift;
 	xa_init_flags(&binding->bound_rxqs, XA_FLAGS_ALLOC);
 
 	err = percpu_ref_init(&binding->ref,
@@ -605,7 +605,7 @@ int mp_dmabuf_devmem_init(struct page_pool *pool)
 	pool->dma_sync = false;
 	pool->dma_sync_for_cpu = false;
 
-	if (pool->p.order != binding->niov_shift - PAGE_SHIFT)
+	if (pool->p.order != binding->area.niov_shift - PAGE_SHIFT)
 		return -E2BIG;
 
 	net_devmem_dmabuf_binding_get(binding);
net/core/devmem.h +1 -3
index c4f476947dfa..448521990ad7 100644
@@ -83,8 +83,6 @@ struct net_devmem_dmabuf_binding {
 	 */
 	struct net_iov **tx_vec;
 
-	unsigned int niov_shift;
-
 	struct work_struct unbind_w;
 };
 
@@ -127,7 +125,7 @@ static inline unsigned long net_iov_virtual_addr(const struct net_iov *niov)
 	struct net_devmem_dmabuf_binding *binding =
 		net_devmem_iov_binding(niov);
 
-	return (unsigned long)net_iov_idx(niov) << binding->niov_shift;
+	return (unsigned long)net_iov_idx(niov) << binding->area.niov_shift;
 }
 
 static inline bool
Signature · 1 line
2.56.0
#2 lore raw

Re: [PATCH net-next v1 01/11] net: Get skb fragment addresses through netmem

Quoted 6 lines · Björn Töpel

skb_frag_address() goes through struct page, so a net_iov never has an address. Only unreadable memory should lack one: XDP and BPF read fragments through this helper, and AF_XDP UMEM will back readable net_iovs. netmem_address() also returns NULL, not a bogus pointer, for an unmapped highmem page.

Does this mean that skb_frag_address_safe() is practically identical to skb_frag_address()? I assume highmem page is the only case where non niov page isn't mapped.

Quoted 7 lines

*
- * Returns: the address of the data within @frag. The page must already
- * be mapped.
+ * Returns: the address of the data within @frag, or %NULL if the CPU cannot
+ * read it.

"CPU cannot read" isn't accurate, I assume that in iouring case the buffer is mapped to userspace.

Quoted 1 line

*/

#3 lore raw

Re: [PATCH net-next v1 01/11] net: Get skb fragment addresses through netmem

Quoted 10 lines · saeed bishara
Quoted 6 lines · Björn Töpel

skb_frag_address() goes through struct page, so a net_iov never has an address. Only unreadable memory should lack one: XDP and BPF read fragments through this helper, and AF_XDP UMEM will back readable net_iovs. netmem_address() also returns NULL, not a bogus pointer, for an unmapped highmem page.

Does this mean that skb_frag_address_safe() is practically identical to skb_frag_address()? I assume highmem page is the only case where non niov page isn't mapped.

Yes to both. With this patch they're the same, so I'll have skb_frag_address_safe() call skb_frag_address() instead of keeping a copy. Its callers can move over separately.

Quoted 7 lines
Quoted 5 lines

*
- * Returns: the address of the data within @frag. The page must already
- * be mapped.
+ * Returns: the address of the data within @frag, or %NULL if the CPU cannot
+ * read it.

"CPU cannot read" isn't accurate, I assume that in iouring case the buffer is mapped to userspace.

I'll use the netmem.rst term: "%NULL for unreadable netmem or an unmapped highmem page". Same for netmem_address() in patch 4 and MP_CAP_READABLE in patch 2.

Björn

#4 lore raw

Re: [PATCH net-next v1 01/11] net: Get skb fragment addresses through netmem

In reply to Björn Töpel
Quoted 7 lines · Björn Töpel

skb_frag_address() goes through struct page, so a net_iov never has an address. Only unreadable memory should lack one: XDP and BPF read fragments through this helper, and AF_XDP UMEM will back readable net_iovs. netmem_address() also returns NULL, not a bogus pointer, for an unmapped highmem page.

Quoted 6 lines

Generic code needs the size of a net_iov to find its address, so keep it in struct net_iov_area instead of the devmem binding.

Are the changes for niov_shift some kind of rebase error? I don't see how they're related. Otherwise changes LGTM.

Signature · 2 lines
Thanks,
Mina
#5 lore raw

Re: [PATCH net-next v1 01/11] net: Get skb fragment addresses through netmem

Quoted 11 lines · Mina Almasry
Quoted 10 lines · Björn Töpel

skb_frag_address() goes through struct page, so a net_iov never has an address. Only unreadable memory should lack one: XDP and BPF read fragments through this helper, and AF_XDP UMEM will back readable net_iovs. netmem_address() also returns NULL, not a bogus pointer, for an unmapped highmem page.

Generic code needs the size of a net_iov to find its address, so keep it in struct net_iov_area instead of the devmem binding.

Quoted 6 lines
Quoted 3 lines

Are the changes for niov_shift some kind of rebase error? I don't see how they're related. Otherwise changes LGTM.

Not a rebase error, but it's early. Nothing here reads it.

The generic code that needs it is net_iov_address() in patch 4; in this patch netmem_address() still returns NULL for every net_iov. I'll move it to patch 4.

Björn

maintainer
#6 lore raw

Re: [PATCH net-next v1 01/11] net: Get skb fragment addresses through netmem

In reply to Björn Töpel
Quoted 8 lines · On Tue, 10 Nov 2026 11:20:22 +0100 Björn Töpel wrote:

skb_frag_address() goes through struct page, so a net_iov never has an address. Only unreadable memory should lack one: XDP and BPF read fragments through this helper, and AF_XDP UMEM will back readable net_iovs. netmem_address() also returns NULL, not a bogus pointer, for an unmapped highmem page.

Generic code needs the size of a net_iov to find its address, so keep it in struct net_iov_area instead of the devmem binding.

IIRC netmem is supposed to be used for frags and memory CPU never needs to access. This patch looks odd. I haven't read the rest of the series yet but at the very least commit message should explain why this aberration is needed / correct.

#7 lore raw

Re: [PATCH net-next v1 01/11] net: Get skb fragment addresses through netmem

Quoted 7 lines · Jakub Kicinski
Quoted 6 lines · On Tue, 10 Nov 2026 11:20:22 +0100 Björn Töpel wrote:

skb_frag_address() goes through struct page, so a net_iov never has an address. Only unreadable memory should lack one: XDP and BPF read fragments through this helper, and AF_XDP UMEM will back readable net_iovs. netmem_address() also returns NULL, not a bogus pointer, for an unmapped highmem page.

Quoted 5 lines
Quoted 2 lines

Generic code needs the size of a net_iov to find its address, so keep it in struct net_iov_area instead of the devmem binding.

IIRC netmem is supposed to be used for frags and memory CPU never needs to access.

netmem covers pages too, and netmem.rst already allows readable net_iovs ("Decouple net_iov from unreadability"); the in-tree ones just happen to be unreadable.

Quoted 3 lines

This patch looks odd. I haven't read the rest of the series yet but at the very least commit message should explain why this aberration is needed / correct.

I'll expand the wording in the commit message.

maintainer
#8 lore raw

Re: [PATCH net-next v1 01/11] net: Get skb fragment addresses through netmem

Quoted 6 lines · On Mon, 16 Nov 2026 15:31:27 +0100 Björn Töpel wrote:
Quoted 2 lines

IIRC netmem is supposed to be used for frags and memory CPU never needs to access.

netmem covers pages too, and netmem.rst already allows readable net_iovs ("Decouple net_iov from unreadability"); the in-tree ones just happen to be unreadable.

Ugh, slop got in :/ I really don't think "the in-tree ones just happen to be unreadable." I seem to recall being involved in that design.

#9 lore raw

Re: [PATCH net-next v1 01/11] net: Get skb fragment addresses through netmem

Quoted 11 lines · Jakub Kicinski
Quoted 6 lines · On Mon, 16 Nov 2026 15:31:27 +0100 Björn Töpel wrote:
Quoted 2 lines

IIRC netmem is supposed to be used for frags and memory CPU never needs to access.

netmem covers pages too, and netmem.rst already allows readable net_iovs ("Decouple net_iov from unreadability"); the in-tree ones just happen to be unreadable.

Ugh, slop got in :/ I really don't think "the in-tree ones just happen to be unreadable." I seem to recall being involved in that design.

Oh, that was an intentional, I didn't think there was any reason readable net_iovs couldn't exist in the future. Actually even dmabuf net_iovs can be made readable sometimes, as some dmabufs support dma_buf_vmap, and in theory the net_iov could hold a virtual address derived from the return value of dma_buf_vmap that the kernel can access.

Do you think there is a reason net_iovs can never be extended to readable memory?

Do you want that point from netmem.rst reverted?

Signature · 2 lines
Thanks,
Mina
#10 lore raw

PATCH 2/11 net: Add memory provider capabilities

In reply to Björn Töpel

The core treats every memory provider as unreadable: installing one needs header split and no XDP program, and any page pool that allows unreadable netmem takes it. An AF_XDP UMEM provider is readable, needs XDP, and hands out whole buffers.

Describe providers by MP_CAP_READABLE and MP_CAP_FRAG; devmem and io_uring keep their behavior with MP_CAP_FRAG. A page pool takes a readable provider only with the new PP_FLAG_MEM_PROVIDER:
PP_FLAG_ALLOW_UNREADABLE_NETMEM says that a driver handles unreadable netmem, not that it handles any provider.

---
 Documentation/networking/netmem.rst     |  5 ++++
 drivers/net/netkit.c                    |  3 +-
 include/net/page_pool/helpers.h         | 14 +++++++++-
 include/net/page_pool/memory_provider.h | 14 ++++++++++
 include/net/page_pool/types.h           | 15 ++++++++--
 io_uring/zcrx.c                         |  1 +
 net/core/dev.c                          | 10 ++++---
 net/core/devmem.c                       |  1 +
 net/core/netdev_rx_queue.c              | 37 ++++++++++++++++++++-----
 net/core/page_pool.c                    | 34 +++++++++++++++++++++--
 net/ethtool/rings.c                     |  7 +++--
 net/xdp/xsk_buff_pool.c                 |  3 +-
 12 files changed, 122 insertions(+), 22 deletions(-)
Documentation/networking/netmem.rst +5 -0
index 6871dcdd700c..39cb75339704 100644
@@ -103,6 +103,11 @@ Driver RX Requirements
      which knows when dma-syncing is (or is not) appropriate.
    - PP_FLAG_ALLOW_UNREADABLE_NETMEM. The driver must specify this flag iff
      tcp-data-split is enabled.
+   - PP_FLAG_MEM_PROVIDER. The page pool takes memory from the memory
+     provider of its RX queue, readable or not. Page pool creation fails if
+     the provider is unreadable and PP_FLAG_ALLOW_UNREADABLE_NETMEM is not
+     set, so do not set it on header page pools of such a queue. Without it,
+     PP_FLAG_ALLOW_UNREADABLE_NETMEM selects unreadable providers only.
 
 5. The driver must not assume the netmem is readable and/or backed by pages.
    The netmem returned by the page_pool may be unreadable, in which case
drivers/net/netkit.c +2 -1
index 82e608e733d9..df672ed5ffcc 100644
@@ -12,6 +12,7 @@
 #include <net/netdev_lock.h>
 #include <net/netdev_queues.h>
 #include <net/netdev_rx_queue.h>
+#include <net/page_pool/memory_provider.h>
 #include <net/xdp_sock_drv.h>
 #include <net/netkit.h>
 #include <net/dst.h>
@@ -289,7 +290,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 || netif_all_mps_have_cap(phys, MP_CAP_READABLE))
 		ret = phys->netdev_ops->ndo_bpf(phys, &xdp_lower);
 out:
 	netdev_unlock(phys);
include/net/page_pool/helpers.h +13 -1
index 28635ce9454e..96e6b62cdebb 100644
@@ -62,6 +62,7 @@
 
 #include <linux/dma-mapping.h>
 
+#include <net/page_pool/memory_provider.h>
 #include <net/page_pool/types.h>
 #include <net/net_debug.h>
 #include <net/netmem.h>
@@ -519,7 +520,18 @@ static inline void page_pool_nid_changed(struct page_pool *pool, int new_nid)
  */
 static inline bool page_pool_is_unreadable(struct page_pool *pool)
 {
-	return !!pool->mp_ops;
+	return pool->mp_ops && !(pool->mp_ops->caps & MP_CAP_READABLE);
+}
+
+/**
+ * page_pool_supports_frag() - may page pool buffers be split
+ * @pool: queried page pool
+ *
+ * Return: false if the memory provider of @pool hands out whole buffers only
+ */
+static inline bool page_pool_supports_frag(const struct page_pool *pool)
+{
+	return !pool->mp_ops || pool->mp_ops->caps & MP_CAP_FRAG;
 }
 
 #endif /* _NET_PAGE_POOL_HELPERS_H */
include/net/page_pool/memory_provider.h +14 -0
index bceb5f7740e2..4417e54a0f81 100644
@@ -19,6 +19,18 @@ 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_caps - memory provider capabilities
+ * @MP_CAP_READABLE: The CPU can access provider memory. It may back header
+ *	page pools, and XDP programs may run on it.
+ * @MP_CAP_FRAG: Page pool fragments may split provider buffers.
+ */
+enum mp_caps {
+	MP_CAP_READABLE		= BIT(0),
+	MP_CAP_FRAG		= BIT(1),
+};
+
 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 +39,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 caps;
 };
 
 bool net_mp_niov_set_dma_addr(struct net_iov *niov, dma_addr_t addr);
@@ -38,6 +51,7 @@ int netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		      struct netlink_ext_ack *extack);
 int netif_mp_close_rxq(struct net_device *dev, unsigned int rxq_idx,
 		       const struct pp_memory_provider_params *old_p);
+bool netif_all_mps_have_cap(struct net_device *dev, u32 cap);
 
 /**
   * net_mp_netmem_place_in_cache() - give a netmem to a page pool
include/net/page_pool/types.h +13 -2
index 6d543076a0c0..0d48c05f1462 100644
@@ -31,8 +31,19 @@
  */
 #define PP_FLAG_ALLOW_UNREADABLE_NETMEM BIT(3)
 
+/* Take memory from the memory provider of the RX queue, if one is installed.
+ * Set page_pool_params.slow.netdev and queue_idx, and create the pool under
+ * the instance lock of the netdev.
+ * An unreadable provider also needs PP_FLAG_ALLOW_UNREADABLE_NETMEM, or page
+ * pool creation fails. Without this flag, PP_FLAG_ALLOW_UNREADABLE_NETMEM
+ * selects unreadable providers only.
+ */
+#define PP_FLAG_MEM_PROVIDER	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_MEM_PROVIDER)
 
 /* 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)
@@ -82,7 +93,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_MEM_PROVIDER.
  */
 struct page_pool_params {
 	struct_group_tagged(page_pool_params_fast, fast,
io_uring/zcrx.c +1 -0
index 555f27e6c1ba..3b5bf97aa203 100644
@@ -1478,6 +1478,7 @@ static const struct memory_provider_ops io_uring_pp_zc_ops = {
 	.destroy		= io_pp_zc_destroy,
 	.nl_fill		= io_pp_nl_fill,
 	.uninstall		= io_pp_uninstall,
+	.caps			= MP_CAP_FRAG,
 };
 
 static unsigned zcrx_parse_rq(netmem_ref *netmem_array, unsigned nr,
net/core/dev.c +6 -4
index 3b60b15e2175..663fe3e32ea0 100644
@@ -10546,8 +10546,9 @@ int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 		return -EBUSY;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
-		NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider");
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE)) {
+		NL_SET_ERR_MSG(bpf->extack,
+			       "unable to propagate XDP to device using unreadable memory provider");
 		return -EBUSY;
 	}
 
@@ -10622,8 +10623,9 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
 		return -EBUSY;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
-		NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider");
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE)) {
+		NL_SET_ERR_MSG(extack,
+			       "unable to install XDP to device using unreadable memory provider");
 		return -EBUSY;
 	}
 
net/core/devmem.c +1 -0
index b9146b1f294a..8f190b574beb 100644
@@ -698,4 +698,5 @@ static const struct memory_provider_ops dmabuf_devmem_ops = {
 	.release_netmem		= mp_dmabuf_devmem_release_page,
 	.nl_fill		= mp_dmabuf_devmem_nl_fill,
 	.uninstall		= mp_dmabuf_devmem_uninstall,
+	.caps			= MP_CAP_FRAG,
 };
net/core/netdev_rx_queue.c +30 -7
index a7261fedd5e7..9e14a747f9b5 100644
@@ -82,9 +82,13 @@ __netif_get_rx_queue_lease(struct net_device **dev, unsigned int *rxq_idx,
 /* See also page_pool_is_unreadable() */
 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->caps & MP_CAP_READABLE);
 }
 EXPORT_SYMBOL(netif_rxq_has_unreadable_mp);
 
@@ -95,6 +99,22 @@ bool netif_rxq_has_mp(struct net_device *dev, unsigned int rxq_idx)
 	return false;
 }
 
+bool netif_all_mps_have_cap(struct net_device *dev, u32 cap)
+{
+	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->caps & cap) != cap)
+			return false;
+	}
+
+	return true;
+}
+
 static int netdev_rx_queue_reconfig(struct net_device *dev,
 				    unsigned int rxq_idx,
 				    struct netdev_queue_config *qcfg_old,
@@ -189,6 +209,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 unreadable = !(p->mp_ops->caps & MP_CAP_READABLE);
 	struct netdev_queue_config qcfg[2];
 	struct netdev_rx_queue *rxq;
 	int ret;
@@ -196,16 +217,18 @@ 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) {
+	if (unreadable &&
+	    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 (unreadable && dev->cfg->hds_thresh) {
 		NL_SET_ERR_MSG(extack, "hds-thresh is not zero");
 		return -EINVAL;
 	}
-	if (dev_xdp_prog_count(dev)) {
-		NL_SET_ERR_MSG(extack, "unable to custom memory provider to device with XDP program attached");
+	if (unreadable && dev_xdp_prog_count(dev)) {
+		NL_SET_ERR_MSG(extack,
+			       "unable to use unreadable memory provider with XDP program attached");
 		return -EEXIST;
 	}
 	if (p->rx_page_size && !(qops->supported_params & QCFG_RX_PAGE_SIZE)) {
net/core/page_pool.c +31 -3
index d7c88c0b67e5..d88a3ea528d4 100644
@@ -188,6 +188,29 @@ static void page_pool_struct_check(void)
 				    PAGE_POOL_FRAG_GROUP_ALIGN);
 }
 
+static int page_pool_select_mp(struct page_pool *pool,
+			       const struct pp_memory_provider_params *mpp)
+{
+	const struct memory_provider_ops *ops = mpp->mp_ops;
+	unsigned int flags = pool->slow.flags;
+	bool readable;
+
+	if (!ops)
+		return 0;
+
+	readable = ops->caps & MP_CAP_READABLE;
+	if (flags & PP_FLAG_MEM_PROVIDER) {
+		if (!readable && !(flags & PP_FLAG_ALLOW_UNREADABLE_NETMEM))
+			return -EOPNOTSUPP;
+	} else if (readable) {
+		return 0;
+	}
+
+	pool->mp_priv = mpp->mp_priv;
+	pool->mp_ops = ops;
+	return 0;
+}
+
 static int page_pool_init(struct page_pool *pool,
 			  const struct page_pool_params *params,
 			  int cpuid)
@@ -272,12 +295,14 @@ 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_MEM_PROVIDER |
+				PP_FLAG_ALLOW_UNREADABLE_NETMEM)) {
 		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;
+		err = page_pool_select_mp(pool, &rxq->mp_params);
+		if (err)
+			goto free_ptr_ring;
 	}
 
 	if (pool->mp_ops) {
@@ -1070,6 +1095,9 @@ netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool,
 	unsigned int max_size = PAGE_SIZE << pool->p.order;
 	netmem_ref netmem = pool->frag_page;
 
+	if (static_branch_unlikely(&page_pool_mem_providers) &&
+	    WARN_ON_ONCE(!page_pool_supports_frag(pool)))
+		return 0;
 	if (WARN_ON(size > max_size))
 		return 0;
 
net/ethtool/rings.c +4 -3
index e3810c0320e3..378e171d4e10 100644
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0-only
 
 #include <net/netdev_queues.h>
+#include <net/page_pool/memory_provider.h>
 
 #include "common.h"
 #include "netlink.h"
@@ -258,15 +259,15 @@ ethnl_set_rings(struct ethnl_req_info *req_info, struct genl_info *info)
 		return -EINVAL;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE)) {
 		if (kernel_ringparam.tcp_data_split !=
 		    ETHTOOL_TCP_DATA_SPLIT_ENABLED) {
 			NL_SET_ERR_MSG(info->extack,
-				       "can't disable tcp-data-split while device has memory provider enabled");
+				       "can't disable tcp-data-split while device has unreadable memory provider enabled");
 			return -EINVAL;
 		} else if (kernel_ringparam.hds_thresh) {
 			NL_SET_ERR_MSG(info->extack,
-				       "can't set non-zero hds_thresh while device is memory provider enabled");
+				       "can't set non-zero hds_thresh while device has unreadable memory provider enabled");
 			return -EINVAL;
 		}
 	}
net/xdp/xsk_buff_pool.c +2 -1
index 7750d2ec4ee2..18966bbdb5b7 100644
@@ -2,6 +2,7 @@
 
 #include <linux/netdevice.h>
 #include <net/netdev_lock.h>
+#include <net/page_pool/memory_provider.h>
 #include <net/xsk_buff_pool.h>
 #include <net/xdp_sock.h>
 #include <net/xdp_sock_drv.h>
@@ -241,7 +242,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 		goto err_unreg_pool;
 	}
 
-	if (dev_get_min_mp_channel_count(netdev)) {
+	if (!netif_all_mps_have_cap(netdev, MP_CAP_READABLE)) {
 		err = -EBUSY;
 		goto err_unreg_pool;
 	}
Signature · 1 line
2.56.0
#11 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

Quoted 350 lines · Björn Töpel

The core treats every memory provider as unreadable: installing one needs header split and no XDP program, and any page pool that allows unreadable netmem takes it. An AF_XDP UMEM provider is readable, needs XDP, and hands out whole buffers.

Describe providers by MP_CAP_READABLE and MP_CAP_FRAG; devmem and io_uring keep their behavior with MP_CAP_FRAG. A page pool takes a readable provider only with the new PP_FLAG_MEM_PROVIDER:
PP_FLAG_ALLOW_UNREADABLE_NETMEM says that a driver handles unreadable netmem, not that it handles any provider.

---
 Documentation/networking/netmem.rst     |  5 ++++
 drivers/net/netkit.c                    |  3 +-
 include/net/page_pool/helpers.h         | 14 +++++++++-
 include/net/page_pool/memory_provider.h | 14 ++++++++++
 include/net/page_pool/types.h           | 15 ++++++++--
 io_uring/zcrx.c                         |  1 +
 net/core/dev.c                          | 10 ++++---
 net/core/devmem.c                       |  1 +
 net/core/netdev_rx_queue.c              | 37 ++++++++++++++++++++-----
 net/core/page_pool.c                    | 34 +++++++++++++++++++++--
 net/ethtool/rings.c                     |  7 +++--
 net/xdp/xsk_buff_pool.c                 |  3 +-
 12 files changed, 122 insertions(+), 22 deletions(-)
Documentation/networking/netmem.rst +5 -0
index 6871dcdd700c..39cb75339704 100644
@@ -103,6 +103,11 @@ Driver RX Requirements
      which knows when dma-syncing is (or is not) appropriate.
    - PP_FLAG_ALLOW_UNREADABLE_NETMEM. The driver must specify this flag iff
      tcp-data-split is enabled.
+   - PP_FLAG_MEM_PROVIDER. The page pool takes memory from the memory
+     provider of its RX queue, readable or not. Page pool creation fails if
+     the provider is unreadable and PP_FLAG_ALLOW_UNREADABLE_NETMEM is not
+     set, so do not set it on header page pools of such a queue. Without it,
+     PP_FLAG_ALLOW_UNREADABLE_NETMEM selects unreadable providers only.
 
 5. The driver must not assume the netmem is readable and/or backed by pages.
    The netmem returned by the page_pool may be unreadable, in which case
drivers/net/netkit.c +2 -1
index 82e608e733d9..df672ed5ffcc 100644
@@ -12,6 +12,7 @@
 #include <net/netdev_lock.h>
 #include <net/netdev_queues.h>
 #include <net/netdev_rx_queue.h>
+#include <net/page_pool/memory_provider.h>
 #include <net/xdp_sock_drv.h>
 #include <net/netkit.h>
 #include <net/dst.h>
@@ -289,7 +290,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 || netif_all_mps_have_cap(phys, MP_CAP_READABLE))
 		ret = phys->netdev_ops->ndo_bpf(phys, &xdp_lower);
 out:
 	netdev_unlock(phys);
include/net/page_pool/helpers.h +13 -1
index 28635ce9454e..96e6b62cdebb 100644
@@ -62,6 +62,7 @@
 
 #include <linux/dma-mapping.h>
 
+#include <net/page_pool/memory_provider.h>
 #include <net/page_pool/types.h>
 #include <net/net_debug.h>
 #include <net/netmem.h>
@@ -519,7 +520,18 @@ static inline void page_pool_nid_changed(struct page_pool *pool, int new_nid)
  */
 static inline bool page_pool_is_unreadable(struct page_pool *pool)
 {
-	return !!pool->mp_ops;
+	return pool->mp_ops && !(pool->mp_ops->caps & MP_CAP_READABLE);
+}
+
+/**
+ * page_pool_supports_frag() - may page pool buffers be split
+ * @pool: queried page pool
+ *
+ * Return: false if the memory provider of @pool hands out whole buffers only
+ */
+static inline bool page_pool_supports_frag(const struct page_pool *pool)
+{
+	return !pool->mp_ops || pool->mp_ops->caps & MP_CAP_FRAG;
 }
 
 #endif /* _NET_PAGE_POOL_HELPERS_H */
include/net/page_pool/memory_provider.h +14 -0
index bceb5f7740e2..4417e54a0f81 100644
@@ -19,6 +19,18 @@ 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_caps - memory provider capabilities
+ * @MP_CAP_READABLE: The CPU can access provider memory. It may back header
+ *	page pools, and XDP programs may run on it.
+ * @MP_CAP_FRAG: Page pool fragments may split provider buffers.
+ */
+enum mp_caps {
+	MP_CAP_READABLE		= BIT(0),
+	MP_CAP_FRAG		= BIT(1),
+};
+
 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 +39,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 caps;
 };
 
 bool net_mp_niov_set_dma_addr(struct net_iov *niov, dma_addr_t addr);
@@ -38,6 +51,7 @@ int netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		      struct netlink_ext_ack *extack);
 int netif_mp_close_rxq(struct net_device *dev, unsigned int rxq_idx,
 		       const struct pp_memory_provider_params *old_p);
+bool netif_all_mps_have_cap(struct net_device *dev, u32 cap);
 
 /**
   * net_mp_netmem_place_in_cache() - give a netmem to a page pool
include/net/page_pool/types.h +13 -2
index 6d543076a0c0..0d48c05f1462 100644
@@ -31,8 +31,19 @@
  */
 #define PP_FLAG_ALLOW_UNREADABLE_NETMEM BIT(3)
 
+/* Take memory from the memory provider of the RX queue, if one is installed.
+ * Set page_pool_params.slow.netdev and queue_idx, and create the pool under
+ * the instance lock of the netdev.
+ * An unreadable provider also needs PP_FLAG_ALLOW_UNREADABLE_NETMEM, or page
+ * pool creation fails. Without this flag, PP_FLAG_ALLOW_UNREADABLE_NETMEM
+ * selects unreadable providers only.
+ */
+#define PP_FLAG_MEM_PROVIDER	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_MEM_PROVIDER)
 
 /* 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)
@@ -82,7 +93,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_MEM_PROVIDER.
  */
 struct page_pool_params {
 	struct_group_tagged(page_pool_params_fast, fast,
io_uring/zcrx.c +1 -0
index 555f27e6c1ba..3b5bf97aa203 100644
@@ -1478,6 +1478,7 @@ static const struct memory_provider_ops io_uring_pp_zc_ops = {
 	.destroy		= io_pp_zc_destroy,
 	.nl_fill		= io_pp_nl_fill,
 	.uninstall		= io_pp_uninstall,
+	.caps			= MP_CAP_FRAG,
 };
 
 static unsigned zcrx_parse_rq(netmem_ref *netmem_array, unsigned nr,
net/core/dev.c +6 -4
index 3b60b15e2175..663fe3e32ea0 100644
@@ -10546,8 +10546,9 @@ int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 		return -EBUSY;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
-		NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider");
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE)) {
+		NL_SET_ERR_MSG(bpf->extack,
+			       "unable to propagate XDP to device using unreadable memory provider");
 		return -EBUSY;
 	}
 
@@ -10622,8 +10623,9 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
 		return -EBUSY;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
-		NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider");
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE)) {
+		NL_SET_ERR_MSG(extack,
+			       "unable to install XDP to device using unreadable memory provider");
 		return -EBUSY;
 	}
 
net/core/devmem.c +1 -0
index b9146b1f294a..8f190b574beb 100644
@@ -698,4 +698,5 @@ static const struct memory_provider_ops dmabuf_devmem_ops = {
 	.release_netmem		= mp_dmabuf_devmem_release_page,
 	.nl_fill		= mp_dmabuf_devmem_nl_fill,
 	.uninstall		= mp_dmabuf_devmem_uninstall,
+	.caps			= MP_CAP_FRAG,
 };
net/core/netdev_rx_queue.c +30 -7
index a7261fedd5e7..9e14a747f9b5 100644
@@ -82,9 +82,13 @@ __netif_get_rx_queue_lease(struct net_device **dev, unsigned int *rxq_idx,
 /* See also page_pool_is_unreadable() */
 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->caps & MP_CAP_READABLE);
 }
 EXPORT_SYMBOL(netif_rxq_has_unreadable_mp);
 
@@ -95,6 +99,22 @@ bool netif_rxq_has_mp(struct net_device *dev, unsigned int rxq_idx)
 	return false;
 }
 
+bool netif_all_mps_have_cap(struct net_device *dev, u32 cap)
+{
+	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->caps & cap) != cap)
+			return false;
+	}
+
+	return true;
+}
+
 static int netdev_rx_queue_reconfig(struct net_device *dev,
 				    unsigned int rxq_idx,
 				    struct netdev_queue_config *qcfg_old,
@@ -189,6 +209,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 unreadable = !(p->mp_ops->caps & MP_CAP_READABLE);
 	struct netdev_queue_config qcfg[2];
 	struct netdev_rx_queue *rxq;
 	int ret;
@@ -196,16 +217,18 @@ 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) {
+	if (unreadable &&
+	    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 (unreadable && dev->cfg->hds_thresh) {
 		NL_SET_ERR_MSG(extack, "hds-thresh is not zero");
 		return -EINVAL;
 	}
-	if (dev_xdp_prog_count(dev)) {
-		NL_SET_ERR_MSG(extack, "unable to custom memory provider to device with XDP program attached");
+	if (unreadable && dev_xdp_prog_count(dev)) {
+		NL_SET_ERR_MSG(extack,
+			       "unable to use unreadable memory provider with XDP program attached");
 		return -EEXIST;
 	}
 	if (p->rx_page_size && !(qops->supported_params & QCFG_RX_PAGE_SIZE)) {
net/core/page_pool.c +28 -3
index d7c88c0b67e5..d88a3ea528d4 100644
@@ -188,6 +188,29 @@ static void page_pool_struct_check(void)
 				    PAGE_POOL_FRAG_GROUP_ALIGN);
 }
 
+static int page_pool_select_mp(struct page_pool *pool,
+			       const struct pp_memory_provider_params *mpp)
+{
+	const struct memory_provider_ops *ops = mpp->mp_ops;
+	unsigned int flags = pool->slow.flags;
+	bool readable;
+
+	if (!ops)
+		return 0;
+
+	readable = ops->caps & MP_CAP_READABLE;
+	if (flags & PP_FLAG_MEM_PROVIDER) {
+		if (!readable && !(flags & PP_FLAG_ALLOW_UNREADABLE_NETMEM))
+			return -EOPNOTSUPP;
+	} else if (readable) {
+		return 0;
+	}
+
+	pool->mp_priv = mpp->mp_priv;
+	pool->mp_ops = ops;
+	return 0;
+}
+
 static int page_pool_init(struct page_pool *pool,
 			  const struct page_pool_params *params,
 			  int cpuid)
@@ -272,12 +295,14 @@ 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_MEM_PROVIDER |
+				PP_FLAG_ALLOW_UNREADABLE_NETMEM)) {
 		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;
+		err = page_pool_select_mp(pool, &rxq->mp_params);
+		if (err)
+			goto free_ptr_ring;
 	}
 
 	if (pool->mp_ops) {
@@ -1070,6 +1095,9 @@ netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool,
 	unsigned int max_size = PAGE_SIZE << pool->p.order;
 	netmem_ref netmem = pool->frag_page;
 

[..]

net/core/page_pool.c netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool, · line 1102

Quoted 6 lines
net/core/page_pool.c +3 -0
+	if (static_branch_unlikely(&page_pool_mem_providers) &&
+	    WARN_ON_ONCE(!page_pool_supports_frag(pool)))
+		return 0;
 	if (WARN_ON(size > max_size))
 		return 0;

What's the deal with that? How do we get here?

#12 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

Quoted 354 lines · Stanislav Fomichev
Quoted 350 lines · Björn Töpel

The core treats every memory provider as unreadable: installing one needs header split and no XDP program, and any page pool that allows unreadable netmem takes it. An AF_XDP UMEM provider is readable, needs XDP, and hands out whole buffers.

Describe providers by MP_CAP_READABLE and MP_CAP_FRAG; devmem and io_uring keep their behavior with MP_CAP_FRAG. A page pool takes a readable provider only with the new PP_FLAG_MEM_PROVIDER:
PP_FLAG_ALLOW_UNREADABLE_NETMEM says that a driver handles unreadable netmem, not that it handles any provider.

---
 Documentation/networking/netmem.rst     |  5 ++++
 drivers/net/netkit.c                    |  3 +-
 include/net/page_pool/helpers.h         | 14 +++++++++-
 include/net/page_pool/memory_provider.h | 14 ++++++++++
 include/net/page_pool/types.h           | 15 ++++++++--
 io_uring/zcrx.c                         |  1 +
 net/core/dev.c                          | 10 ++++---
 net/core/devmem.c                       |  1 +
 net/core/netdev_rx_queue.c              | 37 ++++++++++++++++++++-----
 net/core/page_pool.c                    | 34 +++++++++++++++++++++--
 net/ethtool/rings.c                     |  7 +++--
 net/xdp/xsk_buff_pool.c                 |  3 +-
 12 files changed, 122 insertions(+), 22 deletions(-)
Documentation/networking/netmem.rst +5 -0
index 6871dcdd700c..39cb75339704 100644
@@ -103,6 +103,11 @@ Driver RX Requirements
      which knows when dma-syncing is (or is not) appropriate.
    - PP_FLAG_ALLOW_UNREADABLE_NETMEM. The driver must specify this flag iff
      tcp-data-split is enabled.
+   - PP_FLAG_MEM_PROVIDER. The page pool takes memory from the memory
+     provider of its RX queue, readable or not. Page pool creation fails if
+     the provider is unreadable and PP_FLAG_ALLOW_UNREADABLE_NETMEM is not
+     set, so do not set it on header page pools of such a queue. Without it,
+     PP_FLAG_ALLOW_UNREADABLE_NETMEM selects unreadable providers only.
 
 5. The driver must not assume the netmem is readable and/or backed by pages.
    The netmem returned by the page_pool may be unreadable, in which case
drivers/net/netkit.c +2 -1
index 82e608e733d9..df672ed5ffcc 100644
@@ -12,6 +12,7 @@
 #include <net/netdev_lock.h>
 #include <net/netdev_queues.h>
 #include <net/netdev_rx_queue.h>
+#include <net/page_pool/memory_provider.h>
 #include <net/xdp_sock_drv.h>
 #include <net/netkit.h>
 #include <net/dst.h>
@@ -289,7 +290,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 || netif_all_mps_have_cap(phys, MP_CAP_READABLE))
 		ret = phys->netdev_ops->ndo_bpf(phys, &xdp_lower);
 out:
 	netdev_unlock(phys);
include/net/page_pool/helpers.h +13 -1
index 28635ce9454e..96e6b62cdebb 100644
@@ -62,6 +62,7 @@
 
 #include <linux/dma-mapping.h>
 
+#include <net/page_pool/memory_provider.h>
 #include <net/page_pool/types.h>
 #include <net/net_debug.h>
 #include <net/netmem.h>
@@ -519,7 +520,18 @@ static inline void page_pool_nid_changed(struct page_pool *pool, int new_nid)
  */
 static inline bool page_pool_is_unreadable(struct page_pool *pool)
 {
-	return !!pool->mp_ops;
+	return pool->mp_ops && !(pool->mp_ops->caps & MP_CAP_READABLE);
+}
+
+/**
+ * page_pool_supports_frag() - may page pool buffers be split
+ * @pool: queried page pool
+ *
+ * Return: false if the memory provider of @pool hands out whole buffers only
+ */
+static inline bool page_pool_supports_frag(const struct page_pool *pool)
+{
+	return !pool->mp_ops || pool->mp_ops->caps & MP_CAP_FRAG;
 }
 
 #endif /* _NET_PAGE_POOL_HELPERS_H */
include/net/page_pool/memory_provider.h +14 -0
index bceb5f7740e2..4417e54a0f81 100644
@@ -19,6 +19,18 @@ 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_caps - memory provider capabilities
+ * @MP_CAP_READABLE: The CPU can access provider memory. It may back header
+ *	page pools, and XDP programs may run on it.
+ * @MP_CAP_FRAG: Page pool fragments may split provider buffers.
+ */
+enum mp_caps {
+	MP_CAP_READABLE		= BIT(0),
+	MP_CAP_FRAG		= BIT(1),
+};
+
 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 +39,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 caps;
 };
 
 bool net_mp_niov_set_dma_addr(struct net_iov *niov, dma_addr_t addr);
@@ -38,6 +51,7 @@ int netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		      struct netlink_ext_ack *extack);
 int netif_mp_close_rxq(struct net_device *dev, unsigned int rxq_idx,
 		       const struct pp_memory_provider_params *old_p);
+bool netif_all_mps_have_cap(struct net_device *dev, u32 cap);
 
 /**
   * net_mp_netmem_place_in_cache() - give a netmem to a page pool
include/net/page_pool/types.h +13 -2
index 6d543076a0c0..0d48c05f1462 100644
@@ -31,8 +31,19 @@
  */
 #define PP_FLAG_ALLOW_UNREADABLE_NETMEM BIT(3)
 
+/* Take memory from the memory provider of the RX queue, if one is installed.
+ * Set page_pool_params.slow.netdev and queue_idx, and create the pool under
+ * the instance lock of the netdev.
+ * An unreadable provider also needs PP_FLAG_ALLOW_UNREADABLE_NETMEM, or page
+ * pool creation fails. Without this flag, PP_FLAG_ALLOW_UNREADABLE_NETMEM
+ * selects unreadable providers only.
+ */
+#define PP_FLAG_MEM_PROVIDER	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_MEM_PROVIDER)
 
 /* 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)
@@ -82,7 +93,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_MEM_PROVIDER.
  */
 struct page_pool_params {
 	struct_group_tagged(page_pool_params_fast, fast,
io_uring/zcrx.c +1 -0
index 555f27e6c1ba..3b5bf97aa203 100644
@@ -1478,6 +1478,7 @@ static const struct memory_provider_ops io_uring_pp_zc_ops = {
 	.destroy		= io_pp_zc_destroy,
 	.nl_fill		= io_pp_nl_fill,
 	.uninstall		= io_pp_uninstall,
+	.caps			= MP_CAP_FRAG,
 };
 
 static unsigned zcrx_parse_rq(netmem_ref *netmem_array, unsigned nr,
net/core/dev.c +6 -4
index 3b60b15e2175..663fe3e32ea0 100644
@@ -10546,8 +10546,9 @@ int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 		return -EBUSY;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
-		NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider");
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE)) {
+		NL_SET_ERR_MSG(bpf->extack,
+			       "unable to propagate XDP to device using unreadable memory provider");
 		return -EBUSY;
 	}
 
@@ -10622,8 +10623,9 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
 		return -EBUSY;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
-		NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider");
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE)) {
+		NL_SET_ERR_MSG(extack,
+			       "unable to install XDP to device using unreadable memory provider");
 		return -EBUSY;
 	}
 
net/core/devmem.c +1 -0
index b9146b1f294a..8f190b574beb 100644
@@ -698,4 +698,5 @@ static const struct memory_provider_ops dmabuf_devmem_ops = {
 	.release_netmem		= mp_dmabuf_devmem_release_page,
 	.nl_fill		= mp_dmabuf_devmem_nl_fill,
 	.uninstall		= mp_dmabuf_devmem_uninstall,
+	.caps			= MP_CAP_FRAG,
 };
net/core/netdev_rx_queue.c +30 -7
index a7261fedd5e7..9e14a747f9b5 100644
@@ -82,9 +82,13 @@ __netif_get_rx_queue_lease(struct net_device **dev, unsigned int *rxq_idx,
 /* See also page_pool_is_unreadable() */
 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->caps & MP_CAP_READABLE);
 }
 EXPORT_SYMBOL(netif_rxq_has_unreadable_mp);
 
@@ -95,6 +99,22 @@ bool netif_rxq_has_mp(struct net_device *dev, unsigned int rxq_idx)
 	return false;
 }
 
+bool netif_all_mps_have_cap(struct net_device *dev, u32 cap)
+{
+	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->caps & cap) != cap)
+			return false;
+	}
+
+	return true;
+}
+
 static int netdev_rx_queue_reconfig(struct net_device *dev,
 				    unsigned int rxq_idx,
 				    struct netdev_queue_config *qcfg_old,
@@ -189,6 +209,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 unreadable = !(p->mp_ops->caps & MP_CAP_READABLE);
 	struct netdev_queue_config qcfg[2];
 	struct netdev_rx_queue *rxq;
 	int ret;
@@ -196,16 +217,18 @@ 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) {
+	if (unreadable &&
+	    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 (unreadable && dev->cfg->hds_thresh) {
 		NL_SET_ERR_MSG(extack, "hds-thresh is not zero");
 		return -EINVAL;
 	}
-	if (dev_xdp_prog_count(dev)) {
-		NL_SET_ERR_MSG(extack, "unable to custom memory provider to device with XDP program attached");
+	if (unreadable && dev_xdp_prog_count(dev)) {
+		NL_SET_ERR_MSG(extack,
+			       "unable to use unreadable memory provider with XDP program attached");
 		return -EEXIST;
 	}
 	if (p->rx_page_size && !(qops->supported_params & QCFG_RX_PAGE_SIZE)) {
net/core/page_pool.c +28 -3
index d7c88c0b67e5..d88a3ea528d4 100644
@@ -188,6 +188,29 @@ static void page_pool_struct_check(void)
 				    PAGE_POOL_FRAG_GROUP_ALIGN);
 }
 
+static int page_pool_select_mp(struct page_pool *pool,
+			       const struct pp_memory_provider_params *mpp)
+{
+	const struct memory_provider_ops *ops = mpp->mp_ops;
+	unsigned int flags = pool->slow.flags;
+	bool readable;
+
+	if (!ops)
+		return 0;
+
+	readable = ops->caps & MP_CAP_READABLE;
+	if (flags & PP_FLAG_MEM_PROVIDER) {
+		if (!readable && !(flags & PP_FLAG_ALLOW_UNREADABLE_NETMEM))
+			return -EOPNOTSUPP;
+	} else if (readable) {
+		return 0;
+	}
+
+	pool->mp_priv = mpp->mp_priv;
+	pool->mp_ops = ops;
+	return 0;
+}
+
 static int page_pool_init(struct page_pool *pool,
 			  const struct page_pool_params *params,
 			  int cpuid)
@@ -272,12 +295,14 @@ 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_MEM_PROVIDER |
+				PP_FLAG_ALLOW_UNREADABLE_NETMEM)) {
 		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;
+		err = page_pool_select_mp(pool, &rxq->mp_params);
+		if (err)
+			goto free_ptr_ring;
 	}
 
 	if (pool->mp_ops) {
@@ -1070,6 +1095,9 @@ netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool,
 	unsigned int max_size = PAGE_SIZE << pool->p.order;
 	netmem_ref netmem = pool->frag_page;
 

[..]

Quoted 8 lines

net/core/page_pool.c netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool, · line 1102

Quoted 6 lines
net/core/page_pool.c +3 -0
+	if (static_branch_unlikely(&page_pool_mem_providers) &&
+	    WARN_ON_ONCE(!page_pool_supports_frag(pool)))
+		return 0;
 	if (WARN_ON(size > max_size))
 		return 0;

What's the deal with that? How do we get here?

Hey! Thanks for taking a look at the series!

An explicit frag call on a whole-buffer provider is a driver bug: UMEM chunks can be smaller than a page, and RX gives the whole chunk to userspace.

But page_pool_alloc_netmem() also picks frags for small requests, so a valid call can warn.

I think it would be better to make it return a whole buffer and its actual size. The WARN stays in the frag API, before taking a new buffer? Wdyt?

Björn

#13 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

Quoted 371 lines · Björn Töpel
Quoted 354 lines · Stanislav Fomichev
Quoted 350 lines · Björn Töpel

The core treats every memory provider as unreadable: installing one needs header split and no XDP program, and any page pool that allows unreadable netmem takes it. An AF_XDP UMEM provider is readable, needs XDP, and hands out whole buffers.

Describe providers by MP_CAP_READABLE and MP_CAP_FRAG; devmem and io_uring keep their behavior with MP_CAP_FRAG. A page pool takes a readable provider only with the new PP_FLAG_MEM_PROVIDER:
PP_FLAG_ALLOW_UNREADABLE_NETMEM says that a driver handles unreadable netmem, not that it handles any provider.

---
 Documentation/networking/netmem.rst     |  5 ++++
 drivers/net/netkit.c                    |  3 +-
 include/net/page_pool/helpers.h         | 14 +++++++++-
 include/net/page_pool/memory_provider.h | 14 ++++++++++
 include/net/page_pool/types.h           | 15 ++++++++--
 io_uring/zcrx.c                         |  1 +
 net/core/dev.c                          | 10 ++++---
 net/core/devmem.c                       |  1 +
 net/core/netdev_rx_queue.c              | 37 ++++++++++++++++++++-----
 net/core/page_pool.c                    | 34 +++++++++++++++++++++--
 net/ethtool/rings.c                     |  7 +++--
 net/xdp/xsk_buff_pool.c                 |  3 +-
 12 files changed, 122 insertions(+), 22 deletions(-)
Documentation/networking/netmem.rst +5 -0
index 6871dcdd700c..39cb75339704 100644
@@ -103,6 +103,11 @@ Driver RX Requirements
      which knows when dma-syncing is (or is not) appropriate.
    - PP_FLAG_ALLOW_UNREADABLE_NETMEM. The driver must specify this flag iff
      tcp-data-split is enabled.
+   - PP_FLAG_MEM_PROVIDER. The page pool takes memory from the memory
+     provider of its RX queue, readable or not. Page pool creation fails if
+     the provider is unreadable and PP_FLAG_ALLOW_UNREADABLE_NETMEM is not
+     set, so do not set it on header page pools of such a queue. Without it,
+     PP_FLAG_ALLOW_UNREADABLE_NETMEM selects unreadable providers only.
 
 5. The driver must not assume the netmem is readable and/or backed by pages.
    The netmem returned by the page_pool may be unreadable, in which case
drivers/net/netkit.c +2 -1
index 82e608e733d9..df672ed5ffcc 100644
@@ -12,6 +12,7 @@
 #include <net/netdev_lock.h>
 #include <net/netdev_queues.h>
 #include <net/netdev_rx_queue.h>
+#include <net/page_pool/memory_provider.h>
 #include <net/xdp_sock_drv.h>
 #include <net/netkit.h>
 #include <net/dst.h>
@@ -289,7 +290,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 || netif_all_mps_have_cap(phys, MP_CAP_READABLE))
 		ret = phys->netdev_ops->ndo_bpf(phys, &xdp_lower);
 out:
 	netdev_unlock(phys);
include/net/page_pool/helpers.h +13 -1
index 28635ce9454e..96e6b62cdebb 100644
@@ -62,6 +62,7 @@
 
 #include <linux/dma-mapping.h>
 
+#include <net/page_pool/memory_provider.h>
 #include <net/page_pool/types.h>
 #include <net/net_debug.h>
 #include <net/netmem.h>
@@ -519,7 +520,18 @@ static inline void page_pool_nid_changed(struct page_pool *pool, int new_nid)
  */
 static inline bool page_pool_is_unreadable(struct page_pool *pool)
 {
-	return !!pool->mp_ops;
+	return pool->mp_ops && !(pool->mp_ops->caps & MP_CAP_READABLE);
+}
+
+/**
+ * page_pool_supports_frag() - may page pool buffers be split
+ * @pool: queried page pool
+ *
+ * Return: false if the memory provider of @pool hands out whole buffers only
+ */
+static inline bool page_pool_supports_frag(const struct page_pool *pool)
+{
+	return !pool->mp_ops || pool->mp_ops->caps & MP_CAP_FRAG;
 }
 
 #endif /* _NET_PAGE_POOL_HELPERS_H */
include/net/page_pool/memory_provider.h +14 -0
index bceb5f7740e2..4417e54a0f81 100644
@@ -19,6 +19,18 @@ 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_caps - memory provider capabilities
+ * @MP_CAP_READABLE: The CPU can access provider memory. It may back header
+ *	page pools, and XDP programs may run on it.
+ * @MP_CAP_FRAG: Page pool fragments may split provider buffers.
+ */
+enum mp_caps {
+	MP_CAP_READABLE		= BIT(0),
+	MP_CAP_FRAG		= BIT(1),
+};
+
 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 +39,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 caps;
 };
 
 bool net_mp_niov_set_dma_addr(struct net_iov *niov, dma_addr_t addr);
@@ -38,6 +51,7 @@ int netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		      struct netlink_ext_ack *extack);
 int netif_mp_close_rxq(struct net_device *dev, unsigned int rxq_idx,
 		       const struct pp_memory_provider_params *old_p);
+bool netif_all_mps_have_cap(struct net_device *dev, u32 cap);
 
 /**
   * net_mp_netmem_place_in_cache() - give a netmem to a page pool
include/net/page_pool/types.h +13 -2
index 6d543076a0c0..0d48c05f1462 100644
@@ -31,8 +31,19 @@
  */
 #define PP_FLAG_ALLOW_UNREADABLE_NETMEM BIT(3)
 
+/* Take memory from the memory provider of the RX queue, if one is installed.
+ * Set page_pool_params.slow.netdev and queue_idx, and create the pool under
+ * the instance lock of the netdev.
+ * An unreadable provider also needs PP_FLAG_ALLOW_UNREADABLE_NETMEM, or page
+ * pool creation fails. Without this flag, PP_FLAG_ALLOW_UNREADABLE_NETMEM
+ * selects unreadable providers only.
+ */
+#define PP_FLAG_MEM_PROVIDER	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_MEM_PROVIDER)
 
 /* 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)
@@ -82,7 +93,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_MEM_PROVIDER.
  */
 struct page_pool_params {
 	struct_group_tagged(page_pool_params_fast, fast,
io_uring/zcrx.c +1 -0
index 555f27e6c1ba..3b5bf97aa203 100644
@@ -1478,6 +1478,7 @@ static const struct memory_provider_ops io_uring_pp_zc_ops = {
 	.destroy		= io_pp_zc_destroy,
 	.nl_fill		= io_pp_nl_fill,
 	.uninstall		= io_pp_uninstall,
+	.caps			= MP_CAP_FRAG,
 };
 
 static unsigned zcrx_parse_rq(netmem_ref *netmem_array, unsigned nr,
net/core/dev.c +6 -4
index 3b60b15e2175..663fe3e32ea0 100644
@@ -10546,8 +10546,9 @@ int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 		return -EBUSY;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
-		NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider");
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE)) {
+		NL_SET_ERR_MSG(bpf->extack,
+			       "unable to propagate XDP to device using unreadable memory provider");
 		return -EBUSY;
 	}
 
@@ -10622,8 +10623,9 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
 		return -EBUSY;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
-		NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider");
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE)) {
+		NL_SET_ERR_MSG(extack,
+			       "unable to install XDP to device using unreadable memory provider");
 		return -EBUSY;
 	}
 
net/core/devmem.c +1 -0
index b9146b1f294a..8f190b574beb 100644
@@ -698,4 +698,5 @@ static const struct memory_provider_ops dmabuf_devmem_ops = {
 	.release_netmem		= mp_dmabuf_devmem_release_page,
 	.nl_fill		= mp_dmabuf_devmem_nl_fill,
 	.uninstall		= mp_dmabuf_devmem_uninstall,
+	.caps			= MP_CAP_FRAG,
 };
net/core/netdev_rx_queue.c +30 -7
index a7261fedd5e7..9e14a747f9b5 100644
@@ -82,9 +82,13 @@ __netif_get_rx_queue_lease(struct net_device **dev, unsigned int *rxq_idx,
 /* See also page_pool_is_unreadable() */
 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->caps & MP_CAP_READABLE);
 }
 EXPORT_SYMBOL(netif_rxq_has_unreadable_mp);
 
@@ -95,6 +99,22 @@ bool netif_rxq_has_mp(struct net_device *dev, unsigned int rxq_idx)
 	return false;
 }
 
+bool netif_all_mps_have_cap(struct net_device *dev, u32 cap)
+{
+	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->caps & cap) != cap)
+			return false;
+	}
+
+	return true;
+}
+
 static int netdev_rx_queue_reconfig(struct net_device *dev,
 				    unsigned int rxq_idx,
 				    struct netdev_queue_config *qcfg_old,
@@ -189,6 +209,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 unreadable = !(p->mp_ops->caps & MP_CAP_READABLE);
 	struct netdev_queue_config qcfg[2];
 	struct netdev_rx_queue *rxq;
 	int ret;
@@ -196,16 +217,18 @@ 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) {
+	if (unreadable &&
+	    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 (unreadable && dev->cfg->hds_thresh) {
 		NL_SET_ERR_MSG(extack, "hds-thresh is not zero");
 		return -EINVAL;
 	}
-	if (dev_xdp_prog_count(dev)) {
-		NL_SET_ERR_MSG(extack, "unable to custom memory provider to device with XDP program attached");
+	if (unreadable && dev_xdp_prog_count(dev)) {
+		NL_SET_ERR_MSG(extack,
+			       "unable to use unreadable memory provider with XDP program attached");
 		return -EEXIST;
 	}
 	if (p->rx_page_size && !(qops->supported_params & QCFG_RX_PAGE_SIZE)) {
net/core/page_pool.c +28 -3
index d7c88c0b67e5..d88a3ea528d4 100644
@@ -188,6 +188,29 @@ static void page_pool_struct_check(void)
 				    PAGE_POOL_FRAG_GROUP_ALIGN);
 }
 
+static int page_pool_select_mp(struct page_pool *pool,
+			       const struct pp_memory_provider_params *mpp)
+{
+	const struct memory_provider_ops *ops = mpp->mp_ops;
+	unsigned int flags = pool->slow.flags;
+	bool readable;
+
+	if (!ops)
+		return 0;
+
+	readable = ops->caps & MP_CAP_READABLE;
+	if (flags & PP_FLAG_MEM_PROVIDER) {
+		if (!readable && !(flags & PP_FLAG_ALLOW_UNREADABLE_NETMEM))
+			return -EOPNOTSUPP;
+	} else if (readable) {
+		return 0;
+	}
+
+	pool->mp_priv = mpp->mp_priv;
+	pool->mp_ops = ops;
+	return 0;
+}
+
 static int page_pool_init(struct page_pool *pool,
 			  const struct page_pool_params *params,
 			  int cpuid)
@@ -272,12 +295,14 @@ 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_MEM_PROVIDER |
+				PP_FLAG_ALLOW_UNREADABLE_NETMEM)) {
 		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;
+		err = page_pool_select_mp(pool, &rxq->mp_params);
+		if (err)
+			goto free_ptr_ring;
 	}
 
 	if (pool->mp_ops) {
@@ -1070,6 +1095,9 @@ netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool,
 	unsigned int max_size = PAGE_SIZE << pool->p.order;
 	netmem_ref netmem = pool->frag_page;
 

[..]

Quoted 8 lines

net/core/page_pool.c netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool, · line 1102

Quoted 6 lines
net/core/page_pool.c +3 -0
+	if (static_branch_unlikely(&page_pool_mem_providers) &&
+	    WARN_ON_ONCE(!page_pool_supports_frag(pool)))
+		return 0;
 	if (WARN_ON(size > max_size))
 		return 0;

What's the deal with that? How do we get here?

Hey! Thanks for taking a look at the series!

An explicit frag call on a whole-buffer provider is a driver bug: UMEM chunks can be smaller than a page, and RX gives the whole chunk to userspace.

Quoted 6 lines

But page_pool_alloc_netmem() also picks frags for small requests, so a valid call can warn.

I think it would be better to make it return a whole buffer and its actual size. The WARN stays in the frag API, before taking a new buffer? Wdyt?

I see.. Idk, I'd still return 0 here, but without a warn. Not sure we want a warn for any api misuse? Returning no netmem is gonna be enough to debug things? As for the calls from page_pool_alloc_netmem, I'd also handle it explicitly? if (size > max_size || !page_pool_supports_frag) ? But no strong preference, up to you, was mostly trying to understand what we are warning against here :-)

#14 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

Quoted 26 lines · Stanislav Fomichev
Quoted 18 lines · Björn Töpel
Quoted 10 lines · Stanislav Fomichev

net/core/page_pool.c netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool, · line 1102

Quoted 6 lines · Björn Töpel
net/core/page_pool.c +3 -0
+	if (static_branch_unlikely(&page_pool_mem_providers) &&
+	    WARN_ON_ONCE(!page_pool_supports_frag(pool)))
+		return 0;
 	if (WARN_ON(size > max_size))
 		return 0;

What's the deal with that? How do we get here?

Hey! Thanks for taking a look at the series!

An explicit frag call on a whole-buffer provider is a driver bug: UMEM chunks can be smaller than a page, and RX gives the whole chunk to userspace.

Quoted 6 lines

But page_pool_alloc_netmem() also picks frags for small requests, so a valid call can warn.

I think it would be better to make it return a whole buffer and its actual size. The WARN stays in the frag API, before taking a new buffer? Wdyt?

Quoted 6 lines

I see.. Idk, I'd still return 0 here, but without a warn. Not sure we want a warn for any api misuse? Returning no netmem is gonna be enough to debug things? As for the calls from page_pool_alloc_netmem, I'd also handle it explicitly? if (size > max_size || !page_pool_supports_frag) ? But no strong preference, up to you, was mostly trying to understand what we are warning against here :-)

Yes, page_pool_alloc_netmem() gets the explicit check. Thanks!

For the frag API I'd keep a WARN_ON_ONCE, like the size check right below it. A silent 0 looks like an empty provider: the queue just stalls, and nothing points at the driver. With the helper fixed, only an explicit frag call on such a pool gets there... Wdyt? I'll probably take that route for v2.

Björn

#15 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

Quoted 35 lines · Björn Töpel
Quoted 26 lines · Stanislav Fomichev
Quoted 18 lines · Björn Töpel
Quoted 10 lines · Stanislav Fomichev

net/core/page_pool.c netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool, · line 1102

Quoted 6 lines · Björn Töpel
net/core/page_pool.c +3 -0
+	if (static_branch_unlikely(&page_pool_mem_providers) &&
+	    WARN_ON_ONCE(!page_pool_supports_frag(pool)))
+		return 0;
 	if (WARN_ON(size > max_size))
 		return 0;

What's the deal with that? How do we get here?

Hey! Thanks for taking a look at the series!

An explicit frag call on a whole-buffer provider is a driver bug: UMEM chunks can be smaller than a page, and RX gives the whole chunk to userspace.

Quoted 6 lines

But page_pool_alloc_netmem() also picks frags for small requests, so a valid call can warn.

I think it would be better to make it return a whole buffer and its actual size. The WARN stays in the frag API, before taking a new buffer? Wdyt?

Quoted 6 lines

I see.. Idk, I'd still return 0 here, but without a warn. Not sure we want a warn for any api misuse? Returning no netmem is gonna be enough to debug things? As for the calls from page_pool_alloc_netmem, I'd also handle it explicitly? if (size > max_size || !page_pool_supports_frag) ? But no strong preference, up to you, was mostly trying to understand what we are warning against here :-)

Quoted 7 lines

Yes, page_pool_alloc_netmem() gets the explicit check. Thanks!

For the frag API I'd keep a WARN_ON_ONCE, like the size check right below it. A silent 0 looks like an empty provider: the queue just stalls, and nothing points at the driver. With the helper fixed, only an explicit frag call on such a pool gets there... Wdyt? I'll probably take that route for v2.

I guess, yeah, makes sense, let's return full size and warn. Maybe also a short comment will help to explain why?

#16 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

Quoted 38 lines · Stanislav Fomichev
Quoted 37 lines · Björn Töpel
Quoted 26 lines · Stanislav Fomichev
Quoted 18 lines · Björn Töpel
Quoted 10 lines · Stanislav Fomichev

net/core/page_pool.c netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool, · line 1102

Quoted 6 lines · Björn Töpel
net/core/page_pool.c +3 -0
+	if (static_branch_unlikely(&page_pool_mem_providers) &&
+	    WARN_ON_ONCE(!page_pool_supports_frag(pool)))
+		return 0;
 	if (WARN_ON(size > max_size))
 		return 0;

What's the deal with that? How do we get here?

Hey! Thanks for taking a look at the series!

An explicit frag call on a whole-buffer provider is a driver bug: UMEM chunks can be smaller than a page, and RX gives the whole chunk to userspace.

Quoted 6 lines

But page_pool_alloc_netmem() also picks frags for small requests, so a valid call can warn.

I think it would be better to make it return a whole buffer and its actual size. The WARN stays in the frag API, before taking a new buffer? Wdyt?

Quoted 6 lines

I see.. Idk, I'd still return 0 here, but without a warn. Not sure we want a warn for any api misuse? Returning no netmem is gonna be enough to debug things? As for the calls from page_pool_alloc_netmem, I'd also handle it explicitly? if (size > max_size || !page_pool_supports_frag) ? But no strong preference, up to you, was mostly trying to understand what we are warning against here :-)

Yes, page_pool_alloc_netmem() gets the explicit check. Thanks!

Quoted 8 lines
Quoted 5 lines

For the frag API I'd keep a WARN_ON_ONCE, like the size check right below it. A silent 0 looks like an empty provider: the queue just stalls, and nothing points at the driver. With the helper fixed, only an explicit frag call on such a pool gets there... Wdyt? I'll probably take that route for v2.

I guess, yeah, makes sense, let's return full size and warn. Maybe also a short comment will help to explain why?

Will do, with a comment!

Björn

#17 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [Critical] xsk: dangling driver pool pointer…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [Critical] xsk: dangling driver pool pointer in xp_assign_dev() [1] --

commit c73a20cf1440e29e283d9ab9dca3cd14c95d4e33
Author: Björn Töpel <[email protected]>

net: Add memory provider capabilities

This commit adds MP_CAP_READABLE and MP_CAP_FRAG capability flags to describe memory providers and introduces PP_FLAG_MEM_PROVIDER so page pools can explicitly opt into using readable memory providers.

Quoted 4 lines
net/xdp/xsk_buff_pool.c +0 -0
index 7750d2ec4ee24..18966bbdb5b73 100644

[ ... ]

net/xdp/xsk_buff_pool.c int xp_assign_dev(struct xsk_buff_pool *pool, · line 248

Quoted 9 lines
net/xdp/xsk_buff_pool.c +1 -1
@@ -241,7 +242,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 		goto err_unreg_pool;
 	}
 
-	if (dev_get_min_mp_channel_count(netdev)) {
+	if (!netif_all_mps_have_cap(netdev, MP_CAP_READABLE)) {
 		err = -EBUSY;
 		goto err_unreg_pool;
 	}

[Severity: Critical]
This problem wasn't introduced by this patch, but can the err_unreg_xsk cleanup path in xp_assign_dev() leave a dangling pool pointer in the driver [1]?

Just below this hunk, if ndo_bpf() succeeds for XDP_SETUP_XSK_POOL but leaves pool->dma_pages NULL, xp_assign_dev() jumps to err_unreg_xsk to call xp_disable_drv_zc(pool) before pool->umem->zc is set:

net/xdp/xsk_buff_pool.c:xp_assign_dev() {
	...
	err = netdev->netdev_ops->ndo_bpf(netdev, &bpf);
	if (err)
		goto err_unreg_pool;

	if (!pool->dma_pages) {
		WARN(1, "Driver did not DMA map zero-copy buffers");
		err = -EINVAL;
		goto err_unreg_xsk;
	}
	pool->umem->zc = true;
	...
err_unreg_xsk:
	xp_disable_drv_zc(pool);
}

Because xp_disable_drv_zc() only calls ndo_bpf() with a NULL pool when pool->umem->zc is true, it returns without unregistering the pool from the driver, which can lead to a use-after-free when the pool is freed.

[1] https://sashiko.dev/#/bug/linux-ebfe949d-701b-490d-90a5-2d87285eb1c1

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#18 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] Documentation/networking/netmem.rst, 'Driver RX Requirements', disagrees with the readable-provider semantics this patch adds.

--

net: Add memory provider capabilities

This adds MP_CAP_READABLE and MP_CAP_FRAG memory provider capabilities. The header split and XDP restrictions now apply only to unreadable providers. A new PP_FLAG_MEM_PROVIDER flag lets a page pool take a readable provider from its RX queue. devmem and io_uring are marked MP_CAP_FRAG and keep their current behavior.

Documentation/networking/netmem.rst Driver RX Requirements · line 110

Quoted 13 lines
Documentation/networking/netmem.rst +5 -0
index 6871dcdd700cc..39cb75339704d 100644
@@ -103,6 +103,11 @@ Driver RX Requirements
      which knows when dma-syncing is (or is not) appropriate.
    - PP_FLAG_ALLOW_UNREADABLE_NETMEM. The driver must specify this flag iff
      tcp-data-split is enabled.
+   - PP_FLAG_MEM_PROVIDER. The page pool takes memory from the memory
+     provider of its RX queue, readable or not. Page pool creation fails if
+     the provider is unreadable and PP_FLAG_ALLOW_UNREADABLE_NETMEM is not
+     set, so do not set it on header page pools of such a queue. Without it,
+     PP_FLAG_ALLOW_UNREADABLE_NETMEM selects unreadable providers only.

[Severity: Low]
This isn't a bug, but does this entry belong under item 4's heading, "The driver must use the following PP_FLAGS:"?

PP_FLAG_MEM_PROVIDER is opt-in. The comment in include/net/page_pool/types.h says "Take memory from the memory provider of the RX queue, if one is installed".

devmem and io_uring pools still get their unreadable provider with only PP_FLAG_ALLOW_UNREADABLE_NETMEM set, because page_pool_select_mp() assigns unreadable providers without the new flag. The entry itself also says not to set the flag on header page pools of a queue with an unreadable provider.

Item 2 above is still an unconditional requirement:

2. The driver must support the tcp-data-split ethtool option.

However, __netif_mp_open_rxq() now checks hds_config and hds_thresh only when the provider lacks MP_CAP_READABLE:

    if (unreadable &&
        dev->cfg->hds_config != ETHTOOL_TCP_DATA_SPLIT_ENABLED) {

The MP_CAP_READABLE kernel-doc also says such a provider "may back header page pools".

Could items 2 and 4 be reworded to cover the readable provider case? As far as I can tell, this text is still unchanged at the end of the series. That leaves af_xdp.rst as the only place that describes the readable-provider driver contract.

Quoted 3 lines
Documentation/networking/netmem.rst +0 -0
 5. The driver must not assume the netmem is readable and/or backed by pages.
    The netmem returned by the page_pool may be unreadable, in which case

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261110102039.1002605-1-bjorn%40kernel.org
#19 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

In reply to Björn Töpel
Quoted 9 lines · Björn Töpel

The core treats every memory provider as unreadable: installing one needs header split and no XDP program, and any page pool that allows unreadable netmem takes it. An AF_XDP UMEM provider is readable, needs XDP, and hands out whole buffers.

Describe providers by MP_CAP_READABLE and MP_CAP_FRAG; devmem and io_uring keep their behavior with MP_CAP_FRAG. A page pool takes a readable provider only with the new PP_FLAG_MEM_PROVIDER:

Why do we need this? I thought whatever creates the pool actually shouldn't get to pick whether the pool picks up the memory provider. I thought if core has configured the rxq for a memory provider then the pool is forced to take it.

#20 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

Quoted 7 lines · Mina Almasry
Quoted 6 lines · Björn Töpel

The core treats every memory provider as unreadable: installing one needs header split and no XDP program, and any page pool that allows unreadable netmem takes it. An AF_XDP UMEM provider is readable, needs XDP, and hands out whole buffers.

Quoted 8 lines
Quoted 3 lines

Describe providers by MP_CAP_READABLE and MP_CAP_FRAG; devmem and io_uring keep their behavior with MP_CAP_FRAG. A page pool takes a readable provider only with the new PP_FLAG_MEM_PROVIDER:

Why do we need this? I thought whatever creates the pool actually shouldn't get to pick whether the pool picks up the memory provider. I thought if core has configured the rxq for a memory provider then the pool is forced to take it.

Thanks for looking at series, Mina. ...this needed some thinking.

It isn't forced today either: only pools with PP_FLAG_ALLOW_UNREADABLE_NETMEM take the queue's provider. Drivers set it on the pool that holds payloads, and keep headers in host memory: in a separate pool (fbnic, bnxt), or outside the page pool (gve, mlx5). That works because every provider so far backs payloads only.

UMEM doesn't. The socket gets whole packets, so UMEM has to back the header buffers, and with multi-buffer the payloads too. The flag was my way to get it there, but you're right that it's the wrong knob: it lets the driver opt in, where it should only say what each pool holds.

How about this instead. Both sides use the rx_roles bits from patch 5, HEAD and PAYLOAD:

- The provider says which buffers it backs, next to rx_page_size in
pp_memory_provider_params: devmem and io_uring zcrx PAYLOAD, AF_XDP HEAD, or HEAD|PAYLOAD with multi-buffer.
- The driver says what each pool holds, in rx_roles. A pool without roles but with PP_FLAG_ALLOW_UNREADABLE_NETMEM holds PAYLOAD, so existing drivers don't change.
- page_pool_create() gives the provider to a pool whose roles are all backed; the others get host pages. No opt-in.
- After ndo_queue_mem_alloc(), the core checks that the new pools that took the provider cover everything it backs, or fails the restart.

With fbnic's header and payload pools:

  devmem:                header pool host, payload pool devmem
  AF_XDP single-buffer:  header pool UMEM, payload pool host
  AF_XDP multi-buffer:   one shared pool, UMEM

A shared pool on a devmem queue doesn't take devmem, since devmem doesn't back HEAD, so the check fails and the driver has to split. That's the "headers in host memory" rule, without the driver asking which provider it is.

Wdyt?

Björn

#21 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

Quoted 52 lines · Björn Töpel
Quoted 7 lines · Mina Almasry
Quoted 6 lines · Björn Töpel

The core treats every memory provider as unreadable: installing one needs header split and no XDP program, and any page pool that allows unreadable netmem takes it. An AF_XDP UMEM provider is readable, needs XDP, and hands out whole buffers.

Quoted 8 lines
Quoted 3 lines

Describe providers by MP_CAP_READABLE and MP_CAP_FRAG; devmem and io_uring keep their behavior with MP_CAP_FRAG. A page pool takes a readable provider only with the new PP_FLAG_MEM_PROVIDER:

Why do we need this? I thought whatever creates the pool actually shouldn't get to pick whether the pool picks up the memory provider. I thought if core has configured the rxq for a memory provider then the pool is forced to take it.

Thanks for looking at series, Mina. ...this needed some thinking.

It isn't forced today either: only pools with PP_FLAG_ALLOW_UNREADABLE_NETMEM take the queue's provider. Drivers set it on the pool that holds payloads, and keep headers in host memory: in a separate pool (fbnic, bnxt), or outside the page pool (gve, mlx5). That works because every provider so far backs payloads only.

UMEM doesn't. The socket gets whole packets, so UMEM has to back the header buffers, and with multi-buffer the payloads too. The flag was my way to get it there, but you're right that it's the wrong knob: it lets the driver opt in, where it should only say what each pool holds.

How about this instead. Both sides use the rx_roles bits from patch 5, HEAD and PAYLOAD:

- The provider says which buffers it backs, next to rx_page_size in
pp_memory_provider_params: devmem and io_uring zcrx PAYLOAD, AF_XDP HEAD, or HEAD|PAYLOAD with multi-buffer.
- The driver says what each pool holds, in rx_roles. A pool without roles but with PP_FLAG_ALLOW_UNREADABLE_NETMEM holds PAYLOAD, so existing drivers don't change.
- page_pool_create() gives the provider to a pool whose roles are all backed; the others get host pages. No opt-in.
- After ndo_queue_mem_alloc(), the core checks that the new pools that took the provider cover everything it backs, or fails the restart.

With fbnic's header and payload pools:

  devmem:                header pool host, payload pool devmem
  AF_XDP single-buffer:  header pool UMEM, payload pool host
  AF_XDP multi-buffer:   one shared pool, UMEM
Quoted 7 lines

A shared pool on a devmem queue doesn't take devmem, since devmem doesn't back HEAD, so the check fails and the driver has to split. That's the "headers in host memory" rule, without the driver asking which provider it is.

Wdyt?

Hmm, I think maybe the exsiting knobs PP_FLAG_ALLOW_UNREADABLE + CAP_READABLE covers your needs.

The pp says whether the memory it provides is readable or not via CAP_READABLE (or !CAP_UNREADABLE).

The driver says whether it will allow unreadable memory for this pool. For header pools, it doesn't specfiy PP_FLAG_ALLOW_UNREADABLE and for paylaod pools it specifies ALLOW_UNREADABLE.

The change I think you need to make is: today we disallow any providers if the caller did not specify ALLOW_UNREADABLE (because we assume mp's are unreadable). After your series we only need to disallow memory providers if the mp is unreadable and the caller said it's not fine with unreadable.

Signature · 2 lines
Thanks,
Mina
#22 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

Quoted 71 lines · Mina Almasry
Quoted 52 lines · Björn Töpel
Quoted 7 lines · Mina Almasry
Quoted 6 lines · Björn Töpel

The core treats every memory provider as unreadable: installing one needs header split and no XDP program, and any page pool that allows unreadable netmem takes it. An AF_XDP UMEM provider is readable, needs XDP, and hands out whole buffers.

Quoted 8 lines
Quoted 3 lines

Describe providers by MP_CAP_READABLE and MP_CAP_FRAG; devmem and io_uring keep their behavior with MP_CAP_FRAG. A page pool takes a readable provider only with the new PP_FLAG_MEM_PROVIDER:

Why do we need this? I thought whatever creates the pool actually shouldn't get to pick whether the pool picks up the memory provider. I thought if core has configured the rxq for a memory provider then the pool is forced to take it.

Thanks for looking at series, Mina. ...this needed some thinking.

It isn't forced today either: only pools with PP_FLAG_ALLOW_UNREADABLE_NETMEM take the queue's provider. Drivers set it on the pool that holds payloads, and keep headers in host memory: in a separate pool (fbnic, bnxt), or outside the page pool (gve, mlx5). That works because every provider so far backs payloads only.

UMEM doesn't. The socket gets whole packets, so UMEM has to back the header buffers, and with multi-buffer the payloads too. The flag was my way to get it there, but you're right that it's the wrong knob: it lets the driver opt in, where it should only say what each pool holds.

How about this instead. Both sides use the rx_roles bits from patch 5, HEAD and PAYLOAD:

- The provider says which buffers it backs, next to rx_page_size in
pp_memory_provider_params: devmem and io_uring zcrx PAYLOAD, AF_XDP HEAD, or HEAD|PAYLOAD with multi-buffer.
- The driver says what each pool holds, in rx_roles. A pool without roles but with PP_FLAG_ALLOW_UNREADABLE_NETMEM holds PAYLOAD, so existing drivers don't change.
- page_pool_create() gives the provider to a pool whose roles are all backed; the others get host pages. No opt-in.
- After ndo_queue_mem_alloc(), the core checks that the new pools that took the provider cover everything it backs, or fails the restart.

With fbnic's header and payload pools:

  devmem:                header pool host, payload pool devmem
  AF_XDP single-buffer:  header pool UMEM, payload pool host
  AF_XDP multi-buffer:   one shared pool, UMEM
Quoted 7 lines

A shared pool on a devmem queue doesn't take devmem, since devmem doesn't back HEAD, so the check fails and the driver has to split. That's the "headers in host memory" rule, without the driver asking which provider it is.

Wdyt?

Hmm, I think maybe the exsiting knobs PP_FLAG_ALLOW_UNREADABLE + CAP_READABLE covers your needs.

The pp says whether the memory it provides is readable or not via CAP_READABLE (or !CAP_UNREADABLE).

The driver says whether it will allow unreadable memory for this pool. For header pools, it doesn't specfiy PP_FLAG_ALLOW_UNREADABLE and for paylaod pools it specifies ALLOW_UNREADABLE.

Quoted 5 lines

The change I think you need to make is: today we disallow any providers if the caller did not specify ALLOW_UNREADABLE (because we assume mp's are unreadable). After your series we only need to disallow memory providers if the mp is unreadable and the caller said it's not fine with unreadable.

I'm all in on making v1 simpler -- I'll try this path! So, an unreadable provider still goes only to pools that set ALLOW_UNREADABLE. A readable provider goes to all RX pools of the queue. The roles and PP_FLAG_MEM_PROVIDER are gone.

One addition: a driver must opt in with a readable_mp flag in its queue ops. Without it, its pools don't look for a provider. The reason is that today only ALLOW_UNREADABLE pools must set queue_idx and be created under the instance lock. Other pools may not, so they could pick up the wrong queue's provider. Maybe there's a better way?

Thanks!

Björn

maintainer
#23 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

In reply to Björn Töpel

include/net/page_pool/memory_provider.h struct sk_buff; · line 26

Quoted 13 lines · On Tue, 10 Nov 2026 11:20:23 +0100 Björn Töpel wrote:
include/net/page_pool/memory_provider.h +5 -0
index bceb5f7740e2..4417e54a0f81 100644
@@ -19,6 +19,18 @@ 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_caps - memory provider capabilities
+ * @MP_CAP_READABLE: The CPU can access provider memory. It may back header
+ *	page pools, and XDP programs may run on it.

Being readable is the normal state for memory. We should be marking mps as unreadable, not as readable?

include/net/page_pool/memory_provider.h netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool, · line 1100

Quoted 7 lines
include/net/page_pool/memory_provider.h +3 -0
@@ -1070,6 +1095,9 @@ netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool,
 	unsigned int max_size = PAGE_SIZE << pool->p.order;
 	netmem_ref netmem = pool->frag_page;
 
+	if (static_branch_unlikely(&page_pool_mem_providers) &&
+	    WARN_ON_ONCE(!page_pool_supports_frag(pool)))
+		return 0;

Shouldn't we return a full page if we can't frag? Fragmentation breaks up a page into smaller units, it should be legal to simply return a full page if fragmentation is not supported for the provider.

Quoted 2 lines
include/net/page_pool/memory_provider.h +0 -0
 	if (WARN_ON(size > max_size))
 		return 0;
#24 lore raw

Re: [PATCH net-next v1 02/11] net: Add memory provider capabilities

Quoted 17 lines · Jakub Kicinski

include/net/page_pool/memory_provider.h struct sk_buff; · line 26

Quoted 13 lines · On Tue, 10 Nov 2026 11:20:23 +0100 Björn Töpel wrote:
include/net/page_pool/memory_provider.h +5 -0
index bceb5f7740e2..4417e54a0f81 100644
@@ -19,6 +19,18 @@ 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_caps - memory provider capabilities
+ * @MP_CAP_READABLE: The CPU can access provider memory. It may back header
+ *	page pools, and XDP programs may run on it.

Being readable is the normal state for memory. We should be marking mps as unreadable, not as readable?

Fair, I'll flip it. devmem and io_uring zcrx mark themselves unreadable. The same goes for the other two caps; page memory can be split and kept, so AF_XDP marks that its buffers can't be.

Quoted 4 lines
Quoted 4 lines
include/net/page_pool/memory_provider.h +0 -0
@@ -1070,6 +1095,9 @@ netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool,
 	unsigned int max_size = PAGE_SIZE << pool->p.order;
 	netmem_ref netmem = pool->frag_page;
 
Quoted 8 lines

include/net/page_pool/memory_provider.h netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool, · line 1100

Quoted 3 lines
include/net/page_pool/memory_provider.h +3 -0
+	if (static_branch_unlikely(&page_pool_mem_providers) &&
+	    WARN_ON_ONCE(!page_pool_supports_frag(pool)))
+		return 0;

Shouldn't we return a full page if we can't frag? Fragmentation breaks up a page into smaller units, it should be legal to simply return a full page if fragmentation is not supported for the provider.

Yeah, make sense. I'll return the whole buffer at offset 0, instead of the WARN Stan and I settled on, and page_pool_alloc_netmem() reports the chunk size for callers that need it for truesize.

Björn

#25 lore raw

PATCH 3/11 xdp: Copy buffers with restricted lifetime

In reply to Björn Töpel

UMEM stays mapped writable in userspace, and it has a fixed number of chunks. The stack must not keep its chunks in an skb or an xdp_frame. Mark the providers whose buffers the stack may keep with MP_CAP_RETAIN, and copy packets of the others on XDP_PASS, on conversion to a frame, and on redirects other than XSKMAP.

The head chunk is writable by userspace, so it cannot hold skb_shared_info, and virt_to_netmem() cannot find a net_iov head. Drivers pass kernel memory for both to xdp_init_buff_netmem().

A static key keeps the check off while no such page pool exists. A frame copy is linear, so a multi-buffer packet of such a provider cannot go to a device or CPU map.

---
 include/linux/skbuff.h                  |  1 +
 include/net/netmem.h                    | 10 +++
 include/net/page_pool/memory_provider.h |  3 +
 include/net/xdp.h                       | 92 +++++++++++++++++++++++--
 io_uring/zcrx.c                         |  2 +-
 net/core/dev.h                          |  4 ++
 net/core/devmem.c                       |  2 +-
 net/core/filter.c                       | 20 +++++-
 net/core/page_pool.c                    | 30 ++++++++
 net/core/xdp.c                          | 78 +++++++++++++++++----
 10 files changed, 221 insertions(+), 21 deletions(-)
include/linux/skbuff.h +1 -0
index 8b0039d49905..a9cc5dd0211a 100644
@@ -2691,6 +2691,7 @@ static inline void skb_add_rx_frag_netmem(struct sk_buff *skb, int i,
 					  int size, unsigned int truesize)
 {
 	DEBUG_NET_WARN_ON_ONCE(size > truesize);
+	DEBUG_NET_WARN_ON_ONCE(!netmem_can_retain(netmem));
 
 	skb_fill_netmem_desc(skb, i, netmem, off, size);
 	skb->len += size;
include/net/netmem.h +10 -0
index f196b014184c..b986ad616334 100644
@@ -59,6 +59,7 @@ static_assert(sizeof(struct netmem_desc) <= offsetof(struct page, _refcount));
 /* net_iov */
 
 DECLARE_STATIC_KEY_FALSE(page_pool_mem_providers);
+DECLARE_STATIC_KEY_FALSE(page_pool_restricted);
 
 /*  We overload the LSB of the struct page pointer to indicate whether it's
  *  a page or net_iov.
@@ -414,6 +415,15 @@ static inline bool net_is_devmem_iov(const struct net_iov *niov)
 void net_iov_inc_ref(struct net_iov *niov);
 void net_iov_dec_ref(struct net_iov *niov);
 
+#if IS_ENABLED(CONFIG_PAGE_POOL)
+bool netmem_can_retain(netmem_ref netmem);
+#else
+static inline bool netmem_can_retain(netmem_ref netmem)
+{
+	return true;
+}
+#endif
+
 /**
  * netmem_inc_ref - acquire a non-page_pool reference on a netmem
  * @netmem: netmem to reference
include/net/page_pool/memory_provider.h +3 -0
index 4417e54a0f81..e732b21be9a2 100644
@@ -25,10 +25,13 @@ struct sk_buff;
  * @MP_CAP_READABLE: The CPU can access provider memory. It may back header
  *	page pools, and XDP programs may run on it.
  * @MP_CAP_FRAG: Page pool fragments may split provider buffers.
+ * @MP_CAP_RETAIN: The stack may keep page pool references to provider
+ *	buffers after the RX poll, for example in an skb or an xdp_frame.
  */
 enum mp_caps {
 	MP_CAP_READABLE		= BIT(0),
 	MP_CAP_FRAG		= BIT(1),
+	MP_CAP_RETAIN		= BIT(2),
 };
 
 struct memory_provider_ops {
include/net/xdp.h +87 -5

148 lines not on this page · raw message

io_uring/zcrx.c +1 -1
index 3b5bf97aa203..98d83a8e45e4 100644
@@ -1478,7 +1478,7 @@ static const struct memory_provider_ops io_uring_pp_zc_ops = {
 	.destroy		= io_pp_zc_destroy,
 	.nl_fill		= io_pp_nl_fill,
 	.uninstall		= io_pp_uninstall,
-	.caps			= MP_CAP_FRAG,
+	.caps			= MP_CAP_FRAG | MP_CAP_RETAIN,
 };
 
 static unsigned zcrx_parse_rq(netmem_ref *netmem_array, unsigned nr,
net/core/dev.h +4 -0
index 4e9e8cd15697..e3337013ffc8 100644
@@ -13,6 +13,10 @@ struct netlink_ext_ack;
 struct netdev_queue_config;
 struct cpumask;
 struct pp_memory_provider_params;
+struct xdp_buff;
+struct xdp_frame;
+
+struct xdp_frame *xdp_copy_buff_to_frame(const struct xdp_buff *xdp);
 
 /* Random bits of netdevice that don't need to be exposed */
 #define FLOW_LIMIT_HISTORY	(1 << 7)  /* must be ^2 and !overflow buckets */
net/core/devmem.c +1 -1
index 8f190b574beb..dea4a4a17e86 100644
@@ -698,5 +698,5 @@ static const struct memory_provider_ops dmabuf_devmem_ops = {
 	.release_netmem		= mp_dmabuf_devmem_release_page,
 	.nl_fill		= mp_dmabuf_devmem_nl_fill,
 	.uninstall		= mp_dmabuf_devmem_uninstall,
-	.caps			= MP_CAP_FRAG,
+	.caps			= MP_CAP_FRAG | MP_CAP_RETAIN,
 };
net/core/filter.c +18 -2
index 80380f89adf9..f93839b493b2 100644
@@ -4774,12 +4774,28 @@ int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
 {
 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
 	enum bpf_map_type map_type = ri->map_type;
+	struct xdp_frame *xdpf;
+	int err;
 
 	if (map_type == BPF_MAP_TYPE_XSKMAP)
 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
 
-	return __xdp_do_redirect_frame(ri, dev, xdp_convert_buff_to_frame(xdp),
-				       xdp_prog);
+	if (likely(!xdp_buff_needs_copy(xdp)))
+		return __xdp_do_redirect_frame(ri, dev,
+					       xdp_convert_buff_to_frame(xdp),
+					       xdp_prog);
+
+	/* Release the source only after the target took the copy. */
+	xdpf = xdp_copy_buff_to_frame(xdp);
+	err = __xdp_do_redirect_frame(ri, dev, xdpf, xdp_prog);
+	if (unlikely(err)) {
+		if (xdpf)
+			xdp_return_frame(xdpf);
+		return err;
+	}
+
+	xdp_return_buff(xdp);
+	return 0;
 }
 EXPORT_SYMBOL_GPL(xdp_do_redirect);
 
net/core/page_pool.c +30 -0
index d88a3ea528d4..8237fda598ab 100644
@@ -34,6 +34,10 @@
 
 DEFINE_STATIC_KEY_FALSE(page_pool_mem_providers);
 
+/* Enabled while a pool of a provider without MP_CAP_RETAIN exists. */
+DEFINE_STATIC_KEY_FALSE(page_pool_restricted);
+EXPORT_SYMBOL(page_pool_restricted);
+
 #define DEFER_TIME (msecs_to_jiffies(1000))
 #define DEFER_WARN_INTERVAL (60 * HZ)
 
@@ -188,6 +192,28 @@ static void page_pool_struct_check(void)
 				    PAGE_POOL_FRAG_GROUP_ALIGN);
 }
 
+/**
+ * netmem_can_retain() - may the stack keep @netmem after the RX poll
+ * @netmem: netmem to check
+ *
+ * Context: the caller holds @netmem through its page pool. A plain page
+ * reference does not keep the page in its pool.
+ * Return: false if @netmem belongs to a memory provider without
+ * MP_CAP_RETAIN.
+ */
+bool netmem_can_retain(netmem_ref netmem)
+{
+	const struct memory_provider_ops *ops;
+
+	netmem = netmem_compound_head(netmem);
+	if (!netmem_is_pp(netmem))
+		return true;
+
+	ops = netmem_get_pp(netmem)->mp_ops;
+	return !ops || ops->caps & MP_CAP_RETAIN;
+}
+EXPORT_SYMBOL(netmem_can_retain);
+
 static int page_pool_select_mp(struct page_pool *pool,
 			       const struct pp_memory_provider_params *mpp)
 {
@@ -324,6 +350,8 @@ static int page_pool_init(struct page_pool *pool,
 		}
 
 		static_branch_inc(&page_pool_mem_providers);
+		if (!(pool->mp_ops->caps & MP_CAP_RETAIN))
+			static_branch_inc(&page_pool_restricted);
 	} else if (pool->p.order > MAX_PAGE_ORDER) {
 		err = -EINVAL;
 		goto free_ptr_ring;
@@ -352,6 +380,8 @@ static void page_pool_uninit(struct page_pool *pool)
 #endif
 
 	if (pool->mp_ops) {
+		if (!(pool->mp_ops->caps & MP_CAP_RETAIN))
+			static_branch_dec(&page_pool_restricted);
 		pool->mp_ops->destroy(pool);
 		static_branch_dec(&page_pool_mem_providers);
 	}
net/core/xdp.c +66 -12

151 lines not on this page · raw message

Signature · 1 line
2.56.0
#26 lore raw

Re: [PATCH net-next v1 03/11] xdp: Copy buffers with restricted lifetime

Quoted 93 lines · Björn Töpel

UMEM stays mapped writable in userspace, and it has a fixed number of chunks. The stack must not keep its chunks in an skb or an xdp_frame. Mark the providers whose buffers the stack may keep with MP_CAP_RETAIN, and copy packets of the others on XDP_PASS, on conversion to a frame, and on redirects other than XSKMAP.

The head chunk is writable by userspace, so it cannot hold skb_shared_info, and virt_to_netmem() cannot find a net_iov head. Drivers pass kernel memory for both to xdp_init_buff_netmem().

A static key keeps the check off while no such page pool exists. A frame copy is linear, so a multi-buffer packet of such a provider cannot go to a device or CPU map.

---
 include/linux/skbuff.h                  |  1 +
 include/net/netmem.h                    | 10 +++
 include/net/page_pool/memory_provider.h |  3 +
 include/net/xdp.h                       | 92 +++++++++++++++++++++++--
 io_uring/zcrx.c                         |  2 +-
 net/core/dev.h                          |  4 ++
 net/core/devmem.c                       |  2 +-
 net/core/filter.c                       | 20 +++++-
 net/core/page_pool.c                    | 30 ++++++++
 net/core/xdp.c                          | 78 +++++++++++++++++----
 10 files changed, 221 insertions(+), 21 deletions(-)
include/linux/skbuff.h +1 -0
index 8b0039d49905..a9cc5dd0211a 100644
@@ -2691,6 +2691,7 @@ static inline void skb_add_rx_frag_netmem(struct sk_buff *skb, int i,
 					  int size, unsigned int truesize)
 {
 	DEBUG_NET_WARN_ON_ONCE(size > truesize);
+	DEBUG_NET_WARN_ON_ONCE(!netmem_can_retain(netmem));
 
 	skb_fill_netmem_desc(skb, i, netmem, off, size);
 	skb->len += size;
include/net/netmem.h +10 -0
index f196b014184c..b986ad616334 100644
@@ -59,6 +59,7 @@ static_assert(sizeof(struct netmem_desc) <= offsetof(struct page, _refcount));
 /* net_iov */
 
 DECLARE_STATIC_KEY_FALSE(page_pool_mem_providers);
+DECLARE_STATIC_KEY_FALSE(page_pool_restricted);
 
 /*  We overload the LSB of the struct page pointer to indicate whether it's
  *  a page or net_iov.
@@ -414,6 +415,15 @@ static inline bool net_is_devmem_iov(const struct net_iov *niov)
 void net_iov_inc_ref(struct net_iov *niov);
 void net_iov_dec_ref(struct net_iov *niov);
 
+#if IS_ENABLED(CONFIG_PAGE_POOL)
+bool netmem_can_retain(netmem_ref netmem);
+#else
+static inline bool netmem_can_retain(netmem_ref netmem)
+{
+	return true;
+}
+#endif
+
 /**
  * netmem_inc_ref - acquire a non-page_pool reference on a netmem
  * @netmem: netmem to reference
include/net/page_pool/memory_provider.h +3 -0
index 4417e54a0f81..e732b21be9a2 100644
@@ -25,10 +25,13 @@ struct sk_buff;
  * @MP_CAP_READABLE: The CPU can access provider memory. It may back header
  *	page pools, and XDP programs may run on it.
  * @MP_CAP_FRAG: Page pool fragments may split provider buffers.
+ * @MP_CAP_RETAIN: The stack may keep page pool references to provider
+ *	buffers after the RX poll, for example in an skb or an xdp_frame.
  */
 enum mp_caps {
 	MP_CAP_READABLE		= BIT(0),
 	MP_CAP_FRAG		= BIT(1),
+	MP_CAP_RETAIN		= BIT(2),
 };
 
 struct memory_provider_ops {
include/net/xdp.h +0 -0
index 07231adfb5f8..1105bb9e3292 100644
@@ -81,6 +81,16 @@ enum xdp_buff_flags {
 	 * XDP program is not attached.
 	 */

include/net/xdp.h enum xdp_buff_flags { · line 92

Quoted 10 lines
include/net/xdp.h +9 -0
 	XDP_FLAGS_FRAGS_UNREADABLE	= BIT(2),
+	/* Internal: the head netmem and the shared info are in &xdp_buff.ext.
+	 * Not copied to xdp_frames or skbs.
+	 */
+	XDP_FLAGS_EXT			= BIT(3),
+};
+
+/* For a head buffer that cannot hold kernel data, see xdp_init_buff_netmem() */
+struct xdp_buff_ext {
+	netmem_ref netmem;

nit: netmem -> head ? and the same for xdp_init_buff_netmem netmem arg?

Quoted 19 lines
include/net/xdp.h +7 -1
+	struct skb_shared_info sinfo;
 };
 
 struct xdp_buff {
@@ -89,7 +99,12 @@ struct xdp_buff {
 	void *data_meta;
 	void *data_hard_start;
 	struct xdp_rxq_info *rxq;
-	struct xdp_txq_info *txq;
+	union {
+		/* DEVMAP egress programs only */
+		struct xdp_txq_info *txq;
+		/* RX buffers with XDP_FLAGS_EXT */
+		struct xdp_buff_ext *ext;
+	};
 
 	union {
 		struct {

include/net/xdp.h static __always_inline void xdp_buff_set_frag_unreadable(struct xdp_buff *xdp) · line 156

Quoted 5 lines
include/net/xdp.h +1 -1
@@ -138,7 +153,7 @@ static __always_inline void xdp_buff_set_frag_unreadable(struct xdp_buff *xdp)
 
 static __always_inline u32 xdp_buff_get_skb_flags(const struct xdp_buff *xdp)
 {
-	return xdp->flags;
+	return xdp->flags & ~XDP_FLAGS_EXT;

The only consumer is xdp_update_skb_frags_info, so probably not worth filtering out XDP_FLAGS_EXT here? Or is it for xdp_update_frame_from_buff? Can we explicitly clear it at the caller?

Quoted 153 lines
include/net/xdp.h +70 -3
 }
 
 static __always_inline void xdp_buff_clear_frag_pfmemalloc(struct xdp_buff *xdp)
@@ -176,6 +191,50 @@ xdp_prepare_buff(struct xdp_buff *xdp, unsigned char *hard_start,
 	xdp->data_meta = meta_valid ? data : data + 1;
 }
 
+/* See MP_CAP_RETAIN */
+static __always_inline bool xdp_netmem_restricted(netmem_ref netmem)
+{
+	return IS_ENABLED(CONFIG_PAGE_POOL) &&
+	       static_branch_unlikely(&page_pool_restricted) &&
+	       !netmem_can_retain(netmem);
+}
+
+/**
+ * xdp_init_buff_netmem - initialize an &xdp_buff for a netmem head buffer
+ * @xdp: &xdp_buff to initialize
+ * @frame_sz: frame size
+ * @rxq: RX queue info
+ * @netmem: head buffer
+ * @ext: kernel memory used if @netmem cannot hold the shared info, or the
+ *	stack must not keep it. It must live as long as @xdp.
+ *
+ * A driver that may receive into memory provider buffers uses this instead
+ * of xdp_init_buff().
+ */
+static __always_inline void
+xdp_init_buff_netmem(struct xdp_buff *xdp, u32 frame_sz,
+		     struct xdp_rxq_info *rxq, netmem_ref netmem,
+		     struct xdp_buff_ext *ext)
+{
+	xdp_init_buff(xdp, frame_sz, rxq);
+	if (likely(!netmem_is_net_iov(netmem) &&
+		   !xdp_netmem_restricted(netmem)))
+		return;
+
+	ext->netmem = netmem;
+	xdp->ext = ext;
+	xdp->flags |= XDP_FLAGS_EXT;
+}
+
+static __always_inline netmem_ref
+xdp_buff_head_netmem(const struct xdp_buff *xdp)
+{
+	if (unlikely(xdp->flags & XDP_FLAGS_EXT))
+		return xdp->ext->netmem;
+
+	return virt_to_netmem(xdp->data);
+}
+
 /* Reserve memory area at end-of data area.
  *
  * This macro reserves tailroom in the XDP buffer by limiting the
@@ -189,9 +248,28 @@ xdp_prepare_buff(struct xdp_buff *xdp, unsigned char *hard_start,
 static inline struct skb_shared_info *
 xdp_get_shared_info_from_buff(const struct xdp_buff *xdp)
 {
+	if (unlikely(xdp->flags & XDP_FLAGS_EXT))
+		return &xdp->ext->sinfo;
+
 	return (struct skb_shared_info *)xdp_data_hard_end(xdp);
 }
 
+bool __xdp_buff_needs_copy(const struct xdp_buff *xdp);
+
+/* Must the stack copy a buffer of @xdp before it keeps it? XSK buffers are
+ * copied by their own conversion.
+ */
+static __always_inline bool xdp_buff_needs_copy(const struct xdp_buff *xdp)
+{
+	if (unlikely(xdp->flags & XDP_FLAGS_EXT))
+		return true;
+	if (!IS_ENABLED(CONFIG_PAGE_POOL) ||
+	    !static_branch_unlikely(&page_pool_restricted))
+		return false;
+
+	return __xdp_buff_needs_copy(xdp);
+}
+
 static __always_inline unsigned int
 xdp_get_buff_len(const struct xdp_buff *xdp)
 {
@@ -379,7 +457,7 @@ xdp_update_skb_frags_info(struct sk_buff *skb, u8 nr_frags,
 void xdp_warn(const char *msg, const char *func, const int line);
 #define XDP_WARN(msg) xdp_warn(msg, __func__, __LINE__)
 
-struct sk_buff *xdp_build_skb_from_buff(const struct xdp_buff *xdp);
+struct sk_buff *xdp_build_skb_from_buff(struct xdp_buff *xdp);
 struct sk_buff *xdp_build_skb_from_zc(struct xdp_buff *xdp);
 struct xdp_frame *xdp_convert_zc_to_xdp_frame(struct xdp_buff *xdp);
 struct sk_buff *__xdp_build_skb_from_frame(struct xdp_frame *xdpf,
@@ -420,12 +498,15 @@ int xdp_update_frame_from_buff(const struct xdp_buff *xdp,
 		return -ENOSPC;
 	}
 
+	/* The stack may keep the frame, see xdp_buff_needs_copy(). */
+	DEBUG_NET_WARN_ON_ONCE(xdp_buff_needs_copy(xdp));
+
 	xdp_frame->data = xdp->data;
 	xdp_frame->len  = xdp->data_end - xdp->data;
 	xdp_frame->headroom = headroom - sizeof(*xdp_frame);
 	xdp_frame->metasize = metasize;
 	xdp_frame->frame_sz = xdp->frame_sz;
-	xdp_frame->flags = xdp->flags;
+	xdp_frame->flags = xdp_buff_get_skb_flags(xdp);
 
 	return 0;
 }
@@ -436,7 +517,8 @@ struct xdp_frame *xdp_convert_buff_to_frame(struct xdp_buff *xdp)
 {
 	struct xdp_frame *xdp_frame;
 
-	if (xdp->rxq->mem.type == MEM_TYPE_XSK_BUFF_POOL)
+	if (xdp->rxq->mem.type == MEM_TYPE_XSK_BUFF_POOL ||
+	    xdp_buff_needs_copy(xdp))
 		return xdp_convert_zc_to_xdp_frame(xdp);
 
 	/* Store info in top of packet */
io_uring/zcrx.c +1 -1
index 3b5bf97aa203..98d83a8e45e4 100644
@@ -1478,7 +1478,7 @@ static const struct memory_provider_ops io_uring_pp_zc_ops = {
 	.destroy		= io_pp_zc_destroy,
 	.nl_fill		= io_pp_nl_fill,
 	.uninstall		= io_pp_uninstall,
-	.caps			= MP_CAP_FRAG,
+	.caps			= MP_CAP_FRAG | MP_CAP_RETAIN,
 
 };
 

static unsigned zcrx_parse_rq(netmem_ref *netmem_array, unsigned nr,

net/core/dev.h +4 -0
index 4e9e8cd15697..e3337013ffc8 100644
@@ -13,6 +13,10 @@ struct netlink_ext_ack;
 struct netdev_queue_config;
 struct cpumask;
 struct pp_memory_provider_params;
+struct xdp_buff;
+struct xdp_frame;
+
+struct xdp_frame *xdp_copy_buff_to_frame(const struct xdp_buff *xdp);
 
 /* Random bits of netdevice that don't need to be exposed */
 #define FLOW_LIMIT_HISTORY	(1 << 7)  /* must be ^2 and !overflow buckets */
net/core/devmem.c +0 -0
index 8f190b574beb..dea4a4a17e86 100644

net/core/devmem.c static const struct memory_provider_ops dmabuf_devmem_ops = { · line 701

Quoted 5 lines
net/core/devmem.c +1 -1
@@ -698,5 +698,5 @@ static const struct memory_provider_ops dmabuf_devmem_ops = {
 	.release_netmem		= mp_dmabuf_devmem_release_page,
 	.nl_fill		= mp_dmabuf_devmem_nl_fill,
 	.uninstall		= mp_dmabuf_devmem_uninstall,
-	.caps			= MP_CAP_FRAG,
+	.caps			= MP_CAP_FRAG | MP_CAP_RETAIN,

Not sure I understand this part, can you explain? These are MP_CAP_RETAIN because they are unreadable?

Quoted 127 lines
net/core/devmem.c +0 -0
 };
net/core/filter.c +18 -2
index 80380f89adf9..f93839b493b2 100644
@@ -4774,12 +4774,28 @@ int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
 {
 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
 	enum bpf_map_type map_type = ri->map_type;
+	struct xdp_frame *xdpf;
+	int err;
 
 	if (map_type == BPF_MAP_TYPE_XSKMAP)
 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
 
-	return __xdp_do_redirect_frame(ri, dev, xdp_convert_buff_to_frame(xdp),
-				       xdp_prog);
+	if (likely(!xdp_buff_needs_copy(xdp)))
+		return __xdp_do_redirect_frame(ri, dev,
+					       xdp_convert_buff_to_frame(xdp),
+					       xdp_prog);
+
+	/* Release the source only after the target took the copy. */
+	xdpf = xdp_copy_buff_to_frame(xdp);
+	err = __xdp_do_redirect_frame(ri, dev, xdpf, xdp_prog);
+	if (unlikely(err)) {
+		if (xdpf)
+			xdp_return_frame(xdpf);
+		return err;
+	}
+
+	xdp_return_buff(xdp);
+	return 0;
 }
 EXPORT_SYMBOL_GPL(xdp_do_redirect);
 
net/core/page_pool.c +30 -0
index d88a3ea528d4..8237fda598ab 100644
@@ -34,6 +34,10 @@
 
 DEFINE_STATIC_KEY_FALSE(page_pool_mem_providers);
 
+/* Enabled while a pool of a provider without MP_CAP_RETAIN exists. */
+DEFINE_STATIC_KEY_FALSE(page_pool_restricted);
+EXPORT_SYMBOL(page_pool_restricted);
+
 #define DEFER_TIME (msecs_to_jiffies(1000))
 #define DEFER_WARN_INTERVAL (60 * HZ)
 
@@ -188,6 +192,28 @@ static void page_pool_struct_check(void)
 				    PAGE_POOL_FRAG_GROUP_ALIGN);
 }
 
+/**
+ * netmem_can_retain() - may the stack keep @netmem after the RX poll
+ * @netmem: netmem to check
+ *
+ * Context: the caller holds @netmem through its page pool. A plain page
+ * reference does not keep the page in its pool.
+ * Return: false if @netmem belongs to a memory provider without
+ * MP_CAP_RETAIN.
+ */
+bool netmem_can_retain(netmem_ref netmem)
+{
+	const struct memory_provider_ops *ops;
+
+	netmem = netmem_compound_head(netmem);
+	if (!netmem_is_pp(netmem))
+		return true;
+
+	ops = netmem_get_pp(netmem)->mp_ops;
+	return !ops || ops->caps & MP_CAP_RETAIN;
+}
+EXPORT_SYMBOL(netmem_can_retain);
+
 static int page_pool_select_mp(struct page_pool *pool,
 			       const struct pp_memory_provider_params *mpp)
 {
@@ -324,6 +350,8 @@ static int page_pool_init(struct page_pool *pool,
 		}
 
 		static_branch_inc(&page_pool_mem_providers);
+		if (!(pool->mp_ops->caps & MP_CAP_RETAIN))
+			static_branch_inc(&page_pool_restricted);
 	} else if (pool->p.order > MAX_PAGE_ORDER) {
 		err = -EINVAL;
 		goto free_ptr_ring;
@@ -352,6 +380,8 @@ static void page_pool_uninit(struct page_pool *pool)
 #endif
 
 	if (pool->mp_ops) {
+		if (!(pool->mp_ops->caps & MP_CAP_RETAIN))
+			static_branch_dec(&page_pool_restricted);
 		pool->mp_ops->destroy(pool);
 		static_branch_dec(&page_pool_mem_providers);
 	}
net/core/xdp.c +10 -1
index 1d679e8fd649..0cf46d492d91 100644
@@ -23,6 +23,8 @@
 #include <trace/events/xdp.h>
 #include <net/xdp_sock_drv.h>
 
+#include "dev.h"
+
 #define REG_STATE_NEW		0x0
 #define REG_STATE_REGISTERED	0x1
 #define REG_STATE_UNREGISTERED	0x2
@@ -559,10 +561,41 @@ void xdp_return_buff(struct xdp_buff *xdp)
 			     xdp->rxq->mem.type, true, xdp);
 
 out:
-	__xdp_return(virt_to_netmem(xdp->data), xdp->rxq->mem.type, true, xdp);
+	__xdp_return(xdp_buff_head_netmem(xdp), xdp->rxq->mem.type, true, xdp);
 }
 EXPORT_SYMBOL_GPL(xdp_return_buff);
 
+bool __xdp_buff_needs_copy(const struct xdp_buff *xdp)
+{
+	const struct skb_shared_info *sinfo;
+	u32 i;
+
+	/* Provider buffers come only from page pool queues */
+	if (xdp->rxq->mem.type != MEM_TYPE_PAGE_POOL)

net/core/xdp.c void xdp_return_buff(struct xdp_buff *xdp) · line 584

Quoted 10 lines
net/core/xdp.c +10 -0
+		return false;
+	if (!netmem_can_retain(xdp_buff_head_netmem(xdp)))
+		return true;
+	if (likely(!xdp_buff_has_frags(xdp)))
+		return false;
+
+	sinfo = xdp_get_shared_info_from_buff(xdp);
+	for (i = 0; i < sinfo->nr_frags; i++) {
+		if (!netmem_can_retain(skb_frag_netmem(&sinfo->frags[i])))
+			return true;

Do we want/need to go that deep? Can we have a skb-like assumptions that mixing retain and non-retain in the same shinfo is not allowed?

#27 lore raw

Re: [PATCH net-next v1 03/11] xdp: Copy buffers with restricted lifetime

Quoted 13 lines · Stanislav Fomichev
Quoted 11 lines · Björn Töpel
include/net/xdp.h +3 -0
index 07231adfb5f8..1105bb9e3292 100644
@@ -81,6 +81,16 @@ enum xdp_buff_flags {
 	 * XDP program is not attached.
 	 */
 	XDP_FLAGS_FRAGS_UNREADABLE	= BIT(2),
+	/* Internal: the head netmem and the shared info are in &xdp_buff.ext.
+	 * Not copied to xdp_frames or skbs.
+	 */
Quoted 8 lines

include/net/xdp.h enum xdp_buff_flags { · line 92

Quoted 6 lines
include/net/xdp.h +6 -0
+	XDP_FLAGS_EXT			= BIT(3),
+};
+
+/* For a head buffer that cannot hold kernel data, see xdp_init_buff_netmem() */
+struct xdp_buff_ext {
+	netmem_ref netmem;

nit: netmem -> head ? and the same for xdp_init_buff_netmem netmem arg?

Yup, will fix.

Quoted 10 lines

include/net/xdp.h static __always_inline void xdp_buff_set_frag_unreadable(struct xdp_buff *xdp) · line 156

Quoted 6 lines
include/net/xdp.h +1 -1
@@ -138,7 +153,7 @@ static __always_inline void xdp_buff_set_frag_unreadable(struct xdp_buff *xdp)
 
 static __always_inline u32 xdp_buff_get_skb_flags(const struct xdp_buff *xdp)
 {
-	return xdp->flags;
+	return xdp->flags & ~XDP_FLAGS_EXT;

The only consumer is xdp_update_skb_frags_info, so probably not worth filtering out XDP_FLAGS_EXT here? Or is it for xdp_update_frame_from_buff? Can we explicitly clear it at the caller?

It was for xdp_update_frame_from_buff(), but looking closer EXT never gets there...

I'll drop the mask. Thanks!

Quoted 5 lines
Quoted 5 lines
net/core/devmem.c +0 -0
index 8f190b574beb..dea4a4a17e86 100644
@@ -698,5 +698,5 @@ static const struct memory_provider_ops dmabuf_devmem_ops = {
Quoted 8 lines

net/core/devmem.c static const struct memory_provider_ops dmabuf_devmem_ops = { · line 701

Quoted 5 lines
net/core/devmem.c +1 -1
 	.release_netmem		= mp_dmabuf_devmem_release_page,
 	.nl_fill		= mp_dmabuf_devmem_nl_fill,
 	.uninstall		= mp_dmabuf_devmem_uninstall,
-	.caps			= MP_CAP_FRAG,
+	.caps			= MP_CAP_FRAG | MP_CAP_RETAIN,

Not sure I understand this part, can you explain? These are MP_CAP_RETAIN because they are unreadable?

No, RETAIN is about lifetime: the stack may hold page pool references after the RX poll, e.g. skbs on a TCP receive queue. That's how devmem and zcrx work; without it the stack would try to copy them, and they'd trip the DEBUG_NET check in skb_add_rx_frag_netmem().

A provider without RETAIN gets copied, so it must be readable. I'll try to make that more clear in the kdoc, and probably refuse a provider that is neither.

Quoted 34 lines
Quoted 34 lines
net/core/xdp.c +15 -1
index 1d679e8fd649..0cf46d492d91 100644
@@ -23,6 +23,8 @@
 #include <trace/events/xdp.h>
 #include <net/xdp_sock_drv.h>
 
+#include "dev.h"
+
 #define REG_STATE_NEW		0x0
 #define REG_STATE_REGISTERED	0x1
 #define REG_STATE_UNREGISTERED	0x2
@@ -559,10 +561,41 @@ void xdp_return_buff(struct xdp_buff *xdp)
 			     xdp->rxq->mem.type, true, xdp);
 
 out:
-	__xdp_return(virt_to_netmem(xdp->data), xdp->rxq->mem.type, true, xdp);
+	__xdp_return(xdp_buff_head_netmem(xdp), xdp->rxq->mem.type, true, xdp);
 }
 EXPORT_SYMBOL_GPL(xdp_return_buff);
 
+bool __xdp_buff_needs_copy(const struct xdp_buff *xdp)
+{
+	const struct skb_shared_info *sinfo;
+	u32 i;
+
+	/* Provider buffers come only from page pool queues */
+	if (xdp->rxq->mem.type != MEM_TYPE_PAGE_POOL)
+		return false;
+	if (!netmem_can_retain(xdp_buff_head_netmem(xdp)))
+		return true;
+	if (likely(!xdp_buff_has_frags(xdp)))
+		return false;
Quoted 8 lines

net/core/xdp.c void xdp_return_buff(struct xdp_buff *xdp) · line 584

Quoted 5 lines
net/core/xdp.c +5 -0
+
+	sinfo = xdp_get_shared_info_from_buff(xdp);
+	for (i = 0; i < sinfo->nr_frags; i++) {
+		if (!netmem_can_retain(skb_frag_netmem(&sinfo->frags[i])))
+			return true;

Do we want/need to go that deep? Can we have a skb-like assumptions that mixing retain and non-retain in the same shinfo is not allowed?

Yep, let's make that the rule. I'll remove the deep checks.

Björn

#28 lore raw

Re: [PATCH net-next v1 03/11] xdp: Copy buffers with restricted lifetime

Quoted 56 lines · Björn Töpel
Quoted 13 lines · Stanislav Fomichev
Quoted 11 lines · Björn Töpel
include/net/xdp.h +3 -0
index 07231adfb5f8..1105bb9e3292 100644
@@ -81,6 +81,16 @@ enum xdp_buff_flags {
 	 * XDP program is not attached.
 	 */
 	XDP_FLAGS_FRAGS_UNREADABLE	= BIT(2),
+	/* Internal: the head netmem and the shared info are in &xdp_buff.ext.
+	 * Not copied to xdp_frames or skbs.
+	 */
Quoted 8 lines

include/net/xdp.h enum xdp_buff_flags { · line 92

Quoted 6 lines
include/net/xdp.h +6 -0
+	XDP_FLAGS_EXT			= BIT(3),
+};
+
+/* For a head buffer that cannot hold kernel data, see xdp_init_buff_netmem() */
+struct xdp_buff_ext {
+	netmem_ref netmem;

nit: netmem -> head ? and the same for xdp_init_buff_netmem netmem arg?

Yup, will fix.

Quoted 10 lines

include/net/xdp.h static __always_inline void xdp_buff_set_frag_unreadable(struct xdp_buff *xdp) · line 156

Quoted 6 lines
include/net/xdp.h +1 -1
@@ -138,7 +153,7 @@ static __always_inline void xdp_buff_set_frag_unreadable(struct xdp_buff *xdp)
 
 static __always_inline u32 xdp_buff_get_skb_flags(const struct xdp_buff *xdp)
 {
-	return xdp->flags;
+	return xdp->flags & ~XDP_FLAGS_EXT;

The only consumer is xdp_update_skb_frags_info, so probably not worth filtering out XDP_FLAGS_EXT here? Or is it for xdp_update_frame_from_buff? Can we explicitly clear it at the caller?

It was for xdp_update_frame_from_buff(), but looking closer EXT never gets there...

I'll drop the mask. Thanks!

Quoted 5 lines
Quoted 5 lines
net/core/devmem.c +0 -0
index 8f190b574beb..dea4a4a17e86 100644
@@ -698,5 +698,5 @@ static const struct memory_provider_ops dmabuf_devmem_ops = {
Quoted 8 lines

net/core/devmem.c static const struct memory_provider_ops dmabuf_devmem_ops = { · line 701

Quoted 5 lines
net/core/devmem.c +1 -1
 	.release_netmem		= mp_dmabuf_devmem_release_page,
 	.nl_fill		= mp_dmabuf_devmem_nl_fill,
 	.uninstall		= mp_dmabuf_devmem_uninstall,
-	.caps			= MP_CAP_FRAG,
+	.caps			= MP_CAP_FRAG | MP_CAP_RETAIN,

Not sure I understand this part, can you explain? These are MP_CAP_RETAIN because they are unreadable?

Quoted 8 lines

No, RETAIN is about lifetime: the stack may hold page pool references after the RX poll, e.g. skbs on a TCP receive queue. That's how devmem and zcrx work; without it the stack would try to copy them, and they'd trip the DEBUG_NET check in skb_add_rx_frag_netmem().

A provider without RETAIN gets copied, so it must be readable. I'll try to make that more clear in the kdoc, and probably refuse a provider that is neither.

Ah, yes, thanks, I did miss that warn in skb_add_rx_frag_netme, makes sense!

#29 lore raw

Re: [PATCH net-next v1 03/11] xdp: Copy buffers with restricted lifetime

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] xdp: missing xdp_data_meta_unsupported() check in xdp_build_skb_from_zc() - [High] xdp…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] xdp: missing xdp_data_meta_unsupported() check in xdp_build_skb_from_zc()
- [High] xdp: skb_shared_info overwrite in xdp_build_skb_from_zc() via aligned memcpy
It also noticed 2 related pre-existing issues this patch does not introduce:
- [Critical] bpf: double free and memory leak in xdp_do_redirect() [1]
- [Critical] xdp: double-free in xdp_return_buff() [2]
--

commit b80d3a81c03c102ec5d4e46044e260ec432b9137
Author: Björn Töpel <[email protected]>

xdp: Copy buffers with restricted lifetime

This commit adds the MP_CAP_RETAIN memory provider capability and copies XDP buffers from providers without MP_CAP_RETAIN when building an skb, converting to an xdp_frame, or redirecting outside XSKMAP.

Quoted 14 lines
net/core/filter.c +2 -0
index 80380f89adf90..f93839b493b25 100644
@@ -4774,12 +4774,28 @@ int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
 {
 	struct bpf_redirect_info *ri = bpf_net_ctx_get_ri();
 	enum bpf_map_type map_type = ri->map_type;
+	struct xdp_frame *xdpf;
+	int err;
 
 	if (map_type == BPF_MAP_TYPE_XSKMAP)
 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
 

net/core/filter.c int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp, · line 4790

Quoted 10 lines
net/core/filter.c +8 -2
-	return __xdp_do_redirect_frame(ri, dev, xdp_convert_buff_to_frame(xdp),
-				       xdp_prog);
+	if (likely(!xdp_buff_needs_copy(xdp)))
+		return __xdp_do_redirect_frame(ri, dev,
+					       xdp_convert_buff_to_frame(xdp),
+					       xdp_prog);
+
+	/* Release the source only after the target took the copy. */
+	xdpf = xdp_copy_buff_to_frame(xdp);
+	err = __xdp_do_redirect_frame(ri, dev, xdpf, xdp_prog);

[Severity: Critical]
This problem wasn't introduced by this patch, but can redirecting a MEM_TYPE_XSK_BUFF_POOL buffer still double free xdp and leak xdpf [1] when __xdp_do_redirect_frame() fails?

For MEM_TYPE_XSK_BUFF_POOL buffers, xdp_buff_needs_copy(xdp) is false, so xdp_do_redirect() takes the xdp_convert_buff_to_frame() -> xdp_convert_zc_to_xdp_frame() path, which frees xdp via xsk_buff_free() before __xdp_do_redirect_frame() runs. If __xdp_do_redirect_frame() returns an error, the allocated xdpf is leaked and the caller frees xdp a second time on its error path.

net/core/xdp.c void xdp_return_buff(struct xdp_buff *xdp) · line 565

Quoted 11 lines
net/core/xdp.c +1 -1
index 1d679e8fd6493..0cf46d492d91b 100644
@@ -559,10 +561,41 @@ void xdp_return_buff(struct xdp_buff *xdp)
 			     xdp->rxq->mem.type, true, xdp);
 
 out:
-	__xdp_return(virt_to_netmem(xdp->data), xdp->rxq->mem.type, true, xdp);
+	__xdp_return(xdp_buff_head_netmem(xdp), xdp->rxq->mem.type, true, xdp);
 }

[Severity: Critical]
This problem wasn't introduced by this patch, but does xdp_return_buff() call xsk_buff_free(xdp) once per fragment [2] on multi-fragment MEM_TYPE_XSK_BUFF_POOL buffers?

When xdp->rxq->mem.type is MEM_TYPE_XSK_BUFF_POOL, __xdp_return() ignores the netmem argument and calls xsk_buff_free(xdp), which frees the head buffer and all attached fragments at once. Looping over sinfo->nr_frags before the final __xdp_return() frees the same xdp_buff 1 + nr_frags times, corrupting the XSK buffer pool.

[ ... ]

net/core/xdp.c struct sk_buff *xdp_build_skb_from_buff(const struct xdp_buff *xdp) · line 693

Quoted 6 lines
net/core/xdp.c +2 -0
@@ -638,6 +689,9 @@ struct sk_buff *xdp_build_skb_from_buff(const struct xdp_buff *xdp)
 	u32 nr_frags = 0;
 	int metalen;
 
+	if (unlikely(xdp_buff_needs_copy(xdp)))
+		return xdp_build_skb_from_zc(xdp);

[Severity: High]
Does delegating to xdp_build_skb_from_zc() drop the first byte of the packet when xdp_data_meta_unsupported(xdp) is true?

When a driver passes meta_valid == false to xdp_prepare_buff(), or calls xdp_set_data_meta_invalid(), xdp->data_meta is set to xdp->data + 1. Unlike xdp_copy_buff_to_frame(), xdp_build_skb_from_zc() does not check xdp_data_meta_unsupported(xdp):

net/core/xdp.c:xdp_build_skb_from_zc() {
	const struct xdp_rxq_info *rxq = xdp->rxq;
	u32 len = xdp->data_end - xdp->data_meta;
	...
	skb_reserve(skb, xdp->data_meta - xdp->data_hard_start);

	memcpy(__skb_put(skb, len), xdp->data_meta, LARGEST_ALIGN(len));

	metalen = xdp->data - xdp->data_meta;
	if (metalen > 0) {
		skb_metadata_set(skb, metalen);
		__skb_pull(skb, metalen);
	}
}

With xdp->data_meta == xdp->data + 1, this copies from xdp->data + 1, sets skb->len one byte short, and skips __skb_pull() because metalen is -1, corrupting the packet header on XDP_PASS.

[ ... ]

net/core/xdp.c struct sk_buff *xdp_build_skb_from_zc(struct xdp_buff *xdp) · line 838

Quoted 6 lines
net/core/xdp.c +1 -1
@@ -781,7 +835,7 @@ struct sk_buff *xdp_build_skb_from_zc(struct xdp_buff *xdp)
 		goto out;
 	}
 
-	xsk_buff_free(xdp);
+	xdp_release_copied(xdp);

[Severity: High]
Can the LARGEST_ALIGN(len) memcpy in xdp_build_skb_from_zc() overwrite skb_shinfo(skb) when copying a buffer that reaches xdp_data_hard_end(xdp)?

In xdp_build_skb_from_zc(), napi_build_skb(data, truesize) initializes skb_shinfo(skb) at data + truesize - SKB_DATA_ALIGN(sizeof(struct skb_shared_info)), and then:

	skb_reserve(skb, xdp->data_meta - xdp->data_hard_start);

	memcpy(__skb_put(skb, len), xdp->data_meta, LARGEST_ALIGN(len));

When truesize equals xdp->frame_sz, skb->end is at the same offset from data as xdp_data_hard_end(xdp) is from xdp->data_hard_start. If an XDP program adjusts xdp->data or xdp->data_meta to an offset that is not 16-byte aligned and the head buffer is full up to xdp_data_hard_end(xdp), LARGEST_ALIGN(len) extends up to 15 bytes past skb->end and overwrites skb_shinfo(skb) (including nr_frags and frag_list) with bytes from xdp->data_end.

[1] https://sashiko.dev/#/bug/linux-c51b4a6d-8f07-471a-858e-04053743c6d2
[2] https://sashiko.dev/#/bug/linux-ad1513d6-3423-4560-95ce-a92871813ba4

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#30 lore raw

Re: [PATCH net-next v1 03/11] xdp: Copy buffers with restricted lifetime

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

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

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

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

- [High] xdp: missing xdp_data_meta_unsupported() check in xdp_build_skb_from_zc()
- [High] xdp: skb_shared_info overwrite in xdp_build_skb_from_zc() via aligned memcpy

--

net/core/xdp.c struct sk_buff *xdp_build_skb_from_buff(const struct xdp_buff *xdp) · line 697

Quoted 13 lines
net/core/xdp.c +3 -0
@@ -638,6 +689,9 @@ struct sk_buff *xdp_build_skb_from_buff(const struct xdp_buff *xdp)
 	u32 nr_frags = 0;
 	int metalen;
 
+	if (unlikely(xdp_buff_needs_copy(xdp)))
+		return xdp_build_skb_from_zc(xdp);
+
 	if (unlikely(xdp_buff_has_frags(xdp))) {
 		sinfo = xdp_get_shared_info_from_buff(xdp);
 		nr_frags = sinfo->nr_frags;

[Severity: High]
This makes xdp_build_skb_from_zc() the XDP_PASS path for restricted page pool buffers, and its copy can overrun the new head into the skb_shared_info.

The function asks the system page pool for truesize = xdp->frame_sz. When that comes back unchanged, napi_build_skb() places skb_shared_info at the same offset that xdp_data_hard_end() has in the source. The code then copies LARGEST_ALIGN(len) bytes starting at offset xdp->data_meta - xdp->data_hard_start.

That offset is often not a multiple of 16, which is normal after bpf_xdp_adjust_head() by an Ethernet or VLAN header. If data_end is also close to xdp_data_hard_end(), the rounded-up memcpy writes into the already initialised skb_shinfo() of the new skb: flags, nr_frags, the gso fields and frag_list.

The bytes written come from past data_end in the head chunk, which for UMEM is writable by userspace. Freeing or segmenting the skb later then walks a bogus nr_frags or frag_list.

With XDP_FLAGS_EXT the head chunk no longer holds the shared info at all. Does anything still keep data_end below xdp_data_hard_end() for these buffers? If not, len alone can run past skb->end, since __skb_put() does not check.

Should the destination size be derived from the copy instead of xdp->frame_sz? For example: headroom + LARGEST_ALIGN(len) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)). Or should this path copy exactly len bytes?

[Severity: High]
Restricted buffers on XDP_PASS now go through xdp_build_skb_from_zc(), but that function cannot cope with unsupported metadata. If the driver called xdp_prepare_buff(..., false), or metadata is otherwise invalid, xdp->data_meta is xdp->data + 1.

The non-copy path of xdp_build_skb_from_buff() handles this. It reserves and puts from xdp->data and only sets metadata when metalen > 0. xdp_copy_buff_to_frame() in this patch also checks xdp_data_meta_unsupported().

xdp_build_skb_from_zc() does not. It:

- computes len as data_end - data_meta,
- reserves data_meta - data_hard_start,
- copies from data_meta,
- then sees metalen == -1 and skips the __skb_pull().

The resulting skb starts at the second byte of the Ethernet header and is one byte short, so eth_type_trans() and everything above it parse shifted data. If data_end == data, len also wraps as a u32.

The XSK callers did not hit this, because the pool sets data_meta == data. Page pool drivers without metadata support pass meta_valid == false routinely, though.

Could xdp_build_skb_from_zc() compute the metadata size the way xdp_copy_buff_to_frame() does? That means treating unsupported metadata as zero length and copying from xdp->data.

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261110102039.1002605-1-bjorn%40kernel.org
#31 lore raw

Re: [PATCH net-next v1 03/11] xdp: Copy buffers with restricted lifetime

[email protected] writes:

[...]

Quoted 4 lines

With XDP_FLAGS_EXT the head chunk no longer holds the shared info at all. Does anything still keep data_end below xdp_data_hard_end() for these buffers? If not, len alone can run past skb->end, since __skb_put() does not check.

Yes. fbnic's MAX_HDR leaves the same tailroom, and bpf_xdp_adjust_tail() stops at xdp_data_hard_end().

Quoted 4 lines

Should the destination size be derived from the copy instead of xdp->frame_sz? For example: headroom + LARGEST_ALIGN(len) + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)). Or should this path copy exactly len bytes?

Yes, but that's pre-existing. XSK buffers without XDP_USE_SG have no tailroom at all, so it's worse there. It's the head sizing from Clement's thread [1]. A fix that sizes the head by its contents and copies exact lengths goes to net, and v2 sits on top of it.

[...]

Quoted 3 lines

Could xdp_build_skb_from_zc() compute the metadata size the way xdp_copy_buff_to_frame() does? That means treating unsupported metadata as zero length and copying from xdp->data.

Yes. Nothing hits it today, as fbnic marks the metadata valid, but this patch makes it a generic path. Will fix.

pw-bot: cr

Björn

[1] https://lore.kernel.org/bpf/[email protected]/

#32 lore raw

Re: [PATCH net-next v1 03/11] xdp: Copy buffers with restricted lifetime

In reply to Björn Töpel
Quoted 7 lines · Björn Töpel

UMEM stays mapped writable in userspace, and it has a fixed number of chunks. The stack must not keep its chunks in an skb or an xdp_frame. Mark the providers whose buffers the stack may keep with MP_CAP_RETAIN, and copy packets of the others on XDP_PASS, on conversion to a frame, and on redirects other than XSKMAP.

I'm not understanding why that needs special handling. Devmem stays mapped and writeable and did not need MP_CAP_RETAIN. Also, today the stack can keep any pp page in the socket's receive queue for arbitrary time without _RETAIN. I'm espcially confused you're not adding _RETAIN as a cap to existing providers, but their netmems can be retained.

Quoted 8 lines

The head chunk is writable by userspace, so it cannot hold skb_shared_info, and virt_to_netmem() cannot find a net_iov head. Drivers pass kernel memory for both to xdp_init_buff_netmem().

A static key keeps the check off while no such page pool exists. A frame copy is linear, so a multi-buffer packet of such a provider cannot go to a device or CPU map.

Did this actually improve perf? I recall that when I benchmarked the performance improvement, it was questionable.

Signature · 2 lines
Thanks,
Mina
#33 lore raw

Re: [PATCH net-next v1 03/11] xdp: Copy buffers with restricted lifetime

Quoted 9 lines · Mina Almasry
Quoted 7 lines · Björn Töpel

UMEM stays mapped writable in userspace, and it has a fixed number of chunks. The stack must not keep its chunks in an skb or an xdp_frame. Mark the providers whose buffers the stack may keep with MP_CAP_RETAIN, and copy packets of the others on XDP_PASS, on conversion to a frame, and on redirects other than XSKMAP.

Quoted 5 lines

I'm not understanding why that needs special handling. Devmem stays mapped and writeable and did not need MP_CAP_RETAIN. Also, today the stack can keep any pp page in the socket's receive queue for arbitrary time without _RETAIN. I'm espcially confused you're not adding _RETAIN as a cap to existing providers, but their netmems can be retained.

This patch does give devmem and io_uring zcrx MP_CAP_RETAIN, and pages need nothing... a pool without a provider is retainable. Only UMEM isn't.

The stack never reads devmem or io_uring zcrx payloads, so it doesn't matter that userspace can write them. UMEM is readable, and the stack would parse headers and payload that the application can change under it. An AF_XDP socket also has a fixed set of chunks, and chunks held in skbs elsewhere starve it. Driver zero copy copies on XDP_PASS for the same reasons, in xdp_build_skb_from_zc(); this does the same for provider buffers.

Quoted 11 lines
Quoted 8 lines

The head chunk is writable by userspace, so it cannot hold skb_shared_info, and virt_to_netmem() cannot find a net_iov head. Drivers pass kernel memory for both to xdp_init_buff_netmem().

A static key keeps the check off while no such page pool exists. A frame copy is linear, so a multi-buffer packet of such a provider cannot go to a device or CPU map.

Did this actually improve perf? I recall that when I benchmarked the performance improvement, it was questionable.

I have no numbers for it, and it goes in v2. With the frag walk gone, as agreed with Stan, the only check left under the key is for page heads, and no provider hands out pages.

Björn

#34 lore raw

PATCH 4/11 xsk: Allocate UMEM chunks through page_pool

In reply to Björn Töpel

AF_XDP zero copy needs a second RX allocator in every driver. A page_pool driver can take UMEM chunks from a memory provider instead, and keep its refill, recycling and DMA sync code.

Each aligned chunk becomes a net_iov, whose address netmem_address() finds without calling the provider. Userspace may post a chunk that the kernel still owns, so the provider tracks the owner of each chunk and drops such FILL entries. Chunks that a page pool releases stay in the kernel for reuse. Nothing installs the provider yet.

---
 include/net/netmem.h |  25 ++++-
 include/net/xdp.h    |   2 +-
 net/xdp/Kconfig      |   1 +
 net/xdp/Makefile     |   2 +-
 net/xdp/xsk.h        |   6 ++
 net/xdp/xsk_pp.c     | 246 +++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 279 insertions(+), 3 deletions(-)
 create mode 100644 net/xdp/xsk_pp.c
include/net/netmem.h +24 -1
index b986ad616334..a3b67ef32b21 100644
@@ -69,6 +69,7 @@ DECLARE_STATIC_KEY_FALSE(page_pool_restricted);
 enum net_iov_type {
 	NET_IOV_DMABUF,
 	NET_IOV_IOURING,
+	NET_IOV_XSK,
 };
 
 /* A memory descriptor representing abstract networking I/O vectors.
@@ -107,6 +108,10 @@ struct net_iov_area {
 	size_t num_niovs;
 	/* Each net_iov covers 1 << niov_shift bytes. */
 	unsigned int niov_shift;
+	/* CPU address of the first net_iov, or NULL if the CPU cannot read
+	 * the area.
+	 */
+	void *vaddr;
 };
 
 static inline struct net_iov_area *net_iov_owner(const struct net_iov *niov)
@@ -119,6 +124,18 @@ static inline unsigned int net_iov_idx(const struct net_iov *niov)
 	return niov - net_iov_owner(niov)->niovs;
 }
 
+static inline void *net_iov_address(const struct net_iov *niov)
+{
+	const struct net_iov_area *area = net_iov_owner(niov);
+	unsigned long off;
+
+	if (!area->vaddr)
+		return NULL;
+
+	off = (unsigned long)net_iov_idx(niov) << area->niov_shift;
+	return area->vaddr + off;
+}
+
 /* Initialize a niov: stamp the owning area, the memory provider type.
  */
 static inline void net_iov_init(struct net_iov *niov,
@@ -345,10 +362,16 @@ static inline void *__netmem_address(netmem_ref netmem)
 	return page_address(__netmem_to_page(netmem));
 }
 
+/**
+ * netmem_address - get the CPU address of the memory behind @netmem
+ * @netmem: netmem to get the address of
+ *
+ * Return: the address, or NULL if the CPU cannot read @netmem.
+ */
 static inline void *netmem_address(netmem_ref netmem)
 {
 	if (netmem_is_net_iov(netmem))
-		return NULL;
+		return net_iov_address(netmem_to_net_iov(netmem));
 
 	return __netmem_address(netmem);
 }
include/net/xdp.h +1 -1
index 1105bb9e3292..5ab7802ac4e1 100644
@@ -368,7 +368,7 @@ 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) && !netmem_address(netmem)))
 		xdp_buff_set_frag_unreadable(xdp);
 
 	return true;
net/xdp/Kconfig +1 -0
index 71af2febe72a..c9c68d3b3712 100644
@@ -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
net/xdp/Makefile +1 -1
index 30cdc4315f42..6e9d60f9f7f1 100644
@@ -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_pp.o
 obj-$(CONFIG_XDP_SOCKETS_DIAG) += xsk_diag.o
net/xdp/xsk.h +6 -0
index 7c811b5cce76..4dab7b9a1487 100644
@@ -34,6 +34,12 @@ static inline struct xdp_sock *xdp_sk(struct sock *sk)
 
 void xsk_map_try_sock_delete(struct xsk_map *map, struct xdp_sock *xs,
 			     struct xdp_sock __rcu **map_entry);
+struct xsk_pp;
+
+extern const struct memory_provider_ops xsk_pp_ops;
+
+struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool);
+void xsk_pp_put(struct xsk_pp *pp);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
 			u16 queue_id);
net/xdp/xsk_pp.c new file +246 -0

246 lines not on this page · raw message

Signature · 1 line
2.56.0
#35 lore raw

Re: [PATCH net-next v1 04/11] xsk: Allocate UMEM chunks through page_pool

Quoted 122 lines · Björn Töpel

AF_XDP zero copy needs a second RX allocator in every driver. A page_pool driver can take UMEM chunks from a memory provider instead, and keep its refill, recycling and DMA sync code.

Each aligned chunk becomes a net_iov, whose address netmem_address() finds without calling the provider. Userspace may post a chunk that the kernel still owns, so the provider tracks the owner of each chunk and drops such FILL entries. Chunks that a page pool releases stay in the kernel for reuse. Nothing installs the provider yet.

---
 include/net/netmem.h |  25 ++++-
 include/net/xdp.h    |   2 +-
 net/xdp/Kconfig      |   1 +
 net/xdp/Makefile     |   2 +-
 net/xdp/xsk.h        |   6 ++
 net/xdp/xsk_pp.c     | 246 +++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 279 insertions(+), 3 deletions(-)
 create mode 100644 net/xdp/xsk_pp.c
include/net/netmem.h +24 -1
index b986ad616334..a3b67ef32b21 100644
@@ -69,6 +69,7 @@ DECLARE_STATIC_KEY_FALSE(page_pool_restricted);
 enum net_iov_type {
        NET_IOV_DMABUF,
        NET_IOV_IOURING,
+       NET_IOV_XSK,
 };
 
 /* A memory descriptor representing abstract networking I/O vectors.
@@ -107,6 +108,10 @@ struct net_iov_area {
        size_t num_niovs;
        /* Each net_iov covers 1 << niov_shift bytes. */
        unsigned int niov_shift;
+       /* CPU address of the first net_iov, or NULL if the CPU cannot read
+        * the area.
+        */
+       void *vaddr;
 };
 
 static inline struct net_iov_area *net_iov_owner(const struct net_iov *niov)
@@ -119,6 +124,18 @@ static inline unsigned int net_iov_idx(const struct net_iov *niov)
        return niov - net_iov_owner(niov)->niovs;
 }
 
+static inline void *net_iov_address(const struct net_iov *niov)
+{
+       const struct net_iov_area *area = net_iov_owner(niov);
+       unsigned long off;
+
+       if (!area->vaddr)
+               return NULL;
+
+       off = (unsigned long)net_iov_idx(niov) << area->niov_shift;
+       return area->vaddr + off;
+}
+
 /* Initialize a niov: stamp the owning area, the memory provider type.
  */
 static inline void net_iov_init(struct net_iov *niov,
@@ -345,10 +362,16 @@ static inline void *__netmem_address(netmem_ref netmem)
        return page_address(__netmem_to_page(netmem));
 }
 
+/**
+ * netmem_address - get the CPU address of the memory behind @netmem
+ * @netmem: netmem to get the address of
+ *
+ * Return: the address, or NULL if the CPU cannot read @netmem.
+ */
 static inline void *netmem_address(netmem_ref netmem)
 {
        if (netmem_is_net_iov(netmem))
-               return NULL;
+               return net_iov_address(netmem_to_net_iov(netmem));
 
        return __netmem_address(netmem);
 }
include/net/xdp.h +1 -1
index 1105bb9e3292..5ab7802ac4e1 100644
@@ -368,7 +368,7 @@ 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) && !netmem_address(netmem)))
                xdp_buff_set_frag_unreadable(xdp);
 
        return true;
net/xdp/Kconfig +1 -0
index 71af2febe72a..c9c68d3b3712 100644
@@ -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
net/xdp/Makefile +1 -1
index 30cdc4315f42..6e9d60f9f7f1 100644
@@ -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_pp.o
 obj-$(CONFIG_XDP_SOCKETS_DIAG) += xsk_diag.o
net/xdp/xsk.h +0 -0
index 7c811b5cce76..4dab7b9a1487 100644

net/xdp/xsk.h static inline struct xdp_sock *xdp_sk(struct sock *sk) · line 37

Quoted 4 lines
net/xdp/xsk.h +1 -0
@@ -34,6 +34,12 @@ static inline struct xdp_sock *xdp_sk(struct sock *sk)
 
 void xsk_map_try_sock_delete(struct xsk_map *map, struct xdp_sock *xs,
                             struct xdp_sock __rcu **map_entry);
+struct xsk_pp;

How about a header file instead of a forward declaration?

Quoted 38 lines
net/xdp/xsk.h +4 -0
+extern const struct memory_provider_ops xsk_pp_ops;
+
+struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool);
+void xsk_pp_put(struct xsk_pp *pp);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
                        u16 queue_id);
net/xdp/xsk_pp.c new file +25 -0
new file mode 100644
index 000000000000..fdd55265a6cd
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP UMEM as a page pool memory provider
+ *
+ * Each aligned UMEM chunk is a readable net_iov with one owner at a time:
+ *
+ *   userspace --FILL--> page pool --release--> reuse --alloc--> page pool
+ *       ^                   |
+ *       +-----RX ring-------+
+ */
+
+#include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
+
+#include "xsk.h"
+#include "xsk_queue.h"
+
+enum xsk_pp_chunk {
+       XSK_PP_USER,    /* owned by userspace */
+       XSK_PP_POOL,    /* owned by a page pool */
+       XSK_PP_REUSE,   /* on the reuse stack */
+};
+
+struct xsk_pp {
+       struct net_iov_area area;

net/xdp/xsk_pp.c line 35

Quoted 10 lines
net/xdp/xsk_pp.c new file +10 -0
+       struct xsk_buff_pool *pool;
+       /* Protects fq, state and reuse */
+       spinlock_t lock;
+       struct xsk_queue *fq;
+       refcount_t refs;
+       u32 nr_pools;
+       bool dma_need_sync;
+       u8 *state;
+       u32 reuse_cnt;
+       u32 reuse[];

Is the reason that you have a reuse stack here and not use the one in xsk_buff_pool that it only exists in unaligned mode, which you are not supporting? Could you still use the "pre-calculated" heads in aligned mode and link them up? There is already a xskb_list and free_list in there that is used for that purpose. Just an idea that could cut down the state and maybe the amount of code.

Quoted 33 lines
net/xdp/xsk_pp.c new file +33 -0
+};
+
+static void xsk_pp_free(struct xsk_pp *pp)
+{
+       kvfree(pp->state);
+       kvfree(pp->area.niovs);
+       kvfree(pp);
+}
+
+void xsk_pp_put(struct xsk_pp *pp)
+{
+       if (refcount_dec_and_test(&pp->refs))
+               xsk_pp_free(pp);
+}
+
+/* @pool must be DMA mapped and have aligned chunks. The provider must be
+ * the only consumer of its FILL ring.
+ */
+struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool)
+{
+       struct net_iov *niov;
+       struct xsk_pp *pp;
+       dma_addr_t dma;
+       u32 i;
+
+       pp = kvzalloc_flex(*pp, reuse, pool->heads_cnt, GFP_KERNEL_ACCOUNT);
+       if (!pp)
+               return ERR_PTR(-ENOMEM);
+
+       pp->area.niovs = kvzalloc_objs(*pp->area.niovs, pool->heads_cnt,
+                                      GFP_KERNEL_ACCOUNT);
+       pp->state = kvzalloc(pool->heads_cnt, GFP_KERNEL_ACCOUNT);
+       if (!pp->area.niovs || !pp->state) {

net/xdp/xsk_pp.c line 78

Quoted 10 lines
net/xdp/xsk_pp.c new file +10 -0
+               xsk_pp_free(pp);
+               return ERR_PTR(-ENOMEM);
+       }
+
+       pp->area.num_niovs = pool->heads_cnt;
+       pp->area.niov_shift = pool->chunk_shift;
+       pp->area.vaddr = pool->addrs;
+       pp->pool = pool;
+       pp->fq = pool->fq;
+       pp->dma_need_sync = dma_dev_need_sync(pool->dev);

Are you copying these for performance reasons, i.e. no extra pointer dereference in the fast path? In the same manner as the pool copies some information from the umem?

Quoted 20 lines
net/xdp/xsk_pp.c new file +20 -0
+       spin_lock_init(&pp->lock);
+       refcount_set(&pp->refs, 1);
+
+       for (i = 0; i < pp->area.num_niovs; i++) {
+               niov = &pp->area.niovs[i];
+               dma = xp_raw_get_dma(pool, (u64)i << pool->chunk_shift);
+               net_iov_init(niov, &pp->area, NET_IOV_XSK);
+               if (net_mp_niov_set_dma_addr(niov, dma)) {
+                       xsk_pp_free(pp);
+                       return ERR_PTR(-ERANGE);
+               }
+       }
+
+       return pp;
+}
+
+static int xsk_pp_init(struct page_pool *pool)
+{
+       struct xsk_pp *pp = pool->mp_priv;
+

net/xdp/xsk_pp.c line 108

Quoted 10 lines
net/xdp/xsk_pp.c new file +10 -0
+       if (pool->p.order || pool->p.dma_dir != DMA_BIDIRECTIONAL ||
+           pool->p.dev != pp->pool->dev)
+               return -EINVAL;
+       if (pool->p.max_len > pp->pool->chunk_size ||
+           pool->p.offset > pp->pool->chunk_size - pool->p.max_len)
+               return -EINVAL;
+
+       refcount_inc(&pp->refs);
+       spin_lock_bh(&pp->lock);
+       pp->nr_pools++;

What is the difference between this counter and the refcount?

Quoted 72 lines
net/xdp/xsk_pp.c new file +72 -0
+       spin_unlock_bh(&pp->lock);
+       return 0;
+}
+
+static void xsk_pp_destroy(struct page_pool *pool)
+{
+       struct xsk_pp *pp = pool->mp_priv;
+
+       spin_lock_bh(&pp->lock);
+       pp->nr_pools--;
+       spin_unlock_bh(&pp->lock);
+       xsk_pp_put(pp);
+}
+
+static bool xsk_pp_claim(struct xsk_pp *pp, u32 idx, enum xsk_pp_chunk from)
+{
+       lockdep_assert_held(&pp->lock);
+
+       if (pp->state[idx] != from)
+               return false;
+
+       pp->state[idx] = XSK_PP_POOL;
+       return true;
+}
+
+static u32 xsk_pp_alloc_reuse(struct xsk_pp *pp, netmem_ref *netmems, u32 max)
+{
+       u32 idx, n = 0;
+
+       while (n < max && pp->reuse_cnt) {
+               idx = pp->reuse[--pp->reuse_cnt];
+               if (WARN_ON_ONCE(!xsk_pp_claim(pp, idx, XSK_PP_REUSE)))
+                       continue;
+               netmems[n++] = net_iov_to_netmem(&pp->area.niovs[idx]);
+       }
+
+       return n;
+}
+
+static u32 xsk_pp_alloc_fill(struct xsk_pp *pp, netmem_ref *netmems, u32 max)
+{
+       struct xsk_buff_pool *pool = pp->pool;
+       struct xsk_queue *fq = pp->fq;
+       u32 i, entries, cons, idx, n = 0;
+       u64 addr;
+
+       if (!fq || !max)
+               return 0;
+
+       entries = xskq_cons_nb_entries(fq, max);
+       if (!entries) {
+               fq->queue_empty_descs++;
+               return 0;
+       }
+
+       cons = fq->cached_cons;
+       for (i = 0; i < entries; i++) {
+               __xskq_cons_read_addr_unchecked(fq, cons++, &addr);
+               addr &= pool->chunk_mask;
+               idx = addr >> pp->area.niov_shift;
+               if (unlikely(addr >= pool->addrs_cnt ||
+                            !xsk_pp_claim(pp, idx, XSK_PP_USER))) {
+                       fq->invalid_descs++;
+                       continue;
+               }
+               netmems[n++] = net_iov_to_netmem(&pp->area.niovs[idx]);
+       }
+
+       xskq_cons_release_n(fq, entries);
+       __xskq_cons_release(fq);
+       return n;
+}

net/xdp/xsk_pp.c line 190

Quoted 10 lines
net/xdp/xsk_pp.c new file +10 -0
+
+static netmem_ref xsk_pp_alloc_netmems(struct page_pool *pool, gfp_t gfp)
+{
+       netmem_ref *netmems = pool->alloc.cache;
+       struct xsk_pp *pp = pool->mp_priv;
+       struct net_iov *niov;
+       dma_addr_t dma;
+       u32 i, n;
+
+       if (WARN_ON_ONCE(pool->alloc.count))

What has the driver writer or system done if this ever happens?

net/xdp/xsk_pp.c line 117

Quoted 3 lines
net/xdp/xsk_pp.c new file +3 -0
+               return 0;
+
+       spin_lock_bh(&pp->lock);

For my understanding, what entities can call this function at the same time? With the xsk_buff_pool we were protected by NAPI.

Quoted 57 lines
net/xdp/xsk_pp.c new file +53 -1
+       n = xsk_pp_alloc_reuse(pp, netmems, PP_ALLOC_CACHE_REFILL);
+       n += xsk_pp_alloc_fill(pp, netmems + n, PP_ALLOC_CACHE_REFILL - n);
+       spin_unlock_bh(&pp->lock);
+       if (!n)
+               return 0;
+
+       for (i = 0; i < n; i++) {
+               niov = netmem_to_net_iov(netmems[i]);
+               dma = page_pool_get_dma_addr_netmem(netmems[i]);
+               if (pp->dma_need_sync)
+                       dma_sync_single_range_for_device(pool->p.dev, dma,
+                                                        pool->p.offset,
+                                                        pool->p.max_len,
+                                                        pool->p.dma_dir);
+               net_mp_niov_set_page_pool(pool, niov);
+       }
+
+       pool->alloc.count = n - 1;
+       return netmems[n - 1];
+}
+
+static bool xsk_pp_release_netmem(struct page_pool *pool, netmem_ref netmem)
+{
+       struct net_iov *niov = netmem_to_net_iov(netmem);
+       struct xsk_pp *pp = pool->mp_priv;
+       u32 idx = net_iov_idx(niov);
+
+       spin_lock_bh(&pp->lock);
+       net_mp_niov_clear_page_pool(niov);
+       if (!WARN_ON_ONCE(pp->state[idx] != XSK_PP_POOL ||
+                         pp->reuse_cnt == pp->area.num_niovs)) {
+               pp->state[idx] = XSK_PP_REUSE;
+               pp->reuse[pp->reuse_cnt++] = idx;
+       }
+       spin_unlock_bh(&pp->lock);
+
+       return false;
+}
+
+static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
+                         struct netdev_rx_queue *rxq)
+{
+       return 0;
+}
+
+const struct memory_provider_ops xsk_pp_ops = {
+       .init           = xsk_pp_init,
+       .destroy        = xsk_pp_destroy,
+       .alloc_netmems  = xsk_pp_alloc_netmems,
+       .release_netmem = xsk_pp_release_netmem,
+       .nl_fill        = xsk_pp_nl_fill,
+       .caps           = MP_CAP_READABLE,
+};
--

2.56.0

#36 lore raw

Re: [PATCH net-next v1 04/11] xsk: Allocate UMEM chunks through page_pool

Quoted 8 lines · Magnus Karlsson
Quoted 6 lines · Björn Töpel
net/xdp/xsk.h +0 -0
index 7c811b5cce76..4dab7b9a1487 100644
@@ -34,6 +34,12 @@ static inline struct xdp_sock *xdp_sk(struct sock *sk)
 
Quoted 5 lines

net/xdp/xsk.h static inline struct xdp_sock *xdp_sk(struct sock *sk) · line 37

Quoted 3 lines
net/xdp/xsk.h +1 -0
 void xsk_map_try_sock_delete(struct xsk_map *map, struct xdp_sock *xs,
                             struct xdp_sock __rcu **map_entry);
+struct xsk_pp;

How about a header file instead of a forward declaration?

Thanks for taking a look, Magnus!

Hmm, my take was this this was ont by itself sufficient for a header. Let me think about it, and I might add net/xdp/xsk_pp.h.

Quoted 48 lines
Quoted 48 lines
net/xdp/xsk.h +4 -0
+extern const struct memory_provider_ops xsk_pp_ops;
+
+struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool);
+void xsk_pp_put(struct xsk_pp *pp);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
                        u16 queue_id);
net/xdp/xsk_pp.c new file +34 -0
new file mode 100644
index 000000000000..fdd55265a6cd
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP UMEM as a page pool memory provider
+ *
+ * Each aligned UMEM chunk is a readable net_iov with one owner at a time:
+ *
+ *   userspace --FILL--> page pool --release--> reuse --alloc--> page pool
+ *       ^                   |
+ *       +-----RX ring-------+
+ */
+
+#include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
+
+#include "xsk.h"
+#include "xsk_queue.h"
+
+enum xsk_pp_chunk {
+       XSK_PP_USER,    /* owned by userspace */
+       XSK_PP_POOL,    /* owned by a page pool */
+       XSK_PP_REUSE,   /* on the reuse stack */
+};
+
+struct xsk_pp {
+       struct net_iov_area area;
+       struct xsk_buff_pool *pool;
+       /* Protects fq, state and reuse */
+       spinlock_t lock;
+       struct xsk_queue *fq;
+       refcount_t refs;
+       u32 nr_pools;
+       bool dma_need_sync;
+       u8 *state;
+       u32 reuse_cnt;
Quoted 8 lines

net/xdp/xsk_pp.c line 35

Quoted 1 line
net/xdp/xsk_pp.c new file +1 -0
+       u32 reuse[];

Is the reason that you have a reuse stack here and not use the one in xsk_buff_pool that it only exists in unaligned mode, which you are not supporting? Could you still use the "pre-calculated" heads in aligned mode and link them up? There is already a xskb_list and free_list in there that is used for that purpose. Just an idea that could cut down the state and maybe the amount of code.

Not quite. reuse is the counterpart of free_list, which aligned mode has too. But free_list links xdp_buff_xsk, and this mode has none: the page pool hands out net_iovs, and the driver has its own xdp_buff. Patch 5 stops allocating the heads here: 128 bytes per chunk, against 69 for net_iov, reuse and state. devmem and zcrx use the same kind of index stack.

free_list is also NAPI only, while the page pool releases chunks from process context too (below). And state is needed either way; it is what drops a FILL entry for a chunk the kernel still owns.

Quoted 39 lines
Quoted 39 lines
net/xdp/xsk_pp.c new file +39 -0
+};
+
+static void xsk_pp_free(struct xsk_pp *pp)
+{
+       kvfree(pp->state);
+       kvfree(pp->area.niovs);
+       kvfree(pp);
+}
+
+void xsk_pp_put(struct xsk_pp *pp)
+{
+       if (refcount_dec_and_test(&pp->refs))
+               xsk_pp_free(pp);
+}
+
+/* @pool must be DMA mapped and have aligned chunks. The provider must be
+ * the only consumer of its FILL ring.
+ */
+struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool)
+{
+       struct net_iov *niov;
+       struct xsk_pp *pp;
+       dma_addr_t dma;
+       u32 i;
+
+       pp = kvzalloc_flex(*pp, reuse, pool->heads_cnt, GFP_KERNEL_ACCOUNT);
+       if (!pp)
+               return ERR_PTR(-ENOMEM);
+
+       pp->area.niovs = kvzalloc_objs(*pp->area.niovs, pool->heads_cnt,
+                                      GFP_KERNEL_ACCOUNT);
+       pp->state = kvzalloc(pool->heads_cnt, GFP_KERNEL_ACCOUNT);
+       if (!pp->area.niovs || !pp->state) {
+               xsk_pp_free(pp);
+               return ERR_PTR(-ENOMEM);
+       }
+
+       pp->area.num_niovs = pool->heads_cnt;
+       pp->area.niov_shift = pool->chunk_shift;
Quoted 8 lines

net/xdp/xsk_pp.c line 78

Quoted 4 lines
net/xdp/xsk_pp.c new file +4 -0
+       pp->area.vaddr = pool->addrs;
+       pp->pool = pool;
+       pp->fq = pool->fq;
+       pp->dma_need_sync = dma_dev_need_sync(pool->dev);

Are you copying these for performance reasons, i.e. no extra pointer dereference in the fast path? In the same manner as the pool copies some information from the umem?

Only dma_need_sync is a cache -- I'll drop that!

fq stays. It's the provider's handle on FILL: unbind clears it under the lock (patch 5), so the provider stops reading FILL, while pool->fq stays with the socket for mmap, need_wakeup and copy mode until the ring is freed. The area fields are the generic net_iov_area that netmem_address() needs.

Does that make sense?

Quoted 24 lines
Quoted 24 lines
net/xdp/xsk_pp.c new file +24 -0
+       spin_lock_init(&pp->lock);
+       refcount_set(&pp->refs, 1);
+
+       for (i = 0; i < pp->area.num_niovs; i++) {
+               niov = &pp->area.niovs[i];
+               dma = xp_raw_get_dma(pool, (u64)i << pool->chunk_shift);
+               net_iov_init(niov, &pp->area, NET_IOV_XSK);
+               if (net_mp_niov_set_dma_addr(niov, dma)) {
+                       xsk_pp_free(pp);
+                       return ERR_PTR(-ERANGE);
+               }
+       }
+
+       return pp;
+}
+
+static int xsk_pp_init(struct page_pool *pool)
+{
+       struct xsk_pp *pp = pool->mp_priv;
+
+       if (pool->p.order || pool->p.dma_dir != DMA_BIDIRECTIONAL ||
+           pool->p.dev != pp->pool->dev)
+               return -EINVAL;
+       if (pool->p.max_len > pp->pool->chunk_size ||
Quoted 8 lines

net/xdp/xsk_pp.c line 108

Quoted 6 lines
net/xdp/xsk_pp.c new file +6 -0
+           pool->p.offset > pp->pool->chunk_size - pool->p.max_len)
+               return -EINVAL;
+
+       refcount_inc(&pp->refs);
+       spin_lock_bh(&pp->lock);
+       pp->nr_pools++;

What is the difference between this counter and the refcount?

refs is the lifetime of struct xsk_pp. The buffer pool holds one reference, and each page pool that takes the provider holds one. A page pool can outlive the socket, as page_pool_destroy() defers while buffers are in flight. The struct is freed with the last reference.

nr_pools only tells whether a page pool still exists, when a failed bind (patch 5) hands the leftover chunks to copy mode. But the page pools of a failed bind never ran, and are gone by then, so a WARN on refs != 1 does the same job... I'll drop nr_pools. Thanks!

Quoted 76 lines
Quoted 76 lines
net/xdp/xsk_pp.c new file +76 -0
+       spin_unlock_bh(&pp->lock);
+       return 0;
+}
+
+static void xsk_pp_destroy(struct page_pool *pool)
+{
+       struct xsk_pp *pp = pool->mp_priv;
+
+       spin_lock_bh(&pp->lock);
+       pp->nr_pools--;
+       spin_unlock_bh(&pp->lock);
+       xsk_pp_put(pp);
+}
+
+static bool xsk_pp_claim(struct xsk_pp *pp, u32 idx, enum xsk_pp_chunk from)
+{
+       lockdep_assert_held(&pp->lock);
+
+       if (pp->state[idx] != from)
+               return false;
+
+       pp->state[idx] = XSK_PP_POOL;
+       return true;
+}
+
+static u32 xsk_pp_alloc_reuse(struct xsk_pp *pp, netmem_ref *netmems, u32 max)
+{
+       u32 idx, n = 0;
+
+       while (n < max && pp->reuse_cnt) {
+               idx = pp->reuse[--pp->reuse_cnt];
+               if (WARN_ON_ONCE(!xsk_pp_claim(pp, idx, XSK_PP_REUSE)))
+                       continue;
+               netmems[n++] = net_iov_to_netmem(&pp->area.niovs[idx]);
+       }
+
+       return n;
+}
+
+static u32 xsk_pp_alloc_fill(struct xsk_pp *pp, netmem_ref *netmems, u32 max)
+{
+       struct xsk_buff_pool *pool = pp->pool;
+       struct xsk_queue *fq = pp->fq;
+       u32 i, entries, cons, idx, n = 0;
+       u64 addr;
+
+       if (!fq || !max)
+               return 0;
+
+       entries = xskq_cons_nb_entries(fq, max);
+       if (!entries) {
+               fq->queue_empty_descs++;
+               return 0;
+       }
+
+       cons = fq->cached_cons;
+       for (i = 0; i < entries; i++) {
+               __xskq_cons_read_addr_unchecked(fq, cons++, &addr);
+               addr &= pool->chunk_mask;
+               idx = addr >> pp->area.niov_shift;
+               if (unlikely(addr >= pool->addrs_cnt ||
+                            !xsk_pp_claim(pp, idx, XSK_PP_USER))) {
+                       fq->invalid_descs++;
+                       continue;
+               }
+               netmems[n++] = net_iov_to_netmem(&pp->area.niovs[idx]);
+       }
+
+       xskq_cons_release_n(fq, entries);
+       __xskq_cons_release(fq);
+       return n;
+}
+
+static netmem_ref xsk_pp_alloc_netmems(struct page_pool *pool, gfp_t gfp)
+{
+       netmem_ref *netmems = pool->alloc.cache;
Quoted 8 lines

net/xdp/xsk_pp.c line 190

Quoted 6 lines
net/xdp/xsk_pp.c new file +6 -0
+       struct xsk_pp *pp = pool->mp_priv;
+       struct net_iov *niov;
+       dma_addr_t dma;
+       u32 i, n;
+
+       if (WARN_ON_ONCE(pool->alloc.count))

What has the driver writer or system done if this ever happens?

A correct driver can't get there; the page pool calls ->alloc_netmems() only with an empty cache. It fires on a page_pool core bug, or when a driver recycles with allow_direct outside the pool's NAPI, and races the cache. The provider fills the cache from index 0, so failing beats overwriting live entries. devmem and zcrx have the same check; I'll add zcrx's comment.

Quoted 6 lines

net/xdp/xsk_pp.c line 117

Quoted 3 lines
net/xdp/xsk_pp.c new file +3 -0
+               return 0;
+
+       spin_lock_bh(&pp->lock);

For my understanding, what entities can call this function at the same time? With the xsk_buff_pool we were protected by NAPI.

Yeah... this is a bit gnarley.

The provider outlives a page pool: a queue restart starts the new queue before it frees the old pool, so the old pool releases chunks while the new NAPI allocates. Teardown can be deferred to a work item, and the initial fill, bind and unbind run in process context. A driver that fills its new rings in ndo_queue_mem_alloc() even has two pools on one FILL ring.

However, in steady state only in NAPI, once per refill, so the lock is uncontended. I haven't been able to see it in perf...

I'll list that in a comment.

Björn

#37 lore raw

Re: [PATCH net-next v1 04/11] xsk: Allocate UMEM chunks through page_pool

In reply to Björn Töpel
Quoted 150 lines · Björn Töpel

AF_XDP zero copy needs a second RX allocator in every driver. A page_pool driver can take UMEM chunks from a memory provider instead, and keep its refill, recycling and DMA sync code.

Each aligned chunk becomes a net_iov, whose address netmem_address() finds without calling the provider. Userspace may post a chunk that the kernel still owns, so the provider tracks the owner of each chunk and drops such FILL entries. Chunks that a page pool releases stay in the kernel for reuse. Nothing installs the provider yet.

---
 include/net/netmem.h |  25 ++++-
 include/net/xdp.h    |   2 +-
 net/xdp/Kconfig      |   1 +
 net/xdp/Makefile     |   2 +-
 net/xdp/xsk.h        |   6 ++
 net/xdp/xsk_pp.c     | 246 +++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 279 insertions(+), 3 deletions(-)
 create mode 100644 net/xdp/xsk_pp.c
include/net/netmem.h +24 -1
index b986ad616334..a3b67ef32b21 100644
@@ -69,6 +69,7 @@ DECLARE_STATIC_KEY_FALSE(page_pool_restricted);
 enum net_iov_type {
 	NET_IOV_DMABUF,
 	NET_IOV_IOURING,
+	NET_IOV_XSK,
 };
 
 /* A memory descriptor representing abstract networking I/O vectors.
@@ -107,6 +108,10 @@ struct net_iov_area {
 	size_t num_niovs;
 	/* Each net_iov covers 1 << niov_shift bytes. */
 	unsigned int niov_shift;
+	/* CPU address of the first net_iov, or NULL if the CPU cannot read
+	 * the area.
+	 */
+	void *vaddr;
 };
 
 static inline struct net_iov_area *net_iov_owner(const struct net_iov *niov)
@@ -119,6 +124,18 @@ static inline unsigned int net_iov_idx(const struct net_iov *niov)
 	return niov - net_iov_owner(niov)->niovs;
 }
 
+static inline void *net_iov_address(const struct net_iov *niov)
+{
+	const struct net_iov_area *area = net_iov_owner(niov);
+	unsigned long off;
+
+	if (!area->vaddr)
+		return NULL;
+
+	off = (unsigned long)net_iov_idx(niov) << area->niov_shift;
+	return area->vaddr + off;
+}
+
 /* Initialize a niov: stamp the owning area, the memory provider type.
  */
 static inline void net_iov_init(struct net_iov *niov,
@@ -345,10 +362,16 @@ static inline void *__netmem_address(netmem_ref netmem)
 	return page_address(__netmem_to_page(netmem));
 }
 
+/**
+ * netmem_address - get the CPU address of the memory behind @netmem
+ * @netmem: netmem to get the address of
+ *
+ * Return: the address, or NULL if the CPU cannot read @netmem.
+ */
 static inline void *netmem_address(netmem_ref netmem)
 {
 	if (netmem_is_net_iov(netmem))
-		return NULL;
+		return net_iov_address(netmem_to_net_iov(netmem));
 
 	return __netmem_address(netmem);
 }
include/net/xdp.h +1 -1
index 1105bb9e3292..5ab7802ac4e1 100644
@@ -368,7 +368,7 @@ 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) && !netmem_address(netmem)))
 		xdp_buff_set_frag_unreadable(xdp);
 
 	return true;
net/xdp/Kconfig +1 -0
index 71af2febe72a..c9c68d3b3712 100644
@@ -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
net/xdp/Makefile +1 -1
index 30cdc4315f42..6e9d60f9f7f1 100644
@@ -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_pp.o
 obj-$(CONFIG_XDP_SOCKETS_DIAG) += xsk_diag.o
net/xdp/xsk.h +6 -0
index 7c811b5cce76..4dab7b9a1487 100644
@@ -34,6 +34,12 @@ static inline struct xdp_sock *xdp_sk(struct sock *sk)
 
 void xsk_map_try_sock_delete(struct xsk_map *map, struct xdp_sock *xs,
 			     struct xdp_sock __rcu **map_entry);
+struct xsk_pp;
+
+extern const struct memory_provider_ops xsk_pp_ops;
+
+struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool);
+void xsk_pp_put(struct xsk_pp *pp);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
 			u16 queue_id);
net/xdp/xsk_pp.c new file +11 -0
new file mode 100644
index 000000000000..fdd55265a6cd
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP UMEM as a page pool memory provider
+ *
+ * Each aligned UMEM chunk is a readable net_iov with one owner at a time:
+ *
+ *   userspace --FILL--> page pool --release--> reuse --alloc--> page pool
+ *       ^                   |
+ *       +-----RX ring-------+
+ */
+
+#include <net/page_pool/helpers.h>

net/xdp/xsk_pp.c line 21

Quoted 10 lines
net/xdp/xsk_pp.c new file +10 -0
+#include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
+
+#include "xsk.h"
+#include "xsk_queue.h"
+
+enum xsk_pp_chunk {
+	XSK_PP_USER,	/* owned by userspace */
+	XSK_PP_POOL,	/* owned by a page pool */
+	XSK_PP_REUSE,	/* on the reuse stack */

Can you explain more about that reuse/reuse_cnt? When is the chunk reused? How is it different from FILL->RX path?

#38 lore raw

Re: [PATCH net-next v1 04/11] xsk: Allocate UMEM chunks through page_pool

Quoted 24 lines · Stanislav Fomichev
Quoted 22 lines · Björn Töpel
net/xdp/xsk_pp.c new file +16 -0
new file mode 100644
index 000000000000..fdd55265a6cd
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP UMEM as a page pool memory provider
+ *
+ * Each aligned UMEM chunk is a readable net_iov with one owner at a time:
+ *
+ *   userspace --FILL--> page pool --release--> reuse --alloc--> page pool
+ *       ^                   |
+ *       +-----RX ring-------+
+ */
+
+#include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
+
+#include "xsk.h"
+#include "xsk_queue.h"
Quoted 8 lines

net/xdp/xsk_pp.c line 21

Quoted 5 lines
net/xdp/xsk_pp.c new file +5 -0
+
+enum xsk_pp_chunk {
+	XSK_PP_USER,	/* owned by userspace */
+	XSK_PP_POOL,	/* owned by a page pool */
+	XSK_PP_REUSE,	/* on the reuse stack */

Can you explain more about that reuse/reuse_cnt? When is the chunk reused? How is it different from FILL->RX path?

FILL RX ring
USER ----------> POOL ---------------> USER

                   |  ^
   release_netmem  |  |  next refill,
                   v  |  before FILL

REUSE

POOL is a chunk in the page pool or on a driver ring. XDP_DROP, copied XDP_PASS and XDP_TX recycle it inside the page pool, so it stays POOL. FILL->RX is the only way back to userspace: an XSK redirect puts the chunk on the RX ring, and the flush (patch 7) marks it USER. Userspace posts it to FILL again.

REUSE is a chunk the page pool lets go of without a packet: when the pool is destroyed (queue restart, unbind), or its ring is full on a recycle. Userspace already gave it up, and the kernel can't post to FILL, so the next refill takes it before FILL. Same job as free_list in xsk_buff_pool. A FILL entry for a chunk the kernel holds is dropped.

I'll put that in the comment at the top of xsk_pp.c.

Björn

#39 lore raw

Re: [PATCH net-next v1 04/11] xsk: Allocate UMEM chunks through page_pool

Quoted 49 lines · Björn Töpel
Quoted 24 lines · Stanislav Fomichev
Quoted 22 lines · Björn Töpel
net/xdp/xsk_pp.c new file +16 -0
new file mode 100644
index 000000000000..fdd55265a6cd
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP UMEM as a page pool memory provider
+ *
+ * Each aligned UMEM chunk is a readable net_iov with one owner at a time:
+ *
+ *   userspace --FILL--> page pool --release--> reuse --alloc--> page pool
+ *       ^                   |
+ *       +-----RX ring-------+
+ */
+
+#include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
+
+#include "xsk.h"
+#include "xsk_queue.h"
Quoted 8 lines

net/xdp/xsk_pp.c line 21

Quoted 5 lines
net/xdp/xsk_pp.c new file +5 -0
+
+enum xsk_pp_chunk {
+	XSK_PP_USER,	/* owned by userspace */
+	XSK_PP_POOL,	/* owned by a page pool */
+	XSK_PP_REUSE,	/* on the reuse stack */

Can you explain more about that reuse/reuse_cnt? When is the chunk reused? How is it different from FILL->RX path?

FILL RX ring
USER ----------> POOL ---------------> USER

                   |  ^
   release_netmem  |  |  next refill,
                   v  |  before FILL

REUSE

POOL is a chunk in the page pool or on a driver ring. XDP_DROP, copied XDP_PASS and XDP_TX recycle it inside the page pool, so it stays POOL. FILL->RX is the only way back to userspace: an XSK redirect puts the chunk on the RX ring, and the flush (patch 7) marks it USER. Userspace posts it to FILL again.

Quoted 7 lines

REUSE is a chunk the page pool lets go of without a packet: when the pool is destroyed (queue restart, unbind), or its ring is full on a recycle. Userspace already gave it up, and the kernel can't post to FILL, so the next refill takes it before FILL. Same job as free_list in xsk_buff_pool. A FILL entry for a chunk the kernel holds is dropped.

I'll put that in the comment at the top of xsk_pp.c.

Yes, that helps a lot, thanks!

#40 lore raw

Re: [PATCH net-next v1 04/11] xsk: Allocate UMEM chunks through page_pool

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] The patch adds NET_IOV_XSK, a net_iov type the CPU can read:
net_iov_address() returns area->vaddr + (idx << niov_shift), and…
- [Low] The kernel-doc of __netmem_address() (include/net/netmem.h) still describes header buffers as the standard case of always-page-backed…

--

xsk: Allocate UMEM chunks through page_pool

This patch adds an AF_XDP memory provider for page_pool. Each aligned UMEM chunk becomes a CPU-readable net_iov of the new type NET_IOV_XSK, and netmem_address() can now return an address for it. The provider tracks which owner holds each chunk, and keeps chunks released by a page pool on an internal reuse stack.

include/net/netmem.h DECLARE_STATIC_KEY_FALSE(page_pool_restricted); · line 75

Quoted 12 lines
include/net/netmem.h +1 -0
index b986ad616334b..a3b67ef32b218 100644
@@ -69,6 +69,7 @@ DECLARE_STATIC_KEY_FALSE(page_pool_restricted);
 enum net_iov_type {
 	NET_IOV_DMABUF,
 	NET_IOV_IOURING,
+	NET_IOV_XSK,
 };
 
 /* A memory descriptor representing abstract networking I/O vectors.

[Severity: Low]
The struct net_iov kernel-doc just below this enum still says:

* Examples include imported dmabuf memory and imported io_uring memory. See
* net_iov_type for all the supported types. While current net_iov types are
* unreadable by the CPU, net_iov has no inherent restrictions and may be

NET_IOV_XSK is readable by the CPU. xsk_pp_create() sets pp->area.vaddr = pool->addrs, so net_iov_address() returns area->vaddr + (idx << niov_shift), and netmem_address() is no longer NULL for every in-tree net_iov.

Documentation/networking/netmem.rst has the same problem. Its "Decouple net_iov from unreadability" section still says that in-tree net_iov implementations are unreadable by the CPU and that netmem_address() returns NULL for them.

Should both texts be updated to list XSK UMEM as a readable net_iov type? Neither has changed by the last commit of the series, "eth: fbnic:
Support AF_XDP page pool zero copy".

[ ... ]

include/net/netmem.h static inline void *__netmem_address(netmem_ref netmem) · line 364

Quoted 4 lines
include/net/netmem.h +0 -0
@@ -345,10 +362,16 @@ static inline void *__netmem_address(netmem_ref netmem)
 	return page_address(__netmem_to_page(netmem));
 }
 

[Severity: Low]
The kernel-doc for __netmem_address() above still uses a header buffer as its example of netmem that is always page-backed:

* Unsafe version of netmem_address(). When @netmem is always page-backed,
* e.g. when it's a header buffer, performs faster and generates smaller
* object code (no check for the LSB). When @netmem points to IOV, provokes
* undefined behaviour.

memory_provider.h says MP_CAP_READABLE providers "may back header page pools". xsk_pp is the first provider that is both net_iov based and MP_CAP_READABLE.

xsk_pp_init() does not reject header pools, and xsk_pp_alloc_netmems() only hands out NET_IOV_XSK net_iovs. Later in the series, "xsk: Install UMEM page pool providers in the core" requires the readable provider to back the header pool.

A driver that follows this doc could call __netmem_address() on a header buffer of an xsk_pp backed queue. Would it get a garbage pointer back?

No in-tree caller does this today; fbnic uses netmem_address(). Should the "e.g. when it's a header buffer" wording be updated, though?

Quoted 14 lines
include/net/netmem.h +7 -1
+/**
+ * netmem_address - get the CPU address of the memory behind @netmem
+ * @netmem: netmem to get the address of
+ *
+ * Return: the address, or NULL if the CPU cannot read @netmem.
+ */
 static inline void *netmem_address(netmem_ref netmem)
 {
 	if (netmem_is_net_iov(netmem))
-		return NULL;
+		return net_iov_address(netmem_to_net_iov(netmem));
 
 	return __netmem_address(netmem);
 }

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261110102039.1002605-1-bjorn%40kernel.org
#41 lore raw

Re: [PATCH net-next v1 04/11] xsk: Allocate UMEM chunks through page_pool

In reply to Björn Töpel
Quoted 87 lines · Björn Töpel

AF_XDP zero copy needs a second RX allocator in every driver. A page_pool driver can take UMEM chunks from a memory provider instead, and keep its refill, recycling and DMA sync code.

Each aligned chunk becomes a net_iov, whose address netmem_address() finds without calling the provider. Userspace may post a chunk that the kernel still owns, so the provider tracks the owner of each chunk and drops such FILL entries. Chunks that a page pool releases stay in the kernel for reuse. Nothing installs the provider yet.

---
 include/net/netmem.h |  25 ++++-
 include/net/xdp.h    |   2 +-
 net/xdp/Kconfig      |   1 +
 net/xdp/Makefile     |   2 +-
 net/xdp/xsk.h        |   6 ++
 net/xdp/xsk_pp.c     | 246 +++++++++++++++++++++++++++++++++++++++++++
 6 files changed, 279 insertions(+), 3 deletions(-)
 create mode 100644 net/xdp/xsk_pp.c
include/net/netmem.h +24 -1
index b986ad616334..a3b67ef32b21 100644
@@ -69,6 +69,7 @@ DECLARE_STATIC_KEY_FALSE(page_pool_restricted);
 enum net_iov_type {
        NET_IOV_DMABUF,
        NET_IOV_IOURING,
+       NET_IOV_XSK,
 };
 
 /* A memory descriptor representing abstract networking I/O vectors.
@@ -107,6 +108,10 @@ struct net_iov_area {
        size_t num_niovs;
        /* Each net_iov covers 1 << niov_shift bytes. */
        unsigned int niov_shift;
+       /* CPU address of the first net_iov, or NULL if the CPU cannot read
+        * the area.
+        */
+       void *vaddr;
 };
 
 static inline struct net_iov_area *net_iov_owner(const struct net_iov *niov)
@@ -119,6 +124,18 @@ static inline unsigned int net_iov_idx(const struct net_iov *niov)
        return niov - net_iov_owner(niov)->niovs;
 }
 
+static inline void *net_iov_address(const struct net_iov *niov)
+{
+       const struct net_iov_area *area = net_iov_owner(niov);
+       unsigned long off;
+
+       if (!area->vaddr)
+               return NULL;
+
+       off = (unsigned long)net_iov_idx(niov) << area->niov_shift;
+       return area->vaddr + off;
+}
+
 /* Initialize a niov: stamp the owning area, the memory provider type.
  */
 static inline void net_iov_init(struct net_iov *niov,
@@ -345,10 +362,16 @@ static inline void *__netmem_address(netmem_ref netmem)
        return page_address(__netmem_to_page(netmem));
 }
 
+/**
+ * netmem_address - get the CPU address of the memory behind @netmem
+ * @netmem: netmem to get the address of
+ *
+ * Return: the address, or NULL if the CPU cannot read @netmem.
+ */
 static inline void *netmem_address(netmem_ref netmem)
 {
        if (netmem_is_net_iov(netmem))
-               return NULL;
+               return net_iov_address(netmem_to_net_iov(netmem));
 
        return __netmem_address(netmem);
 }
include/net/xdp.h +0 -0
index 1105bb9e3292..5ab7802ac4e1 100644

include/net/xdp.h static inline bool xdp_buff_add_frag(struct xdp_buff *xdp, netmem_ref netmem, · line 373

Quoted 7 lines
include/net/xdp.h +1 -1
@@ -368,7 +368,7 @@ 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) && !netmem_address(netmem)))
                xdp_buff_set_frag_unreadable(xdp);
 

netmem_is_net_iov() check became redundant.

Quoted 58 lines
include/net/xdp.h +0 -0
        return true;
net/xdp/Kconfig +1 -0
index 71af2febe72a..c9c68d3b3712 100644
@@ -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
net/xdp/Makefile +1 -1
index 30cdc4315f42..6e9d60f9f7f1 100644
@@ -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_pp.o
 obj-$(CONFIG_XDP_SOCKETS_DIAG) += xsk_diag.o
net/xdp/xsk.h +6 -0
index 7c811b5cce76..4dab7b9a1487 100644
@@ -34,6 +34,12 @@ static inline struct xdp_sock *xdp_sk(struct sock *sk)
 
 void xsk_map_try_sock_delete(struct xsk_map *map, struct xdp_sock *xs,
                             struct xdp_sock __rcu **map_entry);
+struct xsk_pp;
+
+extern const struct memory_provider_ops xsk_pp_ops;
+
+struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool);
+void xsk_pp_put(struct xsk_pp *pp);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
                        u16 queue_id);
net/xdp/xsk_pp.c new file +12 -0
new file mode 100644
index 000000000000..fdd55265a6cd
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP UMEM as a page pool memory provider
+ *
+ * Each aligned UMEM chunk is a readable net_iov with one owner at a time:
+ *
+ *   userspace --FILL--> page pool --release--> reuse --alloc--> page pool
+ *       ^                   |
+ *       +-----RX ring-------+
+ */
+
+#include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>

net/xdp/xsk_pp.c line 22

Quoted 10 lines
net/xdp/xsk_pp.c new file +10 -0
+#include <net/xdp_sock_drv.h>
+
+#include "xsk.h"
+#include "xsk_queue.h"
+
+enum xsk_pp_chunk {
+       XSK_PP_USER,    /* owned by userspace */
+       XSK_PP_POOL,    /* owned by a page pool */
+       XSK_PP_REUSE,   /* on the reuse stack */
+};

maybe should be xsk_mp_chunk.

But also, why is this 3? Usually the mp's track allocated and free. I assume PP_REUSE is actually free, but I'm curious why it matters to your mp whether the pool or the userspace holds the memory (or whether the net stack holds it. Can't it hold it?)

net/xdp/xsk_pp.c line 24

Quoted 2 lines
net/xdp/xsk_pp.c new file +2 -0
+
+struct xsk_pp {

maybe xsk_mp? this is a memory provider right?

Quoted 223 lines
net/xdp/xsk_pp.c new file +222 -1
+       struct net_iov_area area;
+       struct xsk_buff_pool *pool;
+       /* Protects fq, state and reuse */
+       spinlock_t lock;
+       struct xsk_queue *fq;
+       refcount_t refs;
+       u32 nr_pools;
+       bool dma_need_sync;
+       u8 *state;
+       u32 reuse_cnt;
+       u32 reuse[];
+};
+
+static void xsk_pp_free(struct xsk_pp *pp)
+{
+       kvfree(pp->state);
+       kvfree(pp->area.niovs);
+       kvfree(pp);
+}
+
+void xsk_pp_put(struct xsk_pp *pp)
+{
+       if (refcount_dec_and_test(&pp->refs))
+               xsk_pp_free(pp);
+}
+
+/* @pool must be DMA mapped and have aligned chunks. The provider must be
+ * the only consumer of its FILL ring.
+ */
+struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool)
+{
+       struct net_iov *niov;
+       struct xsk_pp *pp;
+       dma_addr_t dma;
+       u32 i;
+
+       pp = kvzalloc_flex(*pp, reuse, pool->heads_cnt, GFP_KERNEL_ACCOUNT);
+       if (!pp)
+               return ERR_PTR(-ENOMEM);
+
+       pp->area.niovs = kvzalloc_objs(*pp->area.niovs, pool->heads_cnt,
+                                      GFP_KERNEL_ACCOUNT);
+       pp->state = kvzalloc(pool->heads_cnt, GFP_KERNEL_ACCOUNT);
+       if (!pp->area.niovs || !pp->state) {
+               xsk_pp_free(pp);
+               return ERR_PTR(-ENOMEM);
+       }
+
+       pp->area.num_niovs = pool->heads_cnt;
+       pp->area.niov_shift = pool->chunk_shift;
+       pp->area.vaddr = pool->addrs;
+       pp->pool = pool;
+       pp->fq = pool->fq;
+       pp->dma_need_sync = dma_dev_need_sync(pool->dev);
+       spin_lock_init(&pp->lock);
+       refcount_set(&pp->refs, 1);
+
+       for (i = 0; i < pp->area.num_niovs; i++) {
+               niov = &pp->area.niovs[i];
+               dma = xp_raw_get_dma(pool, (u64)i << pool->chunk_shift);
+               net_iov_init(niov, &pp->area, NET_IOV_XSK);
+               if (net_mp_niov_set_dma_addr(niov, dma)) {
+                       xsk_pp_free(pp);
+                       return ERR_PTR(-ERANGE);
+               }
+       }
+
+       return pp;
+}
+
+static int xsk_pp_init(struct page_pool *pool)
+{
+       struct xsk_pp *pp = pool->mp_priv;
+
+       if (pool->p.order || pool->p.dma_dir != DMA_BIDIRECTIONAL ||
+           pool->p.dev != pp->pool->dev)
+               return -EINVAL;
+       if (pool->p.max_len > pp->pool->chunk_size ||
+           pool->p.offset > pp->pool->chunk_size - pool->p.max_len)
+               return -EINVAL;
+
+       refcount_inc(&pp->refs);
+       spin_lock_bh(&pp->lock);
+       pp->nr_pools++;
+       spin_unlock_bh(&pp->lock);
+       return 0;
+}
+
+static void xsk_pp_destroy(struct page_pool *pool)
+{
+       struct xsk_pp *pp = pool->mp_priv;
+
+       spin_lock_bh(&pp->lock);
+       pp->nr_pools--;
+       spin_unlock_bh(&pp->lock);
+       xsk_pp_put(pp);
+}
+
+static bool xsk_pp_claim(struct xsk_pp *pp, u32 idx, enum xsk_pp_chunk from)
+{
+       lockdep_assert_held(&pp->lock);
+
+       if (pp->state[idx] != from)
+               return false;
+
+       pp->state[idx] = XSK_PP_POOL;
+       return true;
+}
+
+static u32 xsk_pp_alloc_reuse(struct xsk_pp *pp, netmem_ref *netmems, u32 max)
+{
+       u32 idx, n = 0;
+
+       while (n < max && pp->reuse_cnt) {
+               idx = pp->reuse[--pp->reuse_cnt];
+               if (WARN_ON_ONCE(!xsk_pp_claim(pp, idx, XSK_PP_REUSE)))
+                       continue;
+               netmems[n++] = net_iov_to_netmem(&pp->area.niovs[idx]);
+       }
+
+       return n;
+}
+
+static u32 xsk_pp_alloc_fill(struct xsk_pp *pp, netmem_ref *netmems, u32 max)
+{
+       struct xsk_buff_pool *pool = pp->pool;
+       struct xsk_queue *fq = pp->fq;
+       u32 i, entries, cons, idx, n = 0;
+       u64 addr;
+
+       if (!fq || !max)
+               return 0;
+
+       entries = xskq_cons_nb_entries(fq, max);
+       if (!entries) {
+               fq->queue_empty_descs++;
+               return 0;
+       }
+
+       cons = fq->cached_cons;
+       for (i = 0; i < entries; i++) {
+               __xskq_cons_read_addr_unchecked(fq, cons++, &addr);
+               addr &= pool->chunk_mask;
+               idx = addr >> pp->area.niov_shift;
+               if (unlikely(addr >= pool->addrs_cnt ||
+                            !xsk_pp_claim(pp, idx, XSK_PP_USER))) {
+                       fq->invalid_descs++;
+                       continue;
+               }
+               netmems[n++] = net_iov_to_netmem(&pp->area.niovs[idx]);
+       }
+
+       xskq_cons_release_n(fq, entries);
+       __xskq_cons_release(fq);
+       return n;
+}
+
+static netmem_ref xsk_pp_alloc_netmems(struct page_pool *pool, gfp_t gfp)
+{
+       netmem_ref *netmems = pool->alloc.cache;
+       struct xsk_pp *pp = pool->mp_priv;
+       struct net_iov *niov;
+       dma_addr_t dma;
+       u32 i, n;
+
+       if (WARN_ON_ONCE(pool->alloc.count))
+               return 0;
+
+       spin_lock_bh(&pp->lock);
+       n = xsk_pp_alloc_reuse(pp, netmems, PP_ALLOC_CACHE_REFILL);
+       n += xsk_pp_alloc_fill(pp, netmems + n, PP_ALLOC_CACHE_REFILL - n);
+       spin_unlock_bh(&pp->lock);
+       if (!n)
+               return 0;
+
+       for (i = 0; i < n; i++) {
+               niov = netmem_to_net_iov(netmems[i]);
+               dma = page_pool_get_dma_addr_netmem(netmems[i]);
+               if (pp->dma_need_sync)
+                       dma_sync_single_range_for_device(pool->p.dev, dma,
+                                                        pool->p.offset,
+                                                        pool->p.max_len,
+                                                        pool->p.dma_dir);
+               net_mp_niov_set_page_pool(pool, niov);
+       }
+
+       pool->alloc.count = n - 1;
+       return netmems[n - 1];
+}
+
+static bool xsk_pp_release_netmem(struct page_pool *pool, netmem_ref netmem)
+{
+       struct net_iov *niov = netmem_to_net_iov(netmem);
+       struct xsk_pp *pp = pool->mp_priv;
+       u32 idx = net_iov_idx(niov);
+
+       spin_lock_bh(&pp->lock);
+       net_mp_niov_clear_page_pool(niov);
+       if (!WARN_ON_ONCE(pp->state[idx] != XSK_PP_POOL ||
+                         pp->reuse_cnt == pp->area.num_niovs)) {
+               pp->state[idx] = XSK_PP_REUSE;
+               pp->reuse[pp->reuse_cnt++] = idx;
+       }
+       spin_unlock_bh(&pp->lock);
+
+       return false;
+}
+
+static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
+                         struct netdev_rx_queue *rxq)
+{
+       return 0;
+}
+
+const struct memory_provider_ops xsk_pp_ops = {
+       .init           = xsk_pp_init,
+       .destroy        = xsk_pp_destroy,
+       .alloc_netmems  = xsk_pp_alloc_netmems,
+       .release_netmem = xsk_pp_release_netmem,
+       .nl_fill        = xsk_pp_nl_fill,
+       .caps           = MP_CAP_READABLE,
+};
--
Quoted 2 lines

2.56.0

--
Thanks,
Mina

#42 lore raw

Re: [PATCH net-next v1 04/11] xsk: Allocate UMEM chunks through page_pool

Quoted 8 lines · Mina Almasry
Quoted 6 lines · Björn Töpel
include/net/xdp.h +0 -0
index 1105bb9e3292..5ab7802ac4e1 100644
@@ -368,7 +368,7 @@ static inline bool xdp_buff_add_frag(struct xdp_buff *xdp, netmem_ref netmem,
 
Quoted 9 lines

include/net/xdp.h static inline bool xdp_buff_add_frag(struct xdp_buff *xdp, netmem_ref netmem, · line 373

Quoted 6 lines
include/net/xdp.h +1 -1
        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) && !netmem_address(netmem)))
                xdp_buff_set_frag_unreadable(xdp);
 

netmem_is_net_iov() check became redundant.

Hmm, not quite... netmem_address() is also NULL for a highmem page without a mapping, and the stack reads those through kmap, so they aren't unreadable. The net_iov test keeps them out. I'll add a comment.

Quoted 31 lines
Quoted 18 lines
net/xdp/xsk_pp.c new file +12 -0
new file mode 100644
index 000000000000..fdd55265a6cd
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP UMEM as a page pool memory provider
+ *
+ * Each aligned UMEM chunk is a readable net_iov with one owner at a time:
+ *
+ *   userspace --FILL--> page pool --release--> reuse --alloc--> page pool
+ *       ^                   |
+ *       +-----RX ring-------+
+ */
+
+#include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>

net/xdp/xsk_pp.c line 22

Quoted 10 lines
net/xdp/xsk_pp.c new file +10 -0
+#include <net/xdp_sock_drv.h>
+
+#include "xsk.h"
+#include "xsk_queue.h"
+
+enum xsk_pp_chunk {
+       XSK_PP_USER,    /* owned by userspace */
+       XSK_PP_POOL,    /* owned by a page pool */
+       XSK_PP_REUSE,   /* on the reuse stack */
+};

maybe should be xsk_mp_chunk.

Quoted 4 lines

But also, why is this 3? Usually the mp's track allocated and free. I assume PP_REUSE is actually free, but I'm curious why it matters to your mp whether the pool or the userspace holds the memory (or whether the net stack holds it. Can't it hold it?)

REUSE is free, yes. USER and POOL are both allocated, but userspace gives chunks back by writing addresses to FILL, and it can write any address, also one of a chunk the kernel still owns. Taking that entry would hand the device the same chunk twice. So the provider only takes FILL entries for chunks in USER, and drops the rest. io_uring zcrx checks the same with user_refs, and devmem with the socket's token xarray.

The stack can't hold a chunk, see my reply on patch 3.

Quoted 4 lines

net/xdp/xsk_pp.c line 24

Quoted 2 lines
net/xdp/xsk_pp.c new file +2 -0
+
+struct xsk_pp {

maybe xsk_mp? this is a memory provider right?

Yes, I'll rename it to xsk_mp, the enum too.

Björn

#43 lore raw

Re: [PATCH net-next v1 04/11] xsk: Allocate UMEM chunks through page_pool

Quoted 21 lines · Björn Töpel
Quoted 8 lines · Mina Almasry
Quoted 6 lines · Björn Töpel
include/net/xdp.h +0 -0
index 1105bb9e3292..5ab7802ac4e1 100644
@@ -368,7 +368,7 @@ static inline bool xdp_buff_add_frag(struct xdp_buff *xdp, netmem_ref netmem,
 
Quoted 9 lines

include/net/xdp.h static inline bool xdp_buff_add_frag(struct xdp_buff *xdp, netmem_ref netmem, · line 373

Quoted 6 lines
include/net/xdp.h +1 -1
        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) && !netmem_address(netmem)))
                xdp_buff_set_frag_unreadable(xdp);
 

netmem_is_net_iov() check became redundant.

Quoted 4 lines

Hmm, not quite... netmem_address() is also NULL for a highmem page without a mapping, and the stack reads those through kmap, so they aren't unreadable. The net_iov test keeps them out. I'll add a comment.

Oh. I missed that. There are a bunch of docs actually that explicitly wrongly say to use netmem_address to tell if the memory si readable.

Can you, in a separate patch, add a netmem_readable() helper and update the docs (and if possible code places) that checked net-iov when they were really checks for readability? Now that you're adding readable net-iovs, all that assumption break right?

Quoted 36 lines
Quoted 31 lines
Quoted 18 lines
net/xdp/xsk_pp.c new file +12 -0
new file mode 100644
index 000000000000..fdd55265a6cd
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP UMEM as a page pool memory provider
+ *
+ * Each aligned UMEM chunk is a readable net_iov with one owner at a time:
+ *
+ *   userspace --FILL--> page pool --release--> reuse --alloc--> page pool
+ *       ^                   |
+ *       +-----RX ring-------+
+ */
+
+#include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>

net/xdp/xsk_pp.c line 22

Quoted 10 lines
net/xdp/xsk_pp.c new file +10 -0
+#include <net/xdp_sock_drv.h>
+
+#include "xsk.h"
+#include "xsk_queue.h"
+
+enum xsk_pp_chunk {
+       XSK_PP_USER,    /* owned by userspace */
+       XSK_PP_POOL,    /* owned by a page pool */
+       XSK_PP_REUSE,   /* on the reuse stack */
+};

maybe should be xsk_mp_chunk.

Quoted 4 lines

But also, why is this 3? Usually the mp's track allocated and free. I assume PP_REUSE is actually free, but I'm curious why it matters to your mp whether the pool or the userspace holds the memory (or whether the net stack holds it. Can't it hold it?)

Quoted 8 lines

REUSE is free, yes. USER and POOL are both allocated, but userspace gives chunks back by writing addresses to FILL, and it can write any address, also one of a chunk the kernel still owns. Taking that entry would hand the device the same chunk twice. So the provider only takes FILL entries for chunks in USER, and drops the rest. io_uring zcrx checks the same with user_refs, and devmem with the socket's token xarray.

Sounds like devmem choose to do extra-pp-refs on netmems given to userspace, io-uring choose to give extra user_refs for netmems given to userspace, and you have choosen to do something new? I need to read the patches more thoroughly to understand.

--
Thanks,
Mina

#44 lore raw

Re: [PATCH net-next v1 04/11] xsk: Allocate UMEM chunks through page_pool

Quoted 28 lines · Mina Almasry
Quoted 21 lines · Björn Töpel
Quoted 8 lines · Mina Almasry
Quoted 6 lines · Björn Töpel
include/net/xdp.h +0 -0
index 1105bb9e3292..5ab7802ac4e1 100644
@@ -368,7 +368,7 @@ static inline bool xdp_buff_add_frag(struct xdp_buff *xdp, netmem_ref netmem,
 
Quoted 9 lines

include/net/xdp.h static inline bool xdp_buff_add_frag(struct xdp_buff *xdp, netmem_ref netmem, · line 373

Quoted 6 lines
include/net/xdp.h +1 -1
        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) && !netmem_address(netmem)))
                xdp_buff_set_frag_unreadable(xdp);
 

netmem_is_net_iov() check became redundant.

Quoted 4 lines

Hmm, not quite... netmem_address() is also NULL for a highmem page without a mapping, and the stack reads those through kmap, so they aren't unreadable. The net_iov test keeps them out. I'll add a comment.

Quoted 7 lines

Oh. I missed that. There are a bunch of docs actually that explicitly wrongly say to use netmem_address to tell if the memory si readable.

Can you, in a separate patch, add a netmem_readable() helper and update the docs (and if possible code places) that checked net-iov when they were really checks for readability? Now that you're adding readable net-iovs, all that assumption break right?

Uhm, yes. I'll cook a separate patch that adds netmem_readable().

Quoted 45 lines
Quoted 36 lines
Quoted 31 lines
Quoted 18 lines
net/xdp/xsk_pp.c new file +12 -0
new file mode 100644
index 000000000000..fdd55265a6cd
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP UMEM as a page pool memory provider
+ *
+ * Each aligned UMEM chunk is a readable net_iov with one owner at a time:
+ *
+ *   userspace --FILL--> page pool --release--> reuse --alloc--> page pool
+ *       ^                   |
+ *       +-----RX ring-------+
+ */
+
+#include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>

net/xdp/xsk_pp.c line 22

Quoted 10 lines
net/xdp/xsk_pp.c new file +10 -0
+#include <net/xdp_sock_drv.h>
+
+#include "xsk.h"
+#include "xsk_queue.h"
+
+enum xsk_pp_chunk {
+       XSK_PP_USER,    /* owned by userspace */
+       XSK_PP_POOL,    /* owned by a page pool */
+       XSK_PP_REUSE,   /* on the reuse stack */
+};

maybe should be xsk_mp_chunk.

Quoted 4 lines

But also, why is this 3? Usually the mp's track allocated and free. I assume PP_REUSE is actually free, but I'm curious why it matters to your mp whether the pool or the userspace holds the memory (or whether the net stack holds it. Can't it hold it?)

Quoted 8 lines

REUSE is free, yes. USER and POOL are both allocated, but userspace gives chunks back by writing addresses to FILL, and it can write any address, also one of a chunk the kernel still owns. Taking that entry would hand the device the same chunk twice. So the provider only takes FILL entries for chunks in USER, and drops the rest. io_uring zcrx checks the same with user_refs, and devmem with the socket's token xarray.

Quoted 4 lines

Sounds like devmem choose to do extra-pp-refs on netmems given to userspace, io-uring choose to give extra user_refs for netmems given to userspace, and you have choosen to do something new? I need to read the patches more thoroughly to understand.

It is close to io_uring's scheme, but simpler. io_uring counts user refs per buffer, because one buffer can reach userspace in several pieces, each returned on its own, and it keeps a page pool ref while userspace holds it. A UMEM chunk is never split, so userspace holds it at most once, and one state per chunk replaces the counter: USER means userspace has it, REUSE is the free list. The chunk also leaves its page pool before userspace gets it, so no page pool ref is held meanwhile. When userspace returns a chunk on the FILL ring, we take it only if it is in USER state, so userspace cannot return a chunk the kernel still uses.

Björn

#45 lore raw

PATCH 5/11 xsk: Install UMEM page pool providers in the core

In reply to Björn Töpel

A page_pool driver should not need its own AF_XDP setup. When it sets netdev_queue_mgmt_ops.xsk_page_pool, a zero-copy bind installs the UMEM provider through the queue API, as devmem and io_uring do. The driver only judges the chunk size, headroom and multi-buffer mode against its MTU and XDP program, in XDP_VALIDATE_XSK_POOL; MTU and program changes of a bound device get the same check. The UMEM headroom belongs to the socket, so the queue gets it as rx_headroom, next to rx_page_size.

After a queue restart, the core checks that the new page pools took the provider. A readable provider must back the header pool, where an unsplit packet lands, so pools declare the buffers they supply in rx_roles. The old queue's pools carry the same provider during the check, so a per-queue generation, mp_gen, tells the new ones apart.

Generic XDP runs outside the queue NAPI, so it cannot feed the socket.

The provider needs no xdp_buff_xsk per chunk. The buffer pool allocates them only for copy mode and driver zero copy, which saves 128 bytes per chunk.

---
 include/linux/netdevice.h     |   8 ++
 include/net/netdev_queues.h   |  12 ++
 include/net/netdev_rx_queue.h |   2 +
 include/net/page_pool/types.h |  12 ++
 include/net/xdp_sock.h        |   4 +
 include/net/xdp_sock_drv.h    |  45 +++++++
 include/net/xsk_buff_pool.h   |   3 +
 net/core/dev.c                |  16 +++
 net/core/netdev_config.c      |   2 +
 net/core/netdev_rx_queue.c    |   9 +-
 net/core/page_pool.c          |   6 +-
 net/core/page_pool_user.c     |  25 ++--
 net/xdp/xsk.h                 |   7 +-
 net/xdp/xsk_buff_pool.c       |  69 ++++++++---
 net/xdp/xsk_pp.c              | 221 ++++++++++++++++++++++++++++++++++
 15 files changed, 410 insertions(+), 31 deletions(-)
include/linux/netdevice.h +8 -0
index 435be7880d7e..11e51e684003 100644
@@ -77,6 +77,7 @@ struct udp_tunnel_info;
 struct udp_tunnel_nic_info;
 struct udp_tunnel_nic;
 struct bpf_prog;
+struct xsk_rx_check;
 struct xdp_buff;
 struct xdp_frame;
 struct xdp_metadata_ops;
@@ -1010,6 +1011,8 @@ enum bpf_netdev_command {
 	BPF_OFFLOAD_MAP_ALLOC,
 	BPF_OFFLOAD_MAP_FREE,
 	XDP_SETUP_XSK_POOL,
+	/* Check an AF_XDP page pool setup, see netdev_queue_mgmt_ops */
+	XDP_VALIDATE_XSK_POOL,
 };
 
 struct bpf_prog_offload_ops;
@@ -1048,6 +1051,11 @@ struct netdev_bpf {
 			struct xsk_buff_pool *pool;
 			u16 queue_id;
 		} xsk;
+		/* XDP_VALIDATE_XSK_POOL */
+		struct {
+			const struct xsk_rx_check *check;
+			struct netlink_ext_ack *extack;
+		} xsk_check;
 	};
 };
 
include/net/netdev_queues.h +12 -0
index c5335e935b7d..ad5f0420c21d 100644
@@ -45,12 +45,15 @@ struct netdev_config {
 /**
  * struct netdev_queue_config - rendered configuration for an RX queue
  * @rx_page_size:	Size of one RX page-pool allocation.
+ * @rx_headroom:	Space before the packet in a head buffer, including
+ *			XDP_PACKET_HEADROOM. Zero selects the driver default.
  * @rx_ring_size:	Configured size of the regular RX ring.
  * @rx_mini_ring_size:	Configured size of the RX mini ring.
  * @rx_jumbo_ring_size:	Configured size of the RX jumbo ring.
  */
 struct netdev_queue_config {
 	u32	rx_page_size;
+	u32	rx_headroom;
 	u32	rx_ring_size;
 	u32	rx_mini_ring_size;
 	u32	rx_jumbo_ring_size;
@@ -156,6 +159,8 @@ void netdev_stat_queue_sum(struct net_device *netdev,
 enum {
 	/* The queue checks and honours the page size qcfg parameter */
 	QCFG_RX_PAGE_SIZE	= 0x1,
+	/* The queue checks and honours the headroom qcfg parameter */
+	QCFG_RX_HEADROOM	= 0x2,
 };
 
 /**
@@ -199,6 +204,12 @@ enum {
  *
  * @supported_params:	Bitmask of supported parameters, see QCFG_*.
  *
+ * @xsk_page_pool:	AF_XDP zero copy installs the UMEM as the page pool
+ *			memory provider of the RX queue. The driver selects it
+ *			with PP_FLAG_MEM_PROVIDER and PP_RX_ROLE_HEAD, honours
+ *			whole buffers and QCFG_RX_HEADROOM, and accepts or
+ *			rejects the setup in XDP_VALIDATE_XSK_POOL.
+ *
  * Note that @ndo_queue_mem_alloc and @ndo_queue_mem_free may be called while
  * the interface is closed. @ndo_queue_start and @ndo_queue_stop will only
  * be called for an interface which is open.
@@ -229,6 +240,7 @@ struct netdev_queue_mgmt_ops {
 				    struct netlink_ext_ack *extack);
 
 	unsigned int supported_params;
+	bool xsk_page_pool;
 };
 
 void netdev_queue_config(struct net_device *dev, int rxq,
include/net/netdev_rx_queue.h +2 -0
index 9415a94d333d..989120cbf452 100644
@@ -31,6 +31,8 @@ struct netdev_rx_queue {
 	struct napi_struct		*napi;
 	struct netdev_queue_config	qcfg;
 	struct pp_memory_provider_params mp_params;
+	/* stamps the page pools of each queue allocation */
+	u32				mp_gen;
 
 	/* If a queue is leased, then the lease pointer is always
 	 * valid. From the physical device it points to the virtual
include/net/page_pool/types.h +12 -0
index 0d48c05f1462..e9f3af91e305 100644
@@ -40,6 +40,12 @@
  */
 #define PP_FLAG_MEM_PROVIDER	BIT(4)
 
+/* RX buffers a page pool supplies, see page_pool_params.rx_roles */
+enum pp_rx_role {
+	PP_RX_ROLE_HEAD		= BIT(0),	/* packet headers */
+	PP_RX_ROLE_PAYLOAD	= BIT(1),	/* payload after header split */
+};
+
 #define PP_FLAG_ALL		(PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV | \
 				 PP_FLAG_SYSTEM_POOL | \
 				 PP_FLAG_ALLOW_UNREADABLE_NETMEM | \
@@ -94,6 +100,8 @@ struct pp_alloc_cache {
  * @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_MEM_PROVIDER.
+ * @rx_roles:	&enum pp_rx_role mask, for pools that select a memory
+ *		provider. Zero means payload buffers.
  */
 struct page_pool_params {
 	struct_group_tagged(page_pool_params_fast, fast,
@@ -110,6 +118,7 @@ struct page_pool_params {
 		struct net_device *netdev;
 		unsigned int queue_idx;
 		unsigned int	flags;
+		unsigned int	rx_roles;
 /* private: used by test code only */
 		void (*init_callback)(netmem_ref netmem, void *arg);
 		void *init_arg;
@@ -182,6 +191,7 @@ struct pp_memory_provider_params {
 	void *mp_priv;
 	const struct memory_provider_ops *mp_ops;
 	u32 rx_page_size;
+	u32 rx_headroom;
 };
 
 struct page_pool {
@@ -245,6 +255,8 @@ struct page_pool {
 
 	void *mp_priv;
 	const struct memory_provider_ops *mp_ops;
+	/* queue allocation that selected the provider */
+	u32 mp_gen;
 
 	struct xarray dma_mapped;
 
include/net/xdp_sock.h +4 -0
index 6e70b320b399..e0e22ef839e1 100644
@@ -19,6 +19,10 @@
 struct net_device;
 struct xsk_queue;
 struct xdp_buff;
+struct memory_provider_ops;
+
+/* The memory provider of AF_XDP page pool zero copy */
+extern const struct memory_provider_ops xsk_pp_ops;
 
 struct xdp_umem {
 	void *addrs;
include/net/xdp_sock_drv.h +45 -0

71 lines not on this page · raw message

include/net/xsk_buff_pool.h +3 -0
index 02e89350faf9..6d7cfdf99a8b 100644
@@ -11,6 +11,7 @@
 #include <net/xdp.h>
 
 struct xsk_buff_pool;
+struct xsk_pp;
 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;
+	/* page pool memory provider, see net/xdp/xsk_pp.c */
+	struct xsk_pp *pp;
 	struct work_struct work;
 	/* Protects generic receive in shared and non-shared umem mode. */
 	spinlock_t rx_lock;
net/core/dev.c +16 -0
index 663fe3e32ea0..7e985fb82488 100644
@@ -163,6 +163,7 @@
 #include <net/page_pool/types.h>
 #include <net/page_pool/helpers.h>
 #include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
 #include <net/rps.h>
 #include <linux/phy_link_topology.h>
 
@@ -10535,6 +10536,8 @@ u8 dev_xdp_sb_prog_count(struct net_device *dev)
 
 int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 {
+	int err;
+
 	if (!dev->netdev_ops->ndo_bpf)
 		return -EOPNOTSUPP;
 
@@ -10552,6 +10555,13 @@ int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 		return -EBUSY;
 	}
 
+	if (bpf->command == XDP_SETUP_PROG && bpf->prog) {
+		err = xsk_validate_dev(dev, dev->mtu, bpf->prog, XDP_MODE_DRV,
+				       bpf->extack);
+		if (err)
+			return err;
+	}
+
 	return dev->netdev_ops->ndo_bpf(dev, bpf);
 }
 EXPORT_SYMBOL_GPL(netif_xdp_propagate);
@@ -10629,6 +10639,12 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
 		return -EBUSY;
 	}
 
+	if (mode != XDP_MODE_HW && prog) {
+		err = xsk_validate_dev(dev, dev->mtu, prog, mode, extack);
+		if (err)
+			return err;
+	}
+
 	memset(&xdp, 0, sizeof(xdp));
 	xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
 	xdp.extack = extack;
net/core/netdev_config.c +2 -0
index 1975de42a60d..97e33764737b 100644
@@ -88,6 +88,8 @@ static int __netdev_queue_config(struct net_device *dev, int rxq_idx,
 	mpp = &__netif_get_rx_queue(dev, rxq_idx)->mp_params;
 	if (mpp->rx_page_size)
 		qcfg->rx_page_size = mpp->rx_page_size;
+	if (mpp->rx_headroom)
+		qcfg->rx_headroom = mpp->rx_headroom;
 	err = validate_cb(dev, qcfg, extack);
 	if (err)
 		return err;
net/core/netdev_rx_queue.c +8 -1
index 9e14a747f9b5..4e2f906fbc73 100644
@@ -6,6 +6,7 @@
 #include <net/netdev_queues.h>
 #include <net/netdev_rx_queue.h>
 #include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock.h>
 
 #include "dev.h"
 #include "page_pool_priv.h"
@@ -141,6 +142,7 @@ static int netdev_rx_queue_reconfig(struct net_device *dev,
 		goto err_free_new_mem;
 	}
 
+	rxq->mp_gen++;
 	err = qops->ndo_queue_mem_alloc(dev, qcfg_new, new_mem, rxq_idx);
 	if (err)
 		goto err_free_old_mem;
@@ -235,6 +237,10 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		NL_SET_ERR_MSG(extack, "device does not support: rx_page_size");
 		return -EOPNOTSUPP;
 	}
+	if (p->rx_headroom && !(qops->supported_params & QCFG_RX_HEADROOM)) {
+		NL_SET_ERR_MSG(extack, "device does not support: rx_headroom");
+		return -EOPNOTSUPP;
+	}
 
 	rxq = __netif_get_rx_queue(dev, rxq_idx);
 	if (rxq->mp_params.mp_ops) {
@@ -242,7 +248,8 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		return -EEXIST;
 	}
 #ifdef CONFIG_XDP_SOCKETS
-	if (rxq->pool) {
+	/* An AF_XDP pool owns the queue, unless it installs its provider. */
+	if (rxq->pool && p->mp_ops != &xsk_pp_ops) {
 		NL_SET_ERR_MSG(extack, "designated queue already in use by AF_XDP");
 		return -EBUSY;
 	}
net/core/page_pool.c +4 -2
index 8237fda598ab..e897e79d31f1 100644
@@ -215,7 +215,8 @@ bool netmem_can_retain(netmem_ref netmem)
 EXPORT_SYMBOL(netmem_can_retain);
 
 static int page_pool_select_mp(struct page_pool *pool,
-			       const struct pp_memory_provider_params *mpp)
+			       const struct pp_memory_provider_params *mpp,
+			       u32 rxq_mp_gen)
 {
 	const struct memory_provider_ops *ops = mpp->mp_ops;
 	unsigned int flags = pool->slow.flags;
@@ -234,6 +235,7 @@ static int page_pool_select_mp(struct page_pool *pool,
 
 	pool->mp_priv = mpp->mp_priv;
 	pool->mp_ops = ops;
+	pool->mp_gen = rxq_mp_gen;
 	return 0;
 }
 
@@ -326,7 +328,7 @@ static int page_pool_init(struct page_pool *pool,
 		netdev_assert_locked(pool->slow.netdev);
 		rxq = __netif_get_rx_queue(pool->slow.netdev,
 					   pool->slow.queue_idx);
-		err = page_pool_select_mp(pool, &rxq->mp_params);
+		err = page_pool_select_mp(pool, &rxq->mp_params, rxq->mp_gen);
 		if (err)
 			goto free_ptr_ring;
 	}
net/core/page_pool_user.c +17 -8
index f30f3779624c..b69da0f74756 100644
@@ -398,28 +398,37 @@ void page_pool_unlist(struct page_pool *pool)
 	mutex_unlock(&page_pools_lock);
 }
 
+/* Check that the queue allocation that just ran put the provider in every
+ * pool role it needs: headers for a readable provider, payload otherwise.
+ * Pools of earlier allocations do not count.
+ */
 int page_pool_check_memory_provider(struct net_device *dev,
 				    struct netdev_rx_queue *rxq)
 {
-	void *binding = rxq->mp_params.mp_priv;
+	const struct memory_provider_ops *ops = rxq->mp_params.mp_ops;
+	void *mp_priv = rxq->mp_params.mp_priv;
+	unsigned int need, have = 0;
 	struct page_pool *pool;
 	struct hlist_node *n;
 
-	if (!binding)
+	if (!mp_priv)
 		return 0;
 
+	need = PP_RX_ROLE_PAYLOAD;
+	if (ops->caps & MP_CAP_READABLE)
+		need = PP_RX_ROLE_HEAD;
+
 	mutex_lock(&page_pools_lock);
 	hlist_for_each_entry_safe(pool, n, &dev->page_pools, user.list) {
-		if (pool->mp_priv != binding)
+		if (pool->mp_priv != mp_priv || pool->mp_gen != rxq->mp_gen ||
+		    pool->slow.queue_idx != get_netdev_rx_queue_index(rxq))
 			continue;
 
-		if (pool->slow.queue_idx == get_netdev_rx_queue_index(rxq)) {
-			mutex_unlock(&page_pools_lock);
-			return 0;
-		}
+		have |= pool->slow.rx_roles ? : PP_RX_ROLE_PAYLOAD;
 	}
 	mutex_unlock(&page_pools_lock);
-	return -ENODATA;
+
+	return (have & need) == need ? 0 : -ENODATA;
 }
 
 static void page_pool_unreg_netdev_wipe(struct net_device *netdev)
net/xdp/xsk.h +5 -2
index 4dab7b9a1487..9699e9a499a3 100644
@@ -36,10 +36,13 @@ void xsk_map_try_sock_delete(struct xsk_map *map, struct xdp_sock *xs,
 			     struct xdp_sock __rcu **map_entry);
 struct xsk_pp;
 
-extern const struct memory_provider_ops xsk_pp_ops;
-
 struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool);
 void xsk_pp_put(struct xsk_pp *pp);
+bool xsk_pp_supported(struct net_device *dev);
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+		u16 queue_id);
+void xsk_pp_unbind(struct xsk_buff_pool *pool);
+int xp_alloc_heads(struct xsk_buff_pool *pool);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
 			u16 queue_id);
net/xdp/xsk_buff_pool.c +51 -18

127 lines not on this page · raw message

net/xdp/xsk_pp.c +221 -0

250 lines not on this page · raw message

Signature · 1 line
2.56.0
#46 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

Quoted 542 lines · Björn Töpel

A page_pool driver should not need its own AF_XDP setup. When it sets netdev_queue_mgmt_ops.xsk_page_pool, a zero-copy bind installs the UMEM provider through the queue API, as devmem and io_uring do. The driver only judges the chunk size, headroom and multi-buffer mode against its MTU and XDP program, in XDP_VALIDATE_XSK_POOL; MTU and program changes of a bound device get the same check. The UMEM headroom belongs to the socket, so the queue gets it as rx_headroom, next to rx_page_size.

After a queue restart, the core checks that the new page pools took the provider. A readable provider must back the header pool, where an unsplit packet lands, so pools declare the buffers they supply in rx_roles. The old queue's pools carry the same provider during the check, so a per-queue generation, mp_gen, tells the new ones apart.

Generic XDP runs outside the queue NAPI, so it cannot feed the socket.

The provider needs no xdp_buff_xsk per chunk. The buffer pool allocates them only for copy mode and driver zero copy, which saves 128 bytes per chunk.

---
 include/linux/netdevice.h     |   8 ++
 include/net/netdev_queues.h   |  12 ++
 include/net/netdev_rx_queue.h |   2 +
 include/net/page_pool/types.h |  12 ++
 include/net/xdp_sock.h        |   4 +
 include/net/xdp_sock_drv.h    |  45 +++++++
 include/net/xsk_buff_pool.h   |   3 +
 net/core/dev.c                |  16 +++
 net/core/netdev_config.c      |   2 +
 net/core/netdev_rx_queue.c    |   9 +-
 net/core/page_pool.c          |   6 +-
 net/core/page_pool_user.c     |  25 ++--
 net/xdp/xsk.h                 |   7 +-
 net/xdp/xsk_buff_pool.c       |  69 ++++++++---
 net/xdp/xsk_pp.c              | 221 ++++++++++++++++++++++++++++++++++
 15 files changed, 410 insertions(+), 31 deletions(-)
include/linux/netdevice.h +8 -0
index 435be7880d7e..11e51e684003 100644
@@ -77,6 +77,7 @@ struct udp_tunnel_info;
 struct udp_tunnel_nic_info;
 struct udp_tunnel_nic;
 struct bpf_prog;
+struct xsk_rx_check;
 struct xdp_buff;
 struct xdp_frame;
 struct xdp_metadata_ops;
@@ -1010,6 +1011,8 @@ enum bpf_netdev_command {
 	BPF_OFFLOAD_MAP_ALLOC,
 	BPF_OFFLOAD_MAP_FREE,
 	XDP_SETUP_XSK_POOL,
+	/* Check an AF_XDP page pool setup, see netdev_queue_mgmt_ops */
+	XDP_VALIDATE_XSK_POOL,
 };
 
 struct bpf_prog_offload_ops;
@@ -1048,6 +1051,11 @@ struct netdev_bpf {
 			struct xsk_buff_pool *pool;
 			u16 queue_id;
 		} xsk;
+		/* XDP_VALIDATE_XSK_POOL */
+		struct {
+			const struct xsk_rx_check *check;
+			struct netlink_ext_ack *extack;
+		} xsk_check;
 	};
 };
 
include/net/netdev_queues.h +12 -0
index c5335e935b7d..ad5f0420c21d 100644
@@ -45,12 +45,15 @@ struct netdev_config {
 /**
  * struct netdev_queue_config - rendered configuration for an RX queue
  * @rx_page_size:	Size of one RX page-pool allocation.
+ * @rx_headroom:	Space before the packet in a head buffer, including
+ *			XDP_PACKET_HEADROOM. Zero selects the driver default.
  * @rx_ring_size:	Configured size of the regular RX ring.
  * @rx_mini_ring_size:	Configured size of the RX mini ring.
  * @rx_jumbo_ring_size:	Configured size of the RX jumbo ring.
  */
 struct netdev_queue_config {
 	u32	rx_page_size;
+	u32	rx_headroom;
 	u32	rx_ring_size;
 	u32	rx_mini_ring_size;
 	u32	rx_jumbo_ring_size;
@@ -156,6 +159,8 @@ void netdev_stat_queue_sum(struct net_device *netdev,
 enum {
 	/* The queue checks and honours the page size qcfg parameter */
 	QCFG_RX_PAGE_SIZE	= 0x1,
+	/* The queue checks and honours the headroom qcfg parameter */
+	QCFG_RX_HEADROOM	= 0x2,
 };
 
 /**
@@ -199,6 +204,12 @@ enum {
  *
  * @supported_params:	Bitmask of supported parameters, see QCFG_*.
  *
+ * @xsk_page_pool:	AF_XDP zero copy installs the UMEM as the page pool
+ *			memory provider of the RX queue. The driver selects it
+ *			with PP_FLAG_MEM_PROVIDER and PP_RX_ROLE_HEAD, honours
+ *			whole buffers and QCFG_RX_HEADROOM, and accepts or
+ *			rejects the setup in XDP_VALIDATE_XSK_POOL.
+ *
  * Note that @ndo_queue_mem_alloc and @ndo_queue_mem_free may be called while
  * the interface is closed. @ndo_queue_start and @ndo_queue_stop will only
  * be called for an interface which is open.
@@ -229,6 +240,7 @@ struct netdev_queue_mgmt_ops {
 				    struct netlink_ext_ack *extack);
 
 	unsigned int supported_params;
+	bool xsk_page_pool;
 };
 
 void netdev_queue_config(struct net_device *dev, int rxq,
include/net/netdev_rx_queue.h +2 -0
index 9415a94d333d..989120cbf452 100644
@@ -31,6 +31,8 @@ struct netdev_rx_queue {
 	struct napi_struct		*napi;
 	struct netdev_queue_config	qcfg;
 	struct pp_memory_provider_params mp_params;
+	/* stamps the page pools of each queue allocation */
+	u32				mp_gen;
 
 	/* If a queue is leased, then the lease pointer is always
 	 * valid. From the physical device it points to the virtual
include/net/page_pool/types.h +12 -0
index 0d48c05f1462..e9f3af91e305 100644
@@ -40,6 +40,12 @@
  */
 #define PP_FLAG_MEM_PROVIDER	BIT(4)
 
+/* RX buffers a page pool supplies, see page_pool_params.rx_roles */
+enum pp_rx_role {
+	PP_RX_ROLE_HEAD		= BIT(0),	/* packet headers */
+	PP_RX_ROLE_PAYLOAD	= BIT(1),	/* payload after header split */
+};
+
 #define PP_FLAG_ALL		(PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV | \
 				 PP_FLAG_SYSTEM_POOL | \
 				 PP_FLAG_ALLOW_UNREADABLE_NETMEM | \
@@ -94,6 +100,8 @@ struct pp_alloc_cache {
  * @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_MEM_PROVIDER.
+ * @rx_roles:	&enum pp_rx_role mask, for pools that select a memory
+ *		provider. Zero means payload buffers.
  */
 struct page_pool_params {
 	struct_group_tagged(page_pool_params_fast, fast,
@@ -110,6 +118,7 @@ struct page_pool_params {
 		struct net_device *netdev;
 		unsigned int queue_idx;
 		unsigned int	flags;
+		unsigned int	rx_roles;
 /* private: used by test code only */
 		void (*init_callback)(netmem_ref netmem, void *arg);
 		void *init_arg;
@@ -182,6 +191,7 @@ struct pp_memory_provider_params {
 	void *mp_priv;
 	const struct memory_provider_ops *mp_ops;
 	u32 rx_page_size;
+	u32 rx_headroom;
 };
 
 struct page_pool {
@@ -245,6 +255,8 @@ struct page_pool {
 
 	void *mp_priv;
 	const struct memory_provider_ops *mp_ops;
+	/* queue allocation that selected the provider */
+	u32 mp_gen;
 
 	struct xarray dma_mapped;
 
include/net/xdp_sock.h +4 -0
index 6e70b320b399..e0e22ef839e1 100644
@@ -19,6 +19,10 @@
 struct net_device;
 struct xsk_queue;
 struct xdp_buff;
+struct memory_provider_ops;
+
+/* The memory provider of AF_XDP page pool zero copy */
+extern const struct memory_provider_ops xsk_pp_ops;
 
 struct xdp_umem {
 	void *addrs;
include/net/xdp_sock_drv.h +45 -0
index d94aeb506379..5bb1949a0aa7 100644
@@ -22,8 +22,29 @@ struct xsk_cb_desc {
 	u8 bytes;
 };
 
+/**
+ * struct xsk_rx_check - AF_XDP page pool RX setup a driver must accept
+ * @buf_size: size of each RX buffer
+ * @headroom: space before the packet in a head buffer, including
+ *	XDP_PACKET_HEADROOM. The UMEM headroom is the rest.
+ * @mtu: MTU of the device
+ * @sg: the socket takes packets in more than one buffer
+ * @prog: XDP program to check, or NULL for the current one
+ */
+struct xsk_rx_check {
+	u32 buf_size;
+	u32 headroom;
+	unsigned int mtu;
+	bool sg;
+	struct bpf_prog *prog;
+};
+
 #ifdef CONFIG_XDP_SOCKETS
 
+int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+		     struct bpf_prog *prog, enum bpf_xdp_mode mode,
+		     struct netlink_ext_ack *extack);
+struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev, u16 queue_id);
 void xsk_tx_completed(struct xsk_buff_pool *pool, u32 nb_entries);
 bool xsk_tx_peek_desc(struct xsk_buff_pool *pool, struct xdp_desc *desc);
 u32 xsk_tx_peek_release_desc_batch(struct xsk_buff_pool *pool, u32 max);
@@ -36,6 +57,11 @@ void xsk_clear_rx_need_wakeup(struct xsk_buff_pool *pool);
 void xsk_clear_tx_need_wakeup(struct xsk_buff_pool *pool);
 bool xsk_uses_need_wakeup(struct xsk_buff_pool *pool);
 
+static inline bool xsk_pool_uses_sg(struct xsk_buff_pool *pool)
+{
+	return pool->umem->flags & XDP_UMEM_SG_FLAG;
+}
+
 static inline u32 xsk_pool_get_headroom(struct xsk_buff_pool *pool)
 {
 	return XDP_PACKET_HEADROOM + pool->headroom;
@@ -351,6 +377,20 @@ static inline void xsk_buff_raw_dma_sync_for_device(struct xsk_buff_pool *pool,
 
 #else
 
+static inline int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+				   struct bpf_prog *prog,
+				   enum bpf_xdp_mode mode,
+				   struct netlink_ext_ack *extack)
+{
+	return 0;
+}
+
+static inline struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev,
+						 u16 queue_id)
+{
+	return NULL;
+}
+
 static inline void xsk_tx_completed(struct xsk_buff_pool *pool, u32 nb_entries)
 {
 }
@@ -397,6 +437,11 @@ static inline bool xsk_uses_need_wakeup(struct xsk_buff_pool *pool)
 	return false;
 }
 
+static inline bool xsk_pool_uses_sg(struct xsk_buff_pool *pool)
+{
+	return false;
+}
+
 static inline u32 xsk_pool_get_headroom(struct xsk_buff_pool *pool)
 {
 	return 0;
include/net/xsk_buff_pool.h +3 -0
index 02e89350faf9..6d7cfdf99a8b 100644
@@ -11,6 +11,7 @@
 #include <net/xdp.h>
 
 struct xsk_buff_pool;
+struct xsk_pp;
 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;
+	/* page pool memory provider, see net/xdp/xsk_pp.c */
+	struct xsk_pp *pp;
 	struct work_struct work;
 	/* Protects generic receive in shared and non-shared umem mode. */
 	spinlock_t rx_lock;
net/core/dev.c +16 -0
index 663fe3e32ea0..7e985fb82488 100644
@@ -163,6 +163,7 @@
 #include <net/page_pool/types.h>
 #include <net/page_pool/helpers.h>
 #include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
 #include <net/rps.h>
 #include <linux/phy_link_topology.h>
 
@@ -10535,6 +10536,8 @@ u8 dev_xdp_sb_prog_count(struct net_device *dev)
 
 int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 {
+	int err;
+
 	if (!dev->netdev_ops->ndo_bpf)
 		return -EOPNOTSUPP;
 
@@ -10552,6 +10555,13 @@ int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 		return -EBUSY;
 	}
 
+	if (bpf->command == XDP_SETUP_PROG && bpf->prog) {
+		err = xsk_validate_dev(dev, dev->mtu, bpf->prog, XDP_MODE_DRV,
+				       bpf->extack);
+		if (err)
+			return err;
+	}
+
 	return dev->netdev_ops->ndo_bpf(dev, bpf);
 }
 EXPORT_SYMBOL_GPL(netif_xdp_propagate);
@@ -10629,6 +10639,12 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
 		return -EBUSY;
 	}
 
+	if (mode != XDP_MODE_HW && prog) {
+		err = xsk_validate_dev(dev, dev->mtu, prog, mode, extack);
+		if (err)
+			return err;
+	}
+
 	memset(&xdp, 0, sizeof(xdp));
 	xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
 	xdp.extack = extack;
net/core/netdev_config.c +2 -0
index 1975de42a60d..97e33764737b 100644
@@ -88,6 +88,8 @@ static int __netdev_queue_config(struct net_device *dev, int rxq_idx,
 	mpp = &__netif_get_rx_queue(dev, rxq_idx)->mp_params;
 	if (mpp->rx_page_size)
 		qcfg->rx_page_size = mpp->rx_page_size;
+	if (mpp->rx_headroom)
+		qcfg->rx_headroom = mpp->rx_headroom;
 	err = validate_cb(dev, qcfg, extack);
 	if (err)
 		return err;
net/core/netdev_rx_queue.c +8 -1
index 9e14a747f9b5..4e2f906fbc73 100644
@@ -6,6 +6,7 @@
 #include <net/netdev_queues.h>
 #include <net/netdev_rx_queue.h>
 #include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock.h>
 
 #include "dev.h"
 #include "page_pool_priv.h"
@@ -141,6 +142,7 @@ static int netdev_rx_queue_reconfig(struct net_device *dev,
 		goto err_free_new_mem;
 	}
 
+	rxq->mp_gen++;
 	err = qops->ndo_queue_mem_alloc(dev, qcfg_new, new_mem, rxq_idx);
 	if (err)
 		goto err_free_old_mem;
@@ -235,6 +237,10 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		NL_SET_ERR_MSG(extack, "device does not support: rx_page_size");
 		return -EOPNOTSUPP;
 	}
+	if (p->rx_headroom && !(qops->supported_params & QCFG_RX_HEADROOM)) {
+		NL_SET_ERR_MSG(extack, "device does not support: rx_headroom");
+		return -EOPNOTSUPP;
+	}
 
 	rxq = __netif_get_rx_queue(dev, rxq_idx);
 	if (rxq->mp_params.mp_ops) {
@@ -242,7 +248,8 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		return -EEXIST;
 	}
 #ifdef CONFIG_XDP_SOCKETS
-	if (rxq->pool) {
+	/* An AF_XDP pool owns the queue, unless it installs its provider. */
+	if (rxq->pool && p->mp_ops != &xsk_pp_ops) {
 		NL_SET_ERR_MSG(extack, "designated queue already in use by AF_XDP");
 		return -EBUSY;
 	}
net/core/page_pool.c +4 -2
index 8237fda598ab..e897e79d31f1 100644
@@ -215,7 +215,8 @@ bool netmem_can_retain(netmem_ref netmem)
 EXPORT_SYMBOL(netmem_can_retain);
 
 static int page_pool_select_mp(struct page_pool *pool,
-			       const struct pp_memory_provider_params *mpp)
+			       const struct pp_memory_provider_params *mpp,
+			       u32 rxq_mp_gen)
 {
 	const struct memory_provider_ops *ops = mpp->mp_ops;
 	unsigned int flags = pool->slow.flags;
@@ -234,6 +235,7 @@ static int page_pool_select_mp(struct page_pool *pool,
 
 	pool->mp_priv = mpp->mp_priv;
 	pool->mp_ops = ops;
+	pool->mp_gen = rxq_mp_gen;
 	return 0;
 }
 
@@ -326,7 +328,7 @@ static int page_pool_init(struct page_pool *pool,
 		netdev_assert_locked(pool->slow.netdev);
 		rxq = __netif_get_rx_queue(pool->slow.netdev,
 					   pool->slow.queue_idx);
-		err = page_pool_select_mp(pool, &rxq->mp_params);
+		err = page_pool_select_mp(pool, &rxq->mp_params, rxq->mp_gen);
 		if (err)
 			goto free_ptr_ring;
 	}
net/core/page_pool_user.c +17 -8
index f30f3779624c..b69da0f74756 100644
@@ -398,28 +398,37 @@ void page_pool_unlist(struct page_pool *pool)
 	mutex_unlock(&page_pools_lock);
 }
 
+/* Check that the queue allocation that just ran put the provider in every
+ * pool role it needs: headers for a readable provider, payload otherwise.
+ * Pools of earlier allocations do not count.
+ */
 int page_pool_check_memory_provider(struct net_device *dev,
 				    struct netdev_rx_queue *rxq)
 {
-	void *binding = rxq->mp_params.mp_priv;
+	const struct memory_provider_ops *ops = rxq->mp_params.mp_ops;
+	void *mp_priv = rxq->mp_params.mp_priv;
+	unsigned int need, have = 0;
 	struct page_pool *pool;
 	struct hlist_node *n;
 
-	if (!binding)
+	if (!mp_priv)
 		return 0;
 
+	need = PP_RX_ROLE_PAYLOAD;
+	if (ops->caps & MP_CAP_READABLE)
+		need = PP_RX_ROLE_HEAD;
+
 	mutex_lock(&page_pools_lock);
 	hlist_for_each_entry_safe(pool, n, &dev->page_pools, user.list) {
-		if (pool->mp_priv != binding)
+		if (pool->mp_priv != mp_priv || pool->mp_gen != rxq->mp_gen ||
+		    pool->slow.queue_idx != get_netdev_rx_queue_index(rxq))
 			continue;
 
-		if (pool->slow.queue_idx == get_netdev_rx_queue_index(rxq)) {
-			mutex_unlock(&page_pools_lock);
-			return 0;
-		}
+		have |= pool->slow.rx_roles ? : PP_RX_ROLE_PAYLOAD;
 	}
 	mutex_unlock(&page_pools_lock);
-	return -ENODATA;
+
+	return (have & need) == need ? 0 : -ENODATA;
 }
 
 static void page_pool_unreg_netdev_wipe(struct net_device *netdev)
net/xdp/xsk.h +5 -2
index 4dab7b9a1487..9699e9a499a3 100644
@@ -36,10 +36,13 @@ void xsk_map_try_sock_delete(struct xsk_map *map, struct xdp_sock *xs,
 			     struct xdp_sock __rcu **map_entry);
 struct xsk_pp;
 
-extern const struct memory_provider_ops xsk_pp_ops;
-
 struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool);
 void xsk_pp_put(struct xsk_pp *pp);
+bool xsk_pp_supported(struct net_device *dev);
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+		u16 queue_id);
+void xsk_pp_unbind(struct xsk_buff_pool *pool);
+int xp_alloc_heads(struct xsk_buff_pool *pool);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
 			u16 queue_id);
net/xdp/xsk_buff_pool.c +3 -6
index 18966bbdb5b7..c620a0c32c17 100644
@@ -38,6 +38,8 @@ void xp_destroy(struct xsk_buff_pool *pool)
 	if (!pool)
 		return;
 
+	if (pool->pp)
+		xsk_pp_put(pool->pp);
 	kvfree(pool->tx_descs);
 	kvfree(pool->heads);
 	kvfree(pool);
@@ -62,18 +64,13 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
 {
 	bool unaligned = umem->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;
 	struct xsk_buff_pool *pool;
-	struct xdp_buff_xsk *xskb;
-	u32 i, entries;
+	u32 entries;
 
 	entries = unaligned ? umem->chunks : 0;
 	pool = kvzalloc_flex(*pool, free_heads, entries);
 	if (!pool)
 		goto out;
 
-	pool->heads = kvzalloc_objs(*pool->heads, umem->chunks);
-	if (!pool->heads)
-		goto out;
-
 	if (xs->tx)
 		if (xp_alloc_tx_descs(pool, xs, max_segs))
 			goto out;
@@ -104,10 +101,30 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
 	pool->fq = xs->fq_tmp;
 	pool->cq = xs->cq_tmp;
 

net/xdp/xsk_buff_pool.c struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs, · line 112

Quoted 10 lines
net/xdp/xsk_buff_pool.c +9 -1
-	for (i = 0; i < pool->free_heads_cnt; i++) {
+	return pool;
+
+out:
+	xp_destroy(pool);
+	return NULL;
+}
+
+/* Only copy mode and driver zero copy use heads */
+int xp_alloc_heads(struct xsk_buff_pool *pool)

nit: move xp_alloc_heads rework into a separate patch? this one is quite big already

#47 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

Quoted 10 lines · Stanislav Fomichev
Quoted 8 lines · Björn Töpel
net/xdp/xsk_buff_pool.c +0 -0
index 18966bbdb5b7..c620a0c32c17 100644
@@ -104,10 +101,30 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
 	pool->fq = xs->fq_tmp;
 	pool->cq = xs->cq_tmp;
 
Quoted 13 lines

net/xdp/xsk_buff_pool.c struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs, · line 112

Quoted 10 lines
net/xdp/xsk_buff_pool.c +9 -1
-	for (i = 0; i < pool->free_heads_cnt; i++) {
+	return pool;
+
+out:
+	xp_destroy(pool);
+	return NULL;
+}
+
+/* Only copy mode and driver zero copy use heads */
+int xp_alloc_heads(struct xsk_buff_pool *pool)

nit: move xp_alloc_heads rework into a separate patch? this one is quite big already

Will do!

Björn

#48 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

In reply to Björn Töpel
Quoted 555 lines · Björn Töpel

A page_pool driver should not need its own AF_XDP setup. When it sets netdev_queue_mgmt_ops.xsk_page_pool, a zero-copy bind installs the UMEM provider through the queue API, as devmem and io_uring do. The driver only judges the chunk size, headroom and multi-buffer mode against its MTU and XDP program, in XDP_VALIDATE_XSK_POOL; MTU and program changes of a bound device get the same check. The UMEM headroom belongs to the socket, so the queue gets it as rx_headroom, next to rx_page_size.

After a queue restart, the core checks that the new page pools took the provider. A readable provider must back the header pool, where an unsplit packet lands, so pools declare the buffers they supply in rx_roles. The old queue's pools carry the same provider during the check, so a per-queue generation, mp_gen, tells the new ones apart.

Generic XDP runs outside the queue NAPI, so it cannot feed the socket.

The provider needs no xdp_buff_xsk per chunk. The buffer pool allocates them only for copy mode and driver zero copy, which saves 128 bytes per chunk.

---
 include/linux/netdevice.h     |   8 ++
 include/net/netdev_queues.h   |  12 ++
 include/net/netdev_rx_queue.h |   2 +
 include/net/page_pool/types.h |  12 ++
 include/net/xdp_sock.h        |   4 +
 include/net/xdp_sock_drv.h    |  45 +++++++
 include/net/xsk_buff_pool.h   |   3 +
 net/core/dev.c                |  16 +++
 net/core/netdev_config.c      |   2 +
 net/core/netdev_rx_queue.c    |   9 +-
 net/core/page_pool.c          |   6 +-
 net/core/page_pool_user.c     |  25 ++--
 net/xdp/xsk.h                 |   7 +-
 net/xdp/xsk_buff_pool.c       |  69 ++++++++---
 net/xdp/xsk_pp.c              | 221 ++++++++++++++++++++++++++++++++++
 15 files changed, 410 insertions(+), 31 deletions(-)
include/linux/netdevice.h +8 -0
index 435be7880d7e..11e51e684003 100644
@@ -77,6 +77,7 @@ struct udp_tunnel_info;
 struct udp_tunnel_nic_info;
 struct udp_tunnel_nic;
 struct bpf_prog;
+struct xsk_rx_check;
 struct xdp_buff;
 struct xdp_frame;
 struct xdp_metadata_ops;
@@ -1010,6 +1011,8 @@ enum bpf_netdev_command {
        BPF_OFFLOAD_MAP_ALLOC,
        BPF_OFFLOAD_MAP_FREE,
        XDP_SETUP_XSK_POOL,
+       /* Check an AF_XDP page pool setup, see netdev_queue_mgmt_ops */
+       XDP_VALIDATE_XSK_POOL,
 };
 
 struct bpf_prog_offload_ops;
@@ -1048,6 +1051,11 @@ struct netdev_bpf {
                        struct xsk_buff_pool *pool;
                        u16 queue_id;
                } xsk;
+               /* XDP_VALIDATE_XSK_POOL */
+               struct {
+                       const struct xsk_rx_check *check;
+                       struct netlink_ext_ack *extack;
+               } xsk_check;
        };
 };
 
include/net/netdev_queues.h +12 -0
index c5335e935b7d..ad5f0420c21d 100644
@@ -45,12 +45,15 @@ struct netdev_config {
 /**
  * struct netdev_queue_config - rendered configuration for an RX queue
  * @rx_page_size:      Size of one RX page-pool allocation.
+ * @rx_headroom:       Space before the packet in a head buffer, including
+ *                     XDP_PACKET_HEADROOM. Zero selects the driver default.
  * @rx_ring_size:      Configured size of the regular RX ring.
  * @rx_mini_ring_size: Configured size of the RX mini ring.
  * @rx_jumbo_ring_size:        Configured size of the RX jumbo ring.
  */
 struct netdev_queue_config {
        u32     rx_page_size;
+       u32     rx_headroom;
        u32     rx_ring_size;
        u32     rx_mini_ring_size;
        u32     rx_jumbo_ring_size;
@@ -156,6 +159,8 @@ void netdev_stat_queue_sum(struct net_device *netdev,
 enum {
        /* The queue checks and honours the page size qcfg parameter */
        QCFG_RX_PAGE_SIZE       = 0x1,
+       /* The queue checks and honours the headroom qcfg parameter */
+       QCFG_RX_HEADROOM        = 0x2,
 };
 
 /**
@@ -199,6 +204,12 @@ enum {
  *
  * @supported_params:  Bitmask of supported parameters, see QCFG_*.
  *
+ * @xsk_page_pool:     AF_XDP zero copy installs the UMEM as the page pool
+ *                     memory provider of the RX queue. The driver selects it
+ *                     with PP_FLAG_MEM_PROVIDER and PP_RX_ROLE_HEAD, honours
+ *                     whole buffers and QCFG_RX_HEADROOM, and accepts or
+ *                     rejects the setup in XDP_VALIDATE_XSK_POOL.
+ *
  * Note that @ndo_queue_mem_alloc and @ndo_queue_mem_free may be called while
  * the interface is closed. @ndo_queue_start and @ndo_queue_stop will only
  * be called for an interface which is open.
@@ -229,6 +240,7 @@ struct netdev_queue_mgmt_ops {
                                    struct netlink_ext_ack *extack);
 
        unsigned int supported_params;
+       bool xsk_page_pool;
 };
 
 void netdev_queue_config(struct net_device *dev, int rxq,
include/net/netdev_rx_queue.h +2 -0
index 9415a94d333d..989120cbf452 100644
@@ -31,6 +31,8 @@ struct netdev_rx_queue {
        struct napi_struct              *napi;
        struct netdev_queue_config      qcfg;
        struct pp_memory_provider_params mp_params;
+       /* stamps the page pools of each queue allocation */
+       u32                             mp_gen;
 
        /* If a queue is leased, then the lease pointer is always
         * valid. From the physical device it points to the virtual
include/net/page_pool/types.h +12 -0
index 0d48c05f1462..e9f3af91e305 100644
@@ -40,6 +40,12 @@
  */
 #define PP_FLAG_MEM_PROVIDER   BIT(4)
 
+/* RX buffers a page pool supplies, see page_pool_params.rx_roles */
+enum pp_rx_role {
+       PP_RX_ROLE_HEAD         = BIT(0),       /* packet headers */
+       PP_RX_ROLE_PAYLOAD      = BIT(1),       /* payload after header split */
+};
+
 #define PP_FLAG_ALL            (PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV | \
                                 PP_FLAG_SYSTEM_POOL | \
                                 PP_FLAG_ALLOW_UNREADABLE_NETMEM | \
@@ -94,6 +100,8 @@ struct pp_alloc_cache {
  * @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_MEM_PROVIDER.
+ * @rx_roles:  &enum pp_rx_role mask, for pools that select a memory
+ *             provider. Zero means payload buffers.
  */
 struct page_pool_params {
        struct_group_tagged(page_pool_params_fast, fast,
@@ -110,6 +118,7 @@ struct page_pool_params {
                struct net_device *netdev;
                unsigned int queue_idx;
                unsigned int    flags;
+               unsigned int    rx_roles;
 /* private: used by test code only */
                void (*init_callback)(netmem_ref netmem, void *arg);
                void *init_arg;
@@ -182,6 +191,7 @@ struct pp_memory_provider_params {
        void *mp_priv;
        const struct memory_provider_ops *mp_ops;
        u32 rx_page_size;
+       u32 rx_headroom;
 };
 
 struct page_pool {
@@ -245,6 +255,8 @@ struct page_pool {
 
        void *mp_priv;
        const struct memory_provider_ops *mp_ops;
+       /* queue allocation that selected the provider */
+       u32 mp_gen;
 
        struct xarray dma_mapped;
 
include/net/xdp_sock.h +4 -0
index 6e70b320b399..e0e22ef839e1 100644
@@ -19,6 +19,10 @@
 struct net_device;
 struct xsk_queue;
 struct xdp_buff;
+struct memory_provider_ops;
+
+/* The memory provider of AF_XDP page pool zero copy */
+extern const struct memory_provider_ops xsk_pp_ops;
 
 struct xdp_umem {
        void *addrs;
include/net/xdp_sock_drv.h +45 -0
index d94aeb506379..5bb1949a0aa7 100644
@@ -22,8 +22,29 @@ struct xsk_cb_desc {
        u8 bytes;
 };
 
+/**
+ * struct xsk_rx_check - AF_XDP page pool RX setup a driver must accept
+ * @buf_size: size of each RX buffer
+ * @headroom: space before the packet in a head buffer, including
+ *     XDP_PACKET_HEADROOM. The UMEM headroom is the rest.
+ * @mtu: MTU of the device
+ * @sg: the socket takes packets in more than one buffer
+ * @prog: XDP program to check, or NULL for the current one
+ */
+struct xsk_rx_check {
+       u32 buf_size;
+       u32 headroom;
+       unsigned int mtu;
+       bool sg;
+       struct bpf_prog *prog;
+};
+
 #ifdef CONFIG_XDP_SOCKETS
 
+int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+                    struct bpf_prog *prog, enum bpf_xdp_mode mode,
+                    struct netlink_ext_ack *extack);
+struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev, u16 queue_id);
 void xsk_tx_completed(struct xsk_buff_pool *pool, u32 nb_entries);
 bool xsk_tx_peek_desc(struct xsk_buff_pool *pool, struct xdp_desc *desc);
 u32 xsk_tx_peek_release_desc_batch(struct xsk_buff_pool *pool, u32 max);
@@ -36,6 +57,11 @@ void xsk_clear_rx_need_wakeup(struct xsk_buff_pool *pool);
 void xsk_clear_tx_need_wakeup(struct xsk_buff_pool *pool);
 bool xsk_uses_need_wakeup(struct xsk_buff_pool *pool);
 
+static inline bool xsk_pool_uses_sg(struct xsk_buff_pool *pool)
+{
+       return pool->umem->flags & XDP_UMEM_SG_FLAG;
+}
+
 static inline u32 xsk_pool_get_headroom(struct xsk_buff_pool *pool)
 {
        return XDP_PACKET_HEADROOM + pool->headroom;
@@ -351,6 +377,20 @@ static inline void xsk_buff_raw_dma_sync_for_device(struct xsk_buff_pool *pool,
 
 #else
 
+static inline int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+                                  struct bpf_prog *prog,
+                                  enum bpf_xdp_mode mode,
+                                  struct netlink_ext_ack *extack)
+{
+       return 0;
+}
+
+static inline struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev,
+                                                u16 queue_id)
+{
+       return NULL;
+}
+
 static inline void xsk_tx_completed(struct xsk_buff_pool *pool, u32 nb_entries)
 {
 }
@@ -397,6 +437,11 @@ static inline bool xsk_uses_need_wakeup(struct xsk_buff_pool *pool)
        return false;
 }
 
+static inline bool xsk_pool_uses_sg(struct xsk_buff_pool *pool)
+{
+       return false;
+}
+
 static inline u32 xsk_pool_get_headroom(struct xsk_buff_pool *pool)
 {
        return 0;
include/net/xsk_buff_pool.h +3 -0
index 02e89350faf9..6d7cfdf99a8b 100644
@@ -11,6 +11,7 @@
 #include <net/xdp.h>
 
 struct xsk_buff_pool;
+struct xsk_pp;
 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;
+       /* page pool memory provider, see net/xdp/xsk_pp.c */
+       struct xsk_pp *pp;
        struct work_struct work;
        /* Protects generic receive in shared and non-shared umem mode. */
        spinlock_t rx_lock;
net/core/dev.c +16 -0
index 663fe3e32ea0..7e985fb82488 100644
@@ -163,6 +163,7 @@
 #include <net/page_pool/types.h>
 #include <net/page_pool/helpers.h>
 #include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
 #include <net/rps.h>
 #include <linux/phy_link_topology.h>
 
@@ -10535,6 +10536,8 @@ u8 dev_xdp_sb_prog_count(struct net_device *dev)
 
 int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 {
+       int err;
+
        if (!dev->netdev_ops->ndo_bpf)
                return -EOPNOTSUPP;
 
@@ -10552,6 +10555,13 @@ int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
                return -EBUSY;
        }
 
+       if (bpf->command == XDP_SETUP_PROG && bpf->prog) {
+               err = xsk_validate_dev(dev, dev->mtu, bpf->prog, XDP_MODE_DRV,
+                                      bpf->extack);
+               if (err)
+                       return err;
+       }
+
        return dev->netdev_ops->ndo_bpf(dev, bpf);
 }
 EXPORT_SYMBOL_GPL(netif_xdp_propagate);
@@ -10629,6 +10639,12 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
                return -EBUSY;
        }
 
+       if (mode != XDP_MODE_HW && prog) {
+               err = xsk_validate_dev(dev, dev->mtu, prog, mode, extack);
+               if (err)
+                       return err;
+       }
+
        memset(&xdp, 0, sizeof(xdp));
        xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
        xdp.extack = extack;
net/core/netdev_config.c +2 -0
index 1975de42a60d..97e33764737b 100644
@@ -88,6 +88,8 @@ static int __netdev_queue_config(struct net_device *dev, int rxq_idx,
        mpp = &__netif_get_rx_queue(dev, rxq_idx)->mp_params;
        if (mpp->rx_page_size)
                qcfg->rx_page_size = mpp->rx_page_size;
+       if (mpp->rx_headroom)
+               qcfg->rx_headroom = mpp->rx_headroom;
        err = validate_cb(dev, qcfg, extack);
        if (err)
                return err;
net/core/netdev_rx_queue.c +8 -1
index 9e14a747f9b5..4e2f906fbc73 100644
@@ -6,6 +6,7 @@
 #include <net/netdev_queues.h>
 #include <net/netdev_rx_queue.h>
 #include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock.h>
 
 #include "dev.h"
 #include "page_pool_priv.h"
@@ -141,6 +142,7 @@ static int netdev_rx_queue_reconfig(struct net_device *dev,
                goto err_free_new_mem;
        }
 
+       rxq->mp_gen++;
        err = qops->ndo_queue_mem_alloc(dev, qcfg_new, new_mem, rxq_idx);
        if (err)
                goto err_free_old_mem;
@@ -235,6 +237,10 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
                NL_SET_ERR_MSG(extack, "device does not support: rx_page_size");
                return -EOPNOTSUPP;
        }
+       if (p->rx_headroom && !(qops->supported_params & QCFG_RX_HEADROOM)) {
+               NL_SET_ERR_MSG(extack, "device does not support: rx_headroom");
+               return -EOPNOTSUPP;
+       }
 
        rxq = __netif_get_rx_queue(dev, rxq_idx);
        if (rxq->mp_params.mp_ops) {
@@ -242,7 +248,8 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
                return -EEXIST;
        }
 #ifdef CONFIG_XDP_SOCKETS
-       if (rxq->pool) {
+       /* An AF_XDP pool owns the queue, unless it installs its provider. */
+       if (rxq->pool && p->mp_ops != &xsk_pp_ops) {
                NL_SET_ERR_MSG(extack, "designated queue already in use by AF_XDP");
                return -EBUSY;
        }
net/core/page_pool.c +4 -2
index 8237fda598ab..e897e79d31f1 100644
@@ -215,7 +215,8 @@ bool netmem_can_retain(netmem_ref netmem)
 EXPORT_SYMBOL(netmem_can_retain);
 
 static int page_pool_select_mp(struct page_pool *pool,
-                              const struct pp_memory_provider_params *mpp)
+                              const struct pp_memory_provider_params *mpp,
+                              u32 rxq_mp_gen)
 {
        const struct memory_provider_ops *ops = mpp->mp_ops;
        unsigned int flags = pool->slow.flags;
@@ -234,6 +235,7 @@ static int page_pool_select_mp(struct page_pool *pool,
 
        pool->mp_priv = mpp->mp_priv;
        pool->mp_ops = ops;
+       pool->mp_gen = rxq_mp_gen;
        return 0;
 }
 
@@ -326,7 +328,7 @@ static int page_pool_init(struct page_pool *pool,
                netdev_assert_locked(pool->slow.netdev);
                rxq = __netif_get_rx_queue(pool->slow.netdev,
                                           pool->slow.queue_idx);
-               err = page_pool_select_mp(pool, &rxq->mp_params);
+               err = page_pool_select_mp(pool, &rxq->mp_params, rxq->mp_gen);
                if (err)
                        goto free_ptr_ring;
        }
net/core/page_pool_user.c +17 -8
index f30f3779624c..b69da0f74756 100644
@@ -398,28 +398,37 @@ void page_pool_unlist(struct page_pool *pool)
        mutex_unlock(&page_pools_lock);
 }
 
+/* Check that the queue allocation that just ran put the provider in every
+ * pool role it needs: headers for a readable provider, payload otherwise.
+ * Pools of earlier allocations do not count.
+ */
 int page_pool_check_memory_provider(struct net_device *dev,
                                    struct netdev_rx_queue *rxq)
 {
-       void *binding = rxq->mp_params.mp_priv;
+       const struct memory_provider_ops *ops = rxq->mp_params.mp_ops;
+       void *mp_priv = rxq->mp_params.mp_priv;
+       unsigned int need, have = 0;
        struct page_pool *pool;
        struct hlist_node *n;
 
-       if (!binding)
+       if (!mp_priv)
                return 0;
 
+       need = PP_RX_ROLE_PAYLOAD;
+       if (ops->caps & MP_CAP_READABLE)
+               need = PP_RX_ROLE_HEAD;
+
        mutex_lock(&page_pools_lock);
        hlist_for_each_entry_safe(pool, n, &dev->page_pools, user.list) {
-               if (pool->mp_priv != binding)
+               if (pool->mp_priv != mp_priv || pool->mp_gen != rxq->mp_gen ||
+                   pool->slow.queue_idx != get_netdev_rx_queue_index(rxq))
                        continue;
 
-               if (pool->slow.queue_idx == get_netdev_rx_queue_index(rxq)) {
-                       mutex_unlock(&page_pools_lock);
-                       return 0;
-               }
+               have |= pool->slow.rx_roles ? : PP_RX_ROLE_PAYLOAD;
        }
        mutex_unlock(&page_pools_lock);
-       return -ENODATA;
+
+       return (have & need) == need ? 0 : -ENODATA;
 }
 
 static void page_pool_unreg_netdev_wipe(struct net_device *netdev)
net/xdp/xsk.h +5 -2
index 4dab7b9a1487..9699e9a499a3 100644
@@ -36,10 +36,13 @@ void xsk_map_try_sock_delete(struct xsk_map *map, struct xdp_sock *xs,
                             struct xdp_sock __rcu **map_entry);
 struct xsk_pp;
 
-extern const struct memory_provider_ops xsk_pp_ops;
-
 struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool);
 void xsk_pp_put(struct xsk_pp *pp);
+bool xsk_pp_supported(struct net_device *dev);
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+               u16 queue_id);
+void xsk_pp_unbind(struct xsk_buff_pool *pool);
+int xp_alloc_heads(struct xsk_buff_pool *pool);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
                        u16 queue_id);
net/xdp/xsk_buff_pool.c +14 -7
index 18966bbdb5b7..c620a0c32c17 100644
@@ -38,6 +38,8 @@ void xp_destroy(struct xsk_buff_pool *pool)
        if (!pool)
                return;
 
+       if (pool->pp)
+               xsk_pp_put(pool->pp);
        kvfree(pool->tx_descs);
        kvfree(pool->heads);
        kvfree(pool);
@@ -62,18 +64,13 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
 {
        bool unaligned = umem->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;
        struct xsk_buff_pool *pool;
-       struct xdp_buff_xsk *xskb;
-       u32 i, entries;
+       u32 entries;
 
        entries = unaligned ? umem->chunks : 0;
        pool = kvzalloc_flex(*pool, free_heads, entries);
        if (!pool)
                goto out;
 
-       pool->heads = kvzalloc_objs(*pool->heads, umem->chunks);
-       if (!pool->heads)
-               goto out;
-
        if (xs->tx)
                if (xp_alloc_tx_descs(pool, xs, max_segs))
                        goto out;
@@ -104,10 +101,30 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
        pool->fq = xs->fq_tmp;
        pool->cq = xs->cq_tmp;
 
-       for (i = 0; i < pool->free_heads_cnt; i++) {
+       return pool;
+
+out:
+       xp_destroy(pool);
+       return NULL;
+}
+
+/* Only copy mode and driver zero copy use heads */
+int xp_alloc_heads(struct xsk_buff_pool *pool)
+{
+       struct xdp_buff_xsk *xskb;

net/xdp/xsk_buff_pool.c struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs, · line 124

Quoted 10 lines
net/xdp/xsk_buff_pool.c +10 -0
+       u32 i;
+
+       if (pool->heads)
+               return 0;
+
+       pool->heads = kvzalloc_objs(*pool->heads, pool->heads_cnt);
+       if (!pool->heads)
+               return -ENOMEM;
+
+       for (i = 0; i < pool->heads_cnt; i++) {

Now I get why you are not reusing the existing xdp_buff_xsk infra, you are removing them here for the PP case. Please mention this in the cover letter of the previous patch. There might be a good argument for it at least in aligned mode. It is wasting memory versus performance. Today when memory is expensive and also for umems that are shared between many sockets, the current scheme in the xsk_buffer pool for aligned mode might not be worth it.

I have two questions for you. What would the performance be if you moved the aligned mode over to use the same free_list as unaligned mode and then use that in PP? Would reuse more code, but would it be fast enough?

If that is not performant, what if you instead decreased the cost of the current pre-allocated xskbs in aligned mode by just creating a single copy per umem and using those in PP? Might be a good thing for regular xsk drivers too these days, but do not know if it will work for you.

I do not know if any of these suggestions would work, but I think you should examine them as less code paths is generally a good thing. You might also improve the non-PP case too by optimizing it for your case!

Quoted 8 lines
net/xdp/xsk_buff_pool.c +1 -1
                xskb = &pool->heads[i];
                xskb->pool = pool;
-               xskb->xdp.frame_sz = umem->chunk_size - umem->headroom;
+               xskb->xdp.frame_sz = pool->chunk_size - pool->headroom;
                INIT_LIST_HEAD(&xskb->list_node);
                if (pool->unaligned)
                        pool->free_heads[i] = xskb;

net/xdp/xsk_buff_pool.c struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs, · line 135

Quoted 9 lines
net/xdp/xsk_buff_pool.c +1 -5
@@ -115,11 +132,7 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
                        xp_init_xskb_addr(xskb, pool, (u64)i * pool->chunk_size);
        }
 
-       return pool;
-
-out:
-       xp_destroy(pool);
-       return NULL;
+       return 0;

Agree with Stan that these changes should be in a separate commit. Think also about if it would make sense to put your page_pool changes in yet another commit.

Quoted 96 lines
net/xdp/xsk_buff_pool.c +25 -5
 }
 
 void xp_set_rxq_info(struct xsk_buff_pool *pool, struct xdp_rxq_info *rxq)
@@ -212,9 +225,24 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
         */
        hlist_add_head(&pool->dev_node, &netdev->xsk_pools);
 
-       if (force_copy)
+       if (force_copy) {
                /* For copy-mode, we are done. */
+               err = xp_alloc_heads(pool);
+               goto out;
+       }
+
+       if (xsk_pp_supported(netdev)) {
+               err = xsk_pp_bind(pool, netdev, queue_id);
+               if (err)
+                       goto err_unreg_pool;
+
+               pool->umem->zc = true;
                return 0;
+       }
+
+       err = xp_alloc_heads(pool);
+       if (err)
+               goto out;
 
        if ((netdev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK) {
                err = -EOPNOTSUPP;
@@ -267,8 +295,10 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 err_unreg_xsk:
        xp_disable_drv_zc(pool);
 err_unreg_pool:
-       if (!force_zc)
-               err = 0; /* fallback to copy mode */
+       /* An old page pool may still own chunks of a failed provider. */
+       if (!force_zc && !pool->pp)
+               err = xp_alloc_heads(pool); /* fallback to copy mode */
+out:
        if (err) {
                pool->umem->flags = umem_flags;
                xsk_clear_pool_at_qid(netdev, queue_id);
@@ -301,7 +331,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->pp)
+               xsk_pp_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;
@@ -474,7 +507,7 @@ static void xp_check_dma_contiguity(struct xsk_dma_map *dma_map)
 
 static int xp_init_dma_info(struct xsk_buff_pool *pool, struct xsk_dma_map *dma_map)
 {
-       if (!pool->unaligned) {
+       if (!pool->unaligned && pool->heads) {
                u32 i;
 
                for (i = 0; i < pool->heads_cnt; i++) {
net/xdp/xsk_pp.c +7 -0
index fdd55265a6cd..c2214e718cdb 100644
@@ -8,6 +8,9 @@
  *       +-----RX ring-------+
  */
 
+#include <net/netdev_lock.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>
@@ -15,6 +18,8 @@
 #include "xsk.h"
 #include "xsk_queue.h"
 
+#define XSK_PP_DMA_ATTR        (DMA_ATTR_WEAK_ORDERING | DMA_ATTR_SKIP_CPU_SYNC)
+
 enum xsk_pp_chunk {
        XSK_PP_USER,    /* owned by userspace */
        XSK_PP_POOL,    /* owned by a page pool */
@@ -30,6 +35,8 @@ struct xsk_pp {
        refcount_t refs;
        u32 nr_pools;
        bool dma_need_sync;
+       /* RX queue of the provider, NULL once it is removed */
+       struct netdev_rx_queue *rxq;
        u8 *state;
        u32 reuse_cnt;
        u32 reuse[];

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 250

Quoted 8 lines
net/xdp/xsk_pp.c +5 -0
@@ -236,11 +243,225 @@ static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
        return 0;
 }
 
+/* The queue no longer uses the provider, and its DMA stopped */
+static void xsk_pp_detach(struct xsk_pp *pp)
+{
+       pp->rxq = NULL;
+       spin_lock_bh(&pp->lock);

Just curious, but why this protection of the fq here?

Quoted 221 lines
net/xdp/xsk_pp.c +209 -1
+       pp->fq = NULL;
+       spin_unlock_bh(&pp->lock);
+       xp_dma_unmap(pp->pool, XSK_PP_DMA_ATTR);
+}
+
+/* The device unregisters, and is closed */
+static void xsk_pp_uninstall(void *mp_priv, struct netdev_rx_queue *rxq)
+{
+       xsk_pp_detach(mp_priv);
+}
+
 const struct memory_provider_ops xsk_pp_ops = {
        .init           = xsk_pp_init,
        .destroy        = xsk_pp_destroy,
        .alloc_netmems  = xsk_pp_alloc_netmems,
        .release_netmem = xsk_pp_release_netmem,
        .nl_fill        = xsk_pp_nl_fill,
+       .uninstall      = xsk_pp_uninstall,
        .caps           = MP_CAP_READABLE,
 };
+
+static bool xsk_pp_abandon(struct xsk_pp *pp)
+{
+       struct xsk_buff_pool *pool = pp->pool;
+       bool busy;
+       u32 idx;
+
+       spin_lock_bh(&pp->lock);
+       busy = pp->nr_pools;
+       while (!busy && pp->reuse_cnt) {
+               idx = pp->reuse[--pp->reuse_cnt];
+               pp->state[idx] = XSK_PP_USER;
+               xp_free(&pool->heads[idx]);
+       }
+       spin_unlock_bh(&pp->lock);
+
+       return !busy;
+}
+
+static int xsk_pp_validate(struct net_device *dev, struct xsk_buff_pool *pool,
+                          unsigned int mtu, struct bpf_prog *prog,
+                          struct netlink_ext_ack *extack)
+{
+       struct xsk_rx_check check = {
+               .buf_size = pool->chunk_size,
+               .headroom = xsk_pool_get_headroom(pool),
+               .mtu = mtu,
+               .sg = xsk_pool_uses_sg(pool),
+               .prog = prog,
+       };
+       struct netdev_bpf bpf = {
+               .command = XDP_VALIDATE_XSK_POOL,
+               .xsk_check.check = &check,
+               .xsk_check.extack = extack,
+       };
+
+       return dev->netdev_ops->ndo_bpf(dev, &bpf);
+}
+
+/**
+ * xsk_validate_dev - check AF_XDP page pool queues against a new setting
+ * @dev: device of the queues
+ * @mtu: MTU to check
+ * @prog: XDP program to check, or NULL for the current one
+ * @mode: XDP mode of @prog
+ * @extack: netlink extended ack
+ *
+ * Context: holds the instance lock of @dev, or RTNL for a device without it.
+ * Return: 0 if the driver accepts all queues of @dev that have an AF_XDP
+ * memory provider, or its error.
+ */
+int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+                    struct bpf_prog *prog, enum bpf_xdp_mode mode,
+                    struct netlink_ext_ack *extack)
+{
+       struct netdev_rx_queue *rxq;
+       struct xsk_pp *pp;
+       unsigned int i;
+       int err;
+
+       netdev_assert_locked_ops_compat(dev);
+
+       for (i = 0; i < dev->real_num_rx_queues; i++) {
+               rxq = __netif_get_rx_queue(dev, i);
+               if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+                       continue;
+
+               /* Generic XDP runs outside the queue NAPI */
+               if (mode == XDP_MODE_SKB) {
+                       NL_SET_ERR_MSG(extack,
+                                      "generic XDP cannot feed an AF_XDP page pool socket");
+                       return -EBUSY;
+               }
+
+               pp = rxq->mp_params.mp_priv;
+               err = xsk_pp_validate(dev, pp->pool, mtu, prog, extack);
+               if (err)
+                       return err;
+       }
+
+       return 0;
+}
+EXPORT_SYMBOL_GPL(xsk_validate_dev);
+
+/**
+ * xsk_rxq_pool - get the AF_XDP pool that provides memory to an RX queue
+ * @dev: device of the queue
+ * @queue_id: RX queue
+ *
+ * The pool stays valid while the queue that the caller allocates runs.
+ *
+ * Context: holds the instance lock of @dev.
+ * Return: the buffer pool, or NULL.
+ */
+struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev, u16 queue_id)
+{
+       struct netdev_rx_queue *rxq;
+       struct xsk_pp *pp;
+
+       netdev_assert_locked(dev);
+
+       if (queue_id >= dev->real_num_rx_queues)
+               return NULL;
+
+       rxq = __netif_get_rx_queue(dev, queue_id);
+       if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+               return NULL;
+
+       pp = rxq->mp_params.mp_priv;
+       return pp->pool;
+}
+EXPORT_SYMBOL_GPL(xsk_rxq_pool);
+
+bool xsk_pp_supported(struct net_device *dev)
+{
+       const struct netdev_queue_mgmt_ops *qops = dev->queue_mgmt_ops;
+
+       return qops && qops->xsk_page_pool;
+}
+
+/* Called with RTNL and the instance lock of @dev. On error, @pool->pp stays
+ * set if an old page pool still owns chunks; copy mode must not take the pool.
+ */
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+               u16 queue_id)
+{
+       struct pp_memory_provider_params mp = { .mp_ops = &xsk_pp_ops };
+       struct device *dma_dev;
+       struct xsk_pp *pp;
+       int err;
+
+       if (queue_id >= dev->real_num_rx_queues || pool->unaligned)
+               return -EOPNOTSUPP;
+       if ((dev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK ||
+           (xsk_pool_uses_sg(pool) && dev->xdp_zc_max_segs == 1))
+               return -EOPNOTSUPP;
+       if (dev_xdp_prog_id(dev, XDP_MODE_SKB))
+               return -EOPNOTSUPP;
+       if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE))
+               return -EBUSY;
+
+       err = xsk_pp_validate(dev, pool, dev->mtu, NULL, NULL);
+       if (err)
+               return err;
+
+       dma_dev = netdev_queue_get_dma_dev(dev, queue_id, NETDEV_QUEUE_TYPE_RX);
+       if (!dma_dev)
+               return -EOPNOTSUPP;
+
+       err = xp_dma_map(pool, dma_dev, XSK_PP_DMA_ATTR, pool->umem->pgs,
+                        pool->umem->npgs);
+       if (err)
+               return err;
+
+       pp = xsk_pp_create(pool);
+       if (IS_ERR(pp)) {
+               xp_dma_unmap(pool, XSK_PP_DMA_ATTR);
+               return PTR_ERR(pp);
+       }
+
+       mp.mp_priv = pp;
+       mp.rx_page_size = pool->chunk_size;
+       mp.rx_headroom = xsk_pool_get_headroom(pool);
+       err = netif_mp_open_rxq(dev, queue_id, &mp, NULL);
+       if (!err) {
+               pp->rxq = __netif_get_rx_queue(dev, queue_id);
+               pool->pp = pp;
+               pool->xdp_zc_max_segs = dev->xdp_zc_max_segs;
+               return 0;
+       }
+
+       xp_dma_unmap(pool, XSK_PP_DMA_ATTR);
+       /* Copy mode takes the chunks that the provider holds */
+       if (!xp_alloc_heads(pool) && xsk_pp_abandon(pp))
+               xsk_pp_put(pp);
+       else
+               pool->pp = pp;
+
+       return err;
+}
+
+/* Called with RTNL and the instance lock of the device */
+void xsk_pp_unbind(struct xsk_buff_pool *pool)
+{
+       struct xsk_pp *pp = pool->pp;
+       struct pp_memory_provider_params mp = {
+               .mp_ops = &xsk_pp_ops,
+               .mp_priv = pp,
+       };
+
+       /* Unregister removed the provider already */
+       if (!pp->rxq)
+               return;
+
+       netif_mp_close_rxq(pool->netdev, pool->queue_id, &mp);
+       xsk_pp_detach(pp);
+}
--

2.56.0

#49 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

Quoted 33 lines · Magnus Karlsson
Quoted 20 lines · Björn Töpel
net/xdp/xsk_buff_pool.c +11 -1
index 18966bbdb5b7..c620a0c32c17 100644
@@ -104,10 +101,30 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
        pool->fq = xs->fq_tmp;
        pool->cq = xs->cq_tmp;
 
-       for (i = 0; i < pool->free_heads_cnt; i++) {
+       return pool;
+
+out:
+       xp_destroy(pool);
+       return NULL;
+}
+
+/* Only copy mode and driver zero copy use heads */
+int xp_alloc_heads(struct xsk_buff_pool *pool)
+{
+       struct xdp_buff_xsk *xskb;

net/xdp/xsk_buff_pool.c struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs, · line 124

Quoted 10 lines
net/xdp/xsk_buff_pool.c +10 -0
+       u32 i;
+
+       if (pool->heads)
+               return 0;
+
+       pool->heads = kvzalloc_objs(*pool->heads, pool->heads_cnt);
+       if (!pool->heads)
+               return -ENOMEM;
+
+       for (i = 0; i < pool->heads_cnt; i++) {
Quoted 7 lines

Now I get why you are not reusing the existing xdp_buff_xsk infra, you are removing them here for the PP case. Please mention this in the cover letter of the previous patch. There might be a good argument for it at least in aligned mode. It is wasting memory versus performance. Today when memory is expensive and also for umems that are shared between many sockets, the current scheme in the xsk_buffer pool for aligned mode might not be worth it.

Will do!

Quoted 11 lines

I have two questions for you. What would the performance be if you moved the aligned mode over to use the same free_list as unaligned mode and then use that in PP? Would reuse more code, but would it be fast enough?

If that is not performant, what if you instead decreased the cost of the current pre-allocated xskbs in aligned mode by just creating a single copy per umem and using those in PP? Might be a good thing for regular xsk drivers too these days, but do not know if it will work for you.

Quoted 3 lines

I do not know if any of these suggestions would work, but I think you should examine them as less code paths is generally a good thing. You might also improve the non-PP case too by optimizing it for your case!

Neither would help the provider. The page pool hands out net_iovs, so it needs one per chunk anyway, and the driver brings its own xdp_buff. net_iov, reuse and state are 69 bytes per chunk, against 128 for an xdp_buff_xsk; free_list would add those 128 on top. Nor is reuse on the hot path: the page pool recycles in its own cache and ring, and gives chunks back only when it is destroyed or its ring is full. The hot path is the FILL claim and the RX ring flush.

I don't like the reuse[] fixes size tho...

One copy per UMEM doesn't work either: an xdp_buff_xsk holds pool, rxq, DMA addresses and cb, so it can only be shared by pools of the same device and queue, and those already share the pool.

For driver ZC I agree, heads add up with a shared UMEM: 32 MB per pool for 1 GB of 4K chunks. Unaligned mode allocates a head per chunk too, though, so moving aligned mode to free_heads saves nothing by itself; heads would have to be sized by the rings. Worth a look, with numbers, but in a separate series.

Quoted 11 lines
Quoted 11 lines
net/xdp/xsk_buff_pool.c +1 -1
                xskb = &pool->heads[i];
                xskb->pool = pool;
-               xskb->xdp.frame_sz = umem->chunk_size - umem->headroom;
+               xskb->xdp.frame_sz = pool->chunk_size - pool->headroom;
                INIT_LIST_HEAD(&xskb->list_node);
                if (pool->unaligned)
                        pool->free_heads[i] = xskb;
@@ -115,11 +132,7 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
                        xp_init_xskb_addr(xskb, pool, (u64)i * pool->chunk_size);
        }
 
Quoted 10 lines

net/xdp/xsk_buff_pool.c struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs, · line 135

Quoted 6 lines
net/xdp/xsk_buff_pool.c +1 -5
-       return pool;
-
-out:
-       xp_destroy(pool);
-       return NULL;
+       return 0;

Agree with Stan that these changes should be in a separate commit. Think also about if it would make sense to put your page_pool changes in yet another commit.

ACK!

Quoted 99 lines
Quoted 99 lines
net/xdp/xsk_buff_pool.c +25 -5
 }
 
 void xp_set_rxq_info(struct xsk_buff_pool *pool, struct xdp_rxq_info *rxq)
@@ -212,9 +225,24 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
         */
        hlist_add_head(&pool->dev_node, &netdev->xsk_pools);
 
-       if (force_copy)
+       if (force_copy) {
                /* For copy-mode, we are done. */
+               err = xp_alloc_heads(pool);
+               goto out;
+       }
+
+       if (xsk_pp_supported(netdev)) {
+               err = xsk_pp_bind(pool, netdev, queue_id);
+               if (err)
+                       goto err_unreg_pool;
+
+               pool->umem->zc = true;
                return 0;
+       }
+
+       err = xp_alloc_heads(pool);
+       if (err)
+               goto out;
 
        if ((netdev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK) {
                err = -EOPNOTSUPP;
@@ -267,8 +295,10 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 err_unreg_xsk:
        xp_disable_drv_zc(pool);
 err_unreg_pool:
-       if (!force_zc)
-               err = 0; /* fallback to copy mode */
+       /* An old page pool may still own chunks of a failed provider. */
+       if (!force_zc && !pool->pp)
+               err = xp_alloc_heads(pool); /* fallback to copy mode */
+out:
        if (err) {
                pool->umem->flags = umem_flags;
                xsk_clear_pool_at_qid(netdev, queue_id);
@@ -301,7 +331,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->pp)
+               xsk_pp_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;
@@ -474,7 +507,7 @@ static void xp_check_dma_contiguity(struct xsk_dma_map *dma_map)
 
 static int xp_init_dma_info(struct xsk_buff_pool *pool, struct xsk_dma_map *dma_map)
 {
-       if (!pool->unaligned) {
+       if (!pool->unaligned && pool->heads) {
                u32 i;
 
                for (i = 0; i < pool->heads_cnt; i++) {
net/xdp/xsk_pp.c +7 -0
index fdd55265a6cd..c2214e718cdb 100644
@@ -8,6 +8,9 @@
  *       +-----RX ring-------+
  */
 
+#include <net/netdev_lock.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>
@@ -15,6 +18,8 @@
 #include "xsk.h"
 #include "xsk_queue.h"
 
+#define XSK_PP_DMA_ATTR        (DMA_ATTR_WEAK_ORDERING | DMA_ATTR_SKIP_CPU_SYNC)
+
 enum xsk_pp_chunk {
        XSK_PP_USER,    /* owned by userspace */
        XSK_PP_POOL,    /* owned by a page pool */
@@ -30,6 +35,8 @@ struct xsk_pp {
        refcount_t refs;
        u32 nr_pools;
        bool dma_need_sync;
+       /* RX queue of the provider, NULL once it is removed */
+       struct netdev_rx_queue *rxq;
        u8 *state;
        u32 reuse_cnt;
        u32 reuse[];
@@ -236,11 +243,225 @@ static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
        return 0;
 }
 
Quoted 7 lines

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 250

Quoted 5 lines
net/xdp/xsk_pp.c +5 -0
+/* The queue no longer uses the provider, and its DMA stopped */
+static void xsk_pp_detach(struct xsk_pp *pp)
+{
+       pp->rxq = NULL;
+       spin_lock_bh(&pp->lock);

Just curious, but why this protection of the fq here?

After a normal unbind the queue is already stopped, so nothing reads FILL anyway. It matters when the restart fails and the old queue keeps running; I have a net fix that keeps the provider on such a queue until a retry succeeds... but maybe it's better to introduce the lock then. Let me noodle on it for the next rev.

Björn

#50 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

Quoted 75 lines · Björn Töpel
Quoted 33 lines · Magnus Karlsson
Quoted 20 lines · Björn Töpel
net/xdp/xsk_buff_pool.c +11 -1
index 18966bbdb5b7..c620a0c32c17 100644
@@ -104,10 +101,30 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
        pool->fq = xs->fq_tmp;
        pool->cq = xs->cq_tmp;
 
-       for (i = 0; i < pool->free_heads_cnt; i++) {
+       return pool;
+
+out:
+       xp_destroy(pool);
+       return NULL;
+}
+
+/* Only copy mode and driver zero copy use heads */
+int xp_alloc_heads(struct xsk_buff_pool *pool)
+{
+       struct xdp_buff_xsk *xskb;

net/xdp/xsk_buff_pool.c struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs, · line 124

Quoted 10 lines
net/xdp/xsk_buff_pool.c +10 -0
+       u32 i;
+
+       if (pool->heads)
+               return 0;
+
+       pool->heads = kvzalloc_objs(*pool->heads, pool->heads_cnt);
+       if (!pool->heads)
+               return -ENOMEM;
+
+       for (i = 0; i < pool->heads_cnt; i++) {
Quoted 7 lines

Now I get why you are not reusing the existing xdp_buff_xsk infra, you are removing them here for the PP case. Please mention this in the cover letter of the previous patch. There might be a good argument for it at least in aligned mode. It is wasting memory versus performance. Today when memory is expensive and also for umems that are shared between many sockets, the current scheme in the xsk_buffer pool for aligned mode might not be worth it.

Will do!

Quoted 11 lines

I have two questions for you. What would the performance be if you moved the aligned mode over to use the same free_list as unaligned mode and then use that in PP? Would reuse more code, but would it be fast enough?

If that is not performant, what if you instead decreased the cost of the current pre-allocated xskbs in aligned mode by just creating a single copy per umem and using those in PP? Might be a good thing for regular xsk drivers too these days, but do not know if it will work for you.

Quoted 3 lines

I do not know if any of these suggestions would work, but I think you should examine them as less code paths is generally a good thing. You might also improve the non-PP case too by optimizing it for your case!

Neither would help the provider. The page pool hands out net_iovs, so it needs one per chunk anyway, and the driver brings its own xdp_buff. net_iov, reuse and state are 69 bytes per chunk, against 128 for an xdp_buff_xsk; free_list would add those 128 on top. Nor is reuse on the hot path: the page pool recycles in its own cache and ring, and gives chunks back only when it is destroyed or its ring is full. The hot path is the FILL claim and the RX ring flush.

I don't like the reuse[] fixes size tho...

One copy per UMEM doesn't work either: an xdp_buff_xsk holds pool, rxq, DMA addresses and cb, so it can only be shared by pools of the same device and queue, and those already share the pool.

Quoted 5 lines

For driver ZC I agree, heads add up with a shared UMEM: 32 MB per pool for 1 GB of 4K chunks. Unaligned mode allocates a head per chunk too, though, so moving aligned mode to free_heads saves nothing by itself; heads would have to be sized by the rings. Worth a look, with numbers, but in a separate series.

Agreed, that would be too much tangential work for this series.

Quoted 139 lines
Quoted 11 lines
Quoted 11 lines
net/xdp/xsk_buff_pool.c +1 -1
                xskb = &pool->heads[i];
                xskb->pool = pool;
-               xskb->xdp.frame_sz = umem->chunk_size - umem->headroom;
+               xskb->xdp.frame_sz = pool->chunk_size - pool->headroom;
                INIT_LIST_HEAD(&xskb->list_node);
                if (pool->unaligned)
                        pool->free_heads[i] = xskb;
@@ -115,11 +132,7 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
                        xp_init_xskb_addr(xskb, pool, (u64)i * pool->chunk_size);
        }
 
Quoted 10 lines

net/xdp/xsk_buff_pool.c struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs, · line 135

Quoted 6 lines
net/xdp/xsk_buff_pool.c +1 -5
-       return pool;
-
-out:
-       xp_destroy(pool);
-       return NULL;
+       return 0;

Agree with Stan that these changes should be in a separate commit. Think also about if it would make sense to put your page_pool changes in yet another commit.

ACK!

Quoted 99 lines
Quoted 99 lines
net/xdp/xsk_buff_pool.c +25 -5
 }
 
 void xp_set_rxq_info(struct xsk_buff_pool *pool, struct xdp_rxq_info *rxq)
@@ -212,9 +225,24 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
         */
        hlist_add_head(&pool->dev_node, &netdev->xsk_pools);
 
-       if (force_copy)
+       if (force_copy) {
                /* For copy-mode, we are done. */
+               err = xp_alloc_heads(pool);
+               goto out;
+       }
+
+       if (xsk_pp_supported(netdev)) {
+               err = xsk_pp_bind(pool, netdev, queue_id);
+               if (err)
+                       goto err_unreg_pool;
+
+               pool->umem->zc = true;
                return 0;
+       }
+
+       err = xp_alloc_heads(pool);
+       if (err)
+               goto out;
 
        if ((netdev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK) {
                err = -EOPNOTSUPP;
@@ -267,8 +295,10 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 err_unreg_xsk:
        xp_disable_drv_zc(pool);
 err_unreg_pool:
-       if (!force_zc)
-               err = 0; /* fallback to copy mode */
+       /* An old page pool may still own chunks of a failed provider. */
+       if (!force_zc && !pool->pp)
+               err = xp_alloc_heads(pool); /* fallback to copy mode */
+out:
        if (err) {
                pool->umem->flags = umem_flags;
                xsk_clear_pool_at_qid(netdev, queue_id);
@@ -301,7 +331,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->pp)
+               xsk_pp_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;
@@ -474,7 +507,7 @@ static void xp_check_dma_contiguity(struct xsk_dma_map *dma_map)
 
 static int xp_init_dma_info(struct xsk_buff_pool *pool, struct xsk_dma_map *dma_map)
 {
-       if (!pool->unaligned) {
+       if (!pool->unaligned && pool->heads) {
                u32 i;
 
                for (i = 0; i < pool->heads_cnt; i++) {
net/xdp/xsk_pp.c +7 -0
index fdd55265a6cd..c2214e718cdb 100644
@@ -8,6 +8,9 @@
  *       +-----RX ring-------+
  */
 
+#include <net/netdev_lock.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>
@@ -15,6 +18,8 @@
 #include "xsk.h"
 #include "xsk_queue.h"
 
+#define XSK_PP_DMA_ATTR        (DMA_ATTR_WEAK_ORDERING | DMA_ATTR_SKIP_CPU_SYNC)
+
 enum xsk_pp_chunk {
        XSK_PP_USER,    /* owned by userspace */
        XSK_PP_POOL,    /* owned by a page pool */
@@ -30,6 +35,8 @@ struct xsk_pp {
        refcount_t refs;
        u32 nr_pools;
        bool dma_need_sync;
+       /* RX queue of the provider, NULL once it is removed */
+       struct netdev_rx_queue *rxq;
        u8 *state;
        u32 reuse_cnt;
        u32 reuse[];
@@ -236,11 +243,225 @@ static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
        return 0;
 }
 
Quoted 7 lines

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 250

Quoted 5 lines
net/xdp/xsk_pp.c +5 -0
+/* The queue no longer uses the provider, and its DMA stopped */
+static void xsk_pp_detach(struct xsk_pp *pp)
+{
+       pp->rxq = NULL;
+       spin_lock_bh(&pp->lock);

Just curious, but why this protection of the fq here?

After a normal unbind the queue is already stopped, so nothing reads FILL anyway. It matters when the restart fails and the old queue keeps running; I have a net fix that keeps the provider on such a queue until a retry succeeds... but maybe it's better to introduce the lock then. Let me noodle on it for the next rev.

Björn

#51 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [High] xsk: UAF of pool and UMEM on xsk_pp_bind() failure with active page_pool - [High] xsk: unconditional…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [High] xsk: UAF of pool and UMEM on xsk_pp_bind() failure with active page_pool
- [High] xsk: unconditional DMA unmap and UMEM release in xsk_pp_unbind()
It also noticed 1 related pre-existing issue this patch does not introduce:
- [Critical] net: null pointer dereference in __netdev_queue_config()
[1]
--

commit 34e15c1f4828114e9aaedcfa55376bd7c379c9a3
Author: Björn Töpel <[email protected]>

xsk: Install UMEM page pool providers in the core

This commit installs AF_XDP UMEM memory providers through the netdev RX queue API for drivers setting netdev_queue_mgmt_ops.xsk_page_pool, and defers allocating pool->heads to copy mode and driver zero-copy.

net/core/netdev_config.c static int __netdev_queue_config(struct net_device *dev, int rxq_idx, · line 95

Quoted 13 lines
net/core/netdev_config.c +2 -0
index 1975de42a60d9..97e33764737bd 100644
@@ -88,6 +88,8 @@ static int __netdev_queue_config(struct net_device *dev, int rxq_idx,
 	mpp = &__netif_get_rx_queue(dev, rxq_idx)->mp_params;
 	if (mpp->rx_page_size)
 		qcfg->rx_page_size = mpp->rx_page_size;
+	if (mpp->rx_headroom)
+		qcfg->rx_headroom = mpp->rx_headroom;
 	err = validate_cb(dev, qcfg, extack);
 	if (err)
 		return err;

[Severity: Critical]
This problem wasn't introduced by this patch, but can __netdev_queue_config() dereference a NULL dev->queue_mgmt_ops pointer [1] when called on a device without queue management ops?

Earlier in __netdev_queue_config(), dev->queue_mgmt_ops is dereferenced without a NULL check:

net/core/netdev_config.c:__netdev_queue_config() {
	...
	validate_cb = netdev_nop_validate_qcfg;
	if (validate && dev->queue_mgmt_ops->ndo_validate_qcfg)
		validate_cb = dev->queue_mgmt_ops->ndo_validate_qcfg;

	memset(qcfg, 0, sizeof(*qcfg));

	/* Get defaults from the driver, in case user config not set */
	if (dev->queue_mgmt_ops->ndo_default_qcfg)
		dev->queue_mgmt_ops->ndo_default_qcfg(dev, qcfg);
	...
}

Calling netdev_queue_config() or netdev_queue_config_validate() on a device where dev->queue_mgmt_ops is NULL will panic.

Quoted 4 lines
net/xdp/xsk_pp.c +0 -0
index fdd55265a6cdc..c2214e718cdb3 100644

[ ... ]

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+	mp.mp_priv = pp;
+	mp.rx_page_size = pool->chunk_size;
+	mp.rx_headroom = xsk_pool_get_headroom(pool);
+	err = netif_mp_open_rxq(dev, queue_id, &mp, NULL);
+	if (!err) {
+		pp->rxq = __netif_get_rx_queue(dev, queue_id);
+		pool->pp = pp;
+		pool->xdp_zc_max_segs = dev->xdp_zc_max_segs;
+		return 0;
+	}

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 450

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+
+	xp_dma_unmap(pool, XSK_PP_DMA_ATTR);
+	/* Copy mode takes the chunks that the provider holds */
+	if (!xp_alloc_heads(pool) && xsk_pp_abandon(pp))
+		xsk_pp_put(pp);
+	else
+		pool->pp = pp;
+
+	return err;
+}

[Severity: High]
If netif_mp_open_rxq() fails after ndo_queue_mem_alloc() has created a page_pool that attached to pp, can this error path cause a use-after-free of pool and UMEM?

When page_pool_destroy() defers destruction because chunks are still held (pp->nr_pools > 0), or when xp_alloc_heads(pool) fails:

1. xp_dma_unmap() runs unconditionally before xsk_pp_abandon(), unmapping DMA pages while the lingering page_pool still owns chunks.
2. xsk_pp_bind() sets pool->pp = pp without clearing pp->fq, and xp_assign_dev() skips the copy-mode fallback because pool->pp is set, returning err to xsk_bind().
3. xsk_bind() calls xp_destroy(xs->pool), which drops only pool's reference on pp via xsk_pp_put(pool->pp) and immediately kvfree()s pool:

net/xdp/xsk.c:xsk_bind() {
	...
		err = xp_assign_dev(xs->pool, dev, qid, flags);
		if (err) {
			xp_destroy(xs->pool);
			xs->pool = NULL;
			goto out_unlock;
		}
	...
}

The lingering page_pool still holds its reference to pp, leaving pp->pool dangling (dereferenced in xsk_pp_alloc_fill() and xsk_pp_refill_done()) and pp->fq pointing to xs->fq_tmp. Because xs->pool is now NULL and xs->state remains XSK_READY, closing the socket frees xs->fq_tmp and calls xdp_put_umem(xs->umem, true), which vunmaps umem->addrs and unpins umem->pgs while the page_pool still holds chunks.

Quoted 6 lines
net/xdp/xsk_pp.c +6 -0
+/* Called with RTNL and the instance lock of the device */
+void xsk_pp_unbind(struct xsk_buff_pool *pool)
+{
+	struct xsk_pp *pp = pool->pp;
+	struct pp_memory_provider_params mp = {
+		.mp_ops = &xsk_pp_ops,

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 467

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+		.mp_priv = pp,
+	};
+
+	/* Unregister removed the provider already */
+	if (!pp->rxq)
+		return;
+
+	netif_mp_close_rxq(pool->netdev, pool->queue_id, &mp);
+	xsk_pp_detach(pp);
+}

[Severity: High]
Can xsk_pp_unbind() and xp_release_deferred() unmap DMA and free the pool and UMEM while the RX queue or page_pool is still using them?

xsk_pp_unbind() ignores the return value of netif_mp_close_rxq() and unconditionally calls xsk_pp_detach(pp) -> xp_dma_unmap(). If netif_mp_close_rxq() fails (for example, -ENOMEM when allocating replacement queue memory in netdev_rx_queue_reconfig()), the hardware RX queue remains active on the unmapped UMEM pages.

Furthermore, right after xp_clear_dev() returns in xp_release_deferred(), xdp_put_umem(pool->umem, false) unpins and vunmaps the UMEM and xp_destroy(pool) frees pool, even if netif_mp_close_rxq() failed or page_pool_destroy() deferred releasing in-flight netmems (pp->refs > 0).

[1] https://sashiko.dev/#/bug/linux-47dd1618-68d7-4419-9441-df54e8f32d4d

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#52 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider.

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

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

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

- [High] xsk_pp_unbind() in net/xdp/xsk_pp.c ignores the return value of netif_mp_close_rxq() and always calls xsk_pp_detach().
- [High] xsk: UAF of pool and UMEM on xsk_pp_bind() failure with active page_pool

--

xsk: Install UMEM page pool providers in the core

This commit installs the AF_XDP UMEM as a page pool memory provider through the queue management API, for drivers that set netdev_queue_mgmt_ops.xsk_page_pool. Drivers check the chunk size, headroom and multi-buffer setup in XDP_VALIDATE_XSK_POOL. The core then verifies, using a per-queue mp_gen, that the new page pools picked up the provider.

Quoted 4 lines
net/xdp/xsk_pp.c +0 -0
index fdd55265a6cdc..c2214e718cdb3 100644

[ ... ]

Quoted 13 lines
net/xdp/xsk_pp.c +9 -0
@@ -236,11 +243,225 @@ static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
 	return 0;
 }
 
+/* The queue no longer uses the provider, and its DMA stopped */
+static void xsk_pp_detach(struct xsk_pp *pp)
+{
+	pp->rxq = NULL;
+	spin_lock_bh(&pp->lock);
+	pp->fq = NULL;
+	spin_unlock_bh(&pp->lock);
+	xp_dma_unmap(pp->pool, XSK_PP_DMA_ATTR);
+}

[ ... ]

Quoted 6 lines
net/xdp/xsk_pp.c +6 -0
+/* Called with RTNL and the instance lock of the device */
+void xsk_pp_unbind(struct xsk_buff_pool *pool)
+{
+	struct xsk_pp *pp = pool->pp;
+	struct pp_memory_provider_params mp = {
+		.mp_ops = &xsk_pp_ops,

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 467

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+		.mp_priv = pp,
+	};
+
+	/* Unregister removed the provider already */
+	if (!pp->rxq)
+		return;
+
+	netif_mp_close_rxq(pool->netdev, pool->queue_id, &mp);
+	xsk_pp_detach(pp);
+}

[Severity: High]
What happens here if netif_mp_close_rxq() fails? xsk_pp_unbind() drops its return value and always calls xsk_pp_detach(), and that unmaps the UMEM DMA.

netif_mp_close_rxq() can return an error after the reconfig fails:

net/core/netdev_rx_queue.c:__netif_mp_close_rxq() {
    ...
	memset(&rxq->mp_params, 0, sizeof(rxq->mp_params));
	netdev_queue_config(dev, rxq_idx, &qcfg[1]);

	err = netdev_rx_queue_reconfig(dev, rxq_idx, &qcfg[0], &qcfg[1]);
	if (err == -ENETDOWN)
		return 0;
	WARN_ON(err);
	return err;
}

netdev_rx_queue_reconfig() can fail in several places:

- kvzalloc() of new_mem or old_mem
- ndo_queue_mem_alloc()
- ndo_queue_stop()
- ndo_queue_start(), which falls back to restarting the old queue

In each case the old queue keeps running. Its page pools still have mp_priv == pp and mp_ops == &xsk_pp_ops, and the hardware RX ring still holds UMEM chunk DMA addresses.

The teardown then continues:

xp_release_deferred()
xp_clear_dev()

    __xp_clear_dev()
      xsk_pp_unbind()
        netif_mp_close_rxq()   <- fails, result dropped
        xsk_pp_detach()
          xp_dma_unmap()

xdp_put_umem() <- vunmap(umem->addrs), unpin pages
xp_destroy(pool) <- frees the xsk_buff_pool

The surviving page pools hold a reference on the xsk_pp only, taken in xsk_pp_init(). They hold none on the DMA mapping, the UMEM pages or the xsk_buff_pool.

Can the NIC then DMA into unmapped IOVAs? Without an IOMMU, can it DMA into unpinned pages that may already be reused?

Also, xsk_pp_alloc_reuse() would keep recycling chunks with stale DMA addresses. CPU reads through pp->area.vaddr would hit the vunmapped umem->addrs, and pp->pool would point to the freed xsk_buff_pool.

Devmem doesn't seem to have this problem, because its page pools pin the binding and the DMA unmap happens on the last reference drop. Here the unmap happens no matter what pp->nr_pools is.

netif_rxq_cleanup_unlease() seems to follow the same pattern:

	__netif_mp_close_rxq(phys_rxq->dev, rxq_idx, &p);
	__netif_mp_uninstall_rxq(virt_rxq, &p);

It ignores the close result and then reaches xsk_pp_uninstall(), which calls xsk_pp_detach().

No driver sets xsk_page_pool at this commit. fbnic opts in later in the series, and its queue mem_alloc can fail with -ENOMEM.

A later patch in the series adds synchronize_net() before xp_dma_unmap() in this path. That doesn't seem to help when the old queue is still running.

Should xsk_pp_detach() be skipped, or the DMA unmap and UMEM release be deferred until pp->nr_pools drops to zero, when the close fails?

[ ... ]

Quoted 216 lines
net/xdp/xsk_pp.c +204 -0
@@ -236,11 +243,225 @@ static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
 	return 0;
 }
 
+/* The queue no longer uses the provider, and its DMA stopped */
+static void xsk_pp_detach(struct xsk_pp *pp)
+{
+	pp->rxq = NULL;
+	spin_lock_bh(&pp->lock);
+	pp->fq = NULL;
+	spin_unlock_bh(&pp->lock);
+	xp_dma_unmap(pp->pool, XSK_PP_DMA_ATTR);
+}
+
+/* The device unregisters, and is closed */
+static void xsk_pp_uninstall(void *mp_priv, struct netdev_rx_queue *rxq)
+{
+	xsk_pp_detach(mp_priv);
+}
+
 const struct memory_provider_ops xsk_pp_ops = {
 	.init		= xsk_pp_init,
 	.destroy	= xsk_pp_destroy,
 	.alloc_netmems	= xsk_pp_alloc_netmems,
 	.release_netmem	= xsk_pp_release_netmem,
 	.nl_fill	= xsk_pp_nl_fill,
+	.uninstall	= xsk_pp_uninstall,
 	.caps		= MP_CAP_READABLE,
 };
+
+static bool xsk_pp_abandon(struct xsk_pp *pp)
+{
+	struct xsk_buff_pool *pool = pp->pool;
+	bool busy;
+	u32 idx;
+
+	spin_lock_bh(&pp->lock);
+	busy = pp->nr_pools;
+	while (!busy && pp->reuse_cnt) {
+		idx = pp->reuse[--pp->reuse_cnt];
+		pp->state[idx] = XSK_PP_USER;
+		xp_free(&pool->heads[idx]);
+	}
+	spin_unlock_bh(&pp->lock);
+
+	return !busy;
+}
+
+static int xsk_pp_validate(struct net_device *dev, struct xsk_buff_pool *pool,
+			   unsigned int mtu, struct bpf_prog *prog,
+			   struct netlink_ext_ack *extack)
+{
+	struct xsk_rx_check check = {
+		.buf_size = pool->chunk_size,
+		.headroom = xsk_pool_get_headroom(pool),
+		.mtu = mtu,
+		.sg = xsk_pool_uses_sg(pool),
+		.prog = prog,
+	};
+	struct netdev_bpf bpf = {
+		.command = XDP_VALIDATE_XSK_POOL,
+		.xsk_check.check = &check,
+		.xsk_check.extack = extack,
+	};
+
+	return dev->netdev_ops->ndo_bpf(dev, &bpf);
+}
+
+/**
+ * xsk_validate_dev - check AF_XDP page pool queues against a new setting
+ * @dev: device of the queues
+ * @mtu: MTU to check
+ * @prog: XDP program to check, or NULL for the current one
+ * @mode: XDP mode of @prog
+ * @extack: netlink extended ack
+ *
+ * Context: holds the instance lock of @dev, or RTNL for a device without it.
+ * Return: 0 if the driver accepts all queues of @dev that have an AF_XDP
+ * memory provider, or its error.
+ */
+int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+		     struct bpf_prog *prog, enum bpf_xdp_mode mode,
+		     struct netlink_ext_ack *extack)
+{
+	struct netdev_rx_queue *rxq;
+	struct xsk_pp *pp;
+	unsigned int i;
+	int err;
+
+	netdev_assert_locked_ops_compat(dev);
+
+	for (i = 0; i < dev->real_num_rx_queues; i++) {
+		rxq = __netif_get_rx_queue(dev, i);
+		if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+			continue;
+
+		/* Generic XDP runs outside the queue NAPI */
+		if (mode == XDP_MODE_SKB) {
+			NL_SET_ERR_MSG(extack,
+				       "generic XDP cannot feed an AF_XDP page pool socket");
+			return -EBUSY;
+		}
+
+		pp = rxq->mp_params.mp_priv;
+		err = xsk_pp_validate(dev, pp->pool, mtu, prog, extack);
+		if (err)
+			return err;
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(xsk_validate_dev);
+
+/**
+ * xsk_rxq_pool - get the AF_XDP pool that provides memory to an RX queue
+ * @dev: device of the queue
+ * @queue_id: RX queue
+ *
+ * The pool stays valid while the queue that the caller allocates runs.
+ *
+ * Context: holds the instance lock of @dev.
+ * Return: the buffer pool, or NULL.
+ */
+struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev, u16 queue_id)
+{
+	struct netdev_rx_queue *rxq;
+	struct xsk_pp *pp;
+
+	netdev_assert_locked(dev);
+
+	if (queue_id >= dev->real_num_rx_queues)
+		return NULL;
+
+	rxq = __netif_get_rx_queue(dev, queue_id);
+	if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+		return NULL;
+
+	pp = rxq->mp_params.mp_priv;
+	return pp->pool;
+}
+EXPORT_SYMBOL_GPL(xsk_rxq_pool);
+
+bool xsk_pp_supported(struct net_device *dev)
+{
+	const struct netdev_queue_mgmt_ops *qops = dev->queue_mgmt_ops;
+
+	return qops && qops->xsk_page_pool;
+}
+
+/* Called with RTNL and the instance lock of @dev. On error, @pool->pp stays
+ * set if an old page pool still owns chunks; copy mode must not take the pool.
+ */
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+		u16 queue_id)
+{
+	struct pp_memory_provider_params mp = { .mp_ops = &xsk_pp_ops };
+	struct device *dma_dev;
+	struct xsk_pp *pp;
+	int err;
+
+	if (queue_id >= dev->real_num_rx_queues || pool->unaligned)
+		return -EOPNOTSUPP;
+	if ((dev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK ||
+	    (xsk_pool_uses_sg(pool) && dev->xdp_zc_max_segs == 1))
+		return -EOPNOTSUPP;
+	if (dev_xdp_prog_id(dev, XDP_MODE_SKB))
+		return -EOPNOTSUPP;
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE))
+		return -EBUSY;
+
+	err = xsk_pp_validate(dev, pool, dev->mtu, NULL, NULL);
+	if (err)
+		return err;
+
+	dma_dev = netdev_queue_get_dma_dev(dev, queue_id, NETDEV_QUEUE_TYPE_RX);
+	if (!dma_dev)
+		return -EOPNOTSUPP;
+
+	err = xp_dma_map(pool, dma_dev, XSK_PP_DMA_ATTR, pool->umem->pgs,
+			 pool->umem->npgs);
+	if (err)
+		return err;
+
+	pp = xsk_pp_create(pool);
+	if (IS_ERR(pp)) {
+		xp_dma_unmap(pool, XSK_PP_DMA_ATTR);
+		return PTR_ERR(pp);
+	}
+
+	mp.mp_priv = pp;
+	mp.rx_page_size = pool->chunk_size;
+	mp.rx_headroom = xsk_pool_get_headroom(pool);
+	err = netif_mp_open_rxq(dev, queue_id, &mp, NULL);
+	if (!err) {
+		pp->rxq = __netif_get_rx_queue(dev, queue_id);
+		pool->pp = pp;
+		pool->xdp_zc_max_segs = dev->xdp_zc_max_segs;
+		return 0;
+	}
+
+	xp_dma_unmap(pool, XSK_PP_DMA_ATTR);
+	/* Copy mode takes the chunks that the provider holds */
+	if (!xp_alloc_heads(pool) && xsk_pp_abandon(pp))
+		xsk_pp_put(pp);
+	else
+		pool->pp = pp;
+
+	return err;
+}
+
+/* Called with RTNL and the instance lock of the device */
+void xsk_pp_unbind(struct xsk_buff_pool *pool)
+{
+	struct xsk_pp *pp = pool->pp;
+	struct pp_memory_provider_params mp = {
+		.mp_ops = &xsk_pp_ops,

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 467

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+		.mp_priv = pp,
+	};
+
+	/* Unregister removed the provider already */
+	if (!pp->rxq)
+		return;
+
+	netif_mp_close_rxq(pool->netdev, pool->queue_id, &mp);
+	xsk_pp_detach(pp);
+}

[Severity: High]
What keeps the buffer pool and the UMEM alive when this error path leaves pool->pp set?

netif_mp_open_rxq() can fail after ndo_queue_mem_alloc() has already created page pools that selected the provider. That happens when page_pool_check_memory_provider() returns -ENODATA, and when ndo_queue_stop() or ndo_queue_start() fails. Each of those page pools took a reference and bumped pp->nr_pools in xsk_pp_init().

If ndo_queue_mem_free() leaves one of them in deferred destruction because chunks are still out, xsk_pp_abandon() returns false and pool->pp is set. The same happens when xp_alloc_heads() fails with -ENOMEM.

By that point xp_dma_unmap() has already run unconditionally. The lingering page pool may still own chunks whose DMA addresses came from that mapping. pp->fq is also left pointing at the fill queue, unlike in xsk_pp_detach().

xp_assign_dev() then sees pool->pp set, skips the copy mode fallback and returns the error. xsk_bind() destroys the pool right away:

	err = xp_assign_dev(xs->pool, dev, qid, flags);
	if (err) {
		xp_destroy(xs->pool);
		xs->pool = NULL;
		goto out_unlock;
	}

xp_destroy() drops only the buffer pool's reference on the xsk_pp. The xsk_pp survives on the page pool's reference, and then the xsk_buff_pool is freed, which leaves pp->pool dangling.

The socket stays in XSK_READY, so on close xsk_release() frees xs->fq_tmp, which pp->fq still points to. xsk_destruct() then calls xdp_put_umem(), which vunmaps umem->addrs (pp->area.vaddr) and unpins the UMEM pages. The lingering page pool still holds chunks backed by those pages.

When that page pool finally returns its chunks, won't the provider ops reach pp->pool, pp->fq or pp->area.vaddr after they are gone?

The comment above xsk_pp_bind() says pool->pp stays set so that copy mode does not take the pool. But the caller frees the pool anyway, so what does keeping pool->pp set protect? A second bind() on the same socket also gets a fresh pool with pool->pp == NULL for the same UMEM, so the pool->pp check in xp_assign_dev() does not help there either.

Should the xsk_pp pin the buffer pool and the UMEM, and do the DMA unmap in xsk_pp_free(), so they outlive the last page pool? Or should xsk_bind() defer releasing the pool in this case?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261110102039.1002605-1-bjorn%40kernel.org
#53 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

[email protected] writes:

[...]

Quoted 2 lines

Should xsk_pp_detach() be skipped, or the DMA unmap and UMEM release be deferred until pp->nr_pools drops to zero, when the close fails?

Deferred. A failed restart leaves the old queue running on the provider. I have a net fix that keeps the provider on such a queue and retries the removal, which also covers netif_rxq_cleanup_unlease(); I might add a fix in v2 that unmaps and releases the UMEM only once the queue DMA has stopped.

[...]

Quoted 3 lines

Should the xsk_pp pin the buffer pool and the UMEM, and do the DMA unmap in xsk_pp_free(), so they outlive the last page pool? Or should xsk_bind() defer releasing the pool in this case?

This case can't happen. The page pools of a failed open never hold a chunk. fbnic fills its rings only in ndo_queue_start(), which can't fail, so a failed open frees empty pools, and they're destroyed at once. pool->pp protects nothing there, so v2 drops that branch for a WARN.

Björn

#54 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

In reply to Björn Töpel
Quoted 40 lines · Björn Töpel

A page_pool driver should not need its own AF_XDP setup. When it sets netdev_queue_mgmt_ops.xsk_page_pool, a zero-copy bind installs the UMEM provider through the queue API, as devmem and io_uring do. The driver only judges the chunk size, headroom and multi-buffer mode against its MTU and XDP program, in XDP_VALIDATE_XSK_POOL; MTU and program changes of a bound device get the same check. The UMEM headroom belongs to the socket, so the queue gets it as rx_headroom, next to rx_page_size.

After a queue restart, the core checks that the new page pools took the provider. A readable provider must back the header pool, where an unsplit packet lands, so pools declare the buffers they supply in rx_roles. The old queue's pools carry the same provider during the check, so a per-queue generation, mp_gen, tells the new ones apart.

Generic XDP runs outside the queue NAPI, so it cannot feed the socket.

The provider needs no xdp_buff_xsk per chunk. The buffer pool allocates them only for copy mode and driver zero copy, which saves 128 bytes per chunk.

---
 include/linux/netdevice.h     |   8 ++
 include/net/netdev_queues.h   |  12 ++
 include/net/netdev_rx_queue.h |   2 +
 include/net/page_pool/types.h |  12 ++
 include/net/xdp_sock.h        |   4 +
 include/net/xdp_sock_drv.h    |  45 +++++++
 include/net/xsk_buff_pool.h   |   3 +
 net/core/dev.c                |  16 +++
 net/core/netdev_config.c      |   2 +
 net/core/netdev_rx_queue.c    |   9 +-
 net/core/page_pool.c          |   6 +-
 net/core/page_pool_user.c     |  25 ++--
 net/xdp/xsk.h                 |   7 +-
 net/xdp/xsk_buff_pool.c       |  69 ++++++++---
 net/xdp/xsk_pp.c              | 221 ++++++++++++++++++++++++++++++++++
 15 files changed, 410 insertions(+), 31 deletions(-)

(...)

Quoted 88 lines
net/xdp/xsk_pp.c +88 -0
+
+/**
+ * xsk_validate_dev - check AF_XDP page pool queues against a new setting
+ * @dev: device of the queues
+ * @mtu: MTU to check
+ * @prog: XDP program to check, or NULL for the current one
+ * @mode: XDP mode of @prog
+ * @extack: netlink extended ack
+ *
+ * Context: holds the instance lock of @dev, or RTNL for a device without it.
+ * Return: 0 if the driver accepts all queues of @dev that have an AF_XDP
+ * memory provider, or its error.
+ */
+int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+		     struct bpf_prog *prog, enum bpf_xdp_mode mode,
+		     struct netlink_ext_ack *extack)
+{
+	struct netdev_rx_queue *rxq;
+	struct xsk_pp *pp;
+	unsigned int i;
+	int err;
+
+	netdev_assert_locked_ops_compat(dev);
+
+	for (i = 0; i < dev->real_num_rx_queues; i++) {
+		rxq = __netif_get_rx_queue(dev, i);
+		if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+			continue;
+
+		/* Generic XDP runs outside the queue NAPI */
+		if (mode == XDP_MODE_SKB) {
+			NL_SET_ERR_MSG(extack,
+				       "generic XDP cannot feed an AF_XDP page pool socket");
+			return -EBUSY;
+		}
+
+		pp = rxq->mp_params.mp_priv;
+		err = xsk_pp_validate(dev, pp->pool, mtu, prog, extack);
+		if (err)
+			return err;
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(xsk_validate_dev);
+
+/**
+ * xsk_rxq_pool - get the AF_XDP pool that provides memory to an RX queue
+ * @dev: device of the queue
+ * @queue_id: RX queue
+ *
+ * The pool stays valid while the queue that the caller allocates runs.
+ *
+ * Context: holds the instance lock of @dev.
+ * Return: the buffer pool, or NULL.
+ */
+struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev, u16 queue_id)
+{
+	struct netdev_rx_queue *rxq;
+	struct xsk_pp *pp;
+
+	netdev_assert_locked(dev);
+
+	if (queue_id >= dev->real_num_rx_queues)
+		return NULL;
+
+	rxq = __netif_get_rx_queue(dev, queue_id);
+	if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+		return NULL;
+
+	pp = rxq->mp_params.mp_priv;
+	return pp->pool;
+}
+EXPORT_SYMBOL_GPL(xsk_rxq_pool);
+
+bool xsk_pp_supported(struct net_device *dev)
+{
+	const struct netdev_queue_mgmt_ops *qops = dev->queue_mgmt_ops;
+
+	return qops && qops->xsk_page_pool;
+}
+
+/* Called with RTNL and the instance lock of @dev. On error, @pool->pp stays
+ * set if an old page pool still owns chunks; copy mode must not take the pool.
+ */
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+		u16 queue_id)
+{

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 406

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+	struct pp_memory_provider_params mp = { .mp_ops = &xsk_pp_ops };
+	struct device *dma_dev;
+	struct xsk_pp *pp;
+	int err;
+
+	if (queue_id >= dev->real_num_rx_queues || pool->unaligned)
+		return -EOPNOTSUPP;
+	if ((dev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK ||
+	    (xsk_pool_uses_sg(pool) && dev->xdp_zc_max_segs == 1))
+		return -EOPNOTSUPP;

that is checked elsewhere, in xp_assign_dev() I assume.

Why there are skb mode checks?

You sort of introduce totally separate control path and rx data path. It is hard for me to buy onto the management burden of all this new code :(

I believe we should break this up onto smaller chunks and don't try to solve everything within a single set...or wil that not be possible?

Quoted 7 lines
net/xdp/xsk_pp.c +7 -0
+	if (dev_xdp_prog_id(dev, XDP_MODE_SKB))
+		return -EOPNOTSUPP;
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE))
+		return -EBUSY;
+
+	err = xsk_pp_validate(dev, pool, dev->mtu, NULL, NULL);
+	if (err)

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 423

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+		return err;
+
+	dma_dev = netdev_queue_get_dma_dev(dev, queue_id, NETDEV_QUEUE_TYPE_RX);
+	if (!dma_dev)
+		return -EOPNOTSUPP;
+
+	err = xp_dma_map(pool, dma_dev, XSK_PP_DMA_ATTR, pool->umem->pgs,
+			 pool->umem->npgs);
+	if (err)
+		return err;

Couldn't we have this part common across drivers wanting to do ZC?

Quoted 47 lines
net/xdp/xsk_pp.c +44 -0
+
+	pp = xsk_pp_create(pool);
+	if (IS_ERR(pp)) {
+		xp_dma_unmap(pool, XSK_PP_DMA_ATTR);
+		return PTR_ERR(pp);
+	}
+
+	mp.mp_priv = pp;
+	mp.rx_page_size = pool->chunk_size;
+	mp.rx_headroom = xsk_pool_get_headroom(pool);
+	err = netif_mp_open_rxq(dev, queue_id, &mp, NULL);
+	if (!err) {
+		pp->rxq = __netif_get_rx_queue(dev, queue_id);
+		pool->pp = pp;
+		pool->xdp_zc_max_segs = dev->xdp_zc_max_segs;
+		return 0;
+	}
+
+	xp_dma_unmap(pool, XSK_PP_DMA_ATTR);
+	/* Copy mode takes the chunks that the provider holds */
+	if (!xp_alloc_heads(pool) && xsk_pp_abandon(pp))
+		xsk_pp_put(pp);
+	else
+		pool->pp = pp;
+
+	return err;
+}
+
+/* Called with RTNL and the instance lock of the device */
+void xsk_pp_unbind(struct xsk_buff_pool *pool)
+{
+	struct xsk_pp *pp = pool->pp;
+	struct pp_memory_provider_params mp = {
+		.mp_ops = &xsk_pp_ops,
+		.mp_priv = pp,
+	};
+
+	/* Unregister removed the provider already */
+	if (!pp->rxq)
+		return;
+
+	netif_mp_close_rxq(pool->netdev, pool->queue_id, &mp);
+	xsk_pp_detach(pp);
+}
Signature · 1 line
2.56.0
#55 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

Quoted 136 lines · Maciej Fijalkowski
Quoted 40 lines · Björn Töpel

A page_pool driver should not need its own AF_XDP setup. When it sets netdev_queue_mgmt_ops.xsk_page_pool, a zero-copy bind installs the UMEM provider through the queue API, as devmem and io_uring do. The driver only judges the chunk size, headroom and multi-buffer mode against its MTU and XDP program, in XDP_VALIDATE_XSK_POOL; MTU and program changes of a bound device get the same check. The UMEM headroom belongs to the socket, so the queue gets it as rx_headroom, next to rx_page_size.

After a queue restart, the core checks that the new page pools took the provider. A readable provider must back the header pool, where an unsplit packet lands, so pools declare the buffers they supply in rx_roles. The old queue's pools carry the same provider during the check, so a per-queue generation, mp_gen, tells the new ones apart.

Generic XDP runs outside the queue NAPI, so it cannot feed the socket.

The provider needs no xdp_buff_xsk per chunk. The buffer pool allocates them only for copy mode and driver zero copy, which saves 128 bytes per chunk.

---
 include/linux/netdevice.h     |   8 ++
 include/net/netdev_queues.h   |  12 ++
 include/net/netdev_rx_queue.h |   2 +
 include/net/page_pool/types.h |  12 ++
 include/net/xdp_sock.h        |   4 +
 include/net/xdp_sock_drv.h    |  45 +++++++
 include/net/xsk_buff_pool.h   |   3 +
 net/core/dev.c                |  16 +++
 net/core/netdev_config.c      |   2 +
 net/core/netdev_rx_queue.c    |   9 +-
 net/core/page_pool.c          |   6 +-
 net/core/page_pool_user.c     |  25 ++--
 net/xdp/xsk.h                 |   7 +-
 net/xdp/xsk_buff_pool.c       |  69 ++++++++---
 net/xdp/xsk_pp.c              | 221 ++++++++++++++++++++++++++++++++++
 15 files changed, 410 insertions(+), 31 deletions(-)

(...)

Quoted 92 lines
net/xdp/xsk_pp.c +92 -0
+
+/**
+ * xsk_validate_dev - check AF_XDP page pool queues against a new setting
+ * @dev: device of the queues
+ * @mtu: MTU to check
+ * @prog: XDP program to check, or NULL for the current one
+ * @mode: XDP mode of @prog
+ * @extack: netlink extended ack
+ *
+ * Context: holds the instance lock of @dev, or RTNL for a device without it.
+ * Return: 0 if the driver accepts all queues of @dev that have an AF_XDP
+ * memory provider, or its error.
+ */
+int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+		     struct bpf_prog *prog, enum bpf_xdp_mode mode,
+		     struct netlink_ext_ack *extack)
+{
+	struct netdev_rx_queue *rxq;
+	struct xsk_pp *pp;
+	unsigned int i;
+	int err;
+
+	netdev_assert_locked_ops_compat(dev);
+
+	for (i = 0; i < dev->real_num_rx_queues; i++) {
+		rxq = __netif_get_rx_queue(dev, i);
+		if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+			continue;
+
+		/* Generic XDP runs outside the queue NAPI */
+		if (mode == XDP_MODE_SKB) {
+			NL_SET_ERR_MSG(extack,
+				       "generic XDP cannot feed an AF_XDP page pool socket");
+			return -EBUSY;
+		}
+
+		pp = rxq->mp_params.mp_priv;
+		err = xsk_pp_validate(dev, pp->pool, mtu, prog, extack);
+		if (err)
+			return err;
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(xsk_validate_dev);
+
+/**
+ * xsk_rxq_pool - get the AF_XDP pool that provides memory to an RX queue
+ * @dev: device of the queue
+ * @queue_id: RX queue
+ *
+ * The pool stays valid while the queue that the caller allocates runs.
+ *
+ * Context: holds the instance lock of @dev.
+ * Return: the buffer pool, or NULL.
+ */
+struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev, u16 queue_id)
+{
+	struct netdev_rx_queue *rxq;
+	struct xsk_pp *pp;
+
+	netdev_assert_locked(dev);
+
+	if (queue_id >= dev->real_num_rx_queues)
+		return NULL;
+
+	rxq = __netif_get_rx_queue(dev, queue_id);
+	if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+		return NULL;
+
+	pp = rxq->mp_params.mp_priv;
+	return pp->pool;
+}
+EXPORT_SYMBOL_GPL(xsk_rxq_pool);
+
+bool xsk_pp_supported(struct net_device *dev)
+{
+	const struct netdev_queue_mgmt_ops *qops = dev->queue_mgmt_ops;
+
+	return qops && qops->xsk_page_pool;
+}
+
+/* Called with RTNL and the instance lock of @dev. On error, @pool->pp stays
+ * set if an old page pool still owns chunks; copy mode must not take the pool.
+ */
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+		u16 queue_id)
+{
+	struct pp_memory_provider_params mp = { .mp_ops = &xsk_pp_ops };
+	struct device *dma_dev;
+	struct xsk_pp *pp;
+	int err;
Quoted 8 lines

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 406

Quoted 6 lines
net/xdp/xsk_pp.c +6 -0
+
+	if (queue_id >= dev->real_num_rx_queues || pool->unaligned)
+		return -EOPNOTSUPP;
+	if ((dev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK ||
+	    (xsk_pool_uses_sg(pool) && dev->xdp_zc_max_segs == 1))
+		return -EOPNOTSUPP;

that is checked elsewhere, in xp_assign_dev() I assume.

Ah, yes! I'll do the common checks first in xp_assign_dev(), and branch after.

Quoted 1 line

Why there are skb mode checks?

(Note to self: I need to make some details/designs more obvious in the cover!)

Because the provider is turned on by the queue API at bind, not by an XDP program. This is a big difference. Once the socket is bound, the queue's page pool hands the device chunks from FILL, whatever program is
attached: native, generic or none. A generic redirect would copy into a chunk taken from FILL behind the provider's back, and a provider pool doesn't have the heads that copy path needs. So 07 drops those redirects.

The checks make that visible (I hope): with a generic program attached, bind falls back to copy mode, where generic XDP works, and attaching one to a provider queue fails instead of dropping everything.

Driver ZC is different: ice and i40e use the pool only while a native program is attached, so with a generic one the queue runs on normal buffers, and the copy is the only FILL user.

Quoted 5 lines

You sort of introduce totally separate control path and rx data path. It is hard for me to buy onto the management burden of all this new code :(

I believe we should break this up onto smaller chunks and don't try to solve everything within a single set...or wil that not be possible?

Separate from driver ZC, yes, but not new: the provider binds the way devmem and io_uring zcrx do, netif_mp_open_rxq() and a queue restart, and the driver keeps its normal page pool RX path, with no ZC RX loop of its own. The cost moves into the AF_XDP core, and xsk_pp.c is real code, I know.

It can be split:

1. preparation, no new behaviour: netmem frag addresses, the page pool caps, fbnic's redirect and netmem patches, the TX metadata fix;
2. the provider for single-buffer packets, with fbnic, without the copy fallback or fbnic's shared header/payload pool;
3. multi-buffer.

Not sure it would help much TBH.

The provider, its bind and the delivery need a driver to land, so 2 is the smallest set that does something. v2 also loses some things (but I'd like to keep the validate ndo_bpf), e.g. nr_pools and the duplicate checks. And I'm happy to look after xsk_pp.c. Would that work for you?

Quoted 11 lines
Quoted 11 lines
net/xdp/xsk_pp.c +11 -0
+	if (dev_xdp_prog_id(dev, XDP_MODE_SKB))
+		return -EOPNOTSUPP;
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE))
+		return -EBUSY;
+
+	err = xsk_pp_validate(dev, pool, dev->mtu, NULL, NULL);
+	if (err)
+		return err;
+
+	dma_dev = netdev_queue_get_dma_dev(dev, queue_id, NETDEV_QUEUE_TYPE_RX);
+	if (!dma_dev)
Quoted 8 lines

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 423

Quoted 6 lines
net/xdp/xsk_pp.c +6 -0
+		return -EOPNOTSUPP;
+
+	err = xp_dma_map(pool, dma_dev, XSK_PP_DMA_ATTR, pool->umem->pgs,
+			 pool->umem->npgs);
+	if (err)
+		return err;

Couldn't we have this part common across drivers wanting to do ZC?

It is: this is core code, and no provider driver maps UMEM itself; netdev_queue_get_dma_dev() gives the core the device, as for io_uring zcrx. Driver ZC could map in xp_assign_dev() too, but drivers differ in DMA device and attributes, so that's its own series.

Björn

#56 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

Quoted 163 lines · Björn Töpel
Quoted 136 lines · Maciej Fijalkowski
Quoted 40 lines · Björn Töpel

A page_pool driver should not need its own AF_XDP setup. When it sets netdev_queue_mgmt_ops.xsk_page_pool, a zero-copy bind installs the UMEM provider through the queue API, as devmem and io_uring do. The driver only judges the chunk size, headroom and multi-buffer mode against its MTU and XDP program, in XDP_VALIDATE_XSK_POOL; MTU and program changes of a bound device get the same check. The UMEM headroom belongs to the socket, so the queue gets it as rx_headroom, next to rx_page_size.

After a queue restart, the core checks that the new page pools took the provider. A readable provider must back the header pool, where an unsplit packet lands, so pools declare the buffers they supply in rx_roles. The old queue's pools carry the same provider during the check, so a per-queue generation, mp_gen, tells the new ones apart.

Generic XDP runs outside the queue NAPI, so it cannot feed the socket.

The provider needs no xdp_buff_xsk per chunk. The buffer pool allocates them only for copy mode and driver zero copy, which saves 128 bytes per chunk.

---
 include/linux/netdevice.h     |   8 ++
 include/net/netdev_queues.h   |  12 ++
 include/net/netdev_rx_queue.h |   2 +
 include/net/page_pool/types.h |  12 ++
 include/net/xdp_sock.h        |   4 +
 include/net/xdp_sock_drv.h    |  45 +++++++
 include/net/xsk_buff_pool.h   |   3 +
 net/core/dev.c                |  16 +++
 net/core/netdev_config.c      |   2 +
 net/core/netdev_rx_queue.c    |   9 +-
 net/core/page_pool.c          |   6 +-
 net/core/page_pool_user.c     |  25 ++--
 net/xdp/xsk.h                 |   7 +-
 net/xdp/xsk_buff_pool.c       |  69 ++++++++---
 net/xdp/xsk_pp.c              | 221 ++++++++++++++++++++++++++++++++++
 15 files changed, 410 insertions(+), 31 deletions(-)

(...)

Quoted 92 lines
net/xdp/xsk_pp.c +92 -0
+
+/**
+ * xsk_validate_dev - check AF_XDP page pool queues against a new setting
+ * @dev: device of the queues
+ * @mtu: MTU to check
+ * @prog: XDP program to check, or NULL for the current one
+ * @mode: XDP mode of @prog
+ * @extack: netlink extended ack
+ *
+ * Context: holds the instance lock of @dev, or RTNL for a device without it.
+ * Return: 0 if the driver accepts all queues of @dev that have an AF_XDP
+ * memory provider, or its error.
+ */
+int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+		     struct bpf_prog *prog, enum bpf_xdp_mode mode,
+		     struct netlink_ext_ack *extack)
+{
+	struct netdev_rx_queue *rxq;
+	struct xsk_pp *pp;
+	unsigned int i;
+	int err;
+
+	netdev_assert_locked_ops_compat(dev);
+
+	for (i = 0; i < dev->real_num_rx_queues; i++) {
+		rxq = __netif_get_rx_queue(dev, i);
+		if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+			continue;
+
+		/* Generic XDP runs outside the queue NAPI */
+		if (mode == XDP_MODE_SKB) {
+			NL_SET_ERR_MSG(extack,
+				       "generic XDP cannot feed an AF_XDP page pool socket");
+			return -EBUSY;
+		}
+
+		pp = rxq->mp_params.mp_priv;
+		err = xsk_pp_validate(dev, pp->pool, mtu, prog, extack);
+		if (err)
+			return err;
+	}
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(xsk_validate_dev);
+
+/**
+ * xsk_rxq_pool - get the AF_XDP pool that provides memory to an RX queue
+ * @dev: device of the queue
+ * @queue_id: RX queue
+ *
+ * The pool stays valid while the queue that the caller allocates runs.
+ *
+ * Context: holds the instance lock of @dev.
+ * Return: the buffer pool, or NULL.
+ */
+struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev, u16 queue_id)
+{
+	struct netdev_rx_queue *rxq;
+	struct xsk_pp *pp;
+
+	netdev_assert_locked(dev);
+
+	if (queue_id >= dev->real_num_rx_queues)
+		return NULL;
+
+	rxq = __netif_get_rx_queue(dev, queue_id);
+	if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+		return NULL;
+
+	pp = rxq->mp_params.mp_priv;
+	return pp->pool;
+}
+EXPORT_SYMBOL_GPL(xsk_rxq_pool);
+
+bool xsk_pp_supported(struct net_device *dev)
+{
+	const struct netdev_queue_mgmt_ops *qops = dev->queue_mgmt_ops;
+
+	return qops && qops->xsk_page_pool;
+}
+
+/* Called with RTNL and the instance lock of @dev. On error, @pool->pp stays
+ * set if an old page pool still owns chunks; copy mode must not take the pool.
+ */
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+		u16 queue_id)
+{
+	struct pp_memory_provider_params mp = { .mp_ops = &xsk_pp_ops };
+	struct device *dma_dev;
+	struct xsk_pp *pp;
+	int err;
Quoted 8 lines

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 406

Quoted 6 lines
net/xdp/xsk_pp.c +6 -0
+
+	if (queue_id >= dev->real_num_rx_queues || pool->unaligned)
+		return -EOPNOTSUPP;
+	if ((dev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK ||
+	    (xsk_pool_uses_sg(pool) && dev->xdp_zc_max_segs == 1))
+		return -EOPNOTSUPP;

that is checked elsewhere, in xp_assign_dev() I assume.

Ah, yes! I'll do the common checks first in xp_assign_dev(), and branch after.

Quoted 1 line

Why there are skb mode checks?

(Note to self: I need to make some details/designs more obvious in the cover!)

Because the provider is turned on by the queue API at bind, not by an XDP program. This is a big difference. Once the socket is bound, the queue's page pool hands the device chunks from FILL, whatever program is
attached: native, generic or none. A generic redirect would copy into a chunk taken from FILL behind the provider's back, and a provider pool doesn't have the heads that copy path needs. So 07 drops those redirects.

Quoted 3 lines

The checks make that visible (I hope): with a generic program attached, bind falls back to copy mode, where generic XDP works, and attaching one to a provider queue fails instead of dropping everything.

Might be a dumb question but couldn't you forbid generic xdp attach if you detect zc socket active on netdev? Or can't you have some deferring mechanism like other drivers do? Or is it now not possible as decision at that other drivers is done early at napi and here you don't really have a way to distinguish it?

Another thought here - if user binds ZC socket and follows with generic XDP prog, then i'd say something is wrong.

You generally *need* native xdp prog for resource bringup. I don't see why we have to worry that much about generic hook, which probably lacks real world use cases (sorry if I offended someone actually using it) ?

Quoted 19 lines

Driver ZC is different: ice and i40e use the pool only while a native program is attached, so with a generic one the queue runs on normal buffers, and the copy is the only FILL user.

Quoted 5 lines

You sort of introduce totally separate control path and rx data path. It is hard for me to buy onto the management burden of all this new code :(

I believe we should break this up onto smaller chunks and don't try to solve everything within a single set...or wil that not be possible?

Separate from driver ZC, yes, but not new: the provider binds the way devmem and io_uring zcrx do, netif_mp_open_rxq() and a queue restart, and the driver keeps its normal page pool RX path, with no ZC RX loop of its own. The cost moves into the AF_XDP core, and xsk_pp.c is real code, I know.

It can be split:

Quoted 7 lines

1. preparation, no new behaviour: netmem frag addresses, the page pool caps, fbnic's redirect and netmem patches, the TX metadata fix;
2. the provider for single-buffer packets, with fbnic, without the copy fallback or fbnic's shared header/payload pool;
3. multi-buffer.

Not sure it would help much TBH.

1 as prep would be good, but I believe we were saying new ZC drivers are supposed to include mbuf support from day 0. Otherwise it might be hard to enforce this later.

Quoted 26 lines

The provider, its bind and the delivery need a driver to land, so 2 is the smallest set that does something. v2 also loses some things (but I'd like to keep the validate ndo_bpf), e.g. nr_pools and the duplicate checks. And I'm happy to look after xsk_pp.c. Would that work for you?

Quoted 11 lines
Quoted 11 lines
net/xdp/xsk_pp.c +11 -0
+	if (dev_xdp_prog_id(dev, XDP_MODE_SKB))
+		return -EOPNOTSUPP;
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE))
+		return -EBUSY;
+
+	err = xsk_pp_validate(dev, pool, dev->mtu, NULL, NULL);
+	if (err)
+		return err;
+
+	dma_dev = netdev_queue_get_dma_dev(dev, queue_id, NETDEV_QUEUE_TYPE_RX);
+	if (!dma_dev)
Quoted 8 lines

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 423

Quoted 6 lines
net/xdp/xsk_pp.c +6 -0
+		return -EOPNOTSUPP;
+
+	err = xp_dma_map(pool, dma_dev, XSK_PP_DMA_ATTR, pool->umem->pgs,
+			 pool->umem->npgs);
+	if (err)
+		return err;

Couldn't we have this part common across drivers wanting to do ZC?

Quoted 4 lines

It is: this is core code, and no provider driver maps UMEM itself; netdev_queue_get_dma_dev() gives the core the device, as for io_uring zcrx. Driver ZC could map in xp_assign_dev() too, but drivers differ in DMA device and attributes, so that's its own series.

I meant existing drivers do this on their side, idea was to make it common before your set so that you could reuse existing code.

I am wondering what is the end goal here. If we would have enough of work force (or tokens) and time and willpower, I assume we would have every current xsk ZC driver converted to page_pool and finally orphan the MEM_TYPE_XSK_BUFF_POOL.

That might not happen, so I feel like I sound like a sentinel, but current code can't just be abandonded. Hence all these asks for code reuse, etc.

Quoted 4 lines

Björn

#57 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

Quoted 48 lines · Maciej Fijalkowski
Quoted 37 lines · Björn Töpel
Quoted 10 lines · Maciej Fijalkowski
Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+/* Called with RTNL and the instance lock of @dev. On error, @pool->pp stays
+ * set if an old page pool still owns chunks; copy mode must not take the pool.
+ */
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+		u16 queue_id)
+{
+	struct pp_memory_provider_params mp = { .mp_ops = &xsk_pp_ops };
+	struct device *dma_dev;
+	struct xsk_pp *pp;
+	int err;
Quoted 8 lines

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 406

Quoted 6 lines
net/xdp/xsk_pp.c +6 -0
+
+	if (queue_id >= dev->real_num_rx_queues || pool->unaligned)
+		return -EOPNOTSUPP;
+	if ((dev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK ||
+	    (xsk_pool_uses_sg(pool) && dev->xdp_zc_max_segs == 1))
+		return -EOPNOTSUPP;

that is checked elsewhere, in xp_assign_dev() I assume.

Ah, yes! I'll do the common checks first in xp_assign_dev(), and branch after.

Quoted 1 line

Why there are skb mode checks?

(Note to self: I need to make some details/designs more obvious in the cover!)

Because the provider is turned on by the queue API at bind, not by an XDP program. This is a big difference. Once the socket is bound, the queue's page pool hands the device chunks from FILL, whatever program is
attached: native, generic or none. A generic redirect would copy into a chunk taken from FILL behind the provider's back, and a provider pool doesn't have the heads that copy path needs. So 07 drops those redirects.

Quoted 3 lines

The checks make that visible (I hope): with a generic program attached, bind falls back to copy mode, where generic XDP works, and attaching one to a provider queue fails instead of dropping everything.

Might be a dumb question but couldn't you forbid generic xdp attach if you detect zc socket active on netdev? Or can't you have some deferring mechanism like other drivers do? Or is it now not possible as decision at that other drivers is done early at napi and here you don't really have a way to distinguish it?

Quoted 6 lines

Another thought here - if user binds ZC socket and follows with generic XDP prog, then i'd say something is wrong.

You generally *need* native xdp prog for resource bringup. I don't see why we have to worry that much about generic hook, which probably lacks real world use cases (sorry if I offended someone actually using it) ?

Not dumb, and that's what the attach check does: a generic program fails to attach while a provider socket is bound, and a bind with one attached falls back to copy mode. With those two, the drop in 07 can't trigger, so it goes, as I told Stan. I agree generic doesn't deserve more than that.

And I'd rather not tie the bringup to a native program, as driver ZC does. That adds state: attach and detach would install and remove the provider, restart the queues and handle that failing half way, and whether a bound socket gets zero copy would depend on the program. Here a socket depends only on its allocator, set up at bind, and the program just picks the packets that go to it; the two are orthogonal.

That also leaves room for a mode without an XDP program, steering flows to the queue like devmem and io_uring zcrx do ;-)

Quoted 25 lines
Quoted 25 lines

Driver ZC is different: ice and i40e use the pool only while a native program is attached, so with a generic one the queue runs on normal buffers, and the copy is the only FILL user.

Quoted 5 lines

You sort of introduce totally separate control path and rx data path. It is hard for me to buy onto the management burden of all this new code :(

I believe we should break this up onto smaller chunks and don't try to solve everything within a single set...or wil that not be possible?

Separate from driver ZC, yes, but not new: the provider binds the way devmem and io_uring zcrx do, netif_mp_open_rxq() and a queue restart, and the driver keeps its normal page pool RX path, with no ZC RX loop of its own. The cost moves into the AF_XDP core, and xsk_pp.c is real code, I know.

It can be split:

1. preparation, no new behaviour: netmem frag addresses, the page pool caps, fbnic's redirect and netmem patches, the TX metadata fix;
2. the provider for single-buffer packets, with fbnic, without the copy fallback or fbnic's shared header/payload pool;
3. multi-buffer.

Quoted 5 lines
Quoted 1 line

Not sure it would help much TBH.

1 as prep would be good, but I believe we were saying new ZC drivers are supposed to include mbuf support from day 0. Otherwise it might be hard to enforce this later.

TBH I fail to see how moving 1 to a separate set would make it easier to review.

Quoted 34 lines
Quoted 26 lines

The provider, its bind and the delivery need a driver to land, so 2 is the smallest set that does something. v2 also loses some things (but I'd like to keep the validate ndo_bpf), e.g. nr_pools and the duplicate checks. And I'm happy to look after xsk_pp.c. Would that work for you?

Quoted 11 lines
Quoted 11 lines
net/xdp/xsk_pp.c +11 -0
+	if (dev_xdp_prog_id(dev, XDP_MODE_SKB))
+		return -EOPNOTSUPP;
+	if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE))
+		return -EBUSY;
+
+	err = xsk_pp_validate(dev, pool, dev->mtu, NULL, NULL);
+	if (err)
+		return err;
+
+	dma_dev = netdev_queue_get_dma_dev(dev, queue_id, NETDEV_QUEUE_TYPE_RX);
+	if (!dma_dev)
Quoted 8 lines

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 423

Quoted 6 lines
net/xdp/xsk_pp.c +6 -0
+		return -EOPNOTSUPP;
+
+	err = xp_dma_map(pool, dma_dev, XSK_PP_DMA_ATTR, pool->umem->pgs,
+			 pool->umem->npgs);
+	if (err)
+		return err;

Couldn't we have this part common across drivers wanting to do ZC?

Quoted 4 lines

It is: this is core code, and no provider driver maps UMEM itself; netdev_queue_get_dma_dev() gives the core the device, as for io_uring zcrx. Driver ZC could map in xp_assign_dev() too, but drivers differ in DMA device and attributes, so that's its own series.

I meant existing drivers do this on their side, idea was to make it common before your set so that you could reuse existing code.

Quoted 7 lines

I am wondering what is the end goal here. If we would have enough of work force (or tokens) and time and willpower, I assume we would have every current xsk ZC driver converted to page_pool and finally orphan the MEM_TYPE_XSK_BUFF_POOL.

That might not happen, so I feel like I sound like a sentinel, but current code can't just be abandonded. Hence all these asks for code reuse, etc.

I'm not saying we're orphaning anything. I am trying to reuse as much as possible, but some parts does not fit. Like using xsk_buff_head -- the page_pool return netmems. Type type is PAGE_POOL, and driver typically use a stack allocated xdp_buff.

The end goal is enable the XSK core, so that a netdev driver does not need to build a secondary shadow driver for XSK. Instead, driver supports the page pool + queue restart APIs, and you can then use XSK, devmem, and iouring zc with less code. Initially Rx, but we need a plan for Tx as well at some point.

It would be awesome if over time we move from the existing "shadow driver" world, to page pool and the provider, and MEM_TYPE_XSK_BUFF_POOL goes once the last one has. Until then driver ZC keeps working as it does today, and v2 will have numbers for it. FWIW, I'll keep converting drivers too, not just land the core.

The fact that Linux does not have a driver ABI, which IMO a strength, is just for work like this. We can clean up drivers, as the world change, without keeping old stuff around forever.

Björn

#58 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

In reply to Björn Töpel
Quoted 892 lines · Björn Töpel

A page_pool driver should not need its own AF_XDP setup. When it sets netdev_queue_mgmt_ops.xsk_page_pool, a zero-copy bind installs the UMEM provider through the queue API, as devmem and io_uring do. The driver only judges the chunk size, headroom and multi-buffer mode against its MTU and XDP program, in XDP_VALIDATE_XSK_POOL; MTU and program changes of a bound device get the same check. The UMEM headroom belongs to the socket, so the queue gets it as rx_headroom, next to rx_page_size.

After a queue restart, the core checks that the new page pools took the provider. A readable provider must back the header pool, where an unsplit packet lands, so pools declare the buffers they supply in rx_roles. The old queue's pools carry the same provider during the check, so a per-queue generation, mp_gen, tells the new ones apart.

Generic XDP runs outside the queue NAPI, so it cannot feed the socket.

The provider needs no xdp_buff_xsk per chunk. The buffer pool allocates them only for copy mode and driver zero copy, which saves 128 bytes per chunk.

---
 include/linux/netdevice.h     |   8 ++
 include/net/netdev_queues.h   |  12 ++
 include/net/netdev_rx_queue.h |   2 +
 include/net/page_pool/types.h |  12 ++
 include/net/xdp_sock.h        |   4 +
 include/net/xdp_sock_drv.h    |  45 +++++++
 include/net/xsk_buff_pool.h   |   3 +
 net/core/dev.c                |  16 +++
 net/core/netdev_config.c      |   2 +
 net/core/netdev_rx_queue.c    |   9 +-
 net/core/page_pool.c          |   6 +-
 net/core/page_pool_user.c     |  25 ++--
 net/xdp/xsk.h                 |   7 +-
 net/xdp/xsk_buff_pool.c       |  69 ++++++++---
 net/xdp/xsk_pp.c              | 221 ++++++++++++++++++++++++++++++++++
 15 files changed, 410 insertions(+), 31 deletions(-)
include/linux/netdevice.h +8 -0
index 435be7880d7e..11e51e684003 100644
@@ -77,6 +77,7 @@ struct udp_tunnel_info;
 struct udp_tunnel_nic_info;
 struct udp_tunnel_nic;
 struct bpf_prog;
+struct xsk_rx_check;
 struct xdp_buff;
 struct xdp_frame;
 struct xdp_metadata_ops;
@@ -1010,6 +1011,8 @@ enum bpf_netdev_command {
        BPF_OFFLOAD_MAP_ALLOC,
        BPF_OFFLOAD_MAP_FREE,
        XDP_SETUP_XSK_POOL,
+       /* Check an AF_XDP page pool setup, see netdev_queue_mgmt_ops */
+       XDP_VALIDATE_XSK_POOL,
 };
 
 struct bpf_prog_offload_ops;
@@ -1048,6 +1051,11 @@ struct netdev_bpf {
                        struct xsk_buff_pool *pool;
                        u16 queue_id;
                } xsk;
+               /* XDP_VALIDATE_XSK_POOL */
+               struct {
+                       const struct xsk_rx_check *check;
+                       struct netlink_ext_ack *extack;
+               } xsk_check;
        };
 };
 
include/net/netdev_queues.h +12 -0
index c5335e935b7d..ad5f0420c21d 100644
@@ -45,12 +45,15 @@ struct netdev_config {
 /**
  * struct netdev_queue_config - rendered configuration for an RX queue
  * @rx_page_size:      Size of one RX page-pool allocation.
+ * @rx_headroom:       Space before the packet in a head buffer, including
+ *                     XDP_PACKET_HEADROOM. Zero selects the driver default.
  * @rx_ring_size:      Configured size of the regular RX ring.
  * @rx_mini_ring_size: Configured size of the RX mini ring.
  * @rx_jumbo_ring_size:        Configured size of the RX jumbo ring.
  */
 struct netdev_queue_config {
        u32     rx_page_size;
+       u32     rx_headroom;
        u32     rx_ring_size;
        u32     rx_mini_ring_size;
        u32     rx_jumbo_ring_size;
@@ -156,6 +159,8 @@ void netdev_stat_queue_sum(struct net_device *netdev,
 enum {
        /* The queue checks and honours the page size qcfg parameter */
        QCFG_RX_PAGE_SIZE       = 0x1,
+       /* The queue checks and honours the headroom qcfg parameter */
+       QCFG_RX_HEADROOM        = 0x2,
 };
 
 /**
@@ -199,6 +204,12 @@ enum {
  *
  * @supported_params:  Bitmask of supported parameters, see QCFG_*.
  *
+ * @xsk_page_pool:     AF_XDP zero copy installs the UMEM as the page pool
+ *                     memory provider of the RX queue. The driver selects it
+ *                     with PP_FLAG_MEM_PROVIDER and PP_RX_ROLE_HEAD, honours
+ *                     whole buffers and QCFG_RX_HEADROOM, and accepts or
+ *                     rejects the setup in XDP_VALIDATE_XSK_POOL.
+ *
  * Note that @ndo_queue_mem_alloc and @ndo_queue_mem_free may be called while
  * the interface is closed. @ndo_queue_start and @ndo_queue_stop will only
  * be called for an interface which is open.
@@ -229,6 +240,7 @@ struct netdev_queue_mgmt_ops {
                                    struct netlink_ext_ack *extack);
 
        unsigned int supported_params;
+       bool xsk_page_pool;
 };
 
 void netdev_queue_config(struct net_device *dev, int rxq,
include/net/netdev_rx_queue.h +2 -0
index 9415a94d333d..989120cbf452 100644
@@ -31,6 +31,8 @@ struct netdev_rx_queue {
        struct napi_struct              *napi;
        struct netdev_queue_config      qcfg;
        struct pp_memory_provider_params mp_params;
+       /* stamps the page pools of each queue allocation */
+       u32                             mp_gen;
 
        /* If a queue is leased, then the lease pointer is always
         * valid. From the physical device it points to the virtual
include/net/page_pool/types.h +12 -0
index 0d48c05f1462..e9f3af91e305 100644
@@ -40,6 +40,12 @@
  */
 #define PP_FLAG_MEM_PROVIDER   BIT(4)
 
+/* RX buffers a page pool supplies, see page_pool_params.rx_roles */
+enum pp_rx_role {
+       PP_RX_ROLE_HEAD         = BIT(0),       /* packet headers */
+       PP_RX_ROLE_PAYLOAD      = BIT(1),       /* payload after header split */
+};
+
 #define PP_FLAG_ALL            (PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV | \
                                 PP_FLAG_SYSTEM_POOL | \
                                 PP_FLAG_ALLOW_UNREADABLE_NETMEM | \
@@ -94,6 +100,8 @@ struct pp_alloc_cache {
  * @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_MEM_PROVIDER.
+ * @rx_roles:  &enum pp_rx_role mask, for pools that select a memory
+ *             provider. Zero means payload buffers.
  */
 struct page_pool_params {
        struct_group_tagged(page_pool_params_fast, fast,
@@ -110,6 +118,7 @@ struct page_pool_params {
                struct net_device *netdev;
                unsigned int queue_idx;
                unsigned int    flags;
+               unsigned int    rx_roles;
 /* private: used by test code only */
                void (*init_callback)(netmem_ref netmem, void *arg);
                void *init_arg;
@@ -182,6 +191,7 @@ struct pp_memory_provider_params {
        void *mp_priv;
        const struct memory_provider_ops *mp_ops;
        u32 rx_page_size;
+       u32 rx_headroom;
 };
 
 struct page_pool {
@@ -245,6 +255,8 @@ struct page_pool {
 
        void *mp_priv;
        const struct memory_provider_ops *mp_ops;
+       /* queue allocation that selected the provider */
+       u32 mp_gen;
 
        struct xarray dma_mapped;
 
include/net/xdp_sock.h +4 -0
index 6e70b320b399..e0e22ef839e1 100644
@@ -19,6 +19,10 @@
 struct net_device;
 struct xsk_queue;
 struct xdp_buff;
+struct memory_provider_ops;
+
+/* The memory provider of AF_XDP page pool zero copy */
+extern const struct memory_provider_ops xsk_pp_ops;
 
 struct xdp_umem {
        void *addrs;
include/net/xdp_sock_drv.h +45 -0
index d94aeb506379..5bb1949a0aa7 100644
@@ -22,8 +22,29 @@ struct xsk_cb_desc {
        u8 bytes;
 };
 
+/**
+ * struct xsk_rx_check - AF_XDP page pool RX setup a driver must accept
+ * @buf_size: size of each RX buffer
+ * @headroom: space before the packet in a head buffer, including
+ *     XDP_PACKET_HEADROOM. The UMEM headroom is the rest.
+ * @mtu: MTU of the device
+ * @sg: the socket takes packets in more than one buffer
+ * @prog: XDP program to check, or NULL for the current one
+ */
+struct xsk_rx_check {
+       u32 buf_size;
+       u32 headroom;
+       unsigned int mtu;
+       bool sg;
+       struct bpf_prog *prog;
+};
+
 #ifdef CONFIG_XDP_SOCKETS
 
+int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+                    struct bpf_prog *prog, enum bpf_xdp_mode mode,
+                    struct netlink_ext_ack *extack);
+struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev, u16 queue_id);
 void xsk_tx_completed(struct xsk_buff_pool *pool, u32 nb_entries);
 bool xsk_tx_peek_desc(struct xsk_buff_pool *pool, struct xdp_desc *desc);
 u32 xsk_tx_peek_release_desc_batch(struct xsk_buff_pool *pool, u32 max);
@@ -36,6 +57,11 @@ void xsk_clear_rx_need_wakeup(struct xsk_buff_pool *pool);
 void xsk_clear_tx_need_wakeup(struct xsk_buff_pool *pool);
 bool xsk_uses_need_wakeup(struct xsk_buff_pool *pool);
 
+static inline bool xsk_pool_uses_sg(struct xsk_buff_pool *pool)
+{
+       return pool->umem->flags & XDP_UMEM_SG_FLAG;
+}
+
 static inline u32 xsk_pool_get_headroom(struct xsk_buff_pool *pool)
 {
        return XDP_PACKET_HEADROOM + pool->headroom;
@@ -351,6 +377,20 @@ static inline void xsk_buff_raw_dma_sync_for_device(struct xsk_buff_pool *pool,
 
 #else
 
+static inline int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+                                  struct bpf_prog *prog,
+                                  enum bpf_xdp_mode mode,
+                                  struct netlink_ext_ack *extack)
+{
+       return 0;
+}
+
+static inline struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev,
+                                                u16 queue_id)
+{
+       return NULL;
+}
+
 static inline void xsk_tx_completed(struct xsk_buff_pool *pool, u32 nb_entries)
 {
 }
@@ -397,6 +437,11 @@ static inline bool xsk_uses_need_wakeup(struct xsk_buff_pool *pool)
        return false;
 }
 
+static inline bool xsk_pool_uses_sg(struct xsk_buff_pool *pool)
+{
+       return false;
+}
+
 static inline u32 xsk_pool_get_headroom(struct xsk_buff_pool *pool)
 {
        return 0;
include/net/xsk_buff_pool.h +3 -0
index 02e89350faf9..6d7cfdf99a8b 100644
@@ -11,6 +11,7 @@
 #include <net/xdp.h>
 
 struct xsk_buff_pool;
+struct xsk_pp;
 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;
+       /* page pool memory provider, see net/xdp/xsk_pp.c */
+       struct xsk_pp *pp;
        struct work_struct work;
        /* Protects generic receive in shared and non-shared umem mode. */
        spinlock_t rx_lock;
net/core/dev.c +16 -0
index 663fe3e32ea0..7e985fb82488 100644
@@ -163,6 +163,7 @@
 #include <net/page_pool/types.h>
 #include <net/page_pool/helpers.h>
 #include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
 #include <net/rps.h>
 #include <linux/phy_link_topology.h>
 
@@ -10535,6 +10536,8 @@ u8 dev_xdp_sb_prog_count(struct net_device *dev)
 
 int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 {
+       int err;
+
        if (!dev->netdev_ops->ndo_bpf)
                return -EOPNOTSUPP;
 
@@ -10552,6 +10555,13 @@ int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
                return -EBUSY;
        }
 
+       if (bpf->command == XDP_SETUP_PROG && bpf->prog) {
+               err = xsk_validate_dev(dev, dev->mtu, bpf->prog, XDP_MODE_DRV,
+                                      bpf->extack);
+               if (err)
+                       return err;
+       }
+
        return dev->netdev_ops->ndo_bpf(dev, bpf);
 }
 EXPORT_SYMBOL_GPL(netif_xdp_propagate);
@@ -10629,6 +10639,12 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
                return -EBUSY;
        }
 
+       if (mode != XDP_MODE_HW && prog) {
+               err = xsk_validate_dev(dev, dev->mtu, prog, mode, extack);
+               if (err)
+                       return err;
+       }
+
        memset(&xdp, 0, sizeof(xdp));
        xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
        xdp.extack = extack;
net/core/netdev_config.c +2 -0
index 1975de42a60d..97e33764737b 100644
@@ -88,6 +88,8 @@ static int __netdev_queue_config(struct net_device *dev, int rxq_idx,
        mpp = &__netif_get_rx_queue(dev, rxq_idx)->mp_params;
        if (mpp->rx_page_size)
                qcfg->rx_page_size = mpp->rx_page_size;
+       if (mpp->rx_headroom)
+               qcfg->rx_headroom = mpp->rx_headroom;
        err = validate_cb(dev, qcfg, extack);
        if (err)
                return err;
net/core/netdev_rx_queue.c +8 -1
index 9e14a747f9b5..4e2f906fbc73 100644
@@ -6,6 +6,7 @@
 #include <net/netdev_queues.h>
 #include <net/netdev_rx_queue.h>
 #include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock.h>
 
 #include "dev.h"
 #include "page_pool_priv.h"
@@ -141,6 +142,7 @@ static int netdev_rx_queue_reconfig(struct net_device *dev,
                goto err_free_new_mem;
        }
 
+       rxq->mp_gen++;
        err = qops->ndo_queue_mem_alloc(dev, qcfg_new, new_mem, rxq_idx);
        if (err)
                goto err_free_old_mem;
@@ -235,6 +237,10 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
                NL_SET_ERR_MSG(extack, "device does not support: rx_page_size");
                return -EOPNOTSUPP;
        }
+       if (p->rx_headroom && !(qops->supported_params & QCFG_RX_HEADROOM)) {
+               NL_SET_ERR_MSG(extack, "device does not support: rx_headroom");
+               return -EOPNOTSUPP;
+       }
 
        rxq = __netif_get_rx_queue(dev, rxq_idx);
        if (rxq->mp_params.mp_ops) {
@@ -242,7 +248,8 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
                return -EEXIST;
        }
 #ifdef CONFIG_XDP_SOCKETS
-       if (rxq->pool) {
+       /* An AF_XDP pool owns the queue, unless it installs its provider. */
+       if (rxq->pool && p->mp_ops != &xsk_pp_ops) {
                NL_SET_ERR_MSG(extack, "designated queue already in use by AF_XDP");
                return -EBUSY;
        }
net/core/page_pool.c +4 -2
index 8237fda598ab..e897e79d31f1 100644
@@ -215,7 +215,8 @@ bool netmem_can_retain(netmem_ref netmem)
 EXPORT_SYMBOL(netmem_can_retain);
 
 static int page_pool_select_mp(struct page_pool *pool,
-                              const struct pp_memory_provider_params *mpp)
+                              const struct pp_memory_provider_params *mpp,
+                              u32 rxq_mp_gen)
 {
        const struct memory_provider_ops *ops = mpp->mp_ops;
        unsigned int flags = pool->slow.flags;
@@ -234,6 +235,7 @@ static int page_pool_select_mp(struct page_pool *pool,
 
        pool->mp_priv = mpp->mp_priv;
        pool->mp_ops = ops;
+       pool->mp_gen = rxq_mp_gen;
        return 0;
 }
 
@@ -326,7 +328,7 @@ static int page_pool_init(struct page_pool *pool,
                netdev_assert_locked(pool->slow.netdev);
                rxq = __netif_get_rx_queue(pool->slow.netdev,
                                           pool->slow.queue_idx);
-               err = page_pool_select_mp(pool, &rxq->mp_params);
+               err = page_pool_select_mp(pool, &rxq->mp_params, rxq->mp_gen);
                if (err)
                        goto free_ptr_ring;
        }
net/core/page_pool_user.c +17 -8
index f30f3779624c..b69da0f74756 100644
@@ -398,28 +398,37 @@ void page_pool_unlist(struct page_pool *pool)
        mutex_unlock(&page_pools_lock);
 }
 
+/* Check that the queue allocation that just ran put the provider in every
+ * pool role it needs: headers for a readable provider, payload otherwise.
+ * Pools of earlier allocations do not count.
+ */
 int page_pool_check_memory_provider(struct net_device *dev,
                                    struct netdev_rx_queue *rxq)
 {
-       void *binding = rxq->mp_params.mp_priv;
+       const struct memory_provider_ops *ops = rxq->mp_params.mp_ops;
+       void *mp_priv = rxq->mp_params.mp_priv;
+       unsigned int need, have = 0;
        struct page_pool *pool;
        struct hlist_node *n;
 
-       if (!binding)
+       if (!mp_priv)
                return 0;
 
+       need = PP_RX_ROLE_PAYLOAD;
+       if (ops->caps & MP_CAP_READABLE)
+               need = PP_RX_ROLE_HEAD;
+
        mutex_lock(&page_pools_lock);
        hlist_for_each_entry_safe(pool, n, &dev->page_pools, user.list) {
-               if (pool->mp_priv != binding)
+               if (pool->mp_priv != mp_priv || pool->mp_gen != rxq->mp_gen ||
+                   pool->slow.queue_idx != get_netdev_rx_queue_index(rxq))
                        continue;
 
-               if (pool->slow.queue_idx == get_netdev_rx_queue_index(rxq)) {
-                       mutex_unlock(&page_pools_lock);
-                       return 0;
-               }
+               have |= pool->slow.rx_roles ? : PP_RX_ROLE_PAYLOAD;
        }
        mutex_unlock(&page_pools_lock);
-       return -ENODATA;
+
+       return (have & need) == need ? 0 : -ENODATA;
 }
 
 static void page_pool_unreg_netdev_wipe(struct net_device *netdev)
net/xdp/xsk.h +5 -2
index 4dab7b9a1487..9699e9a499a3 100644
@@ -36,10 +36,13 @@ void xsk_map_try_sock_delete(struct xsk_map *map, struct xdp_sock *xs,
                             struct xdp_sock __rcu **map_entry);
 struct xsk_pp;
 
-extern const struct memory_provider_ops xsk_pp_ops;
-
 struct xsk_pp *xsk_pp_create(struct xsk_buff_pool *pool);
 void xsk_pp_put(struct xsk_pp *pp);
+bool xsk_pp_supported(struct net_device *dev);
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+               u16 queue_id);
+void xsk_pp_unbind(struct xsk_buff_pool *pool);
+int xp_alloc_heads(struct xsk_buff_pool *pool);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
                        u16 queue_id);
net/xdp/xsk_buff_pool.c +51 -18
index 18966bbdb5b7..c620a0c32c17 100644
@@ -38,6 +38,8 @@ void xp_destroy(struct xsk_buff_pool *pool)
        if (!pool)
                return;
 
+       if (pool->pp)
+               xsk_pp_put(pool->pp);
        kvfree(pool->tx_descs);
        kvfree(pool->heads);
        kvfree(pool);
@@ -62,18 +64,13 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
 {
        bool unaligned = umem->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;
        struct xsk_buff_pool *pool;
-       struct xdp_buff_xsk *xskb;
-       u32 i, entries;
+       u32 entries;
 
        entries = unaligned ? umem->chunks : 0;
        pool = kvzalloc_flex(*pool, free_heads, entries);
        if (!pool)
                goto out;
 
-       pool->heads = kvzalloc_objs(*pool->heads, umem->chunks);
-       if (!pool->heads)
-               goto out;
-
        if (xs->tx)
                if (xp_alloc_tx_descs(pool, xs, max_segs))
                        goto out;
@@ -104,10 +101,30 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
        pool->fq = xs->fq_tmp;
        pool->cq = xs->cq_tmp;
 
-       for (i = 0; i < pool->free_heads_cnt; i++) {
+       return pool;
+
+out:
+       xp_destroy(pool);
+       return NULL;
+}
+
+/* Only copy mode and driver zero copy use heads */
+int xp_alloc_heads(struct xsk_buff_pool *pool)
+{
+       struct xdp_buff_xsk *xskb;
+       u32 i;
+
+       if (pool->heads)
+               return 0;
+
+       pool->heads = kvzalloc_objs(*pool->heads, pool->heads_cnt);
+       if (!pool->heads)
+               return -ENOMEM;
+
+       for (i = 0; i < pool->heads_cnt; i++) {
                xskb = &pool->heads[i];
                xskb->pool = pool;
-               xskb->xdp.frame_sz = umem->chunk_size - umem->headroom;
+               xskb->xdp.frame_sz = pool->chunk_size - pool->headroom;
                INIT_LIST_HEAD(&xskb->list_node);
                if (pool->unaligned)
                        pool->free_heads[i] = xskb;
@@ -115,11 +132,7 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
                        xp_init_xskb_addr(xskb, pool, (u64)i * pool->chunk_size);
        }
 
-       return pool;
-
-out:
-       xp_destroy(pool);
-       return NULL;
+       return 0;
 }
 
 void xp_set_rxq_info(struct xsk_buff_pool *pool, struct xdp_rxq_info *rxq)
@@ -212,9 +225,24 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
         */
        hlist_add_head(&pool->dev_node, &netdev->xsk_pools);
 
-       if (force_copy)
+       if (force_copy) {
                /* For copy-mode, we are done. */
+               err = xp_alloc_heads(pool);
+               goto out;
+       }
+
+       if (xsk_pp_supported(netdev)) {
+               err = xsk_pp_bind(pool, netdev, queue_id);
+               if (err)
+                       goto err_unreg_pool;
+
+               pool->umem->zc = true;
                return 0;
+       }
+
+       err = xp_alloc_heads(pool);
+       if (err)
+               goto out;
 
        if ((netdev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK) {
                err = -EOPNOTSUPP;
@@ -267,8 +295,10 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 err_unreg_xsk:
        xp_disable_drv_zc(pool);
 err_unreg_pool:
-       if (!force_zc)
-               err = 0; /* fallback to copy mode */
+       /* An old page pool may still own chunks of a failed provider. */
+       if (!force_zc && !pool->pp)
+               err = xp_alloc_heads(pool); /* fallback to copy mode */
+out:
        if (err) {
                pool->umem->flags = umem_flags;
                xsk_clear_pool_at_qid(netdev, queue_id);
@@ -301,7 +331,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->pp)
+               xsk_pp_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;
@@ -474,7 +507,7 @@ static void xp_check_dma_contiguity(struct xsk_dma_map *dma_map)
 
 static int xp_init_dma_info(struct xsk_buff_pool *pool, struct xsk_dma_map *dma_map)
 {
-       if (!pool->unaligned) {
+       if (!pool->unaligned && pool->heads) {
                u32 i;
 
                for (i = 0; i < pool->heads_cnt; i++) {
net/xdp/xsk_pp.c +210 -0
index fdd55265a6cd..c2214e718cdb 100644
@@ -8,6 +8,9 @@
  *       +-----RX ring-------+
  */
 
+#include <net/netdev_lock.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>
@@ -15,6 +18,8 @@
 #include "xsk.h"
 #include "xsk_queue.h"
 
+#define XSK_PP_DMA_ATTR        (DMA_ATTR_WEAK_ORDERING | DMA_ATTR_SKIP_CPU_SYNC)
+
 enum xsk_pp_chunk {
        XSK_PP_USER,    /* owned by userspace */
        XSK_PP_POOL,    /* owned by a page pool */
@@ -30,6 +35,8 @@ struct xsk_pp {
        refcount_t refs;
        u32 nr_pools;
        bool dma_need_sync;
+       /* RX queue of the provider, NULL once it is removed */
+       struct netdev_rx_queue *rxq;
        u8 *state;
        u32 reuse_cnt;
        u32 reuse[];
@@ -236,11 +243,225 @@ static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
        return 0;
 }
 
+/* The queue no longer uses the provider, and its DMA stopped */
+static void xsk_pp_detach(struct xsk_pp *pp)
+{
+       pp->rxq = NULL;
+       spin_lock_bh(&pp->lock);
+       pp->fq = NULL;
+       spin_unlock_bh(&pp->lock);
+       xp_dma_unmap(pp->pool, XSK_PP_DMA_ATTR);
+}
+
+/* The device unregisters, and is closed */
+static void xsk_pp_uninstall(void *mp_priv, struct netdev_rx_queue *rxq)
+{
+       xsk_pp_detach(mp_priv);
+}
+
 const struct memory_provider_ops xsk_pp_ops = {
        .init           = xsk_pp_init,
        .destroy        = xsk_pp_destroy,
        .alloc_netmems  = xsk_pp_alloc_netmems,
        .release_netmem = xsk_pp_release_netmem,
        .nl_fill        = xsk_pp_nl_fill,
+       .uninstall      = xsk_pp_uninstall,
        .caps           = MP_CAP_READABLE,
 };
+
+static bool xsk_pp_abandon(struct xsk_pp *pp)
+{
+       struct xsk_buff_pool *pool = pp->pool;
+       bool busy;
+       u32 idx;
+
+       spin_lock_bh(&pp->lock);
+       busy = pp->nr_pools;
+       while (!busy && pp->reuse_cnt) {
+               idx = pp->reuse[--pp->reuse_cnt];
+               pp->state[idx] = XSK_PP_USER;
+               xp_free(&pool->heads[idx]);
+       }
+       spin_unlock_bh(&pp->lock);
+
+       return !busy;
+}
+
+static int xsk_pp_validate(struct net_device *dev, struct xsk_buff_pool *pool,
+                          unsigned int mtu, struct bpf_prog *prog,
+                          struct netlink_ext_ack *extack)
+{
+       struct xsk_rx_check check = {
+               .buf_size = pool->chunk_size,
+               .headroom = xsk_pool_get_headroom(pool),
+               .mtu = mtu,
+               .sg = xsk_pool_uses_sg(pool),
+               .prog = prog,
+       };
+       struct netdev_bpf bpf = {
+               .command = XDP_VALIDATE_XSK_POOL,
+               .xsk_check.check = &check,
+               .xsk_check.extack = extack,
+       };
+
+       return dev->netdev_ops->ndo_bpf(dev, &bpf);
+}
+
+/**
+ * xsk_validate_dev - check AF_XDP page pool queues against a new setting
+ * @dev: device of the queues
+ * @mtu: MTU to check
+ * @prog: XDP program to check, or NULL for the current one
+ * @mode: XDP mode of @prog
+ * @extack: netlink extended ack
+ *
+ * Context: holds the instance lock of @dev, or RTNL for a device without it.
+ * Return: 0 if the driver accepts all queues of @dev that have an AF_XDP
+ * memory provider, or its error.
+ */
+int xsk_validate_dev(struct net_device *dev, unsigned int mtu,
+                    struct bpf_prog *prog, enum bpf_xdp_mode mode,
+                    struct netlink_ext_ack *extack)
+{
+       struct netdev_rx_queue *rxq;
+       struct xsk_pp *pp;
+       unsigned int i;
+       int err;
+
+       netdev_assert_locked_ops_compat(dev);
+
+       for (i = 0; i < dev->real_num_rx_queues; i++) {
+               rxq = __netif_get_rx_queue(dev, i);
+               if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+                       continue;
+
+               /* Generic XDP runs outside the queue NAPI */
+               if (mode == XDP_MODE_SKB) {
+                       NL_SET_ERR_MSG(extack,
+                                      "generic XDP cannot feed an AF_XDP page pool socket");
+                       return -EBUSY;
+               }
+
+               pp = rxq->mp_params.mp_priv;
+               err = xsk_pp_validate(dev, pp->pool, mtu, prog, extack);
+               if (err)
+                       return err;
+       }
+
+       return 0;
+}
+EXPORT_SYMBOL_GPL(xsk_validate_dev);
+
+/**
+ * xsk_rxq_pool - get the AF_XDP pool that provides memory to an RX queue
+ * @dev: device of the queue
+ * @queue_id: RX queue
+ *
+ * The pool stays valid while the queue that the caller allocates runs.
+ *
+ * Context: holds the instance lock of @dev.
+ * Return: the buffer pool, or NULL.
+ */
+struct xsk_buff_pool *xsk_rxq_pool(struct net_device *dev, u16 queue_id)
+{
+       struct netdev_rx_queue *rxq;
+       struct xsk_pp *pp;
+
+       netdev_assert_locked(dev);
+
+       if (queue_id >= dev->real_num_rx_queues)
+               return NULL;
+
+       rxq = __netif_get_rx_queue(dev, queue_id);
+       if (rxq->mp_params.mp_ops != &xsk_pp_ops)
+               return NULL;
+
+       pp = rxq->mp_params.mp_priv;
+       return pp->pool;
+}
+EXPORT_SYMBOL_GPL(xsk_rxq_pool);
+
+bool xsk_pp_supported(struct net_device *dev)
+{
+       const struct netdev_queue_mgmt_ops *qops = dev->queue_mgmt_ops;
+
+       return qops && qops->xsk_page_pool;
+}
+
+/* Called with RTNL and the instance lock of @dev. On error, @pool->pp stays
+ * set if an old page pool still owns chunks; copy mode must not take the pool.
+ */
+int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+               u16 queue_id)
+{
+       struct pp_memory_provider_params mp = { .mp_ops = &xsk_pp_ops };
+       struct device *dma_dev;
+       struct xsk_pp *pp;
+       int err;
+
+       if (queue_id >= dev->real_num_rx_queues || pool->unaligned)
+               return -EOPNOTSUPP;
+       if ((dev->xdp_features & NETDEV_XDP_ACT_XSK) != NETDEV_XDP_ACT_XSK ||
+           (xsk_pool_uses_sg(pool) && dev->xdp_zc_max_segs == 1))
+               return -EOPNOTSUPP;
+       if (dev_xdp_prog_id(dev, XDP_MODE_SKB))
+               return -EOPNOTSUPP;
+       if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE))
+               return -EBUSY;
+
+       err = xsk_pp_validate(dev, pool, dev->mtu, NULL, NULL);
+       if (err)
+               return err;
+
+       dma_dev = netdev_queue_get_dma_dev(dev, queue_id, NETDEV_QUEUE_TYPE_RX);
+       if (!dma_dev)
+               return -EOPNOTSUPP;
+
+       err = xp_dma_map(pool, dma_dev, XSK_PP_DMA_ATTR, pool->umem->pgs,
+                        pool->umem->npgs);
+       if (err)
+               return err;
+
+       pp = xsk_pp_create(pool);
+       if (IS_ERR(pp)) {
+               xp_dma_unmap(pool, XSK_PP_DMA_ATTR);
+               return PTR_ERR(pp);
+       }
+
+       mp.mp_priv = pp;
+       mp.rx_page_size = pool->chunk_size;
+       mp.rx_headroom = xsk_pool_get_headroom(pool);
+       err = netif_mp_open_rxq(dev, queue_id, &mp, NULL);
+       if (!err) {
+               pp->rxq = __netif_get_rx_queue(dev, queue_id);
+               pool->pp = pp;
+               pool->xdp_zc_max_segs = dev->xdp_zc_max_segs;
+               return 0;
+       }
+
+       xp_dma_unmap(pool, XSK_PP_DMA_ATTR);
+       /* Copy mode takes the chunks that the provider holds */
+       if (!xp_alloc_heads(pool) && xsk_pp_abandon(pp))
+               xsk_pp_put(pp);
+       else
+               pool->pp = pp;
+
+       return err;
+}
+
+/* Called with RTNL and the instance lock of the device */
+void xsk_pp_unbind(struct xsk_buff_pool *pool)
+{
+       struct xsk_pp *pp = pool->pp;
+       struct pp_memory_provider_params mp = {

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 466

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+               .mp_ops = &xsk_pp_ops,
+               .mp_priv = pp,
+       };
+
+       /* Unregister removed the provider already */
+       if (!pp->rxq)
+               return;
+
+       netif_mp_close_rxq(pool->netdev, pool->queue_id, &mp);
+       xsk_pp_detach(pp);

Need to handle netif_mp_close_rxq() failing here maybe?

Signature · 2 lines
Thanks,
Mina
#59 lore raw

Re: [PATCH net-next v1 05/11] xsk: Install UMEM page pool providers in the core

Quoted 6 lines · Mina Almasry
Quoted 4 lines · Björn Töpel
net/xdp/xsk_pp.c +0 -0
index fdd55265a6cd..c2214e718cdb 100644

[...]

Quoted 9 lines
Quoted 9 lines
net/xdp/xsk_pp.c +9 -0
+/* Called with RTNL and the instance lock of the device */
+void xsk_pp_unbind(struct xsk_buff_pool *pool)
+{
+       struct xsk_pp *pp = pool->pp;
+       struct pp_memory_provider_params mp = {
+               .mp_ops = &xsk_pp_ops,
+               .mp_priv = pp,
+       };
+
Quoted 8 lines

net/xdp/xsk_pp.c static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp, · line 466

Quoted 6 lines
net/xdp/xsk_pp.c +6 -0
+       /* Unregister removed the provider already */
+       if (!pp->rxq)
+               return;
+
+       netif_mp_close_rxq(pool->netdev, pool->queue_id, &mp);
+       xsk_pp_detach(pp);

Need to handle netif_mp_close_rxq() failing here maybe?

Ya, Sashiko found that too... a failed restart leaves the old queue running on the provider, and this unmaps the UMEM under it. I have a net fix that keeps the provider on such a queue and retries the removal; it covers io_uring zcrx too, which drops the error the same way. The fix then releases the UMEM only once the queue DMA has stopped.

Björn

#60 lore raw

PATCH 6/11 page_pool: Coordinate refill with memory providers

In reply to Björn Töpel

A UMEM has a fixed number of chunks. When a refill finds none, and the chunks come back later, nothing schedules the queue again: RX stalls. Kicks after each queue operation are easy to miss.

Drivers report the end of each refill with page_pool_refill_done(). The provider then asks for another poll, or wakes the queue later through the NAPI that the core publishes while the queue runs. Socket wakeups use that NAPI too, so such drivers need no ndo_xsk_wakeup.

With XDP_USE_NEED_WAKEUP, the FILL flag stays set: a flag set only when starved can miss an entry posted at the same time.

---
 Documentation/networking/netmem.rst     | 10 +++
 include/net/netdev_rx_queue.h           |  6 ++
 include/net/page_pool/helpers.h         | 24 ++++++
 include/net/page_pool/memory_provider.h |  2 +
 include/net/page_pool/types.h           |  6 ++
 net/core/dev.c                          |  4 +
 net/core/dev.h                          |  4 +
 net/core/netdev_rx_queue.c              | 97 ++++++++++++++++++++++++-
 net/xdp/xsk.c                           |  4 +
 net/xdp/xsk.h                           |  1 +
 net/xdp/xsk_pp.c                        | 73 ++++++++++++++++++-
 11 files changed, 226 insertions(+), 5 deletions(-)
Documentation/networking/netmem.rst +10 -0
index 39cb75339704..74c73d7d126e 100644
@@ -136,6 +136,16 @@ Driver RX Requirements
    circulation times, such as when userspace holds a reference in zerocopy
    scenarios.
 
+8. After each RX ring refill, call page_pool_refill_done() once per page
+   pool, with PP_REFILL_FULL only if all rings that use the pool are full.
+   Rings of a queue that take buffers from one such provider share one
+   page pool. Keep buffers in each of them, first in a ring that every
+   packet needs, like a header ring, so that a provider with few buffers
+   does not leave them all in one ring. If the call returns false, poll
+   again soon, for example by returning the full NAPI budget. Register the
+   NAPI of each RX queue with netif_queue_set_napi(); the core schedules
+   it when provider buffers become available.
+
 Driver TX Requirements
 ======================
 
include/net/netdev_rx_queue.h +6 -0
index 989120cbf452..ca12cbf7b825 100644
@@ -33,6 +33,12 @@ struct netdev_rx_queue {
 	struct pp_memory_provider_params mp_params;
 	/* stamps the page pools of each queue allocation */
 	u32				mp_gen;
+	/* NAPI of the running queue, for memory provider wakeups. Set while
+	 * mp_armed, and if the provider has a refill_done op. Written under
+	 * the ops lock, read under RCU, see netif_mp_wake().
+	 */
+	struct napi_struct __rcu	*mp_napi;
+	bool				mp_armed;
 
 	/* If a queue is leased, then the lease pointer is always
 	 * valid. From the physical device it points to the virtual
include/net/page_pool/helpers.h +24 -0
index 96e6b62cdebb..245a904e0b2b 100644
@@ -523,6 +523,30 @@ static inline bool page_pool_is_unreadable(struct page_pool *pool)
 	return pool->mp_ops && !(pool->mp_ops->caps & MP_CAP_READABLE);
 }
 
+/**
+ * page_pool_refill_done() - report the end of an RX ring refill
+ * @pool: page pool of the rings
+ * @state: whether all rings that take buffers from @pool are full
+ *
+ * A memory provider with a fixed set of buffers must know when the rings
+ * are full, and when they wait for buffers. Call this once per page pool
+ * after each refill, also when the rings were full already.
+ *
+ * Context: the NAPI poll that allocates from @pool, or the driver while that
+ * NAPI is disabled, with IRQs enabled.
+ * Return: true if the refill is done, false if NAPI should retry it soon.
+ */
+static inline bool page_pool_refill_done(struct page_pool *pool,
+					 enum pp_refill state)
+{
+	const struct memory_provider_ops *ops = pool->mp_ops;
+
+	if (ops && ops->refill_done)
+		return ops->refill_done(pool, state);
+
+	return true;
+}
+
 /**
  * page_pool_supports_frag() - may page pool buffers be split
  * @pool: queried page pool
include/net/page_pool/memory_provider.h +2 -0
index e732b21be9a2..daec73c9dcee 100644
@@ -42,6 +42,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);
+	bool (*refill_done)(struct page_pool *pool, enum pp_refill state);
 	u32 caps;
 };
 
@@ -55,6 +56,7 @@ int netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 int netif_mp_close_rxq(struct net_device *dev, unsigned int rxq_idx,
 		       const struct pp_memory_provider_params *old_p);
 bool netif_all_mps_have_cap(struct net_device *dev, u32 cap);
+bool netif_mp_wake(struct netdev_rx_queue *rxq);
 
 /**
   * net_mp_netmem_place_in_cache() - give a netmem to a page pool
include/net/page_pool/types.h +6 -0
index e9f3af91e305..58ca414fa3d2 100644
@@ -40,6 +40,12 @@
  */
 #define PP_FLAG_MEM_PROVIDER	BIT(4)
 
+/* Ring state after a refill, see page_pool_refill_done() */
+enum pp_refill {
+	PP_REFILL_PARTIAL,	/* some ring of the pool has room left */
+	PP_REFILL_FULL,		/* all rings of the pool are full */
+};
+
 /* RX buffers a page pool supplies, see page_pool_params.rx_roles */
 enum pp_rx_role {
 	PP_RX_ROLE_HEAD		= BIT(0),	/* packet headers */
net/core/dev.c +4 -0
index 7e985fb82488..6033fc61a666 100644
@@ -1771,6 +1771,7 @@ static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
 		dev_set_rx_mode(dev);
 		dev_activate(dev);
 		add_device_randomness(dev->dev_addr, dev->addr_len);
+		netif_mp_arm_dev(dev);
 	}
 
 	return ret;
@@ -1833,6 +1834,7 @@ static void __dev_close_many(struct list_head *head)
 
 		netdev_assert_locked_ops_compat(dev);
 
+		netif_mp_disarm_dev(dev);
 		if (ops->ndo_stop)
 			ops->ndo_stop(dev);
 
@@ -7559,6 +7561,7 @@ void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index,
 	case NETDEV_QUEUE_TYPE_RX:
 		rxq = __netif_get_rx_queue(dev, queue_index);
 		rxq->napi = napi;
+		netif_mp_update_napi(rxq);
 		return;
 	case NETDEV_QUEUE_TYPE_TX:
 		txq = netdev_get_tx_queue(dev, queue_index);
@@ -7960,6 +7963,7 @@ void __netif_napi_del_locked(struct napi_struct *napi)
 	}
 
 	list_del_rcu(&napi->dev_list);
+	netif_mp_napi_del(napi);
 	napi_free_frags(napi);
 
 	gro_cleanup(&napi->gro);
net/core/dev.h +4 -0
index e3337013ffc8..56386fd8c767 100644
@@ -125,6 +125,10 @@ bool netif_is_queue_leasee(const struct net_device *dev);
 
 void __netif_mp_uninstall_rxq(struct netdev_rx_queue *rxq,
 			      const struct pp_memory_provider_params *p);
+void netif_mp_update_napi(struct netdev_rx_queue *rxq);
+void netif_mp_arm_dev(struct net_device *dev);
+void netif_mp_disarm_dev(struct net_device *dev);
+void netif_mp_napi_del(struct napi_struct *napi);
 
 void netif_rxq_cleanup_unlease(struct netdev_rx_queue *phys_rxq,
 			       struct netdev_rx_queue *virt_rxq);
net/core/netdev_rx_queue.c +96 -1

123 lines not on this page · raw message

net/xdp/xsk.c +4 -0
index 781ba46eb152..113b0b08356d 100644
@@ -794,6 +794,10 @@ static int xsk_wakeup(struct xdp_sock *xs, u8 flags)
 {
 	struct net_device *dev = xs->dev;
 
+	/* The core wakes the queue for both RX and TX. */
+	if (xs->pool->pp)
+		return xsk_pp_wakeup(xs->pool->pp);
+
 	return dev->netdev_ops->ndo_xsk_wakeup(dev, xs->queue_id, flags);
 }
 
net/xdp/xsk.h +1 -0
index 9699e9a499a3..d7d6bcf0a893 100644
@@ -42,6 +42,7 @@ bool xsk_pp_supported(struct net_device *dev);
 int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
 		u16 queue_id);
 void xsk_pp_unbind(struct xsk_buff_pool *pool);
+int xsk_pp_wakeup(struct xsk_pp *pp);
 int xp_alloc_heads(struct xsk_buff_pool *pool);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
net/xdp/xsk_pp.c +69 -4

138 lines not on this page · raw message

Signature · 1 line
2.56.0
#61 lore raw

Re: [PATCH net-next v1 06/11] page_pool: Coordinate refill with memory providers

Quoted 53 lines · Björn Töpel

A UMEM has a fixed number of chunks. When a refill finds none, and the chunks come back later, nothing schedules the queue again: RX stalls. Kicks after each queue operation are easy to miss.

Drivers report the end of each refill with page_pool_refill_done(). The provider then asks for another poll, or wakes the queue later through the NAPI that the core publishes while the queue runs. Socket wakeups use that NAPI too, so such drivers need no ndo_xsk_wakeup.

With XDP_USE_NEED_WAKEUP, the FILL flag stays set: a flag set only when starved can miss an entry posted at the same time.

---
 Documentation/networking/netmem.rst     | 10 +++
 include/net/netdev_rx_queue.h           |  6 ++
 include/net/page_pool/helpers.h         | 24 ++++++
 include/net/page_pool/memory_provider.h |  2 +
 include/net/page_pool/types.h           |  6 ++
 net/core/dev.c                          |  4 +
 net/core/dev.h                          |  4 +
 net/core/netdev_rx_queue.c              | 97 ++++++++++++++++++++++++-
 net/xdp/xsk.c                           |  4 +
 net/xdp/xsk.h                           |  1 +
 net/xdp/xsk_pp.c                        | 73 ++++++++++++++++++-
 11 files changed, 226 insertions(+), 5 deletions(-)
Documentation/networking/netmem.rst +10 -0
index 39cb75339704..74c73d7d126e 100644
@@ -136,6 +136,16 @@ Driver RX Requirements
    circulation times, such as when userspace holds a reference in zerocopy
    scenarios.
 
+8. After each RX ring refill, call page_pool_refill_done() once per page
+   pool, with PP_REFILL_FULL only if all rings that use the pool are full.
+   Rings of a queue that take buffers from one such provider share one
+   page pool. Keep buffers in each of them, first in a ring that every
+   packet needs, like a header ring, so that a provider with few buffers
+   does not leave them all in one ring. If the call returns false, poll
+   again soon, for example by returning the full NAPI budget. Register the
+   NAPI of each RX queue with netif_queue_set_napi(); the core schedules
+   it when provider buffers become available.
+
 Driver TX Requirements
 ======================
 
include/net/netdev_rx_queue.h +0 -0
index 989120cbf452..ca12cbf7b825 100644

include/net/netdev_rx_queue.h struct netdev_rx_queue { · line 41

Quoted 9 lines
include/net/netdev_rx_queue.h +6 -0
@@ -33,6 +33,12 @@ struct netdev_rx_queue {
 	struct pp_memory_provider_params mp_params;
 	/* stamps the page pools of each queue allocation */
 	u32				mp_gen;
+	/* NAPI of the running queue, for memory provider wakeups. Set while
+	 * mp_armed, and if the provider has a refill_done op. Written under
+	 * the ops lock, read under RCU, see netif_mp_wake().
+	 */
+	struct napi_struct __rcu	*mp_napi;
+	bool				mp_armed;

The comment should explain why mp_napi != napi? (I do not understand why)

#62 lore raw

Re: [PATCH net-next v1 06/11] page_pool: Coordinate refill with memory providers

Quoted 18 lines · Stanislav Fomichev
Quoted 5 lines · Björn Töpel
include/net/netdev_rx_queue.h +0 -0
index 989120cbf452..ca12cbf7b825 100644

include/net/netdev_rx_queue.h struct netdev_rx_queue { · line 41

Quoted 9 lines
include/net/netdev_rx_queue.h +6 -0
@@ -33,6 +33,12 @@ struct netdev_rx_queue {
 	struct pp_memory_provider_params mp_params;
 	/* stamps the page pools of each queue allocation */
 	u32				mp_gen;
+	/* NAPI of the running queue, for memory provider wakeups. Set while
+	 * mp_armed, and if the provider has a refill_done op. Written under
+	 * the ops lock, read under RCU, see netif_mp_wake().
+	 */
+	struct napi_struct __rcu	*mp_napi;
+	bool				mp_armed;

The comment should explain why mp_napi != napi? (I do not understand why)

Fair. It's the same NAPI, with other rules. napi is the driver's
association: read under the ops lock, and not cleared when the NAPI is deleted. Provider wakeups run without that lock, from socket syscalls and ->release_netmem().

mp_napi is an RCU copy, set only while the device is up and the queue isn't restarting, for providers with ->refill_done(). netif_napi_del() clears it before its grace period. Setting it also schedules the NAPI once, which replays wakeups lost while the queue was stopped. I'll put that in the comment.

Björn

#63 lore raw

Re: [PATCH net-next v1 06/11] page_pool: Coordinate refill with memory providers

Quoted 26 lines · Björn Töpel
Quoted 18 lines · Stanislav Fomichev
Quoted 5 lines · Björn Töpel
include/net/netdev_rx_queue.h +0 -0
index 989120cbf452..ca12cbf7b825 100644

include/net/netdev_rx_queue.h struct netdev_rx_queue { · line 41

Quoted 9 lines
include/net/netdev_rx_queue.h +6 -0
@@ -33,6 +33,12 @@ struct netdev_rx_queue {
 	struct pp_memory_provider_params mp_params;
 	/* stamps the page pools of each queue allocation */
 	u32				mp_gen;
+	/* NAPI of the running queue, for memory provider wakeups. Set while
+	 * mp_armed, and if the provider has a refill_done op. Written under
+	 * the ops lock, read under RCU, see netif_mp_wake().
+	 */
+	struct napi_struct __rcu	*mp_napi;
+	bool				mp_armed;

The comment should explain why mp_napi != napi? (I do not understand why)

Fair. It's the same NAPI, with other rules. napi is the driver's
association: read under the ops lock, and not cleared when the NAPI is deleted. Provider wakeups run without that lock, from socket syscalls and ->release_netmem().

Quoted 5 lines

mp_napi is an RCU copy, set only while the device is up and the queue isn't restarting, for providers with ->refill_done(). netif_napi_del() clears it before its grace period. Setting it also schedules the NAPI once, which replays wakeups lost while the queue was stopped. I'll put that in the comment.

And all this only to make sure that we are not recycling something from the old pp into the new one? And reworking existing pointer to change/update its lifetime is not gonna do it?

#64 lore raw

Re: [PATCH net-next v1 06/11] page_pool: Coordinate refill with memory providers

Quoted 33 lines · Stanislav Fomichev
Quoted 26 lines · Björn Töpel
Quoted 18 lines · Stanislav Fomichev
Quoted 5 lines · Björn Töpel
include/net/netdev_rx_queue.h +0 -0
index 989120cbf452..ca12cbf7b825 100644

include/net/netdev_rx_queue.h struct netdev_rx_queue { · line 41

Quoted 9 lines
include/net/netdev_rx_queue.h +6 -0
@@ -33,6 +33,12 @@ struct netdev_rx_queue {
 	struct pp_memory_provider_params mp_params;
 	/* stamps the page pools of each queue allocation */
 	u32				mp_gen;
+	/* NAPI of the running queue, for memory provider wakeups. Set while
+	 * mp_armed, and if the provider has a refill_done op. Written under
+	 * the ops lock, read under RCU, see netif_mp_wake().
+	 */
+	struct napi_struct __rcu	*mp_napi;
+	bool				mp_armed;

The comment should explain why mp_napi != napi? (I do not understand why)

Fair. It's the same NAPI, with other rules. napi is the driver's
association: read under the ops lock, and not cleared when the NAPI is deleted. Provider wakeups run without that lock, from socket syscalls and ->release_netmem().

Quoted 5 lines

mp_napi is an RCU copy, set only while the device is up and the queue isn't restarting, for providers with ->refill_done(). netif_napi_del() clears it before its grace period. Setting it also schedules the NAPI once, which replays wakeups lost while the queue was stopped. I'll put that in the comment.

Quoted 3 lines

And all this only to make sure that we are not recycling something from the old pp into the new one? And reworking existing pointer to change/update its lifetime is not gonna do it?

No, it's how the provider wakes the queue when chunks show up: userspace posts FILL and calls {e,}poll() or sendto(), or an old page pool releases chunks after a restart. It replaces ndo_xsk_wakeup.

But! I think that rxq->napi can do it: make it RCU, clear it when the NAPI is deleted, and have the driver poll the queue once after enabling its NAPI, as fbnic does. A wakeup that hits a stopped queue is then covered by that poll, so mp_napi and mp_armed go (and with them the error-path bugs Sashiko found...) I'll do that in v2.

Björn

#65 lore raw

Re: [PATCH net-next v1 06/11] page_pool: Coordinate refill with memory providers

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] xsk: use-after-free of pp->pool in xsk_pp_refill_done() after detach - [Medium] net: wrong mp_napi…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] xsk: use-after-free of pp->pool in xsk_pp_refill_done() after detach
- [Medium] net: wrong mp_napi state after netdev_rx_queue_reconfig() error recovery
- [Medium] net: dangling rxq->napi left by netif_mp_napi_del() and republished
--

commit 3fe1ff48cc345ebc097d0481e784047c7126ab42
Author: Björn Töpel <[email protected]>

page_pool: Coordinate refill with memory providers

This commit adds page_pool_refill_done() and NAPI wakeup tracking on RX queues so that memory providers such as AF_XDP can re-poll or wake queues when buffers return.

Quoted 85 lines
net/core/netdev_rx_queue.c +77 -0
index 4e2f906fbc735..3fe904b56791b 100644
@@ -116,6 +116,94 @@ bool netif_all_mps_have_cap(struct net_device *dev, u32 cap)
 	return true;
 }
 
+/**
+ * netif_mp_wake - schedule the NAPI that refills a memory provider queue
+ * @rxq: physical RX queue of the provider
+ *
+ * Context: IRQs enabled, not in hardirq. The caller keeps the device of
+ * @rxq alive.
+ *
+ * Return: false if no NAPI refills the queue.
+ */
+bool netif_mp_wake(struct netdev_rx_queue *rxq)
+{
+	struct napi_struct *napi;
+	bool running = false;
+
+	rcu_read_lock();
+	napi = rcu_dereference(rxq->mp_napi);
+	if (napi) {
+		local_bh_disable();
+		napi_schedule(napi);
+		local_bh_enable();
+		running = true;
+	}
+	rcu_read_unlock();
+
+	return running;
+}
+
+/* Point wakeups at the NAPI of the running queue, and schedule it once: a
+ * refill during the start may have found no buffers.
+ */
+void netif_mp_update_napi(struct netdev_rx_queue *rxq)
+{
+	const struct memory_provider_ops *ops = rxq->mp_params.mp_ops;
+	struct napi_struct *napi = NULL;
+
+	if (rxq->mp_armed && ops && ops->refill_done)
+		napi = rxq->napi;
+	if (rcu_access_pointer(rxq->mp_napi) == napi)
+		return;
+
+	rcu_assign_pointer(rxq->mp_napi, napi);
+	if (napi)
+		netif_mp_wake(rxq);
+}
+
+static void netif_mp_arm_napi(struct netdev_rx_queue *rxq)
+{
+	rxq->mp_armed = true;
+	netif_mp_update_napi(rxq);
+}
+
+static void netif_mp_disarm_napi(struct netdev_rx_queue *rxq)
+{
+	rxq->mp_armed = false;
+	RCU_INIT_POINTER(rxq->mp_napi, NULL);
+}
+
+void netif_mp_arm_dev(struct net_device *dev)
+{
+	unsigned int i;
+
+	for (i = 0; i < dev->real_num_rx_queues; i++)
+		netif_mp_arm_napi(__netif_get_rx_queue(dev, i));
+}
+
+void netif_mp_disarm_dev(struct net_device *dev)
+{
+	unsigned int i;
+
+	for (i = 0; i < dev->num_rx_queues; i++)
+		netif_mp_disarm_napi(&dev->_rx[i]);
+}
+
+/* The grace period of netif_napi_del() covers wakeups that found @napi. */
+void netif_mp_napi_del(struct napi_struct *napi)
+{
+	struct net_device *dev = napi->dev;

net/core/netdev_rx_queue.c bool netif_all_mps_have_cap(struct net_device *dev, u32 cap) · line 205

Quoted 10 lines
net/core/netdev_rx_queue.c +10 -0
+	unsigned int i;
+
+	/* free_netdev() frees the queues before it deletes the last NAPIs */
+	if (dev->reg_state != NETREG_REGISTERED)
+		return;
+
+	for (i = 0; i < dev->num_rx_queues; i++)
+		if (rcu_access_pointer(dev->_rx[i].mp_napi) == napi)
+			RCU_INIT_POINTER(dev->_rx[i].mp_napi, NULL);
+}

[Severity: Medium]
Does netif_mp_napi_del() leave a dangling pointer in dev->_rx[i].napi?

__netif_napi_del_locked() calls netif_mp_napi_del(), which clears dev->_rx[i].mp_napi, including when mp_napi is already NULL because __dev_close_many() or netdev_rx_queue_reconfig() disarmed the queue first. Because dev->_rx[i].napi is left pointing to @napi, if a driver deletes a NAPI without calling netif_queue_set_napi(..., NULL), the next netif_mp_update_napi() copies the freed dev->_rx[i].napi back into rxq->mp_napi and calls napi_schedule() on it, causing a use-after-free.

Quoted 20 lines
net/core/netdev_rx_queue.c +3 -1
@@ -152,13 +240,15 @@ static int netdev_rx_queue_reconfig(struct net_device *dev,
 		goto err_free_new_queue_mem;
 
 	if (netif_running(dev)) {
+		netif_mp_disarm_napi(rxq);
 		err = qops->ndo_queue_stop(dev, old_mem, rxq_idx);
 		if (err)
-			goto err_free_new_queue_mem;
+			goto err_arm_old_queue;
 
 		err = qops->ndo_queue_start(dev, qcfg_new, new_mem, rxq_idx);
 		if (err)
 			goto err_start_queue;
+		netif_mp_arm_napi(rxq);
 	} else {
 		swap(new_mem, old_mem);
 	}
@@ -183,8 +273,13 @@ static int netdev_rx_queue_reconfig(struct net_device *dev,
 		     "Failed to restart old queue in error path. RX queue %d may be unhealthy.",
 		     rxq_idx);

net/core/netdev_rx_queue.c static int netdev_rx_queue_reconfig(struct net_device *dev, · line 284

Quoted 10 lines
net/core/netdev_rx_queue.c +5 -0
 		qops->ndo_queue_mem_free(dev, old_mem);
+		goto err_free_new_queue_mem;
 	}
 
+err_arm_old_queue:
+	/* The old queue may run */
+	netif_mp_arm_napi(rxq);
+
 err_free_new_queue_mem:
 	qops->ndo_queue_mem_free(dev, new_mem);

[Severity: Medium]
Does err_arm_old_queue arm rxq->mp_napi using the target rxq->mp_params instead of the running old queue's provider state?

Both __netif_mp_open_rxq() and __netif_mp_close_rxq() mutate rxq->mp_params before calling netdev_rx_queue_reconfig():

net/core/netdev_rx_queue.c:__netif_mp_open_rxq() {
	...
	rxq->mp_params = *p;
	...
	ret = netdev_rx_queue_reconfig(dev, rxq_idx, &qcfg[0], &qcfg[1]);
	if (ret)
		goto err_clear_mp;

	return 0;

err_clear_mp:

	memset(&rxq->mp_params, 0, sizeof(rxq->mp_params));
	return ret;
}

When ndo_queue_stop() or ndo_queue_start() fails during __netif_mp_open_rxq(), err_arm_old_queue sees the new provider in rxq->mp_params, sets rxq->mp_napi to rxq->napi, and wakes NAPI before err_clear_mp zeroes rxq->mp_params, leaving rxq->mp_napi set with no provider installed. Conversely, __netif_mp_close_rxq() zeroes rxq->mp_params before calling netdev_rx_queue_reconfig(), so on failure err_arm_old_queue sees NULL mp_ops and leaves rxq->mp_napi NULL even though the old provider-backed queue is still running.

Quoted 4 lines
net/xdp/xsk_pp.c +0 -0
index c2214e718cdb3..a77213f7fef6b 100644

[ ... ]

Quoted 20 lines
net/xdp/xsk_pp.c +11 -0
@@ -232,11 +253,47 @@ static bool xsk_pp_release_netmem(struct page_pool *pool, netmem_ref netmem)
 		pp->state[idx] = XSK_PP_REUSE;
 		pp->reuse[pp->reuse_cnt++] = idx;
 	}
+	starved = pp->starved;
+	WRITE_ONCE(pp->starved, false);
 	spin_unlock_bh(&pp->lock);
 
+	/* A starved queue may wait for this release */
+	if (starved)
+		xsk_pp_wake(pp);
+
 	return false;
 }
 
+static bool xsk_pp_refill_done(struct page_pool *pool, enum pp_refill state)
+{
+	struct xsk_pp *pp = pool->mp_priv;
+	struct xsk_buff_pool *xp = pp->pool;
+	bool wait = xp->uses_need_wakeup;

net/xdp/xsk_pp.c static bool xsk_pp_release_netmem(struct page_pool *pool, netmem_ref netmem) · line 281

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+	bool more;
+
+	if (state == PP_REFILL_FULL && !READ_ONCE(pp->starved))
+		return true;
+
+	spin_lock_bh(&pp->lock);
+	if (!pp->fq) {
+		spin_unlock_bh(&pp->lock);
+		return true;
+	}

[Severity: High]
Can xsk_pp_refill_done() dereference pp->pool after xp_destroy() has freed it?

A page_pool holds its own reference on struct xsk_pp via pp->refs, while pp->pool is an uncounted backpointer to struct xsk_buff_pool. When xp_release_deferred() tears down the pool, xsk_pp_unbind() calls netif_mp_close_rxq() and unconditionally calls xsk_pp_detach(pp) (which sets pp->fq = NULL under pp->lock and unmaps DMA), and xp_release_deferred() then frees pp->pool in xp_destroy(). If netif_mp_close_rxq() fails in netdev_rx_queue_reconfig(), the old queue and its page_pool keep running and calling xsk_pp_refill_done(), which reads xp->uses_need_wakeup before taking pp->lock and checking pp->fq, causing a use-after-free.

In addition, if netif_mp_open_rxq() fails in xsk_pp_bind() while a page_pool still holds a reference on pp (so xsk_pp_abandon(pp) returns false), xsk_pp_bind() leaves pp->fq non-NULL when xsk_bind() calls xp_destroy().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#66 lore raw

Re: [PATCH net-next v1 06/11] page_pool: Coordinate refill with memory providers

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider.

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

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

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

- [Medium] net/xdp/xsk_pp.c: xsk_pp_refill_done() can read freed memory.
- [Medium] Provider wakeups that land on a disabled NAPI are dropped silently, and xsk_pp_release_netmem() clears pp->starved before it…
- [Medium] net: wrong mp_napi state after netdev_rx_queue_reconfig() error recovery
- [Medium] net: dangling rxq->napi left by netif_mp_napi_del() and republished
- [Low] Not confirmed (baseline: false positive).
- [Low] Not confirmed (baseline: false positive).

--

page_pool: Coordinate refill with memory providers

This commit adds a refill_done memory provider op and a page_pool_refill_done() helper, so drivers can report the end of each RX ring refill. While a queue runs, the core publishes its NAPI in rxq->mp_napi, and a provider can use it to wake the queue when buffers come back. The xsk provider uses this to track starvation, and AF_XDP socket wakeups go through it instead of ndo_xsk_wakeup.

Quoted 10 lines
net/core/netdev_rx_queue.c +2 -0
index 4e2f906fbc735..3fe904b56791b 100644
@@ -116,6 +116,94 @@ bool netif_all_mps_have_cap(struct net_device *dev, u32 cap)
 	return true;
 }
 
+/**
+ * netif_mp_wake - schedule the NAPI that refills a memory provider queue

[ ... ]

Quoted 25 lines
net/core/netdev_rx_queue.c +25 -0
+bool netif_mp_wake(struct netdev_rx_queue *rxq)
+{
+	struct napi_struct *napi;
+	bool running = false;
+
+	rcu_read_lock();
+	napi = rcu_dereference(rxq->mp_napi);
+	if (napi) {
+		local_bh_disable();
+		napi_schedule(napi);
+		local_bh_enable();
+		running = true;
+	}
+	rcu_read_unlock();
+
+	return running;
+}
+
+/* Point wakeups at the NAPI of the running queue, and schedule it once: a
+ * refill during the start may have found no buffers.
+ */
+void netif_mp_update_napi(struct netdev_rx_queue *rxq)
+{
+	const struct memory_provider_ops *ops = rxq->mp_params.mp_ops;
+	struct napi_struct *napi = NULL;

net/core/netdev_rx_queue.c bool netif_all_mps_have_cap(struct net_device *dev, u32 cap) · line 162

Quoted 10 lines
net/core/netdev_rx_queue.c +10 -0
+
+	if (rxq->mp_armed && ops && ops->refill_done)
+		napi = rxq->napi;
+	if (rcu_access_pointer(rxq->mp_napi) == napi)
+		return;
+
+	rcu_assign_pointer(rxq->mp_napi, napi);
+	if (napi)
+		netif_mp_wake(rxq);
+}

[Severity: Medium]
Can this leave rxq->napi dangling for netif_mp_update_napi() to pick up again?

netif_mp_napi_del() clears dev->_rx[i].mp_napi when it matches the NAPI being deleted, but dev->_rx[i].napi still points at it. __dev_close_many() and netdev_rx_queue_reconfig() disarm the queue around ndo_stop() and ndo_queue_stop(). While it is disarmed, mp_napi is already NULL, so this loop does not touch the queue at all.

Suppose the driver deletes the NAPI without first calling netif_queue_set_napi() with a NULL napi. Suppose it also does not register another NAPI for that queue before the next netif_mp_arm_napi() or netif_mp_arm_dev(). Then netif_mp_update_napi() reads the stale rxq->napi and publishes it in rxq->mp_napi. It then calls netif_mp_wake(), which does napi_schedule() on a deleted napi_struct.

For drivers that free the NAPI together with their queue vectors, this is a use-after-free. Every later provider wakeup also goes through the same pointer.

Should netif_mp_napi_del() also clear rxq->napi when it matches, or should netif_mp_update_napi() only publish a NAPI that is still listed? If drivers are expected to clear the association themselves, could netmem.rst item 8 say so?

[Severity: Medium]
Can this kick be lost when it lands on a disabled NAPI?

Drivers often call netif_queue_set_napi() during ring setup, before napi_enable(). If the NAPI is disabled, napi_schedule_prep() sees NAPIF_STATE_SCHED already set and only sets NAPIF_STATE_MISSED. napi_enable_locked() then clears SCHED/NPSVC/DISABLED without acting on MISSED, so no poll runs.

netif_mp_wake() still returns true, because it ignores the result of napi_schedule().

If the driver reuses the same napi_struct across a restart, the early return on rcu_access_pointer(rxq->mp_napi) == napi skips the kick entirely.

The core re-kicks only from netif_mp_arm_dev() and netif_mp_arm_napi(). Driver-internal restarts (ethtool -G/-L, MTU or XDP changes, resets) keep mp_armed set, so this kick is the only one they get.

The starved state doesn't recover either. xsk_pp_release_netmem() clears pp->starved before it knows whether the wakeup reached an enabled NAPI:

	starved = pp->starved;
	WRITE_ONCE(pp->starved, false);
	spin_unlock_bh(&pp->lock);

	/* A starved queue may wait for this release */
	if (starved)
		xsk_pp_wake(pp);

Here is one sequence:

- The new rings are filled while the old pool still holds the chunks, so the refill finds nothing and sets starved.
- The old pool then releases the chunks while mp_napi is NULL or the NAPI is still disabled, so the wakeup is dropped.
- Later releases don't retry, and the empty ring raises no IRQ.

Wouldn't that leave RX stalled, which is the problem this patch sets out to fix?

fbnic avoids this because fbnic_napi_enable() and __fbnic_nv_restart() write FBNIC_INTR_SET after napi_enable_locked(). However, netmem.rst item 8 only says "the core schedules it when provider buffers become available", and does not ask drivers to force a poll after napi_enable().

Should the documented contract require that, or should the core handle the disabled-NAPI case itself?

[ ... ]

Quoted 4 lines
net/xdp/xsk_pp.c +0 -0
index c2214e718cdb3..a77213f7fef6b 100644

[ ... ]

Quoted 1 line
net/xdp/xsk_pp.c +0 -0
@@ -232,11 +253,47 @@ static bool xsk_pp_release_netmem(struct page_pool *pool, netmem_ref netmem)

[ ... ]

net/xdp/xsk_pp.c static bool xsk_pp_release_netmem(struct page_pool *pool, netmem_ref netmem) · line 271

Quoted 5 lines
net/xdp/xsk_pp.c +5 -0
+static bool xsk_pp_refill_done(struct page_pool *pool, enum pp_refill state)
+{
+	struct xsk_pp *pp = pool->mp_priv;
+	struct xsk_buff_pool *xp = pp->pool;
+	bool wait = xp->uses_need_wakeup;

[Severity: Medium]
Can this read a freed xsk_buff_pool?

pp->pool is dereferenced in the initializer, before the !pp->fq check that handles a detached provider. So the read happens even on the PP_REFILL_FULL fast path.

The xsk_pp can outlive the buff pool. Each page pool built on it holds a ref taken in xsk_pp_init(), but xp_destroy() drops only the buff pool's own ref before freeing it:

net/xdp/xsk_buff_pool.c:xp_destroy() {
    ...
	if (pool->pp)
		xsk_pp_put(pool->pp);
	kvfree(pool->tx_descs);
	kvfree(pool->heads);
	kvfree(pool);
}

One way to get there is a failed queue reconfig during unbind, after which the old queue keeps running on the provider's page pools. The reconfig can fail in kvzalloc() or ndo_queue_mem_alloc(), or in ndo_queue_start(), whose error path restarts old_mem:

xsk_pp_unbind()
netif_mp_close_rxq()
__netif_mp_close_rxq()
netdev_rx_queue_reconfig() <- fails, only WARNs
xsk_pp_detach() <- error ignored, fq = NULL
xp_destroy() <- kvfree(pool)

After that, the old queue's NAPI still calls page_pool_refill_done() after each refill. That reaches xsk_pp_refill_done(), which reads xp->uses_need_wakeup from the freed pool.

Before this patch, the provider callbacks that can run after detach either didn't touch pp->pool or checked pp->fq first.

Could uses_need_wakeup be cached in struct xsk_pp when it is created, or read only after pp->fq is confirmed under pp->lock?

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+	bool more;
+
+	if (state == PP_REFILL_FULL && !READ_ONCE(pp->starved))
+		return true;
+
+	spin_lock_bh(&pp->lock);
+	if (!pp->fq) {
+		spin_unlock_bh(&pp->lock);
+		return true;
+	}

[ ... ]

Quoted 4 lines
net/xdp/xsk_pp.c +0 -0
@@ -183,8 +273,13 @@ static int netdev_rx_queue_reconfig(struct net_device *dev,
 		     "Failed to restart old queue in error path. RX queue %d may be unhealthy.",
 		     rxq_idx);
 		qops->ndo_queue_mem_free(dev, old_mem);

net/xdp/xsk_pp.c static int netdev_rx_queue_reconfig(struct net_device *dev, · line 285

Quoted 10 lines
net/xdp/xsk_pp.c +5 -0
+		goto err_free_new_queue_mem;
 	}
 
+err_arm_old_queue:
+	/* The old queue may run */
+	netif_mp_arm_napi(rxq);
+
 err_free_new_queue_mem:
 	qops->ndo_queue_mem_free(dev, new_mem);
 

[Severity: Medium]
Does this arm the queue from the right provider state?

When netdev_rx_queue_reconfig() runs, rxq->mp_params already holds the target configuration. It does not hold the configuration of the queue that is restarted on this error path.

In __netif_mp_open_rxq(), rxq->mp_params = *p is written before the reconfig. If ndo_queue_stop() fails, or ndo_queue_start() fails and the old queue is restarted, netif_mp_arm_napi() here sees the new provider's refill_done. It publishes rxq->napi in rxq->mp_napi and kicks it. The error then goes back to __netif_mp_open_rxq(), which zeroes rxq->mp_params at err_clear_mp but never resyncs mp_napi.

That leaves mp_napi published for a queue with no provider installed, which breaks the rule documented in struct netdev_rx_queue. A later netif_mp_wake() on that rxq would schedule it. The early return in netif_mp_update_napi() would also compare against a pointer that should not be there.

The close direction is the mirror image. __netif_mp_close_rxq() clears rxq->mp_params before the reconfig. If the stop or the restart then fails, netif_mp_update_napi() sees no mp_ops and leaves mp_napi NULL, even though the old queue keeps running on the provider's page pools.

Should the error path arm from the configuration that is running again, or should __netif_mp_open_rxq() and __netif_mp_close_rxq() call netif_mp_update_napi() once they have settled rxq->mp_params?

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261110102039.1002605-1-bjorn%40kernel.org
#67 lore raw

Re: [PATCH net-next v1 06/11] page_pool: Coordinate refill with memory providers

[email protected] writes:

[...]

Quoted 4 lines

Should netif_mp_napi_del() also clear rxq->napi when it matches, or should netif_mp_update_napi() only publish a NAPI that is still listed? If drivers are expected to clear the association themselves, could netmem.rst item 8 say so?

The first. v2 drops mp_napi, so wakeups use rxq->napi itself, under RCU, and the core clears it when the NAPI is deleted.

[...]

Quoted 2 lines

Should the documented contract require that, or should the core handle the disabled-NAPI case itself?

The contract. fbnic polls the vector right after napi_enable() (FBNIC_INTR_SET), so the queue refills once, from the reuse stack or FILL, and refill_done marks it starved again if both are empty. A wakeup lost on a stopped queue doesn't matter then. v2 documents that a driver polls the queue once after enabling its NAPI.

Quoted 2 lines

Could uses_need_wakeup be cached in struct xsk_pp when it is created, or read only after pp->fq is confirmed under pp->lock?

Same root cause as the failed removal in 05, and the same fix. The pool then stays until the queue DMA has stopped, and no refill runs after that.

Quoted 3 lines

Should the error path arm from the configuration that is running again, or should __netif_mp_open_rxq() and __netif_mp_close_rxq() call netif_mp_update_napi() once they have settled rxq->mp_params?

Neither is needed -- with mp_napi and mp_armed gone in v2, there is no wakeup target to arm from the wrong configuration.

Björn

#68 lore raw

PATCH 7/11 xsk: Deliver provider chunks without copying

In reply to Björn Töpel

A provider socket still receives through the copy path, which takes FILL entries without the provider's ownership checks: a chunk that a page pool holds could be handed out twice. No driver opts in yet.

Put packets whose buffers all belong to the socket's provider on the RX ring as they are, and copy others into chunks the provider claims. Only the queue NAPI may produce to such a socket, so generic XDP and CPUMAP redirects to it are dropped.

A device may place payload at chunk offset 0, as fbnic does, so only the first buffer of a packet keeps the UMEM headroom. Such buffers may be sent back as they are, so only descriptors with XDP_TX_METADATA need room for TX metadata in front.

---
 Documentation/networking/af_xdp.rst          |   6 +-
 Documentation/networking/xsk-tx-metadata.rst |   3 +-
 include/net/page_pool/memory_provider.h      |   2 +
 net/core/page_pool.c                         |  34 +++-
 net/xdp/xsk.c                                |  82 ++++++++-
 net/xdp/xsk.h                                |   5 +
 net/xdp/xsk_pp.c                             | 165 +++++++++++++++++++
 net/xdp/xsk_queue.h                          |  18 +-
 8 files changed, 304 insertions(+), 11 deletions(-)
Documentation/networking/af_xdp.rst +4 -2
index cc3f0d16b28f..e73a0005e169 100644
@@ -428,8 +428,10 @@ area and that your largest packet size can be 2K.
 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.
+application to use. In a multi-buffer packet, only the first buffer is
+guaranteed this headroom; the others may start at offset 0 of their
+chunk. The final option is the flags field, but it will be dealt with
+in separate sections for each UMEM flag.
 
 SO_BINDTODEVICE setsockopt
 --------------------------
Documentation/networking/xsk-tx-metadata.rst +2 -1
index f240930ca1df..8bb74a569c26 100644
@@ -59,7 +59,8 @@ The flags field enables the particular offload:
 Besides the flags above, in order to trigger the offloads, the first
 packet's ``struct xdp_desc`` descriptor should set ``XDP_TX_METADATA``
 bit in the ``options`` field. Also note that in a multi-buffer packet
-only the first chunk should carry the metadata.
+only the first chunk should carry the metadata. Only a descriptor with
+``XDP_TX_METADATA`` needs ``tx_metadata_len`` bytes in front of it.
 
 Software TX Checksum
 ====================
include/net/page_pool/memory_provider.h +2 -0
index daec73c9dcee..849db08513b8 100644
@@ -49,6 +49,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_bulk(struct page_pool *pool,
+				   netmem_ref *netmems, u32 count);
 
 int netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		      const struct pp_memory_provider_params *p,
net/core/page_pool.c +33 -1
index e897e79d31f1..56c299f2280d 100644
@@ -1401,7 +1401,7 @@ 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_bulk()
  */
 void net_mp_niov_set_page_pool(struct page_pool *pool, struct net_iov *niov)
 {
@@ -1422,3 +1422,35 @@ void net_mp_niov_clear_page_pool(struct net_iov *niov)
 
 	page_pool_clear_pp_info(netmem);
 }
+
+/**
+ * net_mp_release_page_pool_bulk() - take net_iovs back from a page pool
+ * @pool: page pool that holds one reference to each net_iov
+ * @netmems: net_iovs of the memory provider of @pool
+ * @count: number of entries in @netmems
+ *
+ * A memory provider takes net_iovs out of a page pool without
+ * ->release_netmem(), for example to give them to userspace. @pool may be
+ * freed on return.
+ */
+void net_mp_release_page_pool_bulk(struct page_pool *pool,
+				   netmem_ref *netmems, u32 count)
+{
+	bool trace = trace_page_pool_state_release_enabled();
+	atomic_t *release_cnt = &pool->pages_state_release_cnt;
+	int released;
+	u32 i;
+
+	for (i = 0; i < count; i++) {
+		DEBUG_NET_WARN_ON_ONCE(netmem_get_pp(netmems[i]) != pool);
+		page_pool_clear_pp_info(netmems[i]);
+		if (!trace)
+			continue;
+
+		released = atomic_inc_return_relaxed(release_cnt);
+		trace_page_pool_state_release(pool, netmems[i], released);
+	}
+
+	if (!trace)
+		atomic_add(count, release_cnt);
+}
net/xdp/xsk.c +80 -2

107 lines not on this page · raw message

net/xdp/xsk.h +5 -0
index d7d6bcf0a893..a5f52ef382a6 100644
@@ -43,6 +43,11 @@ int xsk_pp_bind(struct xsk_buff_pool *pool, struct net_device *dev,
 		u16 queue_id);
 void xsk_pp_unbind(struct xsk_buff_pool *pool);
 int xsk_pp_wakeup(struct xsk_pp *pp);
+void xsk_pp_flush(struct xsk_pp *pp);
+bool xsk_pp_queue_buf(struct xsk_pp *pp, struct xdp_buff *xdp);
+int xsk_pp_rcv_zc(struct xsk_pp *pp, struct xdp_sock *xs,
+		  struct xdp_buff *xdp);
+bool xsk_pp_claim_copy(struct xsk_pp *pp, u64 *addrs, u32 n);
 int xp_alloc_heads(struct xsk_buff_pool *pool);
 void xsk_clear_pool_at_qid(struct net_device *dev, u16 queue_id);
 int xsk_reg_pool_at_qid(struct net_device *dev, struct xsk_buff_pool *pool,
net/xdp/xsk_pp.c +165 -0

188 lines not on this page · raw message

net/xdp/xsk_queue.h +13 -5
index 1bc42c8902f4..b9464b917a88 100644
@@ -156,17 +156,24 @@ static inline bool xp_unused_options_set(u32 options)
 	return options & ~(XDP_PKT_CONTD | XDP_TX_METADATA);
 }
 
+static inline u32 xp_desc_meta_len(struct xsk_buff_pool *pool,
+				   struct xdp_desc *desc)
+{
+	return desc->options & XDP_TX_METADATA ? pool->tx_metadata_len : 0;
+}
+
 static inline bool xp_aligned_validate_desc(struct xsk_buff_pool *pool,
 					    struct xdp_desc *desc)
 {
+	u32 meta = xp_desc_meta_len(pool, desc);
 	u64 len = desc->len;
 	u64 addr, offset;
 
 	if (!len)
 		return false;
 
-	/* Can overflow if desc->addr < pool->tx_metadata_len */
-	if (check_sub_overflow(desc->addr, pool->tx_metadata_len, &addr))
+	/* Can overflow if desc->addr < meta */
+	if (check_sub_overflow(desc->addr, meta, &addr))
 		return false;
 
 	offset = addr & (pool->chunk_size - 1);
@@ -176,7 +183,7 @@ static inline bool xp_aligned_validate_desc(struct xsk_buff_pool *pool,
 	 * (pool->chunk_size is ``u32``), @len is guaranteed
 	 * to be <= ``U32_MAX``.
 	 */
-	if (offset + len + pool->tx_metadata_len > pool->chunk_size)
+	if (offset + len + meta > pool->chunk_size)
 		return false;
 
 	if (addr >= pool->addrs_cnt)
@@ -191,6 +198,7 @@ static inline bool xp_aligned_validate_desc(struct xsk_buff_pool *pool,
 static inline bool xp_unaligned_validate_desc(struct xsk_buff_pool *pool,
 					      struct xdp_desc *desc)
 {
+	u32 meta = xp_desc_meta_len(pool, desc);
 	u64 len = desc->len;
 	u64 addr, end;
 
@@ -198,13 +206,13 @@ static inline bool xp_unaligned_validate_desc(struct xsk_buff_pool *pool,
 		return false;
 
 	/* Can't overflow: @len is guaranteed to be <= ``U32_MAX`` */
-	len += pool->tx_metadata_len;
+	len += meta;
 	if (len > pool->chunk_size)
 		return false;
 
 	/* Can overflow if desc->addr is close to 0 */
 	if (check_sub_overflow(xp_unaligned_add_offset_to_addr(desc->addr),
-			       pool->tx_metadata_len, &addr))
+			       meta, &addr))
 		return false;
 
 	if (addr >= pool->addrs_cnt)
Signature · 1 line
2.56.0
#69 lore raw

Re: [PATCH net-next v1 07/11] xsk: Deliver provider chunks without copying

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

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

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

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

- [Medium] The patch weakens a documented AF_XDP UAPI guarantee, and userspace cannot opt in or detect it.
- [Low] The commit message gets wrong what the old copy path did.
- [Low] The patch adds a new core page_pool memory-provider API, net_mp_release_page_pool_bulk(), in net/core/page_pool.c and…
- [Low] The new drop paths for provider sockets in xsk_rcv() do a plain non-atomic xs->rx_dropped++ on a u64 from contexts outside the queue…

--

xsk: Deliver provider chunks without copying

This commit puts packets whose buffers all belong to the socket's memory provider directly on the AF_XDP RX ring, and copies other packets into chunks claimed from the provider. Generic XDP and CPUMAP redirects to provider sockets are dropped. TX descriptor validation now reserves tx_metadata_len only for descriptors with XDP_TX_METADATA.

Quoted 3 lines

A provider socket still receives through the copy path, which takes FILL entries without the provider's ownership checks: a chunk that a page pool holds could be handed out twice. No driver opts in yet.

[Severity: Low]
Does this describe what the old copy path actually does for a provider socket?

Before this patch, xsk_rcv() calls __xsk_rcv() for provider sockets, because their mem.type is MEM_TYPE_PAGE_POOL. That leads to:

xsk_rcv()->__xsk_rcv()->xsk_buff_alloc()->xp_alloc()->__xp_alloc()

    ->xp_get_xskb()

For a provider bind, pool->free_heads_cnt is umem->chunks and pool->fq is still set. So __xp_alloc() peeks a FILL entry, and in aligned mode (the only mode xsk_pp_bind() accepts) xp_get_xskb() returns &pool->heads[idx].

pool->heads is never allocated here. xp_assign_dev() returns right after a successful xsk_pp_bind() and never calls xp_alloc_heads():

net/xdp/xsk_buff_pool.c:xp_assign_dev() {
    ...
	if (xsk_pp_supported(netdev)) {
		err = xsk_pp_bind(pool, netdev, queue_id);
		if (err)
			goto err_unreg_pool;

		pool->umem->zc = true;
		return 0;
	}
    ...
}

xp_alloc() then writes xskb->xdp.data through a NULL-based pointer.

So the failure would be a NULL or wild pointer dereference in NAPI, not a chunk handed out twice. No driver opts in yet, so there is no runtime impact. Could the commit message describe the actual failure mode?

Quoted 4 lines
net/core/page_pool.c +0 -0
index e897e79d31f19..56c299f2280d7 100644

[ ... ]

Quoted 8 lines
net/core/page_pool.c +4 -0
@@ -1422,3 +1422,35 @@ void net_mp_niov_clear_page_pool(struct net_iov *niov)
 
 	page_pool_clear_pp_info(netmem);
 }
+
+/**
+ * net_mp_release_page_pool_bulk() - take net_iovs back from a page pool
+ * @pool: page pool that holds one reference to each net_iov

net/core/page_pool.c void net_mp_niov_clear_page_pool(struct net_iov *niov) · line 1438

Quoted 10 lines
net/core/page_pool.c +10 -0
+ * @netmems: net_iovs of the memory provider of @pool
+ * @count: number of entries in @netmems
+ *
+ * A memory provider takes net_iovs out of a page pool without
+ * ->release_netmem(), for example to give them to userspace. @pool may be
+ * freed on return.
+ */
+void net_mp_release_page_pool_bulk(struct page_pool *pool,
+				   netmem_ref *netmems, u32 count)
+{

[Severity: Low]
This isn't a bug, but this adds a new core page_pool memory provider API, declared in include/net/page_pool/memory_provider.h. The xsk commit message doesn't mention it.

The helper clears pp_info and advances pool->pages_state_release_cnt. That counter feeds the inflight accounting that decides when a destroyed pool is freed. The helper also documents that @pool may be freed on return.

Other core changes in this series, such as "page_pool: Coordinate refill with memory providers", got their own patches. Could this go in a separate page_pool patch, so the page_pool maintainers can review the new contract?

[ ... ]

Quoted 4 lines
net/xdp/xsk.c +0 -0
index 113b0b08356d5..b419c673e3f14 100644

[ ... ]

Quoted 13 lines
net/xdp/xsk.c +8 -1
@@ -488,7 +547,26 @@ static int xsk_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 		return xsk_rcv_zc(xs, xdp, len);
 	}
 
-	err = __xsk_rcv(xs, xdp, len);
+	if (!xs->pool->pp) {
+		err = __xsk_rcv(xs, xdp, len);
+	} else {
+		/* A CPUMAP program runs XDP on another CPU, not in NAPI. */
+		if (unlikely(!xdp_rxq_info_is_reg(xdp->rxq))) {
+			xs->rx_dropped++;
+			return -EINVAL;
+		}

net/xdp/xsk.c static int xsk_rcv(struct xdp_sock *xs, struct xdp_buff *xdp) · line 567

Quoted 10 lines
net/xdp/xsk.c +10 -0
+
+		err = xsk_pp_rcv_zc(xs->pool->pp, xs, xdp);
+		if (err != -EXDEV)
+			return err;
+
+		/* Copy only packets of the queue, from its NAPI */
+		if (unlikely(!xsk_pp_queue_buf(xs->pool->pp, xdp))) {
+			xs->rx_dropped++;
+			return -EINVAL;
+		}

[Severity: Low]
Can these xs->rx_dropped++ updates race with the queue NAPI?

The CPUMAP kthread reaches the unregistered rxq branch. cpu_map_bpf_prog_run_xdp() uses an on-stack rxq:

kernel/bpf/cpumap.c:cpu_map_bpf_prog_run_xdp() {
    ...
	struct xdp_rxq_info rxq = {};
    ...
}

It sets rxq.dev = xdpf->dev_rx and leaves queue_index at 0, so xsk_rcv_check() passes for a socket bound to queue 0.

A BPF_F_TEST_XDP_LIVE_FRAMES test run reaches the xsk_pp_queue_buf() branch. xdp_test_run_setup() registers a fake rxq on the real device with queue_index 0 and page-backed MEM_TYPE_PAGE_POOL buffers. xsk_pp_rcv_zc() returns -EXDEV, then xsk_pp_queue_buf() returns false, all in process context.

At the same time, the queue NAPI on another CPU can increment xs->rx_dropped and xs->rx_queue_full in xsk_pp_rcv_copy(), xsk_pp_rcv_zc() and xsk_rcv_check(). No lock is shared between these contexts.

Would concurrent increments get lost, and could the u64 counter tear on 32-bit, so that XDP_STATISTICS reports wrong drop counts? xsk_rcv_check() already has the same unsynchronized pattern, and the effect is limited to these counters.

Quoted 5 lines
net/xdp/xsk.c +2 -0
+		err = xsk_pp_rcv_copy(xs, xdp, len);
+	}
 	if (!err)
 		xdp_return_buff(xdp);
 	return err;

[ ... ]

Quoted 4 lines
net/xdp/xsk_pp.c +0 -0
index a77213f7fef6b..a1c2ca00f0169 100644

[ ... ]

Quoted 1 line
net/xdp/xsk_pp.c +0 -0
@@ -294,6 +299,166 @@ static bool xsk_pp_refill_done(struct page_pool *pool, enum pp_refill state)

[ ... ]

Quoted 4 lines
net/xdp/xsk_pp.c +4 -0
+/* Returns -EXDEV for a packet that must be copied. Called from the NAPI. */
+int xsk_pp_rcv_zc(struct xsk_pp *pp, struct xdp_sock *xs,
+		  struct xdp_buff *xdp)
+{

[ ... ]

net/xdp/xsk_pp.c static bool xsk_pp_refill_done(struct page_pool *pool, enum pp_refill state) · line 421

Quoted 10 lines
net/xdp/xsk_pp.c +10 -0
+	__xskq_prod_reserve_desc(xs->rx, xdp->data - umem,
+				 xdp->data_end - xdp->data,
+				 nr_frags ? XDP_PKT_CONTD : 0);
+	pp->pending[pp->pending_cnt++] = head;
+
+	for (i = 0; i < nr_frags; i++) {
+		frag = &sinfo->frags[i];
+		__xskq_prod_reserve_desc(xs->rx, skb_frag_address(frag) - umem,
+					 skb_frag_size(frag),
+					 i + 1 < nr_frags ? XDP_PKT_CONTD : 0);

[Severity: Medium]
Does this weaken the documented AF_XDP headroom guarantee for XDP_USE_SG applications, with no way to opt in or detect it?

af_xdp.rst says a UMEM headroom of N means the packet "will start N bytes into the buffer leaving the first N bytes for the application to use". Before this patch, every RX buffer kept this headroom:

- copy mode, in __xsk_rcv()
- driver zero copy, in xp_alloc()
- the new xsk_pp_rcv_copy() path, which uses addrs[i] + headroom

Here the frag descriptors are published at skb_frag_address(frag) - umem, wherever the device placed the payload. On fbnic that can be chunk offset 0. The device has then DMA-written into the first N bytes of those chunks. Any per-chunk application data kept in the headroom is overwritten.

xp_assign_dev() picks xsk_pp_bind() automatically whenever xsk_pp_supported(netdev) is true. That covers both XDP_ZEROCOPY and a bind without flags. No bind or UMEM flag lets an application accept or refuse the weaker rule. The af_xdp.rst hunk changes the documented rule for all drivers:

In a multi-buffer packet, only the first buffer is guaranteed this headroom; the others may start at offset 0 of their chunk.

At the end of the series only fbnic opts in, and fbnic had no AF_XDP RX before, so no existing deployment changes today. An application that relies on per-buffer headroom could still lose it, with no change on its side, if another driver later moves to xsk_page_pool.

Should this be gated by a flag? Or should the commit message describe it as a UAPI change rather than as a device property?

Quoted 5 lines
net/xdp/xsk_pp.c +5 -0
+		pp->pending[pp->pending_cnt++] = skb_frag_netmem(frag);
+	}
+
+	return 0;
+}

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261110102039.1002605-1-bjorn%40kernel.org
#70 lore raw

Re: [PATCH net-next v1 07/11] xsk: Deliver provider chunks without copying

Quoted 2 lines · [email protected] writes:

Should this be gated by a flag? Or should the commit message describe it as a UAPI change rather than as a device property?

Neither, it isn't a UAPI change. The headroom text predates multi-buffer, when a buffer held a whole packet: "the packet will start N bytes into the buffer". A continuation buffer doesn't start a packet, and the room in front of the packet, for headers or metadata, is still there in its first buffer. Userspace reads each buffer at the address in its descriptor anyway; XDP can already move the start with bpf_xdp_adjust_head(). The doc change only spells out a valid multi-buffer variant, and I'll say so in the commit message.

I'll also fix the commit message on the old copy path, and give net_mp_release_page_pool_bulk() its own page_pool patch.

Björn

#71 lore raw

Re: [PATCH net-next v1 07/11] xsk: Deliver provider chunks without copying

In reply to Björn Töpel
Quoted 182 lines · Björn Töpel

A provider socket still receives through the copy path, which takes FILL entries without the provider's ownership checks: a chunk that a page pool holds could be handed out twice. No driver opts in yet.

Put packets whose buffers all belong to the socket's provider on the RX ring as they are, and copy others into chunks the provider claims. Only the queue NAPI may produce to such a socket, so generic XDP and CPUMAP redirects to it are dropped.

A device may place payload at chunk offset 0, as fbnic does, so only the first buffer of a packet keeps the UMEM headroom. Such buffers may be sent back as they are, so only descriptors with XDP_TX_METADATA need room for TX metadata in front.

---
 Documentation/networking/af_xdp.rst          |   6 +-
 Documentation/networking/xsk-tx-metadata.rst |   3 +-
 include/net/page_pool/memory_provider.h      |   2 +
 net/core/page_pool.c                         |  34 +++-
 net/xdp/xsk.c                                |  82 ++++++++-
 net/xdp/xsk.h                                |   5 +
 net/xdp/xsk_pp.c                             | 165 +++++++++++++++++++
 net/xdp/xsk_queue.h                          |  18 +-
 8 files changed, 304 insertions(+), 11 deletions(-)
Documentation/networking/af_xdp.rst +4 -2
index cc3f0d16b28f..e73a0005e169 100644
@@ -428,8 +428,10 @@ area and that your largest packet size can be 2K.
 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.
+application to use. In a multi-buffer packet, only the first buffer is
+guaranteed this headroom; the others may start at offset 0 of their
+chunk. The final option is the flags field, but it will be dealt with
+in separate sections for each UMEM flag.
 
 SO_BINDTODEVICE setsockopt
 --------------------------
Documentation/networking/xsk-tx-metadata.rst +2 -1
index f240930ca1df..8bb74a569c26 100644
@@ -59,7 +59,8 @@ The flags field enables the particular offload:
 Besides the flags above, in order to trigger the offloads, the first
 packet's ``struct xdp_desc`` descriptor should set ``XDP_TX_METADATA``
 bit in the ``options`` field. Also note that in a multi-buffer packet
-only the first chunk should carry the metadata.
+only the first chunk should carry the metadata. Only a descriptor with
+``XDP_TX_METADATA`` needs ``tx_metadata_len`` bytes in front of it.
 
 Software TX Checksum
 ====================
include/net/page_pool/memory_provider.h +2 -0
index daec73c9dcee..849db08513b8 100644
@@ -49,6 +49,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_bulk(struct page_pool *pool,
+				   netmem_ref *netmems, u32 count);
 
 int netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		      const struct pp_memory_provider_params *p,
net/core/page_pool.c +33 -1
index e897e79d31f1..56c299f2280d 100644
@@ -1401,7 +1401,7 @@ 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_bulk()
  */
 void net_mp_niov_set_page_pool(struct page_pool *pool, struct net_iov *niov)
 {
@@ -1422,3 +1422,35 @@ void net_mp_niov_clear_page_pool(struct net_iov *niov)
 
 	page_pool_clear_pp_info(netmem);
 }
+
+/**
+ * net_mp_release_page_pool_bulk() - take net_iovs back from a page pool
+ * @pool: page pool that holds one reference to each net_iov
+ * @netmems: net_iovs of the memory provider of @pool
+ * @count: number of entries in @netmems
+ *
+ * A memory provider takes net_iovs out of a page pool without
+ * ->release_netmem(), for example to give them to userspace. @pool may be
+ * freed on return.
+ */
+void net_mp_release_page_pool_bulk(struct page_pool *pool,
+				   netmem_ref *netmems, u32 count)
+{
+	bool trace = trace_page_pool_state_release_enabled();
+	atomic_t *release_cnt = &pool->pages_state_release_cnt;
+	int released;
+	u32 i;
+
+	for (i = 0; i < count; i++) {
+		DEBUG_NET_WARN_ON_ONCE(netmem_get_pp(netmems[i]) != pool);
+		page_pool_clear_pp_info(netmems[i]);
+		if (!trace)
+			continue;
+
+		released = atomic_inc_return_relaxed(release_cnt);
+		trace_page_pool_state_release(pool, netmems[i], released);
+	}
+
+	if (!trace)
+		atomic_add(count, release_cnt);
+}
net/xdp/xsk.c +48 -0
index 113b0b08356d..b419c673e3f1 100644
@@ -386,6 +386,54 @@ static int __xsk_rcv(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len)
 	return -ENOMEM;
 }
 
+static int xsk_pp_rcv_copy(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len)
+{
+	u32 frame_size = __xsk_pool_get_rx_frame_size(xs->pool);
+	u32 headroom = xsk_pool_get_headroom(xs->pool);
+	void *copy_from = xsk_copy_xdp_start(xdp);
+	u32 from_len, meta_len, rem, num_desc, i;
+	u64 addrs[MAX_SKB_FRAGS + 1];
+	skb_frag_t *frag = NULL;
+	u32 to_len, copied;
+	void *to;
+
+	from_len = xdp->data_end - copy_from;
+	meta_len = xdp->data - copy_from;
+	rem = len + meta_len;
+
+	num_desc = (len - 1) / frame_size + 1;
+	if (num_desc > ARRAY_SIZE(addrs)) {
+		xs->rx_dropped++;
+		return -ENOSPC;
+	}
+	if (xskq_prod_nb_free(xs->rx, num_desc) < num_desc) {
+		xs->rx_queue_full++;
+		return -ENOBUFS;
+	}
+	if (!xsk_pp_claim_copy(xs->pool->pp, addrs, num_desc)) {
+		xs->rx_dropped++;
+		return -ENOMEM;
+	}
+
+	if (xdp_buff_has_frags(xdp))
+		frag = &xdp_get_shared_info_from_buff(xdp)->frags[0];
+
+	for (i = 0; rem && i < num_desc; i++) {
+		to = xp_raw_get_data(xs->pool, addrs[i] + headroom) - meta_len;
+		to_len = frame_size + meta_len;
+		copied = xsk_copy_xdp(to, &copy_from, to_len, &from_len, &frag,
+				      rem);
+		rem -= copied;
+
+		__xskq_prod_reserve_desc(xs->rx, addrs[i] + headroom,
+					 copied - meta_len,
+					 rem ? XDP_PKT_CONTD : 0);
+		meta_len = 0;
+	}
+
+	return 0;
+}
+
 static bool xsk_tx_writeable(struct xdp_sock *xs)
 {
 	if (xskq_cons_present_entries(xs->tx) > xs->tx->nentries / 2)
@@ -453,8 +501,14 @@ static int xsk_rcv_check(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len)
 
 static void xsk_flush(struct xdp_sock *xs)
 {

net/xdp/xsk.c static int xsk_rcv_check(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len) · line 512

Quoted 10 lines
net/xdp/xsk.c +7 -1
+	struct xsk_pp *pp = xs->pool->pp;
+
+	if (pp)
+		xsk_pp_flush(pp);
 	xskq_prod_submit(xs->rx);
-	__xskq_cons_release(xs->pool->fq);
+	/* A provider releases FILL entries under its lock. */
+	if (!pp)
+		__xskq_cons_release(xs->pool->fq);
 	sock_def_readable(&xs->sk);

optional nit:

if (pp) {
pp_flush
prod_submit
} else {
prod_submit
cons_release
}

sock_def_readable

(hard to follow these scattered if(pp) checks :-( )

net/xdp/xsk.c int xsk_generic_rcv(struct xdp_sock *xs, struct xdp_buff *xdp) · line 525

Quoted 11 lines
net/xdp/xsk.c +5 -0
 }
 
@@ -464,6 +518,11 @@ int xsk_generic_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 	int err;
 
 	err = xsk_rcv_check(xs, xdp, len);
+	/* Only the NAPI of the queue feeds a memory provider socket. */
+	if (!err && xs->pool->pp) {
+		xs->rx_dropped++;
+		err = -EOPNOTSUPP;
+	}

This is confusing? Why even call xsk_rcv_check for pp case?

Quoted 11 lines
net/xdp/xsk.c +3 -1
 	if (!err) {
 		spin_lock_bh(&xs->pool->rx_lock);
 		err = __xsk_rcv(xs, xdp, len);
@@ -488,7 +547,26 @@ static int xsk_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 		return xsk_rcv_zc(xs, xdp, len);
 	}
 
-	err = __xsk_rcv(xs, xdp, len);
+	if (!xs->pool->pp) {
+		err = __xsk_rcv(xs, xdp, len);
+	} else {

[..]

Quoted 6 lines
net/xdp/xsk.c +6 -0
+		/* A CPUMAP program runs XDP on another CPU, not in NAPI. */
+		if (unlikely(!xdp_rxq_info_is_reg(xdp->rxq))) {
+			xs->rx_dropped++;
+			return -EINVAL;
+		}
+

net/xdp/xsk.c static int xsk_rcv(struct xdp_sock *xs, struct xdp_buff *xdp) · line 568

Quoted 10 lines
net/xdp/xsk.c +10 -0
+		err = xsk_pp_rcv_zc(xs->pool->pp, xs, xdp);
+		if (err != -EXDEV)
+			return err;
+
+		/* Copy only packets of the queue, from its NAPI */
+		if (unlikely(!xsk_pp_queue_buf(xs->pool->pp, xdp))) {
+			xs->rx_dropped++;
+			return -EINVAL;
+		}
+		err = xsk_pp_rcv_copy(xs, xdp, len);

Move this into __xsk_rcv_pp ?

#72 lore raw

Re: [PATCH net-next v1 07/11] xsk: Deliver provider chunks without copying

Quoted 32 lines · Stanislav Fomichev
Quoted 9 lines · Björn Töpel
net/xdp/xsk.c +0 -0
index 113b0b08356d..b419c673e3f1 100644
@@ -453,8 +501,14 @@ static int xsk_rcv_check(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len)
 
 static void xsk_flush(struct xdp_sock *xs)
 {

net/xdp/xsk.c static int xsk_rcv_check(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len) · line 512

Quoted 10 lines
net/xdp/xsk.c +7 -1
+	struct xsk_pp *pp = xs->pool->pp;
+
+	if (pp)
+		xsk_pp_flush(pp);
 	xskq_prod_submit(xs->rx);
-	__xskq_cons_release(xs->pool->fq);
+	/* A provider releases FILL entries under its lock. */
+	if (!pp)
+		__xskq_cons_release(xs->pool->fq);
 	sock_def_readable(&xs->sk);

optional nit:

if (pp) {
pp_flush
prod_submit
} else {
prod_submit
cons_release
}

Quoted 3 lines

sock_def_readable

(hard to follow these scattered if(pp) checks :-( )

Sure, will do!

Quoted 6 lines
Quoted 6 lines
net/xdp/xsk.c +0 -0
 }
 
@@ -464,6 +518,11 @@ int xsk_generic_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 	int err;
 
Quoted 8 lines

net/xdp/xsk.c int xsk_generic_rcv(struct xdp_sock *xs, struct xdp_buff *xdp) · line 525

Quoted 6 lines
net/xdp/xsk.c +5 -0
 	err = xsk_rcv_check(xs, xdp, len);
+	/* Only the NAPI of the queue feeds a memory provider socket. */
+	if (!err && xs->pool->pp) {
+		xs->rx_dropped++;
+		err = -EOPNOTSUPP;
+	}

This is confusing? Why even call xsk_rcv_check for pp case?

Hmm! I think you're right here... this was a (is it bound) check. I might have been wrong in my reply to Maciej as well. I'll drop this.

Quoted 24 lines
Quoted 11 lines
net/xdp/xsk.c +3 -1
 	if (!err) {
 		spin_lock_bh(&xs->pool->rx_lock);
 		err = __xsk_rcv(xs, xdp, len);
@@ -488,7 +547,26 @@ static int xsk_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 		return xsk_rcv_zc(xs, xdp, len);
 	}
 
-	err = __xsk_rcv(xs, xdp, len);
+	if (!xs->pool->pp) {
+		err = __xsk_rcv(xs, xdp, len);
+	} else {

[..]

Quoted 10 lines
net/xdp/xsk.c +10 -0
+		/* A CPUMAP program runs XDP on another CPU, not in NAPI. */
+		if (unlikely(!xdp_rxq_info_is_reg(xdp->rxq))) {
+			xs->rx_dropped++;
+			return -EINVAL;
+		}
+
+		err = xsk_pp_rcv_zc(xs->pool->pp, xs, xdp);
+		if (err != -EXDEV)
+			return err;
+
Quoted 8 lines

net/xdp/xsk.c static int xsk_rcv(struct xdp_sock *xs, struct xdp_buff *xdp) · line 568

Quoted 6 lines
net/xdp/xsk.c +6 -0
+		/* Copy only packets of the queue, from its NAPI */
+		if (unlikely(!xsk_pp_queue_buf(xs->pool->pp, xdp))) {
+			xs->rx_dropped++;
+			return -EINVAL;
+		}
+		err = xsk_pp_rcv_copy(xs, xdp, len);

Move this into __xsk_rcv_pp ?

Yes.

Björn

#73 lore raw

Re: [PATCH net-next v1 07/11] xsk: Deliver provider chunks without copying

In reply to Björn Töpel
Quoted 26 lines · Björn Töpel

A provider socket still receives through the copy path, which takes FILL entries without the provider's ownership checks: a chunk that a page pool holds could be handed out twice. No driver opts in yet.

Put packets whose buffers all belong to the socket's provider on the RX ring as they are, and copy others into chunks the provider claims. Only the queue NAPI may produce to such a socket, so generic XDP and CPUMAP redirects to it are dropped.

A device may place payload at chunk offset 0, as fbnic does, so only the first buffer of a packet keeps the UMEM headroom. Such buffers may be sent back as they are, so only descriptors with XDP_TX_METADATA need room for TX metadata in front.

---
 Documentation/networking/af_xdp.rst          |   6 +-
 Documentation/networking/xsk-tx-metadata.rst |   3 +-
 include/net/page_pool/memory_provider.h      |   2 +
 net/core/page_pool.c                         |  34 +++-
 net/xdp/xsk.c                                |  82 ++++++++-
 net/xdp/xsk.h                                |   5 +
 net/xdp/xsk_pp.c                             | 165 +++++++++++++++++++
 net/xdp/xsk_queue.h                          |  18 +-
 8 files changed, 304 insertions(+), 11 deletions(-)

(...)

Quoted 9 lines
net/xdp/xsk_pp.c +1 -0
+
 static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
 			  struct netdev_rx_queue *rxq)
 {
net/xdp/xsk_queue.h +0 -0
index 1bc42c8902f4..b9464b917a88 100644

net/xdp/xsk_queue.h static inline bool xp_unused_options_set(u32 options) · line 162

Quoted 7 lines
net/xdp/xsk_queue.h +4 -0
@@ -156,17 +156,24 @@ static inline bool xp_unused_options_set(u32 options)
 	return options & ~(XDP_PKT_CONTD | XDP_TX_METADATA);
 }
 
+static inline u32 xp_desc_meta_len(struct xsk_buff_pool *pool,
+				   struct xdp_desc *desc)
+{
+	return desc->options & XDP_TX_METADATA ? pool->tx_metadata_len : 0;

How is it related to this patch? I know I trimmed, but I didn't see any references above to tx_metadata_len, only some documentation bump.

Besides, the amount of branches introduced to existing hot path is worrying. On next revision, could you provide numbers from xdpsock before and after this set run on existing zc driver?

Quoted 55 lines
net/xdp/xsk_queue.h +9 -5
+}
+
 static inline bool xp_aligned_validate_desc(struct xsk_buff_pool *pool,
 					    struct xdp_desc *desc)
 {
+	u32 meta = xp_desc_meta_len(pool, desc);
 	u64 len = desc->len;
 	u64 addr, offset;
 
 	if (!len)
 		return false;
 
-	/* Can overflow if desc->addr < pool->tx_metadata_len */
-	if (check_sub_overflow(desc->addr, pool->tx_metadata_len, &addr))
+	/* Can overflow if desc->addr < meta */
+	if (check_sub_overflow(desc->addr, meta, &addr))
 		return false;
 
 	offset = addr & (pool->chunk_size - 1);
@@ -176,7 +183,7 @@ static inline bool xp_aligned_validate_desc(struct xsk_buff_pool *pool,
 	 * (pool->chunk_size is ``u32``), @len is guaranteed
 	 * to be <= ``U32_MAX``.
 	 */
-	if (offset + len + pool->tx_metadata_len > pool->chunk_size)
+	if (offset + len + meta > pool->chunk_size)
 		return false;
 
 	if (addr >= pool->addrs_cnt)
@@ -191,6 +198,7 @@ static inline bool xp_aligned_validate_desc(struct xsk_buff_pool *pool,
 static inline bool xp_unaligned_validate_desc(struct xsk_buff_pool *pool,
 					      struct xdp_desc *desc)
 {
+	u32 meta = xp_desc_meta_len(pool, desc);
 	u64 len = desc->len;
 	u64 addr, end;
 
@@ -198,13 +206,13 @@ static inline bool xp_unaligned_validate_desc(struct xsk_buff_pool *pool,
 		return false;
 
 	/* Can't overflow: @len is guaranteed to be <= ``U32_MAX`` */
-	len += pool->tx_metadata_len;
+	len += meta;
 	if (len > pool->chunk_size)
 		return false;
 
 	/* Can overflow if desc->addr is close to 0 */
 	if (check_sub_overflow(xp_unaligned_add_offset_to_addr(desc->addr),
-			       pool->tx_metadata_len, &addr))
+			       meta, &addr))
 		return false;
 
 	if (addr >= pool->addrs_cnt)
Signature · 1 line
2.56.0
#74 lore raw

Re: [PATCH net-next v1 07/11] xsk: Deliver provider chunks without copying

Quoted 42 lines · Maciej Fijalkowski
Quoted 26 lines · Björn Töpel

A provider socket still receives through the copy path, which takes FILL entries without the provider's ownership checks: a chunk that a page pool holds could be handed out twice. No driver opts in yet.

Put packets whose buffers all belong to the socket's provider on the RX ring as they are, and copy others into chunks the provider claims. Only the queue NAPI may produce to such a socket, so generic XDP and CPUMAP redirects to it are dropped.

A device may place payload at chunk offset 0, as fbnic does, so only the first buffer of a packet keeps the UMEM headroom. Such buffers may be sent back as they are, so only descriptors with XDP_TX_METADATA need room for TX metadata in front.

---
 Documentation/networking/af_xdp.rst          |   6 +-
 Documentation/networking/xsk-tx-metadata.rst |   3 +-
 include/net/page_pool/memory_provider.h      |   2 +
 net/core/page_pool.c                         |  34 +++-
 net/xdp/xsk.c                                |  82 ++++++++-
 net/xdp/xsk.h                                |   5 +
 net/xdp/xsk_pp.c                             | 165 +++++++++++++++++++
 net/xdp/xsk_queue.h                          |  18 +-
 8 files changed, 304 insertions(+), 11 deletions(-)

(...)

Quoted 12 lines
net/xdp/xsk_pp.c +1 -0
+
 static int xsk_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
 			  struct netdev_rx_queue *rxq)
 {
net/xdp/xsk_queue.h +0 -0
index 1bc42c8902f4..b9464b917a88 100644
@@ -156,17 +156,24 @@ static inline bool xp_unused_options_set(u32 options)
 	return options & ~(XDP_PKT_CONTD | XDP_TX_METADATA);
 }
 
Quoted 7 lines

net/xdp/xsk_queue.h static inline bool xp_unused_options_set(u32 options) · line 162

Quoted 4 lines
net/xdp/xsk_queue.h +4 -0
+static inline u32 xp_desc_meta_len(struct xsk_buff_pool *pool,
+				   struct xdp_desc *desc)
+{
+	return desc->options & XDP_TX_METADATA ? pool->tx_metadata_len : 0;

How is it related to this patch? I know I trimmed, but I didn't see any references above to tx_metadata_len, only some documentation bump.

Provider frags start at chunk offset 0, and an application may send them back as they are. TX validation wants tx_metadata_len in front of every descriptor once the UMEM has it, so such a descriptor fails, though only XDP_TX_METADATA descriptors use that room. Driver ZC never puts RX data below offset 256, so it never came up. It stands on its own; I'll make it a separate patch.

Quoted 3 lines

Besides, the amount of branches introduced to existing hot path is worrying. On next revision, could you provide numbers from xdpsock before and after this set run on existing zc driver?

(FWIW, I've left a all my performance patches out, to keep the size of set down.)

Will do, but the only one I got is mlx5. Would be awesome if you or Magnus could take it for a spin on Intel NICs.

Single-buffer RX on driver ZC gets no new per-packet branch: xsk_rcv() leaves through xsk_rcv_zc() first. The rest is one test per flush, one XDP_TX_METADATA test per TX descriptor, and a flag test in the multi-buffer and XDP_PASS/redirect helpers. v2 also moves pool->pp next to fq, which the flush reads anyway, and drops the frag walk in xdp_buff_needs_copy(), as agreed with Stan.

Anything specific, or just in general?

Björn

#75 lore raw

PATCH 8/11 eth: fbnic: Support XDP redirect

In reply to Björn Töpel

fbnic treats XDP_REDIRECT as an invalid action and drops the packet, so AF_XDP, devmap and cpumap do not work. A failed redirect counts as received, as XDP_DROP does, and as dropped.

---
 .../net/ethernet/meta/fbnic/fbnic_netdev.c    |  4 +++-
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c  | 19 +++++++++++++++++++
 2 files changed, 22 insertions(+), 1 deletion(-)
drivers/net/ethernet/meta/fbnic/fbnic_netdev.c +3 -1
index 8a6703afca38..ae2585508690 100644
@@ -822,7 +822,9 @@ struct net_device *fbnic_netdev_alloc(struct fbnic_dev *fbd)
 	netdev->hw_enc_features |= netdev->features;
 	netdev->features |= NETIF_F_NTUPLE;
 
-	netdev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_RX_SG;
+	netdev->xdp_features = NETDEV_XDP_ACT_BASIC |
+			       NETDEV_XDP_ACT_REDIRECT |
+			       NETDEV_XDP_ACT_RX_SG;
 
 	netdev->min_mtu = IPV6_MIN_MTU;
 	netdev->max_mtu = FBNIC_MAX_JUMBO_FRAME_SIZE - ETH_HLEN;
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +19 -0
index 0bcee152d47c..51d573c9c5b8 100644
@@ -22,6 +22,8 @@ enum {
 	FBNIC_XDP_PASS = 0,
 	FBNIC_XDP_CONSUME,
 	FBNIC_XDP_TX,
+	FBNIC_XDP_REDIRECT,
+	FBNIC_XDP_REDIRECT_ERR,
 	FBNIC_XDP_LEN_ERR,
 };
 
@@ -1211,6 +1213,10 @@ static struct sk_buff *fbnic_run_xdp(struct fbnic_napi_vector *nv,
 		return fbnic_build_skb(nv, pkt);
 	case XDP_TX:
 		return ERR_PTR(fbnic_pkt_tx(nv, pkt));
+	case XDP_REDIRECT:
+		if (xdp_do_redirect(nv->napi.dev, &pkt->buff, xdp_prog))
+			return ERR_PTR(-FBNIC_XDP_REDIRECT_ERR);
+		return ERR_PTR(-FBNIC_XDP_REDIRECT);
 	default:
 		bpf_warn_invalid_xdp_action(nv->napi.dev, xdp_prog, act);
 		fallthrough;
@@ -1280,6 +1286,7 @@ static int fbnic_clean_rcq(struct fbnic_napi_vector *nv,
 	struct fbnic_ring *rcq = &qt->cmpl;
 	struct fbnic_pkt_buff *pkt;
 	__le64 *raw_rcd, done;
+	bool redirect = false;
 	u32 head = rcq->head;
 
 	done = (head & (rcq->size_mask + 1)) ? cpu_to_le64(FBNIC_RCD_DONE) : 0;
@@ -1336,6 +1343,16 @@ static int fbnic_clean_rcq(struct fbnic_napi_vector *nv,
 				pkt_tail = nv->qt[0].sub1.tail;
 			} else if (PTR_ERR(skb) == -FBNIC_XDP_CONSUME) {
 				fbnic_put_pkt_buff(qt, pkt, 1);
+			} else if (skb == ERR_PTR(-FBNIC_XDP_REDIRECT)) {
+				redirect = true;
+			} else if (skb == ERR_PTR(-FBNIC_XDP_REDIRECT_ERR)) {
+				/* A broadcast may queue frames, then fail. XDP
+				 * consumed the packet, so it also counts as
+				 * received.
+				 */
+				redirect = true;
+				dropped++;
+				fbnic_put_pkt_buff(qt, pkt, 1);
 			} else {
 				if (!skb)
 					alloc_failed++;
@@ -1377,6 +1394,8 @@ static int fbnic_clean_rcq(struct fbnic_napi_vector *nv,
 
 	if (pkt_tail >= 0)
 		fbnic_pkt_commit_tail(nv, pkt_tail);
+	if (redirect)
+		xdp_do_flush();
 
 	/* Unmap and free processed buffers */
 	if (head0 >= 0)
Signature · 1 line
2.56.0
#76 lore raw

Re: [PATCH net-next v1 08/11] eth: fbnic: Support XDP redirect

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [High] eth: fbnic: memory leak in…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [High] eth: fbnic: memory leak in fbnic_pkt_prepare() [1] --

commit 8a7293bd4896ffd0472ecd918ba40c84ba4499d4
Author: Björn Töpel <[email protected]>

eth: fbnic: Support XDP redirect

This commit adds support for the XDP_REDIRECT action in fbnic, including flushing redirected packets at the end of the RX completion poll and advertising NETDEV_XDP_ACT_REDIRECT.

Quoted 4 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +0 -0
index 0bcee152d47c3..51d573c9c5b83 100644

[ ... ]

Quoted 4 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +0 -0
@@ -1336,6 +1343,16 @@ static int fbnic_clean_rcq(struct fbnic_napi_vector *nv,
 				pkt_tail = nv->qt[0].sub1.tail;
 			} else if (PTR_ERR(skb) == -FBNIC_XDP_CONSUME) {
 				fbnic_put_pkt_buff(qt, pkt, 1);

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c static int fbnic_clean_rcq(struct fbnic_napi_vector *nv, · line 1355

Quoted 10 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +10 -0
+			} else if (skb == ERR_PTR(-FBNIC_XDP_REDIRECT)) {
+				redirect = true;
+			} else if (skb == ERR_PTR(-FBNIC_XDP_REDIRECT_ERR)) {
+				/* A broadcast may queue frames, then fail. XDP
+				 * consumed the packet, so it also counts as
+				 * received.
+				 */
+				redirect = true;
+				dropped++;
+				fbnic_put_pkt_buff(qt, pkt, 1);

[Severity: High]
This problem wasn't introduced by this patch, but can fbnic_pkt_prepare() leak the existing packet buffer [1]?

If fbnic_clean_rcq() sees consecutive FBNIC_RCD_TYPE_HDR_AL descriptors without an intervening FBNIC_RCD_TYPE_META descriptor, it calls fbnic_pkt_prepare() again on the same pkt:

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c:fbnic_pkt_prepare() {
	...
	/* data_hard_start should always be NULL when this is called */
	WARN_ON_ONCE(pkt->buff.data_hard_start);
	...
	xdp_init_buff(&pkt->buff, frame_sz, &qt->xdp_rxq);
	...
}

Reinitializing pkt->buff without first calling fbnic_put_pkt_buff() drops the reference to the previously allocated head page and any attached fragments, allowing a malfunctioning or compromised device to leak page_pool buffers.

[1] https://sashiko.dev/#/bug/linux-155b4068-9e56-4cd0-bea5-9b3a787a5d5d

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#77 lore raw

PATCH 9/11 eth: fbnic: Use netmem for RX headers and XDP_TX

In reply to Björn Töpel

fbnic reaches header and XDP_TX buffers through struct page, which a provider net_iov does not have. Use netmem for both, and set up the xdp_buff with xdp_init_buff_netmem(), so XDP_PASS copies heads that must not leave the RX poll.

---
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c | 47 +++++++++-----------
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h |  3 ++
 2 files changed, 25 insertions(+), 25 deletions(-)
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +22 -25
index 51d573c9c5b8..bfaa284e497e 100644
@@ -665,14 +665,14 @@ static void fbnic_clean_twq1(struct fbnic_napi_vector *nv, bool pp_allow_direct,
 	unsigned int head = ring->head;
 
 	while (hw_head != head) {
-		struct page *page;
+		netmem_ref netmem;
 		u64 twd;
 
 		if (unlikely(!(ring->desc[head] & FBNIC_TWD_TYPE(AL))))
 			goto next_desc;
 
 		twd = le64_to_cpu(ring->desc[head]);
-		page = ring->tx_buf[head];
+		netmem = ring->tx_netmem[head];
 
 		/* TYPE_AL is 2, TYPE_LAST_AL is 3. So this trick gives
 		 * us one increment per packet, with no branches.
@@ -681,8 +681,8 @@ static void fbnic_clean_twq1(struct fbnic_napi_vector *nv, bool pp_allow_direct,
 				 FBNIC_TWD_TYPE_AL;
 		total_bytes += FIELD_GET(FBNIC_TWD_LEN_MASK, twd);
 
-		page_pool_put_page(pp_page_to_nmdesc(page)->pp, page, -1,
-				   pp_allow_direct);
+		page_pool_put_netmem(netmem_get_pp(netmem), netmem, -1,
+				     pp_allow_direct);
 next_desc:
 		head++;
 		head &= ring->size_mask;
@@ -766,15 +766,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
@@ -1003,12 +1002,13 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 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);
+	pkt->head = netmem;
 
 	/* Short-cut the end calculation if we know page is fully consumed */
 	hdr_pg_end = FIELD_GET(FBNIC_RCD_AL_PAGE_FIN, rcd) ?
@@ -1017,16 +1017,16 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 
 	headroom = hdr_pg_off - hdr_pg_start + FBNIC_RX_PAD;
 	frame_sz = hdr_pg_end - hdr_pg_start;
-	xdp_init_buff(&pkt->buff, frame_sz, &qt->xdp_rxq);
+	xdp_init_buff_netmem(&pkt->buff, frame_sz, &qt->xdp_rxq, netmem,
+			     &pkt->ext);
 	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),
-				      hdr_pg_start, frame_sz,
-				      DMA_BIDIRECTIONAL);
+	page_pool_dma_sync_netmem_for_cpu(qt->sub0.page_pool, netmem,
+					  hdr_pg_start, frame_sz);
 
 	/* Build frame around buffer */
-	hdr_start = page_address(page) + hdr_pg_start;
+	hdr_start = netmem_address(netmem) + hdr_pg_start;
 	net_prefetch(hdr_start + headroom);
 	xdp_prepare_buff(&pkt->buff, hdr_start, headroom,
 			 len - FBNIC_RX_PAD, true);
@@ -1073,8 +1073,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;
 
@@ -1093,8 +1091,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,
@@ -1121,7 +1118,7 @@ static long fbnic_pkt_tx(struct fbnic_napi_vector *nv,
 	unsigned int tail = ring->tail;
 	struct skb_shared_info *shinfo;
 	skb_frag_t *frag = NULL;
-	struct page *page;
+	netmem_ref netmem;
 	dma_addr_t dma;
 	__le64 *twd;
 
@@ -1139,9 +1136,9 @@ static long fbnic_pkt_tx(struct fbnic_napi_vector *nv,
 		return -FBNIC_XDP_CONSUME;
 	}
 
-	page = virt_to_page(pkt->buff.data_hard_start);
-	offset = offset_in_page(pkt->buff.data);
-	dma = page_pool_get_dma_addr(page);
+	netmem = pkt->head;
+	offset = (u8 *)pkt->buff.data - (u8 *)netmem_address(netmem);
+	dma = page_pool_get_dma_addr_netmem(netmem);
 
 	size = pkt->buff.data_end - pkt->buff.data;
 
@@ -1150,7 +1147,7 @@ static long fbnic_pkt_tx(struct fbnic_napi_vector *nv,
 						 DMA_BIDIRECTIONAL);
 		dma += offset;
 
-		ring->tx_buf[tail] = page;
+		ring->tx_netmem[tail] = netmem;
 
 		twd = &ring->desc[tail];
 		*twd = cpu_to_le64(FIELD_PREP(FBNIC_TWD_ADDR_MASK, dma) |
@@ -1165,8 +1162,8 @@ static long fbnic_pkt_tx(struct fbnic_napi_vector *nv,
 			break;
 
 		offset = skb_frag_off(frag);
-		page = skb_frag_page(frag);
-		dma = page_pool_get_dma_addr(page);
+		netmem = skb_frag_netmem(frag);
+		dma = page_pool_get_dma_addr_netmem(netmem);
 
 		size = skb_frag_size(frag);
 		data_len -= size;
drivers/net/ethernet/meta/fbnic/fbnic_txrx.h +3 -0
index 6ee3cce3d942..d036c8399364 100644
@@ -82,7 +82,9 @@ struct fbnic_net;
 struct fbnic_pkt_buff {
 	struct xdp_buff buff;
 	ktime_t hwtstamp;
+	netmem_ref head;
 	bool add_frag_failed;
+	struct xdp_buff_ext ext;
 };
 
 struct fbnic_queue_stats {
@@ -123,6 +125,7 @@ struct fbnic_ring {
 	union {
 		struct fbnic_pkt_buff *pkt;	/* RCQ */
 		struct fbnic_rx_buf *rx_buf;	/* BDQ */
+		netmem_ref *tx_netmem;		/* TWQ1 */
 		void **tx_buf;			/* TWQ */
 		void *buffer;			/* Generic pointer */
 	};
Signature · 1 line
2.56.0
Acked-by on v1 9/11
#78 lore raw

Re: [PATCH net-next v1 09/11] eth: fbnic: Use netmem for RX headers and XDP_TX

Quoted 7 lines · Björn Töpel

fbnic reaches header and XDP_TX buffers through struct page, which a provider net_iov does not have. Use netmem for both, and set up the xdp_buff with xdp_init_buff_netmem(), so XDP_PASS copies heads that must not leave the RX poll.

Signature · 2 lines
Thanks,
Mina
#79 lore raw

PATCH 10/11 eth: fbnic: Support RX buffers it cannot split

In reply to Björn Töpel

fbnic packs several headers, and several payloads, into one page. A provider without MP_CAP_FRAG needs one descriptor per buffer. Give such a buffer a single reference, program the queue so each header and payload takes a buffer of its own, and drop packets that break this.

Header split is now set per queue, so link up changes only the drop mode.

---
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c | 119 ++++++++++++++++---
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h |   2 +
 2 files changed, 102 insertions(+), 19 deletions(-)
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +100 -19
index bfaa284e497e..d96c957d6fba 100644
@@ -761,8 +761,14 @@ static void fbnic_page_pool_init(struct fbnic_ring *ring, unsigned int idx,
 {
 	struct fbnic_rx_buf *rx_buf = &ring->rx_buf[idx];
 
-	page_pool_fragment_netmem(netmem, FBNIC_PAGECNT_BIAS_MAX);
-	rx_buf->pagecnt_bias = FBNIC_PAGECNT_BIAS_MAX;
+	/* A whole buffer has one reference. The packet takes it, so the buffer
+	 * may be reused before its BDQ entry is cleaned.
+	 */
+	rx_buf->pagecnt_bias = 1;
+	if (page_pool_supports_frag(ring->page_pool)) {
+		page_pool_fragment_netmem(netmem, FBNIC_PAGECNT_BIAS_MAX);
+		rx_buf->pagecnt_bias = FBNIC_PAGECNT_BIAS_MAX;
+	}
 	rx_buf->netmem = netmem;
 }
 
@@ -792,7 +798,8 @@ static void fbnic_page_pool_drain(struct fbnic_ring *ring, unsigned int idx,
 	struct fbnic_rx_buf *rx_buf = &ring->rx_buf[idx];
 	netmem_ref netmem = rx_buf->netmem;
 
-	if (!page_pool_unref_netmem(netmem, rx_buf->pagecnt_bias))
+	if (rx_buf->pagecnt_bias &&
+	    !page_pool_unref_netmem(netmem, rx_buf->pagecnt_bias))
 		page_pool_put_unrefed_netmem(ring->page_pool, netmem, -1,
 					     !!budget);
 
@@ -993,6 +1000,19 @@ static unsigned int fbnic_hdr_pg_end(unsigned int pg_off, unsigned int len)
 	return ALIGN(pg_off, 128) - FBNIC_RX_HROOM;
 }
 
+/* A buffer that cannot be split has one reference and takes one descriptor */
+static bool fbnic_bd_one_desc(struct fbnic_napi_vector *nv,
+			      const struct fbnic_ring *bdq, unsigned int idx,
+			      bool ok)
+{
+	if (likely(page_pool_supports_frag(bdq->page_pool) ||
+		   (bdq->rx_buf[idx].pagecnt_bias == 1 && ok)))
+		return true;
+
+	netdev_err_once(nv->napi.dev, "Bad descriptor for a whole RX buffer\n");
+	return false;
+}
+
 static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 			      struct fbnic_pkt_buff *pkt,
 			      struct fbnic_q_triad *qt)
@@ -1007,6 +1027,17 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 	/* data_hard_start should always be NULL when this is called */
 	WARN_ON_ONCE(pkt->buff.data_hard_start);
 
+	/* MAX_HDR leaves no room for a second header in a whole buffer, so
+	 * the device closes it, with PAGE_FIN, after the first.
+	 */
+	pkt->add_frag_failed = false;
+	if (unlikely(!fbnic_bd_one_desc(nv, &qt->sub0, hdr_pg_idx,
+					FIELD_GET(FBNIC_RCD_AL_PAGE_FIN,
+						  rcd)))) {
+		pkt->add_frag_failed = true;
+		return;
+	}
+
 	netmem = fbnic_page_pool_get_head(qt, hdr_pg_idx);
 	pkt->head = netmem;
 
@@ -1032,7 +1063,6 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 			 len - FBNIC_RX_PAD, true);
 
 	pkt->hwtstamp = 0;
-	pkt->add_frag_failed = false;
 }
 
 static void fbnic_add_rx_frag(struct fbnic_napi_vector *nv, u64 rcd,
@@ -1046,8 +1076,20 @@ static void fbnic_add_rx_frag(struct fbnic_napi_vector *nv, u64 rcd,
 	netmem_ref netmem;
 	bool added;
 
+	if (unlikely(!fbnic_bd_one_desc(nv, &qt->sub1, pg_idx, !pg_off))) {
+		pkt->add_frag_failed = true;
+		return;
+	}
+
 	netmem = fbnic_page_pool_get_data(qt, pg_idx);
 
+	/* Without a header buffer, the packet is dropped. */
+	if (unlikely(!pkt->buff.data_hard_start)) {
+		page_pool_put_full_netmem(qt->sub1.page_pool, netmem, true);
+		pkt->add_frag_failed = true;
+		return;
+	}
+
 	truesize = FIELD_GET(FBNIC_RCD_AL_PAGE_FIN, rcd) ?
 		   FBNIC_BD_PAGE_SIZE - pg_off :
 		   ALIGN(len, FBNIC_RX_PAYLD_ALIGN);
@@ -1608,6 +1650,13 @@ void fbnic_free_napi_vectors(struct fbnic_net *fbn)
 			fbnic_free_napi_vector(fbn, fbn->napi[i]);
 }
 
+/* No second header fits behind the first in a whole buffer */
+static u32 fbnic_whole_hdr_max(u32 hroom)
+{
+	return FBNIC_BD_PAGE_SIZE - ALIGN(hroom, FBNIC_RX_HDR_ALIGN) -
+	       FBNIC_RX_TROOM - FBNIC_RX_PAD;
+}
+
 static int
 fbnic_alloc_qt_page_pools(struct fbnic_net *fbn, struct fbnic_q_triad *qt,
 			  unsigned int rxq_idx, u32 rx_page_size)
@@ -1644,6 +1693,9 @@ fbnic_alloc_qt_page_pools(struct fbnic_net *fbn, struct fbnic_q_triad *qt,
 		return PTR_ERR(pp);
 
 	qt->sub0.page_pool = pp;
+	qt->hdr_max = 0;
+	if (!page_pool_supports_frag(pp))
+		qt->hdr_max = fbnic_whole_hdr_max(FBNIC_RX_HROOM);
 	if (netif_rxq_has_unreadable_mp(fbn->netdev, rxq_idx)) {
 		pp_params.order = get_order(rx_page_size);
 		pp_params.max_len = rx_page_size;
@@ -2672,6 +2724,14 @@ static void fbnic_enable_bdq(struct fbnic_ring *hpq, struct fbnic_ring *ppq)
 	fbnic_ring_wr32(hpq, FBNIC_QUEUE_BDQ_CTL, bdq_ctl);
 }
 
+static u32 fbnic_drop_mode(struct fbnic_net *fbn, bool tx_pause)
+{
+	if (!tx_pause && fbn->num_rx_queues > 1)
+		return FBNIC_QUEUE_RDE_CTL0_DROP_IMMEDIATE;
+
+	return FBNIC_QUEUE_RDE_CTL0_DROP_NEVER;
+}
+
 static void fbnic_config_drop_mode_rcq(struct fbnic_napi_vector *nv,
 				       struct fbnic_ring *rcq, bool tx_pause,
 				       bool hdr_split)
@@ -2679,10 +2739,7 @@ static void fbnic_config_drop_mode_rcq(struct fbnic_napi_vector *nv,
 	struct fbnic_net *fbn = netdev_priv(nv->napi.dev);
 	u32 drop_mode, rcq_ctl;
 
-	if (!tx_pause && fbn->num_rx_queues > 1)
-		drop_mode = FBNIC_QUEUE_RDE_CTL0_DROP_IMMEDIATE;
-	else
-		drop_mode = FBNIC_QUEUE_RDE_CTL0_DROP_NEVER;
+	drop_mode = fbnic_drop_mode(fbn, tx_pause);
 
 	/* Specify packet layout */
 	rcq_ctl = FIELD_PREP(FBNIC_QUEUE_RDE_CTL0_DROP_MODE_MASK, drop_mode) |
@@ -2693,20 +2750,32 @@ static void fbnic_config_drop_mode_rcq(struct fbnic_napi_vector *nv,
 	fbnic_ring_wr32(rcq, FBNIC_QUEUE_RDE_CTL0, rcq_ctl);
 }
 
+static u32 fbnic_rcq_hds_thresh(const struct fbnic_net *fbn,
+				const struct fbnic_ring *rcq)
+{
+	const struct fbnic_q_triad *qt;
+
+	qt = container_of_const(rcq, struct fbnic_q_triad, cmpl);
+	return qt->hdr_max ? : fbn->hds_thresh;
+}
+
+/* Only the drop mode: a queue start may write the rest of the register */
 void fbnic_config_drop_mode(struct fbnic_net *fbn, bool txp)
 {
-	bool hds;
+	struct fbnic_ring *rcq;
+	u32 drop_mode, rcq_ctl;
 	int i, t;
 
-	hds = fbn->hds_thresh < FBNIC_HDR_BYTES_MIN;
-
+	drop_mode = fbnic_drop_mode(fbn, txp);
 	for (i = 0; i < fbn->num_napi; i++) {
 		struct fbnic_napi_vector *nv = fbn->napi[i];
 
 		for (t = 0; t < nv->rxt_count; t++) {
-			struct fbnic_q_triad *qt = &nv->qt[nv->txt_count + t];
-
-			fbnic_config_drop_mode_rcq(nv, &qt->cmpl, txp, hds);
+			rcq = &nv->qt[nv->txt_count + t].cmpl;
+			rcq_ctl = fbnic_ring_rd32(rcq, FBNIC_QUEUE_RDE_CTL0);
+			FIELD_MODIFY(FBNIC_QUEUE_RDE_CTL0_DROP_MODE_MASK,
+				     &rcq_ctl, drop_mode);
+			fbnic_ring_wr32(rcq, FBNIC_QUEUE_RDE_CTL0, rcq_ctl);
 		}
 	}
 }
@@ -2771,26 +2840,38 @@ void fbnic_config_rx_frames(struct fbnic_napi_vector *nv)
 static void fbnic_enable_rcq(struct fbnic_napi_vector *nv,
 			     struct fbnic_ring *rcq)
 {
+	struct fbnic_q_triad *qt = container_of_const(rcq, struct fbnic_q_triad,
+						     cmpl);
 	struct fbnic_net *fbn = netdev_priv(nv->napi.dev);
+	u32 payld_pg_cl = FBNIC_RX_PAYLD_PG_CL;
+	u32 payld_off = FBNIC_RX_PAYLD_OFFSET;
 	u32 log_size = fls(rcq->size_mask);
 	u32 rcq_ctl = 0;
 	bool hdr_split;
 	u32 hds_thresh;
 
+	/* At 4 KiB, PAYLD_OFF puts each payload in a fresh buffer, and
+	 * PAYLD_PG_CL closes it after the payload.
+	 */
+	if (!page_pool_supports_frag(qt->sub1.page_pool)) {
+		payld_off = ilog2(FBNIC_BD_PAGE_SIZE / FBNIC_RX_PAYLD_ALIGN);
+		payld_pg_cl = payld_off;
+	}
+
 	/* Force lower bound on MAX_HEADER_BYTES. Below this, all frames should
 	 * be split at L4. It would also result in the frames being split at
 	 * L2/L3 depending on the frame size.
 	 */
-	hdr_split = fbn->hds_thresh < FBNIC_HDR_BYTES_MIN;
+	hds_thresh = fbnic_rcq_hds_thresh(fbn, rcq);
+	hdr_split = hds_thresh < FBNIC_HDR_BYTES_MIN;
 	fbnic_config_drop_mode_rcq(nv, rcq, fbn->tx_pause, hdr_split);
 
-	hds_thresh = max(fbn->hds_thresh, FBNIC_HDR_BYTES_MIN);
+	hds_thresh = max(hds_thresh, FBNIC_HDR_BYTES_MIN);
 	rcq_ctl |= FIELD_PREP(FBNIC_QUEUE_RDE_CTL1_PADLEN_MASK, FBNIC_RX_PAD) |
 		   FIELD_PREP(FBNIC_QUEUE_RDE_CTL1_MAX_HDR_MASK, hds_thresh) |
-		   FIELD_PREP(FBNIC_QUEUE_RDE_CTL1_PAYLD_OFF_MASK,
-			      FBNIC_RX_PAYLD_OFFSET) |
+		   FIELD_PREP(FBNIC_QUEUE_RDE_CTL1_PAYLD_OFF_MASK, payld_off) |
 		   FIELD_PREP(FBNIC_QUEUE_RDE_CTL1_PAYLD_PG_CL_MASK,
-			      FBNIC_RX_PAYLD_PG_CL);
+			      payld_pg_cl);
 	fbnic_ring_wr32(rcq, FBNIC_QUEUE_RDE_CTL1, rcq_ctl);
 
 	/* Reset head/tail */
drivers/net/ethernet/meta/fbnic/fbnic_txrx.h +2 -0
index d036c8399364..3077d9bbd587 100644
@@ -65,6 +65,7 @@ struct fbnic_net;
 #define FBNIC_RX_HROOM \
 	(ALIGN(FBNIC_RX_TROOM + FBNIC_RX_HROOM_PAD, 128) - FBNIC_RX_TROOM)
 #define FBNIC_RX_PAD			0
+#define FBNIC_RX_HDR_ALIGN		128
 #define FBNIC_RX_PAYLD_ALIGN		128
 #define FBNIC_RX_PAYLD_OFFSET		0
 #define FBNIC_RX_PAYLD_PG_CL		0
@@ -165,6 +166,7 @@ struct fbnic_ring {
 struct fbnic_q_triad {
 	struct fbnic_ring sub0, sub1, cmpl;
 	struct xdp_rxq_info xdp_rxq;
+	u16 hdr_max;	/* Header bytes for whole header buffers, or 0 */
 };
 
 struct fbnic_napi_vector {
Signature · 1 line
2.56.0
#80 lore raw

Re: [PATCH net-next v1 10/11] eth: fbnic: Support RX buffers it cannot split

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] eth: fbnic: incomplete split-buffer checks in fbnic_bd_one_desc() callers - [Medium] eth: fbnic…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] eth: fbnic: incomplete split-buffer checks in fbnic_bd_one_desc() callers
- [Medium] eth: fbnic: race on FBNIC_QUEUE_RDE_CTL0 in fbnic_config_drop_mode()
--

commit 054b7a97f2c49f63f4a411460a28df28be50d728
Author: Björn Töpel <[email protected]>

eth: fbnic: Support RX buffers it cannot split

This commit adds support for RX memory providers without MP_CAP_FRAG by assigning a single reference per buffer, programming per-queue header and payload thresholds so each descriptor uses a whole buffer, and updating link-up drop mode configuration to preserve per-queue header split settings.

Quoted 28 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +11 -1
index bfaa284e497eb..d96c957d6fbad 100644
 
+	/* MAX_HDR leaves no room for a second header in a whole buffer, so
+	 * the device closes it, with PAGE_FIN, after the first.
+	 */
+	pkt->add_frag_failed = false;
+	if (unlikely(!fbnic_bd_one_desc(nv, &qt->sub0, hdr_pg_idx,
+					FIELD_GET(FBNIC_RCD_AL_PAGE_FIN,
+						  rcd)))) {
+		pkt->add_frag_failed = true;
+		return;
+	}
+
 	netmem = fbnic_page_pool_get_head(qt, hdr_pg_idx);
 	pkt->head = netmem;
@@ -1032,7 +1063,6 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 			 len - FBNIC_RX_PAD, true);
 
 	pkt->hwtstamp = 0;
-	pkt->add_frag_failed = false;
 }
 
 static void fbnic_add_rx_frag(struct fbnic_napi_vector *nv, u64 rcd,

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c static void fbnic_add_rx_frag(struct fbnic_napi_vector *nv, u64 rcd, · line 1082

Quoted 7 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +4 -0
@@ -1046,8 +1076,20 @@ static void fbnic_add_rx_frag(struct fbnic_napi_vector *nv, u64 rcd,
 	netmem_ref netmem;
 	bool added;
 
+	if (unlikely(!fbnic_bd_one_desc(nv, &qt->sub1, pg_idx, !pg_off))) {
+		pkt->add_frag_failed = true;
+		return;
+	}

[Severity: Medium]
Can a split RX completion descriptor still pass fbnic_bd_one_desc() on both the header and payload rings?

In fbnic_add_rx_frag(), fbnic_bd_one_desc() checks !pg_off but does not check FIELD_GET(FBNIC_RCD_AL_PAGE_FIN, rcd) (or the subpage offset from fbnic_rcd_bd_page_offset()). If the device splits a whole payload buffer across multiple descriptors, the first descriptor has pg_off == 0 and PAGE_FIN == 0, so it passes fbnic_bd_one_desc() and consumes the buffer's single netmem reference while the hardware still holds the buffer open for subsequent descriptors.

Conversely, in fbnic_pkt_prepare(), fbnic_bd_one_desc() checks only PAGE_FIN. When the first descriptor of a split header buffer has PAGE_FIN == 0, fbnic_pkt_prepare() returns before fbnic_page_pool_get_head() decrements pagecnt_bias. Because pagecnt_bias stays 1 and the starting offset is not checked, the trailing descriptor for that buffer (with PAGE_FIN == 1 at a non-zero offset) passes fbnic_bd_one_desc().

[ ... ]

Quoted 56 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +22 -8
@@ -2672,6 +2724,14 @@ static void fbnic_enable_bdq(struct fbnic_ring *hpq, struct fbnic_ring *ppq)
 	fbnic_ring_wr32(hpq, FBNIC_QUEUE_BDQ_CTL, bdq_ctl);
 }
 
+static u32 fbnic_drop_mode(struct fbnic_net *fbn, bool tx_pause)
+{
+	if (!tx_pause && fbn->num_rx_queues > 1)
+		return FBNIC_QUEUE_RDE_CTL0_DROP_IMMEDIATE;
+
+	return FBNIC_QUEUE_RDE_CTL0_DROP_NEVER;
+}
+
 static void fbnic_config_drop_mode_rcq(struct fbnic_napi_vector *nv,
 				       struct fbnic_ring *rcq, bool tx_pause,
 				       bool hdr_split)
@@ -2679,10 +2739,7 @@ static void fbnic_config_drop_mode_rcq(struct fbnic_napi_vector *nv,
 	struct fbnic_net *fbn = netdev_priv(nv->napi.dev);
 	u32 drop_mode, rcq_ctl;
 
-	if (!tx_pause && fbn->num_rx_queues > 1)
-		drop_mode = FBNIC_QUEUE_RDE_CTL0_DROP_IMMEDIATE;
-	else
-		drop_mode = FBNIC_QUEUE_RDE_CTL0_DROP_NEVER;
+	drop_mode = fbnic_drop_mode(fbn, tx_pause);
 
 	/* Specify packet layout */
 	rcq_ctl = FIELD_PREP(FBNIC_QUEUE_RDE_CTL0_DROP_MODE_MASK, drop_mode) |
@@ -2693,20 +2750,32 @@ static void fbnic_config_drop_mode_rcq(struct fbnic_napi_vector *nv,
 	fbnic_ring_wr32(rcq, FBNIC_QUEUE_RDE_CTL0, rcq_ctl);
 }
 
+static u32 fbnic_rcq_hds_thresh(const struct fbnic_net *fbn,
+				const struct fbnic_ring *rcq)
+{
+	const struct fbnic_q_triad *qt;
+
+	qt = container_of_const(rcq, struct fbnic_q_triad, cmpl);
+	return qt->hdr_max ? : fbn->hds_thresh;
+}
+
+/* Only the drop mode: a queue start may write the rest of the register */
 void fbnic_config_drop_mode(struct fbnic_net *fbn, bool txp)
 {
-	bool hds;
+	struct fbnic_ring *rcq;
+	u32 drop_mode, rcq_ctl;
 	int i, t;
 
-	hds = fbn->hds_thresh < FBNIC_HDR_BYTES_MIN;
-
+	drop_mode = fbnic_drop_mode(fbn, txp);
 	for (i = 0; i < fbn->num_napi; i++) {
 		struct fbnic_napi_vector *nv = fbn->napi[i];
 
 		for (t = 0; t < nv->rxt_count; t++) {
-			struct fbnic_q_triad *qt = &nv->qt[nv->txt_count + t];

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c static void fbnic_config_drop_mode_rcq(struct fbnic_napi_vector *nv, · line 2781

Quoted 10 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +5 -2
-
-			fbnic_config_drop_mode_rcq(nv, &qt->cmpl, txp, hds);
+			rcq = &nv->qt[nv->txt_count + t].cmpl;
+			rcq_ctl = fbnic_ring_rd32(rcq, FBNIC_QUEUE_RDE_CTL0);
+			FIELD_MODIFY(FBNIC_QUEUE_RDE_CTL0_DROP_MODE_MASK,
+				     &rcq_ctl, drop_mode);
+			fbnic_ring_wr32(rcq, FBNIC_QUEUE_RDE_CTL0, rcq_ctl);
 		}
 	}
 }

[Severity: Medium]
Can the read-modify-write of FBNIC_QUEUE_RDE_CTL0 in fbnic_config_drop_mode() race with fbnic_enable_rcq() and overwrite the per-queue EN_HDR_SPLIT setting?

kworker (phylink_resolve) CPU0
fbnic_phylink_mac_link_up() fbnic_queue_start()
fbn->tx_pause = tx_pause ...
fbnic_config_drop_mode() fbnic_enable_rcq()

    rcq_ctl = fbnic_ring_rd32(...)      fbnic_config_drop_mode_rcq()
                                          fbnic_ring_wr32(rcq,
                                            FBNIC_QUEUE_RDE_CTL0, ...)
    FIELD_MODIFY(..., &rcq_ctl, ...)
    fbnic_ring_wr32(rcq,
      FBNIC_QUEUE_RDE_CTL0, rcq_ctl)  <-- clobbers EN_HDR_SPLIT

fbnic_phylink_mac_link_up() runs from the phylink workqueue without netdev_lock(dev), while fbnic_queue_start() (or fbnic_up() after __fbnic_open() calls phylink_resume()) programs FBNIC_QUEUE_RDE_CTL0 via fbnic_enable_rcq(). If the two interleave, fbnic_config_drop_mode() can restore a stale EN_HDR_SPLIT, MIN_HROOM or MIN_TROOM value, or fbnic_enable_rcq() can write a stale fbn->tx_pause drop mode.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#81 lore raw

Re: [PATCH net-next v1 10/11] eth: fbnic: Support RX buffers it cannot split

In reply to Björn Töpel
Quoted 99 lines · Björn Töpel

fbnic packs several headers, and several payloads, into one page. A provider without MP_CAP_FRAG needs one descriptor per buffer. Give such a buffer a single reference, program the queue so each header and payload takes a buffer of its own, and drop packets that break this.

Header split is now set per queue, so link up changes only the drop mode.

---
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c | 119 ++++++++++++++++---
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h |   2 +
 2 files changed, 102 insertions(+), 19 deletions(-)
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +38 -4
index bfaa284e497e..d96c957d6fba 100644
@@ -761,8 +761,14 @@ static void fbnic_page_pool_init(struct fbnic_ring *ring, unsigned int idx,
 {
 	struct fbnic_rx_buf *rx_buf = &ring->rx_buf[idx];
 
-	page_pool_fragment_netmem(netmem, FBNIC_PAGECNT_BIAS_MAX);
-	rx_buf->pagecnt_bias = FBNIC_PAGECNT_BIAS_MAX;
+	/* A whole buffer has one reference. The packet takes it, so the buffer
+	 * may be reused before its BDQ entry is cleaned.
+	 */
+	rx_buf->pagecnt_bias = 1;
+	if (page_pool_supports_frag(ring->page_pool)) {
+		page_pool_fragment_netmem(netmem, FBNIC_PAGECNT_BIAS_MAX);
+		rx_buf->pagecnt_bias = FBNIC_PAGECNT_BIAS_MAX;
+	}
 	rx_buf->netmem = netmem;
 }
 
@@ -792,7 +798,8 @@ static void fbnic_page_pool_drain(struct fbnic_ring *ring, unsigned int idx,
 	struct fbnic_rx_buf *rx_buf = &ring->rx_buf[idx];
 	netmem_ref netmem = rx_buf->netmem;
 
-	if (!page_pool_unref_netmem(netmem, rx_buf->pagecnt_bias))
+	if (rx_buf->pagecnt_bias &&
+	    !page_pool_unref_netmem(netmem, rx_buf->pagecnt_bias))
 		page_pool_put_unrefed_netmem(ring->page_pool, netmem, -1,
 					     !!budget);
 
@@ -993,6 +1000,19 @@ static unsigned int fbnic_hdr_pg_end(unsigned int pg_off, unsigned int len)
 	return ALIGN(pg_off, 128) - FBNIC_RX_HROOM;
 }
 
+/* A buffer that cannot be split has one reference and takes one descriptor */
+static bool fbnic_bd_one_desc(struct fbnic_napi_vector *nv,
+			      const struct fbnic_ring *bdq, unsigned int idx,
+			      bool ok)
+{
+	if (likely(page_pool_supports_frag(bdq->page_pool) ||
+		   (bdq->rx_buf[idx].pagecnt_bias == 1 && ok)))
+		return true;
+
+	netdev_err_once(nv->napi.dev, "Bad descriptor for a whole RX buffer\n");
+	return false;
+}
+
 static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 			      struct fbnic_pkt_buff *pkt,
 			      struct fbnic_q_triad *qt)
@@ -1007,6 +1027,17 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 	/* data_hard_start should always be NULL when this is called */
 	WARN_ON_ONCE(pkt->buff.data_hard_start);
 
+	/* MAX_HDR leaves no room for a second header in a whole buffer, so
+	 * the device closes it, with PAGE_FIN, after the first.
+	 */
+	pkt->add_frag_failed = false;
+	if (unlikely(!fbnic_bd_one_desc(nv, &qt->sub0, hdr_pg_idx,
+					FIELD_GET(FBNIC_RCD_AL_PAGE_FIN,
+						  rcd)))) {
+		pkt->add_frag_failed = true;
+		return;
+	}
+
 	netmem = fbnic_page_pool_get_head(qt, hdr_pg_idx);
 	pkt->head = netmem;
 
@@ -1032,7 +1063,6 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 			 len - FBNIC_RX_PAD, true);
 
 	pkt->hwtstamp = 0;
-	pkt->add_frag_failed = false;
 }
 
 static void fbnic_add_rx_frag(struct fbnic_napi_vector *nv, u64 rcd,
@@ -1046,8 +1076,20 @@ static void fbnic_add_rx_frag(struct fbnic_napi_vector *nv, u64 rcd,
 	netmem_ref netmem;
 	bool added;
 
+	if (unlikely(!fbnic_bd_one_desc(nv, &qt->sub1, pg_idx, !pg_off))) {
+		pkt->add_frag_failed = true;
+		return;
+	}

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c static void fbnic_add_rx_frag(struct fbnic_napi_vector *nv, u64 rcd, · line 1092

Quoted 10 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +8 -0
+
 	netmem = fbnic_page_pool_get_data(qt, pg_idx);
 
+	/* Without a header buffer, the packet is dropped. */
+	if (unlikely(!pkt->buff.data_hard_start)) {
+		page_pool_put_full_netmem(qt->sub1.page_pool, netmem, true);
+		pkt->add_frag_failed = true;
+		return;
+	}
+

How would we get in this state? Does the device need to misbehave and skip the header descriptor?

#82 lore raw

Re: [PATCH net-next v1 10/11] eth: fbnic: Support RX buffers it cannot split

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider.

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

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

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

- [Medium] fbnic_config_drop_mode() in drivers/net/ethernet/meta/fbnic/fbnic_txrx.c changes the drop mode in…
- [Medium] eth: fbnic: incomplete split-buffer checks in fbnic_bd_one_desc() callers
- [Low] (Baseline: rejected.) At this commit none of the whole-buffer code can run.

--

eth: fbnic: Support RX buffers it cannot split

The patch lets fbnic RX queues use a page pool provider without MP_CAP_FRAG. Each such buffer gets a single reference, the queue is programmed so each header and payload takes its own buffer, and packets that break this are dropped. Header split is now set per queue, and link up only modifies the drop mode in RDE_CTL0.

Quoted 4 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +0 -0
index bfaa284e497eb..d96c957d6fbad 100644

[ ... ]

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c fbnic_alloc_qt_page_pools(struct fbnic_net *fbn, struct fbnic_q_triad *qt, · line 1698

Quoted 7 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +3 -0
@@ -1644,6 +1693,9 @@ fbnic_alloc_qt_page_pools(struct fbnic_net *fbn, struct fbnic_q_triad *qt,
 		return PTR_ERR(pp);
 
 	qt->sub0.page_pool = pp;
+	qt->hdr_max = 0;
+	if (!page_pool_supports_frag(pp))
+		qt->hdr_max = fbnic_whole_hdr_max(FBNIC_RX_HROOM);

[Severity: Low]
This isn't a bug, but can this branch be reached at this commit?

Both fbnic page pools are still created without PP_FLAG_MEM_PROVIDER. That means no provider without MP_CAP_FRAG can be attached (xsk_pp only advertises MP_CAP_READABLE), so page_pool_supports_frag() is always true here.

As a result, qt->hdr_max stays 0. The whole-buffer paths in fbnic_bd_one_desc(), fbnic_page_pool_init() and fbnic_enable_rcq() are not used until the later patch "eth: fbnic: Support AF_XDP page pool zero copy" sets PP_FLAG_MEM_PROVIDER.

Could the commit message say that a later patch in the series enables this?

Quoted 3 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +0 -0
 	if (netif_rxq_has_unreadable_mp(fbn->netdev, rxq_idx)) {
 		pp_params.order = get_order(rx_page_size);
 		pp_params.max_len = rx_page_size;

[ ... ]

Quoted 26 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +13 -3
@@ -2693,20 +2750,32 @@ static void fbnic_config_drop_mode_rcq(struct fbnic_napi_vector *nv,
 	fbnic_ring_wr32(rcq, FBNIC_QUEUE_RDE_CTL0, rcq_ctl);
 }
 
+static u32 fbnic_rcq_hds_thresh(const struct fbnic_net *fbn,
+				const struct fbnic_ring *rcq)
+{
+	const struct fbnic_q_triad *qt;
+
+	qt = container_of_const(rcq, struct fbnic_q_triad, cmpl);
+	return qt->hdr_max ? : fbn->hds_thresh;
+}
+
+/* Only the drop mode: a queue start may write the rest of the register */
 void fbnic_config_drop_mode(struct fbnic_net *fbn, bool txp)
 {
-	bool hds;
+	struct fbnic_ring *rcq;
+	u32 drop_mode, rcq_ctl;
 	int i, t;
 
-	hds = fbn->hds_thresh < FBNIC_HDR_BYTES_MIN;
-
+	drop_mode = fbnic_drop_mode(fbn, txp);
 	for (i = 0; i < fbn->num_napi; i++) {
 		struct fbnic_napi_vector *nv = fbn->napi[i];

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c static void fbnic_config_drop_mode_rcq(struct fbnic_napi_vector *nv, · line 2778

Quoted 10 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +5 -3
 
 		for (t = 0; t < nv->rxt_count; t++) {
-			struct fbnic_q_triad *qt = &nv->qt[nv->txt_count + t];
-
-			fbnic_config_drop_mode_rcq(nv, &qt->cmpl, txp, hds);
+			rcq = &nv->qt[nv->txt_count + t].cmpl;
+			rcq_ctl = fbnic_ring_rd32(rcq, FBNIC_QUEUE_RDE_CTL0);
+			FIELD_MODIFY(FBNIC_QUEUE_RDE_CTL0_DROP_MODE_MASK,
+				     &rcq_ctl, drop_mode);
+			fbnic_ring_wr32(rcq, FBNIC_QUEUE_RDE_CTL0, rcq_ctl);

[Severity: Medium]
Does anything serialize this read-modify-write of FBNIC_QUEUE_RDE_CTL0 against a queue restart?

fbnic_config_drop_mode() is called from fbnic_phylink_mac_link_up():

fbnic_phylink.c:fbnic_phylink_mac_link_up() {
    ...
	fbn->tx_pause = tx_pause;
	fbnic_config_drop_mode(fbn, tx_pause);
    ...
}

That runs from the phylink_resolve() work item. The work item holds pl->state_mutex and the phy locks, but not rtnl or the netdev instance lock.

The queue start path runs under the netdev instance lock and writes the whole register from per-queue state:

fbnic_queue_start()
__fbnic_nv_restart()

    fbnic_enable_rcq()
      fbnic_config_drop_mode_rcq()
        fbnic_ring_wr32(rcq, FBNIC_QUEUE_RDE_CTL0, rcq_ctl);

Suppose the link up worker reads CTL0. A queue start then writes a new CTL0 with a different EN_HDR_SPLIT, derived from qt->hdr_max. The worker then writes its saved copy back.

Wouldn't the restarted queue keep the old EN_HDR_SPLIT, which no longer matches the MAX_HDR, PAYLD_OFF and PAYLD_PG_CL values in CTL1? Nothing corrects it until the next restart of that queue.

At this commit qt->hdr_max is always 0, so the written-back value still matches. Later in the series, "eth: fbnic: Support AF_XDP page pool zero copy" makes hdr_max and MIN_HROOM (from qt->rx_hroom) truly per queue.

After that, an AF_XDP bind or unbind that overlaps a link up event could leave the queue misconfigured. For example, a stale EN_HDR_SPLIT on a non-SG AF_XDP queue would make every packet multi-buffer, and fbnic_run_xdp() would drop it.

Quoted 3 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +0 -0
 		}
 	}
 }

[ ... ]

Quoted 10 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +6 -0
@@ -993,6 +1000,19 @@ static unsigned int fbnic_hdr_pg_end(unsigned int pg_off, unsigned int len)
 	return ALIGN(pg_off, 128) - FBNIC_RX_HROOM;
 }
 
+/* A buffer that cannot be split has one reference and takes one descriptor */
+static bool fbnic_bd_one_desc(struct fbnic_napi_vector *nv,
+			      const struct fbnic_ring *bdq, unsigned int idx,
+			      bool ok)
+{
+	if (likely(page_pool_supports_frag(bdq->page_pool) ||

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c static unsigned int fbnic_hdr_pg_end(unsigned int pg_off, unsigned int len) · line 1018

Quoted 10 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +7 -0
+		   (bdq->rx_buf[idx].pagecnt_bias == 1 && ok)))
+		return true;
+
+	netdev_err_once(nv->napi.dev, "Bad descriptor for a whole RX buffer\n");
+	return false;
+}
+
 static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 			      struct fbnic_pkt_buff *pkt,
 			      struct fbnic_q_triad *qt)

[Severity: Medium]
Do the two callers of fbnic_bd_one_desc() check enough to catch a whole buffer that the device splits across more than one completion?

The commit message says packets that break the one descriptor per buffer rule are dropped. Each caller only checks half of that condition, though.

In fbnic_add_rx_frag() the ok argument is only !pg_off, and FBNIC_RCD_AL_PAGE_FIN is not checked. Suppose a payload buffer ends up holding more than one payload. The first completion then has pg_off == 0 and PAGE_FIN == 0, so it passes. fbnic_page_pool_get_data() drops pagecnt_bias from 1 to 0, and the packet takes the only reference to the netmem.

That reference can then go back to the pool through page_pool_put_full_netmem(), or be handed to the AF_XDP socket. The device still has the buffer open at that point and may DMA the next payload into it. The next completion for that buffer is rejected because pagecnt_bias is now 0, but the buffer has already been released by then.

fbnic_pkt_prepare() has the opposite gap. It checks only PAGE_FIN, not where the header sits in the buffer. Suppose two headers land in the same header buffer. The first completion has PAGE_FIN == 0 and is rejected before fbnic_page_pool_get_head() runs, so pagecnt_bias stays at 1.

The second completion has PAGE_FIN == 1 at a non-zero offset. It still sees pagecnt_bias == 1 and is accepted. An xdp_buff is then built from the middle of a buffer that was meant to hold a single header.

A conforming device should not do either of these with the MAX_HDR, PAYLD_OFF and PAYLD_PG_CL values programmed in fbnic_enable_rcq(). However, these checks exist to catch the case where it does.

Should both callers require that the completion starts the buffer and also closes it, i.e. a zero offset and PAGE_FIN set? Passing the rcd into fbnic_bd_one_desc() and doing both checks there might keep the header and payload paths from drifting apart again.

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261110102039.1002605-1-bjorn%40kernel.org
#83 lore raw

Re: [PATCH net-next v1 10/11] eth: fbnic: Support RX buffers it cannot split

[email protected] writes:

[...]

Quoted 3 lines

Wouldn't the restarted queue keep the old EN_HDR_SPLIT, which no longer matches the MAX_HDR, PAYLD_OFF and PAYLD_PG_CL values in CTL1? Nothing corrects it until the next restart of that queue.

Pre-existing for the drop mode, and the per-queue bits make it worse. I have a net fix that serializes link up and queue start with a lock.

[...]

Quoted 4 lines

Should both callers require that the completion starts the buffer and also closes it, i.e. a zero offset and PAGE_FIN set? Passing the rcd into fbnic_bd_one_desc() and doing both checks there might keep the header and payload paths from drifting apart again.

v2 drops these checks instead. With MAX_HDR, PAYLD_OFF and PAYLD_PG_CL as programmed, the device closes a whole buffer after one descriptor, and fbnic trusts its completion ring everywhere else.

Björn

#84 lore raw

PATCH 11/11 eth: fbnic: Support AF_XDP page pool zero copy

In reply to Björn Töpel

Header and payload rings share one provider page pool, so refills even them out, and a short pool does not starve one of them. Payload buffers start at chunk offset 0, and the UMEM headroom rules require headroom only in the first buffer. A chunk is one 4 KiB device page, also with larger kernel pages, so rings fed by the provider post one descriptor per chunk.

Socket TX shares the XDP TX ring and runs after RX: XDP_TX drops frames that do not fit, while socket descriptors can wait. The TX need_wakeup flag stays set, as for ice, since clearing it can miss the last wakeup.

---
 Documentation/networking/af_xdp.rst           |  58 +++
 .../net/ethernet/meta/fbnic/fbnic_netdev.c    |  18 +
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c  | 428 ++++++++++++++----
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h  |  25 +-
 4 files changed, 446 insertions(+), 83 deletions(-)
Documentation/networking/af_xdp.rst +58 -0
index e73a0005e169..f152ae8812d1 100644
@@ -346,6 +346,64 @@ Note that a UMEM can be shared between sockets on the same queue id
 and device, as well as between queues on the same device and between
 devices at the same time.
 
+Zero-copy through page pool
+---------------------------
+
+Some drivers, for example fbnic, receive into the UMEM through a page
+pool memory provider instead of their own allocator. The socket API
+does not change: zero-copy mode is selected as before, and XDP_OPTIONS
+reports it.
+
+The requirements are:
+
+* Aligned chunks of a size the driver supports, 4 KiB for fbnic.
+* The queue id has an RX queue, also for a socket that only transmits.
+  Such a socket needs the FILL and COMPLETION rings, like any other.
+* The driver accepts the headroom, MTU and XDP program. fbnic accepts
+  a UMEM headroom of 0, 128 or 256 bytes. An MTU larger than its header
+  buffer needs XDP_USE_SG, and frags support in an XDP program. The
+  first buffer of a larger frame may hold only its headers, and the
+  other buffers start at offset 0 of their chunk. Such a frame can take
+  one chunk more than in copy mode.
+
+If the device cannot do zero-copy for the socket, a bind with
+XDP_ZEROCOPY fails with EOPNOTSUPP, while a bind without it falls back
+to copy mode. MTU and XDP program changes that a bound socket cannot
+handle are refused.
+
+Binding restarts the RX queue. The queue takes chunks from the FILL
+ring and returns them on the RX ring. A FILL entry for a chunk that
+the RX side still owns is dropped; TX chunks stay with userspace until
+their completion, as before. XDP_PASS copies the packet. Redirects to
+anything but a socket copy single-buffer packets and drop others. A
+redirect to a socket of another queue fails, and generic XDP cannot
+redirect to the socket.
+
+When the queue has no chunks left to post, RX waits for the FILL ring.
+With XDP_USE_NEED_WAKEUP, the flag on the FILL ring stays set, and
+userspace must call poll(), or recvfrom() with an RX ring or sendto()
+with a TX ring, after it posts entries. Without the flag, the queue
+polls the FILL ring, which costs CPU time while the ring is empty.
+Post FILL entries before bind() if possible.
+
+A driver supports this mode when it:
+
+* uses netmem for header buffers and XDP_TX, and handles page pools
+  whose buffers cannot be split (see page_pool_supports_frag()),
+* selects the provider with PP_FLAG_MEM_PROVIDER and pp_rx_role for
+  one page pool of each queue, and honours the rx_headroom queue
+  configuration,
+* calls page_pool_refill_done() after each refill,
+* sends socket TX descriptors from the NAPI of the RX queue, with
+  xsk_tx_peek_release_desc_batch() for the pool that xsk_rxq_pool()
+  returns,
+* advertises NETDEV_XDP_ACT_XSK_ZEROCOPY and xdp_zc_max_segs,
+* checks the setup in XDP_VALIDATE_XSK_POOL, and sets xsk_page_pool
+  in its netdev_queue_mgmt_ops.
+
+The core schedules that NAPI for RX and TX wakeups, so no
+ndo_xsk_wakeup is needed.
+
 XDP_USE_NEED_WAKEUP bind flag
 -----------------------------
 
drivers/net/ethernet/meta/fbnic/fbnic_netdev.c +18 -0
index ae2585508690..8cb5b5b93c70 100644
@@ -5,6 +5,7 @@
 #include <linux/ipv6.h>
 #include <linux/types.h>
 #include <net/netdev_queues.h>
+#include <net/xdp_sock_drv.h>
 
 #include "fbnic.h"
 #include "fbnic_netdev.h"
@@ -276,6 +277,7 @@ static int fbnic_set_mac(struct net_device *netdev, void *p)
 static int fbnic_change_mtu(struct net_device *dev, int new_mtu)
 {
 	struct fbnic_net *fbn = netdev_priv(dev);
+	int err;
 
 	if (fbnic_check_split_frames(fbn->xdp_prog, new_mtu, fbn->hds_thresh)) {
 		dev_err(&dev->dev,
@@ -285,6 +287,13 @@ static int fbnic_change_mtu(struct net_device *dev, int new_mtu)
 		return -EINVAL;
 	}
 
+	err = xsk_validate_dev(dev, new_mtu, NULL, XDP_MODE_DRV, NULL);
+	if (err) {
+		dev_err(&dev->dev, "MTU %d does not fit a bound AF_XDP socket\n",
+			new_mtu);
+		return err;
+	}
+
 	WRITE_ONCE(dev->mtu, new_mtu);
 
 	return 0;
@@ -538,6 +547,13 @@ static int fbnic_bpf(struct net_device *netdev, struct netdev_bpf *bpf)
 {
 	struct bpf_prog *prog = bpf->prog, *prev_prog;
 	struct fbnic_net *fbn = netdev_priv(netdev);
+	const struct xsk_rx_check *check;
+
+	if (bpf->command == XDP_VALIDATE_XSK_POOL) {
+		check = bpf->xsk_check.check;
+		prog = check->prog ? : READ_ONCE(fbn->xdp_prog);
+		return fbnic_xsk_validate(check, prog, bpf->xsk_check.extack);
+	}
 
 	if (bpf->command != XDP_SETUP_PROG)
 		return -EINVAL;
@@ -825,6 +841,8 @@ struct net_device *fbnic_netdev_alloc(struct fbnic_dev *fbd)
 	netdev->xdp_features = NETDEV_XDP_ACT_BASIC |
 			       NETDEV_XDP_ACT_REDIRECT |
 			       NETDEV_XDP_ACT_RX_SG;
+	netdev->xdp_features |= NETDEV_XDP_ACT_XSK_ZEROCOPY;
+	netdev->xdp_zc_max_segs = FBNIC_MAX_RX_BUFS;
 
 	netdev->min_mtu = IPV6_MIN_MTU;
 	netdev->max_mtu = FBNIC_MAX_JUMBO_FRAME_SIZE - ETH_HLEN;
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +346 -82

661 lines not on this page · raw message

drivers/net/ethernet/meta/fbnic/fbnic_txrx.h +24 -1
index 3077d9bbd587..b4baaa914585 100644
@@ -14,7 +14,11 @@
 
 #include "fbnic_csr.h"
 
+struct bpf_prog;
 struct fbnic_net;
+struct netlink_ext_ack;
+struct xsk_buff_pool;
+struct xsk_rx_check;
 
 /* Guarantee we have space needed for storing the buffer
  * To store the buffer we need:
@@ -36,6 +40,8 @@ struct fbnic_net;
  */
 #define FBNIC_MAX_RX_PKT_DESC	7
 #define FBNIC_RX_DESC_MIN	roundup_pow_of_two(FBNIC_MAX_RX_PKT_DESC * 2)
+/* All descriptors of a packet but the two metadata ones */
+#define FBNIC_MAX_RX_BUFS	(FBNIC_MAX_RX_PKT_DESC - 2)
 
 #define FBNIC_MAX_TXQS			128u
 #define FBNIC_MAX_RXQS			128u
@@ -66,6 +72,9 @@ struct fbnic_net;
 	(ALIGN(FBNIC_RX_TROOM + FBNIC_RX_HROOM_PAD, 128) - FBNIC_RX_TROOM)
 #define FBNIC_RX_PAD			0
 #define FBNIC_RX_HDR_ALIGN		128
+#define FBNIC_RX_HROOM_MAX \
+	ALIGN(FIELD_MAX(FBNIC_QUEUE_RDE_CTL0_MIN_HROOM_MASK), \
+	      FBNIC_RX_HDR_ALIGN)
 #define FBNIC_RX_PAYLD_ALIGN		128
 #define FBNIC_RX_PAYLD_OFFSET		0
 #define FBNIC_RX_PAYLD_PG_CL		0
@@ -73,6 +82,7 @@ struct fbnic_net;
 #define FBNIC_RING_F_DISABLED		BIT(0)
 #define FBNIC_RING_F_CTX		BIT(1)
 #define FBNIC_RING_F_STATS		BIT(2)	/* Ring's stats may be used */
+#define FBNIC_RING_F_XDP		BIT(3)	/* XDP TX ring */
 
 #define FBNIC_HDS_THRESH_MAX \
 	(4096 - FBNIC_RX_HROOM - FBNIC_RX_TROOM - FBNIC_RX_PAD)
@@ -121,12 +131,18 @@ struct fbnic_rx_buf {
 	long pagecnt_bias;
 };
 
+/* XDP TX ring entry: an XDP_TX buffer, or an AF_XDP TX descriptor */
+struct fbnic_xdp_tx_buf {
+	netmem_ref netmem;
+	struct xsk_buff_pool *xsk;
+};
+
 struct fbnic_ring {
 	/* Pointer to buffer specific info */
 	union {
 		struct fbnic_pkt_buff *pkt;	/* RCQ */
 		struct fbnic_rx_buf *rx_buf;	/* BDQ */
-		netmem_ref *tx_netmem;		/* TWQ1 */
+		struct fbnic_xdp_tx_buf *xdp_buf; /* TWQ1 */
 		void **tx_buf;			/* TWQ */
 		void *buffer;			/* Generic pointer */
 	};
@@ -167,6 +183,10 @@ struct fbnic_q_triad {
 	struct fbnic_ring sub0, sub1, cmpl;
 	struct xdp_rxq_info xdp_rxq;
 	u16 hdr_max;	/* Header bytes for whole header buffers, or 0 */
+	u16 rx_hroom;	/* Headroom before a header */
+	u16 rx_hdr_first; /* Offset of the first header in a buffer */
+	u16 rx_frame_off; /* Offset of the frame in a header buffer */
+	struct xsk_buff_pool *xsk_pool;	/* AF_XDP pool of an RX queue */
 };
 
 struct fbnic_napi_vector {
@@ -178,6 +198,7 @@ struct fbnic_napi_vector {
 	u16 v_idx;
 	u8 txt_count;
 	u8 rxt_count;
+	u8 xsk_tx_next;		/* RX queue that sends socket TX first */
 
 	struct fbnic_q_triad qt[];
 };
@@ -203,6 +224,8 @@ void fbnic_aggregate_ring_tx_counters(struct fbnic_net *fbn,
 void fbnic_aggregate_ring_xdp_counters(struct fbnic_net *fbn,
 				       struct fbnic_ring *xdpr);
 
+int fbnic_xsk_validate(const struct xsk_rx_check *check,
+		       struct bpf_prog *prog, struct netlink_ext_ack *extack);
 int fbnic_alloc_napi_vectors(struct fbnic_net *fbn);
 void fbnic_free_napi_vectors(struct fbnic_net *fbn);
 int fbnic_alloc_resources(struct fbnic_net *fbn);
Signature · 1 line
2.56.0
#85 lore raw

Re: [PATCH net-next v1 11/11] eth: fbnic: Support AF_XDP page pool zero copy

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce: - [Critical] eth: fbnic: wrong Rx queue index…

Thank you for your contribution! Sashiko AI review found no new issues in this patch, but noticed 1 related pre-existing issue it does not introduce:
- [Critical] eth: fbnic: wrong Rx queue index used for idle polling in fbnic_queue_stop() [1]
--

commit 94641017ff155e4aaace7b6d7179917c8e4199a7
Author: Björn Töpel <[email protected]>

eth: fbnic: Support AF_XDP page pool zero copy

This commit adds AF_XDP zero-copy support to fbnic using a page pool memory provider shared between header and payload rings, and transmits socket descriptors on the XDP TX ring during NAPI polling.

Quoted 4 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +0 -0
index d96c957d6fbad..c358003f053b6 100644

[ ... ]

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c const struct netdev_queue_mgmt_ops fbnic_queue_mgmt_ops = { · line 3484

Quoted 8 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +2 -1
@@ -3216,5 +3479,6 @@ const struct netdev_queue_mgmt_ops fbnic_queue_mgmt_ops = {
 	.ndo_queue_stop		= fbnic_queue_stop,
 	.ndo_default_qcfg	= fbnic_default_qcfg,
 	.ndo_validate_qcfg	= fbnic_validate_qcfg,
-	.supported_params	= QCFG_RX_PAGE_SIZE,
+	.supported_params	= QCFG_RX_PAGE_SIZE | QCFG_RX_HEADROOM,
+	.xsk_page_pool		= true,
 };

[Severity: Critical]
This problem wasn't introduced by this patch, but does fbnic_queue_stop() poll the wrong RX hardware queue index for idle state [1] when stopping a non-zero RX queue (such as when binding an AF_XDP socket)?

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c:fbnic_queue_stop() {
	...
	for (t = 0; t < nv->txt_count + nv->rxt_count; t++) {
		err = fbnic_wait_queue_idle(fbn, t >= nv->txt_count,
					    nv->qt[t].sub0.q_idx);
		if (err)
			goto err_restart;
	}
	...
}

In fbnic_alloc_napi_vector(), RX queue triads initialize qt->sub0.q_idx to 0 and store rxq_idx in qt->cmpl.q_idx. Passing sub0.q_idx to fbnic_wait_queue_idle() checks RX queue 0 instead of the target RX queue:
if queue 0 is idle while the target RX queue is still active, fbnic_queue_stop() frees the active queue's resources while DMA is still in flight, whereas if queue 0 is busy, stopping another RX queue can time out.

[1] https://sashiko.dev/#/bug/linux-197dd65d-fb9f-419a-afba-7621f586ae26

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#86 lore raw

Re: [PATCH net-next v1 11/11] eth: fbnic: Support AF_XDP page pool zero copy

In reply to Björn Töpel
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider.

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

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

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

- [High] Stale, unreferenced xsk_buff_pool pointer is used after a failed queue restart during AF_XDP unbind.
- [Medium] On an AF_XDP provider queue, an empty FILL ring is normal flow control, but fbnic counts it as a buffer allocation failure.
- [Low] The commit message presents the balanced header/payload refill as something for the shared provider page pool ("Header and payload rings…
- [Low] The new "Zero-copy through page pool" section of Documentation/networking/af_xdp.rst says "MTU and XDP program changes…
- [Low] The new af_xdp.rst text says: "If the device cannot do zero-copy for the socket, a bind with XDP_ZEROCOPY fails with EOPNOTSUPP, while…

--

eth: fbnic: Support AF_XDP page pool zero copy

This adds AF_XDP zero-copy support to fbnic through a page pool memory provider. The header and payload BDQs share one provider page pool and use a new balanced refill policy, and socket TX descriptors go out on the XDP TX ring from the RX NAPI after RX processing. It also adds per-queue rx_headroom support and documents the page pool zero-copy mode in af_xdp.rst.

Quoted 5 lines
Documentation/networking/af_xdp.rst +0 -0
index e73a0005e169c..f152ae8812d17 100644
@@ -346,6 +346,64 @@ Note that a UMEM can be shared between sockets on the same queue id

[ ... ]

Documentation/networking/af_xdp.rst Note that a UMEM can be shared between sockets on the same queue id · line 372

Quoted 4 lines
Documentation/networking/af_xdp.rst +4 -0
+If the device cannot do zero-copy for the socket, a bind with
+XDP_ZEROCOPY fails with EOPNOTSUPP, while a bind without it falls back
+to copy mode. MTU and XDP program changes that a bound socket cannot
+handle are refused.

[Severity: Low]
Does the page pool bind path always behave this way?

xsk_pp_bind() in net/xdp/xsk_pp.c returns -EBUSY when another queue has an unreadable memory provider:

if (!netif_all_mps_have_cap(dev, MP_CAP_READABLE))
return -EBUSY;

It also passes on errors from the driver's XDP_VALIDATE_XSK_POOL check, xp_dma_map(), xsk_pp_create() (-ENOMEM, -ERANGE) and netif_mp_open_rxq() (for example -EEXIST, -EINVAL, -ENOMEM).

The copy-mode fallback is also conditional. In xp_assign_dev():

if (!force_zc && !pool->pp)
err = xp_alloc_heads(pool); /* fallback to copy mode */

Suppose netif_mp_open_rxq() fails, and then either xp_alloc_heads() fails or xsk_pp_abandon() finds an old page pool still holding chunks. In that case xsk_pp_bind() leaves pool->pp set, and a bind without XDP_ZEROCOPY fails instead of falling back to copy mode.

Could the text mention the other errnos, and the case where copy mode is not available?

[ ... ]

Documentation/networking/af_xdp.rst Note that a UMEM can be shared between sockets on the same queue id · line 402

Quoted 3 lines
Documentation/networking/af_xdp.rst +3 -0
+* advertises NETDEV_XDP_ACT_XSK_ZEROCOPY and xdp_zc_max_segs,
+* checks the setup in XDP_VALIDATE_XSK_POOL, and sets xsk_page_pool
+  in its netdev_queue_mgmt_ops.

[Severity: Low]
Should this list also say that the driver must call xsk_validate_dev() from its own ndo_change_mtu?

In net/core/dev.c, the only callers of xsk_validate_dev() are the XDP program install paths. No core MTU path calls it. fbnic refuses such MTU changes only because this patch adds this to fbnic_change_mtu():

    err = xsk_validate_dev(dev, new_mtu, NULL, XDP_MODE_DRV, NULL);

A driver that follows only this list would accept MTU changes that a bound socket cannot handle. One example is raising the MTU above the header buffer size for a non-SG socket. The statement above that such MTU changes are refused would then not hold.

[ ... ]

Quoted 4 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +0 -0
index d96c957d6fbad..c358003f053b6 100644

[ ... ]

Quoted 6 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +2 -0
@@ -938,66 +969,146 @@ static void fbnic_bd_prep(struct fbnic_ring *bdq, u16 id, netmem_ref netmem)
 	} while (--i);
 }
 
+static bool fbnic_fill_bdq_one(struct fbnic_ring *bdq, unsigned int *tail)
+{

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c static void fbnic_bd_prep(struct fbnic_ring *bdq, u16 id, netmem_ref netmem) · line 983

Quoted 10 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +10 -0
+	netmem_ref netmem;
+
+	netmem = page_pool_dev_alloc_netmems(bdq->page_pool);
+	if (!netmem) {
+		u64_stats_update_begin(&bdq->stats.syncp);
+		bdq->stats.bdq.alloc_failed++;
+		u64_stats_update_end(&bdq->stats.syncp);
+
+		return false;
+	}

[Severity: Medium]
On an AF_XDP provider queue, xsk_pp_alloc_netmems() returns 0 whenever the reuse stack and the FILL ring are empty. That is normal flow control for the socket. Is it intended to count it as alloc_failed?

Without XDP_USE_NEED_WAKEUP, xsk_pp_refill_done() returns false in this case:

    more = pp->reuse_cnt || xskq_cons_nb_entries(pp->fq, 1);
    WRITE_ONCE(pp->starved, !more);
    spin_unlock_bh(&pp->lock);

    return !more && wait;

fbnic_fill_bdqs() then returns false, fbnic_clean_rcq() returns budget, and NAPI polls again at once. Each poll fails the allocation again and increments the counter again.

This counter reaches userspace through the standard queue stats in fbnic_netdev.c:

    rx->alloc_fail = fbn->rx_stats.rx.alloc_failed +
        fbn->bdq_stats.bdq.alloc_failed;

Won't an idle xsk queue then report a fast-growing alloc_fail count that has nothing to do with memory pressure? With need_wakeup, each wakeup that finds the FILL ring empty would also be counted.

[ ... ]

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c static void fbnic_bd_prep(struct fbnic_ring *bdq, u16 id, netmem_ref netmem)

Quoted 9 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +7 -1
+static bool fbnic_fill_bdqs(struct fbnic_q_triad *qt)
+{
+	struct fbnic_ring *hpq = &qt->sub0, *ppq = &qt->sub1;
+	enum pp_refill state;
+	bool done;
 
-		writel(i * fbnic_bd_page_count(bdq), bdq->doorbell);
+	if (hpq->page_pool == ppq->page_pool) {
+		fbnic_fill_shared_bdqs(hpq, ppq);

[Severity: Low]
The commit message says:

Header and payload rings share one provider page pool, so refills even them out, and a short pool does not starve one of them.

In the default configuration, without AF_XDP, fbnic_alloc_qt_page_pools() already shares one regular page pool between sub0 and sub1, through this unchanged branch:

    } else {
        page_pool_get(pp);
    }
    qt->sub1.page_pool = pp;

So this test is true for every normal RX queue as well. fbnic_fill_shared_bdqs() replaces the old policy, which filled the HPQ fully and then filled the PPQ, on the default datapath. The new policy interleaves per buffer through fbnic_hpq_takes_next(), which does u64 multiplications for each buffer. Filling of both rings also stops at the first allocation failure.

Should the commit message mention this change to the existing datapath? It also does not mention two other changes: QCFG_RX_HEADROOM is now accepted, and RDE_CTL0 MIN_HROOM is programmed per queue.

Quoted 5 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +4 -0
+		state = fbnic_bdq_state(hpq);
+		if (state == PP_REFILL_FULL)
+			state = fbnic_bdq_state(ppq);
+		return page_pool_refill_done(hpq->page_pool, state);
 	}

[ ... ]

Quoted 7 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +1 -0
@@ -1674,8 +1901,29 @@ fbnic_alloc_qt_page_pools(struct fbnic_net *fbn, struct fbnic_q_triad *qt,
 		.netdev	= fbn->netdev,
 		.queue_idx = rxq_idx,
 	};
+	struct xsk_buff_pool *xsk;
 	struct page_pool *pp;
 

[ ... ]

drivers/net/ethernet/meta/fbnic/fbnic_txrx.c fbnic_alloc_qt_page_pools(struct fbnic_net *fbn, struct fbnic_q_triad *qt, · line 1917

Quoted 3 lines
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +3 -0
+	/* Payload buffers come from UMEM only for multi-buffer sockets */
+	xsk = xsk_rxq_pool(fbn->netdev, rxq_idx);
+	qt->xsk_pool = xsk;

[Severity: High]
This stores the xsk_buff_pool pointer without taking a reference, and fbnic_queue_start() copies it into the live triad. What happens to this pointer if the queue restart during unbind fails?

On socket close, this chain can fail:

__xp_clear_dev()
xsk_pp_unbind()

    netif_mp_close_rxq()
      __netif_mp_close_rxq()
        netdev_rx_queue_reconfig()

Some ways it can fail:

- fbnic_queue_mem_alloc() returns -ENOMEM from page_pool_create(), kvzalloc() or the descriptor ring allocation.
- fbnic_queue_stop() fails through fbnic_wait_queue_idle().
- ndo_queue_start() fails and the old queue is restarted.

__netif_mp_close_rxq() only warns:

    err = netdev_rx_queue_reconfig(dev, rxq_idx, &qcfg[0], &qcfg[1]);
    if (err == -ENETDOWN)
        return 0;
    WARN_ON(err);
    return err;

xsk_pp_unbind() then ignores the result:

    netif_mp_close_rxq(pool->netdev, pool->queue_id, &mp);
    xsk_pp_detach(pp);

xsk_pp_detach() unmaps the DMA through xp_dma_unmap(), and xp_destroy() later frees the pool. Meanwhile the old fbnic triad keeps running with qt->xsk_pool still set.

On every poll, fbnic_poll()->fbnic_xsk_tx()->fbnic_xsk_tx_pool() calls xsk_set_tx_need_wakeup(), xsk_tx_peek_release_desc_batch() and xsk_buff_raw_get_dma() on that pool. Wouldn't these then read and write freed memory? In-flight entries in ring->xdp_buf[].xsk would also be passed to xsk_tx_completed() from fbnic_clean_twq1().

The xsk_rxq_pool() comment says "The pool stays valid while the queue that the caller allocates runs", but that does not seem to hold on this failure path. Part of the cause is the core error handling. Still, the fbnic TX code added here is what keeps using the raw pointer.

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261110102039.1002605-1-bjorn%40kernel.org
#87 lore raw

Re: [PATCH net-next v1 11/11] eth: fbnic: Support AF_XDP page pool zero copy

[email protected] writes:

[...]

Quoted 3 lines

Won't an idle xsk queue then report a fast-growing alloc_fail count that has nothing to do with memory pressure? With need_wakeup, each wakeup that finds the FILL ring empty would also be counted.

mlx5 counts it the same way, ice doesn't. It's already in fill_ring_empty_descs, so v2 doesn't count it on rings the provider feeds.

[...]

Quoted 4 lines

The xsk_rxq_pool() comment says "The pool stays valid while the queue that the caller allocates runs", but that does not seem to hold on this failure path. Part of the cause is the core error handling. Still, the fbnic TX code added here is what keeps using the raw pointer.

Same root cause as the failed removal in 05, and the same fix. The provider then keeps the pool, its rings and the UMEM until the queue DMA has stopped, so the comment holds. The socket is off the pool's TX list by then, so TX finds nothing, and completions go to a live ring.

Björn

#88 lore raw

Re: [PATCH net-next v1 11/11] eth: fbnic: Support AF_XDP page pool zero copy

In reply to Björn Töpel
Quoted 124 lines · Björn Töpel

Header and payload rings share one provider page pool, so refills even them out, and a short pool does not starve one of them. Payload buffers start at chunk offset 0, and the UMEM headroom rules require headroom only in the first buffer. A chunk is one 4 KiB device page, also with larger kernel pages, so rings fed by the provider post one descriptor per chunk.

Socket TX shares the XDP TX ring and runs after RX: XDP_TX drops frames that do not fit, while socket descriptors can wait. The TX need_wakeup flag stays set, as for ice, since clearing it can miss the last wakeup.

---
 Documentation/networking/af_xdp.rst           |  58 +++
 .../net/ethernet/meta/fbnic/fbnic_netdev.c    |  18 +
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c  | 428 ++++++++++++++----
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h  |  25 +-
 4 files changed, 446 insertions(+), 83 deletions(-)
Documentation/networking/af_xdp.rst +58 -0
index e73a0005e169..f152ae8812d1 100644
@@ -346,6 +346,64 @@ Note that a UMEM can be shared between sockets on the same queue id
 and device, as well as between queues on the same device and between
 devices at the same time.
 
+Zero-copy through page pool
+---------------------------
+
+Some drivers, for example fbnic, receive into the UMEM through a page
+pool memory provider instead of their own allocator. The socket API
+does not change: zero-copy mode is selected as before, and XDP_OPTIONS
+reports it.
+
+The requirements are:
+
+* Aligned chunks of a size the driver supports, 4 KiB for fbnic.
+* The queue id has an RX queue, also for a socket that only transmits.
+  Such a socket needs the FILL and COMPLETION rings, like any other.
+* The driver accepts the headroom, MTU and XDP program. fbnic accepts
+  a UMEM headroom of 0, 128 or 256 bytes. An MTU larger than its header
+  buffer needs XDP_USE_SG, and frags support in an XDP program. The
+  first buffer of a larger frame may hold only its headers, and the
+  other buffers start at offset 0 of their chunk. Such a frame can take
+  one chunk more than in copy mode.
+
+If the device cannot do zero-copy for the socket, a bind with
+XDP_ZEROCOPY fails with EOPNOTSUPP, while a bind without it falls back
+to copy mode. MTU and XDP program changes that a bound socket cannot
+handle are refused.
+
+Binding restarts the RX queue. The queue takes chunks from the FILL
+ring and returns them on the RX ring. A FILL entry for a chunk that
+the RX side still owns is dropped; TX chunks stay with userspace until
+their completion, as before. XDP_PASS copies the packet. Redirects to
+anything but a socket copy single-buffer packets and drop others. A
+redirect to a socket of another queue fails, and generic XDP cannot
+redirect to the socket.
+
+When the queue has no chunks left to post, RX waits for the FILL ring.
+With XDP_USE_NEED_WAKEUP, the flag on the FILL ring stays set, and
+userspace must call poll(), or recvfrom() with an RX ring or sendto()
+with a TX ring, after it posts entries. Without the flag, the queue
+polls the FILL ring, which costs CPU time while the ring is empty.
+Post FILL entries before bind() if possible.
+
+A driver supports this mode when it:
+
+* uses netmem for header buffers and XDP_TX, and handles page pools
+  whose buffers cannot be split (see page_pool_supports_frag()),
+* selects the provider with PP_FLAG_MEM_PROVIDER and pp_rx_role for
+  one page pool of each queue, and honours the rx_headroom queue
+  configuration,
+* calls page_pool_refill_done() after each refill,
+* sends socket TX descriptors from the NAPI of the RX queue, with
+  xsk_tx_peek_release_desc_batch() for the pool that xsk_rxq_pool()
+  returns,
+* advertises NETDEV_XDP_ACT_XSK_ZEROCOPY and xdp_zc_max_segs,
+* checks the setup in XDP_VALIDATE_XSK_POOL, and sets xsk_page_pool
+  in its netdev_queue_mgmt_ops.
+
+The core schedules that NAPI for RX and TX wakeups, so no
+ndo_xsk_wakeup is needed.
+
 XDP_USE_NEED_WAKEUP bind flag
 -----------------------------
 
drivers/net/ethernet/meta/fbnic/fbnic_netdev.c +9 -0
index ae2585508690..8cb5b5b93c70 100644
@@ -5,6 +5,7 @@
 #include <linux/ipv6.h>
 #include <linux/types.h>
 #include <net/netdev_queues.h>
+#include <net/xdp_sock_drv.h>
 
 #include "fbnic.h"
 #include "fbnic_netdev.h"
@@ -276,6 +277,7 @@ static int fbnic_set_mac(struct net_device *netdev, void *p)
 static int fbnic_change_mtu(struct net_device *dev, int new_mtu)
 {
 	struct fbnic_net *fbn = netdev_priv(dev);
+	int err;
 
 	if (fbnic_check_split_frames(fbn->xdp_prog, new_mtu, fbn->hds_thresh)) {
 		dev_err(&dev->dev,
@@ -285,6 +287,13 @@ static int fbnic_change_mtu(struct net_device *dev, int new_mtu)
 		return -EINVAL;
 	}
 
+	err = xsk_validate_dev(dev, new_mtu, NULL, XDP_MODE_DRV, NULL);
+	if (err) {
+		dev_err(&dev->dev, "MTU %d does not fit a bound AF_XDP socket\n",
+			new_mtu);
+		return err;
+	}
+
 	WRITE_ONCE(dev->mtu, new_mtu);
 
 	return 0;

drivers/net/ethernet/meta/fbnic/fbnic_netdev.c static int fbnic_bpf(struct net_device *netdev, struct netdev_bpf *bpf) · line 552

Quoted 6 lines
drivers/net/ethernet/meta/fbnic/fbnic_netdev.c +3 -0
@@ -538,6 +547,13 @@ static int fbnic_bpf(struct net_device *netdev, struct netdev_bpf *bpf)
 {
 	struct bpf_prog *prog = bpf->prog, *prev_prog;
 	struct fbnic_net *fbn = netdev_priv(netdev);
+	const struct xsk_rx_check *check;
+
+	if (bpf->command == XDP_VALIDATE_XSK_POOL) {

do you really need a separate command here? why not rely on existing XDP_SETUP_XSK_POOL ?

here it doesn't look like things being validated are something unique that you could not check during XDP_SETUP_XSK_POOL and XDP_SETUP_PROG.

Overall, +400 lines for zc pp-based support...not sure what I was expecting and I know we need Tx side implementation.

However, I am wondering if better example for this change set would be the driver that already supports pp *and* carries the separate ZC data path (ekhm, see ice?). Then you could show case at least in diffstat how much less work is needed for AF_XDP support.

Quoted 16 lines
drivers/net/ethernet/meta/fbnic/fbnic_netdev.c +6 -0
+		check = bpf->xsk_check.check;
+		prog = check->prog ? : READ_ONCE(fbn->xdp_prog);
+		return fbnic_xsk_validate(check, prog, bpf->xsk_check.extack);
+	}
 
 	if (bpf->command != XDP_SETUP_PROG)
 		return -EINVAL;
@@ -825,6 +841,8 @@ struct net_device *fbnic_netdev_alloc(struct fbnic_dev *fbd)
 	netdev->xdp_features = NETDEV_XDP_ACT_BASIC |
 			       NETDEV_XDP_ACT_REDIRECT |
 			       NETDEV_XDP_ACT_RX_SG;
+	netdev->xdp_features |= NETDEV_XDP_ACT_XSK_ZEROCOPY;
+	netdev->xdp_zc_max_segs = FBNIC_MAX_RX_BUFS;
 
 	netdev->min_mtu = IPV6_MIN_MTU;
 	netdev->max_mtu = FBNIC_MAX_JUMBO_FRAME_SIZE - ETH_HLEN;