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