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