net/af_xdp: use recvfrom only if busy polling enabled
[dpdk.git] / drivers / net / af_xdp / rte_eth_af_xdp.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2019-2020 Intel Corporation.
3  */
4 #include <unistd.h>
5 #include <errno.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <netinet/in.h>
9 #include <net/if.h>
10 #include <sys/socket.h>
11 #include <sys/ioctl.h>
12 #include <linux/if_ether.h>
13 #include <linux/if_xdp.h>
14 #include <linux/if_link.h>
15 #include <linux/ethtool.h>
16 #include <linux/sockios.h>
17 #include "af_xdp_deps.h"
18 #include <bpf/xsk.h>
19
20 #include <rte_ethdev.h>
21 #include <ethdev_driver.h>
22 #include <ethdev_vdev.h>
23 #include <rte_kvargs.h>
24 #include <rte_bus_vdev.h>
25 #include <rte_string_fns.h>
26 #include <rte_branch_prediction.h>
27 #include <rte_common.h>
28 #include <rte_dev.h>
29 #include <rte_eal.h>
30 #include <rte_ether.h>
31 #include <rte_lcore.h>
32 #include <rte_log.h>
33 #include <rte_memory.h>
34 #include <rte_memzone.h>
35 #include <rte_mempool.h>
36 #include <rte_mbuf.h>
37 #include <rte_malloc.h>
38 #include <rte_ring.h>
39 #include <rte_spinlock.h>
40
41 #include "compat.h"
42
43 #ifndef SO_PREFER_BUSY_POLL
44 #define SO_PREFER_BUSY_POLL 69
45 #endif
46 #ifndef SO_BUSY_POLL_BUDGET
47 #define SO_BUSY_POLL_BUDGET 70
48 #endif
49
50
51 #ifndef SOL_XDP
52 #define SOL_XDP 283
53 #endif
54
55 #ifndef AF_XDP
56 #define AF_XDP 44
57 #endif
58
59 #ifndef PF_XDP
60 #define PF_XDP AF_XDP
61 #endif
62
63 RTE_LOG_REGISTER(af_xdp_logtype, pmd.net.af_xdp, NOTICE);
64
65 #define AF_XDP_LOG(level, fmt, args...)                 \
66         rte_log(RTE_LOG_ ## level, af_xdp_logtype,      \
67                 "%s(): " fmt, __func__, ##args)
68
69 #define ETH_AF_XDP_FRAME_SIZE           2048
70 #define ETH_AF_XDP_NUM_BUFFERS          4096
71 #define ETH_AF_XDP_DFLT_NUM_DESCS       XSK_RING_CONS__DEFAULT_NUM_DESCS
72 #define ETH_AF_XDP_DFLT_START_QUEUE_IDX 0
73 #define ETH_AF_XDP_DFLT_QUEUE_COUNT     1
74 #define ETH_AF_XDP_DFLT_BUSY_BUDGET     64
75 #define ETH_AF_XDP_DFLT_BUSY_TIMEOUT    20
76
77 #define ETH_AF_XDP_RX_BATCH_SIZE        XSK_RING_CONS__DEFAULT_NUM_DESCS
78 #define ETH_AF_XDP_TX_BATCH_SIZE        XSK_RING_CONS__DEFAULT_NUM_DESCS
79
80
81 struct xsk_umem_info {
82         struct xsk_umem *umem;
83         struct rte_ring *buf_ring;
84         const struct rte_memzone *mz;
85         struct rte_mempool *mb_pool;
86         void *buffer;
87         uint8_t refcnt;
88         uint32_t max_xsks;
89 };
90
91 struct rx_stats {
92         uint64_t rx_pkts;
93         uint64_t rx_bytes;
94         uint64_t rx_dropped;
95 };
96
97 struct pkt_rx_queue {
98         struct xsk_ring_cons rx;
99         struct xsk_umem_info *umem;
100         struct xsk_socket *xsk;
101         struct rte_mempool *mb_pool;
102
103         struct rx_stats stats;
104
105         struct xsk_ring_prod fq;
106         struct xsk_ring_cons cq;
107
108         struct pkt_tx_queue *pair;
109         struct pollfd fds[1];
110         int xsk_queue_idx;
111         int busy_budget;
112 };
113
114 struct tx_stats {
115         uint64_t tx_pkts;
116         uint64_t tx_bytes;
117         uint64_t tx_dropped;
118 };
119
120 struct pkt_tx_queue {
121         struct xsk_ring_prod tx;
122         struct xsk_umem_info *umem;
123
124         struct tx_stats stats;
125
126         struct pkt_rx_queue *pair;
127         int xsk_queue_idx;
128 };
129
130 struct pmd_internals {
131         int if_index;
132         char if_name[IFNAMSIZ];
133         int start_queue_idx;
134         int queue_cnt;
135         int max_queue_cnt;
136         int combined_queue_cnt;
137         bool shared_umem;
138         char prog_path[PATH_MAX];
139         bool custom_prog_configured;
140
141         struct rte_ether_addr eth_addr;
142
143         struct pkt_rx_queue *rx_queues;
144         struct pkt_tx_queue *tx_queues;
145 };
146
147 #define ETH_AF_XDP_IFACE_ARG                    "iface"
148 #define ETH_AF_XDP_START_QUEUE_ARG              "start_queue"
149 #define ETH_AF_XDP_QUEUE_COUNT_ARG              "queue_count"
150 #define ETH_AF_XDP_SHARED_UMEM_ARG              "shared_umem"
151 #define ETH_AF_XDP_PROG_ARG                     "xdp_prog"
152 #define ETH_AF_XDP_BUDGET_ARG                   "busy_budget"
153
154 static const char * const valid_arguments[] = {
155         ETH_AF_XDP_IFACE_ARG,
156         ETH_AF_XDP_START_QUEUE_ARG,
157         ETH_AF_XDP_QUEUE_COUNT_ARG,
158         ETH_AF_XDP_SHARED_UMEM_ARG,
159         ETH_AF_XDP_PROG_ARG,
160         ETH_AF_XDP_BUDGET_ARG,
161         NULL
162 };
163
164 static const struct rte_eth_link pmd_link = {
165         .link_speed = ETH_SPEED_NUM_10G,
166         .link_duplex = ETH_LINK_FULL_DUPLEX,
167         .link_status = ETH_LINK_DOWN,
168         .link_autoneg = ETH_LINK_AUTONEG
169 };
170
171 /* List which tracks PMDs to facilitate sharing UMEMs across them. */
172 struct internal_list {
173         TAILQ_ENTRY(internal_list) next;
174         struct rte_eth_dev *eth_dev;
175 };
176
177 TAILQ_HEAD(internal_list_head, internal_list);
178 static struct internal_list_head internal_list =
179         TAILQ_HEAD_INITIALIZER(internal_list);
180
181 static pthread_mutex_t internal_list_lock = PTHREAD_MUTEX_INITIALIZER;
182
183 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
184 static inline int
185 reserve_fill_queue_zc(struct xsk_umem_info *umem, uint16_t reserve_size,
186                       struct rte_mbuf **bufs, struct xsk_ring_prod *fq)
187 {
188         uint32_t idx;
189         uint16_t i;
190
191         if (unlikely(!xsk_ring_prod__reserve(fq, reserve_size, &idx))) {
192                 for (i = 0; i < reserve_size; i++)
193                         rte_pktmbuf_free(bufs[i]);
194                 AF_XDP_LOG(DEBUG, "Failed to reserve enough fq descs.\n");
195                 return -1;
196         }
197
198         for (i = 0; i < reserve_size; i++) {
199                 __u64 *fq_addr;
200                 uint64_t addr;
201
202                 fq_addr = xsk_ring_prod__fill_addr(fq, idx++);
203                 addr = (uint64_t)bufs[i] - (uint64_t)umem->buffer -
204                                 umem->mb_pool->header_size;
205                 *fq_addr = addr;
206         }
207
208         xsk_ring_prod__submit(fq, reserve_size);
209
210         return 0;
211 }
212 #else
213 static inline int
214 reserve_fill_queue_cp(struct xsk_umem_info *umem, uint16_t reserve_size,
215                       struct rte_mbuf **bufs __rte_unused,
216                       struct xsk_ring_prod *fq)
217 {
218         void *addrs[reserve_size];
219         uint32_t idx;
220         uint16_t i;
221
222         if (rte_ring_dequeue_bulk(umem->buf_ring, addrs, reserve_size, NULL)
223                     != reserve_size) {
224                 AF_XDP_LOG(DEBUG, "Failed to get enough buffers for fq.\n");
225                 return -1;
226         }
227
228         if (unlikely(!xsk_ring_prod__reserve(fq, reserve_size, &idx))) {
229                 AF_XDP_LOG(DEBUG, "Failed to reserve enough fq descs.\n");
230                 rte_ring_enqueue_bulk(umem->buf_ring, addrs,
231                                 reserve_size, NULL);
232                 return -1;
233         }
234
235         for (i = 0; i < reserve_size; i++) {
236                 __u64 *fq_addr;
237
238                 fq_addr = xsk_ring_prod__fill_addr(fq, idx++);
239                 *fq_addr = (uint64_t)addrs[i];
240         }
241
242         xsk_ring_prod__submit(fq, reserve_size);
243
244         return 0;
245 }
246 #endif
247
248 static inline int
249 reserve_fill_queue(struct xsk_umem_info *umem, uint16_t reserve_size,
250                    struct rte_mbuf **bufs, struct xsk_ring_prod *fq)
251 {
252 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
253         return reserve_fill_queue_zc(umem, reserve_size, bufs, fq);
254 #else
255         return reserve_fill_queue_cp(umem, reserve_size, bufs, fq);
256 #endif
257 }
258
259 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
260 static uint16_t
261 af_xdp_rx_zc(void *queue, struct rte_mbuf **bufs, uint16_t nb_pkts)
262 {
263         struct pkt_rx_queue *rxq = queue;
264         struct xsk_ring_cons *rx = &rxq->rx;
265         struct xsk_ring_prod *fq = &rxq->fq;
266         struct xsk_umem_info *umem = rxq->umem;
267         uint32_t idx_rx = 0;
268         unsigned long rx_bytes = 0;
269         int i;
270         struct rte_mbuf *fq_bufs[ETH_AF_XDP_RX_BATCH_SIZE];
271
272         nb_pkts = xsk_ring_cons__peek(rx, nb_pkts, &idx_rx);
273
274         if (nb_pkts == 0) {
275                 rx_syscall_handler(&rxq->fq, rxq->busy_budget, &rxq->fds[0],
276                                    rxq->xsk);
277                 return 0;
278         }
279
280         /* allocate bufs for fill queue replenishment after rx */
281         if (rte_pktmbuf_alloc_bulk(umem->mb_pool, fq_bufs, nb_pkts)) {
282                 AF_XDP_LOG(DEBUG,
283                         "Failed to get enough buffers for fq.\n");
284                 /* rollback cached_cons which is added by
285                  * xsk_ring_cons__peek
286                  */
287                 rx->cached_cons -= nb_pkts;
288                 return 0;
289         }
290
291         for (i = 0; i < nb_pkts; i++) {
292                 const struct xdp_desc *desc;
293                 uint64_t addr;
294                 uint32_t len;
295                 uint64_t offset;
296
297                 desc = xsk_ring_cons__rx_desc(rx, idx_rx++);
298                 addr = desc->addr;
299                 len = desc->len;
300
301                 offset = xsk_umem__extract_offset(addr);
302                 addr = xsk_umem__extract_addr(addr);
303
304                 bufs[i] = (struct rte_mbuf *)
305                                 xsk_umem__get_data(umem->buffer, addr +
306                                         umem->mb_pool->header_size);
307                 bufs[i]->data_off = offset - sizeof(struct rte_mbuf) -
308                         rte_pktmbuf_priv_size(umem->mb_pool) -
309                         umem->mb_pool->header_size;
310
311                 rte_pktmbuf_pkt_len(bufs[i]) = len;
312                 rte_pktmbuf_data_len(bufs[i]) = len;
313                 rx_bytes += len;
314         }
315
316         xsk_ring_cons__release(rx, nb_pkts);
317         (void)reserve_fill_queue(umem, nb_pkts, fq_bufs, fq);
318
319         /* statistics */
320         rxq->stats.rx_pkts += nb_pkts;
321         rxq->stats.rx_bytes += rx_bytes;
322
323         return nb_pkts;
324 }
325 #else
326 static uint16_t
327 af_xdp_rx_cp(void *queue, struct rte_mbuf **bufs, uint16_t nb_pkts)
328 {
329         struct pkt_rx_queue *rxq = queue;
330         struct xsk_ring_cons *rx = &rxq->rx;
331         struct xsk_umem_info *umem = rxq->umem;
332         struct xsk_ring_prod *fq = &rxq->fq;
333         uint32_t idx_rx = 0;
334         unsigned long rx_bytes = 0;
335         int i;
336         uint32_t free_thresh = fq->size >> 1;
337         struct rte_mbuf *mbufs[ETH_AF_XDP_RX_BATCH_SIZE];
338
339         if (xsk_prod_nb_free(fq, free_thresh) >= free_thresh)
340                 (void)reserve_fill_queue(umem, nb_pkts, NULL, fq);
341
342         nb_pkts = xsk_ring_cons__peek(rx, nb_pkts, &idx_rx);
343         if (nb_pkts == 0) {
344 #if defined(XDP_USE_NEED_WAKEUP)
345                 if (xsk_ring_prod__needs_wakeup(fq))
346                         (void)poll(rxq->fds, 1, 1000);
347 #endif
348                 return 0;
349         }
350
351         if (unlikely(rte_pktmbuf_alloc_bulk(rxq->mb_pool, mbufs, nb_pkts))) {
352                 /* rollback cached_cons which is added by
353                  * xsk_ring_cons__peek
354                  */
355                 rx->cached_cons -= nb_pkts;
356                 return 0;
357         }
358
359         for (i = 0; i < nb_pkts; i++) {
360                 const struct xdp_desc *desc;
361                 uint64_t addr;
362                 uint32_t len;
363                 void *pkt;
364
365                 desc = xsk_ring_cons__rx_desc(rx, idx_rx++);
366                 addr = desc->addr;
367                 len = desc->len;
368                 pkt = xsk_umem__get_data(rxq->umem->mz->addr, addr);
369
370                 rte_memcpy(rte_pktmbuf_mtod(mbufs[i], void *), pkt, len);
371                 rte_ring_enqueue(umem->buf_ring, (void *)addr);
372                 rte_pktmbuf_pkt_len(mbufs[i]) = len;
373                 rte_pktmbuf_data_len(mbufs[i]) = len;
374                 rx_bytes += len;
375                 bufs[i] = mbufs[i];
376         }
377
378         xsk_ring_cons__release(rx, nb_pkts);
379
380         /* statistics */
381         rxq->stats.rx_pkts += nb_pkts;
382         rxq->stats.rx_bytes += rx_bytes;
383
384         return nb_pkts;
385 }
386 #endif
387
388 static uint16_t
389 af_xdp_rx(void *queue, struct rte_mbuf **bufs, uint16_t nb_pkts)
390 {
391 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
392         return af_xdp_rx_zc(queue, bufs, nb_pkts);
393 #else
394         return af_xdp_rx_cp(queue, bufs, nb_pkts);
395 #endif
396 }
397
398 static uint16_t
399 eth_af_xdp_rx(void *queue, struct rte_mbuf **bufs, uint16_t nb_pkts)
400 {
401         uint16_t nb_rx;
402
403         if (likely(nb_pkts <= ETH_AF_XDP_RX_BATCH_SIZE))
404                 return af_xdp_rx(queue, bufs, nb_pkts);
405
406         /* Split larger batch into smaller batches of size
407          * ETH_AF_XDP_RX_BATCH_SIZE or less.
408          */
409         nb_rx = 0;
410         while (nb_pkts) {
411                 uint16_t ret, n;
412
413                 n = (uint16_t)RTE_MIN(nb_pkts, ETH_AF_XDP_RX_BATCH_SIZE);
414                 ret = af_xdp_rx(queue, &bufs[nb_rx], n);
415                 nb_rx = (uint16_t)(nb_rx + ret);
416                 nb_pkts = (uint16_t)(nb_pkts - ret);
417                 if (ret < n)
418                         break;
419         }
420
421         return nb_rx;
422 }
423
424 static void
425 pull_umem_cq(struct xsk_umem_info *umem, int size, struct xsk_ring_cons *cq)
426 {
427         size_t i, n;
428         uint32_t idx_cq = 0;
429
430         n = xsk_ring_cons__peek(cq, size, &idx_cq);
431
432         for (i = 0; i < n; i++) {
433                 uint64_t addr;
434                 addr = *xsk_ring_cons__comp_addr(cq, idx_cq++);
435 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
436                 addr = xsk_umem__extract_addr(addr);
437                 rte_pktmbuf_free((struct rte_mbuf *)
438                                         xsk_umem__get_data(umem->buffer,
439                                         addr + umem->mb_pool->header_size));
440 #else
441                 rte_ring_enqueue(umem->buf_ring, (void *)addr);
442 #endif
443         }
444
445         xsk_ring_cons__release(cq, n);
446 }
447
448 static void
449 kick_tx(struct pkt_tx_queue *txq, struct xsk_ring_cons *cq)
450 {
451         struct xsk_umem_info *umem = txq->umem;
452
453         pull_umem_cq(umem, XSK_RING_CONS__DEFAULT_NUM_DESCS, cq);
454
455         if (tx_syscall_needed(&txq->tx))
456                 while (send(xsk_socket__fd(txq->pair->xsk), NULL,
457                             0, MSG_DONTWAIT) < 0) {
458                         /* some thing unexpected */
459                         if (errno != EBUSY && errno != EAGAIN && errno != EINTR)
460                                 break;
461
462                         /* pull from completion queue to leave more space */
463                         if (errno == EAGAIN)
464                                 pull_umem_cq(umem,
465                                              XSK_RING_CONS__DEFAULT_NUM_DESCS,
466                                              cq);
467                 }
468 }
469
470 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
471 static uint16_t
472 af_xdp_tx_zc(void *queue, struct rte_mbuf **bufs, uint16_t nb_pkts)
473 {
474         struct pkt_tx_queue *txq = queue;
475         struct xsk_umem_info *umem = txq->umem;
476         struct rte_mbuf *mbuf;
477         unsigned long tx_bytes = 0;
478         int i;
479         uint32_t idx_tx;
480         uint16_t count = 0;
481         struct xdp_desc *desc;
482         uint64_t addr, offset;
483         struct xsk_ring_cons *cq = &txq->pair->cq;
484         uint32_t free_thresh = cq->size >> 1;
485
486         if (xsk_cons_nb_avail(cq, free_thresh) >= free_thresh)
487                 pull_umem_cq(umem, XSK_RING_CONS__DEFAULT_NUM_DESCS, cq);
488
489         for (i = 0; i < nb_pkts; i++) {
490                 mbuf = bufs[i];
491
492                 if (mbuf->pool == umem->mb_pool) {
493                         if (!xsk_ring_prod__reserve(&txq->tx, 1, &idx_tx)) {
494                                 kick_tx(txq, cq);
495                                 if (!xsk_ring_prod__reserve(&txq->tx, 1,
496                                                             &idx_tx))
497                                         goto out;
498                         }
499                         desc = xsk_ring_prod__tx_desc(&txq->tx, idx_tx);
500                         desc->len = mbuf->pkt_len;
501                         addr = (uint64_t)mbuf - (uint64_t)umem->buffer -
502                                         umem->mb_pool->header_size;
503                         offset = rte_pktmbuf_mtod(mbuf, uint64_t) -
504                                         (uint64_t)mbuf +
505                                         umem->mb_pool->header_size;
506                         offset = offset << XSK_UNALIGNED_BUF_OFFSET_SHIFT;
507                         desc->addr = addr | offset;
508                         count++;
509                 } else {
510                         struct rte_mbuf *local_mbuf =
511                                         rte_pktmbuf_alloc(umem->mb_pool);
512                         void *pkt;
513
514                         if (local_mbuf == NULL)
515                                 goto out;
516
517                         if (!xsk_ring_prod__reserve(&txq->tx, 1, &idx_tx)) {
518                                 rte_pktmbuf_free(local_mbuf);
519                                 kick_tx(txq, cq);
520                                 goto out;
521                         }
522
523                         desc = xsk_ring_prod__tx_desc(&txq->tx, idx_tx);
524                         desc->len = mbuf->pkt_len;
525
526                         addr = (uint64_t)local_mbuf - (uint64_t)umem->buffer -
527                                         umem->mb_pool->header_size;
528                         offset = rte_pktmbuf_mtod(local_mbuf, uint64_t) -
529                                         (uint64_t)local_mbuf +
530                                         umem->mb_pool->header_size;
531                         pkt = xsk_umem__get_data(umem->buffer, addr + offset);
532                         offset = offset << XSK_UNALIGNED_BUF_OFFSET_SHIFT;
533                         desc->addr = addr | offset;
534                         rte_memcpy(pkt, rte_pktmbuf_mtod(mbuf, void *),
535                                         desc->len);
536                         rte_pktmbuf_free(mbuf);
537                         count++;
538                 }
539
540                 tx_bytes += mbuf->pkt_len;
541         }
542
543         kick_tx(txq, cq);
544
545 out:
546         xsk_ring_prod__submit(&txq->tx, count);
547
548         txq->stats.tx_pkts += count;
549         txq->stats.tx_bytes += tx_bytes;
550         txq->stats.tx_dropped += nb_pkts - count;
551
552         return count;
553 }
554 #else
555 static uint16_t
556 af_xdp_tx_cp(void *queue, struct rte_mbuf **bufs, uint16_t nb_pkts)
557 {
558         struct pkt_tx_queue *txq = queue;
559         struct xsk_umem_info *umem = txq->umem;
560         struct rte_mbuf *mbuf;
561         void *addrs[ETH_AF_XDP_TX_BATCH_SIZE];
562         unsigned long tx_bytes = 0;
563         int i;
564         uint32_t idx_tx;
565         struct xsk_ring_cons *cq = &txq->pair->cq;
566
567         pull_umem_cq(umem, nb_pkts, cq);
568
569         nb_pkts = rte_ring_dequeue_bulk(umem->buf_ring, addrs,
570                                         nb_pkts, NULL);
571         if (nb_pkts == 0)
572                 return 0;
573
574         if (xsk_ring_prod__reserve(&txq->tx, nb_pkts, &idx_tx) != nb_pkts) {
575                 kick_tx(txq, cq);
576                 rte_ring_enqueue_bulk(umem->buf_ring, addrs, nb_pkts, NULL);
577                 return 0;
578         }
579
580         for (i = 0; i < nb_pkts; i++) {
581                 struct xdp_desc *desc;
582                 void *pkt;
583
584                 desc = xsk_ring_prod__tx_desc(&txq->tx, idx_tx + i);
585                 mbuf = bufs[i];
586                 desc->len = mbuf->pkt_len;
587
588                 desc->addr = (uint64_t)addrs[i];
589                 pkt = xsk_umem__get_data(umem->mz->addr,
590                                          desc->addr);
591                 rte_memcpy(pkt, rte_pktmbuf_mtod(mbuf, void *), desc->len);
592                 tx_bytes += mbuf->pkt_len;
593                 rte_pktmbuf_free(mbuf);
594         }
595
596         xsk_ring_prod__submit(&txq->tx, nb_pkts);
597
598         kick_tx(txq, cq);
599
600         txq->stats.tx_pkts += nb_pkts;
601         txq->stats.tx_bytes += tx_bytes;
602
603         return nb_pkts;
604 }
605
606 static uint16_t
607 af_xdp_tx_cp_batch(void *queue, struct rte_mbuf **bufs, uint16_t nb_pkts)
608 {
609         uint16_t nb_tx;
610
611         if (likely(nb_pkts <= ETH_AF_XDP_TX_BATCH_SIZE))
612                 return af_xdp_tx_cp(queue, bufs, nb_pkts);
613
614         nb_tx = 0;
615         while (nb_pkts) {
616                 uint16_t ret, n;
617
618                 /* Split larger batch into smaller batches of size
619                  * ETH_AF_XDP_TX_BATCH_SIZE or less.
620                  */
621                 n = (uint16_t)RTE_MIN(nb_pkts, ETH_AF_XDP_TX_BATCH_SIZE);
622                 ret = af_xdp_tx_cp(queue, &bufs[nb_tx], n);
623                 nb_tx = (uint16_t)(nb_tx + ret);
624                 nb_pkts = (uint16_t)(nb_pkts - ret);
625                 if (ret < n)
626                         break;
627         }
628
629         return nb_tx;
630 }
631 #endif
632
633 static uint16_t
634 eth_af_xdp_tx(void *queue, struct rte_mbuf **bufs, uint16_t nb_pkts)
635 {
636 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
637         return af_xdp_tx_zc(queue, bufs, nb_pkts);
638 #else
639         return af_xdp_tx_cp_batch(queue, bufs, nb_pkts);
640 #endif
641 }
642
643 static int
644 eth_dev_start(struct rte_eth_dev *dev)
645 {
646         dev->data->dev_link.link_status = ETH_LINK_UP;
647
648         return 0;
649 }
650
651 /* This function gets called when the current port gets stopped. */
652 static int
653 eth_dev_stop(struct rte_eth_dev *dev)
654 {
655         dev->data->dev_link.link_status = ETH_LINK_DOWN;
656         return 0;
657 }
658
659 /* Find ethdev in list */
660 static inline struct internal_list *
661 find_internal_resource(struct pmd_internals *port_int)
662 {
663         int found = 0;
664         struct internal_list *list = NULL;
665
666         if (port_int == NULL)
667                 return NULL;
668
669         pthread_mutex_lock(&internal_list_lock);
670
671         TAILQ_FOREACH(list, &internal_list, next) {
672                 struct pmd_internals *list_int =
673                                 list->eth_dev->data->dev_private;
674                 if (list_int == port_int) {
675                         found = 1;
676                         break;
677                 }
678         }
679
680         pthread_mutex_unlock(&internal_list_lock);
681
682         if (!found)
683                 return NULL;
684
685         return list;
686 }
687
688 /* Check if the netdev,qid context already exists */
689 static inline bool
690 ctx_exists(struct pkt_rx_queue *rxq, const char *ifname,
691                 struct pkt_rx_queue *list_rxq, const char *list_ifname)
692 {
693         bool exists = false;
694
695         if (rxq->xsk_queue_idx == list_rxq->xsk_queue_idx &&
696                         !strncmp(ifname, list_ifname, IFNAMSIZ)) {
697                 AF_XDP_LOG(ERR, "ctx %s,%i already exists, cannot share umem\n",
698                                         ifname, rxq->xsk_queue_idx);
699                 exists = true;
700         }
701
702         return exists;
703 }
704
705 /* Get a pointer to an existing UMEM which overlays the rxq's mb_pool */
706 static inline int
707 get_shared_umem(struct pkt_rx_queue *rxq, const char *ifname,
708                         struct xsk_umem_info **umem)
709 {
710         struct internal_list *list;
711         struct pmd_internals *internals;
712         int i = 0, ret = 0;
713         struct rte_mempool *mb_pool = rxq->mb_pool;
714
715         if (mb_pool == NULL)
716                 return ret;
717
718         pthread_mutex_lock(&internal_list_lock);
719
720         TAILQ_FOREACH(list, &internal_list, next) {
721                 internals = list->eth_dev->data->dev_private;
722                 for (i = 0; i < internals->queue_cnt; i++) {
723                         struct pkt_rx_queue *list_rxq =
724                                                 &internals->rx_queues[i];
725                         if (rxq == list_rxq)
726                                 continue;
727                         if (mb_pool == internals->rx_queues[i].mb_pool) {
728                                 if (ctx_exists(rxq, ifname, list_rxq,
729                                                 internals->if_name)) {
730                                         ret = -1;
731                                         goto out;
732                                 }
733                                 if (__atomic_load_n(
734                                         &internals->rx_queues[i].umem->refcnt,
735                                                         __ATOMIC_ACQUIRE)) {
736                                         *umem = internals->rx_queues[i].umem;
737                                         goto out;
738                                 }
739                         }
740                 }
741         }
742
743 out:
744         pthread_mutex_unlock(&internal_list_lock);
745
746         return ret;
747 }
748
749 static int
750 eth_dev_configure(struct rte_eth_dev *dev)
751 {
752         struct pmd_internals *internal = dev->data->dev_private;
753
754         /* rx/tx must be paired */
755         if (dev->data->nb_rx_queues != dev->data->nb_tx_queues)
756                 return -EINVAL;
757
758         if (internal->shared_umem) {
759                 struct internal_list *list = NULL;
760                 const char *name = dev->device->name;
761
762                 /* Ensure PMD is not already inserted into the list */
763                 list = find_internal_resource(internal);
764                 if (list)
765                         return 0;
766
767                 list = rte_zmalloc_socket(name, sizeof(*list), 0,
768                                         dev->device->numa_node);
769                 if (list == NULL)
770                         return -1;
771
772                 list->eth_dev = dev;
773                 pthread_mutex_lock(&internal_list_lock);
774                 TAILQ_INSERT_TAIL(&internal_list, list, next);
775                 pthread_mutex_unlock(&internal_list_lock);
776         }
777
778         return 0;
779 }
780
781 static int
782 eth_dev_info(struct rte_eth_dev *dev, struct rte_eth_dev_info *dev_info)
783 {
784         struct pmd_internals *internals = dev->data->dev_private;
785
786         dev_info->if_index = internals->if_index;
787         dev_info->max_mac_addrs = 1;
788         dev_info->max_rx_pktlen = ETH_FRAME_LEN;
789         dev_info->max_rx_queues = internals->queue_cnt;
790         dev_info->max_tx_queues = internals->queue_cnt;
791
792         dev_info->min_mtu = RTE_ETHER_MIN_MTU;
793 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
794         dev_info->max_mtu = getpagesize() -
795                                 sizeof(struct rte_mempool_objhdr) -
796                                 sizeof(struct rte_mbuf) -
797                                 RTE_PKTMBUF_HEADROOM - XDP_PACKET_HEADROOM;
798 #else
799         dev_info->max_mtu = ETH_AF_XDP_FRAME_SIZE - XDP_PACKET_HEADROOM;
800 #endif
801
802         dev_info->default_rxportconf.burst_size = ETH_AF_XDP_DFLT_BUSY_BUDGET;
803         dev_info->default_txportconf.burst_size = ETH_AF_XDP_DFLT_BUSY_BUDGET;
804         dev_info->default_rxportconf.nb_queues = 1;
805         dev_info->default_txportconf.nb_queues = 1;
806         dev_info->default_rxportconf.ring_size = ETH_AF_XDP_DFLT_NUM_DESCS;
807         dev_info->default_txportconf.ring_size = ETH_AF_XDP_DFLT_NUM_DESCS;
808
809         return 0;
810 }
811
812 static int
813 eth_stats_get(struct rte_eth_dev *dev, struct rte_eth_stats *stats)
814 {
815         struct pmd_internals *internals = dev->data->dev_private;
816         struct xdp_statistics xdp_stats;
817         struct pkt_rx_queue *rxq;
818         struct pkt_tx_queue *txq;
819         socklen_t optlen;
820         int i, ret;
821
822         for (i = 0; i < dev->data->nb_rx_queues; i++) {
823                 optlen = sizeof(struct xdp_statistics);
824                 rxq = &internals->rx_queues[i];
825                 txq = rxq->pair;
826                 stats->q_ipackets[i] = rxq->stats.rx_pkts;
827                 stats->q_ibytes[i] = rxq->stats.rx_bytes;
828
829                 stats->q_opackets[i] = txq->stats.tx_pkts;
830                 stats->q_obytes[i] = txq->stats.tx_bytes;
831
832                 stats->ipackets += stats->q_ipackets[i];
833                 stats->ibytes += stats->q_ibytes[i];
834                 stats->imissed += rxq->stats.rx_dropped;
835                 stats->oerrors += txq->stats.tx_dropped;
836                 ret = getsockopt(xsk_socket__fd(rxq->xsk), SOL_XDP,
837                                 XDP_STATISTICS, &xdp_stats, &optlen);
838                 if (ret != 0) {
839                         AF_XDP_LOG(ERR, "getsockopt() failed for XDP_STATISTICS.\n");
840                         return -1;
841                 }
842                 stats->imissed += xdp_stats.rx_dropped;
843
844                 stats->opackets += stats->q_opackets[i];
845                 stats->obytes += stats->q_obytes[i];
846         }
847
848         return 0;
849 }
850
851 static int
852 eth_stats_reset(struct rte_eth_dev *dev)
853 {
854         struct pmd_internals *internals = dev->data->dev_private;
855         int i;
856
857         for (i = 0; i < internals->queue_cnt; i++) {
858                 memset(&internals->rx_queues[i].stats, 0,
859                                         sizeof(struct rx_stats));
860                 memset(&internals->tx_queues[i].stats, 0,
861                                         sizeof(struct tx_stats));
862         }
863
864         return 0;
865 }
866
867 static void
868 remove_xdp_program(struct pmd_internals *internals)
869 {
870         uint32_t curr_prog_id = 0;
871
872         if (bpf_get_link_xdp_id(internals->if_index, &curr_prog_id,
873                                 XDP_FLAGS_UPDATE_IF_NOEXIST)) {
874                 AF_XDP_LOG(ERR, "bpf_get_link_xdp_id failed\n");
875                 return;
876         }
877         bpf_set_link_xdp_fd(internals->if_index, -1,
878                         XDP_FLAGS_UPDATE_IF_NOEXIST);
879 }
880
881 static void
882 xdp_umem_destroy(struct xsk_umem_info *umem)
883 {
884 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
885         umem->mb_pool = NULL;
886 #else
887         rte_memzone_free(umem->mz);
888         umem->mz = NULL;
889
890         rte_ring_free(umem->buf_ring);
891         umem->buf_ring = NULL;
892 #endif
893
894         rte_free(umem);
895 }
896
897 static int
898 eth_dev_close(struct rte_eth_dev *dev)
899 {
900         struct pmd_internals *internals = dev->data->dev_private;
901         struct pkt_rx_queue *rxq;
902         int i;
903
904         if (rte_eal_process_type() != RTE_PROC_PRIMARY)
905                 return 0;
906
907         AF_XDP_LOG(INFO, "Closing AF_XDP ethdev on numa socket %u\n",
908                 rte_socket_id());
909
910         for (i = 0; i < internals->queue_cnt; i++) {
911                 rxq = &internals->rx_queues[i];
912                 if (rxq->umem == NULL)
913                         break;
914                 xsk_socket__delete(rxq->xsk);
915
916                 if (__atomic_sub_fetch(&rxq->umem->refcnt, 1, __ATOMIC_ACQUIRE)
917                                 == 0) {
918                         (void)xsk_umem__delete(rxq->umem->umem);
919                         xdp_umem_destroy(rxq->umem);
920                 }
921
922                 /* free pkt_tx_queue */
923                 rte_free(rxq->pair);
924                 rte_free(rxq);
925         }
926
927         /*
928          * MAC is not allocated dynamically, setting it to NULL would prevent
929          * from releasing it in rte_eth_dev_release_port.
930          */
931         dev->data->mac_addrs = NULL;
932
933         remove_xdp_program(internals);
934
935         if (internals->shared_umem) {
936                 struct internal_list *list;
937
938                 /* Remove ethdev from list used to track and share UMEMs */
939                 list = find_internal_resource(internals);
940                 if (list) {
941                         pthread_mutex_lock(&internal_list_lock);
942                         TAILQ_REMOVE(&internal_list, list, next);
943                         pthread_mutex_unlock(&internal_list_lock);
944                         rte_free(list);
945                 }
946         }
947
948         return 0;
949 }
950
951 static void
952 eth_queue_release(void *q __rte_unused)
953 {
954 }
955
956 static int
957 eth_link_update(struct rte_eth_dev *dev __rte_unused,
958                 int wait_to_complete __rte_unused)
959 {
960         return 0;
961 }
962
963 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
964 static inline uintptr_t get_base_addr(struct rte_mempool *mp, uint64_t *align)
965 {
966         struct rte_mempool_memhdr *memhdr;
967         uintptr_t memhdr_addr, aligned_addr;
968
969         memhdr = STAILQ_FIRST(&mp->mem_list);
970         memhdr_addr = (uintptr_t)memhdr->addr;
971         aligned_addr = memhdr_addr & ~(getpagesize() - 1);
972         *align = memhdr_addr - aligned_addr;
973
974         return aligned_addr;
975 }
976
977 static struct
978 xsk_umem_info *xdp_umem_configure(struct pmd_internals *internals,
979                                   struct pkt_rx_queue *rxq)
980 {
981         struct xsk_umem_info *umem = NULL;
982         int ret;
983         struct xsk_umem_config usr_config = {
984                 .fill_size = ETH_AF_XDP_DFLT_NUM_DESCS * 2,
985                 .comp_size = ETH_AF_XDP_DFLT_NUM_DESCS,
986                 .flags = XDP_UMEM_UNALIGNED_CHUNK_FLAG};
987         void *base_addr = NULL;
988         struct rte_mempool *mb_pool = rxq->mb_pool;
989         uint64_t umem_size, align = 0;
990
991         if (internals->shared_umem) {
992                 if (get_shared_umem(rxq, internals->if_name, &umem) < 0)
993                         return NULL;
994
995                 if (umem != NULL &&
996                         __atomic_load_n(&umem->refcnt, __ATOMIC_ACQUIRE) <
997                                         umem->max_xsks) {
998                         AF_XDP_LOG(INFO, "%s,qid%i sharing UMEM\n",
999                                         internals->if_name, rxq->xsk_queue_idx);
1000                         __atomic_fetch_add(&umem->refcnt, 1, __ATOMIC_ACQUIRE);
1001                 }
1002         }
1003
1004         if (umem == NULL) {
1005                 usr_config.frame_size =
1006                         rte_mempool_calc_obj_size(mb_pool->elt_size,
1007                                                   mb_pool->flags, NULL);
1008                 usr_config.frame_headroom = mb_pool->header_size +
1009                                                 sizeof(struct rte_mbuf) +
1010                                                 rte_pktmbuf_priv_size(mb_pool) +
1011                                                 RTE_PKTMBUF_HEADROOM;
1012
1013                 umem = rte_zmalloc_socket("umem", sizeof(*umem), 0,
1014                                           rte_socket_id());
1015                 if (umem == NULL) {
1016                         AF_XDP_LOG(ERR, "Failed to allocate umem info");
1017                         return NULL;
1018                 }
1019
1020                 umem->mb_pool = mb_pool;
1021                 base_addr = (void *)get_base_addr(mb_pool, &align);
1022                 umem_size = (uint64_t)mb_pool->populated_size *
1023                                 (uint64_t)usr_config.frame_size +
1024                                 align;
1025
1026                 ret = xsk_umem__create(&umem->umem, base_addr, umem_size,
1027                                 &rxq->fq, &rxq->cq, &usr_config);
1028                 if (ret) {
1029                         AF_XDP_LOG(ERR, "Failed to create umem");
1030                         goto err;
1031                 }
1032                 umem->buffer = base_addr;
1033
1034                 if (internals->shared_umem) {
1035                         umem->max_xsks = mb_pool->populated_size /
1036                                                 ETH_AF_XDP_NUM_BUFFERS;
1037                         AF_XDP_LOG(INFO, "Max xsks for UMEM %s: %u\n",
1038                                                 mb_pool->name, umem->max_xsks);
1039                 }
1040
1041                 __atomic_store_n(&umem->refcnt, 1, __ATOMIC_RELEASE);
1042         }
1043
1044 #else
1045 static struct
1046 xsk_umem_info *xdp_umem_configure(struct pmd_internals *internals,
1047                                   struct pkt_rx_queue *rxq)
1048 {
1049         struct xsk_umem_info *umem;
1050         const struct rte_memzone *mz;
1051         struct xsk_umem_config usr_config = {
1052                 .fill_size = ETH_AF_XDP_DFLT_NUM_DESCS,
1053                 .comp_size = ETH_AF_XDP_DFLT_NUM_DESCS,
1054                 .frame_size = ETH_AF_XDP_FRAME_SIZE,
1055                 .frame_headroom = 0 };
1056         char ring_name[RTE_RING_NAMESIZE];
1057         char mz_name[RTE_MEMZONE_NAMESIZE];
1058         int ret;
1059         uint64_t i;
1060
1061         umem = rte_zmalloc_socket("umem", sizeof(*umem), 0, rte_socket_id());
1062         if (umem == NULL) {
1063                 AF_XDP_LOG(ERR, "Failed to allocate umem info");
1064                 return NULL;
1065         }
1066
1067         snprintf(ring_name, sizeof(ring_name), "af_xdp_ring_%s_%u",
1068                        internals->if_name, rxq->xsk_queue_idx);
1069         umem->buf_ring = rte_ring_create(ring_name,
1070                                          ETH_AF_XDP_NUM_BUFFERS,
1071                                          rte_socket_id(),
1072                                          0x0);
1073         if (umem->buf_ring == NULL) {
1074                 AF_XDP_LOG(ERR, "Failed to create rte_ring\n");
1075                 goto err;
1076         }
1077
1078         for (i = 0; i < ETH_AF_XDP_NUM_BUFFERS; i++)
1079                 rte_ring_enqueue(umem->buf_ring,
1080                                  (void *)(i * ETH_AF_XDP_FRAME_SIZE));
1081
1082         snprintf(mz_name, sizeof(mz_name), "af_xdp_umem_%s_%u",
1083                        internals->if_name, rxq->xsk_queue_idx);
1084         mz = rte_memzone_reserve_aligned(mz_name,
1085                         ETH_AF_XDP_NUM_BUFFERS * ETH_AF_XDP_FRAME_SIZE,
1086                         rte_socket_id(), RTE_MEMZONE_IOVA_CONTIG,
1087                         getpagesize());
1088         if (mz == NULL) {
1089                 AF_XDP_LOG(ERR, "Failed to reserve memzone for af_xdp umem.\n");
1090                 goto err;
1091         }
1092
1093         ret = xsk_umem__create(&umem->umem, mz->addr,
1094                                ETH_AF_XDP_NUM_BUFFERS * ETH_AF_XDP_FRAME_SIZE,
1095                                &rxq->fq, &rxq->cq,
1096                                &usr_config);
1097
1098         if (ret) {
1099                 AF_XDP_LOG(ERR, "Failed to create umem");
1100                 goto err;
1101         }
1102         umem->mz = mz;
1103
1104 #endif
1105         return umem;
1106
1107 err:
1108         xdp_umem_destroy(umem);
1109         return NULL;
1110 }
1111
1112 static int
1113 load_custom_xdp_prog(const char *prog_path, int if_index)
1114 {
1115         int ret, prog_fd = -1;
1116         struct bpf_object *obj;
1117         struct bpf_map *map;
1118
1119         ret = bpf_prog_load(prog_path, BPF_PROG_TYPE_XDP, &obj, &prog_fd);
1120         if (ret) {
1121                 AF_XDP_LOG(ERR, "Failed to load program %s\n", prog_path);
1122                 return ret;
1123         }
1124
1125         /*
1126          * The loaded program must provision for a map of xsks, such that some
1127          * traffic can be redirected to userspace. When the xsk is created,
1128          * libbpf inserts it into the map.
1129          */
1130         map = bpf_object__find_map_by_name(obj, "xsks_map");
1131         if (!map) {
1132                 AF_XDP_LOG(ERR, "Failed to find xsks_map in %s\n", prog_path);
1133                 return -1;
1134         }
1135
1136         /* Link the program with the given network device */
1137         ret = bpf_set_link_xdp_fd(if_index, prog_fd,
1138                                         XDP_FLAGS_UPDATE_IF_NOEXIST);
1139         if (ret) {
1140                 AF_XDP_LOG(ERR, "Failed to set prog fd %d on interface\n",
1141                                 prog_fd);
1142                 return -1;
1143         }
1144
1145         AF_XDP_LOG(INFO, "Successfully loaded XDP program %s with fd %d\n",
1146                                 prog_path, prog_fd);
1147
1148         return 0;
1149 }
1150
1151 /* Detect support for busy polling through setsockopt(). */
1152 static int
1153 configure_preferred_busy_poll(struct pkt_rx_queue *rxq)
1154 {
1155         int sock_opt = 1;
1156         int fd = xsk_socket__fd(rxq->xsk);
1157         int ret = 0;
1158
1159         ret = setsockopt(fd, SOL_SOCKET, SO_PREFER_BUSY_POLL,
1160                         (void *)&sock_opt, sizeof(sock_opt));
1161         if (ret < 0) {
1162                 AF_XDP_LOG(DEBUG, "Failed to set SO_PREFER_BUSY_POLL\n");
1163                 goto err_prefer;
1164         }
1165
1166         sock_opt = ETH_AF_XDP_DFLT_BUSY_TIMEOUT;
1167         ret = setsockopt(fd, SOL_SOCKET, SO_BUSY_POLL, (void *)&sock_opt,
1168                         sizeof(sock_opt));
1169         if (ret < 0) {
1170                 AF_XDP_LOG(DEBUG, "Failed to set SO_BUSY_POLL\n");
1171                 goto err_timeout;
1172         }
1173
1174         sock_opt = rxq->busy_budget;
1175         ret = setsockopt(fd, SOL_SOCKET, SO_BUSY_POLL_BUDGET,
1176                         (void *)&sock_opt, sizeof(sock_opt));
1177         if (ret < 0) {
1178                 AF_XDP_LOG(DEBUG, "Failed to set SO_BUSY_POLL_BUDGET\n");
1179         } else {
1180                 AF_XDP_LOG(INFO, "Busy polling budget set to: %u\n",
1181                                         rxq->busy_budget);
1182                 return 0;
1183         }
1184
1185         /* setsockopt failure - attempt to restore xsk to default state and
1186          * proceed without busy polling support.
1187          */
1188         sock_opt = 0;
1189         ret = setsockopt(fd, SOL_SOCKET, SO_BUSY_POLL, (void *)&sock_opt,
1190                         sizeof(sock_opt));
1191         if (ret < 0) {
1192                 AF_XDP_LOG(ERR, "Failed to unset SO_BUSY_POLL\n");
1193                 return -1;
1194         }
1195
1196 err_timeout:
1197         sock_opt = 0;
1198         ret = setsockopt(fd, SOL_SOCKET, SO_PREFER_BUSY_POLL,
1199                         (void *)&sock_opt, sizeof(sock_opt));
1200         if (ret < 0) {
1201                 AF_XDP_LOG(ERR, "Failed to unset SO_PREFER_BUSY_POLL\n");
1202                 return -1;
1203         }
1204
1205 err_prefer:
1206         rxq->busy_budget = 0;
1207         return 0;
1208 }
1209
1210 static int
1211 xsk_configure(struct pmd_internals *internals, struct pkt_rx_queue *rxq,
1212               int ring_size)
1213 {
1214         struct xsk_socket_config cfg;
1215         struct pkt_tx_queue *txq = rxq->pair;
1216         int ret = 0;
1217         int reserve_size = ETH_AF_XDP_DFLT_NUM_DESCS;
1218         struct rte_mbuf *fq_bufs[reserve_size];
1219
1220         rxq->umem = xdp_umem_configure(internals, rxq);
1221         if (rxq->umem == NULL)
1222                 return -ENOMEM;
1223         txq->umem = rxq->umem;
1224
1225         cfg.rx_size = ring_size;
1226         cfg.tx_size = ring_size;
1227         cfg.libbpf_flags = 0;
1228         cfg.xdp_flags = XDP_FLAGS_UPDATE_IF_NOEXIST;
1229         cfg.bind_flags = 0;
1230
1231 #if defined(XDP_USE_NEED_WAKEUP)
1232         cfg.bind_flags |= XDP_USE_NEED_WAKEUP;
1233 #endif
1234
1235         if (strnlen(internals->prog_path, PATH_MAX) &&
1236                                 !internals->custom_prog_configured) {
1237                 ret = load_custom_xdp_prog(internals->prog_path,
1238                                            internals->if_index);
1239                 if (ret) {
1240                         AF_XDP_LOG(ERR, "Failed to load custom XDP program %s\n",
1241                                         internals->prog_path);
1242                         goto err;
1243                 }
1244                 internals->custom_prog_configured = 1;
1245         }
1246
1247         if (internals->shared_umem)
1248                 ret = create_shared_socket(&rxq->xsk, internals->if_name,
1249                                 rxq->xsk_queue_idx, rxq->umem->umem, &rxq->rx,
1250                                 &txq->tx, &rxq->fq, &rxq->cq, &cfg);
1251         else
1252                 ret = xsk_socket__create(&rxq->xsk, internals->if_name,
1253                                 rxq->xsk_queue_idx, rxq->umem->umem, &rxq->rx,
1254                                 &txq->tx, &cfg);
1255
1256         if (ret) {
1257                 AF_XDP_LOG(ERR, "Failed to create xsk socket.\n");
1258                 goto err;
1259         }
1260
1261 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
1262         ret = rte_pktmbuf_alloc_bulk(rxq->umem->mb_pool, fq_bufs, reserve_size);
1263         if (ret) {
1264                 AF_XDP_LOG(DEBUG, "Failed to get enough buffers for fq.\n");
1265                 goto err;
1266         }
1267 #endif
1268
1269         if (rxq->busy_budget) {
1270                 ret = configure_preferred_busy_poll(rxq);
1271                 if (ret) {
1272                         AF_XDP_LOG(ERR, "Failed configure busy polling.\n");
1273                         goto err;
1274                 }
1275         }
1276
1277         ret = reserve_fill_queue(rxq->umem, reserve_size, fq_bufs, &rxq->fq);
1278         if (ret) {
1279                 xsk_socket__delete(rxq->xsk);
1280                 AF_XDP_LOG(ERR, "Failed to reserve fill queue.\n");
1281                 goto err;
1282         }
1283
1284         return 0;
1285
1286 err:
1287         if (__atomic_sub_fetch(&rxq->umem->refcnt, 1, __ATOMIC_ACQUIRE) == 0)
1288                 xdp_umem_destroy(rxq->umem);
1289
1290         return ret;
1291 }
1292
1293 static int
1294 eth_rx_queue_setup(struct rte_eth_dev *dev,
1295                    uint16_t rx_queue_id,
1296                    uint16_t nb_rx_desc,
1297                    unsigned int socket_id __rte_unused,
1298                    const struct rte_eth_rxconf *rx_conf __rte_unused,
1299                    struct rte_mempool *mb_pool)
1300 {
1301         struct pmd_internals *internals = dev->data->dev_private;
1302         struct pkt_rx_queue *rxq;
1303         int ret;
1304
1305         rxq = &internals->rx_queues[rx_queue_id];
1306
1307         AF_XDP_LOG(INFO, "Set up rx queue, rx queue id: %d, xsk queue id: %d\n",
1308                    rx_queue_id, rxq->xsk_queue_idx);
1309
1310 #ifndef XDP_UMEM_UNALIGNED_CHUNK_FLAG
1311         uint32_t buf_size, data_size;
1312
1313         /* Now get the space available for data in the mbuf */
1314         buf_size = rte_pktmbuf_data_room_size(mb_pool) -
1315                 RTE_PKTMBUF_HEADROOM;
1316         data_size = ETH_AF_XDP_FRAME_SIZE;
1317
1318         if (data_size > buf_size) {
1319                 AF_XDP_LOG(ERR, "%s: %d bytes will not fit in mbuf (%d bytes)\n",
1320                         dev->device->name, data_size, buf_size);
1321                 ret = -ENOMEM;
1322                 goto err;
1323         }
1324 #endif
1325
1326         rxq->mb_pool = mb_pool;
1327
1328         if (xsk_configure(internals, rxq, nb_rx_desc)) {
1329                 AF_XDP_LOG(ERR, "Failed to configure xdp socket\n");
1330                 ret = -EINVAL;
1331                 goto err;
1332         }
1333
1334         if (!rxq->busy_budget)
1335                 AF_XDP_LOG(DEBUG, "Preferred busy polling not enabled\n");
1336
1337         rxq->fds[0].fd = xsk_socket__fd(rxq->xsk);
1338         rxq->fds[0].events = POLLIN;
1339
1340         dev->data->rx_queues[rx_queue_id] = rxq;
1341         return 0;
1342
1343 err:
1344         return ret;
1345 }
1346
1347 static int
1348 eth_tx_queue_setup(struct rte_eth_dev *dev,
1349                    uint16_t tx_queue_id,
1350                    uint16_t nb_tx_desc __rte_unused,
1351                    unsigned int socket_id __rte_unused,
1352                    const struct rte_eth_txconf *tx_conf __rte_unused)
1353 {
1354         struct pmd_internals *internals = dev->data->dev_private;
1355         struct pkt_tx_queue *txq;
1356
1357         txq = &internals->tx_queues[tx_queue_id];
1358
1359         dev->data->tx_queues[tx_queue_id] = txq;
1360         return 0;
1361 }
1362
1363 static int
1364 eth_dev_mtu_set(struct rte_eth_dev *dev, uint16_t mtu)
1365 {
1366         struct pmd_internals *internals = dev->data->dev_private;
1367         struct ifreq ifr = { .ifr_mtu = mtu };
1368         int ret;
1369         int s;
1370
1371         s = socket(PF_INET, SOCK_DGRAM, 0);
1372         if (s < 0)
1373                 return -EINVAL;
1374
1375         strlcpy(ifr.ifr_name, internals->if_name, IFNAMSIZ);
1376         ret = ioctl(s, SIOCSIFMTU, &ifr);
1377         close(s);
1378
1379         return (ret < 0) ? -errno : 0;
1380 }
1381
1382 static int
1383 eth_dev_change_flags(char *if_name, uint32_t flags, uint32_t mask)
1384 {
1385         struct ifreq ifr;
1386         int ret = 0;
1387         int s;
1388
1389         s = socket(PF_INET, SOCK_DGRAM, 0);
1390         if (s < 0)
1391                 return -errno;
1392
1393         strlcpy(ifr.ifr_name, if_name, IFNAMSIZ);
1394         if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0) {
1395                 ret = -errno;
1396                 goto out;
1397         }
1398         ifr.ifr_flags &= mask;
1399         ifr.ifr_flags |= flags;
1400         if (ioctl(s, SIOCSIFFLAGS, &ifr) < 0) {
1401                 ret = -errno;
1402                 goto out;
1403         }
1404 out:
1405         close(s);
1406         return ret;
1407 }
1408
1409 static int
1410 eth_dev_promiscuous_enable(struct rte_eth_dev *dev)
1411 {
1412         struct pmd_internals *internals = dev->data->dev_private;
1413
1414         return eth_dev_change_flags(internals->if_name, IFF_PROMISC, ~0);
1415 }
1416
1417 static int
1418 eth_dev_promiscuous_disable(struct rte_eth_dev *dev)
1419 {
1420         struct pmd_internals *internals = dev->data->dev_private;
1421
1422         return eth_dev_change_flags(internals->if_name, 0, ~IFF_PROMISC);
1423 }
1424
1425 static const struct eth_dev_ops ops = {
1426         .dev_start = eth_dev_start,
1427         .dev_stop = eth_dev_stop,
1428         .dev_close = eth_dev_close,
1429         .dev_configure = eth_dev_configure,
1430         .dev_infos_get = eth_dev_info,
1431         .mtu_set = eth_dev_mtu_set,
1432         .promiscuous_enable = eth_dev_promiscuous_enable,
1433         .promiscuous_disable = eth_dev_promiscuous_disable,
1434         .rx_queue_setup = eth_rx_queue_setup,
1435         .tx_queue_setup = eth_tx_queue_setup,
1436         .rx_queue_release = eth_queue_release,
1437         .tx_queue_release = eth_queue_release,
1438         .link_update = eth_link_update,
1439         .stats_get = eth_stats_get,
1440         .stats_reset = eth_stats_reset,
1441 };
1442
1443 /** parse busy_budget argument */
1444 static int
1445 parse_budget_arg(const char *key __rte_unused,
1446                   const char *value, void *extra_args)
1447 {
1448         int *i = (int *)extra_args;
1449         char *end;
1450
1451         *i = strtol(value, &end, 10);
1452         if (*i < 0 || *i > UINT16_MAX) {
1453                 AF_XDP_LOG(ERR, "Invalid busy_budget %i, must be >= 0 and <= %u\n",
1454                                 *i, UINT16_MAX);
1455                 return -EINVAL;
1456         }
1457
1458         return 0;
1459 }
1460
1461 /** parse integer from integer argument */
1462 static int
1463 parse_integer_arg(const char *key __rte_unused,
1464                   const char *value, void *extra_args)
1465 {
1466         int *i = (int *)extra_args;
1467         char *end;
1468
1469         *i = strtol(value, &end, 10);
1470         if (*i < 0) {
1471                 AF_XDP_LOG(ERR, "Argument has to be positive.\n");
1472                 return -EINVAL;
1473         }
1474
1475         return 0;
1476 }
1477
1478 /** parse name argument */
1479 static int
1480 parse_name_arg(const char *key __rte_unused,
1481                const char *value, void *extra_args)
1482 {
1483         char *name = extra_args;
1484
1485         if (strnlen(value, IFNAMSIZ) > IFNAMSIZ - 1) {
1486                 AF_XDP_LOG(ERR, "Invalid name %s, should be less than %u bytes.\n",
1487                            value, IFNAMSIZ);
1488                 return -EINVAL;
1489         }
1490
1491         strlcpy(name, value, IFNAMSIZ);
1492
1493         return 0;
1494 }
1495
1496 /** parse xdp prog argument */
1497 static int
1498 parse_prog_arg(const char *key __rte_unused,
1499                const char *value, void *extra_args)
1500 {
1501         char *path = extra_args;
1502
1503         if (strnlen(value, PATH_MAX) == PATH_MAX) {
1504                 AF_XDP_LOG(ERR, "Invalid path %s, should be less than %u bytes.\n",
1505                            value, PATH_MAX);
1506                 return -EINVAL;
1507         }
1508
1509         if (access(value, F_OK) != 0) {
1510                 AF_XDP_LOG(ERR, "Error accessing %s: %s\n",
1511                            value, strerror(errno));
1512                 return -EINVAL;
1513         }
1514
1515         strlcpy(path, value, PATH_MAX);
1516
1517         return 0;
1518 }
1519
1520 static int
1521 xdp_get_channels_info(const char *if_name, int *max_queues,
1522                                 int *combined_queues)
1523 {
1524         struct ethtool_channels channels;
1525         struct ifreq ifr;
1526         int fd, ret;
1527
1528         fd = socket(AF_INET, SOCK_DGRAM, 0);
1529         if (fd < 0)
1530                 return -1;
1531
1532         channels.cmd = ETHTOOL_GCHANNELS;
1533         ifr.ifr_data = (void *)&channels;
1534         strlcpy(ifr.ifr_name, if_name, IFNAMSIZ);
1535         ret = ioctl(fd, SIOCETHTOOL, &ifr);
1536         if (ret) {
1537                 if (errno == EOPNOTSUPP) {
1538                         ret = 0;
1539                 } else {
1540                         ret = -errno;
1541                         goto out;
1542                 }
1543         }
1544
1545         if (channels.max_combined == 0 || errno == EOPNOTSUPP) {
1546                 /* If the device says it has no channels, then all traffic
1547                  * is sent to a single stream, so max queues = 1.
1548                  */
1549                 *max_queues = 1;
1550                 *combined_queues = 1;
1551         } else {
1552                 *max_queues = channels.max_combined;
1553                 *combined_queues = channels.combined_count;
1554         }
1555
1556  out:
1557         close(fd);
1558         return ret;
1559 }
1560
1561 static int
1562 parse_parameters(struct rte_kvargs *kvlist, char *if_name, int *start_queue,
1563                         int *queue_cnt, int *shared_umem, char *prog_path,
1564                         int *busy_budget)
1565 {
1566         int ret;
1567
1568         ret = rte_kvargs_process(kvlist, ETH_AF_XDP_IFACE_ARG,
1569                                  &parse_name_arg, if_name);
1570         if (ret < 0)
1571                 goto free_kvlist;
1572
1573         ret = rte_kvargs_process(kvlist, ETH_AF_XDP_START_QUEUE_ARG,
1574                                  &parse_integer_arg, start_queue);
1575         if (ret < 0)
1576                 goto free_kvlist;
1577
1578         ret = rte_kvargs_process(kvlist, ETH_AF_XDP_QUEUE_COUNT_ARG,
1579                                  &parse_integer_arg, queue_cnt);
1580         if (ret < 0 || *queue_cnt <= 0) {
1581                 ret = -EINVAL;
1582                 goto free_kvlist;
1583         }
1584
1585         ret = rte_kvargs_process(kvlist, ETH_AF_XDP_SHARED_UMEM_ARG,
1586                                 &parse_integer_arg, shared_umem);
1587         if (ret < 0)
1588                 goto free_kvlist;
1589
1590         ret = rte_kvargs_process(kvlist, ETH_AF_XDP_PROG_ARG,
1591                                  &parse_prog_arg, prog_path);
1592         if (ret < 0)
1593                 goto free_kvlist;
1594
1595         ret = rte_kvargs_process(kvlist, ETH_AF_XDP_BUDGET_ARG,
1596                                 &parse_budget_arg, busy_budget);
1597         if (ret < 0)
1598                 goto free_kvlist;
1599
1600 free_kvlist:
1601         rte_kvargs_free(kvlist);
1602         return ret;
1603 }
1604
1605 static int
1606 get_iface_info(const char *if_name,
1607                struct rte_ether_addr *eth_addr,
1608                int *if_index)
1609 {
1610         struct ifreq ifr;
1611         int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
1612
1613         if (sock < 0)
1614                 return -1;
1615
1616         strlcpy(ifr.ifr_name, if_name, IFNAMSIZ);
1617         if (ioctl(sock, SIOCGIFINDEX, &ifr))
1618                 goto error;
1619
1620         *if_index = ifr.ifr_ifindex;
1621
1622         if (ioctl(sock, SIOCGIFHWADDR, &ifr))
1623                 goto error;
1624
1625         rte_memcpy(eth_addr, ifr.ifr_hwaddr.sa_data, RTE_ETHER_ADDR_LEN);
1626
1627         close(sock);
1628         return 0;
1629
1630 error:
1631         close(sock);
1632         return -1;
1633 }
1634
1635 static struct rte_eth_dev *
1636 init_internals(struct rte_vdev_device *dev, const char *if_name,
1637                 int start_queue_idx, int queue_cnt, int shared_umem,
1638                 const char *prog_path, int busy_budget)
1639 {
1640         const char *name = rte_vdev_device_name(dev);
1641         const unsigned int numa_node = dev->device.numa_node;
1642         struct pmd_internals *internals;
1643         struct rte_eth_dev *eth_dev;
1644         int ret;
1645         int i;
1646
1647         internals = rte_zmalloc_socket(name, sizeof(*internals), 0, numa_node);
1648         if (internals == NULL)
1649                 return NULL;
1650
1651         internals->start_queue_idx = start_queue_idx;
1652         internals->queue_cnt = queue_cnt;
1653         strlcpy(internals->if_name, if_name, IFNAMSIZ);
1654         strlcpy(internals->prog_path, prog_path, PATH_MAX);
1655         internals->custom_prog_configured = 0;
1656
1657 #ifndef ETH_AF_XDP_SHARED_UMEM
1658         if (shared_umem) {
1659                 AF_XDP_LOG(ERR, "Shared UMEM feature not available. "
1660                                 "Check kernel and libbpf version\n");
1661                 goto err_free_internals;
1662         }
1663 #endif
1664         internals->shared_umem = shared_umem;
1665
1666         if (xdp_get_channels_info(if_name, &internals->max_queue_cnt,
1667                                   &internals->combined_queue_cnt)) {
1668                 AF_XDP_LOG(ERR, "Failed to get channel info of interface: %s\n",
1669                                 if_name);
1670                 goto err_free_internals;
1671         }
1672
1673         if (queue_cnt > internals->combined_queue_cnt) {
1674                 AF_XDP_LOG(ERR, "Specified queue count %d is larger than combined queue count %d.\n",
1675                                 queue_cnt, internals->combined_queue_cnt);
1676                 goto err_free_internals;
1677         }
1678
1679         internals->rx_queues = rte_zmalloc_socket(NULL,
1680                                         sizeof(struct pkt_rx_queue) * queue_cnt,
1681                                         0, numa_node);
1682         if (internals->rx_queues == NULL) {
1683                 AF_XDP_LOG(ERR, "Failed to allocate memory for rx queues.\n");
1684                 goto err_free_internals;
1685         }
1686
1687         internals->tx_queues = rte_zmalloc_socket(NULL,
1688                                         sizeof(struct pkt_tx_queue) * queue_cnt,
1689                                         0, numa_node);
1690         if (internals->tx_queues == NULL) {
1691                 AF_XDP_LOG(ERR, "Failed to allocate memory for tx queues.\n");
1692                 goto err_free_rx;
1693         }
1694         for (i = 0; i < queue_cnt; i++) {
1695                 internals->tx_queues[i].pair = &internals->rx_queues[i];
1696                 internals->rx_queues[i].pair = &internals->tx_queues[i];
1697                 internals->rx_queues[i].xsk_queue_idx = start_queue_idx + i;
1698                 internals->tx_queues[i].xsk_queue_idx = start_queue_idx + i;
1699                 internals->rx_queues[i].busy_budget = busy_budget;
1700         }
1701
1702         ret = get_iface_info(if_name, &internals->eth_addr,
1703                              &internals->if_index);
1704         if (ret)
1705                 goto err_free_tx;
1706
1707         eth_dev = rte_eth_vdev_allocate(dev, 0);
1708         if (eth_dev == NULL)
1709                 goto err_free_tx;
1710
1711         eth_dev->data->dev_private = internals;
1712         eth_dev->data->dev_link = pmd_link;
1713         eth_dev->data->mac_addrs = &internals->eth_addr;
1714         eth_dev->data->dev_flags |= RTE_ETH_DEV_AUTOFILL_QUEUE_XSTATS;
1715         eth_dev->dev_ops = &ops;
1716         eth_dev->rx_pkt_burst = eth_af_xdp_rx;
1717         eth_dev->tx_pkt_burst = eth_af_xdp_tx;
1718
1719 #if defined(XDP_UMEM_UNALIGNED_CHUNK_FLAG)
1720         AF_XDP_LOG(INFO, "Zero copy between umem and mbuf enabled.\n");
1721 #endif
1722
1723         return eth_dev;
1724
1725 err_free_tx:
1726         rte_free(internals->tx_queues);
1727 err_free_rx:
1728         rte_free(internals->rx_queues);
1729 err_free_internals:
1730         rte_free(internals);
1731         return NULL;
1732 }
1733
1734 static int
1735 rte_pmd_af_xdp_probe(struct rte_vdev_device *dev)
1736 {
1737         struct rte_kvargs *kvlist;
1738         char if_name[IFNAMSIZ] = {'\0'};
1739         int xsk_start_queue_idx = ETH_AF_XDP_DFLT_START_QUEUE_IDX;
1740         int xsk_queue_cnt = ETH_AF_XDP_DFLT_QUEUE_COUNT;
1741         int shared_umem = 0;
1742         char prog_path[PATH_MAX] = {'\0'};
1743         int busy_budget = -1;
1744         struct rte_eth_dev *eth_dev = NULL;
1745         const char *name;
1746
1747         AF_XDP_LOG(INFO, "Initializing pmd_af_xdp for %s\n",
1748                 rte_vdev_device_name(dev));
1749
1750         name = rte_vdev_device_name(dev);
1751         if (rte_eal_process_type() == RTE_PROC_SECONDARY &&
1752                 strlen(rte_vdev_device_args(dev)) == 0) {
1753                 eth_dev = rte_eth_dev_attach_secondary(name);
1754                 if (eth_dev == NULL) {
1755                         AF_XDP_LOG(ERR, "Failed to probe %s\n", name);
1756                         return -EINVAL;
1757                 }
1758                 eth_dev->dev_ops = &ops;
1759                 rte_eth_dev_probing_finish(eth_dev);
1760                 return 0;
1761         }
1762
1763         kvlist = rte_kvargs_parse(rte_vdev_device_args(dev), valid_arguments);
1764         if (kvlist == NULL) {
1765                 AF_XDP_LOG(ERR, "Invalid kvargs key\n");
1766                 return -EINVAL;
1767         }
1768
1769         if (dev->device.numa_node == SOCKET_ID_ANY)
1770                 dev->device.numa_node = rte_socket_id();
1771
1772         if (parse_parameters(kvlist, if_name, &xsk_start_queue_idx,
1773                              &xsk_queue_cnt, &shared_umem, prog_path,
1774                              &busy_budget) < 0) {
1775                 AF_XDP_LOG(ERR, "Invalid kvargs value\n");
1776                 return -EINVAL;
1777         }
1778
1779         if (strlen(if_name) == 0) {
1780                 AF_XDP_LOG(ERR, "Network interface must be specified\n");
1781                 return -EINVAL;
1782         }
1783
1784         busy_budget = busy_budget == -1 ? ETH_AF_XDP_DFLT_BUSY_BUDGET :
1785                                         busy_budget;
1786
1787         eth_dev = init_internals(dev, if_name, xsk_start_queue_idx,
1788                                         xsk_queue_cnt, shared_umem, prog_path,
1789                                         busy_budget);
1790         if (eth_dev == NULL) {
1791                 AF_XDP_LOG(ERR, "Failed to init internals\n");
1792                 return -1;
1793         }
1794
1795         rte_eth_dev_probing_finish(eth_dev);
1796
1797         return 0;
1798 }
1799
1800 static int
1801 rte_pmd_af_xdp_remove(struct rte_vdev_device *dev)
1802 {
1803         struct rte_eth_dev *eth_dev = NULL;
1804
1805         AF_XDP_LOG(INFO, "Removing AF_XDP ethdev on numa socket %u\n",
1806                 rte_socket_id());
1807
1808         if (dev == NULL)
1809                 return -1;
1810
1811         /* find the ethdev entry */
1812         eth_dev = rte_eth_dev_allocated(rte_vdev_device_name(dev));
1813         if (eth_dev == NULL)
1814                 return 0;
1815
1816         eth_dev_close(eth_dev);
1817         rte_eth_dev_release_port(eth_dev);
1818
1819
1820         return 0;
1821 }
1822
1823 static struct rte_vdev_driver pmd_af_xdp_drv = {
1824         .probe = rte_pmd_af_xdp_probe,
1825         .remove = rte_pmd_af_xdp_remove,
1826 };
1827
1828 RTE_PMD_REGISTER_VDEV(net_af_xdp, pmd_af_xdp_drv);
1829 RTE_PMD_REGISTER_PARAM_STRING(net_af_xdp,
1830                               "iface=<string> "
1831                               "start_queue=<int> "
1832                               "queue_count=<int> "
1833                               "shared_umem=<int> "
1834                               "xdp_prog=<string> "
1835                               "busy_budget=<int>");