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