Get rid of unused parameter to rate_limit_start().
[sliver-openvswitch.git] / lib / netdev.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWRE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <config.h>
35 #include "netdev.h"
36
37 #include <assert.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <arpa/inet.h>
41 #include <inttypes.h>
42 #include <linux/if_tun.h>
43 #include <linux/types.h>
44 #include <linux/ethtool.h>
45 #include <linux/sockios.h>
46 #include <linux/version.h>
47 #include <sys/types.h>
48 #include <sys/ioctl.h>
49 #include <sys/socket.h>
50 #include <netpacket/packet.h>
51 #include <net/ethernet.h>
52 #include <net/if.h>
53 #include <net/if_arp.h>
54 #include <net/if_packet.h>
55 #include <net/route.h>
56 #include <netinet/in.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60
61 #include "fatal-signal.h"
62 #include "list.h"
63 #include "ofpbuf.h"
64 #include "openflow/openflow.h"
65 #include "packets.h"
66 #include "poll-loop.h"
67 #include "socket-util.h"
68
69 #define THIS_MODULE VLM_netdev
70 #include "vlog.h"
71
72 struct netdev {
73     struct list node;
74     char *name;
75
76     /* File descriptors.  For ordinary network devices, the two fds below are
77      * the same; for tap devices, they differ. */
78     int netdev_fd;              /* Network device. */
79     int tap_fd;                 /* TAP character device, if any, otherwise the
80                                  * network device. */
81
82     /* Cached network device information. */
83     int ifindex;
84     uint8_t etheraddr[ETH_ADDR_LEN];
85     struct in6_addr in6;
86     int speed;
87     int mtu;
88     int txqlen;
89     int hwaddr_family;
90
91     /* Bitmaps of OFPPF_* that describe features.  All bits disabled if
92      * unsupported or unavailable. */
93     uint32_t curr;              /* Current features. */
94     uint32_t advertised;        /* Features being advertised by the port. */
95     uint32_t supported;         /* Features supported by the port. */
96     uint32_t peer;              /* Features advertised by the peer. */
97
98     int save_flags;             /* Initial device flags. */
99     int changed_flags;          /* Flags that we changed. */
100 };
101
102 /* All open network devices. */
103 static struct list netdev_list = LIST_INITIALIZER(&netdev_list);
104
105 /* An AF_INET socket (used for ioctl operations). */
106 static int af_inet_sock = -1;
107
108 /* This is set pretty low because we probably won't learn anything from the
109  * additional log messages. */
110 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
111
112 static void init_netdev(void);
113 static int do_open_netdev(const char *name, int ethertype, int tap_fd,
114                           struct netdev **netdev_);
115 static int restore_flags(struct netdev *netdev);
116 static int get_flags(const struct netdev *, int fd, int *flagsp);
117 static int set_flags(struct netdev *, int fd, int flags);
118
119 /* Obtains the IPv6 address for 'name' into 'in6'. */
120 static void
121 get_ipv6_address(const char *name, struct in6_addr *in6)
122 {
123     FILE *file;
124     char line[128];
125
126     file = fopen("/proc/net/if_inet6", "r");
127     if (file == NULL) {
128         /* This most likely indicates that the host doesn't have IPv6 support,
129          * so it's not really a failure condition.*/
130         *in6 = in6addr_any;
131         return;
132     }
133
134     while (fgets(line, sizeof line, file)) {
135         uint8_t *s6 = in6->s6_addr;
136         char ifname[16 + 1];
137
138 #define X8 "%2"SCNx8
139         if (sscanf(line, " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
140                    "%*x %*x %*x %*x %16s\n",
141                    &s6[0], &s6[1], &s6[2], &s6[3],
142                    &s6[4], &s6[5], &s6[6], &s6[7],
143                    &s6[8], &s6[9], &s6[10], &s6[11],
144                    &s6[12], &s6[13], &s6[14], &s6[15],
145                    ifname) == 17
146             && !strcmp(name, ifname))
147         {
148             return;
149         }
150     }
151     *in6 = in6addr_any;
152
153     fclose(file);
154 }
155
156 static void
157 do_ethtool(struct netdev *netdev) 
158 {
159     struct ifreq ifr;
160     struct ethtool_cmd ecmd;
161
162     netdev->curr = 0;
163     netdev->supported = 0;
164     netdev->advertised = 0;
165     netdev->peer = 0;
166
167     memset(&ifr, 0, sizeof ifr);
168     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
169     ifr.ifr_data = (caddr_t) &ecmd;
170
171     memset(&ecmd, 0, sizeof ecmd);
172     ecmd.cmd = ETHTOOL_GSET;
173     if (ioctl(netdev->netdev_fd, SIOCETHTOOL, &ifr) == 0) {
174         if (ecmd.supported & SUPPORTED_10baseT_Half) {
175             netdev->supported |= OFPPF_10MB_HD;
176         }
177         if (ecmd.supported & SUPPORTED_10baseT_Full) {
178             netdev->supported |= OFPPF_10MB_FD;
179         }
180         if (ecmd.supported & SUPPORTED_100baseT_Half)  {
181             netdev->supported |= OFPPF_100MB_HD;
182         }
183         if (ecmd.supported & SUPPORTED_100baseT_Full) {
184             netdev->supported |= OFPPF_100MB_FD;
185         }
186         if (ecmd.supported & SUPPORTED_1000baseT_Half) {
187             netdev->supported |= OFPPF_1GB_HD;
188         }
189         if (ecmd.supported & SUPPORTED_1000baseT_Full) {
190             netdev->supported |= OFPPF_1GB_FD;
191         }
192         if (ecmd.supported & SUPPORTED_10000baseT_Full) {
193             netdev->supported |= OFPPF_10GB_FD;
194         }
195         if (ecmd.supported & SUPPORTED_TP) {
196             netdev->supported |= OFPPF_COPPER;
197         }
198         if (ecmd.supported & SUPPORTED_FIBRE) {
199             netdev->supported |= OFPPF_FIBER;
200         }
201         if (ecmd.supported & SUPPORTED_Autoneg) {
202             netdev->supported |= OFPPF_AUTONEG;
203         }
204 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,14)
205         if (ecmd.supported & SUPPORTED_Pause) {
206             netdev->supported |= OFPPF_PAUSE;
207         }
208         if (ecmd.supported & SUPPORTED_Asym_Pause) {
209             netdev->supported |= OFPPF_PAUSE_ASYM;
210         }
211 #endif /* kernel >= 2.6.14 */
212
213         /* Set the advertised features */
214         if (ecmd.advertising & ADVERTISED_10baseT_Half) {
215             netdev->advertised |= OFPPF_10MB_HD;
216         }
217         if (ecmd.advertising & ADVERTISED_10baseT_Full) {
218             netdev->advertised |= OFPPF_10MB_FD;
219         }
220         if (ecmd.advertising & ADVERTISED_100baseT_Half) {
221             netdev->advertised |= OFPPF_100MB_HD;
222         }
223         if (ecmd.advertising & ADVERTISED_100baseT_Full) {
224             netdev->advertised |= OFPPF_100MB_FD;
225         }
226         if (ecmd.advertising & ADVERTISED_1000baseT_Half) {
227             netdev->advertised |= OFPPF_1GB_HD;
228         }
229         if (ecmd.advertising & ADVERTISED_1000baseT_Full) {
230             netdev->advertised |= OFPPF_1GB_FD;
231         }
232         if (ecmd.advertising & ADVERTISED_10000baseT_Full) {
233             netdev->advertised |= OFPPF_10GB_FD;
234         }
235         if (ecmd.advertising & ADVERTISED_TP) {
236             netdev->advertised |= OFPPF_COPPER;
237         }
238         if (ecmd.advertising & ADVERTISED_FIBRE) {
239             netdev->advertised |= OFPPF_FIBER;
240         }
241         if (ecmd.advertising & ADVERTISED_Autoneg) {
242             netdev->advertised |= OFPPF_AUTONEG;
243         }
244 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,14)
245         if (ecmd.advertising & ADVERTISED_Pause) {
246             netdev->advertised |= OFPPF_PAUSE;
247         }
248         if (ecmd.advertising & ADVERTISED_Asym_Pause) {
249             netdev->advertised |= OFPPF_PAUSE_ASYM;
250         }
251 #endif /* kernel >= 2.6.14 */
252
253         /* Set the current features */
254         if (ecmd.speed == SPEED_10) {
255             netdev->curr = (ecmd.duplex) ? OFPPF_10MB_FD : OFPPF_10MB_HD;
256         }
257         else if (ecmd.speed == SPEED_100) {
258             netdev->curr = (ecmd.duplex) ? OFPPF_100MB_FD : OFPPF_100MB_HD;
259         }
260         else if (ecmd.speed == SPEED_1000) {
261             netdev->curr = (ecmd.duplex) ? OFPPF_1GB_FD : OFPPF_1GB_HD;
262         }
263         else if (ecmd.speed == SPEED_10000) {
264             netdev->curr = OFPPF_10GB_FD;
265         }
266
267         if (ecmd.port == PORT_TP) {
268             netdev->curr |= OFPPF_COPPER;
269         }
270         else if (ecmd.port == PORT_FIBRE) {
271             netdev->curr |= OFPPF_FIBER;
272         }
273
274         if (ecmd.autoneg) {
275             netdev->curr |= OFPPF_AUTONEG;
276         }
277     } else {
278         VLOG_DBG("ioctl(SIOCETHTOOL) failed: %s", strerror(errno));
279     }
280 }
281
282 /* Opens the network device named 'name' (e.g. "eth0") and returns zero if
283  * successful, otherwise a positive errno value.  On success, sets '*netdevp'
284  * to the new network device, otherwise to null.
285  *
286  * 'ethertype' may be a 16-bit Ethernet protocol value in host byte order to
287  * capture frames of that type received on the device.  It may also be one of
288  * the 'enum netdev_pseudo_ethertype' values to receive frames in one of those
289  * categories. */
290 int
291 netdev_open(const char *name, int ethertype, struct netdev **netdevp) 
292 {
293     if (!strncmp(name, "tap:", 4)) {
294         return netdev_open_tap(name + 4, netdevp);
295     } else {
296         return do_open_netdev(name, ethertype, -1, netdevp); 
297     }
298 }
299
300 /* Opens a TAP virtual network device.  If 'name' is a nonnull, non-empty
301  * string, attempts to assign that name to the TAP device (failing if the name
302  * is already in use); otherwise, a name is automatically assigned.  Returns
303  * zero if successful, otherwise a positive errno value.  On success, sets
304  * '*netdevp' to the new network device, otherwise to null.  */
305 int
306 netdev_open_tap(const char *name, struct netdev **netdevp)
307 {
308     static const char tap_dev[] = "/dev/net/tun";
309     struct ifreq ifr;
310     int error;
311     int tap_fd;
312
313     tap_fd = open(tap_dev, O_RDWR);
314     if (tap_fd < 0) {
315         ofp_error(errno, "opening \"%s\" failed", tap_dev);
316         return errno;
317     }
318
319     memset(&ifr, 0, sizeof ifr);
320     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
321     if (name) {
322         strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
323     }
324     if (ioctl(tap_fd, TUNSETIFF, &ifr) < 0) {
325         int error = errno;
326         ofp_error(error, "ioctl(TUNSETIFF) on \"%s\" failed", tap_dev);
327         close(tap_fd);
328         return error;
329     }
330
331     error = set_nonblocking(tap_fd);
332     if (error) {
333         ofp_error(error, "set_nonblocking on \"%s\" failed", tap_dev);
334         close(tap_fd);
335         return error;
336     }
337
338     error = do_open_netdev(ifr.ifr_name, NETDEV_ETH_TYPE_NONE, tap_fd,
339                            netdevp);
340     if (error) {
341         close(tap_fd);
342     }
343     return error;
344 }
345
346 static int
347 do_open_netdev(const char *name, int ethertype, int tap_fd,
348                struct netdev **netdev_)
349 {
350     int netdev_fd;
351     struct sockaddr_ll sll;
352     struct ifreq ifr;
353     unsigned int ifindex;
354     uint8_t etheraddr[ETH_ADDR_LEN];
355     struct in6_addr in6;
356     int mtu;
357     int txqlen;
358     int hwaddr_family;
359     int error;
360     struct netdev *netdev;
361
362     init_netdev();
363     *netdev_ = NULL;
364
365     /* Create raw socket. */
366     netdev_fd = socket(PF_PACKET, SOCK_RAW,
367                        htons(ethertype == NETDEV_ETH_TYPE_NONE ? 0
368                              : ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
369                              : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
370                              : ethertype));
371     if (netdev_fd < 0) {
372         return errno;
373     }
374
375     /* Set non-blocking mode. */
376     error = set_nonblocking(netdev_fd);
377     if (error) {
378         goto error_already_set;
379     }
380
381     /* Get ethernet device index. */
382     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
383     if (ioctl(netdev_fd, SIOCGIFINDEX, &ifr) < 0) {
384         VLOG_ERR("ioctl(SIOCGIFINDEX) on %s device failed: %s",
385                  name, strerror(errno));
386         goto error;
387     }
388     ifindex = ifr.ifr_ifindex;
389
390     /* Bind to specific ethernet device. */
391     memset(&sll, 0, sizeof sll);
392     sll.sll_family = AF_PACKET;
393     sll.sll_ifindex = ifindex;
394     if (bind(netdev_fd, (struct sockaddr *) &sll, sizeof sll) < 0) {
395         VLOG_ERR("bind to %s failed: %s", name, strerror(errno));
396         goto error;
397     }
398
399     if (ethertype != NETDEV_ETH_TYPE_NONE) {
400         /* Between the socket() and bind() calls above, the socket receives all
401          * packets of the requested type on all system interfaces.  We do not
402          * want to receive that data, but there is no way to avoid it.  So we
403          * must now drain out the receive queue. */
404         error = drain_rcvbuf(netdev_fd);
405         if (error) {
406             goto error;
407         }
408     }
409
410     /* Get MAC address. */
411     if (ioctl(netdev_fd, SIOCGIFHWADDR, &ifr) < 0) {
412         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
413                  name, strerror(errno));
414         goto error;
415     }
416     hwaddr_family = ifr.ifr_hwaddr.sa_family;
417     if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
418         VLOG_WARN("%s device has unknown hardware address family %d",
419                   name, hwaddr_family);
420     }
421     memcpy(etheraddr, ifr.ifr_hwaddr.sa_data, sizeof etheraddr);
422
423     /* Get MTU. */
424     if (ioctl(netdev_fd, SIOCGIFMTU, &ifr) < 0) {
425         VLOG_ERR("ioctl(SIOCGIFMTU) on %s device failed: %s",
426                  name, strerror(errno));
427         goto error;
428     }
429     mtu = ifr.ifr_mtu;
430
431     /* Get TX queue length. */
432     if (ioctl(netdev_fd, SIOCGIFTXQLEN, &ifr) < 0) {
433         VLOG_ERR("ioctl(SIOCGIFTXQLEN) on %s device failed: %s",
434                  name, strerror(errno));
435         goto error;
436     }
437     txqlen = ifr.ifr_qlen;
438
439     get_ipv6_address(name, &in6);
440
441     /* Allocate network device. */
442     netdev = xmalloc(sizeof *netdev);
443     netdev->name = xstrdup(name);
444     netdev->ifindex = ifindex;
445     netdev->txqlen = txqlen;
446     netdev->hwaddr_family = hwaddr_family;
447     netdev->netdev_fd = netdev_fd;
448     netdev->tap_fd = tap_fd < 0 ? netdev_fd : tap_fd;
449     memcpy(netdev->etheraddr, etheraddr, sizeof etheraddr);
450     netdev->mtu = mtu;
451     netdev->in6 = in6;
452
453     /* Get speed, features. */
454     do_ethtool(netdev);
455
456     /* Save flags to restore at close or exit. */
457     error = get_flags(netdev, netdev_fd, &netdev->save_flags);
458     if (error) {
459         goto error_already_set;
460     }
461     netdev->changed_flags = 0;
462     fatal_signal_block();
463     list_push_back(&netdev_list, &netdev->node);
464     fatal_signal_unblock();
465
466     /* Success! */
467     *netdev_ = netdev;
468     return 0;
469
470 error:
471     error = errno;
472 error_already_set:
473     close(netdev_fd);
474     if (tap_fd >= 0) {
475         close(tap_fd);
476     }
477     return error;
478 }
479
480 /* Closes and destroys 'netdev'. */
481 void
482 netdev_close(struct netdev *netdev)
483 {
484     if (netdev) {
485         /* Bring down interface and drop promiscuous mode, if we brought up
486          * the interface or enabled promiscuous mode. */
487         int error;
488         fatal_signal_block();
489         error = restore_flags(netdev);
490         list_remove(&netdev->node);
491         fatal_signal_unblock();
492         if (error) {
493             VLOG_WARN("failed to restore network device flags on %s: %s",
494                       netdev->name, strerror(error));
495         }
496
497         /* Free. */
498         free(netdev->name);
499         close(netdev->netdev_fd);
500         if (netdev->netdev_fd != netdev->tap_fd) {
501             close(netdev->tap_fd);
502         }
503         free(netdev);
504     }
505 }
506
507 /* Pads 'buffer' out with zero-bytes to the minimum valid length of an
508  * Ethernet packet, if necessary.  */
509 static void
510 pad_to_minimum_length(struct ofpbuf *buffer)
511 {
512     if (buffer->size < ETH_TOTAL_MIN) {
513         ofpbuf_put_zeros(buffer, ETH_TOTAL_MIN - buffer->size);
514     }
515 }
516
517 /* Attempts to receive a packet from 'netdev' into 'buffer', which the caller
518  * must have initialized with sufficient room for the packet.  The space
519  * required to receive any packet is ETH_HEADER_LEN bytes, plus VLAN_HEADER_LEN
520  * bytes, plus the device's MTU (which may be retrieved via netdev_get_mtu()).
521  * (Some devices do not allow for a VLAN header, in which case VLAN_HEADER_LEN
522  * need not be included.)
523  *
524  * If a packet is successfully retrieved, returns 0.  In this case 'buffer' is
525  * guaranteed to contain at least ETH_TOTAL_MIN bytes.  Otherwise, returns a
526  * positive errno value.  Returns EAGAIN immediately if no packet is ready to
527  * be returned.
528  */
529 int
530 netdev_recv(struct netdev *netdev, struct ofpbuf *buffer)
531 {
532     ssize_t n_bytes;
533
534     assert(buffer->size == 0);
535     assert(ofpbuf_tailroom(buffer) >= ETH_TOTAL_MIN);
536     do {
537         n_bytes = read(netdev->tap_fd,
538                        ofpbuf_tail(buffer), ofpbuf_tailroom(buffer));
539     } while (n_bytes < 0 && errno == EINTR);
540     if (n_bytes < 0) {
541         if (errno != EAGAIN) {
542             VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
543                          strerror(errno), netdev->name);
544         }
545         return errno;
546     } else {
547         buffer->size += n_bytes;
548
549         /* When the kernel internally sends out an Ethernet frame on an
550          * interface, it gives us a copy *before* padding the frame to the
551          * minimum length.  Thus, when it sends out something like an ARP
552          * request, we see a too-short frame.  So pad it out to the minimum
553          * length. */
554         pad_to_minimum_length(buffer);
555         return 0;
556     }
557 }
558
559 /* Registers with the poll loop to wake up from the next call to poll_block()
560  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
561 void
562 netdev_recv_wait(struct netdev *netdev)
563 {
564     poll_fd_wait(netdev->tap_fd, POLLIN);
565 }
566
567 /* Discards all packets waiting to be received from 'netdev'. */
568 int
569 netdev_drain(struct netdev *netdev)
570 {
571     if (netdev->tap_fd != netdev->netdev_fd) {
572         drain_fd(netdev->tap_fd, netdev->txqlen);
573         return 0;
574     } else {
575         return drain_rcvbuf(netdev->netdev_fd);
576     }
577 }
578
579 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
580  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
581  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
582  * the packet is too big or too small to transmit on the device.
583  *
584  * The caller retains ownership of 'buffer' in all cases.
585  *
586  * The kernel maintains a packet transmission queue, so the caller is not
587  * expected to do additional queuing of packets. */
588 int
589 netdev_send(struct netdev *netdev, const struct ofpbuf *buffer)
590 {
591     ssize_t n_bytes;
592
593     do {
594         n_bytes = write(netdev->tap_fd, buffer->data, buffer->size);
595     } while (n_bytes < 0 && errno == EINTR);
596
597     if (n_bytes < 0) {
598         /* The Linux AF_PACKET implementation never blocks waiting for room
599          * for packets, instead returning ENOBUFS.  Translate this into EAGAIN
600          * for the caller. */
601         if (errno == ENOBUFS) {
602             return EAGAIN;
603         } else if (errno != EAGAIN) {
604             VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: %s",
605                          netdev->name, strerror(errno));
606         }
607         return errno;
608     } else if (n_bytes != buffer->size) {
609         VLOG_WARN_RL(&rl,
610                      "send partial Ethernet packet (%d bytes of %zu) on %s",
611                      (int) n_bytes, buffer->size, netdev->name);
612         return EMSGSIZE;
613     } else {
614         return 0;
615     }
616 }
617
618 /* Registers with the poll loop to wake up from the next call to poll_block()
619  * when the packet transmission queue has sufficient room to transmit a packet
620  * with netdev_send().
621  *
622  * The kernel maintains a packet transmission queue, so the client is not
623  * expected to do additional queuing of packets.  Thus, this function is
624  * unlikely to ever be used.  It is included for completeness. */
625 void
626 netdev_send_wait(struct netdev *netdev)
627 {
628     if (netdev->tap_fd == netdev->netdev_fd) {
629         poll_fd_wait(netdev->tap_fd, POLLOUT);
630     } else {
631         /* TAP device always accepts packets.*/
632         poll_immediate_wake();
633     }
634 }
635
636 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
637  * otherwise a positive errno value. */
638 int
639 netdev_set_etheraddr(struct netdev *netdev, const uint8_t mac[ETH_ADDR_LEN])
640 {
641     struct ifreq ifr;
642
643     memset(&ifr, 0, sizeof ifr);
644     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
645     ifr.ifr_hwaddr.sa_family = netdev->hwaddr_family;
646     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
647     if (ioctl(netdev->netdev_fd, SIOCSIFHWADDR, &ifr) < 0) {
648         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
649                  netdev->name, strerror(errno));
650         return errno;
651     }
652     memcpy(netdev->etheraddr, mac, ETH_ADDR_LEN);
653     return 0;
654 }
655
656 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
657  * free the returned buffer. */
658 const uint8_t *
659 netdev_get_etheraddr(const struct netdev *netdev)
660 {
661     return netdev->etheraddr;
662 }
663
664 /* Returns the name of the network device that 'netdev' represents,
665  * e.g. "eth0".  The caller must not modify or free the returned string. */
666 const char *
667 netdev_get_name(const struct netdev *netdev)
668 {
669     return netdev->name;
670 }
671
672 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
673  * in bytes, not including the hardware header; thus, this is typically 1500
674  * bytes for Ethernet devices. */
675 int
676 netdev_get_mtu(const struct netdev *netdev) 
677 {
678     return netdev->mtu;
679 }
680
681 /* Checks the link status.  Returns 1 or 0 to indicate the link is active 
682  * or not, respectively.  Any other return value indicates an error. */
683 int
684 netdev_get_link_status(const struct netdev *netdev) 
685 {
686     struct ifreq ifr;
687     struct ethtool_value edata;
688
689     memset(&ifr, 0, sizeof ifr);
690     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
691     ifr.ifr_data = (caddr_t) &edata;
692
693     memset(&edata, 0, sizeof edata);
694     edata.cmd = ETHTOOL_GLINK;
695     if (ioctl(netdev->netdev_fd, SIOCETHTOOL, &ifr) == 0) {
696         if (edata.data) {
697             return 1;
698         } else {
699             return 0;
700         }
701     }
702
703     return -1;
704 }
705
706 /* Returns the features supported by 'netdev' of type 'type', as a bitmap 
707  * of bits from enum ofp_phy_features, in host byte order. */
708 uint32_t
709 netdev_get_features(struct netdev *netdev, int type) 
710 {
711     do_ethtool(netdev);
712     switch (type) {
713     case NETDEV_FEAT_CURRENT:
714         return netdev->curr;
715     case NETDEV_FEAT_ADVERTISED:
716         return netdev->advertised;
717     case NETDEV_FEAT_SUPPORTED:
718         return netdev->supported;
719     case NETDEV_FEAT_PEER:
720         return netdev->peer;
721     default:
722         VLOG_WARN("Unknown feature type: %d\n", type);
723         return 0;
724     }
725 }
726
727 /* If 'netdev' has an assigned IPv4 address, sets '*in4' to that address (if
728  * 'in4' is non-null) and returns true.  Otherwise, returns false. */
729 bool
730 netdev_get_in4(const struct netdev *netdev, struct in_addr *in4)
731 {
732     struct ifreq ifr;
733     struct in_addr ip = { INADDR_ANY };
734
735     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
736     ifr.ifr_addr.sa_family = AF_INET;
737     if (ioctl(af_inet_sock, SIOCGIFADDR, &ifr) == 0) {
738         struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
739         ip = sin->sin_addr;
740     } else {
741         VLOG_DBG_RL(&rl, "%s: ioctl(SIOCGIFADDR) failed: %s",
742                     netdev->name, strerror(errno));
743     }
744     if (in4) {
745         *in4 = ip;
746     }
747     return ip.s_addr != INADDR_ANY;
748 }
749
750 static void
751 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
752 {
753     struct sockaddr_in sin;
754     memset(&sin, 0, sizeof sin);
755     sin.sin_family = AF_INET;
756     sin.sin_addr = addr;
757     sin.sin_port = 0;
758
759     memset(sa, 0, sizeof *sa);
760     memcpy(sa, &sin, sizeof sin);
761 }
762
763 static int
764 do_set_addr(struct netdev *netdev, int sock,
765             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
766 {
767     struct ifreq ifr;
768     int error;
769
770     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
771     make_in4_sockaddr(&ifr.ifr_addr, addr);
772     error = ioctl(sock, ioctl_nr, &ifr) < 0 ? errno : 0;
773     if (error) {
774         VLOG_WARN("ioctl(%s): %s", ioctl_name, strerror(error));
775     }
776     return error;
777 }
778
779 /* Assigns 'addr' as 'netdev''s IPv4 address and 'mask' as its netmask.  If
780  * 'addr' is INADDR_ANY, 'netdev''s IPv4 address is cleared.  Returns a
781  * positive errno value. */
782 int
783 netdev_set_in4(struct netdev *netdev, struct in_addr addr, struct in_addr mask)
784 {
785     int error;
786
787     error = do_set_addr(netdev, af_inet_sock,
788                         SIOCSIFADDR, "SIOCSIFADDR", addr);
789     if (!error && addr.s_addr != INADDR_ANY) {
790         error = do_set_addr(netdev, af_inet_sock,
791                             SIOCSIFNETMASK, "SIOCSIFNETMASK", mask);
792     }
793     return error;
794 }
795
796 /* Adds 'router' as a default gateway for 'netdev''s IP address. */
797 int
798 netdev_add_router(struct netdev *netdev, struct in_addr router)
799 {
800     struct in_addr any = { INADDR_ANY };
801     struct rtentry rt;
802     int error;
803
804     memset(&rt, 0, sizeof rt);
805     make_in4_sockaddr(&rt.rt_dst, any);
806     make_in4_sockaddr(&rt.rt_gateway, router);
807     make_in4_sockaddr(&rt.rt_genmask, any);
808     rt.rt_flags = RTF_UP | RTF_GATEWAY;
809     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
810     if (error) {
811         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
812     }
813     return error;
814 }
815
816 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
817  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
818 bool
819 netdev_get_in6(const struct netdev *netdev, struct in6_addr *in6)
820 {
821     if (in6) {
822         *in6 = netdev->in6;
823     }
824     return memcmp(&netdev->in6, &in6addr_any, sizeof netdev->in6) != 0;
825 }
826
827 /* Obtains the current flags for 'netdev' and stores them into '*flagsp'.
828  * Returns 0 if successful, otherwise a positive errno value. */
829 int
830 netdev_get_flags(const struct netdev *netdev, enum netdev_flags *flagsp)
831 {
832     int error, flags;
833
834     error = get_flags(netdev, netdev->netdev_fd, &flags);
835     if (error) {
836         return error;
837     }
838
839     *flagsp = 0;
840     if (flags & IFF_UP) {
841         *flagsp |= NETDEV_UP;
842     }
843     if (flags & IFF_PROMISC) {
844         *flagsp |= NETDEV_PROMISC;
845     }
846     return 0;
847 }
848
849 static int
850 nd_to_iff_flags(enum netdev_flags nd)
851 {
852     int iff = 0;
853     if (nd & NETDEV_UP) {
854         iff |= IFF_UP;
855     }
856     if (nd & NETDEV_PROMISC) {
857         iff |= IFF_PROMISC;
858     }
859     return iff;
860 }
861
862 /* On 'netdev', turns off the flags in 'off' and then turns on the flags in
863  * 'on'.  If 'permanent' is true, the changes will persist; otherwise, they
864  * will be reverted when 'netdev' is closed or the program exits.  Returns 0 if
865  * successful, otherwise a positive errno value. */
866 static int
867 do_update_flags(struct netdev *netdev, int fd, enum netdev_flags off,
868                 enum netdev_flags on, bool permanent)
869 {
870     int old_flags, new_flags;
871     int error;
872
873     error = get_flags(netdev, fd, &old_flags);
874     if (error) {
875         return error;
876     }
877
878     new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
879     if (!permanent) {
880         netdev->changed_flags |= new_flags ^ old_flags; 
881     }
882     if (new_flags != old_flags) {
883         error = set_flags(netdev, fd, new_flags);
884     }
885     return error;
886 }
887
888 /* Sets the flags for 'netdev' to 'flags'.
889  * If 'permanent' is true, the changes will persist; otherwise, they
890  * will be reverted when 'netdev' is closed or the program exits.
891  * Returns 0 if successful, otherwise a positive errno value. */
892 int
893 netdev_set_flags(struct netdev *netdev, enum netdev_flags flags,
894                  bool permanent)
895 {
896     return do_update_flags(netdev, netdev->netdev_fd, -1, flags, permanent);
897 }
898
899 /* Turns on the specified 'flags' on 'netdev'.
900  * If 'permanent' is true, the changes will persist; otherwise, they
901  * will be reverted when 'netdev' is closed or the program exits.
902  * Returns 0 if successful, otherwise a positive errno value. */
903 int
904 netdev_turn_flags_on(struct netdev *netdev, enum netdev_flags flags,
905                      bool permanent)
906 {
907     return do_update_flags(netdev, netdev->netdev_fd, 0, flags, permanent);
908 }
909
910 /* Turns off the specified 'flags' on 'netdev'.
911  * If 'permanent' is true, the changes will persist; otherwise, they
912  * will be reverted when 'netdev' is closed or the program exits.
913  * Returns 0 if successful, otherwise a positive errno value. */
914 int
915 netdev_turn_flags_off(struct netdev *netdev, enum netdev_flags flags,
916                       bool permanent)
917 {
918     return do_update_flags(netdev, netdev->netdev_fd, flags, 0, permanent);
919 }
920
921 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
922  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
923  * returns 0.  Otherwise, it returns a positive errno value; in particular,
924  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
925 int
926 netdev_arp_lookup(const struct netdev *netdev,
927                   uint32_t ip, uint8_t mac[ETH_ADDR_LEN]) 
928 {
929     struct arpreq r;
930     struct sockaddr_in *pa;
931     int retval;
932
933     memset(&r, 0, sizeof r);
934     pa = (struct sockaddr_in *) &r.arp_pa;
935     pa->sin_family = AF_INET;
936     pa->sin_addr.s_addr = ip;
937     pa->sin_port = 0;
938     r.arp_ha.sa_family = ARPHRD_ETHER;
939     r.arp_flags = 0;
940     strncpy(r.arp_dev, netdev->name, sizeof r.arp_dev);
941     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
942     if (!retval) {
943         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
944     } else if (retval != ENXIO) {
945         VLOG_WARN_RL(&rl, "%s: could not look up ARP entry for "IP_FMT": %s",
946                      netdev->name, IP_ARGS(&ip), strerror(retval));
947     }
948     return retval;
949 }
950 \f
951 static void restore_all_flags(void *aux);
952
953 /* Set up a signal hook to restore network device flags on program
954  * termination.  */
955 static void
956 init_netdev(void)
957 {
958     static bool inited;
959     if (!inited) {
960         inited = true;
961         fatal_signal_add_hook(restore_all_flags, NULL, true);
962         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
963         if (af_inet_sock < 0) {
964             ofp_fatal(errno, "socket(AF_INET)");
965         }
966     }
967 }
968
969 /* Restore the network device flags on 'netdev' to those that were active
970  * before we changed them.  Returns 0 if successful, otherwise a positive
971  * errno value.
972  *
973  * To avoid reentry, the caller must ensure that fatal signals are blocked. */
974 static int
975 restore_flags(struct netdev *netdev)
976 {
977     struct ifreq ifr;
978     int restore_flags;
979
980     /* Get current flags. */
981     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
982     if (ioctl(netdev->netdev_fd, SIOCGIFFLAGS, &ifr) < 0) {
983         return errno;
984     }
985
986     /* Restore flags that we might have changed, if necessary. */
987     restore_flags = netdev->changed_flags & (IFF_PROMISC | IFF_UP);
988     if ((ifr.ifr_flags ^ netdev->save_flags) & restore_flags) {
989         ifr.ifr_flags &= ~restore_flags;
990         ifr.ifr_flags |= netdev->save_flags & restore_flags;
991         if (ioctl(netdev->netdev_fd, SIOCSIFFLAGS, &ifr) < 0) {
992             return errno;
993         }
994     }
995
996     return 0;
997 }
998
999 /* Retores all the flags on all network devices that we modified.  Called from
1000  * a signal handler, so it does not attempt to report error conditions. */
1001 static void
1002 restore_all_flags(void *aux UNUSED)
1003 {
1004     struct netdev *netdev;
1005     LIST_FOR_EACH (netdev, struct netdev, node, &netdev_list) {
1006         restore_flags(netdev);
1007     }
1008 }
1009
1010 static int
1011 get_flags(const struct netdev *netdev, int fd, int *flags)
1012 {
1013     struct ifreq ifr;
1014     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
1015     if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
1016         VLOG_ERR("ioctl(SIOCGIFFLAGS) on %s device failed: %s",
1017                  netdev->name, strerror(errno));
1018         return errno;
1019     }
1020     *flags = ifr.ifr_flags;
1021     return 0;
1022 }
1023
1024 static int
1025 set_flags(struct netdev *netdev, int fd, int flags)
1026 {
1027     struct ifreq ifr;
1028     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
1029     ifr.ifr_flags = flags;
1030     if (ioctl(netdev->netdev_fd, SIOCSIFFLAGS, &ifr) < 0) {
1031         VLOG_ERR("ioctl(SIOCSIFFLAGS) on %s device failed: %s",
1032                  netdev->name, strerror(errno));
1033         return errno;
1034     }
1035     return 0;
1036 }