1e43daec90778ea3bc1bff7c3badb77ee0e97dc9
[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     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->real_n_txq = NR_QUEUE;
618
619     if (type == DPDK_DEV_ETH) {
620         netdev_dpdk_alloc_txq(netdev, NR_QUEUE);
621         err = dpdk_eth_dev_init(netdev);
622         if (err) {
623             goto unlock;
624         }
625     }
626
627     list_push_back(&dpdk_list, &netdev->list_node);
628
629 unlock:
630     if (err) {
631         rte_free(netdev->tx_q);
632     }
633     ovs_mutex_unlock(&netdev->mutex);
634     return err;
635 }
636
637 static int
638 dpdk_dev_parse_name(const char dev_name[], const char prefix[],
639                     unsigned int *port_no)
640 {
641     const char *cport;
642
643     if (strncmp(dev_name, prefix, strlen(prefix))) {
644         return ENODEV;
645     }
646
647     cport = dev_name + strlen(prefix);
648     *port_no = strtol(cport, NULL, 0); /* string must be null terminated */
649     return 0;
650 }
651
652 static int
653 vhost_construct_helper(struct netdev *netdev_) OVS_REQUIRES(dpdk_mutex)
654 {
655     if (rte_eal_init_ret) {
656         return rte_eal_init_ret;
657     }
658
659     return netdev_dpdk_init(netdev_, -1, DPDK_DEV_VHOST);
660 }
661
662 static int
663 netdev_dpdk_vhost_cuse_construct(struct netdev *netdev_)
664 {
665     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
666     int err;
667
668     ovs_mutex_lock(&dpdk_mutex);
669     strncpy(netdev->vhost_id, netdev->up.name, sizeof(netdev->vhost_id));
670     err = vhost_construct_helper(netdev_);
671     ovs_mutex_unlock(&dpdk_mutex);
672     return err;
673 }
674
675 static int
676 netdev_dpdk_vhost_user_construct(struct netdev *netdev_)
677 {
678     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
679     int err;
680
681     ovs_mutex_lock(&dpdk_mutex);
682     /* Take the name of the vhost-user port and append it to the location where
683      * the socket is to be created, then register the socket.
684      */
685     snprintf(netdev->vhost_id, sizeof(netdev->vhost_id), "%s/%s",
686             vhost_sock_dir, netdev_->name);
687     err = rte_vhost_driver_register(netdev->vhost_id);
688     if (err) {
689         VLOG_ERR("vhost-user socket device setup failure for socket %s\n",
690                  netdev->vhost_id);
691     } else {
692         fatal_signal_add_file_to_unlink(netdev->vhost_id);
693     }
694
695     VLOG_INFO("Socket %s created for vhost-user port %s\n", netdev->vhost_id, netdev_->name);
696     err = vhost_construct_helper(netdev_);
697     ovs_mutex_unlock(&dpdk_mutex);
698     return err;
699 }
700
701 static int
702 netdev_dpdk_construct(struct netdev *netdev)
703 {
704     unsigned int port_no;
705     int err;
706
707     if (rte_eal_init_ret) {
708         return rte_eal_init_ret;
709     }
710
711     /* Names always start with "dpdk" */
712     err = dpdk_dev_parse_name(netdev->name, "dpdk", &port_no);
713     if (err) {
714         return err;
715     }
716
717     ovs_mutex_lock(&dpdk_mutex);
718     err = netdev_dpdk_init(netdev, port_no, DPDK_DEV_ETH);
719     ovs_mutex_unlock(&dpdk_mutex);
720     return err;
721 }
722
723 static void
724 netdev_dpdk_destruct(struct netdev *netdev_)
725 {
726     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
727
728     ovs_mutex_lock(&dev->mutex);
729     rte_eth_dev_stop(dev->port_id);
730     ovs_mutex_unlock(&dev->mutex);
731
732     ovs_mutex_lock(&dpdk_mutex);
733     rte_free(dev->tx_q);
734     list_remove(&dev->list_node);
735     dpdk_mp_put(dev->dpdk_mp);
736     ovs_mutex_unlock(&dpdk_mutex);
737 }
738
739 static void
740 netdev_dpdk_vhost_destruct(struct netdev *netdev_)
741 {
742     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
743
744     /* Can't remove a port while a guest is attached to it. */
745     if (netdev_dpdk_get_virtio(dev) != NULL) {
746         VLOG_ERR("Can not remove port, vhost device still attached");
747                 return;
748     }
749
750     if (rte_vhost_driver_unregister(dev->vhost_id)) {
751         VLOG_ERR("Unable to remove vhost-user socket %s", dev->vhost_id);
752     } else {
753         fatal_signal_remove_file_to_unlink(dev->vhost_id);
754     }
755
756     ovs_mutex_lock(&dpdk_mutex);
757     list_remove(&dev->list_node);
758     dpdk_mp_put(dev->dpdk_mp);
759     ovs_mutex_unlock(&dpdk_mutex);
760 }
761
762 static void
763 netdev_dpdk_dealloc(struct netdev *netdev_)
764 {
765     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
766
767     rte_free(netdev);
768 }
769
770 static int
771 netdev_dpdk_get_config(const struct netdev *netdev_, struct smap *args)
772 {
773     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
774
775     ovs_mutex_lock(&dev->mutex);
776
777     smap_add_format(args, "configured_rx_queues", "%d", netdev_->n_rxq);
778     smap_add_format(args, "requested_tx_queues", "%d", netdev_->n_txq);
779     smap_add_format(args, "configured_tx_queues", "%d", dev->real_n_txq);
780     ovs_mutex_unlock(&dev->mutex);
781
782     return 0;
783 }
784
785 static int
786 netdev_dpdk_get_numa_id(const struct netdev *netdev_)
787 {
788     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
789
790     return netdev->socket_id;
791 }
792
793 /* Sets the number of tx queues and rx queues for the dpdk interface.
794  * If the configuration fails, do not try restoring its old configuration
795  * and just returns the error. */
796 static int
797 netdev_dpdk_set_multiq(struct netdev *netdev_, unsigned int n_txq,
798                        unsigned int n_rxq)
799 {
800     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
801     int err = 0;
802     int old_rxq, old_txq;
803
804     if (netdev->up.n_txq == n_txq && netdev->up.n_rxq == n_rxq) {
805         return err;
806     }
807
808     ovs_mutex_lock(&dpdk_mutex);
809     ovs_mutex_lock(&netdev->mutex);
810
811     rte_eth_dev_stop(netdev->port_id);
812
813     old_txq = netdev->up.n_txq;
814     old_rxq = netdev->up.n_rxq;
815     netdev->up.n_txq = n_txq;
816     netdev->up.n_rxq = n_rxq;
817
818     rte_free(netdev->tx_q);
819     err = dpdk_eth_dev_init(netdev);
820     netdev_dpdk_alloc_txq(netdev, netdev->real_n_txq);
821     if (err) {
822         /* If there has been an error, it means that the requested queues
823          * have not been created.  Restore the old numbers. */
824         netdev->up.n_txq = old_txq;
825         netdev->up.n_rxq = old_rxq;
826     }
827
828     netdev->txq_needs_locking = netdev->real_n_txq != netdev->up.n_txq;
829
830     ovs_mutex_unlock(&netdev->mutex);
831     ovs_mutex_unlock(&dpdk_mutex);
832
833     return err;
834 }
835
836 static int
837 netdev_dpdk_vhost_cuse_set_multiq(struct netdev *netdev_, unsigned int n_txq,
838                              unsigned int n_rxq)
839 {
840     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
841     int err = 0;
842
843     if (netdev->up.n_txq == n_txq && netdev->up.n_rxq == n_rxq) {
844         return err;
845     }
846
847     ovs_mutex_lock(&dpdk_mutex);
848     ovs_mutex_lock(&netdev->mutex);
849
850     netdev->up.n_txq = n_txq;
851     netdev->real_n_txq = 1;
852     netdev->up.n_rxq = 1;
853     netdev->txq_needs_locking = netdev->real_n_txq != netdev->up.n_txq;
854
855     ovs_mutex_unlock(&netdev->mutex);
856     ovs_mutex_unlock(&dpdk_mutex);
857
858     return err;
859 }
860
861 static int
862 netdev_dpdk_vhost_set_multiq(struct netdev *netdev_, unsigned int n_txq,
863                              unsigned int n_rxq)
864 {
865     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
866     int err = 0;
867
868     if (netdev->up.n_txq == n_txq && netdev->up.n_rxq == n_rxq) {
869         return err;
870     }
871
872     ovs_mutex_lock(&dpdk_mutex);
873     ovs_mutex_lock(&netdev->mutex);
874
875     rte_free(netdev->tx_q);
876     netdev->up.n_txq = n_txq;
877     netdev->up.n_rxq = n_rxq;
878     netdev_dpdk_alloc_txq(netdev, netdev->up.n_txq);
879
880     ovs_mutex_unlock(&netdev->mutex);
881     ovs_mutex_unlock(&dpdk_mutex);
882
883     return err;
884 }
885
886 static struct netdev_rxq *
887 netdev_dpdk_rxq_alloc(void)
888 {
889     struct netdev_rxq_dpdk *rx = dpdk_rte_mzalloc(sizeof *rx);
890
891     return &rx->up;
892 }
893
894 static struct netdev_rxq_dpdk *
895 netdev_rxq_dpdk_cast(const struct netdev_rxq *rx)
896 {
897     return CONTAINER_OF(rx, struct netdev_rxq_dpdk, up);
898 }
899
900 static int
901 netdev_dpdk_rxq_construct(struct netdev_rxq *rxq_)
902 {
903     struct netdev_rxq_dpdk *rx = netdev_rxq_dpdk_cast(rxq_);
904     struct netdev_dpdk *netdev = netdev_dpdk_cast(rx->up.netdev);
905
906     ovs_mutex_lock(&netdev->mutex);
907     rx->port_id = netdev->port_id;
908     ovs_mutex_unlock(&netdev->mutex);
909
910     return 0;
911 }
912
913 static void
914 netdev_dpdk_rxq_destruct(struct netdev_rxq *rxq_ OVS_UNUSED)
915 {
916 }
917
918 static void
919 netdev_dpdk_rxq_dealloc(struct netdev_rxq *rxq_)
920 {
921     struct netdev_rxq_dpdk *rx = netdev_rxq_dpdk_cast(rxq_);
922
923     rte_free(rx);
924 }
925
926 static inline void
927 dpdk_queue_flush__(struct netdev_dpdk *dev, int qid)
928 {
929     struct dpdk_tx_queue *txq = &dev->tx_q[qid];
930     uint32_t nb_tx = 0;
931
932     while (nb_tx != txq->count) {
933         uint32_t ret;
934
935         ret = rte_eth_tx_burst(dev->port_id, qid, txq->burst_pkts + nb_tx,
936                                txq->count - nb_tx);
937         if (!ret) {
938             break;
939         }
940
941         nb_tx += ret;
942     }
943
944     if (OVS_UNLIKELY(nb_tx != txq->count)) {
945         /* free buffers, which we couldn't transmit, one at a time (each
946          * packet could come from a different mempool) */
947         int i;
948
949         for (i = nb_tx; i < txq->count; i++) {
950             rte_pktmbuf_free_seg(txq->burst_pkts[i]);
951         }
952         rte_spinlock_lock(&dev->stats_lock);
953         dev->stats.tx_dropped += txq->count-nb_tx;
954         rte_spinlock_unlock(&dev->stats_lock);
955     }
956
957     txq->count = 0;
958     txq->tsc = rte_get_timer_cycles();
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
966     if (txq->count == 0) {
967         return;
968     }
969     dpdk_queue_flush__(dev, qid);
970 }
971
972 static bool
973 is_vhost_running(struct virtio_net *dev)
974 {
975     return (dev != NULL && (dev->flags & VIRTIO_DEV_RUNNING));
976 }
977
978 static inline void
979 netdev_dpdk_vhost_update_rx_counters(struct netdev_stats *stats,
980                                      struct dp_packet **packets, int count)
981 {
982     int i;
983     struct dp_packet *packet;
984
985     stats->rx_packets += count;
986     for (i = 0; i < count; i++) {
987         packet = packets[i];
988
989         if (OVS_UNLIKELY(dp_packet_size(packet) < ETH_HEADER_LEN)) {
990             /* This only protects the following multicast counting from
991              * too short packets, but it does not stop the packet from
992              * further processing. */
993             stats->rx_errors++;
994             stats->rx_length_errors++;
995             continue;
996         }
997
998         struct eth_header *eh = (struct eth_header *) dp_packet_data(packet);
999         if (OVS_UNLIKELY(eth_addr_is_multicast(eh->eth_dst))) {
1000             stats->multicast++;
1001         }
1002
1003         stats->rx_bytes += dp_packet_size(packet);
1004     }
1005 }
1006
1007 /*
1008  * The receive path for the vhost port is the TX path out from guest.
1009  */
1010 static int
1011 netdev_dpdk_vhost_rxq_recv(struct netdev_rxq *rxq_,
1012                            struct dp_packet **packets, int *c)
1013 {
1014     struct netdev_rxq_dpdk *rx = netdev_rxq_dpdk_cast(rxq_);
1015     struct netdev *netdev = rx->up.netdev;
1016     struct netdev_dpdk *vhost_dev = netdev_dpdk_cast(netdev);
1017     struct virtio_net *virtio_dev = netdev_dpdk_get_virtio(vhost_dev);
1018     int qid = rxq_->queue_id;
1019     uint16_t nb_rx = 0;
1020
1021     if (OVS_UNLIKELY(!is_vhost_running(virtio_dev))) {
1022         return EAGAIN;
1023     }
1024
1025     if (rxq_->queue_id >= vhost_dev->real_n_rxq) {
1026         return EOPNOTSUPP;
1027     }
1028
1029     nb_rx = rte_vhost_dequeue_burst(virtio_dev, qid * VIRTIO_QNUM + VIRTIO_TXQ,
1030                                     vhost_dev->dpdk_mp->mp,
1031                                     (struct rte_mbuf **)packets,
1032                                     NETDEV_MAX_BURST);
1033     if (!nb_rx) {
1034         return EAGAIN;
1035     }
1036
1037     rte_spinlock_lock(&vhost_dev->stats_lock);
1038     netdev_dpdk_vhost_update_rx_counters(&vhost_dev->stats, packets, nb_rx);
1039     rte_spinlock_unlock(&vhost_dev->stats_lock);
1040
1041     *c = (int) nb_rx;
1042     return 0;
1043 }
1044
1045 static int
1046 netdev_dpdk_rxq_recv(struct netdev_rxq *rxq_, struct dp_packet **packets,
1047                      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 *dev = netdev_dpdk_cast(netdev);
1052     int nb_rx;
1053
1054     /* There is only one tx queue for this core.  Do not flush other
1055      * queues.
1056      * Do not flush tx queue which is shared among CPUs
1057      * since it is always flushed */
1058     if (rxq_->queue_id == rte_lcore_id() &&
1059         OVS_LIKELY(!dev->txq_needs_locking)) {
1060         dpdk_queue_flush(dev, rxq_->queue_id);
1061     }
1062
1063     nb_rx = rte_eth_rx_burst(rx->port_id, rxq_->queue_id,
1064                              (struct rte_mbuf **) packets,
1065                              NETDEV_MAX_BURST);
1066     if (!nb_rx) {
1067         return EAGAIN;
1068     }
1069
1070     *c = nb_rx;
1071
1072     return 0;
1073 }
1074
1075 static inline void
1076 netdev_dpdk_vhost_update_tx_counters(struct netdev_stats *stats,
1077                                      struct dp_packet **packets,
1078                                      int attempted,
1079                                      int dropped)
1080 {
1081     int i;
1082     int sent = attempted - dropped;
1083
1084     stats->tx_packets += sent;
1085     stats->tx_dropped += dropped;
1086
1087     for (i = 0; i < sent; i++) {
1088         stats->tx_bytes += dp_packet_size(packets[i]);
1089     }
1090 }
1091
1092 static void
1093 __netdev_dpdk_vhost_send(struct netdev *netdev, int qid,
1094                          struct dp_packet **pkts, int cnt,
1095                          bool may_steal)
1096 {
1097     struct netdev_dpdk *vhost_dev = netdev_dpdk_cast(netdev);
1098     struct virtio_net *virtio_dev = netdev_dpdk_get_virtio(vhost_dev);
1099     struct rte_mbuf **cur_pkts = (struct rte_mbuf **) pkts;
1100     unsigned int total_pkts = cnt;
1101     uint64_t start = 0;
1102
1103     if (OVS_UNLIKELY(!is_vhost_running(virtio_dev))) {
1104         rte_spinlock_lock(&vhost_dev->stats_lock);
1105         vhost_dev->stats.tx_dropped+= cnt;
1106         rte_spinlock_unlock(&vhost_dev->stats_lock);
1107         goto out;
1108     }
1109
1110     if (vhost_dev->txq_needs_locking) {
1111         qid = qid % vhost_dev->real_n_txq;
1112         rte_spinlock_lock(&vhost_dev->tx_q[qid].tx_lock);
1113     }
1114
1115     do {
1116         int vhost_qid = qid * VIRTIO_QNUM + VIRTIO_RXQ;
1117         unsigned int tx_pkts;
1118
1119         tx_pkts = rte_vhost_enqueue_burst(virtio_dev, vhost_qid,
1120                                           cur_pkts, cnt);
1121         if (OVS_LIKELY(tx_pkts)) {
1122             /* Packets have been sent.*/
1123             cnt -= tx_pkts;
1124             /* Prepare for possible next iteration.*/
1125             cur_pkts = &cur_pkts[tx_pkts];
1126         } else {
1127             uint64_t timeout = VHOST_ENQ_RETRY_USECS * rte_get_timer_hz() / 1E6;
1128             unsigned int expired = 0;
1129
1130             if (!start) {
1131                 start = rte_get_timer_cycles();
1132             }
1133
1134             /*
1135              * Unable to enqueue packets to vhost interface.
1136              * Check available entries before retrying.
1137              */
1138             while (!rte_vring_available_entries(virtio_dev, vhost_qid)) {
1139                 if (OVS_UNLIKELY((rte_get_timer_cycles() - start) > timeout)) {
1140                     expired = 1;
1141                     break;
1142                 }
1143             }
1144             if (expired) {
1145                 /* break out of main loop. */
1146                 break;
1147             }
1148         }
1149     } while (cnt);
1150
1151     if (vhost_dev->txq_needs_locking) {
1152         rte_spinlock_unlock(&vhost_dev->tx_q[qid].tx_lock);
1153     }
1154
1155     rte_spinlock_lock(&vhost_dev->stats_lock);
1156     netdev_dpdk_vhost_update_tx_counters(&vhost_dev->stats, pkts, total_pkts,
1157                                          cnt);
1158     rte_spinlock_unlock(&vhost_dev->stats_lock);
1159
1160 out:
1161     if (may_steal) {
1162         int i;
1163
1164         for (i = 0; i < total_pkts; i++) {
1165             dp_packet_delete(pkts[i]);
1166         }
1167     }
1168 }
1169
1170 inline static void
1171 dpdk_queue_pkts(struct netdev_dpdk *dev, int qid,
1172                struct rte_mbuf **pkts, int cnt)
1173 {
1174     struct dpdk_tx_queue *txq = &dev->tx_q[qid];
1175     uint64_t diff_tsc;
1176
1177     int i = 0;
1178
1179     while (i < cnt) {
1180         int freeslots = MAX_TX_QUEUE_LEN - txq->count;
1181         int tocopy = MIN(freeslots, cnt-i);
1182
1183         memcpy(&txq->burst_pkts[txq->count], &pkts[i],
1184                tocopy * sizeof (struct rte_mbuf *));
1185
1186         txq->count += tocopy;
1187         i += tocopy;
1188
1189         if (txq->count == MAX_TX_QUEUE_LEN || txq->flush_tx) {
1190             dpdk_queue_flush__(dev, qid);
1191         }
1192         diff_tsc = rte_get_timer_cycles() - txq->tsc;
1193         if (diff_tsc >= DRAIN_TSC) {
1194             dpdk_queue_flush__(dev, qid);
1195         }
1196     }
1197 }
1198
1199 /* Tx function. Transmit packets indefinitely */
1200 static void
1201 dpdk_do_tx_copy(struct netdev *netdev, int qid, struct dp_packet **pkts,
1202                 int cnt)
1203     OVS_NO_THREAD_SAFETY_ANALYSIS
1204 {
1205 #if !defined(__CHECKER__) && !defined(_WIN32)
1206     const size_t PKT_ARRAY_SIZE = cnt;
1207 #else
1208     /* Sparse or MSVC doesn't like variable length array. */
1209     enum { PKT_ARRAY_SIZE = NETDEV_MAX_BURST };
1210 #endif
1211     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1212     struct rte_mbuf *mbufs[PKT_ARRAY_SIZE];
1213     int dropped = 0;
1214     int newcnt = 0;
1215     int i;
1216
1217     /* If we are on a non pmd thread we have to use the mempool mutex, because
1218      * every non pmd thread shares the same mempool cache */
1219
1220     if (!dpdk_thread_is_pmd()) {
1221         ovs_mutex_lock(&nonpmd_mempool_mutex);
1222     }
1223
1224     for (i = 0; i < cnt; i++) {
1225         int size = dp_packet_size(pkts[i]);
1226
1227         if (OVS_UNLIKELY(size > dev->max_packet_len)) {
1228             VLOG_WARN_RL(&rl, "Too big size %d max_packet_len %d",
1229                          (int)size , dev->max_packet_len);
1230
1231             dropped++;
1232             continue;
1233         }
1234
1235         mbufs[newcnt] = rte_pktmbuf_alloc(dev->dpdk_mp->mp);
1236
1237         if (!mbufs[newcnt]) {
1238             dropped += cnt - i;
1239             break;
1240         }
1241
1242         /* We have to do a copy for now */
1243         memcpy(rte_pktmbuf_mtod(mbufs[newcnt], void *), dp_packet_data(pkts[i]), size);
1244
1245         rte_pktmbuf_data_len(mbufs[newcnt]) = size;
1246         rte_pktmbuf_pkt_len(mbufs[newcnt]) = size;
1247
1248         newcnt++;
1249     }
1250
1251     if (OVS_UNLIKELY(dropped)) {
1252         rte_spinlock_lock(&dev->stats_lock);
1253         dev->stats.tx_dropped += dropped;
1254         rte_spinlock_unlock(&dev->stats_lock);
1255     }
1256
1257     if (dev->type == DPDK_DEV_VHOST) {
1258         __netdev_dpdk_vhost_send(netdev, qid, (struct dp_packet **) mbufs, newcnt, true);
1259     } else {
1260         dpdk_queue_pkts(dev, qid, mbufs, newcnt);
1261         dpdk_queue_flush(dev, qid);
1262     }
1263
1264     if (!dpdk_thread_is_pmd()) {
1265         ovs_mutex_unlock(&nonpmd_mempool_mutex);
1266     }
1267 }
1268
1269 static int
1270 netdev_dpdk_vhost_send(struct netdev *netdev, int qid, struct dp_packet **pkts,
1271                  int cnt, bool may_steal)
1272 {
1273     if (OVS_UNLIKELY(pkts[0]->source != DPBUF_DPDK)) {
1274         int i;
1275
1276         dpdk_do_tx_copy(netdev, qid, pkts, cnt);
1277         if (may_steal) {
1278             for (i = 0; i < cnt; i++) {
1279                 dp_packet_delete(pkts[i]);
1280             }
1281         }
1282     } else {
1283         __netdev_dpdk_vhost_send(netdev, qid, pkts, cnt, may_steal);
1284     }
1285     return 0;
1286 }
1287
1288 static inline void
1289 netdev_dpdk_send__(struct netdev_dpdk *dev, int qid,
1290                    struct dp_packet **pkts, int cnt, bool may_steal)
1291 {
1292     int i;
1293
1294     if (OVS_UNLIKELY(dev->txq_needs_locking)) {
1295         qid = qid % dev->real_n_txq;
1296         rte_spinlock_lock(&dev->tx_q[qid].tx_lock);
1297     }
1298
1299     if (OVS_UNLIKELY(!may_steal ||
1300                      pkts[0]->source != DPBUF_DPDK)) {
1301         struct netdev *netdev = &dev->up;
1302
1303         dpdk_do_tx_copy(netdev, qid, pkts, cnt);
1304
1305         if (may_steal) {
1306             for (i = 0; i < cnt; i++) {
1307                 dp_packet_delete(pkts[i]);
1308             }
1309         }
1310     } else {
1311         int next_tx_idx = 0;
1312         int dropped = 0;
1313
1314         for (i = 0; i < cnt; i++) {
1315             int size = dp_packet_size(pkts[i]);
1316
1317             if (OVS_UNLIKELY(size > dev->max_packet_len)) {
1318                 if (next_tx_idx != i) {
1319                     dpdk_queue_pkts(dev, qid,
1320                                     (struct rte_mbuf **)&pkts[next_tx_idx],
1321                                     i-next_tx_idx);
1322                 }
1323
1324                 VLOG_WARN_RL(&rl, "Too big size %d max_packet_len %d",
1325                              (int)size , dev->max_packet_len);
1326
1327                 dp_packet_delete(pkts[i]);
1328                 dropped++;
1329                 next_tx_idx = i + 1;
1330             }
1331         }
1332         if (next_tx_idx != cnt) {
1333            dpdk_queue_pkts(dev, qid,
1334                             (struct rte_mbuf **)&pkts[next_tx_idx],
1335                             cnt-next_tx_idx);
1336         }
1337
1338         if (OVS_UNLIKELY(dropped)) {
1339             rte_spinlock_lock(&dev->stats_lock);
1340             dev->stats.tx_dropped += dropped;
1341             rte_spinlock_unlock(&dev->stats_lock);
1342         }
1343     }
1344
1345     if (OVS_UNLIKELY(dev->txq_needs_locking)) {
1346         rte_spinlock_unlock(&dev->tx_q[qid].tx_lock);
1347     }
1348 }
1349
1350 static int
1351 netdev_dpdk_eth_send(struct netdev *netdev, int qid,
1352                      struct dp_packet **pkts, int cnt, bool may_steal)
1353 {
1354     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1355
1356     netdev_dpdk_send__(dev, qid, pkts, cnt, may_steal);
1357     return 0;
1358 }
1359
1360 static int
1361 netdev_dpdk_set_etheraddr(struct netdev *netdev, const struct eth_addr mac)
1362 {
1363     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1364
1365     ovs_mutex_lock(&dev->mutex);
1366     if (!eth_addr_equals(dev->hwaddr, mac)) {
1367         dev->hwaddr = mac;
1368         netdev_change_seq_changed(netdev);
1369     }
1370     ovs_mutex_unlock(&dev->mutex);
1371
1372     return 0;
1373 }
1374
1375 static int
1376 netdev_dpdk_get_etheraddr(const struct netdev *netdev, struct eth_addr *mac)
1377 {
1378     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1379
1380     ovs_mutex_lock(&dev->mutex);
1381     *mac = dev->hwaddr;
1382     ovs_mutex_unlock(&dev->mutex);
1383
1384     return 0;
1385 }
1386
1387 static int
1388 netdev_dpdk_get_mtu(const struct netdev *netdev, int *mtup)
1389 {
1390     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1391
1392     ovs_mutex_lock(&dev->mutex);
1393     *mtup = dev->mtu;
1394     ovs_mutex_unlock(&dev->mutex);
1395
1396     return 0;
1397 }
1398
1399 static int
1400 netdev_dpdk_set_mtu(const struct netdev *netdev, int mtu)
1401 {
1402     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1403     int old_mtu, err;
1404     struct dpdk_mp *old_mp;
1405     struct dpdk_mp *mp;
1406
1407     ovs_mutex_lock(&dpdk_mutex);
1408     ovs_mutex_lock(&dev->mutex);
1409     if (dev->mtu == mtu) {
1410         err = 0;
1411         goto out;
1412     }
1413
1414     mp = dpdk_mp_get(dev->socket_id, dev->mtu);
1415     if (!mp) {
1416         err = ENOMEM;
1417         goto out;
1418     }
1419
1420     rte_eth_dev_stop(dev->port_id);
1421
1422     old_mtu = dev->mtu;
1423     old_mp = dev->dpdk_mp;
1424     dev->dpdk_mp = mp;
1425     dev->mtu = mtu;
1426     dev->max_packet_len = MTU_TO_MAX_LEN(dev->mtu);
1427
1428     err = dpdk_eth_dev_init(dev);
1429     if (err) {
1430         dpdk_mp_put(mp);
1431         dev->mtu = old_mtu;
1432         dev->dpdk_mp = old_mp;
1433         dev->max_packet_len = MTU_TO_MAX_LEN(dev->mtu);
1434         dpdk_eth_dev_init(dev);
1435         goto out;
1436     }
1437
1438     dpdk_mp_put(old_mp);
1439     netdev_change_seq_changed(netdev);
1440 out:
1441     ovs_mutex_unlock(&dev->mutex);
1442     ovs_mutex_unlock(&dpdk_mutex);
1443     return err;
1444 }
1445
1446 static int
1447 netdev_dpdk_get_carrier(const struct netdev *netdev_, bool *carrier);
1448
1449 static int
1450 netdev_dpdk_vhost_get_stats(const struct netdev *netdev,
1451                             struct netdev_stats *stats)
1452 {
1453     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1454
1455     ovs_mutex_lock(&dev->mutex);
1456     memset(stats, 0, sizeof(*stats));
1457     /* Unsupported Stats */
1458     stats->collisions = UINT64_MAX;
1459     stats->rx_crc_errors = UINT64_MAX;
1460     stats->rx_fifo_errors = UINT64_MAX;
1461     stats->rx_frame_errors = UINT64_MAX;
1462     stats->rx_missed_errors = UINT64_MAX;
1463     stats->rx_over_errors = UINT64_MAX;
1464     stats->tx_aborted_errors = UINT64_MAX;
1465     stats->tx_carrier_errors = UINT64_MAX;
1466     stats->tx_errors = UINT64_MAX;
1467     stats->tx_fifo_errors = UINT64_MAX;
1468     stats->tx_heartbeat_errors = UINT64_MAX;
1469     stats->tx_window_errors = UINT64_MAX;
1470     stats->rx_dropped += UINT64_MAX;
1471
1472     rte_spinlock_lock(&dev->stats_lock);
1473     /* Supported Stats */
1474     stats->rx_packets += dev->stats.rx_packets;
1475     stats->tx_packets += dev->stats.tx_packets;
1476     stats->tx_dropped += dev->stats.tx_dropped;
1477     stats->multicast = dev->stats.multicast;
1478     stats->rx_bytes = dev->stats.rx_bytes;
1479     stats->tx_bytes = dev->stats.tx_bytes;
1480     stats->rx_errors = dev->stats.rx_errors;
1481     stats->rx_length_errors = dev->stats.rx_length_errors;
1482     rte_spinlock_unlock(&dev->stats_lock);
1483
1484     ovs_mutex_unlock(&dev->mutex);
1485
1486     return 0;
1487 }
1488
1489 static int
1490 netdev_dpdk_get_stats(const struct netdev *netdev, struct netdev_stats *stats)
1491 {
1492     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1493     struct rte_eth_stats rte_stats;
1494     bool gg;
1495
1496     netdev_dpdk_get_carrier(netdev, &gg);
1497     ovs_mutex_lock(&dev->mutex);
1498     rte_eth_stats_get(dev->port_id, &rte_stats);
1499
1500     memset(stats, 0, sizeof(*stats));
1501
1502     stats->rx_packets = rte_stats.ipackets;
1503     stats->tx_packets = rte_stats.opackets;
1504     stats->rx_bytes = rte_stats.ibytes;
1505     stats->tx_bytes = rte_stats.obytes;
1506     /* DPDK counts imissed as errors, but count them here as dropped instead */
1507     stats->rx_errors = rte_stats.ierrors - rte_stats.imissed;
1508     stats->tx_errors = rte_stats.oerrors;
1509     stats->multicast = rte_stats.imcasts;
1510
1511     rte_spinlock_lock(&dev->stats_lock);
1512     stats->tx_dropped = dev->stats.tx_dropped;
1513     rte_spinlock_unlock(&dev->stats_lock);
1514
1515     /* These are the available DPDK counters for packets not received due to
1516      * local resource constraints in DPDK and NIC respectively. */
1517     stats->rx_dropped = rte_stats.rx_nombuf + rte_stats.imissed;
1518     stats->collisions = UINT64_MAX;
1519
1520     stats->rx_length_errors = UINT64_MAX;
1521     stats->rx_over_errors = UINT64_MAX;
1522     stats->rx_crc_errors = UINT64_MAX;
1523     stats->rx_frame_errors = UINT64_MAX;
1524     stats->rx_fifo_errors = UINT64_MAX;
1525     stats->rx_missed_errors = rte_stats.imissed;
1526
1527     stats->tx_aborted_errors = UINT64_MAX;
1528     stats->tx_carrier_errors = UINT64_MAX;
1529     stats->tx_fifo_errors = UINT64_MAX;
1530     stats->tx_heartbeat_errors = UINT64_MAX;
1531     stats->tx_window_errors = UINT64_MAX;
1532
1533     ovs_mutex_unlock(&dev->mutex);
1534
1535     return 0;
1536 }
1537
1538 static int
1539 netdev_dpdk_get_features(const struct netdev *netdev_,
1540                          enum netdev_features *current,
1541                          enum netdev_features *advertised OVS_UNUSED,
1542                          enum netdev_features *supported OVS_UNUSED,
1543                          enum netdev_features *peer OVS_UNUSED)
1544 {
1545     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
1546     struct rte_eth_link link;
1547
1548     ovs_mutex_lock(&dev->mutex);
1549     link = dev->link;
1550     ovs_mutex_unlock(&dev->mutex);
1551
1552     if (link.link_duplex == ETH_LINK_AUTONEG_DUPLEX) {
1553         if (link.link_speed == ETH_LINK_SPEED_AUTONEG) {
1554             *current = NETDEV_F_AUTONEG;
1555         }
1556     } else if (link.link_duplex == ETH_LINK_HALF_DUPLEX) {
1557         if (link.link_speed == ETH_LINK_SPEED_10) {
1558             *current = NETDEV_F_10MB_HD;
1559         }
1560         if (link.link_speed == ETH_LINK_SPEED_100) {
1561             *current = NETDEV_F_100MB_HD;
1562         }
1563         if (link.link_speed == ETH_LINK_SPEED_1000) {
1564             *current = NETDEV_F_1GB_HD;
1565         }
1566     } else if (link.link_duplex == ETH_LINK_FULL_DUPLEX) {
1567         if (link.link_speed == ETH_LINK_SPEED_10) {
1568             *current = NETDEV_F_10MB_FD;
1569         }
1570         if (link.link_speed == ETH_LINK_SPEED_100) {
1571             *current = NETDEV_F_100MB_FD;
1572         }
1573         if (link.link_speed == ETH_LINK_SPEED_1000) {
1574             *current = NETDEV_F_1GB_FD;
1575         }
1576         if (link.link_speed == ETH_LINK_SPEED_10000) {
1577             *current = NETDEV_F_10GB_FD;
1578         }
1579     }
1580
1581     return 0;
1582 }
1583
1584 static int
1585 netdev_dpdk_get_ifindex(const struct netdev *netdev)
1586 {
1587     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev);
1588     int ifindex;
1589
1590     ovs_mutex_lock(&dev->mutex);
1591     ifindex = dev->port_id;
1592     ovs_mutex_unlock(&dev->mutex);
1593
1594     return ifindex;
1595 }
1596
1597 static int
1598 netdev_dpdk_get_carrier(const struct netdev *netdev_, bool *carrier)
1599 {
1600     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
1601
1602     ovs_mutex_lock(&dev->mutex);
1603     check_link_status(dev);
1604     *carrier = dev->link.link_status;
1605
1606     ovs_mutex_unlock(&dev->mutex);
1607
1608     return 0;
1609 }
1610
1611 static int
1612 netdev_dpdk_vhost_get_carrier(const struct netdev *netdev_, bool *carrier)
1613 {
1614     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
1615     struct virtio_net *virtio_dev = netdev_dpdk_get_virtio(dev);
1616
1617     ovs_mutex_lock(&dev->mutex);
1618
1619     if (is_vhost_running(virtio_dev)) {
1620         *carrier = 1;
1621     } else {
1622         *carrier = 0;
1623     }
1624
1625     ovs_mutex_unlock(&dev->mutex);
1626
1627     return 0;
1628 }
1629
1630 static long long int
1631 netdev_dpdk_get_carrier_resets(const struct netdev *netdev_)
1632 {
1633     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
1634     long long int carrier_resets;
1635
1636     ovs_mutex_lock(&dev->mutex);
1637     carrier_resets = dev->link_reset_cnt;
1638     ovs_mutex_unlock(&dev->mutex);
1639
1640     return carrier_resets;
1641 }
1642
1643 static int
1644 netdev_dpdk_set_miimon(struct netdev *netdev_ OVS_UNUSED,
1645                        long long int interval OVS_UNUSED)
1646 {
1647     return EOPNOTSUPP;
1648 }
1649
1650 static int
1651 netdev_dpdk_update_flags__(struct netdev_dpdk *dev,
1652                            enum netdev_flags off, enum netdev_flags on,
1653                            enum netdev_flags *old_flagsp) OVS_REQUIRES(dev->mutex)
1654 {
1655     int err;
1656
1657     if ((off | on) & ~(NETDEV_UP | NETDEV_PROMISC)) {
1658         return EINVAL;
1659     }
1660
1661     *old_flagsp = dev->flags;
1662     dev->flags |= on;
1663     dev->flags &= ~off;
1664
1665     if (dev->flags == *old_flagsp) {
1666         return 0;
1667     }
1668
1669     if (dev->type == DPDK_DEV_ETH) {
1670         if (dev->flags & NETDEV_UP) {
1671             err = rte_eth_dev_start(dev->port_id);
1672             if (err)
1673                 return -err;
1674         }
1675
1676         if (dev->flags & NETDEV_PROMISC) {
1677             rte_eth_promiscuous_enable(dev->port_id);
1678         }
1679
1680         if (!(dev->flags & NETDEV_UP)) {
1681             rte_eth_dev_stop(dev->port_id);
1682         }
1683     }
1684
1685     return 0;
1686 }
1687
1688 static int
1689 netdev_dpdk_update_flags(struct netdev *netdev_,
1690                          enum netdev_flags off, enum netdev_flags on,
1691                          enum netdev_flags *old_flagsp)
1692 {
1693     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
1694     int error;
1695
1696     ovs_mutex_lock(&netdev->mutex);
1697     error = netdev_dpdk_update_flags__(netdev, off, on, old_flagsp);
1698     ovs_mutex_unlock(&netdev->mutex);
1699
1700     return error;
1701 }
1702
1703 static int
1704 netdev_dpdk_get_status(const struct netdev *netdev_, struct smap *args)
1705 {
1706     struct netdev_dpdk *dev = netdev_dpdk_cast(netdev_);
1707     struct rte_eth_dev_info dev_info;
1708
1709     if (dev->port_id < 0)
1710         return ENODEV;
1711
1712     ovs_mutex_lock(&dev->mutex);
1713     rte_eth_dev_info_get(dev->port_id, &dev_info);
1714     ovs_mutex_unlock(&dev->mutex);
1715
1716     smap_add_format(args, "driver_name", "%s", dev_info.driver_name);
1717
1718     smap_add_format(args, "port_no", "%d", dev->port_id);
1719     smap_add_format(args, "numa_id", "%d", rte_eth_dev_socket_id(dev->port_id));
1720     smap_add_format(args, "driver_name", "%s", dev_info.driver_name);
1721     smap_add_format(args, "min_rx_bufsize", "%u", dev_info.min_rx_bufsize);
1722     smap_add_format(args, "max_rx_pktlen", "%u", dev_info.max_rx_pktlen);
1723     smap_add_format(args, "max_rx_queues", "%u", dev_info.max_rx_queues);
1724     smap_add_format(args, "max_tx_queues", "%u", dev_info.max_tx_queues);
1725     smap_add_format(args, "max_mac_addrs", "%u", dev_info.max_mac_addrs);
1726     smap_add_format(args, "max_hash_mac_addrs", "%u", dev_info.max_hash_mac_addrs);
1727     smap_add_format(args, "max_vfs", "%u", dev_info.max_vfs);
1728     smap_add_format(args, "max_vmdq_pools", "%u", dev_info.max_vmdq_pools);
1729
1730     if (dev_info.pci_dev) {
1731         smap_add_format(args, "pci-vendor_id", "0x%u",
1732                         dev_info.pci_dev->id.vendor_id);
1733         smap_add_format(args, "pci-device_id", "0x%x",
1734                         dev_info.pci_dev->id.device_id);
1735     }
1736
1737     return 0;
1738 }
1739
1740 static void
1741 netdev_dpdk_set_admin_state__(struct netdev_dpdk *dev, bool admin_state)
1742     OVS_REQUIRES(dev->mutex)
1743 {
1744     enum netdev_flags old_flags;
1745
1746     if (admin_state) {
1747         netdev_dpdk_update_flags__(dev, 0, NETDEV_UP, &old_flags);
1748     } else {
1749         netdev_dpdk_update_flags__(dev, NETDEV_UP, 0, &old_flags);
1750     }
1751 }
1752
1753 static void
1754 netdev_dpdk_set_admin_state(struct unixctl_conn *conn, int argc,
1755                             const char *argv[], void *aux OVS_UNUSED)
1756 {
1757     bool up;
1758
1759     if (!strcasecmp(argv[argc - 1], "up")) {
1760         up = true;
1761     } else if ( !strcasecmp(argv[argc - 1], "down")) {
1762         up = false;
1763     } else {
1764         unixctl_command_reply_error(conn, "Invalid Admin State");
1765         return;
1766     }
1767
1768     if (argc > 2) {
1769         struct netdev *netdev = netdev_from_name(argv[1]);
1770         if (netdev && is_dpdk_class(netdev->netdev_class)) {
1771             struct netdev_dpdk *dpdk_dev = netdev_dpdk_cast(netdev);
1772
1773             ovs_mutex_lock(&dpdk_dev->mutex);
1774             netdev_dpdk_set_admin_state__(dpdk_dev, up);
1775             ovs_mutex_unlock(&dpdk_dev->mutex);
1776
1777             netdev_close(netdev);
1778         } else {
1779             unixctl_command_reply_error(conn, "Not a DPDK Interface");
1780             netdev_close(netdev);
1781             return;
1782         }
1783     } else {
1784         struct netdev_dpdk *netdev;
1785
1786         ovs_mutex_lock(&dpdk_mutex);
1787         LIST_FOR_EACH (netdev, list_node, &dpdk_list) {
1788             ovs_mutex_lock(&netdev->mutex);
1789             netdev_dpdk_set_admin_state__(netdev, up);
1790             ovs_mutex_unlock(&netdev->mutex);
1791         }
1792         ovs_mutex_unlock(&dpdk_mutex);
1793     }
1794     unixctl_command_reply(conn, "OK");
1795 }
1796
1797 /*
1798  * Set virtqueue flags so that we do not receive interrupts.
1799  */
1800 static void
1801 set_irq_status(struct virtio_net *dev)
1802 {
1803     uint32_t i;
1804     uint64_t idx;
1805
1806     for (i = 0; i < dev->virt_qp_nb; i++) {
1807         idx = i * VIRTIO_QNUM;
1808         rte_vhost_enable_guest_notification(dev, idx + VIRTIO_RXQ, 0);
1809         rte_vhost_enable_guest_notification(dev, idx + VIRTIO_TXQ, 0);
1810     }
1811 }
1812
1813
1814 static int
1815 netdev_dpdk_vhost_set_queues(struct netdev_dpdk *netdev, struct virtio_net *dev)
1816 {
1817     uint32_t qp_num;
1818
1819     qp_num = dev->virt_qp_nb;
1820     if (qp_num > netdev->up.n_rxq) {
1821         VLOG_ERR("vHost Device '%s' %"PRIu64" can't be added - "
1822                  "too many queues %d > %d", dev->ifname, dev->device_fh,
1823                  qp_num, netdev->up.n_rxq);
1824         return -1;
1825     }
1826
1827     netdev->real_n_rxq = qp_num;
1828     netdev->real_n_txq = qp_num;
1829     if (netdev->up.n_txq > netdev->real_n_txq) {
1830         netdev->txq_needs_locking = true;
1831     } else {
1832         netdev->txq_needs_locking = false;
1833     }
1834
1835     return 0;
1836 }
1837
1838 /*
1839  * A new virtio-net device is added to a vhost port.
1840  */
1841 static int
1842 new_device(struct virtio_net *dev)
1843 {
1844     struct netdev_dpdk *netdev;
1845     bool exists = false;
1846
1847     ovs_mutex_lock(&dpdk_mutex);
1848     /* Add device to the vhost port with the same name as that passed down. */
1849     LIST_FOR_EACH(netdev, list_node, &dpdk_list) {
1850         if (strncmp(dev->ifname, netdev->vhost_id, IF_NAME_SZ) == 0) {
1851             ovs_mutex_lock(&netdev->mutex);
1852             if (netdev_dpdk_vhost_set_queues(netdev, dev)) {
1853                 ovs_mutex_unlock(&netdev->mutex);
1854                 ovs_mutex_unlock(&dpdk_mutex);
1855                 return -1;
1856             }
1857             ovsrcu_set(&netdev->virtio_dev, dev);
1858             exists = true;
1859             dev->flags |= VIRTIO_DEV_RUNNING;
1860             /* Disable notifications. */
1861             set_irq_status(dev);
1862             ovs_mutex_unlock(&netdev->mutex);
1863             break;
1864         }
1865     }
1866     ovs_mutex_unlock(&dpdk_mutex);
1867
1868     if (!exists) {
1869         VLOG_INFO("vHost Device '%s' %"PRIu64" can't be added - name not "
1870                   "found", dev->ifname, dev->device_fh);
1871
1872         return -1;
1873     }
1874
1875     VLOG_INFO("vHost Device '%s' %"PRIu64" has been added", dev->ifname,
1876               dev->device_fh);
1877     return 0;
1878 }
1879
1880 /*
1881  * Remove a virtio-net device from the specific vhost port.  Use dev->remove
1882  * flag to stop any more packets from being sent or received to/from a VM and
1883  * ensure all currently queued packets have been sent/received before removing
1884  *  the device.
1885  */
1886 static void
1887 destroy_device(volatile struct virtio_net *dev)
1888 {
1889     struct netdev_dpdk *vhost_dev;
1890
1891     ovs_mutex_lock(&dpdk_mutex);
1892     LIST_FOR_EACH (vhost_dev, list_node, &dpdk_list) {
1893         if (netdev_dpdk_get_virtio(vhost_dev) == dev) {
1894
1895             ovs_mutex_lock(&vhost_dev->mutex);
1896             dev->flags &= ~VIRTIO_DEV_RUNNING;
1897             ovsrcu_set(&vhost_dev->virtio_dev, NULL);
1898             ovs_mutex_unlock(&vhost_dev->mutex);
1899
1900             /*
1901              * Wait for other threads to quiesce before
1902              * setting the virtio_dev to NULL.
1903              */
1904             ovsrcu_synchronize();
1905             /*
1906              * As call to ovsrcu_synchronize() will end the quiescent state,
1907              * put thread back into quiescent state before returning.
1908              */
1909             ovsrcu_quiesce_start();
1910         }
1911     }
1912     ovs_mutex_unlock(&dpdk_mutex);
1913
1914     VLOG_INFO("vHost Device '%s' %"PRIu64" has been removed", dev->ifname,
1915               dev->device_fh);
1916 }
1917
1918 struct virtio_net *
1919 netdev_dpdk_get_virtio(const struct netdev_dpdk *dev)
1920 {
1921     return ovsrcu_get(struct virtio_net *, &dev->virtio_dev);
1922 }
1923
1924 /*
1925  * These callbacks allow virtio-net devices to be added to vhost ports when
1926  * configuration has been fully complete.
1927  */
1928 static const struct virtio_net_device_ops virtio_net_device_ops =
1929 {
1930     .new_device =  new_device,
1931     .destroy_device = destroy_device,
1932 };
1933
1934 static void *
1935 start_vhost_loop(void *dummy OVS_UNUSED)
1936 {
1937      pthread_detach(pthread_self());
1938      /* Put the cuse thread into quiescent state. */
1939      ovsrcu_quiesce_start();
1940      rte_vhost_driver_session_start();
1941      return NULL;
1942 }
1943
1944 static int
1945 dpdk_vhost_class_init(void)
1946 {
1947     rte_vhost_driver_callback_register(&virtio_net_device_ops);
1948     ovs_thread_create("vhost_thread", start_vhost_loop, NULL);
1949     return 0;
1950 }
1951
1952 static int
1953 dpdk_vhost_cuse_class_init(void)
1954 {
1955     int err = -1;
1956
1957
1958     /* Register CUSE device to handle IOCTLs.
1959      * Unless otherwise specified on the vswitchd command line, cuse_dev_name
1960      * is set to vhost-net.
1961      */
1962     err = rte_vhost_driver_register(cuse_dev_name);
1963
1964     if (err != 0) {
1965         VLOG_ERR("CUSE device setup failure.");
1966         return -1;
1967     }
1968
1969     dpdk_vhost_class_init();
1970     return 0;
1971 }
1972
1973 static int
1974 dpdk_vhost_user_class_init(void)
1975 {
1976     dpdk_vhost_class_init();
1977     return 0;
1978 }
1979
1980 static void
1981 dpdk_common_init(void)
1982 {
1983     unixctl_command_register("netdev-dpdk/set-admin-state",
1984                              "[netdev] up|down", 1, 2,
1985                              netdev_dpdk_set_admin_state, NULL);
1986
1987     ovs_thread_create("dpdk_watchdog", dpdk_watchdog, NULL);
1988 }
1989
1990 /* Client Rings */
1991
1992 static int
1993 dpdk_ring_create(const char dev_name[], unsigned int port_no,
1994                  unsigned int *eth_port_id)
1995 {
1996     struct dpdk_ring *ivshmem;
1997     char ring_name[10];
1998     int err;
1999
2000     ivshmem = dpdk_rte_mzalloc(sizeof *ivshmem);
2001     if (ivshmem == NULL) {
2002         return ENOMEM;
2003     }
2004
2005     /* XXX: Add support for multiquque ring. */
2006     err = snprintf(ring_name, 10, "%s_tx", dev_name);
2007     if (err < 0) {
2008         return -err;
2009     }
2010
2011     /* Create single producer tx ring, netdev does explicit locking. */
2012     ivshmem->cring_tx = rte_ring_create(ring_name, DPDK_RING_SIZE, SOCKET0,
2013                                         RING_F_SP_ENQ);
2014     if (ivshmem->cring_tx == NULL) {
2015         rte_free(ivshmem);
2016         return ENOMEM;
2017     }
2018
2019     err = snprintf(ring_name, 10, "%s_rx", dev_name);
2020     if (err < 0) {
2021         return -err;
2022     }
2023
2024     /* Create single consumer rx ring, netdev does explicit locking. */
2025     ivshmem->cring_rx = rte_ring_create(ring_name, DPDK_RING_SIZE, SOCKET0,
2026                                         RING_F_SC_DEQ);
2027     if (ivshmem->cring_rx == NULL) {
2028         rte_free(ivshmem);
2029         return ENOMEM;
2030     }
2031
2032     err = rte_eth_from_rings(dev_name, &ivshmem->cring_rx, 1,
2033                              &ivshmem->cring_tx, 1, SOCKET0);
2034
2035     if (err < 0) {
2036         rte_free(ivshmem);
2037         return ENODEV;
2038     }
2039
2040     ivshmem->user_port_id = port_no;
2041     ivshmem->eth_port_id = rte_eth_dev_count() - 1;
2042     list_push_back(&dpdk_ring_list, &ivshmem->list_node);
2043
2044     *eth_port_id = ivshmem->eth_port_id;
2045     return 0;
2046 }
2047
2048 static int
2049 dpdk_ring_open(const char dev_name[], unsigned int *eth_port_id) OVS_REQUIRES(dpdk_mutex)
2050 {
2051     struct dpdk_ring *ivshmem;
2052     unsigned int port_no;
2053     int err = 0;
2054
2055     /* Names always start with "dpdkr" */
2056     err = dpdk_dev_parse_name(dev_name, "dpdkr", &port_no);
2057     if (err) {
2058         return err;
2059     }
2060
2061     /* look through our list to find the device */
2062     LIST_FOR_EACH (ivshmem, list_node, &dpdk_ring_list) {
2063          if (ivshmem->user_port_id == port_no) {
2064             VLOG_INFO("Found dpdk ring device %s:", dev_name);
2065             *eth_port_id = ivshmem->eth_port_id; /* really all that is needed */
2066             return 0;
2067          }
2068     }
2069     /* Need to create the device rings */
2070     return dpdk_ring_create(dev_name, port_no, eth_port_id);
2071 }
2072
2073 static int
2074 netdev_dpdk_ring_send(struct netdev *netdev_, int qid,
2075                       struct dp_packet **pkts, int cnt, bool may_steal)
2076 {
2077     struct netdev_dpdk *netdev = netdev_dpdk_cast(netdev_);
2078     unsigned i;
2079
2080     /* When using 'dpdkr' and sending to a DPDK ring, we want to ensure that the
2081      * rss hash field is clear. This is because the same mbuf may be modified by
2082      * the consumer of the ring and return into the datapath without recalculating
2083      * the RSS hash. */
2084     for (i = 0; i < cnt; i++) {
2085         dp_packet_rss_invalidate(pkts[i]);
2086     }
2087
2088     netdev_dpdk_send__(netdev, qid, pkts, cnt, may_steal);
2089     return 0;
2090 }
2091
2092 static int
2093 netdev_dpdk_ring_construct(struct netdev *netdev)
2094 {
2095     unsigned int port_no = 0;
2096     int err = 0;
2097
2098     if (rte_eal_init_ret) {
2099         return rte_eal_init_ret;
2100     }
2101
2102     ovs_mutex_lock(&dpdk_mutex);
2103
2104     err = dpdk_ring_open(netdev->name, &port_no);
2105     if (err) {
2106         goto unlock_dpdk;
2107     }
2108
2109     err = netdev_dpdk_init(netdev, port_no, DPDK_DEV_ETH);
2110
2111 unlock_dpdk:
2112     ovs_mutex_unlock(&dpdk_mutex);
2113     return err;
2114 }
2115
2116 #define NETDEV_DPDK_CLASS(NAME, INIT, CONSTRUCT, DESTRUCT, MULTIQ, SEND, \
2117     GET_CARRIER, GET_STATS, GET_FEATURES, GET_STATUS, RXQ_RECV)          \
2118 {                                                             \
2119     NAME,                                                     \
2120     INIT,                       /* init */                    \
2121     NULL,                       /* netdev_dpdk_run */         \
2122     NULL,                       /* netdev_dpdk_wait */        \
2123                                                               \
2124     netdev_dpdk_alloc,                                        \
2125     CONSTRUCT,                                                \
2126     DESTRUCT,                                                 \
2127     netdev_dpdk_dealloc,                                      \
2128     netdev_dpdk_get_config,                                   \
2129     NULL,                       /* netdev_dpdk_set_config */  \
2130     NULL,                       /* get_tunnel_config */       \
2131     NULL,                       /* build header */            \
2132     NULL,                       /* push header */             \
2133     NULL,                       /* pop header */              \
2134     netdev_dpdk_get_numa_id,    /* get_numa_id */             \
2135     MULTIQ,                     /* set_multiq */              \
2136                                                               \
2137     SEND,                       /* send */                    \
2138     NULL,                       /* send_wait */               \
2139                                                               \
2140     netdev_dpdk_set_etheraddr,                                \
2141     netdev_dpdk_get_etheraddr,                                \
2142     netdev_dpdk_get_mtu,                                      \
2143     netdev_dpdk_set_mtu,                                      \
2144     netdev_dpdk_get_ifindex,                                  \
2145     GET_CARRIER,                                              \
2146     netdev_dpdk_get_carrier_resets,                           \
2147     netdev_dpdk_set_miimon,                                   \
2148     GET_STATS,                                                \
2149     GET_FEATURES,                                             \
2150     NULL,                       /* set_advertisements */      \
2151                                                               \
2152     NULL,                       /* set_policing */            \
2153     NULL,                       /* get_qos_types */           \
2154     NULL,                       /* get_qos_capabilities */    \
2155     NULL,                       /* get_qos */                 \
2156     NULL,                       /* set_qos */                 \
2157     NULL,                       /* get_queue */               \
2158     NULL,                       /* set_queue */               \
2159     NULL,                       /* delete_queue */            \
2160     NULL,                       /* get_queue_stats */         \
2161     NULL,                       /* queue_dump_start */        \
2162     NULL,                       /* queue_dump_next */         \
2163     NULL,                       /* queue_dump_done */         \
2164     NULL,                       /* dump_queue_stats */        \
2165                                                               \
2166     NULL,                       /* get_in4 */                 \
2167     NULL,                       /* set_in4 */                 \
2168     NULL,                       /* get_in6 */                 \
2169     NULL,                       /* add_router */              \
2170     NULL,                       /* get_next_hop */            \
2171     GET_STATUS,                                               \
2172     NULL,                       /* arp_lookup */              \
2173                                                               \
2174     netdev_dpdk_update_flags,                                 \
2175                                                               \
2176     netdev_dpdk_rxq_alloc,                                    \
2177     netdev_dpdk_rxq_construct,                                \
2178     netdev_dpdk_rxq_destruct,                                 \
2179     netdev_dpdk_rxq_dealloc,                                  \
2180     RXQ_RECV,                                                 \
2181     NULL,                       /* rx_wait */                 \
2182     NULL,                       /* rxq_drain */               \
2183 }
2184
2185 static int
2186 process_vhost_flags(char *flag, char *default_val, int size,
2187                     char **argv, char **new_val)
2188 {
2189     int changed = 0;
2190
2191     /* Depending on which version of vhost is in use, process the vhost-specific
2192      * flag if it is provided on the vswitchd command line, otherwise resort to
2193      * a default value.
2194      *
2195      * For vhost-user: Process "-vhost_sock_dir" to set the custom location of
2196      * the vhost-user socket(s).
2197      * For vhost-cuse: Process "-cuse_dev_name" to set the custom name of the
2198      * vhost-cuse character device.
2199      */
2200     if (!strcmp(argv[1], flag) && (strlen(argv[2]) <= size)) {
2201         changed = 1;
2202         *new_val = xstrdup(argv[2]);
2203         VLOG_INFO("User-provided %s in use: %s", flag, *new_val);
2204     } else {
2205         VLOG_INFO("No %s provided - defaulting to %s", flag, default_val);
2206         *new_val = default_val;
2207     }
2208
2209     return changed;
2210 }
2211
2212 int
2213 dpdk_init(int argc, char **argv)
2214 {
2215     int result;
2216     int base = 0;
2217     char *pragram_name = argv[0];
2218
2219     if (argc < 2 || strcmp(argv[1], "--dpdk"))
2220         return 0;
2221
2222     /* Remove the --dpdk argument from arg list.*/
2223     argc--;
2224     argv++;
2225
2226     /* Reject --user option */
2227     int i;
2228     for (i = 0; i < argc; i++) {
2229         if (!strcmp(argv[i], "--user")) {
2230             VLOG_ERR("Can not mix --dpdk and --user options, aborting.");
2231         }
2232     }
2233
2234 #ifdef VHOST_CUSE
2235     if (process_vhost_flags("-cuse_dev_name", xstrdup("vhost-net"),
2236                             PATH_MAX, argv, &cuse_dev_name)) {
2237 #else
2238     if (process_vhost_flags("-vhost_sock_dir", xstrdup(ovs_rundir()),
2239                             NAME_MAX, argv, &vhost_sock_dir)) {
2240         struct stat s;
2241         int err;
2242
2243         err = stat(vhost_sock_dir, &s);
2244         if (err) {
2245             VLOG_ERR("vHostUser socket DIR '%s' does not exist.",
2246                      vhost_sock_dir);
2247             return err;
2248         }
2249 #endif
2250         /* Remove the vhost flag configuration parameters from the argument
2251          * list, so that the correct elements are passed to the DPDK
2252          * initialization function
2253          */
2254         argc -= 2;
2255         argv += 2;    /* Increment by two to bypass the vhost flag arguments */
2256         base = 2;
2257     }
2258
2259     /* Keep the program name argument as this is needed for call to
2260      * rte_eal_init()
2261      */
2262     argv[0] = pragram_name;
2263
2264     /* Make sure things are initialized ... */
2265     result = rte_eal_init(argc, argv);
2266     if (result < 0) {
2267         ovs_abort(result, "Cannot init EAL");
2268     }
2269
2270     rte_memzone_dump(stdout);
2271     rte_eal_init_ret = 0;
2272
2273     if (argc > result) {
2274         argv[result] = argv[0];
2275     }
2276
2277     /* We are called from the main thread here */
2278     RTE_PER_LCORE(_lcore_id) = NON_PMD_CORE_ID;
2279
2280     return result + 1 + base;
2281 }
2282
2283 static const struct netdev_class dpdk_class =
2284     NETDEV_DPDK_CLASS(
2285         "dpdk",
2286         NULL,
2287         netdev_dpdk_construct,
2288         netdev_dpdk_destruct,
2289         netdev_dpdk_set_multiq,
2290         netdev_dpdk_eth_send,
2291         netdev_dpdk_get_carrier,
2292         netdev_dpdk_get_stats,
2293         netdev_dpdk_get_features,
2294         netdev_dpdk_get_status,
2295         netdev_dpdk_rxq_recv);
2296
2297 static const struct netdev_class dpdk_ring_class =
2298     NETDEV_DPDK_CLASS(
2299         "dpdkr",
2300         NULL,
2301         netdev_dpdk_ring_construct,
2302         netdev_dpdk_destruct,
2303         netdev_dpdk_set_multiq,
2304         netdev_dpdk_ring_send,
2305         netdev_dpdk_get_carrier,
2306         netdev_dpdk_get_stats,
2307         netdev_dpdk_get_features,
2308         netdev_dpdk_get_status,
2309         netdev_dpdk_rxq_recv);
2310
2311 static const struct netdev_class OVS_UNUSED dpdk_vhost_cuse_class =
2312     NETDEV_DPDK_CLASS(
2313         "dpdkvhostcuse",
2314         dpdk_vhost_cuse_class_init,
2315         netdev_dpdk_vhost_cuse_construct,
2316         netdev_dpdk_vhost_destruct,
2317         netdev_dpdk_vhost_cuse_set_multiq,
2318         netdev_dpdk_vhost_send,
2319         netdev_dpdk_vhost_get_carrier,
2320         netdev_dpdk_vhost_get_stats,
2321         NULL,
2322         NULL,
2323         netdev_dpdk_vhost_rxq_recv);
2324
2325 static const struct netdev_class OVS_UNUSED dpdk_vhost_user_class =
2326     NETDEV_DPDK_CLASS(
2327         "dpdkvhostuser",
2328         dpdk_vhost_user_class_init,
2329         netdev_dpdk_vhost_user_construct,
2330         netdev_dpdk_vhost_destruct,
2331         netdev_dpdk_vhost_set_multiq,
2332         netdev_dpdk_vhost_send,
2333         netdev_dpdk_vhost_get_carrier,
2334         netdev_dpdk_vhost_get_stats,
2335         NULL,
2336         NULL,
2337         netdev_dpdk_vhost_rxq_recv);
2338
2339 void
2340 netdev_dpdk_register(void)
2341 {
2342     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
2343
2344     if (rte_eal_init_ret) {
2345         return;
2346     }
2347
2348     if (ovsthread_once_start(&once)) {
2349         dpdk_common_init();
2350         netdev_register_provider(&dpdk_class);
2351         netdev_register_provider(&dpdk_ring_class);
2352 #ifdef VHOST_CUSE
2353         netdev_register_provider(&dpdk_vhost_cuse_class);
2354 #else
2355         netdev_register_provider(&dpdk_vhost_user_class);
2356 #endif
2357         ovsthread_once_done(&once);
2358     }
2359 }
2360
2361 int
2362 pmd_thread_setaffinity_cpu(unsigned cpu)
2363 {
2364     cpu_set_t cpuset;
2365     int err;
2366
2367     CPU_ZERO(&cpuset);
2368     CPU_SET(cpu, &cpuset);
2369     err = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
2370     if (err) {
2371         VLOG_ERR("Thread affinity error %d",err);
2372         return err;
2373     }
2374     /* NON_PMD_CORE_ID is reserved for use by non pmd threads. */
2375     ovs_assert(cpu != NON_PMD_CORE_ID);
2376     RTE_PER_LCORE(_lcore_id) = cpu;
2377
2378     return 0;
2379 }
2380
2381 static bool
2382 dpdk_thread_is_pmd(void)
2383 {
2384     return rte_lcore_id() != NON_PMD_CORE_ID;
2385 }