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