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