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