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