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