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