Add support for extended netdev statistics based on RFC 2819.
[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     /* Statistics are initialized before passing it to particular device
1335      * implementation so all values are filtered out by default. */
1336     memset(stats, 0xFF, sizeof *stats);
1337
1338     COVERAGE_INC(netdev_get_stats);
1339     error = (netdev->netdev_class->get_stats
1340              ? netdev->netdev_class->get_stats(netdev, stats)
1341              : EOPNOTSUPP);
1342     if (error) {
1343         /* In case of error all statistics are filtered out */
1344         memset(stats, 0xff, sizeof *stats);
1345     }
1346     return error;
1347 }
1348
1349 /* Attempts to set input rate limiting (policing) policy, such that up to
1350  * 'kbits_rate' kbps of traffic is accepted, with a maximum accumulative burst
1351  * size of 'kbits' kb. */
1352 int
1353 netdev_set_policing(struct netdev *netdev, uint32_t kbits_rate,
1354                     uint32_t kbits_burst)
1355 {
1356     return (netdev->netdev_class->set_policing
1357             ? netdev->netdev_class->set_policing(netdev,
1358                     kbits_rate, kbits_burst)
1359             : EOPNOTSUPP);
1360 }
1361
1362 /* Adds to 'types' all of the forms of QoS supported by 'netdev', or leaves it
1363  * empty if 'netdev' does not support QoS.  Any names added to 'types' should
1364  * be documented as valid for the "type" column in the "QoS" table in
1365  * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
1366  *
1367  * Every network device supports disabling QoS with a type of "", but this type
1368  * will not be added to 'types'.
1369  *
1370  * The caller must initialize 'types' (e.g. with sset_init()) before calling
1371  * this function.  The caller is responsible for destroying 'types' (e.g. with
1372  * sset_destroy()) when it is no longer needed.
1373  *
1374  * Returns 0 if successful, otherwise a positive errno value. */
1375 int
1376 netdev_get_qos_types(const struct netdev *netdev, struct sset *types)
1377 {
1378     const struct netdev_class *class = netdev->netdev_class;
1379     return (class->get_qos_types
1380             ? class->get_qos_types(netdev, types)
1381             : 0);
1382 }
1383
1384 /* Queries 'netdev' for its capabilities regarding the specified 'type' of QoS,
1385  * which should be "" or one of the types returned by netdev_get_qos_types()
1386  * for 'netdev'.  Returns 0 if successful, otherwise a positive errno value.
1387  * On success, initializes 'caps' with the QoS capabilities; on failure, clears
1388  * 'caps' to all zeros. */
1389 int
1390 netdev_get_qos_capabilities(const struct netdev *netdev, const char *type,
1391                             struct netdev_qos_capabilities *caps)
1392 {
1393     const struct netdev_class *class = netdev->netdev_class;
1394
1395     if (*type) {
1396         int retval = (class->get_qos_capabilities
1397                       ? class->get_qos_capabilities(netdev, type, caps)
1398                       : EOPNOTSUPP);
1399         if (retval) {
1400             memset(caps, 0, sizeof *caps);
1401         }
1402         return retval;
1403     } else {
1404         /* Every netdev supports turning off QoS. */
1405         memset(caps, 0, sizeof *caps);
1406         return 0;
1407     }
1408 }
1409
1410 /* Obtains the number of queues supported by 'netdev' for the specified 'type'
1411  * of QoS.  Returns 0 if successful, otherwise a positive errno value.  Stores
1412  * the number of queues (zero on failure) in '*n_queuesp'.
1413  *
1414  * This is just a simple wrapper around netdev_get_qos_capabilities(). */
1415 int
1416 netdev_get_n_queues(const struct netdev *netdev,
1417                     const char *type, unsigned int *n_queuesp)
1418 {
1419     struct netdev_qos_capabilities caps;
1420     int retval;
1421
1422     retval = netdev_get_qos_capabilities(netdev, type, &caps);
1423     *n_queuesp = caps.n_queues;
1424     return retval;
1425 }
1426
1427 /* Queries 'netdev' about its currently configured form of QoS.  If successful,
1428  * stores the name of the current form of QoS into '*typep', stores any details
1429  * of configuration as string key-value pairs in 'details', and returns 0.  On
1430  * failure, sets '*typep' to NULL and returns a positive errno value.
1431  *
1432  * A '*typep' of "" indicates that QoS is currently disabled on 'netdev'.
1433  *
1434  * The caller must initialize 'details' as an empty smap (e.g. with
1435  * smap_init()) before calling this function.  The caller must free 'details'
1436  * when it is no longer needed (e.g. with smap_destroy()).
1437  *
1438  * The caller must not modify or free '*typep'.
1439  *
1440  * '*typep' will be one of the types returned by netdev_get_qos_types() for
1441  * 'netdev'.  The contents of 'details' should be documented as valid for
1442  * '*typep' in the "other_config" column in the "QoS" table in
1443  * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)). */
1444 int
1445 netdev_get_qos(const struct netdev *netdev,
1446                const char **typep, struct smap *details)
1447 {
1448     const struct netdev_class *class = netdev->netdev_class;
1449     int retval;
1450
1451     if (class->get_qos) {
1452         retval = class->get_qos(netdev, typep, details);
1453         if (retval) {
1454             *typep = NULL;
1455             smap_clear(details);
1456         }
1457         return retval;
1458     } else {
1459         /* 'netdev' doesn't support QoS, so report that QoS is disabled. */
1460         *typep = "";
1461         return 0;
1462     }
1463 }
1464
1465 /* Attempts to reconfigure QoS on 'netdev', changing the form of QoS to 'type'
1466  * with details of configuration from 'details'.  Returns 0 if successful,
1467  * otherwise a positive errno value.  On error, the previous QoS configuration
1468  * is retained.
1469  *
1470  * When this function changes the type of QoS (not just 'details'), this also
1471  * resets all queue configuration for 'netdev' to their defaults (which depend
1472  * on the specific type of QoS).  Otherwise, the queue configuration for
1473  * 'netdev' is unchanged.
1474  *
1475  * 'type' should be "" (to disable QoS) or one of the types returned by
1476  * netdev_get_qos_types() for 'netdev'.  The contents of 'details' should be
1477  * documented as valid for the given 'type' in the "other_config" column in the
1478  * "QoS" table in vswitchd/vswitch.xml (which is built as
1479  * ovs-vswitchd.conf.db(8)).
1480  *
1481  * NULL may be specified for 'details' if there are no configuration
1482  * details. */
1483 int
1484 netdev_set_qos(struct netdev *netdev,
1485                const char *type, const struct smap *details)
1486 {
1487     const struct netdev_class *class = netdev->netdev_class;
1488
1489     if (!type) {
1490         type = "";
1491     }
1492
1493     if (class->set_qos) {
1494         if (!details) {
1495             static const struct smap empty = SMAP_INITIALIZER(&empty);
1496             details = &empty;
1497         }
1498         return class->set_qos(netdev, type, details);
1499     } else {
1500         return *type ? EOPNOTSUPP : 0;
1501     }
1502 }
1503
1504 /* Queries 'netdev' for information about the queue numbered 'queue_id'.  If
1505  * successful, adds that information as string key-value pairs to 'details'.
1506  * Returns 0 if successful, otherwise a positive errno value.
1507  *
1508  * 'queue_id' must be less than the number of queues supported by 'netdev' for
1509  * the current form of QoS (e.g. as returned by netdev_get_n_queues(netdev)).
1510  *
1511  * The returned contents of 'details' should be documented as valid for the
1512  * given 'type' in the "other_config" column in the "Queue" table in
1513  * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
1514  *
1515  * The caller must initialize 'details' (e.g. with smap_init()) before calling
1516  * this function.  The caller must free 'details' when it is no longer needed
1517  * (e.g. with smap_destroy()). */
1518 int
1519 netdev_get_queue(const struct netdev *netdev,
1520                  unsigned int queue_id, struct smap *details)
1521 {
1522     const struct netdev_class *class = netdev->netdev_class;
1523     int retval;
1524
1525     retval = (class->get_queue
1526               ? class->get_queue(netdev, queue_id, details)
1527               : EOPNOTSUPP);
1528     if (retval) {
1529         smap_clear(details);
1530     }
1531     return retval;
1532 }
1533
1534 /* Configures the queue numbered 'queue_id' on 'netdev' with the key-value
1535  * string pairs in 'details'.  The contents of 'details' should be documented
1536  * as valid for the given 'type' in the "other_config" column in the "Queue"
1537  * table in vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
1538  * Returns 0 if successful, otherwise a positive errno value.  On failure, the
1539  * given queue's configuration should be unmodified.
1540  *
1541  * 'queue_id' must be less than the number of queues supported by 'netdev' for
1542  * the current form of QoS (e.g. as returned by netdev_get_n_queues(netdev)).
1543  *
1544  * This function does not modify 'details', and the caller retains ownership of
1545  * it. */
1546 int
1547 netdev_set_queue(struct netdev *netdev,
1548                  unsigned int queue_id, const struct smap *details)
1549 {
1550     const struct netdev_class *class = netdev->netdev_class;
1551     return (class->set_queue
1552             ? class->set_queue(netdev, queue_id, details)
1553             : EOPNOTSUPP);
1554 }
1555
1556 /* Attempts to delete the queue numbered 'queue_id' from 'netdev'.  Some kinds
1557  * of QoS may have a fixed set of queues, in which case attempts to delete them
1558  * will fail with EOPNOTSUPP.
1559  *
1560  * Returns 0 if successful, otherwise a positive errno value.  On failure, the
1561  * given queue will be unmodified.
1562  *
1563  * 'queue_id' must be less than the number of queues supported by 'netdev' for
1564  * the current form of QoS (e.g. as returned by
1565  * netdev_get_n_queues(netdev)). */
1566 int
1567 netdev_delete_queue(struct netdev *netdev, unsigned int queue_id)
1568 {
1569     const struct netdev_class *class = netdev->netdev_class;
1570     return (class->delete_queue
1571             ? class->delete_queue(netdev, queue_id)
1572             : EOPNOTSUPP);
1573 }
1574
1575 /* Obtains statistics about 'queue_id' on 'netdev'.  On success, returns 0 and
1576  * fills 'stats' with the queue's statistics; individual members of 'stats' may
1577  * be set to all-1-bits if the statistic is unavailable.  On failure, returns a
1578  * positive errno value and fills 'stats' with values indicating unsupported
1579  * statistics. */
1580 int
1581 netdev_get_queue_stats(const struct netdev *netdev, unsigned int queue_id,
1582                        struct netdev_queue_stats *stats)
1583 {
1584     const struct netdev_class *class = netdev->netdev_class;
1585     int retval;
1586
1587     retval = (class->get_queue_stats
1588               ? class->get_queue_stats(netdev, queue_id, stats)
1589               : EOPNOTSUPP);
1590     if (retval) {
1591         stats->tx_bytes = UINT64_MAX;
1592         stats->tx_packets = UINT64_MAX;
1593         stats->tx_errors = UINT64_MAX;
1594         stats->created = LLONG_MIN;
1595     }
1596     return retval;
1597 }
1598
1599 /* Initializes 'dump' to begin dumping the queues in a netdev.
1600  *
1601  * This function provides no status indication.  An error status for the entire
1602  * dump operation is provided when it is completed by calling
1603  * netdev_queue_dump_done().
1604  */
1605 void
1606 netdev_queue_dump_start(struct netdev_queue_dump *dump,
1607                         const struct netdev *netdev)
1608 {
1609     dump->netdev = netdev_ref(netdev);
1610     if (netdev->netdev_class->queue_dump_start) {
1611         dump->error = netdev->netdev_class->queue_dump_start(netdev,
1612                                                              &dump->state);
1613     } else {
1614         dump->error = EOPNOTSUPP;
1615     }
1616 }
1617
1618 /* Attempts to retrieve another queue from 'dump', which must have been
1619  * initialized with netdev_queue_dump_start().  On success, stores a new queue
1620  * ID into '*queue_id', fills 'details' with configuration details for the
1621  * queue, and returns true.  On failure, returns false.
1622  *
1623  * Queues are not necessarily dumped in increasing order of queue ID (or any
1624  * other predictable order).
1625  *
1626  * Failure might indicate an actual error or merely that the last queue has
1627  * been dumped.  An error status for the entire dump operation is provided when
1628  * it is completed by calling netdev_queue_dump_done().
1629  *
1630  * The returned contents of 'details' should be documented as valid for the
1631  * given 'type' in the "other_config" column in the "Queue" table in
1632  * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
1633  *
1634  * The caller must initialize 'details' (e.g. with smap_init()) before calling
1635  * this function.  This function will clear and replace its contents.  The
1636  * caller must free 'details' when it is no longer needed (e.g. with
1637  * smap_destroy()). */
1638 bool
1639 netdev_queue_dump_next(struct netdev_queue_dump *dump,
1640                        unsigned int *queue_id, struct smap *details)
1641 {
1642     const struct netdev *netdev = dump->netdev;
1643
1644     if (dump->error) {
1645         return false;
1646     }
1647
1648     dump->error = netdev->netdev_class->queue_dump_next(netdev, dump->state,
1649                                                         queue_id, details);
1650
1651     if (dump->error) {
1652         netdev->netdev_class->queue_dump_done(netdev, dump->state);
1653         return false;
1654     }
1655     return true;
1656 }
1657
1658 /* Completes queue table dump operation 'dump', which must have been
1659  * initialized with netdev_queue_dump_start().  Returns 0 if the dump operation
1660  * was error-free, otherwise a positive errno value describing the problem. */
1661 int
1662 netdev_queue_dump_done(struct netdev_queue_dump *dump)
1663 {
1664     const struct netdev *netdev = dump->netdev;
1665     if (!dump->error && netdev->netdev_class->queue_dump_done) {
1666         dump->error = netdev->netdev_class->queue_dump_done(netdev,
1667                                                             dump->state);
1668     }
1669     netdev_close(dump->netdev);
1670     return dump->error == EOF ? 0 : dump->error;
1671 }
1672
1673 /* Iterates over all of 'netdev''s queues, calling 'cb' with the queue's ID,
1674  * its statistics, and the 'aux' specified by the caller.  The order of
1675  * iteration is unspecified, but (when successful) each queue is visited
1676  * exactly once.
1677  *
1678  * Calling this function may be more efficient than calling
1679  * netdev_get_queue_stats() for every queue.
1680  *
1681  * 'cb' must not modify or free the statistics passed in.
1682  *
1683  * Returns 0 if successful, otherwise a positive errno value.  On error, some
1684  * configured queues may not have been included in the iteration. */
1685 int
1686 netdev_dump_queue_stats(const struct netdev *netdev,
1687                         netdev_dump_queue_stats_cb *cb, void *aux)
1688 {
1689     const struct netdev_class *class = netdev->netdev_class;
1690     return (class->dump_queue_stats
1691             ? class->dump_queue_stats(netdev, cb, aux)
1692             : EOPNOTSUPP);
1693 }
1694
1695 \f
1696 /* Returns the class type of 'netdev'.
1697  *
1698  * The caller must not free the returned value. */
1699 const char *
1700 netdev_get_type(const struct netdev *netdev)
1701 {
1702     return netdev->netdev_class->type;
1703 }
1704
1705 /* Returns the class associated with 'netdev'. */
1706 const struct netdev_class *
1707 netdev_get_class(const struct netdev *netdev)
1708 {
1709     return netdev->netdev_class;
1710 }
1711
1712 /* Returns the netdev with 'name' or NULL if there is none.
1713  *
1714  * The caller must free the returned netdev with netdev_close(). */
1715 struct netdev *
1716 netdev_from_name(const char *name)
1717     OVS_EXCLUDED(netdev_mutex)
1718 {
1719     struct netdev *netdev;
1720
1721     ovs_mutex_lock(&netdev_mutex);
1722     netdev = shash_find_data(&netdev_shash, name);
1723     if (netdev) {
1724         netdev->ref_cnt++;
1725     }
1726     ovs_mutex_unlock(&netdev_mutex);
1727
1728     return netdev;
1729 }
1730
1731 /* Fills 'device_list' with devices that match 'netdev_class'.
1732  *
1733  * The caller is responsible for initializing and destroying 'device_list' and
1734  * must close each device on the list. */
1735 void
1736 netdev_get_devices(const struct netdev_class *netdev_class,
1737                    struct shash *device_list)
1738     OVS_EXCLUDED(netdev_mutex)
1739 {
1740     struct shash_node *node;
1741
1742     ovs_mutex_lock(&netdev_mutex);
1743     SHASH_FOR_EACH (node, &netdev_shash) {
1744         struct netdev *dev = node->data;
1745
1746         if (dev->netdev_class == netdev_class) {
1747             dev->ref_cnt++;
1748             shash_add(device_list, node->name, node->data);
1749         }
1750     }
1751     ovs_mutex_unlock(&netdev_mutex);
1752 }
1753
1754 /* Extracts pointers to all 'netdev-vports' into an array 'vports'
1755  * and returns it.  Stores the size of the array into '*size'.
1756  *
1757  * The caller is responsible for freeing 'vports' and must close
1758  * each 'netdev-vport' in the list. */
1759 struct netdev **
1760 netdev_get_vports(size_t *size)
1761     OVS_EXCLUDED(netdev_mutex)
1762 {
1763     struct netdev **vports;
1764     struct shash_node *node;
1765     size_t n = 0;
1766
1767     if (!size) {
1768         return NULL;
1769     }
1770
1771     /* Explicitly allocates big enough chunk of memory. */
1772     vports = xmalloc(shash_count(&netdev_shash) * sizeof *vports);
1773     ovs_mutex_lock(&netdev_mutex);
1774     SHASH_FOR_EACH (node, &netdev_shash) {
1775         struct netdev *dev = node->data;
1776
1777         if (netdev_vport_is_vport_class(dev->netdev_class)) {
1778             dev->ref_cnt++;
1779             vports[n] = dev;
1780             n++;
1781         }
1782     }
1783     ovs_mutex_unlock(&netdev_mutex);
1784     *size = n;
1785
1786     return vports;
1787 }
1788
1789 const char *
1790 netdev_get_type_from_name(const char *name)
1791 {
1792     struct netdev *dev = netdev_from_name(name);
1793     const char *type = dev ? netdev_get_type(dev) : NULL;
1794     netdev_close(dev);
1795     return type;
1796 }
1797 \f
1798 struct netdev *
1799 netdev_rxq_get_netdev(const struct netdev_rxq *rx)
1800 {
1801     ovs_assert(rx->netdev->ref_cnt > 0);
1802     return rx->netdev;
1803 }
1804
1805 const char *
1806 netdev_rxq_get_name(const struct netdev_rxq *rx)
1807 {
1808     return netdev_get_name(netdev_rxq_get_netdev(rx));
1809 }
1810
1811 int
1812 netdev_rxq_get_queue_id(const struct netdev_rxq *rx)
1813 {
1814     return rx->queue_id;
1815 }
1816
1817 static void
1818 restore_all_flags(void *aux OVS_UNUSED)
1819 {
1820     struct shash_node *node;
1821
1822     SHASH_FOR_EACH (node, &netdev_shash) {
1823         struct netdev *netdev = node->data;
1824         const struct netdev_saved_flags *sf;
1825         enum netdev_flags saved_values;
1826         enum netdev_flags saved_flags;
1827
1828         saved_values = saved_flags = 0;
1829         LIST_FOR_EACH (sf, node, &netdev->saved_flags_list) {
1830             saved_flags |= sf->saved_flags;
1831             saved_values &= ~sf->saved_flags;
1832             saved_values |= sf->saved_flags & sf->saved_values;
1833         }
1834         if (saved_flags) {
1835             enum netdev_flags old_flags;
1836
1837             netdev->netdev_class->update_flags(netdev,
1838                                                saved_flags & saved_values,
1839                                                saved_flags & ~saved_values,
1840                                                &old_flags);
1841         }
1842     }
1843 }
1844
1845 uint64_t
1846 netdev_get_change_seq(const struct netdev *netdev)
1847 {
1848     return netdev->change_seq;
1849 }
1850
1851 #ifndef _WIN32
1852 /* This implementation is shared by Linux and BSD. */
1853
1854 static struct ifaddrs *if_addr_list;
1855 static struct ovs_mutex if_addr_list_lock = OVS_MUTEX_INITIALIZER;
1856
1857 void
1858 netdev_get_addrs_list_flush(void)
1859 {
1860     ovs_mutex_lock(&if_addr_list_lock);
1861     if (if_addr_list) {
1862         freeifaddrs(if_addr_list);
1863         if_addr_list = NULL;
1864     }
1865     ovs_mutex_unlock(&if_addr_list_lock);
1866 }
1867
1868 int
1869 netdev_get_addrs(const char dev[], struct in6_addr **paddr,
1870                  struct in6_addr **pmask, int *n_in)
1871 {
1872     struct in6_addr *addr_array, *mask_array;
1873     const struct ifaddrs *ifa;
1874     int cnt = 0, i = 0;
1875
1876     ovs_mutex_lock(&if_addr_list_lock);
1877     if (!if_addr_list) {
1878         int err;
1879
1880         err = getifaddrs(&if_addr_list);
1881         if (err) {
1882             ovs_mutex_unlock(&if_addr_list_lock);
1883             return -err;
1884         }
1885     }
1886
1887     for (ifa = if_addr_list; ifa; ifa = ifa->ifa_next) {
1888         if (ifa->ifa_addr != NULL) {
1889             int family;
1890
1891             family = ifa->ifa_addr->sa_family;
1892             if (family == AF_INET || family == AF_INET6) {
1893                 if (!strncmp(ifa->ifa_name, dev, IFNAMSIZ)) {
1894                     cnt++;
1895                 }
1896             }
1897         }
1898     }
1899
1900     if (!cnt) {
1901         ovs_mutex_unlock(&if_addr_list_lock);
1902         return EADDRNOTAVAIL;
1903     }
1904     addr_array = xzalloc(sizeof *addr_array * cnt);
1905     mask_array = xzalloc(sizeof *mask_array * cnt);
1906     for (ifa = if_addr_list; ifa; ifa = ifa->ifa_next) {
1907         int family;
1908
1909         if (strncmp(ifa->ifa_name, dev, IFNAMSIZ) || ifa->ifa_addr == NULL) {
1910             continue;
1911         }
1912
1913         family = ifa->ifa_addr->sa_family;
1914         if (family == AF_INET) {
1915             const struct sockaddr_in *sin;
1916
1917             sin = ALIGNED_CAST(const struct sockaddr_in *, ifa->ifa_addr);
1918             in6_addr_set_mapped_ipv4(&addr_array[i], sin->sin_addr.s_addr);
1919             sin = (struct sockaddr_in *) &ifa->ifa_netmask;
1920             in6_addr_set_mapped_ipv4(&mask_array[i], sin->sin_addr.s_addr);
1921             i++;
1922         } else if (family == AF_INET6) {
1923             const struct sockaddr_in6 *sin6;
1924
1925             sin6 = ALIGNED_CAST(const struct sockaddr_in6 *, ifa->ifa_addr);
1926             memcpy(&addr_array[i], &sin6->sin6_addr, sizeof *addr_array);
1927             sin6 = (struct sockaddr_in6 *) &ifa->ifa_netmask;
1928             memcpy(&mask_array[i], &sin6->sin6_addr, sizeof *mask_array);
1929             i++;
1930         }
1931     }
1932     ovs_mutex_unlock(&if_addr_list_lock);
1933     if (paddr) {
1934         *n_in = cnt;
1935         *paddr = addr_array;
1936         *pmask = mask_array;
1937     } else {
1938         free(addr_array);
1939         free(mask_array);
1940     }
1941     return 0;
1942 }
1943 #endif