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