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