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