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