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