71034a0eb96eedbf6fc10fa61b0d567f32ee3c2e
[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
33 #include "dirs.h"
34 #include "dp-packet.h"
35 #include "dpif-netdev.h"
36 #include "fatal-signal.h"
37 #include "list.h"
38 #include "netdev-dpdk.h"
39 #include "netdev-provider.h"
40 #include "netdev-vport.h"
41 #include "odp-util.h"
42 #include "ofp-print.h"
43 #include "ovs-numa.h"
44 #include "ovs-thread.h"
45 #include "ovs-rcu.h"
46 #include "packets.h"
47 #include "shash.h"
48 #include "sset.h"
49 #include "unaligned.h"
50 #include "timeval.h"
51 #include "unixctl.h"
52 #include "openvswitch/vlog.h"
53
54 #include "rte_config.h"
55 #include "rte_mbuf.h"
56 #include "rte_virtio_net.h"
57
58 VLOG_DEFINE_THIS_MODULE(dpdk);
59 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
60
61 #define DPDK_PORT_WATCHDOG_INTERVAL 5
62
63 #define OVS_CACHE_LINE_SIZE CACHE_LINE_SIZE
64 #define OVS_VPORT_DPDK "ovs_dpdk"
65
66 /*
67  * need to reserve tons of extra space in the mbufs so we can align the
68  * DMA addresses to 4KB.
69  * The minimum mbuf size is limited to avoid scatter behaviour and drop in
70  * performance for standard Ethernet MTU.
71  */
72 #define MTU_TO_MAX_LEN(mtu)  ((mtu) + ETHER_HDR_LEN + ETHER_CRC_LEN)
73 #define MBUF_SIZE_MTU(mtu)   (MTU_TO_MAX_LEN(mtu)        \
74                               + sizeof(struct dp_packet) \
75                               + RTE_PKTMBUF_HEADROOM)
76 #define MBUF_SIZE_DRIVER     (2048                       \
77                               + sizeof (struct rte_mbuf) \
78                               + RTE_PKTMBUF_HEADROOM)
79 #define MBUF_SIZE(mtu)       MAX(MBUF_SIZE_MTU(mtu), MBUF_SIZE_DRIVER)
80
81 /* Max and min number of packets in the mempool.  OVS tries to allocate a
82  * mempool with MAX_NB_MBUF: if this fails (because the system doesn't have
83  * enough hugepages) we keep halving the number until the allocation succeeds
84  * or we reach MIN_NB_MBUF */
85
86 #define MAX_NB_MBUF          (4096 * 64)
87 #define MIN_NB_MBUF          (4096 * 4)
88 #define MP_CACHE_SZ          RTE_MEMPOOL_CACHE_MAX_SIZE
89
90 /* MAX_NB_MBUF can be divided by 2 many times, until MIN_NB_MBUF */
91 BUILD_ASSERT_DECL(MAX_NB_MBUF % ROUND_DOWN_POW2(MAX_NB_MBUF/MIN_NB_MBUF) == 0);
92
93 /* The smallest possible NB_MBUF that we're going to try should be a multiple
94  * of MP_CACHE_SZ. This is advised by DPDK documentation. */
95 BUILD_ASSERT_DECL((MAX_NB_MBUF / ROUND_DOWN_POW2(MAX_NB_MBUF/MIN_NB_MBUF))
96                   % MP_CACHE_SZ == 0);
97
98 #define SOCKET0              0
99
100 #define NIC_PORT_RX_Q_SIZE 2048  /* Size of Physical NIC RX Queue, Max (n+32<=4096)*/
101 #define NIC_PORT_TX_Q_SIZE 2048  /* Size of Physical NIC TX Queue, Max (n+32<=4096)*/
102
103 static char *cuse_dev_name = NULL;    /* Character device cuse_dev_name. */
104 static char *vhost_sock_dir = NULL;   /* Location of vhost-user sockets */
105
106 /*
107  * Maximum amount of time in micro seconds to try and enqueue to vhost.
108  */
109 #define VHOST_ENQ_RETRY_USECS 100
110
111 static const struct rte_eth_conf port_conf = {
112     .rxmode = {
113         .mq_mode = ETH_MQ_RX_RSS,
114         .split_hdr_size = 0,
115         .header_split   = 0, /* Header Split disabled */
116         .hw_ip_checksum = 0, /* IP checksum offload disabled */
117         .hw_vlan_filter = 0, /* VLAN filtering disabled */
118         .jumbo_frame    = 0, /* Jumbo Frame Support disabled */
119         .hw_strip_crc   = 0,
120     },
121     .rx_adv_conf = {
122         .rss_conf = {
123             .rss_key = NULL,
124             .rss_hf = ETH_RSS_IP | ETH_RSS_UDP | ETH_RSS_TCP,
125         },
126     },
127     .txmode = {
128         .mq_mode = ETH_MQ_TX_NONE,
129     },
130 };
131
132 enum { MAX_TX_QUEUE_LEN = 384 };
133 enum { DPDK_RING_SIZE = 256 };
134 BUILD_ASSERT_DECL(IS_POW2(DPDK_RING_SIZE));
135 enum { DRAIN_TSC = 200000ULL };
136
137 enum dpdk_dev_type {
138     DPDK_DEV_ETH = 0,
139     DPDK_DEV_VHOST = 1,
140 };
141
142 static int rte_eal_init_ret = ENODEV;
143
144 static struct ovs_mutex dpdk_mutex = OVS_MUTEX_INITIALIZER;
145
146 /* Contains all 'struct dpdk_dev's. */
147 static struct ovs_list dpdk_list OVS_GUARDED_BY(dpdk_mutex)
148     = OVS_LIST_INITIALIZER(&dpdk_list);
149
150 static struct ovs_list dpdk_mp_list OVS_GUARDED_BY(dpdk_mutex)
151     = OVS_LIST_INITIALIZER(&dpdk_mp_list);
152
153 /* This mutex must be used by non pmd threads when allocating or freeing
154  * mbufs through mempools. Since dpdk_queue_pkts() and dpdk_queue_flush() may
155  * use mempools, a non pmd thread should hold this mutex while calling them */
156 static struct ovs_mutex nonpmd_mempool_mutex = OVS_MUTEX_INITIALIZER;
157
158 struct dpdk_mp {
159     struct rte_mempool *mp;
160     int mtu;
161     int socket_id;
162     int refcount;
163     struct ovs_list list_node OVS_GUARDED_BY(dpdk_mutex);
164 };
165
166 /* There should be one 'struct dpdk_tx_queue' created for
167  * each cpu core. */
168 struct dpdk_tx_queue {
169     bool flush_tx;                 /* Set to true to flush queue everytime */
170                                    /* pkts are queued. */
171     int count;
172     rte_spinlock_t tx_lock;        /* Protects the members and the NIC queue
173                                     * from concurrent access.  It is used only
174                                     * if the queue is shared among different
175                                     * pmd threads (see 'txq_needs_locking'). */
176     uint64_t tsc;
177     struct rte_mbuf *burst_pkts[MAX_TX_QUEUE_LEN];
178 };
179
180 /* dpdk has no way to remove dpdk ring ethernet devices
181    so we have to keep them around once they've been created
182 */
183
184 static struct ovs_list dpdk_ring_list OVS_GUARDED_BY(dpdk_mutex)
185     = OVS_LIST_INITIALIZER(&dpdk_ring_list);
186
187 struct dpdk_ring {
188     /* For the client rings */
189     struct rte_ring *cring_tx;
190     struct rte_ring *cring_rx;
191     unsigned int user_port_id; /* User given port no, parsed from port name */
192     int eth_port_id; /* ethernet device port id */
193     struct ovs_list list_node OVS_GUARDED_BY(dpdk_mutex);
194 };
195
196 struct netdev_dpdk {
197     struct netdev up;
198     int port_id;
199     int max_packet_len;
200     enum dpdk_dev_type type;
201
202     struct dpdk_tx_queue *tx_q;
203
204     struct ovs_mutex mutex OVS_ACQ_AFTER(dpdk_mutex);
205
206     struct dpdk_mp *dpdk_mp;
207     int mtu;
208     int socket_id;
209     int buf_size;
210     struct netdev_stats stats;
211     /* Protects stats */
212     rte_spinlock_t stats_lock;
213
214     struct eth_addr hwaddr;
215     enum netdev_flags flags;
216
217     struct rte_eth_link link;
218     int link_reset_cnt;
219
220     /* The user might request more txqs than the NIC has.  We remap those
221      * ('up.n_txq') on these ('real_n_txq').
222      * If the numbers match, 'txq_needs_locking' is false, otherwise it is
223      * true and we will take a spinlock on transmission */
224     int real_n_txq;
225     int real_n_rxq;
226     bool txq_needs_locking;
227
228     /* virtio-net structure for vhost device */
229     OVSRCU_TYPE(struct virtio_net *) virtio_dev;
230
231     /* Identifier used to distinguish vhost devices from each other */
232     char vhost_id[PATH_MAX];
233
234     /* In dpdk_list. */
235     struct ovs_list list_node OVS_GUARDED_BY(dpdk_mutex);
236 };
237
238 struct netdev_rxq_dpdk {
239     struct netdev_rxq up;
240     int port_id;
241 };
242
243 static bool dpdk_thread_is_pmd(void);
244
245 static int netdev_dpdk_construct(struct netdev *);
246
247 struct virtio_net * netdev_dpdk_get_virtio(const struct netdev_dpdk *dev);
248
249 static bool
250 is_dpdk_class(const struct netdev_class *class)
251 {
252     return class->construct == netdev_dpdk_construct;
253 }
254
255 /* XXX: use dpdk malloc for entire OVS. in fact huge page should be used
256  * for all other segments data, bss and text. */
257
258 static void *
259 dpdk_rte_mzalloc(size_t sz)
260 {
261     void *ptr;
262
263     ptr = rte_zmalloc(OVS_VPORT_DPDK, sz, OVS_CACHE_LINE_SIZE);
264     if (ptr == NULL) {
265         out_of_memory();
266     }
267     return ptr;
268 }
269
270 /* XXX this function should be called only by pmd threads (or by non pmd
271  * threads holding the nonpmd_mempool_mutex) */
272 void
273 free_dpdk_buf(struct dp_packet *p)
274 {
275     struct rte_mbuf *pkt = (struct rte_mbuf *) p;
276
277     rte_pktmbuf_free_seg(pkt);
278 }
279
280 static void
281 __rte_pktmbuf_init(struct rte_mempool *mp,
282                    void *opaque_arg OVS_UNUSED,
283                    void *_m,
284                    unsigned i OVS_UNUSED)
285 {
286     struct rte_mbuf *m = _m;
287     uint32_t buf_len = mp->elt_size - sizeof(struct dp_packet);
288
289     RTE_MBUF_ASSERT(mp->elt_size >= sizeof(struct dp_packet));
290
291     memset(m, 0, mp->elt_size);
292
293     /* start of buffer is just after mbuf structure */
294     m->buf_addr = (char *)m + sizeof(struct dp_packet);
295     m->buf_physaddr = rte_mempool_virt2phy(mp, m) +
296                     sizeof(struct dp_packet);
297     m->buf_len = (uint16_t)buf_len;
298
299     /* keep some headroom between start of buffer and data */
300     m->data_off = RTE_MIN(RTE_PKTMBUF_HEADROOM, m->buf_len);
301
302     /* init some constant fields */
303     m->pool = mp;
304     m->nb_segs = 1;
305     m->port = 0xff;
306 }
307
308 static void
309 ovs_rte_pktmbuf_init(struct rte_mempool *mp,
310                      void *opaque_arg OVS_UNUSED,
311                      void *_m,
312                      unsigned i OVS_UNUSED)
313 {
314     struct rte_mbuf *m = _m;
315
316     __rte_pktmbuf_init(mp, opaque_arg, _m, i);
317
318     dp_packet_init_dpdk((struct dp_packet *) m, m->buf_len);
319 }
320
321 static struct dpdk_mp *
322 dpdk_mp_get(int socket_id, int mtu) OVS_REQUIRES(dpdk_mutex)
323 {
324     struct dpdk_mp *dmp = NULL;
325     char mp_name[RTE_MEMPOOL_NAMESIZE];
326     unsigned mp_size;
327
328     LIST_FOR_EACH (dmp, list_node, &dpdk_mp_list) {
329         if (dmp->socket_id == socket_id && dmp->mtu == mtu) {
330             dmp->refcount++;
331             return dmp;
332         }
333     }
334
335     dmp = dpdk_rte_mzalloc(sizeof *dmp);
336     dmp->socket_id = socket_id;
337     dmp->mtu = mtu;
338     dmp->refcount = 1;
339
340     mp_size = MAX_NB_MBUF;
341     do {
342         if (snprintf(mp_name, RTE_MEMPOOL_NAMESIZE, "ovs_mp_%d_%d_%u",
343                      dmp->mtu, dmp->socket_id, mp_size) < 0) {
344             return NULL;
345         }
346
347         dmp->mp = rte_mempool_create(mp_name, mp_size, MBUF_SIZE(mtu),
348                                      MP_CACHE_SZ,
349                                      sizeof(struct rte_pktmbuf_pool_private),
350                                      rte_pktmbuf_pool_init, NULL,
351                                      ovs_rte_pktmbuf_init, NULL,
352                                      socket_id, 0);
353     } while (!dmp->mp && rte_errno == ENOMEM && (mp_size /= 2) >= MIN_NB_MBUF);
354
355     if (dmp->mp == NULL) {
356         return NULL;
357     } else {
358         VLOG_DBG("Allocated \"%s\" mempool with %u mbufs", mp_name, mp_size );
359     }
360
361     list_push_back(&dpdk_mp_list, &dmp->list_node);
362     return dmp;
363 }
364
365 static void
366 dpdk_mp_put(struct dpdk_mp *dmp)
367 {
368
369     if (!dmp) {
370         return;
371     }
372
373     dmp->refcount--;
374     ovs_assert(dmp->refcount >= 0);
375
376 #if 0
377     /* I could not find any API to destroy mp. */
378     if (dmp->refcount == 0) {
379         list_delete(dmp->list_node);
380         /* destroy mp-pool. */
381     }
382 #endif
383 }
384
385 static void
386 check_link_status(struct netdev_dpdk *dev)
387 {
388     struct rte_eth_link link;
389
390     rte_eth_link_get_nowait(dev->port_id, &link);
391
392     if (dev->link.link_status != link.link_status) {
393         netdev_change_seq_changed(&dev->up);
394
395         dev->link_reset_cnt++;
396         dev->link = link;
397         if (dev->link.link_status) {
398             VLOG_DBG_RL(&rl, "Port %d Link Up - speed %u Mbps - %s",
399                         dev->port_id, (unsigned)dev->link.link_speed,
400                         (dev->link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
401                          ("full-duplex") : ("half-duplex"));
402         } else {
403             VLOG_DBG_RL(&rl, "Port %d Link Down", dev->port_id);
404         }
405     }
406 }
407
408 static void *
409 dpdk_watchdog(void *dummy OVS_UNUSED)
410 {
411     struct netdev_dpdk *dev;
412
413     pthread_detach(pthread_self());
414
415     for (;;) {
416         ovs_mutex_lock(&dpdk_mutex);
417         LIST_FOR_EACH (dev, list_node, &dpdk_list) {
418             ovs_mutex_lock(&dev->mutex);
419             check_link_status(dev);
420             ovs_mutex_unlock(&dev->mutex);
421         }
422         ovs_mutex_unlock(&dpdk_mutex);
423         xsleep(DPDK_PORT_WATCHDOG_INTERVAL);
424     }
425
426     return NULL;
427 }
428
429 static int
430 dpdk_eth_dev_queue_setup(struct netdev_dpdk *dev, int n_rxq, int n_txq)
431 {
432     int diag = 0;
433     int i;
434
435     /* A device may report more queues than it makes available (this has
436      * been observed for Intel xl710, which reserves some of them for
437      * SRIOV):  rte_eth_*_queue_setup will fail if a queue is not
438      * available.  When this happens we can retry the configuration
439      * and request less queues */
440     while (n_rxq && n_txq) {
441         if (diag) {
442             VLOG_INFO("Retrying setup with (rxq:%d txq:%d)", n_rxq, n_txq);
443         }
444
445         diag = rte_eth_dev_configure(dev->port_id, n_rxq, n_txq, &port_conf);
446         if (diag) {
447             break;
448         }
449
450         for (i = 0; i < n_txq; i++) {
451             diag = rte_eth_tx_queue_setup(dev->port_id, i, NIC_PORT_TX_Q_SIZE,
452                                           dev->socket_id, NULL);
453             if (diag) {
454                 VLOG_INFO("Interface %s txq(%d) setup error: %s",
455                           dev->up.name, i, rte_strerror(-diag));
456                 break;
457             }
458         }
459
460         if (i != n_txq) {
461             /* Retry with less tx queues */
462             n_txq = i;
463             continue;
464         }
465
466         for (i = 0; i < n_rxq; i++) {
467             diag = rte_eth_rx_queue_setup(dev->port_id, i, NIC_PORT_RX_Q_SIZE,
468                                           dev->socket_id, NULL,
469                                           dev->dpdk_mp->mp);
470             if (diag) {
471                 VLOG_INFO("Interface %s rxq(%d) setup error: %s",
472                           dev->up.name, i, rte_strerror(-diag));
473                 break;
474             }
475         }
476
477         if (i != n_rxq) {
478             /* Retry with less rx queues */
479             n_rxq = i;
480             continue;
481         }
482
483         dev->up.n_rxq = n_rxq;
484         dev->real_n_txq = n_txq;
485
486         return 0;
487     }
488
489     return diag;
490 }
491
492
493 static int
494 dpdk_eth_dev_init(struct netdev_dpdk *dev) OVS_REQUIRES(dpdk_mutex)
495 {
496     struct rte_pktmbuf_pool_private *mbp_priv;
497     struct rte_eth_dev_info info;
498     struct ether_addr eth_addr;
499     int diag;
500     int n_rxq, n_txq;
501
502     if (dev->port_id < 0 || dev->port_id >= rte_eth_dev_count()) {
503         return ENODEV;
504     }
505
506     rte_eth_dev_info_get(dev->port_id, &info);
507
508     n_rxq = MIN(info.max_rx_queues, dev->up.n_rxq);
509     n_txq = MIN(info.max_tx_queues, dev->up.n_txq);
510
511     diag = dpdk_eth_dev_queue_setup(dev, n_rxq, n_txq);
512     if (diag) {
513         VLOG_ERR("Interface %s(rxq:%d txq:%d) configure error: %s",
514                  dev->up.name, n_rxq, n_txq, rte_strerror(-diag));
515         return -diag;
516     }
517
518     diag = rte_eth_dev_start(dev->port_id);
519     if (diag) {
520         VLOG_ERR("Interface %s start error: %s", dev->up.name,
521                  rte_strerror(-diag));
522         return -diag;
523     }
524
525     rte_eth_promiscuous_enable(dev->port_id);
526     rte_eth_allmulticast_enable(dev->port_id);
527
528     memset(&eth_addr, 0x0, sizeof(eth_addr));
529     rte_eth_macaddr_get(dev->port_id, &eth_addr);
530     VLOG_INFO_RL(&rl, "Port %d: "ETH_ADDR_FMT"",
531                     dev->port_id, ETH_ADDR_BYTES_ARGS(eth_addr.addr_bytes));
532
533     memcpy(dev->hwaddr.ea, eth_addr.addr_bytes, ETH_ADDR_LEN);
534     rte_eth_link_get_nowait(dev->port_id, &dev->link);
535
536     mbp_priv = rte_mempool_get_priv(dev->dpdk_mp->mp);
537     dev->buf_size = mbp_priv->mbuf_data_room_size - RTE_PKTMBUF_HEADROOM;
538
539     dev->flags = NETDEV_UP | NETDEV_PROMISC;
540     return 0;
541 }
542
543 static struct netdev_dpdk *
544 netdev_dpdk_cast(const struct netdev *netdev)
545 {
546     return CONTAINER_OF(netdev, struct netdev_dpdk, up);
547 }
548
549 static struct netdev *
550 netdev_dpdk_alloc(void)
551 {
552     struct netdev_dpdk *netdev = dpdk_rte_mzalloc(sizeof *netdev);
553     return &netdev->up;
554 }
555
556 static void
557 netdev_dpdk_alloc_txq(struct netdev_dpdk *netdev, unsigned int n_txqs)
558 {
559     unsigned i;
560
561     netdev->tx_q = dpdk_rte_mzalloc(n_txqs * sizeof *netdev->tx_q);
562     for (i = 0; i < n_txqs; i++) {
563         int numa_id = ovs_numa_get_numa_id(i);
564
565         if (!netdev->txq_needs_locking) {
566             /* Each index is considered as a cpu core id, since there should
567              * be one tx queue for each cpu core.  If the corresponding core
568              * is not on the same numa node as 'netdev', flags the
569              * 'flush_tx'. */
570             netdev->tx_q[i].flush_tx = netdev->socket_id == numa_id;
571         } else {
572             /* Queues are shared among CPUs. Always flush */
573             netdev->tx_q[i].flush_tx = true;
574         }
575         rte_spinlock_init(&netdev->tx_q[i].tx_lock);
576     }
577 }
578
579 static int
580 netdev_dpdk_init(struct netdev *netdev_, unsigned int port_no,
581                  enum dpdk_dev_type type)
582     OVS_REQUIRES(dpdk_mutex)
583 {
584     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
585     int sid;
586     int err = 0;
587
588     ovs_mutex_init(&netdev->mutex);
589     ovs_mutex_lock(&netdev->mutex);
590
591     rte_spinlock_init(&netdev->stats_lock);
592
593     /* If the 'sid' is negative, it means that the kernel fails
594      * to obtain the pci numa info.  In that situation, always
595      * use 'SOCKET0'. */
596     if (type == DPDK_DEV_ETH) {
597         sid = rte_eth_dev_socket_id(port_no);
598     } else {
599         sid = rte_lcore_to_socket_id(rte_get_master_lcore());
600     }
601
602     netdev->socket_id = sid < 0 ? SOCKET0 : sid;
603     netdev->port_id = port_no;
604     netdev->type = type;
605     netdev->flags = 0;
606     netdev->mtu = ETHER_MTU;
607     netdev->max_packet_len = MTU_TO_MAX_LEN(netdev->mtu);
608
609     netdev->dpdk_mp = dpdk_mp_get(netdev->socket_id, netdev->mtu);
610     if (!netdev->dpdk_mp) {
611         err = ENOMEM;
612         goto unlock;
613     }
614
615     netdev_->n_txq = NR_QUEUE;
616     netdev_->n_rxq = NR_QUEUE;
617     netdev_->requested_n_rxq = NR_QUEUE;
618     netdev->real_n_txq = NR_QUEUE;
619
620     if (type == DPDK_DEV_ETH) {
621         netdev_dpdk_alloc_txq(netdev, NR_QUEUE);
622         err = dpdk_eth_dev_init(netdev);
623         if (err) {
624             goto unlock;
625         }
626     }
627
628     list_push_back(&dpdk_list, &netdev->list_node);
629
630 unlock:
631     if (err) {
632         rte_free(netdev->tx_q);
633     }
634     ovs_mutex_unlock(&netdev->mutex);
635     return err;
636 }
637
638 /* dev_name must be the prefix followed by a positive decimal number.
639  * (no leading + or - signs are allowed) */
640 static int
641 dpdk_dev_parse_name(const char dev_name[], const char prefix[],
642                     unsigned int *port_no)
643 {
644     const char *cport;
645
646     if (strncmp(dev_name, prefix, strlen(prefix))) {
647         return ENODEV;
648     }
649
650     cport = dev_name + strlen(prefix);
651
652     if (str_to_uint(cport, 10, port_no)) {
653         return 0;
654     } else {
655         return ENODEV;
656     }
657 }
658
659 static int
660 vhost_construct_helper(struct netdev *netdev_) OVS_REQUIRES(dpdk_mutex)
661 {
662     if (rte_eal_init_ret) {
663         return rte_eal_init_ret;
664     }
665
666     return netdev_dpdk_init(netdev_, -1, DPDK_DEV_VHOST);
667 }
668
669 static int
670 netdev_dpdk_vhost_cuse_construct(struct netdev *netdev_)
671 {
672     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
673     int err;
674
675     ovs_mutex_lock(&dpdk_mutex);
676     strncpy(netdev->vhost_id, netdev->up.name, sizeof(netdev->vhost_id));
677     err = vhost_construct_helper(netdev_);
678     ovs_mutex_unlock(&dpdk_mutex);
679     return err;
680 }
681
682 static int
683 netdev_dpdk_vhost_user_construct(struct netdev *netdev_)
684 {
685     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
686     const char *name = netdev_->name;
687     int err;
688
689     /* 'name' is appended to 'vhost_sock_dir' and used to create a socket in
690      * the file system. '/' or '\' would traverse directories, so they're not
691      * acceptable in 'name'. */
692     if (strchr(name, '/') || strchr(name, '\\')) {
693         VLOG_ERR("\"%s\" is not a valid name for a vhost-user port. "
694                  "A valid name must not include '/' or '\\'",
695                  name);
696         return EINVAL;
697     }
698
699     ovs_mutex_lock(&dpdk_mutex);
700     /* Take the name of the vhost-user port and append it to the location where
701      * the socket is to be created, then register the socket.
702      */
703     snprintf(netdev->vhost_id, sizeof(netdev->vhost_id), "%s/%s",
704              vhost_sock_dir, name);
705
706     err = rte_vhost_driver_register(netdev->vhost_id);
707     if (err) {
708         VLOG_ERR("vhost-user socket device setup failure for socket %s\n",
709                  netdev->vhost_id);
710     } else {
711         fatal_signal_add_file_to_unlink(netdev->vhost_id);
712         VLOG_INFO("Socket %s created for vhost-user port %s\n",
713                   netdev->vhost_id, name);
714         err = vhost_construct_helper(netdev_);
715     }
716
717     ovs_mutex_unlock(&dpdk_mutex);
718     return err;
719 }
720
721 static int
722 netdev_dpdk_construct(struct netdev *netdev)
723 {
724     unsigned int port_no;
725     int err;
726
727     if (rte_eal_init_ret) {
728         return rte_eal_init_ret;
729     }
730
731     /* Names always start with "dpdk" */
732     err = dpdk_dev_parse_name(netdev->name, "dpdk", &port_no);
733     if (err) {
734         return err;
735     }
736
737     ovs_mutex_lock(&dpdk_mutex);
738     err = netdev_dpdk_init(netdev, port_no, DPDK_DEV_ETH);
739     ovs_mutex_unlock(&dpdk_mutex);
740     return err;
741 }
742
743 static void
744 netdev_dpdk_destruct(struct netdev *netdev_)
745 {
746     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
747
748     ovs_mutex_lock(&dev->mutex);
749     rte_eth_dev_stop(dev->port_id);
750     ovs_mutex_unlock(&dev->mutex);
751
752     ovs_mutex_lock(&dpdk_mutex);
753     rte_free(dev->tx_q);
754     list_remove(&dev->list_node);
755     dpdk_mp_put(dev->dpdk_mp);
756     ovs_mutex_unlock(&dpdk_mutex);
757 }
758
759 static void
760 netdev_dpdk_vhost_destruct(struct netdev *netdev_)
761 {
762     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
763
764     /* Can't remove a port while a guest is attached to it. */
765     if (netdev_dpdk_get_virtio(dev) != NULL) {
766         VLOG_ERR("Can not remove port, vhost device still attached");
767                 return;
768     }
769
770     if (rte_vhost_driver_unregister(dev->vhost_id)) {
771         VLOG_ERR("Unable to remove vhost-user socket %s", dev->vhost_id);
772     } else {
773         fatal_signal_remove_file_to_unlink(dev->vhost_id);
774     }
775
776     ovs_mutex_lock(&dpdk_mutex);
777     list_remove(&dev->list_node);
778     dpdk_mp_put(dev->dpdk_mp);
779     ovs_mutex_unlock(&dpdk_mutex);
780 }
781
782 static void
783 netdev_dpdk_dealloc(struct netdev *netdev_)
784 {
785     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
786
787     rte_free(netdev);
788 }
789
790 static int
791 netdev_dpdk_get_config(const struct netdev *netdev, struct smap *args)
792 {
793     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
794
795     ovs_mutex_lock(&dev->mutex);
796
797     smap_add_format(args, "requested_rx_queues", "%d", netdev->requested_n_rxq);
798     smap_add_format(args, "configured_rx_queues", "%d", netdev->n_rxq);
799     smap_add_format(args, "requested_tx_queues", "%d", netdev->n_txq);
800     smap_add_format(args, "configured_tx_queues", "%d", dev->real_n_txq);
801     ovs_mutex_unlock(&dev->mutex);
802
803     return 0;
804 }
805
806 static int
807 netdev_dpdk_set_config(struct netdev *netdev, const struct smap *args)
808 {
809     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
810
811     ovs_mutex_lock(&dev->mutex);
812     netdev->requested_n_rxq = MAX(smap_get_int(args, "n_rxq",
813                                                netdev->requested_n_rxq), 1);
814     netdev_change_seq_changed(netdev);
815     ovs_mutex_unlock(&dev->mutex);
816
817     return 0;
818 }
819
820 static int
821 netdev_dpdk_get_numa_id(const struct netdev *netdev_)
822 {
823     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
824
825     return netdev->socket_id;
826 }
827
828 /* Sets the number of tx queues and rx queues for the dpdk interface.
829  * If the configuration fails, do not try restoring its old configuration
830  * and just returns the error. */
831 static int
832 netdev_dpdk_set_multiq(struct netdev *netdev_, unsigned int n_txq,
833                        unsigned int n_rxq)
834 {
835     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
836     int err = 0;
837     int old_rxq, old_txq;
838
839     if (netdev->up.n_txq == n_txq && netdev->up.n_rxq == n_rxq) {
840         return err;
841     }
842
843     ovs_mutex_lock(&dpdk_mutex);
844     ovs_mutex_lock(&netdev->mutex);
845
846     rte_eth_dev_stop(netdev->port_id);
847
848     old_txq = netdev->up.n_txq;
849     old_rxq = netdev->up.n_rxq;
850     netdev->up.n_txq = n_txq;
851     netdev->up.n_rxq = n_rxq;
852
853     rte_free(netdev->tx_q);
854     err = dpdk_eth_dev_init(netdev);
855     netdev_dpdk_alloc_txq(netdev, netdev->real_n_txq);
856     if (err) {
857         /* If there has been an error, it means that the requested queues
858          * have not been created.  Restore the old numbers. */
859         netdev->up.n_txq = old_txq;
860         netdev->up.n_rxq = old_rxq;
861     }
862
863     netdev->txq_needs_locking = netdev->real_n_txq != netdev->up.n_txq;
864
865     ovs_mutex_unlock(&netdev->mutex);
866     ovs_mutex_unlock(&dpdk_mutex);
867
868     return err;
869 }
870
871 static int
872 netdev_dpdk_vhost_cuse_set_multiq(struct netdev *netdev_, unsigned int n_txq,
873                              unsigned int n_rxq)
874 {
875     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
876     int err = 0;
877
878     if (netdev->up.n_txq == n_txq && netdev->up.n_rxq == n_rxq) {
879         return err;
880     }
881
882     ovs_mutex_lock(&dpdk_mutex);
883     ovs_mutex_lock(&netdev->mutex);
884
885     netdev->up.n_txq = n_txq;
886     netdev->real_n_txq = 1;
887     netdev->up.n_rxq = 1;
888     netdev->txq_needs_locking = netdev->real_n_txq != netdev->up.n_txq;
889
890     ovs_mutex_unlock(&netdev->mutex);
891     ovs_mutex_unlock(&dpdk_mutex);
892
893     return err;
894 }
895
896 static int
897 netdev_dpdk_vhost_set_multiq(struct netdev *netdev_, unsigned int n_txq,
898                              unsigned int n_rxq)
899 {
900     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
901     int err = 0;
902
903     if (netdev->up.n_txq == n_txq && netdev->up.n_rxq == n_rxq) {
904         return err;
905     }
906
907     ovs_mutex_lock(&dpdk_mutex);
908     ovs_mutex_lock(&netdev->mutex);
909
910     rte_free(netdev->tx_q);
911     netdev->up.n_txq = n_txq;
912     netdev->up.n_rxq = n_rxq;
913     netdev_dpdk_alloc_txq(netdev, netdev->up.n_txq);
914
915     ovs_mutex_unlock(&netdev->mutex);
916     ovs_mutex_unlock(&dpdk_mutex);
917
918     return err;
919 }
920
921 static struct netdev_rxq *
922 netdev_dpdk_rxq_alloc(void)
923 {
924     struct netdev_rxq_dpdk *rx = dpdk_rte_mzalloc(sizeof *rx);
925
926     return &rx->up;
927 }
928
929 static struct netdev_rxq_dpdk *
930 netdev_rxq_dpdk_cast(const struct netdev_rxq *rx)
931 {
932     return CONTAINER_OF(rx, struct netdev_rxq_dpdk, up);
933 }
934
935 static int
936 netdev_dpdk_rxq_construct(struct netdev_rxq *rxq_)
937 {
938     struct netdev_rxq_dpdk *rx = netdev_rxq_dpdk_cast(rxq_);
939     struct netdev_dpdk *netdev = netdev_dpdk_cast(rx->up.netdev);
940
941     ovs_mutex_lock(&netdev->mutex);
942     rx->port_id = netdev->port_id;
943     ovs_mutex_unlock(&netdev->mutex);
944
945     return 0;
946 }
947
948 static void
949 netdev_dpdk_rxq_destruct(struct netdev_rxq *rxq_ OVS_UNUSED)
950 {
951 }
952
953 static void
954 netdev_dpdk_rxq_dealloc(struct netdev_rxq *rxq_)
955 {
956     struct netdev_rxq_dpdk *rx = netdev_rxq_dpdk_cast(rxq_);
957
958     rte_free(rx);
959 }
960
961 static inline void
962 dpdk_queue_flush__(struct netdev_dpdk *dev, int qid)
963 {
964     struct dpdk_tx_queue *txq = &dev->tx_q[qid];
965     uint32_t nb_tx = 0;
966
967     while (nb_tx != txq->count) {
968         uint32_t ret;
969
970         ret = rte_eth_tx_burst(dev->port_id, qid, txq->burst_pkts + nb_tx,
971                                txq->count - nb_tx);
972         if (!ret) {
973             break;
974         }
975
976         nb_tx += ret;
977     }
978
979     if (OVS_UNLIKELY(nb_tx != txq->count)) {
980         /* free buffers, which we couldn't transmit, one at a time (each
981          * packet could come from a different mempool) */
982         int i;
983
984         for (i = nb_tx; i < txq->count; i++) {
985             rte_pktmbuf_free_seg(txq->burst_pkts[i]);
986         }
987         rte_spinlock_lock(&dev->stats_lock);
988         dev->stats.tx_dropped += txq->count-nb_tx;
989         rte_spinlock_unlock(&dev->stats_lock);
990     }
991
992     txq->count = 0;
993     txq->tsc = rte_get_timer_cycles();
994 }
995
996 static inline void
997 dpdk_queue_flush(struct netdev_dpdk *dev, int qid)
998 {
999     struct dpdk_tx_queue *txq = &dev->tx_q[qid];
1000
1001     if (txq->count == 0) {
1002         return;
1003     }
1004     dpdk_queue_flush__(dev, qid);
1005 }
1006
1007 static bool
1008 is_vhost_running(struct virtio_net *dev)
1009 {
1010     return (dev != NULL && (dev->flags & VIRTIO_DEV_RUNNING));
1011 }
1012
1013 static inline void
1014 netdev_dpdk_vhost_update_rx_counters(struct netdev_stats *stats,
1015                                      struct dp_packet **packets, int count)
1016 {
1017     int i;
1018     struct dp_packet *packet;
1019
1020     stats->rx_packets += count;
1021     for (i = 0; i < count; i++) {
1022         packet = packets[i];
1023
1024         if (OVS_UNLIKELY(dp_packet_size(packet) < ETH_HEADER_LEN)) {
1025             /* This only protects the following multicast counting from
1026              * too short packets, but it does not stop the packet from
1027              * further processing. */
1028             stats->rx_errors++;
1029             stats->rx_length_errors++;
1030             continue;
1031         }
1032
1033         struct eth_header *eh = (struct eth_header *) dp_packet_data(packet);
1034         if (OVS_UNLIKELY(eth_addr_is_multicast(eh->eth_dst))) {
1035             stats->multicast++;
1036         }
1037
1038         stats->rx_bytes += dp_packet_size(packet);
1039     }
1040 }
1041
1042 /*
1043  * The receive path for the vhost port is the TX path out from guest.
1044  */
1045 static int
1046 netdev_dpdk_vhost_rxq_recv(struct netdev_rxq *rxq_,
1047                            struct dp_packet **packets, int *c)
1048 {
1049     struct netdev_rxq_dpdk *rx = netdev_rxq_dpdk_cast(rxq_);
1050     struct netdev *netdev = rx->up.netdev;
1051     struct netdev_dpdk *vhost_dev = netdev_dpdk_cast(netdev);
1052     struct virtio_net *virtio_dev = netdev_dpdk_get_virtio(vhost_dev);
1053     int qid = rxq_->queue_id;
1054     uint16_t nb_rx = 0;
1055
1056     if (OVS_UNLIKELY(!is_vhost_running(virtio_dev))) {
1057         return EAGAIN;
1058     }
1059
1060     if (rxq_->queue_id >= vhost_dev->real_n_rxq) {
1061         return EOPNOTSUPP;
1062     }
1063
1064     nb_rx = rte_vhost_dequeue_burst(virtio_dev, qid * VIRTIO_QNUM + VIRTIO_TXQ,
1065                                     vhost_dev->dpdk_mp->mp,
1066                                     (struct rte_mbuf **)packets,
1067                                     NETDEV_MAX_BURST);
1068     if (!nb_rx) {
1069         return EAGAIN;
1070     }
1071
1072     rte_spinlock_lock(&vhost_dev->stats_lock);
1073     netdev_dpdk_vhost_update_rx_counters(&vhost_dev->stats, packets, nb_rx);
1074     rte_spinlock_unlock(&vhost_dev->stats_lock);
1075
1076     *c = (int) nb_rx;
1077     return 0;
1078 }
1079
1080 static int
1081 netdev_dpdk_rxq_recv(struct netdev_rxq *rxq_, struct dp_packet **packets,
1082                      int *c)
1083 {
1084     struct netdev_rxq_dpdk *rx = netdev_rxq_dpdk_cast(rxq_);
1085     struct netdev *netdev = rx->up.netdev;
1086     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1087     int nb_rx;
1088
1089     /* There is only one tx queue for this core.  Do not flush other
1090      * queues.
1091      * Do not flush tx queue which is shared among CPUs
1092      * since it is always flushed */
1093     if (rxq_->queue_id == rte_lcore_id() &&
1094         OVS_LIKELY(!dev->txq_needs_locking)) {
1095         dpdk_queue_flush(dev, rxq_->queue_id);
1096     }
1097
1098     nb_rx = rte_eth_rx_burst(rx->port_id, rxq_->queue_id,
1099                              (struct rte_mbuf **) packets,
1100                              NETDEV_MAX_BURST);
1101     if (!nb_rx) {
1102         return EAGAIN;
1103     }
1104
1105     *c = nb_rx;
1106
1107     return 0;
1108 }
1109
1110 static inline void
1111 netdev_dpdk_vhost_update_tx_counters(struct netdev_stats *stats,
1112                                      struct dp_packet **packets,
1113                                      int attempted,
1114                                      int dropped)
1115 {
1116     int i;
1117     int sent = attempted - dropped;
1118
1119     stats->tx_packets += sent;
1120     stats->tx_dropped += dropped;
1121
1122     for (i = 0; i < sent; i++) {
1123         stats->tx_bytes += dp_packet_size(packets[i]);
1124     }
1125 }
1126
1127 static void
1128 __netdev_dpdk_vhost_send(struct netdev *netdev, int qid,
1129                          struct dp_packet **pkts, int cnt,
1130                          bool may_steal)
1131 {
1132     struct netdev_dpdk *vhost_dev = netdev_dpdk_cast(netdev);
1133     struct virtio_net *virtio_dev = netdev_dpdk_get_virtio(vhost_dev);
1134     struct rte_mbuf **cur_pkts = (struct rte_mbuf **) pkts;
1135     unsigned int total_pkts = cnt;
1136     uint64_t start = 0;
1137
1138     if (OVS_UNLIKELY(!is_vhost_running(virtio_dev))) {
1139         rte_spinlock_lock(&vhost_dev->stats_lock);
1140         vhost_dev->stats.tx_dropped+= cnt;
1141         rte_spinlock_unlock(&vhost_dev->stats_lock);
1142         goto out;
1143     }
1144
1145     if (vhost_dev->txq_needs_locking) {
1146         qid = qid % vhost_dev->real_n_txq;
1147         rte_spinlock_lock(&vhost_dev->tx_q[qid].tx_lock);
1148     }
1149
1150     do {
1151         int vhost_qid = qid * VIRTIO_QNUM + VIRTIO_RXQ;
1152         unsigned int tx_pkts;
1153
1154         tx_pkts = rte_vhost_enqueue_burst(virtio_dev, vhost_qid,
1155                                           cur_pkts, cnt);
1156         if (OVS_LIKELY(tx_pkts)) {
1157             /* Packets have been sent.*/
1158             cnt -= tx_pkts;
1159             /* Prepare for possible next iteration.*/
1160             cur_pkts = &cur_pkts[tx_pkts];
1161         } else {
1162             uint64_t timeout = VHOST_ENQ_RETRY_USECS * rte_get_timer_hz() / 1E6;
1163             unsigned int expired = 0;
1164
1165             if (!start) {
1166                 start = rte_get_timer_cycles();
1167             }
1168
1169             /*
1170              * Unable to enqueue packets to vhost interface.
1171              * Check available entries before retrying.
1172              */
1173             while (!rte_vring_available_entries(virtio_dev, vhost_qid)) {
1174                 if (OVS_UNLIKELY((rte_get_timer_cycles() - start) > timeout)) {
1175                     expired = 1;
1176                     break;
1177                 }
1178             }
1179             if (expired) {
1180                 /* break out of main loop. */
1181                 break;
1182             }
1183         }
1184     } while (cnt);
1185
1186     if (vhost_dev->txq_needs_locking) {
1187         rte_spinlock_unlock(&vhost_dev->tx_q[qid].tx_lock);
1188     }
1189
1190     rte_spinlock_lock(&vhost_dev->stats_lock);
1191     netdev_dpdk_vhost_update_tx_counters(&vhost_dev->stats, pkts, total_pkts,
1192                                          cnt);
1193     rte_spinlock_unlock(&vhost_dev->stats_lock);
1194
1195 out:
1196     if (may_steal) {
1197         int i;
1198
1199         for (i = 0; i < total_pkts; i++) {
1200             dp_packet_delete(pkts[i]);
1201         }
1202     }
1203 }
1204
1205 inline static void
1206 dpdk_queue_pkts(struct netdev_dpdk *dev, int qid,
1207                struct rte_mbuf **pkts, int cnt)
1208 {
1209     struct dpdk_tx_queue *txq = &dev->tx_q[qid];
1210     uint64_t diff_tsc;
1211
1212     int i = 0;
1213
1214     while (i < cnt) {
1215         int freeslots = MAX_TX_QUEUE_LEN - txq->count;
1216         int tocopy = MIN(freeslots, cnt-i);
1217
1218         memcpy(&txq->burst_pkts[txq->count], &pkts[i],
1219                tocopy * sizeof (struct rte_mbuf *));
1220
1221         txq->count += tocopy;
1222         i += tocopy;
1223
1224         if (txq->count == MAX_TX_QUEUE_LEN || txq->flush_tx) {
1225             dpdk_queue_flush__(dev, qid);
1226         }
1227         diff_tsc = rte_get_timer_cycles() - txq->tsc;
1228         if (diff_tsc >= DRAIN_TSC) {
1229             dpdk_queue_flush__(dev, qid);
1230         }
1231     }
1232 }
1233
1234 /* Tx function. Transmit packets indefinitely */
1235 static void
1236 dpdk_do_tx_copy(struct netdev *netdev, int qid, struct dp_packet **pkts,
1237                 int cnt)
1238     OVS_NO_THREAD_SAFETY_ANALYSIS
1239 {
1240 #if !defined(__CHECKER__) && !defined(_WIN32)
1241     const size_t PKT_ARRAY_SIZE = cnt;
1242 #else
1243     /* Sparse or MSVC doesn't like variable length array. */
1244     enum { PKT_ARRAY_SIZE = NETDEV_MAX_BURST };
1245 #endif
1246     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1247     struct rte_mbuf *mbufs[PKT_ARRAY_SIZE];
1248     int dropped = 0;
1249     int newcnt = 0;
1250     int i;
1251
1252     /* If we are on a non pmd thread we have to use the mempool mutex, because
1253      * every non pmd thread shares the same mempool cache */
1254
1255     if (!dpdk_thread_is_pmd()) {
1256         ovs_mutex_lock(&nonpmd_mempool_mutex);
1257     }
1258
1259     for (i = 0; i < cnt; i++) {
1260         int size = dp_packet_size(pkts[i]);
1261
1262         if (OVS_UNLIKELY(size > dev->max_packet_len)) {
1263             VLOG_WARN_RL(&rl, "Too big size %d max_packet_len %d",
1264                          (int)size , dev->max_packet_len);
1265
1266             dropped++;
1267             continue;
1268         }
1269
1270         mbufs[newcnt] = rte_pktmbuf_alloc(dev->dpdk_mp->mp);
1271
1272         if (!mbufs[newcnt]) {
1273             dropped += cnt - i;
1274             break;
1275         }
1276
1277         /* We have to do a copy for now */
1278         memcpy(rte_pktmbuf_mtod(mbufs[newcnt], void *), dp_packet_data(pkts[i]), size);
1279
1280         rte_pktmbuf_data_len(mbufs[newcnt]) = size;
1281         rte_pktmbuf_pkt_len(mbufs[newcnt]) = size;
1282
1283         newcnt++;
1284     }
1285
1286     if (OVS_UNLIKELY(dropped)) {
1287         rte_spinlock_lock(&dev->stats_lock);
1288         dev->stats.tx_dropped += dropped;
1289         rte_spinlock_unlock(&dev->stats_lock);
1290     }
1291
1292     if (dev->type == DPDK_DEV_VHOST) {
1293         __netdev_dpdk_vhost_send(netdev, qid, (struct dp_packet **) mbufs, newcnt, true);
1294     } else {
1295         dpdk_queue_pkts(dev, qid, mbufs, newcnt);
1296         dpdk_queue_flush(dev, qid);
1297     }
1298
1299     if (!dpdk_thread_is_pmd()) {
1300         ovs_mutex_unlock(&nonpmd_mempool_mutex);
1301     }
1302 }
1303
1304 static int
1305 netdev_dpdk_vhost_send(struct netdev *netdev, int qid, struct dp_packet **pkts,
1306                  int cnt, bool may_steal)
1307 {
1308     if (OVS_UNLIKELY(pkts[0]->source != DPBUF_DPDK)) {
1309         int i;
1310
1311         dpdk_do_tx_copy(netdev, qid, pkts, cnt);
1312         if (may_steal) {
1313             for (i = 0; i < cnt; i++) {
1314                 dp_packet_delete(pkts[i]);
1315             }
1316         }
1317     } else {
1318         __netdev_dpdk_vhost_send(netdev, qid, pkts, cnt, may_steal);
1319     }
1320     return 0;
1321 }
1322
1323 static inline void
1324 netdev_dpdk_send__(struct netdev_dpdk *dev, int qid,
1325                    struct dp_packet **pkts, int cnt, bool may_steal)
1326 {
1327     int i;
1328
1329     if (OVS_UNLIKELY(dev->txq_needs_locking)) {
1330         qid = qid % dev->real_n_txq;
1331         rte_spinlock_lock(&dev->tx_q[qid].tx_lock);
1332     }
1333
1334     if (OVS_UNLIKELY(!may_steal ||
1335                      pkts[0]->source != DPBUF_DPDK)) {
1336         struct netdev *netdev = &dev->up;
1337
1338         dpdk_do_tx_copy(netdev, qid, pkts, cnt);
1339
1340         if (may_steal) {
1341             for (i = 0; i < cnt; i++) {
1342                 dp_packet_delete(pkts[i]);
1343             }
1344         }
1345     } else {
1346         int next_tx_idx = 0;
1347         int dropped = 0;
1348
1349         for (i = 0; i < cnt; i++) {
1350             int size = dp_packet_size(pkts[i]);
1351
1352             if (OVS_UNLIKELY(size > dev->max_packet_len)) {
1353                 if (next_tx_idx != i) {
1354                     dpdk_queue_pkts(dev, qid,
1355                                     (struct rte_mbuf **)&pkts[next_tx_idx],
1356                                     i-next_tx_idx);
1357                 }
1358
1359                 VLOG_WARN_RL(&rl, "Too big size %d max_packet_len %d",
1360                              (int)size , dev->max_packet_len);
1361
1362                 dp_packet_delete(pkts[i]);
1363                 dropped++;
1364                 next_tx_idx = i + 1;
1365             }
1366         }
1367         if (next_tx_idx != cnt) {
1368            dpdk_queue_pkts(dev, qid,
1369                             (struct rte_mbuf **)&pkts[next_tx_idx],
1370                             cnt-next_tx_idx);
1371         }
1372
1373         if (OVS_UNLIKELY(dropped)) {
1374             rte_spinlock_lock(&dev->stats_lock);
1375             dev->stats.tx_dropped += dropped;
1376             rte_spinlock_unlock(&dev->stats_lock);
1377         }
1378     }
1379
1380     if (OVS_UNLIKELY(dev->txq_needs_locking)) {
1381         rte_spinlock_unlock(&dev->tx_q[qid].tx_lock);
1382     }
1383 }
1384
1385 static int
1386 netdev_dpdk_eth_send(struct netdev *netdev, int qid,
1387                      struct dp_packet **pkts, int cnt, bool may_steal)
1388 {
1389     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1390
1391     netdev_dpdk_send__(dev, qid, pkts, cnt, may_steal);
1392     return 0;
1393 }
1394
1395 static int
1396 netdev_dpdk_set_etheraddr(struct netdev *netdev, const struct eth_addr mac)
1397 {
1398     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1399
1400     ovs_mutex_lock(&dev->mutex);
1401     if (!eth_addr_equals(dev->hwaddr, mac)) {
1402         dev->hwaddr = mac;
1403         netdev_change_seq_changed(netdev);
1404     }
1405     ovs_mutex_unlock(&dev->mutex);
1406
1407     return 0;
1408 }
1409
1410 static int
1411 netdev_dpdk_get_etheraddr(const struct netdev *netdev, struct eth_addr *mac)
1412 {
1413     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1414
1415     ovs_mutex_lock(&dev->mutex);
1416     *mac = dev->hwaddr;
1417     ovs_mutex_unlock(&dev->mutex);
1418
1419     return 0;
1420 }
1421
1422 static int
1423 netdev_dpdk_get_mtu(const struct netdev *netdev, int *mtup)
1424 {
1425     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1426
1427     ovs_mutex_lock(&dev->mutex);
1428     *mtup = dev->mtu;
1429     ovs_mutex_unlock(&dev->mutex);
1430
1431     return 0;
1432 }
1433
1434 static int
1435 netdev_dpdk_set_mtu(const struct netdev *netdev, int mtu)
1436 {
1437     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1438     int old_mtu, err;
1439     struct dpdk_mp *old_mp;
1440     struct dpdk_mp *mp;
1441
1442     ovs_mutex_lock(&dpdk_mutex);
1443     ovs_mutex_lock(&dev->mutex);
1444     if (dev->mtu == mtu) {
1445         err = 0;
1446         goto out;
1447     }
1448
1449     mp = dpdk_mp_get(dev->socket_id, dev->mtu);
1450     if (!mp) {
1451         err = ENOMEM;
1452         goto out;
1453     }
1454
1455     rte_eth_dev_stop(dev->port_id);
1456
1457     old_mtu = dev->mtu;
1458     old_mp = dev->dpdk_mp;
1459     dev->dpdk_mp = mp;
1460     dev->mtu = mtu;
1461     dev->max_packet_len = MTU_TO_MAX_LEN(dev->mtu);
1462
1463     err = dpdk_eth_dev_init(dev);
1464     if (err) {
1465         dpdk_mp_put(mp);
1466         dev->mtu = old_mtu;
1467         dev->dpdk_mp = old_mp;
1468         dev->max_packet_len = MTU_TO_MAX_LEN(dev->mtu);
1469         dpdk_eth_dev_init(dev);
1470         goto out;
1471     }
1472
1473     dpdk_mp_put(old_mp);
1474     netdev_change_seq_changed(netdev);
1475 out:
1476     ovs_mutex_unlock(&dev->mutex);
1477     ovs_mutex_unlock(&dpdk_mutex);
1478     return err;
1479 }
1480
1481 static int
1482 netdev_dpdk_get_carrier(const struct netdev *netdev_, bool *carrier);
1483
1484 static int
1485 netdev_dpdk_vhost_get_stats(const struct netdev *netdev,
1486                             struct netdev_stats *stats)
1487 {
1488     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1489
1490     ovs_mutex_lock(&dev->mutex);
1491     memset(stats, 0, sizeof(*stats));
1492     /* Unsupported Stats */
1493     stats->collisions = UINT64_MAX;
1494     stats->rx_crc_errors = UINT64_MAX;
1495     stats->rx_fifo_errors = UINT64_MAX;
1496     stats->rx_frame_errors = UINT64_MAX;
1497     stats->rx_missed_errors = UINT64_MAX;
1498     stats->rx_over_errors = UINT64_MAX;
1499     stats->tx_aborted_errors = UINT64_MAX;
1500     stats->tx_carrier_errors = UINT64_MAX;
1501     stats->tx_errors = UINT64_MAX;
1502     stats->tx_fifo_errors = UINT64_MAX;
1503     stats->tx_heartbeat_errors = UINT64_MAX;
1504     stats->tx_window_errors = UINT64_MAX;
1505     stats->rx_dropped += UINT64_MAX;
1506
1507     rte_spinlock_lock(&dev->stats_lock);
1508     /* Supported Stats */
1509     stats->rx_packets += dev->stats.rx_packets;
1510     stats->tx_packets += dev->stats.tx_packets;
1511     stats->tx_dropped += dev->stats.tx_dropped;
1512     stats->multicast = dev->stats.multicast;
1513     stats->rx_bytes = dev->stats.rx_bytes;
1514     stats->tx_bytes = dev->stats.tx_bytes;
1515     stats->rx_errors = dev->stats.rx_errors;
1516     stats->rx_length_errors = dev->stats.rx_length_errors;
1517     rte_spinlock_unlock(&dev->stats_lock);
1518
1519     ovs_mutex_unlock(&dev->mutex);
1520
1521     return 0;
1522 }
1523
1524 static int
1525 netdev_dpdk_get_stats(const struct netdev *netdev, struct netdev_stats *stats)
1526 {
1527     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1528     struct rte_eth_stats rte_stats;
1529     bool gg;
1530
1531     netdev_dpdk_get_carrier(netdev, &gg);
1532     ovs_mutex_lock(&dev->mutex);
1533     rte_eth_stats_get(dev->port_id, &rte_stats);
1534
1535     memset(stats, 0, sizeof(*stats));
1536
1537     stats->rx_packets = rte_stats.ipackets;
1538     stats->tx_packets = rte_stats.opackets;
1539     stats->rx_bytes = rte_stats.ibytes;
1540     stats->tx_bytes = rte_stats.obytes;
1541     /* DPDK counts imissed as errors, but count them here as dropped instead */
1542     stats->rx_errors = rte_stats.ierrors - rte_stats.imissed;
1543     stats->tx_errors = rte_stats.oerrors;
1544     stats->multicast = rte_stats.imcasts;
1545
1546     rte_spinlock_lock(&dev->stats_lock);
1547     stats->tx_dropped = dev->stats.tx_dropped;
1548     rte_spinlock_unlock(&dev->stats_lock);
1549
1550     /* These are the available DPDK counters for packets not received due to
1551      * local resource constraints in DPDK and NIC respectively. */
1552     stats->rx_dropped = rte_stats.rx_nombuf + rte_stats.imissed;
1553     stats->collisions = UINT64_MAX;
1554
1555     stats->rx_length_errors = UINT64_MAX;
1556     stats->rx_over_errors = UINT64_MAX;
1557     stats->rx_crc_errors = UINT64_MAX;
1558     stats->rx_frame_errors = UINT64_MAX;
1559     stats->rx_fifo_errors = UINT64_MAX;
1560     stats->rx_missed_errors = rte_stats.imissed;
1561
1562     stats->tx_aborted_errors = UINT64_MAX;
1563     stats->tx_carrier_errors = UINT64_MAX;
1564     stats->tx_fifo_errors = UINT64_MAX;
1565     stats->tx_heartbeat_errors = UINT64_MAX;
1566     stats->tx_window_errors = UINT64_MAX;
1567
1568     ovs_mutex_unlock(&dev->mutex);
1569
1570     return 0;
1571 }
1572
1573 static int
1574 netdev_dpdk_get_features(const struct netdev *netdev_,
1575                          enum netdev_features *current,
1576                          enum netdev_features *advertised OVS_UNUSED,
1577                          enum netdev_features *supported OVS_UNUSED,
1578                          enum netdev_features *peer OVS_UNUSED)
1579 {
1580     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
1581     struct rte_eth_link link;
1582
1583     ovs_mutex_lock(&dev->mutex);
1584     link = dev->link;
1585     ovs_mutex_unlock(&dev->mutex);
1586
1587     if (link.link_duplex == ETH_LINK_AUTONEG_DUPLEX) {
1588         if (link.link_speed == ETH_LINK_SPEED_AUTONEG) {
1589             *current = NETDEV_F_AUTONEG;
1590         }
1591     } else if (link.link_duplex == ETH_LINK_HALF_DUPLEX) {
1592         if (link.link_speed == ETH_LINK_SPEED_10) {
1593             *current = NETDEV_F_10MB_HD;
1594         }
1595         if (link.link_speed == ETH_LINK_SPEED_100) {
1596             *current = NETDEV_F_100MB_HD;
1597         }
1598         if (link.link_speed == ETH_LINK_SPEED_1000) {
1599             *current = NETDEV_F_1GB_HD;
1600         }
1601     } else if (link.link_duplex == ETH_LINK_FULL_DUPLEX) {
1602         if (link.link_speed == ETH_LINK_SPEED_10) {
1603             *current = NETDEV_F_10MB_FD;
1604         }
1605         if (link.link_speed == ETH_LINK_SPEED_100) {
1606             *current = NETDEV_F_100MB_FD;
1607         }
1608         if (link.link_speed == ETH_LINK_SPEED_1000) {
1609             *current = NETDEV_F_1GB_FD;
1610         }
1611         if (link.link_speed == ETH_LINK_SPEED_10000) {
1612             *current = NETDEV_F_10GB_FD;
1613         }
1614     }
1615
1616     return 0;
1617 }
1618
1619 static int
1620 netdev_dpdk_get_ifindex(const struct netdev *netdev)
1621 {
1622     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1623     int ifindex;
1624
1625     ovs_mutex_lock(&dev->mutex);
1626     ifindex = dev->port_id;
1627     ovs_mutex_unlock(&dev->mutex);
1628
1629     return ifindex;
1630 }
1631
1632 static int
1633 netdev_dpdk_get_carrier(const struct netdev *netdev_, bool *carrier)
1634 {
1635     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
1636
1637     ovs_mutex_lock(&dev->mutex);
1638     check_link_status(dev);
1639     *carrier = dev->link.link_status;
1640
1641     ovs_mutex_unlock(&dev->mutex);
1642
1643     return 0;
1644 }
1645
1646 static int
1647 netdev_dpdk_vhost_get_carrier(const struct netdev *netdev_, bool *carrier)
1648 {
1649     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
1650     struct virtio_net *virtio_dev = netdev_dpdk_get_virtio(dev);
1651
1652     ovs_mutex_lock(&dev->mutex);
1653
1654     if (is_vhost_running(virtio_dev)) {
1655         *carrier = 1;
1656     } else {
1657         *carrier = 0;
1658     }
1659
1660     ovs_mutex_unlock(&dev->mutex);
1661
1662     return 0;
1663 }
1664
1665 static long long int
1666 netdev_dpdk_get_carrier_resets(const struct netdev *netdev_)
1667 {
1668     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
1669     long long int carrier_resets;
1670
1671     ovs_mutex_lock(&dev->mutex);
1672     carrier_resets = dev->link_reset_cnt;
1673     ovs_mutex_unlock(&dev->mutex);
1674
1675     return carrier_resets;
1676 }
1677
1678 static int
1679 netdev_dpdk_set_miimon(struct netdev *netdev_ OVS_UNUSED,
1680                        long long int interval OVS_UNUSED)
1681 {
1682     return EOPNOTSUPP;
1683 }
1684
1685 static int
1686 netdev_dpdk_update_flags__(struct netdev_dpdk *dev,
1687                            enum netdev_flags off, enum netdev_flags on,
1688                            enum netdev_flags *old_flagsp) OVS_REQUIRES(dev->mutex)
1689 {
1690     int err;
1691
1692     if ((off | on) & ~(NETDEV_UP | NETDEV_PROMISC)) {
1693         return EINVAL;
1694     }
1695
1696     *old_flagsp = dev->flags;
1697     dev->flags |= on;
1698     dev->flags &= ~off;
1699
1700     if (dev->flags == *old_flagsp) {
1701         return 0;
1702     }
1703
1704     if (dev->type == DPDK_DEV_ETH) {
1705         if (dev->flags & NETDEV_UP) {
1706             err = rte_eth_dev_start(dev->port_id);
1707             if (err)
1708                 return -err;
1709         }
1710
1711         if (dev->flags & NETDEV_PROMISC) {
1712             rte_eth_promiscuous_enable(dev->port_id);
1713         }
1714
1715         if (!(dev->flags & NETDEV_UP)) {
1716             rte_eth_dev_stop(dev->port_id);
1717         }
1718     }
1719
1720     return 0;
1721 }
1722
1723 static int
1724 netdev_dpdk_update_flags(struct netdev *netdev_,
1725                          enum netdev_flags off, enum netdev_flags on,
1726                          enum netdev_flags *old_flagsp)
1727 {
1728     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
1729     int error;
1730
1731     ovs_mutex_lock(&netdev->mutex);
1732     error = netdev_dpdk_update_flags__(netdev, off, on, old_flagsp);
1733     ovs_mutex_unlock(&netdev->mutex);
1734
1735     return error;
1736 }
1737
1738 static int
1739 netdev_dpdk_get_status(const struct netdev *netdev_, struct smap *args)
1740 {
1741     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
1742     struct rte_eth_dev_info dev_info;
1743
1744     if (dev->port_id < 0)
1745         return ENODEV;
1746
1747     ovs_mutex_lock(&dev->mutex);
1748     rte_eth_dev_info_get(dev->port_id, &dev_info);
1749     ovs_mutex_unlock(&dev->mutex);
1750
1751     smap_add_format(args, "driver_name", "%s", dev_info.driver_name);
1752
1753     smap_add_format(args, "port_no", "%d", dev->port_id);
1754     smap_add_format(args, "numa_id", "%d", rte_eth_dev_socket_id(dev->port_id));
1755     smap_add_format(args, "driver_name", "%s", dev_info.driver_name);
1756     smap_add_format(args, "min_rx_bufsize", "%u", dev_info.min_rx_bufsize);
1757     smap_add_format(args, "max_rx_pktlen", "%u", dev_info.max_rx_pktlen);
1758     smap_add_format(args, "max_rx_queues", "%u", dev_info.max_rx_queues);
1759     smap_add_format(args, "max_tx_queues", "%u", dev_info.max_tx_queues);
1760     smap_add_format(args, "max_mac_addrs", "%u", dev_info.max_mac_addrs);
1761     smap_add_format(args, "max_hash_mac_addrs", "%u", dev_info.max_hash_mac_addrs);
1762     smap_add_format(args, "max_vfs", "%u", dev_info.max_vfs);
1763     smap_add_format(args, "max_vmdq_pools", "%u", dev_info.max_vmdq_pools);
1764
1765     if (dev_info.pci_dev) {
1766         smap_add_format(args, "pci-vendor_id", "0x%u",
1767                         dev_info.pci_dev->id.vendor_id);
1768         smap_add_format(args, "pci-device_id", "0x%x",
1769                         dev_info.pci_dev->id.device_id);
1770     }
1771
1772     return 0;
1773 }
1774
1775 static void
1776 netdev_dpdk_set_admin_state__(struct netdev_dpdk *dev, bool admin_state)
1777     OVS_REQUIRES(dev->mutex)
1778 {
1779     enum netdev_flags old_flags;
1780
1781     if (admin_state) {
1782         netdev_dpdk_update_flags__(dev, 0, NETDEV_UP, &old_flags);
1783     } else {
1784         netdev_dpdk_update_flags__(dev, NETDEV_UP, 0, &old_flags);
1785     }
1786 }
1787
1788 static void
1789 netdev_dpdk_set_admin_state(struct unixctl_conn *conn, int argc,
1790                             const char *argv[], void *aux OVS_UNUSED)
1791 {
1792     bool up;
1793
1794     if (!strcasecmp(argv[argc - 1], "up")) {
1795         up = true;
1796     } else if ( !strcasecmp(argv[argc - 1], "down")) {
1797         up = false;
1798     } else {
1799         unixctl_command_reply_error(conn, "Invalid Admin State");
1800         return;
1801     }
1802
1803     if (argc > 2) {
1804         struct netdev *netdev = netdev_from_name(argv[1]);
1805         if (netdev && is_dpdk_class(netdev->netdev_class)) {
1806             struct netdev_dpdk *dpdk_dev = netdev_dpdk_cast(netdev);
1807
1808             ovs_mutex_lock(&dpdk_dev->mutex);
1809             netdev_dpdk_set_admin_state__(dpdk_dev, up);
1810             ovs_mutex_unlock(&dpdk_dev->mutex);
1811
1812             netdev_close(netdev);
1813         } else {
1814             unixctl_command_reply_error(conn, "Not a DPDK Interface");
1815             netdev_close(netdev);
1816             return;
1817         }
1818     } else {
1819         struct netdev_dpdk *netdev;
1820
1821         ovs_mutex_lock(&dpdk_mutex);
1822         LIST_FOR_EACH (netdev, list_node, &dpdk_list) {
1823             ovs_mutex_lock(&netdev->mutex);
1824             netdev_dpdk_set_admin_state__(netdev, up);
1825             ovs_mutex_unlock(&netdev->mutex);
1826         }
1827         ovs_mutex_unlock(&dpdk_mutex);
1828     }
1829     unixctl_command_reply(conn, "OK");
1830 }
1831
1832 /*
1833  * Set virtqueue flags so that we do not receive interrupts.
1834  */
1835 static void
1836 set_irq_status(struct virtio_net *dev)
1837 {
1838     uint32_t i;
1839     uint64_t idx;
1840
1841     for (i = 0; i < dev->virt_qp_nb; i++) {
1842         idx = i * VIRTIO_QNUM;
1843         rte_vhost_enable_guest_notification(dev, idx + VIRTIO_RXQ, 0);
1844         rte_vhost_enable_guest_notification(dev, idx + VIRTIO_TXQ, 0);
1845     }
1846 }
1847
1848
1849 static int
1850 netdev_dpdk_vhost_set_queues(struct netdev_dpdk *netdev, struct virtio_net *dev)
1851 {
1852     uint32_t qp_num;
1853
1854     qp_num = dev->virt_qp_nb;
1855     if (qp_num > netdev->up.n_rxq) {
1856         VLOG_ERR("vHost Device '%s' %"PRIu64" can't be added - "
1857                  "too many queues %d > %d", dev->ifname, dev->device_fh,
1858                  qp_num, netdev->up.n_rxq);
1859         return -1;
1860     }
1861
1862     netdev->real_n_rxq = qp_num;
1863     netdev->real_n_txq = qp_num;
1864     if (netdev->up.n_txq > netdev->real_n_txq) {
1865         netdev->txq_needs_locking = true;
1866     } else {
1867         netdev->txq_needs_locking = false;
1868     }
1869
1870     return 0;
1871 }
1872
1873 /*
1874  * A new virtio-net device is added to a vhost port.
1875  */
1876 static int
1877 new_device(struct virtio_net *dev)
1878 {
1879     struct netdev_dpdk *netdev;
1880     bool exists = false;
1881
1882     ovs_mutex_lock(&dpdk_mutex);
1883     /* Add device to the vhost port with the same name as that passed down. */
1884     LIST_FOR_EACH(netdev, list_node, &dpdk_list) {
1885         if (strncmp(dev->ifname, netdev->vhost_id, IF_NAME_SZ) == 0) {
1886             ovs_mutex_lock(&netdev->mutex);
1887             if (netdev_dpdk_vhost_set_queues(netdev, dev)) {
1888                 ovs_mutex_unlock(&netdev->mutex);
1889                 ovs_mutex_unlock(&dpdk_mutex);
1890                 return -1;
1891             }
1892             ovsrcu_set(&netdev->virtio_dev, dev);
1893             exists = true;
1894             dev->flags |= VIRTIO_DEV_RUNNING;
1895             /* Disable notifications. */
1896             set_irq_status(dev);
1897             ovs_mutex_unlock(&netdev->mutex);
1898             break;
1899         }
1900     }
1901     ovs_mutex_unlock(&dpdk_mutex);
1902
1903     if (!exists) {
1904         VLOG_INFO("vHost Device '%s' %"PRIu64" can't be added - name not "
1905                   "found", dev->ifname, dev->device_fh);
1906
1907         return -1;
1908     }
1909
1910     VLOG_INFO("vHost Device '%s' %"PRIu64" has been added", dev->ifname,
1911               dev->device_fh);
1912     return 0;
1913 }
1914
1915 /*
1916  * Remove a virtio-net device from the specific vhost port.  Use dev->remove
1917  * flag to stop any more packets from being sent or received to/from a VM and
1918  * ensure all currently queued packets have been sent/received before removing
1919  *  the device.
1920  */
1921 static void
1922 destroy_device(volatile struct virtio_net *dev)
1923 {
1924     struct netdev_dpdk *vhost_dev;
1925     bool exists = false;
1926
1927     ovs_mutex_lock(&dpdk_mutex);
1928     LIST_FOR_EACH (vhost_dev, list_node, &dpdk_list) {
1929         if (netdev_dpdk_get_virtio(vhost_dev) == dev) {
1930
1931             ovs_mutex_lock(&vhost_dev->mutex);
1932             dev->flags &= ~VIRTIO_DEV_RUNNING;
1933             ovsrcu_set(&vhost_dev->virtio_dev, NULL);
1934             exists = true;
1935             ovs_mutex_unlock(&vhost_dev->mutex);
1936             break;
1937         }
1938     }
1939
1940     ovs_mutex_unlock(&dpdk_mutex);
1941
1942     if (exists == true) {
1943         /*
1944          * Wait for other threads to quiesce after setting the 'virtio_dev'
1945          * to NULL, before returning.
1946          */
1947         ovsrcu_synchronize();
1948         /*
1949          * As call to ovsrcu_synchronize() will end the quiescent state,
1950          * put thread back into quiescent state before returning.
1951          */
1952         ovsrcu_quiesce_start();
1953         VLOG_INFO("vHost Device '%s' %"PRIu64" has been removed", dev->ifname,
1954                   dev->device_fh);
1955     } else {
1956         VLOG_INFO("vHost Device '%s' %"PRIu64" not found", dev->ifname,
1957                   dev->device_fh);
1958     }
1959
1960 }
1961
1962 struct virtio_net *
1963 netdev_dpdk_get_virtio(const struct netdev_dpdk *dev)
1964 {
1965     return ovsrcu_get(struct virtio_net *, &dev->virtio_dev);
1966 }
1967
1968 /*
1969  * These callbacks allow virtio-net devices to be added to vhost ports when
1970  * configuration has been fully complete.
1971  */
1972 static const struct virtio_net_device_ops virtio_net_device_ops =
1973 {
1974     .new_device =  new_device,
1975     .destroy_device = destroy_device,
1976 };
1977
1978 static void *
1979 start_vhost_loop(void *dummy OVS_UNUSED)
1980 {
1981      pthread_detach(pthread_self());
1982      /* Put the cuse thread into quiescent state. */
1983      ovsrcu_quiesce_start();
1984      rte_vhost_driver_session_start();
1985      return NULL;
1986 }
1987
1988 static int
1989 dpdk_vhost_class_init(void)
1990 {
1991     rte_vhost_driver_callback_register(&virtio_net_device_ops);
1992     ovs_thread_create("vhost_thread", start_vhost_loop, NULL);
1993     return 0;
1994 }
1995
1996 static int
1997 dpdk_vhost_cuse_class_init(void)
1998 {
1999     int err = -1;
2000
2001
2002     /* Register CUSE device to handle IOCTLs.
2003      * Unless otherwise specified on the vswitchd command line, cuse_dev_name
2004      * is set to vhost-net.
2005      */
2006     err = rte_vhost_driver_register(cuse_dev_name);
2007
2008     if (err != 0) {
2009         VLOG_ERR("CUSE device setup failure.");
2010         return -1;
2011     }
2012
2013     dpdk_vhost_class_init();
2014     return 0;
2015 }
2016
2017 static int
2018 dpdk_vhost_user_class_init(void)
2019 {
2020     dpdk_vhost_class_init();
2021     return 0;
2022 }
2023
2024 static void
2025 dpdk_common_init(void)
2026 {
2027     unixctl_command_register("netdev-dpdk/set-admin-state",
2028                              "[netdev] up|down", 1, 2,
2029                              netdev_dpdk_set_admin_state, NULL);
2030
2031     ovs_thread_create("dpdk_watchdog", dpdk_watchdog, NULL);
2032 }
2033
2034 /* Client Rings */
2035
2036 static int
2037 dpdk_ring_create(const char dev_name[], unsigned int port_no,
2038                  unsigned int *eth_port_id)
2039 {
2040     struct dpdk_ring *ivshmem;
2041     char ring_name[RTE_RING_NAMESIZE];
2042     int err;
2043
2044     ivshmem = dpdk_rte_mzalloc(sizeof *ivshmem);
2045     if (ivshmem == NULL) {
2046         return ENOMEM;
2047     }
2048
2049     /* XXX: Add support for multiquque ring. */
2050     err = snprintf(ring_name, sizeof(ring_name), "%s_tx", dev_name);
2051     if (err < 0) {
2052         return -err;
2053     }
2054
2055     /* Create single producer tx ring, netdev does explicit locking. */
2056     ivshmem->cring_tx = rte_ring_create(ring_name, DPDK_RING_SIZE, SOCKET0,
2057                                         RING_F_SP_ENQ);
2058     if (ivshmem->cring_tx == NULL) {
2059         rte_free(ivshmem);
2060         return ENOMEM;
2061     }
2062
2063     err = snprintf(ring_name, sizeof(ring_name), "%s_rx", dev_name);
2064     if (err < 0) {
2065         return -err;
2066     }
2067
2068     /* Create single consumer rx ring, netdev does explicit locking. */
2069     ivshmem->cring_rx = rte_ring_create(ring_name, DPDK_RING_SIZE, SOCKET0,
2070                                         RING_F_SC_DEQ);
2071     if (ivshmem->cring_rx == NULL) {
2072         rte_free(ivshmem);
2073         return ENOMEM;
2074     }
2075
2076     err = rte_eth_from_rings(dev_name, &ivshmem->cring_rx, 1,
2077                              &ivshmem->cring_tx, 1, SOCKET0);
2078
2079     if (err < 0) {
2080         rte_free(ivshmem);
2081         return ENODEV;
2082     }
2083
2084     ivshmem->user_port_id = port_no;
2085     ivshmem->eth_port_id = rte_eth_dev_count() - 1;
2086     list_push_back(&dpdk_ring_list, &ivshmem->list_node);
2087
2088     *eth_port_id = ivshmem->eth_port_id;
2089     return 0;
2090 }
2091
2092 static int
2093 dpdk_ring_open(const char dev_name[], unsigned int *eth_port_id) OVS_REQUIRES(dpdk_mutex)
2094 {
2095     struct dpdk_ring *ivshmem;
2096     unsigned int port_no;
2097     int err = 0;
2098
2099     /* Names always start with "dpdkr" */
2100     err = dpdk_dev_parse_name(dev_name, "dpdkr", &port_no);
2101     if (err) {
2102         return err;
2103     }
2104
2105     /* look through our list to find the device */
2106     LIST_FOR_EACH (ivshmem, list_node, &dpdk_ring_list) {
2107          if (ivshmem->user_port_id == port_no) {
2108             VLOG_INFO("Found dpdk ring device %s:", dev_name);
2109             *eth_port_id = ivshmem->eth_port_id; /* really all that is needed */
2110             return 0;
2111          }
2112     }
2113     /* Need to create the device rings */
2114     return dpdk_ring_create(dev_name, port_no, eth_port_id);
2115 }
2116
2117 static int
2118 netdev_dpdk_ring_send(struct netdev *netdev_, int qid,
2119                       struct dp_packet **pkts, int cnt, bool may_steal)
2120 {
2121     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
2122     unsigned i;
2123
2124     /* When using 'dpdkr' and sending to a DPDK ring, we want to ensure that the
2125      * rss hash field is clear. This is because the same mbuf may be modified by
2126      * the consumer of the ring and return into the datapath without recalculating
2127      * the RSS hash. */
2128     for (i = 0; i < cnt; i++) {
2129         dp_packet_rss_invalidate(pkts[i]);
2130     }
2131
2132     netdev_dpdk_send__(netdev, qid, pkts, cnt, may_steal);
2133     return 0;
2134 }
2135
2136 static int
2137 netdev_dpdk_ring_construct(struct netdev *netdev)
2138 {
2139     unsigned int port_no = 0;
2140     int err = 0;
2141
2142     if (rte_eal_init_ret) {
2143         return rte_eal_init_ret;
2144     }
2145
2146     ovs_mutex_lock(&dpdk_mutex);
2147
2148     err = dpdk_ring_open(netdev->name, &port_no);
2149     if (err) {
2150         goto unlock_dpdk;
2151     }
2152
2153     err = netdev_dpdk_init(netdev, port_no, DPDK_DEV_ETH);
2154
2155 unlock_dpdk:
2156     ovs_mutex_unlock(&dpdk_mutex);
2157     return err;
2158 }
2159
2160 #define NETDEV_DPDK_CLASS(NAME, INIT, CONSTRUCT, DESTRUCT, MULTIQ, SEND, \
2161     GET_CARRIER, GET_STATS, GET_FEATURES, GET_STATUS, RXQ_RECV)          \
2162 {                                                             \
2163     NAME,                                                     \
2164     INIT,                       /* init */                    \
2165     NULL,                       /* netdev_dpdk_run */         \
2166     NULL,                       /* netdev_dpdk_wait */        \
2167                                                               \
2168     netdev_dpdk_alloc,                                        \
2169     CONSTRUCT,                                                \
2170     DESTRUCT,                                                 \
2171     netdev_dpdk_dealloc,                                      \
2172     netdev_dpdk_get_config,                                   \
2173     netdev_dpdk_set_config,                                   \
2174     NULL,                       /* get_tunnel_config */       \
2175     NULL,                       /* build header */            \
2176     NULL,                       /* push header */             \
2177     NULL,                       /* pop header */              \
2178     netdev_dpdk_get_numa_id,    /* get_numa_id */             \
2179     MULTIQ,                     /* set_multiq */              \
2180                                                               \
2181     SEND,                       /* send */                    \
2182     NULL,                       /* send_wait */               \
2183                                                               \
2184     netdev_dpdk_set_etheraddr,                                \
2185     netdev_dpdk_get_etheraddr,                                \
2186     netdev_dpdk_get_mtu,                                      \
2187     netdev_dpdk_set_mtu,                                      \
2188     netdev_dpdk_get_ifindex,                                  \
2189     GET_CARRIER,                                              \
2190     netdev_dpdk_get_carrier_resets,                           \
2191     netdev_dpdk_set_miimon,                                   \
2192     GET_STATS,                                                \
2193     GET_FEATURES,                                             \
2194     NULL,                       /* set_advertisements */      \
2195                                                               \
2196     NULL,                       /* set_policing */            \
2197     NULL,                       /* get_qos_types */           \
2198     NULL,                       /* get_qos_capabilities */    \
2199     NULL,                       /* get_qos */                 \
2200     NULL,                       /* set_qos */                 \
2201     NULL,                       /* get_queue */               \
2202     NULL,                       /* set_queue */               \
2203     NULL,                       /* delete_queue */            \
2204     NULL,                       /* get_queue_stats */         \
2205     NULL,                       /* queue_dump_start */        \
2206     NULL,                       /* queue_dump_next */         \
2207     NULL,                       /* queue_dump_done */         \
2208     NULL,                       /* dump_queue_stats */        \
2209                                                               \
2210     NULL,                       /* get_in4 */                 \
2211     NULL,                       /* set_in4 */                 \
2212     NULL,                       /* get_in6 */                 \
2213     NULL,                       /* add_router */              \
2214     NULL,                       /* get_next_hop */            \
2215     GET_STATUS,                                               \
2216     NULL,                       /* arp_lookup */              \
2217                                                               \
2218     netdev_dpdk_update_flags,                                 \
2219                                                               \
2220     netdev_dpdk_rxq_alloc,                                    \
2221     netdev_dpdk_rxq_construct,                                \
2222     netdev_dpdk_rxq_destruct,                                 \
2223     netdev_dpdk_rxq_dealloc,                                  \
2224     RXQ_RECV,                                                 \
2225     NULL,                       /* rx_wait */                 \
2226     NULL,                       /* rxq_drain */               \
2227 }
2228
2229 static int
2230 process_vhost_flags(char *flag, char *default_val, int size,
2231                     char **argv, char **new_val)
2232 {
2233     int changed = 0;
2234
2235     /* Depending on which version of vhost is in use, process the vhost-specific
2236      * flag if it is provided on the vswitchd command line, otherwise resort to
2237      * a default value.
2238      *
2239      * For vhost-user: Process "-vhost_sock_dir" to set the custom location of
2240      * the vhost-user socket(s).
2241      * For vhost-cuse: Process "-cuse_dev_name" to set the custom name of the
2242      * vhost-cuse character device.
2243      */
2244     if (!strcmp(argv[1], flag) && (strlen(argv[2]) <= size)) {
2245         changed = 1;
2246         *new_val = xstrdup(argv[2]);
2247         VLOG_INFO("User-provided %s in use: %s", flag, *new_val);
2248     } else {
2249         VLOG_INFO("No %s provided - defaulting to %s", flag, default_val);
2250         *new_val = default_val;
2251     }
2252
2253     return changed;
2254 }
2255
2256 int
2257 dpdk_init(int argc, char **argv)
2258 {
2259     int result;
2260     int base = 0;
2261     char *pragram_name = argv[0];
2262
2263     if (argc < 2 || strcmp(argv[1], "--dpdk"))
2264         return 0;
2265
2266     /* Remove the --dpdk argument from arg list.*/
2267     argc--;
2268     argv++;
2269
2270     /* Reject --user option */
2271     int i;
2272     for (i = 0; i < argc; i++) {
2273         if (!strcmp(argv[i], "--user")) {
2274             VLOG_ERR("Can not mix --dpdk and --user options, aborting.");
2275         }
2276     }
2277
2278 #ifdef VHOST_CUSE
2279     if (process_vhost_flags("-cuse_dev_name", xstrdup("vhost-net"),
2280                             PATH_MAX, argv, &cuse_dev_name)) {
2281 #else
2282     if (process_vhost_flags("-vhost_sock_dir", xstrdup(ovs_rundir()),
2283                             NAME_MAX, argv, &vhost_sock_dir)) {
2284         struct stat s;
2285         int err;
2286
2287         err = stat(vhost_sock_dir, &s);
2288         if (err) {
2289             VLOG_ERR("vHostUser socket DIR '%s' does not exist.",
2290                      vhost_sock_dir);
2291             return err;
2292         }
2293 #endif
2294         /* Remove the vhost flag configuration parameters from the argument
2295          * list, so that the correct elements are passed to the DPDK
2296          * initialization function
2297          */
2298         argc -= 2;
2299         argv += 2;    /* Increment by two to bypass the vhost flag arguments */
2300         base = 2;
2301     }
2302
2303     /* Keep the program name argument as this is needed for call to
2304      * rte_eal_init()
2305      */
2306     argv[0] = pragram_name;
2307
2308     /* Make sure things are initialized ... */
2309     result = rte_eal_init(argc, argv);
2310     if (result < 0) {
2311         ovs_abort(result, "Cannot init EAL");
2312     }
2313
2314     rte_memzone_dump(stdout);
2315     rte_eal_init_ret = 0;
2316
2317     if (argc > result) {
2318         argv[result] = argv[0];
2319     }
2320
2321     /* We are called from the main thread here */
2322     RTE_PER_LCORE(_lcore_id) = NON_PMD_CORE_ID;
2323
2324     return result + 1 + base;
2325 }
2326
2327 static const struct netdev_class dpdk_class =
2328     NETDEV_DPDK_CLASS(
2329         "dpdk",
2330         NULL,
2331         netdev_dpdk_construct,
2332         netdev_dpdk_destruct,
2333         netdev_dpdk_set_multiq,
2334         netdev_dpdk_eth_send,
2335         netdev_dpdk_get_carrier,
2336         netdev_dpdk_get_stats,
2337         netdev_dpdk_get_features,
2338         netdev_dpdk_get_status,
2339         netdev_dpdk_rxq_recv);
2340
2341 static const struct netdev_class dpdk_ring_class =
2342     NETDEV_DPDK_CLASS(
2343         "dpdkr",
2344         NULL,
2345         netdev_dpdk_ring_construct,
2346         netdev_dpdk_destruct,
2347         netdev_dpdk_set_multiq,
2348         netdev_dpdk_ring_send,
2349         netdev_dpdk_get_carrier,
2350         netdev_dpdk_get_stats,
2351         netdev_dpdk_get_features,
2352         netdev_dpdk_get_status,
2353         netdev_dpdk_rxq_recv);
2354
2355 static const struct netdev_class OVS_UNUSED dpdk_vhost_cuse_class =
2356     NETDEV_DPDK_CLASS(
2357         "dpdkvhostcuse",
2358         dpdk_vhost_cuse_class_init,
2359         netdev_dpdk_vhost_cuse_construct,
2360         netdev_dpdk_vhost_destruct,
2361         netdev_dpdk_vhost_cuse_set_multiq,
2362         netdev_dpdk_vhost_send,
2363         netdev_dpdk_vhost_get_carrier,
2364         netdev_dpdk_vhost_get_stats,
2365         NULL,
2366         NULL,
2367         netdev_dpdk_vhost_rxq_recv);
2368
2369 static const struct netdev_class OVS_UNUSED dpdk_vhost_user_class =
2370     NETDEV_DPDK_CLASS(
2371         "dpdkvhostuser",
2372         dpdk_vhost_user_class_init,
2373         netdev_dpdk_vhost_user_construct,
2374         netdev_dpdk_vhost_destruct,
2375         netdev_dpdk_vhost_set_multiq,
2376         netdev_dpdk_vhost_send,
2377         netdev_dpdk_vhost_get_carrier,
2378         netdev_dpdk_vhost_get_stats,
2379         NULL,
2380         NULL,
2381         netdev_dpdk_vhost_rxq_recv);
2382
2383 void
2384 netdev_dpdk_register(void)
2385 {
2386     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
2387
2388     if (rte_eal_init_ret) {
2389         return;
2390     }
2391
2392     if (ovsthread_once_start(&once)) {
2393         dpdk_common_init();
2394         netdev_register_provider(&dpdk_class);
2395         netdev_register_provider(&dpdk_ring_class);
2396 #ifdef VHOST_CUSE
2397         netdev_register_provider(&dpdk_vhost_cuse_class);
2398 #else
2399         netdev_register_provider(&dpdk_vhost_user_class);
2400 #endif
2401         ovsthread_once_done(&once);
2402     }
2403 }
2404
2405 int
2406 pmd_thread_setaffinity_cpu(unsigned cpu)
2407 {
2408     cpu_set_t cpuset;
2409     int err;
2410
2411     CPU_ZERO(&cpuset);
2412     CPU_SET(cpu, &cpuset);
2413     err = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
2414     if (err) {
2415         VLOG_ERR("Thread affinity error %d",err);
2416         return err;
2417     }
2418     /* NON_PMD_CORE_ID is reserved for use by non pmd threads. */
2419     ovs_assert(cpu != NON_PMD_CORE_ID);
2420     RTE_PER_LCORE(_lcore_id) = cpu;
2421
2422     return 0;
2423 }
2424
2425 static bool
2426 dpdk_thread_is_pmd(void)
2427 {
2428     return rte_lcore_id() != NON_PMD_CORE_ID;
2429 }