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