netdev: Compare full arguments instead of hash for reconfigure.
[sliver-openvswitch.git] / lib / netdev.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
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 <assert.h>
21 #include <errno.h>
22 #include <inttypes.h>
23 #include <netinet/in.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27
28 #include "coverage.h"
29 #include "dynamic-string.h"
30 #include "fatal-signal.h"
31 #include "hash.h"
32 #include "list.h"
33 #include "netdev-provider.h"
34 #include "ofpbuf.h"
35 #include "packets.h"
36 #include "poll-loop.h"
37 #include "shash.h"
38 #include "svec.h"
39
40 #define THIS_MODULE VLM_netdev
41 #include "vlog.h"
42
43 static const struct netdev_class *netdev_classes[] = {
44     &netdev_linux_class,
45     &netdev_tap_class,
46     &netdev_gre_class,
47 };
48 static int n_netdev_classes = ARRAY_SIZE(netdev_classes);
49
50 /* All created network devices. */
51 static struct shash netdev_dev_shash = SHASH_INITIALIZER(&netdev_dev_shash);
52
53 /* All open network devices. */
54 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
55
56 /* This is set pretty low because we probably won't learn anything from the
57  * additional log messages. */
58 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
59
60 static void close_all_netdevs(void *aux UNUSED);
61 static int restore_flags(struct netdev *netdev);
62 void update_device_args(struct netdev_dev *, const struct shash *args);
63
64 /* Attempts to initialize the netdev module.  Returns 0 if successful,
65  * otherwise a positive errno value.
66  *
67  * Calling this function is optional.  If not called explicitly, it will
68  * automatically be called upon the first attempt to open or create a 
69  * network device. */
70 int
71 netdev_initialize(void)
72 {
73     static int status = -1;
74
75     if (status < 0) {
76         int i, j;
77
78         fatal_signal_add_hook(close_all_netdevs, NULL, NULL, true);
79
80         status = 0;
81         for (i = j = 0; i < n_netdev_classes; i++) {
82             const struct netdev_class *class = netdev_classes[i];
83             if (class->init) {
84                 int retval = class->init();
85                 if (!retval) {
86                     netdev_classes[j++] = class;
87                 } else {
88                     VLOG_ERR("failed to initialize %s network device "
89                              "class: %s", class->type, strerror(retval));
90                     if (!status) {
91                         status = retval;
92                     }
93                 }
94             } else {
95                 netdev_classes[j++] = class;
96             }
97         }
98         n_netdev_classes = j;
99     }
100     return status;
101 }
102
103 /* Performs periodic work needed by all the various kinds of netdevs.
104  *
105  * If your program opens any netdevs, it must call this function within its
106  * main poll loop. */
107 void
108 netdev_run(void)
109 {
110     int i;
111     for (i = 0; i < n_netdev_classes; i++) {
112         const struct netdev_class *class = netdev_classes[i];
113         if (class->run) {
114             class->run();
115         }
116     }
117 }
118
119 /* Arranges for poll_block() to wake up when netdev_run() needs to be called.
120  *
121  * If your program opens any netdevs, it must call this function within its
122  * main poll loop. */
123 void
124 netdev_wait(void)
125 {
126     int i;
127     for (i = 0; i < n_netdev_classes; i++) {
128         const struct netdev_class *class = netdev_classes[i];
129         if (class->wait) {
130             class->wait();
131         }
132     }
133 }
134
135 /* Compares 'args' to those used to those used by 'dev'.  Returns true
136  * if the arguments are the same, false otherwise.  Does not update the
137  * values stored in 'dev'. */
138 static bool
139 compare_device_args(const struct netdev_dev *dev, const struct shash *args)
140 {
141     const struct shash_node **new_args;
142     bool result = true;
143     int i;
144
145     if (shash_count(args) != dev->n_args) {
146         return false;
147     }
148
149     new_args = shash_sort(args);
150     for (i = 0; i < dev->n_args; i++) {
151         if (strcmp(dev->args[i].key, new_args[i]->name) || 
152             strcmp(dev->args[i].value, new_args[i]->data)) {
153             result = false;
154             goto finish;
155         }
156     }
157
158 finish:
159     free(new_args);
160     return result;
161 }
162
163 static int
164 compare_args(const void *a_, const void *b_)
165 {
166     const struct arg *a = a_;
167     const struct arg *b = b_;
168     return strcmp(a->key, b->key);
169 }
170
171 void
172 update_device_args(struct netdev_dev *dev, const struct shash *args)
173 {
174     struct shash_node *node;
175     int i;
176
177     if (dev->n_args) {
178         for (i = 0; i < dev->n_args; i++) {
179             free(dev->args[i].key);
180             free(dev->args[i].value);
181         }
182
183         free(dev->args);
184         dev->n_args = 0;
185     }
186
187     if (!args || shash_is_empty(args)) {
188         return;
189     }
190
191     dev->n_args = shash_count(args);
192     dev->args = xmalloc(dev->n_args * sizeof *dev->args);
193
194     i = 0;
195     SHASH_FOR_EACH(node, args) {
196         dev->args[i].key = xstrdup(node->name);
197         dev->args[i].value = xstrdup(node->data);
198         i++;
199     }
200
201     qsort(dev->args, dev->n_args, sizeof *dev->args, compare_args);
202 }
203
204 static int
205 create_device(struct netdev_options *options, struct netdev_dev **netdev_devp)
206 {
207     int i;
208
209     if (!options->may_create) {
210         VLOG_WARN("attempted to create a device that may not be created: %s",
211                   options->name);
212         return ENODEV;
213     }
214
215     if (!options->type || strlen(options->type) == 0) {
216         /* Default to system. */
217         options->type = "system";
218     }
219
220     for (i = 0; i < n_netdev_classes; i++) {
221         const struct netdev_class *class = netdev_classes[i];
222
223         if (!strcmp(options->type, class->type)) {
224             return class->create(options->name, options->type, options->args,
225                                  netdev_devp);
226         }
227     }
228
229     VLOG_WARN("could not create netdev %s of unknown type %s", options->name,
230                                                                 options->type);
231     return EINVAL;
232 }
233
234 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
235  * successful, otherwise a positive errno value.  On success, sets '*netdevp'
236  * to the new network device, otherwise to null.
237  *
238  * If this is the first time the device has been opened, then create is called
239  * before opening.  The device is  created using the given type and arguments.
240  *
241  * 'ethertype' may be a 16-bit Ethernet protocol value in host byte order to
242  * capture frames of that type received on the device.  It may also be one of
243  * the 'enum netdev_pseudo_ethertype' values to receive frames in one of those
244  * categories.
245  *
246  * If the 'may_create' flag is set then this is allowed to be the first time
247  * the device is opened (i.e. the refcount will be 1 after this call).  It
248  * may be set to false if the device should have already been created.
249  *
250  * If the 'may_open' flag is set then the call will succeed even if another
251  * caller has already opened it.  It may be to false if the device should not
252  * currently be open. */
253
254 int
255 netdev_open(struct netdev_options *options, struct netdev **netdevp)
256 {
257     struct shash empty_args = SHASH_INITIALIZER(&empty_args);
258     struct netdev_dev *netdev_dev;
259     int error;
260
261     *netdevp = NULL;
262     netdev_initialize();
263
264     if (!options->args) {
265         options->args = &empty_args;
266     }
267
268     netdev_dev = shash_find_data(&netdev_dev_shash, options->name);
269
270     if (!netdev_dev) {
271         error = create_device(options, &netdev_dev);
272         if (error) {
273             return error;
274         }
275         update_device_args(netdev_dev, options->args);
276
277     } else if (options->may_open) {
278         if (!shash_is_empty(options->args) &&
279             !compare_device_args(netdev_dev, options->args)) {
280
281             VLOG_WARN("%s: attempted to open already created netdev with "
282                       "different arguments", options->name);
283             return EINVAL;
284         }
285     } else {
286         VLOG_WARN("%s: attempted to create a netdev device with bound name",
287                   options->name);
288         return EEXIST;
289     }
290
291     error = netdev_dev->class->open(netdev_dev, options->ethertype, netdevp);
292
293     if (!error) {
294         netdev_dev->ref_cnt++;
295     } else {
296         if (!netdev_dev->ref_cnt) {
297             netdev_dev_uninit(netdev_dev, true);
298         }
299     }
300
301     return error;
302 }
303
304 int
305 netdev_open_default(const char *name, struct netdev **netdevp)
306 {
307     struct netdev_options options;
308
309     memset(&options, 0, sizeof options);
310
311     options.name = name;
312     options.ethertype = NETDEV_ETH_TYPE_NONE;
313     options.may_create = true;
314     options.may_open = true;
315
316     return netdev_open(&options, netdevp);
317 }
318
319 /* Reconfigures the device 'netdev' with 'args'.  'args' may be empty
320  * or NULL if none are needed. */
321 int
322 netdev_reconfigure(struct netdev *netdev, const struct shash *args)
323 {
324     struct shash empty_args = SHASH_INITIALIZER(&empty_args);
325     struct netdev_dev *netdev_dev = netdev_get_dev(netdev);
326
327     if (!args) {
328         args = &empty_args;
329     }
330
331     if (netdev_dev->class->reconfigure) {
332         if (!compare_device_args(netdev_dev, args)) {
333             update_device_args(netdev_dev, args);
334             return netdev_dev->class->reconfigure(netdev_dev, args);
335         }
336     } else if (!shash_is_empty(args)) {
337         VLOG_WARN("%s: arguments provided to device that does not have a "
338                   "reconfigure function", netdev_get_name(netdev));
339     }
340
341     return 0;
342 }
343
344 /* Closes and destroys 'netdev'. */
345 void
346 netdev_close(struct netdev *netdev)
347 {
348     if (netdev) {
349         struct netdev_dev *netdev_dev = netdev_get_dev(netdev);
350
351         assert(netdev_dev->ref_cnt);
352         netdev_dev->ref_cnt--;
353         netdev_uninit(netdev, true);
354
355         /* If the reference count for the netdev device is zero, destroy it. */
356         if (!netdev_dev->ref_cnt) {
357             netdev_dev_uninit(netdev_dev, true);
358         }
359     }
360 }
361
362 /* Returns true if a network device named 'name' exists and may be opened,
363  * otherwise false. */
364 bool
365 netdev_exists(const char *name)
366 {
367     struct netdev *netdev;
368     int error;
369
370     error = netdev_open_default(name, &netdev);
371     if (!error) {
372         netdev_close(netdev);
373         return true;
374     } else {
375         if (error != ENODEV) {
376             VLOG_WARN("failed to open network device %s: %s",
377                       name, strerror(error));
378         }
379         return false;
380     }
381 }
382
383 /* Initializes 'svec' with a list of the names of all known network devices. */
384 int
385 netdev_enumerate(struct svec *svec)
386 {
387     int error;
388     int i;
389
390     svec_init(svec);
391
392     netdev_initialize();
393
394     error = 0;
395     for (i = 0; i < n_netdev_classes; i++) {
396         const struct netdev_class *class = netdev_classes[i];
397         if (class->enumerate) {
398             int retval = class->enumerate(svec);
399             if (retval) {
400                 VLOG_WARN("failed to enumerate %s network devices: %s",
401                           class->type, strerror(retval));
402                 if (!error) {
403                     error = retval;
404                 }
405             }
406         }
407     }
408     return error;
409 }
410
411 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
412  * must have initialized with sufficient room for the packet.  The space
413  * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
414  * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
415  * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
416  * need not be included.)
417  *
418  * If a packet is successfully retrieved, returns 0.  In this case 'buffer' is
419  * guaranteed to contain at least ETH_TOTAL_MIN bytes.  Otherwise, returns a
420  * positive errno value.  Returns EAGAIN immediately if no packet is ready to
421  * be returned.
422  */
423 int
424 netdev_recv(struct netdev *netdev, struct ofpbuf *buffer)
425 {
426     int retval;
427
428     assert(buffer->size == 0);
429     assert(ofpbuf_tailroom(buffer) >= ETH_TOTAL_MIN);
430
431     retval = netdev_get_dev(netdev)->class->recv(netdev, buffer->data,
432              ofpbuf_tailroom(buffer));
433     if (retval >= 0) {
434         COVERAGE_INC(netdev_received);
435         buffer->size += retval;
436         if (buffer->size < ETH_TOTAL_MIN) {
437             ofpbuf_put_zeros(buffer, ETH_TOTAL_MIN - buffer->size);
438         }
439         return 0;
440     } else {
441         return -retval;
442     }
443 }
444
445 /* Registers with the poll loop to wake up from the next call to poll_block()
446  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
447 void
448 netdev_recv_wait(struct netdev *netdev)
449 {
450     netdev_get_dev(netdev)->class->recv_wait(netdev);
451 }
452
453 /* Discards all packets waiting to be received from 'netdev'. */
454 int
455 netdev_drain(struct netdev *netdev)
456 {
457     return netdev_get_dev(netdev)->class->drain(netdev);
458 }
459
460 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
461  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
462  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
463  * the packet is too big or too small to transmit on the device.
464  *
465  * The caller retains ownership of 'buffer' in all cases.
466  *
467  * The kernel maintains a packet transmission queue, so the caller is not
468  * expected to do additional queuing of packets. */
469 int
470 netdev_send(struct netdev *netdev, const struct ofpbuf *buffer)
471 {
472     int error = netdev_get_dev(netdev)->class->send(netdev, buffer->data,
473                                                     buffer->size);
474     if (!error) {
475         COVERAGE_INC(netdev_sent);
476     }
477     return error;
478 }
479
480 /* Registers with the poll loop to wake up from the next call to poll_block()
481  * when the packet transmission queue has sufficient room to transmit a packet
482  * with netdev_send().
483  *
484  * The kernel maintains a packet transmission queue, so the client is not
485  * expected to do additional queuing of packets.  Thus, this function is
486  * unlikely to ever be used.  It is included for completeness. */
487 void
488 netdev_send_wait(struct netdev *netdev)
489 {
490     return netdev_get_dev(netdev)->class->send_wait(netdev);
491 }
492
493 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
494  * otherwise a positive errno value. */
495 int
496 netdev_set_etheraddr(struct netdev *netdev, const uint8_t mac[ETH_ADDR_LEN])
497 {
498     return netdev_get_dev(netdev)->class->set_etheraddr(netdev, mac);
499 }
500
501 /* Retrieves 'netdev''s MAC address.  If successful, returns 0 and copies the
502  * the MAC address into 'mac'.  On failure, returns a positive errno value and
503  * clears 'mac' to all-zeros. */
504 int
505 netdev_get_etheraddr(const struct netdev *netdev, uint8_t mac[ETH_ADDR_LEN])
506 {
507     return netdev_get_dev(netdev)->class->get_etheraddr(netdev, mac);
508 }
509
510 /* Returns the name of the network device that 'netdev' represents,
511  * e.g. "eth0".  The caller must not modify or free the returned string. */
512 const char *
513 netdev_get_name(const struct netdev *netdev)
514 {
515     return netdev_get_dev(netdev)->name;
516 }
517
518 /* Retrieves the MTU of 'netdev'.  The MTU is the maximum size of transmitted
519  * (and received) packets, in bytes, not including the hardware header; thus,
520  * this is typically 1500 bytes for Ethernet devices.
521  *
522  * If successful, returns 0 and stores the MTU size in '*mtup'.  On failure,
523  * returns a positive errno value and stores ETH_PAYLOAD_MAX (1500) in
524  * '*mtup'. */
525 int
526 netdev_get_mtu(const struct netdev *netdev, int *mtup)
527 {
528     int error = netdev_get_dev(netdev)->class->get_mtu(netdev, mtup);
529     if (error) {
530         VLOG_WARN_RL(&rl, "failed to retrieve MTU for network device %s: %s",
531                      netdev_get_name(netdev), strerror(error));
532         *mtup = ETH_PAYLOAD_MAX;
533     }
534     return error;
535 }
536
537 /* Returns the ifindex of 'netdev', if successful, as a positive number.  On
538  * failure, returns a negative errno value.
539  *
540  * The desired semantics of the ifindex value are a combination of those
541  * specified by POSIX for if_nametoindex() and by SNMP for ifIndex.  An ifindex
542  * value should be unique within a host and remain stable at least until
543  * reboot.  SNMP says an ifindex "ranges between 1 and the value of ifNumber"
544  * but many systems do not follow this rule anyhow.
545  */
546 int
547 netdev_get_ifindex(const struct netdev *netdev)
548 {
549     return netdev_get_dev(netdev)->class->get_ifindex(netdev);
550 }
551
552 /* Stores the features supported by 'netdev' into each of '*current',
553  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
554  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
555  * successful, otherwise a positive errno value.  On failure, all of the
556  * passed-in values are set to 0. */
557 int
558 netdev_get_features(struct netdev *netdev,
559                     uint32_t *current, uint32_t *advertised,
560                     uint32_t *supported, uint32_t *peer)
561 {
562     uint32_t dummy[4];
563     int error;
564
565     if (!current) {
566         current = &dummy[0];
567     }
568     if (!advertised) {
569         advertised = &dummy[1];
570     }
571     if (!supported) {
572         supported = &dummy[2];
573     }
574     if (!peer) {
575         peer = &dummy[3];
576     }
577
578     error = netdev_get_dev(netdev)->class->get_features(netdev, current,
579                                                         advertised, supported,
580                                                         peer);
581     if (error) {
582         *current = *advertised = *supported = *peer = 0;
583     }
584     return error;
585 }
586
587 /* Set the features advertised by 'netdev' to 'advertise'.  Returns 0 if
588  * successful, otherwise a positive errno value. */
589 int
590 netdev_set_advertisements(struct netdev *netdev, uint32_t advertise)
591 {
592     return (netdev_get_dev(netdev)->class->set_advertisements
593             ? netdev_get_dev(netdev)->class->set_advertisements(netdev,
594                                                                 advertise)
595             : EOPNOTSUPP);
596 }
597
598 /* If 'netdev' has an assigned IPv4 address, sets '*address' to that address
599  * and '*netmask' to its netmask and returns 0.  Otherwise, returns a positive
600  * errno value and sets '*address' to 0 (INADDR_ANY).
601  *
602  * The following error values have well-defined meanings:
603  *
604  *   - EADDRNOTAVAIL: 'netdev' has no assigned IPv4 address.
605  *
606  *   - EOPNOTSUPP: No IPv4 network stack attached to 'netdev'.
607  *
608  * 'address' or 'netmask' or both may be null, in which case the address or netmask
609  * is not reported. */
610 int
611 netdev_get_in4(const struct netdev *netdev,
612                struct in_addr *address_, struct in_addr *netmask_)
613 {
614     struct in_addr address;
615     struct in_addr netmask;
616     int error;
617
618     error = (netdev_get_dev(netdev)->class->get_in4
619              ? netdev_get_dev(netdev)->class->get_in4(netdev, &address,
620                                                       &netmask)
621              : EOPNOTSUPP);
622     if (address_) {
623         address_->s_addr = error ? 0 : address.s_addr;
624     }
625     if (netmask_) {
626         netmask_->s_addr = error ? 0 : netmask.s_addr;
627     }
628     return error;
629 }
630
631 /* Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
632  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
633  * positive errno value. */
634 int
635 netdev_set_in4(struct netdev *netdev, struct in_addr addr, struct in_addr mask)
636 {
637     return (netdev_get_dev(netdev)->class->set_in4
638             ? netdev_get_dev(netdev)->class->set_in4(netdev, addr, mask)
639             : EOPNOTSUPP);
640 }
641
642 /* Adds 'router' as a default IP gateway for the TCP/IP stack that corresponds
643  * to 'netdev'. */
644 int
645 netdev_add_router(struct netdev *netdev, struct in_addr router)
646 {
647     COVERAGE_INC(netdev_add_router);
648     return (netdev_get_dev(netdev)->class->add_router
649             ? netdev_get_dev(netdev)->class->add_router(netdev, router)
650             : EOPNOTSUPP);
651 }
652
653 /* Looks up the next hop for 'host' for the TCP/IP stack that corresponds to
654  * 'netdev'.  If a route cannot not be determined, sets '*next_hop' to 0,
655  * '*netdev_name' to null, and returns a positive errno value.  Otherwise, if a
656  * next hop is found, stores the next hop gateway's address (0 if 'host' is on
657  * a directly connected network) in '*next_hop' and a copy of the name of the
658  * device to reach 'host' in '*netdev_name', and returns 0.  The caller is
659  * responsible for freeing '*netdev_name' (by calling free()). */
660 int
661 netdev_get_next_hop(const struct netdev *netdev,
662                     const struct in_addr *host, struct in_addr *next_hop,
663                     char **netdev_name)
664 {
665     int error = (netdev_get_dev(netdev)->class->get_next_hop
666                  ? netdev_get_dev(netdev)->class->get_next_hop(host, next_hop,
667                                                                netdev_name)
668                  : EOPNOTSUPP);
669     if (error) {
670         next_hop->s_addr = 0;
671         *netdev_name = NULL;
672     }
673     return error;
674 }
675
676 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address and
677  * returns 0.  Otherwise, returns a positive errno value and sets '*in6' to
678  * all-zero-bits (in6addr_any).
679  *
680  * The following error values have well-defined meanings:
681  *
682  *   - EADDRNOTAVAIL: 'netdev' has no assigned IPv6 address.
683  *
684  *   - EOPNOTSUPP: No IPv6 network stack attached to 'netdev'.
685  *
686  * 'in6' may be null, in which case the address itself is not reported. */
687 int
688 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
689 {
690     struct in6_addr dummy;
691     int error;
692
693     error = (netdev_get_dev(netdev)->class->get_in6
694              ? netdev_get_dev(netdev)->class->get_in6(netdev, in6 ? in6
695                                                                   : &dummy)
696              : EOPNOTSUPP);
697     if (error && in6) {
698         memset(in6, 0, sizeof *in6);
699     }
700     return error;
701 }
702
703 /* On 'netdev', turns off the flags in 'off' and then turns on the flags in
704  * 'on'.  If 'permanent' is true, the changes will persist; otherwise, they
705  * will be reverted when 'netdev' is closed or the program exits.  Returns 0 if
706  * successful, otherwise a positive errno value. */
707 static int
708 do_update_flags(struct netdev *netdev, enum netdev_flags off,
709                 enum netdev_flags on, enum netdev_flags *old_flagsp,
710                 bool permanent)
711 {
712     enum netdev_flags old_flags;
713     int error;
714
715     error = netdev_get_dev(netdev)->class->update_flags(netdev, off & ~on, on,
716                                                         &old_flags);
717     if (error) {
718         VLOG_WARN_RL(&rl, "failed to %s flags for network device %s: %s",
719                      off || on ? "set" : "get", netdev_get_name(netdev),
720                      strerror(error));
721         old_flags = 0;
722     } else if ((off || on) && !permanent) {
723         enum netdev_flags new_flags = (old_flags & ~off) | on;
724         enum netdev_flags changed_flags = old_flags ^ new_flags;
725         if (changed_flags) {
726             if (!netdev->changed_flags) {
727                 netdev->save_flags = old_flags;
728             }
729             netdev->changed_flags |= changed_flags;
730         }
731     }
732     if (old_flagsp) {
733         *old_flagsp = old_flags;
734     }
735     return error;
736 }
737
738 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
739  * Returns 0 if successful, otherwise a positive errno value.  On failure,
740  * stores 0 into '*flagsp'. */
741 int
742 netdev_get_flags(const struct netdev *netdev_, enum netdev_flags *flagsp)
743 {
744     struct netdev *netdev = (struct netdev *) netdev_;
745     return do_update_flags(netdev, 0, 0, flagsp, false);
746 }
747
748 /* Sets the flags for 'netdev' to 'flags'.
749  * If 'permanent' is true, the changes will persist; otherwise, they
750  * will be reverted when 'netdev' is closed or the program exits.
751  * Returns 0 if successful, otherwise a positive errno value. */
752 int
753 netdev_set_flags(struct netdev *netdev, enum netdev_flags flags,
754                  bool permanent)
755 {
756     return do_update_flags(netdev, -1, flags, NULL, permanent);
757 }
758
759 /* Turns on the specified 'flags' on 'netdev'.
760  * If 'permanent' is true, the changes will persist; otherwise, they
761  * will be reverted when 'netdev' is closed or the program exits.
762  * Returns 0 if successful, otherwise a positive errno value. */
763 int
764 netdev_turn_flags_on(struct netdev *netdev, enum netdev_flags flags,
765                      bool permanent)
766 {
767     return do_update_flags(netdev, 0, flags, NULL, permanent);
768 }
769
770 /* Turns off the specified 'flags' on 'netdev'.
771  * If 'permanent' is true, the changes will persist; otherwise, they
772  * will be reverted when 'netdev' is closed or the program exits.
773  * Returns 0 if successful, otherwise a positive errno value. */
774 int
775 netdev_turn_flags_off(struct netdev *netdev, enum netdev_flags flags,
776                       bool permanent)
777 {
778     return do_update_flags(netdev, flags, 0, NULL, permanent);
779 }
780
781 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
782  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
783  * returns 0.  Otherwise, it returns a positive errno value; in particular,
784  * ENXIO indicates that there is no ARP table entry for 'ip' on 'netdev'. */
785 int
786 netdev_arp_lookup(const struct netdev *netdev,
787                   uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
788 {
789     int error = (netdev_get_dev(netdev)->class->arp_lookup
790                  ? netdev_get_dev(netdev)->class->arp_lookup(netdev, ip, mac)
791                  : EOPNOTSUPP);
792     if (error) {
793         memset(mac, 0, ETH_ADDR_LEN);
794     }
795     return error;
796 }
797
798 /* Sets 'carrier' to true if carrier is active (link light is on) on
799  * 'netdev'. */
800 int
801 netdev_get_carrier(const struct netdev *netdev, bool *carrier)
802 {
803     int error = (netdev_get_dev(netdev)->class->get_carrier
804                  ? netdev_get_dev(netdev)->class->get_carrier(netdev, carrier)
805                  : EOPNOTSUPP);
806     if (error) {
807         *carrier = false;
808     }
809     return error;
810 }
811
812 /* Retrieves current device stats for 'netdev'. */
813 int
814 netdev_get_stats(const struct netdev *netdev, struct netdev_stats *stats)
815 {
816     int error;
817
818     COVERAGE_INC(netdev_get_stats);
819     error = (netdev_get_dev(netdev)->class->get_stats
820              ? netdev_get_dev(netdev)->class->get_stats(netdev, stats)
821              : EOPNOTSUPP);
822     if (error) {
823         memset(stats, 0xff, sizeof *stats);
824     }
825     return error;
826 }
827
828 /* Attempts to set input rate limiting (policing) policy, such that up to
829  * 'kbits_rate' kbps of traffic is accepted, with a maximum accumulative burst
830  * size of 'kbits' kb. */
831 int
832 netdev_set_policing(struct netdev *netdev, uint32_t kbits_rate,
833                     uint32_t kbits_burst)
834 {
835     return (netdev_get_dev(netdev)->class->set_policing
836             ? netdev_get_dev(netdev)->class->set_policing(netdev, kbits_rate,
837                                                           kbits_burst)
838             : EOPNOTSUPP);
839 }
840
841 /* If 'netdev' is a VLAN network device (e.g. one created with vconfig(8)),
842  * sets '*vlan_vid' to the VLAN VID associated with that device and returns 0.
843  * Otherwise returns a errno value (specifically ENOENT if 'netdev_name' is the
844  * name of a network device that is not a VLAN device) and sets '*vlan_vid' to
845  * -1. */
846 int
847 netdev_get_vlan_vid(const struct netdev *netdev, int *vlan_vid)
848 {
849     int error = (netdev_get_dev(netdev)->class->get_vlan_vid
850                  ? netdev_get_dev(netdev)->class->get_vlan_vid(netdev, vlan_vid)
851                  : ENOENT);
852     if (error) {
853         *vlan_vid = 0;
854     }
855     return error;
856 }
857
858 /* Returns a network device that has 'in4' as its IP address, if one exists,
859  * otherwise a null pointer. */
860 struct netdev *
861 netdev_find_dev_by_in4(const struct in_addr *in4)
862 {
863     struct netdev *netdev;
864     struct svec dev_list;
865     size_t i;
866
867     netdev_enumerate(&dev_list);
868     for (i = 0; i < dev_list.n; i++) {
869         const char *name = dev_list.names[i];
870         struct in_addr dev_in4;
871
872         if (!netdev_open_default(name, &netdev)
873             && !netdev_get_in4(netdev, &dev_in4, NULL)
874             && dev_in4.s_addr == in4->s_addr) {
875             goto exit;
876         }
877         netdev_close(netdev);
878     }
879     netdev = NULL;
880
881 exit:
882     svec_destroy(&dev_list);
883     return netdev;
884 }
885 \f
886 /* Initializes 'netdev_dev' as a netdev device named 'name' of the
887  * specified 'class'.
888  *
889  * This function adds 'netdev_dev' to a netdev-owned shash, so it is
890  * very important that 'netdev_dev' only be freed after calling
891  * the refcount drops to zero.  */
892 void
893 netdev_dev_init(struct netdev_dev *netdev_dev, const char *name,
894                 const struct netdev_class *class)
895 {
896     assert(!shash_find(&netdev_dev_shash, name));
897
898     memset(netdev_dev, 0, sizeof *netdev_dev);
899     netdev_dev->class = class;
900     netdev_dev->name = xstrdup(name);
901     netdev_dev->node = shash_add(&netdev_dev_shash, name, netdev_dev);
902 }
903
904 /* Undoes the results of initialization.
905  *
906  * Normally this function does not need to be called as netdev_close has
907  * the same effect when the refcount drops to zero.
908  * However, it may be called by providers due to an error on creation
909  * that occurs after initialization.  It this case netdev_close() would
910  * never be called. */
911 void
912 netdev_dev_uninit(struct netdev_dev *netdev_dev, bool destroy)
913 {
914     char *name = netdev_dev->name;
915
916     assert(!netdev_dev->ref_cnt);
917
918     shash_delete(&netdev_dev_shash, netdev_dev->node);
919     update_device_args(netdev_dev, NULL);
920
921     if (destroy) {
922         netdev_dev->class->destroy(netdev_dev);
923     }
924     free(name);
925 }
926
927 /* Returns the class type of 'netdev_dev'.
928  *
929  * The caller must not free the returned value. */
930 const char *
931 netdev_dev_get_type(const struct netdev_dev *netdev_dev)
932 {
933     return netdev_dev->class->type;
934 }
935
936 /* Returns the name of 'netdev_dev'.
937  *
938  * The caller must not free the returned value. */
939 const char *
940 netdev_dev_get_name(const struct netdev_dev *netdev_dev)
941 {
942     return netdev_dev->name;
943 }
944
945 /* Returns the netdev_dev with 'name' or NULL if there is none.
946  *
947  * The caller must not free the returned value. */
948 struct netdev_dev *
949 netdev_dev_from_name(const char *name)
950 {
951     return shash_find_data(&netdev_dev_shash, name);
952 }
953
954 /* Fills 'device_list' with devices that match 'class'.
955  *
956  * The caller is responsible for initializing and destroying 'device_list'
957  * but the contained netdev_devs must not be freed. */
958 void
959 netdev_dev_get_devices(const struct netdev_class *class,
960                        struct shash *device_list)
961 {
962     struct shash_node *node;
963     SHASH_FOR_EACH (node, &netdev_dev_shash) {
964         struct netdev_dev *dev = node->data;
965
966         if (dev->class == class) {
967             shash_add(device_list, node->name, node->data);
968         }
969     }
970 }
971
972 /* Initializes 'netdev' as a instance of the netdev_dev.
973  *
974  * This function adds 'netdev' to a netdev-owned linked list, so it is very
975  * important that 'netdev' only be freed after calling netdev_close(). */
976 void
977 netdev_init(struct netdev *netdev, struct netdev_dev *netdev_dev)
978 {
979     memset(netdev, 0, sizeof *netdev);
980     netdev->netdev_dev = netdev_dev;
981     list_push_back(&netdev_list, &netdev->node);
982 }
983
984 /* Undoes the results of initialization.
985  *
986  * Normally this function only needs to be called from netdev_close().
987  * However, it may be called by providers due to an error on opening
988  * that occurs after initialization.  It this case netdev_close() would
989  * never be called. */
990 void
991 netdev_uninit(struct netdev *netdev, bool close)
992 {
993     /* Restore flags that we changed, if any. */
994     int error = restore_flags(netdev);
995     list_remove(&netdev->node);
996     if (error) {
997         VLOG_WARN("failed to restore network device flags on %s: %s",
998                   netdev_get_name(netdev), strerror(error));
999     }
1000
1001     if (close) {
1002         netdev_get_dev(netdev)->class->close(netdev);
1003     }
1004 }
1005
1006
1007 /* Returns the class type of 'netdev'.  
1008  *
1009  * The caller must not free the returned value. */
1010 const char *
1011 netdev_get_type(const struct netdev *netdev)
1012 {
1013     return netdev_get_dev(netdev)->class->type;
1014 }
1015
1016 struct netdev_dev *
1017 netdev_get_dev(const struct netdev *netdev)
1018 {
1019     return netdev->netdev_dev;
1020 }
1021
1022 /* Initializes 'notifier' as a netdev notifier for 'netdev', for which
1023  * notification will consist of calling 'cb', with auxiliary data 'aux'. */
1024 void
1025 netdev_notifier_init(struct netdev_notifier *notifier, struct netdev *netdev,
1026                      void (*cb)(struct netdev_notifier *), void *aux)
1027 {
1028     notifier->netdev = netdev;
1029     notifier->cb = cb;
1030     notifier->aux = aux;
1031 }
1032 \f
1033 /* Tracks changes in the status of a set of network devices. */
1034 struct netdev_monitor {
1035     struct shash polled_netdevs;
1036     struct shash changed_netdevs;
1037 };
1038
1039 /* Creates and returns a new structure for monitor changes in the status of
1040  * network devices. */
1041 struct netdev_monitor *
1042 netdev_monitor_create(void)
1043 {
1044     struct netdev_monitor *monitor = xmalloc(sizeof *monitor);
1045     shash_init(&monitor->polled_netdevs);
1046     shash_init(&monitor->changed_netdevs);
1047     return monitor;
1048 }
1049
1050 /* Destroys 'monitor'. */
1051 void
1052 netdev_monitor_destroy(struct netdev_monitor *monitor)
1053 {
1054     if (monitor) {
1055         struct shash_node *node;
1056
1057         SHASH_FOR_EACH (node, &monitor->polled_netdevs) {
1058             struct netdev_notifier *notifier = node->data;
1059             netdev_get_dev(notifier->netdev)->class->poll_remove(notifier);
1060         }
1061
1062         shash_destroy(&monitor->polled_netdevs);
1063         shash_destroy(&monitor->changed_netdevs);
1064         free(monitor);
1065     }
1066 }
1067
1068 static void
1069 netdev_monitor_cb(struct netdev_notifier *notifier)
1070 {
1071     struct netdev_monitor *monitor = notifier->aux;
1072     const char *name = netdev_get_name(notifier->netdev);
1073     if (!shash_find(&monitor->changed_netdevs, name)) {
1074         shash_add(&monitor->changed_netdevs, name, NULL);
1075     }
1076 }
1077
1078 /* Attempts to add 'netdev' as a netdev monitored by 'monitor'.  Returns 0 if
1079  * successful, otherwise a positive errno value.
1080  *
1081  * Adding a given 'netdev' to a monitor multiple times is equivalent to adding
1082  * it once. */
1083 int
1084 netdev_monitor_add(struct netdev_monitor *monitor, struct netdev *netdev)
1085 {
1086     const char *netdev_name = netdev_get_name(netdev);
1087     int error = 0;
1088     if (!shash_find(&monitor->polled_netdevs, netdev_name)
1089         && netdev_get_dev(netdev)->class->poll_add)
1090     {
1091         struct netdev_notifier *notifier;
1092         error = netdev_get_dev(netdev)->class->poll_add(netdev,
1093                                                         netdev_monitor_cb,
1094                                                         monitor, &notifier);
1095         if (!error) {
1096             assert(notifier->netdev == netdev);
1097             shash_add(&monitor->polled_netdevs, netdev_name, notifier);
1098         }
1099     }
1100     return error;
1101 }
1102
1103 /* Removes 'netdev' from the set of netdevs monitored by 'monitor'.  (This has
1104  * no effect if 'netdev' is not in the set of devices monitored by
1105  * 'monitor'.) */
1106 void
1107 netdev_monitor_remove(struct netdev_monitor *monitor, struct netdev *netdev)
1108 {
1109     const char *netdev_name = netdev_get_name(netdev);
1110     struct shash_node *node;
1111
1112     node = shash_find(&monitor->polled_netdevs, netdev_name);
1113     if (node) {
1114         /* Cancel future notifications. */
1115         struct netdev_notifier *notifier = node->data;
1116         netdev_get_dev(netdev)->class->poll_remove(notifier);
1117         shash_delete(&monitor->polled_netdevs, node);
1118
1119         /* Drop any pending notification. */
1120         node = shash_find(&monitor->changed_netdevs, netdev_name);
1121         if (node) {
1122             shash_delete(&monitor->changed_netdevs, node);
1123         }
1124     }
1125 }
1126
1127 /* Checks for changes to netdevs in the set monitored by 'monitor'.  If any of
1128  * the attributes (Ethernet address, carrier status, speed or peer-advertised
1129  * speed, flags, etc.) of a network device monitored by 'monitor' has changed,
1130  * sets '*devnamep' to the name of a device that has changed and returns 0.
1131  * The caller is responsible for freeing '*devnamep' (with free()).
1132  *
1133  * If no devices have changed, sets '*devnamep' to NULL and returns EAGAIN.
1134  */
1135 int
1136 netdev_monitor_poll(struct netdev_monitor *monitor, char **devnamep)
1137 {
1138     struct shash_node *node = shash_first(&monitor->changed_netdevs);
1139     if (!node) {
1140         *devnamep = NULL;
1141         return EAGAIN;
1142     } else {
1143         *devnamep = xstrdup(node->name);
1144         shash_delete(&monitor->changed_netdevs, node);
1145         return 0;
1146     }
1147 }
1148
1149 /* Registers with the poll loop to wake up from the next call to poll_block()
1150  * when netdev_monitor_poll(monitor) would indicate that a device has
1151  * changed. */
1152 void
1153 netdev_monitor_poll_wait(const struct netdev_monitor *monitor)
1154 {
1155     if (!shash_is_empty(&monitor->changed_netdevs)) {
1156         poll_immediate_wake();
1157     } else {
1158         /* XXX Nothing needed here for netdev_linux, but maybe other netdev
1159          * classes need help. */
1160     }
1161 }
1162 \f
1163 /* Restore the network device flags on 'netdev' to those that were active
1164  * before we changed them.  Returns 0 if successful, otherwise a positive
1165  * errno value.
1166  *
1167  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
1168 static int
1169 restore_flags(struct netdev *netdev)
1170 {
1171     if (netdev->changed_flags) {
1172         enum netdev_flags restore = netdev->save_flags & netdev->changed_flags;
1173         enum netdev_flags old_flags;
1174         return netdev_get_dev(netdev)->class->update_flags(netdev,
1175                                            netdev->changed_flags & ~restore,
1176                                            restore, &old_flags);
1177     }
1178     return 0;
1179 }
1180
1181 /* Close all netdevs on shutdown so they can do any needed cleanup such as
1182  * destroying devices, restoring flags, etc. */
1183 static void
1184 close_all_netdevs(void *aux UNUSED)
1185 {
1186     struct netdev *netdev, *next;
1187     LIST_FOR_EACH_SAFE(netdev, next, struct netdev, node, &netdev_list) {
1188         netdev_close(netdev);
1189     }
1190 }