remove version in all files
[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  */
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <stdint.h>
38 #include <inttypes.h>
39 #include <string.h>
40 #include <sys/queue.h>
41 #include <stdarg.h>
42 #include <errno.h>
43 #include <getopt.h>
44
45 #include <netinet/in.h>
46 #include <linux/if.h>
47 #include <linux/if_tun.h>
48 #include <fcntl.h>
49 #include <sys/ioctl.h>
50 #include <unistd.h>
51 #include <signal.h>
52
53 #include <rte_common.h>
54 #include <rte_log.h>
55 #include <rte_memory.h>
56 #include <rte_memcpy.h>
57 #include <rte_memzone.h>
58 #include <rte_tailq.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_ring.h>
71 #include <rte_log.h>
72 #include <rte_mempool.h>
73 #include <rte_mbuf.h>
74 #include <rte_string_fns.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 /* NUMA socket to allocate mbuf pool on */
82 #define SOCKET                  0
83
84 /* Max ports than can be used (each port is associated with two lcores) */
85 #define MAX_PORTS               (RTE_MAX_LCORE / 2)
86
87 /* Max size of a single packet */
88 #define MAX_PACKET_SZ           2048
89
90 /* Number of bytes needed for each mbuf */
91 #define MBUF_SZ \
92         (MAX_PACKET_SZ + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
93
94 /* Number of mbufs in mempool that is created */
95 #define NB_MBUF                 8192
96
97 /* How many packets to attempt to read from NIC in one go */
98 #define PKT_BURST_SZ            32
99
100 /* How many objects (mbufs) to keep in per-lcore mempool cache */
101 #define MEMPOOL_CACHE_SZ        PKT_BURST_SZ
102
103 /* Number of RX ring descriptors */
104 #define NB_RXD                  128
105
106 /* Number of TX ring descriptors */
107 #define NB_TXD                  512
108
109 /*
110  * RX and TX Prefetch, Host, and Write-back threshold values should be
111  * carefully set for optimal performance. Consult the network
112  * controller's datasheet and supporting DPDK documentation for guidance
113  * on how these parameters should be set.
114  */
115 /* RX ring configuration */
116 static const struct rte_eth_rxconf rx_conf = {
117         .rx_thresh = {
118                 .pthresh = 8,   /* Ring prefetch threshold */
119                 .hthresh = 8,   /* Ring host threshold */
120                 .wthresh = 4,   /* Ring writeback threshold */
121         },
122         .rx_free_thresh = 0,    /* Immediately free RX descriptors */
123 };
124
125 /*
126  * These default values are optimized for use with the Intel(R) 82599 10 GbE
127  * Controller and the DPDK ixgbe PMD. Consider using other values for other
128  * network controllers and/or network drivers.
129  */
130 /* TX ring configuration */
131 static const struct rte_eth_txconf tx_conf = {
132         .tx_thresh = {
133                 .pthresh = 36,  /* Ring prefetch threshold */
134                 .hthresh = 0,   /* Ring host threshold */
135                 .wthresh = 0,   /* Ring writeback threshold */
136         },
137         .tx_free_thresh = 0,    /* Use PMD default values */
138         .tx_rs_thresh = 0,      /* Use PMD default values */
139 };
140
141 /* Options for configuring ethernet port */
142 static const struct rte_eth_conf port_conf = {
143         .rxmode = {
144                 .header_split = 0,      /* Header Split disabled */
145                 .hw_ip_checksum = 0,    /* IP checksum offload disabled */
146                 .hw_vlan_filter = 0,    /* VLAN filtering disabled */
147                 .jumbo_frame = 0,       /* Jumbo Frame Support disabled */
148                 .hw_strip_crc = 0,      /* CRC stripped by hardware */
149         },
150         .txmode = {
151         },
152 };
153
154 /* Mempool for mbufs */
155 static struct rte_mempool * pktmbuf_pool = NULL;
156
157 /* Mask of enabled ports */
158 static uint32_t ports_mask = 0;
159
160 /* Mask of cores that read from NIC and write to tap */
161 static uint32_t input_cores_mask = 0;
162
163 /* Mask of cores that read from tap and write to NIC */
164 static uint32_t output_cores_mask = 0;
165
166 /* Array storing port_id that is associated with each lcore */
167 static uint8_t port_ids[RTE_MAX_LCORE];
168
169 /* Structure type for recording lcore-specific stats */
170 struct stats {
171         uint64_t rx;
172         uint64_t tx;
173         uint64_t dropped;
174 };
175
176 /* Array of lcore-specific stats */
177 static struct stats lcore_stats[RTE_MAX_LCORE];
178
179 /* Print out statistics on packets handled */
180 static void
181 print_stats(void)
182 {
183         unsigned i;
184
185         printf("\n**Exception-Path example application statistics**\n"
186                "=======  ======  ============  ============  ===============\n"
187                " Lcore    Port            RX            TX    Dropped on TX\n"
188                "-------  ------  ------------  ------------  ---------------\n");
189         RTE_LCORE_FOREACH(i) {
190                 printf("%6u %7u %13"PRIu64" %13"PRIu64" %16"PRIu64"\n",
191                        i, (unsigned)port_ids[i],
192                        lcore_stats[i].rx, lcore_stats[i].tx,
193                        lcore_stats[i].dropped);
194         }
195         printf("=======  ======  ============  ============  ===============\n");
196 }
197
198 /* Custom handling of signals to handle stats */
199 static void
200 signal_handler(int signum)
201 {
202         /* When we receive a USR1 signal, print stats */
203         if (signum == SIGUSR1) {
204                 print_stats();
205         }
206
207         /* When we receive a USR2 signal, reset stats */
208         if (signum == SIGUSR2) {
209                 memset(&lcore_stats, 0, sizeof(lcore_stats));
210                 printf("\n**Statistics have been reset**\n");
211                 return;
212         }
213 }
214
215 /*
216  * Create a tap network interface, or use existing one with same name.
217  * If name[0]='\0' then a name is automatically assigned and returned in name.
218  */
219 static int tap_create(char *name)
220 {
221         struct ifreq ifr;
222         int fd, ret;
223
224         fd = open("/dev/net/tun", O_RDWR);
225         if (fd < 0)
226                 return fd;
227
228         memset(&ifr, 0, sizeof(ifr));
229
230         /* TAP device without packet information */
231         ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
232
233         if (name && *name)
234                 rte_snprintf(ifr.ifr_name, IFNAMSIZ, name);
235
236         ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
237         if (ret < 0) {
238                 close(fd);
239                 return ret;
240         }
241
242         if (name)
243                 rte_snprintf(name, IFNAMSIZ, ifr.ifr_name);
244
245         return fd;
246 }
247
248 /* Main processing loop */
249 static  __attribute__((noreturn)) int
250 main_loop(__attribute__((unused)) void *arg)
251 {
252         const unsigned lcore_id = rte_lcore_id();
253         char tap_name[IFNAMSIZ];
254         int tap_fd;
255
256         /* Create new tap interface */
257         rte_snprintf(tap_name, IFNAMSIZ, "tap_dpdk_%.2u", lcore_id);
258         tap_fd = tap_create(tap_name);
259         if (tap_fd < 0)
260                 FATAL_ERROR("Could not create tap interface \"%s\" (%d)",
261                             tap_name, tap_fd);
262
263         if ((1 << lcore_id) & input_cores_mask) {
264                 PRINT_INFO("Lcore %u is reading from port %u and writing to %s",
265                            lcore_id, (unsigned)port_ids[lcore_id], tap_name);
266                 fflush(stdout);
267                 /* Loop forever reading from NIC and writing to tap */
268                 for (;;) {
269                         struct rte_mbuf *pkts_burst[PKT_BURST_SZ];
270                         unsigned i;
271                         const unsigned nb_rx =
272                                         rte_eth_rx_burst(port_ids[lcore_id], 0,
273                                             pkts_burst, PKT_BURST_SZ);
274                         lcore_stats[lcore_id].rx += nb_rx;
275                         for (i = 0; likely(i < nb_rx); i++) {
276                                 struct rte_mbuf *m = pkts_burst[i];
277                                 /* Ignore return val from write() */
278                                 int ret = write(tap_fd,
279                                                 rte_pktmbuf_mtod(m, void*),
280                                                 rte_pktmbuf_data_len(m));
281                                 rte_pktmbuf_free(m);
282                                 if (unlikely(ret < 0))
283                                         lcore_stats[lcore_id].dropped++;
284                                 else
285                                         lcore_stats[lcore_id].tx++;
286                         }
287                 }
288         }
289         else if ((1 << lcore_id) & output_cores_mask) {
290                 PRINT_INFO("Lcore %u is reading from %s and writing to port %u",
291                            lcore_id, tap_name, (unsigned)port_ids[lcore_id]);
292                 fflush(stdout);
293                 /* Loop forever reading from tap and writing to NIC */
294                 for (;;) {
295                         int ret;
296                         struct rte_mbuf *m = rte_pktmbuf_alloc(pktmbuf_pool);
297                         if (m == NULL)
298                                 continue;
299
300                         ret = read(tap_fd, m->pkt.data, MAX_PACKET_SZ);
301                         lcore_stats[lcore_id].rx++;
302                         if (unlikely(ret < 0)) {
303                                 FATAL_ERROR("Reading from %s interface failed",
304                                             tap_name);
305                         }
306                         m->pkt.nb_segs = 1;
307                         m->pkt.next = NULL;
308                         m->pkt.pkt_len = (uint16_t)ret;
309                         m->pkt.data_len = (uint16_t)ret;
310                         ret = rte_eth_tx_burst(port_ids[lcore_id], 0, &m, 1);
311                         if (unlikely(ret < 1)) {
312                                 rte_pktmbuf_free(m);
313                                 lcore_stats[lcore_id].dropped++;
314                         }
315                         else {
316                                 lcore_stats[lcore_id].tx++;
317                         }
318                 }
319         }
320         else {
321                 PRINT_INFO("Lcore %u has nothing to do", lcore_id);
322                 for (;;)
323                         ; /* loop doing nothing */
324         }
325         /*
326          * Tap file is closed automatically when program exits. Putting close()
327          * here will cause the compiler to give an error about unreachable code.
328          */
329 }
330
331 /* Display usage instructions */
332 static void
333 print_usage(const char *prgname)
334 {
335         PRINT_INFO("\nUsage: %s [EAL options] -- -p PORTMASK -i IN_CORES -o OUT_CORES\n"
336                    "    -p PORTMASK: hex bitmask of ports to use\n"
337                    "    -i IN_CORES: hex bitmask of cores which read from NIC\n"
338                    "    -o OUT_CORES: hex bitmask of cores which write to NIC",
339                    prgname);
340 }
341
342 /* Convert string to unsigned number. 0 is returned if error occurs */
343 static uint32_t
344 parse_unsigned(const char *portmask)
345 {
346         char *end = NULL;
347         unsigned long num;
348
349         num = strtoul(portmask, &end, 16);
350         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
351                 return 0;
352
353         return (uint32_t)num;
354 }
355
356 /* Record affinities between ports and lcores in global port_ids[] array */
357 static void
358 setup_port_lcore_affinities(void)
359 {
360         unsigned i;
361         uint8_t tx_port = 0;
362         uint8_t rx_port = 0;
363
364         /* Setup port_ids[] array, and check masks were ok */
365         RTE_LCORE_FOREACH(i) {
366                 if (input_cores_mask & (1 << i)) {
367                         /* Skip ports that are not enabled */
368                         while ((ports_mask & (1 << rx_port)) == 0) {
369                                 rx_port++;
370                                 if (rx_port > (sizeof(ports_mask) * 8))
371                                         goto fail; /* not enough ports */
372                         }
373
374                         port_ids[i] = rx_port++;
375                 }
376                 else if (output_cores_mask & (1 << i)) {
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(uint8_t port)
447 {
448         struct rte_eth_link link;
449         int ret;
450
451         /* Initialise device and RX/TX queues */
452         PRINT_INFO("Initialising port %u ...", (unsigned)port);
453         fflush(stdout);
454         ret = rte_eth_dev_configure(port, 1, 1, &port_conf);
455         if (ret < 0)
456                 FATAL_ERROR("Could not configure port%u (%d)",
457                             (unsigned)port, ret);
458
459         ret = rte_eth_rx_queue_setup(port, 0, NB_RXD, SOCKET, &rx_conf,
460                                      pktmbuf_pool);
461         if (ret < 0)
462                 FATAL_ERROR("Could not setup up RX queue for port%u (%d)",
463                             (unsigned)port, ret);
464
465         ret = rte_eth_tx_queue_setup(port, 0, NB_TXD, SOCKET, &tx_conf);
466         if (ret < 0)
467                 FATAL_ERROR("Could not setup up TX queue for port%u (%d)",
468                             (unsigned)port, ret);
469
470         ret = rte_eth_dev_start(port);
471         if (ret < 0)
472                 FATAL_ERROR("Could not start port%u (%d)", (unsigned)port, ret);
473
474         /*  Everything is setup and started, print link status */
475         rte_eth_link_get(port, &link);
476         if (link.link_status)
477                 PRINT_INFO("    link up - %u Mbit/s - %s",
478                            (unsigned)link.link_speed,
479                            (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
480                            ("full-duplex") : ("half-duplex"));
481         else
482                 PRINT_INFO("    link down");
483
484         rte_eth_promiscuous_enable(port);
485 }
486
487 /* Initialise ports/queues etc. and start main loop on each core */
488 int
489 main(int argc, char** argv)
490 {
491         int ret;
492         unsigned i,high_port;
493         uint8_t nb_sys_ports, port;
494
495         /* Associate signal_hanlder function with USR signals */
496         signal(SIGUSR1, signal_handler);
497         signal(SIGUSR2, signal_handler);
498
499         /* Initialise EAL */
500         ret = rte_eal_init(argc, argv);
501         if (ret < 0)
502                 FATAL_ERROR("Could not initialise EAL (%d)", ret);
503         argc -= ret;
504         argv += ret;
505
506         /* Parse application arguments (after the EAL ones) */
507         parse_args(argc, argv);
508
509         /* Create the mbuf pool */
510         pktmbuf_pool = rte_mempool_create("mbuf_pool", NB_MBUF, MBUF_SZ,
511                         MEMPOOL_CACHE_SZ,
512                         sizeof(struct rte_pktmbuf_pool_private),
513                         rte_pktmbuf_pool_init, NULL, rte_pktmbuf_init, NULL,
514                         SOCKET, 0);
515         if (pktmbuf_pool == NULL) {
516                 FATAL_ERROR("Could not initialise mbuf pool");
517                 return -1;
518         }
519
520         /* Initialise PMD driver(s) */
521 #ifdef RTE_LIBRTE_IGB_PMD
522         ret = rte_igb_pmd_init();
523         if (ret < 0)
524                 FATAL_ERROR("Could not initialise igb PMD (%d)", ret);
525 #endif
526 #ifdef RTE_LIBRTE_IXGBE_PMD
527         ret = rte_ixgbe_pmd_init();
528         if (ret < 0)
529                 FATAL_ERROR("Could not initialise ixgbe PMD (%d)", ret);
530 #endif
531
532         /* Scan PCI bus for recognised devices */
533         ret = rte_eal_pci_probe();
534         if (ret < 0)
535                 FATAL_ERROR("Could not probe PCI (%d)", ret);
536
537         /* Get number of ports found in scan */
538         nb_sys_ports = rte_eth_dev_count();
539         if (nb_sys_ports == 0)
540                 FATAL_ERROR("No supported Ethernet devices found - check that "
541                             "CONFIG_RTE_LIBRTE_IGB_PMD=y and/or "
542                             "CONFIG_RTE_LIBRTE_IXGBE_PMD=y in the config file");
543         /* Find highest port set in portmask */
544         for (high_port = (sizeof(ports_mask) * 8) - 1;
545                         (high_port != 0) && !(ports_mask & (1 << high_port));
546                         high_port--)
547                 ; /* empty body */
548         if (high_port > nb_sys_ports)
549                 FATAL_ERROR("Port mask requires more ports than available");
550
551         /* Initialise each port */
552         for (port = 0; port < nb_sys_ports; port++) {
553                 /* Skip ports that are not enabled */
554                 if ((ports_mask & (1 << port)) == 0) {
555                         continue;
556                 }
557                 init_port(port);
558         }
559
560         /* Launch per-lcore function on every lcore */
561         rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
562         RTE_LCORE_FOREACH_SLAVE(i) {
563                 if (rte_eal_wait_lcore(i) < 0)
564                         return -1;
565         }
566
567         return 0;
568 }