xref: /dpdk/examples/ip_reassembly/main.c (revision 0857b942113874c69dc3db5df11a828ee3cc9b6b)
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 <stdio.h>
35 #include <stdlib.h>
36 #include <stdint.h>
37 #include <inttypes.h>
38 #include <sys/types.h>
39 #include <string.h>
40 #include <sys/queue.h>
41 #include <stdarg.h>
42 #include <errno.h>
43 #include <getopt.h>
44 #include <signal.h>
45 #include <sys/param.h>
46 
47 #include <rte_common.h>
48 #include <rte_byteorder.h>
49 #include <rte_log.h>
50 #include <rte_memory.h>
51 #include <rte_memcpy.h>
52 #include <rte_memzone.h>
53 #include <rte_eal.h>
54 #include <rte_per_lcore.h>
55 #include <rte_launch.h>
56 #include <rte_atomic.h>
57 #include <rte_cycles.h>
58 #include <rte_prefetch.h>
59 #include <rte_lcore.h>
60 #include <rte_per_lcore.h>
61 #include <rte_branch_prediction.h>
62 #include <rte_interrupts.h>
63 #include <rte_pci.h>
64 #include <rte_random.h>
65 #include <rte_debug.h>
66 #include <rte_ether.h>
67 #include <rte_ethdev.h>
68 #include <rte_mempool.h>
69 #include <rte_mbuf.h>
70 #include <rte_malloc.h>
71 #include <rte_ip.h>
72 #include <rte_tcp.h>
73 #include <rte_udp.h>
74 #include <rte_string_fns.h>
75 #include <rte_lpm.h>
76 #include <rte_lpm6.h>
77 
78 #include <rte_ip_frag.h>
79 
80 #define MAX_PKT_BURST 32
81 
82 
83 #define RTE_LOGTYPE_IP_RSMBL RTE_LOGTYPE_USER1
84 
85 #define MAX_JUMBO_PKT_LEN  9600
86 
87 #define	BUF_SIZE	RTE_MBUF_DEFAULT_DATAROOM
88 #define MBUF_SIZE	\
89 	(BUF_SIZE + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
90 
91 #define NB_MBUF 8192
92 
93 /* allow max jumbo frame 9.5 KB */
94 #define JUMBO_FRAME_MAX_SIZE	0x2600
95 
96 #define	MAX_FLOW_NUM	UINT16_MAX
97 #define	MIN_FLOW_NUM	1
98 #define	DEF_FLOW_NUM	0x1000
99 
100 /* TTL numbers are in ms. */
101 #define	MAX_FLOW_TTL	(3600 * MS_PER_S)
102 #define	MIN_FLOW_TTL	1
103 #define	DEF_FLOW_TTL	MS_PER_S
104 
105 #define MAX_FRAG_NUM RTE_LIBRTE_IP_FRAG_MAX_FRAG
106 
107 /* Should be power of two. */
108 #define	IP_FRAG_TBL_BUCKET_ENTRIES	16
109 
110 static uint32_t max_flow_num = DEF_FLOW_NUM;
111 static uint32_t max_flow_ttl = DEF_FLOW_TTL;
112 
113 #define BURST_TX_DRAIN_US 100 /* TX drain every ~100us */
114 
115 #define NB_SOCKETS 8
116 
117 /* Configure how many packets ahead to prefetch, when reading packets */
118 #define PREFETCH_OFFSET	3
119 
120 /*
121  * Configurable number of RX/TX ring descriptors
122  */
123 #define RTE_TEST_RX_DESC_DEFAULT 128
124 #define RTE_TEST_TX_DESC_DEFAULT 512
125 
126 static uint16_t nb_rxd = RTE_TEST_RX_DESC_DEFAULT;
127 static uint16_t nb_txd = RTE_TEST_TX_DESC_DEFAULT;
128 
129 /* ethernet addresses of ports */
130 static struct ether_addr ports_eth_addr[RTE_MAX_ETHPORTS];
131 
132 #ifndef IPv4_BYTES
133 #define IPv4_BYTES_FMT "%" PRIu8 ".%" PRIu8 ".%" PRIu8 ".%" PRIu8
134 #define IPv4_BYTES(addr) \
135 		(uint8_t) (((addr) >> 24) & 0xFF),\
136 		(uint8_t) (((addr) >> 16) & 0xFF),\
137 		(uint8_t) (((addr) >> 8) & 0xFF),\
138 		(uint8_t) ((addr) & 0xFF)
139 #endif
140 
141 #ifndef IPv6_BYTES
142 #define IPv6_BYTES_FMT "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"\
143                        "%02x%02x:%02x%02x:%02x%02x:%02x%02x"
144 #define IPv6_BYTES(addr) \
145 	addr[0],  addr[1], addr[2],  addr[3], \
146 	addr[4],  addr[5], addr[6],  addr[7], \
147 	addr[8],  addr[9], addr[10], addr[11],\
148 	addr[12], addr[13],addr[14], addr[15]
149 #endif
150 
151 #define IPV6_ADDR_LEN 16
152 
153 /* mask of enabled ports */
154 static uint32_t enabled_port_mask = 0;
155 
156 static int rx_queue_per_lcore = 1;
157 
158 struct mbuf_table {
159 	uint32_t len;
160 	uint32_t head;
161 	uint32_t tail;
162 	struct rte_mbuf *m_table[0];
163 };
164 
165 struct rx_queue {
166 	struct rte_ip_frag_tbl *frag_tbl;
167 	struct rte_mempool *pool;
168 	struct rte_lpm *lpm;
169 	struct rte_lpm6 *lpm6;
170 	uint8_t portid;
171 };
172 
173 struct tx_lcore_stat {
174 	uint64_t call;
175 	uint64_t drop;
176 	uint64_t queue;
177 	uint64_t send;
178 };
179 
180 #define MAX_RX_QUEUE_PER_LCORE 16
181 #define MAX_TX_QUEUE_PER_PORT 16
182 #define MAX_RX_QUEUE_PER_PORT 128
183 
184 struct lcore_queue_conf {
185 	uint16_t n_rx_queue;
186 	struct rx_queue rx_queue_list[MAX_RX_QUEUE_PER_LCORE];
187 	uint16_t tx_queue_id[RTE_MAX_ETHPORTS];
188 	struct rte_ip_frag_death_row death_row;
189 	struct mbuf_table *tx_mbufs[RTE_MAX_ETHPORTS];
190 	struct tx_lcore_stat tx_stat;
191 } __rte_cache_aligned;
192 static struct lcore_queue_conf lcore_queue_conf[RTE_MAX_LCORE];
193 
194 static struct rte_eth_conf port_conf = {
195 	.rxmode = {
196 		.mq_mode        = ETH_MQ_RX_RSS,
197 		.max_rx_pkt_len = JUMBO_FRAME_MAX_SIZE,
198 		.split_hdr_size = 0,
199 		.header_split   = 0, /**< Header Split disabled */
200 		.hw_ip_checksum = 1, /**< IP checksum offload enabled */
201 		.hw_vlan_filter = 0, /**< VLAN filtering disabled */
202 		.jumbo_frame    = 1, /**< Jumbo Frame Support disabled */
203 		.hw_strip_crc   = 0, /**< CRC stripped by hardware */
204 	},
205 	.rx_adv_conf = {
206 			.rss_conf = {
207 				.rss_key = NULL,
208 				.rss_hf = ETH_RSS_IP,
209 		},
210 	},
211 	.txmode = {
212 		.mq_mode = ETH_MQ_TX_NONE,
213 	},
214 };
215 
216 /*
217  * IPv4 forwarding table
218  */
219 struct l3fwd_ipv4_route {
220 	uint32_t ip;
221 	uint8_t  depth;
222 	uint8_t  if_out;
223 };
224 
225 struct l3fwd_ipv4_route l3fwd_ipv4_route_array[] = {
226 		{IPv4(100,10,0,0), 16, 0},
227 		{IPv4(100,20,0,0), 16, 1},
228 		{IPv4(100,30,0,0), 16, 2},
229 		{IPv4(100,40,0,0), 16, 3},
230 		{IPv4(100,50,0,0), 16, 4},
231 		{IPv4(100,60,0,0), 16, 5},
232 		{IPv4(100,70,0,0), 16, 6},
233 		{IPv4(100,80,0,0), 16, 7},
234 };
235 
236 /*
237  * IPv6 forwarding table
238  */
239 
240 struct l3fwd_ipv6_route {
241 	uint8_t ip[IPV6_ADDR_LEN];
242 	uint8_t depth;
243 	uint8_t if_out;
244 };
245 
246 static struct l3fwd_ipv6_route l3fwd_ipv6_route_array[] = {
247 	{{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, 48, 0},
248 	{{2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, 48, 1},
249 	{{3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, 48, 2},
250 	{{4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, 48, 3},
251 	{{5,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, 48, 4},
252 	{{6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, 48, 5},
253 	{{7,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, 48, 6},
254 	{{8,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, 48, 7},
255 };
256 
257 #define LPM_MAX_RULES         1024
258 #define LPM6_MAX_RULES         1024
259 #define LPM6_NUMBER_TBL8S (1 << 16)
260 
261 struct rte_lpm6_config lpm6_config = {
262 		.max_rules = LPM6_MAX_RULES,
263 		.number_tbl8s = LPM6_NUMBER_TBL8S,
264 		.flags = 0
265 };
266 
267 static struct rte_lpm *socket_lpm[RTE_MAX_NUMA_NODES];
268 static struct rte_lpm6 *socket_lpm6[RTE_MAX_NUMA_NODES];
269 
270 #ifdef RTE_LIBRTE_IP_FRAG_TBL_STAT
271 #define TX_LCORE_STAT_UPDATE(s, f, v)   ((s)->f += (v))
272 #else
273 #define TX_LCORE_STAT_UPDATE(s, f, v)   do {} while (0)
274 #endif /* RTE_LIBRTE_IP_FRAG_TBL_STAT */
275 
276 /*
277  * If number of queued packets reached given threahold, then
278  * send burst of packets on an output interface.
279  */
280 static inline uint32_t
281 send_burst(struct lcore_queue_conf *qconf, uint32_t thresh, uint8_t port)
282 {
283 	uint32_t fill, len, k, n;
284 	struct mbuf_table *txmb;
285 
286 	txmb = qconf->tx_mbufs[port];
287 	len = txmb->len;
288 
289 	if ((int32_t)(fill = txmb->head - txmb->tail) < 0)
290 		fill += len;
291 
292 	if (fill >= thresh) {
293 		n = RTE_MIN(len - txmb->tail, fill);
294 
295 		k = rte_eth_tx_burst(port, qconf->tx_queue_id[port],
296 			txmb->m_table + txmb->tail, (uint16_t)n);
297 
298 		TX_LCORE_STAT_UPDATE(&qconf->tx_stat, call, 1);
299 		TX_LCORE_STAT_UPDATE(&qconf->tx_stat, send, k);
300 
301 		fill -= k;
302 		if ((txmb->tail += k) == len)
303 			txmb->tail = 0;
304 	}
305 
306 	return fill;
307 }
308 
309 /* Enqueue a single packet, and send burst if queue is filled */
310 static inline int
311 send_single_packet(struct rte_mbuf *m, uint8_t port)
312 {
313 	uint32_t fill, lcore_id, len;
314 	struct lcore_queue_conf *qconf;
315 	struct mbuf_table *txmb;
316 
317 	lcore_id = rte_lcore_id();
318 	qconf = &lcore_queue_conf[lcore_id];
319 
320 	txmb = qconf->tx_mbufs[port];
321 	len = txmb->len;
322 
323 	fill = send_burst(qconf, MAX_PKT_BURST, port);
324 
325 	if (fill == len - 1) {
326 		TX_LCORE_STAT_UPDATE(&qconf->tx_stat, drop, 1);
327 		rte_pktmbuf_free(txmb->m_table[txmb->tail]);
328 		if (++txmb->tail == len)
329 			txmb->tail = 0;
330 	}
331 
332 	TX_LCORE_STAT_UPDATE(&qconf->tx_stat, queue, 1);
333 	txmb->m_table[txmb->head] = m;
334 	if(++txmb->head == len)
335 		txmb->head = 0;
336 
337 	return 0;
338 }
339 
340 static inline void
341 reassemble(struct rte_mbuf *m, uint8_t portid, uint32_t queue,
342 	struct lcore_queue_conf *qconf, uint64_t tms)
343 {
344 	struct ether_hdr *eth_hdr;
345 	struct rte_ip_frag_tbl *tbl;
346 	struct rte_ip_frag_death_row *dr;
347 	struct rx_queue *rxq;
348 	void *d_addr_bytes;
349 	uint32_t next_hop;
350 	uint8_t dst_port;
351 
352 	rxq = &qconf->rx_queue_list[queue];
353 
354 	eth_hdr = rte_pktmbuf_mtod(m, struct ether_hdr *);
355 
356 	dst_port = portid;
357 
358 	/* if packet is IPv4 */
359 	if (RTE_ETH_IS_IPV4_HDR(m->packet_type)) {
360 		struct ipv4_hdr *ip_hdr;
361 		uint32_t ip_dst;
362 
363 		ip_hdr = (struct ipv4_hdr *)(eth_hdr + 1);
364 
365 		 /* if it is a fragmented packet, then try to reassemble. */
366 		if (rte_ipv4_frag_pkt_is_fragmented(ip_hdr)) {
367 			struct rte_mbuf *mo;
368 
369 			tbl = rxq->frag_tbl;
370 			dr = &qconf->death_row;
371 
372 			/* prepare mbuf: setup l2_len/l3_len. */
373 			m->l2_len = sizeof(*eth_hdr);
374 			m->l3_len = sizeof(*ip_hdr);
375 
376 			/* process this fragment. */
377 			mo = rte_ipv4_frag_reassemble_packet(tbl, dr, m, tms, ip_hdr);
378 			if (mo == NULL)
379 				/* no packet to send out. */
380 				return;
381 
382 			/* we have our packet reassembled. */
383 			if (mo != m) {
384 				m = mo;
385 				eth_hdr = rte_pktmbuf_mtod(m,
386 					struct ether_hdr *);
387 				ip_hdr = (struct ipv4_hdr *)(eth_hdr + 1);
388 			}
389 		}
390 		ip_dst = rte_be_to_cpu_32(ip_hdr->dst_addr);
391 
392 		/* Find destination port */
393 		if (rte_lpm_lookup(rxq->lpm, ip_dst, &next_hop) == 0 &&
394 				(enabled_port_mask & 1 << next_hop) != 0) {
395 			dst_port = next_hop;
396 		}
397 
398 		eth_hdr->ether_type = rte_be_to_cpu_16(ETHER_TYPE_IPv4);
399 	} else if (RTE_ETH_IS_IPV6_HDR(m->packet_type)) {
400 		/* if packet is IPv6 */
401 		struct ipv6_extension_fragment *frag_hdr;
402 		struct ipv6_hdr *ip_hdr;
403 
404 		ip_hdr = (struct ipv6_hdr *)(eth_hdr + 1);
405 
406 		frag_hdr = rte_ipv6_frag_get_ipv6_fragment_header(ip_hdr);
407 
408 		if (frag_hdr != NULL) {
409 			struct rte_mbuf *mo;
410 
411 			tbl = rxq->frag_tbl;
412 			dr  = &qconf->death_row;
413 
414 			/* prepare mbuf: setup l2_len/l3_len. */
415 			m->l2_len = sizeof(*eth_hdr);
416 			m->l3_len = sizeof(*ip_hdr) + sizeof(*frag_hdr);
417 
418 			mo = rte_ipv6_frag_reassemble_packet(tbl, dr, m, tms, ip_hdr, frag_hdr);
419 			if (mo == NULL)
420 				return;
421 
422 			if (mo != m) {
423 				m = mo;
424 				eth_hdr = rte_pktmbuf_mtod(m, struct ether_hdr *);
425 				ip_hdr = (struct ipv6_hdr *)(eth_hdr + 1);
426 			}
427 		}
428 
429 		/* Find destination port */
430 		if (rte_lpm6_lookup(rxq->lpm6, ip_hdr->dst_addr,
431 						&next_hop) == 0 &&
432 				(enabled_port_mask & 1 << next_hop) != 0) {
433 			dst_port = next_hop;
434 		}
435 
436 		eth_hdr->ether_type = rte_be_to_cpu_16(ETHER_TYPE_IPv6);
437 	}
438 	/* if packet wasn't IPv4 or IPv6, it's forwarded to the port it came from */
439 
440 	/* 02:00:00:00:00:xx */
441 	d_addr_bytes = &eth_hdr->d_addr.addr_bytes[0];
442 	*((uint64_t *)d_addr_bytes) = 0x000000000002 + ((uint64_t)dst_port << 40);
443 
444 	/* src addr */
445 	ether_addr_copy(&ports_eth_addr[dst_port], &eth_hdr->s_addr);
446 
447 	send_single_packet(m, dst_port);
448 }
449 
450 /* main processing loop */
451 static int
452 main_loop(__attribute__((unused)) void *dummy)
453 {
454 	struct rte_mbuf *pkts_burst[MAX_PKT_BURST];
455 	unsigned lcore_id;
456 	uint64_t diff_tsc, cur_tsc, prev_tsc;
457 	int i, j, nb_rx;
458 	uint8_t portid;
459 	struct lcore_queue_conf *qconf;
460 	const uint64_t drain_tsc = (rte_get_tsc_hz() + US_PER_S - 1) / US_PER_S * BURST_TX_DRAIN_US;
461 
462 	prev_tsc = 0;
463 
464 	lcore_id = rte_lcore_id();
465 	qconf = &lcore_queue_conf[lcore_id];
466 
467 	if (qconf->n_rx_queue == 0) {
468 		RTE_LOG(INFO, IP_RSMBL, "lcore %u has nothing to do\n", lcore_id);
469 		return 0;
470 	}
471 
472 	RTE_LOG(INFO, IP_RSMBL, "entering main loop on lcore %u\n", lcore_id);
473 
474 	for (i = 0; i < qconf->n_rx_queue; i++) {
475 
476 		portid = qconf->rx_queue_list[i].portid;
477 		RTE_LOG(INFO, IP_RSMBL, " -- lcoreid=%u portid=%hhu\n", lcore_id,
478 			portid);
479 	}
480 
481 	while (1) {
482 
483 		cur_tsc = rte_rdtsc();
484 
485 		/*
486 		 * TX burst queue drain
487 		 */
488 		diff_tsc = cur_tsc - prev_tsc;
489 		if (unlikely(diff_tsc > drain_tsc)) {
490 
491 			/*
492 			 * This could be optimized (use queueid instead of
493 			 * portid), but it is not called so often
494 			 */
495 			for (portid = 0; portid < RTE_MAX_ETHPORTS; portid++) {
496 				if ((enabled_port_mask & (1 << portid)) != 0)
497 					send_burst(qconf, 1, portid);
498 			}
499 
500 			prev_tsc = cur_tsc;
501 		}
502 
503 		/*
504 		 * Read packet from RX queues
505 		 */
506 		for (i = 0; i < qconf->n_rx_queue; ++i) {
507 
508 			portid = qconf->rx_queue_list[i].portid;
509 
510 			nb_rx = rte_eth_rx_burst(portid, 0, pkts_burst,
511 				MAX_PKT_BURST);
512 
513 			/* Prefetch first packets */
514 			for (j = 0; j < PREFETCH_OFFSET && j < nb_rx; j++) {
515 				rte_prefetch0(rte_pktmbuf_mtod(
516 						pkts_burst[j], void *));
517 			}
518 
519 			/* Prefetch and forward already prefetched packets */
520 			for (j = 0; j < (nb_rx - PREFETCH_OFFSET); j++) {
521 				rte_prefetch0(rte_pktmbuf_mtod(pkts_burst[
522 					j + PREFETCH_OFFSET], void *));
523 				reassemble(pkts_burst[j], portid,
524 					i, qconf, cur_tsc);
525 			}
526 
527 			/* Forward remaining prefetched packets */
528 			for (; j < nb_rx; j++) {
529 				reassemble(pkts_burst[j], portid,
530 					i, qconf, cur_tsc);
531 			}
532 
533 			rte_ip_frag_free_death_row(&qconf->death_row,
534 				PREFETCH_OFFSET);
535 		}
536 	}
537 }
538 
539 /* display usage */
540 static void
541 print_usage(const char *prgname)
542 {
543 	printf("%s [EAL options] -- -p PORTMASK [-q NQ]"
544 		"  [--max-pkt-len PKTLEN]"
545 		"  [--maxflows=<flows>]  [--flowttl=<ttl>[(s|ms)]]\n"
546 		"  -p PORTMASK: hexadecimal bitmask of ports to configure\n"
547 		"  -q NQ: number of RX queues per lcore\n"
548 		"  --maxflows=<flows>: optional, maximum number of flows "
549 		"supported\n"
550 		"  --flowttl=<ttl>[(s|ms)]: optional, maximum TTL for each "
551 		"flow\n",
552 		prgname);
553 }
554 
555 static uint32_t
556 parse_flow_num(const char *str, uint32_t min, uint32_t max, uint32_t *val)
557 {
558 	char *end;
559 	uint64_t v;
560 
561 	/* parse decimal string */
562 	errno = 0;
563 	v = strtoul(str, &end, 10);
564 	if (errno != 0 || *end != '\0')
565 		return -EINVAL;
566 
567 	if (v < min || v > max)
568 		return -EINVAL;
569 
570 	*val = (uint32_t)v;
571 	return 0;
572 }
573 
574 static int
575 parse_flow_ttl(const char *str, uint32_t min, uint32_t max, uint32_t *val)
576 {
577 	char *end;
578 	uint64_t v;
579 
580 	static const char frmt_sec[] = "s";
581 	static const char frmt_msec[] = "ms";
582 
583 	/* parse decimal string */
584 	errno = 0;
585 	v = strtoul(str, &end, 10);
586 	if (errno != 0)
587 		return -EINVAL;
588 
589 	if (*end != '\0') {
590 		if (strncmp(frmt_sec, end, sizeof(frmt_sec)) == 0)
591 			v *= MS_PER_S;
592 		else if (strncmp(frmt_msec, end, sizeof (frmt_msec)) != 0)
593 			return -EINVAL;
594 	}
595 
596 	if (v < min || v > max)
597 		return -EINVAL;
598 
599 	*val = (uint32_t)v;
600 	return 0;
601 }
602 
603 static int
604 parse_portmask(const char *portmask)
605 {
606 	char *end = NULL;
607 	unsigned long pm;
608 
609 	/* parse hexadecimal string */
610 	pm = strtoul(portmask, &end, 16);
611 	if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
612 		return -1;
613 
614 	if (pm == 0)
615 		return -1;
616 
617 	return pm;
618 }
619 
620 static int
621 parse_nqueue(const char *q_arg)
622 {
623 	char *end = NULL;
624 	unsigned long n;
625 
626 	printf("%p\n", q_arg);
627 
628 	/* parse hexadecimal string */
629 	n = strtoul(q_arg, &end, 10);
630 	if ((q_arg[0] == '\0') || (end == NULL) || (*end != '\0'))
631 		return -1;
632 	if (n == 0)
633 		return -1;
634 	if (n >= MAX_RX_QUEUE_PER_LCORE)
635 		return -1;
636 
637 	return n;
638 }
639 
640 /* Parse the argument given in the command line of the application */
641 static int
642 parse_args(int argc, char **argv)
643 {
644 	int opt, ret;
645 	char **argvopt;
646 	int option_index;
647 	char *prgname = argv[0];
648 	static struct option lgopts[] = {
649 		{"max-pkt-len", 1, 0, 0},
650 		{"maxflows", 1, 0, 0},
651 		{"flowttl", 1, 0, 0},
652 		{NULL, 0, 0, 0}
653 	};
654 
655 	argvopt = argv;
656 
657 	while ((opt = getopt_long(argc, argvopt, "p:q:",
658 				lgopts, &option_index)) != EOF) {
659 
660 		switch (opt) {
661 		/* portmask */
662 		case 'p':
663 			enabled_port_mask = parse_portmask(optarg);
664 			if (enabled_port_mask == 0) {
665 				printf("invalid portmask\n");
666 				print_usage(prgname);
667 				return -1;
668 			}
669 			break;
670 
671 		/* nqueue */
672 		case 'q':
673 			rx_queue_per_lcore = parse_nqueue(optarg);
674 			if (rx_queue_per_lcore < 0) {
675 				printf("invalid queue number\n");
676 				print_usage(prgname);
677 				return -1;
678 			}
679 			break;
680 
681 		/* long options */
682 		case 0:
683 			if (!strncmp(lgopts[option_index].name,
684 					"maxflows", 8)) {
685 				if ((ret = parse_flow_num(optarg, MIN_FLOW_NUM,
686 						MAX_FLOW_NUM,
687 						&max_flow_num)) != 0) {
688 					printf("invalid value: \"%s\" for "
689 						"parameter %s\n",
690 						optarg,
691 						lgopts[option_index].name);
692 					print_usage(prgname);
693 					return ret;
694 				}
695 			}
696 
697 			if (!strncmp(lgopts[option_index].name, "flowttl", 7)) {
698 				if ((ret = parse_flow_ttl(optarg, MIN_FLOW_TTL,
699 						MAX_FLOW_TTL,
700 						&max_flow_ttl)) != 0) {
701 					printf("invalid value: \"%s\" for "
702 						"parameter %s\n",
703 						optarg,
704 						lgopts[option_index].name);
705 					print_usage(prgname);
706 					return ret;
707 				}
708 			}
709 
710 			break;
711 
712 		default:
713 			print_usage(prgname);
714 			return -1;
715 		}
716 	}
717 
718 	if (optind >= 0)
719 		argv[optind-1] = prgname;
720 
721 	ret = optind-1;
722 	optind = 1; /* reset getopt lib */
723 	return ret;
724 }
725 
726 static void
727 print_ethaddr(const char *name, const struct ether_addr *eth_addr)
728 {
729 	char buf[ETHER_ADDR_FMT_SIZE];
730 	ether_format_addr(buf, ETHER_ADDR_FMT_SIZE, eth_addr);
731 	printf("%s%s", name, buf);
732 }
733 
734 /* Check the link status of all ports in up to 9s, and print them finally */
735 static void
736 check_all_ports_link_status(uint8_t port_num, uint32_t port_mask)
737 {
738 #define CHECK_INTERVAL 100 /* 100ms */
739 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
740 	uint8_t portid, count, all_ports_up, print_flag = 0;
741 	struct rte_eth_link link;
742 
743 	printf("\nChecking link status");
744 	fflush(stdout);
745 	for (count = 0; count <= MAX_CHECK_TIME; count++) {
746 		all_ports_up = 1;
747 		for (portid = 0; portid < port_num; portid++) {
748 			if ((port_mask & (1 << portid)) == 0)
749 				continue;
750 			memset(&link, 0, sizeof(link));
751 			rte_eth_link_get_nowait(portid, &link);
752 			/* print link status if flag set */
753 			if (print_flag == 1) {
754 				if (link.link_status)
755 					printf("Port %d Link Up - speed %u "
756 						"Mbps - %s\n", (uint8_t)portid,
757 						(unsigned)link.link_speed,
758 				(link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
759 					("full-duplex") : ("half-duplex\n"));
760 				else
761 					printf("Port %d Link Down\n",
762 						(uint8_t)portid);
763 				continue;
764 			}
765 			/* clear all_ports_up flag if any link down */
766 			if (link.link_status == ETH_LINK_DOWN) {
767 				all_ports_up = 0;
768 				break;
769 			}
770 		}
771 		/* after finally printing all link status, get out */
772 		if (print_flag == 1)
773 			break;
774 
775 		if (all_ports_up == 0) {
776 			printf(".");
777 			fflush(stdout);
778 			rte_delay_ms(CHECK_INTERVAL);
779 		}
780 
781 		/* set the print_flag if all ports up or timeout */
782 		if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
783 			print_flag = 1;
784 			printf("\ndone\n");
785 		}
786 	}
787 }
788 
789 static int
790 init_routing_table(void)
791 {
792 	struct rte_lpm *lpm;
793 	struct rte_lpm6 *lpm6;
794 	int socket, ret;
795 	unsigned i;
796 
797 	for (socket = 0; socket < RTE_MAX_NUMA_NODES; socket++) {
798 		if (socket_lpm[socket]) {
799 			lpm = socket_lpm[socket];
800 			/* populate the LPM table */
801 			for (i = 0; i < RTE_DIM(l3fwd_ipv4_route_array); i++) {
802 				ret = rte_lpm_add(lpm,
803 					l3fwd_ipv4_route_array[i].ip,
804 					l3fwd_ipv4_route_array[i].depth,
805 					l3fwd_ipv4_route_array[i].if_out);
806 
807 				if (ret < 0) {
808 					RTE_LOG(ERR, IP_RSMBL, "Unable to add entry %i to the l3fwd "
809 						"LPM table\n", i);
810 					return -1;
811 				}
812 
813 				RTE_LOG(INFO, IP_RSMBL, "Socket %i: adding route " IPv4_BYTES_FMT
814 						"/%d (port %d)\n",
815 					socket,
816 					IPv4_BYTES(l3fwd_ipv4_route_array[i].ip),
817 					l3fwd_ipv4_route_array[i].depth,
818 					l3fwd_ipv4_route_array[i].if_out);
819 			}
820 		}
821 
822 		if (socket_lpm6[socket]) {
823 			lpm6 = socket_lpm6[socket];
824 			/* populate the LPM6 table */
825 			for (i = 0; i < RTE_DIM(l3fwd_ipv6_route_array); i++) {
826 				ret = rte_lpm6_add(lpm6,
827 					l3fwd_ipv6_route_array[i].ip,
828 					l3fwd_ipv6_route_array[i].depth,
829 					l3fwd_ipv6_route_array[i].if_out);
830 
831 				if (ret < 0) {
832 					RTE_LOG(ERR, IP_RSMBL, "Unable to add entry %i to the l3fwd "
833 						"LPM6 table\n", i);
834 					return -1;
835 				}
836 
837 				RTE_LOG(INFO, IP_RSMBL, "Socket %i: adding route " IPv6_BYTES_FMT
838 						"/%d (port %d)\n",
839 					socket,
840 					IPv6_BYTES(l3fwd_ipv6_route_array[i].ip),
841 					l3fwd_ipv6_route_array[i].depth,
842 					l3fwd_ipv6_route_array[i].if_out);
843 			}
844 		}
845 	}
846 	return 0;
847 }
848 
849 static int
850 setup_port_tbl(struct lcore_queue_conf *qconf, uint32_t lcore, int socket,
851 	uint32_t port)
852 {
853 	struct mbuf_table *mtb;
854 	uint32_t n;
855 	size_t sz;
856 
857 	n = RTE_MAX(max_flow_num, 2UL * MAX_PKT_BURST);
858 	sz = sizeof (*mtb) + sizeof (mtb->m_table[0]) *  n;
859 
860 	if ((mtb = rte_zmalloc_socket(__func__, sz, RTE_CACHE_LINE_SIZE,
861 			socket)) == NULL) {
862 		RTE_LOG(ERR, IP_RSMBL, "%s() for lcore: %u, port: %u "
863 			"failed to allocate %zu bytes\n",
864 			__func__, lcore, port, sz);
865 		return -1;
866 	}
867 
868 	mtb->len = n;
869 	qconf->tx_mbufs[port] = mtb;
870 
871 	return 0;
872 }
873 
874 static int
875 setup_queue_tbl(struct rx_queue *rxq, uint32_t lcore, uint32_t queue)
876 {
877 	int socket;
878 	uint32_t nb_mbuf;
879 	uint64_t frag_cycles;
880 	char buf[RTE_MEMPOOL_NAMESIZE];
881 
882 	socket = rte_lcore_to_socket_id(lcore);
883 	if (socket == SOCKET_ID_ANY)
884 		socket = 0;
885 
886 	frag_cycles = (rte_get_tsc_hz() + MS_PER_S - 1) / MS_PER_S *
887 		max_flow_ttl;
888 
889 	if ((rxq->frag_tbl = rte_ip_frag_table_create(max_flow_num,
890 			IP_FRAG_TBL_BUCKET_ENTRIES, max_flow_num, frag_cycles,
891 			socket)) == NULL) {
892 		RTE_LOG(ERR, IP_RSMBL, "ip_frag_tbl_create(%u) on "
893 			"lcore: %u for queue: %u failed\n",
894 			max_flow_num, lcore, queue);
895 		return -1;
896 	}
897 
898 	/*
899 	 * At any given moment up to <max_flow_num * (MAX_FRAG_NUM)>
900 	 * mbufs could be stored int the fragment table.
901 	 * Plus, each TX queue can hold up to <max_flow_num> packets.
902 	 */
903 
904 	nb_mbuf = RTE_MAX(max_flow_num, 2UL * MAX_PKT_BURST) * MAX_FRAG_NUM;
905 	nb_mbuf *= (port_conf.rxmode.max_rx_pkt_len + BUF_SIZE - 1) / BUF_SIZE;
906 	nb_mbuf *= 2; /* ipv4 and ipv6 */
907 	nb_mbuf += RTE_TEST_RX_DESC_DEFAULT + RTE_TEST_TX_DESC_DEFAULT;
908 
909 	nb_mbuf = RTE_MAX(nb_mbuf, (uint32_t)NB_MBUF);
910 
911 	snprintf(buf, sizeof(buf), "mbuf_pool_%u_%u", lcore, queue);
912 
913 	if ((rxq->pool = rte_mempool_create(buf, nb_mbuf, MBUF_SIZE, 0,
914 			sizeof(struct rte_pktmbuf_pool_private),
915 			rte_pktmbuf_pool_init, NULL, rte_pktmbuf_init, NULL,
916 			socket, MEMPOOL_F_SP_PUT | MEMPOOL_F_SC_GET)) == NULL) {
917 		RTE_LOG(ERR, IP_RSMBL, "mempool_create(%s) failed", buf);
918 		return -1;
919 	}
920 
921 	return 0;
922 }
923 
924 static int
925 init_mem(void)
926 {
927 	char buf[PATH_MAX];
928 	struct rte_lpm *lpm;
929 	struct rte_lpm6 *lpm6;
930 	struct rte_lpm_config lpm_config;
931 	int socket;
932 	unsigned lcore_id;
933 
934 	/* traverse through lcores and initialize structures on each socket */
935 
936 	for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
937 
938 		if (rte_lcore_is_enabled(lcore_id) == 0)
939 			continue;
940 
941 		socket = rte_lcore_to_socket_id(lcore_id);
942 
943 		if (socket == SOCKET_ID_ANY)
944 			socket = 0;
945 
946 		if (socket_lpm[socket] == NULL) {
947 			RTE_LOG(INFO, IP_RSMBL, "Creating LPM table on socket %i\n", socket);
948 			snprintf(buf, sizeof(buf), "IP_RSMBL_LPM_%i", socket);
949 
950 			lpm_config.max_rules = LPM_MAX_RULES;
951 			lpm_config.number_tbl8s = 256;
952 			lpm_config.flags = 0;
953 
954 			lpm = rte_lpm_create(buf, socket, &lpm_config);
955 			if (lpm == NULL) {
956 				RTE_LOG(ERR, IP_RSMBL, "Cannot create LPM table\n");
957 				return -1;
958 			}
959 			socket_lpm[socket] = lpm;
960 		}
961 
962 		if (socket_lpm6[socket] == NULL) {
963 			RTE_LOG(INFO, IP_RSMBL, "Creating LPM6 table on socket %i\n", socket);
964 			snprintf(buf, sizeof(buf), "IP_RSMBL_LPM_%i", socket);
965 
966 			lpm6 = rte_lpm6_create(buf, socket, &lpm6_config);
967 			if (lpm6 == NULL) {
968 				RTE_LOG(ERR, IP_RSMBL, "Cannot create LPM table\n");
969 				return -1;
970 			}
971 			socket_lpm6[socket] = lpm6;
972 		}
973 	}
974 
975 	return 0;
976 }
977 
978 static void
979 queue_dump_stat(void)
980 {
981 	uint32_t i, lcore;
982 	const struct lcore_queue_conf *qconf;
983 
984 	for (lcore = 0; lcore < RTE_MAX_LCORE; lcore++) {
985 		if (rte_lcore_is_enabled(lcore) == 0)
986 			continue;
987 
988 		qconf = &lcore_queue_conf[lcore];
989 		for (i = 0; i < qconf->n_rx_queue; i++) {
990 
991 			fprintf(stdout, " -- lcoreid=%u portid=%hhu "
992 				"frag tbl stat:\n",
993 				lcore,  qconf->rx_queue_list[i].portid);
994 			rte_ip_frag_table_statistics_dump(stdout,
995 					qconf->rx_queue_list[i].frag_tbl);
996 			fprintf(stdout, "TX bursts:\t%" PRIu64 "\n"
997 				"TX packets _queued:\t%" PRIu64 "\n"
998 				"TX packets dropped:\t%" PRIu64 "\n"
999 				"TX packets send:\t%" PRIu64 "\n",
1000 				qconf->tx_stat.call,
1001 				qconf->tx_stat.queue,
1002 				qconf->tx_stat.drop,
1003 				qconf->tx_stat.send);
1004 		}
1005 	}
1006 }
1007 
1008 static void
1009 signal_handler(int signum)
1010 {
1011 	queue_dump_stat();
1012 	if (signum != SIGUSR1)
1013 		rte_exit(0, "received signal: %d, exiting\n", signum);
1014 }
1015 
1016 int
1017 main(int argc, char **argv)
1018 {
1019 	struct lcore_queue_conf *qconf;
1020 	struct rte_eth_dev_info dev_info;
1021 	struct rte_eth_txconf *txconf;
1022 	struct rx_queue *rxq;
1023 	int ret, socket;
1024 	unsigned nb_ports;
1025 	uint16_t queueid;
1026 	unsigned lcore_id = 0, rx_lcore_id = 0;
1027 	uint32_t n_tx_queue, nb_lcores;
1028 	uint8_t portid;
1029 
1030 	/* init EAL */
1031 	ret = rte_eal_init(argc, argv);
1032 	if (ret < 0)
1033 		rte_exit(EXIT_FAILURE, "Invalid EAL parameters\n");
1034 	argc -= ret;
1035 	argv += ret;
1036 
1037 	/* parse application arguments (after the EAL ones) */
1038 	ret = parse_args(argc, argv);
1039 	if (ret < 0)
1040 		rte_exit(EXIT_FAILURE, "Invalid IP reassembly parameters\n");
1041 
1042 	nb_ports = rte_eth_dev_count();
1043 	if (nb_ports == 0)
1044 		rte_exit(EXIT_FAILURE, "No ports found!\n");
1045 
1046 	nb_lcores = rte_lcore_count();
1047 
1048 	/* initialize structures (mempools, lpm etc.) */
1049 	if (init_mem() < 0)
1050 		rte_panic("Cannot initialize memory structures!\n");
1051 
1052 	/* check if portmask has non-existent ports */
1053 	if (enabled_port_mask & ~(RTE_LEN2MASK(nb_ports, unsigned)))
1054 		rte_exit(EXIT_FAILURE, "Non-existent ports in portmask!\n");
1055 
1056 	/* initialize all ports */
1057 	for (portid = 0; portid < nb_ports; portid++) {
1058 		/* skip ports that are not enabled */
1059 		if ((enabled_port_mask & (1 << portid)) == 0) {
1060 			printf("\nSkipping disabled port %d\n", portid);
1061 			continue;
1062 		}
1063 
1064 		qconf = &lcore_queue_conf[rx_lcore_id];
1065 
1066 		/* get the lcore_id for this port */
1067 		while (rte_lcore_is_enabled(rx_lcore_id) == 0 ||
1068 			   qconf->n_rx_queue == (unsigned)rx_queue_per_lcore) {
1069 
1070 			rx_lcore_id++;
1071 			if (rx_lcore_id >= RTE_MAX_LCORE)
1072 				rte_exit(EXIT_FAILURE, "Not enough cores\n");
1073 
1074 			qconf = &lcore_queue_conf[rx_lcore_id];
1075 		}
1076 
1077 		socket = rte_lcore_to_socket_id(portid);
1078 		if (socket == SOCKET_ID_ANY)
1079 			socket = 0;
1080 
1081 		queueid = qconf->n_rx_queue;
1082 		rxq = &qconf->rx_queue_list[queueid];
1083 		rxq->portid = portid;
1084 		rxq->lpm = socket_lpm[socket];
1085 		rxq->lpm6 = socket_lpm6[socket];
1086 		if (setup_queue_tbl(rxq, rx_lcore_id, queueid) < 0)
1087 			rte_exit(EXIT_FAILURE, "Failed to set up queue table\n");
1088 		qconf->n_rx_queue++;
1089 
1090 		/* init port */
1091 		printf("Initializing port %d ... ", portid );
1092 		fflush(stdout);
1093 
1094 		n_tx_queue = nb_lcores;
1095 		if (n_tx_queue > MAX_TX_QUEUE_PER_PORT)
1096 			n_tx_queue = MAX_TX_QUEUE_PER_PORT;
1097 		ret = rte_eth_dev_configure(portid, 1, (uint16_t)n_tx_queue,
1098 					    &port_conf);
1099 		if (ret < 0) {
1100 			printf("\n");
1101 			rte_exit(EXIT_FAILURE, "Cannot configure device: "
1102 				"err=%d, port=%d\n",
1103 				ret, portid);
1104 		}
1105 
1106 		/* init one RX queue */
1107 		ret = rte_eth_rx_queue_setup(portid, 0, nb_rxd,
1108 					     socket, NULL,
1109 					     rxq->pool);
1110 		if (ret < 0) {
1111 			printf("\n");
1112 			rte_exit(EXIT_FAILURE, "rte_eth_rx_queue_setup: "
1113 				"err=%d, port=%d\n",
1114 				ret, portid);
1115 		}
1116 
1117 		rte_eth_macaddr_get(portid, &ports_eth_addr[portid]);
1118 		print_ethaddr(" Address:", &ports_eth_addr[portid]);
1119 		printf("\n");
1120 
1121 		/* init one TX queue per couple (lcore,port) */
1122 		queueid = 0;
1123 		for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1124 			if (rte_lcore_is_enabled(lcore_id) == 0)
1125 				continue;
1126 
1127 			socket = (int) rte_lcore_to_socket_id(lcore_id);
1128 
1129 			printf("txq=%u,%d,%d ", lcore_id, queueid, socket);
1130 			fflush(stdout);
1131 
1132 			rte_eth_dev_info_get(portid, &dev_info);
1133 			txconf = &dev_info.default_txconf;
1134 			txconf->txq_flags = 0;
1135 
1136 			ret = rte_eth_tx_queue_setup(portid, queueid, nb_txd,
1137 					socket, txconf);
1138 			if (ret < 0)
1139 				rte_exit(EXIT_FAILURE, "rte_eth_tx_queue_setup: err=%d, "
1140 					"port=%d\n", ret, portid);
1141 
1142 			qconf = &lcore_queue_conf[lcore_id];
1143 			qconf->tx_queue_id[portid] = queueid;
1144 			setup_port_tbl(qconf, lcore_id, socket, portid);
1145 			queueid++;
1146 		}
1147 		printf("\n");
1148 	}
1149 
1150 	printf("\n");
1151 
1152 	/* start ports */
1153 	for (portid = 0; portid < nb_ports; portid++) {
1154 		if ((enabled_port_mask & (1 << portid)) == 0) {
1155 			continue;
1156 		}
1157 		/* Start device */
1158 		ret = rte_eth_dev_start(portid);
1159 		if (ret < 0)
1160 			rte_exit(EXIT_FAILURE, "rte_eth_dev_start: err=%d, port=%d\n",
1161 				ret, portid);
1162 
1163 		rte_eth_promiscuous_enable(portid);
1164 	}
1165 
1166 	if (init_routing_table() < 0)
1167 		rte_exit(EXIT_FAILURE, "Cannot init routing table\n");
1168 
1169 	check_all_ports_link_status((uint8_t)nb_ports, enabled_port_mask);
1170 
1171 	signal(SIGUSR1, signal_handler);
1172 	signal(SIGTERM, signal_handler);
1173 	signal(SIGINT, signal_handler);
1174 
1175 	/* launch per-lcore init on every lcore */
1176 	rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
1177 	RTE_LCORE_FOREACH_SLAVE(lcore_id) {
1178 		if (rte_eal_wait_lcore(lcore_id) < 0)
1179 			return -1;
1180 	}
1181 
1182 	return 0;
1183 }
1184