update copyright date to 2013
[dpdk.git] / examples / exception_path / main.c
1 /*-
2  *   BSD LICENSE
3  * 
4  *   Copyright(c) 2010-2013 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 #include <rte_cycles.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                 .mq_mode = ETH_DCB_NONE,
153         },
154 };
155
156 /* Mempool for mbufs */
157 static struct rte_mempool * pktmbuf_pool = NULL;
158
159 /* Mask of enabled ports */
160 static uint32_t ports_mask = 0;
161
162 /* Mask of cores that read from NIC and write to tap */
163 static uint32_t input_cores_mask = 0;
164
165 /* Mask of cores that read from tap and write to NIC */
166 static uint32_t output_cores_mask = 0;
167
168 /* Array storing port_id that is associated with each lcore */
169 static uint8_t port_ids[RTE_MAX_LCORE];
170
171 /* Structure type for recording lcore-specific stats */
172 struct stats {
173         uint64_t rx;
174         uint64_t tx;
175         uint64_t dropped;
176 };
177
178 /* Array of lcore-specific stats */
179 static struct stats lcore_stats[RTE_MAX_LCORE];
180
181 /* Print out statistics on packets handled */
182 static void
183 print_stats(void)
184 {
185         unsigned i;
186
187         printf("\n**Exception-Path example application statistics**\n"
188                "=======  ======  ============  ============  ===============\n"
189                " Lcore    Port            RX            TX    Dropped on TX\n"
190                "-------  ------  ------------  ------------  ---------------\n");
191         RTE_LCORE_FOREACH(i) {
192                 printf("%6u %7u %13"PRIu64" %13"PRIu64" %16"PRIu64"\n",
193                        i, (unsigned)port_ids[i],
194                        lcore_stats[i].rx, lcore_stats[i].tx,
195                        lcore_stats[i].dropped);
196         }
197         printf("=======  ======  ============  ============  ===============\n");
198 }
199
200 /* Custom handling of signals to handle stats */
201 static void
202 signal_handler(int signum)
203 {
204         /* When we receive a USR1 signal, print stats */
205         if (signum == SIGUSR1) {
206                 print_stats();
207         }
208
209         /* When we receive a USR2 signal, reset stats */
210         if (signum == SIGUSR2) {
211                 memset(&lcore_stats, 0, sizeof(lcore_stats));
212                 printf("\n**Statistics have been reset**\n");
213                 return;
214         }
215 }
216
217 /*
218  * Create a tap network interface, or use existing one with same name.
219  * If name[0]='\0' then a name is automatically assigned and returned in name.
220  */
221 static int tap_create(char *name)
222 {
223         struct ifreq ifr;
224         int fd, ret;
225
226         fd = open("/dev/net/tun", O_RDWR);
227         if (fd < 0)
228                 return fd;
229
230         memset(&ifr, 0, sizeof(ifr));
231
232         /* TAP device without packet information */
233         ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
234
235         if (name && *name)
236                 rte_snprintf(ifr.ifr_name, IFNAMSIZ, name);
237
238         ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
239         if (ret < 0) {
240                 close(fd);
241                 return ret;
242         }
243
244         if (name)
245                 rte_snprintf(name, IFNAMSIZ, ifr.ifr_name);
246
247         return fd;
248 }
249
250 /* Main processing loop */
251 static  __attribute__((noreturn)) int
252 main_loop(__attribute__((unused)) void *arg)
253 {
254         const unsigned lcore_id = rte_lcore_id();
255         char tap_name[IFNAMSIZ];
256         int tap_fd;
257
258         /* Create new tap interface */
259         rte_snprintf(tap_name, IFNAMSIZ, "tap_dpdk_%.2u", lcore_id);
260         tap_fd = tap_create(tap_name);
261         if (tap_fd < 0)
262                 FATAL_ERROR("Could not create tap interface \"%s\" (%d)",
263                             tap_name, tap_fd);
264
265         if ((1 << lcore_id) & input_cores_mask) {
266                 PRINT_INFO("Lcore %u is reading from port %u and writing to %s",
267                            lcore_id, (unsigned)port_ids[lcore_id], tap_name);
268                 fflush(stdout);
269                 /* Loop forever reading from NIC and writing to tap */
270                 for (;;) {
271                         struct rte_mbuf *pkts_burst[PKT_BURST_SZ];
272                         unsigned i;
273                         const unsigned nb_rx =
274                                         rte_eth_rx_burst(port_ids[lcore_id], 0,
275                                             pkts_burst, PKT_BURST_SZ);
276                         lcore_stats[lcore_id].rx += nb_rx;
277                         for (i = 0; likely(i < nb_rx); i++) {
278                                 struct rte_mbuf *m = pkts_burst[i];
279                                 /* Ignore return val from write() */
280                                 int ret = write(tap_fd,
281                                                 rte_pktmbuf_mtod(m, void*),
282                                                 rte_pktmbuf_data_len(m));
283                                 rte_pktmbuf_free(m);
284                                 if (unlikely(ret < 0))
285                                         lcore_stats[lcore_id].dropped++;
286                                 else
287                                         lcore_stats[lcore_id].tx++;
288                         }
289                 }
290         }
291         else if ((1 << lcore_id) & output_cores_mask) {
292                 PRINT_INFO("Lcore %u is reading from %s and writing to port %u",
293                            lcore_id, tap_name, (unsigned)port_ids[lcore_id]);
294                 fflush(stdout);
295                 /* Loop forever reading from tap and writing to NIC */
296                 for (;;) {
297                         int ret;
298                         struct rte_mbuf *m = rte_pktmbuf_alloc(pktmbuf_pool);
299                         if (m == NULL)
300                                 continue;
301
302                         ret = read(tap_fd, m->pkt.data, MAX_PACKET_SZ);
303                         lcore_stats[lcore_id].rx++;
304                         if (unlikely(ret < 0)) {
305                                 FATAL_ERROR("Reading from %s interface failed",
306                                             tap_name);
307                         }
308                         m->pkt.nb_segs = 1;
309                         m->pkt.next = NULL;
310                         m->pkt.pkt_len = (uint16_t)ret;
311                         m->pkt.data_len = (uint16_t)ret;
312                         ret = rte_eth_tx_burst(port_ids[lcore_id], 0, &m, 1);
313                         if (unlikely(ret < 1)) {
314                                 rte_pktmbuf_free(m);
315                                 lcore_stats[lcore_id].dropped++;
316                         }
317                         else {
318                                 lcore_stats[lcore_id].tx++;
319                         }
320                 }
321         }
322         else {
323                 PRINT_INFO("Lcore %u has nothing to do", lcore_id);
324                 for (;;)
325                         ; /* loop doing nothing */
326         }
327         /*
328          * Tap file is closed automatically when program exits. Putting close()
329          * here will cause the compiler to give an error about unreachable code.
330          */
331 }
332
333 /* Display usage instructions */
334 static void
335 print_usage(const char *prgname)
336 {
337         PRINT_INFO("\nUsage: %s [EAL options] -- -p PORTMASK -i IN_CORES -o OUT_CORES\n"
338                    "    -p PORTMASK: hex bitmask of ports to use\n"
339                    "    -i IN_CORES: hex bitmask of cores which read from NIC\n"
340                    "    -o OUT_CORES: hex bitmask of cores which write to NIC",
341                    prgname);
342 }
343
344 /* Convert string to unsigned number. 0 is returned if error occurs */
345 static uint32_t
346 parse_unsigned(const char *portmask)
347 {
348         char *end = NULL;
349         unsigned long num;
350
351         num = strtoul(portmask, &end, 16);
352         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
353                 return 0;
354
355         return (uint32_t)num;
356 }
357
358 /* Record affinities between ports and lcores in global port_ids[] array */
359 static void
360 setup_port_lcore_affinities(void)
361 {
362         unsigned i;
363         uint8_t tx_port = 0;
364         uint8_t rx_port = 0;
365
366         /* Setup port_ids[] array, and check masks were ok */
367         RTE_LCORE_FOREACH(i) {
368                 if (input_cores_mask & (1 << i)) {
369                         /* Skip ports that are not enabled */
370                         while ((ports_mask & (1 << rx_port)) == 0) {
371                                 rx_port++;
372                                 if (rx_port > (sizeof(ports_mask) * 8))
373                                         goto fail; /* not enough ports */
374                         }
375
376                         port_ids[i] = rx_port++;
377                 }
378                 else if (output_cores_mask & (1 << i)) {
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
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         rte_eth_promiscuous_enable(port);
476 }
477
478 /* Check the link status of all ports in up to 9s, and print them finally */
479 static void
480 check_all_ports_link_status(uint8_t port_num, uint32_t port_mask)
481 {
482 #define CHECK_INTERVAL 100 /* 100ms */
483 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
484         uint8_t portid, count, all_ports_up, print_flag = 0;
485         struct rte_eth_link link;
486
487         printf("\nChecking link status");
488         fflush(stdout);
489         for (count = 0; count <= MAX_CHECK_TIME; count++) {
490                 all_ports_up = 1;
491                 for (portid = 0; portid < port_num; portid++) {
492                         if ((port_mask & (1 << portid)) == 0)
493                                 continue;
494                         memset(&link, 0, sizeof(link));
495                         rte_eth_link_get_nowait(portid, &link);
496                         /* print link status if flag set */
497                         if (print_flag == 1) {
498                                 if (link.link_status)
499                                         printf("Port %d Link Up - speed %u "
500                                                 "Mbps - %s\n", (uint8_t)portid,
501                                                 (unsigned)link.link_speed,
502                                 (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
503                                         ("full-duplex") : ("half-duplex\n"));
504                                 else
505                                         printf("Port %d Link Down\n",
506                                                 (uint8_t)portid);
507                                 continue;
508                         }
509                         /* clear all_ports_up flag if any link down */
510                         if (link.link_status == 0) {
511                                 all_ports_up = 0;
512                                 break;
513                         }
514                 }
515                 /* after finally printing all link status, get out */
516                 if (print_flag == 1)
517                         break;
518
519                 if (all_ports_up == 0) {
520                         printf(".");
521                         fflush(stdout);
522                         rte_delay_ms(CHECK_INTERVAL);
523                 }
524
525                 /* set the print_flag if all ports up or timeout */
526                 if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
527                         print_flag = 1;
528                         printf("done\n");
529                 }
530         }
531 }
532
533 /* Initialise ports/queues etc. and start main loop on each core */
534 int
535 main(int argc, char** argv)
536 {
537         int ret;
538         unsigned i,high_port;
539         uint8_t nb_sys_ports, port;
540
541         /* Associate signal_hanlder function with USR signals */
542         signal(SIGUSR1, signal_handler);
543         signal(SIGUSR2, signal_handler);
544
545         /* Initialise EAL */
546         ret = rte_eal_init(argc, argv);
547         if (ret < 0)
548                 FATAL_ERROR("Could not initialise EAL (%d)", ret);
549         argc -= ret;
550         argv += ret;
551
552         /* Parse application arguments (after the EAL ones) */
553         parse_args(argc, argv);
554
555         /* Create the mbuf pool */
556         pktmbuf_pool = rte_mempool_create("mbuf_pool", NB_MBUF, MBUF_SZ,
557                         MEMPOOL_CACHE_SZ,
558                         sizeof(struct rte_pktmbuf_pool_private),
559                         rte_pktmbuf_pool_init, NULL, rte_pktmbuf_init, NULL,
560                         SOCKET, 0);
561         if (pktmbuf_pool == NULL) {
562                 FATAL_ERROR("Could not initialise mbuf pool");
563                 return -1;
564         }
565
566         /* Initialise PMD driver(s) */
567         ret = rte_pmd_init_all();
568         if (ret < 0)
569                 FATAL_ERROR("Could not probe PMD (%d)", ret);
570
571         /* Scan PCI bus for recognised devices */
572         ret = rte_eal_pci_probe();
573         if (ret < 0)
574                 FATAL_ERROR("Could not probe PCI (%d)", ret);
575
576         /* Get number of ports found in scan */
577         nb_sys_ports = rte_eth_dev_count();
578         if (nb_sys_ports == 0)
579                 FATAL_ERROR("No supported Ethernet devices found - check that "
580                             "CONFIG_RTE_LIBRTE_IGB_PMD=y and/or "
581                             "CONFIG_RTE_LIBRTE_IXGBE_PMD=y in the config file");
582         /* Find highest port set in portmask */
583         for (high_port = (sizeof(ports_mask) * 8) - 1;
584                         (high_port != 0) && !(ports_mask & (1 << high_port));
585                         high_port--)
586                 ; /* empty body */
587         if (high_port > nb_sys_ports)
588                 FATAL_ERROR("Port mask requires more ports than available");
589
590         /* Initialise each port */
591         for (port = 0; port < nb_sys_ports; port++) {
592                 /* Skip ports that are not enabled */
593                 if ((ports_mask & (1 << port)) == 0) {
594                         continue;
595                 }
596                 init_port(port);
597         }
598         check_all_ports_link_status(nb_sys_ports, ports_mask);
599
600         /* Launch per-lcore function on every lcore */
601         rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
602         RTE_LCORE_FOREACH_SLAVE(i) {
603                 if (rte_eal_wait_lcore(i) < 0)
604                         return -1;
605         }
606
607         return 0;
608 }