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