examples/tep_term: implement VXLAN processing
[dpdk.git] / examples / tep_termination / main.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2015 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 <arpa/inet.h>
35 #include <getopt.h>
36 #include <linux/if_ether.h>
37 #include <linux/if_vlan.h>
38 #include <linux/virtio_net.h>
39 #include <linux/virtio_ring.h>
40 #include <signal.h>
41 #include <stdint.h>
42 #include <sys/eventfd.h>
43 #include <sys/param.h>
44 #include <unistd.h>
45
46 #include <rte_atomic.h>
47 #include <rte_cycles.h>
48 #include <rte_ethdev.h>
49 #include <rte_log.h>
50 #include <rte_string_fns.h>
51 #include <rte_malloc.h>
52 #include <rte_virtio_net.h>
53
54 #include "main.h"
55 #include "vxlan.h"
56 #include "vxlan_setup.h"
57
58 /* the maximum number of external ports supported */
59 #define MAX_SUP_PORTS 1
60
61 /**
62  * Calculate the number of buffers needed per port
63  */
64 #define NUM_MBUFS_PER_PORT ((MAX_QUEUES * RTE_TEST_RX_DESC_DEFAULT) +\
65                                 (nb_switching_cores * MAX_PKT_BURST) +\
66                                 (nb_switching_cores * \
67                                 RTE_TEST_TX_DESC_DEFAULT) +\
68                                 (nb_switching_cores * MBUF_CACHE_SIZE))
69
70 #define MBUF_CACHE_SIZE 128
71 #define MBUF_SIZE (2048 + sizeof(struct rte_mbuf) + RTE_PKTMBUF_HEADROOM)
72
73 #define MAX_PKT_BURST 32        /* Max burst size for RX/TX */
74 #define BURST_TX_DRAIN_US 100   /* TX drain every ~100us */
75
76 /* Defines how long we wait between retries on RX */
77 #define BURST_RX_WAIT_US 15
78
79 #define BURST_RX_RETRIES 4      /* Number of retries on RX. */
80
81 #define JUMBO_FRAME_MAX_SIZE    0x2600
82
83 /* State of virtio device. */
84 #define DEVICE_MAC_LEARNING 0
85 #define DEVICE_RX           1
86 #define DEVICE_SAFE_REMOVE  2
87
88 /* Config_core_flag status definitions. */
89 #define REQUEST_DEV_REMOVAL 1
90 #define ACK_DEV_REMOVAL     0
91
92 /* Configurable number of RX/TX ring descriptors */
93 #define RTE_TEST_RX_DESC_DEFAULT 1024
94 #define RTE_TEST_TX_DESC_DEFAULT 512
95
96 /* Get first 4 bytes in mbuf headroom. */
97 #define MBUF_HEADROOM_UINT32(mbuf) (*(uint32_t *)((uint8_t *)(mbuf) \
98                 + sizeof(struct rte_mbuf)))
99
100 #define INVALID_PORT_ID 0xFF
101
102 /* Size of buffers used for snprintfs. */
103 #define MAX_PRINT_BUFF 6072
104
105 /* Maximum character device basename size. */
106 #define MAX_BASENAME_SZ 20
107
108 /* Maximum long option length for option parsing. */
109 #define MAX_LONG_OPT_SZ 64
110
111 /* Used to compare MAC addresses. */
112 #define MAC_ADDR_CMP 0xFFFFFFFFFFFFULL
113
114 #define CMD_LINE_OPT_NB_DEVICES "nb-devices"
115 #define CMD_LINE_OPT_RX_RETRY "rx-retry"
116 #define CMD_LINE_OPT_RX_RETRY_DELAY "rx-retry-delay"
117 #define CMD_LINE_OPT_RX_RETRY_NUM "rx-retry-num"
118 #define CMD_LINE_OPT_STATS "stats"
119 #define CMD_LINE_OPT_DEV_BASENAME "dev-basename"
120
121 /* mask of enabled ports */
122 static uint32_t enabled_port_mask;
123
124 /*Number of switching cores enabled*/
125 static uint32_t nb_switching_cores;
126
127 /* number of devices/queues to support*/
128 uint16_t nb_devices = 2;
129
130 /* max ring descriptor, ixgbe, i40e, e1000 all are 4096. */
131 #define MAX_RING_DESC 4096
132
133 struct vpool {
134         struct rte_mempool *pool;
135         struct rte_ring *ring;
136         uint32_t buf_size;
137 } vpool_array[MAX_QUEUES+MAX_QUEUES];
138
139 /* overlay packet operation */
140 struct ol_switch_ops overlay_options = {
141         .port_configure = vxlan_port_init,
142         .tunnel_setup = vxlan_link,
143         .tunnel_destroy = vxlan_unlink,
144         .tx_handle = vxlan_tx_pkts,
145         .rx_handle = vxlan_rx_pkts,
146         .param_handle = NULL,
147 };
148
149 /* Enable stats. */
150 uint32_t enable_stats = 0;
151 /* Enable retries on RX. */
152 static uint32_t enable_retry = 1;
153 /* Specify timeout (in useconds) between retries on RX. */
154 static uint32_t burst_rx_delay_time = BURST_RX_WAIT_US;
155 /* Specify the number of retries on RX. */
156 static uint32_t burst_rx_retry_num = BURST_RX_RETRIES;
157
158 /* Character device basename. Can be set by user. */
159 static char dev_basename[MAX_BASENAME_SZ] = "vhost-net";
160
161 static unsigned lcore_ids[RTE_MAX_LCORE];
162 uint8_t ports[RTE_MAX_ETHPORTS];
163
164 static unsigned nb_ports; /**< The number of ports specified in command line */
165
166 /* ethernet addresses of ports */
167 struct ether_addr ports_eth_addr[RTE_MAX_ETHPORTS];
168
169 /* heads for the main used and free linked lists for the data path. */
170 static struct virtio_net_data_ll *ll_root_used;
171 static struct virtio_net_data_ll *ll_root_free;
172
173 /**
174  * Array of data core structures containing information on
175  * individual core linked lists.
176  */
177 static struct lcore_info lcore_info[RTE_MAX_LCORE];
178
179 /* Used for queueing bursts of TX packets. */
180 struct mbuf_table {
181         unsigned len;
182         unsigned txq_id;
183         struct rte_mbuf *m_table[MAX_PKT_BURST];
184 };
185
186 /* TX queue for each data core. */
187 struct mbuf_table lcore_tx_queue[RTE_MAX_LCORE];
188
189 struct device_statistics dev_statistics[MAX_DEVICES];
190
191 /**
192  * Set character device basename.
193  */
194 static int
195 us_vhost_parse_basename(const char *q_arg)
196 {
197         /* parse number string */
198         if (strlen(q_arg) >= MAX_BASENAME_SZ)
199                 return -1;
200         else
201                 snprintf((char *)&dev_basename, MAX_BASENAME_SZ, "%s", q_arg);
202
203         return 0;
204 }
205
206 /**
207  * Parse the portmask provided at run time.
208  */
209 static int
210 parse_portmask(const char *portmask)
211 {
212         char *end = NULL;
213         unsigned long pm;
214
215         /* parse hexadecimal string */
216         pm = strtoul(portmask, &end, 16);
217         if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
218                 return -1;
219
220         if (pm == 0)
221                 return -1;
222
223         return pm;
224 }
225
226 /**
227  * Parse num options at run time.
228  */
229 static int
230 parse_num_opt(const char *q_arg, uint32_t max_valid_value)
231 {
232         char *end = NULL;
233         unsigned long num;
234
235         /* parse unsigned int string */
236         num = strtoul(q_arg, &end, 10);
237         if ((q_arg[0] == '\0') || (end == NULL) || (*end != '\0'))
238                 return -1;
239
240         if (num > max_valid_value)
241                 return -1;
242
243         return num;
244 }
245
246 /**
247  * Display usage
248  */
249 static void
250 tep_termination_usage(const char *prgname)
251 {
252         RTE_LOG(INFO, VHOST_CONFIG, "%s [EAL options] -- -p PORTMASK\n"
253         "               --nb-devices[1-64]: The number of virtIO device\n"
254         "               -p PORTMASK: Set mask for ports to be used by application\n"
255         "               --rx-retry [0|1]: disable/enable(default) retries on rx."
256         "                Enable retry if destintation queue is full\n"
257         "               --rx-retry-delay [0-N]: timeout(in usecond) between retries on RX."
258         "                This makes effect only if retries on rx enabled\n"
259         "               --rx-retry-num [0-N]: the number of retries on rx."
260         "                This makes effect only if retries on rx enabled\n"
261         "               --stats [0-N]: 0: Disable stats, N: Time in seconds to print stats\n"
262         "               --dev-basename: The basename to be used for the character device.\n",
263                prgname);
264 }
265
266 /**
267  * Parse the arguments given in the command line of the application.
268  */
269 static int
270 tep_termination_parse_args(int argc, char **argv)
271 {
272         int opt, ret;
273         int option_index;
274         unsigned i;
275         const char *prgname = argv[0];
276         static struct option long_option[] = {
277                 {CMD_LINE_OPT_NB_DEVICES, required_argument, NULL, 0},
278                 {CMD_LINE_OPT_RX_RETRY, required_argument, NULL, 0},
279                 {CMD_LINE_OPT_RX_RETRY_DELAY, required_argument, NULL, 0},
280                 {CMD_LINE_OPT_RX_RETRY_NUM, required_argument, NULL, 0},
281                 {CMD_LINE_OPT_STATS, required_argument, NULL, 0},
282                 {CMD_LINE_OPT_DEV_BASENAME, required_argument, NULL, 0},
283                 {NULL, 0, 0, 0},
284         };
285
286         /* Parse command line */
287         while ((opt = getopt_long(argc, argv, "p:",
288                         long_option, &option_index)) != EOF) {
289                 switch (opt) {
290                 /* Portmask */
291                 case 'p':
292                         enabled_port_mask = parse_portmask(optarg);
293                         if (enabled_port_mask == 0) {
294                                 RTE_LOG(INFO, VHOST_CONFIG,
295                                         "Invalid portmask\n");
296                                 tep_termination_usage(prgname);
297                                 return -1;
298                         }
299                         break;
300                 case 0:
301                         if (!strncmp(long_option[option_index].name,
302                                 CMD_LINE_OPT_NB_DEVICES,
303                                 sizeof(CMD_LINE_OPT_NB_DEVICES))) {
304                                 ret = parse_num_opt(optarg, MAX_DEVICES);
305                                 if (ret == -1) {
306                                         RTE_LOG(INFO, VHOST_CONFIG,
307                                         "Invalid argument for nb-devices [0-%d]\n",
308                                         MAX_DEVICES);
309                                         tep_termination_usage(prgname);
310                                         return -1;
311                                 } else
312                                         nb_devices = ret;
313                         }
314
315                         /* Enable/disable retries on RX. */
316                         if (!strncmp(long_option[option_index].name,
317                                 CMD_LINE_OPT_RX_RETRY,
318                                 sizeof(CMD_LINE_OPT_RX_RETRY))) {
319                                 ret = parse_num_opt(optarg, 1);
320                                 if (ret == -1) {
321                                         RTE_LOG(INFO, VHOST_CONFIG,
322                                                 "Invalid argument for rx-retry [0|1]\n");
323                                         tep_termination_usage(prgname);
324                                         return -1;
325                                 } else
326                                         enable_retry = ret;
327                         }
328
329                         /* Specify the retries delay time (in useconds) on RX.*/
330                         if (!strncmp(long_option[option_index].name,
331                                 CMD_LINE_OPT_RX_RETRY_DELAY,
332                                 sizeof(CMD_LINE_OPT_RX_RETRY_DELAY))) {
333                                 ret = parse_num_opt(optarg, INT32_MAX);
334                                 if (ret == -1) {
335                                         RTE_LOG(INFO, VHOST_CONFIG,
336                                                 "Invalid argument for rx-retry-delay [0-N]\n");
337                                         tep_termination_usage(prgname);
338                                         return -1;
339                                 } else
340                                         burst_rx_delay_time = ret;
341                         }
342
343                         /* Specify the retries number on RX. */
344                         if (!strncmp(long_option[option_index].name,
345                                 CMD_LINE_OPT_RX_RETRY_NUM,
346                                 sizeof(CMD_LINE_OPT_RX_RETRY_NUM))) {
347                                 ret = parse_num_opt(optarg, INT32_MAX);
348                                 if (ret == -1) {
349                                         RTE_LOG(INFO, VHOST_CONFIG,
350                                                 "Invalid argument for rx-retry-num [0-N]\n");
351                                         tep_termination_usage(prgname);
352                                         return -1;
353                                 } else
354                                         burst_rx_retry_num = ret;
355                         }
356
357                         /* Enable/disable stats. */
358                         if (!strncmp(long_option[option_index].name,
359                                 CMD_LINE_OPT_STATS,
360                                 sizeof(CMD_LINE_OPT_STATS))) {
361                                 ret = parse_num_opt(optarg, INT32_MAX);
362                                 if (ret == -1) {
363                                         RTE_LOG(INFO, VHOST_CONFIG,
364                                                         "Invalid argument for stats [0..N]\n");
365                                         tep_termination_usage(prgname);
366                                         return -1;
367                                 } else
368                                         enable_stats = ret;
369                         }
370
371                         /* Set character device basename. */
372                         if (!strncmp(long_option[option_index].name,
373                                 CMD_LINE_OPT_DEV_BASENAME,
374                                 sizeof(CMD_LINE_OPT_DEV_BASENAME))) {
375                                 if (us_vhost_parse_basename(optarg) == -1) {
376                                         RTE_LOG(INFO, VHOST_CONFIG,
377                                                 "Invalid argument for character "
378                                                 "device basename (Max %d characters)\n",
379                                                 MAX_BASENAME_SZ);
380                                         tep_termination_usage(prgname);
381                                         return -1;
382                                 }
383                         }
384
385                         break;
386
387                         /* Invalid option - print options. */
388                 default:
389                         tep_termination_usage(prgname);
390                         return -1;
391                 }
392         }
393
394         for (i = 0; i < RTE_MAX_ETHPORTS; i++) {
395                 if (enabled_port_mask & (1 << i))
396                         ports[nb_ports++] = (uint8_t)i;
397         }
398
399         if ((nb_ports ==  0) || (nb_ports > MAX_SUP_PORTS)) {
400                 RTE_LOG(INFO, VHOST_PORT, "Current enabled port number is %u,"
401                         "but only %u port can be enabled\n", nb_ports,
402                         MAX_SUP_PORTS);
403                 return -1;
404         }
405
406         return 0;
407 }
408
409 /**
410  * Update the global var NB_PORTS and array PORTS
411  * according to system ports number and return valid ports number
412  */
413 static unsigned
414 check_ports_num(unsigned max_nb_ports)
415 {
416         unsigned valid_nb_ports = nb_ports;
417         unsigned portid;
418
419         if (nb_ports > max_nb_ports) {
420                 RTE_LOG(INFO, VHOST_PORT, "\nSpecified port number(%u) "
421                         " exceeds total system port number(%u)\n",
422                         nb_ports, max_nb_ports);
423                 nb_ports = max_nb_ports;
424         }
425
426         for (portid = 0; portid < nb_ports; portid++) {
427                 if (ports[portid] >= max_nb_ports) {
428                         RTE_LOG(INFO, VHOST_PORT,
429                                 "\nSpecified port ID(%u) exceeds max "
430                                 " system port ID(%u)\n",
431                                 ports[portid], (max_nb_ports - 1));
432                         ports[portid] = INVALID_PORT_ID;
433                         valid_nb_ports--;
434                 }
435         }
436         return valid_nb_ports;
437 }
438
439 /**
440  * This function routes the TX packet to the correct interface. This may be a local device
441  * or the physical port.
442  */
443 static inline void __attribute__((always_inline))
444 virtio_tx_route(struct vhost_dev *vdev, struct rte_mbuf *m)
445 {
446         struct mbuf_table *tx_q;
447         struct rte_mbuf **m_table;
448         unsigned len, ret = 0;
449         const uint16_t lcore_id = rte_lcore_id();
450         struct virtio_net *dev = vdev->dev;
451
452         LOG_DEBUG(VHOST_DATA, "(%"PRIu64") TX: MAC address is external\n",
453                 dev->device_fh);
454
455         /* Add packet to the port tx queue */
456         tx_q = &lcore_tx_queue[lcore_id];
457         len = tx_q->len;
458
459         tx_q->m_table[len] = m;
460         len++;
461         if (enable_stats) {
462                 dev_statistics[dev->device_fh].tx_total++;
463                 dev_statistics[dev->device_fh].tx++;
464         }
465
466         if (unlikely(len == MAX_PKT_BURST)) {
467                 m_table = (struct rte_mbuf **)tx_q->m_table;
468                 ret = overlay_options.tx_handle(ports[0],
469                         (uint16_t)tx_q->txq_id, m_table,
470                         (uint16_t)tx_q->len);
471
472                 /* Free any buffers not handled by TX and update
473                  * the port stats.
474                  */
475                 if (unlikely(ret < len)) {
476                         do {
477                                 rte_pktmbuf_free(m_table[ret]);
478                         } while (++ret < len);
479                 }
480
481                 len = 0;
482         }
483
484         tx_q->len = len;
485         return;
486 }
487
488 /**
489  * This function is called by each data core. It handles all
490  * RX/TX registered with the core. For TX the specific lcore
491  * linked list is used. For RX, MAC addresses are compared
492  * with all devices in the main linked list.
493  */
494 static int
495 switch_worker(__rte_unused void *arg)
496 {
497         struct rte_mempool *mbuf_pool = arg;
498         struct virtio_net *dev = NULL;
499         struct vhost_dev *vdev = NULL;
500         struct rte_mbuf *pkts_burst[MAX_PKT_BURST];
501         struct virtio_net_data_ll *dev_ll;
502         struct mbuf_table *tx_q;
503         volatile struct lcore_ll_info *lcore_ll;
504         const uint64_t drain_tsc = (rte_get_tsc_hz() + US_PER_S - 1)
505                                         / US_PER_S * BURST_TX_DRAIN_US;
506         uint64_t prev_tsc, diff_tsc, cur_tsc, ret_count = 0;
507         unsigned i, ret = 0;
508         const uint16_t lcore_id = rte_lcore_id();
509         const uint16_t num_cores = (uint16_t)rte_lcore_count();
510         uint16_t rx_count = 0;
511         uint16_t tx_count;
512         uint32_t retry = 0;
513
514         RTE_LOG(INFO, VHOST_DATA, "Procesing on Core %u started\n", lcore_id);
515         lcore_ll = lcore_info[lcore_id].lcore_ll;
516         prev_tsc = 0;
517
518         tx_q = &lcore_tx_queue[lcore_id];
519         for (i = 0; i < num_cores; i++) {
520                 if (lcore_ids[i] == lcore_id) {
521                         tx_q->txq_id = i;
522                         break;
523                 }
524         }
525
526         while (1) {
527                 cur_tsc = rte_rdtsc();
528                 /*
529                  * TX burst queue drain
530                  */
531                 diff_tsc = cur_tsc - prev_tsc;
532                 if (unlikely(diff_tsc > drain_tsc)) {
533
534                         if (tx_q->len) {
535                                 LOG_DEBUG(VHOST_DATA, "TX queue drained after "
536                                         "timeout with burst size %u\n",
537                                         tx_q->len);
538                                 ret = overlay_options.tx_handle(ports[0],
539                                         (uint16_t)tx_q->txq_id,
540                                         (struct rte_mbuf **)tx_q->m_table,
541                                         (uint16_t)tx_q->len);
542                                 if (unlikely(ret < tx_q->len)) {
543                                         do {
544                                                 rte_pktmbuf_free(tx_q->m_table[ret]);
545                                         } while (++ret < tx_q->len);
546                                 }
547
548                                 tx_q->len = 0;
549                         }
550
551                         prev_tsc = cur_tsc;
552
553                 }
554
555                 rte_prefetch0(lcore_ll->ll_root_used);
556
557                 /**
558                  * Inform the configuration core that we have exited
559                  * the linked list and that no devices are
560                  * in use if requested.
561                  */
562                 if (lcore_ll->dev_removal_flag == REQUEST_DEV_REMOVAL)
563                         lcore_ll->dev_removal_flag = ACK_DEV_REMOVAL;
564
565                 /*
566                  * Process devices
567                  */
568                 dev_ll = lcore_ll->ll_root_used;
569
570                 while (dev_ll != NULL) {
571                         vdev = dev_ll->vdev;
572                         dev = vdev->dev;
573
574                         if (unlikely(vdev->remove)) {
575                                 dev_ll = dev_ll->next;
576                                 overlay_options.tunnel_destroy(vdev);
577                                 vdev->ready = DEVICE_SAFE_REMOVE;
578                                 continue;
579                         }
580                         if (likely(vdev->ready == DEVICE_RX)) {
581                                 /* Handle guest RX */
582                                 rx_count = rte_eth_rx_burst(ports[0],
583                                         vdev->rx_q, pkts_burst, MAX_PKT_BURST);
584
585                                 if (rx_count) {
586                                         /*
587                                         * Retry is enabled and the queue is
588                                         * full then we wait and retry to
589                                         * avoid packet loss. Here MAX_PKT_BURST
590                                         * must be less than virtio queue size
591                                         */
592                                         if (enable_retry && unlikely(rx_count >
593                                                 rte_vring_available_entries(dev, VIRTIO_RXQ))) {
594                                                 for (retry = 0; retry < burst_rx_retry_num;
595                                                         retry++) {
596                                                         rte_delay_us(burst_rx_delay_time);
597                                                         if (rx_count <= rte_vring_available_entries(dev, VIRTIO_RXQ))
598                                                                 break;
599                                                 }
600                                         }
601
602                                         ret_count = overlay_options.rx_handle(dev, pkts_burst, rx_count);
603                                         if (enable_stats) {
604                                                 rte_atomic64_add(
605                                                 &dev_statistics[dev->device_fh].rx_total_atomic,
606                                                 rx_count);
607                                                 rte_atomic64_add(
608                                                 &dev_statistics[dev->device_fh].rx_atomic, ret_count);
609                                         }
610                                         while (likely(rx_count)) {
611                                                 rx_count--;
612                                                 rte_pktmbuf_free(pkts_burst[rx_count]);
613                                         }
614
615                                 }
616                         }
617
618                         if (likely(!vdev->remove)) {
619                                 /* Handle guest TX*/
620                                 tx_count = rte_vhost_dequeue_burst(dev,
621                                                 VIRTIO_TXQ, mbuf_pool,
622                                                 pkts_burst, MAX_PKT_BURST);
623                                 /* If this is the first received packet we need to learn the MAC */
624                                 if (unlikely(vdev->ready == DEVICE_MAC_LEARNING) && tx_count) {
625                                         if (vdev->remove ||
626                                                 (overlay_options.tunnel_setup(vdev, pkts_burst[0]) == -1)) {
627                                                 while (tx_count)
628                                                         rte_pktmbuf_free(pkts_burst[--tx_count]);
629                                         }
630                                 }
631                                 while (tx_count)
632                                         virtio_tx_route(vdev, pkts_burst[--tx_count]);
633                         }
634
635                         /* move to the next device in the list */
636                         dev_ll = dev_ll->next;
637                 }
638         }
639
640         return 0;
641 }
642
643 /**
644  * Add an entry to a used linked list. A free entry must first be found
645  * in the free linked list using get_data_ll_free_entry();
646  */
647 static void
648 add_data_ll_entry(struct virtio_net_data_ll **ll_root_addr,
649         struct virtio_net_data_ll *ll_dev)
650 {
651         struct virtio_net_data_ll *ll = *ll_root_addr;
652
653         /* Set next as NULL and use a compiler barrier to avoid reordering. */
654         ll_dev->next = NULL;
655         rte_compiler_barrier();
656
657         /* If ll == NULL then this is the first device. */
658         if (ll) {
659                 /* Increment to the tail of the linked list. */
660                 while (ll->next != NULL)
661                         ll = ll->next;
662
663                 ll->next = ll_dev;
664         } else {
665                 *ll_root_addr = ll_dev;
666         }
667 }
668
669 /**
670  * Remove an entry from a used linked list. The entry must then be added to
671  * the free linked list using put_data_ll_free_entry().
672  */
673 static void
674 rm_data_ll_entry(struct virtio_net_data_ll **ll_root_addr,
675         struct virtio_net_data_ll *ll_dev,
676         struct virtio_net_data_ll *ll_dev_last)
677 {
678         struct virtio_net_data_ll *ll = *ll_root_addr;
679
680         if (unlikely((ll == NULL) || (ll_dev == NULL)))
681                 return;
682
683         if (ll_dev == ll)
684                 *ll_root_addr = ll_dev->next;
685         else
686                 if (likely(ll_dev_last != NULL))
687                         ll_dev_last->next = ll_dev->next;
688                 else
689                         RTE_LOG(ERR, VHOST_CONFIG,
690                                 "Remove entry form ll failed.\n");
691 }
692
693 /**
694  * Find and return an entry from the free linked list.
695  */
696 static struct virtio_net_data_ll *
697 get_data_ll_free_entry(struct virtio_net_data_ll **ll_root_addr)
698 {
699         struct virtio_net_data_ll *ll_free = *ll_root_addr;
700         struct virtio_net_data_ll *ll_dev;
701
702         if (ll_free == NULL)
703                 return NULL;
704
705         ll_dev = ll_free;
706         *ll_root_addr = ll_free->next;
707
708         return ll_dev;
709 }
710
711 /**
712  * Place an entry back on to the free linked list.
713  */
714 static void
715 put_data_ll_free_entry(struct virtio_net_data_ll **ll_root_addr,
716         struct virtio_net_data_ll *ll_dev)
717 {
718         struct virtio_net_data_ll *ll_free = *ll_root_addr;
719
720         if (ll_dev == NULL)
721                 return;
722
723         ll_dev->next = ll_free;
724         *ll_root_addr = ll_dev;
725 }
726
727 /**
728  * Creates a linked list of a given size.
729  */
730 static struct virtio_net_data_ll *
731 alloc_data_ll(uint32_t size)
732 {
733         struct virtio_net_data_ll *ll_new;
734         uint32_t i;
735
736         /* Malloc and then chain the linked list. */
737         ll_new = malloc(size * sizeof(struct virtio_net_data_ll));
738         if (ll_new == NULL) {
739                 RTE_LOG(ERR, VHOST_CONFIG,
740                         "Failed to allocate memory for ll_new.\n");
741                 return NULL;
742         }
743
744         for (i = 0; i < size - 1; i++) {
745                 ll_new[i].vdev = NULL;
746                 ll_new[i].next = &ll_new[i+1];
747         }
748         ll_new[i].next = NULL;
749
750         return ll_new;
751 }
752
753 /**
754  * Create the main linked list along with each individual cores
755  * linked list. A used and a free list are created to manage entries.
756  */
757 static int
758 init_data_ll(void)
759 {
760         int lcore;
761
762         RTE_LCORE_FOREACH_SLAVE(lcore) {
763                 lcore_info[lcore].lcore_ll =
764                         malloc(sizeof(struct lcore_ll_info));
765                 if (lcore_info[lcore].lcore_ll == NULL) {
766                         RTE_LOG(ERR, VHOST_CONFIG,
767                                 "Failed to allocate memory for lcore_ll.\n");
768                         return -1;
769                 }
770
771                 lcore_info[lcore].lcore_ll->device_num = 0;
772                 lcore_info[lcore].lcore_ll->dev_removal_flag = ACK_DEV_REMOVAL;
773                 lcore_info[lcore].lcore_ll->ll_root_used = NULL;
774                 if (nb_devices % nb_switching_cores)
775                         lcore_info[lcore].lcore_ll->ll_root_free =
776                                 alloc_data_ll((nb_devices / nb_switching_cores)
777                                                 + 1);
778                 else
779                         lcore_info[lcore].lcore_ll->ll_root_free =
780                                 alloc_data_ll(nb_devices / nb_switching_cores);
781         }
782
783         /* Allocate devices up to a maximum of MAX_DEVICES. */
784         ll_root_free = alloc_data_ll(MIN((nb_devices), MAX_DEVICES));
785
786         return 0;
787 }
788
789 /**
790  * Remove a device from the specific data core linked list and
791  * from the main linked list. Synchonization occurs through the use
792  * of the lcore dev_removal_flag. Device is made volatile here
793  * to avoid re-ordering of dev->remove=1 which can cause an infinite
794  * loop in the rte_pause loop.
795  */
796 static void
797 destroy_device(volatile struct virtio_net *dev)
798 {
799         struct virtio_net_data_ll *ll_lcore_dev_cur;
800         struct virtio_net_data_ll *ll_main_dev_cur;
801         struct virtio_net_data_ll *ll_lcore_dev_last = NULL;
802         struct virtio_net_data_ll *ll_main_dev_last = NULL;
803         struct vhost_dev *vdev;
804         int lcore;
805
806         dev->flags &= ~VIRTIO_DEV_RUNNING;
807
808         vdev = (struct vhost_dev *)dev->priv;
809
810         /* set the remove flag. */
811         vdev->remove = 1;
812         while (vdev->ready != DEVICE_SAFE_REMOVE)
813                 rte_pause();
814
815         /* Search for entry to be removed from lcore ll */
816         ll_lcore_dev_cur = lcore_info[vdev->coreid].lcore_ll->ll_root_used;
817         while (ll_lcore_dev_cur != NULL) {
818                 if (ll_lcore_dev_cur->vdev == vdev) {
819                         break;
820                 } else {
821                         ll_lcore_dev_last = ll_lcore_dev_cur;
822                         ll_lcore_dev_cur = ll_lcore_dev_cur->next;
823                 }
824         }
825
826         if (ll_lcore_dev_cur == NULL) {
827                 RTE_LOG(ERR, VHOST_CONFIG,
828                         "(%"PRIu64") Failed to find the dev to be destroy.\n",
829                         dev->device_fh);
830                 return;
831         }
832
833         /* Search for entry to be removed from main ll */
834         ll_main_dev_cur = ll_root_used;
835         ll_main_dev_last = NULL;
836         while (ll_main_dev_cur != NULL) {
837                 if (ll_main_dev_cur->vdev == vdev) {
838                         break;
839                 } else {
840                         ll_main_dev_last = ll_main_dev_cur;
841                         ll_main_dev_cur = ll_main_dev_cur->next;
842                 }
843         }
844
845         /* Remove entries from the lcore and main ll. */
846         rm_data_ll_entry(&lcore_info[vdev->coreid].lcore_ll->ll_root_used,
847                         ll_lcore_dev_cur, ll_lcore_dev_last);
848         rm_data_ll_entry(&ll_root_used, ll_main_dev_cur, ll_main_dev_last);
849
850         /* Set the dev_removal_flag on each lcore. */
851         RTE_LCORE_FOREACH_SLAVE(lcore) {
852                 lcore_info[lcore].lcore_ll->dev_removal_flag =
853                         REQUEST_DEV_REMOVAL;
854         }
855
856         /*
857          * Once each core has set the dev_removal_flag to
858          * ACK_DEV_REMOVAL we can be sure that they can no longer access
859          * the device removed from the linked lists and that the devices
860          * are no longer in use.
861          */
862         RTE_LCORE_FOREACH_SLAVE(lcore) {
863                 while (lcore_info[lcore].lcore_ll->dev_removal_flag
864                         != ACK_DEV_REMOVAL)
865                         rte_pause();
866         }
867
868         /* Add the entries back to the lcore and main free ll.*/
869         put_data_ll_free_entry(&lcore_info[vdev->coreid].lcore_ll->ll_root_free,
870                                 ll_lcore_dev_cur);
871         put_data_ll_free_entry(&ll_root_free, ll_main_dev_cur);
872
873         /* Decrement number of device on the lcore. */
874         lcore_info[vdev->coreid].lcore_ll->device_num--;
875
876         RTE_LOG(INFO, VHOST_DATA, "(%"PRIu64") Device has been removed "
877                 "from data core\n", dev->device_fh);
878
879         rte_free(vdev);
880
881 }
882
883 /**
884  * A new device is added to a data core. First the device is added
885  * to the main linked list and the allocated to a specific data core.
886  */
887 static int
888 new_device(struct virtio_net *dev)
889 {
890         struct virtio_net_data_ll *ll_dev;
891         int lcore, core_add = 0;
892         uint32_t device_num_min = nb_devices;
893         struct vhost_dev *vdev;
894
895         vdev = rte_zmalloc("vhost device", sizeof(*vdev), RTE_CACHE_LINE_SIZE);
896         if (vdev == NULL) {
897                 RTE_LOG(INFO, VHOST_DATA,
898                         "(%"PRIu64") Couldn't allocate memory for vhost dev\n",
899                         dev->device_fh);
900                 return -1;
901         }
902         vdev->dev = dev;
903         dev->priv = vdev;
904         /* Add device to main ll */
905         ll_dev = get_data_ll_free_entry(&ll_root_free);
906         if (ll_dev == NULL) {
907                 RTE_LOG(INFO, VHOST_DATA, "(%"PRIu64") No free entry found in"
908                         " linked list Device limit of %d devices per core"
909                         " has been reached\n", dev->device_fh, nb_devices);
910                 if (vdev->regions_hpa)
911                         rte_free(vdev->regions_hpa);
912                 rte_free(vdev);
913                 return -1;
914         }
915         ll_dev->vdev = vdev;
916         add_data_ll_entry(&ll_root_used, ll_dev);
917         vdev->rx_q = dev->device_fh;
918
919         /* reset ready flag */
920         vdev->ready = DEVICE_MAC_LEARNING;
921         vdev->remove = 0;
922
923         /* Find a suitable lcore to add the device. */
924         RTE_LCORE_FOREACH_SLAVE(lcore) {
925                 if (lcore_info[lcore].lcore_ll->device_num < device_num_min) {
926                         device_num_min = lcore_info[lcore].lcore_ll->device_num;
927                         core_add = lcore;
928                 }
929         }
930         /* Add device to lcore ll */
931         ll_dev = get_data_ll_free_entry(&lcore_info[core_add].lcore_ll->ll_root_free);
932         if (ll_dev == NULL) {
933                 RTE_LOG(INFO, VHOST_DATA,
934                         "(%"PRIu64") Failed to add device to data core\n",
935                         dev->device_fh);
936                 vdev->ready = DEVICE_SAFE_REMOVE;
937                 destroy_device(dev);
938                 rte_free(vdev->regions_hpa);
939                 rte_free(vdev);
940                 return -1;
941         }
942         ll_dev->vdev = vdev;
943         vdev->coreid = core_add;
944
945         add_data_ll_entry(&lcore_info[vdev->coreid].lcore_ll->ll_root_used,
946                         ll_dev);
947
948         /* Initialize device stats */
949         memset(&dev_statistics[dev->device_fh], 0,
950                 sizeof(struct device_statistics));
951
952         /* Disable notifications. */
953         rte_vhost_enable_guest_notification(dev, VIRTIO_RXQ, 0);
954         rte_vhost_enable_guest_notification(dev, VIRTIO_TXQ, 0);
955         lcore_info[vdev->coreid].lcore_ll->device_num++;
956         dev->flags |= VIRTIO_DEV_RUNNING;
957
958         RTE_LOG(INFO, VHOST_DATA, "(%"PRIu64") Device has been added to data core %d\n",
959                 dev->device_fh, vdev->coreid);
960
961         return 0;
962 }
963
964 /**
965  * These callback allow devices to be added to the data core when configuration
966  * has been fully complete.
967  */
968 static const struct virtio_net_device_ops virtio_net_device_ops = {
969         .new_device =  new_device,
970         .destroy_device = destroy_device,
971 };
972
973 /**
974  * This is a thread will wake up after a period to print stats if the user has
975  * enabled them.
976  */
977 static void
978 print_stats(void)
979 {
980         struct virtio_net_data_ll *dev_ll;
981         uint64_t tx_dropped, rx_dropped;
982         uint64_t tx, tx_total, rx, rx_total;
983         uint32_t device_fh;
984         const char clr[] = { 27, '[', '2', 'J', '\0' };
985         const char top_left[] = { 27, '[', '1', ';', '1', 'H', '\0' };
986
987         while (1) {
988                 sleep(enable_stats);
989
990                 /* Clear screen and move to top left */
991                 printf("%s%s", clr, top_left);
992
993                 printf("\nDevice statistics ================================");
994
995                 dev_ll = ll_root_used;
996                 while (dev_ll != NULL) {
997                         device_fh = (uint32_t)dev_ll->vdev->dev->device_fh;
998                         tx_total = dev_statistics[device_fh].tx_total;
999                         tx = dev_statistics[device_fh].tx;
1000                         tx_dropped = tx_total - tx;
1001
1002                         rx_total = rte_atomic64_read(
1003                                 &dev_statistics[device_fh].rx_total_atomic);
1004                         rx = rte_atomic64_read(
1005                                 &dev_statistics[device_fh].rx_atomic);
1006                         rx_dropped = rx_total - rx;
1007
1008                         printf("\nStatistics for device %"PRIu32" ----------"
1009                                         "\nTX total:            %"PRIu64""
1010                                         "\nTX dropped:          %"PRIu64""
1011                                         "\nTX successful:               %"PRIu64""
1012                                         "\nRX total:            %"PRIu64""
1013                                         "\nRX dropped:          %"PRIu64""
1014                                         "\nRX successful:               %"PRIu64"",
1015                                         device_fh,
1016                                         tx_total,
1017                                         tx_dropped,
1018                                         tx,
1019                                         rx_total,
1020                                         rx_dropped,
1021                                         rx);
1022
1023                         dev_ll = dev_ll->next;
1024                 }
1025                 printf("\n================================================\n");
1026         }
1027 }
1028
1029 /**
1030  * Main function, does initialisation and calls the per-lcore functions. The CUSE
1031  * device is also registered here to handle the IOCTLs.
1032  */
1033 int
1034 main(int argc, char *argv[])
1035 {
1036         struct rte_mempool *mbuf_pool = NULL;
1037         unsigned lcore_id, core_id = 0;
1038         unsigned nb_ports, valid_nb_ports;
1039         int ret;
1040         uint8_t portid;
1041         uint16_t queue_id;
1042         static pthread_t tid;
1043
1044         /* init EAL */
1045         ret = rte_eal_init(argc, argv);
1046         if (ret < 0)
1047                 rte_exit(EXIT_FAILURE, "Error with EAL initialization\n");
1048         argc -= ret;
1049         argv += ret;
1050
1051         /* parse app arguments */
1052         ret = tep_termination_parse_args(argc, argv);
1053         if (ret < 0)
1054                 rte_exit(EXIT_FAILURE, "Invalid argument\n");
1055
1056         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++)
1057                 if (rte_lcore_is_enabled(lcore_id))
1058                         lcore_ids[core_id++] = lcore_id;
1059
1060         /* set the number of swithcing cores available */
1061         nb_switching_cores = rte_lcore_count()-1;
1062
1063         /* Get the number of physical ports. */
1064         nb_ports = rte_eth_dev_count();
1065         if (nb_ports > RTE_MAX_ETHPORTS)
1066                 nb_ports = RTE_MAX_ETHPORTS;
1067
1068         /*
1069          * Update the global var NB_PORTS and global array PORTS
1070          * and get value of var VALID_NB_PORTS according to system ports number
1071          */
1072         valid_nb_ports = check_ports_num(nb_ports);
1073
1074         if ((valid_nb_ports == 0) || (valid_nb_ports > MAX_SUP_PORTS)) {
1075                 rte_exit(EXIT_FAILURE, "Current enabled port number is %u,"
1076                         "but only %u port can be enabled\n", nb_ports,
1077                         MAX_SUP_PORTS);
1078         }
1079         /* Create the mbuf pool. */
1080         mbuf_pool = rte_mempool_create(
1081                         "MBUF_POOL",
1082                         NUM_MBUFS_PER_PORT
1083                         * valid_nb_ports,
1084                         MBUF_SIZE, MBUF_CACHE_SIZE,
1085                         sizeof(struct rte_pktmbuf_pool_private),
1086                         rte_pktmbuf_pool_init, NULL,
1087                         rte_pktmbuf_init, NULL,
1088                         rte_socket_id(), 0);
1089         if (mbuf_pool == NULL)
1090                 rte_exit(EXIT_FAILURE, "Cannot create mbuf pool\n");
1091
1092         for (queue_id = 0; queue_id < MAX_QUEUES + 1; queue_id++)
1093                 vpool_array[queue_id].pool = mbuf_pool;
1094
1095         /* Set log level. */
1096         rte_set_log_level(LOG_LEVEL);
1097
1098         /* initialize all ports */
1099         for (portid = 0; portid < nb_ports; portid++) {
1100                 /* skip ports that are not enabled */
1101                 if ((enabled_port_mask & (1 << portid)) == 0) {
1102                         RTE_LOG(INFO, VHOST_PORT,
1103                                 "Skipping disabled port %d\n", portid);
1104                         continue;
1105                 }
1106                 if (overlay_options.port_configure(portid, mbuf_pool) != 0)
1107                         rte_exit(EXIT_FAILURE,
1108                                 "Cannot initialize network ports\n");
1109         }
1110
1111         /* Initialise all linked lists. */
1112         if (init_data_ll() == -1)
1113                 rte_exit(EXIT_FAILURE, "Failed to initialize linked list\n");
1114
1115         /* Initialize device stats */
1116         memset(&dev_statistics, 0, sizeof(dev_statistics));
1117
1118         /* Enable stats if the user option is set. */
1119         if (enable_stats)
1120                 pthread_create(&tid, NULL, (void *)print_stats, NULL);
1121
1122         /* Launch all data cores. */
1123         RTE_LCORE_FOREACH_SLAVE(lcore_id) {
1124                 rte_eal_remote_launch(switch_worker,
1125                         mbuf_pool, lcore_id);
1126         }
1127         rte_vhost_feature_disable(1ULL << VIRTIO_NET_F_MRG_RXBUF);
1128
1129         /* Register CUSE device to handle IOCTLs. */
1130         ret = rte_vhost_driver_register((char *)&dev_basename);
1131         if (ret != 0)
1132                 rte_exit(EXIT_FAILURE, "CUSE device setup failure.\n");
1133
1134         rte_vhost_driver_callback_register(&virtio_net_device_ops);
1135
1136         /* Start CUSE session. */
1137         rte_vhost_driver_session_start();
1138
1139         return 0;
1140 }