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