Skip to contentSkip to conversation

xsk: Receive in the device's buffer layout

PATCH In review Björn Töpel 2 participants 18 messages Nov 24

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

cover xsk: Receive in the device's buffer layout

AF_XDP zero copy makes the device fill one UMEM chunk per buffer, at the UMEM headroom. Each driver carries a second RX path for this, and bends its RX geometry to fit. Packets that the device would split over several buffers, or pack several to a page, cannot be received without a copy. fbnic and bnxt have no AF_XDP zero copy at all.

This series lets an AF_XDP socket receive in the layout that the driver already uses for its page pool. The UMEM backs the page pools of the bound queue through a memory provider, which the socket installs with the queue management API, as devmem and io_uring zcrx install theirs. The device places buffers in UMEM chunks as it places them in pages: several buffers may share a chunk, a packet may span chunks, and the device picks the offsets. The XDP program redirects each packet to the socket through an XSKMAP, and each buffer becomes one RX descriptor. A FILL entry lends a whole chunk, and an RX descriptor with the new XDP_RX_CHUNK_FREE gives it back. This extends the AF_XDP uAPI, see the documentation patch (15):

- XDP_UMEM_DRV_LAYOUT, a UMEM registration flag, selects the device's buffer layout: aligned PAGE_SIZE chunks, no headroom.
- XDP_RX_CHUNK_FREE, an RX descriptor option, gives a chunk back. An empty descriptor (len 0) at a chunk gives it back when the device let go of the chunk after its last buffer reached the socket.
- FILL lends whole chunks, and RX descriptors may point anywhere in a chunk.
- A bind in the device's buffer layout requires XDP_USE_NEED_WAKEUP and fails with EINVAL without it, as only the wakeup restarts a queue that ran out of buffers.
- The bind needs a native XDP program, one socket per queue receives, and XDP_COPY fails.

This series replaces "xsk: Zero copy through page-pool memory providers" [1], see "The earlier series" below.

net_iovs stay unreadable
------------------------

For the core and the stack, UMEM chunks are net_iovs like any other. netmem_address() and skb_frag_address() give NULL for them, every net_iov frag still sets skb->unreadable, and page_pool_is_unreadable() is true for every provider, as in mainline. The series marks no provider readable and adds no readable capability.

Only XDP code reads the chunks, through an opt-in view (patch 1):

- A provider may give its net_iov area an XDP view: an address for each of its net_iovs. XDP code reads a net_iov only through xdp_netmem_address() and xdp_frag_address(), and only if its provider offers a view. The BPF helpers that read and write XDP buffers use them.

- Buffers with a view never become skb frags or xdp_frames. A reader that does not use the two helpers gets NULL, so it fails closed.

- dmabuf and io_uring zcrx offer no view, so nothing changes for them.

One check differs from mainline, and only for XDP-only providers (patch 3): netif_rxq_has_unreadable_mp() leaves them out. Drivers use it to turn on header split, but an XDP-only provider backs the headers too, and with header split each packet would take more buffers. page_pool_is_unreadable() is still true for such a provider, so bnxt sets up its separate head pool for the queue. Page mode never allocates from that pool, so it holds no pages.

The chunks are net_iovs and not pages because the UMEM is user memory, pinned with GUP:

- mm owns the struct page fields that page_pool takes over: lru, where pp_magic and pp live, and mapping.
- A chunk larger than a page, in a follow-up, lies inside a hugetlb folio and is not a page of its own.
- The provider keeps state per chunk, in the net_iov.

io_uring zcrx wraps pinned user pages in net_iovs for the same reasons.

Kernel structures stay out of UMEM
----------------------------------

Userspace may write the UMEM at any time, also while the kernel reads it, so the kernel puts none of its own structures there:

- The shared info of a multi-buffer packet lives in one buffer per RX queue, in kernel memory (patch 2). XDP_FLAGS_SINFO_EXT selects it. Whoever prepares the buffer sets the flag before adding fragments.

- No xdp_frame and no skb is built in a provider buffer (patch 5). The buffers go only to the AF_XDP socket of their queue. The core turns XDP_TX and XDP_PASS into XDP_DROP. Later patches add both:
the copy for XDP_PASS is in the full series, and XDP_TX from the buffer in place is later work, see Follow-ups. This series leaves them out to stay small. XDP_ABORTED and invalid verdicts reach the driver, which traces them and drops the packet. Frame conversion and skb construction refuse the buffers, so devmap and cpumap drop them.

- The kernel takes bounds only from its own fields, and only the program and its helpers read the bytes. A helper that checks bytes and reads them again must check a copy, as the syncookie helpers will, with a fix that goes to bpf separately.

Within these rules, XDP programs read and write the packet in place, fragments included. A one-buffer packet is a normal linear buffer on all three drivers, so programs without xdp.frags work.

How this extends memory providers
---------------------------------

The provider is a page_pool memory provider like devmem and io_uring
zcrx: alloc_netmems(), release_netmem(), init() and destroy(), installed per queue with the queue management API, and uninstalled when the socket unbinds or the device goes away. Drivers get zero copy from their page pool path, the path that they use for the stack and for XDP. They opt in with one page pool flag, take the address of an XDP head with xdp_netmem_address(), and put heads back by netmem. Driver code does not name AF_XDP.

The provider interface gains three things, each in its own patch:

- The XDP view (patch 1), see above.

- XDP-only providers (patch 3): MP_XDP_ONLY for a provider whose buffers go only to XDP. It backs every RX page pool of the queue, needs no header split, and native XDP may run next to it. A driver gets such memory only if it sets PP_FLAG_ALLOW_XDP_ONLY_NETMEM.

- hand_off() (patch 4): the last put of a net_iov that the provider marked goes to the provider instead of the pool cache, and the net_iov stays charged to the pool. AF_XDP gives a chunk back only once both the device and the socket are done with it.

The providers take page pool fragments: drivers split chunks as they split pages, and the hand-off also covers the fragment allocator.

Most of the size is AF_XDP's own contract, not provider plumbing:
chunk ownership through FILL, refill, delivery, give-back and teardown, in net/xdp/xsk_sink.c.

Code size
---------

The series adds 1793 lines and removes 139:

net/xdp/xsk_sink.[ch] +793 (185 of them comments, 99
blank; 26 functions)
rest of AF_XDP +139/-20 (xsk.c, xsk_buff_pool.c,
xdp_umem.c, headers)
XDP core, BPF helpers +228/-13 (xdp.h, xdp.c, netmem.h,
filter.c)
page_pool, providers +110/-14
netdev core +56/-3 (dev.c, netdevice.h,
ethtool rings.c)

  uAPI                       +30       (if_xdp.h and its tools copy)
  fbnic                      +34/-17   (15 of the added for

XDP_REDIRECT, which fbnic lacked)
mlx5 +17/-7
bnxt +23/-37
selftests +250/-27
documentation +113/-1

The sink takes no lock on delivery, as only the queue NAPI writes to the RX ring, and a queue restart stops the old NAPI before the new one runs.

Classic zero copy is a separate RX and TX path in each driver:
ice_xsk.c has 956 lines, mlx5's en/xsk/ 1019 (plus hooks in the rest of the driver), i40e_xsk.c 807, ixgbe_xsk.c 566, and idpf's xsk.c 641 (plus 272 in libeth).

We also wrote classic zero copy for fbnic, without this series. The first version added 1239 lines to fbnic and removed 163. A trimmed version adds 565 and removes 97 (TX is +156/-28 of that), plus 32 lines in xdp_sock_drv.h. This series changes fbnic by +19/-16 for RX, plus +15/-1 for XDP_REDIRECT, which classic zero copy needs too. Zero-copy TX, a follow-up, adds +65/-3 to fbnic. On the same host, on another day, the trimmed classic driver received 28.3 Mpps at 66 bytes; this series receives 27.6 Mpps, and 31.4 Mpps with the speed follow-ups.

The follow-ups, 26 patches in the full series, see Follow-ups:

xskxceiver timeout, 1 +29/-3

  speed, 4 patches             +154/-22   core only
  XDP_PASS copy, 3             +157/-16   bnxt +56/-2 of it
  zero-copy TX, 6              +555/-57   fbnic +65/-3, mlx5 +126/-6,
                                          bnxt +100/-2
  bnxt TX batching, 2           +38/-11
  larger chunks, 5             +167/-84   fbnic +21/-6, mlx5 +12/-5,
                                          bnxt +23/-15

mlx5 performance, 4 +121/-22
bnxt RX loop, 1 +13/-3

Unlike RX, TX needs code in each driver: the driver turns the socket's TX descriptors into device descriptors and completes them.

Generic pieces, and who else gains
----------------------------------

Patches 1-4 and 11 name no AF_XDP:

- Patch 1, the XDP view, works for any provider. io_uring zcrx, for example, could let XDP read its memory, while the stack keeps treating it as unreadable.

- Patch 2, shared info in kernel memory, works for any buffer. Classic zero copy keeps the shared info of a multi-buffer packet in the tail of the head's UMEM frame today, where userspace can change it while the kernel walks the fragments. It can move it out of UMEM with this flag, in a separate series. Buffers with the flag may also use the 320 bytes that the shared info took. No driver in this series packs its buffers tighter for that yet.

- Patches 3 and 11 serve any XDP-only provider, and patch 4 any provider that needs the last put of a net_iov.

Driver changes that help other users:

- fbnic supports XDP_REDIRECT (patch 9). Any native XDP program on fbnic can redirect to devmap, to cpumap and to AF_XDP sockets in copy mode. Before, the verdict was invalid and dropped the packet.

- mlx5 restarts a queue with an XDP program attached (patch 12), for any user of the queue management API. In the tree today only memory providers restart queues, and all but XDP-only ones refuse XDP, so nobody else gains yet.

- In the follow-ups, bnxt reports the VLAN tag of XDP buffers to any XDP program, and its inlined RX loop makes native XDP_DROP 3.6 % faster. Classic zero-copy TX counts its completions in the kernel, so userspace that writes the completion producer cannot change the kernel's count of descriptors in flight. The high-order page patches for mlx5, fbnic and bnxt work for any provider, but XDP-only ones are their only users in the tree today.

The bnxt fixes below help today's users, every busy-poll user and every queue restart with XDP attached, and a separate syncookie fix for bpf protects XDP programs on classic zero-copy queues.

Why a second zero-copy model
----------------------------

Classic zero copy hands the driver one UMEM chunk per RX buffer. The driver fills it at the UMEM headroom, through an AF_XDP RX path of its
own: ice, i40e, idpf and others have one, and mlx5 has a separate XSK RQ for it. The buffer size is the chunk size, so the driver cannot pack several packets into a page or split one packet the way it does for the stack. Teaching classic zero copy the device's layout would mean rewriting that RX path in every driver, and changing what a descriptor owns.

Here the device keeps its own layout, and the driver keeps its own RX path. Ownership moves from the buffer to the chunk: FILL lends a chunk, and the kernel gives it back with XDP_RX_CHUNK_FREE.

The two models serve different users. With classic zero copy, the application decides where each frame lands, one frame per chunk at a headroom it picks, or at any address with unaligned chunks. Applications that need that control keep it, and each driver pays for it with an AF_XDP RX path of its own. With the device's layout, the application gives up that control. The device decides where packets land and how many share a chunk, and the driver needs a few dozen lines on top of its existing RX path.

Classic zero copy stays as it is. A UMEM chooses the model when it is registered, with XDP_UMEM_DRV_LAYOUT, and nothing changes for UMEMs without the flag or for drivers with classic zero copy. Both models share the rings, the descriptors and the XSKMAP, and zero-copy TX in the device's layout, a follow-up, reuses the classic TX helpers.

On mlx5, which has both, classic zero copy is faster at MTU 1500:
24.5 Mpps at 66 bytes against 16.4 Mpps for this series, and 20.7 Mpps with the follow-ups, see Performance. With 16 KiB chunks, a follow-up, the device's layout passes it (25.9 Mpps). At MTU 5000, classic zero copy cannot bind, as the XSK RQ needs a linear RQ and has no multi-buffer. This series receives multi-buffer packets at any MTU.

uAPI
----

- XDP_UMEM_DRV_LAYOUT, a UMEM flag: aligned PAGE_SIZE chunks, no headroom. Binding needs a native XDP program, attached through netlink, and the program cannot be detached while the UMEM backs the queue. That ends when the receiving socket closes, even if a TX-only socket stays bound. One socket per queue receives; a second socket with an RX ring gets -EBUSY. Sockets that share the UMEM may transmit, in copy mode. XDP_COPY fails.

- A bind in the device's buffer layout requires XDP_USE_NEED_WAKEUP and fails with EINVAL without it. The drivers do not poll FILL: once FILL ran dry and the device used its posted buffers, only the wakeup from recvmsg() or poll() restarts the queue.
The kernel also asks for a wakeup while chunks wait for room in the RX ring, as only the queue NAPI gives them back.

- FILL lends whole chunks.

- RX descriptors point at the buffers that the device filled. XDP_PKT_CONTD chains the buffers of a packet. Metadata that the program wrote is in front of the first buffer.

- XDP_RX_CHUNK_FREE, a descriptor option: the kernel is done with the chunk of the descriptor, and the chunk is the application's again. If the device lets go of a chunk after its last buffer reached the socket, an empty descriptor (len 0) at the chunk carries the flag.

Ownership stays per chunk, as in classic AF_XDP. The application never returns single buffers, and a chunk that it got back can go on the TX ring. A held packet keeps its whole chunk.

Patches
-------

1     xdp: the XDP view of net_iovs, and the helpers that use it.
2     xdp: the shared info of a buffer in kernel memory.
3     XDP-only memory providers.
4     page_pool: hand_off() for the last put of a marked net_iov.
5     xdp: programs on buffers that must not hold kernel structures.
6     xsk: chunks lent to the page pools of a queue.
7     xsk: delivery to the socket, and chunks given back.
8     xsk: the uAPI. Nothing in 6 and 7 is reachable before this

patch.
9-10 fbnic: XDP_REDIRECT, then RX.
11 netif_rxq_has_xdp_only_mp(), for drivers that lay out a queue
before they create its page pools.
12-13 mlx5, bnxt.
14 A mode for xskxceiver.
15 Documentation.

Performance
-----------

Machines, one per NIC, all of one platform type:

CPU AMD EPYC 9D64, 88 cores, one socket, SMT on, DDR5-4800.
The test core ran at 2.95 GHz; acpi-cpufreq, performance governor, boost on.

  Kernel    mitigations=off, iommu=pt.
  fbnic     Meta fbnic, firmware 26.01.07-006, 50 Gb/s, PCIe 4.0 x4.
  mlx5      NVIDIA ConnectX-7 (MT2910), firmware 28.48.1000,
            50 Gb/s, PCIe 4.0 x4.
  bnxt      Broadcom BCM57504, firmware 232.0.159.4 (package
            232.1.136.4), 50 Gb/s, PCIe 4.0 x4.

Traffic comes from a second machine of the same type with xdp-trafficgen. One UDP flow lands on the measured queue.

One RX queue. The application, its NAPI and the IRQ share one core, with preferred busy polling (socket timeout 100 us, budget 256, batch 256). The UMEM has 16,384 chunks. The program redirects through an XSKMAP. Mpps and cycles per packet on that core, 66-byte frames, medians over two rounds of alternating boots:

               XDP_DROP     AF_XDP, busy poll   AF_XDP, epoll
  fbnic        38.8  (76)   27.6 (106)          26.6
  mlx5         31.6  (93)   16.4 (179)          16.2
  bnxt [2]     24.3         18.1 (162)          17.9

XDP_DROP is native XDP on the same kernel, without a provider. The rows ran on builds of this series on an older base. The sink has since lost its reserve stack and backlog; A/B
runs of that change measured level on all three NICs, with equal or fewer instructions per packet. At MTU 1500, mlx5 puts one packet in each 4 KiB chunk, as its strides keep room for the shared info of an skb, so every packet costs a FILL entry, a refill and a give-back.

On mlx5, classic zero copy through the XSK RQ receives 24.5 Mpps
(120) on the same host.

fbnic, bnxt and mlx5 run at line rate with 9000-byte frames, which XDP multi-buffer receives as three 4 KiB chunks. The UMEM must hold more chunks than the queue keeps posted: at MTU 9000, mlx5 posts four pages per RX ring entry, up to 16,384 pages, so the 9000-byte runs used 65,536 chunks against 16,384 elsewhere.

[2] With "eth: bnxt: Ring the NQ doorbell during busy poll" and "eth:
bnxt: Do not reset TX queue 0 BQL for XDP rings", see Dependencies.

Programs that use no provider see no measurable change in packet rate with native XDP_DROP, as the variation stays within the 3 % that code layout alone causes. The series adds about 6 instructions per packet on fbnic, and under 3 on mlx5 and bnxt, for the net_iov test in xdp_netmem_address() and the static key of the sink verdict.

What the follow-ups do to the AF_XDP busy-poll test above, measured one part at a time on top of this series, as a share of native XDP_DROP on the same kernel:

                                fbnic          mlx5          bnxt
  this series                   27.6 (71 %)    16.4 (52 %)   18.0 (73 %)
  + speed                       31.4 (83 %)    16.7 (53 %)   18.9 (77 %)
  + mlx5 performance            -              20.8 (67 %)   -
  whole series, 4 KiB chunks    31.0 (85 %)    20.7 (68 %)   18.6 (76 %)
  whole series, 16 KiB chunks   35.9 (99 %)    25.9 (86 %)   20.6 (83 %)
  whole series, 32 KiB chunks   -              -             21.0 (85 %)
  whole series, 128 KiB chunks  37.4 (103 %)   27.1 (90 %)   -

The XDP_PASS copy and TX do not change the redirect path. Larger chunks need huge-page UMEM. With 16 KiB chunks and more, fbnic receives into an AF_XDP socket at the rate of native XDP_DROP. On bnxt the sink stays about 18 cycles per packet above native: native XDP_DROP reuses the RX buffer in place, and the sink takes a new buffer for every packet.

At MTU 5000, with the follow-ups and 16 KiB chunks, on one RX queue, medians over two boots. At 300, 1500 and 5000 bytes, cycles per packet on interrupts; at 66 bytes, Mpps with busy poll:

                         300 B   1500 B   5000 B    66 B
  fbnic  AF_XDP            354      322      565    35.9
         XDP_DROP          204      184      447    36.8
  mlx5   AF_XDP            323      374      418    22.9
         XDP_DROP          165      211      381    36.6
  bnxt   AF_XDP            380      336      802    20.5
         XDP_DROP          116      197      534    26.2

At 1500 and 5000 bytes both receive at line rate, so the table gives the work per packet of the receiving core, with RX interrupt coalescing of 33 us or 88 frames. That cost depends on the coalescing, and with busy poll the core spins whatever the rate. At 300 bytes the AF_XDP column counts two cores, NAPI and the application. fbnic ran on another pair of machines, with firmware 25.08.05-004 and an AF_XDP generator in copy mode.

With 4 KiB chunks at this MTU, mlx5 keeps a nonlinear RQ and costs 700 cycles at 5000 bytes, as does this series alone (699). Classic mlx5 zero copy cannot bind at MTU 5000.

Zero-copy TX, a follow-up, at 66 bytes on one core: fbnic 35.3 Mpps, mlx5 29.5, bnxt 35.8, against 1.0 to 2.4 Mpps in copy mode.

Dependencies
------------

These fixes go separately:

- "eth: bnxt: Ring the NQ doorbell during busy poll", for net. Without it, a busy-polled bnxt queue stalls.

- "eth: bnxt: Do not reset TX queue 0 BQL for XDP rings", for net. With TPH, every RX queue restart with XDP attached resets BQL of TX queue 0, and the next completion there hits the BUG in dql_completed(). Binding and unbinding an AF_XDP socket in this mode restarts the queue with XDP attached.

Follow-ups
----------

The full series, 42 patches with the syncookie fix, is at
https://github.com/fb-bjorn/linux/tree/xsk-device-v1. Each part comes with its own numbers, see Performance.

- Speed: a kfunc that redirects to the queue's socket without an XSKMAP, batched reference drops, a path for one-buffer packets, and a prefetch of FILL chunks.

- XDP_PASS: the stack gets a copy instead of a drop. bnxt first reports the VLAN tag of XDP buffers, and offers XDP-only providers only in legacy eswitch mode, as the copy would otherwise reach the PF instead of the representor.

- Zero-copy TX in the device's buffer layout for fbnic, mlx5 and bnxt, with no uAPI change, and one completion per TX batch on bnxt.

- Larger chunks: 16 KiB to 128 KiB chunks in huge pages, through the rx_page_size of the queue.

- mlx5: keep XDP-only RQs linear above a page-sized MTU, so that larger chunks hold several packets at MTU 5000, flush redirects after reposting WQEs, let go of a page after its last stride, and skip head prefetches.

- bnxt: inline RX packets into the completion loop.

Later work, not in the full series:

- Small MTUs on mlx5: leave the shared info out of the strides of XDP-only RQs, two packets per 4 KiB chunk at MTU 1500. It takes this series from 16.4 to 19.6 Mpps on mlx5, but cannot act above MTU 1770.

- XDP_TX for these buffers, sent from the buffer in place.

- Classic zero copy with its shared info in kernel memory, with the flag from patch 2.

The earlier series
------------------

"[PATCH net-next v1 00/11] xsk: Zero copy through page-pool memory providers" [1], posted on 10 Nov 2026, kept the application's buffer layout, one UMEM chunk per buffer at the UMEM headroom, behind a memory provider that the core could read. This series is new rather than a version of it, and answers the review there:

- The device's buffer layout instead of the application's. The device places buffers in chunks as it places them in pages, and ownership moves from the buffer to the chunk.

- Providers stay unreadable to the core and the stack. There is no readable capability: XDP alone reads provider memory, through an opt-in view. The providers take page pool fragments.

- Smaller driver changes, and no AF_XDP code in drivers. The earlier series changed 651 lines of fbnic, its only driver. This one changes 51 lines of fbnic, 24 of mlx5 and 60 of bnxt for RX.

Open questions
--------------

- Shared info outside the buffer: one per RX queue behind a flag, as here, or a pointer in struct xdp_buff that classic zero copy can use as well?

- Provider buffers are told by their address in xdp_prepare_buff(), with one range check under a static key. Is that fine, or should drivers mark them?

- MAINTAINERS needs an entry for net/xdp/xsk_sink.c.

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

