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