examples/l3fwd-power: support traffic pattern aware control
[dpdk.git] / examples / l3fwd-power / main.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2018 Intel Corporation
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdint.h>
8 #include <inttypes.h>
9 #include <sys/types.h>
10 #include <string.h>
11 #include <sys/queue.h>
12 #include <stdarg.h>
13 #include <errno.h>
14 #include <getopt.h>
15 #include <unistd.h>
16 #include <signal.h>
17
18 #include <rte_common.h>
19 #include <rte_byteorder.h>
20 #include <rte_log.h>
21 #include <rte_malloc.h>
22 #include <rte_memory.h>
23 #include <rte_memcpy.h>
24 #include <rte_eal.h>
25 #include <rte_launch.h>
26 #include <rte_atomic.h>
27 #include <rte_cycles.h>
28 #include <rte_prefetch.h>
29 #include <rte_lcore.h>
30 #include <rte_per_lcore.h>
31 #include <rte_branch_prediction.h>
32 #include <rte_interrupts.h>
33 #include <rte_random.h>
34 #include <rte_debug.h>
35 #include <rte_ether.h>
36 #include <rte_ethdev.h>
37 #include <rte_mempool.h>
38 #include <rte_mbuf.h>
39 #include <rte_ip.h>
40 #include <rte_tcp.h>
41 #include <rte_udp.h>
42 #include <rte_string_fns.h>
43 #include <rte_timer.h>
44 #include <rte_power.h>
45 #include <rte_spinlock.h>
46 #include <rte_power_empty_poll.h>
47
48 #include "perf_core.h"
49 #include "main.h"
50
51 #define RTE_LOGTYPE_L3FWD_POWER RTE_LOGTYPE_USER1
52
53 #define MAX_PKT_BURST 32
54
55 #define MIN_ZERO_POLL_COUNT 10
56
57 /* 100 ms interval */
58 #define TIMER_NUMBER_PER_SECOND           10
59 /* (10ms) */
60 #define INTERVALS_PER_SECOND             100
61 /* 100000 us */
62 #define SCALING_PERIOD                    (1000000/TIMER_NUMBER_PER_SECOND)
63 #define SCALING_DOWN_TIME_RATIO_THRESHOLD 0.25
64
65 #define APP_LOOKUP_EXACT_MATCH          0
66 #define APP_LOOKUP_LPM                  1
67 #define DO_RFC_1812_CHECKS
68
69 #ifndef APP_LOOKUP_METHOD
70 #define APP_LOOKUP_METHOD             APP_LOOKUP_LPM
71 #endif
72
73 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
74 #include <rte_hash.h>
75 #elif (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
76 #include <rte_lpm.h>
77 #else
78 #error "APP_LOOKUP_METHOD set to incorrect value"
79 #endif
80
81 #ifndef IPv6_BYTES
82 #define IPv6_BYTES_FMT "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"\
83                        "%02x%02x:%02x%02x:%02x%02x:%02x%02x"
84 #define IPv6_BYTES(addr) \
85         addr[0],  addr[1], addr[2],  addr[3], \
86         addr[4],  addr[5], addr[6],  addr[7], \
87         addr[8],  addr[9], addr[10], addr[11],\
88         addr[12], addr[13],addr[14], addr[15]
89 #endif
90
91 #define MAX_JUMBO_PKT_LEN  9600
92
93 #define IPV6_ADDR_LEN 16
94
95 #define MEMPOOL_CACHE_SIZE 256
96
97 /*
98  * This expression is used to calculate the number of mbufs needed depending on
99  * user input, taking into account memory for rx and tx hardware rings, cache
100  * per lcore and mtable per port per lcore. RTE_MAX is used to ensure that
101  * NB_MBUF never goes below a minimum value of 8192.
102  */
103
104 #define NB_MBUF RTE_MAX ( \
105         (nb_ports*nb_rx_queue*nb_rxd + \
106         nb_ports*nb_lcores*MAX_PKT_BURST + \
107         nb_ports*n_tx_queue*nb_txd + \
108         nb_lcores*MEMPOOL_CACHE_SIZE), \
109         (unsigned)8192)
110
111 #define BURST_TX_DRAIN_US 100 /* TX drain every ~100us */
112
113 #define NB_SOCKETS 8
114
115 /* Configure how many packets ahead to prefetch, when reading packets */
116 #define PREFETCH_OFFSET 3
117
118 /*
119  * Configurable number of RX/TX ring descriptors
120  */
121 #define RTE_TEST_RX_DESC_DEFAULT 1024
122 #define RTE_TEST_TX_DESC_DEFAULT 1024
123
124 /*
125  * These two thresholds were decided on by running the training algorithm on
126  * a 2.5GHz Xeon. These defaults can be overridden by supplying non-zero values
127  * for the med_threshold and high_threshold parameters on the command line.
128  */
129 #define EMPTY_POLL_MED_THRESHOLD 350000UL
130 #define EMPTY_POLL_HGH_THRESHOLD 580000UL
131
132
133
134 static uint16_t nb_rxd = RTE_TEST_RX_DESC_DEFAULT;
135 static uint16_t nb_txd = RTE_TEST_TX_DESC_DEFAULT;
136
137 /* ethernet addresses of ports */
138 static struct ether_addr ports_eth_addr[RTE_MAX_ETHPORTS];
139
140 /* ethernet addresses of ports */
141 static rte_spinlock_t locks[RTE_MAX_ETHPORTS];
142
143 /* mask of enabled ports */
144 static uint32_t enabled_port_mask = 0;
145 /* Ports set in promiscuous mode off by default. */
146 static int promiscuous_on = 0;
147 /* NUMA is enabled by default. */
148 static int numa_on = 1;
149 /* emptypoll is disabled by default. */
150 static bool empty_poll_on;
151 static bool empty_poll_train;
152 volatile bool empty_poll_stop;
153 static struct  ep_params *ep_params;
154 static struct  ep_policy policy;
155 static long  ep_med_edpi, ep_hgh_edpi;
156
157 static int parse_ptype; /**< Parse packet type using rx callback, and */
158                         /**< disabled by default */
159
160 enum freq_scale_hint_t
161 {
162         FREQ_LOWER    =      -1,
163         FREQ_CURRENT  =       0,
164         FREQ_HIGHER   =       1,
165         FREQ_HIGHEST  =       2
166 };
167
168 struct lcore_rx_queue {
169         uint16_t port_id;
170         uint8_t queue_id;
171         enum freq_scale_hint_t freq_up_hint;
172         uint32_t zero_rx_packet_count;
173         uint32_t idle_hint;
174 } __rte_cache_aligned;
175
176 #define MAX_RX_QUEUE_PER_LCORE 16
177 #define MAX_TX_QUEUE_PER_PORT RTE_MAX_ETHPORTS
178 #define MAX_RX_QUEUE_PER_PORT 128
179
180 #define MAX_RX_QUEUE_INTERRUPT_PER_PORT 16
181
182
183 struct lcore_params lcore_params_array[MAX_LCORE_PARAMS];
184 static struct lcore_params lcore_params_array_default[] = {
185         {0, 0, 2},
186         {0, 1, 2},
187         {0, 2, 2},
188         {1, 0, 2},
189         {1, 1, 2},
190         {1, 2, 2},
191         {2, 0, 2},
192         {3, 0, 3},
193         {3, 1, 3},
194 };
195
196 struct lcore_params *lcore_params = lcore_params_array_default;
197 uint16_t nb_lcore_params = sizeof(lcore_params_array_default) /
198                                 sizeof(lcore_params_array_default[0]);
199
200 static struct rte_eth_conf port_conf = {
201         .rxmode = {
202                 .mq_mode        = ETH_MQ_RX_RSS,
203                 .max_rx_pkt_len = ETHER_MAX_LEN,
204                 .split_hdr_size = 0,
205                 .offloads = DEV_RX_OFFLOAD_CHECKSUM,
206         },
207         .rx_adv_conf = {
208                 .rss_conf = {
209                         .rss_key = NULL,
210                         .rss_hf = ETH_RSS_UDP,
211                 },
212         },
213         .txmode = {
214                 .mq_mode = ETH_MQ_TX_NONE,
215         },
216         .intr_conf = {
217                 .rxq = 1,
218         },
219 };
220
221 static struct rte_mempool * pktmbuf_pool[NB_SOCKETS];
222
223
224 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
225
226 #ifdef RTE_ARCH_X86
227 #include <rte_hash_crc.h>
228 #define DEFAULT_HASH_FUNC       rte_hash_crc
229 #else
230 #include <rte_jhash.h>
231 #define DEFAULT_HASH_FUNC       rte_jhash
232 #endif
233
234 struct ipv4_5tuple {
235         uint32_t ip_dst;
236         uint32_t ip_src;
237         uint16_t port_dst;
238         uint16_t port_src;
239         uint8_t  proto;
240 } __attribute__((__packed__));
241
242 struct ipv6_5tuple {
243         uint8_t  ip_dst[IPV6_ADDR_LEN];
244         uint8_t  ip_src[IPV6_ADDR_LEN];
245         uint16_t port_dst;
246         uint16_t port_src;
247         uint8_t  proto;
248 } __attribute__((__packed__));
249
250 struct ipv4_l3fwd_route {
251         struct ipv4_5tuple key;
252         uint8_t if_out;
253 };
254
255 struct ipv6_l3fwd_route {
256         struct ipv6_5tuple key;
257         uint8_t if_out;
258 };
259
260 static struct ipv4_l3fwd_route ipv4_l3fwd_route_array[] = {
261         {{IPv4(100,10,0,1), IPv4(200,10,0,1), 101, 11, IPPROTO_TCP}, 0},
262         {{IPv4(100,20,0,2), IPv4(200,20,0,2), 102, 12, IPPROTO_TCP}, 1},
263         {{IPv4(100,30,0,3), IPv4(200,30,0,3), 103, 13, IPPROTO_TCP}, 2},
264         {{IPv4(100,40,0,4), IPv4(200,40,0,4), 104, 14, IPPROTO_TCP}, 3},
265 };
266
267 static struct ipv6_l3fwd_route ipv6_l3fwd_route_array[] = {
268         {
269                 {
270                         {0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
271                          0x02, 0x1b, 0x21, 0xff, 0xfe, 0x91, 0x38, 0x05},
272                         {0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
273                          0x02, 0x1e, 0x67, 0xff, 0xfe, 0x0d, 0xb6, 0x0a},
274                          1, 10, IPPROTO_UDP
275                 }, 4
276         },
277 };
278
279 typedef struct rte_hash lookup_struct_t;
280 static lookup_struct_t *ipv4_l3fwd_lookup_struct[NB_SOCKETS];
281 static lookup_struct_t *ipv6_l3fwd_lookup_struct[NB_SOCKETS];
282
283 #define L3FWD_HASH_ENTRIES      1024
284
285 #define IPV4_L3FWD_NUM_ROUTES \
286         (sizeof(ipv4_l3fwd_route_array) / sizeof(ipv4_l3fwd_route_array[0]))
287
288 #define IPV6_L3FWD_NUM_ROUTES \
289         (sizeof(ipv6_l3fwd_route_array) / sizeof(ipv6_l3fwd_route_array[0]))
290
291 static uint16_t ipv4_l3fwd_out_if[L3FWD_HASH_ENTRIES] __rte_cache_aligned;
292 static uint16_t ipv6_l3fwd_out_if[L3FWD_HASH_ENTRIES] __rte_cache_aligned;
293 #endif
294
295 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
296 struct ipv4_l3fwd_route {
297         uint32_t ip;
298         uint8_t  depth;
299         uint8_t  if_out;
300 };
301
302 static struct ipv4_l3fwd_route ipv4_l3fwd_route_array[] = {
303         {IPv4(1,1,1,0), 24, 0},
304         {IPv4(2,1,1,0), 24, 1},
305         {IPv4(3,1,1,0), 24, 2},
306         {IPv4(4,1,1,0), 24, 3},
307         {IPv4(5,1,1,0), 24, 4},
308         {IPv4(6,1,1,0), 24, 5},
309         {IPv4(7,1,1,0), 24, 6},
310         {IPv4(8,1,1,0), 24, 7},
311 };
312
313 #define IPV4_L3FWD_NUM_ROUTES \
314         (sizeof(ipv4_l3fwd_route_array) / sizeof(ipv4_l3fwd_route_array[0]))
315
316 #define IPV4_L3FWD_LPM_MAX_RULES     1024
317
318 typedef struct rte_lpm lookup_struct_t;
319 static lookup_struct_t *ipv4_l3fwd_lookup_struct[NB_SOCKETS];
320 #endif
321
322 struct lcore_conf {
323         uint16_t n_rx_queue;
324         struct lcore_rx_queue rx_queue_list[MAX_RX_QUEUE_PER_LCORE];
325         uint16_t n_tx_port;
326         uint16_t tx_port_id[RTE_MAX_ETHPORTS];
327         uint16_t tx_queue_id[RTE_MAX_ETHPORTS];
328         struct rte_eth_dev_tx_buffer *tx_buffer[RTE_MAX_ETHPORTS];
329         lookup_struct_t * ipv4_lookup_struct;
330         lookup_struct_t * ipv6_lookup_struct;
331 } __rte_cache_aligned;
332
333 struct lcore_stats {
334         /* total sleep time in ms since last frequency scaling down */
335         uint32_t sleep_time;
336         /* number of long sleep recently */
337         uint32_t nb_long_sleep;
338         /* freq. scaling up trend */
339         uint32_t trend;
340         /* total packet processed recently */
341         uint64_t nb_rx_processed;
342         /* total iterations looped recently */
343         uint64_t nb_iteration_looped;
344         uint32_t padding[9];
345 } __rte_cache_aligned;
346
347 static struct lcore_conf lcore_conf[RTE_MAX_LCORE] __rte_cache_aligned;
348 static struct lcore_stats stats[RTE_MAX_LCORE] __rte_cache_aligned;
349 static struct rte_timer power_timers[RTE_MAX_LCORE];
350
351 static inline uint32_t power_idle_heuristic(uint32_t zero_rx_packet_count);
352 static inline enum freq_scale_hint_t power_freq_scaleup_heuristic( \
353                 unsigned int lcore_id, uint16_t port_id, uint16_t queue_id);
354
355
356 /*
357  * These defaults are using the max frequency index (1), a medium index (9)
358  * and a typical low frequency index (14). These can be adjusted to use
359  * different indexes using the relevant command line parameters.
360  */
361 static uint8_t  freq_tlb[] = {14, 9, 1};
362
363 static int is_done(void)
364 {
365         return empty_poll_stop;
366 }
367
368 /* exit signal handler */
369 static void
370 signal_exit_now(int sigtype)
371 {
372         unsigned lcore_id;
373         unsigned int portid;
374         int ret;
375
376         RTE_SET_USED(lcore_id);
377         RTE_SET_USED(portid);
378         RTE_SET_USED(ret);
379
380         if (sigtype == SIGINT) {
381                 if (empty_poll_on)
382                         empty_poll_stop = true;
383
384
385                 for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
386                         if (rte_lcore_is_enabled(lcore_id) == 0)
387                                 continue;
388
389                         /* init power management library */
390                         ret = rte_power_exit(lcore_id);
391                         if (ret)
392                                 rte_exit(EXIT_FAILURE, "Power management "
393                                         "library de-initialization failed on "
394                                                         "core%u\n", lcore_id);
395                 }
396
397                 if (!empty_poll_on) {
398                         RTE_ETH_FOREACH_DEV(portid) {
399                                 if ((enabled_port_mask & (1 << portid)) == 0)
400                                         continue;
401
402                                 rte_eth_dev_stop(portid);
403                                 rte_eth_dev_close(portid);
404                         }
405                 }
406         }
407
408         if (!empty_poll_on)
409                 rte_exit(EXIT_SUCCESS, "User forced exit\n");
410 }
411
412 /*  Freqency scale down timer callback */
413 static void
414 power_timer_cb(__attribute__((unused)) struct rte_timer *tim,
415                           __attribute__((unused)) void *arg)
416 {
417         uint64_t hz;
418         float sleep_time_ratio;
419         unsigned lcore_id = rte_lcore_id();
420
421         /* accumulate total execution time in us when callback is invoked */
422         sleep_time_ratio = (float)(stats[lcore_id].sleep_time) /
423                                         (float)SCALING_PERIOD;
424         /**
425          * check whether need to scale down frequency a step if it sleep a lot.
426          */
427         if (sleep_time_ratio >= SCALING_DOWN_TIME_RATIO_THRESHOLD) {
428                 if (rte_power_freq_down)
429                         rte_power_freq_down(lcore_id);
430         }
431         else if ( (unsigned)(stats[lcore_id].nb_rx_processed /
432                 stats[lcore_id].nb_iteration_looped) < MAX_PKT_BURST) {
433                 /**
434                  * scale down a step if average packet per iteration less
435                  * than expectation.
436                  */
437                 if (rte_power_freq_down)
438                         rte_power_freq_down(lcore_id);
439         }
440
441         /**
442          * initialize another timer according to current frequency to ensure
443          * timer interval is relatively fixed.
444          */
445         hz = rte_get_timer_hz();
446         rte_timer_reset(&power_timers[lcore_id], hz/TIMER_NUMBER_PER_SECOND,
447                                 SINGLE, lcore_id, power_timer_cb, NULL);
448
449         stats[lcore_id].nb_rx_processed = 0;
450         stats[lcore_id].nb_iteration_looped = 0;
451
452         stats[lcore_id].sleep_time = 0;
453 }
454
455 /* Enqueue a single packet, and send burst if queue is filled */
456 static inline int
457 send_single_packet(struct rte_mbuf *m, uint16_t port)
458 {
459         uint32_t lcore_id;
460         struct lcore_conf *qconf;
461
462         lcore_id = rte_lcore_id();
463         qconf = &lcore_conf[lcore_id];
464
465         rte_eth_tx_buffer(port, qconf->tx_queue_id[port],
466                         qconf->tx_buffer[port], m);
467
468         return 0;
469 }
470
471 #ifdef DO_RFC_1812_CHECKS
472 static inline int
473 is_valid_ipv4_pkt(struct ipv4_hdr *pkt, uint32_t link_len)
474 {
475         /* From http://www.rfc-editor.org/rfc/rfc1812.txt section 5.2.2 */
476         /*
477          * 1. The packet length reported by the Link Layer must be large
478          * enough to hold the minimum length legal IP datagram (20 bytes).
479          */
480         if (link_len < sizeof(struct ipv4_hdr))
481                 return -1;
482
483         /* 2. The IP checksum must be correct. */
484         /* this is checked in H/W */
485
486         /*
487          * 3. The IP version number must be 4. If the version number is not 4
488          * then the packet may be another version of IP, such as IPng or
489          * ST-II.
490          */
491         if (((pkt->version_ihl) >> 4) != 4)
492                 return -3;
493         /*
494          * 4. The IP header length field must be large enough to hold the
495          * minimum length legal IP datagram (20 bytes = 5 words).
496          */
497         if ((pkt->version_ihl & 0xf) < 5)
498                 return -4;
499
500         /*
501          * 5. The IP total length field must be large enough to hold the IP
502          * datagram header, whose length is specified in the IP header length
503          * field.
504          */
505         if (rte_cpu_to_be_16(pkt->total_length) < sizeof(struct ipv4_hdr))
506                 return -5;
507
508         return 0;
509 }
510 #endif
511
512 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
513 static void
514 print_ipv4_key(struct ipv4_5tuple key)
515 {
516         printf("IP dst = %08x, IP src = %08x, port dst = %d, port src = %d, "
517                 "proto = %d\n", (unsigned)key.ip_dst, (unsigned)key.ip_src,
518                                 key.port_dst, key.port_src, key.proto);
519 }
520 static void
521 print_ipv6_key(struct ipv6_5tuple key)
522 {
523         printf( "IP dst = " IPv6_BYTES_FMT ", IP src = " IPv6_BYTES_FMT ", "
524                 "port dst = %d, port src = %d, proto = %d\n",
525                 IPv6_BYTES(key.ip_dst), IPv6_BYTES(key.ip_src),
526                 key.port_dst, key.port_src, key.proto);
527 }
528
529 static inline uint16_t
530 get_ipv4_dst_port(struct ipv4_hdr *ipv4_hdr, uint16_t portid,
531                 lookup_struct_t * ipv4_l3fwd_lookup_struct)
532 {
533         struct ipv4_5tuple key;
534         struct tcp_hdr *tcp;
535         struct udp_hdr *udp;
536         int ret = 0;
537
538         key.ip_dst = rte_be_to_cpu_32(ipv4_hdr->dst_addr);
539         key.ip_src = rte_be_to_cpu_32(ipv4_hdr->src_addr);
540         key.proto = ipv4_hdr->next_proto_id;
541
542         switch (ipv4_hdr->next_proto_id) {
543         case IPPROTO_TCP:
544                 tcp = (struct tcp_hdr *)((unsigned char *)ipv4_hdr +
545                                         sizeof(struct ipv4_hdr));
546                 key.port_dst = rte_be_to_cpu_16(tcp->dst_port);
547                 key.port_src = rte_be_to_cpu_16(tcp->src_port);
548                 break;
549
550         case IPPROTO_UDP:
551                 udp = (struct udp_hdr *)((unsigned char *)ipv4_hdr +
552                                         sizeof(struct ipv4_hdr));
553                 key.port_dst = rte_be_to_cpu_16(udp->dst_port);
554                 key.port_src = rte_be_to_cpu_16(udp->src_port);
555                 break;
556
557         default:
558                 key.port_dst = 0;
559                 key.port_src = 0;
560                 break;
561         }
562
563         /* Find destination port */
564         ret = rte_hash_lookup(ipv4_l3fwd_lookup_struct, (const void *)&key);
565         return ((ret < 0) ? portid : ipv4_l3fwd_out_if[ret]);
566 }
567
568 static inline uint16_t
569 get_ipv6_dst_port(struct ipv6_hdr *ipv6_hdr, uint16_t portid,
570                         lookup_struct_t *ipv6_l3fwd_lookup_struct)
571 {
572         struct ipv6_5tuple key;
573         struct tcp_hdr *tcp;
574         struct udp_hdr *udp;
575         int ret = 0;
576
577         memcpy(key.ip_dst, ipv6_hdr->dst_addr, IPV6_ADDR_LEN);
578         memcpy(key.ip_src, ipv6_hdr->src_addr, IPV6_ADDR_LEN);
579
580         key.proto = ipv6_hdr->proto;
581
582         switch (ipv6_hdr->proto) {
583         case IPPROTO_TCP:
584                 tcp = (struct tcp_hdr *)((unsigned char *) ipv6_hdr +
585                                         sizeof(struct ipv6_hdr));
586                 key.port_dst = rte_be_to_cpu_16(tcp->dst_port);
587                 key.port_src = rte_be_to_cpu_16(tcp->src_port);
588                 break;
589
590         case IPPROTO_UDP:
591                 udp = (struct udp_hdr *)((unsigned char *) ipv6_hdr +
592                                         sizeof(struct ipv6_hdr));
593                 key.port_dst = rte_be_to_cpu_16(udp->dst_port);
594                 key.port_src = rte_be_to_cpu_16(udp->src_port);
595                 break;
596
597         default:
598                 key.port_dst = 0;
599                 key.port_src = 0;
600                 break;
601         }
602
603         /* Find destination port */
604         ret = rte_hash_lookup(ipv6_l3fwd_lookup_struct, (const void *)&key);
605         return ((ret < 0) ? portid : ipv6_l3fwd_out_if[ret]);
606 }
607 #endif
608
609 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
610 static inline uint16_t
611 get_ipv4_dst_port(struct ipv4_hdr *ipv4_hdr, uint16_t portid,
612                 lookup_struct_t *ipv4_l3fwd_lookup_struct)
613 {
614         uint32_t next_hop;
615
616         return ((rte_lpm_lookup(ipv4_l3fwd_lookup_struct,
617                         rte_be_to_cpu_32(ipv4_hdr->dst_addr), &next_hop) == 0)?
618                         next_hop : portid);
619 }
620 #endif
621
622 static inline void
623 parse_ptype_one(struct rte_mbuf *m)
624 {
625         struct ether_hdr *eth_hdr;
626         uint32_t packet_type = RTE_PTYPE_UNKNOWN;
627         uint16_t ether_type;
628
629         eth_hdr = rte_pktmbuf_mtod(m, struct ether_hdr *);
630         ether_type = eth_hdr->ether_type;
631         if (ether_type == rte_cpu_to_be_16(ETHER_TYPE_IPv4))
632                 packet_type |= RTE_PTYPE_L3_IPV4_EXT_UNKNOWN;
633         else if (ether_type == rte_cpu_to_be_16(ETHER_TYPE_IPv6))
634                 packet_type |= RTE_PTYPE_L3_IPV6_EXT_UNKNOWN;
635
636         m->packet_type = packet_type;
637 }
638
639 static uint16_t
640 cb_parse_ptype(uint16_t port __rte_unused, uint16_t queue __rte_unused,
641                struct rte_mbuf *pkts[], uint16_t nb_pkts,
642                uint16_t max_pkts __rte_unused,
643                void *user_param __rte_unused)
644 {
645         unsigned int i;
646
647         for (i = 0; i < nb_pkts; ++i)
648                 parse_ptype_one(pkts[i]);
649
650         return nb_pkts;
651 }
652
653 static int
654 add_cb_parse_ptype(uint16_t portid, uint16_t queueid)
655 {
656         printf("Port %d: softly parse packet type info\n", portid);
657         if (rte_eth_add_rx_callback(portid, queueid, cb_parse_ptype, NULL))
658                 return 0;
659
660         printf("Failed to add rx callback: port=%d\n", portid);
661         return -1;
662 }
663
664 static inline void
665 l3fwd_simple_forward(struct rte_mbuf *m, uint16_t portid,
666                                 struct lcore_conf *qconf)
667 {
668         struct ether_hdr *eth_hdr;
669         struct ipv4_hdr *ipv4_hdr;
670         void *d_addr_bytes;
671         uint16_t dst_port;
672
673         eth_hdr = rte_pktmbuf_mtod(m, struct ether_hdr *);
674
675         if (RTE_ETH_IS_IPV4_HDR(m->packet_type)) {
676                 /* Handle IPv4 headers.*/
677                 ipv4_hdr =
678                         rte_pktmbuf_mtod_offset(m, struct ipv4_hdr *,
679                                                 sizeof(struct ether_hdr));
680
681 #ifdef DO_RFC_1812_CHECKS
682                 /* Check to make sure the packet is valid (RFC1812) */
683                 if (is_valid_ipv4_pkt(ipv4_hdr, m->pkt_len) < 0) {
684                         rte_pktmbuf_free(m);
685                         return;
686                 }
687 #endif
688
689                 dst_port = get_ipv4_dst_port(ipv4_hdr, portid,
690                                         qconf->ipv4_lookup_struct);
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 #ifdef DO_RFC_1812_CHECKS
701                 /* Update time to live and header checksum */
702                 --(ipv4_hdr->time_to_live);
703                 ++(ipv4_hdr->hdr_checksum);
704 #endif
705
706                 /* src addr */
707                 ether_addr_copy(&ports_eth_addr[dst_port], &eth_hdr->s_addr);
708
709                 send_single_packet(m, dst_port);
710         } else if (RTE_ETH_IS_IPV6_HDR(m->packet_type)) {
711                 /* Handle IPv6 headers.*/
712 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
713                 struct ipv6_hdr *ipv6_hdr;
714
715                 ipv6_hdr =
716                         rte_pktmbuf_mtod_offset(m, struct ipv6_hdr *,
717                                                 sizeof(struct ether_hdr));
718
719                 dst_port = get_ipv6_dst_port(ipv6_hdr, portid,
720                                         qconf->ipv6_lookup_struct);
721
722                 if (dst_port >= RTE_MAX_ETHPORTS ||
723                                 (enabled_port_mask & 1 << dst_port) == 0)
724                         dst_port = portid;
725
726                 /* 02:00:00:00:00:xx */
727                 d_addr_bytes = &eth_hdr->d_addr.addr_bytes[0];
728                 *((uint64_t *)d_addr_bytes) =
729                         0x000000000002 + ((uint64_t)dst_port << 40);
730
731                 /* src addr */
732                 ether_addr_copy(&ports_eth_addr[dst_port], &eth_hdr->s_addr);
733
734                 send_single_packet(m, dst_port);
735 #else
736                 /* We don't currently handle IPv6 packets in LPM mode. */
737                 rte_pktmbuf_free(m);
738 #endif
739         } else
740                 rte_pktmbuf_free(m);
741
742 }
743
744 #define MINIMUM_SLEEP_TIME         1
745 #define SUSPEND_THRESHOLD          300
746
747 static inline uint32_t
748 power_idle_heuristic(uint32_t zero_rx_packet_count)
749 {
750         /* If zero count is less than 100,  sleep 1us */
751         if (zero_rx_packet_count < SUSPEND_THRESHOLD)
752                 return MINIMUM_SLEEP_TIME;
753         /* If zero count is less than 1000, sleep 100 us which is the
754                 minimum latency switching from C3/C6 to C0
755         */
756         else
757                 return SUSPEND_THRESHOLD;
758 }
759
760 static inline enum freq_scale_hint_t
761 power_freq_scaleup_heuristic(unsigned lcore_id,
762                              uint16_t port_id,
763                              uint16_t queue_id)
764 {
765         uint32_t rxq_count = rte_eth_rx_queue_count(port_id, queue_id);
766 /**
767  * HW Rx queue size is 128 by default, Rx burst read at maximum 32 entries
768  * per iteration
769  */
770 #define FREQ_GEAR1_RX_PACKET_THRESHOLD             MAX_PKT_BURST
771 #define FREQ_GEAR2_RX_PACKET_THRESHOLD             (MAX_PKT_BURST*2)
772 #define FREQ_GEAR3_RX_PACKET_THRESHOLD             (MAX_PKT_BURST*3)
773 #define FREQ_UP_TREND1_ACC   1
774 #define FREQ_UP_TREND2_ACC   100
775 #define FREQ_UP_THRESHOLD    10000
776
777         if (likely(rxq_count > FREQ_GEAR3_RX_PACKET_THRESHOLD)) {
778                 stats[lcore_id].trend = 0;
779                 return FREQ_HIGHEST;
780         } else if (likely(rxq_count > FREQ_GEAR2_RX_PACKET_THRESHOLD))
781                 stats[lcore_id].trend += FREQ_UP_TREND2_ACC;
782         else if (likely(rxq_count > FREQ_GEAR1_RX_PACKET_THRESHOLD))
783                 stats[lcore_id].trend += FREQ_UP_TREND1_ACC;
784
785         if (likely(stats[lcore_id].trend > FREQ_UP_THRESHOLD)) {
786                 stats[lcore_id].trend = 0;
787                 return FREQ_HIGHER;
788         }
789
790         return FREQ_CURRENT;
791 }
792
793 /**
794  * force polling thread sleep until one-shot rx interrupt triggers
795  * @param port_id
796  *  Port id.
797  * @param queue_id
798  *  Rx queue id.
799  * @return
800  *  0 on success
801  */
802 static int
803 sleep_until_rx_interrupt(int num)
804 {
805         struct rte_epoll_event event[num];
806         int n, i;
807         uint16_t port_id;
808         uint8_t queue_id;
809         void *data;
810
811         RTE_LOG(INFO, L3FWD_POWER,
812                 "lcore %u sleeps until interrupt triggers\n",
813                 rte_lcore_id());
814
815         n = rte_epoll_wait(RTE_EPOLL_PER_THREAD, event, num, -1);
816         for (i = 0; i < n; i++) {
817                 data = event[i].epdata.data;
818                 port_id = ((uintptr_t)data) >> CHAR_BIT;
819                 queue_id = ((uintptr_t)data) &
820                         RTE_LEN2MASK(CHAR_BIT, uint8_t);
821                 rte_eth_dev_rx_intr_disable(port_id, queue_id);
822                 RTE_LOG(INFO, L3FWD_POWER,
823                         "lcore %u is waked up from rx interrupt on"
824                         " port %d queue %d\n",
825                         rte_lcore_id(), port_id, queue_id);
826         }
827
828         return 0;
829 }
830
831 static void turn_on_intr(struct lcore_conf *qconf)
832 {
833         int i;
834         struct lcore_rx_queue *rx_queue;
835         uint8_t queue_id;
836         uint16_t port_id;
837
838         for (i = 0; i < qconf->n_rx_queue; ++i) {
839                 rx_queue = &(qconf->rx_queue_list[i]);
840                 port_id = rx_queue->port_id;
841                 queue_id = rx_queue->queue_id;
842
843                 rte_spinlock_lock(&(locks[port_id]));
844                 rte_eth_dev_rx_intr_enable(port_id, queue_id);
845                 rte_spinlock_unlock(&(locks[port_id]));
846         }
847 }
848
849 static int event_register(struct lcore_conf *qconf)
850 {
851         struct lcore_rx_queue *rx_queue;
852         uint8_t queueid;
853         uint16_t portid;
854         uint32_t data;
855         int ret;
856         int i;
857
858         for (i = 0; i < qconf->n_rx_queue; ++i) {
859                 rx_queue = &(qconf->rx_queue_list[i]);
860                 portid = rx_queue->port_id;
861                 queueid = rx_queue->queue_id;
862                 data = portid << CHAR_BIT | queueid;
863
864                 ret = rte_eth_dev_rx_intr_ctl_q(portid, queueid,
865                                                 RTE_EPOLL_PER_THREAD,
866                                                 RTE_INTR_EVENT_ADD,
867                                                 (void *)((uintptr_t)data));
868                 if (ret)
869                         return ret;
870         }
871
872         return 0;
873 }
874 /* main processing loop */
875 static int
876 main_empty_poll_loop(__attribute__((unused)) void *dummy)
877 {
878         struct rte_mbuf *pkts_burst[MAX_PKT_BURST];
879         unsigned int lcore_id;
880         uint64_t prev_tsc, diff_tsc, cur_tsc;
881         int i, j, nb_rx;
882         uint8_t queueid;
883         uint16_t portid;
884         struct lcore_conf *qconf;
885         struct lcore_rx_queue *rx_queue;
886
887         const uint64_t drain_tsc =
888                 (rte_get_tsc_hz() + US_PER_S - 1) /
889                 US_PER_S * BURST_TX_DRAIN_US;
890
891         prev_tsc = 0;
892
893         lcore_id = rte_lcore_id();
894         qconf = &lcore_conf[lcore_id];
895
896         if (qconf->n_rx_queue == 0) {
897                 RTE_LOG(INFO, L3FWD_POWER, "lcore %u has nothing to do\n",
898                         lcore_id);
899                 return 0;
900         }
901
902         for (i = 0; i < qconf->n_rx_queue; i++) {
903                 portid = qconf->rx_queue_list[i].port_id;
904                 queueid = qconf->rx_queue_list[i].queue_id;
905                 RTE_LOG(INFO, L3FWD_POWER, " -- lcoreid=%u portid=%u "
906                                 "rxqueueid=%hhu\n", lcore_id, portid, queueid);
907         }
908
909         while (!is_done()) {
910                 stats[lcore_id].nb_iteration_looped++;
911
912                 cur_tsc = rte_rdtsc();
913                 /*
914                  * TX burst queue drain
915                  */
916                 diff_tsc = cur_tsc - prev_tsc;
917                 if (unlikely(diff_tsc > drain_tsc)) {
918                         for (i = 0; i < qconf->n_tx_port; ++i) {
919                                 portid = qconf->tx_port_id[i];
920                                 rte_eth_tx_buffer_flush(portid,
921                                                 qconf->tx_queue_id[portid],
922                                                 qconf->tx_buffer[portid]);
923                         }
924                         prev_tsc = cur_tsc;
925                 }
926
927                 /*
928                  * Read packet from RX queues
929                  */
930                 for (i = 0; i < qconf->n_rx_queue; ++i) {
931                         rx_queue = &(qconf->rx_queue_list[i]);
932                         rx_queue->idle_hint = 0;
933                         portid = rx_queue->port_id;
934                         queueid = rx_queue->queue_id;
935
936                         nb_rx = rte_eth_rx_burst(portid, queueid, pkts_burst,
937                                         MAX_PKT_BURST);
938
939                         stats[lcore_id].nb_rx_processed += nb_rx;
940
941                         if (nb_rx == 0) {
942
943                                 rte_power_empty_poll_stat_update(lcore_id);
944
945                                 continue;
946                         } else {
947                                 rte_power_poll_stat_update(lcore_id, nb_rx);
948                         }
949
950
951                         /* Prefetch first packets */
952                         for (j = 0; j < PREFETCH_OFFSET && j < nb_rx; j++) {
953                                 rte_prefetch0(rte_pktmbuf_mtod(
954                                                         pkts_burst[j], void *));
955                         }
956
957                         /* Prefetch and forward already prefetched packets */
958                         for (j = 0; j < (nb_rx - PREFETCH_OFFSET); j++) {
959                                 rte_prefetch0(rte_pktmbuf_mtod(pkts_burst[
960                                                         j + PREFETCH_OFFSET],
961                                                         void *));
962                                 l3fwd_simple_forward(pkts_burst[j], portid,
963                                                 qconf);
964                         }
965
966                         /* Forward remaining prefetched packets */
967                         for (; j < nb_rx; j++) {
968                                 l3fwd_simple_forward(pkts_burst[j], portid,
969                                                 qconf);
970                         }
971
972                 }
973
974         }
975
976         return 0;
977 }
978 /* main processing loop */
979 static int
980 main_loop(__attribute__((unused)) void *dummy)
981 {
982         struct rte_mbuf *pkts_burst[MAX_PKT_BURST];
983         unsigned lcore_id;
984         uint64_t prev_tsc, diff_tsc, cur_tsc, tim_res_tsc, hz;
985         uint64_t prev_tsc_power = 0, cur_tsc_power, diff_tsc_power;
986         int i, j, nb_rx;
987         uint8_t queueid;
988         uint16_t portid;
989         struct lcore_conf *qconf;
990         struct lcore_rx_queue *rx_queue;
991         enum freq_scale_hint_t lcore_scaleup_hint;
992         uint32_t lcore_rx_idle_count = 0;
993         uint32_t lcore_idle_hint = 0;
994         int intr_en = 0;
995
996         const uint64_t drain_tsc = (rte_get_tsc_hz() + US_PER_S - 1) / US_PER_S * BURST_TX_DRAIN_US;
997
998         prev_tsc = 0;
999         hz = rte_get_timer_hz();
1000         tim_res_tsc = hz/TIMER_NUMBER_PER_SECOND;
1001
1002         lcore_id = rte_lcore_id();
1003         qconf = &lcore_conf[lcore_id];
1004
1005         if (qconf->n_rx_queue == 0) {
1006                 RTE_LOG(INFO, L3FWD_POWER, "lcore %u has nothing to do\n", lcore_id);
1007                 return 0;
1008         }
1009
1010         RTE_LOG(INFO, L3FWD_POWER, "entering main loop on lcore %u\n", lcore_id);
1011
1012         for (i = 0; i < qconf->n_rx_queue; i++) {
1013                 portid = qconf->rx_queue_list[i].port_id;
1014                 queueid = qconf->rx_queue_list[i].queue_id;
1015                 RTE_LOG(INFO, L3FWD_POWER, " -- lcoreid=%u portid=%u "
1016                         "rxqueueid=%hhu\n", lcore_id, portid, queueid);
1017         }
1018
1019         /* add into event wait list */
1020         if (event_register(qconf) == 0)
1021                 intr_en = 1;
1022         else
1023                 RTE_LOG(INFO, L3FWD_POWER, "RX interrupt won't enable.\n");
1024
1025         while (1) {
1026                 stats[lcore_id].nb_iteration_looped++;
1027
1028                 cur_tsc = rte_rdtsc();
1029                 cur_tsc_power = cur_tsc;
1030
1031                 /*
1032                  * TX burst queue drain
1033                  */
1034                 diff_tsc = cur_tsc - prev_tsc;
1035                 if (unlikely(diff_tsc > drain_tsc)) {
1036                         for (i = 0; i < qconf->n_tx_port; ++i) {
1037                                 portid = qconf->tx_port_id[i];
1038                                 rte_eth_tx_buffer_flush(portid,
1039                                                 qconf->tx_queue_id[portid],
1040                                                 qconf->tx_buffer[portid]);
1041                         }
1042                         prev_tsc = cur_tsc;
1043                 }
1044
1045                 diff_tsc_power = cur_tsc_power - prev_tsc_power;
1046                 if (diff_tsc_power > tim_res_tsc) {
1047                         rte_timer_manage();
1048                         prev_tsc_power = cur_tsc_power;
1049                 }
1050
1051 start_rx:
1052                 /*
1053                  * Read packet from RX queues
1054                  */
1055                 lcore_scaleup_hint = FREQ_CURRENT;
1056                 lcore_rx_idle_count = 0;
1057                 for (i = 0; i < qconf->n_rx_queue; ++i) {
1058                         rx_queue = &(qconf->rx_queue_list[i]);
1059                         rx_queue->idle_hint = 0;
1060                         portid = rx_queue->port_id;
1061                         queueid = rx_queue->queue_id;
1062
1063                         nb_rx = rte_eth_rx_burst(portid, queueid, pkts_burst,
1064                                                                 MAX_PKT_BURST);
1065
1066                         stats[lcore_id].nb_rx_processed += nb_rx;
1067                         if (unlikely(nb_rx == 0)) {
1068                                 /**
1069                                  * no packet received from rx queue, try to
1070                                  * sleep for a while forcing CPU enter deeper
1071                                  * C states.
1072                                  */
1073                                 rx_queue->zero_rx_packet_count++;
1074
1075                                 if (rx_queue->zero_rx_packet_count <=
1076                                                         MIN_ZERO_POLL_COUNT)
1077                                         continue;
1078
1079                                 rx_queue->idle_hint = power_idle_heuristic(\
1080                                         rx_queue->zero_rx_packet_count);
1081                                 lcore_rx_idle_count++;
1082                         } else {
1083                                 rx_queue->zero_rx_packet_count = 0;
1084
1085                                 /**
1086                                  * do not scale up frequency immediately as
1087                                  * user to kernel space communication is costly
1088                                  * which might impact packet I/O for received
1089                                  * packets.
1090                                  */
1091                                 rx_queue->freq_up_hint =
1092                                         power_freq_scaleup_heuristic(lcore_id,
1093                                                         portid, queueid);
1094                         }
1095
1096                         /* Prefetch first packets */
1097                         for (j = 0; j < PREFETCH_OFFSET && j < nb_rx; j++) {
1098                                 rte_prefetch0(rte_pktmbuf_mtod(
1099                                                 pkts_burst[j], void *));
1100                         }
1101
1102                         /* Prefetch and forward already prefetched packets */
1103                         for (j = 0; j < (nb_rx - PREFETCH_OFFSET); j++) {
1104                                 rte_prefetch0(rte_pktmbuf_mtod(pkts_burst[
1105                                                 j + PREFETCH_OFFSET], void *));
1106                                 l3fwd_simple_forward(pkts_burst[j], portid,
1107                                                                 qconf);
1108                         }
1109
1110                         /* Forward remaining prefetched packets */
1111                         for (; j < nb_rx; j++) {
1112                                 l3fwd_simple_forward(pkts_burst[j], portid,
1113                                                                 qconf);
1114                         }
1115                 }
1116
1117                 if (likely(lcore_rx_idle_count != qconf->n_rx_queue)) {
1118                         for (i = 1, lcore_scaleup_hint =
1119                                 qconf->rx_queue_list[0].freq_up_hint;
1120                                         i < qconf->n_rx_queue; ++i) {
1121                                 rx_queue = &(qconf->rx_queue_list[i]);
1122                                 if (rx_queue->freq_up_hint >
1123                                                 lcore_scaleup_hint)
1124                                         lcore_scaleup_hint =
1125                                                 rx_queue->freq_up_hint;
1126                         }
1127
1128                         if (lcore_scaleup_hint == FREQ_HIGHEST) {
1129                                 if (rte_power_freq_max)
1130                                         rte_power_freq_max(lcore_id);
1131                         } else if (lcore_scaleup_hint == FREQ_HIGHER) {
1132                                 if (rte_power_freq_up)
1133                                         rte_power_freq_up(lcore_id);
1134                         }
1135                 } else {
1136                         /**
1137                          * All Rx queues empty in recent consecutive polls,
1138                          * sleep in a conservative manner, meaning sleep as
1139                          * less as possible.
1140                          */
1141                         for (i = 1, lcore_idle_hint =
1142                                 qconf->rx_queue_list[0].idle_hint;
1143                                         i < qconf->n_rx_queue; ++i) {
1144                                 rx_queue = &(qconf->rx_queue_list[i]);
1145                                 if (rx_queue->idle_hint < lcore_idle_hint)
1146                                         lcore_idle_hint = rx_queue->idle_hint;
1147                         }
1148
1149                         if (lcore_idle_hint < SUSPEND_THRESHOLD)
1150                                 /**
1151                                  * execute "pause" instruction to avoid context
1152                                  * switch which generally take hundred of
1153                                  * microseconds for short sleep.
1154                                  */
1155                                 rte_delay_us(lcore_idle_hint);
1156                         else {
1157                                 /* suspend until rx interrupt trigges */
1158                                 if (intr_en) {
1159                                         turn_on_intr(qconf);
1160                                         sleep_until_rx_interrupt(
1161                                                 qconf->n_rx_queue);
1162                                         /**
1163                                          * start receiving packets immediately
1164                                          */
1165                                         goto start_rx;
1166                                 }
1167                         }
1168                         stats[lcore_id].sleep_time += lcore_idle_hint;
1169                 }
1170         }
1171 }
1172
1173 static int
1174 check_lcore_params(void)
1175 {
1176         uint8_t queue, lcore;
1177         uint16_t i;
1178         int socketid;
1179
1180         for (i = 0; i < nb_lcore_params; ++i) {
1181                 queue = lcore_params[i].queue_id;
1182                 if (queue >= MAX_RX_QUEUE_PER_PORT) {
1183                         printf("invalid queue number: %hhu\n", queue);
1184                         return -1;
1185                 }
1186                 lcore = lcore_params[i].lcore_id;
1187                 if (!rte_lcore_is_enabled(lcore)) {
1188                         printf("error: lcore %hhu is not enabled in lcore "
1189                                                         "mask\n", lcore);
1190                         return -1;
1191                 }
1192                 if ((socketid = rte_lcore_to_socket_id(lcore) != 0) &&
1193                                                         (numa_on == 0)) {
1194                         printf("warning: lcore %hhu is on socket %d with numa "
1195                                                 "off\n", lcore, socketid);
1196                 }
1197         }
1198         return 0;
1199 }
1200
1201 static int
1202 check_port_config(void)
1203 {
1204         unsigned portid;
1205         uint16_t i;
1206
1207         for (i = 0; i < nb_lcore_params; ++i) {
1208                 portid = lcore_params[i].port_id;
1209                 if ((enabled_port_mask & (1 << portid)) == 0) {
1210                         printf("port %u is not enabled in port mask\n",
1211                                                                 portid);
1212                         return -1;
1213                 }
1214                 if (!rte_eth_dev_is_valid_port(portid)) {
1215                         printf("port %u is not present on the board\n",
1216                                                                 portid);
1217                         return -1;
1218                 }
1219         }
1220         return 0;
1221 }
1222
1223 static uint8_t
1224 get_port_n_rx_queues(const uint16_t port)
1225 {
1226         int queue = -1;
1227         uint16_t i;
1228
1229         for (i = 0; i < nb_lcore_params; ++i) {
1230                 if (lcore_params[i].port_id == port &&
1231                                 lcore_params[i].queue_id > queue)
1232                         queue = lcore_params[i].queue_id;
1233         }
1234         return (uint8_t)(++queue);
1235 }
1236
1237 static int
1238 init_lcore_rx_queues(void)
1239 {
1240         uint16_t i, nb_rx_queue;
1241         uint8_t lcore;
1242
1243         for (i = 0; i < nb_lcore_params; ++i) {
1244                 lcore = lcore_params[i].lcore_id;
1245                 nb_rx_queue = lcore_conf[lcore].n_rx_queue;
1246                 if (nb_rx_queue >= MAX_RX_QUEUE_PER_LCORE) {
1247                         printf("error: too many queues (%u) for lcore: %u\n",
1248                                 (unsigned)nb_rx_queue + 1, (unsigned)lcore);
1249                         return -1;
1250                 } else {
1251                         lcore_conf[lcore].rx_queue_list[nb_rx_queue].port_id =
1252                                 lcore_params[i].port_id;
1253                         lcore_conf[lcore].rx_queue_list[nb_rx_queue].queue_id =
1254                                 lcore_params[i].queue_id;
1255                         lcore_conf[lcore].n_rx_queue++;
1256                 }
1257         }
1258         return 0;
1259 }
1260
1261 /* display usage */
1262 static void
1263 print_usage(const char *prgname)
1264 {
1265         printf ("%s [EAL options] -- -p PORTMASK -P"
1266                 "  [--config (port,queue,lcore)[,(port,queue,lcore]]"
1267                 "  [--high-perf-cores CORELIST"
1268                 "  [--perf-config (port,queue,hi_perf,lcore_index)[,(port,queue,hi_perf,lcore_index]]"
1269                 "  [--enable-jumbo [--max-pkt-len PKTLEN]]\n"
1270                 "  -p PORTMASK: hexadecimal bitmask of ports to configure\n"
1271                 "  -P : enable promiscuous mode\n"
1272                 "  --config (port,queue,lcore): rx queues configuration\n"
1273                 "  --high-perf-cores CORELIST: list of high performance cores\n"
1274                 "  --perf-config: similar as config, cores specified as indices"
1275                 " for bins containing high or regular performance cores\n"
1276                 "  --no-numa: optional, disable numa awareness\n"
1277                 "  --enable-jumbo: enable jumbo frame"
1278                 " which max packet len is PKTLEN in decimal (64-9600)\n"
1279                 "  --parse-ptype: parse packet type by software\n"
1280                 "  --empty-poll: enable empty poll detection"
1281                 " follow (training_flag, high_threshold, med_threshold)\n",
1282                 prgname);
1283 }
1284
1285 static int parse_max_pkt_len(const char *pktlen)
1286 {
1287         char *end = NULL;
1288         unsigned long len;
1289
1290         /* parse decimal string */
1291         len = strtoul(pktlen, &end, 10);
1292         if ((pktlen[0] == '\0') || (end == NULL) || (*end != '\0'))
1293                 return -1;
1294
1295         if (len == 0)
1296                 return -1;
1297
1298         return len;
1299 }
1300
1301 static int
1302 parse_portmask(const char *portmask)
1303 {
1304         char *end = NULL;
1305         unsigned long pm;
1306
1307         /* parse hexadecimal string */
1308         pm = strtoul(portmask, &end, 16);
1309         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
1310                 return -1;
1311
1312         if (pm == 0)
1313                 return -1;
1314
1315         return pm;
1316 }
1317
1318 static int
1319 parse_config(const char *q_arg)
1320 {
1321         char s[256];
1322         const char *p, *p0 = q_arg;
1323         char *end;
1324         enum fieldnames {
1325                 FLD_PORT = 0,
1326                 FLD_QUEUE,
1327                 FLD_LCORE,
1328                 _NUM_FLD
1329         };
1330         unsigned long int_fld[_NUM_FLD];
1331         char *str_fld[_NUM_FLD];
1332         int i;
1333         unsigned size;
1334
1335         nb_lcore_params = 0;
1336
1337         while ((p = strchr(p0,'(')) != NULL) {
1338                 ++p;
1339                 if((p0 = strchr(p,')')) == NULL)
1340                         return -1;
1341
1342                 size = p0 - p;
1343                 if(size >= sizeof(s))
1344                         return -1;
1345
1346                 snprintf(s, sizeof(s), "%.*s", size, p);
1347                 if (rte_strsplit(s, sizeof(s), str_fld, _NUM_FLD, ',') !=
1348                                                                 _NUM_FLD)
1349                         return -1;
1350                 for (i = 0; i < _NUM_FLD; i++){
1351                         errno = 0;
1352                         int_fld[i] = strtoul(str_fld[i], &end, 0);
1353                         if (errno != 0 || end == str_fld[i] || int_fld[i] >
1354                                                                         255)
1355                                 return -1;
1356                 }
1357                 if (nb_lcore_params >= MAX_LCORE_PARAMS) {
1358                         printf("exceeded max number of lcore params: %hu\n",
1359                                 nb_lcore_params);
1360                         return -1;
1361                 }
1362                 lcore_params_array[nb_lcore_params].port_id =
1363                                 (uint8_t)int_fld[FLD_PORT];
1364                 lcore_params_array[nb_lcore_params].queue_id =
1365                                 (uint8_t)int_fld[FLD_QUEUE];
1366                 lcore_params_array[nb_lcore_params].lcore_id =
1367                                 (uint8_t)int_fld[FLD_LCORE];
1368                 ++nb_lcore_params;
1369         }
1370         lcore_params = lcore_params_array;
1371
1372         return 0;
1373 }
1374 static int
1375 parse_ep_config(const char *q_arg)
1376 {
1377         char s[256];
1378         const char *p = q_arg;
1379         char *end;
1380         int  num_arg;
1381
1382         char *str_fld[3];
1383
1384         int training_flag;
1385         int med_edpi;
1386         int hgh_edpi;
1387
1388         ep_med_edpi = EMPTY_POLL_MED_THRESHOLD;
1389         ep_hgh_edpi = EMPTY_POLL_MED_THRESHOLD;
1390
1391         snprintf(s, sizeof(s), "%s", p);
1392
1393         num_arg = rte_strsplit(s, sizeof(s), str_fld, 3, ',');
1394
1395         empty_poll_train = false;
1396
1397         if (num_arg == 0)
1398                 return 0;
1399
1400         if (num_arg == 3) {
1401
1402                 training_flag = strtoul(str_fld[0], &end, 0);
1403                 med_edpi = strtoul(str_fld[1], &end, 0);
1404                 hgh_edpi = strtoul(str_fld[2], &end, 0);
1405
1406                 if (training_flag == 1)
1407                         empty_poll_train = true;
1408
1409                 if (med_edpi > 0)
1410                         ep_med_edpi = med_edpi;
1411
1412                 if (med_edpi > 0)
1413                         ep_hgh_edpi = hgh_edpi;
1414
1415         } else {
1416
1417                 return -1;
1418         }
1419
1420         return 0;
1421
1422 }
1423 #define CMD_LINE_OPT_PARSE_PTYPE "parse-ptype"
1424
1425 /* Parse the argument given in the command line of the application */
1426 static int
1427 parse_args(int argc, char **argv)
1428 {
1429         int opt, ret;
1430         char **argvopt;
1431         int option_index;
1432         uint32_t limit;
1433         char *prgname = argv[0];
1434         static struct option lgopts[] = {
1435                 {"config", 1, 0, 0},
1436                 {"perf-config", 1, 0, 0},
1437                 {"high-perf-cores", 1, 0, 0},
1438                 {"no-numa", 0, 0, 0},
1439                 {"enable-jumbo", 0, 0, 0},
1440                 {"empty-poll", 1, 0, 0},
1441                 {CMD_LINE_OPT_PARSE_PTYPE, 0, 0, 0},
1442                 {NULL, 0, 0, 0}
1443         };
1444
1445         argvopt = argv;
1446
1447         while ((opt = getopt_long(argc, argvopt, "p:l:m:h:P",
1448                                 lgopts, &option_index)) != EOF) {
1449
1450                 switch (opt) {
1451                 /* portmask */
1452                 case 'p':
1453                         enabled_port_mask = parse_portmask(optarg);
1454                         if (enabled_port_mask == 0) {
1455                                 printf("invalid portmask\n");
1456                                 print_usage(prgname);
1457                                 return -1;
1458                         }
1459                         break;
1460                 case 'P':
1461                         printf("Promiscuous mode selected\n");
1462                         promiscuous_on = 1;
1463                         break;
1464                 case 'l':
1465                         limit = parse_max_pkt_len(optarg);
1466                         freq_tlb[LOW] = limit;
1467                         break;
1468                 case 'm':
1469                         limit = parse_max_pkt_len(optarg);
1470                         freq_tlb[MED] = limit;
1471                         break;
1472                 case 'h':
1473                         limit = parse_max_pkt_len(optarg);
1474                         freq_tlb[HGH] = limit;
1475                         break;
1476                 /* long options */
1477                 case 0:
1478                         if (!strncmp(lgopts[option_index].name, "config", 6)) {
1479                                 ret = parse_config(optarg);
1480                                 if (ret) {
1481                                         printf("invalid config\n");
1482                                         print_usage(prgname);
1483                                         return -1;
1484                                 }
1485                         }
1486
1487                         if (!strncmp(lgopts[option_index].name,
1488                                         "perf-config", 11)) {
1489                                 ret = parse_perf_config(optarg);
1490                                 if (ret) {
1491                                         printf("invalid perf-config\n");
1492                                         print_usage(prgname);
1493                                         return -1;
1494                                 }
1495                         }
1496
1497                         if (!strncmp(lgopts[option_index].name,
1498                                         "high-perf-cores", 15)) {
1499                                 ret = parse_perf_core_list(optarg);
1500                                 if (ret) {
1501                                         printf("invalid high-perf-cores\n");
1502                                         print_usage(prgname);
1503                                         return -1;
1504                                 }
1505                         }
1506
1507                         if (!strncmp(lgopts[option_index].name,
1508                                                 "no-numa", 7)) {
1509                                 printf("numa is disabled \n");
1510                                 numa_on = 0;
1511                         }
1512
1513                         if (!strncmp(lgopts[option_index].name,
1514                                                 "empty-poll", 10)) {
1515                                 printf("empty-poll is enabled\n");
1516                                 empty_poll_on = true;
1517                                 ret = parse_ep_config(optarg);
1518
1519                                 if (ret) {
1520                                         printf("invalid empty poll config\n");
1521                                         print_usage(prgname);
1522                                         return -1;
1523                                 }
1524
1525                         }
1526
1527                         if (!strncmp(lgopts[option_index].name,
1528                                         "enable-jumbo", 12)) {
1529                                 struct option lenopts =
1530                                         {"max-pkt-len", required_argument, \
1531                                                                         0, 0};
1532
1533                                 printf("jumbo frame is enabled \n");
1534                                 port_conf.rxmode.offloads |=
1535                                                 DEV_RX_OFFLOAD_JUMBO_FRAME;
1536                                 port_conf.txmode.offloads |=
1537                                                 DEV_TX_OFFLOAD_MULTI_SEGS;
1538
1539                                 /**
1540                                  * if no max-pkt-len set, use the default value
1541                                  * ETHER_MAX_LEN
1542                                  */
1543                                 if (0 == getopt_long(argc, argvopt, "",
1544                                                 &lenopts, &option_index)) {
1545                                         ret = parse_max_pkt_len(optarg);
1546                                         if ((ret < 64) ||
1547                                                 (ret > MAX_JUMBO_PKT_LEN)){
1548                                                 printf("invalid packet "
1549                                                                 "length\n");
1550                                                 print_usage(prgname);
1551                                                 return -1;
1552                                         }
1553                                         port_conf.rxmode.max_rx_pkt_len = ret;
1554                                 }
1555                                 printf("set jumbo frame "
1556                                         "max packet length to %u\n",
1557                                 (unsigned int)port_conf.rxmode.max_rx_pkt_len);
1558                         }
1559
1560                         if (!strncmp(lgopts[option_index].name,
1561                                      CMD_LINE_OPT_PARSE_PTYPE,
1562                                      sizeof(CMD_LINE_OPT_PARSE_PTYPE))) {
1563                                 printf("soft parse-ptype is enabled\n");
1564                                 parse_ptype = 1;
1565                         }
1566
1567                         break;
1568
1569                 default:
1570                         print_usage(prgname);
1571                         return -1;
1572                 }
1573         }
1574
1575         if (optind >= 0)
1576                 argv[optind-1] = prgname;
1577
1578         ret = optind-1;
1579         optind = 1; /* reset getopt lib */
1580         return ret;
1581 }
1582
1583 static void
1584 print_ethaddr(const char *name, const struct ether_addr *eth_addr)
1585 {
1586         char buf[ETHER_ADDR_FMT_SIZE];
1587         ether_format_addr(buf, ETHER_ADDR_FMT_SIZE, eth_addr);
1588         printf("%s%s", name, buf);
1589 }
1590
1591 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
1592 static void
1593 setup_hash(int socketid)
1594 {
1595         struct rte_hash_parameters ipv4_l3fwd_hash_params = {
1596                 .name = NULL,
1597                 .entries = L3FWD_HASH_ENTRIES,
1598                 .key_len = sizeof(struct ipv4_5tuple),
1599                 .hash_func = DEFAULT_HASH_FUNC,
1600                 .hash_func_init_val = 0,
1601         };
1602
1603         struct rte_hash_parameters ipv6_l3fwd_hash_params = {
1604                 .name = NULL,
1605                 .entries = L3FWD_HASH_ENTRIES,
1606                 .key_len = sizeof(struct ipv6_5tuple),
1607                 .hash_func = DEFAULT_HASH_FUNC,
1608                 .hash_func_init_val = 0,
1609         };
1610
1611         unsigned i;
1612         int ret;
1613         char s[64];
1614
1615         /* create ipv4 hash */
1616         snprintf(s, sizeof(s), "ipv4_l3fwd_hash_%d", socketid);
1617         ipv4_l3fwd_hash_params.name = s;
1618         ipv4_l3fwd_hash_params.socket_id = socketid;
1619         ipv4_l3fwd_lookup_struct[socketid] =
1620                 rte_hash_create(&ipv4_l3fwd_hash_params);
1621         if (ipv4_l3fwd_lookup_struct[socketid] == NULL)
1622                 rte_exit(EXIT_FAILURE, "Unable to create the l3fwd hash on "
1623                                 "socket %d\n", socketid);
1624
1625         /* create ipv6 hash */
1626         snprintf(s, sizeof(s), "ipv6_l3fwd_hash_%d", socketid);
1627         ipv6_l3fwd_hash_params.name = s;
1628         ipv6_l3fwd_hash_params.socket_id = socketid;
1629         ipv6_l3fwd_lookup_struct[socketid] =
1630                 rte_hash_create(&ipv6_l3fwd_hash_params);
1631         if (ipv6_l3fwd_lookup_struct[socketid] == NULL)
1632                 rte_exit(EXIT_FAILURE, "Unable to create the l3fwd hash on "
1633                                 "socket %d\n", socketid);
1634
1635
1636         /* populate the ipv4 hash */
1637         for (i = 0; i < IPV4_L3FWD_NUM_ROUTES; i++) {
1638                 ret = rte_hash_add_key (ipv4_l3fwd_lookup_struct[socketid],
1639                                 (void *) &ipv4_l3fwd_route_array[i].key);
1640                 if (ret < 0) {
1641                         rte_exit(EXIT_FAILURE, "Unable to add entry %u to the"
1642                                 "l3fwd hash on socket %d\n", i, socketid);
1643                 }
1644                 ipv4_l3fwd_out_if[ret] = ipv4_l3fwd_route_array[i].if_out;
1645                 printf("Hash: Adding key\n");
1646                 print_ipv4_key(ipv4_l3fwd_route_array[i].key);
1647         }
1648
1649         /* populate the ipv6 hash */
1650         for (i = 0; i < IPV6_L3FWD_NUM_ROUTES; i++) {
1651                 ret = rte_hash_add_key (ipv6_l3fwd_lookup_struct[socketid],
1652                                 (void *) &ipv6_l3fwd_route_array[i].key);
1653                 if (ret < 0) {
1654                         rte_exit(EXIT_FAILURE, "Unable to add entry %u to the"
1655                                 "l3fwd hash on socket %d\n", i, socketid);
1656                 }
1657                 ipv6_l3fwd_out_if[ret] = ipv6_l3fwd_route_array[i].if_out;
1658                 printf("Hash: Adding key\n");
1659                 print_ipv6_key(ipv6_l3fwd_route_array[i].key);
1660         }
1661 }
1662 #endif
1663
1664 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
1665 static void
1666 setup_lpm(int socketid)
1667 {
1668         unsigned i;
1669         int ret;
1670         char s[64];
1671
1672         /* create the LPM table */
1673         struct rte_lpm_config lpm_ipv4_config;
1674
1675         lpm_ipv4_config.max_rules = IPV4_L3FWD_LPM_MAX_RULES;
1676         lpm_ipv4_config.number_tbl8s = 256;
1677         lpm_ipv4_config.flags = 0;
1678
1679         snprintf(s, sizeof(s), "IPV4_L3FWD_LPM_%d", socketid);
1680         ipv4_l3fwd_lookup_struct[socketid] =
1681                         rte_lpm_create(s, socketid, &lpm_ipv4_config);
1682         if (ipv4_l3fwd_lookup_struct[socketid] == NULL)
1683                 rte_exit(EXIT_FAILURE, "Unable to create the l3fwd LPM table"
1684                                 " on socket %d\n", socketid);
1685
1686         /* populate the LPM table */
1687         for (i = 0; i < IPV4_L3FWD_NUM_ROUTES; i++) {
1688                 ret = rte_lpm_add(ipv4_l3fwd_lookup_struct[socketid],
1689                         ipv4_l3fwd_route_array[i].ip,
1690                         ipv4_l3fwd_route_array[i].depth,
1691                         ipv4_l3fwd_route_array[i].if_out);
1692
1693                 if (ret < 0) {
1694                         rte_exit(EXIT_FAILURE, "Unable to add entry %u to the "
1695                                 "l3fwd LPM table on socket %d\n",
1696                                 i, socketid);
1697                 }
1698
1699                 printf("LPM: Adding route 0x%08x / %d (%d)\n",
1700                         (unsigned)ipv4_l3fwd_route_array[i].ip,
1701                         ipv4_l3fwd_route_array[i].depth,
1702                         ipv4_l3fwd_route_array[i].if_out);
1703         }
1704 }
1705 #endif
1706
1707 static int
1708 init_mem(unsigned nb_mbuf)
1709 {
1710         struct lcore_conf *qconf;
1711         int socketid;
1712         unsigned lcore_id;
1713         char s[64];
1714
1715         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1716                 if (rte_lcore_is_enabled(lcore_id) == 0)
1717                         continue;
1718
1719                 if (numa_on)
1720                         socketid = rte_lcore_to_socket_id(lcore_id);
1721                 else
1722                         socketid = 0;
1723
1724                 if (socketid >= NB_SOCKETS) {
1725                         rte_exit(EXIT_FAILURE, "Socket %d of lcore %u is "
1726                                         "out of range %d\n", socketid,
1727                                                 lcore_id, NB_SOCKETS);
1728                 }
1729                 if (pktmbuf_pool[socketid] == NULL) {
1730                         snprintf(s, sizeof(s), "mbuf_pool_%d", socketid);
1731                         pktmbuf_pool[socketid] =
1732                                 rte_pktmbuf_pool_create(s, nb_mbuf,
1733                                         MEMPOOL_CACHE_SIZE, 0,
1734                                         RTE_MBUF_DEFAULT_BUF_SIZE,
1735                                         socketid);
1736                         if (pktmbuf_pool[socketid] == NULL)
1737                                 rte_exit(EXIT_FAILURE,
1738                                         "Cannot init mbuf pool on socket %d\n",
1739                                                                 socketid);
1740                         else
1741                                 printf("Allocated mbuf pool on socket %d\n",
1742                                                                 socketid);
1743
1744 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
1745                         setup_lpm(socketid);
1746 #else
1747                         setup_hash(socketid);
1748 #endif
1749                 }
1750                 qconf = &lcore_conf[lcore_id];
1751                 qconf->ipv4_lookup_struct = ipv4_l3fwd_lookup_struct[socketid];
1752 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
1753                 qconf->ipv6_lookup_struct = ipv6_l3fwd_lookup_struct[socketid];
1754 #endif
1755         }
1756         return 0;
1757 }
1758
1759 /* Check the link status of all ports in up to 9s, and print them finally */
1760 static void
1761 check_all_ports_link_status(uint32_t port_mask)
1762 {
1763 #define CHECK_INTERVAL 100 /* 100ms */
1764 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
1765         uint8_t count, all_ports_up, print_flag = 0;
1766         uint16_t portid;
1767         struct rte_eth_link link;
1768
1769         printf("\nChecking link status");
1770         fflush(stdout);
1771         for (count = 0; count <= MAX_CHECK_TIME; count++) {
1772                 all_ports_up = 1;
1773                 RTE_ETH_FOREACH_DEV(portid) {
1774                         if ((port_mask & (1 << portid)) == 0)
1775                                 continue;
1776                         memset(&link, 0, sizeof(link));
1777                         rte_eth_link_get_nowait(portid, &link);
1778                         /* print link status if flag set */
1779                         if (print_flag == 1) {
1780                                 if (link.link_status)
1781                                         printf("Port %d Link Up - speed %u "
1782                                                 "Mbps - %s\n", (uint8_t)portid,
1783                                                 (unsigned)link.link_speed,
1784                                 (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
1785                                         ("full-duplex") : ("half-duplex\n"));
1786                                 else
1787                                         printf("Port %d Link Down\n",
1788                                                 (uint8_t)portid);
1789                                 continue;
1790                         }
1791                         /* clear all_ports_up flag if any link down */
1792                         if (link.link_status == ETH_LINK_DOWN) {
1793                                 all_ports_up = 0;
1794                                 break;
1795                         }
1796                 }
1797                 /* after finally printing all link status, get out */
1798                 if (print_flag == 1)
1799                         break;
1800
1801                 if (all_ports_up == 0) {
1802                         printf(".");
1803                         fflush(stdout);
1804                         rte_delay_ms(CHECK_INTERVAL);
1805                 }
1806
1807                 /* set the print_flag if all ports up or timeout */
1808                 if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
1809                         print_flag = 1;
1810                         printf("done\n");
1811                 }
1812         }
1813 }
1814
1815 static int check_ptype(uint16_t portid)
1816 {
1817         int i, ret;
1818         int ptype_l3_ipv4 = 0;
1819 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
1820         int ptype_l3_ipv6 = 0;
1821 #endif
1822         uint32_t ptype_mask = RTE_PTYPE_L3_MASK;
1823
1824         ret = rte_eth_dev_get_supported_ptypes(portid, ptype_mask, NULL, 0);
1825         if (ret <= 0)
1826                 return 0;
1827
1828         uint32_t ptypes[ret];
1829
1830         ret = rte_eth_dev_get_supported_ptypes(portid, ptype_mask, ptypes, ret);
1831         for (i = 0; i < ret; ++i) {
1832                 if (ptypes[i] & RTE_PTYPE_L3_IPV4)
1833                         ptype_l3_ipv4 = 1;
1834 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
1835                 if (ptypes[i] & RTE_PTYPE_L3_IPV6)
1836                         ptype_l3_ipv6 = 1;
1837 #endif
1838         }
1839
1840         if (ptype_l3_ipv4 == 0)
1841                 printf("port %d cannot parse RTE_PTYPE_L3_IPV4\n", portid);
1842
1843 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
1844         if (ptype_l3_ipv6 == 0)
1845                 printf("port %d cannot parse RTE_PTYPE_L3_IPV6\n", portid);
1846 #endif
1847
1848 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
1849         if (ptype_l3_ipv4)
1850 #else /* APP_LOOKUP_EXACT_MATCH */
1851         if (ptype_l3_ipv4 && ptype_l3_ipv6)
1852 #endif
1853                 return 1;
1854
1855         return 0;
1856
1857 }
1858
1859 static int
1860 init_power_library(void)
1861 {
1862         int ret = 0, lcore_id;
1863         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1864                 if (rte_lcore_is_enabled(lcore_id)) {
1865                         /* init power management library */
1866                         ret = rte_power_init(lcore_id);
1867                         if (ret)
1868                                 RTE_LOG(ERR, POWER,
1869                                 "Library initialization failed on core %u\n",
1870                                 lcore_id);
1871                 }
1872         }
1873         return ret;
1874 }
1875 static void
1876 empty_poll_setup_timer(void)
1877 {
1878         int lcore_id = rte_lcore_id();
1879         uint64_t hz = rte_get_timer_hz();
1880
1881         struct  ep_params *ep_ptr = ep_params;
1882
1883         ep_ptr->interval_ticks = hz / INTERVALS_PER_SECOND;
1884
1885         rte_timer_reset_sync(&ep_ptr->timer0,
1886                         ep_ptr->interval_ticks,
1887                         PERIODICAL,
1888                         lcore_id,
1889                         rte_empty_poll_detection,
1890                         (void *)ep_ptr);
1891
1892 }
1893 static int
1894 launch_timer(unsigned int lcore_id)
1895 {
1896         int64_t prev_tsc = 0, cur_tsc, diff_tsc, cycles_10ms;
1897
1898         RTE_SET_USED(lcore_id);
1899
1900
1901         if (rte_get_master_lcore() != lcore_id) {
1902                 rte_panic("timer on lcore:%d which is not master core:%d\n",
1903                                 lcore_id,
1904                                 rte_get_master_lcore());
1905         }
1906
1907         RTE_LOG(INFO, POWER, "Bring up the Timer\n");
1908
1909         empty_poll_setup_timer();
1910
1911         cycles_10ms = rte_get_timer_hz() / 100;
1912
1913         while (!is_done()) {
1914                 cur_tsc = rte_rdtsc();
1915                 diff_tsc = cur_tsc - prev_tsc;
1916                 if (diff_tsc > cycles_10ms) {
1917                         rte_timer_manage();
1918                         prev_tsc = cur_tsc;
1919                         cycles_10ms = rte_get_timer_hz() / 100;
1920                 }
1921         }
1922
1923         RTE_LOG(INFO, POWER, "Timer_subsystem is done\n");
1924
1925         return 0;
1926 }
1927
1928
1929 int
1930 main(int argc, char **argv)
1931 {
1932         struct lcore_conf *qconf;
1933         struct rte_eth_dev_info dev_info;
1934         struct rte_eth_txconf *txconf;
1935         int ret;
1936         uint16_t nb_ports;
1937         uint16_t queueid;
1938         unsigned lcore_id;
1939         uint64_t hz;
1940         uint32_t n_tx_queue, nb_lcores;
1941         uint32_t dev_rxq_num, dev_txq_num;
1942         uint8_t nb_rx_queue, queue, socketid;
1943         uint16_t portid;
1944
1945         /* catch SIGINT and restore cpufreq governor to ondemand */
1946         signal(SIGINT, signal_exit_now);
1947
1948         /* init EAL */
1949         ret = rte_eal_init(argc, argv);
1950         if (ret < 0)
1951                 rte_exit(EXIT_FAILURE, "Invalid EAL parameters\n");
1952         argc -= ret;
1953         argv += ret;
1954
1955         /* init RTE timer library to be used late */
1956         rte_timer_subsystem_init();
1957
1958         /* parse application arguments (after the EAL ones) */
1959         ret = parse_args(argc, argv);
1960         if (ret < 0)
1961                 rte_exit(EXIT_FAILURE, "Invalid L3FWD parameters\n");
1962
1963         if (init_power_library())
1964                 rte_exit(EXIT_FAILURE, "init_power_library failed\n");
1965
1966         if (update_lcore_params() < 0)
1967                 rte_exit(EXIT_FAILURE, "update_lcore_params failed\n");
1968
1969         if (check_lcore_params() < 0)
1970                 rte_exit(EXIT_FAILURE, "check_lcore_params failed\n");
1971
1972         ret = init_lcore_rx_queues();
1973         if (ret < 0)
1974                 rte_exit(EXIT_FAILURE, "init_lcore_rx_queues failed\n");
1975
1976         nb_ports = rte_eth_dev_count_avail();
1977
1978         if (check_port_config() < 0)
1979                 rte_exit(EXIT_FAILURE, "check_port_config failed\n");
1980
1981         nb_lcores = rte_lcore_count();
1982
1983         /* initialize all ports */
1984         RTE_ETH_FOREACH_DEV(portid) {
1985                 struct rte_eth_conf local_port_conf = port_conf;
1986
1987                 /* skip ports that are not enabled */
1988                 if ((enabled_port_mask & (1 << portid)) == 0) {
1989                         printf("\nSkipping disabled port %d\n", portid);
1990                         continue;
1991                 }
1992
1993                 /* init port */
1994                 printf("Initializing port %d ... ", portid );
1995                 fflush(stdout);
1996
1997                 rte_eth_dev_info_get(portid, &dev_info);
1998                 dev_rxq_num = dev_info.max_rx_queues;
1999                 dev_txq_num = dev_info.max_tx_queues;
2000
2001                 nb_rx_queue = get_port_n_rx_queues(portid);
2002                 if (nb_rx_queue > dev_rxq_num)
2003                         rte_exit(EXIT_FAILURE,
2004                                 "Cannot configure not existed rxq: "
2005                                 "port=%d\n", portid);
2006
2007                 n_tx_queue = nb_lcores;
2008                 if (n_tx_queue > dev_txq_num)
2009                         n_tx_queue = dev_txq_num;
2010                 printf("Creating queues: nb_rxq=%d nb_txq=%u... ",
2011                         nb_rx_queue, (unsigned)n_tx_queue );
2012                 /* If number of Rx queue is 0, no need to enable Rx interrupt */
2013                 if (nb_rx_queue == 0)
2014                         local_port_conf.intr_conf.rxq = 0;
2015                 rte_eth_dev_info_get(portid, &dev_info);
2016                 if (dev_info.tx_offload_capa & DEV_TX_OFFLOAD_MBUF_FAST_FREE)
2017                         local_port_conf.txmode.offloads |=
2018                                 DEV_TX_OFFLOAD_MBUF_FAST_FREE;
2019
2020                 local_port_conf.rx_adv_conf.rss_conf.rss_hf &=
2021                         dev_info.flow_type_rss_offloads;
2022                 if (local_port_conf.rx_adv_conf.rss_conf.rss_hf !=
2023                                 port_conf.rx_adv_conf.rss_conf.rss_hf) {
2024                         printf("Port %u modified RSS hash function based on hardware support,"
2025                                 "requested:%#"PRIx64" configured:%#"PRIx64"\n",
2026                                 portid,
2027                                 port_conf.rx_adv_conf.rss_conf.rss_hf,
2028                                 local_port_conf.rx_adv_conf.rss_conf.rss_hf);
2029                 }
2030
2031                 ret = rte_eth_dev_configure(portid, nb_rx_queue,
2032                                         (uint16_t)n_tx_queue, &local_port_conf);
2033                 if (ret < 0)
2034                         rte_exit(EXIT_FAILURE, "Cannot configure device: "
2035                                         "err=%d, port=%d\n", ret, portid);
2036
2037                 ret = rte_eth_dev_adjust_nb_rx_tx_desc(portid, &nb_rxd,
2038                                                        &nb_txd);
2039                 if (ret < 0)
2040                         rte_exit(EXIT_FAILURE,
2041                                  "Cannot adjust number of descriptors: err=%d, port=%d\n",
2042                                  ret, portid);
2043
2044                 rte_eth_macaddr_get(portid, &ports_eth_addr[portid]);
2045                 print_ethaddr(" Address:", &ports_eth_addr[portid]);
2046                 printf(", ");
2047
2048                 /* init memory */
2049                 ret = init_mem(NB_MBUF);
2050                 if (ret < 0)
2051                         rte_exit(EXIT_FAILURE, "init_mem failed\n");
2052
2053                 for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
2054                         if (rte_lcore_is_enabled(lcore_id) == 0)
2055                                 continue;
2056
2057                         /* Initialize TX buffers */
2058                         qconf = &lcore_conf[lcore_id];
2059                         qconf->tx_buffer[portid] = rte_zmalloc_socket("tx_buffer",
2060                                 RTE_ETH_TX_BUFFER_SIZE(MAX_PKT_BURST), 0,
2061                                 rte_eth_dev_socket_id(portid));
2062                         if (qconf->tx_buffer[portid] == NULL)
2063                                 rte_exit(EXIT_FAILURE, "Can't allocate tx buffer for port %u\n",
2064                                                  portid);
2065
2066                         rte_eth_tx_buffer_init(qconf->tx_buffer[portid], MAX_PKT_BURST);
2067                 }
2068
2069                 /* init one TX queue per couple (lcore,port) */
2070                 queueid = 0;
2071                 for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
2072                         if (rte_lcore_is_enabled(lcore_id) == 0)
2073                                 continue;
2074
2075                         if (queueid >= dev_txq_num)
2076                                 continue;
2077
2078                         if (numa_on)
2079                                 socketid = \
2080                                 (uint8_t)rte_lcore_to_socket_id(lcore_id);
2081                         else
2082                                 socketid = 0;
2083
2084                         printf("txq=%u,%d,%d ", lcore_id, queueid, socketid);
2085                         fflush(stdout);
2086
2087                         txconf = &dev_info.default_txconf;
2088                         txconf->offloads = local_port_conf.txmode.offloads;
2089                         ret = rte_eth_tx_queue_setup(portid, queueid, nb_txd,
2090                                                      socketid, txconf);
2091                         if (ret < 0)
2092                                 rte_exit(EXIT_FAILURE,
2093                                         "rte_eth_tx_queue_setup: err=%d, "
2094                                                 "port=%d\n", ret, portid);
2095
2096                         qconf = &lcore_conf[lcore_id];
2097                         qconf->tx_queue_id[portid] = queueid;
2098                         queueid++;
2099
2100                         qconf->tx_port_id[qconf->n_tx_port] = portid;
2101                         qconf->n_tx_port++;
2102                 }
2103                 printf("\n");
2104         }
2105
2106         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
2107                 if (rte_lcore_is_enabled(lcore_id) == 0)
2108                         continue;
2109
2110                 if (empty_poll_on == false) {
2111                         /* init timer structures for each enabled lcore */
2112                         rte_timer_init(&power_timers[lcore_id]);
2113                         hz = rte_get_timer_hz();
2114                         rte_timer_reset(&power_timers[lcore_id],
2115                                         hz/TIMER_NUMBER_PER_SECOND,
2116                                         SINGLE, lcore_id,
2117                                         power_timer_cb, NULL);
2118                 }
2119                 qconf = &lcore_conf[lcore_id];
2120                 printf("\nInitializing rx queues on lcore %u ... ", lcore_id );
2121                 fflush(stdout);
2122                 /* init RX queues */
2123                 for(queue = 0; queue < qconf->n_rx_queue; ++queue) {
2124                         struct rte_eth_rxconf rxq_conf;
2125                         struct rte_eth_dev *dev;
2126                         struct rte_eth_conf *conf;
2127
2128                         portid = qconf->rx_queue_list[queue].port_id;
2129                         queueid = qconf->rx_queue_list[queue].queue_id;
2130                         dev = &rte_eth_devices[portid];
2131                         conf = &dev->data->dev_conf;
2132
2133                         if (numa_on)
2134                                 socketid = \
2135                                 (uint8_t)rte_lcore_to_socket_id(lcore_id);
2136                         else
2137                                 socketid = 0;
2138
2139                         printf("rxq=%d,%d,%d ", portid, queueid, socketid);
2140                         fflush(stdout);
2141
2142                         rte_eth_dev_info_get(portid, &dev_info);
2143                         rxq_conf = dev_info.default_rxconf;
2144                         rxq_conf.offloads = conf->rxmode.offloads;
2145                         ret = rte_eth_rx_queue_setup(portid, queueid, nb_rxd,
2146                                 socketid, &rxq_conf,
2147                                 pktmbuf_pool[socketid]);
2148                         if (ret < 0)
2149                                 rte_exit(EXIT_FAILURE,
2150                                         "rte_eth_rx_queue_setup: err=%d, "
2151                                                 "port=%d\n", ret, portid);
2152
2153                         if (parse_ptype) {
2154                                 if (add_cb_parse_ptype(portid, queueid) < 0)
2155                                         rte_exit(EXIT_FAILURE,
2156                                                  "Fail to add ptype cb\n");
2157                         } else if (!check_ptype(portid))
2158                                 rte_exit(EXIT_FAILURE,
2159                                          "PMD can not provide needed ptypes\n");
2160                 }
2161         }
2162
2163         printf("\n");
2164
2165         /* start ports */
2166         RTE_ETH_FOREACH_DEV(portid) {
2167                 if ((enabled_port_mask & (1 << portid)) == 0) {
2168                         continue;
2169                 }
2170                 /* Start device */
2171                 ret = rte_eth_dev_start(portid);
2172                 if (ret < 0)
2173                         rte_exit(EXIT_FAILURE, "rte_eth_dev_start: err=%d, "
2174                                                 "port=%d\n", ret, portid);
2175                 /*
2176                  * If enabled, put device in promiscuous mode.
2177                  * This allows IO forwarding mode to forward packets
2178                  * to itself through 2 cross-connected  ports of the
2179                  * target machine.
2180                  */
2181                 if (promiscuous_on)
2182                         rte_eth_promiscuous_enable(portid);
2183                 /* initialize spinlock for each port */
2184                 rte_spinlock_init(&(locks[portid]));
2185         }
2186
2187         check_all_ports_link_status(enabled_port_mask);
2188
2189         if (empty_poll_on == true) {
2190
2191                 if (empty_poll_train) {
2192                         policy.state = TRAINING;
2193                 } else {
2194                         policy.state = MED_NORMAL;
2195                         policy.med_base_edpi = ep_med_edpi;
2196                         policy.hgh_base_edpi = ep_hgh_edpi;
2197                 }
2198
2199                 ret = rte_power_empty_poll_stat_init(&ep_params,
2200                                 freq_tlb,
2201                                 &policy);
2202                 if (ret < 0)
2203                         rte_exit(EXIT_FAILURE, "empty poll init failed");
2204         }
2205
2206
2207         /* launch per-lcore init on every lcore */
2208         if (empty_poll_on == false) {
2209                 rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
2210         } else {
2211                 empty_poll_stop = false;
2212                 rte_eal_mp_remote_launch(main_empty_poll_loop, NULL,
2213                                 SKIP_MASTER);
2214         }
2215
2216         if (empty_poll_on == true)
2217                 launch_timer(rte_lcore_id());
2218
2219         RTE_LCORE_FOREACH_SLAVE(lcore_id) {
2220                 if (rte_eal_wait_lcore(lcore_id) < 0)
2221                         return -1;
2222         }
2223
2224         if (empty_poll_on)
2225                 rte_power_empty_poll_stat_free();
2226
2227         return 0;
2228 }