From nobody Sun May 19 17:22:40 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1688590779040513.1049106613341; Wed, 5 Jul 2023 13:59:39 -0700 (PDT) Received: from localhost ([::1] helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1qH9aG-0002p8-8Q; Wed, 05 Jul 2023 16:58:44 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1qH9a9-0002os-8w for qemu-devel@nongnu.org; Wed, 05 Jul 2023 16:58:37 -0400 Received: from relay4-d.mail.gandi.net ([217.70.183.196]) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1qH9a4-0003N4-Vt for qemu-devel@nongnu.org; Wed, 05 Jul 2023 16:58:37 -0400 Received: by mail.gandi.net (Postfix) with ESMTPSA id C41AEE0004; Wed, 5 Jul 2023 20:58:28 +0000 (UTC) X-GND-Sasl: i.maximets@ovn.org X-GND-Sasl: i.maximets@ovn.org X-GND-Sasl: i.maximets@ovn.org X-GND-Sasl: i.maximets@ovn.org X-GND-Sasl: i.maximets@ovn.org X-GND-Sasl: i.maximets@ovn.org From: Ilya Maximets To: Jason Wang Cc: Paolo Bonzini , Eric Blake , Stefan Hajnoczi , qemu-devel@nongnu.org, Ilya Maximets Subject: [PATCH v2] net: add initial support for AF_XDP network backend Date: Wed, 5 Jul 2023 22:59:14 +0200 Message-Id: <20230705205914.3457560-1-i.maximets@ovn.org> X-Mailer: git-send-email 2.40.1 MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=217.70.183.196; envelope-from=i.maximets@ovn.org; helo=relay4-d.mail.gandi.net X-Spam_score_int: -25 X-Spam_score: -2.6 X-Spam_bar: -- X-Spam_report: (-2.6 / 5.0 requ) BAYES_00=-1.9, RCVD_IN_DNSWL_LOW=-0.7, RCVD_IN_MSPIKE_H3=0.001, RCVD_IN_MSPIKE_WL=0.001, SPF_HELO_PASS=-0.001, SPF_PASS=-0.001, T_SCC_BODY_TEXT_LINE=-0.01 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: qemu-devel-bounces+importer=patchew.org@nongnu.org X-ZM-MESSAGEID: 1688590779932100001 Content-Type: text/plain; charset="utf-8" AF_XDP is a network socket family that allows communication directly with the network device driver in the kernel, bypassing most or all of the kernel networking stack. In the essence, the technology is pretty similar to netmap. But, unlike netmap, AF_XDP is Linux-native and works with any network interfaces without driver modifications. Unlike vhost-based backends (kernel, user, vdpa), AF_XDP doesn't require access to character devices or unix sockets. Only access to the network interface itself is necessary. This patch implements a network backend that communicates with the kernel by creating an AF_XDP socket. A chunk of userspace memory is shared between QEMU and the host kernel. 4 ring buffers (Tx, Rx, Fill and Completion) are placed in that memory along with a pool of memory buffers for the packet data. Data transmission is done by allocating one of the buffers, copying packet data into it and placing the pointer into Tx ring. After transmission, device will return the buffer via Completion ring. On Rx, device will take a buffer form a pre-populated Fill ring, write the packet data into it and place the buffer into Rx ring. AF_XDP network backend takes on the communication with the host kernel and the network interface and forwards packets to/from the peer device in QEMU. Usage example: -device virtio-net-pci,netdev=3Dguest1,mac=3D00:16:35:AF:AA:5C -netdev af-xdp,ifname=3Dens6f1np1,id=3Dguest1,mode=3Dnative,queues=3D1 XDP program bridges the socket with a network interface. It can be attached to the interface in 2 different modes: 1. skb - this mode should work for any interface and doesn't require driver support. With a caveat of lower performance. 2. native - this does require support from the driver and allows to bypass skb allocation in the kernel and potentially use zero-copy while getting packets in/out userspace. By default, QEMU will try to use native mode and fall back to skb. Mode can be forced via 'mode' option. To force 'copy' even in native mode, use 'force-copy=3Don' option. This might be useful if there is some issue with the driver. Option 'queues=3DN' allows to specify how many device queues should be open. Note that all the queues that are not open are still functional and can receive traffic, but it will not be delivered to QEMU. So, the number of device queues should generally match the QEMU configuration, unless the device is shared with something else and the traffic re-direction to appropriate queues is correctly configured on a device level (e.g. with ethtool -N). 'start-queue=3DM' option can be used to specify from which queue id QEMU should start configuring 'N' queues. It might also be necessary to use this option with certain NICs, e.g. MLX5 NICs. See the docs for examples. In a general case QEMU will need CAP_NET_ADMIN and CAP_SYS_ADMIN capabilities in order to load default XSK/XDP programs to the network interface and configure BPF maps. It is possible, however, to run with no capabilities. For that to work, an external process with admin capabilities will need to pre-load default XSK program, create AF_XDP sockets and pass their file descriptors to QEMU process on startup via 'sock-fds' option. Network backend will need to be configured with 'inhibit=3Don' to avoid loading of the program. QEMU will need 32 MB of locked memory (RLIMIT_MEMLOCK) per queue or CAP_IPC_LOCK. Alternatively, the file descriptor for 'xsks_map' can be passed via 'xsks-map-fd=3DN' option instead of passing socket file descriptors. That will additionally require CAP_NET_RAW on QEMU side. This is useful, because 'sock-fds' may not be available with older libxdp. 'sock-fds' requires libxdp >=3D 1.4.0. There are few performance challenges with the current network backends. First is that they do not support IO threads. This means that data path is handled by the main thread in QEMU and may slow down other work or may be slowed down by some other work. This also means that taking advantage of multi-queue is generally not possible today. Another thing is that data path is going through the device emulation code, which is not really optimized for performance. The fastest "frontend" device is virtio-net. But it's not optimized for heavy traffic either, because it expects such use-cases to be handled via some implementation of vhost (user, kernel, vdpa). In practice, we have virtio notifications and rcu lock/unlock on a per-packet basis and not very efficient accesses to the guest memory. Communication channels between backend and frontend devices do not allow passing more than one packet at a time as well. Some of these challenges can be avoided in the future by adding better batching into device emulation or by implementing vhost-af-xdp variant. There are also a few kernel limitations. AF_XDP sockets do not support any kinds of checksum or segmentation offloading. Buffers are limited to a page size (4K), i.e. MTU is limited. Multi-buffer support implementation for AF_XDP is in progress, but not ready yet. Also, transmission in all non-zero-copy modes is synchronous, i.e. done in a syscall. That doesn't allow high packet rates on virtual interfaces. However, keeping in mind all of these challenges, current implementation of the AF_XDP backend shows a decent performance while running on top of a physical NIC with zero-copy support. Test setup: 2 VMs running on 2 physical hosts connected via ConnectX6-Dx card. Network backend is configured to open the NIC directly in native mode. The driver supports zero-copy. NIC is configured to use 1 queue. Inside a VM - iperf3 for basic TCP performance testing and dpdk-testpmd for PPS testing. iperf3 result: TCP stream : 19.1 Gbps dpdk-testpmd (single queue, single CPU core, 64 B packets) results: Tx only : 3.4 Mpps Rx only : 2.0 Mpps L2 FWD Loopback : 1.5 Mpps In skb mode the same setup shows much lower performance, similar to the setup where pair of physical NICs is replaced with veth pair: iperf3 result: TCP stream : 9 Gbps dpdk-testpmd (single queue, single CPU core, 64 B packets) results: Tx only : 1.2 Mpps Rx only : 1.0 Mpps L2 FWD Loopback : 0.7 Mpps Results in skb mode or over the veth are close to results of a tap backend with vhost=3Don and disabled segmentation offloading bridged with a NIC. Signed-off-by: Ilya Maximets --- Version 2: - Added support for running with no capabilities by passing pre-created AF_XDP socket file descriptors via 'sock-fds' option. Conditionally complied because requires unreleased libxdp 1.4.0. The last restriction is having 32 MB of RLIMIT_MEMLOCK per queue. - Refined and extended documentation. MAINTAINERS | 4 + hmp-commands.hx | 2 +- meson.build | 19 + meson_options.txt | 2 + net/af-xdp.c | 570 ++++++++++++++++++ net/clients.h | 5 + net/meson.build | 3 + net/net.c | 6 + qapi/net.json | 60 +- qemu-options.hx | 83 ++- .../ci/org.centos/stream/8/x86_64/configure | 1 + scripts/meson-buildoptions.sh | 3 + tests/docker/dockerfiles/debian-amd64.docker | 1 + 13 files changed, 756 insertions(+), 3 deletions(-) create mode 100644 net/af-xdp.c diff --git a/MAINTAINERS b/MAINTAINERS index 7164cf55a1..80d4ba4004 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2929,6 +2929,10 @@ W: http://info.iet.unipi.it/~luigi/netmap/ S: Maintained F: net/netmap.c =20 +AF_XDP network backend +R: Ilya Maximets +F: net/af-xdp.c + Host Memory Backends M: David Hildenbrand M: Igor Mammedov diff --git a/hmp-commands.hx b/hmp-commands.hx index 2cbd0f77a0..af9ffe4681 100644 --- a/hmp-commands.hx +++ b/hmp-commands.hx @@ -1295,7 +1295,7 @@ ERST { .name =3D "netdev_add", .args_type =3D "netdev:O", - .params =3D "[user|tap|socket|stream|dgram|vde|bridge|hubport|= netmap|vhost-user" + .params =3D "[user|tap|socket|stream|dgram|vde|bridge|hubport|= netmap|af-xdp|vhost-user" #ifdef CONFIG_VMNET "|vmnet-host|vmnet-shared|vmnet-bridged" #endif diff --git a/meson.build b/meson.build index a9ba0bfab3..1f8772ea5d 100644 --- a/meson.build +++ b/meson.build @@ -1891,6 +1891,18 @@ if libbpf.found() and not cc.links(''' endif endif =20 +# libxdp +libxdp =3D dependency('libxdp', required: get_option('af_xdp'), method: 'p= kg-config') +if libxdp.found() and \ + not (libbpf.found() and libbpf.version().version_compare('>=3D0.7')) + libxdp =3D not_found + if get_option('af_xdp').enabled() + error('af-xdp support requires libbpf version >=3D 0.7') + else + warning('af-xdp support requires libbpf version >=3D 0.7, disabling') + endif +endif + # libdw libdw =3D not_found if not get_option('libdw').auto() or \ @@ -2112,6 +2124,12 @@ config_host_data.set('CONFIG_HEXAGON_IDEF_PARSER', g= et_option('hexagon_idef_pars config_host_data.set('CONFIG_LIBATTR', have_old_libattr) config_host_data.set('CONFIG_LIBCAP_NG', libcap_ng.found()) config_host_data.set('CONFIG_EBPF', libbpf.found()) +config_host_data.set('CONFIG_AF_XDP', libxdp.found()) +if libxdp.found() + config_host_data.set('HAVE_XSK_UMEM__CREATE_WITH_FD', + cc.has_function('xsk_umem__create_with_fd', + dependencies: libxdp)) +endif config_host_data.set('CONFIG_LIBDAXCTL', libdaxctl.found()) config_host_data.set('CONFIG_LIBISCSI', libiscsi.found()) config_host_data.set('CONFIG_LIBNFS', libnfs.found()) @@ -4285,6 +4303,7 @@ summary_info +=3D {'PVRDMA support': have_pvrdma} summary_info +=3D {'fdt support': fdt_opt =3D=3D 'disabled' ? false = : fdt_opt} summary_info +=3D {'libcap-ng support': libcap_ng} summary_info +=3D {'bpf support': libbpf} +summary_info +=3D {'AF_XDP support': libxdp} summary_info +=3D {'rbd support': rbd} summary_info +=3D {'smartcard support': cacard} summary_info +=3D {'U2F support': u2f} diff --git a/meson_options.txt b/meson_options.txt index bbb5c7e886..f4e950ce6a 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -120,6 +120,8 @@ option('avx512bw', type: 'feature', value: 'auto', option('keyring', type: 'feature', value: 'auto', description: 'Linux keyring support') =20 +option('af_xdp', type : 'feature', value : 'auto', + description: 'AF_XDP network backend support') option('attr', type : 'feature', value : 'auto', description: 'attr/xattr support') option('auth_pam', type : 'feature', value : 'auto', diff --git a/net/af-xdp.c b/net/af-xdp.c new file mode 100644 index 0000000000..265ba6b12e --- /dev/null +++ b/net/af-xdp.c @@ -0,0 +1,570 @@ +/* + * AF_XDP network backend. + * + * Copyright (c) 2023 Red Hat, Inc. + * + * Authors: + * Ilya Maximets + * + * This work is licensed under the terms of the GNU GPL, version 2 or late= r. + * See the COPYING file in the top-level directory. + */ + + +#include "qemu/osdep.h" +#include +#include +#include +#include +#include +#include + +#include "clients.h" +#include "monitor/monitor.h" +#include "net/net.h" +#include "qapi/error.h" +#include "qemu/cutils.h" +#include "qemu/error-report.h" +#include "qemu/iov.h" +#include "qemu/main-loop.h" +#include "qemu/memalign.h" + + +typedef struct AFXDPState { + NetClientState nc; + + struct xsk_socket *xsk; + struct xsk_ring_cons rx; + struct xsk_ring_prod tx; + struct xsk_ring_cons cq; + struct xsk_ring_prod fq; + + char ifname[IFNAMSIZ]; + int ifindex; + bool read_poll; + bool write_poll; + uint32_t outstanding_tx; + + uint64_t *pool; + uint32_t n_pool; + char *buffer; + struct xsk_umem *umem; + + uint32_t n_queues; + uint32_t xdp_flags; + bool inhibit; +} AFXDPState; + +#define AF_XDP_BATCH_SIZE 64 + +static void af_xdp_send(void *opaque); +static void af_xdp_writable(void *opaque); + +/* Set the event-loop handlers for the af-xdp backend. */ +static void af_xdp_update_fd_handler(AFXDPState *s) +{ + qemu_set_fd_handler(xsk_socket__fd(s->xsk), + s->read_poll ? af_xdp_send : NULL, + s->write_poll ? af_xdp_writable : NULL, + s); +} + +/* Update the read handler. */ +static void af_xdp_read_poll(AFXDPState *s, bool enable) +{ + if (s->read_poll !=3D enable) { + s->read_poll =3D enable; + af_xdp_update_fd_handler(s); + } +} + +/* Update the write handler. */ +static void af_xdp_write_poll(AFXDPState *s, bool enable) +{ + if (s->write_poll !=3D enable) { + s->write_poll =3D enable; + af_xdp_update_fd_handler(s); + } +} + +static void af_xdp_poll(NetClientState *nc, bool enable) +{ + AFXDPState *s =3D DO_UPCAST(AFXDPState, nc, nc); + + if (s->read_poll !=3D enable || s->write_poll !=3D enable) { + s->write_poll =3D enable; + s->read_poll =3D enable; + af_xdp_update_fd_handler(s); + } +} + +static void af_xdp_complete_tx(AFXDPState *s) +{ + uint32_t idx =3D 0; + uint32_t done, i; + uint64_t *addr; + + done =3D xsk_ring_cons__peek(&s->cq, XSK_RING_CONS__DEFAULT_NUM_DESCS,= &idx); + + for (i =3D 0; i < done; i++) { + addr =3D (void *) xsk_ring_cons__comp_addr(&s->cq, idx++); + s->pool[s->n_pool++] =3D *addr; + s->outstanding_tx--; + } + + if (done) { + xsk_ring_cons__release(&s->cq, done); + } +} + +/* + * The fd_write() callback, invoked if the fd is marked as writable + * after a poll. + */ +static void af_xdp_writable(void *opaque) +{ + AFXDPState *s =3D opaque; + + /* Try to recover buffers that are already sent. */ + af_xdp_complete_tx(s); + + /* + * Unregister the handler, unless we still have packets to transmit + * and kernel needs a wake up. + */ + if (!s->outstanding_tx || !xsk_ring_prod__needs_wakeup(&s->tx)) { + af_xdp_write_poll(s, false); + } + + /* Flush any buffered packets. */ + qemu_flush_queued_packets(&s->nc); +} + +static ssize_t af_xdp_receive(NetClientState *nc, + const uint8_t *buf, size_t size) +{ + AFXDPState *s =3D DO_UPCAST(AFXDPState, nc, nc); + struct xdp_desc *desc; + uint32_t idx; + void *data; + + /* Try to recover buffers that are already sent. */ + af_xdp_complete_tx(s); + + if (size > XSK_UMEM__DEFAULT_FRAME_SIZE) { + /* We can't transmit packet this size... */ + return size; + } + + if (!s->n_pool || !xsk_ring_prod__reserve(&s->tx, 1, &idx)) { + /* + * Out of buffers or space in tx ring. Poll until we can write. + * This will also kick the Tx, if it was waiting on CQ. + */ + af_xdp_write_poll(s, true); + return 0; + } + + desc =3D xsk_ring_prod__tx_desc(&s->tx, idx); + desc->addr =3D s->pool[--s->n_pool]; + desc->len =3D size; + + data =3D xsk_umem__get_data(s->buffer, desc->addr); + memcpy(data, buf, size); + + xsk_ring_prod__submit(&s->tx, 1); + s->outstanding_tx++; + + if (xsk_ring_prod__needs_wakeup(&s->tx)) { + af_xdp_write_poll(s, true); + } + + return size; +} + +/* + * Complete a previous send (backend --> guest) and enable the + * fd_read callback. + */ +static void af_xdp_send_completed(NetClientState *nc, ssize_t len) +{ + AFXDPState *s =3D DO_UPCAST(AFXDPState, nc, nc); + + af_xdp_read_poll(s, true); +} + +static void af_xdp_fq_refill(AFXDPState *s, uint32_t n) +{ + uint32_t i, idx =3D 0; + + /* Leave one packet for Tx, just in case. */ + if (s->n_pool < n + 1) { + n =3D s->n_pool; + } + + if (!n || !xsk_ring_prod__reserve(&s->fq, n, &idx)) { + return; + } + + for (i =3D 0; i < n; i++) { + *xsk_ring_prod__fill_addr(&s->fq, idx++) =3D s->pool[--s->n_pool]; + } + xsk_ring_prod__submit(&s->fq, n); + + if (xsk_ring_prod__needs_wakeup(&s->fq)) { + /* Receive was blocked by not having enough buffers. Wake it up. = */ + af_xdp_read_poll(s, true); + } +} + +static void af_xdp_send(void *opaque) +{ + uint32_t i, n_rx, idx =3D 0; + AFXDPState *s =3D opaque; + + n_rx =3D xsk_ring_cons__peek(&s->rx, AF_XDP_BATCH_SIZE, &idx); + if (!n_rx) { + return; + } + + for (i =3D 0; i < n_rx; i++) { + const struct xdp_desc *desc; + struct iovec iov; + + desc =3D xsk_ring_cons__rx_desc(&s->rx, idx++); + + iov.iov_base =3D xsk_umem__get_data(s->buffer, desc->addr); + iov.iov_len =3D desc->len; + + s->pool[s->n_pool++] =3D desc->addr; + + if (!qemu_sendv_packet_async(&s->nc, &iov, 1, + af_xdp_send_completed)) { + /* + * The peer does not receive anymore. Packet is queued, stop + * reading from the backend until af_xdp_send_completed(). + */ + af_xdp_read_poll(s, false); + + /* Re-peek the descriptors to not break the ring cache. */ + xsk_ring_cons__cancel(&s->rx, n_rx); + n_rx =3D xsk_ring_cons__peek(&s->rx, i + 1, &idx); + g_assert(n_rx =3D=3D i + 1); + break; + } + } + + /* Release actually sent descriptors and try to re-fill. */ + xsk_ring_cons__release(&s->rx, n_rx); + af_xdp_fq_refill(s, AF_XDP_BATCH_SIZE); +} + +/* Flush and close. */ +static void af_xdp_cleanup(NetClientState *nc) +{ + AFXDPState *s =3D DO_UPCAST(AFXDPState, nc, nc); + + qemu_purge_queued_packets(nc); + + af_xdp_poll(nc, false); + + xsk_socket__delete(s->xsk); + s->xsk =3D NULL; + g_free(s->pool); + s->pool =3D NULL; + xsk_umem__delete(s->umem); + s->umem =3D NULL; + qemu_vfree(s->buffer); + s->buffer =3D NULL; + + /* Remove the program if it's the last open queue. */ + if (!s->inhibit && nc->queue_index =3D=3D s->n_queues - 1 && s->xdp_fl= ags + && bpf_xdp_detach(s->ifindex, s->xdp_flags, NULL) !=3D 0) { + fprintf(stderr, + "af-xdp: unable to remove XDP program from '%s', ifindex: = %d\n", + s->ifname, s->ifindex); + } +} + +static int af_xdp_umem_create(AFXDPState *s, int sock_fd, Error **errp) +{ + struct xsk_umem_config config =3D { + .fill_size =3D XSK_RING_PROD__DEFAULT_NUM_DESCS, + .comp_size =3D XSK_RING_CONS__DEFAULT_NUM_DESCS, + .frame_size =3D XSK_UMEM__DEFAULT_FRAME_SIZE, + .frame_headroom =3D 0, + }; + uint64_t n_descs; + uint64_t size; + int64_t i; + int ret; + + /* Number of descriptors if all 4 queues (rx, tx, cq, fq) are full. */ + n_descs =3D (XSK_RING_PROD__DEFAULT_NUM_DESCS + + XSK_RING_CONS__DEFAULT_NUM_DESCS) * 2; + size =3D n_descs * XSK_UMEM__DEFAULT_FRAME_SIZE; + + s->buffer =3D qemu_memalign(qemu_real_host_page_size(), size); + memset(s->buffer, 0, size); + + if (sock_fd < 0) { + ret =3D xsk_umem__create(&s->umem, s->buffer, size, + &s->fq, &s->cq, &config); + } else { +#ifdef HAVE_XSK_UMEM__CREATE_WITH_FD + ret =3D xsk_umem__create_with_fd(&s->umem, sock_fd, s->buffer, siz= e, + &s->fq, &s->cq, &config); +#else + ret =3D -1; + errno =3D EINVAL; +#endif + } + + if (ret) { + qemu_vfree(s->buffer); + error_setg_errno(errp, errno, + "failed to create umem for %s queue_index: %d", + s->ifname, s->nc.queue_index); + return -1; + } + + s->pool =3D g_new(uint64_t, n_descs); + /* Fill the pool in the opposite order, because it's a LIFO queue. */ + for (i =3D n_descs; i >=3D 0; i--) { + s->pool[i] =3D i * XSK_UMEM__DEFAULT_FRAME_SIZE; + } + s->n_pool =3D n_descs; + + af_xdp_fq_refill(s, XSK_RING_PROD__DEFAULT_NUM_DESCS); + + return 0; +} + +static int af_xdp_socket_create(AFXDPState *s, + const NetdevAFXDPOptions *opts, + int xsks_map_fd, Error **errp) +{ + struct xsk_socket_config cfg =3D { + .rx_size =3D XSK_RING_CONS__DEFAULT_NUM_DESCS, + .tx_size =3D XSK_RING_PROD__DEFAULT_NUM_DESCS, + .libxdp_flags =3D 0, + .bind_flags =3D XDP_USE_NEED_WAKEUP, + .xdp_flags =3D XDP_FLAGS_UPDATE_IF_NOEXIST, + }; + int queue_id, error =3D 0; + + s->inhibit =3D opts->has_inhibit && opts->inhibit; + if (s->inhibit) { + cfg.libxdp_flags |=3D XSK_LIBXDP_FLAGS__INHIBIT_PROG_LOAD; + } + + if (opts->has_force_copy && opts->force_copy) { + cfg.bind_flags |=3D XDP_COPY; + } + + queue_id =3D s->nc.queue_index; + if (opts->has_start_queue && opts->start_queue > 0) { + queue_id +=3D opts->start_queue; + } + + if (opts->has_mode) { + /* Specific mode requested. */ + cfg.xdp_flags |=3D (opts->mode =3D=3D AFXDP_MODE_NATIVE) + ? XDP_FLAGS_DRV_MODE : XDP_FLAGS_SKB_MODE; + if (xsk_socket__create(&s->xsk, s->ifname, queue_id, + s->umem, &s->rx, &s->tx, &cfg)) { + error =3D errno; + } + } else { + /* No mode requested, try native first. */ + cfg.xdp_flags |=3D XDP_FLAGS_DRV_MODE; + + if (xsk_socket__create(&s->xsk, s->ifname, queue_id, + s->umem, &s->rx, &s->tx, &cfg)) { + /* Can't use native mode, try skb. */ + cfg.xdp_flags &=3D ~XDP_FLAGS_DRV_MODE; + cfg.xdp_flags |=3D XDP_FLAGS_SKB_MODE; + + if (xsk_socket__create(&s->xsk, s->ifname, queue_id, + s->umem, &s->rx, &s->tx, &cfg)) { + error =3D errno; + } + } + } + + if (error) { + error_setg_errno(errp, error, + "failed to create AF_XDP socket for %s queue_id: = %d", + s->ifname, queue_id); + return -1; + } + + if (s->inhibit && xsks_map_fd >=3D 0) { + int xsk_fd =3D xsk_socket__fd(s->xsk); + + /* Need to update the map manually, libxdp skipped that step. */ + error =3D bpf_map_update_elem(xsks_map_fd, &queue_id, &xsk_fd, 0); + if (error) { + error_setg_errno(errp, error, + "failed to update xsks map for %s queue_id: %= d", + s->ifname, queue_id); + return -1; + } + } + + s->xdp_flags =3D cfg.xdp_flags; + + return 0; +} + +/* NetClientInfo methods. */ +static NetClientInfo net_af_xdp_info =3D { + .type =3D NET_CLIENT_DRIVER_AF_XDP, + .size =3D sizeof(AFXDPState), + .receive =3D af_xdp_receive, + .poll =3D af_xdp_poll, + .cleanup =3D af_xdp_cleanup, +}; + +#ifdef HAVE_XSK_UMEM__CREATE_WITH_FD +static int *parse_socket_fds(const char *sock_fds_str, + int64_t n_expected, Error **errp) +{ + gchar **substrings =3D g_strsplit(sock_fds_str, ":", -1); + int64_t i, n_sock_fds =3D g_strv_length(substrings); + int *sock_fds =3D NULL; + + if (n_sock_fds !=3D n_expected) { + error_setg(errp, "expected %"PRIi64" socket fds, got %"PRIi64, + n_expected, n_sock_fds); + goto exit; + } + + sock_fds =3D g_new(int, n_sock_fds); + + for (i =3D 0; i < n_sock_fds; i++) { + sock_fds[i] =3D monitor_fd_param(monitor_cur(), substrings[i], err= p); + if (sock_fds[i] < 0) { + g_free(sock_fds); + sock_fds =3D NULL; + goto exit; + } + } + +exit: + g_strfreev(substrings); + return sock_fds; +} +#endif + +/* + * The exported init function. + * + * ... -net af-xdp,ifname=3D"..." + */ +int net_init_af_xdp(const Netdev *netdev, + const char *name, NetClientState *peer, Error **errp) +{ + const NetdevAFXDPOptions *opts =3D &netdev->u.af_xdp; + NetClientState *nc, *nc0 =3D NULL; + unsigned int ifindex; + uint32_t prog_id =3D 0; + int *sock_fds =3D NULL; + int xsks_map_fd =3D -1; + int64_t i, queues; + Error *err =3D NULL; + AFXDPState *s; + + ifindex =3D if_nametoindex(opts->ifname); + if (!ifindex) { + error_setg_errno(errp, errno, "failed to get ifindex for '%s'", + opts->ifname); + return -1; + } + + queues =3D opts->has_queues ? opts->queues : 1; + if (queues < 1) { + error_setg(errp, "invalid number of queues (%" PRIi64 ") for '%s'", + queues, opts->ifname); + return -1; + } + +#ifndef HAVE_XSK_UMEM__CREATE_WITH_FD + if ((opts->has_inhibit && opts->inhibit) !=3D !!opts->xsks_map_fd) { + error_setg(errp, "expected 'inhibit=3Don' and 'xsks-map-fd' togeth= er"); + return -1; + } +#else + if ((opts->has_inhibit && opts->inhibit) + !=3D (opts->xsks_map_fd || opts->sock_fds)) { + error_setg(errp, "'inhibit=3Don' should be used together with " + "'sock-fds' or 'xsks-map-fd'"); + return -1; + } + + if (opts->xsks_map_fd && opts->sock_fds) { + error_setg(errp, "'sock-fds' and 'xsks-map-fd' are mutually exclus= ive"); + return -1; + } + + if (opts->sock_fds) { + sock_fds =3D parse_socket_fds(opts->sock_fds, queues, errp); + if (!sock_fds) { + return -1; + } + } +#endif + + if (opts->xsks_map_fd) { + xsks_map_fd =3D monitor_fd_param(monitor_cur(), opts->xsks_map_fd,= errp); + if (xsks_map_fd < 0) { + goto err; + } + } + + for (i =3D 0; i < queues; i++) { + nc =3D qemu_new_net_client(&net_af_xdp_info, peer, "af-xdp", name); + qemu_set_info_str(nc, "af-xdp%"PRIi64" to %s", i, opts->ifname); + nc->queue_index =3D i; + + if (!nc0) { + nc0 =3D nc; + } + + s =3D DO_UPCAST(AFXDPState, nc, nc); + + pstrcpy(s->ifname, sizeof(s->ifname), opts->ifname); + s->ifindex =3D ifindex; + s->n_queues =3D queues; + + if (af_xdp_umem_create(s, sock_fds ? sock_fds[i] : -1, errp) + || af_xdp_socket_create(s, opts, xsks_map_fd, errp)) { + /* Make sure the XDP program will be removed. */ + s->n_queues =3D i; + error_propagate(errp, err); + goto err; + } + } + + if (nc0) { + s =3D DO_UPCAST(AFXDPState, nc, nc0); + if (bpf_xdp_query_id(s->ifindex, s->xdp_flags, &prog_id) || !prog_= id) { + error_setg_errno(errp, errno, + "no XDP program loaded on '%s', ifindex: %d", + s->ifname, s->ifindex); + goto err; + } + } + + af_xdp_read_poll(s, true); /* Initially only poll for reads. */ + + return 0; + +err: + g_free(sock_fds); + if (nc0) { + qemu_del_net_client(nc0); + } + + return -1; +} diff --git a/net/clients.h b/net/clients.h index ed8bdfff1e..be53794582 100644 --- a/net/clients.h +++ b/net/clients.h @@ -64,6 +64,11 @@ int net_init_netmap(const Netdev *netdev, const char *na= me, NetClientState *peer, Error **errp); #endif =20 +#ifdef CONFIG_AF_XDP +int net_init_af_xdp(const Netdev *netdev, const char *name, + NetClientState *peer, Error **errp); +#endif + int net_init_vhost_user(const Netdev *netdev, const char *name, NetClientState *peer, Error **errp); =20 diff --git a/net/meson.build b/net/meson.build index bdf564a57b..61628d4684 100644 --- a/net/meson.build +++ b/net/meson.build @@ -36,6 +36,9 @@ system_ss.add(when: vde, if_true: files('vde.c')) if have_netmap system_ss.add(files('netmap.c')) endif + +system_ss.add(when: libxdp, if_true: files('af-xdp.c')) + if have_vhost_net_user system_ss.add(when: 'CONFIG_VIRTIO_NET', if_true: files('vhost-user.c'),= if_false: files('vhost-user-stub.c')) system_ss.add(when: 'CONFIG_ALL', if_true: files('vhost-user-stub.c')) diff --git a/net/net.c b/net/net.c index 6492ad530e..127f70932b 100644 --- a/net/net.c +++ b/net/net.c @@ -1082,6 +1082,9 @@ static int (* const net_client_init_fun[NET_CLIENT_DR= IVER__MAX])( #ifdef CONFIG_NETMAP [NET_CLIENT_DRIVER_NETMAP] =3D net_init_netmap, #endif +#ifdef CONFIG_AF_XDP + [NET_CLIENT_DRIVER_AF_XDP] =3D net_init_af_xdp, +#endif #ifdef CONFIG_NET_BRIDGE [NET_CLIENT_DRIVER_BRIDGE] =3D net_init_bridge, #endif @@ -1186,6 +1189,9 @@ void show_netdevs(void) #ifdef CONFIG_NETMAP "netmap", #endif +#ifdef CONFIG_AF_XDP + "af-xdp", +#endif #ifdef CONFIG_POSIX "vhost-user", #endif diff --git a/qapi/net.json b/qapi/net.json index db67501308..88f2c982c2 100644 --- a/qapi/net.json +++ b/qapi/net.json @@ -408,6 +408,62 @@ 'ifname': 'str', '*devname': 'str' } } =20 +## +# @AFXDPMode: +# +# Attach mode for a default XDP program +# +# @skb: generic mode, no driver support necessary +# +# @native: DRV mode, program is attached to a driver, packets are passed to +# the socket without allocation of skb. +# +# Since: 8.1 +## +{ 'enum': 'AFXDPMode', + 'data': [ 'native', 'skb' ] } + +## +# @NetdevAFXDPOptions: +# +# AF_XDP network backend +# +# @ifname: The name of an existing network interface. +# +# @mode: Attach mode for a default XDP program. If not specified, then +# 'native' will be tried first, then 'skb'. +# +# @force-copy: Force XDP copy mode even if device supports zero-copy. +# (default: false) +# +# @queues: number of queues to be used for multiqueue interfaces (default:= 1). +# +# @start-queue: Use @queues starting from this queue number (default: 0). +# +# @inhibit: Don't load a default XDP program, use one already loaded to +# the interface (default: false). Requires @sock-fds or @xsks-map-fd. +# +# @sock-fds: A colon (:) separated list of file descriptors for already op= en +# but not bound AF_XDP sockets in the queue order. One fd per queue. +# These descriptors should already be added into XDP socket map for +# corresponding queues. Requires @inhibit. +# +# @xsks-map-fd: A file descriptor for an already open XDP socket map in +# the already loaded XDP program. Requires @inhibit. +# +# Since: 8.1 +## +{ 'struct': 'NetdevAFXDPOptions', + 'data': { + 'ifname': 'str', + '*mode': 'AFXDPMode', + '*force-copy': 'bool', + '*queues': 'int', + '*start-queue': 'int', + '*inhibit': 'bool', + '*sock-fds': { 'type': 'str', 'if': 'HAVE_XSK_UMEM__CREATE_WITH_FD'= }, + '*xsks-map-fd': 'str' } } + ## # @NetdevVhostUserOptions: # @@ -642,13 +698,14 @@ # @vmnet-bridged: since 7.1 # @stream: since 7.2 # @dgram: since 7.2 +# @af-xdp: since 8.1 # # Since: 2.7 ## { 'enum': 'NetClientDriver', 'data': [ 'none', 'nic', 'user', 'tap', 'l2tpv3', 'socket', 'stream', 'dgram', 'vde', 'bridge', 'hubport', 'netmap', 'vhost-user', - 'vhost-vdpa', + 'vhost-vdpa', 'af-xdp', { 'name': 'vmnet-host', 'if': 'CONFIG_VMNET' }, { 'name': 'vmnet-shared', 'if': 'CONFIG_VMNET' }, { 'name': 'vmnet-bridged', 'if': 'CONFIG_VMNET' }] } @@ -680,6 +737,7 @@ 'bridge': 'NetdevBridgeOptions', 'hubport': 'NetdevHubPortOptions', 'netmap': 'NetdevNetmapOptions', + 'af-xdp': 'NetdevAFXDPOptions', 'vhost-user': 'NetdevVhostUserOptions', 'vhost-vdpa': 'NetdevVhostVDPAOptions', 'vmnet-host': { 'type': 'NetdevVmnetHostOptions', diff --git a/qemu-options.hx b/qemu-options.hx index b57489d7ca..d91610701c 100644 --- a/qemu-options.hx +++ b/qemu-options.hx @@ -2856,6 +2856,25 @@ DEF("netdev", HAS_ARG, QEMU_OPTION_netdev, " VALE port (created on the fly) called 'name' ('nmname= ' is name of the \n" " netmap device, defaults to '/dev/netmap')\n" #endif +#ifdef CONFIG_AF_XDP + "-netdev af-xdp,id=3Dstr,ifname=3Dname[,mode=3Dnative|skb][,force-copy= =3Don|off]\n" + " [,queues=3Dn][,start-queue=3Dm][,inhibit=3Don|off][,xsks-map= -fd=3Dk]\n" +#ifdef HAVE_XSK_UMEM__CREATE_WITH_FD + " [,sock-fds=3Dx:y:...:z]\n" +#endif + " attach to the existing network interface 'name' with = AF_XDP socket\n" + " use 'mode=3DMODE' to specify an XDP program attach mo= de\n" + " use 'force-copy=3Don|off' to force XDP copy mode even= if device supports zero-copy (default: off)\n" + " use 'inhibit=3Don|off' to inhibit loading of a defaul= t XDP program (default: off)\n" + " with inhibit=3Don,\n" +#ifdef HAVE_XSK_UMEM__CREATE_WITH_FD + " use 'sock-fds' to provide file descriptors for alre= ady open XDP sockets\n" + " added to a socket map in XDP program. One socket p= er queue. Or\n" +#endif + " use 'xsks-map-fd=3Dk' to provide a file descriptor = for xsks map\n" + " use 'queues=3Dn' to specify how many queues of a mult= iqueue interface should be used\n" + " use 'start-queue=3Dm' to specify the first queue that= should be used\n" +#endif #ifdef CONFIG_POSIX "-netdev vhost-user,id=3Dstr,chardev=3Ddev[,vhostforce=3Don|off]\n" " configure a vhost-user network, backed by a chardev '= dev'\n" @@ -2901,6 +2920,9 @@ DEF("nic", HAS_ARG, QEMU_OPTION_nic, #ifdef CONFIG_NETMAP "netmap|" #endif +#ifdef CONFIG_AF_XDP + "af-xdp|" +#endif #ifdef CONFIG_POSIX "vhost-user|" #endif @@ -2929,6 +2951,9 @@ DEF("net", HAS_ARG, QEMU_OPTION_net, #ifdef CONFIG_NETMAP "netmap|" #endif +#ifdef CONFIG_AF_XDP + "af-xdp|" +#endif #ifdef CONFIG_VMNET "vmnet-host|vmnet-shared|vmnet-bridged|" #endif @@ -2936,7 +2961,7 @@ DEF("net", HAS_ARG, QEMU_OPTION_net, " old way to initialize a host network interface\n" " (use the -netdev option if possible instead)\n", QEMU= _ARCH_ALL) SRST -``-nic [tap|bridge|user|l2tpv3|vde|netmap|vhost-user|socket][,...][,mac=3D= macaddr][,model=3Dmn]`` +``-nic [tap|bridge|user|l2tpv3|vde|netmap|af-xdp|vhost-user|socket][,...][= ,mac=3Dmacaddr][,model=3Dmn]`` This option is a shortcut for configuring both the on-board (default) guest NIC hardware and the host network backend in one go. The host backend options are the same as with the corresponding @@ -3350,6 +3375,62 @@ SRST # launch QEMU instance |qemu_system| linux.img -nic vde,sock=3D/tmp/myswitch =20 +``-netdev af-xdp,id=3Dstr,ifname=3Dname[,mode=3Dnative|skb][,force-copy=3D= on|off][,queues=3Dn][,start-queue=3Dm][,inhibit=3Don|off][,xsks-map-fd=3Dk]= [,sock-fds=3Dx:y:...:z]`` + Configure AF_XDP backend to connect to a network interface 'name' + using AF_XDP socket. A specific program attach mode for a default + XDP program can be forced with 'mode', defaults to best-effort, + where the likely most performant mode will be in use. Number of queues + 'n' should generally match the number or queues in the interface, + defaults to 1. Traffic arriving on non-configured device queues will + not be delivered to the network backend. + + .. parsed-literal:: + + # set number of queues to 1 + ethtool -L eth0 combined 4 + # launch QEMU instance + |qemu_system| linux.img -device virtio-net-pci,netdev=3Dn1 \\ + -netdev af-xdp,id=3Dn1,ifname=3Deth0,queues=3D4 + + 'start-queue' option can be specified if a particular range of queues + [m, m + n] should be in use. For example, this is necessary in order + to use MLX NICs in native mode. The driver will create a separate set + of queues on top of regular ones, and only these queues can be used + for AF_XDP sockets. MLX NICs will also require an additional traffic + redirection with ethtool to these queues. E.g.: + + .. parsed-literal:: + + # set number of queues to 1 + ethtool -L eth0 combined 1 + # redirect all the traffic to the second queue (id: 1) + # note: mlx5 driver requires non-empty key/mask pair. + ethtool -N eth0 flow-type ether \\ + dst 00:00:00:00:00:00 m FF:FF:FF:FF:FF:FE action 1 + ethtool -N eth0 flow-type ether \\ + dst 00:00:00:00:00:01 m FF:FF:FF:FF:FF:FE action 1 + # launch QEMU instance + |qemu_system| linux.img -device virtio-net-pci,netdev=3Dn1 \\ + -netdev af-xdp,id=3Dn1,ifname=3Deth0,queues=3D1,start-queue=3D1 + + XDP program can also be loaded externally. In this case 'inhibit' opt= ion + should be set to 'on' and 'xsks-map-fd' provided with a file descriptor + for an open XDP socket map of that program, or 'sock-fds' with file + descriptors for already open but not bound XDP sockets already added t= o a + socket map for corresponding queues. One socket per queue. + + .. parsed-literal:: + + |qemu_system| linux.img -device virtio-net-pci,netdev=3Dn1 \\ + -netdev af-xdp,id=3Dn1,ifname=3Deth0,queues=3D3,inhibit=3Don,s= ock-fds=3D15:16:17 + + With 'inhibit=3Don' and 'sock-fds', QEMU process will only require 32 = MB + of locked memory (RLIMIT_MEMLOCK) per queue or CAP_IPC_LOCK capability. + With 'inhibit=3Don' and 'xsks-map-fd' it will additionally require + CAP_NET_RAW capability. With 'inhibit=3Doff', CAP_SYS/NET_ADMIN shoul= d be + added as well. + + ``-netdev vhost-user,chardev=3Did[,vhostforce=3Don|off][,queues=3Dn]`` Establish a vhost-user netdev, backed by a chardev id. The chardev should be a unix domain socket backed one. The vhost-user uses a diff --git a/scripts/ci/org.centos/stream/8/x86_64/configure b/scripts/ci/o= rg.centos/stream/8/x86_64/configure index d02b09a4b9..7585c4c4ed 100755 --- a/scripts/ci/org.centos/stream/8/x86_64/configure +++ b/scripts/ci/org.centos/stream/8/x86_64/configure @@ -35,6 +35,7 @@ --block-drv-ro-whitelist=3D"vmdk,vhdx,vpc,https,ssh" \ --with-coroutine=3Ducontext \ --tls-priority=3D@QEMU,SYSTEM \ +--disable-af-xdp \ --disable-attr \ --disable-auth-pam \ --disable-avx2 \ diff --git a/scripts/meson-buildoptions.sh b/scripts/meson-buildoptions.sh index 7dd5709ef4..162e455309 100644 --- a/scripts/meson-buildoptions.sh +++ b/scripts/meson-buildoptions.sh @@ -74,6 +74,7 @@ meson_options_help() { printf "%s\n" 'disabled with --disable-FEATURE, default is enabled if av= ailable' printf "%s\n" '(unless built with --without-default-features):' printf "%s\n" '' + printf "%s\n" ' af-xdp AF_XDP network backend support' printf "%s\n" ' alsa ALSA sound support' printf "%s\n" ' attr attr/xattr support' printf "%s\n" ' auth-pam PAM access control' @@ -207,6 +208,8 @@ meson_options_help() { } _meson_option_parse() { case $1 in + --enable-af-xdp) printf "%s" -Daf_xdp=3Denabled ;; + --disable-af-xdp) printf "%s" -Daf_xdp=3Ddisabled ;; --enable-alsa) printf "%s" -Dalsa=3Denabled ;; --disable-alsa) printf "%s" -Dalsa=3Ddisabled ;; --enable-attr) printf "%s" -Dattr=3Denabled ;; diff --git a/tests/docker/dockerfiles/debian-amd64.docker b/tests/docker/do= ckerfiles/debian-amd64.docker index e39871c7bb..207f7adfb9 100644 --- a/tests/docker/dockerfiles/debian-amd64.docker +++ b/tests/docker/dockerfiles/debian-amd64.docker @@ -97,6 +97,7 @@ RUN export DEBIAN_FRONTEND=3Dnoninteractive && \ libvirglrenderer-dev \ libvte-2.91-dev \ libxen-dev \ + libxdp-dev \ libzstd-dev \ llvm \ locales \ --=20 2.40.1