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