Björn Töpel (15):
xdp: Let memory providers offer XDP a view of their net_iovs
xdp: Keep the shared info of a buffer in kernel memory
net: Add memory providers that only feed XDP
page_pool: Let memory providers take back net_iovs
xdp: Run programs on buffers that must not hold kernel structures
xsk: Lend UMEM chunks to the page pools of a queue
xsk: Deliver to the socket in the device's buffer layout
xsk: Receive in the device's buffer layout
eth: fbnic: Support XDP redirect
eth: fbnic: Receive into XDP-only memory providers
net: Add netif_rxq_has_xdp_only_mp()
eth: mlx5e: Receive into XDP-only memory providers
eth: bnxt: Receive into XDP-only memory providers
selftests: net: xsk: Test the device's RX buffer layout
Documentation: networking: Describe AF_XDP RX in the device's layout

 Documentation/networking/af_xdp.rst           | 114 ++-
 drivers/net/ethernet/broadcom/bnxt/bnxt.c     |  39 +-
 drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.c |  19 +-
 drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.h |   2 +-
 .../net/ethernet/mellanox/mlx5/core/en_main.c |  14 +-
 .../net/ethernet/mellanox/mlx5/core/en_rx.c   |  10 +-
 .../net/ethernet/meta/fbnic/fbnic_netdev.c    |   3 +-
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c  |  45 +-
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h  |   3 +
 include/linux/netdevice.h                     |   3 +
 include/net/netdev_queues.h                   |   1 +
 include/net/netmem.h                          |  21 +-
 include/net/page_pool/memory_provider.h       |  21 +
 include/net/page_pool/types.h                 |  15 +-
 include/net/xdp.h                             | 131 ++-
 include/net/xdp_sock.h                        |   8 +
 include/net/xsk_buff_pool.h                   |   3 +
 include/uapi/linux/if_xdp.h                   |  15 +
 net/core/dev.c                                |  51 +-
 net/core/filter.c                             |  17 +-
 net/core/netdev_rx_queue.c                    |  51 +-
 net/core/page_pool.c                          |  36 +-
 net/core/xdp.c                                |  72 +-
 net/ethtool/rings.c                           |   5 +-
 net/xdp/Kconfig                               |   1 +
 net/xdp/Makefile                              |   2 +-
 net/xdp/xdp_umem.c                            |   5 +
 net/xdp/xsk.c                                 | 110 ++-
 net/xdp/xsk_buff_pool.c                       |  30 +-
 net/xdp/xsk_sink.c                            | 773 ++++++++++++++++++
 net/xdp/xsk_sink.h                            |  20 +
 tools/include/uapi/linux/if_xdp.h             |  15 +
 .../testing/selftests/net/lib/xsk/test_xsk.c  | 248 +++++-
 .../testing/selftests/net/lib/xsk/test_xsk.h  |   4 +
 .../selftests/net/lib/xsk/xskxceiver.c        |  25 +-
 35 files changed, 1793 insertions(+), 139 deletions(-)
 create mode 100644 net/xdp/xsk_sink.c
 create mode 100644 net/xdp/xsk_sink.h

base-commit: 57f165ff2f30491bc3511d24a52ca516751a268b

Signature · 1 line
2.56.1
#1 lore raw

PATCH 1/15 xdp: Let memory providers offer XDP a view of their net_iovs

Currently, a net_iov is memory that the kernel does not read. netmem_address() and skb_frag_address() give NULL for it, and XDP code, which takes buffer addresses the same way, cannot read it either. Some providers back net_iovs with memory that the CPU can reach and XDP must read, such as the UMEM of an AF_XDP socket that receives in the device's buffer layout, later in this series. io_uring zcrx could do the same.

Such memory is net_iov and not pages because it is user memory pinned with GUP. mm owns the struct page fields that page_pool takes over (lru, where pp_magic and pp live, and mapping), a chunk larger than a page lies inside a hugetlb folio instead of being a page of its own, and the provider keeps state per chunk. io_uring zcrx wraps pinned user pages in net_iovs for the same reasons.

Let a net_iov area offer an XDP view, an address for each of its net_iovs that XDP code may read and write. Add xdp_netmem_address() for the head of an XDP buffer and xdp_frag_address() for its fragments, and use them in bpf_xdp_pointer(), bpf_xdp_copy_buf(), bpf_xdp_pull_data() and the tail growth of bpf_xdp_adjust_tail().

The area keeps the address and size of the view and the log2 of the net_iov size, so net_iov i lies at xdp_vaddr + (i << xdp_shift). For pages the helpers give page_address(), and for a net_iov without a view they give NULL. dmabuf and io_uring zcrx areas are allocated zeroed, so they offer no view. AF_XDP sinks are the first to offer one.

XDP may read a net_iov only through these helpers, and only if its provider offers a view. Such buffers must not become skb frags or xdp_frames. For the core and the stack every net_iov stays unreadable, netmem_address() and skb_frag_address() still give NULL, and skb->unreadable is still set for every net_iov frag. Other readers get NULL for a net_iov with a view too, so they fail closed.

The other rules for providers stay. Native XDP runs next to a provider only if it opts in, and providers without an XDP view still need header split. AF_XDP sinks are exempt from both through MP_XDP_ONLY.

---
 include/net/netmem.h |  8 ++++++++
 include/net/xdp.h    | 34 ++++++++++++++++++++++++++++++++++
 net/core/filter.c    |  8 ++++----
 3 files changed, 46 insertions(+), 4 deletions(-)
include/net/netmem.h +8 -0
index fb693bc1702a..4cf4ee1cd55d 100644
@@ -104,6 +104,14 @@ struct net_iov_area {
 	/* Array of net_iovs for this area. */
 	struct net_iov *niovs;
 	size_t num_niovs;
+	/* XDP view, see xdp_netmem_address(): XDP may read and write net_iov i
+	 * at xdp_vaddr + (i << xdp_shift), xdp_vsize bytes in all. NULL if the
+	 * provider offers none. The core and the stack take every net_iov as
+	 * unreadable either way.
+	 */
+	void *xdp_vaddr;
+	size_t xdp_vsize;
+	unsigned int xdp_shift;
 };
 
 static inline struct net_iov_area *net_iov_owner(const struct net_iov *niov)
include/net/xdp.h +34 -0
index 07231adfb5f8..1629e347b71f 100644
@@ -164,6 +164,40 @@ xdp_init_buff(struct xdp_buff *xdp, u32 frame_sz, struct xdp_rxq_info *rxq)
 #endif
 }
 
+/* XDP view of net_iovs: a memory provider may give XDP an address for its
+ * net_iovs, see &net_iov_area.xdp_vaddr. XDP code may read and write a
+ * net_iov only through these helpers, and only if its provider offers a
+ * view; such buffers must not become skb frags or xdp_frames. For the core
+ * and the stack every net_iov stays unreadable: netmem_address() and
+ * skb_frag_address() give NULL for it. A net_iov without a view gives NULL
+ * here too, so a reader that does not use these helpers fails closed.
+ */
+static __always_inline void *xdp_net_iov_address(const struct net_iov *niov)
+{
+	const struct net_iov_area *area = net_iov_owner(niov);
+
+	if (!area->xdp_vaddr)
+		return NULL;
+	return area->xdp_vaddr +
+	       ((unsigned long)net_iov_idx(niov) << area->xdp_shift);
+}
+
+/* Address of @netmem, which a driver uses as the head of an XDP buffer */
+static __always_inline void *xdp_netmem_address(netmem_ref netmem)
+{
+	if (netmem_is_net_iov(netmem))
+		return xdp_net_iov_address(netmem_to_net_iov(netmem));
+	return __netmem_address(netmem);
+}
+
+/* Address of the bytes of @frag of an XDP buffer */
+static __always_inline void *xdp_frag_address(const skb_frag_t *frag)
+{
+	void *addr = xdp_netmem_address(skb_frag_netmem(frag));
+
+	return addr ? addr + skb_frag_off(frag) : NULL;
+}
+
 static __always_inline void
 xdp_prepare_buff(struct xdp_buff *xdp, unsigned char *hard_start,
 		 int headroom, int data_len, const bool meta_valid)
net/core/filter.c +4 -4
index f42ecfb5841f..d5774b2577e7 100644
@@ -4310,7 +4310,7 @@ void bpf_xdp_copy_buf(struct xdp_buff *xdp, unsigned long off,
 			break;
 
 		ptr_off += ptr_len;
-		ptr_buf = skb_frag_address(next_frag);
+		ptr_buf = xdp_frag_address(next_frag);
 		ptr_len = skb_frag_size(next_frag);
 		next_frag++;
 	}
@@ -4338,7 +4338,7 @@ void *bpf_xdp_pointer(struct xdp_buff *xdp, u32 offset, u32 len)
 		u32 frag_size = skb_frag_size(&sinfo->frags[i]);
 
 		if  (offset < frag_size) {
-			addr = skb_frag_address(&sinfo->frags[i]);
+			addr = xdp_frag_address(&sinfo->frags[i]);
 			size = frag_size;
 			break;
 		}
@@ -4429,7 +4429,7 @@ static int bpf_xdp_frags_increase_tail(struct xdp_buff *xdp, int offset)
 	if (unlikely(offset > tailroom))
 		return -EINVAL;
 
-	memset(skb_frag_address(frag) + skb_frag_size(frag), 0, offset);
+	memset(xdp_frag_address(frag) + skb_frag_size(frag), 0, offset);
 	skb_frag_size_add(frag, offset);
 	sinfo->xdp_frags_size += offset;
 	if (rxq->mem.type == MEM_TYPE_XSK_BUFF_POOL)
@@ -12835,7 +12835,7 @@ __bpf_kfunc int bpf_xdp_pull_data(struct xdp_md *x, u32 len)
 		skb_frag_t *frag = &sinfo->frags[i];
 		u32 shrink = min_t(u32, delta, skb_frag_size(frag));
 
-		memcpy(xdp->data_end, skb_frag_address(frag), shrink);
+		memcpy(xdp->data_end, xdp_frag_address(frag), shrink);
 
 		xdp->data_end += shrink;
 		sinfo->xdp_frags_size -= shrink;
Signature · 1 line
2.56.1
#2 lore raw

PATCH 2/15 xdp: Keep the shared info of a buffer in kernel memory

In reply to Björn Töpel

Currently, the shared info of an XDP buffer, with the fragment list of a multi-buffer packet, lives at the end of the buffer's frame, in memory that the device writes. Helpers follow its fragments, drivers free them through it, and frame and skb conversion copy it, so memory that others may write while the kernel uses it must not hold it. Classic AF_XDP zero copy keeps it in the tail of a UMEM chunk, where userspace can rewrite it.

Let an RX queue keep the shared info of its buffers in kernel memory. The queue gets one from xdp_rxq_info_reg_ext_sinfo(), and xdp_rxq_info_unreg_mem_model() frees it. A buffer with the new XDP_FLAGS_SINFO_EXT finds its shared info there.

Whoever prepares a buffer sets the flag before adding fragments. The queue NAPI builds one buffer at a time, so one shared info per queue is enough. It is valid until the buffer is redirected, dropped or copied. Frame conversion and skb construction refuse buffers with the flag, as a frame or an skb would keep its shared info in the buffer. Nothing sets the flag until later in this series.

xdp_data_hard_end() reserves no shared-info tailroom for such a buffer, so its data may reach the end of the frame. frame_sz then bounds every write past the data, such as tail growth and bpf_xdp_pull_data(), so the frame must not cover memory of other buffers. Drivers may then pack such buffers tighter.

---
 include/net/xdp.h | 41 +++++++++++++++++++++++++++++++++++------
 net/core/xdp.c    | 30 ++++++++++++++++++++++++++++++
 2 files changed, 65 insertions(+), 6 deletions(-)
include/net/xdp.h +35 -6
index 1629e347b71f..944418111a86 100644
@@ -65,6 +65,11 @@ struct xdp_rxq_info {
 	u32 reg_state;
 	struct xdp_mem_info mem;
 	u32 frag_size;
+	/* Shared info of buffers with %XDP_FLAGS_SINFO_EXT, in kernel
+	 * memory, see xdp_rxq_info_reg_ext_sinfo(). The queue builds one
+	 * such buffer at a time.
+	 */
+	struct skb_shared_info *ext_sinfo;
 } ____cacheline_aligned; /* perf critical, avoid false-sharing */
 
 struct xdp_txq_info {
@@ -81,6 +86,15 @@ enum xdp_buff_flags {
 	 * XDP program is not attached.
 	 */
 	XDP_FLAGS_FRAGS_UNREADABLE	= BIT(2),
+	/* The shared info lives in &xdp_rxq_info.ext_sinfo, in kernel memory,
+	 * not at the end of the frame. For memory that someone outside the
+	 * kernel may write. Whoever prepares the buffer sets it before adding
+	 * fragments, on a queue that has ext_sinfo. The queue NAPI builds one
+	 * such buffer at a time: its shared info is valid until the buffer
+	 * is redirected, dropped or copied. The data may reach the end of the
+	 * frame, see xdp_data_hard_end(): the frame must hold nothing else.
+	 */
+	XDP_FLAGS_SINFO_EXT		= BIT(3),
 };
 
 struct xdp_buff {
@@ -212,17 +226,27 @@ xdp_prepare_buff(struct xdp_buff *xdp, unsigned char *hard_start,
 
 /* Reserve memory area at end-of data area.
  *
- * This macro reserves tailroom in the XDP buffer by limiting the
- * XDP/BPF data access to data_hard_end.  Notice same area (and size)
- * is used for XDP_PASS, when constructing the SKB via build_skb().
+ * This reserves tailroom in the XDP buffer by limiting the XDP/BPF data
+ * access to data_hard_end.  Notice same area (and size) is used for
+ * XDP_PASS, when constructing the SKB via build_skb(). Buffers with
+ * %XDP_FLAGS_SINFO_EXT keep the shared info elsewhere and reserve none.
  */
-#define xdp_data_hard_end(xdp)				\
-	((xdp)->data_hard_start + (xdp)->frame_sz -	\
-	 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)))
+static __always_inline void *xdp_data_hard_end(const struct xdp_buff *xdp)
+{
+	u32 tailroom = SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
+
+	if (xdp->flags & XDP_FLAGS_SINFO_EXT)
+		tailroom = 0;
+	return xdp->data_hard_start + xdp->frame_sz - tailroom;
+}
 
 static inline struct skb_shared_info *
 xdp_get_shared_info_from_buff(const struct xdp_buff *xdp)
 {
+	/* Kernel structures stay out of memory that userspace may write */
+	if (unlikely(xdp->flags & XDP_FLAGS_SINFO_EXT))
+		return xdp->rxq->ext_sinfo;
+
 	return (struct skb_shared_info *)xdp_data_hard_end(xdp);
 }
 
@@ -454,6 +478,10 @@ int xdp_update_frame_from_buff(const struct xdp_buff *xdp,
 		return -ENOSPC;
 	}
 
+	/* A frame keeps its shared info in the buffer */
+	if (unlikely(xdp->flags & XDP_FLAGS_SINFO_EXT))
+		return -EFAULT;
+
 	xdp_frame->data = xdp->data;
 	xdp_frame->len  = xdp->data_end - xdp->data;
 	xdp_frame->headroom = headroom - sizeof(*xdp_frame);
@@ -533,6 +561,7 @@ bool xdp_rxq_info_is_reg(struct xdp_rxq_info *xdp_rxq);
 int xdp_rxq_info_reg_mem_model(struct xdp_rxq_info *xdp_rxq,
 			       enum xdp_mem_type type, void *allocator);
 void xdp_rxq_info_unreg_mem_model(struct xdp_rxq_info *xdp_rxq);
+int xdp_rxq_info_reg_ext_sinfo(struct xdp_rxq_info *xdp_rxq);
 int xdp_reg_mem_model(struct xdp_mem_info *mem,
 		      enum xdp_mem_type type, void *allocator);
 void xdp_unreg_mem_model(struct xdp_mem_info *mem);
net/core/xdp.c +30 -0
index 1d679e8fd649..3472b03ee661 100644
@@ -142,6 +142,8 @@ void xdp_rxq_info_unreg_mem_model(struct xdp_rxq_info *xdp_rxq)
 	}
 
 	xdp_unreg_mem_model(&xdp_rxq->mem);
+	kfree(xdp_rxq->ext_sinfo);
+	xdp_rxq->ext_sinfo = NULL;
 }
 EXPORT_SYMBOL_GPL(xdp_rxq_info_unreg_mem_model);
 
@@ -368,6 +370,30 @@ int xdp_rxq_info_reg_mem_model(struct xdp_rxq_info *xdp_rxq,
 
 EXPORT_SYMBOL_GPL(xdp_rxq_info_reg_mem_model);
 
+/**
+ * xdp_rxq_info_reg_ext_sinfo - keep the shared info of buffers in the queue
+ * @xdp_rxq: registered RX queue
+ *
+ * For buffers in memory that someone outside the kernel may write: those
+ * with %XDP_FLAGS_SINFO_EXT keep their shared info in kernel memory of
+ * @xdp_rxq instead of at the end of their frame.
+ * xdp_rxq_info_unreg_mem_model() frees it.
+ *
+ * Return: 0 on success, or a negative errno.
+ */
+int xdp_rxq_info_reg_ext_sinfo(struct xdp_rxq_info *xdp_rxq)
+{
+	if (xdp_rxq->reg_state != REG_STATE_REGISTERED) {
+		WARN(1, "Missing register, driver bug");
+		return -EFAULT;
+	}
+
+	if (!xdp_rxq->ext_sinfo)
+		xdp_rxq->ext_sinfo = kzalloc_obj(*xdp_rxq->ext_sinfo);
+	return xdp_rxq->ext_sinfo ? 0 : -ENOMEM;
+}
+EXPORT_SYMBOL_GPL(xdp_rxq_info_reg_ext_sinfo);
+
 /**
  * xdp_reg_page_pool - register &page_pool as a memory provider for XDP
  * @pool: &page_pool to register
@@ -638,6 +664,10 @@ struct sk_buff *xdp_build_skb_from_buff(const struct xdp_buff *xdp)
 	u32 nr_frags = 0;
 	int metalen;
 
+	/* An skb keeps its shared info in the buffer */
+	if (unlikely(xdp->flags & XDP_FLAGS_SINFO_EXT))
+		return NULL;
+
 	if (unlikely(xdp_buff_has_frags(xdp))) {
 		sinfo = xdp_get_shared_info_from_buff(xdp);
 		nr_frags = sinfo->nr_frags;
Signature · 1 line
2.56.1
#3 lore raw

PATCH 3/15 net: Add memory providers that only feed XDP

In reply to Björn Töpel

Currently, memory providers serve the payload of a header-split queue to the stack. The core requires tcp-data-split with a zero threshold for them, and refuses native XDP next to them. An AF_XDP socket that receives in the device's buffer layout, later in this series, needs a provider whose buffers go only to XDP, never to the stack. It backs every RX page pool of the queue, so that the device places packets as it does in pages, and native XDP must run to steer the packets.

Let a provider declare itself XDP-only with MP_XDP_ONLY, and spare it the checks that only make sense for payload providers.

An XDP-only provider needs no header split and does not block native XDP. A page pool takes an XDP-only provider only if the driver opts in with PP_FLAG_ALLOW_XDP_ONLY_NETMEM. Otherwise installing the provider fails, as for other providers, so neither a driver that did not opt in nor a pool that takes unreadable memory gets XDP-only memory by accident.

Like any provider, an XDP-only one is unreadable to page_pool_is_unreadable(), as the core and the stack never read its memory. netif_rxq_has_unreadable_mp(), which drivers use to turn on header split, leaves XDP-only providers out, as they back the headers too and header split would only spread packets over more buffers. Userspace may write the buffers at any time, so the kernel must keep its own data out of them, which the next patches do.

---
 include/linux/netdevice.h               |  1 +
 include/net/page_pool/memory_provider.h | 15 ++++++++++++++
 include/net/page_pool/types.h           | 14 +++++++++++--
 net/core/dev.c                          | 21 ++++++++++++++++++--
 net/core/netdev_rx_queue.c              | 26 +++++++++++++++++--------
 net/core/page_pool.c                    | 16 ++++++++++++---
 net/ethtool/rings.c                     |  5 ++++-
 7 files changed, 82 insertions(+), 16 deletions(-)
include/linux/netdevice.h +1 -0
index 0325c6f2a7d1..5fd2bec1178a 100644
@@ -4458,6 +4458,7 @@ u8 dev_xdp_sb_prog_count(struct net_device *dev);
 u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode);
 
 u32 dev_get_min_mp_channel_count(const struct net_device *dev);
+bool dev_mp_blocks_xdp(const struct net_device *dev);
 
 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb);
 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb);
include/net/page_pool/memory_provider.h +15 -0
index bceb5f7740e2..d52c7a450c68 100644
@@ -19,6 +19,20 @@ struct sk_buff;
  * Per-provider custom logic must be delegated to memory_provider_ops rather
  * than handled directly in page_pool core code.
  */
+
+/**
+ * enum mp_flags - how a memory provider differs from the default
+ * @MP_XDP_ONLY: Only XDP consumes the buffers: they never reach the stack.
+ *	They back the RX page pools of the queue that set
+ *	%PP_FLAG_ALLOW_XDP_ONLY_NETMEM, so header split is not needed, and
+ *	native XDP may run next to them.
+ *	XDP may read them, but userspace may write them at any time,
+ *	so the kernel must keep its own data out of them.
+ */
+enum mp_flags {
+	MP_XDP_ONLY		= BIT(0),
+};
+
 struct memory_provider_ops {
 	netmem_ref (*alloc_netmems)(struct page_pool *pool, gfp_t gfp);
 	bool (*release_netmem)(struct page_pool *pool, netmem_ref netmem);
@@ -27,6 +41,7 @@ struct memory_provider_ops {
 	int (*nl_fill)(void *mp_priv, struct sk_buff *rsp,
 		       struct netdev_rx_queue *rxq);
 	void (*uninstall)(void *mp_priv, struct netdev_rx_queue *rxq);
+	u32 flags;
 };
 
 bool net_mp_niov_set_dma_addr(struct net_iov *niov, dma_addr_t addr);
include/net/page_pool/types.h +12 -2
index 6d543076a0c0..35d4dc45db6a 100644
@@ -31,8 +31,18 @@
  */
 #define PP_FLAG_ALLOW_UNREADABLE_NETMEM BIT(3)
 
+/*
+ * Allow an XDP-only memory provider of the queue (%MP_XDP_ONLY) to back the
+ * pool. The driver registers the pool as the memory model of the RX queue,
+ * sets up XDP buffers with xdp_prepare_buff() at xdp_netmem_address() of
+ * their head, and puts heads back by netmem, not by address.
+ */
+#define PP_FLAG_ALLOW_XDP_ONLY_NETMEM BIT(4)
+
 #define PP_FLAG_ALL		(PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV | \
-				 PP_FLAG_SYSTEM_POOL | PP_FLAG_ALLOW_UNREADABLE_NETMEM)
+				 PP_FLAG_SYSTEM_POOL | \
+				 PP_FLAG_ALLOW_UNREADABLE_NETMEM | \
+				 PP_FLAG_ALLOW_XDP_ONLY_NETMEM)
 
 /* Index limit to stay within PP_DMA_INDEX_BITS for DMA indices */
 #define PP_DMA_INDEX_LIMIT XA_LIMIT(1, BIT(PP_DMA_INDEX_BITS) - 1)
