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