xref: /linux/Documentation/networking/af_xdp.rst (revision fc9c7ca5fcbf7fe3bcba87d1ff72f0009071ba86)
1.. SPDX-License-Identifier: GPL-2.0
2
3======
4AF_XDP
5======
6
7Overview
8========
9
10AF_XDP is an address family that is optimized for high performance
11packet processing.
12
13This document assumes that the reader is familiar with BPF and XDP. If
14not, the Cilium project has an excellent reference guide at
15http://cilium.readthedocs.io/en/latest/bpf/.
16
17Using the XDP_REDIRECT action from an XDP program, the program can
18redirect ingress frames to other XDP enabled netdevs, using the
19bpf_redirect_map() function. AF_XDP sockets enable the possibility for
20XDP programs to redirect frames to a memory buffer in a user-space
21application.
22
23An AF_XDP socket (XSK) is created with the normal socket()
24syscall. Associated with each XSK are two rings: the RX ring and the
25TX ring. A socket can receive packets on the RX ring and it can send
26packets on the TX ring. These rings are registered and sized with the
27setsockopts XDP_RX_RING and XDP_TX_RING, respectively. It is mandatory
28to have at least one of these rings for each socket. An RX or TX
29descriptor ring points to a data buffer in a memory area called a
30UMEM. RX and TX can share the same UMEM so that a packet does not have
31to be copied between RX and TX. Moreover, if a packet needs to be kept
32for a while due to a possible retransmit, the descriptor that points
33to that packet can be changed to point to another and reused right
34away. This again avoids copying data.
35
36The UMEM consists of a number of equally sized chunks. A descriptor in
37one of the rings references a frame by referencing its addr. The addr
38is simply an offset within the entire UMEM region. The user space
39allocates memory for this UMEM using whatever means it feels is most
40appropriate (malloc, mmap, huge pages, etc). This memory area is then
41registered with the kernel using the new setsockopt XDP_UMEM_REG. The
42UMEM also has two rings: the FILL ring and the COMPLETION ring. The
43FILL ring is used by the application to send down addr for the kernel
44to fill in with RX packet data. References to these frames will then
45appear in the RX ring once each packet has been received. The
46COMPLETION ring, on the other hand, contains frame addresses from Tx
47descriptors that the kernel has finished processing and that can now be
48used again by user space, for either Tx or Rx. This includes frames whose
49transmission has completed as well as frames referenced by invalid Tx
50descriptors rejected by the kernel. A completion therefore returns
51ownership of a frame to user space, but does not by itself guarantee that
52the packet was successfully transmitted.
53
54The socket is then finally bound with a bind() call to a device and a
55specific queue id on that device, and it is not until bind is
56completed that traffic starts to flow.
57
58The UMEM can be shared between processes, if desired. If a process
59wants to do this, it simply skips the registration of the UMEM and its
60corresponding two rings, sets the XDP_SHARED_UMEM flag in the bind
61call and submits the XSK of the process it would like to share UMEM
62with as well as its own newly created XSK socket. The new process will
63then receive frame addr references in its own RX ring that point to
64this shared UMEM. Note that since the ring structures are
65single-consumer / single-producer (for performance reasons), the new
66process has to create its own socket with associated RX and TX rings,
67since it cannot share this with the other process. This is also the
68reason that there is only one set of FILL and COMPLETION rings per
69UMEM. It is the responsibility of a single process to handle the UMEM.
70
71How is then packets distributed from an XDP program to the XSKs? There
72is a BPF map called XSKMAP (or BPF_MAP_TYPE_XSKMAP in full). The
73user-space application can place an XSK at an arbitrary place in this
74map. The XDP program can then redirect a packet to a specific index in
75this map and at this point XDP validates that the XSK in that map was
76indeed bound to that device and ring number. If not, the packet is
77dropped. If the map is empty at that index, the packet is also
78dropped. This also means that it is currently mandatory to have an XDP
79program loaded (and one XSK in the XSKMAP) to be able to get any
80traffic to user space through the XSK.
81
82AF_XDP can operate in two different modes: XDP_SKB and XDP_DRV. If the
83driver does not have support for XDP, or XDP_SKB is explicitly chosen
84when loading the XDP program, XDP_SKB mode is employed that uses SKBs
85together with the generic XDP support and copies out the data to user
86space. A fallback mode that works for any network device. On the other
87hand, if the driver has support for XDP, it will be used by the AF_XDP
88code to provide better performance, but there is still a copy of the
89data into user space.
90
91Concepts
92========
93
94In order to use an AF_XDP socket, a number of associated objects need
95to be setup. These objects and their options are explained in the
96following sections.
97
98For an overview on how AF_XDP works, you can also take a look at the
99Linux Plumbers paper from 2018 on the subject:
100http://vger.kernel.org/lpc_net2018_talks/lpc18_paper_af_xdp_perf-v2.pdf. Do
101NOT consult the paper from 2017 on "AF_PACKET v4", the first attempt
102at AF_XDP. Nearly everything changed since then. Jonathan Corbet has
103also written an excellent article on LWN, "Accelerating networking
104with AF_XDP". It can be found at https://lwn.net/Articles/750845/.
105
106UMEM
107----
108
109UMEM is a region of virtual contiguous memory, divided into
110equal-sized frames. An UMEM is associated to a netdev and a specific
111queue id of that netdev. It is created and configured (chunk size,
112headroom, start address and size) by using the XDP_UMEM_REG setsockopt
113system call. A UMEM is bound to a netdev and queue id, via the bind()
114system call.
115
116An AF_XDP is socket linked to a single UMEM, but one UMEM can have
117multiple AF_XDP sockets. To share an UMEM created via one socket A,
118the next socket B can do this by setting the XDP_SHARED_UMEM flag in
119struct sockaddr_xdp member sxdp_flags, and passing the file descriptor
120of A to struct sockaddr_xdp member sxdp_shared_umem_fd.
121
122The UMEM has two single-producer/single-consumer rings that are used
123to transfer ownership of UMEM frames between the kernel and the
124user-space application.
125
126Rings
127-----
128
129There are a four different kind of rings: FILL, COMPLETION, RX and
130TX. All rings are single-producer/single-consumer, so the user-space
131application need explicit synchronization of multiple
132processes/threads are reading/writing to them.
133
134The UMEM uses two rings: FILL and COMPLETION. Each socket associated
135with the UMEM must have an RX queue, TX queue or both. Say, that there
136is a setup with four sockets (all doing TX and RX). Then there will be
137one FILL ring, one COMPLETION ring, four TX rings and four RX rings.
138
139The rings are head(producer)/tail(consumer) based rings. A producer
140writes the data ring at the index pointed out by struct xdp_ring
141producer member, and increasing the producer index. A consumer reads
142the data ring at the index pointed out by struct xdp_ring consumer
143member, and increasing the consumer index.
144
145The rings are configured and created via the _RING setsockopt system
146calls and mmapped to user-space using the appropriate offset to mmap()
147(XDP_PGOFF_RX_RING, XDP_PGOFF_TX_RING, XDP_UMEM_PGOFF_FILL_RING and
148XDP_UMEM_PGOFF_COMPLETION_RING).
149
150The size of the rings need to be of size power of two.
151
152UMEM Fill Ring
153~~~~~~~~~~~~~~
154
155The FILL ring is used to transfer ownership of UMEM frames from
156user-space to kernel-space. The UMEM addrs are passed in the ring. As
157an example, if the UMEM is 64k and each chunk is 4k, then the UMEM has
15816 chunks and can pass addrs between 0 and 64k.
159
160Frames passed to the kernel are used for the ingress path (RX rings).
161
162The user application produces UMEM addrs to this ring. Note that, if
163running the application with aligned chunk mode, the kernel will mask
164the incoming addr.  E.g. for a chunk size of 2k, the log2(2048) LSB of
165the addr will be masked off, meaning that 2048, 2050 and 3000 refers
166to the same chunk. If the user application is run in the unaligned
167chunks mode, then the incoming addr will be left untouched.
168
169
170UMEM Completion Ring
171~~~~~~~~~~~~~~~~~~~~
172
173The COMPLETION Ring is used to transfer ownership of UMEM frames from
174kernel-space to user-space. Just like the FILL ring, UMEM indices are
175used. Frames passed from the kernel to user-space are frames referenced
176by Tx descriptors that the kernel has finished processing and can be
177used by user-space again. This includes both frames whose transmission
178has completed and frames referenced by invalid Tx descriptors that were
179rejected and reclaimed by the kernel. A completion entry does not
180guarantee successful packet transmission. The user application consumes
181UMEM addrs from this ring.
182
183
184RX Ring
185~~~~~~~
186
187The RX ring is the receiving side of a socket. Each entry in the ring
188is a struct xdp_desc descriptor. The descriptor contains UMEM offset
189(addr) and the length of the data (len).
190
191If no frames have been passed to kernel via the FILL ring, no
192descriptors will (or can) appear on the RX ring.
193
194The user application consumes struct xdp_desc descriptors from this
195ring.
196
197TX Ring
198~~~~~~~
199
200The TX ring is used to send frames. The struct xdp_desc descriptor is
201filled (index, length and offset) and passed into the ring.
202
203To start the transfer a sendmsg() system call is required. This might
204be relaxed in the future.
205
206The user application produces struct xdp_desc descriptors to this
207ring.
208
209Libbpf
210======
211
212Libbpf is a helper library for eBPF and XDP that makes using these
213technologies a lot simpler. It also contains specific helper functions
214in tools/testing/selftests/bpf/xsk.h for facilitating the use of
215AF_XDP. It contains two types of functions: those that can be used to
216make the setup of AF_XDP socket easier and ones that can be used in the
217data plane to access the rings safely and quickly.
218
219We recommend that you use this library unless you have become a power
220user. It will make your program a lot simpler.
221
222XSKMAP / BPF_MAP_TYPE_XSKMAP
223============================
224
225On XDP side there is a BPF map type BPF_MAP_TYPE_XSKMAP (XSKMAP) that
226is used in conjunction with bpf_redirect_map() to pass the ingress
227frame to a socket.
228
229The user application inserts the socket into the map, via the bpf()
230system call.
231
232Note that if an XDP program tries to redirect to a socket that does
233not match the queue configuration and netdev, the frame will be
234dropped. E.g. an AF_XDP socket is bound to netdev eth0 and
235queue 17. Only the XDP program executing for eth0 and queue 17 will
236successfully pass data to the socket. Please refer to the sample
237application (samples/bpf/) in for an example.
238
239Configuration Flags and Socket Options
240======================================
241
242These are the various configuration flags that can be used to control
243and monitor the behavior of AF_XDP sockets.
244
245XDP_COPY and XDP_ZEROCOPY bind flags
246------------------------------------
247
248When you bind to a socket, the kernel will first try to use zero-copy
249copy. If zero-copy is not supported, it will fall back on using copy
250mode, i.e. copying all packets out to user space. But if you would
251like to force a certain mode, you can use the following flags. If you
252pass the XDP_COPY flag to the bind call, the kernel will force the
253socket into copy mode. If it cannot use copy mode, the bind call will
254fail with an error. Conversely, the XDP_ZEROCOPY flag will force the
255socket into zero-copy mode or fail.
256
257XDP_SHARED_UMEM bind flag
258-------------------------
259
260This flag enables you to bind multiple sockets to the same UMEM. It
261works on the same queue id, between queue ids and between
262netdevs/devices. In this mode, each socket has their own RX and TX
263rings as usual, but you are going to have one or more FILL and
264COMPLETION ring pairs. You have to create one of these pairs per
265unique netdev and queue id tuple that you bind to.
266
267Starting with the case were we would like to share a UMEM between
268sockets bound to the same netdev and queue id. The UMEM (tied to the
269fist socket created) will only have a single FILL ring and a single
270COMPLETION ring as there is only on unique netdev,queue_id tuple that
271we have bound to. To use this mode, create the first socket and bind
272it in the normal way. Create a second socket and create an RX and a TX
273ring, or at least one of them, but no FILL or COMPLETION rings as the
274ones from the first socket will be used. In the bind call, set he
275XDP_SHARED_UMEM option and provide the initial socket's fd in the
276sxdp_shared_umem_fd field. You can attach an arbitrary number of extra
277sockets this way.
278
279What socket will then a packet arrive on? This is decided by the XDP
280program. Put all the sockets in the XSK_MAP and just indicate which
281index in the array you would like to send each packet to. A simple
282round-robin example of distributing packets is shown below:
283
284.. code-block:: c
285
286   #include <linux/bpf.h>
287   #include "bpf_helpers.h"
288
289   #define MAX_SOCKS 16
290
291   struct {
292       __uint(type, BPF_MAP_TYPE_XSKMAP);
293       __uint(max_entries, MAX_SOCKS);
294       __uint(key_size, sizeof(int));
295       __uint(value_size, sizeof(int));
296   } xsks_map SEC(".maps");
297
298   static unsigned int rr;
299
300   SEC("xdp_sock") int xdp_sock_prog(struct xdp_md *ctx)
301   {
302       rr = (rr + 1) & (MAX_SOCKS - 1);
303
304       return bpf_redirect_map(&xsks_map, rr, XDP_DROP);
305   }
306
307Note, that since there is only a single set of FILL and COMPLETION
308rings, and they are single producer, single consumer rings, you need
309to make sure that multiple processes or threads do not use these rings
310concurrently. There are no synchronization primitives in the
311libbpf code that protects multiple users at this point in time.
312
313Libbpf uses this mode if you create more than one socket tied to the
314same UMEM. However, note that you need to supply the
315XSK_LIBBPF_FLAGS__INHIBIT_PROG_LOAD libbpf_flag with the
316xsk_socket__create calls and load your own XDP program as there is no
317built in one in libbpf that will route the traffic for you.
318
319The second case is when you share a UMEM between sockets that are
320bound to different queue ids and/or netdevs. In this case you have to
321create one FILL ring and one COMPLETION ring for each unique
322netdev,queue_id pair. Let us say you want to create two sockets bound
323to two different queue ids on the same netdev. Create the first socket
324and bind it in the normal way. Create a second socket and create an RX
325and a TX ring, or at least one of them, and then one FILL and
326COMPLETION ring for this socket. Then in the bind call, set he
327XDP_SHARED_UMEM option and provide the initial socket's fd in the
328sxdp_shared_umem_fd field as you registered the UMEM on that
329socket. These two sockets will now share one and the same UMEM.
330
331There is no need to supply an XDP program like the one in the previous
332case where sockets were bound to the same queue id and
333device. Instead, use the NIC's packet steering capabilities to steer
334the packets to the right queue. In the previous example, there is only
335one queue shared among sockets, so the NIC cannot do this steering. It
336can only steer between queues.
337
338In libbpf, you need to use the xsk_socket__create_shared() API as it
339takes a reference to a FILL ring and a COMPLETION ring that will be
340created for you and bound to the shared UMEM. You can use this
341function for all the sockets you create, or you can use it for the
342second and following ones and use xsk_socket__create() for the first
343one. Both methods yield the same result.
344
345Note that a UMEM can be shared between sockets on the same queue id
346and device, as well as between queues on the same device and between
347devices at the same time.
348
349XDP_USE_NEED_WAKEUP bind flag
350-----------------------------
351
352This option adds support for a new flag called need_wakeup that is
353present in the FILL ring and the TX ring, the rings for which user
354space is a producer. When this option is set in the bind call, the
355need_wakeup flag will be set if the kernel needs to be explicitly
356woken up by a syscall to continue processing packets. If the flag is
357zero, no syscall is needed.
358
359If the flag is set on the FILL ring, the application needs to call
360poll() to be able to continue to receive packets on the RX ring. This
361can happen, for example, when the kernel has detected that there are no
362more buffers on the FILL ring and no buffers left on the RX HW ring of
363the NIC. In this case, interrupts are turned off as the NIC cannot
364receive any packets (as there are no buffers to put them in), and the
365need_wakeup flag is set so that user space can put buffers on the
366FILL ring and then call poll() so that the kernel driver can put these
367buffers on the HW ring and start to receive packets.
368
369If the flag is set for the TX ring, it means that the application
370needs to explicitly notify the kernel to send any packets put on the
371TX ring. This can be accomplished either by a poll() call, as in the
372RX path, or by calling sendto().
373
374An example with the use of libbpf helpers would look like this for the
375TX path:
376
377.. code-block:: c
378
379   if (xsk_ring_prod__needs_wakeup(&my_tx_ring))
380       sendto(xsk_socket__fd(xsk_handle), NULL, 0, MSG_DONTWAIT, NULL, 0);
381
382I.e., only use the syscall if the flag is set.
383
384We recommend that you always enable this mode as it usually leads to
385better performance especially if you run the application and the
386driver on the same core, but also if you use different cores for the
387application and the kernel driver, as it reduces the number of
388syscalls needed for the TX path.
389
390XDP_{RX|TX|UMEM_FILL|UMEM_COMPLETION}_RING setsockopts
391------------------------------------------------------
392
393These setsockopts sets the number of descriptors that the RX, TX,
394FILL, and COMPLETION rings respectively should have. It is mandatory
395to set the size of at least one of the RX and TX rings. If you set
396both, you will be able to both receive and send traffic from your
397application, but if you only want to do one of them, you can save
398resources by only setting up one of them. Both the FILL ring and the
399COMPLETION ring are mandatory as you need to have a UMEM tied to your
400socket. But if the XDP_SHARED_UMEM flag is used, any socket after the
401first one does not have a UMEM and should in that case not have any
402FILL or COMPLETION rings created as the ones from the shared UMEM will
403be used. Note, that the rings are single-producer single-consumer, so
404do not try to access them from multiple processes at the same
405time. See the XDP_SHARED_UMEM section.
406
407In libbpf, you can create Rx-only and Tx-only sockets by supplying
408NULL to the rx and tx arguments, respectively, to the
409xsk_socket__create function.
410
411If you create a Tx-only socket, we recommend that you do not put any
412packets on the fill ring. If you do this, drivers might think you are
413going to receive something when you in fact will not, and this can
414negatively impact performance.
415
416XDP_UMEM_REG setsockopt
417-----------------------
418
419This setsockopt registers a UMEM to a socket. This is the area that
420contain all the buffers that packet can reside in. The call takes a
421pointer to the beginning of this area and the size of it. Moreover, it
422also has parameter called chunk_size that is the size that the UMEM is
423divided into. It can only be 2K or 4K at the moment. If you have an
424UMEM area that is 128K and a chunk size of 2K, this means that you
425will be able to hold a maximum of 128K / 2K = 64 packets in your UMEM
426area and that your largest packet size can be 2K.
427
428There is also an option to set the headroom of each single buffer in
429the UMEM. If you set this to N bytes, it means that the packet will
430start N bytes into the buffer leaving the first N bytes for the
431application to use. The final option is the flags field, but it will
432be dealt with in separate sections for each UMEM flag.
433
434SO_BINDTODEVICE setsockopt
435--------------------------
436
437This is a generic SOL_SOCKET option that can be used to tie AF_XDP
438socket to a particular network interface.  It is useful when a socket
439is created by a privileged process and passed to a non-privileged one.
440Once the option is set, kernel will refuse attempts to bind that socket
441to a different interface.  Updating the value requires CAP_NET_RAW.
442
443XDP_MAX_TX_SKB_BUDGET setsockopt
444--------------------------------
445
446This setsockopt sets the maximum number of descriptors that can be handled
447and passed to the driver at one send syscall. It is applied in the copy
448mode to allow application to tune the per-socket maximum iteration for
449better throughput and less frequency of send syscall.
450Allowed range is [32, xs->tx->nentries].
451
452XDP_STATISTICS getsockopt
453-------------------------
454
455Gets drop statistics of a socket that can be useful for debug
456purposes. The supported statistics are shown below:
457
458.. code-block:: c
459
460   struct xdp_statistics {
461       __u64 rx_dropped; /* Dropped for reasons other than invalid desc */
462       __u64 rx_invalid_descs; /* Dropped due to invalid descriptor */
463       __u64 tx_invalid_descs; /* Dropped due to invalid descriptor */
464   };
465
466XDP_OPTIONS getsockopt
467----------------------
468
469Gets options from an XDP socket. The only one supported so far is
470XDP_OPTIONS_ZEROCOPY which tells you if zero-copy is on or not.
471
472Multi-Buffer Support
473====================
474
475With multi-buffer support, programs using AF_XDP sockets can receive
476and transmit packets consisting of multiple buffers both in copy and
477zero-copy mode. For example, a packet can consist of two
478frames/buffers, one with the header and the other one with the data,
479or a 9K Ethernet jumbo frame can be constructed by chaining together
480three 4K frames.
481
482Some definitions:
483
484* A packet consists of one or more frames
485
486* A descriptor in one of the AF_XDP rings always refers to a single
487  frame. In the case the packet consists of a single frame, the
488  descriptor refers to the whole packet.
489
490To enable multi-buffer support for an AF_XDP socket, use the new bind
491flag XDP_USE_SG. If this is not provided, all multi-buffer packets
492will be dropped just as before. Note that the XDP program loaded also
493needs to be in multi-buffer mode. This can be accomplished by using
494"xdp.frags" as the section name of the XDP program used.
495
496To represent a packet consisting of multiple frames, a new flag called
497XDP_PKT_CONTD is introduced in the options field of the Rx and Tx
498descriptors. If it is true (1) the packet continues with the next
499descriptor and if it is false (0) it means this is the last descriptor
500of the packet. Why the reverse logic of end-of-packet (eop) flag found
501in many NICs? Just to preserve compatibility with non-multi-buffer
502applications that have this bit set to false for all packets on Rx,
503and the apps set the options field to zero for Tx, as anything else
504will be treated as an invalid descriptor.
505
506These are the semantics for producing packets onto AF_XDP Tx ring
507consisting of multiple frames:
508
509* When an invalid descriptor is found, the complete packet is treated as
510  invalid. The kernel consumes descriptors through the descriptor marking
511  the end of the packet and returns all their frame addresses through the
512  COMPLETION ring. A standalone invalid descriptor is treated as a
513  one-descriptor invalid packet. The descriptor following the end of the
514  invalid packet is treated as the start of a new packet. As before, if
515  your program is producing invalid descriptors you have a bug that must
516  be fixed. Rejected descriptors are reported in the ``tx_invalid_descs``
517  statistic.
518
519* Zero length descriptors are treated as invalid descriptors.
520
521* For copy mode, the maximum supported number of frames in a packet is
522  equal to CONFIG_MAX_SKB_FRAGS + 1. If it is exceeded, all descriptors
523  through the end of the oversized packet are consumed, treated as invalid,
524  and their frame addresses are returned through the COMPLETION ring. To
525  produce an application that will work on any system regardless of this
526  config setting, limit the number of frags to 18, as the minimum value of
527  the config is 17.
528
529* For zero-copy mode, the limit is up to what the NIC HW
530  supports. Usually at least five on the NICs we have checked. We
531  consciously chose to not enforce a rigid limit (such as
532  CONFIG_MAX_SKB_FRAGS + 1) for zero-copy mode, as it would have
533  resulted in copy actions under the hood to fit into what limit the
534  NIC supports. Kind of defeats the purpose of zero-copy mode. How to
535  probe for this limit is explained in the "probe for multi-buffer
536  support" section.
537
538On the Rx path in copy-mode, the xsk core copies the XDP data into
539multiple descriptors, if needed, and sets the XDP_PKT_CONTD flag as
540detailed before. Zero-copy mode works the same, though the data is not
541copied. When the application gets a descriptor with the XDP_PKT_CONTD
542flag set to one, it means that the packet consists of multiple buffers
543and it continues with the next buffer in the following
544descriptor. When a descriptor with XDP_PKT_CONTD == 0 is received, it
545means that this is the last buffer of the packet. AF_XDP guarantees
546that only a complete packet (all frames in the packet) is sent to the
547application. If there is not enough space in the AF_XDP Rx ring, all
548frames of the packet will be dropped.
549
550If application reads a batch of descriptors, using for example the libxdp
551interfaces, it is not guaranteed that the batch will end with a full
552packet. It might end in the middle of a packet and the rest of the
553buffers of that packet will arrive at the beginning of the next batch,
554since the libxdp interface does not read the whole ring (unless you
555have an enormous batch size or a very small ring size).
556
557An example program each for Rx and Tx multi-buffer support can be found
558later in this document.
559
560Usage
561-----
562
563In order to use AF_XDP sockets two parts are needed. The user-space
564application and the XDP program. For a complete setup and usage example,
565please refer to the xdp-project at
566https://github.com/xdp-project/bpf-examples/tree/main/AF_XDP-example.
567
568The XDP code sample is the following:
569
570.. code-block:: c
571
572   SEC("xdp_sock") int xdp_sock_prog(struct xdp_md *ctx)
573   {
574       int index = ctx->rx_queue_index;
575
576       // A set entry here means that the corresponding queue_id
577       // has an active AF_XDP socket bound to it.
578       if (bpf_map_lookup_elem(&xsks_map, &index))
579           return bpf_redirect_map(&xsks_map, index, 0);
580
581       return XDP_PASS;
582   }
583
584A simple but not so performance ring dequeue and enqueue could look
585like this:
586
587.. code-block:: c
588
589    // struct xdp_rxtx_ring {
590    //     __u32 *producer;
591    //     __u32 *consumer;
592    //     struct xdp_desc *desc;
593    // };
594
595    // struct xdp_umem_ring {
596    //     __u32 *producer;
597    //     __u32 *consumer;
598    //     __u64 *desc;
599    // };
600
601    // typedef struct xdp_rxtx_ring RING;
602    // typedef struct xdp_umem_ring RING;
603
604    // typedef struct xdp_desc RING_TYPE;
605    // typedef __u64 RING_TYPE;
606
607    int dequeue_one(RING *ring, RING_TYPE *item)
608    {
609        __u32 entries = *ring->producer - *ring->consumer;
610
611        if (entries == 0)
612            return -1;
613
614        // read-barrier!
615
616        *item = ring->desc[*ring->consumer & (RING_SIZE - 1)];
617        (*ring->consumer)++;
618        return 0;
619    }
620
621    int enqueue_one(RING *ring, const RING_TYPE *item)
622    {
623        u32 free_entries = RING_SIZE - (*ring->producer - *ring->consumer);
624
625        if (free_entries == 0)
626            return -1;
627
628        ring->desc[*ring->producer & (RING_SIZE - 1)] = *item;
629
630        // write-barrier!
631
632        (*ring->producer)++;
633        return 0;
634    }
635
636But please use the libbpf functions as they are optimized and ready to
637use. Will make your life easier.
638
639Usage Multi-Buffer Rx
640---------------------
641
642Here is a simple Rx path pseudo-code example (using libxdp interfaces
643for simplicity). Error paths have been excluded to keep it short:
644
645.. code-block:: c
646
647    void rx_packets(struct xsk_socket_info *xsk)
648    {
649        static bool new_packet = true;
650        u32 idx_rx = 0, idx_fq = 0;
651        static char *pkt;
652
653        int rcvd = xsk_ring_cons__peek(&xsk->rx, opt_batch_size, &idx_rx);
654
655        xsk_ring_prod__reserve(&xsk->umem->fq, rcvd, &idx_fq);
656
657        for (int i = 0; i < rcvd; i++) {
658            struct xdp_desc *desc = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx++);
659            char *frag = xsk_umem__get_data(xsk->umem->buffer, desc->addr);
660            bool eop = !(desc->options & XDP_PKT_CONTD);
661
662            if (new_packet)
663                pkt = frag;
664            else
665                add_frag_to_pkt(pkt, frag);
666
667            if (eop)
668                process_pkt(pkt);
669
670            new_packet = eop;
671
672            *xsk_ring_prod__fill_addr(&xsk->umem->fq, idx_fq++) = desc->addr;
673        }
674
675        xsk_ring_prod__submit(&xsk->umem->fq, rcvd);
676        xsk_ring_cons__release(&xsk->rx, rcvd);
677    }
678
679Usage Multi-Buffer Tx
680---------------------
681
682Here is an example Tx path pseudo-code (using libxdp interfaces for
683simplicity) ignoring that the umem is finite in size, and that we
684eventually will run out of packets to send. Also assumes pkts.addr
685points to a valid location in the umem.
686
687.. code-block:: c
688
689    void tx_packets(struct xsk_socket_info *xsk, struct pkt *pkts,
690                    int batch_size)
691    {
692        u32 idx, i, pkt_nb = 0;
693
694        xsk_ring_prod__reserve(&xsk->tx, batch_size, &idx);
695
696        for (i = 0; i < batch_size;) {
697            u64 addr = pkts[pkt_nb].addr;
698            u32 len = pkts[pkt_nb].size;
699
700            do {
701                struct xdp_desc *tx_desc;
702
703                tx_desc = xsk_ring_prod__tx_desc(&xsk->tx, idx + i++);
704                tx_desc->addr = addr;
705
706                if (len > xsk_frame_size) {
707                    tx_desc->len = xsk_frame_size;
708                    tx_desc->options = XDP_PKT_CONTD;
709                } else {
710                    tx_desc->len = len;
711                    tx_desc->options = 0;
712                    pkt_nb++;
713                }
714                len -= tx_desc->len;
715                addr += xsk_frame_size;
716
717                if (i == batch_size) {
718                    /* Remember len, addr, pkt_nb for next iteration.
719                     * Skipped for simplicity.
720                     */
721                    break;
722                }
723            } while (len);
724        }
725
726        xsk_ring_prod__submit(&xsk->tx, i);
727    }
728
729Probing for Multi-Buffer Support
730--------------------------------
731
732To discover if a driver supports multi-buffer AF_XDP in SKB or DRV
733mode, use the XDP_FEATURES feature of netlink in linux/netdev.h to
734query for NETDEV_XDP_ACT_RX_SG support. This is the same flag as for
735querying for XDP multi-buffer support. If XDP supports multi-buffer in
736a driver, then AF_XDP will also support that in SKB and DRV mode.
737
738To discover if a driver supports multi-buffer AF_XDP in zero-copy
739mode, use XDP_FEATURES and first check the NETDEV_XDP_ACT_XSK_ZEROCOPY
740flag. If it is set, it means that at least zero-copy is supported and
741you should go and check the netlink attribute
742NETDEV_A_DEV_XDP_ZC_MAX_SEGS in linux/netdev.h. An unsigned integer
743value will be returned stating the max number of frags that are
744supported by this device in zero-copy mode. These are the possible
745return values:
746
7471: Multi-buffer for zero-copy is not supported by this device, as max
748   one fragment supported means that multi-buffer is not possible.
749
750>=2: Multi-buffer is supported in zero-copy mode for this device. The
751     returned number signifies the max number of frags supported.
752
753For an example on how these are used through libbpf, please take a
754look at tools/testing/selftests/bpf/xskxceiver.c.
755
756Multi-Buffer Support for Zero-Copy Drivers
757------------------------------------------
758
759Zero-copy drivers usually use the batched APIs for Rx and Tx
760processing. Note that the Tx batch API guarantees that it will provide
761a batch of Tx descriptors that ends with full packet at the end. This
762to facilitate extending a zero-copy driver with multi-buffer support.
763
764Sample application
765==================
766There is a xdpsock benchmarking/test application that can be found at
767https://github.com/xdp-project/bpf-examples/tree/main/AF_XDP-example
768that demonstrates how to use AF_XDP sockets with private
769UMEMs. Say that you would like your UDP traffic from port 4242 to end
770up in queue 16, that we will enable AF_XDP on. Here, we use ethtool
771for this::
772
773      ethtool -N p3p2 rx-flow-hash udp4 fn
774      ethtool -N p3p2 flow-type udp4 src-port 4242 dst-port 4242 \
775          action 16
776
777Running the rxdrop benchmark in XDP_DRV mode can then be done
778using::
779
780      samples/bpf/xdpsock -i p3p2 -q 16 -r -N
781
782For XDP_SKB mode, use the switch "-S" instead of "-N" and all options
783can be displayed with "-h", as usual.
784
785This sample application uses libbpf to make the setup and usage of
786AF_XDP simpler. If you want to know how the raw uapi of AF_XDP is
787really used to make something more advanced, take a look at the libbpf
788code in tools/testing/selftests/bpf/xsk.[ch].
789
790FAQ
791=======
792
793Q: I am not seeing any traffic on the socket. What am I doing wrong?
794
795A: When a netdev of a physical NIC is initialized, Linux usually
796   allocates one RX and TX queue pair per core. So on a 8 core system,
797   queue ids 0 to 7 will be allocated, one per core. In the AF_XDP
798   bind call or the xsk_socket__create libbpf function call, you
799   specify a specific queue id to bind to and it is only the traffic
800   towards that queue you are going to get on you socket. So in the
801   example above, if you bind to queue 0, you are NOT going to get any
802   traffic that is distributed to queues 1 through 7. If you are
803   lucky, you will see the traffic, but usually it will end up on one
804   of the queues you have not bound to.
805
806   There are a number of ways to solve the problem of getting the
807   traffic you want to the queue id you bound to. If you want to see
808   all the traffic, you can force the netdev to only have 1 queue, queue
809   id 0, and then bind to queue 0. You can use ethtool to do this::
810
811     sudo ethtool -L <interface> combined 1
812
813   If you want to only see part of the traffic, you can program the
814   NIC through ethtool to filter out your traffic to a single queue id
815   that you can bind your XDP socket to. Here is one example in which
816   UDP traffic to and from port 4242 are sent to queue 2::
817
818     sudo ethtool -N <interface> rx-flow-hash udp4 fn
819     sudo ethtool -N <interface> flow-type udp4 src-port 4242 dst-port \
820     4242 action 2
821
822   A number of other ways are possible all up to the capabilities of
823   the NIC you have.
824
825Q: Can I use the XSKMAP to implement a switch between different umems
826   in copy mode?
827
828A: The short answer is no, that is not supported at the moment. The
829   XSKMAP can only be used to switch traffic coming in on queue id X
830   to sockets bound to the same queue id X. The XSKMAP can contain
831   sockets bound to different queue ids, for example X and Y, but only
832   traffic goming in from queue id Y can be directed to sockets bound
833   to the same queue id Y. In zero-copy mode, you should use the
834   switch, or other distribution mechanism, in your NIC to direct
835   traffic to the correct queue id and socket.
836
837Q: My packets are sometimes corrupted. What is wrong?
838
839A: Care has to be taken not to feed the same buffer in the UMEM into
840   more than one ring at the same time. If you for example feed the
841   same buffer into the FILL ring and the TX ring at the same time, the
842   NIC might receive data into the buffer at the same time it is
843   sending it. This will cause some packets to become corrupted. Same
844   thing goes for feeding the same buffer into the FILL rings
845   belonging to different queue ids or netdevs bound with the
846   XDP_SHARED_UMEM flag.
847
848Credits
849=======
850
851- Björn Töpel (AF_XDP core)
852- Magnus Karlsson (AF_XDP core)
853- Alexander Duyck
854- Alexei Starovoitov
855- Daniel Borkmann
856- Jesper Dangaard Brouer
857- John Fastabend
858- Jonathan Corbet (LWN coverage)
859- Michael S. Tsirkin
860- Qi Z Zhang
861- Willem de Bruijn
862