netdev-dpdk.c: Add generic policer functions.
[cascardo/ovs.git] / lib / netdev-dpdk.c
1 /*
2  * Copyright (c) 2014, 2015, 2016 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include <string.h>
20 #include <signal.h>
21 #include <stdlib.h>
22 #include <pthread.h>
23 #include <config.h>
24 #include <errno.h>
25 #include <sched.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <sys/stat.h>
29 #include <stdio.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <getopt.h>
33
34 #include "dirs.h"
35 #include "dp-packet.h"
36 #include "dpif-netdev.h"
37 #include "fatal-signal.h"
38 #include "netdev-dpdk.h"
39 #include "netdev-provider.h"
40 #include "netdev-vport.h"
41 #include "odp-util.h"
42 #include "openvswitch/dynamic-string.h"
43 #include "openvswitch/list.h"
44 #include "openvswitch/ofp-print.h"
45 #include "openvswitch/vlog.h"
46 #include "ovs-numa.h"
47 #include "ovs-thread.h"
48 #include "ovs-rcu.h"
49 #include "packets.h"
50 #include "shash.h"
51 #include "smap.h"
52 #include "sset.h"
53 #include "unaligned.h"
54 #include "timeval.h"
55 #include "unixctl.h"
56
57 #include "rte_config.h"
58 #include "rte_mbuf.h"
59 #include "rte_meter.h"
60 #include "rte_virtio_net.h"
61
62 VLOG_DEFINE_THIS_MODULE(dpdk);
63 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
64
65 #define DPDK_PORT_WATCHDOG_INTERVAL 5
66
67 #define OVS_CACHE_LINE_SIZE CACHE_LINE_SIZE
68 #define OVS_VPORT_DPDK "ovs_dpdk"
69
70 /*
71  * need to reserve tons of extra space in the mbufs so we can align the
72  * DMA addresses to 4KB.
73  * The minimum mbuf size is limited to avoid scatter behaviour and drop in
74  * performance for standard Ethernet MTU.
75  */
76 #define ETHER_HDR_MAX_LEN           (ETHER_HDR_LEN + ETHER_CRC_LEN + (2 * VLAN_HEADER_LEN))
77 #define MTU_TO_FRAME_LEN(mtu)       ((mtu) + ETHER_HDR_LEN + ETHER_CRC_LEN)
78 #define MTU_TO_MAX_FRAME_LEN(mtu)   ((mtu) + ETHER_HDR_MAX_LEN)
79 #define FRAME_LEN_TO_MTU(frame_len) ((frame_len)- ETHER_HDR_LEN - ETHER_CRC_LEN)
80 #define MBUF_SIZE(mtu)              ( MTU_TO_MAX_FRAME_LEN(mtu)   \
81                                     + sizeof(struct dp_packet)    \
82                                     + RTE_PKTMBUF_HEADROOM)
83 #define NETDEV_DPDK_MBUF_ALIGN      1024
84
85 /* Max and min number of packets in the mempool.  OVS tries to allocate a
86  * mempool with MAX_NB_MBUF: if this fails (because the system doesn't have
87  * enough hugepages) we keep halving the number until the allocation succeeds
88  * or we reach MIN_NB_MBUF */
89
90 #define MAX_NB_MBUF          (4096 * 64)
91 #define MIN_NB_MBUF          (4096 * 4)
92 #define MP_CACHE_SZ          RTE_MEMPOOL_CACHE_MAX_SIZE
93
94 /* MAX_NB_MBUF can be divided by 2 many times, until MIN_NB_MBUF */
95 BUILD_ASSERT_DECL(MAX_NB_MBUF % ROUND_DOWN_POW2(MAX_NB_MBUF/MIN_NB_MBUF) == 0);
96
97 /* The smallest possible NB_MBUF that we're going to try should be a multiple
98  * of MP_CACHE_SZ. This is advised by DPDK documentation. */
99 BUILD_ASSERT_DECL((MAX_NB_MBUF / ROUND_DOWN_POW2(MAX_NB_MBUF/MIN_NB_MBUF))
100                   % MP_CACHE_SZ == 0);
101
102 /*
103  * DPDK XSTATS Counter names definition
104  */
105 #define XSTAT_RX_64_PACKETS              "rx_size_64_packets"
106 #define XSTAT_RX_65_TO_127_PACKETS       "rx_size_65_to_127_packets"
107 #define XSTAT_RX_128_TO_255_PACKETS      "rx_size_128_to_255_packets"
108 #define XSTAT_RX_256_TO_511_PACKETS      "rx_size_256_to_511_packets"
109 #define XSTAT_RX_512_TO_1023_PACKETS     "rx_size_512_to_1023_packets"
110 #define XSTAT_RX_1024_TO_1522_PACKETS    "rx_size_1024_to_1522_packets"
111 #define XSTAT_RX_1523_TO_MAX_PACKETS     "rx_size_1523_to_max_packets"
112
113 #define XSTAT_TX_64_PACKETS              "tx_size_64_packets"
114 #define XSTAT_TX_65_TO_127_PACKETS       "tx_size_65_to_127_packets"
115 #define XSTAT_TX_128_TO_255_PACKETS      "tx_size_128_to_255_packets"
116 #define XSTAT_TX_256_TO_511_PACKETS      "tx_size_256_to_511_packets"
117 #define XSTAT_TX_512_TO_1023_PACKETS     "tx_size_512_to_1023_packets"
118 #define XSTAT_TX_1024_TO_1522_PACKETS    "tx_size_1024_to_1522_packets"
119 #define XSTAT_TX_1523_TO_MAX_PACKETS     "tx_size_1523_to_max_packets"
120
121 #define XSTAT_TX_MULTICAST_PACKETS       "tx_multicast_packets"
122 #define XSTAT_RX_BROADCAST_PACKETS       "rx_broadcast_packets"
123 #define XSTAT_TX_BROADCAST_PACKETS       "tx_broadcast_packets"
124 #define XSTAT_RX_UNDERSIZED_ERRORS       "rx_undersized_errors"
125 #define XSTAT_RX_OVERSIZE_ERRORS         "rx_oversize_errors"
126 #define XSTAT_RX_FRAGMENTED_ERRORS       "rx_fragmented_errors"
127 #define XSTAT_RX_JABBER_ERRORS           "rx_jabber_errors"
128
129 #define SOCKET0              0
130
131 #define NIC_PORT_RX_Q_SIZE 2048  /* Size of Physical NIC RX Queue, Max (n+32<=4096)*/
132 #define NIC_PORT_TX_Q_SIZE 2048  /* Size of Physical NIC TX Queue, Max (n+32<=4096)*/
133
134 #define OVS_VHOST_MAX_QUEUE_NUM 1024  /* Maximum number of vHost TX queues. */
135 #define OVS_VHOST_QUEUE_MAP_UNKNOWN (-1) /* Mapping not initialized. */
136 #define OVS_VHOST_QUEUE_DISABLED    (-2) /* Queue was disabled by guest and not
137                                           * yet mapped to another queue. */
138
139 #ifdef VHOST_CUSE
140 static char *cuse_dev_name = NULL;    /* Character device cuse_dev_name. */
141 #endif
142 static char *vhost_sock_dir = NULL;   /* Location of vhost-user sockets */
143
144 /*
145  * Maximum amount of time in micro seconds to try and enqueue to vhost.
146  */
147 #define VHOST_ENQ_RETRY_USECS 100
148
149 static const struct rte_eth_conf port_conf = {
150     .rxmode = {
151         .mq_mode = ETH_MQ_RX_RSS,
152         .split_hdr_size = 0,
153         .header_split   = 0, /* Header Split disabled */
154         .hw_ip_checksum = 0, /* IP checksum offload disabled */
155         .hw_vlan_filter = 0, /* VLAN filtering disabled */
156         .jumbo_frame    = 0, /* Jumbo Frame Support disabled */
157         .hw_strip_crc   = 0,
158     },
159     .rx_adv_conf = {
160         .rss_conf = {
161             .rss_key = NULL,
162             .rss_hf = ETH_RSS_IP | ETH_RSS_UDP | ETH_RSS_TCP,
163         },
164     },
165     .txmode = {
166         .mq_mode = ETH_MQ_TX_NONE,
167     },
168 };
169
170 enum { MAX_TX_QUEUE_LEN = 384 };
171 enum { DPDK_RING_SIZE = 256 };
172 BUILD_ASSERT_DECL(IS_POW2(DPDK_RING_SIZE));
173 enum { DRAIN_TSC = 200000ULL };
174
175 enum dpdk_dev_type {
176     DPDK_DEV_ETH = 0,
177     DPDK_DEV_VHOST = 1,
178 };
179
180 static int rte_eal_init_ret = ENODEV;
181
182 static struct ovs_mutex dpdk_mutex = OVS_MUTEX_INITIALIZER;
183
184 /* Quality of Service */
185
186 /* An instance of a QoS configuration.  Always associated with a particular
187  * network device.
188  *
189  * Each QoS implementation subclasses this with whatever additional data it
190  * needs.
191  */
192 struct qos_conf {
193     const struct dpdk_qos_ops *ops;
194 };
195
196 /* A particular implementation of dpdk QoS operations.
197  *
198  * The functions below return 0 if successful or a positive errno value on
199  * failure, except where otherwise noted. All of them must be provided, except
200  * where otherwise noted.
201  */
202 struct dpdk_qos_ops {
203
204     /* Name of the QoS type */
205     const char *qos_name;
206
207     /* Called to construct the QoS implementation on 'netdev'. The
208      * implementation should make the appropriate calls to configure QoS
209      * according to 'details'. The implementation may assume that any current
210      * QoS configuration already installed should be destroyed before
211      * constructing the new configuration.
212      *
213      * The contents of 'details' should be documented as valid for 'ovs_name'
214      * in the "other_config" column in the "QoS" table in vswitchd/vswitch.xml
215      * (which is built as ovs-vswitchd.conf.db(8)).
216      *
217      * This function must return 0 if and only if it sets 'netdev->qos_conf'
218      * to an initialized 'struct qos_conf'.
219      *
220      * For all QoS implementations it should always be non-null.
221      */
222     int (*qos_construct)(struct netdev *netdev, const struct smap *details);
223
224     /* Destroys the data structures allocated by the implementation as part of
225      * 'qos_conf.
226      *
227      * For all QoS implementations it should always be non-null.
228      */
229     void (*qos_destruct)(struct netdev *netdev, struct qos_conf *conf);
230
231     /* Retrieves details of 'netdev->qos_conf' configuration into 'details'.
232      *
233      * The contents of 'details' should be documented as valid for 'ovs_name'
234      * in the "other_config" column in the "QoS" table in vswitchd/vswitch.xml
235      * (which is built as ovs-vswitchd.conf.db(8)).
236      */
237     int (*qos_get)(const struct netdev *netdev, struct smap *details);
238
239     /* Reconfigures 'netdev->qos_conf' according to 'details', performing any
240      * required calls to complete the reconfiguration.
241      *
242      * The contents of 'details' should be documented as valid for 'ovs_name'
243      * in the "other_config" column in the "QoS" table in vswitchd/vswitch.xml
244      * (which is built as ovs-vswitchd.conf.db(8)).
245      *
246      * This function may be null if 'qos_conf' is not configurable.
247      */
248     int (*qos_set)(struct netdev *netdev, const struct smap *details);
249
250     /* Modify an array of rte_mbufs. The modification is specific to
251      * each qos implementation.
252      *
253      * The function should take and array of mbufs and an int representing
254      * the current number of mbufs present in the array.
255      *
256      * After the function has performed a qos modification to the array of
257      * mbufs it returns an int representing the number of mbufs now present in
258      * the array. This value is can then be passed to the port send function
259      * along with the modified array for transmission.
260      *
261      * For all QoS implementations it should always be non-null.
262      */
263     int (*qos_run)(struct netdev *netdev, struct rte_mbuf **pkts,
264                            int pkt_cnt);
265 };
266
267 /* dpdk_qos_ops for each type of user space QoS implementation */
268 static const struct dpdk_qos_ops egress_policer_ops;
269
270 /*
271  * Array of dpdk_qos_ops, contains pointer to all supported QoS
272  * operations.
273  */
274 static const struct dpdk_qos_ops *const qos_confs[] = {
275     &egress_policer_ops,
276     NULL
277 };
278
279 /* Contains all 'struct dpdk_dev's. */
280 static struct ovs_list dpdk_list OVS_GUARDED_BY(dpdk_mutex)
281     = OVS_LIST_INITIALIZER(&dpdk_list);
282
283 static struct ovs_list dpdk_mp_list OVS_GUARDED_BY(dpdk_mutex)
284     = OVS_LIST_INITIALIZER(&dpdk_mp_list);
285
286 /* This mutex must be used by non pmd threads when allocating or freeing
287  * mbufs through mempools. Since dpdk_queue_pkts() and dpdk_queue_flush() may
288  * use mempools, a non pmd thread should hold this mutex while calling them */
289 static struct ovs_mutex nonpmd_mempool_mutex = OVS_MUTEX_INITIALIZER;
290
291 struct dpdk_mp {
292     struct rte_mempool *mp;
293     int mtu;
294     int socket_id;
295     int refcount;
296     struct ovs_list list_node OVS_GUARDED_BY(dpdk_mutex);
297 };
298
299 /* There should be one 'struct dpdk_tx_queue' created for
300  * each cpu core. */
301 struct dpdk_tx_queue {
302     bool flush_tx;                 /* Set to true to flush queue everytime */
303                                    /* pkts are queued. */
304     int count;
305     rte_spinlock_t tx_lock;        /* Protects the members and the NIC queue
306                                     * from concurrent access.  It is used only
307                                     * if the queue is shared among different
308                                     * pmd threads (see 'txq_needs_locking'). */
309     int map;                       /* Mapping of configured vhost-user queues
310                                     * to enabled by guest. */
311     uint64_t tsc;
312     struct rte_mbuf *burst_pkts[MAX_TX_QUEUE_LEN];
313 };
314
315 /* dpdk has no way to remove dpdk ring ethernet devices
316    so we have to keep them around once they've been created
317 */
318
319 static struct ovs_list dpdk_ring_list OVS_GUARDED_BY(dpdk_mutex)
320     = OVS_LIST_INITIALIZER(&dpdk_ring_list);
321
322 struct dpdk_ring {
323     /* For the client rings */
324     struct rte_ring *cring_tx;
325     struct rte_ring *cring_rx;
326     unsigned int user_port_id; /* User given port no, parsed from port name */
327     int eth_port_id; /* ethernet device port id */
328     struct ovs_list list_node OVS_GUARDED_BY(dpdk_mutex);
329 };
330
331 struct netdev_dpdk {
332     struct netdev up;
333     int port_id;
334     int max_packet_len;
335     enum dpdk_dev_type type;
336
337     struct dpdk_tx_queue *tx_q;
338
339     struct ovs_mutex mutex OVS_ACQ_AFTER(dpdk_mutex);
340
341     struct dpdk_mp *dpdk_mp;
342     int mtu;
343     int socket_id;
344     int buf_size;
345     struct netdev_stats stats;
346     /* Protects stats */
347     rte_spinlock_t stats_lock;
348
349     struct eth_addr hwaddr;
350     enum netdev_flags flags;
351
352     struct rte_eth_link link;
353     int link_reset_cnt;
354
355     /* The user might request more txqs than the NIC has.  We remap those
356      * ('up.n_txq') on these ('real_n_txq').
357      * If the numbers match, 'txq_needs_locking' is false, otherwise it is
358      * true and we will take a spinlock on transmission */
359     int real_n_txq;
360     int real_n_rxq;
361     bool txq_needs_locking;
362
363     /* virtio-net structure for vhost device */
364     OVSRCU_TYPE(struct virtio_net *) virtio_dev;
365
366     /* Identifier used to distinguish vhost devices from each other */
367     char vhost_id[PATH_MAX];
368
369     /* In dpdk_list. */
370     struct ovs_list list_node OVS_GUARDED_BY(dpdk_mutex);
371
372     /* QoS configuration and lock for the device */
373     struct qos_conf *qos_conf;
374     rte_spinlock_t qos_lock;
375
376     /* The following properties cannot be changed when a device is running,
377      * so we remember the request and update them next time
378      * netdev_dpdk*_reconfigure() is called */
379     int requested_n_txq;
380     int requested_n_rxq;
381 };
382
383 struct netdev_rxq_dpdk {
384     struct netdev_rxq up;
385     int port_id;
386 };
387
388 static bool dpdk_thread_is_pmd(void);
389
390 static int netdev_dpdk_construct(struct netdev *);
391
392 struct virtio_net * netdev_dpdk_get_virtio(const struct netdev_dpdk *dev);
393
394 static bool
395 is_dpdk_class(const struct netdev_class *class)
396 {
397     return class->construct == netdev_dpdk_construct;
398 }
399
400 /* DPDK NIC drivers allocate RX buffers at a particular granularity, typically
401  * aligned at 1k or less. If a declared mbuf size is not a multiple of this
402  * value, insufficient buffers are allocated to accomodate the packet in its
403  * entirety. Furthermore, certain drivers need to ensure that there is also
404  * sufficient space in the Rx buffer to accommodate two VLAN tags (for QinQ
405  * frames). If the RX buffer is too small, then the driver enables scatter RX
406  * behaviour, which reduces performance. To prevent this, use a buffer size that
407  * is closest to 'mtu', but which satisfies the aforementioned criteria.
408  */
409 static uint32_t
410 dpdk_buf_size(int mtu)
411 {
412     return ROUND_UP((MTU_TO_MAX_FRAME_LEN(mtu) + RTE_PKTMBUF_HEADROOM),
413                      NETDEV_DPDK_MBUF_ALIGN);
414 }
415
416 /* XXX: use dpdk malloc for entire OVS. in fact huge page should be used
417  * for all other segments data, bss and text. */
418
419 static void *
420 dpdk_rte_mzalloc(size_t sz)
421 {
422     void *ptr;
423
424     ptr = rte_zmalloc(OVS_VPORT_DPDK, sz, OVS_CACHE_LINE_SIZE);
425     if (ptr == NULL) {
426         out_of_memory();
427     }
428     return ptr;
429 }
430
431 /* XXX this function should be called only by pmd threads (or by non pmd
432  * threads holding the nonpmd_mempool_mutex) */
433 void
434 free_dpdk_buf(struct dp_packet *p)
435 {
436     struct rte_mbuf *pkt = (struct rte_mbuf *) p;
437
438     rte_pktmbuf_free(pkt);
439 }
440
441 static void
442 ovs_rte_pktmbuf_init(struct rte_mempool *mp,
443                      void *opaque_arg OVS_UNUSED,
444                      void *_m,
445                      unsigned i OVS_UNUSED)
446 {
447     struct rte_mbuf *m = _m;
448
449     rte_pktmbuf_init(mp, opaque_arg, _m, i);
450
451     dp_packet_init_dpdk((struct dp_packet *) m, m->buf_len);
452 }
453
454 static struct dpdk_mp *
455 dpdk_mp_get(int socket_id, int mtu) OVS_REQUIRES(dpdk_mutex)
456 {
457     struct dpdk_mp *dmp = NULL;
458     char mp_name[RTE_MEMPOOL_NAMESIZE];
459     unsigned mp_size;
460     struct rte_pktmbuf_pool_private mbp_priv;
461
462     LIST_FOR_EACH (dmp, list_node, &dpdk_mp_list) {
463         if (dmp->socket_id == socket_id && dmp->mtu == mtu) {
464             dmp->refcount++;
465             return dmp;
466         }
467     }
468
469     dmp = dpdk_rte_mzalloc(sizeof *dmp);
470     dmp->socket_id = socket_id;
471     dmp->mtu = mtu;
472     dmp->refcount = 1;
473     mbp_priv.mbuf_data_room_size = MBUF_SIZE(mtu) - sizeof(struct dp_packet);
474     mbp_priv.mbuf_priv_size = sizeof (struct dp_packet) - sizeof (struct rte_mbuf);
475
476     mp_size = MAX_NB_MBUF;
477     do {
478         if (snprintf(mp_name, RTE_MEMPOOL_NAMESIZE, "ovs_mp_%d_%d_%u",
479                      dmp->mtu, dmp->socket_id, mp_size) < 0) {
480             return NULL;
481         }
482
483         dmp->mp = rte_mempool_create(mp_name, mp_size, MBUF_SIZE(mtu),
484                                      MP_CACHE_SZ,
485                                      sizeof(struct rte_pktmbuf_pool_private),
486                                      rte_pktmbuf_pool_init, &mbp_priv,
487                                      ovs_rte_pktmbuf_init, NULL,
488                                      socket_id, 0);
489     } while (!dmp->mp && rte_errno == ENOMEM && (mp_size /= 2) >= MIN_NB_MBUF);
490
491     if (dmp->mp == NULL) {
492         return NULL;
493     } else {
494         VLOG_DBG("Allocated \"%s\" mempool with %u mbufs", mp_name, mp_size );
495     }
496
497     ovs_list_push_back(&dpdk_mp_list, &dmp->list_node);
498     return dmp;
499 }
500
501 static void
502 dpdk_mp_put(struct dpdk_mp *dmp)
503 {
504
505     if (!dmp) {
506         return;
507     }
508
509     dmp->refcount--;
510     ovs_assert(dmp->refcount >= 0);
511
512 #if 0
513     /* I could not find any API to destroy mp. */
514     if (dmp->refcount == 0) {
515         list_delete(dmp->list_node);
516         /* destroy mp-pool. */
517     }
518 #endif
519 }
520
521 static void
522 check_link_status(struct netdev_dpdk *dev)
523 {
524     struct rte_eth_link link;
525
526     rte_eth_link_get_nowait(dev->port_id, &link);
527
528     if (dev->link.link_status != link.link_status) {
529         netdev_change_seq_changed(&dev->up);
530
531         dev->link_reset_cnt++;
532         dev->link = link;
533         if (dev->link.link_status) {
534             VLOG_DBG_RL(&rl, "Port %d Link Up - speed %u Mbps - %s",
535                         dev->port_id, (unsigned)dev->link.link_speed,
536                         (dev->link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
537                          ("full-duplex") : ("half-duplex"));
538         } else {
539             VLOG_DBG_RL(&rl, "Port %d Link Down", dev->port_id);
540         }
541     }
542 }
543
544 static void *
545 dpdk_watchdog(void *dummy OVS_UNUSED)
546 {
547     struct netdev_dpdk *dev;
548
549     pthread_detach(pthread_self());
550
551     for (;;) {
552         ovs_mutex_lock(&dpdk_mutex);
553         LIST_FOR_EACH (dev, list_node, &dpdk_list) {
554             ovs_mutex_lock(&dev->mutex);
555             check_link_status(dev);
556             ovs_mutex_unlock(&dev->mutex);
557         }
558         ovs_mutex_unlock(&dpdk_mutex);
559         xsleep(DPDK_PORT_WATCHDOG_INTERVAL);
560     }
561
562     return NULL;
563 }
564
565 static int
566 dpdk_eth_dev_queue_setup(struct netdev_dpdk *dev, int n_rxq, int n_txq)
567 {
568     int diag = 0;
569     int i;
570
571     /* A device may report more queues than it makes available (this has
572      * been observed for Intel xl710, which reserves some of them for
573      * SRIOV):  rte_eth_*_queue_setup will fail if a queue is not
574      * available.  When this happens we can retry the configuration
575      * and request less queues */
576     while (n_rxq && n_txq) {
577         if (diag) {
578             VLOG_INFO("Retrying setup with (rxq:%d txq:%d)", n_rxq, n_txq);
579         }
580
581         diag = rte_eth_dev_configure(dev->port_id, n_rxq, n_txq, &port_conf);
582         if (diag) {
583             break;
584         }
585
586         for (i = 0; i < n_txq; i++) {
587             diag = rte_eth_tx_queue_setup(dev->port_id, i, NIC_PORT_TX_Q_SIZE,
588                                           dev->socket_id, NULL);
589             if (diag) {
590                 VLOG_INFO("Interface %s txq(%d) setup error: %s",
591                           dev->up.name, i, rte_strerror(-diag));
592                 break;
593             }
594         }
595
596         if (i != n_txq) {
597             /* Retry with less tx queues */
598             n_txq = i;
599             continue;
600         }
601
602         for (i = 0; i < n_rxq; i++) {
603             diag = rte_eth_rx_queue_setup(dev->port_id, i, NIC_PORT_RX_Q_SIZE,
604                                           dev->socket_id, NULL,
605                                           dev->dpdk_mp->mp);
606             if (diag) {
607                 VLOG_INFO("Interface %s rxq(%d) setup error: %s",
608                           dev->up.name, i, rte_strerror(-diag));
609                 break;
610             }
611         }
612
613         if (i != n_rxq) {
614             /* Retry with less rx queues */
615             n_rxq = i;
616             continue;
617         }
618
619         dev->up.n_rxq = n_rxq;
620         dev->real_n_txq = n_txq;
621
622         return 0;
623     }
624
625     return diag;
626 }
627
628
629 static int
630 dpdk_eth_dev_init(struct netdev_dpdk *dev) OVS_REQUIRES(dpdk_mutex)
631 {
632     struct rte_pktmbuf_pool_private *mbp_priv;
633     struct rte_eth_dev_info info;
634     struct ether_addr eth_addr;
635     int diag;
636     int n_rxq, n_txq;
637
638     if (dev->port_id < 0 || dev->port_id >= rte_eth_dev_count()) {
639         return ENODEV;
640     }
641
642     rte_eth_dev_info_get(dev->port_id, &info);
643
644     n_rxq = MIN(info.max_rx_queues, dev->up.n_rxq);
645     n_txq = MIN(info.max_tx_queues, dev->up.n_txq);
646
647     diag = dpdk_eth_dev_queue_setup(dev, n_rxq, n_txq);
648     if (diag) {
649         VLOG_ERR("Interface %s(rxq:%d txq:%d) configure error: %s",
650                  dev->up.name, n_rxq, n_txq, rte_strerror(-diag));
651         return -diag;
652     }
653
654     diag = rte_eth_dev_start(dev->port_id);
655     if (diag) {
656         VLOG_ERR("Interface %s start error: %s", dev->up.name,
657                  rte_strerror(-diag));
658         return -diag;
659     }
660
661     rte_eth_promiscuous_enable(dev->port_id);
662     rte_eth_allmulticast_enable(dev->port_id);
663
664     memset(&eth_addr, 0x0, sizeof(eth_addr));
665     rte_eth_macaddr_get(dev->port_id, &eth_addr);
666     VLOG_INFO_RL(&rl, "Port %d: "ETH_ADDR_FMT"",
667                     dev->port_id, ETH_ADDR_BYTES_ARGS(eth_addr.addr_bytes));
668
669     memcpy(dev->hwaddr.ea, eth_addr.addr_bytes, ETH_ADDR_LEN);
670     rte_eth_link_get_nowait(dev->port_id, &dev->link);
671
672     mbp_priv = rte_mempool_get_priv(dev->dpdk_mp->mp);
673     dev->buf_size = mbp_priv->mbuf_data_room_size - RTE_PKTMBUF_HEADROOM;
674
675     dev->flags = NETDEV_UP | NETDEV_PROMISC;
676     return 0;
677 }
678
679 static struct netdev_dpdk *
680 netdev_dpdk_cast(const struct netdev *netdev)
681 {
682     return CONTAINER_OF(netdev, struct netdev_dpdk, up);
683 }
684
685 static struct netdev *
686 netdev_dpdk_alloc(void)
687 {
688     struct netdev_dpdk *dev;
689
690     if (!rte_eal_init_ret) { /* Only after successful initialization */
691         dev = dpdk_rte_mzalloc(sizeof *dev);
692         if (dev) {
693             return &dev->up;
694         }
695     }
696     return NULL;
697 }
698
699 static void
700 netdev_dpdk_alloc_txq(struct netdev_dpdk *dev, unsigned int n_txqs)
701 {
702     unsigned i;
703
704     dev->tx_q = dpdk_rte_mzalloc(n_txqs * sizeof *dev->tx_q);
705     for (i = 0; i < n_txqs; i++) {
706         int numa_id = ovs_numa_get_numa_id(i);
707
708         if (!dev->txq_needs_locking) {
709             /* Each index is considered as a cpu core id, since there should
710              * be one tx queue for each cpu core.  If the corresponding core
711              * is not on the same numa node as 'dev', flags the
712              * 'flush_tx'. */
713             dev->tx_q[i].flush_tx = dev->socket_id == numa_id;
714         } else {
715             /* Queues are shared among CPUs. Always flush */
716             dev->tx_q[i].flush_tx = true;
717         }
718
719         /* Initialize map for vhost devices. */
720         dev->tx_q[i].map = OVS_VHOST_QUEUE_MAP_UNKNOWN;
721         rte_spinlock_init(&dev->tx_q[i].tx_lock);
722     }
723 }
724
725 static int
726 netdev_dpdk_init(struct netdev *netdev, unsigned int port_no,
727                  enum dpdk_dev_type type)
728     OVS_REQUIRES(dpdk_mutex)
729 {
730     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
731     int sid;
732     int err = 0;
733     uint32_t buf_size;
734
735     ovs_mutex_init(&dev->mutex);
736     ovs_mutex_lock(&dev->mutex);
737
738     rte_spinlock_init(&dev->stats_lock);
739
740     /* If the 'sid' is negative, it means that the kernel fails
741      * to obtain the pci numa info.  In that situation, always
742      * use 'SOCKET0'. */
743     if (type == DPDK_DEV_ETH) {
744         sid = rte_eth_dev_socket_id(port_no);
745     } else {
746         sid = rte_lcore_to_socket_id(rte_get_master_lcore());
747     }
748
749     dev->socket_id = sid < 0 ? SOCKET0 : sid;
750     dev->port_id = port_no;
751     dev->type = type;
752     dev->flags = 0;
753     dev->mtu = ETHER_MTU;
754     dev->max_packet_len = MTU_TO_FRAME_LEN(dev->mtu);
755
756     buf_size = dpdk_buf_size(dev->mtu);
757     dev->dpdk_mp = dpdk_mp_get(dev->socket_id, FRAME_LEN_TO_MTU(buf_size));
758     if (!dev->dpdk_mp) {
759         err = ENOMEM;
760         goto unlock;
761     }
762
763     /* Initialise QoS configuration to NULL and qos lock to unlocked */
764     dev->qos_conf = NULL;
765     rte_spinlock_init(&dev->qos_lock);
766
767     netdev->n_txq = NR_QUEUE;
768     netdev->n_rxq = NR_QUEUE;
769     dev->requested_n_rxq = NR_QUEUE;
770     dev->requested_n_txq = NR_QUEUE;
771     dev->real_n_txq = NR_QUEUE;
772
773     if (type == DPDK_DEV_ETH) {
774         netdev_dpdk_alloc_txq(dev, NR_QUEUE);
775         err = dpdk_eth_dev_init(dev);
776         if (err) {
777             goto unlock;
778         }
779     } else {
780         netdev_dpdk_alloc_txq(dev, OVS_VHOST_MAX_QUEUE_NUM);
781     }
782
783     ovs_list_push_back(&dpdk_list, &dev->list_node);
784
785 unlock:
786     if (err) {
787         rte_free(dev->tx_q);
788     }
789     ovs_mutex_unlock(&dev->mutex);
790     return err;
791 }
792
793 /* dev_name must be the prefix followed by a positive decimal number.
794  * (no leading + or - signs are allowed) */
795 static int
796 dpdk_dev_parse_name(const char dev_name[], const char prefix[],
797                     unsigned int *port_no)
798 {
799     const char *cport;
800
801     if (strncmp(dev_name, prefix, strlen(prefix))) {
802         return ENODEV;
803     }
804
805     cport = dev_name + strlen(prefix);
806
807     if (str_to_uint(cport, 10, port_no)) {
808         return 0;
809     } else {
810         return ENODEV;
811     }
812 }
813
814 static int
815 vhost_construct_helper(struct netdev *netdev) OVS_REQUIRES(dpdk_mutex)
816 {
817     if (rte_eal_init_ret) {
818         return rte_eal_init_ret;
819     }
820
821     return netdev_dpdk_init(netdev, -1, DPDK_DEV_VHOST);
822 }
823
824 static int
825 netdev_dpdk_vhost_cuse_construct(struct netdev *netdev)
826 {
827     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
828     int err;
829
830     if (rte_eal_init_ret) {
831         return rte_eal_init_ret;
832     }
833
834     ovs_mutex_lock(&dpdk_mutex);
835     strncpy(dev->vhost_id, netdev->name, sizeof(dev->vhost_id));
836     err = vhost_construct_helper(netdev);
837     ovs_mutex_unlock(&dpdk_mutex);
838     return err;
839 }
840
841 static int
842 netdev_dpdk_vhost_user_construct(struct netdev *netdev)
843 {
844     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
845     const char *name = netdev->name;
846     int err;
847
848     /* 'name' is appended to 'vhost_sock_dir' and used to create a socket in
849      * the file system. '/' or '\' would traverse directories, so they're not
850      * acceptable in 'name'. */
851     if (strchr(name, '/') || strchr(name, '\\')) {
852         VLOG_ERR("\"%s\" is not a valid name for a vhost-user port. "
853                  "A valid name must not include '/' or '\\'",
854                  name);
855         return EINVAL;
856     }
857
858     if (rte_eal_init_ret) {
859         return rte_eal_init_ret;
860     }
861
862     ovs_mutex_lock(&dpdk_mutex);
863     /* Take the name of the vhost-user port and append it to the location where
864      * the socket is to be created, then register the socket.
865      */
866     snprintf(dev->vhost_id, sizeof(dev->vhost_id), "%s/%s",
867              vhost_sock_dir, name);
868
869     err = rte_vhost_driver_register(dev->vhost_id);
870     if (err) {
871         VLOG_ERR("vhost-user socket device setup failure for socket %s\n",
872                  dev->vhost_id);
873     } else {
874         fatal_signal_add_file_to_unlink(dev->vhost_id);
875         VLOG_INFO("Socket %s created for vhost-user port %s\n",
876                   dev->vhost_id, name);
877         err = vhost_construct_helper(netdev);
878     }
879
880     ovs_mutex_unlock(&dpdk_mutex);
881     return err;
882 }
883
884 static int
885 netdev_dpdk_construct(struct netdev *netdev)
886 {
887     unsigned int port_no;
888     int err;
889
890     if (rte_eal_init_ret) {
891         return rte_eal_init_ret;
892     }
893
894     /* Names always start with "dpdk" */
895     err = dpdk_dev_parse_name(netdev->name, "dpdk", &port_no);
896     if (err) {
897         return err;
898     }
899
900     ovs_mutex_lock(&dpdk_mutex);
901     err = netdev_dpdk_init(netdev, port_no, DPDK_DEV_ETH);
902     ovs_mutex_unlock(&dpdk_mutex);
903     return err;
904 }
905
906 static void
907 netdev_dpdk_destruct(struct netdev *netdev)
908 {
909     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
910
911     ovs_mutex_lock(&dev->mutex);
912     rte_eth_dev_stop(dev->port_id);
913     ovs_mutex_unlock(&dev->mutex);
914
915     ovs_mutex_lock(&dpdk_mutex);
916     rte_free(dev->tx_q);
917     ovs_list_remove(&dev->list_node);
918     dpdk_mp_put(dev->dpdk_mp);
919     ovs_mutex_unlock(&dpdk_mutex);
920 }
921
922 static void
923 netdev_dpdk_vhost_destruct(struct netdev *netdev)
924 {
925     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
926
927     /* Guest becomes an orphan if still attached. */
928     if (netdev_dpdk_get_virtio(dev) != NULL) {
929         VLOG_ERR("Removing port '%s' while vhost device still attached.",
930                  netdev->name);
931         VLOG_ERR("To restore connectivity after re-adding of port, VM on socket"
932                  " '%s' must be restarted.",
933                  dev->vhost_id);
934     }
935
936     if (rte_vhost_driver_unregister(dev->vhost_id)) {
937         VLOG_ERR("Unable to remove vhost-user socket %s", dev->vhost_id);
938     } else {
939         fatal_signal_remove_file_to_unlink(dev->vhost_id);
940     }
941
942     ovs_mutex_lock(&dpdk_mutex);
943     rte_free(dev->tx_q);
944     ovs_list_remove(&dev->list_node);
945     dpdk_mp_put(dev->dpdk_mp);
946     ovs_mutex_unlock(&dpdk_mutex);
947 }
948
949 static void
950 netdev_dpdk_dealloc(struct netdev *netdev)
951 {
952     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
953
954     rte_free(dev);
955 }
956
957 static int
958 netdev_dpdk_get_config(const struct netdev *netdev, struct smap *args)
959 {
960     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
961
962     ovs_mutex_lock(&dev->mutex);
963
964     smap_add_format(args, "requested_rx_queues", "%d", dev->requested_n_rxq);
965     smap_add_format(args, "configured_rx_queues", "%d", netdev->n_rxq);
966     smap_add_format(args, "requested_tx_queues", "%d", netdev->n_txq);
967     smap_add_format(args, "configured_tx_queues", "%d", dev->real_n_txq);
968     ovs_mutex_unlock(&dev->mutex);
969
970     return 0;
971 }
972
973 static int
974 netdev_dpdk_set_config(struct netdev *netdev, const struct smap *args)
975 {
976     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
977     int new_n_rxq;
978
979     ovs_mutex_lock(&dev->mutex);
980     new_n_rxq = MAX(smap_get_int(args, "n_rxq", dev->requested_n_rxq), 1);
981     if (new_n_rxq != dev->requested_n_rxq) {
982         dev->requested_n_rxq = new_n_rxq;
983         netdev_request_reconfigure(netdev);
984     }
985     ovs_mutex_unlock(&dev->mutex);
986
987     return 0;
988 }
989
990 static int
991 netdev_dpdk_get_numa_id(const struct netdev *netdev)
992 {
993     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
994
995     return dev->socket_id;
996 }
997
998 /* Sets the number of tx queues for the dpdk interface. */
999 static int
1000 netdev_dpdk_set_tx_multiq(struct netdev *netdev, unsigned int n_txq)
1001 {
1002     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1003
1004     ovs_mutex_lock(&dev->mutex);
1005
1006     if (dev->requested_n_txq == n_txq) {
1007         goto out;
1008     }
1009
1010     dev->requested_n_txq = n_txq;
1011     netdev_request_reconfigure(netdev);
1012
1013 out:
1014     ovs_mutex_unlock(&dev->mutex);
1015     return 0;
1016 }
1017
1018 static struct netdev_rxq *
1019 netdev_dpdk_rxq_alloc(void)
1020 {
1021     struct netdev_rxq_dpdk *rx = dpdk_rte_mzalloc(sizeof *rx);
1022
1023     return &rx->up;
1024 }
1025
1026 static struct netdev_rxq_dpdk *
1027 netdev_rxq_dpdk_cast(const struct netdev_rxq *rxq)
1028 {
1029     return CONTAINER_OF(rxq, struct netdev_rxq_dpdk, up);
1030 }
1031
1032 static int
1033 netdev_dpdk_rxq_construct(struct netdev_rxq *rxq)
1034 {
1035     struct netdev_rxq_dpdk *rx = netdev_rxq_dpdk_cast(rxq);
1036     struct netdev_dpdk *dev = netdev_dpdk_cast(rxq->netdev);
1037
1038     ovs_mutex_lock(&dev->mutex);
1039     rx->port_id = dev->port_id;
1040     ovs_mutex_unlock(&dev->mutex);
1041
1042     return 0;
1043 }
1044
1045 static void
1046 netdev_dpdk_rxq_destruct(struct netdev_rxq *rxq OVS_UNUSED)
1047 {
1048 }
1049
1050 static void
1051 netdev_dpdk_rxq_dealloc(struct netdev_rxq *rxq)
1052 {
1053     struct netdev_rxq_dpdk *rx = netdev_rxq_dpdk_cast(rxq);
1054
1055     rte_free(rx);
1056 }
1057
1058 static inline void
1059 dpdk_queue_flush__(struct netdev_dpdk *dev, int qid)
1060 {
1061     struct dpdk_tx_queue *txq = &dev->tx_q[qid];
1062     uint32_t nb_tx = 0;
1063
1064     while (nb_tx != txq->count) {
1065         uint32_t ret;
1066
1067         ret = rte_eth_tx_burst(dev->port_id, qid, txq->burst_pkts + nb_tx,
1068                                txq->count - nb_tx);
1069         if (!ret) {
1070             break;
1071         }
1072
1073         nb_tx += ret;
1074     }
1075
1076     if (OVS_UNLIKELY(nb_tx != txq->count)) {
1077         /* free buffers, which we couldn't transmit, one at a time (each
1078          * packet could come from a different mempool) */
1079         int i;
1080
1081         for (i = nb_tx; i < txq->count; i++) {
1082             rte_pktmbuf_free(txq->burst_pkts[i]);
1083         }
1084         rte_spinlock_lock(&dev->stats_lock);
1085         dev->stats.tx_dropped += txq->count-nb_tx;
1086         rte_spinlock_unlock(&dev->stats_lock);
1087     }
1088
1089     txq->count = 0;
1090     txq->tsc = rte_get_timer_cycles();
1091 }
1092
1093 static inline void
1094 dpdk_queue_flush(struct netdev_dpdk *dev, int qid)
1095 {
1096     struct dpdk_tx_queue *txq = &dev->tx_q[qid];
1097
1098     if (txq->count == 0) {
1099         return;
1100     }
1101     dpdk_queue_flush__(dev, qid);
1102 }
1103
1104 static inline bool
1105 netdev_dpdk_policer_pkt_handle(struct rte_meter_srtcm *meter,
1106                                struct rte_mbuf *pkt, uint64_t time)
1107 {
1108     uint32_t pkt_len = rte_pktmbuf_pkt_len(pkt) - sizeof(struct ether_hdr);
1109
1110     return rte_meter_srtcm_color_blind_check(meter, time, pkt_len) ==
1111                                                 e_RTE_METER_GREEN;
1112 }
1113
1114 static int
1115 netdev_dpdk_policer_run(struct rte_meter_srtcm *meter,
1116                         struct rte_mbuf **pkts, int pkt_cnt)
1117 {
1118     int i = 0;
1119     int cnt = 0;
1120     struct rte_mbuf *pkt = NULL;
1121     uint64_t current_time = rte_rdtsc();
1122
1123     for (i = 0; i < pkt_cnt; i++) {
1124         pkt = pkts[i];
1125         /* Handle current packet */
1126         if (netdev_dpdk_policer_pkt_handle(meter, pkt, current_time)) {
1127             if (cnt != i) {
1128                 pkts[cnt] = pkt;
1129             }
1130             cnt++;
1131         } else {
1132             rte_pktmbuf_free(pkt);
1133         }
1134     }
1135
1136     return cnt;
1137 }
1138
1139 static bool
1140 is_vhost_running(struct virtio_net *virtio_dev)
1141 {
1142     return (virtio_dev != NULL && (virtio_dev->flags & VIRTIO_DEV_RUNNING));
1143 }
1144
1145 static inline void
1146 netdev_dpdk_vhost_update_rx_size_counters(struct netdev_stats *stats,
1147                                           unsigned int packet_size)
1148 {
1149     /* Hard-coded search for the size bucket. */
1150     if (packet_size < 256) {
1151         if (packet_size >= 128) {
1152             stats->rx_128_to_255_packets++;
1153         } else if (packet_size <= 64) {
1154             stats->rx_1_to_64_packets++;
1155         } else {
1156             stats->rx_65_to_127_packets++;
1157         }
1158     } else {
1159         if (packet_size >= 1523) {
1160             stats->rx_1523_to_max_packets++;
1161         } else if (packet_size >= 1024) {
1162             stats->rx_1024_to_1522_packets++;
1163         } else if (packet_size < 512) {
1164             stats->rx_256_to_511_packets++;
1165         } else {
1166             stats->rx_512_to_1023_packets++;
1167         }
1168     }
1169 }
1170
1171 static inline void
1172 netdev_dpdk_vhost_update_rx_counters(struct netdev_stats *stats,
1173                                      struct dp_packet **packets, int count)
1174 {
1175     int i;
1176     unsigned int packet_size;
1177     struct dp_packet *packet;
1178
1179     stats->rx_packets += count;
1180     for (i = 0; i < count; i++) {
1181         packet = packets[i];
1182         packet_size = dp_packet_size(packet);
1183
1184         if (OVS_UNLIKELY(packet_size < ETH_HEADER_LEN)) {
1185             /* This only protects the following multicast counting from
1186              * too short packets, but it does not stop the packet from
1187              * further processing. */
1188             stats->rx_errors++;
1189             stats->rx_length_errors++;
1190             continue;
1191         }
1192
1193         netdev_dpdk_vhost_update_rx_size_counters(stats, packet_size);
1194
1195         struct eth_header *eh = (struct eth_header *) dp_packet_data(packet);
1196         if (OVS_UNLIKELY(eth_addr_is_multicast(eh->eth_dst))) {
1197             stats->multicast++;
1198         }
1199
1200         stats->rx_bytes += packet_size;
1201     }
1202 }
1203
1204 /*
1205  * The receive path for the vhost port is the TX path out from guest.
1206  */
1207 static int
1208 netdev_dpdk_vhost_rxq_recv(struct netdev_rxq *rxq,
1209                            struct dp_packet **packets, int *c)
1210 {
1211     struct netdev_dpdk *dev = netdev_dpdk_cast(rxq->netdev);
1212     struct virtio_net *virtio_dev = netdev_dpdk_get_virtio(dev);
1213     int qid = rxq->queue_id;
1214     uint16_t nb_rx = 0;
1215
1216     if (OVS_UNLIKELY(!is_vhost_running(virtio_dev))) {
1217         return EAGAIN;
1218     }
1219
1220     if (rxq->queue_id >= dev->real_n_rxq) {
1221         return EOPNOTSUPP;
1222     }
1223
1224     nb_rx = rte_vhost_dequeue_burst(virtio_dev, qid * VIRTIO_QNUM + VIRTIO_TXQ,
1225                                     dev->dpdk_mp->mp,
1226                                     (struct rte_mbuf **)packets,
1227                                     NETDEV_MAX_BURST);
1228     if (!nb_rx) {
1229         return EAGAIN;
1230     }
1231
1232     rte_spinlock_lock(&dev->stats_lock);
1233     netdev_dpdk_vhost_update_rx_counters(&dev->stats, packets, nb_rx);
1234     rte_spinlock_unlock(&dev->stats_lock);
1235
1236     *c = (int) nb_rx;
1237     return 0;
1238 }
1239
1240 static int
1241 netdev_dpdk_rxq_recv(struct netdev_rxq *rxq, struct dp_packet **packets,
1242                      int *c)
1243 {
1244     struct netdev_rxq_dpdk *rx = netdev_rxq_dpdk_cast(rxq);
1245     struct netdev_dpdk *dev = netdev_dpdk_cast(rxq->netdev);
1246     int nb_rx;
1247
1248     /* There is only one tx queue for this core.  Do not flush other
1249      * queues.
1250      * Do not flush tx queue which is shared among CPUs
1251      * since it is always flushed */
1252     if (rxq->queue_id == rte_lcore_id() &&
1253         OVS_LIKELY(!dev->txq_needs_locking)) {
1254         dpdk_queue_flush(dev, rxq->queue_id);
1255     }
1256
1257     nb_rx = rte_eth_rx_burst(rx->port_id, rxq->queue_id,
1258                              (struct rte_mbuf **) packets,
1259                              NETDEV_MAX_BURST);
1260     if (!nb_rx) {
1261         return EAGAIN;
1262     }
1263
1264     *c = nb_rx;
1265
1266     return 0;
1267 }
1268
1269 static inline int
1270 netdev_dpdk_qos_run__(struct netdev_dpdk *dev, struct rte_mbuf **pkts,
1271                         int cnt)
1272 {
1273     struct netdev *netdev = &dev->up;
1274
1275     if (dev->qos_conf != NULL) {
1276         rte_spinlock_lock(&dev->qos_lock);
1277         if (dev->qos_conf != NULL) {
1278             cnt = dev->qos_conf->ops->qos_run(netdev, pkts, cnt);
1279         }
1280         rte_spinlock_unlock(&dev->qos_lock);
1281     }
1282
1283     return cnt;
1284 }
1285
1286 static inline void
1287 netdev_dpdk_vhost_update_tx_counters(struct netdev_stats *stats,
1288                                      struct dp_packet **packets,
1289                                      int attempted,
1290                                      int dropped)
1291 {
1292     int i;
1293     int sent = attempted - dropped;
1294
1295     stats->tx_packets += sent;
1296     stats->tx_dropped += dropped;
1297
1298     for (i = 0; i < sent; i++) {
1299         stats->tx_bytes += dp_packet_size(packets[i]);
1300     }
1301 }
1302
1303 static void
1304 __netdev_dpdk_vhost_send(struct netdev *netdev, int qid,
1305                          struct dp_packet **pkts, int cnt,
1306                          bool may_steal)
1307 {
1308     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1309     struct virtio_net *virtio_dev = netdev_dpdk_get_virtio(dev);
1310     struct rte_mbuf **cur_pkts = (struct rte_mbuf **) pkts;
1311     unsigned int total_pkts = cnt;
1312     unsigned int qos_pkts = cnt;
1313     uint64_t start = 0;
1314
1315     qid = dev->tx_q[qid % dev->real_n_txq].map;
1316
1317     if (OVS_UNLIKELY(!is_vhost_running(virtio_dev) || qid < 0)) {
1318         rte_spinlock_lock(&dev->stats_lock);
1319         dev->stats.tx_dropped+= cnt;
1320         rte_spinlock_unlock(&dev->stats_lock);
1321         goto out;
1322     }
1323
1324     rte_spinlock_lock(&dev->tx_q[qid].tx_lock);
1325
1326     /* Check has QoS has been configured for the netdev */
1327     cnt = netdev_dpdk_qos_run__(dev, cur_pkts, cnt);
1328     qos_pkts -= cnt;
1329
1330     do {
1331         int vhost_qid = qid * VIRTIO_QNUM + VIRTIO_RXQ;
1332         unsigned int tx_pkts;
1333
1334         tx_pkts = rte_vhost_enqueue_burst(virtio_dev, vhost_qid,
1335                                           cur_pkts, cnt);
1336         if (OVS_LIKELY(tx_pkts)) {
1337             /* Packets have been sent.*/
1338             cnt -= tx_pkts;
1339             /* Prepare for possible next iteration.*/
1340             cur_pkts = &cur_pkts[tx_pkts];
1341         } else {
1342             uint64_t timeout = VHOST_ENQ_RETRY_USECS * rte_get_timer_hz() / 1E6;
1343             unsigned int expired = 0;
1344
1345             if (!start) {
1346                 start = rte_get_timer_cycles();
1347             }
1348
1349             /*
1350              * Unable to enqueue packets to vhost interface.
1351              * Check available entries before retrying.
1352              */
1353             while (!rte_vring_available_entries(virtio_dev, vhost_qid)) {
1354                 if (OVS_UNLIKELY((rte_get_timer_cycles() - start) > timeout)) {
1355                     expired = 1;
1356                     break;
1357                 }
1358             }
1359             if (expired) {
1360                 /* break out of main loop. */
1361                 break;
1362             }
1363         }
1364     } while (cnt);
1365
1366     rte_spinlock_unlock(&dev->tx_q[qid].tx_lock);
1367
1368     rte_spinlock_lock(&dev->stats_lock);
1369     cnt += qos_pkts;
1370     netdev_dpdk_vhost_update_tx_counters(&dev->stats, pkts, total_pkts, cnt);
1371     rte_spinlock_unlock(&dev->stats_lock);
1372
1373 out:
1374     if (may_steal) {
1375         int i;
1376
1377         for (i = 0; i < total_pkts; i++) {
1378             dp_packet_delete(pkts[i]);
1379         }
1380     }
1381 }
1382
1383 inline static void
1384 dpdk_queue_pkts(struct netdev_dpdk *dev, int qid,
1385                struct rte_mbuf **pkts, int cnt)
1386 {
1387     struct dpdk_tx_queue *txq = &dev->tx_q[qid];
1388     uint64_t diff_tsc;
1389
1390     int i = 0;
1391
1392     while (i < cnt) {
1393         int freeslots = MAX_TX_QUEUE_LEN - txq->count;
1394         int tocopy = MIN(freeslots, cnt-i);
1395
1396         memcpy(&txq->burst_pkts[txq->count], &pkts[i],
1397                tocopy * sizeof (struct rte_mbuf *));
1398
1399         txq->count += tocopy;
1400         i += tocopy;
1401
1402         if (txq->count == MAX_TX_QUEUE_LEN || txq->flush_tx) {
1403             dpdk_queue_flush__(dev, qid);
1404         }
1405         diff_tsc = rte_get_timer_cycles() - txq->tsc;
1406         if (diff_tsc >= DRAIN_TSC) {
1407             dpdk_queue_flush__(dev, qid);
1408         }
1409     }
1410 }
1411
1412 /* Tx function. Transmit packets indefinitely */
1413 static void
1414 dpdk_do_tx_copy(struct netdev *netdev, int qid, struct dp_packet **pkts,
1415                 int cnt)
1416     OVS_NO_THREAD_SAFETY_ANALYSIS
1417 {
1418 #if !defined(__CHECKER__) && !defined(_WIN32)
1419     const size_t PKT_ARRAY_SIZE = cnt;
1420 #else
1421     /* Sparse or MSVC doesn't like variable length array. */
1422     enum { PKT_ARRAY_SIZE = NETDEV_MAX_BURST };
1423 #endif
1424     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1425     struct rte_mbuf *mbufs[PKT_ARRAY_SIZE];
1426     int dropped = 0;
1427     int newcnt = 0;
1428     int i;
1429
1430     /* If we are on a non pmd thread we have to use the mempool mutex, because
1431      * every non pmd thread shares the same mempool cache */
1432
1433     if (!dpdk_thread_is_pmd()) {
1434         ovs_mutex_lock(&nonpmd_mempool_mutex);
1435     }
1436
1437     for (i = 0; i < cnt; i++) {
1438         int size = dp_packet_size(pkts[i]);
1439
1440         if (OVS_UNLIKELY(size > dev->max_packet_len)) {
1441             VLOG_WARN_RL(&rl, "Too big size %d max_packet_len %d",
1442                          (int)size , dev->max_packet_len);
1443
1444             dropped++;
1445             continue;
1446         }
1447
1448         mbufs[newcnt] = rte_pktmbuf_alloc(dev->dpdk_mp->mp);
1449
1450         if (!mbufs[newcnt]) {
1451             dropped += cnt - i;
1452             break;
1453         }
1454
1455         /* We have to do a copy for now */
1456         memcpy(rte_pktmbuf_mtod(mbufs[newcnt], void *), dp_packet_data(pkts[i]), size);
1457
1458         rte_pktmbuf_data_len(mbufs[newcnt]) = size;
1459         rte_pktmbuf_pkt_len(mbufs[newcnt]) = size;
1460
1461         newcnt++;
1462     }
1463
1464     if (dev->type == DPDK_DEV_VHOST) {
1465         __netdev_dpdk_vhost_send(netdev, qid, (struct dp_packet **) mbufs, newcnt, true);
1466     } else {
1467         unsigned int qos_pkts = newcnt;
1468
1469         /* Check if QoS has been configured for this netdev. */
1470         newcnt = netdev_dpdk_qos_run__(dev, mbufs, newcnt);
1471
1472         dropped += qos_pkts - newcnt;
1473         dpdk_queue_pkts(dev, qid, mbufs, newcnt);
1474         dpdk_queue_flush(dev, qid);
1475     }
1476
1477     if (OVS_UNLIKELY(dropped)) {
1478         rte_spinlock_lock(&dev->stats_lock);
1479         dev->stats.tx_dropped += dropped;
1480         rte_spinlock_unlock(&dev->stats_lock);
1481     }
1482
1483     if (!dpdk_thread_is_pmd()) {
1484         ovs_mutex_unlock(&nonpmd_mempool_mutex);
1485     }
1486 }
1487
1488 static int
1489 netdev_dpdk_vhost_send(struct netdev *netdev, int qid, struct dp_packet **pkts,
1490                  int cnt, bool may_steal)
1491 {
1492     if (OVS_UNLIKELY(pkts[0]->source != DPBUF_DPDK)) {
1493         int i;
1494
1495         dpdk_do_tx_copy(netdev, qid, pkts, cnt);
1496         if (may_steal) {
1497             for (i = 0; i < cnt; i++) {
1498                 dp_packet_delete(pkts[i]);
1499             }
1500         }
1501     } else {
1502         __netdev_dpdk_vhost_send(netdev, qid, pkts, cnt, may_steal);
1503     }
1504     return 0;
1505 }
1506
1507 static inline void
1508 netdev_dpdk_send__(struct netdev_dpdk *dev, int qid,
1509                    struct dp_packet **pkts, int cnt, bool may_steal)
1510 {
1511     int i;
1512
1513     if (OVS_UNLIKELY(dev->txq_needs_locking)) {
1514         qid = qid % dev->real_n_txq;
1515         rte_spinlock_lock(&dev->tx_q[qid].tx_lock);
1516     }
1517
1518     if (OVS_UNLIKELY(!may_steal ||
1519                      pkts[0]->source != DPBUF_DPDK)) {
1520         struct netdev *netdev = &dev->up;
1521
1522         dpdk_do_tx_copy(netdev, qid, pkts, cnt);
1523
1524         if (may_steal) {
1525             for (i = 0; i < cnt; i++) {
1526                 dp_packet_delete(pkts[i]);
1527             }
1528         }
1529     } else {
1530         int next_tx_idx = 0;
1531         int dropped = 0;
1532         unsigned int qos_pkts = 0;
1533         unsigned int temp_cnt = 0;
1534
1535         for (i = 0; i < cnt; i++) {
1536             int size = dp_packet_size(pkts[i]);
1537
1538             if (OVS_UNLIKELY(size > dev->max_packet_len)) {
1539                 if (next_tx_idx != i) {
1540                     temp_cnt = i - next_tx_idx;
1541                     qos_pkts = temp_cnt;
1542
1543                     temp_cnt = netdev_dpdk_qos_run__(dev, (struct rte_mbuf**)pkts,
1544                                                 temp_cnt);
1545                     dropped += qos_pkts - temp_cnt;
1546                     dpdk_queue_pkts(dev, qid,
1547                                     (struct rte_mbuf **)&pkts[next_tx_idx],
1548                                     temp_cnt);
1549
1550                 }
1551
1552                 VLOG_WARN_RL(&rl, "Too big size %d max_packet_len %d",
1553                              (int)size , dev->max_packet_len);
1554
1555                 dp_packet_delete(pkts[i]);
1556                 dropped++;
1557                 next_tx_idx = i + 1;
1558             }
1559         }
1560         if (next_tx_idx != cnt) {
1561             cnt -= next_tx_idx;
1562             qos_pkts = cnt;
1563
1564             cnt = netdev_dpdk_qos_run__(dev, (struct rte_mbuf**)pkts, cnt);
1565             dropped += qos_pkts - cnt;
1566             dpdk_queue_pkts(dev, qid, (struct rte_mbuf **)&pkts[next_tx_idx],
1567                             cnt);
1568         }
1569
1570         if (OVS_UNLIKELY(dropped)) {
1571             rte_spinlock_lock(&dev->stats_lock);
1572             dev->stats.tx_dropped += dropped;
1573             rte_spinlock_unlock(&dev->stats_lock);
1574         }
1575     }
1576
1577     if (OVS_UNLIKELY(dev->txq_needs_locking)) {
1578         rte_spinlock_unlock(&dev->tx_q[qid].tx_lock);
1579     }
1580 }
1581
1582 static int
1583 netdev_dpdk_eth_send(struct netdev *netdev, int qid,
1584                      struct dp_packet **pkts, int cnt, bool may_steal)
1585 {
1586     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1587
1588     netdev_dpdk_send__(dev, qid, pkts, cnt, may_steal);
1589     return 0;
1590 }
1591
1592 static int
1593 netdev_dpdk_set_etheraddr(struct netdev *netdev, const struct eth_addr mac)
1594 {
1595     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1596
1597     ovs_mutex_lock(&dev->mutex);
1598     if (!eth_addr_equals(dev->hwaddr, mac)) {
1599         dev->hwaddr = mac;
1600         netdev_change_seq_changed(netdev);
1601     }
1602     ovs_mutex_unlock(&dev->mutex);
1603
1604     return 0;
1605 }
1606
1607 static int
1608 netdev_dpdk_get_etheraddr(const struct netdev *netdev, struct eth_addr *mac)
1609 {
1610     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1611
1612     ovs_mutex_lock(&dev->mutex);
1613     *mac = dev->hwaddr;
1614     ovs_mutex_unlock(&dev->mutex);
1615
1616     return 0;
1617 }
1618
1619 static int
1620 netdev_dpdk_get_mtu(const struct netdev *netdev, int *mtup)
1621 {
1622     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1623
1624     ovs_mutex_lock(&dev->mutex);
1625     *mtup = dev->mtu;
1626     ovs_mutex_unlock(&dev->mutex);
1627
1628     return 0;
1629 }
1630
1631 static int
1632 netdev_dpdk_set_mtu(const struct netdev *netdev, int mtu)
1633 {
1634     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1635     int old_mtu, err, dpdk_mtu;
1636     struct dpdk_mp *old_mp;
1637     struct dpdk_mp *mp;
1638     uint32_t buf_size;
1639
1640     ovs_mutex_lock(&dpdk_mutex);
1641     ovs_mutex_lock(&dev->mutex);
1642     if (dev->mtu == mtu) {
1643         err = 0;
1644         goto out;
1645     }
1646
1647     buf_size = dpdk_buf_size(mtu);
1648     dpdk_mtu = FRAME_LEN_TO_MTU(buf_size);
1649
1650     mp = dpdk_mp_get(dev->socket_id, dpdk_mtu);
1651     if (!mp) {
1652         err = ENOMEM;
1653         goto out;
1654     }
1655
1656     rte_eth_dev_stop(dev->port_id);
1657
1658     old_mtu = dev->mtu;
1659     old_mp = dev->dpdk_mp;
1660     dev->dpdk_mp = mp;
1661     dev->mtu = mtu;
1662     dev->max_packet_len = MTU_TO_FRAME_LEN(dev->mtu);
1663
1664     err = dpdk_eth_dev_init(dev);
1665     if (err) {
1666         dpdk_mp_put(mp);
1667         dev->mtu = old_mtu;
1668         dev->dpdk_mp = old_mp;
1669         dev->max_packet_len = MTU_TO_FRAME_LEN(dev->mtu);
1670         dpdk_eth_dev_init(dev);
1671         goto out;
1672     }
1673
1674     dpdk_mp_put(old_mp);
1675     netdev_change_seq_changed(netdev);
1676 out:
1677     ovs_mutex_unlock(&dev->mutex);
1678     ovs_mutex_unlock(&dpdk_mutex);
1679     return err;
1680 }
1681
1682 static int
1683 netdev_dpdk_get_carrier(const struct netdev *netdev, bool *carrier);
1684
1685 static int
1686 netdev_dpdk_vhost_get_stats(const struct netdev *netdev,
1687                             struct netdev_stats *stats)
1688 {
1689     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1690
1691     ovs_mutex_lock(&dev->mutex);
1692
1693     rte_spinlock_lock(&dev->stats_lock);
1694     /* Supported Stats */
1695     stats->rx_packets += dev->stats.rx_packets;
1696     stats->tx_packets += dev->stats.tx_packets;
1697     stats->tx_dropped += dev->stats.tx_dropped;
1698     stats->multicast = dev->stats.multicast;
1699     stats->rx_bytes = dev->stats.rx_bytes;
1700     stats->tx_bytes = dev->stats.tx_bytes;
1701     stats->rx_errors = dev->stats.rx_errors;
1702     stats->rx_length_errors = dev->stats.rx_length_errors;
1703
1704     stats->rx_1_to_64_packets = dev->stats.rx_1_to_64_packets;
1705     stats->rx_65_to_127_packets = dev->stats.rx_65_to_127_packets;
1706     stats->rx_128_to_255_packets = dev->stats.rx_128_to_255_packets;
1707     stats->rx_256_to_511_packets = dev->stats.rx_256_to_511_packets;
1708     stats->rx_512_to_1023_packets = dev->stats.rx_512_to_1023_packets;
1709     stats->rx_1024_to_1522_packets = dev->stats.rx_1024_to_1522_packets;
1710     stats->rx_1523_to_max_packets = dev->stats.rx_1523_to_max_packets;
1711
1712     rte_spinlock_unlock(&dev->stats_lock);
1713
1714     ovs_mutex_unlock(&dev->mutex);
1715
1716     return 0;
1717 }
1718
1719 static void
1720 netdev_dpdk_convert_xstats(struct netdev_stats *stats,
1721                            const struct rte_eth_xstats *xstats,
1722                            const unsigned int size)
1723 {
1724     /* XXX Current implementation is simple search through an array
1725      * to find hardcoded counter names. In future DPDK release (TBD)
1726      * XSTATS API will change so each counter will be represented by
1727      * unique ID instead of String. */
1728
1729     for (unsigned int i = 0; i < size; i++) {
1730         if (strcmp(XSTAT_RX_64_PACKETS, xstats[i].name) == 0) {
1731             stats->rx_1_to_64_packets = xstats[i].value;
1732         } else if (strcmp(XSTAT_RX_65_TO_127_PACKETS, xstats[i].name) == 0) {
1733             stats->rx_65_to_127_packets = xstats[i].value;
1734         } else if (strcmp(XSTAT_RX_128_TO_255_PACKETS, xstats[i].name) == 0) {
1735             stats->rx_128_to_255_packets = xstats[i].value;
1736         } else if (strcmp(XSTAT_RX_256_TO_511_PACKETS, xstats[i].name) == 0) {
1737             stats->rx_256_to_511_packets = xstats[i].value;
1738         } else if (strcmp(XSTAT_RX_512_TO_1023_PACKETS,
1739                           xstats[i].name) == 0) {
1740             stats->rx_512_to_1023_packets = xstats[i].value;
1741         } else if (strcmp(XSTAT_RX_1024_TO_1522_PACKETS,
1742                           xstats[i].name) == 0) {
1743             stats->rx_1024_to_1522_packets = xstats[i].value;
1744         } else if (strcmp(XSTAT_RX_1523_TO_MAX_PACKETS,
1745                           xstats[i].name) == 0) {
1746             stats->rx_1523_to_max_packets = xstats[i].value;
1747         } else if (strcmp(XSTAT_TX_64_PACKETS, xstats[i].name) == 0) {
1748             stats->tx_1_to_64_packets = xstats[i].value;
1749         } else if (strcmp(XSTAT_TX_65_TO_127_PACKETS, xstats[i].name) == 0) {
1750             stats->tx_65_to_127_packets = xstats[i].value;
1751         } else if (strcmp(XSTAT_TX_128_TO_255_PACKETS, xstats[i].name) == 0) {
1752             stats->tx_128_to_255_packets = xstats[i].value;
1753         } else if (strcmp(XSTAT_TX_256_TO_511_PACKETS, xstats[i].name) == 0) {
1754             stats->tx_256_to_511_packets = xstats[i].value;
1755         } else if (strcmp(XSTAT_TX_512_TO_1023_PACKETS,
1756                           xstats[i].name) == 0) {
1757             stats->tx_512_to_1023_packets = xstats[i].value;
1758         } else if (strcmp(XSTAT_TX_1024_TO_1522_PACKETS,
1759                           xstats[i].name) == 0) {
1760             stats->tx_1024_to_1522_packets = xstats[i].value;
1761         } else if (strcmp(XSTAT_TX_1523_TO_MAX_PACKETS,
1762                           xstats[i].name) == 0) {
1763             stats->tx_1523_to_max_packets = xstats[i].value;
1764         } else if (strcmp(XSTAT_TX_MULTICAST_PACKETS, xstats[i].name) == 0) {
1765             stats->tx_multicast_packets = xstats[i].value;
1766         } else if (strcmp(XSTAT_RX_BROADCAST_PACKETS, xstats[i].name) == 0) {
1767             stats->rx_broadcast_packets = xstats[i].value;
1768         } else if (strcmp(XSTAT_TX_BROADCAST_PACKETS, xstats[i].name) == 0) {
1769             stats->tx_broadcast_packets = xstats[i].value;
1770         } else if (strcmp(XSTAT_RX_UNDERSIZED_ERRORS, xstats[i].name) == 0) {
1771             stats->rx_undersized_errors = xstats[i].value;
1772         } else if (strcmp(XSTAT_RX_FRAGMENTED_ERRORS, xstats[i].name) == 0) {
1773             stats->rx_fragmented_errors = xstats[i].value;
1774         } else if (strcmp(XSTAT_RX_JABBER_ERRORS, xstats[i].name) == 0) {
1775             stats->rx_jabber_errors = xstats[i].value;
1776         }
1777     }
1778 }
1779
1780 static int
1781 netdev_dpdk_get_stats(const struct netdev *netdev, struct netdev_stats *stats)
1782 {
1783     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1784     struct rte_eth_stats rte_stats;
1785     bool gg;
1786
1787     netdev_dpdk_get_carrier(netdev, &gg);
1788     ovs_mutex_lock(&dev->mutex);
1789
1790     struct rte_eth_xstats *rte_xstats;
1791     int rte_xstats_len, rte_xstats_ret;
1792
1793     if (rte_eth_stats_get(dev->port_id, &rte_stats)) {
1794         VLOG_ERR("Can't get ETH statistics for port: %i.", dev->port_id);
1795         ovs_mutex_unlock(&dev->mutex);
1796         return EPROTO;
1797     }
1798
1799     rte_xstats_len = rte_eth_xstats_get(dev->port_id, NULL, 0);
1800     if (rte_xstats_len > 0) {
1801         rte_xstats = dpdk_rte_mzalloc(sizeof(*rte_xstats) * rte_xstats_len);
1802         memset(rte_xstats, 0xff, sizeof(*rte_xstats) * rte_xstats_len);
1803         rte_xstats_ret = rte_eth_xstats_get(dev->port_id, rte_xstats,
1804                                             rte_xstats_len);
1805         if (rte_xstats_ret > 0 && rte_xstats_ret <= rte_xstats_len) {
1806             netdev_dpdk_convert_xstats(stats, rte_xstats, rte_xstats_ret);
1807         }
1808         rte_free(rte_xstats);
1809     } else {
1810         VLOG_WARN("Can't get XSTATS counters for port: %i.", dev->port_id);
1811     }
1812
1813     stats->rx_packets = rte_stats.ipackets;
1814     stats->tx_packets = rte_stats.opackets;
1815     stats->rx_bytes = rte_stats.ibytes;
1816     stats->tx_bytes = rte_stats.obytes;
1817     /* DPDK counts imissed as errors, but count them here as dropped instead */
1818     stats->rx_errors = rte_stats.ierrors - rte_stats.imissed;
1819     stats->tx_errors = rte_stats.oerrors;
1820     stats->multicast = rte_stats.imcasts;
1821
1822     rte_spinlock_lock(&dev->stats_lock);
1823     stats->tx_dropped = dev->stats.tx_dropped;
1824     rte_spinlock_unlock(&dev->stats_lock);
1825
1826     /* These are the available DPDK counters for packets not received due to
1827      * local resource constraints in DPDK and NIC respectively. */
1828     stats->rx_dropped = rte_stats.rx_nombuf + rte_stats.imissed;
1829     stats->rx_missed_errors = rte_stats.imissed;
1830
1831     ovs_mutex_unlock(&dev->mutex);
1832
1833     return 0;
1834 }
1835
1836 static int
1837 netdev_dpdk_get_features(const struct netdev *netdev,
1838                          enum netdev_features *current,
1839                          enum netdev_features *advertised OVS_UNUSED,
1840                          enum netdev_features *supported OVS_UNUSED,
1841                          enum netdev_features *peer OVS_UNUSED)
1842 {
1843     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1844     struct rte_eth_link link;
1845
1846     ovs_mutex_lock(&dev->mutex);
1847     link = dev->link;
1848     ovs_mutex_unlock(&dev->mutex);
1849
1850     if (link.link_duplex == ETH_LINK_HALF_DUPLEX) {
1851         if (link.link_speed == ETH_SPEED_NUM_10M) {
1852             *current = NETDEV_F_10MB_HD;
1853         }
1854         if (link.link_speed == ETH_SPEED_NUM_100M) {
1855             *current = NETDEV_F_100MB_HD;
1856         }
1857         if (link.link_speed == ETH_SPEED_NUM_1G) {
1858             *current = NETDEV_F_1GB_HD;
1859         }
1860     } else if (link.link_duplex == ETH_LINK_FULL_DUPLEX) {
1861         if (link.link_speed == ETH_SPEED_NUM_10M) {
1862             *current = NETDEV_F_10MB_FD;
1863         }
1864         if (link.link_speed == ETH_SPEED_NUM_100M) {
1865             *current = NETDEV_F_100MB_FD;
1866         }
1867         if (link.link_speed == ETH_SPEED_NUM_1G) {
1868             *current = NETDEV_F_1GB_FD;
1869         }
1870         if (link.link_speed == ETH_SPEED_NUM_10G) {
1871             *current = NETDEV_F_10GB_FD;
1872         }
1873     }
1874
1875     if (link.link_autoneg) {
1876         *current |= NETDEV_F_AUTONEG;
1877     }
1878
1879     return 0;
1880 }
1881
1882 static int
1883 netdev_dpdk_get_ifindex(const struct netdev *netdev)
1884 {
1885     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1886     int ifindex;
1887
1888     ovs_mutex_lock(&dev->mutex);
1889     ifindex = dev->port_id;
1890     ovs_mutex_unlock(&dev->mutex);
1891
1892     return ifindex;
1893 }
1894
1895 static int
1896 netdev_dpdk_get_carrier(const struct netdev *netdev, bool *carrier)
1897 {
1898     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1899
1900     ovs_mutex_lock(&dev->mutex);
1901     check_link_status(dev);
1902     *carrier = dev->link.link_status;
1903
1904     ovs_mutex_unlock(&dev->mutex);
1905
1906     return 0;
1907 }
1908
1909 static int
1910 netdev_dpdk_vhost_get_carrier(const struct netdev *netdev, bool *carrier)
1911 {
1912     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1913     struct virtio_net *virtio_dev = netdev_dpdk_get_virtio(dev);
1914
1915     ovs_mutex_lock(&dev->mutex);
1916
1917     if (is_vhost_running(virtio_dev)) {
1918         *carrier = 1;
1919     } else {
1920         *carrier = 0;
1921     }
1922
1923     ovs_mutex_unlock(&dev->mutex);
1924
1925     return 0;
1926 }
1927
1928 static long long int
1929 netdev_dpdk_get_carrier_resets(const struct netdev *netdev)
1930 {
1931     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1932     long long int carrier_resets;
1933
1934     ovs_mutex_lock(&dev->mutex);
1935     carrier_resets = dev->link_reset_cnt;
1936     ovs_mutex_unlock(&dev->mutex);
1937
1938     return carrier_resets;
1939 }
1940
1941 static int
1942 netdev_dpdk_set_miimon(struct netdev *netdev OVS_UNUSED,
1943                        long long int interval OVS_UNUSED)
1944 {
1945     return EOPNOTSUPP;
1946 }
1947
1948 static int
1949 netdev_dpdk_update_flags__(struct netdev_dpdk *dev,
1950                            enum netdev_flags off, enum netdev_flags on,
1951                            enum netdev_flags *old_flagsp) OVS_REQUIRES(dev->mutex)
1952 {
1953     int err;
1954
1955     if ((off | on) & ~(NETDEV_UP | NETDEV_PROMISC)) {
1956         return EINVAL;
1957     }
1958
1959     *old_flagsp = dev->flags;
1960     dev->flags |= on;
1961     dev->flags &= ~off;
1962
1963     if (dev->flags == *old_flagsp) {
1964         return 0;
1965     }
1966
1967     if (dev->type == DPDK_DEV_ETH) {
1968         if (dev->flags & NETDEV_UP) {
1969             err = rte_eth_dev_start(dev->port_id);
1970             if (err)
1971                 return -err;
1972         }
1973
1974         if (dev->flags & NETDEV_PROMISC) {
1975             rte_eth_promiscuous_enable(dev->port_id);
1976         }
1977
1978         if (!(dev->flags & NETDEV_UP)) {
1979             rte_eth_dev_stop(dev->port_id);
1980         }
1981     }
1982
1983     return 0;
1984 }
1985
1986 static int
1987 netdev_dpdk_update_flags(struct netdev *netdev,
1988                          enum netdev_flags off, enum netdev_flags on,
1989                          enum netdev_flags *old_flagsp)
1990 {
1991     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1992     int error;
1993
1994     ovs_mutex_lock(&dev->mutex);
1995     error = netdev_dpdk_update_flags__(dev, off, on, old_flagsp);
1996     ovs_mutex_unlock(&dev->mutex);
1997
1998     return error;
1999 }
2000
2001 static int
2002 netdev_dpdk_get_status(const struct netdev *netdev, struct smap *args)
2003 {
2004     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
2005     struct rte_eth_dev_info dev_info;
2006
2007     if (dev->port_id < 0)
2008         return ENODEV;
2009
2010     ovs_mutex_lock(&dev->mutex);
2011     rte_eth_dev_info_get(dev->port_id, &dev_info);
2012     ovs_mutex_unlock(&dev->mutex);
2013
2014     smap_add_format(args, "driver_name", "%s", dev_info.driver_name);
2015
2016     smap_add_format(args, "port_no", "%d", dev->port_id);
2017     smap_add_format(args, "numa_id", "%d", rte_eth_dev_socket_id(dev->port_id));
2018     smap_add_format(args, "driver_name", "%s", dev_info.driver_name);
2019     smap_add_format(args, "min_rx_bufsize", "%u", dev_info.min_rx_bufsize);
2020     smap_add_format(args, "max_rx_pktlen", "%u", dev->max_packet_len);
2021     smap_add_format(args, "max_rx_queues", "%u", dev_info.max_rx_queues);
2022     smap_add_format(args, "max_tx_queues", "%u", dev_info.max_tx_queues);
2023     smap_add_format(args, "max_mac_addrs", "%u", dev_info.max_mac_addrs);
2024     smap_add_format(args, "max_hash_mac_addrs", "%u", dev_info.max_hash_mac_addrs);
2025     smap_add_format(args, "max_vfs", "%u", dev_info.max_vfs);
2026     smap_add_format(args, "max_vmdq_pools", "%u", dev_info.max_vmdq_pools);
2027
2028     if (dev_info.pci_dev) {
2029         smap_add_format(args, "pci-vendor_id", "0x%u",
2030                         dev_info.pci_dev->id.vendor_id);
2031         smap_add_format(args, "pci-device_id", "0x%x",
2032                         dev_info.pci_dev->id.device_id);
2033     }
2034
2035     return 0;
2036 }
2037
2038 static void
2039 netdev_dpdk_set_admin_state__(struct netdev_dpdk *dev, bool admin_state)
2040     OVS_REQUIRES(dev->mutex)
2041 {
2042     enum netdev_flags old_flags;
2043
2044     if (admin_state) {
2045         netdev_dpdk_update_flags__(dev, 0, NETDEV_UP, &old_flags);
2046     } else {
2047         netdev_dpdk_update_flags__(dev, NETDEV_UP, 0, &old_flags);
2048     }
2049 }
2050
2051 static void
2052 netdev_dpdk_set_admin_state(struct unixctl_conn *conn, int argc,
2053                             const char *argv[], void *aux OVS_UNUSED)
2054 {
2055     bool up;
2056
2057     if (!strcasecmp(argv[argc - 1], "up")) {
2058         up = true;
2059     } else if ( !strcasecmp(argv[argc - 1], "down")) {
2060         up = false;
2061     } else {
2062         unixctl_command_reply_error(conn, "Invalid Admin State");
2063         return;
2064     }
2065
2066     if (argc > 2) {
2067         struct netdev *netdev = netdev_from_name(argv[1]);
2068         if (netdev && is_dpdk_class(netdev->netdev_class)) {
2069             struct netdev_dpdk *dpdk_dev = netdev_dpdk_cast(netdev);
2070
2071             ovs_mutex_lock(&dpdk_dev->mutex);
2072             netdev_dpdk_set_admin_state__(dpdk_dev, up);
2073             ovs_mutex_unlock(&dpdk_dev->mutex);
2074
2075             netdev_close(netdev);
2076         } else {
2077             unixctl_command_reply_error(conn, "Not a DPDK Interface");
2078             netdev_close(netdev);
2079             return;
2080         }
2081     } else {
2082         struct netdev_dpdk *netdev;
2083
2084         ovs_mutex_lock(&dpdk_mutex);
2085         LIST_FOR_EACH (netdev, list_node, &dpdk_list) {
2086             ovs_mutex_lock(&netdev->mutex);
2087             netdev_dpdk_set_admin_state__(netdev, up);
2088             ovs_mutex_unlock(&netdev->mutex);
2089         }
2090         ovs_mutex_unlock(&dpdk_mutex);
2091     }
2092     unixctl_command_reply(conn, "OK");
2093 }
2094
2095 /*
2096  * Set virtqueue flags so that we do not receive interrupts.
2097  */
2098 static void
2099 set_irq_status(struct virtio_net *virtio_dev)
2100 {
2101     uint32_t i;
2102     uint64_t idx;
2103
2104     for (i = 0; i < virtio_dev->virt_qp_nb; i++) {
2105         idx = i * VIRTIO_QNUM;
2106         rte_vhost_enable_guest_notification(virtio_dev, idx + VIRTIO_RXQ, 0);
2107         rte_vhost_enable_guest_notification(virtio_dev, idx + VIRTIO_TXQ, 0);
2108     }
2109 }
2110
2111 /*
2112  * Fixes mapping for vhost-user tx queues. Must be called after each
2113  * enabling/disabling of queues and real_n_txq modifications.
2114  */
2115 static void
2116 netdev_dpdk_remap_txqs(struct netdev_dpdk *dev)
2117     OVS_REQUIRES(dev->mutex)
2118 {
2119     int *enabled_queues, n_enabled = 0;
2120     int i, k, total_txqs = dev->real_n_txq;
2121
2122     enabled_queues = dpdk_rte_mzalloc(total_txqs * sizeof *enabled_queues);
2123
2124     for (i = 0; i < total_txqs; i++) {
2125         /* Enabled queues always mapped to themselves. */
2126         if (dev->tx_q[i].map == i) {
2127             enabled_queues[n_enabled++] = i;
2128         }
2129     }
2130
2131     if (n_enabled == 0 && total_txqs != 0) {
2132         enabled_queues[0] = OVS_VHOST_QUEUE_DISABLED;
2133         n_enabled = 1;
2134     }
2135
2136     k = 0;
2137     for (i = 0; i < total_txqs; i++) {
2138         if (dev->tx_q[i].map != i) {
2139             dev->tx_q[i].map = enabled_queues[k];
2140             k = (k + 1) % n_enabled;
2141         }
2142     }
2143
2144     VLOG_DBG("TX queue mapping for %s\n", dev->vhost_id);
2145     for (i = 0; i < total_txqs; i++) {
2146         VLOG_DBG("%2d --> %2d", i, dev->tx_q[i].map);
2147     }
2148
2149     rte_free(enabled_queues);
2150 }
2151
2152 static int
2153 netdev_dpdk_vhost_set_queues(struct netdev_dpdk *dev, struct virtio_net *virtio_dev)
2154     OVS_REQUIRES(dev->mutex)
2155 {
2156     uint32_t qp_num;
2157
2158     qp_num = virtio_dev->virt_qp_nb;
2159     if (qp_num > dev->up.n_rxq) {
2160         VLOG_ERR("vHost Device '%s' %"PRIu64" can't be added - "
2161                  "too many queues %d > %d", virtio_dev->ifname, virtio_dev->device_fh,
2162                  qp_num, dev->up.n_rxq);
2163         return -1;
2164     }
2165
2166     dev->real_n_rxq = qp_num;
2167     dev->real_n_txq = qp_num;
2168     dev->txq_needs_locking = true;
2169     /* Enable TX queue 0 by default if it wasn't disabled. */
2170     if (dev->tx_q[0].map == OVS_VHOST_QUEUE_MAP_UNKNOWN) {
2171         dev->tx_q[0].map = 0;
2172     }
2173
2174     netdev_dpdk_remap_txqs(dev);
2175
2176     return 0;
2177 }
2178
2179 /*
2180  * A new virtio-net device is added to a vhost port.
2181  */
2182 static int
2183 new_device(struct virtio_net *virtio_dev)
2184 {
2185     struct netdev_dpdk *dev;
2186     bool exists = false;
2187
2188     ovs_mutex_lock(&dpdk_mutex);
2189     /* Add device to the vhost port with the same name as that passed down. */
2190     LIST_FOR_EACH(dev, list_node, &dpdk_list) {
2191         if (strncmp(virtio_dev->ifname, dev->vhost_id, IF_NAME_SZ) == 0) {
2192             ovs_mutex_lock(&dev->mutex);
2193             if (netdev_dpdk_vhost_set_queues(dev, virtio_dev)) {
2194                 ovs_mutex_unlock(&dev->mutex);
2195                 ovs_mutex_unlock(&dpdk_mutex);
2196                 return -1;
2197             }
2198             ovsrcu_set(&dev->virtio_dev, virtio_dev);
2199             exists = true;
2200             virtio_dev->flags |= VIRTIO_DEV_RUNNING;
2201             /* Disable notifications. */
2202             set_irq_status(virtio_dev);
2203             ovs_mutex_unlock(&dev->mutex);
2204             break;
2205         }
2206     }
2207     ovs_mutex_unlock(&dpdk_mutex);
2208
2209     if (!exists) {
2210         VLOG_INFO("vHost Device '%s' %"PRIu64" can't be added - name not "
2211                   "found", virtio_dev->ifname, virtio_dev->device_fh);
2212
2213         return -1;
2214     }
2215
2216     VLOG_INFO("vHost Device '%s' %"PRIu64" has been added", virtio_dev->ifname,
2217               virtio_dev->device_fh);
2218     return 0;
2219 }
2220
2221 /* Clears mapping for all available queues of vhost interface. */
2222 static void
2223 netdev_dpdk_txq_map_clear(struct netdev_dpdk *dev)
2224     OVS_REQUIRES(dev->mutex)
2225 {
2226     int i;
2227
2228     for (i = 0; i < dev->real_n_txq; i++) {
2229         dev->tx_q[i].map = OVS_VHOST_QUEUE_MAP_UNKNOWN;
2230     }
2231 }
2232
2233 /*
2234  * Remove a virtio-net device from the specific vhost port.  Use dev->remove
2235  * flag to stop any more packets from being sent or received to/from a VM and
2236  * ensure all currently queued packets have been sent/received before removing
2237  *  the device.
2238  */
2239 static void
2240 destroy_device(volatile struct virtio_net *virtio_dev)
2241 {
2242     struct netdev_dpdk *dev;
2243     bool exists = false;
2244
2245     ovs_mutex_lock(&dpdk_mutex);
2246     LIST_FOR_EACH (dev, list_node, &dpdk_list) {
2247         if (netdev_dpdk_get_virtio(dev) == virtio_dev) {
2248
2249             ovs_mutex_lock(&dev->mutex);
2250             virtio_dev->flags &= ~VIRTIO_DEV_RUNNING;
2251             ovsrcu_set(&dev->virtio_dev, NULL);
2252             netdev_dpdk_txq_map_clear(dev);
2253             exists = true;
2254             ovs_mutex_unlock(&dev->mutex);
2255             break;
2256         }
2257     }
2258
2259     ovs_mutex_unlock(&dpdk_mutex);
2260
2261     if (exists == true) {
2262         /*
2263          * Wait for other threads to quiesce after setting the 'virtio_dev'
2264          * to NULL, before returning.
2265          */
2266         ovsrcu_synchronize();
2267         /*
2268          * As call to ovsrcu_synchronize() will end the quiescent state,
2269          * put thread back into quiescent state before returning.
2270          */
2271         ovsrcu_quiesce_start();
2272         VLOG_INFO("vHost Device '%s' %"PRIu64" has been removed",
2273                   virtio_dev->ifname, virtio_dev->device_fh);
2274     } else {
2275         VLOG_INFO("vHost Device '%s' %"PRIu64" not found", virtio_dev->ifname,
2276                   virtio_dev->device_fh);
2277     }
2278 }
2279
2280 static int
2281 vring_state_changed(struct virtio_net *virtio_dev, uint16_t queue_id,
2282                     int enable)
2283 {
2284     struct netdev_dpdk *dev;
2285     bool exists = false;
2286     int qid = queue_id / VIRTIO_QNUM;
2287
2288     if (queue_id % VIRTIO_QNUM == VIRTIO_TXQ) {
2289         return 0;
2290     }
2291
2292     ovs_mutex_lock(&dpdk_mutex);
2293     LIST_FOR_EACH (dev, list_node, &dpdk_list) {
2294         if (strncmp(virtio_dev->ifname, dev->vhost_id, IF_NAME_SZ) == 0) {
2295             ovs_mutex_lock(&dev->mutex);
2296             if (enable) {
2297                 dev->tx_q[qid].map = qid;
2298             } else {
2299                 dev->tx_q[qid].map = OVS_VHOST_QUEUE_DISABLED;
2300             }
2301             netdev_dpdk_remap_txqs(dev);
2302             exists = true;
2303             ovs_mutex_unlock(&dev->mutex);
2304             break;
2305         }
2306     }
2307     ovs_mutex_unlock(&dpdk_mutex);
2308
2309     if (exists) {
2310         VLOG_INFO("State of queue %d ( tx_qid %d ) of vhost device '%s' %"
2311                   PRIu64" changed to \'%s\'", queue_id, qid,
2312                   virtio_dev->ifname, virtio_dev->device_fh,
2313                   (enable == 1) ? "enabled" : "disabled");
2314     } else {
2315         VLOG_INFO("vHost Device '%s' %"PRIu64" not found", virtio_dev->ifname,
2316                   virtio_dev->device_fh);
2317         return -1;
2318     }
2319
2320     return 0;
2321 }
2322
2323 struct virtio_net *
2324 netdev_dpdk_get_virtio(const struct netdev_dpdk *dev)
2325 {
2326     return ovsrcu_get(struct virtio_net *, &dev->virtio_dev);
2327 }
2328
2329 /*
2330  * These callbacks allow virtio-net devices to be added to vhost ports when
2331  * configuration has been fully complete.
2332  */
2333 static const struct virtio_net_device_ops virtio_net_device_ops =
2334 {
2335     .new_device =  new_device,
2336     .destroy_device = destroy_device,
2337     .vring_state_changed = vring_state_changed
2338 };
2339
2340 static void *
2341 start_vhost_loop(void *dummy OVS_UNUSED)
2342 {
2343      pthread_detach(pthread_self());
2344      /* Put the cuse thread into quiescent state. */
2345      ovsrcu_quiesce_start();
2346      rte_vhost_driver_session_start();
2347      return NULL;
2348 }
2349
2350 static int
2351 dpdk_vhost_class_init(void)
2352 {
2353     rte_vhost_driver_callback_register(&virtio_net_device_ops);
2354     rte_vhost_feature_disable(1ULL << VIRTIO_NET_F_HOST_TSO4
2355                             | 1ULL << VIRTIO_NET_F_HOST_TSO6
2356                             | 1ULL << VIRTIO_NET_F_CSUM);
2357
2358     ovs_thread_create("vhost_thread", start_vhost_loop, NULL);
2359     return 0;
2360 }
2361
2362 static int
2363 dpdk_vhost_cuse_class_init(void)
2364 {
2365     return 0;
2366 }
2367
2368 static int
2369 dpdk_vhost_user_class_init(void)
2370 {
2371     return 0;
2372 }
2373
2374 static void
2375 dpdk_common_init(void)
2376 {
2377     unixctl_command_register("netdev-dpdk/set-admin-state",
2378                              "[netdev] up|down", 1, 2,
2379                              netdev_dpdk_set_admin_state, NULL);
2380
2381 }
2382
2383 /* Client Rings */
2384
2385 static int
2386 dpdk_ring_create(const char dev_name[], unsigned int port_no,
2387                  unsigned int *eth_port_id)
2388 {
2389     struct dpdk_ring *ivshmem;
2390     char ring_name[RTE_RING_NAMESIZE];
2391     int err;
2392
2393     ivshmem = dpdk_rte_mzalloc(sizeof *ivshmem);
2394     if (ivshmem == NULL) {
2395         return ENOMEM;
2396     }
2397
2398     /* XXX: Add support for multiquque ring. */
2399     err = snprintf(ring_name, sizeof(ring_name), "%s_tx", dev_name);
2400     if (err < 0) {
2401         return -err;
2402     }
2403
2404     /* Create single producer tx ring, netdev does explicit locking. */
2405     ivshmem->cring_tx = rte_ring_create(ring_name, DPDK_RING_SIZE, SOCKET0,
2406                                         RING_F_SP_ENQ);
2407     if (ivshmem->cring_tx == NULL) {
2408         rte_free(ivshmem);
2409         return ENOMEM;
2410     }
2411
2412     err = snprintf(ring_name, sizeof(ring_name), "%s_rx", dev_name);
2413     if (err < 0) {
2414         return -err;
2415     }
2416
2417     /* Create single consumer rx ring, netdev does explicit locking. */
2418     ivshmem->cring_rx = rte_ring_create(ring_name, DPDK_RING_SIZE, SOCKET0,
2419                                         RING_F_SC_DEQ);
2420     if (ivshmem->cring_rx == NULL) {
2421         rte_free(ivshmem);
2422         return ENOMEM;
2423     }
2424
2425     err = rte_eth_from_rings(dev_name, &ivshmem->cring_rx, 1,
2426                              &ivshmem->cring_tx, 1, SOCKET0);
2427
2428     if (err < 0) {
2429         rte_free(ivshmem);
2430         return ENODEV;
2431     }
2432
2433     ivshmem->user_port_id = port_no;
2434     ivshmem->eth_port_id = rte_eth_dev_count() - 1;
2435     ovs_list_push_back(&dpdk_ring_list, &ivshmem->list_node);
2436
2437     *eth_port_id = ivshmem->eth_port_id;
2438     return 0;
2439 }
2440
2441 static int
2442 dpdk_ring_open(const char dev_name[], unsigned int *eth_port_id) OVS_REQUIRES(dpdk_mutex)
2443 {
2444     struct dpdk_ring *ivshmem;
2445     unsigned int port_no;
2446     int err = 0;
2447
2448     /* Names always start with "dpdkr" */
2449     err = dpdk_dev_parse_name(dev_name, "dpdkr", &port_no);
2450     if (err) {
2451         return err;
2452     }
2453
2454     /* look through our list to find the device */
2455     LIST_FOR_EACH (ivshmem, list_node, &dpdk_ring_list) {
2456          if (ivshmem->user_port_id == port_no) {
2457             VLOG_INFO("Found dpdk ring device %s:", dev_name);
2458             *eth_port_id = ivshmem->eth_port_id; /* really all that is needed */
2459             return 0;
2460          }
2461     }
2462     /* Need to create the device rings */
2463     return dpdk_ring_create(dev_name, port_no, eth_port_id);
2464 }
2465
2466 static int
2467 netdev_dpdk_ring_send(struct netdev *netdev, int qid,
2468                       struct dp_packet **pkts, int cnt, bool may_steal)
2469 {
2470     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
2471     unsigned i;
2472
2473     /* When using 'dpdkr' and sending to a DPDK ring, we want to ensure that the
2474      * rss hash field is clear. This is because the same mbuf may be modified by
2475      * the consumer of the ring and return into the datapath without recalculating
2476      * the RSS hash. */
2477     for (i = 0; i < cnt; i++) {
2478         dp_packet_rss_invalidate(pkts[i]);
2479     }
2480
2481     netdev_dpdk_send__(dev, qid, pkts, cnt, may_steal);
2482     return 0;
2483 }
2484
2485 static int
2486 netdev_dpdk_ring_construct(struct netdev *netdev)
2487 {
2488     unsigned int port_no = 0;
2489     int err = 0;
2490
2491     if (rte_eal_init_ret) {
2492         return rte_eal_init_ret;
2493     }
2494
2495     ovs_mutex_lock(&dpdk_mutex);
2496
2497     err = dpdk_ring_open(netdev->name, &port_no);
2498     if (err) {
2499         goto unlock_dpdk;
2500     }
2501
2502     err = netdev_dpdk_init(netdev, port_no, DPDK_DEV_ETH);
2503
2504 unlock_dpdk:
2505     ovs_mutex_unlock(&dpdk_mutex);
2506     return err;
2507 }
2508
2509 /* QoS Functions */
2510
2511 /*
2512  * Initialize QoS configuration operations.
2513  */
2514 static void
2515 qos_conf_init(struct qos_conf *conf, const struct dpdk_qos_ops *ops)
2516 {
2517     conf->ops = ops;
2518 }
2519
2520 /*
2521  * Search existing QoS operations in qos_ops and compare each set of
2522  * operations qos_name to name. Return a dpdk_qos_ops pointer to a match,
2523  * else return NULL
2524  */
2525 static const struct dpdk_qos_ops *
2526 qos_lookup_name(const char *name)
2527 {
2528     const struct dpdk_qos_ops *const *opsp;
2529
2530     for (opsp = qos_confs; *opsp != NULL; opsp++) {
2531         const struct dpdk_qos_ops *ops = *opsp;
2532         if (!strcmp(name, ops->qos_name)) {
2533             return ops;
2534         }
2535     }
2536     return NULL;
2537 }
2538
2539 /*
2540  * Call qos_destruct to clean up items associated with the netdevs
2541  * qos_conf. Set netdevs qos_conf to NULL.
2542  */
2543 static void
2544 qos_delete_conf(struct netdev *netdev)
2545 {
2546     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
2547
2548     rte_spinlock_lock(&dev->qos_lock);
2549     if (dev->qos_conf) {
2550         if (dev->qos_conf->ops->qos_destruct) {
2551             dev->qos_conf->ops->qos_destruct(netdev, dev->qos_conf);
2552         }
2553         dev->qos_conf = NULL;
2554     }
2555     rte_spinlock_unlock(&dev->qos_lock);
2556 }
2557
2558 static int
2559 netdev_dpdk_get_qos_types(const struct netdev *netdev OVS_UNUSED,
2560                            struct sset *types)
2561 {
2562     const struct dpdk_qos_ops *const *opsp;
2563
2564     for (opsp = qos_confs; *opsp != NULL; opsp++) {
2565         const struct dpdk_qos_ops *ops = *opsp;
2566         if (ops->qos_construct && ops->qos_name[0] != '\0') {
2567             sset_add(types, ops->qos_name);
2568         }
2569     }
2570     return 0;
2571 }
2572
2573 static int
2574 netdev_dpdk_get_qos(const struct netdev *netdev,
2575                     const char **typep, struct smap *details)
2576 {
2577     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
2578     int error = 0;
2579
2580     ovs_mutex_lock(&dev->mutex);
2581     if(dev->qos_conf) {
2582         *typep = dev->qos_conf->ops->qos_name;
2583         error = (dev->qos_conf->ops->qos_get
2584                  ? dev->qos_conf->ops->qos_get(netdev, details): 0);
2585     }
2586     ovs_mutex_unlock(&dev->mutex);
2587
2588     return error;
2589 }
2590
2591 static int
2592 netdev_dpdk_set_qos(struct netdev *netdev,
2593                     const char *type, const struct smap *details)
2594 {
2595     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
2596     const struct dpdk_qos_ops *new_ops = NULL;
2597     int error = 0;
2598
2599     /* If type is empty or unsupported then the current QoS configuration
2600      * for the dpdk-netdev can be destroyed */
2601     new_ops = qos_lookup_name(type);
2602
2603     if (type[0] == '\0' || !new_ops || !new_ops->qos_construct) {
2604         qos_delete_conf(netdev);
2605         return EOPNOTSUPP;
2606     }
2607
2608     ovs_mutex_lock(&dev->mutex);
2609
2610     if (dev->qos_conf) {
2611         if (new_ops == dev->qos_conf->ops) {
2612             error = new_ops->qos_set ? new_ops->qos_set(netdev, details) : 0;
2613         } else {
2614             /* Delete existing QoS configuration. */
2615             qos_delete_conf(netdev);
2616             ovs_assert(dev->qos_conf == NULL);
2617
2618             /* Install new QoS configuration. */
2619             error = new_ops->qos_construct(netdev, details);
2620             ovs_assert((error == 0) == (dev->qos_conf != NULL));
2621         }
2622     } else {
2623         error = new_ops->qos_construct(netdev, details);
2624         ovs_assert((error == 0) == (dev->qos_conf != NULL));
2625     }
2626
2627     ovs_mutex_unlock(&dev->mutex);
2628     return error;
2629 }
2630
2631 /* egress-policer details */
2632
2633 struct egress_policer {
2634     struct qos_conf qos_conf;
2635     struct rte_meter_srtcm_params app_srtcm_params;
2636     struct rte_meter_srtcm egress_meter;
2637 };
2638
2639 static struct egress_policer *
2640 egress_policer_get__(const struct netdev *netdev)
2641 {
2642     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
2643     return CONTAINER_OF(dev->qos_conf, struct egress_policer, qos_conf);
2644 }
2645
2646 static int
2647 egress_policer_qos_construct(struct netdev *netdev,
2648                              const struct smap *details)
2649 {
2650     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
2651     struct egress_policer *policer;
2652     const char *cir_s;
2653     const char *cbs_s;
2654     int err = 0;
2655
2656     rte_spinlock_lock(&dev->qos_lock);
2657     policer = xmalloc(sizeof *policer);
2658     qos_conf_init(&policer->qos_conf, &egress_policer_ops);
2659     dev->qos_conf = &policer->qos_conf;
2660     cir_s = smap_get(details, "cir");
2661     cbs_s = smap_get(details, "cbs");
2662     policer->app_srtcm_params.cir = cir_s ? strtoull(cir_s, NULL, 10) : 0;
2663     policer->app_srtcm_params.cbs = cbs_s ? strtoull(cbs_s, NULL, 10) : 0;
2664     policer->app_srtcm_params.ebs = 0;
2665     err = rte_meter_srtcm_config(&policer->egress_meter,
2666                                     &policer->app_srtcm_params);
2667     rte_spinlock_unlock(&dev->qos_lock);
2668
2669     return err;
2670 }
2671
2672 static void
2673 egress_policer_qos_destruct(struct netdev *netdev OVS_UNUSED,
2674                         struct qos_conf *conf)
2675 {
2676     struct egress_policer *policer = CONTAINER_OF(conf, struct egress_policer,
2677                                                 qos_conf);
2678     free(policer);
2679 }
2680
2681 static int
2682 egress_policer_qos_get(const struct netdev *netdev, struct smap *details)
2683 {
2684     struct egress_policer *policer = egress_policer_get__(netdev);
2685     smap_add_format(details, "cir", "%llu",
2686                     1ULL * policer->app_srtcm_params.cir);
2687     smap_add_format(details, "cbs", "%llu",
2688                     1ULL * policer->app_srtcm_params.cbs);
2689
2690     return 0;
2691 }
2692
2693 static int
2694 egress_policer_qos_set(struct netdev *netdev, const struct smap *details)
2695 {
2696     struct egress_policer *policer;
2697     const char *cir_s;
2698     const char *cbs_s;
2699     int err = 0;
2700
2701     policer = egress_policer_get__(netdev);
2702     cir_s = smap_get(details, "cir");
2703     cbs_s = smap_get(details, "cbs");
2704     policer->app_srtcm_params.cir = cir_s ? strtoull(cir_s, NULL, 10) : 0;
2705     policer->app_srtcm_params.cbs = cbs_s ? strtoull(cbs_s, NULL, 10) : 0;
2706     policer->app_srtcm_params.ebs = 0;
2707     err = rte_meter_srtcm_config(&policer->egress_meter,
2708                                     &policer->app_srtcm_params);
2709
2710     return err;
2711 }
2712
2713 static int
2714 egress_policer_run(struct netdev *netdev, struct rte_mbuf **pkts, int pkt_cnt)
2715 {
2716     int cnt = 0;
2717     struct egress_policer *policer = egress_policer_get__(netdev);
2718
2719     cnt = netdev_dpdk_policer_run(&policer->egress_meter, pkts, pkt_cnt);
2720
2721     return cnt;
2722 }
2723
2724 static const struct dpdk_qos_ops egress_policer_ops = {
2725     "egress-policer",    /* qos_name */
2726     egress_policer_qos_construct,
2727     egress_policer_qos_destruct,
2728     egress_policer_qos_get,
2729     egress_policer_qos_set,
2730     egress_policer_run
2731 };
2732
2733 static int
2734 netdev_dpdk_reconfigure(struct netdev *netdev)
2735 {
2736     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
2737     int err = 0;
2738
2739     ovs_mutex_lock(&dpdk_mutex);
2740     ovs_mutex_lock(&dev->mutex);
2741
2742     if (netdev->n_txq == dev->requested_n_txq
2743         && netdev->n_rxq == dev->requested_n_rxq) {
2744         /* Reconfiguration is unnecessary */
2745
2746         goto out;
2747     }
2748
2749     rte_eth_dev_stop(dev->port_id);
2750
2751     netdev->n_txq = dev->requested_n_txq;
2752     netdev->n_rxq = dev->requested_n_rxq;
2753
2754     rte_free(dev->tx_q);
2755     err = dpdk_eth_dev_init(dev);
2756     netdev_dpdk_alloc_txq(dev, dev->real_n_txq);
2757
2758     dev->txq_needs_locking = dev->real_n_txq != netdev->n_txq;
2759
2760 out:
2761
2762     ovs_mutex_unlock(&dev->mutex);
2763     ovs_mutex_unlock(&dpdk_mutex);
2764
2765     return err;
2766 }
2767
2768 static int
2769 netdev_dpdk_vhost_user_reconfigure(struct netdev *netdev)
2770 {
2771     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
2772
2773     ovs_mutex_lock(&dpdk_mutex);
2774     ovs_mutex_lock(&dev->mutex);
2775
2776     netdev->n_txq = dev->requested_n_txq;
2777     netdev->n_rxq = dev->requested_n_rxq;
2778
2779     ovs_mutex_unlock(&dev->mutex);
2780     ovs_mutex_unlock(&dpdk_mutex);
2781
2782     return 0;
2783 }
2784
2785 static int
2786 netdev_dpdk_vhost_cuse_reconfigure(struct netdev *netdev)
2787 {
2788     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
2789
2790     ovs_mutex_lock(&dpdk_mutex);
2791     ovs_mutex_lock(&dev->mutex);
2792
2793     netdev->n_txq = dev->requested_n_txq;
2794     dev->real_n_txq = 1;
2795     netdev->n_rxq = 1;
2796     dev->txq_needs_locking = dev->real_n_txq != netdev->n_txq;
2797
2798     ovs_mutex_unlock(&dev->mutex);
2799     ovs_mutex_unlock(&dpdk_mutex);
2800
2801     return 0;
2802 }
2803
2804 #define NETDEV_DPDK_CLASS(NAME, INIT, CONSTRUCT, DESTRUCT, SEND, \
2805                           GET_CARRIER, GET_STATS, GET_FEATURES,  \
2806                           GET_STATUS, RECONFIGURE, RXQ_RECV)     \
2807 {                                                             \
2808     NAME,                                                     \
2809     true,                       /* is_pmd */                  \
2810     INIT,                       /* init */                    \
2811     NULL,                       /* netdev_dpdk_run */         \
2812     NULL,                       /* netdev_dpdk_wait */        \
2813                                                               \
2814     netdev_dpdk_alloc,                                        \
2815     CONSTRUCT,                                                \
2816     DESTRUCT,                                                 \
2817     netdev_dpdk_dealloc,                                      \
2818     netdev_dpdk_get_config,                                   \
2819     netdev_dpdk_set_config,                                   \
2820     NULL,                       /* get_tunnel_config */       \
2821     NULL,                       /* build header */            \
2822     NULL,                       /* push header */             \
2823     NULL,                       /* pop header */              \
2824     netdev_dpdk_get_numa_id,    /* get_numa_id */             \
2825     netdev_dpdk_set_tx_multiq,                                \
2826                                                               \
2827     SEND,                       /* send */                    \
2828     NULL,                       /* send_wait */               \
2829                                                               \
2830     netdev_dpdk_set_etheraddr,                                \
2831     netdev_dpdk_get_etheraddr,                                \
2832     netdev_dpdk_get_mtu,                                      \
2833     netdev_dpdk_set_mtu,                                      \
2834     netdev_dpdk_get_ifindex,                                  \
2835     GET_CARRIER,                                              \
2836     netdev_dpdk_get_carrier_resets,                           \
2837     netdev_dpdk_set_miimon,                                   \
2838     GET_STATS,                                                \
2839     GET_FEATURES,                                             \
2840     NULL,                       /* set_advertisements */      \
2841                                                               \
2842     NULL,                       /* set_policing */            \
2843     netdev_dpdk_get_qos_types,                                \
2844     NULL,                       /* get_qos_capabilities */    \
2845     netdev_dpdk_get_qos,                                      \
2846     netdev_dpdk_set_qos,                                      \
2847     NULL,                       /* get_queue */               \
2848     NULL,                       /* set_queue */               \
2849     NULL,                       /* delete_queue */            \
2850     NULL,                       /* get_queue_stats */         \
2851     NULL,                       /* queue_dump_start */        \
2852     NULL,                       /* queue_dump_next */         \
2853     NULL,                       /* queue_dump_done */         \
2854     NULL,                       /* dump_queue_stats */        \
2855                                                               \
2856     NULL,                       /* set_in4 */                 \
2857     NULL,                       /* get_addr_list */           \
2858     NULL,                       /* add_router */              \
2859     NULL,                       /* get_next_hop */            \
2860     GET_STATUS,                                               \
2861     NULL,                       /* arp_lookup */              \
2862                                                               \
2863     netdev_dpdk_update_flags,                                 \
2864     RECONFIGURE,                                              \
2865                                                               \
2866     netdev_dpdk_rxq_alloc,                                    \
2867     netdev_dpdk_rxq_construct,                                \
2868     netdev_dpdk_rxq_destruct,                                 \
2869     netdev_dpdk_rxq_dealloc,                                  \
2870     RXQ_RECV,                                                 \
2871     NULL,                       /* rx_wait */                 \
2872     NULL,                       /* rxq_drain */               \
2873 }
2874
2875 static int
2876 process_vhost_flags(char *flag, char *default_val, int size,
2877                     const struct smap *ovs_other_config,
2878                     char **new_val)
2879 {
2880     const char *val;
2881     int changed = 0;
2882
2883     val = smap_get(ovs_other_config, flag);
2884
2885     /* Depending on which version of vhost is in use, process the vhost-specific
2886      * flag if it is provided, otherwise resort to default value.
2887      */
2888     if (val && (strlen(val) <= size)) {
2889         changed = 1;
2890         *new_val = xstrdup(val);
2891         VLOG_INFO("User-provided %s in use: %s", flag, *new_val);
2892     } else {
2893         VLOG_INFO("No %s provided - defaulting to %s", flag, default_val);
2894         *new_val = default_val;
2895     }
2896
2897     return changed;
2898 }
2899
2900 static char **
2901 grow_argv(char ***argv, size_t cur_siz, size_t grow_by)
2902 {
2903     return xrealloc(*argv, sizeof(char *) * (cur_siz + grow_by));
2904 }
2905
2906 static void
2907 dpdk_option_extend(char ***argv, int argc, const char *option,
2908                    const char *value)
2909 {
2910     char **newargv = grow_argv(argv, argc, 2);
2911     *argv = newargv;
2912     newargv[argc] = xstrdup(option);
2913     newargv[argc+1] = xstrdup(value);
2914 }
2915
2916 static char **
2917 move_argv(char ***argv, size_t cur_size, char **src_argv, size_t src_argc)
2918 {
2919     char **newargv = grow_argv(argv, cur_size, src_argc);
2920     while (src_argc--) {
2921         newargv[cur_size+src_argc] = src_argv[src_argc];
2922         src_argv[src_argc] = NULL;
2923     }
2924     return newargv;
2925 }
2926
2927 static int
2928 extra_dpdk_args(const char *ovs_extra_config, char ***argv, int argc)
2929 {
2930     int ret = argc;
2931     char *release_tok = xstrdup(ovs_extra_config);
2932     char *tok = release_tok, *endptr = NULL;
2933
2934     for (tok = strtok_r(release_tok, " ", &endptr); tok != NULL;
2935          tok = strtok_r(NULL, " ", &endptr)) {
2936         char **newarg = grow_argv(argv, ret, 1);
2937         *argv = newarg;
2938         newarg[ret++] = xstrdup(tok);
2939     }
2940     free(release_tok);
2941     return ret;
2942 }
2943
2944 static bool
2945 argv_contains(char **argv_haystack, const size_t argc_haystack,
2946               const char *needle)
2947 {
2948     for (size_t i = 0; i < argc_haystack; ++i) {
2949         if (!strcmp(argv_haystack[i], needle))
2950             return true;
2951     }
2952     return false;
2953 }
2954
2955 static int
2956 construct_dpdk_options(const struct smap *ovs_other_config,
2957                        char ***argv, const int initial_size,
2958                        char **extra_args, const size_t extra_argc)
2959 {
2960     struct dpdk_options_map {
2961         const char *ovs_configuration;
2962         const char *dpdk_option;
2963         bool default_enabled;
2964         const char *default_value;
2965     } opts[] = {
2966         {"dpdk-lcore-mask", "-c", false, NULL},
2967         {"dpdk-hugepage-dir", "--huge-dir", false, NULL},
2968     };
2969
2970     int i, ret = initial_size;
2971
2972     /*First, construct from the flat-options (non-mutex)*/
2973     for (i = 0; i < ARRAY_SIZE(opts); ++i) {
2974         const char *lookup = smap_get(ovs_other_config,
2975                                       opts[i].ovs_configuration);
2976         if (!lookup && opts[i].default_enabled) {
2977             lookup = opts[i].default_value;
2978         }
2979
2980         if (lookup) {
2981             if (!argv_contains(extra_args, extra_argc, opts[i].dpdk_option)) {
2982                 dpdk_option_extend(argv, ret, opts[i].dpdk_option, lookup);
2983                 ret += 2;
2984             } else {
2985                 VLOG_WARN("Ignoring database defined option '%s' due to "
2986                           "dpdk_extras config", opts[i].dpdk_option);
2987             }
2988         }
2989     }
2990
2991     return ret;
2992 }
2993
2994 #define MAX_DPDK_EXCL_OPTS 10
2995
2996 static int
2997 construct_dpdk_mutex_options(const struct smap *ovs_other_config,
2998                              char ***argv, const int initial_size,
2999                              char **extra_args, const size_t extra_argc)
3000 {
3001     struct dpdk_exclusive_options_map {
3002         const char *category;
3003         const char *ovs_dpdk_options[MAX_DPDK_EXCL_OPTS];
3004         const char *eal_dpdk_options[MAX_DPDK_EXCL_OPTS];
3005         const char *default_value;
3006         int default_option;
3007     } excl_opts[] = {
3008         {"memory type",
3009          {"dpdk-alloc-mem", "dpdk-socket-mem", NULL,},
3010          {"-m",             "--socket-mem",    NULL,},
3011          "1024,0", 1
3012         },
3013     };
3014
3015     int i, ret = initial_size;
3016     for (i = 0; i < ARRAY_SIZE(excl_opts); ++i) {
3017         int found_opts = 0, scan, found_pos = -1;
3018         const char *found_value;
3019         struct dpdk_exclusive_options_map *popt = &excl_opts[i];
3020
3021         for (scan = 0; scan < MAX_DPDK_EXCL_OPTS
3022                  && popt->ovs_dpdk_options[scan]; ++scan) {
3023             const char *lookup = smap_get(ovs_other_config,
3024                                           popt->ovs_dpdk_options[scan]);
3025             if (lookup && strlen(lookup)) {
3026                 found_opts++;
3027                 found_pos = scan;
3028                 found_value = lookup;
3029             }
3030         }
3031
3032         if (!found_opts) {
3033             if (popt->default_option) {
3034                 found_pos = popt->default_option;
3035                 found_value = popt->default_value;
3036             } else {
3037                 continue;
3038             }
3039         }
3040
3041         if (found_opts > 1) {
3042             VLOG_ERR("Multiple defined options for %s. Please check your"
3043                      " database settings and reconfigure if necessary.",
3044                      popt->category);
3045         }
3046
3047         if (!argv_contains(extra_args, extra_argc,
3048                            popt->eal_dpdk_options[found_pos])) {
3049             dpdk_option_extend(argv, ret, popt->eal_dpdk_options[found_pos],
3050                                found_value);
3051             ret += 2;
3052         } else {
3053             VLOG_WARN("Ignoring database defined option '%s' due to "
3054                       "dpdk_extras config", popt->eal_dpdk_options[found_pos]);
3055         }
3056     }
3057
3058     return ret;
3059 }
3060
3061 static int
3062 get_dpdk_args(const struct smap *ovs_other_config, char ***argv,
3063               int argc)
3064 {
3065     const char *extra_configuration;
3066     char **extra_args = NULL;
3067     int i;
3068     size_t extra_argc = 0;
3069
3070     extra_configuration = smap_get(ovs_other_config, "dpdk-extra");
3071     if (extra_configuration) {
3072         extra_argc = extra_dpdk_args(extra_configuration, &extra_args, 0);
3073     }
3074
3075     i = construct_dpdk_options(ovs_other_config, argv, argc, extra_args,
3076                                extra_argc);
3077     i = construct_dpdk_mutex_options(ovs_other_config, argv, i, extra_args,
3078                                      extra_argc);
3079
3080     if (extra_configuration) {
3081         *argv = move_argv(argv, i, extra_args, extra_argc);
3082     }
3083
3084     return i + extra_argc;
3085 }
3086
3087 static char **dpdk_argv;
3088 static int dpdk_argc;
3089
3090 static void
3091 deferred_argv_release(void)
3092 {
3093     int result;
3094     for (result = 0; result < dpdk_argc; ++result) {
3095         free(dpdk_argv[result]);
3096     }
3097
3098     free(dpdk_argv);
3099 }
3100
3101 static void
3102 dpdk_init__(const struct smap *ovs_other_config)
3103 {
3104     char **argv = NULL;
3105     int result;
3106     int argc, argc_tmp;
3107     bool auto_determine = true;
3108     int err = 0;
3109     cpu_set_t cpuset;
3110 #ifndef VHOST_CUSE
3111     char *sock_dir_subcomponent;
3112 #endif
3113
3114     if (!smap_get_bool(ovs_other_config, "dpdk-init", false)) {
3115         VLOG_INFO("DPDK Disabled - to change this requires a restart.\n");
3116         return;
3117     }
3118
3119     VLOG_INFO("DPDK Enabled, initializing");
3120
3121 #ifdef VHOST_CUSE
3122     if (process_vhost_flags("cuse-dev-name", xstrdup("vhost-net"),
3123                             PATH_MAX, ovs_other_config, &cuse_dev_name)) {
3124 #else
3125     if (process_vhost_flags("vhost-sock-dir", xstrdup(ovs_rundir()),
3126                             NAME_MAX, ovs_other_config,
3127                             &sock_dir_subcomponent)) {
3128         struct stat s;
3129         if (!strstr(sock_dir_subcomponent, "..")) {
3130             vhost_sock_dir = xasprintf("%s/%s", ovs_rundir(),
3131                                        sock_dir_subcomponent);
3132
3133             err = stat(vhost_sock_dir, &s);
3134             if (err) {
3135                 VLOG_ERR("vhost-user sock directory '%s' does not exist.",
3136                          vhost_sock_dir);
3137             }
3138         } else {
3139             vhost_sock_dir = xstrdup(ovs_rundir());
3140             VLOG_ERR("vhost-user sock directory request '%s/%s' has invalid"
3141                      "characters '..' - using %s instead.",
3142                      ovs_rundir(), sock_dir_subcomponent, ovs_rundir());
3143         }
3144         free(sock_dir_subcomponent);
3145     } else {
3146         vhost_sock_dir = sock_dir_subcomponent;
3147 #endif
3148     }
3149
3150     argv = grow_argv(&argv, 0, 1);
3151     argc = 1;
3152     argv[0] = xstrdup(ovs_get_program_name());
3153     argc_tmp = get_dpdk_args(ovs_other_config, &argv, argc);
3154
3155     while (argc_tmp != argc) {
3156         if (!strcmp("-c", argv[argc]) || !strcmp("-l", argv[argc])) {
3157             auto_determine = false;
3158             break;
3159         }
3160         argc++;
3161     }
3162     argc = argc_tmp;
3163
3164     /**
3165      * NOTE: This is an unsophisticated mechanism for determining the DPDK
3166      * lcore for the DPDK Master.
3167      */
3168     if (auto_determine) {
3169         int i;
3170         /* Get the main thread affinity */
3171         CPU_ZERO(&cpuset);
3172         err = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t),
3173                                      &cpuset);
3174         if (!err) {
3175             for (i = 0; i < CPU_SETSIZE; i++) {
3176                 if (CPU_ISSET(i, &cpuset)) {
3177                     argv = grow_argv(&argv, argc, 2);
3178                     argv[argc++] = xstrdup("-c");
3179                     argv[argc++] = xasprintf("0x%08llX", (1ULL<<i));
3180                     i = CPU_SETSIZE;
3181                 }
3182             }
3183         } else {
3184             VLOG_ERR("Thread getaffinity error %d. Using core 0x1", err);
3185             /* User did not set dpdk-lcore-mask and unable to get current
3186              * thread affintity - default to core 0x1 */
3187             argv = grow_argv(&argv, argc, 2);
3188             argv[argc++] = xstrdup("-c");
3189             argv[argc++] = xasprintf("0x%X", 1);
3190         }
3191     }
3192
3193     argv = grow_argv(&argv, argc, 1);
3194     argv[argc] = NULL;
3195
3196     optind = 1;
3197
3198     if (VLOG_IS_INFO_ENABLED()) {
3199         struct ds eal_args;
3200         int opt;
3201         ds_init(&eal_args);
3202         ds_put_cstr(&eal_args, "EAL ARGS:");
3203         for (opt = 0; opt < argc; ++opt) {
3204             ds_put_cstr(&eal_args, " ");
3205             ds_put_cstr(&eal_args, argv[opt]);
3206         }
3207         VLOG_INFO("%s", ds_cstr_ro(&eal_args));
3208         ds_destroy(&eal_args);
3209     }
3210
3211     /* Make sure things are initialized ... */
3212     result = rte_eal_init(argc, argv);
3213     if (result < 0) {
3214         ovs_abort(result, "Cannot init EAL");
3215     }
3216
3217     /* Set the main thread affinity back to pre rte_eal_init() value */
3218     if (auto_determine && !err) {
3219         err = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t),
3220                                      &cpuset);
3221         if (err) {
3222             VLOG_ERR("Thread setaffinity error %d", err);
3223         }
3224     }
3225
3226     dpdk_argv = argv;
3227     dpdk_argc = argc;
3228
3229     atexit(deferred_argv_release);
3230
3231     rte_memzone_dump(stdout);
3232     rte_eal_init_ret = 0;
3233
3234     /* We are called from the main thread here */
3235     RTE_PER_LCORE(_lcore_id) = NON_PMD_CORE_ID;
3236
3237     ovs_thread_create("dpdk_watchdog", dpdk_watchdog, NULL);
3238
3239 #ifdef VHOST_CUSE
3240     /* Register CUSE device to handle IOCTLs.
3241      * Unless otherwise specified, cuse_dev_name is set to vhost-net.
3242      */
3243     err = rte_vhost_driver_register(cuse_dev_name);
3244
3245     if (err != 0) {
3246         VLOG_ERR("CUSE device setup failure.");
3247         return;
3248     }
3249 #endif
3250
3251     dpdk_vhost_class_init();
3252
3253     /* Finally, register the dpdk classes */
3254     netdev_dpdk_register();
3255 }
3256
3257 void
3258 dpdk_init(const struct smap *ovs_other_config)
3259 {
3260     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
3261
3262     if (ovs_other_config && ovsthread_once_start(&once)) {
3263         dpdk_init__(ovs_other_config);
3264         ovsthread_once_done(&once);
3265     }
3266 }
3267
3268 static const struct netdev_class dpdk_class =
3269     NETDEV_DPDK_CLASS(
3270         "dpdk",
3271         NULL,
3272         netdev_dpdk_construct,
3273         netdev_dpdk_destruct,
3274         netdev_dpdk_eth_send,
3275         netdev_dpdk_get_carrier,
3276         netdev_dpdk_get_stats,
3277         netdev_dpdk_get_features,
3278         netdev_dpdk_get_status,
3279         netdev_dpdk_reconfigure,
3280         netdev_dpdk_rxq_recv);
3281
3282 static const struct netdev_class dpdk_ring_class =
3283     NETDEV_DPDK_CLASS(
3284         "dpdkr",
3285         NULL,
3286         netdev_dpdk_ring_construct,
3287         netdev_dpdk_destruct,
3288         netdev_dpdk_ring_send,
3289         netdev_dpdk_get_carrier,
3290         netdev_dpdk_get_stats,
3291         netdev_dpdk_get_features,
3292         netdev_dpdk_get_status,
3293         netdev_dpdk_reconfigure,
3294         netdev_dpdk_rxq_recv);
3295
3296 static const struct netdev_class OVS_UNUSED dpdk_vhost_cuse_class =
3297     NETDEV_DPDK_CLASS(
3298         "dpdkvhostcuse",
3299         dpdk_vhost_cuse_class_init,
3300         netdev_dpdk_vhost_cuse_construct,
3301         netdev_dpdk_vhost_destruct,
3302         netdev_dpdk_vhost_send,
3303         netdev_dpdk_vhost_get_carrier,
3304         netdev_dpdk_vhost_get_stats,
3305         NULL,
3306         NULL,
3307         netdev_dpdk_vhost_cuse_reconfigure,
3308         netdev_dpdk_vhost_rxq_recv);
3309
3310 static const struct netdev_class OVS_UNUSED dpdk_vhost_user_class =
3311     NETDEV_DPDK_CLASS(
3312         "dpdkvhostuser",
3313         dpdk_vhost_user_class_init,
3314         netdev_dpdk_vhost_user_construct,
3315         netdev_dpdk_vhost_destruct,
3316         netdev_dpdk_vhost_send,
3317         netdev_dpdk_vhost_get_carrier,
3318         netdev_dpdk_vhost_get_stats,
3319         NULL,
3320         NULL,
3321         netdev_dpdk_vhost_user_reconfigure,
3322         netdev_dpdk_vhost_rxq_recv);
3323
3324 void
3325 netdev_dpdk_register(void)
3326 {
3327     dpdk_common_init();
3328     netdev_register_provider(&dpdk_class);
3329     netdev_register_provider(&dpdk_ring_class);
3330 #ifdef VHOST_CUSE
3331     netdev_register_provider(&dpdk_vhost_cuse_class);
3332 #else
3333     netdev_register_provider(&dpdk_vhost_user_class);
3334 #endif
3335 }
3336
3337 int
3338 pmd_thread_setaffinity_cpu(unsigned cpu)
3339 {
3340     cpu_set_t cpuset;
3341     int err;
3342
3343     CPU_ZERO(&cpuset);
3344     CPU_SET(cpu, &cpuset);
3345     err = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
3346     if (err) {
3347         VLOG_ERR("Thread affinity error %d",err);
3348         return err;
3349     }
3350     /* NON_PMD_CORE_ID is reserved for use by non pmd threads. */
3351     ovs_assert(cpu != NON_PMD_CORE_ID);
3352     RTE_PER_LCORE(_lcore_id) = cpu;
3353
3354     return 0;
3355 }
3356
3357 static bool
3358 dpdk_thread_is_pmd(void)
3359 {
3360     return rte_lcore_id() != NON_PMD_CORE_ID;
3361 }