a843391151aa87246b0a71c281de27ffc66aedc8
[dpdk.git] / examples / l3fwd-vf / 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_eal.h>
53 #include <rte_launch.h>
54 #include <rte_atomic.h>
55 #include <rte_spinlock.h>
56 #include <rte_cycles.h>
57 #include <rte_prefetch.h>
58 #include <rte_lcore.h>
59 #include <rte_per_lcore.h>
60 #include <rte_branch_prediction.h>
61 #include <rte_interrupts.h>
62 #include <rte_pci.h>
63 #include <rte_random.h>
64 #include <rte_debug.h>
65 #include <rte_ether.h>
66 #include <rte_ethdev.h>
67 #include <rte_mempool.h>
68 #include <rte_mbuf.h>
69 #include <rte_ip.h>
70 #include <rte_tcp.h>
71 #include <rte_udp.h>
72 #include <rte_string_fns.h>
73
74 #define APP_LOOKUP_EXACT_MATCH          0
75 #define APP_LOOKUP_LPM                  1
76 #define DO_RFC_1812_CHECKS
77
78 //#define APP_LOOKUP_METHOD             APP_LOOKUP_EXACT_MATCH
79 #ifndef APP_LOOKUP_METHOD
80 #define APP_LOOKUP_METHOD             APP_LOOKUP_LPM
81 #endif
82
83 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
84 #include <rte_hash.h>
85 #elif (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
86 #include <rte_lpm.h>
87 #else
88 #error "APP_LOOKUP_METHOD set to incorrect value"
89 #endif
90
91 #define RTE_LOGTYPE_L3FWD RTE_LOGTYPE_USER1
92
93 #define MEMPOOL_CACHE_SIZE 256
94
95 /*
96  * This expression is used to calculate the number of mbufs needed depending on user input, taking
97  *  into account memory for rx and tx hardware rings, cache per lcore and mtable per port per lcore.
98  *  RTE_MAX is used to ensure that NB_MBUF never goes below a minimum value of 8192
99  */
100
101 #define NB_MBUF RTE_MAX (                                               \
102                                 (nb_ports*nb_rx_queue*nb_rxd +          \
103                                 nb_ports*nb_lcores*MAX_PKT_BURST +      \
104                                 nb_ports*n_tx_queue*nb_txd +            \
105                                 nb_lcores*MEMPOOL_CACHE_SIZE),          \
106                                 (unsigned)8192)
107
108 /*
109  * RX and TX Prefetch, Host, and Write-back threshold values should be
110  * carefully set for optimal performance. Consult the network
111  * controller's datasheet and supporting DPDK documentation for guidance
112  * on how these parameters should be set.
113  */
114 #define RX_PTHRESH 8 /**< Default values of RX prefetch threshold reg. */
115 #define RX_HTHRESH 8 /**< Default values of RX host threshold reg. */
116 #define RX_WTHRESH 4 /**< Default values of RX write-back threshold reg. */
117
118 /*
119  * These default values are optimized for use with the Intel(R) 82599 10 GbE
120  * Controller and the DPDK ixgbe PMD. Consider using other values for other
121  * network controllers and/or network drivers.
122  */
123 #define TX_PTHRESH 36 /**< Default values of TX prefetch threshold reg. */
124 #define TX_HTHRESH 0  /**< Default values of TX host threshold reg. */
125 #define TX_WTHRESH 0  /**< Default values of TX write-back threshold reg. */
126
127 #define MAX_PKT_BURST 32
128 #define BURST_TX_DRAIN_US 100 /* TX drain every ~100us */
129
130 #define NB_SOCKETS 8
131
132 #define SOCKET0 0
133
134 /* Configure how many packets ahead to prefetch, when reading packets */
135 #define PREFETCH_OFFSET 3
136
137 /*
138  * Configurable number of RX/TX ring descriptors
139  */
140 #define RTE_TEST_RX_DESC_DEFAULT 128
141 #define RTE_TEST_TX_DESC_DEFAULT 512
142 static uint16_t nb_rxd = RTE_TEST_RX_DESC_DEFAULT;
143 static uint16_t nb_txd = RTE_TEST_TX_DESC_DEFAULT;
144
145 /* ethernet addresses of ports */
146 static struct ether_addr ports_eth_addr[RTE_MAX_ETHPORTS];
147
148 /* mask of enabled ports */
149 static uint32_t enabled_port_mask = 0;
150 static int numa_on = 1; /**< NUMA is enabled by default. */
151
152 struct mbuf_table {
153         uint16_t len;
154         struct rte_mbuf *m_table[MAX_PKT_BURST];
155 };
156
157 struct lcore_rx_queue {
158         uint16_t port_id;
159         uint8_t queue_id;
160 } __rte_cache_aligned;
161
162 #define MAX_RX_QUEUE_PER_LCORE 16
163 #define MAX_TX_QUEUE_PER_PORT 1
164 #define MAX_RX_QUEUE_PER_PORT 1
165
166 #define MAX_LCORE_PARAMS 1024
167 struct lcore_params {
168         uint16_t port_id;
169         uint8_t queue_id;
170         uint8_t lcore_id;
171 } __rte_cache_aligned;
172
173 static struct lcore_params lcore_params_array[MAX_LCORE_PARAMS];
174 static struct lcore_params lcore_params_array_default[] = {
175         {0, 0, 2},
176         {0, 1, 2},
177         {0, 2, 2},
178         {1, 0, 2},
179         {1, 1, 2},
180         {1, 2, 2},
181         {2, 0, 2},
182         {3, 0, 3},
183         {3, 1, 3},
184 };
185
186 static struct lcore_params * lcore_params = lcore_params_array_default;
187 static uint16_t nb_lcore_params = sizeof(lcore_params_array_default) /
188                                 sizeof(lcore_params_array_default[0]);
189
190 static struct rte_eth_conf port_conf = {
191         .rxmode = {
192                 .mq_mode        = ETH_MQ_RX_RSS,
193                 .max_rx_pkt_len = ETHER_MAX_LEN,
194                 .split_hdr_size = 0,
195                 .header_split   = 0, /**< Header Split disabled */
196                 .hw_ip_checksum = 1, /**< IP checksum offload enabled */
197                 .hw_vlan_filter = 0, /**< VLAN filtering disabled */
198                 .jumbo_frame    = 0, /**< Jumbo Frame Support disabled */
199                 .hw_strip_crc   = 1, /**< CRC stripped by hardware */
200         },
201         .rx_adv_conf = {
202                 .rss_conf = {
203                         .rss_key = NULL,
204                         .rss_hf = ETH_RSS_IP,
205                 },
206         },
207         .txmode = {
208                 .mq_mode = ETH_MQ_TX_NONE,
209         },
210 };
211
212 static struct rte_mempool * pktmbuf_pool[NB_SOCKETS];
213
214
215 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
216
217 #ifdef RTE_ARCH_X86
218 #include <rte_hash_crc.h>
219 #define DEFAULT_HASH_FUNC       rte_hash_crc
220 #else
221 #include <rte_jhash.h>
222 #define DEFAULT_HASH_FUNC       rte_jhash
223 #endif
224
225 struct ipv4_5tuple {
226         uint32_t ip_dst;
227         uint32_t ip_src;
228         uint16_t port_dst;
229         uint16_t port_src;
230         uint8_t proto;
231 } __attribute__((__packed__));
232
233 struct l3fwd_route {
234         struct ipv4_5tuple key;
235         uint8_t if_out;
236 };
237
238 static struct l3fwd_route l3fwd_route_array[] = {
239         {{IPv4(100,10,0,1), IPv4(200,10,0,1), 101, 11, IPPROTO_TCP}, 0},
240         {{IPv4(100,20,0,2), IPv4(200,20,0,2), 102, 12, IPPROTO_TCP}, 1},
241         {{IPv4(100,30,0,3), IPv4(200,30,0,3), 103, 13, IPPROTO_TCP}, 2},
242         {{IPv4(100,40,0,4), IPv4(200,40,0,4), 104, 14, IPPROTO_TCP}, 3},
243 };
244
245 typedef struct rte_hash lookup_struct_t;
246 static lookup_struct_t *l3fwd_lookup_struct[NB_SOCKETS];
247
248 #define L3FWD_HASH_ENTRIES      1024
249 struct rte_hash_parameters l3fwd_hash_params = {
250         .name = "l3fwd_hash_0",
251         .entries = L3FWD_HASH_ENTRIES,
252         .key_len = sizeof(struct ipv4_5tuple),
253         .hash_func = DEFAULT_HASH_FUNC,
254         .hash_func_init_val = 0,
255         .socket_id = SOCKET0,
256 };
257
258 #define L3FWD_NUM_ROUTES \
259         (sizeof(l3fwd_route_array) / sizeof(l3fwd_route_array[0]))
260
261 static uint8_t l3fwd_out_if[L3FWD_HASH_ENTRIES] __rte_cache_aligned;
262 #endif
263
264 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
265 struct l3fwd_route {
266         uint32_t ip;
267         uint8_t  depth;
268         uint8_t  if_out;
269 };
270
271 static struct l3fwd_route l3fwd_route_array[] = {
272         {IPv4(1,1,1,0), 24, 0},
273         {IPv4(2,1,1,0), 24, 1},
274         {IPv4(3,1,1,0), 24, 2},
275         {IPv4(4,1,1,0), 24, 3},
276         {IPv4(5,1,1,0), 24, 4},
277         {IPv4(6,1,1,0), 24, 5},
278         {IPv4(7,1,1,0), 24, 6},
279         {IPv4(8,1,1,0), 24, 7},
280 };
281
282 #define L3FWD_NUM_ROUTES \
283         (sizeof(l3fwd_route_array) / sizeof(l3fwd_route_array[0]))
284
285 #define L3FWD_LPM_MAX_RULES     1024
286
287 typedef struct rte_lpm lookup_struct_t;
288 static lookup_struct_t *l3fwd_lookup_struct[NB_SOCKETS];
289 #endif
290
291 struct lcore_conf {
292         uint16_t n_rx_queue;
293         struct lcore_rx_queue rx_queue_list[MAX_RX_QUEUE_PER_LCORE];
294         uint16_t tx_queue_id;
295         struct mbuf_table tx_mbufs[RTE_MAX_ETHPORTS];
296         lookup_struct_t * lookup_struct;
297 } __rte_cache_aligned;
298
299 static struct lcore_conf lcore_conf[RTE_MAX_LCORE];
300 static rte_spinlock_t spinlock_conf[RTE_MAX_ETHPORTS] = {RTE_SPINLOCK_INITIALIZER};
301 /* Send burst of packets on an output interface */
302 static inline int
303 send_burst(struct lcore_conf *qconf, uint16_t n, uint16_t port)
304 {
305         struct rte_mbuf **m_table;
306         int ret;
307         uint16_t queueid;
308
309         queueid = qconf->tx_queue_id;
310         m_table = (struct rte_mbuf **)qconf->tx_mbufs[port].m_table;
311
312         rte_spinlock_lock(&spinlock_conf[port]);
313         ret = rte_eth_tx_burst(port, queueid, m_table, n);
314         rte_spinlock_unlock(&spinlock_conf[port]);
315
316         if (unlikely(ret < n)) {
317                 do {
318                         rte_pktmbuf_free(m_table[ret]);
319                 } while (++ret < n);
320         }
321
322         return 0;
323 }
324
325 /* Enqueue a single packet, and send burst if queue is filled */
326 static inline int
327 send_single_packet(struct rte_mbuf *m, uint16_t port)
328 {
329         uint32_t lcore_id;
330         uint16_t len;
331         struct lcore_conf *qconf;
332
333         lcore_id = rte_lcore_id();
334
335         qconf = &lcore_conf[lcore_id];
336         len = qconf->tx_mbufs[port].len;
337         qconf->tx_mbufs[port].m_table[len] = m;
338         len++;
339
340         /* enough pkts to be sent */
341         if (unlikely(len == MAX_PKT_BURST)) {
342                 send_burst(qconf, MAX_PKT_BURST, port);
343                 len = 0;
344         }
345
346         qconf->tx_mbufs[port].len = len;
347         return 0;
348 }
349
350 #ifdef DO_RFC_1812_CHECKS
351 static inline int
352 is_valid_ipv4_pkt(struct ipv4_hdr *pkt, uint32_t link_len)
353 {
354         /* From http://www.rfc-editor.org/rfc/rfc1812.txt section 5.2.2 */
355         /*
356          * 1. The packet length reported by the Link Layer must be large
357          * enough to hold the minimum length legal IP datagram (20 bytes).
358          */
359         if (link_len < sizeof(struct ipv4_hdr))
360                 return -1;
361
362         /* 2. The IP checksum must be correct. */
363         /* this is checked in H/W */
364
365         /*
366          * 3. The IP version number must be 4. If the version number is not 4
367          * then the packet may be another version of IP, such as IPng or
368          * ST-II.
369          */
370         if (((pkt->version_ihl) >> 4) != 4)
371                 return -3;
372         /*
373          * 4. The IP header length field must be large enough to hold the
374          * minimum length legal IP datagram (20 bytes = 5 words).
375          */
376         if ((pkt->version_ihl & 0xf) < 5)
377                 return -4;
378
379         /*
380          * 5. The IP total length field must be large enough to hold the IP
381          * datagram header, whose length is specified in the IP header length
382          * field.
383          */
384         if (rte_cpu_to_be_16(pkt->total_length) < sizeof(struct ipv4_hdr))
385                 return -5;
386
387         return 0;
388 }
389 #endif
390
391 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
392 static void
393 print_key(struct ipv4_5tuple key)
394 {
395         printf("IP dst = %08x, IP src = %08x, port dst = %d, port src = %d, proto = %d\n",
396                (unsigned)key.ip_dst, (unsigned)key.ip_src, key.port_dst, key.port_src, key.proto);
397 }
398
399 static inline uint16_t
400 get_dst_port(struct ipv4_hdr *ipv4_hdr, uint16_t portid,
401               lookup_struct_t *l3fwd_lookup_struct)
402 {
403         struct ipv4_5tuple key;
404         struct tcp_hdr *tcp;
405         struct udp_hdr *udp;
406         int ret = 0;
407
408         key.ip_dst = rte_be_to_cpu_32(ipv4_hdr->dst_addr);
409         key.ip_src = rte_be_to_cpu_32(ipv4_hdr->src_addr);
410         key.proto = ipv4_hdr->next_proto_id;
411
412         switch (ipv4_hdr->next_proto_id) {
413         case IPPROTO_TCP:
414                 tcp = (struct tcp_hdr *)((unsigned char *) ipv4_hdr +
415                                         sizeof(struct ipv4_hdr));
416                 key.port_dst = rte_be_to_cpu_16(tcp->dst_port);
417                 key.port_src = rte_be_to_cpu_16(tcp->src_port);
418                 break;
419
420         case IPPROTO_UDP:
421                 udp = (struct udp_hdr *)((unsigned char *) ipv4_hdr +
422                                         sizeof(struct ipv4_hdr));
423                 key.port_dst = rte_be_to_cpu_16(udp->dst_port);
424                 key.port_src = rte_be_to_cpu_16(udp->src_port);
425                 break;
426
427         default:
428                 key.port_dst = 0;
429                 key.port_src = 0;
430         }
431
432         /* Find destination port */
433         ret = rte_hash_lookup(l3fwd_lookup_struct, (const void *)&key);
434         return ((ret < 0) ? portid : l3fwd_out_if[ret]);
435 }
436 #endif
437
438 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
439 static inline uint32_t
440 get_dst_port(struct ipv4_hdr *ipv4_hdr, uint16_t portid,
441               lookup_struct_t *l3fwd_lookup_struct)
442 {
443         uint32_t next_hop;
444
445         return ((rte_lpm_lookup(l3fwd_lookup_struct,
446                 rte_be_to_cpu_32(ipv4_hdr->dst_addr), &next_hop) == 0) ?
447                 next_hop : portid);
448 }
449 #endif
450
451 static inline void
452 l3fwd_simple_forward(struct rte_mbuf *m, uint16_t portid,
453                       lookup_struct_t *l3fwd_lookup_struct)
454 {
455         struct ether_hdr *eth_hdr;
456         struct ipv4_hdr *ipv4_hdr;
457         void *tmp;
458         uint16_t dst_port;
459
460         eth_hdr = rte_pktmbuf_mtod(m, struct ether_hdr *);
461
462         ipv4_hdr = rte_pktmbuf_mtod_offset(m, struct ipv4_hdr *,
463                                            sizeof(struct ether_hdr));
464
465 #ifdef DO_RFC_1812_CHECKS
466         /* Check to make sure the packet is valid (RFC1812) */
467         if (is_valid_ipv4_pkt(ipv4_hdr, m->pkt_len) < 0) {
468                 rte_pktmbuf_free(m);
469                 return;
470         }
471 #endif
472
473         dst_port = get_dst_port(ipv4_hdr, portid, l3fwd_lookup_struct);
474         if (dst_port >= RTE_MAX_ETHPORTS || (enabled_port_mask & 1 << dst_port) == 0)
475                 dst_port = portid;
476
477         /* 02:00:00:00:00:xx */
478         tmp = &eth_hdr->d_addr.addr_bytes[0];
479         *((uint64_t *)tmp) = 0x000000000002 + ((uint64_t)dst_port << 40);
480
481 #ifdef DO_RFC_1812_CHECKS
482         /* Update time to live and header checksum */
483         --(ipv4_hdr->time_to_live);
484         ++(ipv4_hdr->hdr_checksum);
485 #endif
486
487         /* src addr */
488         ether_addr_copy(&ports_eth_addr[dst_port], &eth_hdr->s_addr);
489
490         send_single_packet(m, dst_port);
491
492 }
493
494 /* main processing loop */
495 static int
496 main_loop(__attribute__((unused)) void *dummy)
497 {
498         struct rte_mbuf *pkts_burst[MAX_PKT_BURST];
499         unsigned lcore_id;
500         uint64_t prev_tsc, diff_tsc, cur_tsc;
501         int i, j, nb_rx;
502         uint8_t queueid;
503         uint16_t portid;
504         struct lcore_conf *qconf;
505         const uint64_t drain_tsc = (rte_get_tsc_hz() + US_PER_S - 1) / US_PER_S * BURST_TX_DRAIN_US;
506
507         prev_tsc = 0;
508
509         lcore_id = rte_lcore_id();
510         qconf = &lcore_conf[lcore_id];
511
512         if (qconf->n_rx_queue == 0) {
513                 RTE_LOG(INFO, L3FWD, "lcore %u has nothing to do\n", lcore_id);
514                 return 0;
515         }
516
517         RTE_LOG(INFO, L3FWD, "entering main loop on lcore %u\n", lcore_id);
518
519         for (i = 0; i < qconf->n_rx_queue; i++) {
520
521                 portid = qconf->rx_queue_list[i].port_id;
522                 queueid = qconf->rx_queue_list[i].queue_id;
523                 RTE_LOG(INFO, L3FWD, " --lcoreid=%u portid=%u rxqueueid=%hhu\n",
524                 lcore_id, portid, queueid);
525         }
526
527         while (1) {
528
529                 cur_tsc = rte_rdtsc();
530
531                 /*
532                  * TX burst queue drain
533                  */
534                 diff_tsc = cur_tsc - prev_tsc;
535                 if (unlikely(diff_tsc > drain_tsc)) {
536
537                         /*
538                          * This could be optimized (use queueid instead of
539                          * portid), but it is not called so often
540                          */
541                         for (portid = 0; portid < RTE_MAX_ETHPORTS; portid++) {
542                                 if (qconf->tx_mbufs[portid].len == 0)
543                                         continue;
544                                 send_burst(&lcore_conf[lcore_id],
545                                         qconf->tx_mbufs[portid].len,
546                                         portid);
547                                 qconf->tx_mbufs[portid].len = 0;
548                         }
549
550                         prev_tsc = cur_tsc;
551                 }
552
553                 /*
554                  * Read packet from RX queues
555                  */
556                 for (i = 0; i < qconf->n_rx_queue; ++i) {
557
558                         portid = qconf->rx_queue_list[i].port_id;
559                         queueid = qconf->rx_queue_list[i].queue_id;
560                         nb_rx = rte_eth_rx_burst(portid, queueid, pkts_burst, MAX_PKT_BURST);
561
562                         /* Prefetch first packets */
563                         for (j = 0; j < PREFETCH_OFFSET && j < nb_rx; j++) {
564                                 rte_prefetch0(rte_pktmbuf_mtod(
565                                                 pkts_burst[j], void *));
566                         }
567
568                         /* Prefetch and forward already prefetched packets */
569                         for (j = 0; j < (nb_rx - PREFETCH_OFFSET); j++) {
570                                 rte_prefetch0(rte_pktmbuf_mtod(pkts_burst[
571                                                 j + PREFETCH_OFFSET], void *));
572                                 l3fwd_simple_forward(pkts_burst[j], portid, qconf->lookup_struct);
573                         }
574
575                         /* Forward remaining prefetched packets */
576                         for (; j < nb_rx; j++) {
577                                 l3fwd_simple_forward(pkts_burst[j], portid, qconf->lookup_struct);
578                         }
579                 }
580         }
581 }
582
583 static int
584 check_lcore_params(void)
585 {
586         uint8_t queue, lcore;
587         uint16_t i;
588         int socketid;
589
590         for (i = 0; i < nb_lcore_params; ++i) {
591                 queue = lcore_params[i].queue_id;
592                 if (queue >= MAX_RX_QUEUE_PER_PORT) {
593                         printf("invalid queue number: %hhu\n", queue);
594                         return -1;
595                 }
596                 lcore = lcore_params[i].lcore_id;
597                 if (!rte_lcore_is_enabled(lcore)) {
598                         printf("error: lcore %hhu is not enabled in lcore mask\n", lcore);
599                         return -1;
600                 }
601                 if ((socketid = rte_lcore_to_socket_id(lcore) != 0) &&
602                         (numa_on == 0)) {
603                         printf("warning: lcore %hhu is on socket %d with numa off \n",
604                                 lcore, socketid);
605                 }
606         }
607         return 0;
608 }
609
610 static int
611 check_port_config(const unsigned nb_ports)
612 {
613         unsigned portid;
614         uint16_t i;
615
616         for (i = 0; i < nb_lcore_params; ++i) {
617                 portid = lcore_params[i].port_id;
618                 if ((enabled_port_mask & (1 << portid)) == 0) {
619                         printf("port %u is not enabled in port mask\n", portid);
620                         return -1;
621                 }
622                 if (portid >= nb_ports) {
623                         printf("port %u is not present on the board\n", portid);
624                         return -1;
625                 }
626         }
627         return 0;
628 }
629
630 static uint8_t
631 get_port_n_rx_queues(const uint16_t port)
632 {
633         int queue = -1;
634         uint16_t i;
635
636         for (i = 0; i < nb_lcore_params; ++i) {
637                 if (lcore_params[i].port_id == port && lcore_params[i].queue_id > queue)
638                         queue = lcore_params[i].queue_id;
639         }
640         return (uint8_t)(++queue);
641 }
642
643 static int
644 init_lcore_rx_queues(void)
645 {
646         uint16_t i, nb_rx_queue;
647         uint8_t lcore;
648
649         for (i = 0; i < nb_lcore_params; ++i) {
650                 lcore = lcore_params[i].lcore_id;
651                 nb_rx_queue = lcore_conf[lcore].n_rx_queue;
652                 if (nb_rx_queue >= MAX_RX_QUEUE_PER_LCORE) {
653                         printf("error: too many queues (%u) for lcore: %u\n",
654                                 (unsigned)nb_rx_queue + 1, (unsigned)lcore);
655                         return -1;
656                 } else {
657                         lcore_conf[lcore].rx_queue_list[nb_rx_queue].port_id =
658                                 lcore_params[i].port_id;
659                         lcore_conf[lcore].rx_queue_list[nb_rx_queue].queue_id =
660                                 lcore_params[i].queue_id;
661                         lcore_conf[lcore].n_rx_queue++;
662                 }
663         }
664         return 0;
665 }
666
667 /* display usage */
668 static void
669 print_usage(const char *prgname)
670 {
671         printf ("%s [EAL options] -- -p PORTMASK"
672                 "  [--config (port,queue,lcore)[,(port,queue,lcore]]\n"
673                 "  -p PORTMASK: hexadecimal bitmask of ports to configure\n"
674                 "  --config (port,queue,lcore): rx queues configuration\n"
675                 "  --no-numa: optional, disable numa awareness\n",
676                 prgname);
677 }
678
679 /* Custom handling of signals to handle process terminal */
680 static void
681 signal_handler(int signum)
682 {
683         uint16_t portid;
684         uint16_t nb_ports = rte_eth_dev_count();
685
686         /* When we receive a SIGINT signal */
687         if (signum == SIGINT) {
688                 for (portid = 0; portid < nb_ports; portid++) {
689                         /* skip ports that are not enabled */
690                         if ((enabled_port_mask & (1 << portid)) == 0)
691                                 continue;
692                         rte_eth_dev_close(portid);
693                 }
694         }
695         rte_exit(EXIT_SUCCESS, "\n User forced exit\n");
696 }
697 static int
698 parse_portmask(const char *portmask)
699 {
700         char *end = NULL;
701         unsigned long pm;
702
703         /* parse hexadecimal string */
704         pm = strtoul(portmask, &end, 16);
705         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
706                 return -1;
707
708         if (pm == 0)
709                 return -1;
710
711         return pm;
712 }
713
714 static int
715 parse_config(const char *q_arg)
716 {
717         char s[256];
718         const char *p, *p0 = q_arg;
719         char *end;
720         enum fieldnames {
721                 FLD_PORT = 0,
722                 FLD_QUEUE,
723                 FLD_LCORE,
724                 _NUM_FLD
725         };
726         unsigned long int_fld[_NUM_FLD];
727         char *str_fld[_NUM_FLD];
728         int i;
729         unsigned size;
730
731         nb_lcore_params = 0;
732
733         while ((p = strchr(p0,'(')) != NULL) {
734                 ++p;
735                 if((p0 = strchr(p,')')) == NULL)
736                         return -1;
737
738                 size = p0 - p;
739                 if(size >= sizeof(s))
740                         return -1;
741
742                 snprintf(s, sizeof(s), "%.*s", size, p);
743                 if (rte_strsplit(s, sizeof(s), str_fld, _NUM_FLD, ',') != _NUM_FLD)
744                         return -1;
745                 for (i = 0; i < _NUM_FLD; i++){
746                         errno = 0;
747                         int_fld[i] = strtoul(str_fld[i], &end, 0);
748                         if (errno != 0 || end == str_fld[i] || int_fld[i] > 255)
749                                 return -1;
750                 }
751                 if (nb_lcore_params >= MAX_LCORE_PARAMS) {
752                         printf("exceeded max number of lcore params: %hu\n",
753                                 nb_lcore_params);
754                         return -1;
755                 }
756                 lcore_params_array[nb_lcore_params].port_id = int_fld[FLD_PORT];
757                 lcore_params_array[nb_lcore_params].queue_id = (uint8_t)int_fld[FLD_QUEUE];
758                 lcore_params_array[nb_lcore_params].lcore_id = (uint8_t)int_fld[FLD_LCORE];
759                 ++nb_lcore_params;
760         }
761         lcore_params = lcore_params_array;
762         return 0;
763 }
764
765 /* Parse the argument given in the command line of the application */
766 static int
767 parse_args(int argc, char **argv)
768 {
769         int opt, ret;
770         char **argvopt;
771         int option_index;
772         char *prgname = argv[0];
773         static struct option lgopts[] = {
774                 {"config", 1, 0, 0},
775                 {"no-numa", 0, 0, 0},
776                 {NULL, 0, 0, 0}
777         };
778
779         argvopt = argv;
780
781         while ((opt = getopt_long(argc, argvopt, "p:",
782                                 lgopts, &option_index)) != EOF) {
783
784                 switch (opt) {
785                 /* portmask */
786                 case 'p':
787                         enabled_port_mask = parse_portmask(optarg);
788                         if (enabled_port_mask == 0) {
789                                 printf("invalid portmask\n");
790                                 print_usage(prgname);
791                                 return -1;
792                         }
793                         break;
794
795                 /* long options */
796                 case 0:
797                         if (!strcmp(lgopts[option_index].name, "config")) {
798                                 ret = parse_config(optarg);
799                                 if (ret) {
800                                         printf("invalid config\n");
801                                         print_usage(prgname);
802                                         return -1;
803                                 }
804                         }
805
806                         if (!strcmp(lgopts[option_index].name, "no-numa")) {
807                                 printf("numa is disabled \n");
808                                 numa_on = 0;
809                         }
810                         break;
811
812                 default:
813                         print_usage(prgname);
814                         return -1;
815                 }
816         }
817
818         if (optind >= 0)
819                 argv[optind-1] = prgname;
820
821         ret = optind-1;
822         optind = 1; /* reset getopt lib */
823         return ret;
824 }
825
826 static void
827 print_ethaddr(const char *name, const struct ether_addr *eth_addr)
828 {
829         char buf[ETHER_ADDR_FMT_SIZE];
830         ether_format_addr(buf, ETHER_ADDR_FMT_SIZE, eth_addr);
831         printf("%s%s", name, buf);
832 }
833
834 #if (APP_LOOKUP_METHOD == APP_LOOKUP_EXACT_MATCH)
835 static void
836 setup_hash(int socketid)
837 {
838         unsigned i;
839         int ret;
840         char s[64];
841
842         /* create  hashes */
843         snprintf(s, sizeof(s), "l3fwd_hash_%d", socketid);
844         l3fwd_hash_params.name = s;
845         l3fwd_hash_params.socket_id = socketid;
846         l3fwd_lookup_struct[socketid] = rte_hash_create(&l3fwd_hash_params);
847         if (l3fwd_lookup_struct[socketid] == NULL)
848                 rte_exit(EXIT_FAILURE, "Unable to create the l3fwd hash on "
849                                 "socket %d\n", socketid);
850
851         /* populate the hash */
852         for (i = 0; i < L3FWD_NUM_ROUTES; i++) {
853                 ret = rte_hash_add_key (l3fwd_lookup_struct[socketid],
854                                 (void *) &l3fwd_route_array[i].key);
855                 if (ret < 0) {
856                         rte_exit(EXIT_FAILURE, "Unable to add entry %u to the"
857                                 "l3fwd hash on socket %d\n", i, socketid);
858                 }
859                 l3fwd_out_if[ret] = l3fwd_route_array[i].if_out;
860                 printf("Hash: Adding key\n");
861                 print_key(l3fwd_route_array[i].key);
862         }
863 }
864 #endif
865
866 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
867 static void
868 setup_lpm(int socketid)
869 {
870         unsigned i;
871         int ret;
872         char s[64];
873
874         struct rte_lpm_config lpm_ipv4_config;
875
876         lpm_ipv4_config.max_rules = L3FWD_LPM_MAX_RULES;
877         lpm_ipv4_config.number_tbl8s = 256;
878         lpm_ipv4_config.flags = 0;
879
880         /* create the LPM table */
881         snprintf(s, sizeof(s), "L3FWD_LPM_%d", socketid);
882         l3fwd_lookup_struct[socketid] =
883                         rte_lpm_create(s, socketid, &lpm_ipv4_config);
884         if (l3fwd_lookup_struct[socketid] == NULL)
885                 rte_exit(EXIT_FAILURE, "Unable to create the l3fwd LPM table"
886                                 " on socket %d\n", socketid);
887
888         /* populate the LPM table */
889         for (i = 0; i < L3FWD_NUM_ROUTES; i++) {
890                 ret = rte_lpm_add(l3fwd_lookup_struct[socketid],
891                         l3fwd_route_array[i].ip,
892                         l3fwd_route_array[i].depth,
893                         l3fwd_route_array[i].if_out);
894
895                 if (ret < 0) {
896                         rte_exit(EXIT_FAILURE, "Unable to add entry %u to the "
897                                 "l3fwd LPM table on socket %d\n",
898                                 i, socketid);
899                 }
900
901                 printf("LPM: Adding route 0x%08x / %d (%d)\n",
902                         (unsigned)l3fwd_route_array[i].ip,
903                         l3fwd_route_array[i].depth,
904                         l3fwd_route_array[i].if_out);
905         }
906 }
907 #endif
908
909 static int
910 init_mem(unsigned nb_mbuf)
911 {
912         struct lcore_conf *qconf;
913         int socketid;
914         unsigned lcore_id;
915         char s[64];
916
917         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
918                 if (rte_lcore_is_enabled(lcore_id) == 0)
919                         continue;
920
921                 if (numa_on)
922                         socketid = rte_lcore_to_socket_id(lcore_id);
923                 else
924                         socketid = 0;
925
926                 if (socketid >= NB_SOCKETS) {
927                         rte_exit(EXIT_FAILURE, "Socket %d of lcore %u is out of range %d\n",
928                                 socketid, lcore_id, NB_SOCKETS);
929                 }
930                 if (pktmbuf_pool[socketid] == NULL) {
931                         snprintf(s, sizeof(s), "mbuf_pool_%d", socketid);
932                         pktmbuf_pool[socketid] = rte_pktmbuf_pool_create(s,
933                                 nb_mbuf, MEMPOOL_CACHE_SIZE, 0,
934                                 RTE_MBUF_DEFAULT_BUF_SIZE, socketid);
935                         if (pktmbuf_pool[socketid] == NULL)
936                                 rte_exit(EXIT_FAILURE, "Cannot init mbuf pool on socket %d\n", socketid);
937                         else
938                                 printf("Allocated mbuf pool on socket %d\n", socketid);
939
940 #if (APP_LOOKUP_METHOD == APP_LOOKUP_LPM)
941                         setup_lpm(socketid);
942 #else
943                         setup_hash(socketid);
944 #endif
945                 }
946                 qconf = &lcore_conf[lcore_id];
947                 qconf->lookup_struct = l3fwd_lookup_struct[socketid];
948         }
949         return 0;
950 }
951
952 int
953 main(int argc, char **argv)
954 {
955         struct lcore_conf *qconf;
956         struct rte_eth_dev_info dev_info;
957         struct rte_eth_txconf *txconf;
958         int ret;
959         unsigned nb_ports;
960         uint16_t queueid, portid;
961         unsigned lcore_id;
962         uint32_t nb_lcores;
963         uint16_t n_tx_queue;
964         uint8_t nb_rx_queue, queue, socketid;
965
966         signal(SIGINT, signal_handler);
967         /* init EAL */
968         ret = rte_eal_init(argc, argv);
969         if (ret < 0)
970                 rte_exit(EXIT_FAILURE, "Invalid EAL parameters\n");
971         argc -= ret;
972         argv += ret;
973
974         /* parse application arguments (after the EAL ones) */
975         ret = parse_args(argc, argv);
976         if (ret < 0)
977                 rte_exit(EXIT_FAILURE, "Invalid L3FWD-VF parameters\n");
978
979         if (check_lcore_params() < 0)
980                 rte_exit(EXIT_FAILURE, "check_lcore_params failed\n");
981
982         ret = init_lcore_rx_queues();
983         if (ret < 0)
984                 rte_exit(EXIT_FAILURE, "init_lcore_rx_queues failed\n");
985
986         nb_ports = rte_eth_dev_count();
987
988         if (check_port_config(nb_ports) < 0)
989                 rte_exit(EXIT_FAILURE, "check_port_config failed\n");
990
991         nb_lcores = rte_lcore_count();
992
993         /* initialize all ports */
994         for (portid = 0; portid < nb_ports; portid++) {
995                 /* skip ports that are not enabled */
996                 if ((enabled_port_mask & (1 << portid)) == 0) {
997                         printf("\nSkipping disabled port %d\n", portid);
998                         continue;
999                 }
1000
1001                 /* init port */
1002                 printf("Initializing port %d ... ", portid );
1003                 fflush(stdout);
1004
1005                 /* must always equal(=1) */
1006                 nb_rx_queue = get_port_n_rx_queues(portid);
1007                 n_tx_queue = MAX_TX_QUEUE_PER_PORT;
1008
1009                 printf("Creating queues: nb_rxq=%d nb_txq=%u... ",
1010                         nb_rx_queue, (unsigned)1 );
1011                 ret = rte_eth_dev_configure(portid, nb_rx_queue, n_tx_queue, &port_conf);
1012                 if (ret < 0)
1013                         rte_exit(EXIT_FAILURE, "Cannot configure device: err=%d, port=%d\n",
1014                                 ret, portid);
1015
1016                 ret = rte_eth_dev_adjust_nb_rx_tx_desc(portid, &nb_rxd,
1017                                                        &nb_txd);
1018                 if (ret < 0)
1019                         rte_exit(EXIT_FAILURE,
1020                                  "Cannot adjust number of descriptors: err=%d, port=%d\n",
1021                                  ret, portid);
1022
1023                 rte_eth_macaddr_get(portid, &ports_eth_addr[portid]);
1024                 print_ethaddr(" Address:", &ports_eth_addr[portid]);
1025                 printf(", ");
1026
1027                 ret = init_mem(NB_MBUF);
1028                 if (ret < 0)
1029                         rte_exit(EXIT_FAILURE, "init_mem failed\n");
1030
1031                 /* init one TX queue */
1032                 socketid = (uint8_t)rte_lcore_to_socket_id(rte_get_master_lcore());
1033
1034                 printf("txq=%d,%d,%d ", portid, 0, socketid);
1035                 fflush(stdout);
1036
1037                 rte_eth_dev_info_get(portid, &dev_info);
1038                 txconf = &dev_info.default_txconf;
1039                 if (port_conf.rxmode.jumbo_frame)
1040                         txconf->txq_flags = 0;
1041                 ret = rte_eth_tx_queue_setup(portid, 0, nb_txd,
1042                                                  socketid, txconf);
1043                 if (ret < 0)
1044                         rte_exit(EXIT_FAILURE, "rte_eth_tx_queue_setup: err=%d, "
1045                                 "port=%d\n", ret, portid);
1046
1047                 printf("\n");
1048         }
1049
1050         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1051                 if (rte_lcore_is_enabled(lcore_id) == 0)
1052                         continue;
1053                 qconf = &lcore_conf[lcore_id];
1054                 qconf->tx_queue_id = 0;
1055
1056                 printf("\nInitializing rx queues on lcore %u ... ", lcore_id );
1057                 fflush(stdout);
1058                 /* init RX queues */
1059                 for(queue = 0; queue < qconf->n_rx_queue; ++queue) {
1060                         portid = qconf->rx_queue_list[queue].port_id;
1061                         queueid = qconf->rx_queue_list[queue].queue_id;
1062
1063                         if (numa_on)
1064                                 socketid = (uint8_t)rte_lcore_to_socket_id(lcore_id);
1065                         else
1066                                 socketid = 0;
1067
1068                         printf("rxq=%d,%d,%d ", portid, queueid, socketid);
1069                         fflush(stdout);
1070
1071                         ret = rte_eth_rx_queue_setup(portid, queueid, nb_rxd,
1072                                                 socketid, NULL,
1073                                                 pktmbuf_pool[socketid]);
1074                         if (ret < 0)
1075                                 rte_exit(EXIT_FAILURE, "rte_eth_rx_queue_setup: err=%d,"
1076                                                 "port=%d\n", ret, portid);
1077                 }
1078         }
1079         printf("\n");
1080
1081         /* start ports */
1082         for (portid = 0; portid < nb_ports; portid++) {
1083                 if ((enabled_port_mask & (1 << portid)) == 0) {
1084                         continue;
1085                 }
1086                 /* Start device */
1087                 ret = rte_eth_dev_start(portid);
1088                 if (ret < 0)
1089                         rte_exit(EXIT_FAILURE, "rte_eth_dev_start: err=%d, port=%d\n",
1090                                 ret, portid);
1091
1092                 printf("done: Port %d\n", portid);
1093
1094         }
1095
1096         /* launch per-lcore init on every lcore */
1097         rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
1098         RTE_LCORE_FOREACH_SLAVE(lcore_id) {
1099                 if (rte_eal_wait_lcore(lcore_id) < 0)
1100                         return -1;
1101         }
1102
1103         return 0;
1104 }