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