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