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