@@ -82,7 +92,7 @@ struct pp_alloc_cache {
  * @netdev:	netdev this pool will serve (leave as NULL if none or multiple)
  * @queue_idx:	queue idx this page_pool is being created for.
  * @flags:	PP_FLAG_DMA_MAP, PP_FLAG_DMA_SYNC_DEV, PP_FLAG_SYSTEM_POOL,
- *		PP_FLAG_ALLOW_UNREADABLE_NETMEM.
+ *		PP_FLAG_ALLOW_UNREADABLE_NETMEM, PP_FLAG_ALLOW_XDP_ONLY_NETMEM.
  */
 struct page_pool_params {
 	struct_group_tagged(page_pool_params_fast, fast,
net/core/dev.c +19 -2
index 4ca8a9f5a7a5..8a1d5a284e53 100644
@@ -10645,7 +10645,7 @@ int netif_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
 			return -EBUSY;
 		}
 
-		if (dev_get_min_mp_channel_count(dev)) {
+		if (dev_mp_blocks_xdp(dev)) {
 			NL_SET_ERR_MSG(bpf->extack,
 				       "unable to propagate XDP to device using memory provider");
 			return -EBUSY;
@@ -10726,7 +10726,7 @@ static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
 				       "unable to install XDP to device using tcp-data-split");
 			return -EBUSY;
 		}
-		if (dev_get_min_mp_channel_count(dev)) {
+		if (dev_mp_blocks_xdp(dev)) {
 			NL_SET_ERR_MSG(extack,
 				       "unable to install XDP to device using memory provider");
 			return -EBUSY;
@@ -11146,6 +11146,23 @@ int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
 	return err;
 }
 
+/* Native XDP runs next to XDP-only providers only, see %MP_XDP_ONLY */
+bool dev_mp_blocks_xdp(const struct net_device *dev)
+{
+	const struct memory_provider_ops *ops;
+	unsigned int i;
+
+	netdev_assert_locked_ops_compat(dev);
+
+	for (i = 0; i < dev->real_num_rx_queues; i++) {
+		ops = dev->_rx[i].mp_params.mp_ops;
+		if (ops && !(ops->flags & MP_XDP_ONLY))
+			return true;
+	}
+
+	return false;
+}
+
 u32 dev_get_min_mp_channel_count(const struct net_device *dev)
 {
 	int i;
net/core/netdev_rx_queue.c +18 -8
index a7261fedd5e7..2e10201fc0c0 100644
@@ -79,12 +79,18 @@ __netif_get_rx_queue_lease(struct net_device **dev, unsigned int *rxq_idx,
 	return rxq;
 }
 
-/* See also page_pool_is_unreadable() */
+/* See also page_pool_is_unreadable(). An XDP-only provider backs the headers
+ * too, so its queue needs no header split, see %MP_XDP_ONLY.
+ */
 bool netif_rxq_has_unreadable_mp(struct net_device *dev, unsigned int rxq_idx)
 {
-	if (rxq_idx < dev->real_num_rx_queues)
-		return __netif_get_rx_queue(dev, rxq_idx)->mp_params.mp_ops;
-	return false;
+	const struct memory_provider_ops *ops;
+
+	if (rxq_idx >= dev->real_num_rx_queues)
+		return false;
+
+	ops = __netif_get_rx_queue(dev, rxq_idx)->mp_params.mp_ops;
+	return ops && !(ops->flags & MP_XDP_ONLY);
 }
 EXPORT_SYMBOL(netif_rxq_has_unreadable_mp);
 
@@ -189,6 +195,7 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 			       struct netlink_ext_ack *extack)
 {
 	const struct netdev_queue_mgmt_ops *qops = dev->queue_mgmt_ops;
+	bool xdp_only = p->mp_ops->flags & MP_XDP_ONLY;
 	struct netdev_queue_config qcfg[2];
 	struct netdev_rx_queue *rxq;
 	int ret;
@@ -196,15 +203,17 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 	if (!qops)
 		return -EOPNOTSUPP;
 
-	if (dev->cfg->hds_config != ETHTOOL_TCP_DATA_SPLIT_ENABLED) {
+	/* An XDP-only provider backs headers too, and runs next to XDP */
+	if (!xdp_only &&
+	    dev->cfg->hds_config != ETHTOOL_TCP_DATA_SPLIT_ENABLED) {
 		NL_SET_ERR_MSG(extack, "tcp-data-split is disabled");
 		return -EINVAL;
 	}
-	if (dev->cfg->hds_thresh) {
+	if (!xdp_only && dev->cfg->hds_thresh) {
 		NL_SET_ERR_MSG(extack, "hds-thresh is not zero");
 		return -EINVAL;
 	}
-	if (dev_xdp_prog_count(dev)) {
+	if (!xdp_only && dev_xdp_prog_count(dev)) {
 		NL_SET_ERR_MSG(extack, "unable to custom memory provider to device with XDP program attached");
 		return -EEXIST;
 	}
@@ -219,7 +228,8 @@ static int __netif_mp_open_rxq(struct net_device *dev, unsigned int rxq_idx,
 		return -EEXIST;
 	}
 #ifdef CONFIG_XDP_SOCKETS
-	if (rxq->pool) {
+	/* Only the AF_XDP socket of the queue installs an XDP-only provider */
+	if (rxq->pool && !xdp_only) {
 		NL_SET_ERR_MSG(extack, "designated queue already in use by AF_XDP");
 		return -EBUSY;
 	}
net/core/page_pool.c +13 -3
index d7c88c0b67e5..8a1ea21ccdcd 100644
@@ -272,12 +272,22 @@ static int page_pool_init(struct page_pool *pool,
 
 	xa_init_flags(&pool->dma_mapped, XA_FLAGS_ALLOC1);
 
-	if (pool->slow.flags & PP_FLAG_ALLOW_UNREADABLE_NETMEM) {
+	if (pool->slow.flags & (PP_FLAG_ALLOW_UNREADABLE_NETMEM |
+				PP_FLAG_ALLOW_XDP_ONLY_NETMEM)) {
+		const struct memory_provider_ops *ops;
+		u32 allow;
+
 		netdev_assert_locked(pool->slow.netdev);
 		rxq = __netif_get_rx_queue(pool->slow.netdev,
 					   pool->slow.queue_idx);
-		pool->mp_priv = rxq->mp_params.mp_priv;
-		pool->mp_ops = rxq->mp_params.mp_ops;
+		ops = rxq->mp_params.mp_ops;
+		allow = ops && ops->flags & MP_XDP_ONLY ?
+			PP_FLAG_ALLOW_XDP_ONLY_NETMEM :
+			PP_FLAG_ALLOW_UNREADABLE_NETMEM;
+		if (pool->slow.flags & allow) {
+			pool->mp_priv = rxq->mp_params.mp_priv;
+			pool->mp_ops = ops;
+		}
 	}
 
 	if (pool->mp_ops) {
net/ethtool/rings.c +4 -1
index e3810c0320e3..84ba17412a40 100644
@@ -258,7 +258,10 @@ ethnl_set_rings(struct ethnl_req_info *req_info, struct genl_info *info)
 		return -EINVAL;
 	}
 
-	if (dev_get_min_mp_channel_count(dev)) {
+	/* Providers that take the payload need header split. XDP-only
+	 * providers back whole packets: they neither need it nor block XDP.
+	 */
+	if (dev_mp_blocks_xdp(dev)) {
 		if (kernel_ringparam.tcp_data_split !=
 		    ETHTOOL_TCP_DATA_SPLIT_ENABLED) {
 			NL_SET_ERR_MSG(info->extack,
Signature · 1 line
2.56.1
#4 lore raw

PATCH 4/15 page_pool: Let memory providers take back net_iovs

In reply to Björn Töpel

Currently, the only provider hook on the last put of a net_iov is release_netmem(), which takes it out of its page pool. The AF_XDP sink, later in this series, gives a chunk back to userspace only once the device is done with it too, so it must see that last put. With release_netmem(), the pool would take the chunk in again each time userspace lends it back.

Let a provider mark a net_iov so that its last put goes to the provider's hand_off() instead of the page pool cache, still charged to the pool, for the provider to put back later.

The hand-off also covers the fragment allocator draining a marked net_iov. Providers that mark net_iovs must implement hand_off(), and nothing changes for others, as the mark is clear by default. Also give providers a byte of their own in the net_iov, in the cache line they touch anyway.

---
 include/net/netmem.h                    |  8 ++++++++
 include/net/page_pool/memory_provider.h |  6 ++++++
 net/core/page_pool.c                    | 20 +++++++++++++++++++-
 3 files changed, 33 insertions(+), 1 deletion(-)
include/net/netmem.h +8 -0
index 4cf4ee1cd55d..1be7298ac6d9 100644
@@ -97,6 +97,12 @@ enum net_iov_type {
 struct net_iov {
 	struct netmem_desc desc;
 	enum net_iov_type type;
+	/* The last put hands it to its memory provider instead of the page
+	 * pool cache, see &memory_provider_ops.hand_off
+	 */
+	bool mp_hand_off;
+	/* Owned by the memory provider */
+	u8 mp_state;
 	struct net_iov_area *owner;
 };
 
@@ -132,6 +138,8 @@ static inline void net_iov_init(struct net_iov *niov,
 {
 	niov->owner = owner;
 	niov->type = type;
+	niov->mp_hand_off = false;
+	niov->mp_state = 0;
 }
 
 /* netmem */
include/net/page_pool/memory_provider.h +6 -0
index d52c7a450c68..bfc284158222 100644
@@ -36,6 +36,12 @@ enum mp_flags {
 struct memory_provider_ops {
 	netmem_ref (*alloc_netmems)(struct page_pool *pool, gfp_t gfp);
 	bool (*release_netmem)(struct page_pool *pool, netmem_ref netmem);
+	/* Takes a free net_iov marked mp_hand_off that stays charged to the
+	 * pool; the provider puts it back later. Returns false to have the
+	 * pool recycle it instead. Called where the pool puts netmem, outside
+	 * hard IRQ context. Needed by providers that mark net_iovs.
+	 */
+	bool (*hand_off)(struct page_pool *pool, netmem_ref netmem);
 	int (*init)(struct page_pool *pool);
 	void (*destroy)(struct page_pool *pool);
 	int (*nl_fill)(void *mp_priv, struct sk_buff *rsp,
net/core/page_pool.c +19 -1
index 8a1ea21ccdcd..200b0569b9fe 100644
@@ -840,6 +840,16 @@ static bool __page_pool_page_can_be_recycled(netmem_ref netmem)
 		!page_is_pfmemalloc(netmem_to_page(netmem)));
 }
 
+/* A memory provider takes back a free net_iov it marked, see
+ * &memory_provider_ops.hand_off
+ */
+static bool page_pool_hand_off(struct page_pool *pool, netmem_ref netmem)
+{
+	return netmem_is_net_iov(netmem) &&
+	       unlikely(netmem_to_net_iov(netmem)->mp_hand_off) &&
+	       pool->mp_ops->hand_off(pool, netmem);
+}
+
 /* If the page refcnt == 1, this will try to recycle the page.
  * If pool->dma_sync is set, we'll try to sync the DMA area for
  * the configured size min(dma_sync_size, pool->max_len).
@@ -852,6 +862,10 @@ __page_pool_put_page(struct page_pool *pool, netmem_ref netmem,
 {
 	lockdep_assert_no_hardirq();
 
+	/* The provider takes the net_iovs it marked */
+	if (page_pool_hand_off(pool, netmem))
+		return 0;
+
 	/* This allocator is optimized for the XDP mode that uses
 	 * one-frame-per-page, but have fallbacks that act like the
 	 * regular page allocator APIs.
@@ -1051,6 +1065,9 @@ static netmem_ref page_pool_drain_frag(struct page_pool *pool,
 	if (likely(page_pool_unref_netmem(netmem, drain_count)))
 		return 0;
 
+	if (page_pool_hand_off(pool, netmem))
+		return 0;
+
 	if (__page_pool_page_can_be_recycled(netmem)) {
 		page_pool_dma_sync_for_device(pool, netmem, -1);
 		return netmem;
@@ -1067,7 +1084,8 @@ static void page_pool_free_frag(struct page_pool *pool)
 
 	pool->frag_page = 0;
 
-	if (!netmem || page_pool_unref_netmem(netmem, drain_count))
+	if (!netmem || page_pool_unref_netmem(netmem, drain_count) ||
+	    page_pool_hand_off(pool, netmem))
 		return;
 
 	page_pool_return_netmem(pool, netmem);
Signature · 1 line
2.56.1
#5 lore raw

PATCH 5/15 xdp: Run programs on buffers that must not hold kernel structures

In reply to Björn Töpel

Currently, the core refuses native XDP programs next to a memory provider. An AF_XDP sink needs XDP to steer its packets and to use the RX metadata kfuncs. Its buffers are UMEM chunks that XDP may read through the kernel mapping, but that userspace may write at any time, also while the kernel reads them. If drivers build XDP buffers on them as on pages, the core puts kernel structures into them, such as the shared info of a multi-buffer packet, the xdp_frame of XDP_TX and redirects, and the skb of XDP_PASS.

Let programs run on sink buffers as on pages, and keep every kernel structure out of them.

A sink offers an XDP view of its UMEM, so drivers build the buffer as for a page, while netmem_address() and skb_frag_address() still give NULL for sink net_iovs. Programs and helpers read and write the packet in place, fragments included. xdp_prepare_buff() tells a sink head by its address, with one range check under a static key, and marks the buffer before the driver adds fragments. Other buffers pay nothing while no sink is bound.

A marked buffer keeps its shared info in the queue, with XDP_FLAGS_SINFO_EXT, set up when the driver registers a sink page pool as its memory model.

A sink buffer may only go to the AF_XDP socket of its queue. The core turns XDP_TX and XDP_PASS into XDP_DROP, so drivers need no checks of their own. XDP_ABORTED and invalid verdicts reach the driver, which traces them and drops the packet. Frame conversion and skb construction refuse sink buffers too, so devmap and cpumap drop them, and sink net_iovs never become skb frags, so every net_iov frag stays unreadable.

As userspace may change the bytes meanwhile, the kernel takes bounds only from its own fields, and only the program and its helpers read the bytes. A helper that reads bytes twice must check a copy.

---
 include/net/netmem.h          |  5 ++-
 include/net/page_pool/types.h |  7 ++--
 include/net/xdp.h             | 60 +++++++++++++++++++++++++++++++++--
 net/core/xdp.c                | 46 +++++++++++++++++++++++++--
 4 files changed, 108 insertions(+), 10 deletions(-)
include/net/netmem.h +4 -1
index 1be7298ac6d9..834a735e33a7 100644
@@ -68,6 +68,7 @@ DECLARE_STATIC_KEY_FALSE(page_pool_mem_providers);
 enum net_iov_type {
 	NET_IOV_DMABUF,
 	NET_IOV_IOURING,
+	NET_IOV_XSK,
 };
 
 /* A memory descriptor representing abstract networking I/O vectors.
@@ -81,7 +82,9 @@ enum net_iov_type {
  * CPU-readable or unreadable. New code must not assume net_iov implies
  * unreadable memory (check readability via netmem_address() or
  * skb_frags_readable() instead) and should, as much as possible, generalize
- * existing limitations to match the design principles.
+ * existing limitations to match the design principles. AF_XDP sink
+ * net_iovs (%NET_IOV_XSK) are unreadable for the core and the stack as well:
+ * only XDP reads them, through their XDP view (&net_iov_area.xdp_vaddr).
  *
  * @pp_magic:	pp field, similar to the one in struct page/struct
  *		netmem_desc.
include/net/page_pool/types.h +4 -3
index 35d4dc45db6a..e932d836316f 100644
@@ -33,9 +33,10 @@
 
 /*
  * Allow an XDP-only memory provider of the queue (%MP_XDP_ONLY) to back the
- * pool. The driver registers the pool as the memory model of the RX queue,
- * sets up XDP buffers with xdp_prepare_buff() at xdp_netmem_address() of
- * their head, and puts heads back by netmem, not by address.
+ * pool. The driver registers the pool as the memory model of the RX queue
+ * with xdp_rxq_info_reg_mem_model(), sets up XDP buffers with
+ * xdp_prepare_buff() at xdp_netmem_address() of their head, and puts heads
+ * back by netmem, not by address.
  */
 #define PP_FLAG_ALLOW_XDP_ONLY_NETMEM BIT(4)
 
include/net/xdp.h +57 -3

115 lines not on this page · raw message

net/core/xdp.c +43 -3

97 lines not on this page · raw message

Signature · 1 line
2.56.1
#6 lore raw

PATCH 6/15 xsk: Lend UMEM chunks to the page pools of a queue

In reply to Björn Töpel

Currently, AF_XDP zero copy makes the device fill one UMEM chunk per buffer, at the UMEM headroom. Drivers bend their RX geometry to that and carry a second RX path for it, and packets that the stack would build from several buffers, or pack into one page, cannot be received without a copy.

Let the device lay out buffers in UMEM chunks as it does in pages, for a UMEM registered with the new flag XDP_UMEM_DRV_LAYOUT. First, let the chunks of such a UMEM back the RX page pools of the bound queue, through a sink memory provider that the socket installs with the queue management API, so drivers need no AF_XDP code.

The chunk is the unit of ownership. A FILL entry lends a chunk to the kernel until the kernel gives it back, see the next patch. A chunk that is lent twice, or lies outside the UMEM, counts as an invalid FILL entry, so userspace cannot make the device use a chunk twice. A refill takes at most a page pool cache worth of FILL entries, bounding the NAPI work. Chunks that a page pool released when it went away, as at a queue restart, stay on a list that refills take from only when FILL gives too few, so every chunk taken from it stays in circulation. The pool allocates no xdp_buff_xsk per chunk, which saves 128 bytes per 4 KiB chunk. The kernel mapping of the UMEM is the XDP view of its net_iovs, so XDP reads the chunks in place.

The provider refuses page pools with pages larger than a chunk, with another DMA device, or so large that the device could hold every chunk. Binding needs a native XDP program, which cannot be detached while the provider is installed, as drivers would otherwise build skbs around the buffers. Unbind restarts the queue without the provider, or closes the device if that fails, as the old queue may go on receiving into the UMEM. Device unregister may uninstall the provider before the socket unbinds, and unbind then only frees what is left.

Bind sets the RX need_wakeup flag before the queue starts, as the queue may need FILL entries to start. After that only the queue NAPI changes the flag, asking for a kick only while FILL is empty. Process-context refills, as when bnxt fills a new queue, leave it alone.

DMA syncs work as with page pools. The UMEM is mapped once, at bind, the provider syncs a chunk for the device when it lends it, page pools sync the chunks they recycle, and drivers sync each buffer for the CPU before XDP runs.

None of this is reachable until UMEM registration accepts XDP_UMEM_DRV_LAYOUT, two patches later.

---
 include/linux/netdevice.h         |   2 +
 include/net/xsk_buff_pool.h       |   3 +
 include/uapi/linux/if_xdp.h       |   7 +
 net/core/dev.c                    |  30 +++
 net/xdp/Kconfig                   |   1 +
 net/xdp/Makefile                  |   2 +-
 net/xdp/xsk_buff_pool.c           |  30 ++-
 net/xdp/xsk_sink.c                | 416 ++++++++++++++++++++++++++++++
 net/xdp/xsk_sink.h                |  14 +
 tools/include/uapi/linux/if_xdp.h |   7 +
 10 files changed, 505 insertions(+), 7 deletions(-)
 create mode 100644 net/xdp/xsk_sink.c
 create mode 100644 net/xdp/xsk_sink.h
include/linux/netdevice.h +2 -0
index 5fd2bec1178a..5a7247873ce8 100644
@@ -4459,6 +4459,8 @@ u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode);
 
 u32 dev_get_min_mp_channel_count(const struct net_device *dev);
 bool dev_mp_blocks_xdp(const struct net_device *dev);
+bool dev_has_xdp_only_mp(const struct net_device *dev);
+bool dev_xdp_drv_prog_held(struct net_device *dev);
 
 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb);
 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb);
include/net/xsk_buff_pool.h +3 -0
index 02e89350faf9..376408994a33 100644
@@ -11,6 +11,7 @@
 #include <net/xdp.h>
 
 struct xsk_buff_pool;
+struct xsk_sink;
 struct xdp_rxq_info;
 struct xsk_cb_desc;
 struct xsk_queue;
@@ -54,6 +55,8 @@ struct xsk_buff_pool {
 	spinlock_t xsk_tx_list_lock;
 	refcount_t users;
 	struct xdp_umem *umem;
+	/* RX in the device's buffer layout, see net/xdp/xsk_sink.c */
+	struct xsk_sink *sink;
 	struct work_struct work;
 	/* Protects generic receive in shared and non-shared umem mode. */
 	spinlock_t rx_lock;
include/uapi/linux/if_xdp.h +7 -0
index 50d67df78911..160a437ed540 100644
@@ -45,6 +45,13 @@
  */
 #define XDP_UMEM_TX_METADATA_LEN	(1 << 2)
 
+/* RX buffers follow the device's layout: a page-sized chunk may hold
+ * several of them, a packet may span chunks, and the device picks the
+ * offsets. A FILL entry lends a chunk to the kernel. Needs aligned
+ * page-sized chunks and no headroom.
+ */
+#define XDP_UMEM_DRV_LAYOUT		(1 << 4)
+
 struct sockaddr_xdp {
 	__u16 sxdp_family;
 	__u16 sxdp_flags;
net/core/dev.c +30 -0
index 8a1d5a284e53..3bc20c7e409f 100644
@@ -10860,6 +10860,11 @@ static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack
 		NL_SET_ERR_MSG(extack, "Active program does not match expected");
 		return -EEXIST;
 	}
+	if (cur_prog && !new_prog && !link && mode == XDP_MODE_DRV &&
+	    dev_has_xdp_only_mp(dev)) {
+		NL_SET_ERR_MSG(extack, "An XDP-only memory provider needs the program");
+		return -EBUSY;
+	}
 
 	/* put effective new program into new_prog */
 	if (link)
@@ -11163,6 +11168,31 @@ bool dev_mp_blocks_xdp(const struct net_device *dev)
 	return false;
 }
 
+/* A native program is attached, and dev_xdp_attach() keeps it while an
+ * AF_XDP socket receives in the buffer layout of @dev. A BPF link could go
+ * without asking, and so could a program that an upper device propagated.
+ */
+bool dev_xdp_drv_prog_held(struct net_device *dev)
+{
+	return dev_xdp_prog_id(dev, XDP_MODE_DRV) &&
+	       !dev_xdp_link(dev, XDP_MODE_DRV) && !dev->xdp_from_upper;
+}
+
+/* A queue of @dev has an XDP-only memory provider */
+bool dev_has_xdp_only_mp(const struct net_device *dev)
+{
+	const struct memory_provider_ops *ops;
+	unsigned int i;
+
+	for (i = 0; i < dev->real_num_rx_queues; i++) {
+		ops = dev->_rx[i].mp_params.mp_ops;
+		if (ops && ops->flags & MP_XDP_ONLY)
+			return true;
+	}
+
+	return false;
+}
+
 u32 dev_get_min_mp_channel_count(const struct net_device *dev)
 {
 	int i;
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..73a638f12843 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_sink.o
 obj-$(CONFIG_XDP_SOCKETS_DIAG) += xsk_diag.o
net/xdp/xsk_buff_pool.c +24 -6
index 5ec092f7cb6f..7ece7d9e3937 100644
@@ -7,6 +7,7 @@
 #include <net/xdp_sock_drv.h>
 
 #include "xsk_queue.h"
+#include "xsk_sink.h"
 #include "xdp_umem.h"
 #include "xsk.h"
 
@@ -69,9 +70,14 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
 	if (!pool)
 		goto out;
 
-	pool->heads = kvzalloc_objs(*pool->heads, umem->chunks);
-	if (!pool->heads)
-		goto out;
+	/* Receiving in the device's buffer layout and copy TX take none */
+	if (!(umem->flags & XDP_UMEM_DRV_LAYOUT)) {
+		pool->heads = kvzalloc_objs(*pool->heads, umem->chunks);
+		if (!pool->heads)
+			goto out;
+		pool->heads_cnt = umem->chunks;
+		pool->free_heads_cnt = umem->chunks;
+	}
 
 	if (xs->tx)
 		if (xp_alloc_tx_descs(pool, xs, max_segs))
@@ -79,8 +85,6 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
 
 	pool->chunk_mask = ~((u64)umem->chunk_size - 1);
 	pool->addrs_cnt = umem->size;
-	pool->heads_cnt = umem->chunks;
-	pool->free_heads_cnt = umem->chunks;
 	pool->headroom = umem->headroom;
 	pool->chunk_size = umem->chunk_size;
 	pool->chunk_shift = ffs(umem->chunk_size) - 1;
@@ -211,6 +215,13 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 	 */
 	hlist_add_head(&pool->dev_node, &netdev->xsk_pools);
 
+	if (pool->umem->flags & XDP_UMEM_DRV_LAYOUT) {
+		err = xsk_sink_bind(pool, netdev, queue_id, flags);
+		if (err)
+			goto err_unbind;
+		return 0;
+	}
+
 	if (force_copy)
 		/* For copy-mode, we are done. */
 		return 0;
@@ -268,6 +279,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 err_unreg_pool:
 	if (!force_zc)
 		err = 0; /* fallback to copy mode */
+err_unbind:
 	if (err) {
 		pool->umem->flags = umem_flags;
 		xsk_clear_pool_at_qid(netdev, queue_id);
@@ -285,6 +297,9 @@ int xp_assign_dev_shared(struct xsk_buff_pool *pool, struct xdp_sock *umem_xs,
 	struct xdp_umem *umem = umem_xs->umem;
 
 	flags = umem->zc ? XDP_ZEROCOPY : XDP_COPY;
+	/* The device layout has no copy mode */
+	if (umem->flags & XDP_UMEM_DRV_LAYOUT)
+		flags = 0;
 
 	if (umem->flags & XDP_UMEM_SG_FLAG)
 		flags |= XDP_USE_SG;
@@ -300,7 +315,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->sink)
+		xsk_sink_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;
net/xdp/xsk_sink.c new file +416 -0

416 lines not on this page · raw message

net/xdp/xsk_sink.h new file +14 -0
new file mode 100644
index 000000000000..3f201163c530
@@ -0,0 +1,14 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* AF_XDP RX in the device's buffer layout, see xsk_sink.c */
+
+#ifndef XSK_SINK_H_
+#define XSK_SINK_H_
+
+struct net_device;
+struct xsk_buff_pool;
+
+int xsk_sink_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+		  u16 queue_id, u16 flags);
+void xsk_sink_unbind(struct xsk_buff_pool *pool);
+
+#endif /* XSK_SINK_H_ */
tools/include/uapi/linux/if_xdp.h +7 -0
index 50d67df78911..160a437ed540 100644
@@ -45,6 +45,13 @@
  */
 #define XDP_UMEM_TX_METADATA_LEN	(1 << 2)
 
+/* RX buffers follow the device's layout: a page-sized chunk may hold
+ * several of them, a packet may span chunks, and the device picks the
+ * offsets. A FILL entry lends a chunk to the kernel. Needs aligned
+ * page-sized chunks and no headroom.
+ */
+#define XDP_UMEM_DRV_LAYOUT		(1 << 4)
+
 struct sockaddr_xdp {
 	__u16 sxdp_family;
 	__u16 sxdp_flags;
Signature · 1 line
2.56.1
#7 lore raw

Re: [PATCH net-next 06/15] xsk: Lend UMEM chunks to the page pools of a queue

Quoted 103 lines · Björn Töpel

Currently, AF_XDP zero copy makes the device fill one UMEM chunk per buffer, at the UMEM headroom. Drivers bend their RX geometry to that and carry a second RX path for it, and packets that the stack would build from several buffers, or pack into one page, cannot be received without a copy.

Let the device lay out buffers in UMEM chunks as it does in pages, for a UMEM registered with the new flag XDP_UMEM_DRV_LAYOUT. First, let the chunks of such a UMEM back the RX page pools of the bound queue, through a sink memory provider that the socket installs with the queue management API, so drivers need no AF_XDP code.

The chunk is the unit of ownership. A FILL entry lends a chunk to the kernel until the kernel gives it back, see the next patch. A chunk that is lent twice, or lies outside the UMEM, counts as an invalid FILL entry, so userspace cannot make the device use a chunk twice. A refill takes at most a page pool cache worth of FILL entries, bounding the NAPI work. Chunks that a page pool released when it went away, as at a queue restart, stay on a list that refills take from only when FILL gives too few, so every chunk taken from it stays in circulation. The pool allocates no xdp_buff_xsk per chunk, which saves 128 bytes per 4 KiB chunk. The kernel mapping of the UMEM is the XDP view of its net_iovs, so XDP reads the chunks in place.

The provider refuses page pools with pages larger than a chunk, with another DMA device, or so large that the device could hold every chunk. Binding needs a native XDP program, which cannot be detached while the provider is installed, as drivers would otherwise build skbs around the buffers. Unbind restarts the queue without the provider, or closes the device if that fails, as the old queue may go on receiving into the UMEM. Device unregister may uninstall the provider before the socket unbinds, and unbind then only frees what is left.

Bind sets the RX need_wakeup flag before the queue starts, as the queue may need FILL entries to start. After that only the queue NAPI changes the flag, asking for a kick only while FILL is empty. Process-context refills, as when bnxt fills a new queue, leave it alone.

DMA syncs work as with page pools. The UMEM is mapped once, at bind, the provider syncs a chunk for the device when it lends it, page pools sync the chunks they recycle, and drivers sync each buffer for the CPU before XDP runs.

None of this is reachable until UMEM registration accepts XDP_UMEM_DRV_LAYOUT, two patches later.

---
 include/linux/netdevice.h         |   2 +
 include/net/xsk_buff_pool.h       |   3 +
 include/uapi/linux/if_xdp.h       |   7 +
 net/core/dev.c                    |  30 +++
 net/xdp/Kconfig                   |   1 +
 net/xdp/Makefile                  |   2 +-
 net/xdp/xsk_buff_pool.c           |  30 ++-
 net/xdp/xsk_sink.c                | 416 ++++++++++++++++++++++++++++++
 net/xdp/xsk_sink.h                |  14 +
 tools/include/uapi/linux/if_xdp.h |   7 +
 10 files changed, 505 insertions(+), 7 deletions(-)
 create mode 100644 net/xdp/xsk_sink.c
 create mode 100644 net/xdp/xsk_sink.h
include/linux/netdevice.h +2 -0
index 5fd2bec1178a..5a7247873ce8 100644
@@ -4459,6 +4459,8 @@ u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode);
 
 u32 dev_get_min_mp_channel_count(const struct net_device *dev);
 bool dev_mp_blocks_xdp(const struct net_device *dev);
+bool dev_has_xdp_only_mp(const struct net_device *dev);
+bool dev_xdp_drv_prog_held(struct net_device *dev);
 
 int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb);
 int dev_forward_skb(struct net_device *dev, struct sk_buff *skb);
include/net/xsk_buff_pool.h +3 -0
index 02e89350faf9..376408994a33 100644
@@ -11,6 +11,7 @@
 #include <net/xdp.h>
 
 struct xsk_buff_pool;
+struct xsk_sink;
 struct xdp_rxq_info;
 struct xsk_cb_desc;
 struct xsk_queue;
@@ -54,6 +55,8 @@ struct xsk_buff_pool {
        spinlock_t xsk_tx_list_lock;
        refcount_t users;
        struct xdp_umem *umem;
+       /* RX in the device's buffer layout, see net/xdp/xsk_sink.c */
+       struct xsk_sink *sink;
        struct work_struct work;
        /* Protects generic receive in shared and non-shared umem mode. */
        spinlock_t rx_lock;
include/uapi/linux/if_xdp.h +0 -0
index 50d67df78911..160a437ed540 100644

include/uapi/linux/if_xdp.h line 53

Quoted 9 lines
include/uapi/linux/if_xdp.h +6 -0
@@ -45,6 +45,13 @@
  */
 #define XDP_UMEM_TX_METADATA_LEN       (1 << 2)
 
+/* RX buffers follow the device's layout: a page-sized chunk may hold
+ * several of them, a packet may span chunks, and the device picks the
+ * offsets. A FILL entry lends a chunk to the kernel. Needs aligned
+ * page-sized chunks and no headroom.
+ */
+#define XDP_UMEM_DRV_LAYOUT            (1 << 4)

First of all, this looks a lot better than the previous patch set. Much simpler from a driver point of view, fewer changes to core networking code, and that with just a small change/extension to the uAPI.

But I do not think this name is good. Most users of this API do not care about driver details such as the layout. Why not call it something that has to do with what has changed from the user's point of view? Previously we had implicit ownership transfers. You got a packet in Rx, you own the chunk. Now we have explicit ownership transfer. You do not own the chunk the packet is in, unless you get the new flag back (introduced later). So something with "explicit ownership" or something similar would be better. Or focus the name on that you can support larger chunks, but that is for later patches so might not be the best choice.

Quoted 349 lines
include/uapi/linux/if_xdp.h +0 -0
 struct sockaddr_xdp {
        __u16 sxdp_family;
        __u16 sxdp_flags;
net/core/dev.c +30 -0
index 8a1d5a284e53..3bc20c7e409f 100644
@@ -10860,6 +10860,11 @@ static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack
                NL_SET_ERR_MSG(extack, "Active program does not match expected");
                return -EEXIST;
        }
+       if (cur_prog && !new_prog && !link && mode == XDP_MODE_DRV &&
+           dev_has_xdp_only_mp(dev)) {
+               NL_SET_ERR_MSG(extack, "An XDP-only memory provider needs the program");
+               return -EBUSY;
+       }
 
        /* put effective new program into new_prog */
        if (link)
@@ -11163,6 +11168,31 @@ bool dev_mp_blocks_xdp(const struct net_device *dev)
        return false;
 }
 
+/* A native program is attached, and dev_xdp_attach() keeps it while an
+ * AF_XDP socket receives in the buffer layout of @dev. A BPF link could go
+ * without asking, and so could a program that an upper device propagated.
+ */
+bool dev_xdp_drv_prog_held(struct net_device *dev)
+{
+       return dev_xdp_prog_id(dev, XDP_MODE_DRV) &&
+              !dev_xdp_link(dev, XDP_MODE_DRV) && !dev->xdp_from_upper;
+}
+
+/* A queue of @dev has an XDP-only memory provider */
+bool dev_has_xdp_only_mp(const struct net_device *dev)
+{
+       const struct memory_provider_ops *ops;
+       unsigned int i;
+
+       for (i = 0; i < dev->real_num_rx_queues; i++) {
+               ops = dev->_rx[i].mp_params.mp_ops;
+               if (ops && ops->flags & MP_XDP_ONLY)
+                       return true;
+       }
+
+       return false;
+}
+
 u32 dev_get_min_mp_channel_count(const struct net_device *dev)
 {
        int i;
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..73a638f12843 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_sink.o
 obj-$(CONFIG_XDP_SOCKETS_DIAG) += xsk_diag.o
net/xdp/xsk_buff_pool.c +24 -6
index 5ec092f7cb6f..7ece7d9e3937 100644
@@ -7,6 +7,7 @@
 #include <net/xdp_sock_drv.h>
 
 #include "xsk_queue.h"
+#include "xsk_sink.h"
 #include "xdp_umem.h"
 #include "xsk.h"
 
@@ -69,9 +70,14 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
        if (!pool)
                goto out;
 
-       pool->heads = kvzalloc_objs(*pool->heads, umem->chunks);
-       if (!pool->heads)
-               goto out;
+       /* Receiving in the device's buffer layout and copy TX take none */
+       if (!(umem->flags & XDP_UMEM_DRV_LAYOUT)) {
+               pool->heads = kvzalloc_objs(*pool->heads, umem->chunks);
+               if (!pool->heads)
+                       goto out;
+               pool->heads_cnt = umem->chunks;
+               pool->free_heads_cnt = umem->chunks;
+       }
 
        if (xs->tx)
                if (xp_alloc_tx_descs(pool, xs, max_segs))
@@ -79,8 +85,6 @@ struct xsk_buff_pool *xp_create_and_assign_umem(struct xdp_sock *xs,
 
        pool->chunk_mask = ~((u64)umem->chunk_size - 1);
        pool->addrs_cnt = umem->size;
-       pool->heads_cnt = umem->chunks;
-       pool->free_heads_cnt = umem->chunks;
        pool->headroom = umem->headroom;
        pool->chunk_size = umem->chunk_size;
        pool->chunk_shift = ffs(umem->chunk_size) - 1;
@@ -211,6 +215,13 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
         */
        hlist_add_head(&pool->dev_node, &netdev->xsk_pools);
 
+       if (pool->umem->flags & XDP_UMEM_DRV_LAYOUT) {
+               err = xsk_sink_bind(pool, netdev, queue_id, flags);
+               if (err)
+                       goto err_unbind;
+               return 0;
+       }
+
        if (force_copy)
                /* For copy-mode, we are done. */
                return 0;
@@ -268,6 +279,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool,
 err_unreg_pool:
        if (!force_zc)
                err = 0; /* fallback to copy mode */
+err_unbind:
        if (err) {
                pool->umem->flags = umem_flags;
                xsk_clear_pool_at_qid(netdev, queue_id);
@@ -285,6 +297,9 @@ int xp_assign_dev_shared(struct xsk_buff_pool *pool, struct xdp_sock *umem_xs,
        struct xdp_umem *umem = umem_xs->umem;
 
        flags = umem->zc ? XDP_ZEROCOPY : XDP_COPY;
+       /* The device layout has no copy mode */
+       if (umem->flags & XDP_UMEM_DRV_LAYOUT)
+               flags = 0;
 
        if (umem->flags & XDP_UMEM_SG_FLAG)
                flags |= XDP_USE_SG;
@@ -300,7 +315,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->sink)
+               xsk_sink_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;
net/xdp/xsk_sink.c new file +187 -0
new file mode 100644
index 000000000000..b78116f25e71
@@ -0,0 +1,416 @@
+// SPDX-License-Identifier: GPL-2.0
+/* AF_XDP RX in the device's buffer layout
+ *
+ * Userspace lends page-sized UMEM chunks through the FILL ring. Each chunk
+ * becomes a net_iov of a page pool memory provider, and the device splits it
+ * as it splits pages: a chunk may hold several RX buffers, and a packet may
+ * span chunks.
+ *
+ * The kernel maps the chunks through the UMEM mapping, so XDP programs read
+ * and write the packets in place. The kernel stores none of its own data in
+ * the chunks: the shared info of a packet lives in the sink, see
+ * %XDP_FLAGS_SINFO_EXT, and the core turns every verdict that would build an
+ * skb or a frame in the buffers into a drop.
+ */
+
+#include <linux/nospec.h>
+#include <net/netdev_queues.h>
+#include <net/netdev_rx_queue.h>
+#include <net/page_pool/helpers.h>
+#include <net/page_pool/memory_provider.h>
+#include <net/xdp_sock_drv.h>
+
+#include "../core/dev.h"
+#include "xsk_queue.h"
+#include "xsk_sink.h"
+
+#define XSK_SINK_DMA_ATTR (DMA_ATTR_WEAK_ORDERING | DMA_ATTR_SKIP_CPU_SYNC)
+/* Chunks a refill tops up to with released ones */
+#define XSK_SINK_RESERVE       32
+
+/* &net_iov.mp_state: whether userspace has the chunk or lent it */
+enum {
+       XSK_SINK_USER,
+       XSK_SINK_LENT,
+};
+
+struct xsk_sink {
+       struct net_iov_area area;
+       struct device *dev;
+       /* Valid until the socket unbinds */
+       struct xsk_buff_pool *pool;
+       /* NULL once no queue uses the provider */
+       struct netdev_rx_queue *rxq;
+       /* Protects fq, which stays set while the UMEM is mapped, and keeps
+        * refills the only taker of released chunks. Besides the queue NAPI,
+        * drivers refill from process context, as bnxt fills the rings of a
+        * new queue while the old one still runs.
+        */
+       spinlock_t lock;
+       struct xsk_queue *fq;
+       refcount_t refs;
+       /* One node per chunk: chunks that page pools released, from any
+        * context
+        */
+       struct llist_node *nodes;
+       struct llist_head released;
+};
+
+static void xsk_sink_free(struct xsk_sink *sink)
+{
+       kvfree(sink->nodes);
+       kvfree(sink->area.niovs);
+       kfree(sink);
+}
+
+static void xsk_sink_put(struct xsk_sink *sink)
+{
+       if (refcount_dec_and_test(&sink->refs))
+               xsk_sink_free(sink);
+}
+
+static int xsk_sink_init(struct page_pool *pp)
+{
+       struct xsk_sink *sink = pp->mp_priv;
+
+       /* Each net_iov is one chunk, mapped for one device */
+       if (pp->p.order)
+               return -E2BIG;
+       if (pp->p.dev != sink->dev || pp->p.offset + pp->p.max_len > PAGE_SIZE)
+               return -EINVAL;
+       /* Rings that keep every chunk posted leave none to replace the ones
+        * the device filled: mlx5 posts about 16K pages per queue at MTU
+        * 9000.
+        */
+       if (pp->p.pool_size + PP_ALLOC_CACHE_SIZE >= sink->area.num_niovs)
+               return -ENOSPC;
+
+       refcount_inc(&sink->refs);
+       return 0;
+}
+
+static void xsk_sink_destroy(struct page_pool *pp)
+{
+       xsk_sink_put(pp->mp_priv);
+}
+
+/* Takes the chunks that FILL entries lend into the cache of @pp, which still
+ * holds those it gave back before. A chunk that an earlier page pool still
+ * holds goes back to it. Returns the number of chunks taken.
+ */
+static u32 xsk_sink_take_fill(struct xsk_sink *sink, struct page_pool *pp)
+{
+       struct net_iov *niov, *niovs = sink->area.niovs;
+       u32 i, entries, cons, mask, nr, n = 0;
+       struct xsk_queue *fq = sink->fq;
+       struct xdp_umem_ring *ring;
+       struct page_pool *owner;
+       netmem_ref netmem;
+       u64 addr;
+
+       lockdep_assert_held(&sink->lock);
+
+       /* One cache worth, bounding NAPI work */
+       entries = fq ? xskq_cons_nb_entries(fq, PP_ALLOC_CACHE_SIZE) : 0;
+       if (!entries)
+               return 0;
+
+       nr = sink->area.num_niovs;
+       ring = (struct xdp_umem_ring *)fq->ring;
+       mask = fq->ring_mask;
+       cons = fq->cached_cons;
+       for (i = 0; i < entries; i++) {
+               addr = ring->desc[(cons + i) & mask];
+               niov = &niovs[array_index_nospec((u32)(addr >> PAGE_SHIFT),
+                                                nr)];
+               /* A chunk lent twice would be in two places at once */
+               if (unlikely(addr >= (u64)nr << PAGE_SHIFT ||
+                            READ_ONCE(niov->mp_state) == XSK_SINK_LENT)) {
+                       fq->invalid_descs++;
+                       continue;
+               }
+
+               WRITE_ONCE(niov->mp_state, XSK_SINK_LENT);
+               netmem = net_iov_to_netmem(niov);
+               owner = netmem_get_pp(netmem);
+               if (owner && owner != pp) {
+                       page_pool_put_unrefed_netmem(owner, netmem, -1, false);
+                       continue;
+               }
+               if (!owner)
+                       net_mp_niov_set_page_pool(pp, niov);
+               pp->alloc.cache[n++] = netmem;
+       }
+
+       xskq_cons_release_n(fq, entries);
+       __xskq_cons_release(fq);
+       return n;
+}
+
+/* Tops up the cache of @pp, which holds @n chunks, with chunks that page
+ * pools released. A reserve, not a source. Each chunk it adds stays in
+ * circulation, so take only what FILL could not give. The lock keeps this
+ * the only consumer of the list, as llist_del_first() needs.
+ */
+static u32 xsk_sink_take_released(struct xsk_sink *sink, struct page_pool *pp,
+                                 u32 n)
+{
+       struct llist_node *node;
+       struct net_iov *niov;
+
+       lockdep_assert_held(&sink->lock);
+
+       /* The page pool cache has 8 entries with 64K pages */
+       while (n < min(XSK_SINK_RESERVE, PP_ALLOC_CACHE_SIZE)) {
+               node = llist_del_first(&sink->released);
+               if (!node)
+                       break;
+               niov = &sink->area.niovs[node - sink->nodes];
+               net_mp_niov_set_page_pool(pp, niov);
+               pp->alloc.cache[n++] = net_iov_to_netmem(niov);
+       }
+       return n;
+}
+
+static netmem_ref xsk_sink_alloc_netmems(struct page_pool *pp, gfp_t gfp)
+{
+       struct xsk_sink *sink = pp->mp_priv;
+       /* The NAPI owns the need_wakeup flags */
+       bool napi = in_softirq() && !in_hardirq();
+       struct xsk_queue *fq;
+       dma_addr_t dma;
+       u32 i, n;
+
+       /* The page pool refills only an empty cache */
+       if (WARN_ON_ONCE(pp->alloc.count))
+               return 0;
+

net/xdp/xsk_sink.c line 197

Quoted 10 lines
net/xdp/xsk_sink.c new file +10 -0
+       spin_lock_bh(&sink->lock);
+       n = xsk_sink_take_fill(sink, pp);
+       n = xsk_sink_take_released(sink, pp, n);
+       fq = sink->fq;
+       /* Ask for kicks only while FILL runs dry, as zero copy drivers do: a
+        * kick schedules the NAPI, which a busy poller would rather run
+        * itself. Process context refills new queues only and leaves the
+        * flags to their NAPI and to bind.
+        */
+       if (napi && fq && sink->pool->uses_need_wakeup) {

Was not need_wakeup a requirement for using this new mode? If so, why not just set it somewhere and not test it after that?

Quoted 191 lines
net/xdp/xsk_sink.c new file +191 -0
+               if (n)
+                       xsk_clear_rx_need_wakeup(sink->pool);
+               else
+                       xsk_set_rx_need_wakeup(sink->pool);
+       }
+       if (fq && !n)
+               fq->queue_empty_descs++;
+       spin_unlock_bh(&sink->lock);
+       if (!n)
+               return 0;
+
+       for (i = 0; i < n; i++) {
+               dma = page_pool_get_dma_addr_netmem(pp->alloc.cache[i]);
+               dma_sync_single_range_for_device(pp->p.dev, dma, pp->p.offset,
+                                                pp->p.max_len, pp->p.dma_dir);
+       }
+
+       pp->alloc.count = n - 1;
+       return pp->alloc.cache[n - 1];
+}
+
+static bool xsk_sink_release_netmem(struct page_pool *pp, netmem_ref netmem)
+{
+       struct net_iov *niov = netmem_to_net_iov(netmem);
+       struct xsk_sink *sink = pp->mp_priv;
+
+       net_mp_niov_clear_page_pool(niov);
+       llist_add(&sink->nodes[net_iov_idx(niov)], &sink->released);
+       return false;
+}
+
+static int xsk_sink_nl_fill(void *mp_priv, struct sk_buff *rsp,
+                           struct netdev_rx_queue *rxq)
+{
+       return 0;
+}
+
+/* No queue DMAs to the UMEM any longer */
+static void xsk_sink_stop(struct xsk_sink *sink)
+{
+       bool unmap;
+
+       spin_lock_bh(&sink->lock);
+       WRITE_ONCE(sink->rxq, NULL);
+       unmap = sink->fq;
+       sink->fq = NULL;
+       spin_unlock_bh(&sink->lock);
+
+       /* Wait for wakeups that found the sink or the queue */
+       synchronize_net();
+       if (unmap)
+               xp_dma_unmap(sink->pool, XSK_SINK_DMA_ATTR);
+}
+
+/* Device unregister, after the queue stopped */
+static void xsk_sink_uninstall(void *mp_priv, struct netdev_rx_queue *rxq)
+{
+       memset(&rxq->mp_params, 0, sizeof(rxq->mp_params));
+       xsk_sink_stop(mp_priv);
+}
+
+static const struct memory_provider_ops xsk_sink_ops = {
+       .alloc_netmems  = xsk_sink_alloc_netmems,
+       .release_netmem = xsk_sink_release_netmem,
+       .init           = xsk_sink_init,
+       .destroy        = xsk_sink_destroy,
+       .nl_fill        = xsk_sink_nl_fill,
+       .uninstall      = xsk_sink_uninstall,
+       .flags          = MP_XDP_ONLY,
+};
+
+static struct xsk_sink *xsk_sink_create(struct xsk_buff_pool *pool,
+                                       struct device *dev)
+{
+       u32 i, nr = pool->umem->chunks;
+       struct xsk_sink *sink;
+       struct net_iov *niov;
+       dma_addr_t dma;
+
+       sink = kzalloc_obj(*sink, GFP_KERNEL_ACCOUNT);
+       if (!sink)
+               return ERR_PTR(-ENOMEM);
+
+       /* See &xdp_rxq_info.sink_area */
+       BUILD_BUG_ON(offsetof(struct xsk_sink, area));
+
+       sink->area.niovs = kvcalloc(nr, sizeof(*niov), GFP_KERNEL_ACCOUNT);
+       sink->nodes = kvcalloc(nr, sizeof(*sink->nodes), GFP_KERNEL_ACCOUNT);
+       if (!sink->area.niovs || !sink->nodes) {
+               xsk_sink_free(sink);
+               return ERR_PTR(-ENOMEM);
+       }
+
+       sink->area.num_niovs = nr;
+       /* Chunks are pages, see XDP_UMEM_DRV_LAYOUT */
+       sink->area.xdp_vaddr = pool->addrs;
+       sink->area.xdp_vsize = (size_t)nr << PAGE_SHIFT;
+       sink->area.xdp_shift = PAGE_SHIFT;
+       sink->dev = dev;
+       sink->pool = pool;
+       sink->fq = pool->fq;
+       spin_lock_init(&sink->lock);
+       init_llist_head(&sink->released);
+       refcount_set(&sink->refs, 1);
+
+       /* Chunks are pages, see XDP_UMEM_DRV_LAYOUT */
+       for (i = 0; i < nr; i++) {
+               niov = &sink->area.niovs[i];
+               dma = pool->dma_pages[i] & ~XSK_NEXT_PG_CONTIG_MASK;
+               net_iov_init(niov, &sink->area, NET_IOV_XSK);
+               if (net_mp_niov_set_dma_addr(niov, dma)) {
+                       xsk_sink_free(sink);
+                       return ERR_PTR(-ERANGE);
+               }
+       }
+
+       return sink;
+}
+
+/* Sockets sharing the pool find no sink after the grace period of
+ * xsk_sink_stop(), see xsk_wakeup()
+ */
+static void xsk_sink_detach(struct xsk_buff_pool *pool)
+{
+       struct xsk_sink *sink = pool->sink;
+
+       WRITE_ONCE(pool->sink, NULL);
+       xsk_sink_stop(sink);
+       xsk_sink_put(sink);
+       static_branch_dec(&xdp_sink_key);
+}
+
+/**
+ * xsk_sink_bind - install the UMEM of @pool as the provider of an RX queue
+ * @pool: buffer pool with an XDP_UMEM_DRV_LAYOUT UMEM
+ * @dev: device of the queue
+ * @queue_id: RX queue
+ * @flags: bind flags
+ *
+ * Context: RTNL and the instance lock of @dev.
+ * Return: 0 on success. No copy mode takes over on error.
+ */
+int xsk_sink_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+                 u16 queue_id, u16 flags)
+{
+       u32 needed = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT;
+       struct pp_memory_provider_params p = { .mp_ops = &xsk_sink_ops };
+       struct device *dma_dev;
+       struct xsk_sink *sink;
+       int err;
+
+       if (flags & XDP_USE_SG)
+               needed |= NETDEV_XDP_ACT_RX_SG;
+       if (flags & XDP_COPY || !dev->queue_mgmt_ops ||
+           (dev->xdp_features & needed) != needed ||
+           queue_id >= dev->real_num_rx_queues)
+               return -EOPNOTSUPP;
+
+       /* The program of another device would see a leased queue's packets */
+       if (netif_rxq_is_leased(dev, queue_id))
+               return -EOPNOTSUPP;
+
+       /* The device of the queue's page pools, which may differ per queue */
+       dma_dev = netdev_queue_get_dma_dev(dev, queue_id, NETDEV_QUEUE_TYPE_RX);
+       if (!dma_dev)
+               return -EOPNOTSUPP;
+
+       /* Without a program, drivers would build skbs from the buffers */
+       if (!dev_xdp_drv_prog_held(dev))
+               return -ENOENT;
+
+       err = xp_dma_map(pool, dma_dev, XSK_SINK_DMA_ATTR, pool->umem->pgs,
+                        pool->umem->npgs);
+       if (err)
+               return err;
+
+       sink = xsk_sink_create(pool, dma_dev);
+       if (IS_ERR(sink)) {
+               xp_dma_unmap(pool, XSK_SINK_DMA_ATTR);
+               return PTR_ERR(sink);
+       }
+
+       /* Until the first refill of the NAPI: the queue may need FILL to
+        * start. Set before the NAPI runs, which owns the flags after that.
+        */
+       if (pool->uses_need_wakeup)
+               xsk_set_rx_need_wakeup(pool);
+
+       /* The core keeps sink buffers to the socket once the queue runs */
+       static_branch_inc(&xdp_sink_key);
+       sink->rxq = __netif_get_rx_queue(dev, queue_id);

net/xdp/xsk_sink.c line 398

Quoted 10 lines
net/xdp/xsk_sink.c new file +10 -0
+       pool->sink = sink;
+       p.mp_priv = sink;
+       err = netif_mp_open_rxq(dev, queue_id, &p, NULL);
+       if (err) {
+               xsk_sink_detach(pool);
+               return err;
+       }
+
+       return 0;
+}

At a first glance it feels like some of this code could be shared with the current bind, but I guess you have already tried and it is not worth it, or? The commonality seems somewhat spread out.

Quoted 60 lines
net/xdp/xsk_sink.c new file +18 -0
+
+/* Context: RTNL and the instance lock of the device */
+void xsk_sink_unbind(struct xsk_buff_pool *pool)
+{
+       struct xsk_sink *sink = pool->sink;
+       struct pp_memory_provider_params p = {
+               .mp_ops = &xsk_sink_ops,
+               .mp_priv = sink,
+       };
+
+       /* Unregister may have uninstalled the provider already. A queue that
+        * cannot restart without it may still use the UMEM: stop the device.
+        */
+       if (READ_ONCE(sink->rxq) &&
+           netif_mp_close_rxq(pool->netdev, pool->queue_id, &p))
+               netif_close(pool->netdev);
+       xsk_sink_detach(pool);
+}
net/xdp/xsk_sink.h new file +14 -0
new file mode 100644
index 000000000000..3f201163c530
@@ -0,0 +1,14 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* AF_XDP RX in the device's buffer layout, see xsk_sink.c */
+
+#ifndef XSK_SINK_H_
+#define XSK_SINK_H_
+
+struct net_device;
+struct xsk_buff_pool;
+
+int xsk_sink_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+                 u16 queue_id, u16 flags);
+void xsk_sink_unbind(struct xsk_buff_pool *pool);
+
+#endif /* XSK_SINK_H_ */
tools/include/uapi/linux/if_xdp.h +7 -1
index 50d67df78911..160a437ed540 100644
@@ -45,6 +45,13 @@
  */
 #define XDP_UMEM_TX_METADATA_LEN       (1 << 2)
 
+/* RX buffers follow the device's layout: a page-sized chunk may hold
+ * several of them, a packet may span chunks, and the device picks the
+ * offsets. A FILL entry lends a chunk to the kernel. Needs aligned
+ * page-sized chunks and no headroom.
+ */
+#define XDP_UMEM_DRV_LAYOUT            (1 << 4)
+
 struct sockaddr_xdp {
        __u16 sxdp_family;
        __u16 sxdp_flags;
--

2.56.1

#8 lore raw

Re: [PATCH net-next 06/15] xsk: Lend UMEM chunks to the page pools of a queue

Quoted 12 lines · Magnus Karlsson

include/uapi/linux/if_xdp.h line 53

Quoted 6 lines · Björn Töpel
include/uapi/linux/if_xdp.h +6 -0
+/* RX buffers follow the device's layout: a page-sized chunk may hold
+ * several of them, a packet may span chunks, and the device picks the
+ * offsets. A FILL entry lends a chunk to the kernel. Needs aligned
+ * page-sized chunks and no headroom.
+ */
+#define XDP_UMEM_DRV_LAYOUT            (1 << 4)

First of all, this looks a lot better than the previous patch set. Much simpler from a driver point of view, fewer changes to core networking code, and that with just a small change/extension to the uAPI.

Thanks, I do as well. Credits to Kuba that took me down this path.

Quoted 10 lines

But I do not think this name is good. Most users of this API do not care about driver details such as the layout. Why not call it something that has to do with what has changed from the user's point of view? Previously we had implicit ownership transfers. You got a packet in Rx, you own the chunk. Now we have explicit ownership transfer. You do not own the chunk the packet is in, unless you get the new flag back (introduced later). So something with "explicit ownership" or something similar would be better. Or focus the name on that you can support larger chunks, but that is for later patches so might not be the best choice.

Magnus... naming is hard! Good point. There are two things in play; You cannot choose your geometry, and explicit ownership.

XDP_UMEM_EXPLICIT_OWNERSHIP?
XDP_UMEM_EXPLICIT_RELEASE?
XDP_UMEM_CHUNK_COMPLETION?
XDP_UMEM_PACKED_RX?

I'm leaning towards XDP_UMEM_EXPLICIT_RELEASE, and naming the flag XDP_RX_CHUNK_RELEASED?

Quoted 24 lines
Quoted 24 lines
net/xdp/xsk_sink.c new file +18 -0
new file mode 100644
index 000000000000..b78116f25e71
 
+static netmem_ref xsk_sink_alloc_netmems(struct page_pool *pp, gfp_t gfp)
+{
+       struct xsk_sink *sink = pp->mp_priv;
+       /* The NAPI owns the need_wakeup flags */
+       bool napi = in_softirq() && !in_hardirq();
+       struct xsk_queue *fq;
+       dma_addr_t dma;
+       u32 i, n;
+
+       /* The page pool refills only an empty cache */
+       if (WARN_ON_ONCE(pp->alloc.count))
+               return 0;
+
+       spin_lock_bh(&sink->lock);
+       n = xsk_sink_take_fill(sink, pp);
+       n = xsk_sink_take_released(sink, pp, n);
+       fq = sink->fq;
+       /* Ask for kicks only while FILL runs dry, as zero copy drivers do: a
Quoted 8 lines

net/xdp/xsk_sink.c line 197

Quoted 5 lines
net/xdp/xsk_sink.c new file +5 -0
+        * kick schedules the NAPI, which a busy poller would rather run
+        * itself. Process context refills new queues only and leaves the
+        * flags to their NAPI and to bind.
+        */
+       if (napi && fq && sink->pool->uses_need_wakeup) {

Was not need_wakeup a requirement for using this new mode? If so, why not just set it somewhere and not test it after that?

Argh, indeed. 08/15 makes XDP_USE_NEED_WAKEUP mandatory and removes both checks when it enables the mode. I'll move that so the requirement is clear from the start. Good catch.

Quoted 55 lines
Quoted 55 lines
net/xdp/xsk_sink.c new file +55 -0
+int xsk_sink_bind(struct xsk_buff_pool *pool, struct net_device *dev,
+                 u16 queue_id, u16 flags)
+{
+       u32 needed = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT;
+       struct pp_memory_provider_params p = { .mp_ops = &xsk_sink_ops };
+       struct device *dma_dev;
+       struct xsk_sink *sink;
+       int err;
+
+       if (flags & XDP_USE_SG)
+               needed |= NETDEV_XDP_ACT_RX_SG;
+       if (flags & XDP_COPY || !dev->queue_mgmt_ops ||
+           (dev->xdp_features & needed) != needed ||
+           queue_id >= dev->real_num_rx_queues)
+               return -EOPNOTSUPP;
+
+       /* The program of another device would see a leased queue's packets */
+       if (netif_rxq_is_leased(dev, queue_id))
+               return -EOPNOTSUPP;
+
+       /* The device of the queue's page pools, which may differ per queue */
+       dma_dev = netdev_queue_get_dma_dev(dev, queue_id, NETDEV_QUEUE_TYPE_RX);
+       if (!dma_dev)
+               return -EOPNOTSUPP;
+
+       /* Without a program, drivers would build skbs from the buffers */
+       if (!dev_xdp_drv_prog_held(dev))
+               return -ENOENT;
+
+       err = xp_dma_map(pool, dma_dev, XSK_SINK_DMA_ATTR, pool->umem->pgs,
+                        pool->umem->npgs);
+       if (err)
+               return err;
+
+       sink = xsk_sink_create(pool, dma_dev);
+       if (IS_ERR(sink)) {
+               xp_dma_unmap(pool, XSK_SINK_DMA_ATTR);
+               return PTR_ERR(sink);
+       }
+
+       /* Until the first refill of the NAPI: the queue may need FILL to
+        * start. Set before the NAPI runs, which owns the flags after that.
+        */
+       if (pool->uses_need_wakeup)
+               xsk_set_rx_need_wakeup(pool);
+
+       /* The core keeps sink buffers to the socket once the queue runs */
+       static_branch_inc(&xdp_sink_key);
+       sink->rxq = __netif_get_rx_queue(dev, queue_id);
+       pool->sink = sink;
+       p.mp_priv = sink;
+       err = netif_mp_open_rxq(dev, queue_id, &p, NULL);
+       if (err) {
+               xsk_sink_detach(pool);
+               return err;
Quoted 8 lines

net/xdp/xsk_sink.c line 90

Quoted 4 lines
net/xdp/xsk_sink.c new file +4 -0
+       }
+
+       return 0;
+}

At a first glance it feels like some of this code could be shared with the current bind, but I guess you have already tried and it is not worth it, or? The commonality seems somewhat spread out.

Pool setup and registration are already shared in xp_assign_dev(). The main difference is how we start the queue. Classic ZC calls the driver with XDP_SETUP_XSK_POOL; this path maps the UMEM and installs a memory provider with netif_mp_open_rxq().

I'll look for checks we can share without mixing the two setup and unwind paths.

Thanks for having a look!
Björn

#9 lore raw

PATCH 7/15 xsk: Deliver to the socket in the device's buffer layout

In reply to Björn Töpel

Currently, the chunks of a UMEM back the page pools of a queue, but nothing delivers their buffers to the AF_XDP socket, and a chunk that the kernel took never goes back.

Deliver redirected sink buffers to the receiving socket of the queue, the first bound socket with an RX ring, and give each chunk back once the device and the socket are done with it.

Each buffer of a packet becomes one RX descriptor, at the address that the device chose, chained with XDP_PKT_CONTD. Metadata that the program wrote in front of the head is already in place. The socket drops and counts a packet with a buffer outside its UMEM, with more than one buffer without XDP_USE_SG, with metadata that does not fit in front of the head within its chunk, or when the RX ring is full. Buffers of other memory, and copies, never go to such a socket.

The socket drops the reference of each buffer it takes without an atomic. Sink buffers go nowhere but the socket of their queue, so only the queue NAPI changes the count of a chunk in flight, or nothing does while it is stopped.

A chunk goes back to userspace once nothing in the kernel uses it, if a buffer of it reached the socket. If the socket's drop frees the chunk, the descriptor of that buffer carries the new XDP_RX_CHUNK_FREE. If the device lets go of the chunk later, the page pool hands it to the provider on its last put, and an empty descriptor at the chunk gives it back at the next flush of the queue NAPI, or at a refill while no packets come. Chunks that find the RX ring full stay on the hand-off list for a later poll, and the refill asks the socket for a kick while any chunk waits, so that a reader that fell behind gets them once it has drained its ring. A returned chunk stays charged to its page pool, which takes it straight into its cache when userspace lends it again. Chunks whose buffers all stayed in the kernel, as for dropped packets, stay there.

Only the queue NAPI writes to the RX ring and takes from the hand-off list. A refill gives chunks back only with BH disabled, which is the queue NAPI, as drivers refill from process context with BH enabled. Busy polling runs the same NAPI, and a queue restart stops the old queue before the new one runs, also in mlx5, whose new channels have their own NAPIs. So the NAPIs of an old and a new page pool never run at the same time. Unbind and device unregister take the list only after the queue stopped.

When the provider goes, page pools put back the chunks they hold for userspace, so that they can be destroyed. Device unregister and unbind may both do this, and the second skips what the first put back. None of this is reachable until the next patch lets sockets bind.

---
 include/net/xdp_sock.h            |   8 +
 include/uapi/linux/if_xdp.h       |  12 +-
 net/core/filter.c                 |   9 +
 net/xdp/xsk.c                     |  28 ++-
 net/xdp/xsk_sink.c                | 362 +++++++++++++++++++++++++++++-
 net/xdp/xsk_sink.h                |   5 +
 tools/include/uapi/linux/if_xdp.h |  12 +-
 7 files changed, 419 insertions(+), 17 deletions(-)
include/net/xdp_sock.h +8 -0
index 6e70b320b399..e81724fd624c 100644
@@ -126,6 +126,8 @@ struct xsk_tx_metadata_ops {
 int xsk_generic_rcv(struct xdp_sock *xs, struct xdp_buff *xdp);
 int __xsk_map_redirect(struct xdp_sock *xs, struct xdp_buff *xdp);
 void __xsk_map_flush(struct list_head *flush_list);
+int xsk_sink_redirect(struct xdp_buff *xdp, enum bpf_map_type map_type,
+		      void *fwd);
 INDIRECT_CALLABLE_DECLARE(void xsk_destruct_skb(struct sk_buff *));
 
 /**
@@ -182,6 +184,12 @@ static inline int xsk_generic_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 	return -ENOTSUPP;
 }
 
+static inline int xsk_sink_redirect(struct xdp_buff *xdp,
+				    enum bpf_map_type map_type, void *fwd)
+{
+	return -EOPNOTSUPP;
+}
+
 static inline int __xsk_map_redirect(struct xdp_sock *xs, struct xdp_buff *xdp)
 {
 	return -EOPNOTSUPP;
include/uapi/linux/if_xdp.h +10 -2
index 160a437ed540..933b8700281f 100644
@@ -47,8 +47,9 @@
 
 /* RX buffers follow the device's layout: a page-sized chunk may hold
  * several of them, a packet may span chunks, and the device picks the
- * offsets. A FILL entry lends a chunk to the kernel. Needs aligned
- * page-sized chunks and no headroom.
+ * offsets. A FILL entry lends a chunk to the kernel, and an RX descriptor
+ * with XDP_RX_CHUNK_FREE gives it back. Needs aligned page-sized chunks and
+ * no headroom.
  */
 #define XDP_UMEM_DRV_LAYOUT		(1 << 4)
 
@@ -189,4 +190,11 @@ struct xdp_desc {
 /* TX packet carries valid metadata. */
 #define XDP_TX_METADATA (1 << 1)
 
+/* Flag on an RX descriptor of an XDP_UMEM_DRV_LAYOUT UMEM: the kernel is done
+ * with the UMEM chunk of the descriptor, and puts nothing more in it. The
+ * chunk is userspace's again. An empty descriptor at the chunk carries only
+ * this flag, when the device let go of the chunk after its last buffer.
+ */
+#define XDP_RX_CHUNK_FREE (1 << 2)
+
 #endif /* _UAPI_LINUX_IF_XDP_H */
net/core/filter.c +9 -0
index d5774b2577e7..30b35d00e6b2 100644
@@ -4775,6 +4775,15 @@ 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;
 
+	/* A sink buffer goes to an AF_XDP socket of its queue */
+	if (static_branch_unlikely(&xdp_sink_key) && xdp_buff_is_sink(xdp)) {
+		void *fwd = ri->tgt_value;
+
+		ri->map_id = 0;
+		ri->map_type = BPF_MAP_TYPE_UNSPEC;
+		return xsk_sink_redirect(xdp, map_type, fwd);
+	}
+
 	if (map_type == BPF_MAP_TYPE_XSKMAP)
 		return __xdp_do_redirect_xsk(ri, dev, xdp, xdp_prog);
 
net/xdp/xsk.c +27 -1
index f22f9a2cdbbe..0753fac8d4a8 100644
@@ -35,6 +35,7 @@
 #include "../core/dev.h"
 
 #include "xsk_queue.h"
+#include "xsk_sink.h"
 #include "xdp_umem.h"
 #include "xsk.h"
 
@@ -437,6 +438,12 @@ static bool xsk_dev_queue_valid(const struct xdp_sock *xs,
 	return false;
 }
 
+/* The pool receives in the device's buffer layout, or did */
+static bool xsk_drv_layout(const struct xdp_sock *xs)
+{
+	return xs->pool->umem->flags & XDP_UMEM_DRV_LAYOUT;
+}
+
 static int xsk_rcv_check(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len)
 {
 	if (!xsk_is_bound(xs))
@@ -454,8 +461,14 @@ static int xsk_rcv_check(struct xdp_sock *xs, struct xdp_buff *xdp, u32 len)
 
 static void xsk_flush(struct xdp_sock *xs)
 {
+	struct xsk_sink *sink = xs->pool->sink;
+
+	if (sink)
+		xsk_sink_flush(sink);
 	xskq_prod_submit(xs->rx);
-	__xskq_cons_release(xs->pool->fq);
+	/* A sink releases FILL under its lock, see xsk_sink_take_fill() */
+	if (!sink)
+		__xskq_cons_release(xs->pool->fq);
 	sock_def_readable(&xs->sk);
 }
 
@@ -465,6 +478,11 @@ int xsk_generic_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 	int err;
 
 	err = xsk_rcv_check(xs, xdp, len);
+	/* A sink socket takes buffers of its provider only */
+	if (!err && xsk_drv_layout(xs)) {
+		xs->rx_dropped++;
+		err = -EOPNOTSUPP;
+	}
 	if (!err) {
 		spin_lock_bh(&xs->pool->rx_lock);
 		err = __xsk_rcv(xs, xdp, len);
@@ -489,6 +507,14 @@ static int xsk_rcv(struct xdp_sock *xs, struct xdp_buff *xdp)
 		return xsk_rcv_zc(xs, xdp, len);
 	}
 
+	/* Sink buffers take xsk_sink_redirect(); others cannot go to a sink
+	 * socket
+	 */
+	if (xsk_drv_layout(xs)) {
+		xs->rx_dropped++;
+		return -EOPNOTSUPP;
+	}
+
 	err = __xsk_rcv(xs, xdp, len);
 	if (!err)
 		xdp_return_buff(xdp);
net/xdp/xsk_sink.c +350 -12

442 lines not on this page · raw message

net/xdp/xsk_sink.h +5 -0
index 3f201163c530..fe73b2916608 100644
@@ -5,10 +5,15 @@
 #define XSK_SINK_H_
 
 struct net_device;
+struct xdp_sock;
 struct xsk_buff_pool;
+struct xsk_sink;
 
 int xsk_sink_bind(struct xsk_buff_pool *pool, struct net_device *dev,
 		  u16 queue_id, u16 flags);
 void xsk_sink_unbind(struct xsk_buff_pool *pool);
+void xsk_sink_flush(struct xsk_sink *sink);
+void xsk_sink_add_sock(struct xsk_sink *sink, struct xdp_sock *xs);
+struct xdp_sock *xsk_sink_sock(struct xsk_sink *sink);
 
 #endif /* XSK_SINK_H_ */
tools/include/uapi/linux/if_xdp.h +10 -2
index 160a437ed540..933b8700281f 100644
@@ -47,8 +47,9 @@
 
 /* RX buffers follow the device's layout: a page-sized chunk may hold
  * several of them, a packet may span chunks, and the device picks the
- * offsets. A FILL entry lends a chunk to the kernel. Needs aligned
- * page-sized chunks and no headroom.
+ * offsets. A FILL entry lends a chunk to the kernel, and an RX descriptor
+ * with XDP_RX_CHUNK_FREE gives it back. Needs aligned page-sized chunks and
+ * no headroom.
  */
 #define XDP_UMEM_DRV_LAYOUT		(1 << 4)
 
@@ -189,4 +190,11 @@ struct xdp_desc {
 /* TX packet carries valid metadata. */
 #define XDP_TX_METADATA (1 << 1)
 
+/* Flag on an RX descriptor of an XDP_UMEM_DRV_LAYOUT UMEM: the kernel is done
+ * with the UMEM chunk of the descriptor, and puts nothing more in it. The
+ * chunk is userspace's again. An empty descriptor at the chunk carries only
+ * this flag, when the device let go of the chunk after its last buffer.
+ */
+#define XDP_RX_CHUNK_FREE (1 << 2)
+
 #endif /* _UAPI_LINUX_IF_XDP_H */
Signature · 1 line
2.56.1
#10 lore raw

PATCH 8/15 xsk: Receive in the device's buffer layout

In reply to Björn Töpel

Currently, userspace cannot use the device's buffer layout of the previous two patches.

Accept XDP_UMEM_DRV_LAYOUT at UMEM registration, with aligned page-sized chunks and no headroom, and install the provider when a socket with such a UMEM binds to a queue.

A queue in the device's buffer layout has one receiving socket, the first that binds with an RX ring. Another socket with an RX ring gets -EBUSY, also after the receiving socket went, as nothing would fill its RX ring. Sockets that share the UMEM may transmit in copy mode. The provider goes when the receiving socket closes, not with the last socket of the pool, so that the program can be detached right after. The UMEM has no copy mode, so a bind with XDP_COPY fails, and a bind that cannot install the provider fails instead of falling back.

recvmsg() and poll() wake the queue NAPI when the RX need_wakeup flag asks for it, as they wake the driver for zero copy. A wakeup that races with unbind finds no queue, and recvmsg() returns -ENETDOWN. The queue NAPI changes the need_wakeup flags while sendmsg(), recvmsg() and poll() read them without a lock, so mark those accesses, and let poll() read the flags once.

---
 net/xdp/xdp_umem.c |  5 +++
 net/xdp/xsk.c      | 82 +++++++++++++++++++++++++++++++++++++++-------
 net/xdp/xsk_sink.c | 25 ++++++++++++--
 net/xdp/xsk_sink.h |  1 +
 4 files changed, 98 insertions(+), 15 deletions(-)
net/xdp/xdp_umem.c +5 -0
index cd8643360eb3..5989e5e0e17e 100644
@@ -153,6 +153,7 @@ static int xdp_umem_account_pages(struct xdp_umem *umem)
 		XDP_UMEM_UNALIGNED_CHUNK_FLAG | \
 		XDP_UMEM_TX_SW_CSUM | \
 		XDP_UMEM_TX_METADATA_LEN | \
+		XDP_UMEM_DRV_LAYOUT | \
 	0)
 
 static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)
@@ -207,6 +208,10 @@ static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)
 		       SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) - 128)
 		return -EINVAL;
 
+	if (mr->flags & XDP_UMEM_DRV_LAYOUT &&
+	    (unaligned_chunks || chunk_size != PAGE_SIZE || headroom))
+		return -EINVAL;
+
 	if (mr->flags & XDP_UMEM_TX_METADATA_LEN) {
 		if (mr->tx_metadata_len >= 256 || mr->tx_metadata_len % 8)
 			return -EINVAL;
net/xdp/xsk.c +70 -12

164 lines not on this page · raw message

net/xdp/xsk_sink.c +22 -3
index 9f1f7cf82266..2c23fecb59d4 100644
@@ -297,7 +297,7 @@ static netmem_ref xsk_sink_alloc_netmems(struct page_pool *pp, gfp_t gfp)
 	 * chunks that waited. Process context refills new queues only and
 	 * leaves the flags to their NAPI and to bind.
 	 */
-	if (napi && fq && sink->pool->uses_need_wakeup) {
+	if (napi && fq) {
 		if (n && llist_empty(&sink->handed))
 			xsk_clear_rx_need_wakeup(sink->pool);
 		else
@@ -501,6 +501,10 @@ int xsk_sink_bind(struct xsk_buff_pool *pool, struct net_device *dev,
 	struct xsk_sink *sink;
 	int err;
 
+	/* Without a wakeup, a queue that used up the FILL ring stays dry */
+	if (!(flags & XDP_USE_NEED_WAKEUP))
+		return -EINVAL;
+
 	if (flags & XDP_USE_SG)
 		needed |= NETDEV_XDP_ACT_RX_SG;
 	if (flags & XDP_COPY || !dev->queue_mgmt_ops ||
@@ -535,8 +539,7 @@ int xsk_sink_bind(struct xsk_buff_pool *pool, struct net_device *dev,
 	/* Until the first refill of the NAPI: the queue may need FILL to
 	 * start. Set before the NAPI runs, which owns the flags after that.
 	 */
-	if (pool->uses_need_wakeup)
-		xsk_set_rx_need_wakeup(pool);
+	xsk_set_rx_need_wakeup(pool);
 
 	/* The core keeps sink buffers to the socket once the queue runs */
 	static_branch_inc(&xdp_sink_key);
@@ -591,6 +594,22 @@ void xsk_sink_unbind(struct xsk_buff_pool *pool)
 	xsk_sink_detach(pool);
 }
 
+int xsk_sink_wakeup(struct xsk_sink *sink)
+{
+	struct netdev_rx_queue *rxq;
+	struct napi_struct *napi;
+
+	rxq = READ_ONCE(sink->rxq);
+	napi = rxq ? READ_ONCE(rxq->napi) : NULL;
+	if (!napi)
+		return -ENETDOWN;
+
+	local_bh_disable();
+	napi_schedule(napi);
+	local_bh_enable();
+	return 0;
+}
+
 /* The net_iov of @netmem if it is one of ours; tells by its address */
 static __always_inline struct net_iov *xsk_sink_niov(struct xsk_sink *sink,
 						     netmem_ref netmem)
net/xdp/xsk_sink.h +1 -0
index fe73b2916608..ac6913207ca0 100644
@@ -12,6 +12,7 @@ struct xsk_sink;
 int xsk_sink_bind(struct xsk_buff_pool *pool, struct net_device *dev,
 		  u16 queue_id, u16 flags);
 void xsk_sink_unbind(struct xsk_buff_pool *pool);
+int xsk_sink_wakeup(struct xsk_sink *sink);
 void xsk_sink_flush(struct xsk_sink *sink);
 void xsk_sink_add_sock(struct xsk_sink *sink, struct xdp_sock *xs);
 struct xdp_sock *xsk_sink_sock(struct xsk_sink *sink);
Signature · 1 line
2.56.1
#11 lore raw

PATCH 9/15 eth: fbnic: Support XDP redirect

In reply to Björn Töpel

Currently, fbnic treats XDP_REDIRECT as an invalid action and drops the packet, so AF_XDP, devmap and cpumap do not work on it.

Support the verdict.

A failed redirect drops the packet, as XDP_DROP does. Each RX queue flushes its redirects once per poll, after refilling its rings, so that a target that gives buffers back, such as an XDP-only memory provider, sees the buffers that the queue freed. Any native XDP program on fbnic can then redirect to devmap, cpumap and AF_XDP sockets in copy mode.

The NAPI vector, not a variable of the RX loop, notes that a flush is due, as one more live variable in that loop costs native XDP_DROP six instructions per packet.

---
 drivers/net/ethernet/meta/fbnic/fbnic_netdev.c |  3 ++-
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c   | 12 ++++++++++++
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h   |  1 +
 3 files changed, 15 insertions(+), 1 deletion(-)
drivers/net/ethernet/meta/fbnic/fbnic_netdev.c +2 -1
index 52244219d166..9f0d8c070d1c 100644
@@ -822,7 +822,8 @@ 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 +12 -0
index 07d4b2e92362..2c8276d23a15 100644
@@ -22,6 +22,7 @@ enum {
 	FBNIC_XDP_PASS = 0,
 	FBNIC_XDP_CONSUME,
 	FBNIC_XDP_TX,
+	FBNIC_XDP_REDIRECT,
 	FBNIC_XDP_LEN_ERR,
 };
 
@@ -1211,6 +1212,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))
+			break;
+		return ERR_PTR(-FBNIC_XDP_REDIRECT);
 	default:
 		bpf_warn_invalid_xdp_action(nv->napi.dev, xdp_prog, act);
 		fallthrough;
@@ -1334,6 +1339,8 @@ static int fbnic_clean_rcq(struct fbnic_napi_vector *nv,
 				napi_gro_receive(&nv->napi, skb);
 			} else if (skb == ERR_PTR(-FBNIC_XDP_TX)) {
 				pkt_tail = nv->qt[0].sub1.tail;
+			} else if (skb == ERR_PTR(-FBNIC_XDP_REDIRECT)) {
+				nv->xdp_flush = true;
 			} else if (PTR_ERR(skb) == -FBNIC_XDP_CONSUME) {
 				fbnic_put_pkt_buff(qt, pkt, 1);
 			} else {
@@ -1387,6 +1394,11 @@ static int fbnic_clean_rcq(struct fbnic_napi_vector *nv,
 		fbnic_clean_bdq(&qt->sub1, head1, budget);
 	fbnic_fill_bdq(&qt->sub1);
 
+	if (nv->xdp_flush) {
+		nv->xdp_flush = false;
+		xdp_do_flush();
+	}
+
 	/* Record the current head/tail of the queue */
 	if (rcq->head != head) {
 		rcq->head = head;
drivers/net/ethernet/meta/fbnic/fbnic_txrx.h +1 -0
index 6ee3cce3d942..7bc0c25ac50b 100644
@@ -173,6 +173,7 @@ struct fbnic_napi_vector {
 	u16 v_idx;
 	u8 txt_count;
 	u8 rxt_count;
+	bool xdp_flush;		/* An XDP redirect awaits xdp_do_flush() */
 
 	struct fbnic_q_triad qt[];
 };
Signature · 1 line
2.56.1
#12 lore raw

PATCH 10/15 eth: fbnic: Receive into XDP-only memory providers

In reply to Björn Töpel

Currently, fbnic takes the address of an RX head as a page address and puts the head back by that address, so an XDP-only memory provider, such as the AF_XDP sink, cannot back its RX pool. Otherwise fbnic builds XDP buffers from page pool netmem and splits pages with page pool fragments, all that such a provider needs.

Let the header page pool, which the payload ring shares without header split, take an XDP-only provider, and handle heads by their netmem, taking their address with xdp_netmem_address().

The core turns XDP_TX and XDP_PASS on XDP-only buffers into drops, so fbnic needs no checks of its own. fbnic skips the prefetch of an XDP-only head, as the kernel reads it only if the program does, and the prefetch may cost a page walk. Redirects are flushed after the poll has freed its buffers, so the provider takes them back in the same poll. The frame of an XDP buffer ends at the headroom of the next one, so a program may grow the tail of an XDP-only buffer into the room that fbnic leaves for a shared info.

---
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.c | 33 ++++++++++----------
 drivers/net/ethernet/meta/fbnic/fbnic_txrx.h |  2 ++
 2 files changed, 19 insertions(+), 16 deletions(-)
drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +17 -16
index 2c8276d23a15..c2e20a7b36a8 100644
@@ -765,15 +765,14 @@ static void fbnic_page_pool_init(struct fbnic_ring *ring, unsigned int idx,
 	rx_buf->netmem = netmem;
 }
 
-static struct page *
+static netmem_ref
 fbnic_page_pool_get_head(struct fbnic_q_triad *qt, unsigned int idx)
 {
 	struct fbnic_rx_buf *rx_buf = &qt->sub0.rx_buf[idx];
 
 	rx_buf->pagecnt_bias--;
 
-	/* sub0 is always fed system pages, from the NAPI-level page_pool */
-	return netmem_to_page(rx_buf->netmem);
+	return rx_buf->netmem;
 }
 
 static netmem_ref
@@ -1001,13 +1000,12 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 	unsigned int len = FIELD_GET(FBNIC_RCD_AL_BUFF_LEN_MASK, rcd);
 	unsigned int hdr_pg_idx = fbnic_rcd_bd_idx(&qt->sub0, rcd);
 	unsigned int frame_sz, hdr_pg_start, hdr_pg_end, headroom;
-	unsigned char *hdr_start;
-	struct page *page;
+	netmem_ref netmem;
 
 	/* data_hard_start should always be NULL when this is called */
 	WARN_ON_ONCE(pkt->buff.data_hard_start);
 
-	page = fbnic_page_pool_get_head(qt, hdr_pg_idx);
+	netmem = fbnic_page_pool_get_head(qt, hdr_pg_idx);
 
 	/* Short-cut the end calculation if we know page is fully consumed */
 	hdr_pg_end = FIELD_GET(FBNIC_RCD_AL_PAGE_FIN, rcd) ?
@@ -1020,15 +1018,20 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd,
 	hdr_pg_start += fbnic_rcd_bd_page_offset(&qt->sub0, rcd);
 
 	/* Sync DMA buffer */
-	dma_sync_single_range_for_cpu(nv->dev, page_pool_get_dma_addr(page),
+	dma_sync_single_range_for_cpu(nv->dev,
+				      page_pool_get_dma_addr_netmem(netmem),
 				      hdr_pg_start, frame_sz,
 				      DMA_BIDIRECTIONAL);
 
 	/* Build frame around buffer */
-	hdr_start = page_address(page) + hdr_pg_start;
-	net_prefetch(hdr_start + headroom);
-	xdp_prepare_buff(&pkt->buff, hdr_start, headroom,
-			 len - FBNIC_RX_PAD, true);
+	xdp_prepare_buff(&pkt->buff, xdp_netmem_address(netmem) + hdr_pg_start,
+			 headroom, len - FBNIC_RX_PAD, true);
+	pkt->head = netmem;
+	/* The kernel reads an XDP-only head only if the program does, and a
+	 * prefetch may cost a page walk
+	 */
+	if (!netmem_is_net_iov(netmem))
+		net_prefetch(pkt->buff.data);
 
 	pkt->hwtstamp = 0;
 	pkt->add_frag_failed = false;
@@ -1072,8 +1075,6 @@ static void fbnic_add_rx_frag(struct fbnic_napi_vector *nv, u64 rcd,
 static void fbnic_put_pkt_buff(struct fbnic_q_triad *qt,
 			       struct fbnic_pkt_buff *pkt, int budget)
 {
-	struct page *page;
-
 	if (!pkt->buff.data_hard_start)
 		return;
 
@@ -1092,8 +1093,7 @@ static void fbnic_put_pkt_buff(struct fbnic_q_triad *qt,
 		}
 	}
 
-	page = virt_to_page(pkt->buff.data_hard_start);
-	page_pool_put_full_page(qt->sub0.page_pool, page, !!budget);
+	page_pool_put_full_netmem(qt->sub0.page_pool, pkt->head, !!budget);
 }
 
 static struct sk_buff *fbnic_build_skb(struct fbnic_napi_vector *nv,
@@ -1611,7 +1611,8 @@ fbnic_alloc_qt_page_pools(struct fbnic_net *fbn, struct fbnic_q_triad *qt,
 	struct page_pool_params pp_params = {
 		.order = 0,
 		.flags = PP_FLAG_DMA_MAP |
-			 PP_FLAG_DMA_SYNC_DEV,
+			 PP_FLAG_DMA_SYNC_DEV |
+			 PP_FLAG_ALLOW_XDP_ONLY_NETMEM,
 		.pool_size = fbn->hpq_size + fbn->ppq_size,
 		.nid = NUMA_NO_NODE,
 		.dev = fbn->netdev->dev.parent,
drivers/net/ethernet/meta/fbnic/fbnic_txrx.h +2 -0
index 7bc0c25ac50b..ea5f70462aa6 100644
@@ -81,6 +81,8 @@ struct fbnic_net;
 
 struct fbnic_pkt_buff {
 	struct xdp_buff buff;
+	/* Head buffer, from the HPQ */
+	netmem_ref head;
 	ktime_t hwtstamp;
 	bool add_frag_failed;
 };
Signature · 1 line
2.56.1
#13 lore raw

PATCH 11/15 net: Add netif_rxq_has_xdp_only_mp()

In reply to Björn Töpel

A driver lays out an RX queue before it creates the page pools of that queue, so it cannot ask a pool whether a memory provider backs it, and a layout that depends on the provider has nothing to read.

Tell the driver from the queue. Return whether the provider of an RX queue is XDP-only, which the next patch uses to keep an mlx5 queue from waiting for buffers that its socket has not lent yet.

Page pools of a queue are created under the instance lock, which the caller holds as well, so the answer agrees with the pools of that queue. A queue index past the device's RX queues has no provider.

---
 include/net/netdev_queues.h |  1 +
 net/core/netdev_rx_queue.c  | 25 +++++++++++++++++++++++++
 2 files changed, 26 insertions(+)
include/net/netdev_queues.h +1 -0
index c5335e935b7d..813388778797 100644
@@ -235,6 +235,7 @@ void netdev_queue_config(struct net_device *dev, int rxq,
 			 struct netdev_queue_config *qcfg);
 
 bool netif_rxq_has_unreadable_mp(struct net_device *dev, unsigned int rxq_idx);
+bool netif_rxq_has_xdp_only_mp(struct net_device *dev, unsigned int rxq_idx);
 
 /**
  * DOC: Lockless queue stopping / waking helpers.
net/core/netdev_rx_queue.c +25 -0
index 2e10201fc0c0..212f1b9415b3 100644
@@ -94,6 +94,31 @@ bool netif_rxq_has_unreadable_mp(struct net_device *dev, unsigned int rxq_idx)
 }
 EXPORT_SYMBOL(netif_rxq_has_unreadable_mp);
 
+/**
+ * netif_rxq_has_xdp_only_mp() - whether an XDP-only provider backs an RX queue
+ * @dev: device of the queue
+ * @rxq_idx: RX queue of @dev itself, not of a lease
+ *
+ * The page pools of the queue that allow it take the provider, see
+ * %PP_FLAG_ALLOW_XDP_ONLY_NETMEM. They are created under the instance lock,
+ * which the caller holds, so they agree with the answer.
+ *
+ * Return: true if the queue has a provider with %MP_XDP_ONLY.
+ */
+bool netif_rxq_has_xdp_only_mp(struct net_device *dev, unsigned int rxq_idx)
+{
+	const struct memory_provider_ops *ops;
+
+	netdev_assert_locked(dev);
+
+	if (rxq_idx >= dev->real_num_rx_queues)
+		return false;
+
+	ops = __netif_get_rx_queue(dev, rxq_idx)->mp_params.mp_ops;
+	return ops && ops->flags & MP_XDP_ONLY;
+}
+EXPORT_SYMBOL(netif_rxq_has_xdp_only_mp);
+
 bool netif_rxq_has_mp(struct net_device *dev, unsigned int rxq_idx)
 {
 	if (rxq_idx < dev->real_num_rx_queues)
Signature · 1 line
2.56.1
#14 lore raw

PATCH 12/15 eth: mlx5e: Receive into XDP-only memory providers

In reply to Björn Töpel

Currently, mlx5 refuses queue restarts while an XDP program is attached, and its page pools take no memory provider next to XDP. An XDP-only memory provider, such as the AF_XDP sink, needs both, as installing it restarts the queue with the program that steers its packets attached.

Let the page pools of RQs that run an XDP program take XDP-only providers, and accept queue restarts with a program attached.

mlx5 already builds and frees XDP buffers by netmem. Take their addresses with xdp_netmem_address(), which covers XDP-only net_iovs and is netmem_address() for pages, so the skb paths do not change. The core handles the rest of the XDP path. The trap RQ and the PTP RQ use queue index 0 as well, but run no program and build skbs around their buffers, so they keep system pages. A restart clones the channel with its program. Each RQ takes its own reference to the program, and the restart deactivates all channels, XDP SQs included, so the clone needs nothing more.

The RQ keeps its layout. A stride of the linear striding RQ still holds the shared info of the skb that XDP_PASS builds, so at MTU 1500 an AF_XDP sink gets one packet per 4 KiB UMEM chunk. With ConnectX-7 and 66-byte frames on one core, it receives 16.42 Mpps (179 cycles per packet).

An RQ that the provider backs fills from the FILL ring of its socket, which stays empty while the socket waits for chunks that only the queue can give back. Activation no longer waits for such an RQ to reach its minimum of posted buffers, as it already skips the XSK RQ for the same reason. Otherwise a queue that restarts under a slow reader times out, the health reporter turns off its ICOSQ, and nothing fills the RQ again. The check takes netif_rxq_has_xdp_only_mp().

Any user of the queue management API may then restart an mlx5 queue with a program attached. In the tree, only memory providers restart queues, and all but XDP-only ones refuse XDP.

---
 drivers/net/ethernet/mellanox/mlx5/core/en_main.c | 14 ++++++++++++--
 drivers/net/ethernet/mellanox/mlx5/core/en_rx.c   | 10 +++++-----
 2 files changed, 17 insertions(+), 7 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/en_main.c +12 -2
index 06a8a4be4be7..a8d46508b6fc 100644
@@ -1012,6 +1012,9 @@ static int mlx5e_alloc_rq(struct mlx5e_params *params,
 
 		pp_params.order     = pool_order;
 		pp_params.flags     = PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV;
+		/* Trap and PTP RQs use queue 0 too, without a program */
+		if (params->xdp_prog)
+			pp_params.flags |= PP_FLAG_ALLOW_XDP_ONLY_NETMEM;
 		pp_params.pool_size = pool_size;
 		pp_params.nid       = node;
 		pp_params.dev       = rq->pdev;
@@ -3050,6 +3053,14 @@ static int mlx5e_wait_channels_min_rx_wqes(struct mlx5e_channels *chs)
 		if (test_bit(MLX5E_CHANNEL_STATE_XSK, c->state))
 			continue;
 
+		/* An RQ that an XDP-only provider backs fills from the FILL
+		 * ring of its socket, which stays empty until the socket
+		 * gets its chunks back, so a queue that restarts under a
+		 * slow reader would never meet the bound.
+		 */
+		if (netif_rxq_has_xdp_only_mp(c->netdev, c->ix))
+			continue;
+
 		err |= mlx5e_wait_for_min_rx_wqes(&c->rq, timeout);
 
 		/* Don't wait on the XSK RQ, because the newer xdpsock sample
@@ -5754,10 +5765,9 @@ static int mlx5e_queue_mem_alloc(struct net_device *dev,
 
 	if (MLX5E_GET_PFLAG(&chs->params, MLX5E_PFLAG_TX_PORT_TS) ||
 	    chs->params.ptp_rx   ||
-	    chs->params.xdp_prog ||
 	    priv->htb) {
 		netdev_err(priv->netdev,
-			   "Cloning channels with Port/rx PTP, XDP or HTB is not supported\n");
+			   "Cloning channels with Port/rx PTP or HTB is not supported\n");
 		err = -EOPNOTSUPP;
 		goto unlock;
 	}
drivers/net/ethernet/mellanox/mlx5/core/en_rx.c +5 -5
index 22fea4739a2c..130e54f81293 100644
@@ -327,7 +327,7 @@ static void *mlx5e_mpwqe_get_linear_page_frag(struct mlx5e_rq *rq)
 	frag_offset = li->frag_page.frags << MLX5E_XDP_LOG_MAX_LINEAR_SZ;
 	WARN_ON(frag_offset >= BIT(rq->mpwqe.page_shift));
 
-	return netmem_address(li->frag_page.netmem) + frag_offset;
+	return xdp_netmem_address(li->frag_page.netmem) + frag_offset;
 }
 
 static inline int mlx5e_get_rx_frag(struct mlx5e_rq *rq,
@@ -1585,7 +1585,7 @@ mlx5e_skb_from_cqe_linear(struct mlx5e_rq *rq, struct mlx5e_wqe_frag_info *wi,
 	dma_addr_t addr;
 	u32 frag_size;
 
-	va             = netmem_address(frag_page->netmem) + wi->offset;
+	va             = xdp_netmem_address(frag_page->netmem) + wi->offset;
 	data           = va + rx_headroom;
 	frag_size      = MLX5_SKB_FRAG_SZ(rx_headroom + cqe_bcnt);
 
@@ -1640,7 +1640,7 @@ mlx5e_skb_from_cqe_nonlinear(struct mlx5e_rq *rq, struct mlx5e_wqe_frag_info *wi
 
 	frag_page = wi->frag_page;
 
-	va = netmem_address(frag_page->netmem) + wi->offset;
+	va = xdp_netmem_address(frag_page->netmem) + wi->offset;
 	frag_consumed_bytes = min_t(u32, frag_info->frag_size, cqe_bcnt);
 
 	addr = page_pool_get_dma_addr_netmem(frag_page->netmem);
@@ -1940,7 +1940,7 @@ mlx5e_skb_from_cqe_mpwrq_nonlinear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *w
 
 	prog = rcu_dereference(rq->xdp_prog);
 
-	head_addr = netmem_address(head_page->netmem) + head_offset;
+	head_addr = xdp_netmem_address(head_page->netmem) + head_offset;
 
 	if (prog) {
 		/* area for bpf_xdp_[store|load]_bytes */
@@ -2114,7 +2114,7 @@ mlx5e_skb_from_cqe_mpwrq_linear(struct mlx5e_rq *rq, struct mlx5e_mpw_info *wi,
 		return NULL;
 	}
 
-	va             = netmem_address(frag_page->netmem) + head_offset;
+	va             = xdp_netmem_address(frag_page->netmem) + head_offset;
 	data           = va + rx_headroom;
 	frag_size      = MLX5_SKB_FRAG_SZ(rx_headroom + cqe_bcnt);
 
Signature · 1 line
2.56.1
#15 lore raw

PATCH 13/15 eth: bnxt: Receive into XDP-only memory providers

In reply to Björn Töpel

Currently, bnxt takes RX heads as pages in page mode, which XDP needs, and frees XDP fragments with page APIs, so an XDP-only memory provider, such as the AF_XDP sink, cannot back its page pool.

Handle heads and fragments as netmem in page mode, and let the page pool take XDP-only providers.

Page-mode heads take their address with xdp_netmem_address(), which is the page address for system pages, and system pages keep their bits in the netmem, so the skb paths do not change. As for any provider, page_pool_is_unreadable() is true for an XDP-only one, so bnxt also sets up its separate head pool, which page mode leaves empty. The core turns XDP_TX and XDP_PASS on XDP-only buffers into drops, so bnxt needs no checks of its own. The frame of an XDP buffer ends with its head buffer, so a program may grow the tail of an XDP-only buffer into the room that bnxt leaves for a shared info.

---
 drivers/net/ethernet/broadcom/bnxt/bnxt.c     | 39 ++++++-------------
 drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.c | 19 +++++----
 drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.h |  2 +-
 3 files changed, 23 insertions(+), 37 deletions(-)
drivers/net/ethernet/broadcom/bnxt/bnxt.c +11 -28
index 5c6c2219a481..465465db53ba 100644
@@ -962,27 +962,6 @@ static bool bnxt_separate_head_pool(struct bnxt_rx_ring_info *rxr)
 	return rxr->need_head_pool || rxr->rx_page_size < PAGE_SIZE;
 }
 
-static struct page *__bnxt_alloc_rx_page(struct bnxt *bp, dma_addr_t *mapping,
-					 struct bnxt_rx_ring_info *rxr,
-					 unsigned int *offset,
-					 gfp_t gfp)
-{
-	struct page *page;
-
-	if (rxr->rx_page_size < PAGE_SIZE) {
-		page = page_pool_dev_alloc_frag(rxr->page_pool, offset,
-						rxr->rx_page_size);
-	} else {
-		page = page_pool_dev_alloc_pages(rxr->page_pool);
-		*offset = 0;
-	}
-	if (!page)
-		return NULL;
-
-	*mapping = page_pool_get_dma_addr(page) + *offset;
-	return page;
-}
-
 static netmem_ref __bnxt_alloc_rx_netmem(struct bnxt *bp, dma_addr_t *mapping,
 					 struct bnxt_rx_ring_info *rxr,
 					 unsigned int *offset,
@@ -1029,15 +1008,17 @@ int bnxt_alloc_rx_data(struct bnxt *bp, struct bnxt_rx_ring_info *rxr,
 
 	if (BNXT_RX_PAGE_MODE(bp)) {
 		unsigned int offset;
-		struct page *page =
-			__bnxt_alloc_rx_page(bp, &mapping, rxr, &offset, gfp);
+		netmem_ref netmem =
+			__bnxt_alloc_rx_netmem(bp, &mapping, rxr, &offset, gfp);
 
-		if (!page)
+		if (!netmem)
 			return -ENOMEM;
 
+		/* Same bits as the struct page for system pages */
 		mapping += bp->rx_dma_offset;
-		rx_buf->data = page;
-		rx_buf->data_ptr = page_address(page) + offset + bp->rx_offset;
+		rx_buf->data = (__force void *)netmem;
+		rx_buf->data_ptr = xdp_netmem_address(netmem) + offset +
+				   bp->rx_offset;
 		rx_buf->offset = offset;
 	} else {
 		u8 *data = __bnxt_alloc_rx_frag(bp, &mapping, rxr, gfp);
@@ -3593,13 +3574,14 @@ static void bnxt_free_one_rx_ring(struct bnxt *bp, struct bnxt_rx_ring_info *rxr
 	for (i = 0; i < max_idx; i++) {
 		struct bnxt_sw_rx_bd *rx_buf = &rxr->rx_buf_ring[i];
 		void *data = rx_buf->data;
+		netmem_ref netmem = (__force netmem_ref)data;
 
 		if (!data)
 			continue;
 
 		rx_buf->data = NULL;
 		if (BNXT_RX_PAGE_MODE(bp))
-			page_pool_recycle_direct(rxr->page_pool, data);
+			page_pool_recycle_direct_netmem(rxr->page_pool, netmem);
 		else
 			page_pool_free_va(rxr->head_pool, data, true);
 	}
@@ -3969,7 +3951,8 @@ static int bnxt_alloc_rx_page_pool(struct bnxt *bp,
 	pp.dma_dir = bp->rx_dir;
 	pp.max_len = PAGE_SIZE << pp.order;
 	pp.flags = PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV |
-		   PP_FLAG_ALLOW_UNREADABLE_NETMEM;
+		   PP_FLAG_ALLOW_UNREADABLE_NETMEM |
+		   PP_FLAG_ALLOW_XDP_ONLY_NETMEM;
 	pp.queue_idx = rxr->bnapi->index;
 
 	pool = page_pool_create(&pp);
drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.c +11 -8
index 161e0dd62be6..8ad04b36d4f0 100644
@@ -210,9 +210,9 @@ void bnxt_xdp_buff_frags_free(struct bnxt_rx_ring_info *rxr,
 		return;
 	shinfo = xdp_get_shared_info_from_buff(xdp);
 	for (i = 0; i < shinfo->nr_frags; i++) {
-		struct page *page = skb_frag_page(&shinfo->frags[i]);
+		netmem_ref netmem = skb_frag_netmem(&shinfo->frags[i]);
 
-		page_pool_recycle_direct(rxr->page_pool, page);
+		page_pool_recycle_direct_netmem(rxr->page_pool, netmem);
 	}
 	shinfo->nr_frags = 0;
 }
@@ -222,7 +222,7 @@ void bnxt_xdp_buff_frags_free(struct bnxt_rx_ring_info *rxr,
  * false   - packet should be passed to the stack.
  */
 bool bnxt_rx_xdp(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 cons,
-		 struct xdp_buff *xdp, struct page *page, u8 **data_ptr,
+		 struct xdp_buff *xdp, void *data, u8 **data_ptr,
 		 unsigned int *len, u8 *event)
 {
 	struct bpf_prog *xdp_prog = READ_ONCE(rxr->xdp_prog);
@@ -278,7 +278,7 @@ bool bnxt_rx_xdp(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 cons,
 		if (tx_avail < tx_needed) {
 			trace_xdp_exception(bp->dev, xdp_prog, act);
 			bnxt_xdp_buff_frags_free(rxr, xdp);
-			bnxt_reuse_rx_data(rxr, cons, page);
+			bnxt_reuse_rx_data(rxr, cons, data);
 			return true;
 		}
 
@@ -289,7 +289,7 @@ bool bnxt_rx_xdp(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 cons,
 		*event |= BNXT_TX_EVENT;
 		__bnxt_xmit_xdp(bp, txr, mapping + offset, *len,
 				NEXT_RX(rxr->rx_prod), xdp);
-		bnxt_reuse_rx_data(rxr, cons, page);
+		bnxt_reuse_rx_data(rxr, cons, data);
 		return true;
 	case XDP_REDIRECT:
 		/* if we are calling this here then we know that the
@@ -301,14 +301,17 @@ bool bnxt_rx_xdp(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 cons,
 		if (bnxt_alloc_rx_data(bp, rxr, rxr->rx_prod, GFP_ATOMIC)) {
 			trace_xdp_exception(bp->dev, xdp_prog, act);
 			bnxt_xdp_buff_frags_free(rxr, xdp);
-			bnxt_reuse_rx_data(rxr, cons, page);
+			bnxt_reuse_rx_data(rxr, cons, data);
 			return true;
 		}
 
 		if (xdp_do_redirect(bp->dev, xdp, xdp_prog)) {
+			/* data holds the netmem of the head */
+			netmem_ref head = (__force netmem_ref)data;
+
 			trace_xdp_exception(bp->dev, xdp_prog, act);
 			bnxt_xdp_buff_frags_free(rxr, xdp);
-			page_pool_recycle_direct(rxr->page_pool, page);
+			page_pool_recycle_direct_netmem(rxr->page_pool, head);
 			return true;
 		}
 
@@ -322,7 +325,7 @@ bool bnxt_rx_xdp(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 cons,
 		fallthrough;
 	case XDP_DROP:
 		bnxt_xdp_buff_frags_free(rxr, xdp);
-		bnxt_reuse_rx_data(rxr, cons, page);
+		bnxt_reuse_rx_data(rxr, cons, data);
 		break;
 	}
 	return true;
drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.h +1 -1
index fb4f9143929f..f9ec204ceb9e 100644
@@ -25,7 +25,7 @@ struct bnxt_sw_tx_bd *bnxt_xmit_bd(struct bnxt *bp,
 				   struct xdp_buff *xdp);
 void bnxt_tx_int_xdp(struct bnxt *bp, struct bnxt_napi *bnapi, int budget);
 bool bnxt_rx_xdp(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 cons,
-		 struct xdp_buff *xdp, struct page *page, u8 **data_ptr,
+		 struct xdp_buff *xdp, void *data, u8 **data_ptr,
 		 unsigned int *len, u8 *event);
 int bnxt_xdp(struct net_device *dev, struct netdev_bpf *xdp);
 int bnxt_xdp_xmit(struct net_device *dev, int num_frames,
Signature · 1 line
2.56.1
#16 lore raw

PATCH 14/15 selftests: net: xsk: Test the device's RX buffer layout

In reply to Björn Töpel

Currently, xskxceiver cannot test a UMEM in the device's buffer layout, as it expects one chunk per packet at the UMEM headroom and puts every received chunk back on FILL.

Add -D, which registers the UMEM with XDP_UMEM_DRV_LAYOUT in drv mode and binds multi-buffer sockets without XDP_COPY.

Buffers may then start anywhere in a chunk and in the packet, so check their bytes by packet offset, and report how many descriptors of an RX batch share a chunk. A chunk goes back on FILL only when an RX descriptor carries XDP_RX_CHUNK_FREE, and empty descriptors are not packets. Skip the tests that need other chunk sizes or headroom, an RX descriptor per packet, or two sockets that receive on one queue.

In this layout the queue takes its first buffers from FILL when bind starts it, and more only when NAPI refills, so populate FILL before bind. Otherwise packets that arrive before the first refill find no buffer, and the device drops them. Other modes, and the test that wants FILL to run dry, keep filling after bind.

---
 .../testing/selftests/net/lib/xsk/test_xsk.c  | 248 ++++++++++++++++--
 .../testing/selftests/net/lib/xsk/test_xsk.h  |   4 +
 .../selftests/net/lib/xsk/xskxceiver.c        |  25 +-
 3 files changed, 250 insertions(+), 27 deletions(-)
tools/testing/selftests/net/lib/xsk/test_xsk.c +227 -21
index ca161511f1e5..bae503432eeb 100644
@@ -19,6 +19,8 @@
 #include "xsk_xdp_progs.skel.h"
 
 #define DEFAULT_BATCH_SIZE		64
+/* Descriptors of an RX batch that count_drv_shared() compares */
+#define DRV_SHARE_WINDOW		64
 #define MIN_PKT_SIZE			64
 #define MAX_ETH_JUMBO_SIZE		9000
 #define MAX_INTERFACES			2
@@ -38,6 +40,9 @@
 static const u8 g_mac[ETH_ALEN] = {0x55, 0x44, 0x33, 0x22, 0x11, 0x00};
 
 bool opt_verbose;
+bool opt_drv_layout;
+/* RX descriptors, and those whose chunk an earlier one of the batch holds */
+u64 drv_rx_descs, drv_rx_shared;
 pthread_barrier_t barr;
 pthread_mutex_t pacing_mutex = PTHREAD_MUTEX_INITIALIZER;
 
@@ -94,6 +99,8 @@ int xsk_configure_umem(struct ifobject *ifobj, struct xsk_umem_info *umem, void
 
 	if (umem->unaligned_mode)
 		cfg.flags |= XDP_UMEM_UNALIGNED_CHUNK_FLAG;
+	if (opt_drv_layout)
+		cfg.flags |= XDP_UMEM_DRV_LAYOUT;
 
 	ret = xsk_umem__create(&umem->umem, buffer, size,
 			       &umem->fq, &umem->cq, &cfg);
@@ -161,7 +168,8 @@ int xsk_configure_socket(struct xsk_socket_info *xsk, struct xsk_umem_info *umem
 	cfg.bind_flags = ifobject->bind_flags;
 	if (shared)
 		cfg.bind_flags |= XDP_SHARED_UMEM;
-	if (ifobject->mtu > MAX_ETH_PKT_SIZE)
+	/* The device may split any frame, see XDP_UMEM_DRV_LAYOUT */
+	if (ifobject->mtu > MAX_ETH_PKT_SIZE || opt_drv_layout)
 		cfg.bind_flags |= XDP_USE_SG;
 	if (umem->comp_size)
 		cfg.tx_size = umem->comp_size;
@@ -262,6 +270,7 @@ static void __test_spec_init(struct test_spec *test, struct ifobject *ifobj_tx,
 	test->set_ring = false;
 	test->adjust_tail = false;
 	test->adjust_tail_support = false;
+	test->adjust_grow = 0;
 	test->mtu = MAX_ETH_PKT_SIZE;
 	test->xdp_prog_rx = ifobj_rx->xdp_progs->progs.xsk_def_prog;
 	test->xskmap_rx = ifobj_rx->xdp_progs->maps.xsk;
@@ -289,7 +298,7 @@ void test_init(struct test_spec *test, struct ifobject *ifobj_tx,
 		ifobj->bind_flags = XDP_USE_NEED_WAKEUP;
 		if (mode == TEST_MODE_ZC)
 			ifobj->bind_flags |= XDP_ZEROCOPY;
-		else
+		else if (!opt_drv_layout || mode != TEST_MODE_DRV)
 			ifobj->bind_flags |= XDP_COPY;
 	}
 
@@ -878,6 +887,77 @@ static bool is_frag_valid(struct xsk_umem_info *umem, u64 addr, u32 len, u32 exp
 	return false;
 }
 
+/* Driver layout: a buffer may start and end anywhere in the packet, and
+ * anywhere in its chunk. Check its bytes against the generated pattern by
+ * packet offset. XDP_ADJUST_TAIL_GROW zeroes the last @grow bytes and
+ * writes the sequence number of the last word, so that word only needs the
+ * right sequence number, and the bytes before it may be zero.
+ */
+static bool is_frag_valid_drv(struct xsk_umem_info *umem, u64 addr, u32 len,
+			      u32 expected_pkt_nb, u32 bytes_processed,
+			      u32 pkt_len, u32 grow)
+{
+	u32 payload_end = PKT_HDR_SIZE + ((pkt_len - PKT_HDR_SIZE) & ~3U);
+	u8 *bytes = xsk_umem__get_data(umem->buffer, addr);
+	u64 umem_sz = umem_size(umem);
+	u32 i, off, word;
+
+	addr -= umem->base_addr;
+	if (addr >= umem_sz || addr + len > umem_sz ||
+	    addr % umem->frame_size + len > umem->frame_size) {
+		ksft_print_msg("Frag invalid addr: %llx len: %u\n",
+			       (unsigned long long)addr, len);
+		return false;
+	}
+
+	for (i = 0; i < len; i++) {
+		off = bytes_processed + i;
+		if (off < PKT_HDR_SIZE || off >= payload_end)
+			continue;
+		if (off >= pkt_len - grow && !bytes[i])
+			continue;
+
+		off -= PKT_HDR_SIZE;
+		word = htonl(expected_pkt_nb << 16 | (off / 4));
+		if (off / 4 == (payload_end - PKT_HDR_SIZE) / 4 - 1 &&
+		    off % 4 < 2)
+			continue;
+		if (bytes[i] == ((u8 *)&word)[off % 4])
+			continue;
+
+		ksft_print_msg("[%s] pkt %u: byte %u (pkt offset %u) is %#x, expected %#x\n",
+			       __func__, expected_pkt_nb, i,
+			       (u32)(off + PKT_HDR_SIZE), bytes[i],
+			       ((u8 *)&word)[off % 4]);
+		return false;
+	}
+
+	return true;
+}
+
+/* Driver layout: count descriptors whose chunk an earlier descriptor of the
+ * same RX batch holds, that is, chunks the device split. Only the first
+ * DRV_SHARE_WINDOW descriptors of a batch are compared.
+ */
+static void count_drv_shared(struct xsk_umem_info *umem, u64 *chunks, u32 n,
+			     u64 addr)
+{
+	u64 chunk = addr / umem->frame_size;
+	u32 i;
+
+	drv_rx_descs++;
+	if (n >= DRV_SHARE_WINDOW)
+		return;
+
+	for (i = 0; i < n; i++) {
+		if (chunks[i] != chunk)
+			continue;
+		drv_rx_shared++;
+		break;
+	}
+	chunks[n] = chunk;
+}
+
 static bool is_pkt_valid(struct pkt *pkt, void *buffer, u64 addr, u32 len)
 {
 	if (pkt->len != len) {
@@ -983,10 +1063,15 @@ static int __receive_pkts(struct test_spec *test, struct xsk_socket_info *xsk)
 {
 	u32 frags_processed = 0, nb_frags = 0, pkt_len = 0;
 	u32 idx_rx = 0, idx_fq = 0, rcvd, pkts_sent = 0;
+	/* Driver layout: FILL entries written, and those of a partial packet */
+	u32 fills = 0, pkt_fills = 0;
 	struct pkt_stream *pkt_stream = xsk->pkt_stream;
 	struct ifobject *ifobj = test->ifobj_rx;
 	struct xsk_umem_info *umem = xsk->umem;
 	struct pollfd fds = { };
+	u64 batch_chunks[DRV_SHARE_WINDOW];
+	/* Entries of batch_chunks[]: data descriptors only */
+	u32 batch_n = 0;
 	struct pkt *pkt;
 	u64 first_addr = 0;
 	int ret;
@@ -1038,6 +1123,22 @@ static int __receive_pkts(struct test_spec *test, struct xsk_socket_info *xsk)
 		orig = xsk_umem__extract_addr(addr);
 		addr = xsk_umem__add_offset_to_addr(addr);
 
+		/* Driver layout: an empty descriptor only gives a chunk back */
+		if (opt_drv_layout && !desc->len) {
+			if (nb_frags || !(desc->options & XDP_RX_CHUNK_FREE)) {
+				ksft_print_msg("[%s] empty descriptor addr: %lx options: %u\n",
+					       __func__, addr, desc->options);
+				return TEST_FAILURE;
+			}
+			if (ifobj->use_fill_ring) {
+				*xsk_ring_prod__fill_addr(&umem->fq, idx_fq++) =
+					orig - orig % umem->frame_size;
+				fills++;
+			}
+			frags_processed++;
+			continue;
+		}
+
 		if (!nb_frags) {
 			pkt = pkt_stream_get_next_rx_pkt(pkt_stream, &pkts_sent);
 			if (!pkt) {
@@ -1050,46 +1151,74 @@ static int __receive_pkts(struct test_spec *test, struct xsk_socket_info *xsk)
 		print_verbose("Rx: addr: %lx len: %u options: %u pkt_nb: %u valid: %u\n",
 			      addr, desc->len, desc->options, pkt->pkt_nb, pkt->valid);
 
-		if (!is_frag_valid(umem, addr, desc->len, pkt->pkt_nb, pkt_len) ||
-		    !is_offset_correct(umem, pkt, addr) || (ifobj->use_metadata &&
-		    !is_metadata_correct(pkt, umem->buffer, addr)))
+		if (opt_drv_layout) {
+			/* The device picks offsets; metadata precedes the
+			 * head
+			 */
+			if (!is_frag_valid_drv(umem, addr, desc->len,
+					       pkt->pkt_nb, pkt_len,
+					       pkt->len, test->adjust_grow) ||
+			    (ifobj->use_metadata && !nb_frags &&
+			     !is_metadata_correct(pkt, umem->buffer, addr)))
+				return TEST_FAILURE;
+			count_drv_shared(umem, batch_chunks, batch_n++, addr);
+		} else if (!is_frag_valid(umem, addr, desc->len, pkt->pkt_nb,
+					  pkt_len) ||
+			   !is_offset_correct(umem, pkt, addr) ||
+			   (ifobj->use_metadata &&
+			    !is_metadata_correct(pkt, umem->buffer, addr))) {
 			return TEST_FAILURE;
+		}
 
 		if (!nb_frags++)
 			first_addr = addr;
 		frags_processed++;
 		pkt_len += desc->len;
-		if (ifobj->use_fill_ring)
+		if (!ifobj->use_fill_ring) {
+		} else if (!opt_drv_layout) {
 			*xsk_ring_prod__fill_addr(&umem->fq, idx_fq++) = orig;
+		} else if (desc->options & XDP_RX_CHUNK_FREE) {
+			/* Driver layout: only a free chunk goes back to FILL */
+			*xsk_ring_prod__fill_addr(&umem->fq, idx_fq++) =
+				orig - orig % umem->frame_size;
+			fills++;
+			pkt_fills++;
+		}
 
 		if (pkt_continues(desc->options))
 			continue;
 
 		/* The complete packet has been received */
 		if (!is_pkt_valid(pkt, umem->buffer, first_addr, pkt_len) ||
-		    !is_offset_correct(umem, pkt, addr))
+		    (!opt_drv_layout && !is_offset_correct(umem, pkt, addr)))
 			return TEST_FAILURE;
 
 		pkt_stream->nb_rx_pkts++;
 		nb_frags = 0;
 		pkt_len = 0;
+		pkt_fills = 0;
 	}
 
 	if (nb_frags) {
 		/* In the middle of a packet. Start over from beginning of packet. */
 		idx_rx -= nb_frags;
 		xsk_ring_cons__cancel(&xsk->rx, nb_frags);
-		if (ifobj->use_fill_ring) {
+		if (ifobj->use_fill_ring && !opt_drv_layout) {
 			idx_fq -= nb_frags;
 			xsk_ring_prod__cancel(&umem->fq, nb_frags);
 		}
 		frags_processed -= nb_frags;
+		fills -= pkt_fills;
 		pkt_stream_cancel(pkt_stream);
 		pkts_sent--;
 	}
 
-	if (ifobj->use_fill_ring)
+	if (ifobj->use_fill_ring && opt_drv_layout) {
+		xsk_ring_prod__cancel(&umem->fq, rcvd - fills);
+		xsk_ring_prod__submit(&umem->fq, fills);
+	} else if (ifobj->use_fill_ring) {
 		xsk_ring_prod__submit(&umem->fq, frags_processed);
+	}
 	if (ifobj->release_rx)
 		xsk_ring_cons__release(&xsk->rx, frags_processed);
 
@@ -1161,19 +1290,29 @@ static int receive_pkts(struct test_spec *test)
 }
 
 static int __send_pkts(struct ifobject *ifobject, struct xsk_socket_info *xsk,
-		       bool test_timeout)
+		       bool test_timeout, bool drv_rx)
 {
 	u32 i, idx = 0, valid_pkts = 0, valid_frags = 0, buffer_len;
 	struct xsk_umem_info *umem = ifobject->xsk_arr[0].umem_real;
 	struct pkt_stream *pkt_stream = xsk->pkt_stream;
 	bool use_poll = ifobject->use_poll;
 	struct pollfd fds = { };
-	int ret;
+	int ret, max_in_flight;
 
 	buffer_len = pkt_get_buffer_len(umem, pkt_stream->max_pkt_len);
+	max_in_flight = (umem_size(umem) - xsk->batch_size * buffer_len) /
+			buffer_len;
+	/* A receiver in the device's buffer layout needs more: its queue
+	 * also holds chunks without packets, posted on rings that the
+	 * traffic does not fill, such as a header ring, and in the page
+	 * pool cache. And a packet takes an RX descriptor per buffer, and
+	 * empty ones that give chunks back. Keep a quarter of the frames in
+	 * flight to such a receiver.
+	 */
+	if (drv_rx)
+		max_in_flight /= 4;
 	/* pkts_in_flight might be negative if many invalid packets are sent */
-	if (pkts_in_flight >= (int)((umem_size(umem) - xsk->batch_size * buffer_len) /
-	    buffer_len) && !test_timeout) {
+	if (pkts_in_flight >= max_in_flight && !test_timeout) {
 		ret = kick_tx(xsk);
 		if (ret)
 			return TEST_FAILURE;
@@ -1316,6 +1455,7 @@ bool all_packets_sent(struct test_spec *test, unsigned long *bitmap)
 
 static int send_pkts(struct test_spec *test, struct ifobject *ifobject)
 {
+	bool drv_rx = opt_drv_layout && test->ifobj_rx->use_fill_ring;
 	DECLARE_BITMAP(bitmap, test->nb_sockets);
 	u32 i, ret;
 
@@ -1330,7 +1470,8 @@ static int send_pkts(struct test_spec *test, struct ifobject *ifobject)
 				__set_bit(i, bitmap);
 				continue;
 			}
-			ret = __send_pkts(ifobject, &ifobject->xsk_arr[i], test->poll_tmout);
+			ret = __send_pkts(ifobject, &ifobject->xsk_arr[i],
+					  test->poll_tmout, drv_rx);
 			if (ret != TEST_CONTINUE)
 				return ret;
 
@@ -1574,6 +1715,7 @@ static int thread_common_ops(struct test_spec *test, struct ifobject *ifobject)
 	LIBBPF_OPTS(bpf_xdp_query_opts, opts);
 	int mmap_flags;
 	u64 umem_sz, mmap_sz;
+	bool fill_first;
 	void *bufs;
 	int ret;
 	u32 i;
@@ -1600,6 +1742,21 @@ static int thread_common_ops(struct test_spec *test, struct ifobject *ifobject)
 	if (ret)
 		return ret;
 
+	/* In the device's buffer layout, the queue takes its first buffers
+	 * from FILL when bind starts it: fill FILL first, or the first
+	 * packets find no buffer. A test without the fill ring wants FILL
+	 * to run dry, so it fills after bind as before.
+	 */
+	fill_first = opt_drv_layout && test->mode == TEST_MODE_DRV &&
+		     ifobject->rx_on && ifobject->use_fill_ring;
+	if (fill_first) {
+		ret = xsk_populate_fill_ring(umem,
+					     ifobject->xsk_arr[0].pkt_stream,
+					     ifobject->use_fill_ring);
+		if (ret)
+			return ret;
+	}
+
 	ret = xsk_configure(test, ifobject, umem, false);
 	if (ret)
 		return ret;
@@ -1609,10 +1766,12 @@ static int thread_common_ops(struct test_spec *test, struct ifobject *ifobject)
 	if (!ifobject->rx_on)
 		return 0;
 
-	ret = xsk_populate_fill_ring(umem, ifobject->xsk->pkt_stream,
-				     ifobject->use_fill_ring);
-	if (ret)
-		return ret;
+	if (!fill_first) {
+		ret = xsk_populate_fill_ring(umem, ifobject->xsk->pkt_stream,
+					     ifobject->use_fill_ring);
+		if (ret)
+			return ret;
+	}
 
 	for (i = 0; i < test->nb_sockets; i++) {
 		ret = xsk_update_xskmap(ifobject->xskmap, ifobject->xsk_arr[i].xsk, i);
@@ -1789,12 +1948,32 @@ static void clean_umem(struct test_spec *test, struct ifobject *ifobj1, struct i
 		testapp_clean_xsk_umem(ifobj2);
 }
 
+/* UMEM in the device's buffer layout: page chunks, no headroom */
+static bool drv_layout(struct test_spec *test)
+{
+	return opt_drv_layout && test->mode == TEST_MODE_DRV;
+}
+
+static bool drv_layout_umem_ok(struct ifobject *ifobj)
+{
+	struct xsk_umem_info *umem = ifobj->xsk->umem;
+
+	return umem->frame_size == getpagesize() && !umem->frame_headroom &&
+	       !umem->unaligned_mode;
+}
+
 static int __testapp_validate_traffic(struct test_spec *test, struct ifobject *ifobj1,
 				      struct ifobject *ifobj2)
 {
 	pthread_t t0, t1;
 	int err;
 
+	if (drv_layout(test) && (!drv_layout_umem_ok(ifobj1) ||
+				 (ifobj2 && !drv_layout_umem_ok(ifobj2)))) {
+		ksft_print_msg("drv layout needs page chunks without headroom\n");
+		return TEST_SKIP;
+	}
+
 	if (test->mtu > MAX_ETH_PKT_SIZE) {
 		if (test->mode == TEST_MODE_ZC && (!ifobj1->multi_buff_zc_supp ||
 						   (ifobj2 && !ifobj2->multi_buff_zc_supp))) {
@@ -1899,11 +2078,12 @@ static int testapp_validate_traffic_single_thread(struct test_spec *test, struct
 
 int testapp_teardown(struct test_spec *test)
 {
-	int i;
+	int i, ret;
 
 	for (i = 0; i < MAX_TEARDOWN_ITER; i++) {
-		if (testapp_validate_traffic(test))
-			return TEST_FAILURE;
+		ret = testapp_validate_traffic(test);
+		if (ret)
+			return ret == TEST_SKIP ? TEST_SKIP : TEST_FAILURE;
 		test_spec_reset(test);
 	}
 
@@ -1926,6 +2106,12 @@ int testapp_bidirectional(struct test_spec *test)
 {
 	int res;
 
+	/* Both sockets would receive on one queue */
+	if (drv_layout(test)) {
+		ksft_print_msg("One socket receives per queue in drv layout\n");
+		return TEST_SKIP;
+	}
+
 	test->ifobj_tx->rx_on = true;
 	test->ifobj_rx->tx_on = true;
 	test->total_steps = 2;
@@ -1960,6 +2146,12 @@ static int swap_xsk_resources(struct test_spec *test)
 
 int testapp_xdp_prog_cleanup(struct test_spec *test)
 {
+	/* The second socket would receive on the queue of the first */
+	if (drv_layout(test)) {
+		ksft_print_msg("One socket receives per queue in drv layout\n");
+		return TEST_SKIP;
+	}
+
 	test->total_steps = 2;
 	test->nb_sockets = 2;
 	if (testapp_validate_traffic(test))
@@ -2013,6 +2205,12 @@ int testapp_stats_rx_full(struct test_spec *test)
 {
 	struct pkt_stream *tmp;
 
+	/* Empty descriptors that give chunks back take RX slots too */
+	if (drv_layout(test)) {
+		ksft_print_msg("RX slots are not all packets in drv layout\n");
+		return TEST_SKIP;
+	}
+
 	tmp = pkt_stream_generate(DEFAULT_UMEM_BUFFERS + DEFAULT_UMEM_BUFFERS / 2, MIN_PKT_SIZE);
 	if (!tmp)
 		return TEST_FAILURE;
@@ -2209,6 +2407,12 @@ int testapp_xdp_shared_umem(struct test_spec *test)
 	struct xsk_xdp_progs *skel_tx = test->ifobj_tx->xdp_progs;
 	int ret;
 
+	/* Both sockets would receive on one queue */
+	if (drv_layout(test)) {
+		ksft_print_msg("One socket receives per queue in drv layout\n");
+		return TEST_SKIP;
+	}
+
 	test->total_steps = 1;
 	test->nb_sockets = 2;
 
@@ -2535,6 +2739,8 @@ static int testapp_adjust_tail(struct test_spec *test, u32 value, u32 pkt_len)
 
 	test->adjust_tail_support = true;
 	test->adjust_tail = true;
+	/* A negative value shrinks */
+	test->adjust_grow = (int)value > 0 ? value : 0;
 	test->total_steps = 1;
 
 	ret = pkt_stream_replace_ifobject(test->ifobj_tx, DEFAULT_BATCH_SIZE, pkt_len);
tools/testing/selftests/net/lib/xsk/test_xsk.h +4 -0
index 2506b0dcc6bf..4f4956c0440f 100644
@@ -35,6 +35,9 @@
 #define SMP_CACHE_BYTES_PATH "/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size"
 
 extern bool opt_verbose;
+/* XDP_UMEM_DRV_LAYOUT: the device lays out RX buffers in UMEM chunks */
+extern bool opt_drv_layout;
+extern u64 drv_rx_descs, drv_rx_shared;
 #define print_verbose(x...) do { if (opt_verbose) ksft_print_msg(x); } while (0)
 
 
@@ -200,6 +203,7 @@ struct test_spec {
 	struct bpf_map *xskmap_tx;
 	test_func_t test_func;
 	int mtu;
+	u32 adjust_grow;
 	u16 total_steps;
 	u16 current_step;
 	u16 nb_sockets;
tools/testing/selftests/net/lib/xsk/xskxceiver.c +19 -6
index 0a63651434a5..6b00a586b3af 100644
@@ -64,11 +64,6 @@
  * - Tx thread Transmits a number of packets from veth<xxxx> to veth<yyyy>
  * - Rx thread verifies if all packets were received and delivered in-order,
  *   and have the right content
- *
- * Enable/disable packet dump mode:
- * --------------------------
- * To enable L2 - L4 headers and payload dump of each packet on STDOUT, add
- * parameter -D to params array in test_xsk.sh, i.e. params=("-S" "-D")
  */
 
 #define _GNU_SOURCE
@@ -164,6 +159,7 @@ static struct option long_options[] = {
 	{"mode", required_argument, 0, 'm'},
 	{"list", no_argument, 0, 'l'},
 	{"test", required_argument, 0, 't'},
+	{"drv-layout", no_argument, 0, 'D'},
 	{"help", no_argument, 0, 'h'},
 	{0, 0, 0, 0}
 };
@@ -179,6 +175,7 @@ static void print_usage(char **argv)
 		"  -m, --mode           Run only mode skb, drv, or zc\n"
 		"  -l, --list           List all available tests\n"
 		"  -t, --test           Run a specific test. Enter number from -l option.\n"
+		"  -D, --drv-layout     Receive in the device's buffer layout (drv mode)\n"
 		"  -h, --help           Display this help and exit\n";
 
 	ksft_print_msg(str, basename(argv[0]));
@@ -202,7 +199,8 @@ static void parse_command_line(struct ifobject *ifobj_tx, struct ifobject *ifobj
 	opterr = 0;
 
 	for (;;) {
-		c = getopt_long(argc, argv, "i:vbm:lt:", long_options, &option_index);
+		c = getopt_long(argc, argv, "i:vbm:lt:D", long_options,
+				&option_index);
 		if (c == -1)
 			break;
 
@@ -244,6 +242,9 @@ static void parse_command_line(struct ifobject *ifobj_tx, struct ifobject *ifobj
 		case 'l':
 			opt_print_tests = true;
 			break;
+		case 'D':
+			opt_drv_layout = true;
+			break;
 		case 't':
 			errno = 0;
 			opt_run_test = strtol(optarg, NULL, 0);
@@ -255,6 +256,12 @@ static void parse_command_line(struct ifobject *ifobj_tx, struct ifobject *ifobj
 			print_usage(argv);
 		}
 	}
+
+	/* The device's buffer layout is a drv mode feature */
+	if (opt_drv_layout && opt_mode == TEST_MODE_ALL)
+		opt_mode = TEST_MODE_DRV;
+	else if (opt_drv_layout && opt_mode != TEST_MODE_DRV)
+		print_usage(argv);
 }
 
 static void xsk_unload_xdp_programs(struct ifobject *ifobj)
@@ -266,7 +273,13 @@ static void run_pkt_test(struct test_spec *test)
 {
 	int ret;
 
+	drv_rx_descs = 0;
+	drv_rx_shared = 0;
 	ret = test->test_func(test);
+	if (opt_drv_layout)
+		ksft_print_msg("drv layout: rx descs %llu, in a chunk shared within an RX batch %llu\n",
+			       (unsigned long long)drv_rx_descs,
+			       (unsigned long long)drv_rx_shared);
 
 	switch (ret) {
 	case TEST_PASS:
Signature · 1 line
2.56.1
#17 lore raw

PATCH 15/15 Documentation: networking: Describe AF_XDP RX in the device's layout

In reply to Björn Töpel

For applications, XDP_UMEM_DRV_LAYOUT changes who owns a chunk and when, what the XDP program may read and write, which verdicts it may return, and how chunks come back. None of it is documented yet.

Describe for application writers the setup and its errors, the program, receiving and giving chunks back, need_wakeup, devices that need DMA syncs, and how TX shares the chunks.

---
 Documentation/networking/af_xdp.rst | 114 +++++++++++++++++++++++++++-
 1 file changed, 113 insertions(+), 1 deletion(-)
Documentation/networking/af_xdp.rst +113 -1
index 538e71adb759..4e37a6074a52 100644
@@ -429,7 +429,9 @@ There is also an option to set the headroom of each single buffer in
 the UMEM. If you set this to N bytes, it means that the packet will
 start N bytes into the buffer leaving the first N bytes for the
 application to use. The final option is the flags field, but it will
-be dealt with in separate sections for each UMEM flag.
+be dealt with in separate sections for each UMEM flag. With the
+XDP_UMEM_DRV_LAYOUT flag, chunks are pages that the device fills in
+its own layout, see the "Device Buffer Layout" section.
 
 SO_BINDTODEVICE setsockopt
 --------------------------
@@ -761,6 +763,116 @@ processing. Note that the Tx batch API guarantees that it will provide
 a batch of Tx descriptors that ends with full packet at the end. This
 to facilitate extending a zero-copy driver with multi-buffer support.
 
+Device Buffer Layout
+====================
+
+In zero-copy mode, the driver fills one UMEM frame per buffer, at the
+UMEM headroom, and needs a receive path of its own for AF_XDP. With
+the XDP_UMEM_DRV_LAYOUT UMEM flag, the device places buffers in UMEM
+chunks as it places them in the pages of its page pool: several
+buffers may share a chunk, a packet may span chunks, and the device
+picks the offsets. The XDP program reads and writes packets in place,
+in the UMEM, but the kernel stores none of its own structures in the
+chunks.
+
+The UMEM backs the page pools of the bound queue through a memory
+provider, so the driver needs no AF_XDP code. A driver supports the
+mode if it runs native XDP with XDP_REDIRECT, takes its receive
+buffers from a page pool of netmem that allows such providers, and
+can restart a queue.
+
+Setting up
+----------
+
+* Register the UMEM with XDP_UMEM_DRV_LAYOUT, aligned chunks of
+  PAGE_SIZE, and no headroom. The UMEM must hold more chunks than the
+  queue keeps posted to the device and in its page pool cache, 128
+  chunks with 4K pages, or the bind fails with ENOSPC. The first
+  number depends on the driver, the ring size and the MTU.
+
+* Attach a native XDP program to the device itself through netlink,
+  not through a BPF link or an upper device such as a bond, before the
+  bind. The bind fails with ENOENT without one. The program cannot be
+  detached while the UMEM backs the queue (EBUSY).
+
+* Put chunks on the FILL ring before the bind. The bind starts the
+  queue with the chunks it finds there, and the queue drops packets
+  while it has none.
+
+* Bind with XDP_USE_NEED_WAKEUP, as only a wakeup restarts a queue
+  that used up the FILL ring, and with XDP_USE_SG to receive packets
+  that span chunks. A bind without XDP_USE_NEED_WAKEUP fails with
+  EINVAL. XDP_COPY fails with EOPNOTSUPP, as does a device
+  without native XDP_REDIRECT or queue management. One socket per
+  queue receives: a second socket with an RX ring gets EBUSY, and so
+  does any socket with an RX ring once the receiving socket is gone.
+  Sockets that share the UMEM with XDP_SHARED_UMEM may transmit.
+
+The XDP program
+---------------
+
+The program works on the packet in place, in the UMEM: direct packet
+access, bpf_xdp_load_bytes(), bpf_xdp_store_bytes(), dynptrs,
+bpf_xdp_adjust_head(), bpf_xdp_adjust_tail(), bpf_xdp_adjust_meta()
+and the RX metadata kfuncs work as with pages, on every buffer of the
+packet. What the program writes is in the UMEM for the application to
+see. The kernel keeps its own data, such as the fragment list of a
+packet that spans buffers, in kernel memory, so the application cannot
+change what the kernel relies on. The application may still change
+the packet at any time, also while the program runs: two reads of the
+same bytes may differ.
+
+Buffers of the bound queue may only go to its receiving socket. Every
+verdict but XDP_REDIRECT drops the packet, XDP_PASS included, and
+redirects to anything but the receiving socket fail.
+
+Redirect through an XSKMAP entry that holds the receiving socket.
+
+Receiving
+---------
+
+A FILL entry lends a whole chunk to the kernel, by its address. Each
+buffer of a packet becomes one RX descriptor that points at the data,
+anywhere in a chunk, and XDP_PKT_CONTD chains the buffers of a packet
+as described in the multi-buffer section. Metadata that the program
+wrote is in front of the first buffer, where the program put it; a
+packet whose metadata does not fit in front of its first buffer, in
+the same chunk, is dropped.
+
+The kernel gives a chunk back with XDP_RX_CHUNK_FREE in the options of
+an RX descriptor:
+
+* On a descriptor with data, the flag means that the kernel is done
+  with the chunk of that descriptor. The application owns the whole
+  chunk again.
+
+* A descriptor with length zero, at the address of a chunk, only gives
+  that chunk back. The kernel posts one when the device let go of the
+  chunk after its last buffer reached the socket. Such a descriptor is
+  never part of a packet.
+
+A chunk may go on the FILL ring again once it came back and the
+application is done with all its buffers. The kernel never gives back
+single buffers, so a packet that the application holds keeps its
+chunk. Chunks whose buffers all stayed in the kernel, as for dropped
+packets, stay lent.
+
+The kernel asks for a wakeup on the FILL ring only while it has run
+out of FILL entries; recvmsg() or poll() then restarts the queue. With
+preferred busy polling, the application's poll runs the queue's NAPI.
+
+Devices that need DMA syncs work as they do with page pools: the
+kernel syncs a chunk for the device when the FILL ring lends it, and
+the driver syncs each buffer for the CPU before the program runs.
+
+Transmitting
+------------
+
+Sockets in this mode transmit in copy mode. A buffer that the
+application received may go on the TX ring. Its chunk may go on the
+FILL ring only once the chunk came back and every TX descriptor that
+points into it is on the COMPLETION ring.
+
 Sample application
 ==================
 There is a xdpsock benchmarking/test application that can be found at
Signature · 1 line
2.56.1