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