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