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