xref: /dpdk/examples/l3fwd-power/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 #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 <unistd.h>
45 #include <signal.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_tailq.h>
54 #include <rte_eal.h>
55 #include <rte_per_lcore.h>
56 #include <rte_launch.h>
57 #include <rte_atomic.h>
58 #include <rte_cycles.h>
59 #include <rte_prefetch.h>
60 #include <rte_lcore.h>
61 #include <rte_per_lcore.h>
62 #include <rte_branch_prediction.h>
63 #include <rte_interrupts.h>
64 #include <rte_pci.h>
65 #include <rte_random.h>
66 #include <rte_debug.h>
67 #include <rte_ether.h>
68 #include <rte_ethdev.h>
69 #include <rte_ring.h>
70 #include <rte_mempool.h>
71 #include <rte_mbuf.h>
72 #include <rte_ip.h>
73 #include <rte_tcp.h>
74 #include <rte_udp.h>
75 #include <rte_string_fns.h>
76 #include <rte_timer.h>
77 #include <rte_power.h>
78 
79 #include "main.h"
80 
81 #define RTE_LOGTYPE_L3FWD_POWER RTE_LOGTYPE_USER1
82 
83 #define MAX_PKT_BURST 32
84 
85 #define MIN_ZERO_POLL_COUNT 5
86 
87 /* around 100ms at 2 Ghz */
88 #define TIMER_RESOLUTION_CYCLES           200000000ULL
89 /* 100 ms interval */
90 #define TIMER_NUMBER_PER_SECOND           10
91 /* 100000 us */
92 #define SCALING_PERIOD                    (1000000/TIMER_NUMBER_PER_SECOND)
93 #define SCALING_DOWN_TIME_RATIO_THRESHOLD 0.25
94 
95 #define APP_LOOKUP_EXACT_MATCH          0
96 #define APP_LOOKUP_LPM                  1
97 #define DO_RFC_1812_CHECKS
98 
99 #ifndef APP_LOOKUP_METHOD
100 #define APP_LOOKUP_METHOD             APP_LOOKUP_LPM
101 #endif
102 
103 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
104 #include <rte_hash.h>
105 #elif (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
106 #include <rte_lpm.h>
107 #else
108 #error "APP_LOOKUP_METHOD set to incorrect value"
109 #endif
110 
111 #ifndef IPv6_BYTES
112 #define IPv6_BYTES_FMT "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"\
113                        "%02x%02x:%02x%02x:%02x%02x:%02x%02x"
114 #define IPv6_BYTES(addr) \
115 	addr[0],  addr[1], addr[2],  addr[3], \
116 	addr[4],  addr[5], addr[6],  addr[7], \
117 	addr[8],  addr[9], addr[10], addr[11],\
118 	addr[12], addr[13],addr[14], addr[15]
119 #endif
120 
121 #define MAX_JUMBO_PKT_LEN  9600
122 
123 #define IPV6_ADDR_LEN 16
124 
125 #define MEMPOOL_CACHE_SIZE 256
126 
127 #define MBUF_SIZE (2048 + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
128 
129 /*
130  * This expression is used to calculate the number of mbufs needed depending on
131  * user input, taking into account memory for rx and tx hardware rings, cache
132  * per lcore and mtable per port per lcore. RTE_MAX is used to ensure that
133  * NB_MBUF never goes below a minimum value of 8192.
134  */
135 
136 #define NB_MBUF RTE_MAX	( \
137 	(nb_ports*nb_rx_queue*RTE_TEST_RX_DESC_DEFAULT + \
138 	nb_ports*nb_lcores*MAX_PKT_BURST + \
139 	nb_ports*n_tx_queue*RTE_TEST_TX_DESC_DEFAULT + \
140 	nb_lcores*MEMPOOL_CACHE_SIZE), \
141 	(unsigned)8192)
142 
143 #define BURST_TX_DRAIN_US 100 /* TX drain every ~100us */
144 
145 #define NB_SOCKETS 8
146 
147 /* Configure how many packets ahead to prefetch, when reading packets */
148 #define PREFETCH_OFFSET	3
149 
150 /*
151  * Configurable number of RX/TX ring descriptors
152  */
153 #define RTE_TEST_RX_DESC_DEFAULT 128
154 #define RTE_TEST_TX_DESC_DEFAULT 512
155 static uint16_t nb_rxd = RTE_TEST_RX_DESC_DEFAULT;
156 static uint16_t nb_txd = RTE_TEST_TX_DESC_DEFAULT;
157 
158 /* ethernet addresses of ports */
159 static struct ether_addr ports_eth_addr[RTE_MAX_ETHPORTS];
160 
161 /* mask of enabled ports */
162 static uint32_t enabled_port_mask = 0;
163 /* Ports set in promiscuous mode off by default. */
164 static int promiscuous_on = 0;
165 /* NUMA is enabled by default. */
166 static int numa_on = 1;
167 
168 enum freq_scale_hint_t
169 {
170 	FREQ_LOWER    =      -1,
171 	FREQ_CURRENT  =       0,
172 	FREQ_HIGHER   =       1,
173 	FREQ_HIGHEST  =       2
174 };
175 
176 struct mbuf_table {
177 	uint16_t len;
178 	struct rte_mbuf *m_table[MAX_PKT_BURST];
179 };
180 
181 struct lcore_rx_queue {
182 	uint8_t port_id;
183 	uint8_t queue_id;
184 	enum freq_scale_hint_t freq_up_hint;
185 	uint32_t zero_rx_packet_count;
186 	uint32_t idle_hint;
187 } __rte_cache_aligned;
188 
189 #define MAX_RX_QUEUE_PER_LCORE 16
190 #define MAX_TX_QUEUE_PER_PORT RTE_MAX_ETHPORTS
191 #define MAX_RX_QUEUE_PER_PORT 128
192 
193 #define MAX_LCORE_PARAMS 1024
194 struct lcore_params {
195 	uint8_t port_id;
196 	uint8_t queue_id;
197 	uint8_t lcore_id;
198 } __rte_cache_aligned;
199 
200 static struct lcore_params lcore_params_array[MAX_LCORE_PARAMS];
201 static struct lcore_params lcore_params_array_default[] = {
202 	{0, 0, 2},
203 	{0, 1, 2},
204 	{0, 2, 2},
205 	{1, 0, 2},
206 	{1, 1, 2},
207 	{1, 2, 2},
208 	{2, 0, 2},
209 	{3, 0, 3},
210 	{3, 1, 3},
211 };
212 
213 static struct lcore_params * lcore_params = lcore_params_array_default;
214 static uint16_t nb_lcore_params = sizeof(lcore_params_array_default) /
215 				sizeof(lcore_params_array_default[0]);
216 
217 static struct rte_eth_conf port_conf = {
218 	.rxmode = {
219 		.mq_mode	= ETH_MQ_RX_RSS,
220 		.max_rx_pkt_len = ETHER_MAX_LEN,
221 		.split_hdr_size = 0,
222 		.header_split   = 0, /**< Header Split disabled */
223 		.hw_ip_checksum = 1, /**< IP checksum offload enabled */
224 		.hw_vlan_filter = 0, /**< VLAN filtering disabled */
225 		.jumbo_frame    = 0, /**< Jumbo Frame Support disabled */
226 		.hw_strip_crc   = 0, /**< CRC stripped by hardware */
227 	},
228 	.rx_adv_conf = {
229 		.rss_conf = {
230 			.rss_key = NULL,
231 			.rss_hf = ETH_RSS_IP,
232 		},
233 	},
234 	.txmode = {
235 		.mq_mode = ETH_DCB_NONE,
236 	},
237 };
238 
239 static struct rte_mempool * pktmbuf_pool[NB_SOCKETS];
240 
241 
242 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
243 
244 #ifdef RTE_MACHINE_CPUFLAG_SSE4_2
245 #include <rte_hash_crc.h>
246 #define DEFAULT_HASH_FUNC       rte_hash_crc
247 #else
248 #include <rte_jhash.h>
249 #define DEFAULT_HASH_FUNC       rte_jhash
250 #endif
251 
252 struct ipv4_5tuple {
253 	uint32_t ip_dst;
254 	uint32_t ip_src;
255 	uint16_t port_dst;
256 	uint16_t port_src;
257 	uint8_t  proto;
258 } __attribute__((__packed__));
259 
260 struct ipv6_5tuple {
261 	uint8_t  ip_dst[IPV6_ADDR_LEN];
262 	uint8_t  ip_src[IPV6_ADDR_LEN];
263 	uint16_t port_dst;
264 	uint16_t port_src;
265 	uint8_t  proto;
266 } __attribute__((__packed__));
267 
268 struct ipv4_l3fwd_route {
269 	struct ipv4_5tuple key;
270 	uint8_t if_out;
271 };
272 
273 struct ipv6_l3fwd_route {
274 	struct ipv6_5tuple key;
275 	uint8_t if_out;
276 };
277 
278 static struct ipv4_l3fwd_route ipv4_l3fwd_route_array[] = {
279 	{{IPv4(100,10,0,1), IPv4(200,10,0,1), 101, 11, IPPROTO_TCP}, 0},
280 	{{IPv4(100,20,0,2), IPv4(200,20,0,2), 102, 12, IPPROTO_TCP}, 1},
281 	{{IPv4(100,30,0,3), IPv4(200,30,0,3), 103, 13, IPPROTO_TCP}, 2},
282 	{{IPv4(100,40,0,4), IPv4(200,40,0,4), 104, 14, IPPROTO_TCP}, 3},
283 };
284 
285 static struct ipv6_l3fwd_route ipv6_l3fwd_route_array[] = {
286 	{
287 		{
288 			{0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
289 			 0x02, 0x1b, 0x21, 0xff, 0xfe, 0x91, 0x38, 0x05},
290 			{0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
291 			 0x02, 0x1e, 0x67, 0xff, 0xfe, 0x0d, 0xb6, 0x0a},
292 			 1, 10, IPPROTO_UDP
293 		}, 4
294 	},
295 };
296 
297 typedef struct rte_hash lookup_struct_t;
298 static lookup_struct_t *ipv4_l3fwd_lookup_struct[NB_SOCKETS];
299 static lookup_struct_t *ipv6_l3fwd_lookup_struct[NB_SOCKETS];
300 
301 #define L3FWD_HASH_ENTRIES	1024
302 
303 #define IPV4_L3FWD_NUM_ROUTES \
304 	(sizeof(ipv4_l3fwd_route_array) / sizeof(ipv4_l3fwd_route_array[0]))
305 
306 #define IPV6_L3FWD_NUM_ROUTES \
307 	(sizeof(ipv6_l3fwd_route_array) / sizeof(ipv6_l3fwd_route_array[0]))
308 
309 static uint8_t ipv4_l3fwd_out_if[L3FWD_HASH_ENTRIES] __rte_cache_aligned;
310 static uint8_t ipv6_l3fwd_out_if[L3FWD_HASH_ENTRIES] __rte_cache_aligned;
311 #endif
312 
313 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
314 struct ipv4_l3fwd_route {
315 	uint32_t ip;
316 	uint8_t  depth;
317 	uint8_t  if_out;
318 };
319 
320 static struct ipv4_l3fwd_route ipv4_l3fwd_route_array[] = {
321 	{IPv4(1,1,1,0), 24, 0},
322 	{IPv4(2,1,1,0), 24, 1},
323 	{IPv4(3,1,1,0), 24, 2},
324 	{IPv4(4,1,1,0), 24, 3},
325 	{IPv4(5,1,1,0), 24, 4},
326 	{IPv4(6,1,1,0), 24, 5},
327 	{IPv4(7,1,1,0), 24, 6},
328 	{IPv4(8,1,1,0), 24, 7},
329 };
330 
331 #define IPV4_L3FWD_NUM_ROUTES \
332 	(sizeof(ipv4_l3fwd_route_array) / sizeof(ipv4_l3fwd_route_array[0]))
333 
334 #define IPV4_L3FWD_LPM_MAX_RULES     1024
335 
336 typedef struct rte_lpm lookup_struct_t;
337 static lookup_struct_t *ipv4_l3fwd_lookup_struct[NB_SOCKETS];
338 #endif
339 
340 struct lcore_conf {
341 	uint16_t n_rx_queue;
342 	struct lcore_rx_queue rx_queue_list[MAX_RX_QUEUE_PER_LCORE];
343 	uint16_t tx_queue_id[RTE_MAX_ETHPORTS];
344 	struct mbuf_table tx_mbufs[RTE_MAX_ETHPORTS];
345 	lookup_struct_t * ipv4_lookup_struct;
346 	lookup_struct_t * ipv6_lookup_struct;
347 } __rte_cache_aligned;
348 
349 struct lcore_stats {
350 	/* total sleep time in ms since last frequency scaling down */
351 	uint32_t sleep_time;
352 	/* number of long sleep recently */
353 	uint32_t nb_long_sleep;
354 	/* freq. scaling up trend */
355 	uint32_t trend;
356 	/* total packet processed recently */
357 	uint64_t nb_rx_processed;
358 	/* total iterations looped recently */
359 	uint64_t nb_iteration_looped;
360 	uint32_t padding[9];
361 } __rte_cache_aligned;
362 
363 static struct lcore_conf lcore_conf[RTE_MAX_LCORE] __rte_cache_aligned;
364 static struct lcore_stats stats[RTE_MAX_LCORE] __rte_cache_aligned;
365 static struct rte_timer power_timers[RTE_MAX_LCORE];
366 
367 static inline uint32_t power_idle_heuristic(uint32_t zero_rx_packet_count);
368 static inline enum freq_scale_hint_t power_freq_scaleup_heuristic( \
369 			unsigned lcore_id, uint8_t port_id, uint16_t queue_id);
370 
371 /* exit signal handler */
372 static void
373 signal_exit_now(int sigtype)
374 {
375 	unsigned lcore_id;
376 	int ret;
377 
378 	if (sigtype == SIGINT) {
379 		for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
380 			if (rte_lcore_is_enabled(lcore_id) == 0)
381 				continue;
382 
383 			/* init power management library */
384 			ret = rte_power_exit(lcore_id);
385 			if (ret)
386 				rte_exit(EXIT_FAILURE, "Power management "
387 					"library de-initialization failed on "
388 							"core%u\n", lcore_id);
389 		}
390 	}
391 
392 	rte_exit(EXIT_SUCCESS, "User forced exit\n");
393 }
394 
395 /*  Freqency scale down timer callback */
396 static void
397 power_timer_cb(__attribute__((unused)) struct rte_timer *tim,
398 			  __attribute__((unused)) void *arg)
399 {
400 	uint64_t hz;
401 	float sleep_time_ratio;
402 	unsigned lcore_id = rte_lcore_id();
403 
404 	/* accumulate total execution time in us when callback is invoked */
405 	sleep_time_ratio = (float)(stats[lcore_id].sleep_time) /
406 					(float)SCALING_PERIOD;
407 
408 	/**
409 	 * check whether need to scale down frequency a step if it sleep a lot.
410 	 */
411 	if (sleep_time_ratio >= SCALING_DOWN_TIME_RATIO_THRESHOLD)
412 		rte_power_freq_down(lcore_id);
413 	else if ( (unsigned)(stats[lcore_id].nb_rx_processed /
414 		stats[lcore_id].nb_iteration_looped) < MAX_PKT_BURST)
415 		/**
416 		 * scale down a step if average packet per iteration less
417 		 * than expectation.
418 		 */
419 		rte_power_freq_down(lcore_id);
420 
421 	/**
422 	 * initialize another timer according to current frequency to ensure
423 	 * timer interval is relatively fixed.
424 	 */
425 	hz = rte_get_timer_hz();
426 	rte_timer_reset(&power_timers[lcore_id], hz/TIMER_NUMBER_PER_SECOND,
427 				SINGLE, lcore_id, power_timer_cb, NULL);
428 
429 	stats[lcore_id].nb_rx_processed = 0;
430 	stats[lcore_id].nb_iteration_looped = 0;
431 
432 	stats[lcore_id].sleep_time = 0;
433 }
434 
435 /* Send burst of packets on an output interface */
436 static inline int
437 send_burst(struct lcore_conf *qconf, uint16_t n, uint8_t port)
438 {
439 	struct rte_mbuf **m_table;
440 	int ret;
441 	uint16_t queueid;
442 
443 	queueid = qconf->tx_queue_id[port];
444 	m_table = (struct rte_mbuf **)qconf->tx_mbufs[port].m_table;
445 
446 	ret = rte_eth_tx_burst(port, queueid, m_table, n);
447 	if (unlikely(ret < n)) {
448 		do {
449 			rte_pktmbuf_free(m_table[ret]);
450 		} while (++ret < n);
451 	}
452 
453 	return 0;
454 }
455 
456 /* Enqueue a single packet, and send burst if queue is filled */
457 static inline int
458 send_single_packet(struct rte_mbuf *m, uint8_t port)
459 {
460 	uint32_t lcore_id;
461 	uint16_t len;
462 	struct lcore_conf *qconf;
463 
464 	lcore_id = rte_lcore_id();
465 
466 	qconf = &lcore_conf[lcore_id];
467 	len = qconf->tx_mbufs[port].len;
468 	qconf->tx_mbufs[port].m_table[len] = m;
469 	len++;
470 
471 	/* enough pkts to be sent */
472 	if (unlikely(len == MAX_PKT_BURST)) {
473 		send_burst(qconf, MAX_PKT_BURST, port);
474 		len = 0;
475 	}
476 
477 	qconf->tx_mbufs[port].len = len;
478 	return 0;
479 }
480 
481 #ifdef DO_RFC_1812_CHECKS
482 static inline int
483 is_valid_ipv4_pkt(struct ipv4_hdr *pkt, uint32_t link_len)
484 {
485 	/* From http://www.rfc-editor.org/rfc/rfc1812.txt section 5.2.2 */
486 	/*
487 	 * 1. The packet length reported by the Link Layer must be large
488 	 * enough to hold the minimum length legal IP datagram (20 bytes).
489 	 */
490 	if (link_len < sizeof(struct ipv4_hdr))
491 		return -1;
492 
493 	/* 2. The IP checksum must be correct. */
494 	/* this is checked in H/W */
495 
496 	/*
497 	 * 3. The IP version number must be 4. If the version number is not 4
498 	 * then the packet may be another version of IP, such as IPng or
499 	 * ST-II.
500 	 */
501 	if (((pkt->version_ihl) >> 4) != 4)
502 		return -3;
503 	/*
504 	 * 4. The IP header length field must be large enough to hold the
505 	 * minimum length legal IP datagram (20 bytes = 5 words).
506 	 */
507 	if ((pkt->version_ihl & 0xf) < 5)
508 		return -4;
509 
510 	/*
511 	 * 5. The IP total length field must be large enough to hold the IP
512 	 * datagram header, whose length is specified in the IP header length
513 	 * field.
514 	 */
515 	if (rte_cpu_to_be_16(pkt->total_length) < sizeof(struct ipv4_hdr))
516 		return -5;
517 
518 	return 0;
519 }
520 #endif
521 
522 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
523 static void
524 print_ipv4_key(struct ipv4_5tuple key)
525 {
526 	printf("IP dst = %08x, IP src = %08x, port dst = %d, port src = %d, "
527 		"proto = %d\n", (unsigned)key.ip_dst, (unsigned)key.ip_src,
528 				key.port_dst, key.port_src, key.proto);
529 }
530 static void
531 print_ipv6_key(struct ipv6_5tuple key)
532 {
533 	printf( "IP dst = " IPv6_BYTES_FMT ", IP src = " IPv6_BYTES_FMT ", "
534 	        "port dst = %d, port src = %d, proto = %d\n",
535 	        IPv6_BYTES(key.ip_dst), IPv6_BYTES(key.ip_src),
536 	        key.port_dst, key.port_src, key.proto);
537 }
538 
539 static inline uint8_t
540 get_ipv4_dst_port(struct ipv4_hdr *ipv4_hdr, uint8_t portid,
541 		lookup_struct_t * ipv4_l3fwd_lookup_struct)
542 {
543 	struct ipv4_5tuple key;
544 	struct tcp_hdr *tcp;
545 	struct udp_hdr *udp;
546 	int ret = 0;
547 
548 	key.ip_dst = rte_be_to_cpu_32(ipv4_hdr->dst_addr);
549 	key.ip_src = rte_be_to_cpu_32(ipv4_hdr->src_addr);
550 	key.proto = ipv4_hdr->next_proto_id;
551 
552 	switch (ipv4_hdr->next_proto_id) {
553 	case IPPROTO_TCP:
554 		tcp = (struct tcp_hdr *)((unsigned char *)ipv4_hdr +
555 					sizeof(struct ipv4_hdr));
556 		key.port_dst = rte_be_to_cpu_16(tcp->dst_port);
557 		key.port_src = rte_be_to_cpu_16(tcp->src_port);
558 		break;
559 
560 	case IPPROTO_UDP:
561 		udp = (struct udp_hdr *)((unsigned char *)ipv4_hdr +
562 					sizeof(struct ipv4_hdr));
563 		key.port_dst = rte_be_to_cpu_16(udp->dst_port);
564 		key.port_src = rte_be_to_cpu_16(udp->src_port);
565 		break;
566 
567 	default:
568 		key.port_dst = 0;
569 		key.port_src = 0;
570 		break;
571 	}
572 
573 	/* Find destination port */
574 	ret = rte_hash_lookup(ipv4_l3fwd_lookup_struct, (const void *)&key);
575 	return (uint8_t)((ret < 0)? portid : ipv4_l3fwd_out_if[ret]);
576 }
577 
578 static inline uint8_t
579 get_ipv6_dst_port(struct ipv6_hdr *ipv6_hdr,  uint8_t portid,
580 			lookup_struct_t *ipv6_l3fwd_lookup_struct)
581 {
582 	struct ipv6_5tuple key;
583 	struct tcp_hdr *tcp;
584 	struct udp_hdr *udp;
585 	int ret = 0;
586 
587 	memcpy(key.ip_dst, ipv6_hdr->dst_addr, IPV6_ADDR_LEN);
588 	memcpy(key.ip_src, ipv6_hdr->src_addr, IPV6_ADDR_LEN);
589 
590 	key.proto = ipv6_hdr->proto;
591 
592 	switch (ipv6_hdr->proto) {
593 	case IPPROTO_TCP:
594 		tcp = (struct tcp_hdr *)((unsigned char *) ipv6_hdr +
595 					sizeof(struct ipv6_hdr));
596 		key.port_dst = rte_be_to_cpu_16(tcp->dst_port);
597 		key.port_src = rte_be_to_cpu_16(tcp->src_port);
598 		break;
599 
600 	case IPPROTO_UDP:
601 		udp = (struct udp_hdr *)((unsigned char *) ipv6_hdr +
602 					sizeof(struct ipv6_hdr));
603 		key.port_dst = rte_be_to_cpu_16(udp->dst_port);
604 		key.port_src = rte_be_to_cpu_16(udp->src_port);
605 		break;
606 
607 	default:
608 		key.port_dst = 0;
609 		key.port_src = 0;
610 		break;
611 	}
612 
613 	/* Find destination port */
614 	ret = rte_hash_lookup(ipv6_l3fwd_lookup_struct, (const void *)&key);
615 	return (uint8_t)((ret < 0)? portid : ipv6_l3fwd_out_if[ret]);
616 }
617 #endif
618 
619 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
620 static inline uint8_t
621 get_ipv4_dst_port(struct ipv4_hdr *ipv4_hdr, uint8_t portid,
622 		lookup_struct_t *ipv4_l3fwd_lookup_struct)
623 {
624 	uint8_t next_hop;
625 
626 	return (uint8_t) ((rte_lpm_lookup(ipv4_l3fwd_lookup_struct,
627 			rte_be_to_cpu_32(ipv4_hdr->dst_addr), &next_hop) == 0)?
628 			next_hop : portid);
629 }
630 #endif
631 
632 static inline void
633 l3fwd_simple_forward(struct rte_mbuf *m, uint8_t portid,
634 				struct lcore_conf *qconf)
635 {
636 	struct ether_hdr *eth_hdr;
637 	struct ipv4_hdr *ipv4_hdr;
638 	void *d_addr_bytes;
639 	uint8_t dst_port;
640 
641 	eth_hdr = rte_pktmbuf_mtod(m, struct ether_hdr *);
642 
643 	if (m->ol_flags & PKT_RX_IPV4_HDR) {
644 		/* Handle IPv4 headers.*/
645 		ipv4_hdr =
646 			(struct ipv4_hdr *)(rte_pktmbuf_mtod(m, unsigned char*)
647 						+ sizeof(struct ether_hdr));
648 
649 #ifdef DO_RFC_1812_CHECKS
650 		/* Check to make sure the packet is valid (RFC1812) */
651 		if (is_valid_ipv4_pkt(ipv4_hdr, m->pkt_len) < 0) {
652 			rte_pktmbuf_free(m);
653 			return;
654 		}
655 #endif
656 
657 		dst_port = get_ipv4_dst_port(ipv4_hdr, portid,
658 					qconf->ipv4_lookup_struct);
659 		if (dst_port >= RTE_MAX_ETHPORTS ||
660 				(enabled_port_mask & 1 << dst_port) == 0)
661 			dst_port = portid;
662 
663 		/* 02:00:00:00:00:xx */
664 		d_addr_bytes = &eth_hdr->d_addr.addr_bytes[0];
665 		*((uint64_t *)d_addr_bytes) =
666 			0x000000000002 + ((uint64_t)dst_port << 40);
667 
668 #ifdef DO_RFC_1812_CHECKS
669 		/* Update time to live and header checksum */
670 		--(ipv4_hdr->time_to_live);
671 		++(ipv4_hdr->hdr_checksum);
672 #endif
673 
674 		/* src addr */
675 		ether_addr_copy(&ports_eth_addr[dst_port], &eth_hdr->s_addr);
676 
677 		send_single_packet(m, dst_port);
678 	}
679 	else {
680 		/* Handle IPv6 headers.*/
681 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
682 		struct ipv6_hdr *ipv6_hdr;
683 
684 		ipv6_hdr =
685 			(struct ipv6_hdr *)(rte_pktmbuf_mtod(m, unsigned char*)
686 						+ sizeof(struct ether_hdr));
687 
688 		dst_port = get_ipv6_dst_port(ipv6_hdr, portid,
689 					qconf->ipv6_lookup_struct);
690 
691 		if (dst_port >= RTE_MAX_ETHPORTS ||
692 				(enabled_port_mask & 1 << dst_port) == 0)
693 			dst_port = portid;
694 
695 		/* 02:00:00:00:00:xx */
696 		d_addr_bytes = &eth_hdr->d_addr.addr_bytes[0];
697 		*((uint64_t *)d_addr_bytes) =
698 			0x000000000002 + ((uint64_t)dst_port << 40);
699 
700 		/* src addr */
701 		ether_addr_copy(&ports_eth_addr[dst_port], &eth_hdr->s_addr);
702 
703 		send_single_packet(m, dst_port);
704 #else
705 		/* We don't currently handle IPv6 packets in LPM mode. */
706 		rte_pktmbuf_free(m);
707 #endif
708 	}
709 
710 }
711 
712 #define SLEEP_GEAR1_THRESHOLD            100
713 #define SLEEP_GEAR2_THRESHOLD            1000
714 
715 static inline uint32_t
716 power_idle_heuristic(uint32_t zero_rx_packet_count)
717 {
718 	/* If zero count is less than 100, use it as the sleep time in us */
719 	if (zero_rx_packet_count < SLEEP_GEAR1_THRESHOLD)
720 		return zero_rx_packet_count;
721 	/* If zero count is less than 1000, sleep time should be 100 us */
722 	else if ((zero_rx_packet_count >= SLEEP_GEAR1_THRESHOLD) &&
723 			(zero_rx_packet_count < SLEEP_GEAR2_THRESHOLD))
724 		return SLEEP_GEAR1_THRESHOLD;
725 	/* If zero count is greater than 1000, sleep time should be 1000 us */
726 	else if (zero_rx_packet_count >= SLEEP_GEAR2_THRESHOLD)
727 		return SLEEP_GEAR2_THRESHOLD;
728 
729 	return 0;
730 }
731 
732 static inline enum freq_scale_hint_t
733 power_freq_scaleup_heuristic(unsigned lcore_id,
734 			     uint8_t port_id,
735 			     uint16_t queue_id)
736 {
737 /**
738  * HW Rx queue size is 128 by default, Rx burst read at maximum 32 entries
739  * per iteration
740  */
741 #define FREQ_GEAR1_RX_PACKET_THRESHOLD             MAX_PKT_BURST
742 #define FREQ_GEAR2_RX_PACKET_THRESHOLD             (MAX_PKT_BURST*2)
743 #define FREQ_GEAR3_RX_PACKET_THRESHOLD             (MAX_PKT_BURST*3)
744 #define FREQ_UP_TREND1_ACC   1
745 #define FREQ_UP_TREND2_ACC   100
746 #define FREQ_UP_THRESHOLD    10000
747 
748 	if (likely(rte_eth_rx_descriptor_done(port_id, queue_id,
749 			FREQ_GEAR3_RX_PACKET_THRESHOLD) > 0)) {
750 		stats[lcore_id].trend = 0;
751 		return FREQ_HIGHEST;
752 	} else if (likely(rte_eth_rx_descriptor_done(port_id, queue_id,
753 			FREQ_GEAR2_RX_PACKET_THRESHOLD) > 0))
754 		stats[lcore_id].trend += FREQ_UP_TREND2_ACC;
755 	else if (likely(rte_eth_rx_descriptor_done(port_id, queue_id,
756 			FREQ_GEAR1_RX_PACKET_THRESHOLD) > 0))
757 		stats[lcore_id].trend += FREQ_UP_TREND1_ACC;
758 
759 	if (likely(stats[lcore_id].trend > FREQ_UP_THRESHOLD)) {
760 		stats[lcore_id].trend = 0;
761 		return FREQ_HIGHER;
762 	}
763 
764 	return FREQ_CURRENT;
765 }
766 
767 /* main processing loop */
768 static int
769 main_loop(__attribute__((unused)) void *dummy)
770 {
771 	struct rte_mbuf *pkts_burst[MAX_PKT_BURST];
772 	unsigned lcore_id;
773 	uint64_t prev_tsc, diff_tsc, cur_tsc;
774 	uint64_t prev_tsc_power = 0, cur_tsc_power, diff_tsc_power;
775 	int i, j, nb_rx;
776 	uint8_t portid, queueid;
777 	struct lcore_conf *qconf;
778 	struct lcore_rx_queue *rx_queue;
779 	enum freq_scale_hint_t lcore_scaleup_hint;
780 
781 	uint32_t lcore_rx_idle_count = 0;
782 	uint32_t lcore_idle_hint = 0;
783 
784 	const uint64_t drain_tsc = (rte_get_tsc_hz() + US_PER_S - 1) / US_PER_S * BURST_TX_DRAIN_US;
785 
786 	prev_tsc = 0;
787 
788 	lcore_id = rte_lcore_id();
789 	qconf = &lcore_conf[lcore_id];
790 
791 	if (qconf->n_rx_queue == 0) {
792 		RTE_LOG(INFO, L3FWD_POWER, "lcore %u has nothing to do\n", lcore_id);
793 		return 0;
794 	}
795 
796 	RTE_LOG(INFO, L3FWD_POWER, "entering main loop on lcore %u\n", lcore_id);
797 
798 	for (i = 0; i < qconf->n_rx_queue; i++) {
799 
800 		portid = qconf->rx_queue_list[i].port_id;
801 		queueid = qconf->rx_queue_list[i].queue_id;
802 		RTE_LOG(INFO, L3FWD_POWER, " -- lcoreid=%u portid=%hhu "
803 			"rxqueueid=%hhu\n", lcore_id, portid, queueid);
804 	}
805 
806 	while (1) {
807 		stats[lcore_id].nb_iteration_looped++;
808 
809 		cur_tsc = rte_rdtsc();
810 		cur_tsc_power = cur_tsc;
811 
812 		/*
813 		 * TX burst queue drain
814 		 */
815 		diff_tsc = cur_tsc - prev_tsc;
816 		if (unlikely(diff_tsc > drain_tsc)) {
817 
818 			/*
819 			 * This could be optimized (use queueid instead of
820 			 * portid), but it is not called so often
821 			 */
822 			for (portid = 0; portid < RTE_MAX_ETHPORTS; portid++) {
823 				if (qconf->tx_mbufs[portid].len == 0)
824 					continue;
825 				send_burst(&lcore_conf[lcore_id],
826 					qconf->tx_mbufs[portid].len,
827 					portid);
828 				qconf->tx_mbufs[portid].len = 0;
829 			}
830 
831 			prev_tsc = cur_tsc;
832 		}
833 
834 		diff_tsc_power = cur_tsc_power - prev_tsc_power;
835 		if (diff_tsc_power > TIMER_RESOLUTION_CYCLES) {
836 			rte_timer_manage();
837 			prev_tsc_power = cur_tsc_power;
838 		}
839 
840 		/*
841 		 * Read packet from RX queues
842 		 */
843 		lcore_scaleup_hint = FREQ_CURRENT;
844 		lcore_rx_idle_count = 0;
845 		for (i = 0; i < qconf->n_rx_queue; ++i) {
846 			rx_queue = &(qconf->rx_queue_list[i]);
847 			rx_queue->idle_hint = 0;
848 			portid = rx_queue->port_id;
849 			queueid = rx_queue->queue_id;
850 
851 			nb_rx = rte_eth_rx_burst(portid, queueid, pkts_burst,
852 								MAX_PKT_BURST);
853 			stats[lcore_id].nb_rx_processed += nb_rx;
854 			if (unlikely(nb_rx == 0)) {
855 				/**
856 				 * no packet received from rx queue, try to
857 				 * sleep for a while forcing CPU enter deeper
858 				 * C states.
859 				 */
860 				rx_queue->zero_rx_packet_count++;
861 
862 				if (rx_queue->zero_rx_packet_count <=
863 							MIN_ZERO_POLL_COUNT)
864 					continue;
865 
866 				rx_queue->idle_hint = power_idle_heuristic(\
867 					rx_queue->zero_rx_packet_count);
868 				lcore_rx_idle_count++;
869 			} else {
870 				rx_queue->zero_rx_packet_count = 0;
871 
872 				/**
873 				 * do not scale up frequency immediately as
874 				 * user to kernel space communication is costly
875 				 * which might impact packet I/O for received
876 				 * packets.
877 				 */
878 				rx_queue->freq_up_hint =
879 					power_freq_scaleup_heuristic(lcore_id,
880 							portid, queueid);
881  			}
882 
883 			/* Prefetch first packets */
884 			for (j = 0; j < PREFETCH_OFFSET && j < nb_rx; j++) {
885 				rte_prefetch0(rte_pktmbuf_mtod(
886 						pkts_burst[j], void *));
887 			}
888 
889 			/* Prefetch and forward already prefetched packets */
890 			for (j = 0; j < (nb_rx - PREFETCH_OFFSET); j++) {
891 				rte_prefetch0(rte_pktmbuf_mtod(pkts_burst[
892 						j + PREFETCH_OFFSET], void *));
893 				l3fwd_simple_forward(pkts_burst[j], portid,
894 								qconf);
895 			}
896 
897 			/* Forward remaining prefetched packets */
898 			for (; j < nb_rx; j++) {
899 				l3fwd_simple_forward(pkts_burst[j], portid,
900 								qconf);
901 			}
902 		}
903 
904 		if (likely(lcore_rx_idle_count != qconf->n_rx_queue)) {
905 			for (i = 1, lcore_scaleup_hint =
906 				qconf->rx_queue_list[0].freq_up_hint;
907 					i < qconf->n_rx_queue; ++i) {
908 				rx_queue = &(qconf->rx_queue_list[i]);
909 				if (rx_queue->freq_up_hint >
910 						lcore_scaleup_hint)
911 					lcore_scaleup_hint =
912 						rx_queue->freq_up_hint;
913 			}
914 
915 			if (lcore_scaleup_hint == FREQ_HIGHEST)
916 				rte_power_freq_max(lcore_id);
917 			else if (lcore_scaleup_hint == FREQ_HIGHER)
918 				rte_power_freq_up(lcore_id);
919 		} else {
920 			/**
921 			 * All Rx queues empty in recent consecutive polls,
922 			 * sleep in a conservative manner, meaning sleep as
923  			 * less as possible.
924  			 */
925 			for (i = 1, lcore_idle_hint =
926 				qconf->rx_queue_list[0].idle_hint;
927 					i < qconf->n_rx_queue; ++i) {
928 				rx_queue = &(qconf->rx_queue_list[i]);
929 				if (rx_queue->idle_hint < lcore_idle_hint)
930 					lcore_idle_hint = rx_queue->idle_hint;
931 			}
932 
933 			if ( lcore_idle_hint < SLEEP_GEAR1_THRESHOLD)
934 				/**
935 				 * execute "pause" instruction to avoid context
936 				 * switch for short sleep.
937  				 */
938 				rte_delay_us(lcore_idle_hint);
939 			else
940 				/* long sleep force runing thread to suspend */
941 				usleep(lcore_idle_hint);
942 
943 			stats[lcore_id].sleep_time += lcore_idle_hint;
944 		}
945 	}
946 }
947 
948 static int
949 check_lcore_params(void)
950 {
951 	uint8_t queue, lcore;
952 	uint16_t i;
953 	int socketid;
954 
955 	for (i = 0; i < nb_lcore_params; ++i) {
956 		queue = lcore_params[i].queue_id;
957 		if (queue >= MAX_RX_QUEUE_PER_PORT) {
958 			printf("invalid queue number: %hhu\n", queue);
959 			return -1;
960 		}
961 		lcore = lcore_params[i].lcore_id;
962 		if (!rte_lcore_is_enabled(lcore)) {
963 			printf("error: lcore %hhu is not enabled in lcore "
964 							"mask\n", lcore);
965 			return -1;
966 		}
967 		if ((socketid = rte_lcore_to_socket_id(lcore) != 0) &&
968 							(numa_on == 0)) {
969 			printf("warning: lcore %hhu is on socket %d with numa "
970 						"off\n", lcore, socketid);
971 		}
972 	}
973 	return 0;
974 }
975 
976 static int
977 check_port_config(const unsigned nb_ports)
978 {
979 	unsigned portid;
980 	uint16_t i;
981 
982 	for (i = 0; i < nb_lcore_params; ++i) {
983 		portid = lcore_params[i].port_id;
984 		if ((enabled_port_mask & (1 << portid)) == 0) {
985 			printf("port %u is not enabled in port mask\n",
986 								portid);
987 			return -1;
988 		}
989 		if (portid >= nb_ports) {
990 			printf("port %u is not present on the board\n",
991 								portid);
992 			return -1;
993 		}
994 	}
995 	return 0;
996 }
997 
998 static uint8_t
999 get_port_n_rx_queues(const uint8_t port)
1000 {
1001 	int queue = -1;
1002 	uint16_t i;
1003 
1004 	for (i = 0; i < nb_lcore_params; ++i) {
1005 		if (lcore_params[i].port_id == port &&
1006 				lcore_params[i].queue_id > queue)
1007 			queue = lcore_params[i].queue_id;
1008 	}
1009 	return (uint8_t)(++queue);
1010 }
1011 
1012 static int
1013 init_lcore_rx_queues(void)
1014 {
1015 	uint16_t i, nb_rx_queue;
1016 	uint8_t lcore;
1017 
1018 	for (i = 0; i < nb_lcore_params; ++i) {
1019 		lcore = lcore_params[i].lcore_id;
1020 		nb_rx_queue = lcore_conf[lcore].n_rx_queue;
1021 		if (nb_rx_queue >= MAX_RX_QUEUE_PER_LCORE) {
1022 			printf("error: too many queues (%u) for lcore: %u\n",
1023 				(unsigned)nb_rx_queue + 1, (unsigned)lcore);
1024 			return -1;
1025 		} else {
1026 			lcore_conf[lcore].rx_queue_list[nb_rx_queue].port_id =
1027 				lcore_params[i].port_id;
1028 			lcore_conf[lcore].rx_queue_list[nb_rx_queue].queue_id =
1029 				lcore_params[i].queue_id;
1030 			lcore_conf[lcore].n_rx_queue++;
1031 		}
1032 	}
1033 	return 0;
1034 }
1035 
1036 /* display usage */
1037 static void
1038 print_usage(const char *prgname)
1039 {
1040 	printf ("%s [EAL options] -- -p PORTMASK -P"
1041 		"  [--config (port,queue,lcore)[,(port,queue,lcore]]"
1042 		"  [--enable-jumbo [--max-pkt-len PKTLEN]]\n"
1043 		"  -p PORTMASK: hexadecimal bitmask of ports to configure\n"
1044 		"  -P : enable promiscuous mode\n"
1045 		"  --config (port,queue,lcore): rx queues configuration\n"
1046 		"  --no-numa: optional, disable numa awareness\n"
1047 		"  --enable-jumbo: enable jumbo frame"
1048 		" which max packet len is PKTLEN in decimal (64-9600)\n",
1049 		prgname);
1050 }
1051 
1052 static int parse_max_pkt_len(const char *pktlen)
1053 {
1054 	char *end = NULL;
1055 	unsigned long len;
1056 
1057 	/* parse decimal string */
1058 	len = strtoul(pktlen, &end, 10);
1059 	if ((pktlen[0] == '\0') || (end == NULL) || (*end != '\0'))
1060 		return -1;
1061 
1062 	if (len == 0)
1063 		return -1;
1064 
1065 	return len;
1066 }
1067 
1068 static int
1069 parse_portmask(const char *portmask)
1070 {
1071 	char *end = NULL;
1072 	unsigned long pm;
1073 
1074 	/* parse hexadecimal string */
1075 	pm = strtoul(portmask, &end, 16);
1076 	if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
1077 		return -1;
1078 
1079 	if (pm == 0)
1080 		return -1;
1081 
1082 	return pm;
1083 }
1084 
1085 static int
1086 parse_config(const char *q_arg)
1087 {
1088 	char s[256];
1089 	const char *p, *p0 = q_arg;
1090 	char *end;
1091 	enum fieldnames {
1092 		FLD_PORT = 0,
1093 		FLD_QUEUE,
1094 		FLD_LCORE,
1095 		_NUM_FLD
1096 	};
1097 	unsigned long int_fld[_NUM_FLD];
1098 	char *str_fld[_NUM_FLD];
1099 	int i;
1100 	unsigned size;
1101 
1102 	nb_lcore_params = 0;
1103 
1104 	while ((p = strchr(p0,'(')) != NULL) {
1105 		++p;
1106 		if((p0 = strchr(p,')')) == NULL)
1107 			return -1;
1108 
1109 		size = p0 - p;
1110 		if(size >= sizeof(s))
1111 			return -1;
1112 
1113 		snprintf(s, sizeof(s), "%.*s", size, p);
1114 		if (rte_strsplit(s, sizeof(s), str_fld, _NUM_FLD, ',') !=
1115 								_NUM_FLD)
1116 			return -1;
1117 		for (i = 0; i < _NUM_FLD; i++){
1118 			errno = 0;
1119 			int_fld[i] = strtoul(str_fld[i], &end, 0);
1120 			if (errno != 0 || end == str_fld[i] || int_fld[i] >
1121 									255)
1122 				return -1;
1123 		}
1124 		if (nb_lcore_params >= MAX_LCORE_PARAMS) {
1125 			printf("exceeded max number of lcore params: %hu\n",
1126 				nb_lcore_params);
1127 			return -1;
1128 		}
1129 		lcore_params_array[nb_lcore_params].port_id =
1130 				(uint8_t)int_fld[FLD_PORT];
1131 		lcore_params_array[nb_lcore_params].queue_id =
1132 				(uint8_t)int_fld[FLD_QUEUE];
1133 		lcore_params_array[nb_lcore_params].lcore_id =
1134 				(uint8_t)int_fld[FLD_LCORE];
1135 		++nb_lcore_params;
1136 	}
1137 	lcore_params = lcore_params_array;
1138 
1139 	return 0;
1140 }
1141 
1142 /* Parse the argument given in the command line of the application */
1143 static int
1144 parse_args(int argc, char **argv)
1145 {
1146 	int opt, ret;
1147 	char **argvopt;
1148 	int option_index;
1149 	char *prgname = argv[0];
1150 	static struct option lgopts[] = {
1151 		{"config", 1, 0, 0},
1152 		{"no-numa", 0, 0, 0},
1153 		{"enable-jumbo", 0, 0, 0},
1154 		{NULL, 0, 0, 0}
1155 	};
1156 
1157 	argvopt = argv;
1158 
1159 	while ((opt = getopt_long(argc, argvopt, "p:P",
1160 				lgopts, &option_index)) != EOF) {
1161 
1162 		switch (opt) {
1163 		/* portmask */
1164 		case 'p':
1165 			enabled_port_mask = parse_portmask(optarg);
1166 			if (enabled_port_mask == 0) {
1167 				printf("invalid portmask\n");
1168 				print_usage(prgname);
1169 				return -1;
1170 			}
1171 			break;
1172 		case 'P':
1173 			printf("Promiscuous mode selected\n");
1174 			promiscuous_on = 1;
1175 			break;
1176 
1177 		/* long options */
1178 		case 0:
1179 			if (!strncmp(lgopts[option_index].name, "config", 6)) {
1180 				ret = parse_config(optarg);
1181 				if (ret) {
1182 					printf("invalid config\n");
1183 					print_usage(prgname);
1184 					return -1;
1185 				}
1186 			}
1187 
1188 			if (!strncmp(lgopts[option_index].name,
1189 						"no-numa", 7)) {
1190 				printf("numa is disabled \n");
1191 				numa_on = 0;
1192 			}
1193 
1194 			if (!strncmp(lgopts[option_index].name,
1195 					"enable-jumbo", 12)) {
1196 				struct option lenopts =
1197 					{"max-pkt-len", required_argument, \
1198 									0, 0};
1199 
1200 				printf("jumbo frame is enabled \n");
1201 				port_conf.rxmode.jumbo_frame = 1;
1202 
1203 				/**
1204 				 * if no max-pkt-len set, use the default value
1205 				 * ETHER_MAX_LEN
1206 				 */
1207 				if (0 == getopt_long(argc, argvopt, "",
1208 						&lenopts, &option_index)) {
1209 					ret = parse_max_pkt_len(optarg);
1210 					if ((ret < 64) ||
1211 						(ret > MAX_JUMBO_PKT_LEN)){
1212 						printf("invalid packet "
1213 								"length\n");
1214 						print_usage(prgname);
1215 						return -1;
1216 					}
1217 					port_conf.rxmode.max_rx_pkt_len = ret;
1218 				}
1219 				printf("set jumbo frame "
1220 					"max packet length to %u\n",
1221 				(unsigned int)port_conf.rxmode.max_rx_pkt_len);
1222 			}
1223 
1224 			break;
1225 
1226 		default:
1227 			print_usage(prgname);
1228 			return -1;
1229 		}
1230 	}
1231 
1232 	if (optind >= 0)
1233 		argv[optind-1] = prgname;
1234 
1235 	ret = optind-1;
1236 	optind = 0; /* reset getopt lib */
1237 	return ret;
1238 }
1239 
1240 static void
1241 print_ethaddr(const char *name, const struct ether_addr *eth_addr)
1242 {
1243 	char buf[ETHER_ADDR_FMT_SIZE];
1244 	ether_format_addr(buf, ETHER_ADDR_FMT_SIZE, eth_addr);
1245 	printf("%s%s", name, buf);
1246 }
1247 
1248 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
1249 static void
1250 setup_hash(int socketid)
1251 {
1252 	struct rte_hash_parameters ipv4_l3fwd_hash_params = {
1253 		.name = NULL,
1254 		.entries = L3FWD_HASH_ENTRIES,
1255 		.bucket_entries = 4,
1256 		.key_len = sizeof(struct ipv4_5tuple),
1257 		.hash_func = DEFAULT_HASH_FUNC,
1258 		.hash_func_init_val = 0,
1259 	};
1260 
1261 	struct rte_hash_parameters ipv6_l3fwd_hash_params = {
1262 		.name = NULL,
1263 		.entries = L3FWD_HASH_ENTRIES,
1264 		.bucket_entries = 4,
1265 		.key_len = sizeof(struct ipv6_5tuple),
1266 		.hash_func = DEFAULT_HASH_FUNC,
1267 		.hash_func_init_val = 0,
1268 	};
1269 
1270 	unsigned i;
1271 	int ret;
1272 	char s[64];
1273 
1274 	/* create ipv4 hash */
1275 	snprintf(s, sizeof(s), "ipv4_l3fwd_hash_%d", socketid);
1276 	ipv4_l3fwd_hash_params.name = s;
1277 	ipv4_l3fwd_hash_params.socket_id = socketid;
1278 	ipv4_l3fwd_lookup_struct[socketid] =
1279 		rte_hash_create(&ipv4_l3fwd_hash_params);
1280 	if (ipv4_l3fwd_lookup_struct[socketid] == NULL)
1281 		rte_exit(EXIT_FAILURE, "Unable to create the l3fwd hash on "
1282 				"socket %d\n", socketid);
1283 
1284 	/* create ipv6 hash */
1285 	snprintf(s, sizeof(s), "ipv6_l3fwd_hash_%d", socketid);
1286 	ipv6_l3fwd_hash_params.name = s;
1287 	ipv6_l3fwd_hash_params.socket_id = socketid;
1288 	ipv6_l3fwd_lookup_struct[socketid] =
1289 		rte_hash_create(&ipv6_l3fwd_hash_params);
1290 	if (ipv6_l3fwd_lookup_struct[socketid] == NULL)
1291 		rte_exit(EXIT_FAILURE, "Unable to create the l3fwd hash on "
1292 				"socket %d\n", socketid);
1293 
1294 
1295 	/* populate the ipv4 hash */
1296 	for (i = 0; i < IPV4_L3FWD_NUM_ROUTES; i++) {
1297 		ret = rte_hash_add_key (ipv4_l3fwd_lookup_struct[socketid],
1298 				(void *) &ipv4_l3fwd_route_array[i].key);
1299 		if (ret < 0) {
1300 			rte_exit(EXIT_FAILURE, "Unable to add entry %u to the"
1301 				"l3fwd hash on socket %d\n", i, socketid);
1302 		}
1303 		ipv4_l3fwd_out_if[ret] = ipv4_l3fwd_route_array[i].if_out;
1304 		printf("Hash: Adding key\n");
1305 		print_ipv4_key(ipv4_l3fwd_route_array[i].key);
1306 	}
1307 
1308 	/* populate the ipv6 hash */
1309 	for (i = 0; i < IPV6_L3FWD_NUM_ROUTES; i++) {
1310 		ret = rte_hash_add_key (ipv6_l3fwd_lookup_struct[socketid],
1311 				(void *) &ipv6_l3fwd_route_array[i].key);
1312 		if (ret < 0) {
1313 			rte_exit(EXIT_FAILURE, "Unable to add entry %u to the"
1314 				"l3fwd hash on socket %d\n", i, socketid);
1315 		}
1316 		ipv6_l3fwd_out_if[ret] = ipv6_l3fwd_route_array[i].if_out;
1317 		printf("Hash: Adding key\n");
1318 		print_ipv6_key(ipv6_l3fwd_route_array[i].key);
1319 	}
1320 }
1321 #endif
1322 
1323 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
1324 static void
1325 setup_lpm(int socketid)
1326 {
1327 	unsigned i;
1328 	int ret;
1329 	char s[64];
1330 
1331 	/* create the LPM table */
1332 	snprintf(s, sizeof(s), "IPV4_L3FWD_LPM_%d", socketid);
1333 	ipv4_l3fwd_lookup_struct[socketid] = rte_lpm_create(s, socketid,
1334 				IPV4_L3FWD_LPM_MAX_RULES, 0);
1335 	if (ipv4_l3fwd_lookup_struct[socketid] == NULL)
1336 		rte_exit(EXIT_FAILURE, "Unable to create the l3fwd LPM table"
1337 				" on socket %d\n", socketid);
1338 
1339 	/* populate the LPM table */
1340 	for (i = 0; i < IPV4_L3FWD_NUM_ROUTES; i++) {
1341 		ret = rte_lpm_add(ipv4_l3fwd_lookup_struct[socketid],
1342 			ipv4_l3fwd_route_array[i].ip,
1343 			ipv4_l3fwd_route_array[i].depth,
1344 			ipv4_l3fwd_route_array[i].if_out);
1345 
1346 		if (ret < 0) {
1347 			rte_exit(EXIT_FAILURE, "Unable to add entry %u to the "
1348 				"l3fwd LPM table on socket %d\n",
1349 				i, socketid);
1350 		}
1351 
1352 		printf("LPM: Adding route 0x%08x / %d (%d)\n",
1353 			(unsigned)ipv4_l3fwd_route_array[i].ip,
1354 			ipv4_l3fwd_route_array[i].depth,
1355 			ipv4_l3fwd_route_array[i].if_out);
1356 	}
1357 }
1358 #endif
1359 
1360 static int
1361 init_mem(unsigned nb_mbuf)
1362 {
1363 	struct lcore_conf *qconf;
1364 	int socketid;
1365 	unsigned lcore_id;
1366 	char s[64];
1367 
1368 	for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1369 		if (rte_lcore_is_enabled(lcore_id) == 0)
1370 			continue;
1371 
1372 		if (numa_on)
1373 			socketid = rte_lcore_to_socket_id(lcore_id);
1374 		else
1375 			socketid = 0;
1376 
1377 		if (socketid >= NB_SOCKETS) {
1378 			rte_exit(EXIT_FAILURE, "Socket %d of lcore %u is "
1379 					"out of range %d\n", socketid,
1380 						lcore_id, NB_SOCKETS);
1381 		}
1382 		if (pktmbuf_pool[socketid] == NULL) {
1383 			snprintf(s, sizeof(s), "mbuf_pool_%d", socketid);
1384 			pktmbuf_pool[socketid] =
1385 				rte_mempool_create(s, nb_mbuf,
1386 					MBUF_SIZE, MEMPOOL_CACHE_SIZE,
1387 					sizeof(struct rte_pktmbuf_pool_private),
1388 					rte_pktmbuf_pool_init, NULL,
1389 					rte_pktmbuf_init, NULL,
1390 					socketid, 0);
1391 			if (pktmbuf_pool[socketid] == NULL)
1392 				rte_exit(EXIT_FAILURE,
1393 					"Cannot init mbuf pool on socket %d\n",
1394 								socketid);
1395 			else
1396 				printf("Allocated mbuf pool on socket %d\n",
1397 								socketid);
1398 
1399 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
1400 			setup_lpm(socketid);
1401 #else
1402 			setup_hash(socketid);
1403 #endif
1404 		}
1405 		qconf = &lcore_conf[lcore_id];
1406 		qconf->ipv4_lookup_struct = ipv4_l3fwd_lookup_struct[socketid];
1407 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
1408 		qconf->ipv6_lookup_struct = ipv6_l3fwd_lookup_struct[socketid];
1409 #endif
1410 	}
1411 	return 0;
1412 }
1413 
1414 /* Check the link status of all ports in up to 9s, and print them finally */
1415 static void
1416 check_all_ports_link_status(uint8_t port_num, uint32_t port_mask)
1417 {
1418 #define CHECK_INTERVAL 100 /* 100ms */
1419 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
1420 	uint8_t portid, count, all_ports_up, print_flag = 0;
1421 	struct rte_eth_link link;
1422 
1423 	printf("\nChecking link status");
1424 	fflush(stdout);
1425 	for (count = 0; count <= MAX_CHECK_TIME; count++) {
1426 		all_ports_up = 1;
1427 		for (portid = 0; portid < port_num; portid++) {
1428 			if ((port_mask & (1 << portid)) == 0)
1429 				continue;
1430 			memset(&link, 0, sizeof(link));
1431 			rte_eth_link_get_nowait(portid, &link);
1432 			/* print link status if flag set */
1433 			if (print_flag == 1) {
1434 				if (link.link_status)
1435 					printf("Port %d Link Up - speed %u "
1436 						"Mbps - %s\n", (uint8_t)portid,
1437 						(unsigned)link.link_speed,
1438 				(link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
1439 					("full-duplex") : ("half-duplex\n"));
1440 				else
1441 					printf("Port %d Link Down\n",
1442 						(uint8_t)portid);
1443 				continue;
1444 			}
1445 			/* clear all_ports_up flag if any link down */
1446 			if (link.link_status == 0) {
1447 				all_ports_up = 0;
1448 				break;
1449 			}
1450 		}
1451 		/* after finally printing all link status, get out */
1452 		if (print_flag == 1)
1453 			break;
1454 
1455 		if (all_ports_up == 0) {
1456 			printf(".");
1457 			fflush(stdout);
1458 			rte_delay_ms(CHECK_INTERVAL);
1459 		}
1460 
1461 		/* set the print_flag if all ports up or timeout */
1462 		if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
1463 			print_flag = 1;
1464 			printf("done\n");
1465 		}
1466 	}
1467 }
1468 
1469 int
1470 MAIN(int argc, char **argv)
1471 {
1472 	struct lcore_conf *qconf;
1473 	struct rte_eth_dev_info dev_info;
1474 	struct rte_eth_txconf *txconf;
1475 	int ret;
1476 	unsigned nb_ports;
1477 	uint16_t queueid;
1478 	unsigned lcore_id;
1479 	uint64_t hz;
1480 	uint32_t n_tx_queue, nb_lcores;
1481 	uint8_t portid, nb_rx_queue, queue, socketid;
1482 
1483 	/* catch SIGINT and restore cpufreq governor to ondemand */
1484 	signal(SIGINT, signal_exit_now);
1485 
1486 	/* init EAL */
1487 	ret = rte_eal_init(argc, argv);
1488 	if (ret < 0)
1489 		rte_exit(EXIT_FAILURE, "Invalid EAL parameters\n");
1490 	argc -= ret;
1491 	argv += ret;
1492 
1493 	/* init RTE timer library to be used late */
1494 	rte_timer_subsystem_init();
1495 
1496 	/* parse application arguments (after the EAL ones) */
1497 	ret = parse_args(argc, argv);
1498 	if (ret < 0)
1499 		rte_exit(EXIT_FAILURE, "Invalid L3FWD parameters\n");
1500 
1501 	if (check_lcore_params() < 0)
1502 		rte_exit(EXIT_FAILURE, "check_lcore_params failed\n");
1503 
1504 	ret = init_lcore_rx_queues();
1505 	if (ret < 0)
1506 		rte_exit(EXIT_FAILURE, "init_lcore_rx_queues failed\n");
1507 
1508 
1509 	nb_ports = rte_eth_dev_count();
1510 	if (nb_ports > RTE_MAX_ETHPORTS)
1511 		nb_ports = RTE_MAX_ETHPORTS;
1512 
1513 	if (check_port_config(nb_ports) < 0)
1514 		rte_exit(EXIT_FAILURE, "check_port_config failed\n");
1515 
1516 	nb_lcores = rte_lcore_count();
1517 
1518 	/* initialize all ports */
1519 	for (portid = 0; portid < nb_ports; portid++) {
1520 		/* skip ports that are not enabled */
1521 		if ((enabled_port_mask & (1 << portid)) == 0) {
1522 			printf("\nSkipping disabled port %d\n", portid);
1523 			continue;
1524 		}
1525 
1526 		/* init port */
1527 		printf("Initializing port %d ... ", portid );
1528 		fflush(stdout);
1529 
1530 		nb_rx_queue = get_port_n_rx_queues(portid);
1531 		n_tx_queue = nb_lcores;
1532 		if (n_tx_queue > MAX_TX_QUEUE_PER_PORT)
1533 			n_tx_queue = MAX_TX_QUEUE_PER_PORT;
1534 		printf("Creating queues: nb_rxq=%d nb_txq=%u... ",
1535 			nb_rx_queue, (unsigned)n_tx_queue );
1536 		ret = rte_eth_dev_configure(portid, nb_rx_queue,
1537 					(uint16_t)n_tx_queue, &port_conf);
1538 		if (ret < 0)
1539 			rte_exit(EXIT_FAILURE, "Cannot configure device: "
1540 					"err=%d, port=%d\n", ret, portid);
1541 
1542 		rte_eth_macaddr_get(portid, &ports_eth_addr[portid]);
1543 		print_ethaddr(" Address:", &ports_eth_addr[portid]);
1544 		printf(", ");
1545 
1546 		/* init memory */
1547 		ret = init_mem(NB_MBUF);
1548 		if (ret < 0)
1549 			rte_exit(EXIT_FAILURE, "init_mem failed\n");
1550 
1551 		/* init one TX queue per couple (lcore,port) */
1552 		queueid = 0;
1553 		for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1554 			if (rte_lcore_is_enabled(lcore_id) == 0)
1555 				continue;
1556 
1557 			if (numa_on)
1558 				socketid = \
1559 				(uint8_t)rte_lcore_to_socket_id(lcore_id);
1560 			else
1561 				socketid = 0;
1562 
1563 			printf("txq=%u,%d,%d ", lcore_id, queueid, socketid);
1564 			fflush(stdout);
1565 
1566 			rte_eth_dev_info_get(portid, &dev_info);
1567 			txconf = &dev_info.default_txconf;
1568 			if (port_conf.rxmode.jumbo_frame)
1569 				txconf->txq_flags = 0;
1570 			ret = rte_eth_tx_queue_setup(portid, queueid, nb_txd,
1571 						     socketid, txconf);
1572 			if (ret < 0)
1573 				rte_exit(EXIT_FAILURE,
1574 					"rte_eth_tx_queue_setup: err=%d, "
1575 						"port=%d\n", ret, portid);
1576 
1577 			qconf = &lcore_conf[lcore_id];
1578 			qconf->tx_queue_id[portid] = queueid;
1579 			queueid++;
1580 		}
1581 		printf("\n");
1582 	}
1583 
1584 	for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1585 		if (rte_lcore_is_enabled(lcore_id) == 0)
1586 			continue;
1587 
1588 		/* init power management library */
1589 		ret = rte_power_init(lcore_id);
1590 		if (ret)
1591 			rte_exit(EXIT_FAILURE, "Power management library "
1592 				"initialization failed on core%u\n", lcore_id);
1593 
1594 		/* init timer structures for each enabled lcore */
1595 		rte_timer_init(&power_timers[lcore_id]);
1596 		hz = rte_get_timer_hz();
1597 		rte_timer_reset(&power_timers[lcore_id],
1598 			hz/TIMER_NUMBER_PER_SECOND, SINGLE, lcore_id,
1599 						power_timer_cb, NULL);
1600 
1601 		qconf = &lcore_conf[lcore_id];
1602 		printf("\nInitializing rx queues on lcore %u ... ", lcore_id );
1603 		fflush(stdout);
1604 		/* init RX queues */
1605 		for(queue = 0; queue < qconf->n_rx_queue; ++queue) {
1606 			portid = qconf->rx_queue_list[queue].port_id;
1607 			queueid = qconf->rx_queue_list[queue].queue_id;
1608 
1609 			if (numa_on)
1610 				socketid = \
1611 				(uint8_t)rte_lcore_to_socket_id(lcore_id);
1612 			else
1613 				socketid = 0;
1614 
1615 			printf("rxq=%d,%d,%d ", portid, queueid, socketid);
1616 			fflush(stdout);
1617 
1618 			ret = rte_eth_rx_queue_setup(portid, queueid, nb_rxd,
1619 				socketid, NULL,
1620 				pktmbuf_pool[socketid]);
1621 			if (ret < 0)
1622 				rte_exit(EXIT_FAILURE,
1623 					"rte_eth_rx_queue_setup: err=%d, "
1624 						"port=%d\n", ret, portid);
1625 		}
1626 	}
1627 
1628 	printf("\n");
1629 
1630 	/* start ports */
1631 	for (portid = 0; portid < nb_ports; portid++) {
1632 		if ((enabled_port_mask & (1 << portid)) == 0) {
1633 			continue;
1634 		}
1635 		/* Start device */
1636 		ret = rte_eth_dev_start(portid);
1637 		if (ret < 0)
1638 			rte_exit(EXIT_FAILURE, "rte_eth_dev_start: err=%d, "
1639 						"port=%d\n", ret, portid);
1640 
1641 		/*
1642 		 * If enabled, put device in promiscuous mode.
1643 		 * This allows IO forwarding mode to forward packets
1644 		 * to itself through 2 cross-connected  ports of the
1645 		 * target machine.
1646 		 */
1647 		if (promiscuous_on)
1648 			rte_eth_promiscuous_enable(portid);
1649 	}
1650 
1651 	check_all_ports_link_status((uint8_t)nb_ports, enabled_port_mask);
1652 
1653 	/* launch per-lcore init on every lcore */
1654 	rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
1655 	RTE_LCORE_FOREACH_SLAVE(lcore_id) {
1656 		if (rte_eal_wait_lcore(lcore_id) < 0)
1657 			return -1;
1658 	}
1659 
1660 	return 0;
1661 }
1662