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