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