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