netdev: Implement an abstract interface to network devices.
[sliver-openvswitch.git] / lib / netdev.c
1 /*
2  * Copyright (c) 2008, 2009 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 "list.h"
32 #include "netdev-provider.h"
33 #include "ofpbuf.h"
34 #include "packets.h"
35 #include "poll-loop.h"
36 #include "shash.h"
37 #include "svec.h"
38
39 #define THIS_MODULE VLM_netdev
40 #include "vlog.h"
41
42 static const struct netdev_class *netdev_classes[] = {
43     &netdev_linux_class,
44     &netdev_tap_class,
45 };
46 enum { N_NETDEV_CLASSES = ARRAY_SIZE(netdev_classes) };
47
48 /* All open network devices. */
49 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
50
51 /* This is set pretty low because we probably won't learn anything from the
52  * additional log messages. */
53 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
54
55 static void restore_all_flags(void *aux);
56 static int restore_flags(struct netdev *netdev);
57
58 /* Attempts to initialize the netdev module.  Returns 0 if successful,
59  * otherwise a positive errno value.
60  *
61  * Calling this function is optional.  If not called explicitly, it will
62  * automatically be called upon the first attempt to open a network device. */
63 int
64 netdev_initialize(void)
65 {
66     static int status = -1;
67     if (status < 0) {
68         int i;
69
70         fatal_signal_add_hook(restore_all_flags, NULL, true);
71
72         status = 0;
73         for (i = 0; i < N_NETDEV_CLASSES; i++) {
74             const struct netdev_class *class = netdev_classes[i];
75             if (class->init) {
76                 int retval = class->init();
77                 if (retval) {
78                     VLOG_ERR("failed to initialize %s network device "
79                              "class: %s", class->name, strerror(retval));
80                     if (!status) {
81                         status = retval;
82                     }
83                 }
84             }
85         }
86     }
87     return status;
88 }
89
90 /* Performs periodic work needed by all the various kinds of netdevs.
91  *
92  * If your program opens any netdevs, it must call this function within its
93  * main poll loop. */
94 void
95 netdev_run(void)
96 {
97     int i;
98     for (i = 0; i < N_NETDEV_CLASSES; i++) {
99         const struct netdev_class *class = netdev_classes[i];
100         if (class->run) {
101             class->run();
102         }
103     }
104 }
105
106 /* Arranges for poll_block() to wake up when netdev_run() needs to be called.
107  *
108  * If your program opens any netdevs, it must call this function within its
109  * main poll loop. */
110 void
111 netdev_wait(void)
112 {
113     int i;
114     for (i = 0; i < N_NETDEV_CLASSES; i++) {
115         const struct netdev_class *class = netdev_classes[i];
116         if (class->wait) {
117             class->wait();
118         }
119     }
120 }
121
122 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
123  * successful, otherwise a positive errno value.  On success, sets '*netdevp'
124  * to the new network device, otherwise to null.
125  *
126  * 'ethertype' may be a 16-bit Ethernet protocol value in host byte order to
127  * capture frames of that type received on the device.  It may also be one of
128  * the 'enum netdev_pseudo_ethertype' values to receive frames in one of those
129  * categories. */
130 int
131 netdev_open(const char *name_, int ethertype, struct netdev **netdevp)
132 {
133     char *name = xstrdup(name_);
134     char *prefix, *suffix, *colon;
135     struct netdev *netdev = NULL;
136     int error;
137     int i;
138
139     error = netdev_initialize();
140     if (error) {
141         return error;
142     }
143
144     colon = strchr(name, ':');
145     if (colon) {
146         *colon = '\0';
147         prefix = name;
148         suffix = colon + 1;
149     } else {
150         prefix = "";
151         suffix = name;
152     }
153
154     for (i = 0; i < N_NETDEV_CLASSES; i++) {
155         const struct netdev_class *class = netdev_classes[i];
156         if (!strcmp(prefix, class->prefix)) {
157             error = class->open(name_, suffix, ethertype, &netdev);
158             goto exit;
159         }
160     }
161     error = EAFNOSUPPORT;
162
163 exit:
164     *netdevp = error ? NULL : netdev;
165     return error;
166 }
167
168 /* Closes and destroys 'netdev'. */
169 void
170 netdev_close(struct netdev *netdev)
171 {
172     if (netdev) {
173         char *name;
174         int error;
175
176         /* Restore flags that we changed, if any. */
177         fatal_signal_block();
178         error = restore_flags(netdev);
179         list_remove(&netdev->node);
180         fatal_signal_unblock();
181         if (error) {
182             VLOG_WARN("failed to restore network device flags on %s: %s",
183                       netdev->name, strerror(error));
184         }
185
186         /* Free. */
187         name = netdev->name;
188         netdev->class->close(netdev);
189         free(name);
190     }
191 }
192
193 /* Returns true if a network device named 'name' exists and may be opened,
194  * otherwise false. */
195 bool
196 netdev_exists(const char *name)
197 {
198     struct netdev *netdev;
199     int error;
200
201     error = netdev_open(name, NETDEV_ETH_TYPE_NONE, &netdev);
202     if (!error) {
203         netdev_close(netdev);
204         return true;
205     } else {
206         if (error != ENODEV) {
207             VLOG_WARN("failed to open network device %s: %s",
208                       name, strerror(error));
209         }
210         return false;
211     }
212 }
213
214 /* Initializes 'svec' with a list of the names of all known network devices. */
215 int
216 netdev_enumerate(struct svec *svec)
217 {
218     int error;
219     int i;
220
221     svec_init(svec);
222
223     error = netdev_initialize();
224     if (error) {
225         return error;
226     }
227
228     error = 0;
229     for (i = 0; i < N_NETDEV_CLASSES; i++) {
230         const struct netdev_class *class = netdev_classes[i];
231         if (class->enumerate) {
232             int retval = class->enumerate(svec);
233             if (retval) {
234                 VLOG_WARN("failed to enumerate %s network devices: %s",
235                           class->name, strerror(retval));
236                 if (!error) {
237                     error = retval;
238                 }
239             }
240         }
241     }
242     return error;
243 }
244
245 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
246  * must have initialized with sufficient room for the packet.  The space
247  * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
248  * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
249  * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
250  * need not be included.)
251  *
252  * If a packet is successfully retrieved, returns 0.  In this case 'buffer' is
253  * guaranteed to contain at least ETH_TOTAL_MIN bytes.  Otherwise, returns a
254  * positive errno value.  Returns EAGAIN immediately if no packet is ready to
255  * be returned.
256  */
257 int
258 netdev_recv(struct netdev *netdev, struct ofpbuf *buffer)
259 {
260     int retval;
261
262     assert(buffer->size == 0);
263     assert(ofpbuf_tailroom(buffer) >= ETH_TOTAL_MIN);
264
265     retval = netdev->class->recv(netdev,
266                                  buffer->data, ofpbuf_tailroom(buffer));
267     if (retval >= 0) {
268         COVERAGE_INC(netdev_received);
269         buffer->size += retval;
270         if (buffer->size < ETH_TOTAL_MIN) {
271             ofpbuf_put_zeros(buffer, ETH_TOTAL_MIN - buffer->size);
272         }
273         return 0;
274     } else {
275         return -retval;
276     }
277 }
278
279 /* Registers with the poll loop to wake up from the next call to poll_block()
280  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
281 void
282 netdev_recv_wait(struct netdev *netdev)
283 {
284     netdev->class->recv_wait(netdev);
285 }
286
287 /* Discards all packets waiting to be received from 'netdev'. */
288 int
289 netdev_drain(struct netdev *netdev)
290 {
291     return netdev->class->drain(netdev);
292 }
293
294 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
295  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
296  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
297  * the packet is too big or too small to transmit on the device.
298  *
299  * The caller retains ownership of 'buffer' in all cases.
300  *
301  * The kernel maintains a packet transmission queue, so the caller is not
302  * expected to do additional queuing of packets. */
303 int
304 netdev_send(struct netdev *netdev, const struct ofpbuf *buffer)
305 {
306     int error = netdev->class->send(netdev, buffer->data, buffer->size);
307     if (!error) {
308         COVERAGE_INC(netdev_sent);
309     }
310     return error;
311 }
312
313 /* Registers with the poll loop to wake up from the next call to poll_block()
314  * when the packet transmission queue has sufficient room to transmit a packet
315  * with netdev_send().
316  *
317  * The kernel maintains a packet transmission queue, so the client is not
318  * expected to do additional queuing of packets.  Thus, this function is
319  * unlikely to ever be used.  It is included for completeness. */
320 void
321 netdev_send_wait(struct netdev *netdev)
322 {
323     return netdev->class->send_wait(netdev);
324 }
325
326 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
327  * otherwise a positive errno value. */
328 int
329 netdev_set_etheraddr(struct netdev *netdev, const uint8_t mac[ETH_ADDR_LEN])
330 {
331     return netdev->class->set_etheraddr(netdev, mac);
332 }
333
334 /* Retrieves 'netdev''s MAC address.  If successful, returns 0 and copies the
335  * the MAC address into 'mac'.  On failure, returns a positive errno value and
336  * clears 'mac' to all-zeros. */
337 int
338 netdev_get_etheraddr(const struct netdev *netdev, uint8_t mac[ETH_ADDR_LEN])
339 {
340     return netdev->class->get_etheraddr(netdev, mac);
341 }
342
343 /* Returns the name of the network device that 'netdev' represents,
344  * e.g. "eth0".  The caller must not modify or free the returned string. */
345 const char *
346 netdev_get_name(const struct netdev *netdev)
347 {
348     return netdev->name;
349 }
350
351 /* Retrieves the MTU of 'netdev'.  The MTU is the maximum size of transmitted
352  * (and received) packets, in bytes, not including the hardware header; thus,
353  * this is typically 1500 bytes for Ethernet devices.
354  *
355  * If successful, returns 0 and stores the MTU size in '*mtup'.  On failure,
356  * returns a positive errno value and stores ETH_PAYLOAD_MAX (1500) in
357  * '*mtup'. */
358 int
359 netdev_get_mtu(const struct netdev *netdev, int *mtup)
360 {
361     int error = netdev->class->get_mtu(netdev, mtup);
362     if (error) {
363         VLOG_WARN_RL(&rl, "failed to retrieve MTU for network device %s: %s",
364                      netdev_get_name(netdev), strerror(error));
365         *mtup = ETH_PAYLOAD_MAX;
366     }
367     return error;
368 }
369
370 /* Stores the features supported by 'netdev' into each of '*current',
371  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
372  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
373  * successful, otherwise a positive errno value.  On failure, all of the
374  * passed-in values are set to 0. */
375 int
376 netdev_get_features(struct netdev *netdev,
377                     uint32_t *current, uint32_t *advertised,
378                     uint32_t *supported, uint32_t *peer)
379 {
380     uint32_t dummy[4];
381     return netdev->class->get_features(netdev,
382                                        current ? current : &dummy[0],
383                                        advertised ? advertised : &dummy[1],
384                                        supported ? supported : &dummy[2],
385                                        peer ? peer : &dummy[3]);
386 }
387
388 /* Set the features advertised by 'netdev' to 'advertise'.  Returns 0 if
389  * successful, otherwise a positive errno value. */
390 int
391 netdev_set_advertisements(struct netdev *netdev, uint32_t advertise)
392 {
393     return (netdev->class->set_advertisements
394             ? netdev->class->set_advertisements(netdev, advertise)
395             : EOPNOTSUPP);
396 }
397
398 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address and
399  * returns 0.  Otherwise, returns a positive errno value and sets '*in4' to 0
400  * (INADDR_ANY).
401  *
402  * The following error values have well-defined meanings:
403  *
404  *   - EADDRNOTAVAIL: 'netdev' has no assigned IPv4 address.
405  *
406  *   - EOPNOTSUPP: No IPv4 network stack attached to 'netdev'.
407  *
408  * 'in4' may be null, in which case the address itself is not reported. */
409 int
410 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
411 {
412     struct in_addr dummy;
413     int error;
414
415     error = (netdev->class->get_in4
416              ? netdev->class->get_in4(netdev, in4 ? in4 : &dummy)
417              : EOPNOTSUPP);
418     if (error && in4) {
419         in4->s_addr = 0;
420     }
421     return error;
422 }
423
424 /* Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
425  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
426  * positive errno value. */
427 int
428 netdev_set_in4(struct netdev *netdev, struct in_addr addr, struct in_addr mask)
429 {
430     return (netdev->class->set_in4
431             ? netdev->class->set_in4(netdev, addr, mask)
432             : EOPNOTSUPP);
433 }
434
435 /* Adds 'router' as a default IP gateway for the TCP/IP stack that corresponds
436  * to 'netdev'. */
437 int
438 netdev_add_router(struct netdev *netdev, struct in_addr router)
439 {
440     COVERAGE_INC(netdev_add_router);
441     return (netdev->class->add_router
442             ? netdev->class->add_router(netdev, router)
443             : EOPNOTSUPP);
444 }
445
446 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address and
447  * returns 0.  Otherwise, returns a positive errno value and sets '*in6' to
448  * all-zero-bits (in6addr_any).
449  *
450  * The following error values have well-defined meanings:
451  *
452  *   - EADDRNOTAVAIL: 'netdev' has no assigned IPv6 address.
453  *
454  *   - EOPNOTSUPP: No IPv6 network stack attached to 'netdev'.
455  *
456  * 'in6' may be null, in which case the address itself is not reported. */
457 int
458 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
459 {
460     struct in6_addr dummy;
461     int error;
462
463     error = (netdev->class->get_in6
464              ? netdev->class->get_in6(netdev, in6 ? in6 : &dummy)
465              : EOPNOTSUPP);
466     if (error && in6) {
467         memset(in6, 0, sizeof *in6);
468     }
469     return error;
470 }
471
472 /* On 'netdev', turns off the flags in 'off' and then turns on the flags in
473  * 'on'.  If 'permanent' is true, the changes will persist; otherwise, they
474  * will be reverted when 'netdev' is closed or the program exits.  Returns 0 if
475  * successful, otherwise a positive errno value. */
476 static int
477 do_update_flags(struct netdev *netdev, enum netdev_flags off,
478                 enum netdev_flags on, enum netdev_flags *old_flagsp,
479                 bool permanent)
480 {
481     enum netdev_flags old_flags;
482     int error;
483
484     error = netdev->class->update_flags(netdev, off & ~on, on, &old_flags);
485     if (error) {
486         VLOG_WARN_RL(&rl, "failed to %s flags for network device %s: %s",
487                      off || on ? "set" : "get", netdev_get_name(netdev),
488                      strerror(error));
489         old_flags = 0;
490     } else if ((off || on) && !permanent) {
491         enum netdev_flags new_flags = (old_flags & ~off) | on;
492         enum netdev_flags changed_flags = old_flags ^ new_flags;
493         if (changed_flags) {
494             if (!netdev->changed_flags) {
495                 netdev->save_flags = old_flags;
496             }
497             netdev->changed_flags |= changed_flags;
498         }
499     }
500     if (old_flagsp) {
501         *old_flagsp = old_flags;
502     }
503     return error;
504 }
505
506 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
507  * Returns 0 if successful, otherwise a positive errno value.  On failure,
508  * stores 0 into '*flagsp'. */
509 int
510 netdev_get_flags(const struct netdev *netdev_, enum netdev_flags *flagsp)
511 {
512     struct netdev *netdev = (struct netdev *) netdev_;
513     return do_update_flags(netdev, 0, 0, flagsp, false);
514 }
515
516 /* Sets the flags for 'netdev' to 'flags'.
517  * If 'permanent' is true, the changes will persist; otherwise, they
518  * will be reverted when 'netdev' is closed or the program exits.
519  * Returns 0 if successful, otherwise a positive errno value. */
520 int
521 netdev_set_flags(struct netdev *netdev, enum netdev_flags flags,
522                  bool permanent)
523 {
524     return do_update_flags(netdev, -1, flags, NULL, permanent);
525 }
526
527 /* Turns on the specified 'flags' on 'netdev'.
528  * If 'permanent' is true, the changes will persist; otherwise, they
529  * will be reverted when 'netdev' is closed or the program exits.
530  * Returns 0 if successful, otherwise a positive errno value. */
531 int
532 netdev_turn_flags_on(struct netdev *netdev, enum netdev_flags flags,
533                      bool permanent)
534 {
535     return do_update_flags(netdev, 0, flags, NULL, permanent);
536 }
537
538 /* Turns off the specified 'flags' on 'netdev'.
539  * If 'permanent' is true, the changes will persist; otherwise, they
540  * will be reverted when 'netdev' is closed or the program exits.
541  * Returns 0 if successful, otherwise a positive errno value. */
542 int
543 netdev_turn_flags_off(struct netdev *netdev, enum netdev_flags flags,
544                       bool permanent)
545 {
546     return do_update_flags(netdev, flags, 0, NULL, permanent);
547 }
548
549 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
550  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
551  * returns 0.  Otherwise, it returns a positive errno value; in particular,
552  * ENXIO indicates that there is no ARP table entry for 'ip' on 'netdev'. */
553 int
554 netdev_arp_lookup(const struct netdev *netdev,
555                   uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
556 {
557     int error = (netdev->class->arp_lookup
558                  ? netdev->class->arp_lookup(netdev, ip, mac)
559                  : EOPNOTSUPP);
560     if (error) {
561         memset(mac, 0, ETH_ADDR_LEN);
562     }
563     return error;
564 }
565
566 /* Sets 'carrier' to true if carrier is active (link light is on) on
567  * 'netdev'. */
568 int
569 netdev_get_carrier(const struct netdev *netdev, bool *carrier)
570 {
571     int error = (netdev->class->get_carrier
572                  ? netdev->class->get_carrier(netdev, carrier)
573                  : EOPNOTSUPP);
574     if (error) {
575         *carrier = false;
576     }
577     return error;
578 }
579
580 /* Retrieves current device stats for 'netdev'. */
581 int
582 netdev_get_stats(const struct netdev *netdev, struct netdev_stats *stats)
583 {
584     int error;
585
586     COVERAGE_INC(netdev_get_stats);
587     error = (netdev->class->get_stats
588              ? netdev->class->get_stats(netdev, stats)
589              : EOPNOTSUPP);
590     if (error) {
591         memset(stats, 0xff, sizeof *stats);
592     }
593     return error;
594 }
595
596 /* Attempts to set input rate limiting (policing) policy, such that up to
597  * 'kbits_rate' kbps of traffic is accepted, with a maximum accumulative burst
598  * size of 'kbits' kb. */
599 int
600 netdev_set_policing(struct netdev *netdev, uint32_t kbits_rate,
601                     uint32_t kbits_burst)
602 {
603     return (netdev->class->set_policing
604             ? netdev->class->set_policing(netdev, kbits_rate, kbits_burst)
605             : EOPNOTSUPP);
606 }
607
608 /* If 'netdev' is a VLAN network device (e.g. one created with vconfig(8)),
609  * sets '*vlan_vid' to the VLAN VID associated with that device and returns 0.
610  * Otherwise returns a errno value (specifically ENOENT if 'netdev_name' is the
611  * name of a network device that is not a VLAN device) and sets '*vlan_vid' to
612  * -1. */
613 int
614 netdev_get_vlan_vid(const struct netdev *netdev, int *vlan_vid)
615 {
616     int error = (netdev->class->get_vlan_vid
617                  ? netdev->class->get_vlan_vid(netdev, vlan_vid)
618                  : ENOENT);
619     if (error) {
620         *vlan_vid = 0;
621     }
622     return error;
623 }
624
625 /* Returns a network device that has 'in4' as its IP address, if one exists,
626  * otherwise a null pointer. */
627 struct netdev *
628 netdev_find_dev_by_in4(const struct in_addr *in4)
629 {
630     struct netdev *netdev;
631     struct svec dev_list;
632     size_t i;
633
634     netdev_enumerate(&dev_list);
635     for (i = 0; i < dev_list.n; i++) {
636         const char *name = dev_list.names[i];
637         struct in_addr dev_in4;
638
639         if (!netdev_open(name, NETDEV_ETH_TYPE_NONE, &netdev)
640             && !netdev_get_in4(netdev, &dev_in4)
641             && dev_in4.s_addr == in4->s_addr) {
642             goto exit;
643         }
644         netdev_close(netdev);
645     }
646     netdev = NULL;
647
648 exit:
649     svec_destroy(&dev_list);
650     return netdev;
651 }
652 \f
653 /* Initializes 'netdev' as a netdev named 'name' of the specified 'class'.
654  *
655  * This function adds 'netdev' to a netdev-owned linked list, so it is very
656  * important that 'netdev' only be freed after calling netdev_close(). */
657 void
658 netdev_init(struct netdev *netdev, const char *name,
659             const struct netdev_class *class)
660 {
661     netdev->class = class;
662     netdev->name = xstrdup(name);
663     netdev->save_flags = 0;
664     netdev->changed_flags = 0;
665     list_push_back(&netdev_list, &netdev->node);
666 }
667
668 /* Initializes 'notifier' as a netdev notifier for 'netdev', for which
669  * notification will consist of calling 'cb', with auxiliary data 'aux'. */
670 void
671 netdev_notifier_init(struct netdev_notifier *notifier, struct netdev *netdev,
672                      void (*cb)(struct netdev_notifier *), void *aux)
673 {
674     notifier->netdev = netdev;
675     notifier->cb = cb;
676     notifier->aux = aux;
677 }
678 \f
679 /* Tracks changes in the status of a set of network devices. */
680 struct netdev_monitor {
681     struct shash polled_netdevs;
682     struct shash changed_netdevs;
683 };
684
685 /* Creates and returns a new structure for monitor changes in the status of
686  * network devices. */
687 struct netdev_monitor *
688 netdev_monitor_create(void)
689 {
690     struct netdev_monitor *monitor = xmalloc(sizeof *monitor);
691     shash_init(&monitor->polled_netdevs);
692     shash_init(&monitor->changed_netdevs);
693     return monitor;
694 }
695
696 /* Destroys 'monitor'. */
697 void
698 netdev_monitor_destroy(struct netdev_monitor *monitor)
699 {
700     if (monitor) {
701         struct shash_node *node;
702
703         SHASH_FOR_EACH (node, &monitor->polled_netdevs) {
704             struct netdev_notifier *notifier = node->data;
705             notifier->netdev->class->poll_remove(notifier);
706         }
707
708         shash_destroy(&monitor->polled_netdevs);
709         shash_destroy(&monitor->changed_netdevs);
710         free(monitor);
711     }
712 }
713
714 static void
715 netdev_monitor_cb(struct netdev_notifier *notifier)
716 {
717     struct netdev_monitor *monitor = notifier->aux;
718     const char *name = netdev_get_name(notifier->netdev);
719     if (!shash_find(&monitor->changed_netdevs, name)) {
720         shash_add(&monitor->changed_netdevs, name, NULL);
721     }
722 }
723
724 /* Attempts to add 'netdev' as a netdev monitored by 'monitor'.  Returns 0 if
725  * successful, otherwise a positive errno value.
726  *
727  * Adding a given 'netdev' to a monitor multiple times is equivalent to adding
728  * it once. */
729 int
730 netdev_monitor_add(struct netdev_monitor *monitor, struct netdev *netdev)
731 {
732     const char *netdev_name = netdev_get_name(netdev);
733     int error = 0;
734     if (!shash_find(&monitor->polled_netdevs, netdev_name)
735         && netdev->class->poll_add)
736     {
737         struct netdev_notifier *notifier;
738         error = netdev->class->poll_add(netdev, netdev_monitor_cb, monitor,
739                                         &notifier);
740         if (!error) {
741             assert(notifier->netdev == netdev);
742             shash_add(&monitor->polled_netdevs, netdev_name, notifier);
743         }
744     }
745     return error;
746 }
747
748 /* Removes 'netdev' from the set of netdevs monitored by 'monitor'.  (This has
749  * no effect if 'netdev' is not in the set of devices monitored by
750  * 'monitor'.) */
751 void
752 netdev_monitor_remove(struct netdev_monitor *monitor, struct netdev *netdev)
753 {
754     const char *netdev_name = netdev_get_name(netdev);
755     struct shash_node *node;
756
757     node = shash_find(&monitor->polled_netdevs, netdev_name);
758     if (node) {
759         /* Cancel future notifications. */
760         struct netdev_notifier *notifier = node->data;
761         netdev->class->poll_remove(notifier);
762         shash_delete(&monitor->polled_netdevs, node);
763
764         /* Drop any pending notification. */
765         node = shash_find(&monitor->changed_netdevs, netdev_name);
766         if (node) {
767             shash_delete(&monitor->changed_netdevs, node);
768         }
769     }
770 }
771
772 /* Checks for changes to netdevs in the set monitored by 'monitor'.  If any of
773  * the attributes (Ethernet address, carrier status, speed or peer-advertised
774  * speed, flags, etc.) of a network device monitored by 'monitor' has changed,
775  * sets '*devnamep' to the name of a device that has changed and returns 0.
776  * The caller is responsible for freeing '*devnamep' (with free()).
777  *
778  * If no devices have changed, sets '*devnamep' to NULL and returns EAGAIN.
779  */
780 int
781 netdev_monitor_poll(struct netdev_monitor *monitor, char **devnamep)
782 {
783     struct shash_node *node = shash_first(&monitor->changed_netdevs);
784     if (!node) {
785         *devnamep = NULL;
786         return EAGAIN;
787     } else {
788         *devnamep = xstrdup(node->name);
789         shash_delete(&monitor->changed_netdevs, node);
790         return 0;
791     }
792 }
793
794 /* Registers with the poll loop to wake up from the next call to poll_block()
795  * when netdev_monitor_poll(monitor) would indicate that a device has
796  * changed. */
797 void
798 netdev_monitor_poll_wait(const struct netdev_monitor *monitor)
799 {
800     if (!shash_is_empty(&monitor->changed_netdevs)) {
801         poll_immediate_wake();
802     } else {
803         /* XXX Nothing needed here for netdev_linux, but maybe other netdev
804          * classes need help. */
805     }
806 }
807 \f
808 /* Restore the network device flags on 'netdev' to those that were active
809  * before we changed them.  Returns 0 if successful, otherwise a positive
810  * errno value.
811  *
812  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
813 static int
814 restore_flags(struct netdev *netdev)
815 {
816     if (netdev->changed_flags) {
817         enum netdev_flags restore = netdev->save_flags & netdev->changed_flags;
818         enum netdev_flags old_flags;
819         return netdev->class->update_flags(netdev,
820                                            netdev->changed_flags & ~restore,
821                                            restore, &old_flags);
822     }
823     return 0;
824 }
825
826 /* Retores all the flags on all network devices that we modified.  Called from
827  * a signal handler, so it does not attempt to report error conditions. */
828 static void
829 restore_all_flags(void *aux UNUSED)
830 {
831     struct netdev *netdev;
832     LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
833         restore_flags(netdev);
834     }
835 }