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