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