first public release
[dpdk.git] / examples / exception_path / main.c
1 /*-
2  *   BSD LICENSE
3  * 
4  *   Copyright(c) 2010-2012 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  *  version: DPDK.L.1.2.3-3
34  */
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <stdint.h>
39 #include <inttypes.h>
40 #include <string.h>
41 #include <sys/queue.h>
42 #include <stdarg.h>
43 #include <errno.h>
44 #include <getopt.h>
45
46 #include <netinet/in.h>
47 #include <linux/if.h>
48 #include <linux/if_tun.h>
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_tailq.h>
60 #include <rte_eal.h>
61 #include <rte_per_lcore.h>
62 #include <rte_launch.h>
63 #include <rte_atomic.h>
64 #include <rte_lcore.h>
65 #include <rte_branch_prediction.h>
66 #include <rte_interrupts.h>
67 #include <rte_pci.h>
68 #include <rte_debug.h>
69 #include <rte_ether.h>
70 #include <rte_ethdev.h>
71 #include <rte_ring.h>
72 #include <rte_log.h>
73 #include <rte_mempool.h>
74 #include <rte_mbuf.h>
75 #include <rte_string_fns.h>
76
77 /* Macros for printing using RTE_LOG */
78 #define RTE_LOGTYPE_APP RTE_LOGTYPE_USER1
79 #define FATAL_ERROR(fmt, args...)       rte_exit(EXIT_FAILURE, fmt "\n", ##args)
80 #define PRINT_INFO(fmt, args...)        RTE_LOG(INFO, APP, fmt "\n", ##args)
81
82 /* NUMA socket to allocate mbuf pool on */
83 #define SOCKET                  0
84
85 /* Max ports than can be used (each port is associated with two lcores) */
86 #define MAX_PORTS               (RTE_MAX_LCORE / 2)
87
88 /* Max size of a single packet */
89 #define MAX_PACKET_SZ           2048
90
91 /* Number of bytes needed for each mbuf */
92 #define MBUF_SZ \
93         (MAX_PACKET_SZ + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
94
95 /* Number of mbufs in mempool that is created */
96 #define NB_MBUF                 8192
97
98 /* How many packets to attempt to read from NIC in one go */
99 #define PKT_BURST_SZ            32
100
101 /* How many objects (mbufs) to keep in per-lcore mempool cache */
102 #define MEMPOOL_CACHE_SZ        PKT_BURST_SZ
103
104 /* Number of RX ring descriptors */
105 #define NB_RXD                  128
106
107 /* Number of TX ring descriptors */
108 #define NB_TXD                  512
109
110 /*
111  * RX and TX Prefetch, Host, and Write-back threshold values should be
112  * carefully set for optimal performance. Consult the network
113  * controller's datasheet and supporting DPDK documentation for guidance
114  * on how these parameters should be set.
115  */
116 /* RX ring configuration */
117 static const struct rte_eth_rxconf rx_conf = {
118         .rx_thresh = {
119                 .pthresh = 8,   /* Ring prefetch threshold */
120                 .hthresh = 8,   /* Ring host threshold */
121                 .wthresh = 4,   /* Ring writeback threshold */
122         },
123         .rx_free_thresh = 0,    /* Immediately free RX descriptors */
124 };
125
126 /*
127  * These default values are optimized for use with the Intel(R) 82599 10 GbE
128  * Controller and the DPDK ixgbe PMD. Consider using other values for other
129  * network controllers and/or network drivers.
130  */
131 /* TX ring configuration */
132 static const struct rte_eth_txconf tx_conf = {
133         .tx_thresh = {
134                 .pthresh = 36,  /* Ring prefetch threshold */
135                 .hthresh = 0,   /* Ring host threshold */
136                 .wthresh = 0,   /* Ring writeback threshold */
137         },
138         .tx_free_thresh = 0,    /* Use PMD default values */
139         .tx_rs_thresh = 0,      /* Use PMD default values */
140 };
141
142 /* Options for configuring ethernet port */
143 static const struct rte_eth_conf port_conf = {
144         .rxmode = {
145                 .header_split = 0,      /* Header Split disabled */
146                 .hw_ip_checksum = 0,    /* IP checksum offload disabled */
147                 .hw_vlan_filter = 0,    /* VLAN filtering disabled */
148                 .jumbo_frame = 0,       /* Jumbo Frame Support disabled */
149                 .hw_strip_crc = 0,      /* CRC stripped by hardware */
150         },
151         .txmode = {
152         },
153 };
154
155 /* Mempool for mbufs */
156 static struct rte_mempool * pktmbuf_pool = NULL;
157
158 /* Mask of enabled ports */
159 static uint32_t ports_mask = 0;
160
161 /* Mask of cores that read from NIC and write to tap */
162 static uint32_t input_cores_mask = 0;
163
164 /* Mask of cores that read from tap and write to NIC */
165 static uint32_t output_cores_mask = 0;
166
167 /* Array storing port_id that is associated with each lcore */
168 static uint8_t port_ids[RTE_MAX_LCORE];
169
170 /* Structure type for recording lcore-specific stats */
171 struct stats {
172         uint64_t rx;
173         uint64_t tx;
174         uint64_t dropped;
175 };
176
177 /* Array of lcore-specific stats */
178 static struct stats lcore_stats[RTE_MAX_LCORE];
179
180 /* Print out statistics on packets handled */
181 static void
182 print_stats(void)
183 {
184         unsigned i;
185
186         printf("\n**Exception-Path example application statistics**\n"
187                "=======  ======  ============  ============  ===============\n"
188                " Lcore    Port            RX            TX    Dropped on TX\n"
189                "-------  ------  ------------  ------------  ---------------\n");
190         RTE_LCORE_FOREACH(i) {
191                 printf("%6u %7u %13"PRIu64" %13"PRIu64" %16"PRIu64"\n",
192                        i, (unsigned)port_ids[i],
193                        lcore_stats[i].rx, lcore_stats[i].tx,
194                        lcore_stats[i].dropped);
195         }
196         printf("=======  ======  ============  ============  ===============\n");
197 }
198
199 /* Custom handling of signals to handle stats */
200 static void
201 signal_handler(int signum)
202 {
203         /* When we receive a USR1 signal, print stats */
204         if (signum == SIGUSR1) {
205                 print_stats();
206         }
207
208         /* When we receive a USR2 signal, reset stats */
209         if (signum == SIGUSR2) {
210                 memset(&lcore_stats, 0, sizeof(lcore_stats));
211                 printf("\n**Statistics have been reset**\n");
212                 return;
213         }
214 }
215
216 /*
217  * Create a tap network interface, or use existing one with same name.
218  * If name[0]='\0' then a name is automatically assigned and returned in name.
219  */
220 static int tap_create(char *name)
221 {
222         struct ifreq ifr;
223         int fd, ret;
224
225         fd = open("/dev/net/tun", O_RDWR);
226         if (fd < 0)
227                 return fd;
228
229         memset(&ifr, 0, sizeof(ifr));
230
231         /* TAP device without packet information */
232         ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
233
234         if (name && *name)
235                 rte_snprintf(ifr.ifr_name, IFNAMSIZ, name);
236
237         ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
238         if (ret < 0) {
239                 close(fd);
240                 return ret;
241         }
242
243         if (name)
244                 rte_snprintf(name, IFNAMSIZ, ifr.ifr_name);
245
246         return fd;
247 }
248
249 /* Main processing loop */
250 static  __attribute__((noreturn)) int
251 main_loop(__attribute__((unused)) void *arg)
252 {
253         const unsigned lcore_id = rte_lcore_id();
254         char tap_name[IFNAMSIZ];
255         int tap_fd;
256
257         /* Create new tap interface */
258         rte_snprintf(tap_name, IFNAMSIZ, "tap_dpdk_%.2u", lcore_id);
259         tap_fd = tap_create(tap_name);
260         if (tap_fd < 0)
261                 FATAL_ERROR("Could not create tap interface \"%s\" (%d)",
262                             tap_name, tap_fd);
263
264         if ((1 << lcore_id) & input_cores_mask) {
265                 PRINT_INFO("Lcore %u is reading from port %u and writing to %s",
266                            lcore_id, (unsigned)port_ids[lcore_id], tap_name);
267                 fflush(stdout);
268                 /* Loop forever reading from NIC and writing to tap */
269                 for (;;) {
270                         struct rte_mbuf *pkts_burst[PKT_BURST_SZ];
271                         unsigned i;
272                         const unsigned nb_rx =
273                                         rte_eth_rx_burst(port_ids[lcore_id], 0,
274                                             pkts_burst, PKT_BURST_SZ);
275                         lcore_stats[lcore_id].rx += nb_rx;
276                         for (i = 0; likely(i < nb_rx); i++) {
277                                 struct rte_mbuf *m = pkts_burst[i];
278                                 /* Ignore return val from write() */
279                                 int ret = write(tap_fd,
280                                                 rte_pktmbuf_mtod(m, void*),
281                                                 rte_pktmbuf_data_len(m));
282                                 rte_pktmbuf_free(m);
283                                 if (unlikely(ret < 0))
284                                         lcore_stats[lcore_id].dropped++;
285                                 else
286                                         lcore_stats[lcore_id].tx++;
287                         }
288                 }
289         }
290         else if ((1 << lcore_id) & output_cores_mask) {
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, m->pkt.data, MAX_PACKET_SZ);
302                         lcore_stats[lcore_id].rx++;
303                         if (unlikely(ret < 0)) {
304                                 FATAL_ERROR("Reading from %s interface failed",
305                                             tap_name);
306                         }
307                         m->pkt.nb_segs = 1;
308                         m->pkt.next = NULL;
309                         m->pkt.pkt_len = (uint16_t)ret;
310                         m->pkt.data_len = (uint16_t)ret;
311                         ret = rte_eth_tx_burst(port_ids[lcore_id], 0, &m, 1);
312                         if (unlikely(ret < 1)) {
313                                 rte_pktmbuf_free(m);
314                                 lcore_stats[lcore_id].dropped++;
315                         }
316                         else {
317                                 lcore_stats[lcore_id].tx++;
318                         }
319                 }
320         }
321         else {
322                 PRINT_INFO("Lcore %u has nothing to do", lcore_id);
323                 for (;;)
324                         ; /* loop doing nothing */
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 uint32_t
345 parse_unsigned(const char *portmask)
346 {
347         char *end = NULL;
348         unsigned long num;
349
350         num = strtoul(portmask, &end, 16);
351         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
352                 return 0;
353
354         return (uint32_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 i;
362         uint8_t tx_port = 0;
363         uint8_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 & (1 << 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                 }
377                 else if (output_cores_mask & (1 << i)) {
378                         /* Skip ports that are not enabled */
379                         while ((ports_mask & (1 << tx_port)) == 0) {
380                                 tx_port++;
381                                 if (tx_port > (sizeof(ports_mask) * 8))
382                                         goto fail; /* not enough ports */
383                         }
384
385                         port_ids[i] = tx_port++;
386                 }
387         }
388
389         if (rx_port != tx_port)
390                 goto fail; /* uneven number of cores in masks */
391
392         if (ports_mask & (~((1 << rx_port) - 1)))
393                 goto fail; /* unused ports */
394
395         return;
396 fail:
397         FATAL_ERROR("Invalid core/port masks specified on command line");
398 }
399
400 /* Parse the arguments given in the command line of the application */
401 static void
402 parse_args(int argc, char **argv)
403 {
404         int opt;
405         const char *prgname = argv[0];
406
407         /* Disable printing messages within getopt() */
408         opterr = 0;
409
410         /* Parse command line */
411         while ((opt = getopt(argc, argv, "i:o:p:")) != EOF) {
412                 switch (opt) {
413                 case 'i':
414                         input_cores_mask = parse_unsigned(optarg);
415                         break;
416                 case 'o':
417                         output_cores_mask = parse_unsigned(optarg);
418                         break;
419                 case 'p':
420                         ports_mask = parse_unsigned(optarg);
421                         break;
422                 default:
423                         print_usage(prgname);
424                         FATAL_ERROR("Invalid option specified");
425                 }
426         }
427
428         /* Check that options were parsed ok */
429         if (input_cores_mask == 0) {
430                 print_usage(prgname);
431                 FATAL_ERROR("IN_CORES not specified correctly");
432         }
433         if (output_cores_mask == 0) {
434                 print_usage(prgname);
435                 FATAL_ERROR("OUT_CORES not specified correctly");
436         }
437         if (ports_mask == 0) {
438                 print_usage(prgname);
439                 FATAL_ERROR("PORTMASK not specified correctly");
440         }
441
442         setup_port_lcore_affinities();
443 }
444
445 /* Initialise a single port on an Ethernet device */
446 static void
447 init_port(uint8_t port)
448 {
449         struct rte_eth_link link;
450         int ret;
451
452         /* Initialise device and RX/TX queues */
453         PRINT_INFO("Initialising port %u ...", (unsigned)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)",
458                             (unsigned)port, ret);
459
460         ret = rte_eth_rx_queue_setup(port, 0, NB_RXD, SOCKET, &rx_conf,
461                                      pktmbuf_pool);
462         if (ret < 0)
463                 FATAL_ERROR("Could not setup up RX queue for port%u (%d)",
464                             (unsigned)port, ret);
465
466         ret = rte_eth_tx_queue_setup(port, 0, NB_TXD, SOCKET, &tx_conf);
467         if (ret < 0)
468                 FATAL_ERROR("Could not setup up TX queue for port%u (%d)",
469                             (unsigned)port, ret);
470
471         ret = rte_eth_dev_start(port);
472         if (ret < 0)
473                 FATAL_ERROR("Could not start port%u (%d)", (unsigned)port, ret);
474
475         /*  Everything is setup and started, print link status */
476         rte_eth_link_get(port, &link);
477         if (link.link_status)
478                 PRINT_INFO("    link up - %u Mbit/s - %s",
479                            (unsigned)link.link_speed,
480                            (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
481                            ("full-duplex") : ("half-duplex"));
482         else
483                 PRINT_INFO("    link down");
484
485         rte_eth_promiscuous_enable(port);
486 }
487
488 /* Initialise ports/queues etc. and start main loop on each core */
489 int
490 main(int argc, char** argv)
491 {
492         int ret;
493         unsigned i,high_port;
494         uint8_t nb_sys_ports, port;
495
496         /* Associate signal_hanlder function with USR signals */
497         signal(SIGUSR1, signal_handler);
498         signal(SIGUSR2, signal_handler);
499
500         /* Initialise EAL */
501         ret = rte_eal_init(argc, argv);
502         if (ret < 0)
503                 FATAL_ERROR("Could not initialise EAL (%d)", ret);
504         argc -= ret;
505         argv += ret;
506
507         /* Parse application arguments (after the EAL ones) */
508         parse_args(argc, argv);
509
510         /* Create the mbuf pool */
511         pktmbuf_pool = rte_mempool_create("mbuf_pool", NB_MBUF, MBUF_SZ,
512                         MEMPOOL_CACHE_SZ,
513                         sizeof(struct rte_pktmbuf_pool_private),
514                         rte_pktmbuf_pool_init, NULL, rte_pktmbuf_init, NULL,
515                         SOCKET, 0);
516         if (pktmbuf_pool == NULL) {
517                 FATAL_ERROR("Could not initialise mbuf pool");
518                 return -1;
519         }
520
521         /* Initialise PMD driver(s) */
522 #ifdef RTE_LIBRTE_IGB_PMD
523         ret = rte_igb_pmd_init();
524         if (ret < 0)
525                 FATAL_ERROR("Could not initialise igb PMD (%d)", ret);
526 #endif
527 #ifdef RTE_LIBRTE_IXGBE_PMD
528         ret = rte_ixgbe_pmd_init();
529         if (ret < 0)
530                 FATAL_ERROR("Could not initialise ixgbe PMD (%d)", ret);
531 #endif
532
533         /* Scan PCI bus for recognised devices */
534         ret = rte_eal_pci_probe();
535         if (ret < 0)
536                 FATAL_ERROR("Could not probe PCI (%d)", ret);
537
538         /* Get number of ports found in scan */
539         nb_sys_ports = rte_eth_dev_count();
540         if (nb_sys_ports == 0)
541                 FATAL_ERROR("No supported Ethernet devices found - check that "
542                             "CONFIG_RTE_LIBRTE_IGB_PMD=y and/or "
543                             "CONFIG_RTE_LIBRTE_IXGBE_PMD=y in the config file");
544         /* Find highest port set in portmask */
545         for (high_port = (sizeof(ports_mask) * 8) - 1;
546                         (high_port != 0) && !(ports_mask & (1 << high_port));
547                         high_port--)
548                 ; /* empty body */
549         if (high_port > nb_sys_ports)
550                 FATAL_ERROR("Port mask requires more ports than available");
551
552         /* Initialise each port */
553         for (port = 0; port < nb_sys_ports; port++) {
554                 /* Skip ports that are not enabled */
555                 if ((ports_mask & (1 << port)) == 0) {
556                         continue;
557                 }
558                 init_port(port);
559         }
560
561         /* Launch per-lcore function on every lcore */
562         rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
563         RTE_LCORE_FOREACH_SLAVE(i) {
564                 if (rte_eal_wait_lcore(i) < 0)
565                         return -1;
566         }
567
568         return 0;
569 }