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