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