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