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