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