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