netdev: Allow recv, recv_wait, drain, send, send_wait to be null.
[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 OVS_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 *netdev_class = node->data;
93         if (netdev_class->run) {
94             netdev_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 *netdev_class = node->data;
109         if (netdev_class->wait) {
110             netdev_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  * Some network devices may not implement support for this function.  In such
477  * cases this function will always return EOPNOTSUPP.
478  */
479 int
480 netdev_recv(struct netdev *netdev, struct ofpbuf *buffer)
481 {
482     int (*recv)(struct netdev *, void *, size_t);
483     int retval;
484
485     assert(buffer->size == 0);
486     assert(ofpbuf_tailroom(buffer) >= ETH_TOTAL_MIN);
487
488     recv = netdev_get_dev(netdev)->netdev_class->recv;
489     retval = (recv
490               ? (recv)(netdev, buffer->data, ofpbuf_tailroom(buffer))
491               : -EOPNOTSUPP);
492     if (retval >= 0) {
493         COVERAGE_INC(netdev_received);
494         buffer->size += retval;
495         if (buffer->size < ETH_TOTAL_MIN) {
496             ofpbuf_put_zeros(buffer, ETH_TOTAL_MIN - buffer->size);
497         }
498         return 0;
499     } else {
500         return -retval;
501     }
502 }
503
504 /* Registers with the poll loop to wake up from the next call to poll_block()
505  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
506 void
507 netdev_recv_wait(struct netdev *netdev)
508 {
509     void (*recv_wait)(struct netdev *);
510
511     recv_wait = netdev_get_dev(netdev)->netdev_class->recv_wait;
512     if (recv_wait) {
513         recv_wait(netdev);
514     }
515 }
516
517 /* Discards all packets waiting to be received from 'netdev'. */
518 int
519 netdev_drain(struct netdev *netdev)
520 {
521     int (*drain)(struct netdev *);
522
523     drain = netdev_get_dev(netdev)->netdev_class->drain;
524     return drain ? drain(netdev) : 0;
525 }
526
527 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
528  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
529  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
530  * the packet is too big or too small to transmit on the device.
531  *
532  * The caller retains ownership of 'buffer' in all cases.
533  *
534  * The kernel maintains a packet transmission queue, so the caller is not
535  * expected to do additional queuing of packets.
536  *
537  * Some network devices may not implement support for this function.  In such
538  * cases this function will always return EOPNOTSUPP. */
539 int
540 netdev_send(struct netdev *netdev, const struct ofpbuf *buffer)
541 {
542     int (*send)(struct netdev *, const void *, size_t);
543     int error;
544
545     send = netdev_get_dev(netdev)->netdev_class->send;
546     error = send ? (send)(netdev, buffer->data, buffer->size) : EOPNOTSUPP;
547     if (!error) {
548         COVERAGE_INC(netdev_sent);
549     }
550     return error;
551 }
552
553 /* Registers with the poll loop to wake up from the next call to poll_block()
554  * when the packet transmission queue has sufficient room to transmit a packet
555  * with netdev_send().
556  *
557  * The kernel maintains a packet transmission queue, so the client is not
558  * expected to do additional queuing of packets.  Thus, this function is
559  * unlikely to ever be used.  It is included for completeness. */
560 void
561 netdev_send_wait(struct netdev *netdev)
562 {
563     void (*send_wait)(struct netdev *);
564
565     send_wait = netdev_get_dev(netdev)->netdev_class->send_wait;
566     if (send_wait) {
567         send_wait(netdev);
568     }
569 }
570
571 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
572  * otherwise a positive errno value. */
573 int
574 netdev_set_etheraddr(struct netdev *netdev, const uint8_t mac[ETH_ADDR_LEN])
575 {
576     return netdev_get_dev(netdev)->netdev_class->set_etheraddr(netdev, mac);
577 }
578
579 /* Retrieves 'netdev''s MAC address.  If successful, returns 0 and copies the
580  * the MAC address into 'mac'.  On failure, returns a positive errno value and
581  * clears 'mac' to all-zeros. */
582 int
583 netdev_get_etheraddr(const struct netdev *netdev, uint8_t mac[ETH_ADDR_LEN])
584 {
585     return netdev_get_dev(netdev)->netdev_class->get_etheraddr(netdev, mac);
586 }
587
588 /* Returns the name of the network device that 'netdev' represents,
589  * e.g. "eth0".  The caller must not modify or free the returned string. */
590 const char *
591 netdev_get_name(const struct netdev *netdev)
592 {
593     return netdev_get_dev(netdev)->name;
594 }
595
596 /* Retrieves the MTU of 'netdev'.  The MTU is the maximum size of transmitted
597  * (and received) packets, in bytes, not including the hardware header; thus,
598  * this is typically 1500 bytes for Ethernet devices.
599  *
600  * If successful, returns 0 and stores the MTU size in '*mtup'.  On failure,
601  * returns a positive errno value and stores ETH_PAYLOAD_MAX (1500) in
602  * '*mtup'. */
603 int
604 netdev_get_mtu(const struct netdev *netdev, int *mtup)
605 {
606     int error = netdev_get_dev(netdev)->netdev_class->get_mtu(netdev, mtup);
607     if (error) {
608         VLOG_WARN_RL(&rl, "failed to retrieve MTU for network device %s: %s",
609                      netdev_get_name(netdev), strerror(error));
610         *mtup = ETH_PAYLOAD_MAX;
611     }
612     return error;
613 }
614
615 /* Returns the ifindex of 'netdev', if successful, as a positive number.  On
616  * failure, returns a negative errno value.
617  *
618  * The desired semantics of the ifindex value are a combination of those
619  * specified by POSIX for if_nametoindex() and by SNMP for ifIndex.  An ifindex
620  * value should be unique within a host and remain stable at least until
621  * reboot.  SNMP says an ifindex "ranges between 1 and the value of ifNumber"
622  * but many systems do not follow this rule anyhow.
623  */
624 int
625 netdev_get_ifindex(const struct netdev *netdev)
626 {
627     return netdev_get_dev(netdev)->netdev_class->get_ifindex(netdev);
628 }
629
630 /* Stores the features supported by 'netdev' into each of '*current',
631  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
632  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
633  * successful, otherwise a positive errno value.  On failure, all of the
634  * passed-in values are set to 0. */
635 int
636 netdev_get_features(struct netdev *netdev,
637                     uint32_t *current, uint32_t *advertised,
638                     uint32_t *supported, uint32_t *peer)
639 {
640     uint32_t dummy[4];
641     int error;
642
643     if (!current) {
644         current = &dummy[0];
645     }
646     if (!advertised) {
647         advertised = &dummy[1];
648     }
649     if (!supported) {
650         supported = &dummy[2];
651     }
652     if (!peer) {
653         peer = &dummy[3];
654     }
655
656     error = netdev_get_dev(netdev)->netdev_class->get_features(netdev, current,
657             advertised, supported, peer);
658     if (error) {
659         *current = *advertised = *supported = *peer = 0;
660     }
661     return error;
662 }
663
664 /* Returns the maximum speed of a network connection that has the "enum
665  * ofp_port_features" bits in 'features', in bits per second.  If no bits that
666  * indicate a speed are set in 'features', assumes 100Mbps. */
667 uint64_t
668 netdev_features_to_bps(uint32_t features)
669 {
670     enum {
671         F_10000MB = OFPPF_10GB_FD,
672         F_1000MB = OFPPF_1GB_HD | OFPPF_1GB_FD,
673         F_100MB = OFPPF_100MB_HD | OFPPF_100MB_FD,
674         F_10MB = OFPPF_10MB_HD | OFPPF_10MB_FD
675     };
676
677     return (  features & F_10000MB  ? UINT64_C(10000000000)
678             : features & F_1000MB   ? UINT64_C(1000000000)
679             : features & F_100MB    ? UINT64_C(100000000)
680             : features & F_10MB     ? UINT64_C(10000000)
681                                     : UINT64_C(100000000));
682 }
683
684 /* Returns true if any of the "enum ofp_port_features" bits that indicate a
685  * full-duplex link are set in 'features', otherwise false. */
686 bool
687 netdev_features_is_full_duplex(uint32_t features)
688 {
689     return (features & (OFPPF_10MB_FD | OFPPF_100MB_FD | OFPPF_1GB_FD
690                         | OFPPF_10GB_FD)) != 0;
691 }
692
693 /* Set the features advertised by 'netdev' to 'advertise'.  Returns 0 if
694  * successful, otherwise a positive errno value. */
695 int
696 netdev_set_advertisements(struct netdev *netdev, uint32_t advertise)
697 {
698     return (netdev_get_dev(netdev)->netdev_class->set_advertisements
699             ? netdev_get_dev(netdev)->netdev_class->set_advertisements(
700                     netdev, advertise)
701             : EOPNOTSUPP);
702 }
703
704 /* If 'netdev' has an assigned IPv4 address, sets '*address' to that address
705  * and '*netmask' to its netmask and returns 0.  Otherwise, returns a positive
706  * errno value and sets '*address' to 0 (INADDR_ANY).
707  *
708  * The following error values have well-defined meanings:
709  *
710  *   - EADDRNOTAVAIL: 'netdev' has no assigned IPv4 address.
711  *
712  *   - EOPNOTSUPP: No IPv4 network stack attached to 'netdev'.
713  *
714  * 'address' or 'netmask' or both may be null, in which case the address or netmask
715  * is not reported. */
716 int
717 netdev_get_in4(const struct netdev *netdev,
718                struct in_addr *address_, struct in_addr *netmask_)
719 {
720     struct in_addr address;
721     struct in_addr netmask;
722     int error;
723
724     error = (netdev_get_dev(netdev)->netdev_class->get_in4
725              ? netdev_get_dev(netdev)->netdev_class->get_in4(netdev, 
726                     &address, &netmask)
727              : EOPNOTSUPP);
728     if (address_) {
729         address_->s_addr = error ? 0 : address.s_addr;
730     }
731     if (netmask_) {
732         netmask_->s_addr = error ? 0 : netmask.s_addr;
733     }
734     return error;
735 }
736
737 /* Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
738  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
739  * positive errno value. */
740 int
741 netdev_set_in4(struct netdev *netdev, struct in_addr addr, struct in_addr mask)
742 {
743     return (netdev_get_dev(netdev)->netdev_class->set_in4
744             ? netdev_get_dev(netdev)->netdev_class->set_in4(netdev, addr, mask)
745             : EOPNOTSUPP);
746 }
747
748 /* Adds 'router' as a default IP gateway for the TCP/IP stack that corresponds
749  * to 'netdev'. */
750 int
751 netdev_add_router(struct netdev *netdev, struct in_addr router)
752 {
753     COVERAGE_INC(netdev_add_router);
754     return (netdev_get_dev(netdev)->netdev_class->add_router
755             ? netdev_get_dev(netdev)->netdev_class->add_router(netdev, router)
756             : EOPNOTSUPP);
757 }
758
759 /* Looks up the next hop for 'host' for the TCP/IP stack that corresponds to
760  * 'netdev'.  If a route cannot not be determined, sets '*next_hop' to 0,
761  * '*netdev_name' to null, and returns a positive errno value.  Otherwise, if a
762  * next hop is found, stores the next hop gateway's address (0 if 'host' is on
763  * a directly connected network) in '*next_hop' and a copy of the name of the
764  * device to reach 'host' in '*netdev_name', and returns 0.  The caller is
765  * responsible for freeing '*netdev_name' (by calling free()). */
766 int
767 netdev_get_next_hop(const struct netdev *netdev,
768                     const struct in_addr *host, struct in_addr *next_hop,
769                     char **netdev_name)
770 {
771     int error = (netdev_get_dev(netdev)->netdev_class->get_next_hop
772                  ? netdev_get_dev(netdev)->netdev_class->get_next_hop(
773                         host, next_hop, netdev_name)
774                  : EOPNOTSUPP);
775     if (error) {
776         next_hop->s_addr = 0;
777         *netdev_name = NULL;
778     }
779     return error;
780 }
781
782 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address and
783  * returns 0.  Otherwise, returns a positive errno value and sets '*in6' to
784  * all-zero-bits (in6addr_any).
785  *
786  * The following error values have well-defined meanings:
787  *
788  *   - EADDRNOTAVAIL: 'netdev' has no assigned IPv6 address.
789  *
790  *   - EOPNOTSUPP: No IPv6 network stack attached to 'netdev'.
791  *
792  * 'in6' may be null, in which case the address itself is not reported. */
793 int
794 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
795 {
796     struct in6_addr dummy;
797     int error;
798
799     error = (netdev_get_dev(netdev)->netdev_class->get_in6
800              ? netdev_get_dev(netdev)->netdev_class->get_in6(netdev, 
801                     in6 ? in6 : &dummy)
802              : EOPNOTSUPP);
803     if (error && in6) {
804         memset(in6, 0, sizeof *in6);
805     }
806     return error;
807 }
808
809 /* On 'netdev', turns off the flags in 'off' and then turns on the flags in
810  * 'on'.  If 'permanent' is true, the changes will persist; otherwise, they
811  * will be reverted when 'netdev' is closed or the program exits.  Returns 0 if
812  * successful, otherwise a positive errno value. */
813 static int
814 do_update_flags(struct netdev *netdev, enum netdev_flags off,
815                 enum netdev_flags on, enum netdev_flags *old_flagsp,
816                 bool permanent)
817 {
818     enum netdev_flags old_flags;
819     int error;
820
821     error = netdev_get_dev(netdev)->netdev_class->update_flags(netdev, 
822                 off & ~on, on, &old_flags);
823     if (error) {
824         VLOG_WARN_RL(&rl, "failed to %s flags for network device %s: %s",
825                      off || on ? "set" : "get", netdev_get_name(netdev),
826                      strerror(error));
827         old_flags = 0;
828     } else if ((off || on) && !permanent) {
829         enum netdev_flags new_flags = (old_flags & ~off) | on;
830         enum netdev_flags changed_flags = old_flags ^ new_flags;
831         if (changed_flags) {
832             if (!netdev->changed_flags) {
833                 netdev->save_flags = old_flags;
834             }
835             netdev->changed_flags |= changed_flags;
836         }
837     }
838     if (old_flagsp) {
839         *old_flagsp = old_flags;
840     }
841     return error;
842 }
843
844 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
845  * Returns 0 if successful, otherwise a positive errno value.  On failure,
846  * stores 0 into '*flagsp'. */
847 int
848 netdev_get_flags(const struct netdev *netdev_, enum netdev_flags *flagsp)
849 {
850     struct netdev *netdev = (struct netdev *) netdev_;
851     return do_update_flags(netdev, 0, 0, flagsp, false);
852 }
853
854 /* Sets the flags for 'netdev' to 'flags'.
855  * If 'permanent' is true, the changes will persist; otherwise, they
856  * will be reverted when 'netdev' is closed or the program exits.
857  * Returns 0 if successful, otherwise a positive errno value. */
858 int
859 netdev_set_flags(struct netdev *netdev, enum netdev_flags flags,
860                  bool permanent)
861 {
862     return do_update_flags(netdev, -1, flags, NULL, permanent);
863 }
864
865 /* Turns on the specified 'flags' on 'netdev'.
866  * If 'permanent' is true, the changes will persist; otherwise, they
867  * will be reverted when 'netdev' is closed or the program exits.
868  * Returns 0 if successful, otherwise a positive errno value. */
869 int
870 netdev_turn_flags_on(struct netdev *netdev, enum netdev_flags flags,
871                      bool permanent)
872 {
873     return do_update_flags(netdev, 0, flags, NULL, permanent);
874 }
875
876 /* Turns off the specified 'flags' on 'netdev'.
877  * If 'permanent' is true, the changes will persist; otherwise, they
878  * will be reverted when 'netdev' is closed or the program exits.
879  * Returns 0 if successful, otherwise a positive errno value. */
880 int
881 netdev_turn_flags_off(struct netdev *netdev, enum netdev_flags flags,
882                       bool permanent)
883 {
884     return do_update_flags(netdev, flags, 0, NULL, permanent);
885 }
886
887 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
888  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
889  * returns 0.  Otherwise, it returns a positive errno value; in particular,
890  * ENXIO indicates that there is no ARP table entry for 'ip' on 'netdev'. */
891 int
892 netdev_arp_lookup(const struct netdev *netdev,
893                   uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
894 {
895     int error = (netdev_get_dev(netdev)->netdev_class->arp_lookup
896                  ? netdev_get_dev(netdev)->netdev_class->arp_lookup(netdev, 
897                         ip, mac)
898                  : EOPNOTSUPP);
899     if (error) {
900         memset(mac, 0, ETH_ADDR_LEN);
901     }
902     return error;
903 }
904
905 /* Sets 'carrier' to true if carrier is active (link light is on) on
906  * 'netdev'. */
907 int
908 netdev_get_carrier(const struct netdev *netdev, bool *carrier)
909 {
910     int error = (netdev_get_dev(netdev)->netdev_class->get_carrier
911                  ? netdev_get_dev(netdev)->netdev_class->get_carrier(netdev, 
912                         carrier)
913                  : EOPNOTSUPP);
914     if (error) {
915         *carrier = false;
916     }
917     return error;
918 }
919
920 /* Retrieves current device stats for 'netdev'. */
921 int
922 netdev_get_stats(const struct netdev *netdev, struct netdev_stats *stats)
923 {
924     int error;
925
926     COVERAGE_INC(netdev_get_stats);
927     error = (netdev_get_dev(netdev)->netdev_class->get_stats
928              ? netdev_get_dev(netdev)->netdev_class->get_stats(netdev, stats)
929              : EOPNOTSUPP);
930     if (error) {
931         memset(stats, 0xff, sizeof *stats);
932     }
933     return error;
934 }
935
936 /* Attempts to set input rate limiting (policing) policy, such that up to
937  * 'kbits_rate' kbps of traffic is accepted, with a maximum accumulative burst
938  * size of 'kbits' kb. */
939 int
940 netdev_set_policing(struct netdev *netdev, uint32_t kbits_rate,
941                     uint32_t kbits_burst)
942 {
943     return (netdev_get_dev(netdev)->netdev_class->set_policing
944             ? netdev_get_dev(netdev)->netdev_class->set_policing(netdev, 
945                     kbits_rate, kbits_burst)
946             : EOPNOTSUPP);
947 }
948
949 /* If 'netdev' is a VLAN network device (e.g. one created with vconfig(8)),
950  * sets '*vlan_vid' to the VLAN VID associated with that device and returns 0.
951  * Otherwise returns a errno value (specifically ENOENT if 'netdev_name' is the
952  * name of a network device that is not a VLAN device) and sets '*vlan_vid' to
953  * -1. */
954 int
955 netdev_get_vlan_vid(const struct netdev *netdev, int *vlan_vid)
956 {
957     int error = (netdev_get_dev(netdev)->netdev_class->get_vlan_vid
958                  ? netdev_get_dev(netdev)->netdev_class->get_vlan_vid(netdev, 
959                         vlan_vid)
960                  : ENOENT);
961     if (error) {
962         *vlan_vid = 0;
963     }
964     return error;
965 }
966
967 /* Returns a network device that has 'in4' as its IP address, if one exists,
968  * otherwise a null pointer. */
969 struct netdev *
970 netdev_find_dev_by_in4(const struct in_addr *in4)
971 {
972     struct netdev *netdev;
973     struct svec dev_list = SVEC_EMPTY_INITIALIZER;
974     size_t i;
975
976     netdev_enumerate(&dev_list);
977     for (i = 0; i < dev_list.n; i++) {
978         const char *name = dev_list.names[i];
979         struct in_addr dev_in4;
980
981         if (!netdev_open_default(name, &netdev)
982             && !netdev_get_in4(netdev, &dev_in4, NULL)
983             && dev_in4.s_addr == in4->s_addr) {
984             goto exit;
985         }
986         netdev_close(netdev);
987     }
988     netdev = NULL;
989
990 exit:
991     svec_destroy(&dev_list);
992     return netdev;
993 }
994 \f
995 /* Initializes 'netdev_dev' as a netdev device named 'name' of the
996  * specified 'netdev_class'.
997  *
998  * This function adds 'netdev_dev' to a netdev-owned shash, so it is
999  * very important that 'netdev_dev' only be freed after calling
1000  * the refcount drops to zero.  */
1001 void
1002 netdev_dev_init(struct netdev_dev *netdev_dev, const char *name,
1003                 const struct netdev_class *netdev_class)
1004 {
1005     assert(!shash_find(&netdev_dev_shash, name));
1006
1007     memset(netdev_dev, 0, sizeof *netdev_dev);
1008     netdev_dev->netdev_class = netdev_class;
1009     netdev_dev->name = xstrdup(name);
1010     netdev_dev->node = shash_add(&netdev_dev_shash, name, netdev_dev);
1011 }
1012
1013 /* Undoes the results of initialization.
1014  *
1015  * Normally this function does not need to be called as netdev_close has
1016  * the same effect when the refcount drops to zero.
1017  * However, it may be called by providers due to an error on creation
1018  * that occurs after initialization.  It this case netdev_close() would
1019  * never be called. */
1020 void
1021 netdev_dev_uninit(struct netdev_dev *netdev_dev, bool destroy)
1022 {
1023     char *name = netdev_dev->name;
1024
1025     assert(!netdev_dev->ref_cnt);
1026
1027     shash_delete(&netdev_dev_shash, netdev_dev->node);
1028     update_device_args(netdev_dev, NULL);
1029
1030     if (destroy) {
1031         netdev_dev->netdev_class->destroy(netdev_dev);
1032     }
1033     free(name);
1034 }
1035
1036 /* Returns the class type of 'netdev_dev'.
1037  *
1038  * The caller must not free the returned value. */
1039 const char *
1040 netdev_dev_get_type(const struct netdev_dev *netdev_dev)
1041 {
1042     return netdev_dev->netdev_class->type;
1043 }
1044
1045 /* Returns the name of 'netdev_dev'.
1046  *
1047  * The caller must not free the returned value. */
1048 const char *
1049 netdev_dev_get_name(const struct netdev_dev *netdev_dev)
1050 {
1051     return netdev_dev->name;
1052 }
1053
1054 /* Returns the netdev_dev with 'name' or NULL if there is none.
1055  *
1056  * The caller must not free the returned value. */
1057 struct netdev_dev *
1058 netdev_dev_from_name(const char *name)
1059 {
1060     return shash_find_data(&netdev_dev_shash, name);
1061 }
1062
1063 /* Fills 'device_list' with devices that match 'netdev_class'.
1064  *
1065  * The caller is responsible for initializing and destroying 'device_list'
1066  * but the contained netdev_devs must not be freed. */
1067 void
1068 netdev_dev_get_devices(const struct netdev_class *netdev_class,
1069                        struct shash *device_list)
1070 {
1071     struct shash_node *node;
1072     SHASH_FOR_EACH (node, &netdev_dev_shash) {
1073         struct netdev_dev *dev = node->data;
1074
1075         if (dev->netdev_class == netdev_class) {
1076             shash_add(device_list, node->name, node->data);
1077         }
1078     }
1079 }
1080
1081 /* Initializes 'netdev' as a instance of the netdev_dev.
1082  *
1083  * This function adds 'netdev' to a netdev-owned linked list, so it is very
1084  * important that 'netdev' only be freed after calling netdev_close(). */
1085 void
1086 netdev_init(struct netdev *netdev, struct netdev_dev *netdev_dev)
1087 {
1088     memset(netdev, 0, sizeof *netdev);
1089     netdev->netdev_dev = netdev_dev;
1090     list_push_back(&netdev_list, &netdev->node);
1091 }
1092
1093 /* Undoes the results of initialization.
1094  *
1095  * Normally this function only needs to be called from netdev_close().
1096  * However, it may be called by providers due to an error on opening
1097  * that occurs after initialization.  It this case netdev_close() would
1098  * never be called. */
1099 void
1100 netdev_uninit(struct netdev *netdev, bool close)
1101 {
1102     /* Restore flags that we changed, if any. */
1103     int error = restore_flags(netdev);
1104     list_remove(&netdev->node);
1105     if (error) {
1106         VLOG_WARN("failed to restore network device flags on %s: %s",
1107                   netdev_get_name(netdev), strerror(error));
1108     }
1109
1110     if (close) {
1111         netdev_get_dev(netdev)->netdev_class->close(netdev);
1112     }
1113 }
1114
1115
1116 /* Returns the class type of 'netdev'.  
1117  *
1118  * The caller must not free the returned value. */
1119 const char *
1120 netdev_get_type(const struct netdev *netdev)
1121 {
1122     return netdev_get_dev(netdev)->netdev_class->type;
1123 }
1124
1125 struct netdev_dev *
1126 netdev_get_dev(const struct netdev *netdev)
1127 {
1128     return netdev->netdev_dev;
1129 }
1130
1131 /* Initializes 'notifier' as a netdev notifier for 'netdev', for which
1132  * notification will consist of calling 'cb', with auxiliary data 'aux'. */
1133 void
1134 netdev_notifier_init(struct netdev_notifier *notifier, struct netdev *netdev,
1135                      void (*cb)(struct netdev_notifier *), void *aux)
1136 {
1137     notifier->netdev = netdev;
1138     notifier->cb = cb;
1139     notifier->aux = aux;
1140 }
1141 \f
1142 /* Tracks changes in the status of a set of network devices. */
1143 struct netdev_monitor {
1144     struct shash polled_netdevs;
1145     struct shash changed_netdevs;
1146 };
1147
1148 /* Creates and returns a new structure for monitor changes in the status of
1149  * network devices. */
1150 struct netdev_monitor *
1151 netdev_monitor_create(void)
1152 {
1153     struct netdev_monitor *monitor = xmalloc(sizeof *monitor);
1154     shash_init(&monitor->polled_netdevs);
1155     shash_init(&monitor->changed_netdevs);
1156     return monitor;
1157 }
1158
1159 /* Destroys 'monitor'. */
1160 void
1161 netdev_monitor_destroy(struct netdev_monitor *monitor)
1162 {
1163     if (monitor) {
1164         struct shash_node *node;
1165
1166         SHASH_FOR_EACH (node, &monitor->polled_netdevs) {
1167             struct netdev_notifier *notifier = node->data;
1168             netdev_get_dev(notifier->netdev)->netdev_class->poll_remove(
1169                     notifier);
1170         }
1171
1172         shash_destroy(&monitor->polled_netdevs);
1173         shash_destroy(&monitor->changed_netdevs);
1174         free(monitor);
1175     }
1176 }
1177
1178 static void
1179 netdev_monitor_cb(struct netdev_notifier *notifier)
1180 {
1181     struct netdev_monitor *monitor = notifier->aux;
1182     const char *name = netdev_get_name(notifier->netdev);
1183     if (!shash_find(&monitor->changed_netdevs, name)) {
1184         shash_add(&monitor->changed_netdevs, name, NULL);
1185     }
1186 }
1187
1188 /* Attempts to add 'netdev' as a netdev monitored by 'monitor'.  Returns 0 if
1189  * successful, otherwise a positive errno value.
1190  *
1191  * Adding a given 'netdev' to a monitor multiple times is equivalent to adding
1192  * it once. */
1193 int
1194 netdev_monitor_add(struct netdev_monitor *monitor, struct netdev *netdev)
1195 {
1196     const char *netdev_name = netdev_get_name(netdev);
1197     int error = 0;
1198     if (!shash_find(&monitor->polled_netdevs, netdev_name)
1199             && netdev_get_dev(netdev)->netdev_class->poll_add)
1200     {
1201         struct netdev_notifier *notifier;
1202         error = netdev_get_dev(netdev)->netdev_class->poll_add(netdev,
1203                     netdev_monitor_cb, monitor, &notifier);
1204         if (!error) {
1205             assert(notifier->netdev == netdev);
1206             shash_add(&monitor->polled_netdevs, netdev_name, notifier);
1207         }
1208     }
1209     return error;
1210 }
1211
1212 /* Removes 'netdev' from the set of netdevs monitored by 'monitor'.  (This has
1213  * no effect if 'netdev' is not in the set of devices monitored by
1214  * 'monitor'.) */
1215 void
1216 netdev_monitor_remove(struct netdev_monitor *monitor, struct netdev *netdev)
1217 {
1218     const char *netdev_name = netdev_get_name(netdev);
1219     struct shash_node *node;
1220
1221     node = shash_find(&monitor->polled_netdevs, netdev_name);
1222     if (node) {
1223         /* Cancel future notifications. */
1224         struct netdev_notifier *notifier = node->data;
1225         netdev_get_dev(netdev)->netdev_class->poll_remove(notifier);
1226         shash_delete(&monitor->polled_netdevs, node);
1227
1228         /* Drop any pending notification. */
1229         node = shash_find(&monitor->changed_netdevs, netdev_name);
1230         if (node) {
1231             shash_delete(&monitor->changed_netdevs, node);
1232         }
1233     }
1234 }
1235
1236 /* Checks for changes to netdevs in the set monitored by 'monitor'.  If any of
1237  * the attributes (Ethernet address, carrier status, speed or peer-advertised
1238  * speed, flags, etc.) of a network device monitored by 'monitor' has changed,
1239  * sets '*devnamep' to the name of a device that has changed and returns 0.
1240  * The caller is responsible for freeing '*devnamep' (with free()).
1241  *
1242  * If no devices have changed, sets '*devnamep' to NULL and returns EAGAIN.
1243  */
1244 int
1245 netdev_monitor_poll(struct netdev_monitor *monitor, char **devnamep)
1246 {
1247     struct shash_node *node = shash_first(&monitor->changed_netdevs);
1248     if (!node) {
1249         *devnamep = NULL;
1250         return EAGAIN;
1251     } else {
1252         *devnamep = xstrdup(node->name);
1253         shash_delete(&monitor->changed_netdevs, node);
1254         return 0;
1255     }
1256 }
1257
1258 /* Registers with the poll loop to wake up from the next call to poll_block()
1259  * when netdev_monitor_poll(monitor) would indicate that a device has
1260  * changed. */
1261 void
1262 netdev_monitor_poll_wait(const struct netdev_monitor *monitor)
1263 {
1264     if (!shash_is_empty(&monitor->changed_netdevs)) {
1265         poll_immediate_wake();
1266     } else {
1267         /* XXX Nothing needed here for netdev_linux, but maybe other netdev
1268          * classes need help. */
1269     }
1270 }
1271 \f
1272 /* Restore the network device flags on 'netdev' to those that were active
1273  * before we changed them.  Returns 0 if successful, otherwise a positive
1274  * errno value.
1275  *
1276  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
1277 static int
1278 restore_flags(struct netdev *netdev)
1279 {
1280     if (netdev->changed_flags) {
1281         enum netdev_flags restore = netdev->save_flags & netdev->changed_flags;
1282         enum netdev_flags old_flags;
1283         return netdev_get_dev(netdev)->netdev_class->update_flags(netdev,
1284                                            netdev->changed_flags & ~restore,
1285                                            restore, &old_flags);
1286     }
1287     return 0;
1288 }
1289
1290 /* Close all netdevs on shutdown so they can do any needed cleanup such as
1291  * destroying devices, restoring flags, etc. */
1292 static void
1293 close_all_netdevs(void *aux OVS_UNUSED)
1294 {
1295     struct netdev *netdev, *next;
1296     LIST_FOR_EACH_SAFE(netdev, next, struct netdev, node, &netdev_list) {
1297         netdev_close(netdev);
1298     }
1299 }