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