New upstream version 18.08
[deb_dpdk.git] / examples / exception_path / main.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdint.h>
8 #include <inttypes.h>
9 #include <string.h>
10 #include <sys/queue.h>
11 #include <stdarg.h>
12 #include <errno.h>
13 #include <getopt.h>
14
15 #include <netinet/in.h>
16 #include <net/if.h>
17 #ifdef RTE_EXEC_ENV_LINUXAPP
18 #include <linux/if_tun.h>
19 #endif
20 #include <fcntl.h>
21 #include <sys/ioctl.h>
22 #include <unistd.h>
23 #include <signal.h>
24
25 #include <rte_common.h>
26 #include <rte_log.h>
27 #include <rte_memory.h>
28 #include <rte_memcpy.h>
29 #include <rte_eal.h>
30 #include <rte_per_lcore.h>
31 #include <rte_launch.h>
32 #include <rte_atomic.h>
33 #include <rte_lcore.h>
34 #include <rte_branch_prediction.h>
35 #include <rte_interrupts.h>
36 #include <rte_debug.h>
37 #include <rte_ether.h>
38 #include <rte_ethdev.h>
39 #include <rte_mempool.h>
40 #include <rte_mbuf.h>
41 #include <rte_string_fns.h>
42 #include <rte_cycles.h>
43
44 #ifndef APP_MAX_LCORE
45 #if (RTE_MAX_LCORE > 64)
46 #define APP_MAX_LCORE 64
47 #else
48 #define APP_MAX_LCORE RTE_MAX_LCORE
49 #endif
50 #endif
51
52 /* Macros for printing using RTE_LOG */
53 #define RTE_LOGTYPE_APP RTE_LOGTYPE_USER1
54 #define FATAL_ERROR(fmt, args...)       rte_exit(EXIT_FAILURE, fmt "\n", ##args)
55 #define PRINT_INFO(fmt, args...)        RTE_LOG(INFO, APP, fmt "\n", ##args)
56
57 /* Max ports than can be used (each port is associated with two lcores) */
58 #define MAX_PORTS               (APP_MAX_LCORE / 2)
59
60 /* Max size of a single packet */
61 #define MAX_PACKET_SZ (2048)
62
63 /* Size of the data buffer in each mbuf */
64 #define MBUF_DATA_SZ (MAX_PACKET_SZ + RTE_PKTMBUF_HEADROOM)
65
66 /* Number of mbufs in mempool that is created */
67 #define NB_MBUF                 8192
68
69 /* How many packets to attempt to read from NIC in one go */
70 #define PKT_BURST_SZ            32
71
72 /* How many objects (mbufs) to keep in per-lcore mempool cache */
73 #define MEMPOOL_CACHE_SZ        PKT_BURST_SZ
74
75 /* Number of RX ring descriptors */
76 #define NB_RXD                  1024
77
78 /* Number of TX ring descriptors */
79 #define NB_TXD                  1024
80
81 /*
82  * RX and TX Prefetch, Host, and Write-back threshold values should be
83  * carefully set for optimal performance. Consult the network
84  * controller's datasheet and supporting DPDK documentation for guidance
85  * on how these parameters should be set.
86  */
87
88 /* Options for configuring ethernet port */
89 static struct rte_eth_conf port_conf = {
90         .rxmode = {
91                 .offloads = DEV_RX_OFFLOAD_CRC_STRIP,
92         },
93         .txmode = {
94                 .mq_mode = ETH_MQ_TX_NONE,
95         },
96 };
97
98 /* Mempool for mbufs */
99 static struct rte_mempool * pktmbuf_pool = NULL;
100
101 /* Mask of enabled ports */
102 static uint32_t ports_mask = 0;
103
104 /* Mask of cores that read from NIC and write to tap */
105 static uint64_t input_cores_mask = 0;
106
107 /* Mask of cores that read from tap and write to NIC */
108 static uint64_t output_cores_mask = 0;
109
110 /* Array storing port_id that is associated with each lcore */
111 static uint16_t port_ids[APP_MAX_LCORE];
112
113 /* Structure type for recording lcore-specific stats */
114 struct stats {
115         uint64_t rx;
116         uint64_t tx;
117         uint64_t dropped;
118 } __rte_cache_aligned;
119
120 /* Array of lcore-specific stats */
121 static struct stats lcore_stats[APP_MAX_LCORE];
122
123 /* Print out statistics on packets handled */
124 static void
125 print_stats(void)
126 {
127         unsigned i;
128
129         printf("\n**Exception-Path example application statistics**\n"
130                "=======  ======  ============  ============  ===============\n"
131                " Lcore    Port            RX            TX    Dropped on TX\n"
132                "-------  ------  ------------  ------------  ---------------\n");
133         RTE_LCORE_FOREACH(i) {
134                 /* limit ourselves to application supported cores only */
135                 if (i >= APP_MAX_LCORE)
136                         break;
137                 printf("%6u %7u %13"PRIu64" %13"PRIu64" %16"PRIu64"\n",
138                        i, (unsigned)port_ids[i],
139                        lcore_stats[i].rx, lcore_stats[i].tx,
140                        lcore_stats[i].dropped);
141         }
142         printf("=======  ======  ============  ============  ===============\n");
143 }
144
145 /* Custom handling of signals to handle stats */
146 static void
147 signal_handler(int signum)
148 {
149         /* When we receive a USR1 signal, print stats */
150         if (signum == SIGUSR1) {
151                 print_stats();
152         }
153
154         /* When we receive a USR2 signal, reset stats */
155         if (signum == SIGUSR2) {
156                 memset(&lcore_stats, 0, sizeof(lcore_stats));
157                 printf("\n**Statistics have been reset**\n");
158                 return;
159         }
160 }
161
162 #ifdef RTE_EXEC_ENV_LINUXAPP
163 /*
164  * Create a tap network interface, or use existing one with same name.
165  * If name[0]='\0' then a name is automatically assigned and returned in name.
166  */
167 static int tap_create(char *name)
168 {
169         struct ifreq ifr;
170         int fd, ret;
171
172         fd = open("/dev/net/tun", O_RDWR);
173         if (fd < 0)
174                 return fd;
175
176         memset(&ifr, 0, sizeof(ifr));
177
178         /* TAP device without packet information */
179         ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
180
181         if (name && *name)
182                 snprintf(ifr.ifr_name, IFNAMSIZ, "%s", name);
183
184         ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
185         if (ret < 0) {
186                 close(fd);
187                 return ret;
188         }
189
190         if (name)
191                 snprintf(name, IFNAMSIZ, "%s", ifr.ifr_name);
192
193         return fd;
194 }
195 #else
196 /*
197  * Find a free tap network interface, or create a new one.
198  * The name is automatically assigned and returned in name.
199  */
200 static int tap_create(char *name)
201 {
202         int i, fd = -1;
203         char devname[PATH_MAX];
204
205         for (i = 0; i < 255; i++) {
206                 snprintf(devname, sizeof(devname), "/dev/tap%d", i);
207                 fd = open(devname, O_RDWR);
208                 if (fd >= 0 || errno != EBUSY)
209                         break;
210         }
211
212         if (name)
213                 snprintf(name, IFNAMSIZ, "tap%d", i);
214
215         return fd;
216 }
217 #endif
218
219 /* Main processing loop */
220 static int
221 main_loop(__attribute__((unused)) void *arg)
222 {
223         const unsigned lcore_id = rte_lcore_id();
224         char tap_name[IFNAMSIZ];
225         int tap_fd;
226
227         if ((1ULL << lcore_id) & input_cores_mask) {
228                 /* Create new tap interface */
229                 snprintf(tap_name, IFNAMSIZ, "tap_dpdk_%.2u", lcore_id);
230                 tap_fd = tap_create(tap_name);
231                 if (tap_fd < 0)
232                         FATAL_ERROR("Could not create tap interface \"%s\" (%d)",
233                                         tap_name, tap_fd);
234
235                 PRINT_INFO("Lcore %u is reading from port %u and writing to %s",
236                            lcore_id, (unsigned)port_ids[lcore_id], tap_name);
237                 fflush(stdout);
238                 /* Loop forever reading from NIC and writing to tap */
239                 for (;;) {
240                         struct rte_mbuf *pkts_burst[PKT_BURST_SZ];
241                         unsigned i;
242                         const unsigned nb_rx =
243                                         rte_eth_rx_burst(port_ids[lcore_id], 0,
244                                             pkts_burst, PKT_BURST_SZ);
245                         lcore_stats[lcore_id].rx += nb_rx;
246                         for (i = 0; likely(i < nb_rx); i++) {
247                                 struct rte_mbuf *m = pkts_burst[i];
248                                 /* Ignore return val from write() */
249                                 int ret = write(tap_fd,
250                                                 rte_pktmbuf_mtod(m, void*),
251                                                 rte_pktmbuf_data_len(m));
252                                 rte_pktmbuf_free(m);
253                                 if (unlikely(ret < 0))
254                                         lcore_stats[lcore_id].dropped++;
255                                 else
256                                         lcore_stats[lcore_id].tx++;
257                         }
258                 }
259         }
260         else if ((1ULL << lcore_id) & output_cores_mask) {
261                 /* Create new tap interface */
262                 snprintf(tap_name, IFNAMSIZ, "tap_dpdk_%.2u", lcore_id);
263                 tap_fd = tap_create(tap_name);
264                 if (tap_fd < 0)
265                         FATAL_ERROR("Could not create tap interface \"%s\" (%d)",
266                                         tap_name, tap_fd);
267
268                 PRINT_INFO("Lcore %u is reading from %s and writing to port %u",
269                            lcore_id, tap_name, (unsigned)port_ids[lcore_id]);
270                 fflush(stdout);
271                 /* Loop forever reading from tap and writing to NIC */
272                 for (;;) {
273                         int ret;
274                         struct rte_mbuf *m = rte_pktmbuf_alloc(pktmbuf_pool);
275                         if (m == NULL)
276                                 continue;
277
278                         ret = read(tap_fd, rte_pktmbuf_mtod(m, void *),
279                                 MAX_PACKET_SZ);
280                         lcore_stats[lcore_id].rx++;
281                         if (unlikely(ret < 0)) {
282                                 FATAL_ERROR("Reading from %s interface failed",
283                                             tap_name);
284                         }
285                         m->nb_segs = 1;
286                         m->next = NULL;
287                         m->pkt_len = (uint16_t)ret;
288                         m->data_len = (uint16_t)ret;
289                         ret = rte_eth_tx_burst(port_ids[lcore_id], 0, &m, 1);
290                         if (unlikely(ret < 1)) {
291                                 rte_pktmbuf_free(m);
292                                 lcore_stats[lcore_id].dropped++;
293                         }
294                         else {
295                                 lcore_stats[lcore_id].tx++;
296                         }
297                 }
298         }
299         else {
300                 PRINT_INFO("Lcore %u has nothing to do", lcore_id);
301                 return 0;
302         }
303         /*
304          * Tap file is closed automatically when program exits. Putting close()
305          * here will cause the compiler to give an error about unreachable code.
306          */
307 }
308
309 /* Display usage instructions */
310 static void
311 print_usage(const char *prgname)
312 {
313         PRINT_INFO("\nUsage: %s [EAL options] -- -p PORTMASK -i IN_CORES -o OUT_CORES\n"
314                    "    -p PORTMASK: hex bitmask of ports to use\n"
315                    "    -i IN_CORES: hex bitmask of cores which read from NIC\n"
316                    "    -o OUT_CORES: hex bitmask of cores which write to NIC",
317                    prgname);
318 }
319
320 /* Convert string to unsigned number. 0 is returned if error occurs */
321 static uint64_t
322 parse_unsigned(const char *portmask)
323 {
324         char *end = NULL;
325         uint64_t num;
326
327         num = strtoull(portmask, &end, 16);
328         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
329                 return 0;
330
331         return (uint64_t)num;
332 }
333
334 /* Record affinities between ports and lcores in global port_ids[] array */
335 static void
336 setup_port_lcore_affinities(void)
337 {
338         unsigned long i;
339         uint16_t tx_port = 0;
340         uint16_t rx_port = 0;
341
342         /* Setup port_ids[] array, and check masks were ok */
343         for (i = 0; i < APP_MAX_LCORE; i++) {
344                 if (!rte_lcore_is_enabled(i))
345                         continue;
346                 if (input_cores_mask & (1ULL << i)) {
347                         /* Skip ports that are not enabled */
348                         while ((ports_mask & (1 << rx_port)) == 0) {
349                                 rx_port++;
350                                 if (rx_port > (sizeof(ports_mask) * 8))
351                                         goto fail; /* not enough ports */
352                         }
353
354                         port_ids[i] = rx_port++;
355                 } else if (output_cores_mask & (1ULL << (i & 0x3f))) {
356                         /* Skip ports that are not enabled */
357                         while ((ports_mask & (1 << tx_port)) == 0) {
358                                 tx_port++;
359                                 if (tx_port > (sizeof(ports_mask) * 8))
360                                         goto fail; /* not enough ports */
361                         }
362
363                         port_ids[i] = tx_port++;
364                 }
365         }
366
367         if (rx_port != tx_port)
368                 goto fail; /* uneven number of cores in masks */
369
370         if (ports_mask & (~((1 << rx_port) - 1)))
371                 goto fail; /* unused ports */
372
373         return;
374 fail:
375         FATAL_ERROR("Invalid core/port masks specified on command line");
376 }
377
378 /* Parse the arguments given in the command line of the application */
379 static void
380 parse_args(int argc, char **argv)
381 {
382         int opt;
383         const char *prgname = argv[0];
384
385         /* Disable printing messages within getopt() */
386         opterr = 0;
387
388         /* Parse command line */
389         while ((opt = getopt(argc, argv, "i:o:p:")) != EOF) {
390                 switch (opt) {
391                 case 'i':
392                         input_cores_mask = parse_unsigned(optarg);
393                         break;
394                 case 'o':
395                         output_cores_mask = parse_unsigned(optarg);
396                         break;
397                 case 'p':
398                         ports_mask = parse_unsigned(optarg);
399                         break;
400                 default:
401                         print_usage(prgname);
402                         FATAL_ERROR("Invalid option specified");
403                 }
404         }
405
406         /* Check that options were parsed ok */
407         if (input_cores_mask == 0) {
408                 print_usage(prgname);
409                 FATAL_ERROR("IN_CORES not specified correctly");
410         }
411         if (output_cores_mask == 0) {
412                 print_usage(prgname);
413                 FATAL_ERROR("OUT_CORES not specified correctly");
414         }
415         if (ports_mask == 0) {
416                 print_usage(prgname);
417                 FATAL_ERROR("PORTMASK not specified correctly");
418         }
419
420         setup_port_lcore_affinities();
421 }
422
423 /* Initialise a single port on an Ethernet device */
424 static void
425 init_port(uint16_t port)
426 {
427         int ret;
428         uint16_t nb_rxd = NB_RXD;
429         uint16_t nb_txd = NB_TXD;
430         struct rte_eth_dev_info dev_info;
431         struct rte_eth_rxconf rxq_conf;
432         struct rte_eth_txconf txq_conf;
433         struct rte_eth_conf local_port_conf = port_conf;
434
435         /* Initialise device and RX/TX queues */
436         PRINT_INFO("Initialising port %u ...", port);
437         fflush(stdout);
438         rte_eth_dev_info_get(port, &dev_info);
439         if (dev_info.tx_offload_capa & DEV_TX_OFFLOAD_MBUF_FAST_FREE)
440                 local_port_conf.txmode.offloads |=
441                         DEV_TX_OFFLOAD_MBUF_FAST_FREE;
442         ret = rte_eth_dev_configure(port, 1, 1, &local_port_conf);
443         if (ret < 0)
444                 FATAL_ERROR("Could not configure port%u (%d)", port, ret);
445
446         ret = rte_eth_dev_adjust_nb_rx_tx_desc(port, &nb_rxd, &nb_txd);
447         if (ret < 0)
448                 FATAL_ERROR("Could not adjust number of descriptors for port%u (%d)",
449                             port, ret);
450
451         rxq_conf = dev_info.default_rxconf;
452         rxq_conf.offloads = local_port_conf.rxmode.offloads;
453         ret = rte_eth_rx_queue_setup(port, 0, nb_rxd,
454                                 rte_eth_dev_socket_id(port),
455                                 &rxq_conf,
456                                 pktmbuf_pool);
457         if (ret < 0)
458                 FATAL_ERROR("Could not setup up RX queue for port%u (%d)",
459                                 port, ret);
460
461         txq_conf = dev_info.default_txconf;
462         txq_conf.offloads = local_port_conf.txmode.offloads;
463         ret = rte_eth_tx_queue_setup(port, 0, nb_txd,
464                                 rte_eth_dev_socket_id(port),
465                                 &txq_conf);
466         if (ret < 0)
467                 FATAL_ERROR("Could not setup up TX queue for port%u (%d)",
468                                 port, ret);
469
470         ret = rte_eth_dev_start(port);
471         if (ret < 0)
472                 FATAL_ERROR("Could not start port%u (%d)", port, ret);
473
474         rte_eth_promiscuous_enable(port);
475 }
476
477 /* Check the link status of all ports in up to 9s, and print them finally */
478 static void
479 check_all_ports_link_status(uint32_t port_mask)
480 {
481 #define CHECK_INTERVAL 100 /* 100ms */
482 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
483         uint16_t portid;
484         uint8_t count, all_ports_up, print_flag = 0;
485         struct rte_eth_link link;
486
487         printf("\nChecking link status");
488         fflush(stdout);
489         for (count = 0; count <= MAX_CHECK_TIME; count++) {
490                 all_ports_up = 1;
491                 RTE_ETH_FOREACH_DEV(portid) {
492                         if ((port_mask & (1 << portid)) == 0)
493                                 continue;
494                         memset(&link, 0, sizeof(link));
495                         rte_eth_link_get_nowait(portid, &link);
496                         /* print link status if flag set */
497                         if (print_flag == 1) {
498                                 if (link.link_status)
499                                         printf(
500                                         "Port%d Link Up. Speed %u Mbps - %s\n",
501                                                 portid, link.link_speed,
502                                 (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
503                                         ("full-duplex") : ("half-duplex\n"));
504                                 else
505                                         printf("Port %d Link Down\n", portid);
506                                 continue;
507                         }
508                         /* clear all_ports_up flag if any link down */
509                         if (link.link_status == ETH_LINK_DOWN) {
510                                 all_ports_up = 0;
511                                 break;
512                         }
513                 }
514                 /* after finally printing all link status, get out */
515                 if (print_flag == 1)
516                         break;
517
518                 if (all_ports_up == 0) {
519                         printf(".");
520                         fflush(stdout);
521                         rte_delay_ms(CHECK_INTERVAL);
522                 }
523
524                 /* set the print_flag if all ports up or timeout */
525                 if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
526                         print_flag = 1;
527                         printf("done\n");
528                 }
529         }
530 }
531
532 /* Initialise ports/queues etc. and start main loop on each core */
533 int
534 main(int argc, char** argv)
535 {
536         int ret;
537         unsigned i,high_port;
538         uint16_t nb_sys_ports, port;
539
540         /* Associate signal_hanlder function with USR signals */
541         signal(SIGUSR1, signal_handler);
542         signal(SIGUSR2, signal_handler);
543
544         /* Initialise EAL */
545         ret = rte_eal_init(argc, argv);
546         if (ret < 0)
547                 FATAL_ERROR("Could not initialise EAL (%d)", ret);
548         argc -= ret;
549         argv += ret;
550
551         /* Parse application arguments (after the EAL ones) */
552         parse_args(argc, argv);
553
554         /* Create the mbuf pool */
555         pktmbuf_pool = rte_pktmbuf_pool_create("mbuf_pool", NB_MBUF,
556                         MEMPOOL_CACHE_SZ, 0, MBUF_DATA_SZ, rte_socket_id());
557         if (pktmbuf_pool == NULL) {
558                 FATAL_ERROR("Could not initialise mbuf pool");
559                 return -1;
560         }
561
562         /* Get number of ports found in scan */
563         nb_sys_ports = rte_eth_dev_count_avail();
564         if (nb_sys_ports == 0)
565                 FATAL_ERROR("No supported Ethernet device found");
566         /* Find highest port set in portmask */
567         for (high_port = (sizeof(ports_mask) * 8) - 1;
568                         (high_port != 0) && !(ports_mask & (1 << high_port));
569                         high_port--)
570                 ; /* empty body */
571         if (high_port > nb_sys_ports)
572                 FATAL_ERROR("Port mask requires more ports than available");
573
574         /* Initialise each port */
575         RTE_ETH_FOREACH_DEV(port) {
576                 /* Skip ports that are not enabled */
577                 if ((ports_mask & (1 << port)) == 0) {
578                         continue;
579                 }
580                 init_port(port);
581         }
582         check_all_ports_link_status(ports_mask);
583
584         /* Launch per-lcore function on every lcore */
585         rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
586         RTE_LCORE_FOREACH_SLAVE(i) {
587                 if (rte_eal_wait_lcore(i) < 0)
588                         return -1;
589         }
590
591         return 0;
592 }