554c9e6b5614dd938b40b9f879e22d1ca3ab1ab3
[dpdk.git] / examples / multi_process / symmetric_mp / main.c
1 /*-
2  *   BSD LICENSE
3  * 
4  *   Copyright(c) 2010-2012 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  * 
7  *   Redistribution and use in source and binary forms, with or without 
8  *   modification, are permitted provided that the following conditions 
9  *   are met:
10  * 
11  *     * Redistributions of source code must retain the above copyright 
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright 
14  *       notice, this list of conditions and the following disclaimer in 
15  *       the documentation and/or other materials provided with the 
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its 
18  *       contributors may be used to endorse or promote products derived 
19  *       from this software without specific prior written permission.
20  * 
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  * 
33  */
34
35 /*
36  * Sample application demostrating how to do packet I/O in a multi-process
37  * environment. The same code can be run as a primary process and as a
38  * secondary process, just with a different proc-id parameter in each case
39  * (apart from the EAL flag to indicate a secondary process).
40  *
41  * Each process will read from the same ports, given by the port-mask
42  * parameter, which should be the same in each case, just using a different
43  * queue per port as determined by the proc-id parameter.
44  */
45
46 #include <stdio.h>
47 #include <string.h>
48 #include <stdint.h>
49 #include <stdlib.h>
50 #include <stdarg.h>
51 #include <errno.h>
52 #include <sys/queue.h>
53 #include <getopt.h>
54 #include <signal.h>
55 #include <inttypes.h>
56
57 #include <rte_common.h>
58 #include <rte_log.h>
59 #include <rte_memory.h>
60 #include <rte_memzone.h>
61 #include <rte_launch.h>
62 #include <rte_tailq.h>
63 #include <rte_eal.h>
64 #include <rte_per_lcore.h>
65 #include <rte_lcore.h>
66 #include <rte_debug.h>
67 #include <rte_atomic.h>
68 #include <rte_branch_prediction.h>
69 #include <rte_ring.h>
70 #include <rte_debug.h>
71 #include <rte_interrupts.h>
72 #include <rte_pci.h>
73 #include <rte_ether.h>
74 #include <rte_ethdev.h>
75 #include <rte_mempool.h>
76 #include <rte_memcpy.h>
77 #include <rte_mbuf.h>
78 #include <rte_string_fns.h>
79 #include <rte_cycles.h>
80
81 #define RTE_LOGTYPE_APP RTE_LOGTYPE_USER1
82
83 #define SOCKET0 0
84
85 #define MBUF_SIZE (2048 + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
86 #define NB_MBUFS 64*1024 /* use 64k mbufs */
87 #define MBUF_CACHE_SIZE 256
88 #define PKT_BURST 32
89 #define RX_RING_SIZE 128
90 #define TX_RING_SIZE 512
91
92 #define PARAM_PROC_ID "proc-id"
93 #define PARAM_NUM_PROCS "num-procs"
94
95 /*
96  * RX and TX Prefetch, Host, and Write-back threshold values should be
97  * carefully set for optimal performance. Consult the network
98  * controller's datasheet and supporting DPDK documentation for guidance
99  * on how these parameters should be set.
100  */
101 /* Default configuration for rx and tx thresholds etc. */
102 static const struct rte_eth_rxconf rx_conf_default = {
103         .rx_thresh = {
104                 .pthresh = 8,
105                 .hthresh = 8,
106                 .wthresh = 4,
107         },
108 };
109
110 /*
111  * These default values are optimized for use with the Intel(R) 82599 10 GbE
112  * Controller and the DPDK ixgbe PMD. Consider using other values for other
113  * network controllers and/or network drivers.
114  */
115 static const struct rte_eth_txconf tx_conf_default = {
116         .tx_thresh = {
117                 .pthresh = 36,
118                 .hthresh = 0,
119                 .wthresh = 0,
120         },
121         .tx_free_thresh = 0, /* Use PMD default values */
122         .tx_rs_thresh = 0, /* Use PMD default values */
123 };
124
125 /* for each lcore, record the elements of the ports array to use */
126 struct lcore_ports{
127         unsigned start_port;
128         unsigned num_ports;
129 };
130
131 /* structure to record the rx and tx packets. Put two per cache line as ports
132  * used in pairs */
133 struct port_stats{
134         unsigned rx;
135         unsigned tx;
136         unsigned drop;
137 } __attribute__((aligned(CACHE_LINE_SIZE / 2)));
138
139 static int proc_id = -1;
140 static unsigned num_procs = 0;
141
142 static uint8_t ports[RTE_MAX_ETHPORTS];
143 static unsigned num_ports = 0;
144
145 static struct lcore_ports lcore_ports[RTE_MAX_LCORE];
146 static struct port_stats pstats[RTE_MAX_ETHPORTS];
147
148 /* prints the usage statement and quits with an error message */
149 static void
150 smp_usage(const char *prgname, const char *errmsg)
151 {
152         printf("\nError: %s\n",errmsg);
153         printf("\n%s [EAL options] -- -p <port mask> "
154                         "--"PARAM_NUM_PROCS" <n>"
155                         " --"PARAM_PROC_ID" <id>\n"
156                         "-p         : a hex bitmask indicating what ports are to be used\n"
157                         "--num-procs: the number of processes which will be used\n"
158                         "--proc-id  : the id of the current process (id < num-procs)\n"
159                         "\n",
160                         prgname);
161         exit(1);
162 }
163
164
165 /* signal handler configured for SIGTERM and SIGINT to print stats on exit */
166 static void
167 print_stats(int signum)
168 {
169         unsigned i;
170         printf("\nExiting on signal %d\n\n", signum);
171         for (i = 0; i < num_ports; i++){
172                 const uint8_t p_num = ports[i];
173                 printf("Port %u: RX - %u, TX - %u, Drop - %u\n", (unsigned)p_num,
174                                 pstats[p_num].rx, pstats[p_num].tx, pstats[p_num].drop);
175         }
176         exit(0);
177 }
178
179 /* Parse the argument given in the command line of the application */
180 static int
181 smp_parse_args(int argc, char **argv)
182 {
183         int opt, ret;
184         char **argvopt;
185         int option_index;
186         unsigned i, port_mask = 0;
187         char *prgname = argv[0];
188         static struct option lgopts[] = {
189                         {PARAM_NUM_PROCS, 1, 0, 0},
190                         {PARAM_PROC_ID, 1, 0, 0},
191                         {NULL, 0, 0, 0}
192         };
193
194         argvopt = argv;
195
196         while ((opt = getopt_long(argc, argvopt, "p:", \
197                         lgopts, &option_index)) != EOF) {
198
199                 switch (opt) {
200                 case 'p':
201                         port_mask = strtoull(optarg, NULL, 16);
202                         break;
203                         /* long options */
204                 case 0:
205                         if (strncmp(lgopts[option_index].name, PARAM_NUM_PROCS, 8) == 0)
206                                 num_procs = atoi(optarg);
207                         else if (strncmp(lgopts[option_index].name, PARAM_PROC_ID, 7) == 0)
208                                 proc_id = atoi(optarg);
209                         break;
210
211                 default:
212                         smp_usage(prgname, "Cannot parse all command-line arguments\n");
213                 }
214         }
215
216         if (optind >= 0)
217                 argv[optind-1] = prgname;
218
219         if (proc_id < 0)
220                 smp_usage(prgname, "Invalid or missing proc-id parameter\n");
221         if (rte_eal_process_type() == RTE_PROC_PRIMARY && num_procs == 0)
222                 smp_usage(prgname, "Invalid or missing num-procs parameter\n");
223         if (port_mask == 0)
224                 smp_usage(prgname, "Invalid or missing port mask\n");
225
226         /* get the port numbers from the port mask */
227         for(i = 0; i < rte_eth_dev_count(); i++)
228                 if(port_mask & (1 << i))
229                         ports[num_ports++] = (uint8_t)i;
230
231         ret = optind-1;
232         optind = 0; /* reset getopt lib */
233
234         return (ret);
235 }
236
237 /*
238  * Initialises a given port using global settings and with the rx buffers
239  * coming from the mbuf_pool passed as parameter
240  */
241 static inline int
242 smp_port_init(uint8_t port, struct rte_mempool *mbuf_pool, uint16_t num_queues)
243 {
244         struct rte_eth_conf port_conf = {
245                         .rxmode = {
246                                 .mq_mode = ETH_RSS,
247                                 .split_hdr_size = 0,
248                                 .header_split   = 0, /**< Header Split disabled */
249                                 .hw_ip_checksum = 1, /**< IP checksum offload enabled */
250                                 .hw_vlan_filter = 0, /**< VLAN filtering disabled */
251                                 .jumbo_frame    = 0, /**< Jumbo Frame Support disabled */
252                                 .hw_strip_crc   = 0, /**< CRC stripped by hardware */
253                         },
254                         .rx_adv_conf = {
255                                 .rss_conf = {
256                                         .rss_key = NULL,
257                                         .rss_hf = ETH_RSS_IPV4 | ETH_RSS_IPV6,
258                                 },
259                         },
260                         .txmode = {
261                                 .mq_mode = ETH_DCB_NONE,
262                         }
263         };
264         const uint16_t rx_rings = num_queues, tx_rings = num_queues;
265         int retval;
266         uint16_t q;
267
268         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
269                 return 0;
270
271         if (port >= rte_eth_dev_count())
272                 return -1;
273
274         printf("# Initialising port %u... ", (unsigned)port);
275         fflush(stdout);
276
277         retval = rte_eth_dev_configure(port, rx_rings, tx_rings, &port_conf);
278         if (retval < 0)
279                 return retval;
280
281         for (q = 0; q < rx_rings; q ++) {
282                 retval = rte_eth_rx_queue_setup(port, q, RX_RING_SIZE,
283                                 SOCKET0, &rx_conf_default,
284                                 mbuf_pool);
285                 if (retval < 0)
286                         return retval;
287         }
288
289         for (q = 0; q < tx_rings; q ++) {
290                 retval = rte_eth_tx_queue_setup(port, q, RX_RING_SIZE,
291                                 SOCKET0, &tx_conf_default);
292                 if (retval < 0)
293                         return retval;
294         }
295
296         rte_eth_promiscuous_enable(port);
297
298         retval  = rte_eth_dev_start(port);
299         if (retval < 0)
300                 return retval;
301
302         return 0;
303 }
304
305 /* Goes through each of the lcores and calculates what ports should
306  * be used by that core. Fills in the global lcore_ports[] array.
307  */
308 static void
309 assign_ports_to_cores(void)
310 {
311
312         const unsigned lcores = rte_eal_get_configuration()->lcore_count;
313         const unsigned port_pairs = num_ports / 2;
314         const unsigned pairs_per_lcore = port_pairs / lcores;
315         unsigned extra_pairs = port_pairs % lcores;
316         unsigned ports_assigned = 0;
317         unsigned i;
318
319         RTE_LCORE_FOREACH(i) {
320                 lcore_ports[i].start_port = ports_assigned;
321                 lcore_ports[i].num_ports = pairs_per_lcore * 2;
322                 if (extra_pairs > 0) {
323                         lcore_ports[i].num_ports += 2;
324                         extra_pairs--;
325                 }
326                 ports_assigned += lcore_ports[i].num_ports;
327         }
328 }
329
330 /* Main function used by the processing threads.
331  * Prints out some configuration details for the thread and then begins
332  * performing packet RX and TX.
333  */
334 static int
335 lcore_main(void *arg __rte_unused)
336 {
337         const unsigned id = rte_lcore_id();
338         const unsigned start_port = lcore_ports[id].start_port;
339         const unsigned end_port = start_port + lcore_ports[id].num_ports;
340         const uint16_t q_id = (uint16_t)proc_id;
341         unsigned p, i;
342         char msgbuf[256];
343         int msgbufpos = 0;
344
345         if (start_port == end_port){
346                 printf("Lcore %u has nothing to do\n", id);
347                 return 0;
348         }
349
350         /* build up message in msgbuf before printing to decrease likelihood
351          * of multi-core message interleaving.
352          */
353         msgbufpos += rte_snprintf(msgbuf, sizeof(msgbuf) - msgbufpos,
354                         "Lcore %u using ports ", id);
355         for (p = start_port; p < end_port; p++){
356                 msgbufpos += rte_snprintf(msgbuf + msgbufpos, sizeof(msgbuf) - msgbufpos,
357                                 "%u ", (unsigned)ports[p]);
358         }
359         printf("%s\n", msgbuf);
360         printf("lcore %u using queue %u of each port\n", id, (unsigned)q_id);
361
362         /* handle packet I/O from the ports, reading and writing to the
363          * queue number corresponding to our process number (not lcore id)
364          */
365
366         for (;;) {
367                 struct rte_mbuf *buf[PKT_BURST];
368
369                 for (p = start_port; p < end_port; p++) {
370                         const uint8_t src = ports[p];
371                         const uint8_t dst = ports[p ^ 1]; /* 0 <-> 1, 2 <-> 3 etc */
372                         const uint16_t rx_c = rte_eth_rx_burst(src, q_id, buf, PKT_BURST);
373                         if (rx_c == 0)
374                                 continue;
375                         pstats[src].rx += rx_c;
376
377                         const uint16_t tx_c = rte_eth_tx_burst(dst, q_id, buf, rx_c);
378                         pstats[dst].tx += tx_c;
379                         if (tx_c != rx_c) {
380                                 pstats[dst].drop += (rx_c - tx_c);
381                                 for (i = tx_c; i < rx_c; i++)
382                                         rte_pktmbuf_free(buf[i]);
383                         }
384                 }
385         }
386 }
387
388 /* Check the link status of all ports in up to 9s, and print them finally */
389 static void
390 check_all_ports_link_status(uint8_t port_num, uint32_t port_mask)
391 {
392 #define CHECK_INTERVAL 100 /* 100ms */
393 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
394         uint8_t portid, count, all_ports_up, print_flag = 0;
395         struct rte_eth_link link;
396
397         printf("\nChecking link status");
398         fflush(stdout);
399         for (count = 0; count <= MAX_CHECK_TIME; count++) {
400                 all_ports_up = 1;
401                 for (portid = 0; portid < port_num; portid++) {
402                         if ((port_mask & (1 << portid)) == 0)
403                                 continue;
404                         memset(&link, 0, sizeof(link));
405                         rte_eth_link_get_nowait(portid, &link);
406                         /* print link status if flag set */
407                         if (print_flag == 1) {
408                                 if (link.link_status)
409                                         printf("Port %d Link Up - speed %u "
410                                                 "Mbps - %s\n", (uint8_t)portid,
411                                                 (unsigned)link.link_speed,
412                                 (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
413                                         ("full-duplex") : ("half-duplex\n"));
414                                 else
415                                         printf("Port %d Link Down\n",
416                                                         (uint8_t)portid);
417                                 continue;
418                         }
419                         /* clear all_ports_up flag if any link down */
420                         if (link.link_status == 0) {
421                                 all_ports_up = 0;
422                                 break;
423                         }
424                 }
425                 /* after finally printing all link status, get out */
426                 if (print_flag == 1)
427                         break;
428
429                 if (all_ports_up == 0) {
430                         printf(".");
431                         fflush(stdout);
432                         rte_delay_ms(CHECK_INTERVAL);
433                 }
434
435                 /* set the print_flag if all ports up or timeout */
436                 if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
437                         print_flag = 1;
438                         printf("done\n");
439                 }
440         }
441 }
442
443 /* Main function.
444  * Performs initialisation and then calls the lcore_main on each core
445  * to do the packet-processing work.
446  */
447 int
448 main(int argc, char **argv)
449 {
450         static const char *_SMP_MBUF_POOL = "SMP_MBUF_POOL";
451         int ret;
452         unsigned i;
453         enum rte_proc_type_t proc_type;
454         struct rte_mempool *mp;
455
456         /* set up signal handlers to print stats on exit */
457         signal(SIGINT, print_stats);
458         signal(SIGTERM, print_stats);
459
460         /* initialise the EAL for all */
461         ret = rte_eal_init(argc, argv);
462         if (ret < 0)
463                 rte_exit(EXIT_FAILURE, "Cannot init EAL\n");
464         argc -= ret;
465         argv += ret;
466
467         /* probe to determine the NIC devices available */
468         proc_type = rte_eal_process_type();
469         if (rte_pmd_init_all() < 0)
470                 rte_exit(EXIT_FAILURE, "Cannot init pmd\n");
471         if (rte_eal_pci_probe() < 0)
472                 rte_exit(EXIT_FAILURE, "Cannot probe PCI\n");
473         if (rte_eth_dev_count() == 0)
474                 rte_exit(EXIT_FAILURE, "No Ethernet ports - bye\n");
475
476         /* parse application arguments (those after the EAL ones) */
477         smp_parse_args(argc, argv);
478
479         mp = (proc_type == RTE_PROC_SECONDARY) ?
480                         rte_mempool_lookup(_SMP_MBUF_POOL) :
481                         rte_mempool_create(_SMP_MBUF_POOL, NB_MBUFS, MBUF_SIZE,
482                                         MBUF_CACHE_SIZE, sizeof(struct rte_pktmbuf_pool_private),
483                                         rte_pktmbuf_pool_init, NULL,
484                                         rte_pktmbuf_init, NULL,
485                                         SOCKET0, 0);
486         if (mp == NULL)
487                 rte_exit(EXIT_FAILURE, "Cannot get memory pool for buffers\n");
488
489         if (num_ports & 1)
490                 rte_exit(EXIT_FAILURE, "Application must use an even number of ports\n");
491         for(i = 0; i < num_ports; i++){
492                 if(proc_type == RTE_PROC_PRIMARY)
493                         if (smp_port_init(ports[i], mp, (uint16_t)num_procs) < 0)
494                                 rte_exit(EXIT_FAILURE, "Error initialising ports\n");
495         }
496
497         if (proc_type == RTE_PROC_PRIMARY)
498                 check_all_ports_link_status((uint8_t)num_ports, (~0x0));
499
500         assign_ports_to_cores();
501
502         RTE_LOG(INFO, APP, "Finished Process Init.\n");
503
504         rte_eal_mp_remote_launch(lcore_main, NULL, CALL_MASTER);
505
506         return 0;
507 }