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