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