dpif-netdev: Fix race condition in pmd thread initialization.
[cascardo/ovs.git] / lib / netdev.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 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 #include "netdev.h"
19
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <netinet/in.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26
27 #ifndef _WIN32
28 #include <ifaddrs.h>
29 #include <net/if.h>
30 #include <sys/ioctl.h>
31 #include <sys/types.h>
32 #endif
33
34 #include "cmap.h"
35 #include "coverage.h"
36 #include "dpif.h"
37 #include "dp-packet.h"
38 #include "openvswitch/dynamic-string.h"
39 #include "fatal-signal.h"
40 #include "hash.h"
41 #include "openvswitch/list.h"
42 #include "netdev-dpdk.h"
43 #include "netdev-provider.h"
44 #include "netdev-vport.h"
45 #include "odp-netlink.h"
46 #include "openflow/openflow.h"
47 #include "packets.h"
48 #include "poll-loop.h"
49 #include "seq.h"
50 #include "shash.h"
51 #include "smap.h"
52 #include "sset.h"
53 #include "svec.h"
54 #include "openvswitch/vlog.h"
55 #include "flow.h"
56 #include "util.h"
57
58 VLOG_DEFINE_THIS_MODULE(netdev);
59
60 COVERAGE_DEFINE(netdev_received);
61 COVERAGE_DEFINE(netdev_sent);
62 COVERAGE_DEFINE(netdev_add_router);
63 COVERAGE_DEFINE(netdev_get_stats);
64
65 struct netdev_saved_flags {
66     struct netdev *netdev;
67     struct ovs_list node;           /* In struct netdev's saved_flags_list. */
68     enum netdev_flags saved_flags;
69     enum netdev_flags saved_values;
70 };
71
72 /* Protects 'netdev_shash' and the mutable members of struct netdev. */
73 static struct ovs_mutex netdev_mutex = OVS_MUTEX_INITIALIZER;
74
75 /* All created network devices. */
76 static struct shash netdev_shash OVS_GUARDED_BY(netdev_mutex)
77     = SHASH_INITIALIZER(&netdev_shash);
78
79 /* Mutual exclusion of */
80 static struct ovs_mutex netdev_class_mutex OVS_ACQ_BEFORE(netdev_mutex)
81     = OVS_MUTEX_INITIALIZER;
82
83 /* Contains 'struct netdev_registered_class'es. */
84 static struct cmap netdev_classes = CMAP_INITIALIZER;
85
86 struct netdev_registered_class {
87     struct cmap_node cmap_node; /* In 'netdev_classes', by class->type. */
88     const struct netdev_class *class;
89
90     /* Number of references: one for the class itself and one for every
91      * instance of the class. */
92     struct ovs_refcount refcnt;
93 };
94
95 /* This is set pretty low because we probably won't learn anything from the
96  * additional log messages. */
97 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
98
99 static void restore_all_flags(void *aux OVS_UNUSED);
100 void update_device_args(struct netdev *, const struct shash *args);
101
102 int
103 netdev_n_txq(const struct netdev *netdev)
104 {
105     return netdev->n_txq;
106 }
107
108 int
109 netdev_n_rxq(const struct netdev *netdev)
110 {
111     return netdev->n_rxq;
112 }
113
114 int
115 netdev_requested_n_rxq(const struct netdev *netdev)
116 {
117     return netdev->requested_n_rxq;
118 }
119
120 bool
121 netdev_is_pmd(const struct netdev *netdev)
122 {
123     return netdev->netdev_class->is_pmd;
124 }
125
126 static void
127 netdev_initialize(void)
128     OVS_EXCLUDED(netdev_mutex)
129 {
130     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
131
132     if (ovsthread_once_start(&once)) {
133         fatal_signal_add_hook(restore_all_flags, NULL, NULL, true);
134
135         netdev_vport_patch_register();
136
137 #ifdef __linux__
138         netdev_register_provider(&netdev_linux_class);
139         netdev_register_provider(&netdev_internal_class);
140         netdev_register_provider(&netdev_tap_class);
141         netdev_vport_tunnel_register();
142 #endif
143 #if defined(__FreeBSD__) || defined(__NetBSD__)
144         netdev_register_provider(&netdev_tap_class);
145         netdev_register_provider(&netdev_bsd_class);
146 #endif
147 #ifdef _WIN32
148         netdev_register_provider(&netdev_windows_class);
149         netdev_register_provider(&netdev_internal_class);
150         netdev_vport_tunnel_register();
151 #endif
152         ovsthread_once_done(&once);
153     }
154 }
155
156 /* Performs periodic work needed by all the various kinds of netdevs.
157  *
158  * If your program opens any netdevs, it must call this function within its
159  * main poll loop. */
160 void
161 netdev_run(void)
162     OVS_EXCLUDED(netdev_mutex)
163 {
164     netdev_initialize();
165
166     struct netdev_registered_class *rc;
167     CMAP_FOR_EACH (rc, cmap_node, &netdev_classes) {
168         if (rc->class->run) {
169             rc->class->run();
170         }
171     }
172 }
173
174 /* Arranges for poll_block() to wake up when netdev_run() needs to be called.
175  *
176  * If your program opens any netdevs, it must call this function within its
177  * main poll loop. */
178 void
179 netdev_wait(void)
180     OVS_EXCLUDED(netdev_mutex)
181 {
182     netdev_initialize();
183
184     struct netdev_registered_class *rc;
185     CMAP_FOR_EACH (rc, cmap_node, &netdev_classes) {
186         if (rc->class->wait) {
187             rc->class->wait();
188         }
189     }
190 }
191
192 static struct netdev_registered_class *
193 netdev_lookup_class(const char *type)
194 {
195     struct netdev_registered_class *rc;
196     CMAP_FOR_EACH_WITH_HASH (rc, cmap_node, hash_string(type, 0),
197                              &netdev_classes) {
198         if (!strcmp(type, rc->class->type)) {
199             return rc;
200         }
201     }
202     return NULL;
203 }
204
205 /* Initializes and registers a new netdev provider.  After successful
206  * registration, new netdevs of that type can be opened using netdev_open(). */
207 int
208 netdev_register_provider(const struct netdev_class *new_class)
209     OVS_EXCLUDED(netdev_class_mutex, netdev_mutex)
210 {
211     int error;
212
213     ovs_mutex_lock(&netdev_class_mutex);
214     if (netdev_lookup_class(new_class->type)) {
215         VLOG_WARN("attempted to register duplicate netdev provider: %s",
216                    new_class->type);
217         error = EEXIST;
218     } else {
219         error = new_class->init ? new_class->init() : 0;
220         if (!error) {
221             struct netdev_registered_class *rc;
222
223             rc = xmalloc(sizeof *rc);
224             cmap_insert(&netdev_classes, &rc->cmap_node,
225                         hash_string(new_class->type, 0));
226             rc->class = new_class;
227             ovs_refcount_init(&rc->refcnt);
228         } else {
229             VLOG_ERR("failed to initialize %s network device class: %s",
230                      new_class->type, ovs_strerror(error));
231         }
232     }
233     ovs_mutex_unlock(&netdev_class_mutex);
234
235     return error;
236 }
237
238 /* Unregisters a netdev provider.  'type' must have been previously registered
239  * and not currently be in use by any netdevs.  After unregistration new
240  * netdevs of that type cannot be opened using netdev_open().  (However, the
241  * provider may still be accessible from other threads until the next RCU grace
242  * period, so the caller must not free or re-register the same netdev_class
243  * until that has passed.) */
244 int
245 netdev_unregister_provider(const char *type)
246     OVS_EXCLUDED(netdev_class_mutex, netdev_mutex)
247 {
248     struct netdev_registered_class *rc;
249     int error;
250
251     netdev_initialize();
252
253     ovs_mutex_lock(&netdev_class_mutex);
254     rc = netdev_lookup_class(type);
255     if (!rc) {
256         VLOG_WARN("attempted to unregister a netdev provider that is not "
257                   "registered: %s", type);
258         error = EAFNOSUPPORT;
259     } else if (ovs_refcount_unref(&rc->refcnt) != 1) {
260         ovs_refcount_ref(&rc->refcnt);
261         VLOG_WARN("attempted to unregister in use netdev provider: %s",
262                   type);
263         error = EBUSY;
264     } else  {
265         cmap_remove(&netdev_classes, &rc->cmap_node,
266                     hash_string(rc->class->type, 0));
267         ovsrcu_postpone(free, rc);
268         error = 0;
269     }
270     ovs_mutex_unlock(&netdev_class_mutex);
271
272     return error;
273 }
274
275 /* Clears 'types' and enumerates the types of all currently registered netdev
276  * providers into it.  The caller must first initialize the sset. */
277 void
278 netdev_enumerate_types(struct sset *types)
279     OVS_EXCLUDED(netdev_mutex)
280 {
281     netdev_initialize();
282     sset_clear(types);
283
284     struct netdev_registered_class *rc;
285     CMAP_FOR_EACH (rc, cmap_node, &netdev_classes) {
286         sset_add(types, rc->class->type);
287     }
288 }
289
290 /* Check that the network device name is not the same as any of the registered
291  * vport providers' dpif_port name (dpif_port is NULL if the vport provider
292  * does not define it) or the datapath internal port name (e.g. ovs-system).
293  *
294  * Returns true if there is a name conflict, false otherwise. */
295 bool
296 netdev_is_reserved_name(const char *name)
297     OVS_EXCLUDED(netdev_mutex)
298 {
299     netdev_initialize();
300
301     struct netdev_registered_class *rc;
302     CMAP_FOR_EACH (rc, cmap_node, &netdev_classes) {
303         const char *dpif_port = netdev_vport_class_get_dpif_port(rc->class);
304         if (dpif_port && !strncmp(name, dpif_port, strlen(dpif_port))) {
305             return true;
306         }
307     }
308
309     if (!strncmp(name, "ovs-", 4)) {
310         struct sset types;
311         const char *type;
312
313         sset_init(&types);
314         dp_enumerate_types(&types);
315         SSET_FOR_EACH (type, &types) {
316             if (!strcmp(name+4, type)) {
317                 sset_destroy(&types);
318                 return true;
319             }
320         }
321         sset_destroy(&types);
322     }
323
324     return false;
325 }
326
327 /* Opens the network device named 'name' (e.g. "eth0") of the specified 'type'
328  * (e.g. "system") and returns zero if successful, otherwise a positive errno
329  * value.  On success, sets '*netdevp' to the new network device, otherwise to
330  * null.
331  *
332  * Some network devices may need to be configured (with netdev_set_config())
333  * before they can be used. */
334 int
335 netdev_open(const char *name, const char *type, struct netdev **netdevp)
336     OVS_EXCLUDED(netdev_mutex)
337 {
338     struct netdev *netdev;
339     int error;
340
341     netdev_initialize();
342
343     ovs_mutex_lock(&netdev_mutex);
344     netdev = shash_find_data(&netdev_shash, name);
345     if (!netdev) {
346         struct netdev_registered_class *rc;
347
348         rc = netdev_lookup_class(type && type[0] ? type : "system");
349         if (rc && ovs_refcount_try_ref_rcu(&rc->refcnt)) {
350             netdev = rc->class->alloc();
351             if (netdev) {
352                 memset(netdev, 0, sizeof *netdev);
353                 netdev->netdev_class = rc->class;
354                 netdev->name = xstrdup(name);
355                 netdev->change_seq = 1;
356                 netdev->node = shash_add(&netdev_shash, name, netdev);
357
358                 /* By default enable one tx and rx queue per netdev. */
359                 netdev->n_txq = netdev->netdev_class->send ? 1 : 0;
360                 netdev->n_rxq = netdev->netdev_class->rxq_alloc ? 1 : 0;
361                 netdev->requested_n_rxq = netdev->n_rxq;
362
363                 ovs_list_init(&netdev->saved_flags_list);
364
365                 error = rc->class->construct(netdev);
366                 if (!error) {
367                     netdev_change_seq_changed(netdev);
368                 } else {
369                     ovs_refcount_unref(&rc->refcnt);
370                     free(netdev->name);
371                     ovs_assert(ovs_list_is_empty(&netdev->saved_flags_list));
372                     shash_delete(&netdev_shash, netdev->node);
373                     rc->class->dealloc(netdev);
374                 }
375             } else {
376                 error = ENOMEM;
377             }
378         } else {
379             VLOG_WARN("could not create netdev %s of unknown type %s",
380                       name, type);
381             error = EAFNOSUPPORT;
382         }
383     } else {
384         error = 0;
385     }
386
387     if (!error) {
388         netdev->ref_cnt++;
389         *netdevp = netdev;
390     } else {
391         *netdevp = NULL;
392     }
393     ovs_mutex_unlock(&netdev_mutex);
394
395     return error;
396 }
397
398 /* Returns a reference to 'netdev_' for the caller to own. Returns null if
399  * 'netdev_' is null. */
400 struct netdev *
401 netdev_ref(const struct netdev *netdev_)
402     OVS_EXCLUDED(netdev_mutex)
403 {
404     struct netdev *netdev = CONST_CAST(struct netdev *, netdev_);
405
406     if (netdev) {
407         ovs_mutex_lock(&netdev_mutex);
408         ovs_assert(netdev->ref_cnt > 0);
409         netdev->ref_cnt++;
410         ovs_mutex_unlock(&netdev_mutex);
411     }
412     return netdev;
413 }
414
415 /* Reconfigures the device 'netdev' with 'args'.  'args' may be empty
416  * or NULL if none are needed. */
417 int
418 netdev_set_config(struct netdev *netdev, const struct smap *args, char **errp)
419     OVS_EXCLUDED(netdev_mutex)
420 {
421     if (netdev->netdev_class->set_config) {
422         const struct smap no_args = SMAP_INITIALIZER(&no_args);
423         int error;
424
425         error = netdev->netdev_class->set_config(netdev,
426                                                  args ? args : &no_args);
427         if (error) {
428             VLOG_WARN_BUF(errp, "%s: could not set configuration (%s)",
429                           netdev_get_name(netdev), ovs_strerror(error));
430         }
431         return error;
432     } else if (args && !smap_is_empty(args)) {
433         VLOG_WARN_BUF(errp, "%s: arguments provided to device that is not configurable",
434                       netdev_get_name(netdev));
435     }
436     return 0;
437 }
438
439 /* Returns the current configuration for 'netdev' in 'args'.  The caller must
440  * have already initialized 'args' with smap_init().  Returns 0 on success, in
441  * which case 'args' will be filled with 'netdev''s configuration.  On failure
442  * returns a positive errno value, in which case 'args' will be empty.
443  *
444  * The caller owns 'args' and its contents and must eventually free them with
445  * smap_destroy(). */
446 int
447 netdev_get_config(const struct netdev *netdev, struct smap *args)
448     OVS_EXCLUDED(netdev_mutex)
449 {
450     int error;
451
452     smap_clear(args);
453     if (netdev->netdev_class->get_config) {
454         error = netdev->netdev_class->get_config(netdev, args);
455         if (error) {
456             smap_clear(args);
457         }
458     } else {
459         error = 0;
460     }
461
462     return error;
463 }
464
465 const struct netdev_tunnel_config *
466 netdev_get_tunnel_config(const struct netdev *netdev)
467     OVS_EXCLUDED(netdev_mutex)
468 {
469     if (netdev->netdev_class->get_tunnel_config) {
470         return netdev->netdev_class->get_tunnel_config(netdev);
471     } else {
472         return NULL;
473     }
474 }
475
476 /* Returns the id of the numa node the 'netdev' is on.  If the function
477  * is not implemented, returns NETDEV_NUMA_UNSPEC. */
478 int
479 netdev_get_numa_id(const struct netdev *netdev)
480 {
481     if (netdev->netdev_class->get_numa_id) {
482         return netdev->netdev_class->get_numa_id(netdev);
483     } else {
484         return NETDEV_NUMA_UNSPEC;
485     }
486 }
487
488 static void
489 netdev_unref(struct netdev *dev)
490     OVS_RELEASES(netdev_mutex)
491 {
492     ovs_assert(dev->ref_cnt);
493     if (!--dev->ref_cnt) {
494         const struct netdev_class *class = dev->netdev_class;
495         struct netdev_registered_class *rc;
496
497         dev->netdev_class->destruct(dev);
498
499         if (dev->node) {
500             shash_delete(&netdev_shash, dev->node);
501         }
502         free(dev->name);
503         dev->netdev_class->dealloc(dev);
504         ovs_mutex_unlock(&netdev_mutex);
505
506         rc = netdev_lookup_class(class->type);
507         ovs_refcount_unref(&rc->refcnt);
508     } else {
509         ovs_mutex_unlock(&netdev_mutex);
510     }
511 }
512
513 /* Closes and destroys 'netdev'. */
514 void
515 netdev_close(struct netdev *netdev)
516     OVS_EXCLUDED(netdev_mutex)
517 {
518     if (netdev) {
519         ovs_mutex_lock(&netdev_mutex);
520         netdev_unref(netdev);
521     }
522 }
523
524 /* Removes 'netdev' from the global shash and unrefs 'netdev'.
525  *
526  * This allows handler and revalidator threads to still retain references
527  * to this netdev while the main thread changes interface configuration.
528  *
529  * This function should only be called by the main thread when closing
530  * netdevs during user configuration changes. Otherwise, netdev_close should be
531  * used to close netdevs. */
532 void
533 netdev_remove(struct netdev *netdev)
534 {
535     if (netdev) {
536         ovs_mutex_lock(&netdev_mutex);
537         if (netdev->node) {
538             shash_delete(&netdev_shash, netdev->node);
539             netdev->node = NULL;
540             netdev_change_seq_changed(netdev);
541         }
542         netdev_unref(netdev);
543     }
544 }
545
546 /* Parses 'netdev_name_', which is of the form [type@]name into its component
547  * pieces.  'name' and 'type' must be freed by the caller. */
548 void
549 netdev_parse_name(const char *netdev_name_, char **name, char **type)
550 {
551     char *netdev_name = xstrdup(netdev_name_);
552     char *separator;
553
554     separator = strchr(netdev_name, '@');
555     if (separator) {
556         *separator = '\0';
557         *type = netdev_name;
558         *name = xstrdup(separator + 1);
559     } else {
560         *name = netdev_name;
561         *type = xstrdup("system");
562     }
563 }
564
565 /* Attempts to open a netdev_rxq handle for obtaining packets received on
566  * 'netdev'.  On success, returns 0 and stores a nonnull 'netdev_rxq *' into
567  * '*rxp'.  On failure, returns a positive errno value and stores NULL into
568  * '*rxp'.
569  *
570  * Some kinds of network devices might not support receiving packets.  This
571  * function returns EOPNOTSUPP in that case.*/
572 int
573 netdev_rxq_open(struct netdev *netdev, struct netdev_rxq **rxp, int id)
574     OVS_EXCLUDED(netdev_mutex)
575 {
576     int error;
577
578     if (netdev->netdev_class->rxq_alloc && id < netdev->n_rxq) {
579         struct netdev_rxq *rx = netdev->netdev_class->rxq_alloc();
580         if (rx) {
581             rx->netdev = netdev;
582             rx->queue_id = id;
583             error = netdev->netdev_class->rxq_construct(rx);
584             if (!error) {
585                 netdev_ref(netdev);
586                 *rxp = rx;
587                 return 0;
588             }
589             netdev->netdev_class->rxq_dealloc(rx);
590         } else {
591             error = ENOMEM;
592         }
593     } else {
594         error = EOPNOTSUPP;
595     }
596
597     *rxp = NULL;
598     return error;
599 }
600
601 /* Closes 'rx'. */
602 void
603 netdev_rxq_close(struct netdev_rxq *rx)
604     OVS_EXCLUDED(netdev_mutex)
605 {
606     if (rx) {
607         struct netdev *netdev = rx->netdev;
608         netdev->netdev_class->rxq_destruct(rx);
609         netdev->netdev_class->rxq_dealloc(rx);
610         netdev_close(netdev);
611     }
612 }
613
614 /* Attempts to receive a batch of packets from 'rx'.  'pkts' should point to
615  * the beginning of an array of MAX_RX_BATCH pointers to dp_packet.  If
616  * successful, this function stores pointers to up to MAX_RX_BATCH dp_packets
617  * into the array, transferring ownership of the packets to the caller, stores
618  * the number of received packets into '*cnt', and returns 0.
619  *
620  * The implementation does not necessarily initialize any non-data members of
621  * 'pkts'.  That is, the caller must initialize layer pointers and metadata
622  * itself, if desired, e.g. with pkt_metadata_init() and miniflow_extract().
623  *
624  * Returns EAGAIN immediately if no packet is ready to be received or another
625  * positive errno value if an error was encountered. */
626 int
627 netdev_rxq_recv(struct netdev_rxq *rx, struct dp_packet_batch *batch)
628 {
629     int retval;
630
631     retval = rx->netdev->netdev_class->rxq_recv(rx, batch->packets, &batch->count);
632     if (!retval) {
633         COVERAGE_INC(netdev_received);
634     } else {
635         batch->count = 0;
636     }
637     return retval;
638 }
639
640 /* Arranges for poll_block() to wake up when a packet is ready to be received
641  * on 'rx'. */
642 void
643 netdev_rxq_wait(struct netdev_rxq *rx)
644 {
645     rx->netdev->netdev_class->rxq_wait(rx);
646 }
647
648 /* Discards any packets ready to be received on 'rx'. */
649 int
650 netdev_rxq_drain(struct netdev_rxq *rx)
651 {
652     return (rx->netdev->netdev_class->rxq_drain
653             ? rx->netdev->netdev_class->rxq_drain(rx)
654             : 0);
655 }
656
657 /* Configures the number of tx queues and rx queues of 'netdev'.
658  * Return 0 if successful, otherwise a positive errno value.
659  *
660  * 'n_rxq' specifies the maximum number of receive queues to create.
661  * The netdev provider might choose to create less (e.g. if the hardware
662  * supports only a smaller number).  The caller can check how many have been
663  * actually created by calling 'netdev_n_rxq()'
664  *
665  * 'n_txq' specifies the exact number of transmission queues to create.
666  * If this function returns successfully, the caller can make 'n_txq'
667  * concurrent calls to netdev_send() (each one with a different 'qid' in the
668  * range [0..'n_txq'-1]).
669  *
670  * On error, the tx queue and rx queue configuration is indeterminant.
671  * Caller should make decision on whether to restore the previous or
672  * the default configuration.  Also, caller must make sure there is no
673  * other thread accessing the queues at the same time. */
674 int
675 netdev_set_multiq(struct netdev *netdev, unsigned int n_txq,
676                   unsigned int n_rxq)
677 {
678     int error;
679
680     error = (netdev->netdev_class->set_multiq
681              ? netdev->netdev_class->set_multiq(netdev,
682                                                 MAX(n_txq, 1),
683                                                 MAX(n_rxq, 1))
684              : EOPNOTSUPP);
685
686     if (error && error != EOPNOTSUPP) {
687         VLOG_DBG_RL(&rl, "failed to set tx/rx queue for network device %s:"
688                     "%s", netdev_get_name(netdev), ovs_strerror(error));
689     }
690
691     return error;
692 }
693
694 /* Sends 'buffers' on 'netdev'.  Returns 0 if successful (for every packet),
695  * otherwise a positive errno value.  Returns EAGAIN without blocking if
696  * at least one the packets cannot be queued immediately.  Returns EMSGSIZE
697  * if a partial packet was transmitted or if a packet is too big or too small
698  * to transmit on the device.
699  *
700  * If the function returns a non-zero value, some of the packets might have
701  * been sent anyway.
702  *
703  * If 'may_steal' is false, the caller retains ownership of all the packets.
704  * If 'may_steal' is true, the caller transfers ownership of all the packets
705  * to the network device, regardless of success.
706  *
707  * The network device is expected to maintain one or more packet
708  * transmission queues, so that the caller does not ordinarily have to
709  * do additional queuing of packets.  'qid' specifies the queue to use
710  * and can be ignored if the implementation does not support multiple
711  * queues.
712  *
713  * Some network devices may not implement support for this function.  In such
714  * cases this function will always return EOPNOTSUPP. */
715 int
716 netdev_send(struct netdev *netdev, int qid, struct dp_packet_batch *batch,
717             bool may_steal)
718 {
719     if (!netdev->netdev_class->send) {
720         dp_packet_delete_batch(batch, may_steal);
721         return EOPNOTSUPP;
722     }
723
724     int error = netdev->netdev_class->send(netdev, qid,
725                                            batch->packets, batch->count,
726                                            may_steal);
727     if (!error) {
728         COVERAGE_INC(netdev_sent);
729     }
730     return error;
731 }
732
733 void
734 netdev_pop_header(struct netdev *netdev, struct dp_packet_batch *batch)
735 {
736     int i, n_cnt = 0;
737     struct dp_packet **buffers = batch->packets;
738
739     if (!netdev->netdev_class->pop_header) {
740         dp_packet_delete_batch(batch, true);
741         batch->count = 0;
742         return;
743     }
744
745     for (i = 0; i < batch->count; i++) {
746         buffers[i] = netdev->netdev_class->pop_header(buffers[i]);
747         if (buffers[i]) {
748             buffers[n_cnt++] = buffers[i];
749         }
750     }
751     batch->count = n_cnt;
752 }
753
754 int
755 netdev_build_header(const struct netdev *netdev, struct ovs_action_push_tnl *data,
756                     const struct flow *tnl_flow)
757 {
758     if (netdev->netdev_class->build_header) {
759         return netdev->netdev_class->build_header(netdev, data, tnl_flow);
760     }
761     return EOPNOTSUPP;
762 }
763
764 int
765 netdev_push_header(const struct netdev *netdev,
766                    struct dp_packet_batch *batch,
767                    const struct ovs_action_push_tnl *data)
768 {
769     int i;
770
771     if (!netdev->netdev_class->push_header) {
772         return -EINVAL;
773     }
774
775     for (i = 0; i < batch->count; i++) {
776         netdev->netdev_class->push_header(batch->packets[i], data);
777         pkt_metadata_init(&batch->packets[i]->md, u32_to_odp(data->out_port));
778     }
779
780     return 0;
781 }
782
783 /* Registers with the poll loop to wake up from the next call to poll_block()
784  * when the packet transmission queue has sufficient room to transmit a packet
785  * with netdev_send().
786  *
787  * The network device is expected to maintain one or more packet
788  * transmission queues, so that the caller does not ordinarily have to
789  * do additional queuing of packets.  'qid' specifies the queue to use
790  * and can be ignored if the implementation does not support multiple
791  * queues. */
792 void
793 netdev_send_wait(struct netdev *netdev, int qid)
794 {
795     if (netdev->netdev_class->send_wait) {
796         netdev->netdev_class->send_wait(netdev, qid);
797     }
798 }
799
800 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
801  * otherwise a positive errno value. */
802 int
803 netdev_set_etheraddr(struct netdev *netdev, const struct eth_addr mac)
804 {
805     return netdev->netdev_class->set_etheraddr(netdev, mac);
806 }
807
808 /* Retrieves 'netdev''s MAC address.  If successful, returns 0 and copies the
809  * the MAC address into 'mac'.  On failure, returns a positive errno value and
810  * clears 'mac' to all-zeros. */
811 int
812 netdev_get_etheraddr(const struct netdev *netdev, struct eth_addr *mac)
813 {
814     return netdev->netdev_class->get_etheraddr(netdev, mac);
815 }
816
817 /* Returns the name of the network device that 'netdev' represents,
818  * e.g. "eth0".  The caller must not modify or free the returned string. */
819 const char *
820 netdev_get_name(const struct netdev *netdev)
821 {
822     return netdev->name;
823 }
824
825 /* Retrieves the MTU of 'netdev'.  The MTU is the maximum size of transmitted
826  * (and received) packets, in bytes, not including the hardware header; thus,
827  * this is typically 1500 bytes for Ethernet devices.
828  *
829  * If successful, returns 0 and stores the MTU size in '*mtup'.  Returns
830  * EOPNOTSUPP if 'netdev' does not have an MTU (as e.g. some tunnels do not).
831  * On other failure, returns a positive errno value.  On failure, sets '*mtup'
832  * to 0. */
833 int
834 netdev_get_mtu(const struct netdev *netdev, int *mtup)
835 {
836     const struct netdev_class *class = netdev->netdev_class;
837     int error;
838
839     error = class->get_mtu ? class->get_mtu(netdev, mtup) : EOPNOTSUPP;
840     if (error) {
841         *mtup = 0;
842         if (error != EOPNOTSUPP) {
843             VLOG_DBG_RL(&rl, "failed to retrieve MTU for network device %s: "
844                          "%s", netdev_get_name(netdev), ovs_strerror(error));
845         }
846     }
847     return error;
848 }
849
850 /* Sets the MTU of 'netdev'.  The MTU is the maximum size of transmitted
851  * (and received) packets, in bytes.
852  *
853  * If successful, returns 0.  Returns EOPNOTSUPP if 'netdev' does not have an
854  * MTU (as e.g. some tunnels do not).  On other failure, returns a positive
855  * errno value. */
856 int
857 netdev_set_mtu(const struct netdev *netdev, int mtu)
858 {
859     const struct netdev_class *class = netdev->netdev_class;
860     int error;
861
862     error = class->set_mtu ? class->set_mtu(netdev, mtu) : EOPNOTSUPP;
863     if (error && error != EOPNOTSUPP) {
864         VLOG_DBG_RL(&rl, "failed to set MTU for network device %s: %s",
865                      netdev_get_name(netdev), ovs_strerror(error));
866     }
867
868     return error;
869 }
870
871 /* Returns the ifindex of 'netdev', if successful, as a positive number.  On
872  * failure, returns a negative errno value.
873  *
874  * The desired semantics of the ifindex value are a combination of those
875  * specified by POSIX for if_nametoindex() and by SNMP for ifIndex.  An ifindex
876  * value should be unique within a host and remain stable at least until
877  * reboot.  SNMP says an ifindex "ranges between 1 and the value of ifNumber"
878  * but many systems do not follow this rule anyhow.
879  *
880  * Some network devices may not implement support for this function.  In such
881  * cases this function will always return -EOPNOTSUPP.
882  */
883 int
884 netdev_get_ifindex(const struct netdev *netdev)
885 {
886     int (*get_ifindex)(const struct netdev *);
887
888     get_ifindex = netdev->netdev_class->get_ifindex;
889
890     return get_ifindex ? get_ifindex(netdev) : -EOPNOTSUPP;
891 }
892
893 /* Stores the features supported by 'netdev' into each of '*current',
894  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
895  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
896  * successful, otherwise a positive errno value.  On failure, all of the
897  * passed-in values are set to 0.
898  *
899  * Some network devices may not implement support for this function.  In such
900  * cases this function will always return EOPNOTSUPP. */
901 int
902 netdev_get_features(const struct netdev *netdev,
903                     enum netdev_features *current,
904                     enum netdev_features *advertised,
905                     enum netdev_features *supported,
906                     enum netdev_features *peer)
907 {
908     int (*get_features)(const struct netdev *netdev,
909                         enum netdev_features *current,
910                         enum netdev_features *advertised,
911                         enum netdev_features *supported,
912                         enum netdev_features *peer);
913     enum netdev_features dummy[4];
914     int error;
915
916     if (!current) {
917         current = &dummy[0];
918     }
919     if (!advertised) {
920         advertised = &dummy[1];
921     }
922     if (!supported) {
923         supported = &dummy[2];
924     }
925     if (!peer) {
926         peer = &dummy[3];
927     }
928
929     get_features = netdev->netdev_class->get_features;
930     error = get_features
931                     ? get_features(netdev, current, advertised, supported,
932                                    peer)
933                     : EOPNOTSUPP;
934     if (error) {
935         *current = *advertised = *supported = *peer = 0;
936     }
937     return error;
938 }
939
940 /* Returns the maximum speed of a network connection that has the NETDEV_F_*
941  * bits in 'features', in bits per second.  If no bits that indicate a speed
942  * are set in 'features', returns 'default_bps'. */
943 uint64_t
944 netdev_features_to_bps(enum netdev_features features,
945                        uint64_t default_bps)
946 {
947     enum {
948         F_1000000MB = NETDEV_F_1TB_FD,
949         F_100000MB = NETDEV_F_100GB_FD,
950         F_40000MB = NETDEV_F_40GB_FD,
951         F_10000MB = NETDEV_F_10GB_FD,
952         F_1000MB = NETDEV_F_1GB_HD | NETDEV_F_1GB_FD,
953         F_100MB = NETDEV_F_100MB_HD | NETDEV_F_100MB_FD,
954         F_10MB = NETDEV_F_10MB_HD | NETDEV_F_10MB_FD
955     };
956
957     return (  features & F_1000000MB ? UINT64_C(1000000000000)
958             : features & F_100000MB  ? UINT64_C(100000000000)
959             : features & F_40000MB   ? UINT64_C(40000000000)
960             : features & F_10000MB   ? UINT64_C(10000000000)
961             : features & F_1000MB    ? UINT64_C(1000000000)
962             : features & F_100MB     ? UINT64_C(100000000)
963             : features & F_10MB      ? UINT64_C(10000000)
964                                      : default_bps);
965 }
966
967 /* Returns true if any of the NETDEV_F_* bits that indicate a full-duplex link
968  * are set in 'features', otherwise false. */
969 bool
970 netdev_features_is_full_duplex(enum netdev_features features)
971 {
972     return (features & (NETDEV_F_10MB_FD | NETDEV_F_100MB_FD | NETDEV_F_1GB_FD
973                         | NETDEV_F_10GB_FD | NETDEV_F_40GB_FD
974                         | NETDEV_F_100GB_FD | NETDEV_F_1TB_FD)) != 0;
975 }
976
977 /* Set the features advertised by 'netdev' to 'advertise'.  Returns 0 if
978  * successful, otherwise a positive errno value. */
979 int
980 netdev_set_advertisements(struct netdev *netdev,
981                           enum netdev_features advertise)
982 {
983     return (netdev->netdev_class->set_advertisements
984             ? netdev->netdev_class->set_advertisements(
985                     netdev, advertise)
986             : EOPNOTSUPP);
987 }
988
989 /* Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
990  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
991  * positive errno value. */
992 int
993 netdev_set_in4(struct netdev *netdev, struct in_addr addr, struct in_addr mask)
994 {
995     return (netdev->netdev_class->set_in4
996             ? netdev->netdev_class->set_in4(netdev, addr, mask)
997             : EOPNOTSUPP);
998 }
999
1000 /* Obtains ad IPv4 address from device name and save the address in
1001  * in4.  Returns 0 if successful, otherwise a positive errno value.
1002  */
1003 int
1004 netdev_get_in4_by_name(const char *device_name, struct in_addr *in4)
1005 {
1006     struct in6_addr *mask, *addr6;
1007     int err, n_in6, i;
1008     struct netdev *dev;
1009
1010     err = netdev_open(device_name, NULL, &dev);
1011     if (err) {
1012         return err;
1013     }
1014
1015     err = netdev_get_addr_list(dev, &addr6, &mask, &n_in6);
1016     if (err) {
1017         goto out;
1018     }
1019
1020     for (i = 0; i < n_in6; i++) {
1021         if (IN6_IS_ADDR_V4MAPPED(&addr6[i])) {
1022             in4->s_addr = in6_addr_get_mapped_ipv4(&addr6[i]);
1023             goto out;
1024         }
1025     }
1026     err = -ENOENT;
1027 out:
1028     free(addr6);
1029     free(mask);
1030     netdev_close(dev);
1031     return err;
1032
1033 }
1034
1035 /* Adds 'router' as a default IP gateway for the TCP/IP stack that corresponds
1036  * to 'netdev'. */
1037 int
1038 netdev_add_router(struct netdev *netdev, struct in_addr router)
1039 {
1040     COVERAGE_INC(netdev_add_router);
1041     return (netdev->netdev_class->add_router
1042             ? netdev->netdev_class->add_router(netdev, router)
1043             : EOPNOTSUPP);
1044 }
1045
1046 /* Looks up the next hop for 'host' for the TCP/IP stack that corresponds to
1047  * 'netdev'.  If a route cannot not be determined, sets '*next_hop' to 0,
1048  * '*netdev_name' to null, and returns a positive errno value.  Otherwise, if a
1049  * next hop is found, stores the next hop gateway's address (0 if 'host' is on
1050  * a directly connected network) in '*next_hop' and a copy of the name of the
1051  * device to reach 'host' in '*netdev_name', and returns 0.  The caller is
1052  * responsible for freeing '*netdev_name' (by calling free()). */
1053 int
1054 netdev_get_next_hop(const struct netdev *netdev,
1055                     const struct in_addr *host, struct in_addr *next_hop,
1056                     char **netdev_name)
1057 {
1058     int error = (netdev->netdev_class->get_next_hop
1059                  ? netdev->netdev_class->get_next_hop(
1060                         host, next_hop, netdev_name)
1061                  : EOPNOTSUPP);
1062     if (error) {
1063         next_hop->s_addr = 0;
1064         *netdev_name = NULL;
1065     }
1066     return error;
1067 }
1068
1069 /* Populates 'smap' with status information.
1070  *
1071  * Populates 'smap' with 'netdev' specific status information.  This
1072  * information may be used to populate the status column of the Interface table
1073  * as defined in ovs-vswitchd.conf.db(5). */
1074 int
1075 netdev_get_status(const struct netdev *netdev, struct smap *smap)
1076 {
1077     return (netdev->netdev_class->get_status
1078             ? netdev->netdev_class->get_status(netdev, smap)
1079             : EOPNOTSUPP);
1080 }
1081
1082 /* Returns all assigned IP address to  'netdev' and returns 0.
1083  * API allocates array of address and masks and set it to
1084  * '*addr' and '*mask'.
1085  * Otherwise, returns a positive errno value and sets '*addr', '*mask
1086  * and '*n_addr' to NULL.
1087  *
1088  * The following error values have well-defined meanings:
1089  *
1090  *   - EADDRNOTAVAIL: 'netdev' has no assigned IPv6 address.
1091  *
1092  *   - EOPNOTSUPP: No IPv6 network stack attached to 'netdev'.
1093  *
1094  * 'addr' may be null, in which case the address itself is not reported. */
1095 int
1096 netdev_get_addr_list(const struct netdev *netdev, struct in6_addr **addr,
1097                      struct in6_addr **mask, int *n_addr)
1098 {
1099     int error;
1100
1101     error = (netdev->netdev_class->get_addr_list
1102              ? netdev->netdev_class->get_addr_list(netdev, addr, mask, n_addr): EOPNOTSUPP);
1103     if (error && addr) {
1104         *addr = NULL;
1105         *mask = NULL;
1106         *n_addr = 0;
1107     }
1108
1109     return error;
1110 }
1111
1112 /* On 'netdev', turns off the flags in 'off' and then turns on the flags in
1113  * 'on'.  Returns 0 if successful, otherwise a positive errno value. */
1114 static int
1115 do_update_flags(struct netdev *netdev, enum netdev_flags off,
1116                 enum netdev_flags on, enum netdev_flags *old_flagsp,
1117                 struct netdev_saved_flags **sfp)
1118     OVS_EXCLUDED(netdev_mutex)
1119 {
1120     struct netdev_saved_flags *sf = NULL;
1121     enum netdev_flags old_flags;
1122     int error;
1123
1124     error = netdev->netdev_class->update_flags(netdev, off & ~on, on,
1125                                                &old_flags);
1126     if (error) {
1127         VLOG_WARN_RL(&rl, "failed to %s flags for network device %s: %s",
1128                      off || on ? "set" : "get", netdev_get_name(netdev),
1129                      ovs_strerror(error));
1130         old_flags = 0;
1131     } else if ((off || on) && sfp) {
1132         enum netdev_flags new_flags = (old_flags & ~off) | on;
1133         enum netdev_flags changed_flags = old_flags ^ new_flags;
1134         if (changed_flags) {
1135             ovs_mutex_lock(&netdev_mutex);
1136             *sfp = sf = xmalloc(sizeof *sf);
1137             sf->netdev = netdev;
1138             ovs_list_push_front(&netdev->saved_flags_list, &sf->node);
1139             sf->saved_flags = changed_flags;
1140             sf->saved_values = changed_flags & new_flags;
1141
1142             netdev->ref_cnt++;
1143             ovs_mutex_unlock(&netdev_mutex);
1144         }
1145     }
1146
1147     if (old_flagsp) {
1148         *old_flagsp = old_flags;
1149     }
1150     if (sfp) {
1151         *sfp = sf;
1152     }
1153
1154     return error;
1155 }
1156
1157 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
1158  * Returns 0 if successful, otherwise a positive errno value.  On failure,
1159  * stores 0 into '*flagsp'. */
1160 int
1161 netdev_get_flags(const struct netdev *netdev_, enum netdev_flags *flagsp)
1162 {
1163     struct netdev *netdev = CONST_CAST(struct netdev *, netdev_);
1164     return do_update_flags(netdev, 0, 0, flagsp, NULL);
1165 }
1166
1167 /* Sets the flags for 'netdev' to 'flags'.
1168  * Returns 0 if successful, otherwise a positive errno value. */
1169 int
1170 netdev_set_flags(struct netdev *netdev, enum netdev_flags flags,
1171                  struct netdev_saved_flags **sfp)
1172 {
1173     return do_update_flags(netdev, -1, flags, NULL, sfp);
1174 }
1175
1176 /* Turns on the specified 'flags' on 'netdev':
1177  *
1178  *    - On success, returns 0.  If 'sfp' is nonnull, sets '*sfp' to a newly
1179  *      allocated 'struct netdev_saved_flags *' that may be passed to
1180  *      netdev_restore_flags() to restore the original values of 'flags' on
1181  *      'netdev' (this will happen automatically at program termination if
1182  *      netdev_restore_flags() is never called) , or to NULL if no flags were
1183  *      actually changed.
1184  *
1185  *    - On failure, returns a positive errno value.  If 'sfp' is nonnull, sets
1186  *      '*sfp' to NULL. */
1187 int
1188 netdev_turn_flags_on(struct netdev *netdev, enum netdev_flags flags,
1189                      struct netdev_saved_flags **sfp)
1190 {
1191     return do_update_flags(netdev, 0, flags, NULL, sfp);
1192 }
1193
1194 /* Turns off the specified 'flags' on 'netdev'.  See netdev_turn_flags_on() for
1195  * details of the interface. */
1196 int
1197 netdev_turn_flags_off(struct netdev *netdev, enum netdev_flags flags,
1198                       struct netdev_saved_flags **sfp)
1199 {
1200     return do_update_flags(netdev, flags, 0, NULL, sfp);
1201 }
1202
1203 /* Restores the flags that were saved in 'sf', and destroys 'sf'.
1204  * Does nothing if 'sf' is NULL. */
1205 void
1206 netdev_restore_flags(struct netdev_saved_flags *sf)
1207     OVS_EXCLUDED(netdev_mutex)
1208 {
1209     if (sf) {
1210         struct netdev *netdev = sf->netdev;
1211         enum netdev_flags old_flags;
1212
1213         netdev->netdev_class->update_flags(netdev,
1214                                            sf->saved_flags & sf->saved_values,
1215                                            sf->saved_flags & ~sf->saved_values,
1216                                            &old_flags);
1217
1218         ovs_mutex_lock(&netdev_mutex);
1219         ovs_list_remove(&sf->node);
1220         free(sf);
1221         netdev_unref(netdev);
1222     }
1223 }
1224
1225 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
1226  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
1227  * returns 0.  Otherwise, it returns a positive errno value; in particular,
1228  * ENXIO indicates that there is no ARP table entry for 'ip' on 'netdev'. */
1229 int
1230 netdev_arp_lookup(const struct netdev *netdev,
1231                   ovs_be32 ip, struct eth_addr *mac)
1232 {
1233     int error = (netdev->netdev_class->arp_lookup
1234                  ? netdev->netdev_class->arp_lookup(netdev, ip, mac)
1235                  : EOPNOTSUPP);
1236     if (error) {
1237         *mac = eth_addr_zero;
1238     }
1239     return error;
1240 }
1241
1242 /* Returns true if carrier is active (link light is on) on 'netdev'. */
1243 bool
1244 netdev_get_carrier(const struct netdev *netdev)
1245 {
1246     int error;
1247     enum netdev_flags flags;
1248     bool carrier;
1249
1250     netdev_get_flags(netdev, &flags);
1251     if (!(flags & NETDEV_UP)) {
1252         return false;
1253     }
1254
1255     if (!netdev->netdev_class->get_carrier) {
1256         return true;
1257     }
1258
1259     error = netdev->netdev_class->get_carrier(netdev, &carrier);
1260     if (error) {
1261         VLOG_DBG("%s: failed to get network device carrier status, assuming "
1262                  "down: %s", netdev_get_name(netdev), ovs_strerror(error));
1263         carrier = false;
1264     }
1265
1266     return carrier;
1267 }
1268
1269 /* Returns the number of times 'netdev''s carrier has changed. */
1270 long long int
1271 netdev_get_carrier_resets(const struct netdev *netdev)
1272 {
1273     return (netdev->netdev_class->get_carrier_resets
1274             ? netdev->netdev_class->get_carrier_resets(netdev)
1275             : 0);
1276 }
1277
1278 /* Attempts to force netdev_get_carrier() to poll 'netdev''s MII registers for
1279  * link status instead of checking 'netdev''s carrier.  'netdev''s MII
1280  * registers will be polled once ever 'interval' milliseconds.  If 'netdev'
1281  * does not support MII, another method may be used as a fallback.  If
1282  * 'interval' is less than or equal to zero, reverts netdev_get_carrier() to
1283  * its normal behavior.
1284  *
1285  * Returns 0 if successful, otherwise a positive errno value. */
1286 int
1287 netdev_set_miimon_interval(struct netdev *netdev, long long int interval)
1288 {
1289     return (netdev->netdev_class->set_miimon_interval
1290             ? netdev->netdev_class->set_miimon_interval(netdev, interval)
1291             : EOPNOTSUPP);
1292 }
1293
1294 /* Retrieves current device stats for 'netdev'. */
1295 int
1296 netdev_get_stats(const struct netdev *netdev, struct netdev_stats *stats)
1297 {
1298     int error;
1299
1300     /* Statistics are initialized before passing it to particular device
1301      * implementation so all values are filtered out by default. */
1302     memset(stats, 0xFF, sizeof *stats);
1303
1304     COVERAGE_INC(netdev_get_stats);
1305     error = (netdev->netdev_class->get_stats
1306              ? netdev->netdev_class->get_stats(netdev, stats)
1307              : EOPNOTSUPP);
1308     if (error) {
1309         /* In case of error all statistics are filtered out */
1310         memset(stats, 0xff, sizeof *stats);
1311     }
1312     return error;
1313 }
1314
1315 /* Attempts to set input rate limiting (policing) policy, such that up to
1316  * 'kbits_rate' kbps of traffic is accepted, with a maximum accumulative burst
1317  * size of 'kbits' kb. */
1318 int
1319 netdev_set_policing(struct netdev *netdev, uint32_t kbits_rate,
1320                     uint32_t kbits_burst)
1321 {
1322     return (netdev->netdev_class->set_policing
1323             ? netdev->netdev_class->set_policing(netdev,
1324                     kbits_rate, kbits_burst)
1325             : EOPNOTSUPP);
1326 }
1327
1328 /* Adds to 'types' all of the forms of QoS supported by 'netdev', or leaves it
1329  * empty if 'netdev' does not support QoS.  Any names added to 'types' should
1330  * be documented as valid for the "type" column in the "QoS" table in
1331  * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
1332  *
1333  * Every network device supports disabling QoS with a type of "", but this type
1334  * will not be added to 'types'.
1335  *
1336  * The caller must initialize 'types' (e.g. with sset_init()) before calling
1337  * this function.  The caller is responsible for destroying 'types' (e.g. with
1338  * sset_destroy()) when it is no longer needed.
1339  *
1340  * Returns 0 if successful, otherwise a positive errno value. */
1341 int
1342 netdev_get_qos_types(const struct netdev *netdev, struct sset *types)
1343 {
1344     const struct netdev_class *class = netdev->netdev_class;
1345     return (class->get_qos_types
1346             ? class->get_qos_types(netdev, types)
1347             : 0);
1348 }
1349
1350 /* Queries 'netdev' for its capabilities regarding the specified 'type' of QoS,
1351  * which should be "" or one of the types returned by netdev_get_qos_types()
1352  * for 'netdev'.  Returns 0 if successful, otherwise a positive errno value.
1353  * On success, initializes 'caps' with the QoS capabilities; on failure, clears
1354  * 'caps' to all zeros. */
1355 int
1356 netdev_get_qos_capabilities(const struct netdev *netdev, const char *type,
1357                             struct netdev_qos_capabilities *caps)
1358 {
1359     const struct netdev_class *class = netdev->netdev_class;
1360
1361     if (*type) {
1362         int retval = (class->get_qos_capabilities
1363                       ? class->get_qos_capabilities(netdev, type, caps)
1364                       : EOPNOTSUPP);
1365         if (retval) {
1366             memset(caps, 0, sizeof *caps);
1367         }
1368         return retval;
1369     } else {
1370         /* Every netdev supports turning off QoS. */
1371         memset(caps, 0, sizeof *caps);
1372         return 0;
1373     }
1374 }
1375
1376 /* Obtains the number of queues supported by 'netdev' for the specified 'type'
1377  * of QoS.  Returns 0 if successful, otherwise a positive errno value.  Stores
1378  * the number of queues (zero on failure) in '*n_queuesp'.
1379  *
1380  * This is just a simple wrapper around netdev_get_qos_capabilities(). */
1381 int
1382 netdev_get_n_queues(const struct netdev *netdev,
1383                     const char *type, unsigned int *n_queuesp)
1384 {
1385     struct netdev_qos_capabilities caps;
1386     int retval;
1387
1388     retval = netdev_get_qos_capabilities(netdev, type, &caps);
1389     *n_queuesp = caps.n_queues;
1390     return retval;
1391 }
1392
1393 /* Queries 'netdev' about its currently configured form of QoS.  If successful,
1394  * stores the name of the current form of QoS into '*typep', stores any details
1395  * of configuration as string key-value pairs in 'details', and returns 0.  On
1396  * failure, sets '*typep' to NULL and returns a positive errno value.
1397  *
1398  * A '*typep' of "" indicates that QoS is currently disabled on 'netdev'.
1399  *
1400  * The caller must initialize 'details' as an empty smap (e.g. with
1401  * smap_init()) before calling this function.  The caller must free 'details'
1402  * when it is no longer needed (e.g. with smap_destroy()).
1403  *
1404  * The caller must not modify or free '*typep'.
1405  *
1406  * '*typep' will be one of the types returned by netdev_get_qos_types() for
1407  * 'netdev'.  The contents of 'details' should be documented as valid for
1408  * '*typep' in the "other_config" column in the "QoS" table in
1409  * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)). */
1410 int
1411 netdev_get_qos(const struct netdev *netdev,
1412                const char **typep, struct smap *details)
1413 {
1414     const struct netdev_class *class = netdev->netdev_class;
1415     int retval;
1416
1417     if (class->get_qos) {
1418         retval = class->get_qos(netdev, typep, details);
1419         if (retval) {
1420             *typep = NULL;
1421             smap_clear(details);
1422         }
1423         return retval;
1424     } else {
1425         /* 'netdev' doesn't support QoS, so report that QoS is disabled. */
1426         *typep = "";
1427         return 0;
1428     }
1429 }
1430
1431 /* Attempts to reconfigure QoS on 'netdev', changing the form of QoS to 'type'
1432  * with details of configuration from 'details'.  Returns 0 if successful,
1433  * otherwise a positive errno value.  On error, the previous QoS configuration
1434  * is retained.
1435  *
1436  * When this function changes the type of QoS (not just 'details'), this also
1437  * resets all queue configuration for 'netdev' to their defaults (which depend
1438  * on the specific type of QoS).  Otherwise, the queue configuration for
1439  * 'netdev' is unchanged.
1440  *
1441  * 'type' should be "" (to disable QoS) or one of the types returned by
1442  * netdev_get_qos_types() for 'netdev'.  The contents of 'details' should be
1443  * documented as valid for the given 'type' in the "other_config" column in the
1444  * "QoS" table in vswitchd/vswitch.xml (which is built as
1445  * ovs-vswitchd.conf.db(8)).
1446  *
1447  * NULL may be specified for 'details' if there are no configuration
1448  * details. */
1449 int
1450 netdev_set_qos(struct netdev *netdev,
1451                const char *type, const struct smap *details)
1452 {
1453     const struct netdev_class *class = netdev->netdev_class;
1454
1455     if (!type) {
1456         type = "";
1457     }
1458
1459     if (class->set_qos) {
1460         if (!details) {
1461             static const struct smap empty = SMAP_INITIALIZER(&empty);
1462             details = &empty;
1463         }
1464         return class->set_qos(netdev, type, details);
1465     } else {
1466         return *type ? EOPNOTSUPP : 0;
1467     }
1468 }
1469
1470 /* Queries 'netdev' for information about the queue numbered 'queue_id'.  If
1471  * successful, adds that information as string key-value pairs to 'details'.
1472  * Returns 0 if successful, otherwise a positive errno value.
1473  *
1474  * 'queue_id' must be less than the number of queues supported by 'netdev' for
1475  * the current form of QoS (e.g. as returned by netdev_get_n_queues(netdev)).
1476  *
1477  * The returned contents of 'details' should be documented as valid for the
1478  * given 'type' in the "other_config" column in the "Queue" table in
1479  * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
1480  *
1481  * The caller must initialize 'details' (e.g. with smap_init()) before calling
1482  * this function.  The caller must free 'details' when it is no longer needed
1483  * (e.g. with smap_destroy()). */
1484 int
1485 netdev_get_queue(const struct netdev *netdev,
1486                  unsigned int queue_id, struct smap *details)
1487 {
1488     const struct netdev_class *class = netdev->netdev_class;
1489     int retval;
1490
1491     retval = (class->get_queue
1492               ? class->get_queue(netdev, queue_id, details)
1493               : EOPNOTSUPP);
1494     if (retval) {
1495         smap_clear(details);
1496     }
1497     return retval;
1498 }
1499
1500 /* Configures the queue numbered 'queue_id' on 'netdev' with the key-value
1501  * string pairs in 'details'.  The contents of 'details' should be documented
1502  * as valid for the given 'type' in the "other_config" column in the "Queue"
1503  * table in vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
1504  * Returns 0 if successful, otherwise a positive errno value.  On failure, the
1505  * given queue's configuration should be unmodified.
1506  *
1507  * 'queue_id' must be less than the number of queues supported by 'netdev' for
1508  * the current form of QoS (e.g. as returned by netdev_get_n_queues(netdev)).
1509  *
1510  * This function does not modify 'details', and the caller retains ownership of
1511  * it. */
1512 int
1513 netdev_set_queue(struct netdev *netdev,
1514                  unsigned int queue_id, const struct smap *details)
1515 {
1516     const struct netdev_class *class = netdev->netdev_class;
1517     return (class->set_queue
1518             ? class->set_queue(netdev, queue_id, details)
1519             : EOPNOTSUPP);
1520 }
1521
1522 /* Attempts to delete the queue numbered 'queue_id' from 'netdev'.  Some kinds
1523  * of QoS may have a fixed set of queues, in which case attempts to delete them
1524  * will fail with EOPNOTSUPP.
1525  *
1526  * Returns 0 if successful, otherwise a positive errno value.  On failure, the
1527  * given queue will be unmodified.
1528  *
1529  * 'queue_id' must be less than the number of queues supported by 'netdev' for
1530  * the current form of QoS (e.g. as returned by
1531  * netdev_get_n_queues(netdev)). */
1532 int
1533 netdev_delete_queue(struct netdev *netdev, unsigned int queue_id)
1534 {
1535     const struct netdev_class *class = netdev->netdev_class;
1536     return (class->delete_queue
1537             ? class->delete_queue(netdev, queue_id)
1538             : EOPNOTSUPP);
1539 }
1540
1541 /* Obtains statistics about 'queue_id' on 'netdev'.  On success, returns 0 and
1542  * fills 'stats' with the queue's statistics; individual members of 'stats' may
1543  * be set to all-1-bits if the statistic is unavailable.  On failure, returns a
1544  * positive errno value and fills 'stats' with values indicating unsupported
1545  * statistics. */
1546 int
1547 netdev_get_queue_stats(const struct netdev *netdev, unsigned int queue_id,
1548                        struct netdev_queue_stats *stats)
1549 {
1550     const struct netdev_class *class = netdev->netdev_class;
1551     int retval;
1552
1553     retval = (class->get_queue_stats
1554               ? class->get_queue_stats(netdev, queue_id, stats)
1555               : EOPNOTSUPP);
1556     if (retval) {
1557         stats->tx_bytes = UINT64_MAX;
1558         stats->tx_packets = UINT64_MAX;
1559         stats->tx_errors = UINT64_MAX;
1560         stats->created = LLONG_MIN;
1561     }
1562     return retval;
1563 }
1564
1565 /* Initializes 'dump' to begin dumping the queues in a netdev.
1566  *
1567  * This function provides no status indication.  An error status for the entire
1568  * dump operation is provided when it is completed by calling
1569  * netdev_queue_dump_done().
1570  */
1571 void
1572 netdev_queue_dump_start(struct netdev_queue_dump *dump,
1573                         const struct netdev *netdev)
1574 {
1575     dump->netdev = netdev_ref(netdev);
1576     if (netdev->netdev_class->queue_dump_start) {
1577         dump->error = netdev->netdev_class->queue_dump_start(netdev,
1578                                                              &dump->state);
1579     } else {
1580         dump->error = EOPNOTSUPP;
1581     }
1582 }
1583
1584 /* Attempts to retrieve another queue from 'dump', which must have been
1585  * initialized with netdev_queue_dump_start().  On success, stores a new queue
1586  * ID into '*queue_id', fills 'details' with configuration details for the
1587  * queue, and returns true.  On failure, returns false.
1588  *
1589  * Queues are not necessarily dumped in increasing order of queue ID (or any
1590  * other predictable order).
1591  *
1592  * Failure might indicate an actual error or merely that the last queue has
1593  * been dumped.  An error status for the entire dump operation is provided when
1594  * it is completed by calling netdev_queue_dump_done().
1595  *
1596  * The returned contents of 'details' should be documented as valid for the
1597  * given 'type' in the "other_config" column in the "Queue" table in
1598  * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
1599  *
1600  * The caller must initialize 'details' (e.g. with smap_init()) before calling
1601  * this function.  This function will clear and replace its contents.  The
1602  * caller must free 'details' when it is no longer needed (e.g. with
1603  * smap_destroy()). */
1604 bool
1605 netdev_queue_dump_next(struct netdev_queue_dump *dump,
1606                        unsigned int *queue_id, struct smap *details)
1607 {
1608     const struct netdev *netdev = dump->netdev;
1609
1610     if (dump->error) {
1611         return false;
1612     }
1613
1614     dump->error = netdev->netdev_class->queue_dump_next(netdev, dump->state,
1615                                                         queue_id, details);
1616
1617     if (dump->error) {
1618         netdev->netdev_class->queue_dump_done(netdev, dump->state);
1619         return false;
1620     }
1621     return true;
1622 }
1623
1624 /* Completes queue table dump operation 'dump', which must have been
1625  * initialized with netdev_queue_dump_start().  Returns 0 if the dump operation
1626  * was error-free, otherwise a positive errno value describing the problem. */
1627 int
1628 netdev_queue_dump_done(struct netdev_queue_dump *dump)
1629 {
1630     const struct netdev *netdev = dump->netdev;
1631     if (!dump->error && netdev->netdev_class->queue_dump_done) {
1632         dump->error = netdev->netdev_class->queue_dump_done(netdev,
1633                                                             dump->state);
1634     }
1635     netdev_close(dump->netdev);
1636     return dump->error == EOF ? 0 : dump->error;
1637 }
1638
1639 /* Iterates over all of 'netdev''s queues, calling 'cb' with the queue's ID,
1640  * its statistics, and the 'aux' specified by the caller.  The order of
1641  * iteration is unspecified, but (when successful) each queue is visited
1642  * exactly once.
1643  *
1644  * Calling this function may be more efficient than calling
1645  * netdev_get_queue_stats() for every queue.
1646  *
1647  * 'cb' must not modify or free the statistics passed in.
1648  *
1649  * Returns 0 if successful, otherwise a positive errno value.  On error, some
1650  * configured queues may not have been included in the iteration. */
1651 int
1652 netdev_dump_queue_stats(const struct netdev *netdev,
1653                         netdev_dump_queue_stats_cb *cb, void *aux)
1654 {
1655     const struct netdev_class *class = netdev->netdev_class;
1656     return (class->dump_queue_stats
1657             ? class->dump_queue_stats(netdev, cb, aux)
1658             : EOPNOTSUPP);
1659 }
1660
1661 \f
1662 /* Returns the class type of 'netdev'.
1663  *
1664  * The caller must not free the returned value. */
1665 const char *
1666 netdev_get_type(const struct netdev *netdev)
1667 {
1668     return netdev->netdev_class->type;
1669 }
1670
1671 /* Returns the class associated with 'netdev'. */
1672 const struct netdev_class *
1673 netdev_get_class(const struct netdev *netdev)
1674 {
1675     return netdev->netdev_class;
1676 }
1677
1678 /* Returns the netdev with 'name' or NULL if there is none.
1679  *
1680  * The caller must free the returned netdev with netdev_close(). */
1681 struct netdev *
1682 netdev_from_name(const char *name)
1683     OVS_EXCLUDED(netdev_mutex)
1684 {
1685     struct netdev *netdev;
1686
1687     ovs_mutex_lock(&netdev_mutex);
1688     netdev = shash_find_data(&netdev_shash, name);
1689     if (netdev) {
1690         netdev->ref_cnt++;
1691     }
1692     ovs_mutex_unlock(&netdev_mutex);
1693
1694     return netdev;
1695 }
1696
1697 /* Fills 'device_list' with devices that match 'netdev_class'.
1698  *
1699  * The caller is responsible for initializing and destroying 'device_list' and
1700  * must close each device on the list. */
1701 void
1702 netdev_get_devices(const struct netdev_class *netdev_class,
1703                    struct shash *device_list)
1704     OVS_EXCLUDED(netdev_mutex)
1705 {
1706     struct shash_node *node;
1707
1708     ovs_mutex_lock(&netdev_mutex);
1709     SHASH_FOR_EACH (node, &netdev_shash) {
1710         struct netdev *dev = node->data;
1711
1712         if (dev->netdev_class == netdev_class) {
1713             dev->ref_cnt++;
1714             shash_add(device_list, node->name, node->data);
1715         }
1716     }
1717     ovs_mutex_unlock(&netdev_mutex);
1718 }
1719
1720 /* Extracts pointers to all 'netdev-vports' into an array 'vports'
1721  * and returns it.  Stores the size of the array into '*size'.
1722  *
1723  * The caller is responsible for freeing 'vports' and must close
1724  * each 'netdev-vport' in the list. */
1725 struct netdev **
1726 netdev_get_vports(size_t *size)
1727     OVS_EXCLUDED(netdev_mutex)
1728 {
1729     struct netdev **vports;
1730     struct shash_node *node;
1731     size_t n = 0;
1732
1733     if (!size) {
1734         return NULL;
1735     }
1736
1737     /* Explicitly allocates big enough chunk of memory. */
1738     vports = xmalloc(shash_count(&netdev_shash) * sizeof *vports);
1739     ovs_mutex_lock(&netdev_mutex);
1740     SHASH_FOR_EACH (node, &netdev_shash) {
1741         struct netdev *dev = node->data;
1742
1743         if (netdev_vport_is_vport_class(dev->netdev_class)) {
1744             dev->ref_cnt++;
1745             vports[n] = dev;
1746             n++;
1747         }
1748     }
1749     ovs_mutex_unlock(&netdev_mutex);
1750     *size = n;
1751
1752     return vports;
1753 }
1754
1755 const char *
1756 netdev_get_type_from_name(const char *name)
1757 {
1758     struct netdev *dev = netdev_from_name(name);
1759     const char *type = dev ? netdev_get_type(dev) : NULL;
1760     netdev_close(dev);
1761     return type;
1762 }
1763 \f
1764 struct netdev *
1765 netdev_rxq_get_netdev(const struct netdev_rxq *rx)
1766 {
1767     ovs_assert(rx->netdev->ref_cnt > 0);
1768     return rx->netdev;
1769 }
1770
1771 const char *
1772 netdev_rxq_get_name(const struct netdev_rxq *rx)
1773 {
1774     return netdev_get_name(netdev_rxq_get_netdev(rx));
1775 }
1776
1777 int
1778 netdev_rxq_get_queue_id(const struct netdev_rxq *rx)
1779 {
1780     return rx->queue_id;
1781 }
1782
1783 static void
1784 restore_all_flags(void *aux OVS_UNUSED)
1785 {
1786     struct shash_node *node;
1787
1788     SHASH_FOR_EACH (node, &netdev_shash) {
1789         struct netdev *netdev = node->data;
1790         const struct netdev_saved_flags *sf;
1791         enum netdev_flags saved_values;
1792         enum netdev_flags saved_flags;
1793
1794         saved_values = saved_flags = 0;
1795         LIST_FOR_EACH (sf, node, &netdev->saved_flags_list) {
1796             saved_flags |= sf->saved_flags;
1797             saved_values &= ~sf->saved_flags;
1798             saved_values |= sf->saved_flags & sf->saved_values;
1799         }
1800         if (saved_flags) {
1801             enum netdev_flags old_flags;
1802
1803             netdev->netdev_class->update_flags(netdev,
1804                                                saved_flags & saved_values,
1805                                                saved_flags & ~saved_values,
1806                                                &old_flags);
1807         }
1808     }
1809 }
1810
1811 uint64_t
1812 netdev_get_change_seq(const struct netdev *netdev)
1813 {
1814     return netdev->change_seq;
1815 }
1816
1817 #ifndef _WIN32
1818 /* This implementation is shared by Linux and BSD. */
1819
1820 static struct ifaddrs *if_addr_list;
1821 static struct ovs_mutex if_addr_list_lock = OVS_MUTEX_INITIALIZER;
1822
1823 void
1824 netdev_get_addrs_list_flush(void)
1825 {
1826     ovs_mutex_lock(&if_addr_list_lock);
1827     if (if_addr_list) {
1828         freeifaddrs(if_addr_list);
1829         if_addr_list = NULL;
1830     }
1831     ovs_mutex_unlock(&if_addr_list_lock);
1832 }
1833
1834 int
1835 netdev_get_addrs(const char dev[], struct in6_addr **paddr,
1836                  struct in6_addr **pmask, int *n_in)
1837 {
1838     struct in6_addr *addr_array, *mask_array;
1839     const struct ifaddrs *ifa;
1840     int cnt = 0, i = 0;
1841
1842     ovs_mutex_lock(&if_addr_list_lock);
1843     if (!if_addr_list) {
1844         int err;
1845
1846         err = getifaddrs(&if_addr_list);
1847         if (err) {
1848             ovs_mutex_unlock(&if_addr_list_lock);
1849             return -err;
1850         }
1851     }
1852
1853     for (ifa = if_addr_list; ifa; ifa = ifa->ifa_next) {
1854         if (ifa->ifa_addr != NULL) {
1855             int family;
1856
1857             family = ifa->ifa_addr->sa_family;
1858             if (family == AF_INET || family == AF_INET6) {
1859                 if (!strncmp(ifa->ifa_name, dev, IFNAMSIZ)) {
1860                     cnt++;
1861                 }
1862             }
1863         }
1864     }
1865
1866     if (!cnt) {
1867         ovs_mutex_unlock(&if_addr_list_lock);
1868         return EADDRNOTAVAIL;
1869     }
1870     addr_array = xzalloc(sizeof *addr_array * cnt);
1871     mask_array = xzalloc(sizeof *mask_array * cnt);
1872     for (ifa = if_addr_list; ifa; ifa = ifa->ifa_next) {
1873         int family;
1874
1875         if (strncmp(ifa->ifa_name, dev, IFNAMSIZ) || ifa->ifa_addr == NULL) {
1876             continue;
1877         }
1878
1879         family = ifa->ifa_addr->sa_family;
1880         if (family == AF_INET) {
1881             const struct sockaddr_in *sin;
1882
1883             sin = ALIGNED_CAST(const struct sockaddr_in *, ifa->ifa_addr);
1884             in6_addr_set_mapped_ipv4(&addr_array[i], sin->sin_addr.s_addr);
1885             sin = (struct sockaddr_in *) &ifa->ifa_netmask;
1886             in6_addr_set_mapped_ipv4(&mask_array[i], sin->sin_addr.s_addr);
1887             i++;
1888         } else if (family == AF_INET6) {
1889             const struct sockaddr_in6 *sin6;
1890
1891             sin6 = ALIGNED_CAST(const struct sockaddr_in6 *, ifa->ifa_addr);
1892             memcpy(&addr_array[i], &sin6->sin6_addr, sizeof *addr_array);
1893             sin6 = (struct sockaddr_in6 *) &ifa->ifa_netmask;
1894             memcpy(&mask_array[i], &sin6->sin6_addr, sizeof *mask_array);
1895             i++;
1896         }
1897     }
1898     ovs_mutex_unlock(&if_addr_list_lock);
1899     if (paddr) {
1900         *n_in = cnt;
1901         *paddr = addr_array;
1902         *pmask = mask_array;
1903     } else {
1904         free(addr_array);
1905         free(mask_array);
1906     }
1907     return 0;
1908 }
1909 #endif