19d25d48ac7c6a49d4baa0be9e8577a5e6b048ac
[dpdk.git] / examples / kni / 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 <string.h>
39 #include <sys/queue.h>
40 #include <stdarg.h>
41 #include <errno.h>
42 #include <getopt.h>
43
44 #include <netinet/in.h>
45 #include <linux/if.h>
46 #include <linux/if_tun.h>
47 #include <fcntl.h>
48 #include <sys/ioctl.h>
49 #include <unistd.h>
50 #include <signal.h>
51
52 #include <rte_common.h>
53 #include <rte_log.h>
54 #include <rte_memory.h>
55 #include <rte_memcpy.h>
56 #include <rte_memzone.h>
57 #include <rte_eal.h>
58 #include <rte_per_lcore.h>
59 #include <rte_launch.h>
60 #include <rte_atomic.h>
61 #include <rte_lcore.h>
62 #include <rte_branch_prediction.h>
63 #include <rte_interrupts.h>
64 #include <rte_pci.h>
65 #include <rte_debug.h>
66 #include <rte_ether.h>
67 #include <rte_ethdev.h>
68 #include <rte_ring.h>
69 #include <rte_log.h>
70 #include <rte_mempool.h>
71 #include <rte_mbuf.h>
72 #include <rte_string_fns.h>
73 #include <rte_cycles.h>
74 #include <rte_malloc.h>
75 #include <rte_kni.h>
76
77 /* Macros for printing using RTE_LOG */
78 #define RTE_LOGTYPE_APP RTE_LOGTYPE_USER1
79
80 /* Max size of a single packet */
81 #define MAX_PACKET_SZ           2048
82
83 /* Number of bytes needed for each mbuf */
84 #define MBUF_SZ \
85         (MAX_PACKET_SZ + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
86
87 /* Number of mbufs in mempool that is created */
88 #define NB_MBUF                 (8192 * 16)
89
90 /* How many packets to attempt to read from NIC in one go */
91 #define PKT_BURST_SZ            32
92
93 /* How many objects (mbufs) to keep in per-lcore mempool cache */
94 #define MEMPOOL_CACHE_SZ        PKT_BURST_SZ
95
96 /* Number of RX ring descriptors */
97 #define NB_RXD                  128
98
99 /* Number of TX ring descriptors */
100 #define NB_TXD                  512
101
102 /* Total octets in ethernet header */
103 #define KNI_ENET_HEADER_SIZE    14
104
105 /* Total octets in the FCS */
106 #define KNI_ENET_FCS_SIZE       4
107
108 #define KNI_US_PER_SECOND       1000000
109 #define KNI_SECOND_PER_DAY      86400
110
111 #define KNI_MAX_KTHREAD 32
112 /*
113  * Structure of port parameters
114  */
115 struct kni_port_params {
116         uint8_t port_id;/* Port ID */
117         unsigned lcore_rx; /* lcore ID for RX */
118         unsigned lcore_tx; /* lcore ID for TX */
119         uint32_t nb_lcore_k; /* Number of lcores for KNI multi kernel threads */
120         uint32_t nb_kni; /* Number of KNI devices to be created */
121         unsigned lcore_k[KNI_MAX_KTHREAD]; /* lcore ID list for kthreads */
122         struct rte_kni *kni[KNI_MAX_KTHREAD]; /* KNI context pointers */
123 } __rte_cache_aligned;
124
125 static struct kni_port_params *kni_port_params_array[RTE_MAX_ETHPORTS];
126
127
128 /* Options for configuring ethernet port */
129 static struct rte_eth_conf port_conf = {
130         .rxmode = {
131                 .header_split = 0,      /* Header Split disabled */
132                 .hw_ip_checksum = 0,    /* IP checksum offload disabled */
133                 .hw_vlan_filter = 0,    /* VLAN filtering disabled */
134                 .jumbo_frame = 0,       /* Jumbo Frame Support disabled */
135                 .hw_strip_crc = 0,      /* CRC stripped by hardware */
136         },
137         .txmode = {
138                 .mq_mode = ETH_MQ_TX_NONE,
139         },
140 };
141
142 /* Mempool for mbufs */
143 static struct rte_mempool * pktmbuf_pool = NULL;
144
145 /* Mask of enabled ports */
146 static uint32_t ports_mask = 0;
147 /* Ports set in promiscuous mode off by default. */
148 static int promiscuous_on = 0;
149
150 /* Structure type for recording kni interface specific stats */
151 struct kni_interface_stats {
152         /* number of pkts received from NIC, and sent to KNI */
153         uint64_t rx_packets;
154
155         /* number of pkts received from NIC, but failed to send to KNI */
156         uint64_t rx_dropped;
157
158         /* number of pkts received from KNI, and sent to NIC */
159         uint64_t tx_packets;
160
161         /* number of pkts received from KNI, but failed to send to NIC */
162         uint64_t tx_dropped;
163 };
164
165 /* kni device statistics array */
166 static struct kni_interface_stats kni_stats[RTE_MAX_ETHPORTS];
167
168 static int kni_change_mtu(uint8_t port_id, unsigned new_mtu);
169 static int kni_config_network_interface(uint8_t port_id, uint8_t if_up);
170
171 static rte_atomic32_t kni_stop = RTE_ATOMIC32_INIT(0);
172
173 /* Print out statistics on packets handled */
174 static void
175 print_stats(void)
176 {
177         uint8_t i;
178
179         printf("\n**KNI example application statistics**\n"
180                "======  ==============  ============  ============  ============  ============\n"
181                " Port    Lcore(RX/TX)    rx_packets    rx_dropped    tx_packets    tx_dropped\n"
182                "------  --------------  ------------  ------------  ------------  ------------\n");
183         for (i = 0; i < RTE_MAX_ETHPORTS; i++) {
184                 if (!kni_port_params_array[i])
185                         continue;
186
187                 printf("%7d %10u/%2u %13"PRIu64" %13"PRIu64" %13"PRIu64" "
188                                                         "%13"PRIu64"\n", i,
189                                         kni_port_params_array[i]->lcore_rx,
190                                         kni_port_params_array[i]->lcore_tx,
191                                                 kni_stats[i].rx_packets,
192                                                 kni_stats[i].rx_dropped,
193                                                 kni_stats[i].tx_packets,
194                                                 kni_stats[i].tx_dropped);
195         }
196         printf("======  ==============  ============  ============  ============  ============\n");
197 }
198
199 /* Custom handling of signals to handle stats and kni processing */
200 static void
201 signal_handler(int signum)
202 {
203         /* When we receive a USR1 signal, print stats */
204         if (signum == SIGUSR1) {
205                 print_stats();
206         }
207
208         /* When we receive a USR2 signal, reset stats */
209         if (signum == SIGUSR2) {
210                 memset(&kni_stats, 0, sizeof(kni_stats));
211                 printf("\n**Statistics have been reset**\n");
212                 return;
213         }
214
215         /* When we receive a RTMIN or SIGINT signal, stop kni processing */
216         if (signum == SIGRTMIN || signum == SIGINT){
217                 printf("SIGRTMIN is received, and the KNI processing is "
218                                                         "going to stop\n");
219                 rte_atomic32_inc(&kni_stop);
220                 return;
221         }
222 }
223
224 static void
225 kni_burst_free_mbufs(struct rte_mbuf **pkts, unsigned num)
226 {
227         unsigned i;
228
229         if (pkts == NULL)
230                 return;
231
232         for (i = 0; i < num; i++) {
233                 rte_pktmbuf_free(pkts[i]);
234                 pkts[i] = NULL;
235         }
236 }
237
238 /**
239  * Interface to burst rx and enqueue mbufs into rx_q
240  */
241 static void
242 kni_ingress(struct kni_port_params *p)
243 {
244         uint8_t i, port_id;
245         unsigned nb_rx, num;
246         uint32_t nb_kni;
247         struct rte_mbuf *pkts_burst[PKT_BURST_SZ];
248
249         if (p == NULL)
250                 return;
251
252         nb_kni = p->nb_kni;
253         port_id = p->port_id;
254         for (i = 0; i < nb_kni; i++) {
255                 /* Burst rx from eth */
256                 nb_rx = rte_eth_rx_burst(port_id, 0, pkts_burst, PKT_BURST_SZ);
257                 if (unlikely(nb_rx > PKT_BURST_SZ)) {
258                         RTE_LOG(ERR, APP, "Error receiving from eth\n");
259                         return;
260                 }
261                 /* Burst tx to kni */
262                 num = rte_kni_tx_burst(p->kni[i], pkts_burst, nb_rx);
263                 kni_stats[port_id].rx_packets += num;
264
265                 rte_kni_handle_request(p->kni[i]);
266                 if (unlikely(num < nb_rx)) {
267                         /* Free mbufs not tx to kni interface */
268                         kni_burst_free_mbufs(&pkts_burst[num], nb_rx - num);
269                         kni_stats[port_id].rx_dropped += nb_rx - num;
270                 }
271         }
272 }
273
274 /**
275  * Interface to dequeue mbufs from tx_q and burst tx
276  */
277 static void
278 kni_egress(struct kni_port_params *p)
279 {
280         uint8_t i, port_id;
281         unsigned nb_tx, num;
282         uint32_t nb_kni;
283         struct rte_mbuf *pkts_burst[PKT_BURST_SZ];
284
285         if (p == NULL)
286                 return;
287
288         nb_kni = p->nb_kni;
289         port_id = p->port_id;
290         for (i = 0; i < nb_kni; i++) {
291                 /* Burst rx from kni */
292                 num = rte_kni_rx_burst(p->kni[i], pkts_burst, PKT_BURST_SZ);
293                 if (unlikely(num > PKT_BURST_SZ)) {
294                         RTE_LOG(ERR, APP, "Error receiving from KNI\n");
295                         return;
296                 }
297                 /* Burst tx to eth */
298                 nb_tx = rte_eth_tx_burst(port_id, 0, pkts_burst, (uint16_t)num);
299                 kni_stats[port_id].tx_packets += nb_tx;
300                 if (unlikely(nb_tx < num)) {
301                         /* Free mbufs not tx to NIC */
302                         kni_burst_free_mbufs(&pkts_burst[nb_tx], num - nb_tx);
303                         kni_stats[port_id].tx_dropped += num - nb_tx;
304                 }
305         }
306 }
307
308 static int
309 main_loop(__rte_unused void *arg)
310 {
311         uint8_t i, nb_ports = rte_eth_dev_count();
312         int32_t f_stop;
313         const unsigned lcore_id = rte_lcore_id();
314         enum lcore_rxtx {
315                 LCORE_NONE,
316                 LCORE_RX,
317                 LCORE_TX,
318                 LCORE_MAX
319         };
320         enum lcore_rxtx flag = LCORE_NONE;
321
322         nb_ports = (uint8_t)(nb_ports < RTE_MAX_ETHPORTS ?
323                                 nb_ports : RTE_MAX_ETHPORTS);
324         for (i = 0; i < nb_ports; i++) {
325                 if (!kni_port_params_array[i])
326                         continue;
327                 if (kni_port_params_array[i]->lcore_rx == (uint8_t)lcore_id) {
328                         flag = LCORE_RX;
329                         break;
330                 } else if (kni_port_params_array[i]->lcore_tx ==
331                                                 (uint8_t)lcore_id) {
332                         flag = LCORE_TX;
333                         break;
334                 }
335         }
336
337         if (flag == LCORE_RX) {
338                 RTE_LOG(INFO, APP, "Lcore %u is reading from port %d\n",
339                                         kni_port_params_array[i]->lcore_rx,
340                                         kni_port_params_array[i]->port_id);
341                 while (1) {
342                         f_stop = rte_atomic32_read(&kni_stop);
343                         if (f_stop)
344                                 break;
345                         kni_ingress(kni_port_params_array[i]);
346                 }
347         } else if (flag == LCORE_TX) {
348                 RTE_LOG(INFO, APP, "Lcore %u is writing to port %d\n",
349                                         kni_port_params_array[i]->lcore_tx,
350                                         kni_port_params_array[i]->port_id);
351                 while (1) {
352                         f_stop = rte_atomic32_read(&kni_stop);
353                         if (f_stop)
354                                 break;
355                         kni_egress(kni_port_params_array[i]);
356                 }
357         } else
358                 RTE_LOG(INFO, APP, "Lcore %u has nothing to do\n", lcore_id);
359
360         return 0;
361 }
362
363 /* Display usage instructions */
364 static void
365 print_usage(const char *prgname)
366 {
367         RTE_LOG(INFO, APP, "\nUsage: %s [EAL options] -- -p PORTMASK -P "
368                    "[--config (port,lcore_rx,lcore_tx,lcore_kthread...)"
369                    "[,(port,lcore_rx,lcore_tx,lcore_kthread...)]]\n"
370                    "    -p PORTMASK: hex bitmask of ports to use\n"
371                    "    -P : enable promiscuous mode\n"
372                    "    --config (port,lcore_rx,lcore_tx,lcore_kthread...): "
373                    "port and lcore configurations\n",
374                    prgname);
375 }
376
377 /* Convert string to unsigned number. 0 is returned if error occurs */
378 static uint32_t
379 parse_unsigned(const char *portmask)
380 {
381         char *end = NULL;
382         unsigned long num;
383
384         num = strtoul(portmask, &end, 16);
385         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
386                 return 0;
387
388         return (uint32_t)num;
389 }
390
391 static void
392 print_config(void)
393 {
394         uint32_t i, j;
395         struct kni_port_params **p = kni_port_params_array;
396
397         for (i = 0; i < RTE_MAX_ETHPORTS; i++) {
398                 if (!p[i])
399                         continue;
400                 RTE_LOG(DEBUG, APP, "Port ID: %d\n", p[i]->port_id);
401                 RTE_LOG(DEBUG, APP, "Rx lcore ID: %u, Tx lcore ID: %u\n",
402                                         p[i]->lcore_rx, p[i]->lcore_tx);
403                 for (j = 0; j < p[i]->nb_lcore_k; j++)
404                         RTE_LOG(DEBUG, APP, "Kernel thread lcore ID: %u\n",
405                                                         p[i]->lcore_k[j]);
406         }
407 }
408
409 static int
410 parse_config(const char *arg)
411 {
412         const char *p, *p0 = arg;
413         char s[256], *end;
414         unsigned size;
415         enum fieldnames {
416                 FLD_PORT = 0,
417                 FLD_LCORE_RX,
418                 FLD_LCORE_TX,
419                 _NUM_FLD = KNI_MAX_KTHREAD + 3,
420         };
421         int i, j, nb_token;
422         char *str_fld[_NUM_FLD];
423         unsigned long int_fld[_NUM_FLD];
424         uint8_t port_id, nb_kni_port_params = 0;
425
426         memset(&kni_port_params_array, 0, sizeof(kni_port_params_array));
427         while (((p = strchr(p0, '(')) != NULL) &&
428                 nb_kni_port_params < RTE_MAX_ETHPORTS) {
429                 p++;
430                 if ((p0 = strchr(p, ')')) == NULL)
431                         goto fail;
432                 size = p0 - p;
433                 if (size >= sizeof(s)) {
434                         printf("Invalid config parameters\n");
435                         goto fail;
436                 }
437                 snprintf(s, sizeof(s), "%.*s", size, p);
438                 nb_token = rte_strsplit(s, sizeof(s), str_fld, _NUM_FLD, ',');
439                 if (nb_token <= FLD_LCORE_TX) {
440                         printf("Invalid config parameters\n");
441                         goto fail;
442                 }
443                 for (i = 0; i < nb_token; i++) {
444                         errno = 0;
445                         int_fld[i] = strtoul(str_fld[i], &end, 0);
446                         if (errno != 0 || end == str_fld[i]) {
447                                 printf("Invalid config parameters\n");
448                                 goto fail;
449                         }
450                 }
451
452                 i = 0;
453                 port_id = (uint8_t)int_fld[i++];
454                 if (port_id >= RTE_MAX_ETHPORTS) {
455                         printf("Port ID %d could not exceed the maximum %d\n",
456                                                 port_id, RTE_MAX_ETHPORTS);
457                         goto fail;
458                 }
459                 if (kni_port_params_array[port_id]) {
460                         printf("Port %d has been configured\n", port_id);
461                         goto fail;
462                 }
463                 kni_port_params_array[port_id] =
464                         rte_zmalloc("KNI_port_params",
465                                     sizeof(struct kni_port_params), RTE_CACHE_LINE_SIZE);
466                 kni_port_params_array[port_id]->port_id = port_id;
467                 kni_port_params_array[port_id]->lcore_rx =
468                                         (uint8_t)int_fld[i++];
469                 kni_port_params_array[port_id]->lcore_tx =
470                                         (uint8_t)int_fld[i++];
471                 if (kni_port_params_array[port_id]->lcore_rx >= RTE_MAX_LCORE ||
472                 kni_port_params_array[port_id]->lcore_tx >= RTE_MAX_LCORE) {
473                         printf("lcore_rx %u or lcore_tx %u ID could not "
474                                                 "exceed the maximum %u\n",
475                                 kni_port_params_array[port_id]->lcore_rx,
476                                 kni_port_params_array[port_id]->lcore_tx,
477                                                 (unsigned)RTE_MAX_LCORE);
478                         goto fail;
479                 }
480                 for (j = 0; i < nb_token && j < KNI_MAX_KTHREAD; i++, j++)
481                         kni_port_params_array[port_id]->lcore_k[j] =
482                                                 (uint8_t)int_fld[i];
483                 kni_port_params_array[port_id]->nb_lcore_k = j;
484         }
485         print_config();
486
487         return 0;
488
489 fail:
490         for (i = 0; i < RTE_MAX_ETHPORTS; i++) {
491                 if (kni_port_params_array[i]) {
492                         rte_free(kni_port_params_array[i]);
493                         kni_port_params_array[i] = NULL;
494                 }
495         }
496
497         return -1;
498 }
499
500 static int
501 validate_parameters(uint32_t portmask)
502 {
503         uint32_t i;
504
505         if (!portmask) {
506                 printf("No port configured in port mask\n");
507                 return -1;
508         }
509
510         for (i = 0; i < RTE_MAX_ETHPORTS; i++) {
511                 if (((portmask & (1 << i)) && !kni_port_params_array[i]) ||
512                         (!(portmask & (1 << i)) && kni_port_params_array[i]))
513                         rte_exit(EXIT_FAILURE, "portmask is not consistent "
514                                 "to port ids specified in --config\n");
515
516                 if (kni_port_params_array[i] && !rte_lcore_is_enabled(\
517                         (unsigned)(kni_port_params_array[i]->lcore_rx)))
518                         rte_exit(EXIT_FAILURE, "lcore id %u for "
519                                         "port %d receiving not enabled\n",
520                                         kni_port_params_array[i]->lcore_rx,
521                                         kni_port_params_array[i]->port_id);
522
523                 if (kni_port_params_array[i] && !rte_lcore_is_enabled(\
524                         (unsigned)(kni_port_params_array[i]->lcore_tx)))
525                         rte_exit(EXIT_FAILURE, "lcore id %u for "
526                                         "port %d transmitting not enabled\n",
527                                         kni_port_params_array[i]->lcore_tx,
528                                         kni_port_params_array[i]->port_id);
529
530         }
531
532         return 0;
533 }
534
535 #define CMDLINE_OPT_CONFIG  "config"
536
537 /* Parse the arguments given in the command line of the application */
538 static int
539 parse_args(int argc, char **argv)
540 {
541         int opt, longindex, ret = 0;
542         const char *prgname = argv[0];
543         static struct option longopts[] = {
544                 {CMDLINE_OPT_CONFIG, required_argument, NULL, 0},
545                 {NULL, 0, NULL, 0}
546         };
547
548         /* Disable printing messages within getopt() */
549         opterr = 0;
550
551         /* Parse command line */
552         while ((opt = getopt_long(argc, argv, "p:P", longopts,
553                                                 &longindex)) != EOF) {
554                 switch (opt) {
555                 case 'p':
556                         ports_mask = parse_unsigned(optarg);
557                         break;
558                 case 'P':
559                         promiscuous_on = 1;
560                         break;
561                 case 0:
562                         if (!strncmp(longopts[longindex].name,
563                                      CMDLINE_OPT_CONFIG,
564                                      sizeof(CMDLINE_OPT_CONFIG))) {
565                                 ret = parse_config(optarg);
566                                 if (ret) {
567                                         printf("Invalid config\n");
568                                         print_usage(prgname);
569                                         return -1;
570                                 }
571                         }
572                         break;
573                 default:
574                         print_usage(prgname);
575                         rte_exit(EXIT_FAILURE, "Invalid option specified\n");
576                 }
577         }
578
579         /* Check that options were parsed ok */
580         if (validate_parameters(ports_mask) < 0) {
581                 print_usage(prgname);
582                 rte_exit(EXIT_FAILURE, "Invalid parameters\n");
583         }
584
585         return ret;
586 }
587
588 /* Initialize KNI subsystem */
589 static void
590 init_kni(void)
591 {
592         unsigned int num_of_kni_ports = 0, i;
593         struct kni_port_params **params = kni_port_params_array;
594
595         /* Calculate the maximum number of KNI interfaces that will be used */
596         for (i = 0; i < RTE_MAX_ETHPORTS; i++) {
597                 if (kni_port_params_array[i]) {
598                         num_of_kni_ports += (params[i]->nb_lcore_k ?
599                                 params[i]->nb_lcore_k : 1);
600                 }
601         }
602
603         /* Invoke rte KNI init to preallocate the ports */
604         rte_kni_init(num_of_kni_ports);
605 }
606
607 /* Initialise a single port on an Ethernet device */
608 static void
609 init_port(uint8_t port)
610 {
611         int ret;
612
613         /* Initialise device and RX/TX queues */
614         RTE_LOG(INFO, APP, "Initialising port %u ...\n", (unsigned)port);
615         fflush(stdout);
616         ret = rte_eth_dev_configure(port, 1, 1, &port_conf);
617         if (ret < 0)
618                 rte_exit(EXIT_FAILURE, "Could not configure port%u (%d)\n",
619                             (unsigned)port, ret);
620
621         ret = rte_eth_rx_queue_setup(port, 0, NB_RXD,
622                 rte_eth_dev_socket_id(port), NULL, pktmbuf_pool);
623         if (ret < 0)
624                 rte_exit(EXIT_FAILURE, "Could not setup up RX queue for "
625                                 "port%u (%d)\n", (unsigned)port, ret);
626
627         ret = rte_eth_tx_queue_setup(port, 0, NB_TXD,
628                 rte_eth_dev_socket_id(port), NULL);
629         if (ret < 0)
630                 rte_exit(EXIT_FAILURE, "Could not setup up TX queue for "
631                                 "port%u (%d)\n", (unsigned)port, ret);
632
633         ret = rte_eth_dev_start(port);
634         if (ret < 0)
635                 rte_exit(EXIT_FAILURE, "Could not start port%u (%d)\n",
636                                                 (unsigned)port, ret);
637
638         if (promiscuous_on)
639                 rte_eth_promiscuous_enable(port);
640 }
641
642 /* Check the link status of all ports in up to 9s, and print them finally */
643 static void
644 check_all_ports_link_status(uint8_t port_num, uint32_t port_mask)
645 {
646 #define CHECK_INTERVAL 100 /* 100ms */
647 #define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
648         uint8_t portid, count, all_ports_up, print_flag = 0;
649         struct rte_eth_link link;
650
651         printf("\nChecking link status\n");
652         fflush(stdout);
653         for (count = 0; count <= MAX_CHECK_TIME; count++) {
654                 all_ports_up = 1;
655                 for (portid = 0; portid < port_num; portid++) {
656                         if ((port_mask & (1 << portid)) == 0)
657                                 continue;
658                         memset(&link, 0, sizeof(link));
659                         rte_eth_link_get_nowait(portid, &link);
660                         /* print link status if flag set */
661                         if (print_flag == 1) {
662                                 if (link.link_status)
663                                         printf("Port %d Link Up - speed %u "
664                                                 "Mbps - %s\n", (uint8_t)portid,
665                                                 (unsigned)link.link_speed,
666                                 (link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
667                                         ("full-duplex") : ("half-duplex\n"));
668                                 else
669                                         printf("Port %d Link Down\n",
670                                                 (uint8_t)portid);
671                                 continue;
672                         }
673                         /* clear all_ports_up flag if any link down */
674                         if (link.link_status == 0) {
675                                 all_ports_up = 0;
676                                 break;
677                         }
678                 }
679                 /* after finally printing all link status, get out */
680                 if (print_flag == 1)
681                         break;
682
683                 if (all_ports_up == 0) {
684                         printf(".");
685                         fflush(stdout);
686                         rte_delay_ms(CHECK_INTERVAL);
687                 }
688
689                 /* set the print_flag if all ports up or timeout */
690                 if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
691                         print_flag = 1;
692                         printf("done\n");
693                 }
694         }
695 }
696
697 /* Callback for request of changing MTU */
698 static int
699 kni_change_mtu(uint8_t port_id, unsigned new_mtu)
700 {
701         int ret;
702         struct rte_eth_conf conf;
703
704         if (port_id >= rte_eth_dev_count()) {
705                 RTE_LOG(ERR, APP, "Invalid port id %d\n", port_id);
706                 return -EINVAL;
707         }
708
709         RTE_LOG(INFO, APP, "Change MTU of port %d to %u\n", port_id, new_mtu);
710
711         /* Stop specific port */
712         rte_eth_dev_stop(port_id);
713
714         memcpy(&conf, &port_conf, sizeof(conf));
715         /* Set new MTU */
716         if (new_mtu > ETHER_MAX_LEN)
717                 conf.rxmode.jumbo_frame = 1;
718         else
719                 conf.rxmode.jumbo_frame = 0;
720
721         /* mtu + length of header + length of FCS = max pkt length */
722         conf.rxmode.max_rx_pkt_len = new_mtu + KNI_ENET_HEADER_SIZE +
723                                                         KNI_ENET_FCS_SIZE;
724         ret = rte_eth_dev_configure(port_id, 1, 1, &conf);
725         if (ret < 0) {
726                 RTE_LOG(ERR, APP, "Fail to reconfigure port %d\n", port_id);
727                 return ret;
728         }
729
730         /* Restart specific port */
731         ret = rte_eth_dev_start(port_id);
732         if (ret < 0) {
733                 RTE_LOG(ERR, APP, "Fail to restart port %d\n", port_id);
734                 return ret;
735         }
736
737         return 0;
738 }
739
740 /* Callback for request of configuring network interface up/down */
741 static int
742 kni_config_network_interface(uint8_t port_id, uint8_t if_up)
743 {
744         int ret = 0;
745
746         if (port_id >= rte_eth_dev_count() || port_id >= RTE_MAX_ETHPORTS) {
747                 RTE_LOG(ERR, APP, "Invalid port id %d\n", port_id);
748                 return -EINVAL;
749         }
750
751         RTE_LOG(INFO, APP, "Configure network interface of %d %s\n",
752                                         port_id, if_up ? "up" : "down");
753
754         if (if_up != 0) { /* Configure network interface up */
755                 rte_eth_dev_stop(port_id);
756                 ret = rte_eth_dev_start(port_id);
757         } else /* Configure network interface down */
758                 rte_eth_dev_stop(port_id);
759
760         if (ret < 0)
761                 RTE_LOG(ERR, APP, "Failed to start port %d\n", port_id);
762
763         return ret;
764 }
765
766 static int
767 kni_alloc(uint8_t port_id)
768 {
769         uint8_t i;
770         struct rte_kni *kni;
771         struct rte_kni_conf conf;
772         struct kni_port_params **params = kni_port_params_array;
773
774         if (port_id >= RTE_MAX_ETHPORTS || !params[port_id])
775                 return -1;
776
777         params[port_id]->nb_kni = params[port_id]->nb_lcore_k ?
778                                 params[port_id]->nb_lcore_k : 1;
779
780         for (i = 0; i < params[port_id]->nb_kni; i++) {
781                 /* Clear conf at first */
782                 memset(&conf, 0, sizeof(conf));
783                 if (params[port_id]->nb_lcore_k) {
784                         snprintf(conf.name, RTE_KNI_NAMESIZE,
785                                         "vEth%u_%u", port_id, i);
786                         conf.core_id = params[port_id]->lcore_k[i];
787                         conf.force_bind = 1;
788                 } else
789                         snprintf(conf.name, RTE_KNI_NAMESIZE,
790                                                 "vEth%u", port_id);
791                 conf.group_id = (uint16_t)port_id;
792                 conf.mbuf_size = MAX_PACKET_SZ;
793                 /*
794                  * The first KNI device associated to a port
795                  * is the master, for multiple kernel thread
796                  * environment.
797                  */
798                 if (i == 0) {
799                         struct rte_kni_ops ops;
800                         struct rte_eth_dev_info dev_info;
801
802                         memset(&dev_info, 0, sizeof(dev_info));
803                         rte_eth_dev_info_get(port_id, &dev_info);
804                         conf.addr = dev_info.pci_dev->addr;
805                         conf.id = dev_info.pci_dev->id;
806
807                         memset(&ops, 0, sizeof(ops));
808                         ops.port_id = port_id;
809                         ops.change_mtu = kni_change_mtu;
810                         ops.config_network_if = kni_config_network_interface;
811
812                         kni = rte_kni_alloc(pktmbuf_pool, &conf, &ops);
813                 } else
814                         kni = rte_kni_alloc(pktmbuf_pool, &conf, NULL);
815
816                 if (!kni)
817                         rte_exit(EXIT_FAILURE, "Fail to create kni for "
818                                                 "port: %d\n", port_id);
819                 params[port_id]->kni[i] = kni;
820         }
821
822         return 0;
823 }
824
825 static int
826 kni_free_kni(uint8_t port_id)
827 {
828         uint8_t i;
829         struct kni_port_params **p = kni_port_params_array;
830
831         if (port_id >= RTE_MAX_ETHPORTS || !p[port_id])
832                 return -1;
833
834         for (i = 0; i < p[i]->nb_kni; i++) {
835                 rte_kni_release(p[i]->kni[i]);
836                 p[i]->kni[i] = NULL;
837         }
838         rte_eth_dev_stop(port_id);
839
840         return 0;
841 }
842
843 /* Initialise ports/queues etc. and start main loop on each core */
844 int
845 main(int argc, char** argv)
846 {
847         int ret;
848         uint8_t nb_sys_ports, port;
849         unsigned i;
850
851         /* Associate signal_hanlder function with USR signals */
852         signal(SIGUSR1, signal_handler);
853         signal(SIGUSR2, signal_handler);
854         signal(SIGRTMIN, signal_handler);
855         signal(SIGINT, signal_handler);
856
857         /* Initialise EAL */
858         ret = rte_eal_init(argc, argv);
859         if (ret < 0)
860                 rte_exit(EXIT_FAILURE, "Could not initialise EAL (%d)\n", ret);
861         argc -= ret;
862         argv += ret;
863
864         /* Parse application arguments (after the EAL ones) */
865         ret = parse_args(argc, argv);
866         if (ret < 0)
867                 rte_exit(EXIT_FAILURE, "Could not parse input parameters\n");
868
869         /* Create the mbuf pool */
870         pktmbuf_pool = rte_mempool_create("mbuf_pool", NB_MBUF, MBUF_SZ,
871                         MEMPOOL_CACHE_SZ,
872                         sizeof(struct rte_pktmbuf_pool_private),
873                         rte_pktmbuf_pool_init, NULL, rte_pktmbuf_init, NULL,
874                         rte_socket_id(), 0);
875         if (pktmbuf_pool == NULL) {
876                 rte_exit(EXIT_FAILURE, "Could not initialise mbuf pool\n");
877                 return -1;
878         }
879
880         /* Get number of ports found in scan */
881         nb_sys_ports = rte_eth_dev_count();
882         if (nb_sys_ports == 0)
883                 rte_exit(EXIT_FAILURE, "No supported Ethernet device found\n");
884
885         /* Check if the configured port ID is valid */
886         for (i = 0; i < RTE_MAX_ETHPORTS; i++)
887                 if (kni_port_params_array[i] && i >= nb_sys_ports)
888                         rte_exit(EXIT_FAILURE, "Configured invalid "
889                                                 "port ID %u\n", i);
890
891         /* Initialize KNI subsystem */
892         init_kni();
893
894         /* Initialise each port */
895         for (port = 0; port < nb_sys_ports; port++) {
896                 /* Skip ports that are not enabled */
897                 if (!(ports_mask & (1 << port)))
898                         continue;
899                 init_port(port);
900
901                 if (port >= RTE_MAX_ETHPORTS)
902                         rte_exit(EXIT_FAILURE, "Can not use more than "
903                                 "%d ports for kni\n", RTE_MAX_ETHPORTS);
904
905                 kni_alloc(port);
906         }
907         check_all_ports_link_status(nb_sys_ports, ports_mask);
908
909         /* Launch per-lcore function on every lcore */
910         rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
911         RTE_LCORE_FOREACH_SLAVE(i) {
912                 if (rte_eal_wait_lcore(i) < 0)
913                         return -1;
914         }
915
916         /* Release resources */
917         for (port = 0; port < nb_sys_ports; port++) {
918                 if (!(ports_mask & (1 << port)))
919                         continue;
920                 kni_free_kni(port);
921         }
922 #ifdef RTE_LIBRTE_XEN_DOM0
923         rte_kni_close();
924 #endif
925         for (i = 0; i < RTE_MAX_ETHPORTS; i++)
926                 if (kni_port_params_array[i]) {
927                         rte_free(kni_port_params_array[i]);
928                         kni_port_params_array[i] = NULL;
929                 }
930
931         return 0;
932 }
933