New upstream version 16.11.8
[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                 /* limit ourselves to application supported cores only */
169                 if (i >= APP_MAX_LCORE)
170                         break;
171                 printf("%6u %7u %13"PRIu64" %13"PRIu64" %16"PRIu64"\n",
172                        i, (unsigned)port_ids[i],
173                        lcore_stats[i].rx, lcore_stats[i].tx,
174                        lcore_stats[i].dropped);
175         }
176         printf("=======  ======  ============  ============  ===============\n");
177 }
178
179 /* Custom handling of signals to handle stats */
180 static void
181 signal_handler(int signum)
182 {
183         /* When we receive a USR1 signal, print stats */
184         if (signum == SIGUSR1) {
185                 print_stats();
186         }
187
188         /* When we receive a USR2 signal, reset stats */
189         if (signum == SIGUSR2) {
190                 memset(&lcore_stats, 0, sizeof(lcore_stats));
191                 printf("\n**Statistics have been reset**\n");
192                 return;
193         }
194 }
195
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
229 /* Main processing loop */
230 static int
231 main_loop(__attribute__((unused)) void *arg)
232 {
233         const unsigned lcore_id = rte_lcore_id();
234         char tap_name[IFNAMSIZ];
235         int tap_fd;
236
237         if ((1ULL << lcore_id) & input_cores_mask) {
238                 /* Create new tap interface */
239                 snprintf(tap_name, IFNAMSIZ, "tap_dpdk_%.2u", lcore_id);
240                 tap_fd = tap_create(tap_name);
241                 if (tap_fd < 0)
242                         FATAL_ERROR("Could not create tap interface \"%s\" (%d)",
243                                         tap_name, tap_fd);
244
245                 PRINT_INFO("Lcore %u is reading from port %u and writing to %s",
246                            lcore_id, (unsigned)port_ids[lcore_id], tap_name);
247                 fflush(stdout);
248                 /* Loop forever reading from NIC and writing to tap */
249                 for (;;) {
250                         struct rte_mbuf *pkts_burst[PKT_BURST_SZ];
251                         unsigned i;
252                         const unsigned nb_rx =
253                                         rte_eth_rx_burst(port_ids[lcore_id], 0,
254                                             pkts_burst, PKT_BURST_SZ);
255                         lcore_stats[lcore_id].rx += nb_rx;
256                         for (i = 0; likely(i < nb_rx); i++) {
257                                 struct rte_mbuf *m = pkts_burst[i];
258                                 /* Ignore return val from write() */
259                                 int ret = write(tap_fd,
260                                                 rte_pktmbuf_mtod(m, void*),
261                                                 rte_pktmbuf_data_len(m));
262                                 rte_pktmbuf_free(m);
263                                 if (unlikely(ret < 0))
264                                         lcore_stats[lcore_id].dropped++;
265                                 else
266                                         lcore_stats[lcore_id].tx++;
267                         }
268                 }
269         }
270         else if ((1ULL << lcore_id) & output_cores_mask) {
271                 /* Create new tap interface */
272                 snprintf(tap_name, IFNAMSIZ, "tap_dpdk_%.2u", lcore_id);
273                 tap_fd = tap_create(tap_name);
274                 if (tap_fd < 0)
275                         FATAL_ERROR("Could not create tap interface \"%s\" (%d)",
276                                         tap_name, tap_fd);
277
278                 PRINT_INFO("Lcore %u is reading from %s and writing to port %u",
279                            lcore_id, tap_name, (unsigned)port_ids[lcore_id]);
280                 fflush(stdout);
281                 /* Loop forever reading from tap and writing to NIC */
282                 for (;;) {
283                         int ret;
284                         struct rte_mbuf *m = rte_pktmbuf_alloc(pktmbuf_pool);
285                         if (m == NULL)
286                                 continue;
287
288                         ret = read(tap_fd, rte_pktmbuf_mtod(m, void *),
289                                 MAX_PACKET_SZ);
290                         lcore_stats[lcore_id].rx++;
291                         if (unlikely(ret < 0)) {
292                                 FATAL_ERROR("Reading from %s interface failed",
293                                             tap_name);
294                         }
295                         m->nb_segs = 1;
296                         m->next = NULL;
297                         m->pkt_len = (uint16_t)ret;
298                         m->data_len = (uint16_t)ret;
299                         ret = rte_eth_tx_burst(port_ids[lcore_id], 0, &m, 1);
300                         if (unlikely(ret < 1)) {
301                                 rte_pktmbuf_free(m);
302                                 lcore_stats[lcore_id].dropped++;
303                         }
304                         else {
305                                 lcore_stats[lcore_id].tx++;
306                         }
307                 }
308         }
309         else {
310                 PRINT_INFO("Lcore %u has nothing to do", lcore_id);
311                 return 0;
312         }
313         /*
314          * Tap file is closed automatically when program exits. Putting close()
315          * here will cause the compiler to give an error about unreachable code.
316          */
317 }
318
319 /* Display usage instructions */
320 static void
321 print_usage(const char *prgname)
322 {
323         PRINT_INFO("\nUsage: %s [EAL options] -- -p PORTMASK -i IN_CORES -o OUT_CORES\n"
324                    "    -p PORTMASK: hex bitmask of ports to use\n"
325                    "    -i IN_CORES: hex bitmask of cores which read from NIC\n"
326                    "    -o OUT_CORES: hex bitmask of cores which write to NIC",
327                    prgname);
328 }
329
330 /* Convert string to unsigned number. 0 is returned if error occurs */
331 static uint64_t
332 parse_unsigned(const char *portmask)
333 {
334         char *end = NULL;
335         uint64_t num;
336
337         num = strtoull(portmask, &end, 16);
338         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
339                 return 0;
340
341         return (uint64_t)num;
342 }
343
344 /* Record affinities between ports and lcores in global port_ids[] array */
345 static void
346 setup_port_lcore_affinities(void)
347 {
348         unsigned long i;
349         uint8_t tx_port = 0;
350         uint8_t rx_port = 0;
351
352         /* Setup port_ids[] array, and check masks were ok */
353         for (i = 0; i < APP_MAX_LCORE; i++) {
354                 if (!rte_lcore_is_enabled(i))
355                         continue;
356                 if (input_cores_mask & (1ULL << i)) {
357                         /* Skip ports that are not enabled */
358                         while ((ports_mask & (1 << rx_port)) == 0) {
359                                 rx_port++;
360                                 if (rx_port > (sizeof(ports_mask) * 8))
361                                         goto fail; /* not enough ports */
362                         }
363
364                         port_ids[i] = rx_port++;
365                 } else if (output_cores_mask & (1ULL << (i & 0x3f))) {
366                         /* Skip ports that are not enabled */
367                         while ((ports_mask & (1 << tx_port)) == 0) {
368                                 tx_port++;
369                                 if (tx_port > (sizeof(ports_mask) * 8))
370                                         goto fail; /* not enough ports */
371                         }
372
373                         port_ids[i] = tx_port++;
374                 }
375         }
376
377         if (rx_port != tx_port)
378                 goto fail; /* uneven number of cores in masks */
379
380         if (ports_mask & (~((1 << rx_port) - 1)))
381                 goto fail; /* unused ports */
382
383         return;
384 fail:
385         FATAL_ERROR("Invalid core/port masks specified on command line");
386 }
387
388 /* Parse the arguments given in the command line of the application */
389 static void
390 parse_args(int argc, char **argv)
391 {
392         int opt;
393         const char *prgname = argv[0];
394
395         /* Disable printing messages within getopt() */
396         opterr = 0;
397
398         /* Parse command line */
399         while ((opt = getopt(argc, argv, "i:o:p:")) != EOF) {
400                 switch (opt) {
401                 case 'i':
402                         input_cores_mask = parse_unsigned(optarg);
403                         break;
404                 case 'o':
405                         output_cores_mask = parse_unsigned(optarg);
406                         break;
407                 case 'p':
408                         ports_mask = parse_unsigned(optarg);
409                         break;
410                 default:
411                         print_usage(prgname);
412                         FATAL_ERROR("Invalid option specified");
413                 }
414         }
415
416         /* Check that options were parsed ok */
417         if (input_cores_mask == 0) {
418                 print_usage(prgname);
419                 FATAL_ERROR("IN_CORES not specified correctly");
420         }
421         if (output_cores_mask == 0) {
422                 print_usage(prgname);
423                 FATAL_ERROR("OUT_CORES not specified correctly");
424         }
425         if (ports_mask == 0) {
426                 print_usage(prgname);
427                 FATAL_ERROR("PORTMASK not specified correctly");
428         }
429
430         setup_port_lcore_affinities();
431 }
432
433 /* Initialise a single port on an Ethernet device */
434 static void
435 init_port(uint8_t port)
436 {
437         int ret;
438
439         /* Initialise device and RX/TX queues */
440         PRINT_INFO("Initialising port %u ...", (unsigned)port);
441         fflush(stdout);
442         ret = rte_eth_dev_configure(port, 1, 1, &port_conf);
443         if (ret < 0)
444                 FATAL_ERROR("Could not configure port%u (%d)",
445                             (unsigned)port, ret);
446
447         ret = rte_eth_rx_queue_setup(port, 0, NB_RXD, rte_eth_dev_socket_id(port),
448                                 NULL,
449                                 pktmbuf_pool);
450         if (ret < 0)
451                 FATAL_ERROR("Could not setup up RX queue for port%u (%d)",
452                             (unsigned)port, ret);
453
454         ret = rte_eth_tx_queue_setup(port, 0, NB_TXD, rte_eth_dev_socket_id(port),
455                                 NULL);
456         if (ret < 0)
457                 FATAL_ERROR("Could not setup up TX queue for port%u (%d)",
458                             (unsigned)port, ret);
459
460         ret = rte_eth_dev_start(port);
461         if (ret < 0)
462                 FATAL_ERROR("Could not start port%u (%d)", (unsigned)port, ret);
463
464         rte_eth_promiscuous_enable(port);
465 }
466
467 /* Check the link status of all ports in up to 9s, and print them finally */
468 static void
469 check_all_ports_link_status(uint8_t port_num, uint32_t port_mask)
470 {
471 #define CHECK_INTERVAL 100 /* 100ms */
472 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
473         uint8_t portid, count, all_ports_up, print_flag = 0;
474         struct rte_eth_link link;
475
476         printf("\nChecking link status");
477         fflush(stdout);
478         for (count = 0; count <= MAX_CHECK_TIME; count++) {
479                 all_ports_up = 1;
480                 for (portid = 0; portid < port_num; portid++) {
481                         if ((port_mask & (1 << portid)) == 0)
482                                 continue;
483                         memset(&link, 0, sizeof(link));
484                         rte_eth_link_get_nowait(portid, &link);
485                         /* print link status if flag set */
486                         if (print_flag == 1) {
487                                 if (link.link_status)
488                                         printf("Port %d Link Up - speed %u "
489                                                 "Mbps - %s\n", (uint8_t)portid,
490                                                 (unsigned)link.link_speed,
491                                 (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
492                                         ("full-duplex") : ("half-duplex\n"));
493                                 else
494                                         printf("Port %d Link Down\n",
495                                                 (uint8_t)portid);
496                                 continue;
497                         }
498                         /* clear all_ports_up flag if any link down */
499                         if (link.link_status == ETH_LINK_DOWN) {
500                                 all_ports_up = 0;
501                                 break;
502                         }
503                 }
504                 /* after finally printing all link status, get out */
505                 if (print_flag == 1)
506                         break;
507
508                 if (all_ports_up == 0) {
509                         printf(".");
510                         fflush(stdout);
511                         rte_delay_ms(CHECK_INTERVAL);
512                 }
513
514                 /* set the print_flag if all ports up or timeout */
515                 if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
516                         print_flag = 1;
517                         printf("done\n");
518                 }
519         }
520 }
521
522 /* Initialise ports/queues etc. and start main loop on each core */
523 int
524 main(int argc, char** argv)
525 {
526         int ret;
527         unsigned i,high_port;
528         uint8_t nb_sys_ports, port;
529
530         /* Associate signal_hanlder function with USR signals */
531         signal(SIGUSR1, signal_handler);
532         signal(SIGUSR2, signal_handler);
533
534         /* Initialise EAL */
535         ret = rte_eal_init(argc, argv);
536         if (ret < 0)
537                 FATAL_ERROR("Could not initialise EAL (%d)", ret);
538         argc -= ret;
539         argv += ret;
540
541         /* Parse application arguments (after the EAL ones) */
542         parse_args(argc, argv);
543
544         /* Create the mbuf pool */
545         pktmbuf_pool = rte_pktmbuf_pool_create("mbuf_pool", NB_MBUF,
546                         MEMPOOL_CACHE_SZ, 0, MBUF_DATA_SZ, rte_socket_id());
547         if (pktmbuf_pool == NULL) {
548                 FATAL_ERROR("Could not initialise mbuf pool");
549                 return -1;
550         }
551
552         /* Get number of ports found in scan */
553         nb_sys_ports = rte_eth_dev_count();
554         if (nb_sys_ports == 0)
555                 FATAL_ERROR("No supported Ethernet device found");
556         /* Find highest port set in portmask */
557         for (high_port = (sizeof(ports_mask) * 8) - 1;
558                         (high_port != 0) && !(ports_mask & (1 << high_port));
559                         high_port--)
560                 ; /* empty body */
561         if (high_port > nb_sys_ports)
562                 FATAL_ERROR("Port mask requires more ports than available");
563
564         /* Initialise each port */
565         for (port = 0; port < nb_sys_ports; port++) {
566                 /* Skip ports that are not enabled */
567                 if ((ports_mask & (1 << port)) == 0) {
568                         continue;
569                 }
570                 init_port(port);
571         }
572         check_all_ports_link_status(nb_sys_ports, ports_mask);
573
574         /* Launch per-lcore function on every lcore */
575         rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
576         RTE_LCORE_FOREACH_SLAVE(i) {
577                 if (rte_eal_wait_lcore(i) < 0)
578                         return -1;
579         }
580
581         return 0;
582 }