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