4f1946bda6d8891fa4c7260027fa5602310b1443
[dpdk.git] / examples / multi_process / symmetric_mp / 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 /*
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 MBUF_SIZE (2048 + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
84 #define NB_MBUFS 64*1024 /* use 64k mbufs */
85 #define MBUF_CACHE_SIZE 256
86 #define PKT_BURST 32
87 #define RX_RING_SIZE 128
88 #define TX_RING_SIZE 512
89
90 #define PARAM_PROC_ID "proc-id"
91 #define PARAM_NUM_PROCS "num-procs"
92
93 /*
94  * RX and TX Prefetch, Host, and Write-back threshold values should be
95  * carefully set for optimal performance. Consult the network
96  * controller's datasheet and supporting DPDK documentation for guidance
97  * on how these parameters should be set.
98  */
99 /* Default configuration for rx and tx thresholds etc. */
100 static const struct rte_eth_rxconf rx_conf_default = {
101         .rx_thresh = {
102                 .pthresh = 8,
103                 .hthresh = 8,
104                 .wthresh = 4,
105         },
106 };
107
108 /*
109  * These default values are optimized for use with the Intel(R) 82599 10 GbE
110  * Controller and the DPDK ixgbe PMD. Consider using other values for other
111  * network controllers and/or network drivers.
112  */
113 static const struct rte_eth_txconf tx_conf_default = {
114         .tx_thresh = {
115                 .pthresh = 36,
116                 .hthresh = 0,
117                 .wthresh = 0,
118         },
119         .tx_free_thresh = 0, /* Use PMD default values */
120         .tx_rs_thresh = 0, /* Use PMD default values */
121 };
122
123 /* for each lcore, record the elements of the ports array to use */
124 struct lcore_ports{
125         unsigned start_port;
126         unsigned num_ports;
127 };
128
129 /* structure to record the rx and tx packets. Put two per cache line as ports
130  * used in pairs */
131 struct port_stats{
132         unsigned rx;
133         unsigned tx;
134         unsigned drop;
135 } __attribute__((aligned(CACHE_LINE_SIZE / 2)));
136
137 static int proc_id = -1;
138 static unsigned num_procs = 0;
139
140 static uint8_t ports[RTE_MAX_ETHPORTS];
141 static unsigned num_ports = 0;
142
143 static struct lcore_ports lcore_ports[RTE_MAX_LCORE];
144 static struct port_stats pstats[RTE_MAX_ETHPORTS];
145
146 /* prints the usage statement and quits with an error message */
147 static void
148 smp_usage(const char *prgname, const char *errmsg)
149 {
150         printf("\nError: %s\n",errmsg);
151         printf("\n%s [EAL options] -- -p <port mask> "
152                         "--"PARAM_NUM_PROCS" <n>"
153                         " --"PARAM_PROC_ID" <id>\n"
154                         "-p         : a hex bitmask indicating what ports are to be used\n"
155                         "--num-procs: the number of processes which will be used\n"
156                         "--proc-id  : the id of the current process (id < num-procs)\n"
157                         "\n",
158                         prgname);
159         exit(1);
160 }
161
162
163 /* signal handler configured for SIGTERM and SIGINT to print stats on exit */
164 static void
165 print_stats(int signum)
166 {
167         unsigned i;
168         printf("\nExiting on signal %d\n\n", signum);
169         for (i = 0; i < num_ports; i++){
170                 const uint8_t p_num = ports[i];
171                 printf("Port %u: RX - %u, TX - %u, Drop - %u\n", (unsigned)p_num,
172                                 pstats[p_num].rx, pstats[p_num].tx, pstats[p_num].drop);
173         }
174         exit(0);
175 }
176
177 /* Parse the argument given in the command line of the application */
178 static int
179 smp_parse_args(int argc, char **argv)
180 {
181         int opt, ret;
182         char **argvopt;
183         int option_index;
184         unsigned i, port_mask = 0;
185         char *prgname = argv[0];
186         static struct option lgopts[] = {
187                         {PARAM_NUM_PROCS, 1, 0, 0},
188                         {PARAM_PROC_ID, 1, 0, 0},
189                         {NULL, 0, 0, 0}
190         };
191
192         argvopt = argv;
193
194         while ((opt = getopt_long(argc, argvopt, "p:", \
195                         lgopts, &option_index)) != EOF) {
196
197                 switch (opt) {
198                 case 'p':
199                         port_mask = strtoull(optarg, NULL, 16);
200                         break;
201                         /* long options */
202                 case 0:
203                         if (strncmp(lgopts[option_index].name, PARAM_NUM_PROCS, 8) == 0)
204                                 num_procs = atoi(optarg);
205                         else if (strncmp(lgopts[option_index].name, PARAM_PROC_ID, 7) == 0)
206                                 proc_id = atoi(optarg);
207                         break;
208
209                 default:
210                         smp_usage(prgname, "Cannot parse all command-line arguments\n");
211                 }
212         }
213
214         if (optind >= 0)
215                 argv[optind-1] = prgname;
216
217         if (proc_id < 0)
218                 smp_usage(prgname, "Invalid or missing proc-id parameter\n");
219         if (rte_eal_process_type() == RTE_PROC_PRIMARY && num_procs == 0)
220                 smp_usage(prgname, "Invalid or missing num-procs parameter\n");
221         if (port_mask == 0)
222                 smp_usage(prgname, "Invalid or missing port mask\n");
223
224         /* get the port numbers from the port mask */
225         for(i = 0; i < rte_eth_dev_count(); i++)
226                 if(port_mask & (1 << i))
227                         ports[num_ports++] = (uint8_t)i;
228
229         ret = optind-1;
230         optind = 0; /* reset getopt lib */
231
232         return (ret);
233 }
234
235 /*
236  * Initialises a given port using global settings and with the rx buffers
237  * coming from the mbuf_pool passed as parameter
238  */
239 static inline int
240 smp_port_init(uint8_t port, struct rte_mempool *mbuf_pool, uint16_t num_queues)
241 {
242         struct rte_eth_conf port_conf = {
243                         .rxmode = {
244                                 .mq_mode = ETH_MQ_RX_RSS,
245                                 .split_hdr_size = 0,
246                                 .header_split   = 0, /**< Header Split disabled */
247                                 .hw_ip_checksum = 1, /**< IP checksum offload enabled */
248                                 .hw_vlan_filter = 0, /**< VLAN filtering disabled */
249                                 .jumbo_frame    = 0, /**< Jumbo Frame Support disabled */
250                                 .hw_strip_crc   = 0, /**< CRC stripped by hardware */
251                         },
252                         .rx_adv_conf = {
253                                 .rss_conf = {
254                                         .rss_key = NULL,
255                                         .rss_hf = ETH_RSS_IPV4 | ETH_RSS_IPV6,
256                                 },
257                         },
258                         .txmode = {
259                                 .mq_mode = ETH_MQ_TX_NONE,
260                         }
261         };
262         const uint16_t rx_rings = num_queues, tx_rings = num_queues;
263         int retval;
264         uint16_t q;
265
266         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
267                 return 0;
268
269         if (port >= rte_eth_dev_count())
270                 return -1;
271
272         printf("# Initialising port %u... ", (unsigned)port);
273         fflush(stdout);
274
275         retval = rte_eth_dev_configure(port, rx_rings, tx_rings, &port_conf);
276         if (retval < 0)
277                 return retval;
278
279         for (q = 0; q < rx_rings; q ++) {
280                 retval = rte_eth_rx_queue_setup(port, q, RX_RING_SIZE,
281                                 rte_eth_dev_socket_id(port), &rx_conf_default,
282                                 mbuf_pool);
283                 if (retval < 0)
284                         return retval;
285         }
286
287         for (q = 0; q < tx_rings; q ++) {
288                 retval = rte_eth_tx_queue_setup(port, q, RX_RING_SIZE,
289                                 rte_eth_dev_socket_id(port), &tx_conf_default);
290                 if (retval < 0)
291                         return retval;
292         }
293
294         rte_eth_promiscuous_enable(port);
295
296         retval  = rte_eth_dev_start(port);
297         if (retval < 0)
298                 return retval;
299
300         return 0;
301 }
302
303 /* Goes through each of the lcores and calculates what ports should
304  * be used by that core. Fills in the global lcore_ports[] array.
305  */
306 static void
307 assign_ports_to_cores(void)
308 {
309
310         const unsigned lcores = rte_eal_get_configuration()->lcore_count;
311         const unsigned port_pairs = num_ports / 2;
312         const unsigned pairs_per_lcore = port_pairs / lcores;
313         unsigned extra_pairs = port_pairs % lcores;
314         unsigned ports_assigned = 0;
315         unsigned i;
316
317         RTE_LCORE_FOREACH(i) {
318                 lcore_ports[i].start_port = ports_assigned;
319                 lcore_ports[i].num_ports = pairs_per_lcore * 2;
320                 if (extra_pairs > 0) {
321                         lcore_ports[i].num_ports += 2;
322                         extra_pairs--;
323                 }
324                 ports_assigned += lcore_ports[i].num_ports;
325         }
326 }
327
328 /* Main function used by the processing threads.
329  * Prints out some configuration details for the thread and then begins
330  * performing packet RX and TX.
331  */
332 static int
333 lcore_main(void *arg __rte_unused)
334 {
335         const unsigned id = rte_lcore_id();
336         const unsigned start_port = lcore_ports[id].start_port;
337         const unsigned end_port = start_port + lcore_ports[id].num_ports;
338         const uint16_t q_id = (uint16_t)proc_id;
339         unsigned p, i;
340         char msgbuf[256];
341         int msgbufpos = 0;
342
343         if (start_port == end_port){
344                 printf("Lcore %u has nothing to do\n", id);
345                 return 0;
346         }
347
348         /* build up message in msgbuf before printing to decrease likelihood
349          * of multi-core message interleaving.
350          */
351         msgbufpos += rte_snprintf(msgbuf, sizeof(msgbuf) - msgbufpos,
352                         "Lcore %u using ports ", id);
353         for (p = start_port; p < end_port; p++){
354                 msgbufpos += rte_snprintf(msgbuf + msgbufpos, sizeof(msgbuf) - msgbufpos,
355                                 "%u ", (unsigned)ports[p]);
356         }
357         printf("%s\n", msgbuf);
358         printf("lcore %u using queue %u of each port\n", id, (unsigned)q_id);
359
360         /* handle packet I/O from the ports, reading and writing to the
361          * queue number corresponding to our process number (not lcore id)
362          */
363
364         for (;;) {
365                 struct rte_mbuf *buf[PKT_BURST];
366
367                 for (p = start_port; p < end_port; p++) {
368                         const uint8_t src = ports[p];
369                         const uint8_t dst = ports[p ^ 1]; /* 0 <-> 1, 2 <-> 3 etc */
370                         const uint16_t rx_c = rte_eth_rx_burst(src, q_id, buf, PKT_BURST);
371                         if (rx_c == 0)
372                                 continue;
373                         pstats[src].rx += rx_c;
374
375                         const uint16_t tx_c = rte_eth_tx_burst(dst, q_id, buf, rx_c);
376                         pstats[dst].tx += tx_c;
377                         if (tx_c != rx_c) {
378                                 pstats[dst].drop += (rx_c - tx_c);
379                                 for (i = tx_c; i < rx_c; i++)
380                                         rte_pktmbuf_free(buf[i]);
381                         }
382                 }
383         }
384 }
385
386 /* Check the link status of all ports in up to 9s, and print them finally */
387 static void
388 check_all_ports_link_status(uint8_t port_num, uint32_t port_mask)
389 {
390 #define CHECK_INTERVAL 100 /* 100ms */
391 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
392         uint8_t portid, count, all_ports_up, print_flag = 0;
393         struct rte_eth_link link;
394
395         printf("\nChecking link status");
396         fflush(stdout);
397         for (count = 0; count <= MAX_CHECK_TIME; count++) {
398                 all_ports_up = 1;
399                 for (portid = 0; portid < port_num; portid++) {
400                         if ((port_mask & (1 << portid)) == 0)
401                                 continue;
402                         memset(&link, 0, sizeof(link));
403                         rte_eth_link_get_nowait(portid, &link);
404                         /* print link status if flag set */
405                         if (print_flag == 1) {
406                                 if (link.link_status)
407                                         printf("Port %d Link Up - speed %u "
408                                                 "Mbps - %s\n", (uint8_t)portid,
409                                                 (unsigned)link.link_speed,
410                                 (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
411                                         ("full-duplex") : ("half-duplex\n"));
412                                 else
413                                         printf("Port %d Link Down\n",
414                                                         (uint8_t)portid);
415                                 continue;
416                         }
417                         /* clear all_ports_up flag if any link down */
418                         if (link.link_status == 0) {
419                                 all_ports_up = 0;
420                                 break;
421                         }
422                 }
423                 /* after finally printing all link status, get out */
424                 if (print_flag == 1)
425                         break;
426
427                 if (all_ports_up == 0) {
428                         printf(".");
429                         fflush(stdout);
430                         rte_delay_ms(CHECK_INTERVAL);
431                 }
432
433                 /* set the print_flag if all ports up or timeout */
434                 if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
435                         print_flag = 1;
436                         printf("done\n");
437                 }
438         }
439 }
440
441 /* Main function.
442  * Performs initialisation and then calls the lcore_main on each core
443  * to do the packet-processing work.
444  */
445 int
446 main(int argc, char **argv)
447 {
448         static const char *_SMP_MBUF_POOL = "SMP_MBUF_POOL";
449         int ret;
450         unsigned i;
451         enum rte_proc_type_t proc_type;
452         struct rte_mempool *mp;
453
454         /* set up signal handlers to print stats on exit */
455         signal(SIGINT, print_stats);
456         signal(SIGTERM, print_stats);
457
458         /* initialise the EAL for all */
459         ret = rte_eal_init(argc, argv);
460         if (ret < 0)
461                 rte_exit(EXIT_FAILURE, "Cannot init EAL\n");
462         argc -= ret;
463         argv += ret;
464
465         /* probe to determine the NIC devices available */
466         proc_type = rte_eal_process_type();
467         if (rte_pmd_init_all() < 0)
468                 rte_exit(EXIT_FAILURE, "Cannot init pmd\n");
469         if (rte_eal_pci_probe() < 0)
470                 rte_exit(EXIT_FAILURE, "Cannot probe PCI\n");
471         if (rte_eth_dev_count() == 0)
472                 rte_exit(EXIT_FAILURE, "No Ethernet ports - bye\n");
473
474         /* parse application arguments (those after the EAL ones) */
475         smp_parse_args(argc, argv);
476
477         mp = (proc_type == RTE_PROC_SECONDARY) ?
478                         rte_mempool_lookup(_SMP_MBUF_POOL) :
479                         rte_mempool_create(_SMP_MBUF_POOL, NB_MBUFS, MBUF_SIZE,
480                                         MBUF_CACHE_SIZE, sizeof(struct rte_pktmbuf_pool_private),
481                                         rte_pktmbuf_pool_init, NULL,
482                                         rte_pktmbuf_init, NULL,
483                                         rte_socket_id(), 0);
484         if (mp == NULL)
485                 rte_exit(EXIT_FAILURE, "Cannot get memory pool for buffers\n");
486
487         if (num_ports & 1)
488                 rte_exit(EXIT_FAILURE, "Application must use an even number of ports\n");
489         for(i = 0; i < num_ports; i++){
490                 if(proc_type == RTE_PROC_PRIMARY)
491                         if (smp_port_init(ports[i], mp, (uint16_t)num_procs) < 0)
492                                 rte_exit(EXIT_FAILURE, "Error initialising ports\n");
493         }
494
495         if (proc_type == RTE_PROC_PRIMARY)
496                 check_all_ports_link_status((uint8_t)num_ports, (~0x0));
497
498         assign_ports_to_cores();
499
500         RTE_LOG(INFO, APP, "Finished Process Init.\n");
501
502         rte_eal_mp_remote_launch(lcore_main, NULL, CALL_MASTER);
503
504         return 0;
505 }