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