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