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