af_xdp.rst 34 KB

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