examples: no more bare metal environment
[dpdk.git] / examples / distributor / main.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 #include <stdint.h>
35 #include <inttypes.h>
36 #include <unistd.h>
37 #include <signal.h>
38 #include <getopt.h>
39
40 #include <rte_eal.h>
41 #include <rte_ethdev.h>
42 #include <rte_cycles.h>
43 #include <rte_malloc.h>
44 #include <rte_debug.h>
45 #include <rte_distributor.h>
46
47 #define RX_RING_SIZE 256
48 #define TX_RING_SIZE 512
49 #define NUM_MBUFS ((64*1024)-1)
50 #define MBUF_SIZE (2048 + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
51 #define MBUF_CACHE_SIZE 250
52 #define BURST_SIZE 32
53 #define RTE_RING_SZ 1024
54
55 /* uncommnet below line to enable debug logs */
56 /* #define DEBUG */
57
58 #ifdef DEBUG
59 #define LOG_LEVEL RTE_LOG_DEBUG
60 #define LOG_DEBUG(log_type, fmt, args...) do {  \
61         RTE_LOG(DEBUG, log_type, fmt, ##args)           \
62 } while (0)
63 #else
64 #define LOG_LEVEL RTE_LOG_INFO
65 #define LOG_DEBUG(log_type, fmt, args...) do {} while (0)
66 #endif
67
68 #define RTE_LOGTYPE_DISTRAPP RTE_LOGTYPE_USER1
69
70 /* mask of enabled ports */
71 static uint32_t enabled_port_mask;
72 volatile uint8_t quit_signal;
73 volatile uint8_t quit_signal_rx;
74
75 static volatile struct app_stats {
76         struct {
77                 uint64_t rx_pkts;
78                 uint64_t returned_pkts;
79                 uint64_t enqueued_pkts;
80         } rx __rte_cache_aligned;
81
82         struct {
83                 uint64_t dequeue_pkts;
84                 uint64_t tx_pkts;
85         } tx __rte_cache_aligned;
86 } app_stats;
87
88 static const struct rte_eth_conf port_conf_default = {
89         .rxmode = {
90                 .mq_mode = ETH_MQ_RX_RSS,
91                 .max_rx_pkt_len = ETHER_MAX_LEN,
92         },
93         .txmode = {
94                 .mq_mode = ETH_MQ_TX_NONE,
95         },
96         .rx_adv_conf = {
97                         .rss_conf = {
98                                 .rss_hf = ETH_RSS_IPV4 | ETH_RSS_IPV6 |
99                                         ETH_RSS_IPV4_TCP | ETH_RSS_IPV4_UDP |
100                                         ETH_RSS_IPV6_TCP | ETH_RSS_IPV6_UDP,
101                         }
102         },
103 };
104
105 struct output_buffer {
106         unsigned count;
107         struct rte_mbuf *mbufs[BURST_SIZE];
108 };
109
110 /*
111  * Initialises a given port using global settings and with the rx buffers
112  * coming from the mbuf_pool passed as parameter
113  */
114 static inline int
115 port_init(uint8_t port, struct rte_mempool *mbuf_pool)
116 {
117         struct rte_eth_conf port_conf = port_conf_default;
118         const uint16_t rxRings = 1, txRings = rte_lcore_count() - 1;
119         int retval;
120         uint16_t q;
121
122         if (port >= rte_eth_dev_count())
123                 return -1;
124
125         retval = rte_eth_dev_configure(port, rxRings, txRings, &port_conf);
126         if (retval != 0)
127                 return retval;
128
129         for (q = 0; q < rxRings; q++) {
130                 retval = rte_eth_rx_queue_setup(port, q, RX_RING_SIZE,
131                                                 rte_eth_dev_socket_id(port),
132                                                 NULL, mbuf_pool);
133                 if (retval < 0)
134                         return retval;
135         }
136
137         for (q = 0; q < txRings; q++) {
138                 retval = rte_eth_tx_queue_setup(port, q, TX_RING_SIZE,
139                                                 rte_eth_dev_socket_id(port),
140                                                 NULL);
141                 if (retval < 0)
142                         return retval;
143         }
144
145         retval = rte_eth_dev_start(port);
146         if (retval < 0)
147                 return retval;
148
149         struct rte_eth_link link;
150         rte_eth_link_get_nowait(port, &link);
151         if (!link.link_status) {
152                 sleep(1);
153                 rte_eth_link_get_nowait(port, &link);
154         }
155
156         if (!link.link_status) {
157                 printf("Link down on port %"PRIu8"\n", port);
158                 return 0;
159         }
160
161         struct ether_addr addr;
162         rte_eth_macaddr_get(port, &addr);
163         printf("Port %u MAC: %02"PRIx8" %02"PRIx8" %02"PRIx8
164                         " %02"PRIx8" %02"PRIx8" %02"PRIx8"\n",
165                         (unsigned)port,
166                         addr.addr_bytes[0], addr.addr_bytes[1],
167                         addr.addr_bytes[2], addr.addr_bytes[3],
168                         addr.addr_bytes[4], addr.addr_bytes[5]);
169
170         rte_eth_promiscuous_enable(port);
171
172         return 0;
173 }
174
175 struct lcore_params {
176         unsigned worker_id;
177         struct rte_distributor *d;
178         struct rte_ring *r;
179         struct rte_mempool *mem_pool;
180 };
181
182 static void
183 quit_workers(struct rte_distributor *d, struct rte_mempool *p)
184 {
185         const unsigned num_workers = rte_lcore_count() - 2;
186         unsigned i;
187         struct rte_mbuf *bufs[num_workers];
188         rte_mempool_get_bulk(p, (void *)bufs, num_workers);
189
190         for (i = 0; i < num_workers; i++)
191                 bufs[i]->hash.rss = i << 1;
192
193         rte_distributor_process(d, bufs, num_workers);
194         rte_mempool_put_bulk(p, (void *)bufs, num_workers);
195 }
196
197 static int
198 lcore_rx(struct lcore_params *p)
199 {
200         struct rte_distributor *d = p->d;
201         struct rte_mempool *mem_pool = p->mem_pool;
202         struct rte_ring *r = p->r;
203         const uint8_t nb_ports = rte_eth_dev_count();
204         const int socket_id = rte_socket_id();
205         uint8_t port;
206
207         for (port = 0; port < nb_ports; port++) {
208                 /* skip ports that are not enabled */
209                 if ((enabled_port_mask & (1 << port)) == 0)
210                         continue;
211
212                 if (rte_eth_dev_socket_id(port) > 0 &&
213                                 rte_eth_dev_socket_id(port) != socket_id)
214                         printf("WARNING, port %u is on remote NUMA node to "
215                                         "RX thread.\n\tPerformance will not "
216                                         "be optimal.\n", port);
217         }
218
219         printf("\nCore %u doing packet RX.\n", rte_lcore_id());
220         port = 0;
221         while (!quit_signal_rx) {
222
223                 /* skip ports that are not enabled */
224                 if ((enabled_port_mask & (1 << port)) == 0) {
225                         if (++port == nb_ports)
226                                 port = 0;
227                         continue;
228                 }
229                 struct rte_mbuf *bufs[BURST_SIZE*2];
230                 const uint16_t nb_rx = rte_eth_rx_burst(port, 0, bufs,
231                                 BURST_SIZE);
232                 app_stats.rx.rx_pkts += nb_rx;
233
234                 rte_distributor_process(d, bufs, nb_rx);
235                 const uint16_t nb_ret = rte_distributor_returned_pkts(d,
236                                 bufs, BURST_SIZE*2);
237                 app_stats.rx.returned_pkts += nb_ret;
238                 if (unlikely(nb_ret == 0))
239                         continue;
240
241                 uint16_t sent = rte_ring_enqueue_burst(r, (void *)bufs, nb_ret);
242                 app_stats.rx.enqueued_pkts += sent;
243                 if (unlikely(sent < nb_ret)) {
244                         LOG_DEBUG(DISTRAPP, "%s:Packet loss due to full ring\n", __func__);
245                         while (sent < nb_ret)
246                                 rte_pktmbuf_free(bufs[sent++]);
247                 }
248                 if (++port == nb_ports)
249                         port = 0;
250         }
251         rte_distributor_process(d, NULL, 0);
252         /* flush distributor to bring to known state */
253         rte_distributor_flush(d);
254         /* set worker & tx threads quit flag */
255         quit_signal = 1;
256         /*
257          * worker threads may hang in get packet as
258          * distributor process is not running, just make sure workers
259          * get packets till quit_signal is actually been
260          * received and they gracefully shutdown
261          */
262         quit_workers(d, mem_pool);
263         /* rx thread should quit at last */
264         return 0;
265 }
266
267 static inline void
268 flush_one_port(struct output_buffer *outbuf, uint8_t outp)
269 {
270         unsigned nb_tx = rte_eth_tx_burst(outp, 0, outbuf->mbufs,
271                         outbuf->count);
272         app_stats.tx.tx_pkts += nb_tx;
273
274         if (unlikely(nb_tx < outbuf->count)) {
275                 LOG_DEBUG(DISTRAPP, "%s:Packet loss with tx_burst\n", __func__);
276                 do {
277                         rte_pktmbuf_free(outbuf->mbufs[nb_tx]);
278                 } while (++nb_tx < outbuf->count);
279         }
280         outbuf->count = 0;
281 }
282
283 static inline void
284 flush_all_ports(struct output_buffer *tx_buffers, uint8_t nb_ports)
285 {
286         uint8_t outp;
287         for (outp = 0; outp < nb_ports; outp++) {
288                 /* skip ports that are not enabled */
289                 if ((enabled_port_mask & (1 << outp)) == 0)
290                         continue;
291
292                 if (tx_buffers[outp].count == 0)
293                         continue;
294
295                 flush_one_port(&tx_buffers[outp], outp);
296         }
297 }
298
299 static int
300 lcore_tx(struct rte_ring *in_r)
301 {
302         static struct output_buffer tx_buffers[RTE_MAX_ETHPORTS];
303         const uint8_t nb_ports = rte_eth_dev_count();
304         const int socket_id = rte_socket_id();
305         uint8_t port;
306
307         for (port = 0; port < nb_ports; port++) {
308                 /* skip ports that are not enabled */
309                 if ((enabled_port_mask & (1 << port)) == 0)
310                         continue;
311
312                 if (rte_eth_dev_socket_id(port) > 0 &&
313                                 rte_eth_dev_socket_id(port) != socket_id)
314                         printf("WARNING, port %u is on remote NUMA node to "
315                                         "TX thread.\n\tPerformance will not "
316                                         "be optimal.\n", port);
317         }
318
319         printf("\nCore %u doing packet TX.\n", rte_lcore_id());
320         while (!quit_signal) {
321
322                 for (port = 0; port < nb_ports; port++) {
323                         /* skip ports that are not enabled */
324                         if ((enabled_port_mask & (1 << port)) == 0)
325                                 continue;
326
327                         struct rte_mbuf *bufs[BURST_SIZE];
328                         const uint16_t nb_rx = rte_ring_dequeue_burst(in_r,
329                                         (void *)bufs, BURST_SIZE);
330                         app_stats.tx.dequeue_pkts += nb_rx;
331
332                         /* if we get no traffic, flush anything we have */
333                         if (unlikely(nb_rx == 0)) {
334                                 flush_all_ports(tx_buffers, nb_ports);
335                                 continue;
336                         }
337
338                         /* for traffic we receive, queue it up for transmit */
339                         uint16_t i;
340                         _mm_prefetch(bufs[0], 0);
341                         _mm_prefetch(bufs[1], 0);
342                         _mm_prefetch(bufs[2], 0);
343                         for (i = 0; i < nb_rx; i++) {
344                                 struct output_buffer *outbuf;
345                                 uint8_t outp;
346                                 _mm_prefetch(bufs[i + 3], 0);
347                                 /*
348                                  * workers should update in_port to hold the
349                                  * output port value
350                                  */
351                                 outp = bufs[i]->port;
352                                 /* skip ports that are not enabled */
353                                 if ((enabled_port_mask & (1 << outp)) == 0)
354                                         continue;
355
356                                 outbuf = &tx_buffers[outp];
357                                 outbuf->mbufs[outbuf->count++] = bufs[i];
358                                 if (outbuf->count == BURST_SIZE)
359                                         flush_one_port(outbuf, outp);
360                         }
361                 }
362         }
363         return 0;
364 }
365
366 static void
367 int_handler(int sig_num)
368 {
369         printf("Exiting on signal %d\n", sig_num);
370         /* set quit flag for rx thread to exit */
371         quit_signal_rx = 1;
372 }
373
374 static void
375 print_stats(void)
376 {
377         struct rte_eth_stats eth_stats;
378         unsigned i;
379
380         printf("\nRX thread stats:\n");
381         printf(" - Received:    %"PRIu64"\n", app_stats.rx.rx_pkts);
382         printf(" - Processed:   %"PRIu64"\n", app_stats.rx.returned_pkts);
383         printf(" - Enqueued:    %"PRIu64"\n", app_stats.rx.enqueued_pkts);
384
385         printf("\nTX thread stats:\n");
386         printf(" - Dequeued:    %"PRIu64"\n", app_stats.tx.dequeue_pkts);
387         printf(" - Transmitted: %"PRIu64"\n", app_stats.tx.tx_pkts);
388
389         for (i = 0; i < rte_eth_dev_count(); i++) {
390                 rte_eth_stats_get(i, &eth_stats);
391                 printf("\nPort %u stats:\n", i);
392                 printf(" - Pkts in:   %"PRIu64"\n", eth_stats.ipackets);
393                 printf(" - Pkts out:  %"PRIu64"\n", eth_stats.opackets);
394                 printf(" - In Errs:   %"PRIu64"\n", eth_stats.ierrors);
395                 printf(" - Out Errs:  %"PRIu64"\n", eth_stats.oerrors);
396                 printf(" - Mbuf Errs: %"PRIu64"\n", eth_stats.rx_nombuf);
397         }
398 }
399
400 static int
401 lcore_worker(struct lcore_params *p)
402 {
403         struct rte_distributor *d = p->d;
404         const unsigned id = p->worker_id;
405         /*
406          * for single port, xor_val will be zero so we won't modify the output
407          * port, otherwise we send traffic from 0 to 1, 2 to 3, and vice versa
408          */
409         const unsigned xor_val = (rte_eth_dev_count() > 1);
410         struct rte_mbuf *buf = NULL;
411
412         printf("\nCore %u acting as worker core.\n", rte_lcore_id());
413         while (!quit_signal) {
414                 buf = rte_distributor_get_pkt(d, id, buf);
415                 buf->port ^= xor_val;
416         }
417         return 0;
418 }
419
420 /* display usage */
421 static void
422 print_usage(const char *prgname)
423 {
424         printf("%s [EAL options] -- -p PORTMASK\n"
425                         "  -p PORTMASK: hexadecimal bitmask of ports to configure\n",
426                         prgname);
427 }
428
429 static int
430 parse_portmask(const char *portmask)
431 {
432         char *end = NULL;
433         unsigned long pm;
434
435         /* parse hexadecimal string */
436         pm = strtoul(portmask, &end, 16);
437         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
438                 return -1;
439
440         if (pm == 0)
441                 return -1;
442
443         return pm;
444 }
445
446 /* Parse the argument given in the command line of the application */
447 static int
448 parse_args(int argc, char **argv)
449 {
450         int opt;
451         char **argvopt;
452         int option_index;
453         char *prgname = argv[0];
454         static struct option lgopts[] = {
455                 {NULL, 0, 0, 0}
456         };
457
458         argvopt = argv;
459
460         while ((opt = getopt_long(argc, argvopt, "p:",
461                         lgopts, &option_index)) != EOF) {
462
463                 switch (opt) {
464                 /* portmask */
465                 case 'p':
466                         enabled_port_mask = parse_portmask(optarg);
467                         if (enabled_port_mask == 0) {
468                                 printf("invalid portmask\n");
469                                 print_usage(prgname);
470                                 return -1;
471                         }
472                         break;
473
474                 default:
475                         print_usage(prgname);
476                         return -1;
477                 }
478         }
479
480         if (optind <= 1) {
481                 print_usage(prgname);
482                 return -1;
483         }
484
485         argv[optind-1] = prgname;
486
487         optind = 0; /* reset getopt lib */
488         return 0;
489 }
490
491 /* Main function, does initialization and calls the per-lcore functions */
492 int
493 main(int argc, char *argv[])
494 {
495         struct rte_mempool *mbuf_pool;
496         struct rte_distributor *d;
497         struct rte_ring *output_ring;
498         unsigned lcore_id, worker_id = 0;
499         unsigned nb_ports;
500         uint8_t portid;
501         uint8_t nb_ports_available;
502
503         /* catch ctrl-c so we can print on exit */
504         signal(SIGINT, int_handler);
505
506         /* init EAL */
507         int ret = rte_eal_init(argc, argv);
508         if (ret < 0)
509                 rte_exit(EXIT_FAILURE, "Error with EAL initialization\n");
510         argc -= ret;
511         argv += ret;
512
513         /* parse application arguments (after the EAL ones) */
514         ret = parse_args(argc, argv);
515         if (ret < 0)
516                 rte_exit(EXIT_FAILURE, "Invalid distributor parameters\n");
517
518         if (rte_lcore_count() < 3)
519                 rte_exit(EXIT_FAILURE, "Error, This application needs at "
520                                 "least 3 logical cores to run:\n"
521                                 "1 lcore for packet RX and distribution\n"
522                                 "1 lcore for packet TX\n"
523                                 "and at least 1 lcore for worker threads\n");
524
525         nb_ports = rte_eth_dev_count();
526         if (nb_ports == 0)
527                 rte_exit(EXIT_FAILURE, "Error: no ethernet ports detected\n");
528         if (nb_ports != 1 && (nb_ports & 1))
529                 rte_exit(EXIT_FAILURE, "Error: number of ports must be even, except "
530                                 "when using a single port\n");
531
532         mbuf_pool = rte_mempool_create("MBUF_POOL", NUM_MBUFS * nb_ports,
533                         MBUF_SIZE, MBUF_CACHE_SIZE,
534                         sizeof(struct rte_pktmbuf_pool_private),
535                         rte_pktmbuf_pool_init, NULL,
536                         rte_pktmbuf_init, NULL,
537                         rte_socket_id(), 0);
538         if (mbuf_pool == NULL)
539                 rte_exit(EXIT_FAILURE, "Cannot create mbuf pool\n");
540         nb_ports_available = nb_ports;
541
542         /* initialize all ports */
543         for (portid = 0; portid < nb_ports; portid++) {
544                 /* skip ports that are not enabled */
545                 if ((enabled_port_mask & (1 << portid)) == 0) {
546                         printf("\nSkipping disabled port %d\n", portid);
547                         nb_ports_available--;
548                         continue;
549                 }
550                 /* init port */
551                 printf("Initializing port %u... done\n", (unsigned) portid);
552
553                 if (port_init(portid, mbuf_pool) != 0)
554                         rte_exit(EXIT_FAILURE, "Cannot initialize port %"PRIu8"\n",
555                                         portid);
556         }
557
558         if (!nb_ports_available) {
559                 rte_exit(EXIT_FAILURE,
560                                 "All available ports are disabled. Please set portmask.\n");
561         }
562
563         d = rte_distributor_create("PKT_DIST", rte_socket_id(),
564                         rte_lcore_count() - 2);
565         if (d == NULL)
566                 rte_exit(EXIT_FAILURE, "Cannot create distributor\n");
567
568         /*
569          * scheduler ring is read only by the transmitter core, but written to
570          * by multiple threads
571          */
572         output_ring = rte_ring_create("Output_ring", RTE_RING_SZ,
573                         rte_socket_id(), RING_F_SC_DEQ);
574         if (output_ring == NULL)
575                 rte_exit(EXIT_FAILURE, "Cannot create output ring\n");
576
577         RTE_LCORE_FOREACH_SLAVE(lcore_id) {
578                 if (worker_id == rte_lcore_count() - 2)
579                         rte_eal_remote_launch((lcore_function_t *)lcore_tx,
580                                         output_ring, lcore_id);
581                 else {
582                         struct lcore_params *p =
583                                         rte_malloc(NULL, sizeof(*p), 0);
584                         if (!p)
585                                 rte_panic("malloc failure\n");
586                         *p = (struct lcore_params){worker_id, d, output_ring, mbuf_pool};
587
588                         rte_eal_remote_launch((lcore_function_t *)lcore_worker,
589                                         p, lcore_id);
590                 }
591                 worker_id++;
592         }
593         /* call lcore_main on master core only */
594         struct lcore_params p = { 0, d, output_ring, mbuf_pool};
595         lcore_rx(&p);
596
597         RTE_LCORE_FOREACH_SLAVE(lcore_id) {
598                 if (rte_eal_wait_lcore(lcore_id) < 0)
599                         return -1;
600         }
601
602         print_stats();
603         return 0;
604 }