netdev-linux: Fix tap device stats.
[sliver-openvswitch.git] / lib / netdev-linux.c
1 /*
2  * Copyright (c) 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include <assert.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <arpa/inet.h>
22 #include <inttypes.h>
23 #include <linux/if_tun.h>
24 #include <linux/ip.h>
25 #include <linux/types.h>
26 #include <linux/ethtool.h>
27 #include <linux/pkt_sched.h>
28 #include <linux/rtnetlink.h>
29 #include <linux/sockios.h>
30 #include <linux/version.h>
31 #include <sys/types.h>
32 #include <sys/ioctl.h>
33 #include <sys/socket.h>
34 #include <netpacket/packet.h>
35 #include <net/ethernet.h>
36 #include <net/if.h>
37 #include <linux/if_tunnel.h>
38 #include <net/if_arp.h>
39 #include <net/if_packet.h>
40 #include <net/route.h>
41 #include <netinet/in.h>
42 #include <poll.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46
47 #include "coverage.h"
48 #include "dynamic-string.h"
49 #include "fatal-signal.h"
50 #include "netdev-provider.h"
51 #include "netlink.h"
52 #include "ofpbuf.h"
53 #include "openflow/openflow.h"
54 #include "openvswitch/internal_dev.h"
55 #include "openvswitch/gre.h"
56 #include "packets.h"
57 #include "poll-loop.h"
58 #include "rtnetlink.h"
59 #include "socket-util.h"
60 #include "shash.h"
61 #include "svec.h"
62
63 #define THIS_MODULE VLM_netdev_linux
64 #include "vlog.h"
65 \f
66 /* These were introduced in Linux 2.6.14, so they might be missing if we have
67  * old headers. */
68 #ifndef ADVERTISED_Pause
69 #define ADVERTISED_Pause                (1 << 13)
70 #endif
71 #ifndef ADVERTISED_Asym_Pause
72 #define ADVERTISED_Asym_Pause           (1 << 14)
73 #endif
74
75 static struct rtnetlink_notifier netdev_linux_cache_notifier;
76 static int cache_notifier_refcount;
77
78 enum {
79     VALID_IFINDEX = 1 << 0,
80     VALID_ETHERADDR = 1 << 1,
81     VALID_IN4 = 1 << 2,
82     VALID_IN6 = 1 << 3,
83     VALID_MTU = 1 << 4,
84     VALID_CARRIER = 1 << 5,
85     VALID_IS_PSEUDO = 1 << 6,       /* Represents is_internal and is_tap. */
86     VALID_POLICING = 1 << 7
87 };
88
89 struct tap_state {
90     int fd;
91 };
92
93 struct netdev_dev_linux {
94     struct netdev_dev netdev_dev;
95
96     struct shash_node *shash_node;
97     unsigned int cache_valid;
98
99     /* The following are figured out "on demand" only.  They are only valid
100      * when the corresponding VALID_* bit in 'cache_valid' is set. */
101     int ifindex;
102     uint8_t etheraddr[ETH_ADDR_LEN];
103     struct in_addr address, netmask;
104     struct in6_addr in6;
105     int mtu;
106     int carrier;
107     bool is_internal;           /* Is this an openvswitch internal device? */
108     bool is_tap;                /* Is this a tuntap device? */
109     uint32_t kbits_rate;        /* Policing data. */
110     uint32_t kbits_burst;
111
112     union {
113         struct tap_state tap;
114     } state;
115 };
116
117 struct netdev_linux {
118     struct netdev netdev;
119     int fd;
120 };
121
122 /* An AF_INET socket (used for ioctl operations). */
123 static int af_inet_sock = -1;
124
125 struct netdev_linux_notifier {
126     struct netdev_notifier notifier;
127     struct list node;
128 };
129
130 static struct shash netdev_linux_notifiers =
131     SHASH_INITIALIZER(&netdev_linux_notifiers);
132 static struct rtnetlink_notifier netdev_linux_poll_notifier;
133
134 /* This is set pretty low because we probably won't learn anything from the
135  * additional log messages. */
136 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
137
138 static int netdev_linux_init(void);
139
140 static int netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *,
141                                    int cmd, const char *cmd_name);
142 static int netdev_linux_do_ioctl(const char *name, struct ifreq *, int cmd,
143                                  const char *cmd_name);
144 static int netdev_linux_get_ipv4(const struct netdev *, struct in_addr *,
145                                  int cmd, const char *cmd_name);
146 static int get_flags(const struct netdev *, int *flagsp);
147 static int set_flags(struct netdev *, int flags);
148 static int do_get_ifindex(const char *netdev_name);
149 static int get_ifindex(const struct netdev *, int *ifindexp);
150 static int do_set_addr(struct netdev *netdev,
151                        int ioctl_nr, const char *ioctl_name,
152                        struct in_addr addr);
153 static int get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN]);
154 static int set_etheraddr(const char *netdev_name, int hwaddr_family,
155                          const uint8_t[ETH_ADDR_LEN]);
156 static int get_stats_via_netlink(int ifindex, struct netdev_stats *stats);
157 static int get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats);
158 static int get_rtnl_sock(struct nl_sock **);
159
160 static bool
161 is_netdev_linux_class(const struct netdev_class *netdev_class)
162 {
163     return netdev_class->init == netdev_linux_init;
164 }
165
166 static struct netdev_dev_linux *
167 netdev_dev_linux_cast(const struct netdev_dev *netdev_dev)
168 {
169     const struct netdev_class *netdev_class = netdev_dev_get_class(netdev_dev);
170     assert(is_netdev_linux_class(netdev_class));
171
172     return CONTAINER_OF(netdev_dev, struct netdev_dev_linux, netdev_dev);
173 }
174
175 static struct netdev_linux *
176 netdev_linux_cast(const struct netdev *netdev)
177 {
178     struct netdev_dev *netdev_dev = netdev_get_dev(netdev);
179     const struct netdev_class *netdev_class = netdev_dev_get_class(netdev_dev);
180     assert(is_netdev_linux_class(netdev_class));
181
182     return CONTAINER_OF(netdev, struct netdev_linux, netdev);
183 }
184
185 static int
186 netdev_linux_init(void)
187 {
188     static int status = -1;
189     if (status < 0) {
190         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
191         status = af_inet_sock >= 0 ? 0 : errno;
192         if (status) {
193             VLOG_ERR("failed to create inet socket: %s", strerror(status));
194         }
195     }
196     return status;
197 }
198
199 static void
200 netdev_linux_run(void)
201 {
202     rtnetlink_notifier_run();
203 }
204
205 static void
206 netdev_linux_wait(void)
207 {
208     rtnetlink_notifier_wait();
209 }
210
211 static void
212 netdev_linux_cache_cb(const struct rtnetlink_change *change,
213                       void *aux OVS_UNUSED)
214 {
215     struct netdev_dev_linux *dev;
216     if (change) {
217         struct netdev_dev *base_dev = netdev_dev_from_name(change->ifname);
218         if (base_dev) {
219             const struct netdev_class *netdev_class =
220                                                 netdev_dev_get_class(base_dev);
221
222             if (is_netdev_linux_class(netdev_class)) {
223                 dev = netdev_dev_linux_cast(base_dev);
224                 dev->cache_valid = 0;
225             }
226         }
227     } else {
228         struct shash device_shash;
229         struct shash_node *node;
230
231         shash_init(&device_shash);
232         netdev_dev_get_devices(&netdev_linux_class, &device_shash);
233         SHASH_FOR_EACH (node, &device_shash) {
234             dev = node->data;
235             dev->cache_valid = 0;
236         }
237         shash_destroy(&device_shash);
238     }
239 }
240
241 /* Creates the netdev device of 'type' with 'name'. */
242 static int
243 netdev_linux_create_system(const char *name, const char *type OVS_UNUSED,
244                     const struct shash *args, struct netdev_dev **netdev_devp)
245 {
246     struct netdev_dev_linux *netdev_dev;
247     int error;
248
249     if (!shash_is_empty(args)) {
250         VLOG_WARN("%s: arguments for system devices should be empty", name);
251     }
252
253     if (!cache_notifier_refcount) {
254         error = rtnetlink_notifier_register(&netdev_linux_cache_notifier,
255                                             netdev_linux_cache_cb, NULL);
256         if (error) {
257             return error;
258         }
259     }
260     cache_notifier_refcount++;
261
262     netdev_dev = xzalloc(sizeof *netdev_dev);
263     netdev_dev_init(&netdev_dev->netdev_dev, name, &netdev_linux_class);
264
265     *netdev_devp = &netdev_dev->netdev_dev;
266     return 0;
267 }
268
269 /* For most types of netdevs we open the device for each call of
270  * netdev_open().  However, this is not the case with tap devices,
271  * since it is only possible to open the device once.  In this
272  * situation we share a single file descriptor, and consequently
273  * buffers, across all readers.  Therefore once data is read it will
274  * be unavailable to other reads for tap devices. */
275 static int
276 netdev_linux_create_tap(const char *name, const char *type OVS_UNUSED,
277                     const struct shash *args, struct netdev_dev **netdev_devp)
278 {
279     struct netdev_dev_linux *netdev_dev;
280     struct tap_state *state;
281     static const char tap_dev[] = "/dev/net/tun";
282     struct ifreq ifr;
283     int error;
284
285     if (!shash_is_empty(args)) {
286         VLOG_WARN("%s: arguments for TAP devices should be empty", name);
287     }
288
289     netdev_dev = xzalloc(sizeof *netdev_dev);
290     state = &netdev_dev->state.tap;
291
292     /* Open tap device. */
293     state->fd = open(tap_dev, O_RDWR);
294     if (state->fd < 0) {
295         error = errno;
296         VLOG_WARN("opening \"%s\" failed: %s", tap_dev, strerror(error));
297         goto error;
298     }
299
300     /* Create tap device. */
301     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
302     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
303     if (ioctl(state->fd, TUNSETIFF, &ifr) == -1) {
304         VLOG_WARN("%s: creating tap device failed: %s", name,
305                   strerror(errno));
306         error = errno;
307         goto error;
308     }
309
310     /* Make non-blocking. */
311     error = set_nonblocking(state->fd);
312     if (error) {
313         goto error;
314     }
315
316     netdev_dev_init(&netdev_dev->netdev_dev, name, &netdev_tap_class);
317     *netdev_devp = &netdev_dev->netdev_dev;
318     return 0;
319
320 error:
321     free(netdev_dev);
322     return error;
323 }
324
325 static void
326 destroy_tap(struct netdev_dev_linux *netdev_dev)
327 {
328     struct tap_state *state = &netdev_dev->state.tap;
329
330     if (state->fd >= 0) {
331         close(state->fd);
332     }
333 }
334
335 /* Destroys the netdev device 'netdev_dev_'. */
336 static void
337 netdev_linux_destroy(struct netdev_dev *netdev_dev_)
338 {
339     struct netdev_dev_linux *netdev_dev = netdev_dev_linux_cast(netdev_dev_);
340     const char *type = netdev_dev_get_type(netdev_dev_);
341
342     if (!strcmp(type, "system")) {
343         cache_notifier_refcount--;
344
345         if (!cache_notifier_refcount) {
346             rtnetlink_notifier_unregister(&netdev_linux_cache_notifier);
347         }
348     } else if (!strcmp(type, "tap")) {
349         destroy_tap(netdev_dev);
350     }
351
352     free(netdev_dev);
353 }
354
355 static int
356 netdev_linux_open(struct netdev_dev *netdev_dev_, int ethertype,
357                   struct netdev **netdevp)
358 {
359     struct netdev_dev_linux *netdev_dev = netdev_dev_linux_cast(netdev_dev_);
360     struct netdev_linux *netdev;
361     enum netdev_flags flags;
362     int error;
363
364     /* Allocate network device. */
365     netdev = xzalloc(sizeof *netdev);
366     netdev->fd = -1;
367     netdev_init(&netdev->netdev, netdev_dev_);
368
369     error = netdev_get_flags(&netdev->netdev, &flags);
370     if (error == ENODEV) {
371         goto error;
372     }
373
374     if (!strcmp(netdev_dev_get_type(netdev_dev_), "tap")) {
375         netdev->fd = netdev_dev->state.tap.fd;
376     } else if (ethertype != NETDEV_ETH_TYPE_NONE) {
377         struct sockaddr_ll sll;
378         int protocol;
379         int ifindex;
380
381         /* Create file descriptor. */
382         protocol = (ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
383                     : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
384                     : ethertype);
385         netdev->fd = socket(PF_PACKET, SOCK_RAW, htons(protocol));
386         if (netdev->fd < 0) {
387             error = errno;
388             goto error;
389         }
390
391         /* Set non-blocking mode. */
392         error = set_nonblocking(netdev->fd);
393         if (error) {
394             goto error;
395         }
396
397         /* Get ethernet device index. */
398         error = get_ifindex(&netdev->netdev, &ifindex);
399         if (error) {
400             goto error;
401         }
402
403         /* Bind to specific ethernet device. */
404         memset(&sll, 0, sizeof sll);
405         sll.sll_family = AF_PACKET;
406         sll.sll_ifindex = ifindex;
407         if (bind(netdev->fd,
408                  (struct sockaddr *) &sll, sizeof sll) < 0) {
409             error = errno;
410             VLOG_ERR("bind to %s failed: %s", netdev_dev_get_name(netdev_dev_),
411                      strerror(error));
412             goto error;
413         }
414
415         /* Between the socket() and bind() calls above, the socket receives all
416          * packets of the requested type on all system interfaces.  We do not
417          * want to receive that data, but there is no way to avoid it.  So we
418          * must now drain out the receive queue. */
419         error = drain_rcvbuf(netdev->fd);
420         if (error) {
421             goto error;
422         }
423     }
424
425     *netdevp = &netdev->netdev;
426     return 0;
427
428 error:
429     netdev_uninit(&netdev->netdev, true);
430     return error;
431 }
432
433 /* Closes and destroys 'netdev'. */
434 static void
435 netdev_linux_close(struct netdev *netdev_)
436 {
437     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
438
439     if (netdev->fd > 0 && strcmp(netdev_get_type(netdev_), "tap")) {
440         close(netdev->fd);
441     }
442     free(netdev);
443 }
444
445 /* Initializes 'svec' with a list of the names of all known network devices. */
446 static int
447 netdev_linux_enumerate(struct svec *svec)
448 {
449     struct if_nameindex *names;
450
451     names = if_nameindex();
452     if (names) {
453         size_t i;
454
455         for (i = 0; names[i].if_name != NULL; i++) {
456             svec_add(svec, names[i].if_name);
457         }
458         if_freenameindex(names);
459         return 0;
460     } else {
461         VLOG_WARN("could not obtain list of network device names: %s",
462                   strerror(errno));
463         return errno;
464     }
465 }
466
467 static int
468 netdev_linux_recv(struct netdev *netdev_, void *data, size_t size)
469 {
470     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
471
472     if (netdev->fd < 0) {
473         /* Device was opened with NETDEV_ETH_TYPE_NONE. */
474         return -EAGAIN;
475     }
476
477     for (;;) {
478         ssize_t retval = read(netdev->fd, data, size);
479         if (retval >= 0) {
480             return retval;
481         } else if (errno != EINTR) {
482             if (errno != EAGAIN) {
483                 VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
484                              strerror(errno), netdev_get_name(netdev_));
485             }
486             return -errno;
487         }
488     }
489 }
490
491 /* Registers with the poll loop to wake up from the next call to poll_block()
492  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
493 static void
494 netdev_linux_recv_wait(struct netdev *netdev_)
495 {
496     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
497     if (netdev->fd >= 0) {
498         poll_fd_wait(netdev->fd, POLLIN);
499     }
500 }
501
502 /* Discards all packets waiting to be received from 'netdev'. */
503 static int
504 netdev_linux_drain(struct netdev *netdev_)
505 {
506     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
507     if (netdev->fd < 0) {
508         return 0;
509     } else if (!strcmp(netdev_get_type(netdev_), "tap")) {
510         struct ifreq ifr;
511         int error = netdev_linux_do_ioctl(netdev_get_name(netdev_), &ifr,
512                                           SIOCGIFTXQLEN, "SIOCGIFTXQLEN");
513         if (error) {
514             return error;
515         }
516         drain_fd(netdev->fd, ifr.ifr_qlen);
517         return 0;
518     } else {
519         return drain_rcvbuf(netdev->fd);
520     }
521 }
522
523 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
524  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
525  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
526  * the packet is too big or too small to transmit on the device.
527  *
528  * The caller retains ownership of 'buffer' in all cases.
529  *
530  * The kernel maintains a packet transmission queue, so the caller is not
531  * expected to do additional queuing of packets. */
532 static int
533 netdev_linux_send(struct netdev *netdev_, const void *data, size_t size)
534 {
535     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
536
537     /* XXX should support sending even if 'ethertype' was NETDEV_ETH_TYPE_NONE.
538      */
539     if (netdev->fd < 0) {
540         return EPIPE;
541     }
542
543     for (;;) {
544         ssize_t retval = write(netdev->fd, data, size);
545         if (retval < 0) {
546             /* The Linux AF_PACKET implementation never blocks waiting for room
547              * for packets, instead returning ENOBUFS.  Translate this into
548              * EAGAIN for the caller. */
549             if (errno == ENOBUFS) {
550                 return EAGAIN;
551             } else if (errno == EINTR) {
552                 continue;
553             } else if (errno != EAGAIN) {
554                 VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: %s",
555                              netdev_get_name(netdev_), strerror(errno));
556             }
557             return errno;
558         } else if (retval != size) {
559             VLOG_WARN_RL(&rl, "sent partial Ethernet packet (%zd bytes of "
560                          "%zu) on %s", retval, size, netdev_get_name(netdev_));
561             return EMSGSIZE;
562         } else {
563             return 0;
564         }
565     }
566 }
567
568 /* Registers with the poll loop to wake up from the next call to poll_block()
569  * when the packet transmission queue has sufficient room to transmit a packet
570  * with netdev_send().
571  *
572  * The kernel maintains a packet transmission queue, so the client is not
573  * expected to do additional queuing of packets.  Thus, this function is
574  * unlikely to ever be used.  It is included for completeness. */
575 static void
576 netdev_linux_send_wait(struct netdev *netdev_)
577 {
578     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
579     if (netdev->fd < 0) {
580         /* Nothing to do. */
581     } else if (strcmp(netdev_get_type(netdev_), "tap")) {
582         poll_fd_wait(netdev->fd, POLLOUT);
583     } else {
584         /* TAP device always accepts packets.*/
585         poll_immediate_wake();
586     }
587 }
588
589 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
590  * otherwise a positive errno value. */
591 static int
592 netdev_linux_set_etheraddr(struct netdev *netdev_,
593                            const uint8_t mac[ETH_ADDR_LEN])
594 {
595     struct netdev_dev_linux *netdev_dev =
596                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
597     int error;
598
599     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)
600         || !eth_addr_equals(netdev_dev->etheraddr, mac)) {
601         error = set_etheraddr(netdev_get_name(netdev_), ARPHRD_ETHER, mac);
602         if (!error) {
603             netdev_dev->cache_valid |= VALID_ETHERADDR;
604             memcpy(netdev_dev->etheraddr, mac, ETH_ADDR_LEN);
605         }
606     } else {
607         error = 0;
608     }
609     return error;
610 }
611
612 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
613  * free the returned buffer. */
614 static int
615 netdev_linux_get_etheraddr(const struct netdev *netdev_,
616                            uint8_t mac[ETH_ADDR_LEN])
617 {
618     struct netdev_dev_linux *netdev_dev =
619                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
620     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)) {
621         int error = get_etheraddr(netdev_get_name(netdev_),
622                                   netdev_dev->etheraddr);
623         if (error) {
624             return error;
625         }
626         netdev_dev->cache_valid |= VALID_ETHERADDR;
627     }
628     memcpy(mac, netdev_dev->etheraddr, ETH_ADDR_LEN);
629     return 0;
630 }
631
632 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
633  * in bytes, not including the hardware header; thus, this is typically 1500
634  * bytes for Ethernet devices. */
635 static int
636 netdev_linux_get_mtu(const struct netdev *netdev_, int *mtup)
637 {
638     struct netdev_dev_linux *netdev_dev =
639                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
640     if (!(netdev_dev->cache_valid & VALID_MTU)) {
641         struct ifreq ifr;
642         int error;
643
644         error = netdev_linux_do_ioctl(netdev_get_name(netdev_), &ifr,
645                                       SIOCGIFMTU, "SIOCGIFMTU");
646         if (error) {
647             return error;
648         }
649         netdev_dev->mtu = ifr.ifr_mtu;
650         netdev_dev->cache_valid |= VALID_MTU;
651     }
652     *mtup = netdev_dev->mtu;
653     return 0;
654 }
655
656 /* Returns the ifindex of 'netdev', if successful, as a positive number.
657  * On failure, returns a negative errno value. */
658 static int
659 netdev_linux_get_ifindex(const struct netdev *netdev)
660 {
661     int ifindex, error;
662
663     error = get_ifindex(netdev, &ifindex);
664     return error ? -error : ifindex;
665 }
666
667 static int
668 netdev_linux_get_carrier(const struct netdev *netdev_, bool *carrier)
669 {
670     struct netdev_dev_linux *netdev_dev =
671                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
672     int error = 0;
673     char *fn = NULL;
674     int fd = -1;
675
676     if (!(netdev_dev->cache_valid & VALID_CARRIER)) {
677         char line[8];
678         int retval;
679
680         fn = xasprintf("/sys/class/net/%s/carrier",
681                        netdev_get_name(netdev_));
682         fd = open(fn, O_RDONLY);
683         if (fd < 0) {
684             error = errno;
685             VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(error));
686             goto exit;
687         }
688
689         retval = read(fd, line, sizeof line);
690         if (retval < 0) {
691             error = errno;
692             if (error == EINVAL) {
693                 /* This is the normal return value when we try to check carrier
694                  * if the network device is not up. */
695             } else {
696                 VLOG_WARN_RL(&rl, "%s: read failed: %s", fn, strerror(error));
697             }
698             goto exit;
699         } else if (retval == 0) {
700             error = EPROTO;
701             VLOG_WARN_RL(&rl, "%s: unexpected end of file", fn);
702             goto exit;
703         }
704
705         if (line[0] != '0' && line[0] != '1') {
706             error = EPROTO;
707             VLOG_WARN_RL(&rl, "%s: value is %c (expected 0 or 1)",
708                          fn, line[0]);
709             goto exit;
710         }
711         netdev_dev->carrier = line[0] != '0';
712         netdev_dev->cache_valid |= VALID_CARRIER;
713     }
714     *carrier = netdev_dev->carrier;
715     error = 0;
716
717 exit:
718     if (fd >= 0) {
719         close(fd);
720     }
721     free(fn);
722     return error;
723 }
724
725 /* Check whether we can we use RTM_GETLINK to get network device statistics.
726  * In pre-2.6.19 kernels, this was only available if wireless extensions were
727  * enabled. */
728 static bool
729 check_for_working_netlink_stats(void)
730 {
731     /* Decide on the netdev_get_stats() implementation to use.  Netlink is
732      * preferable, so if that works, we'll use it. */
733     int ifindex = do_get_ifindex("lo");
734     if (ifindex < 0) {
735         VLOG_WARN("failed to get ifindex for lo, "
736                   "obtaining netdev stats from proc");
737         return false;
738     } else {
739         struct netdev_stats stats;
740         int error = get_stats_via_netlink(ifindex, &stats);
741         if (!error) {
742             VLOG_DBG("obtaining netdev stats via rtnetlink");
743             return true;
744         } else {
745             VLOG_INFO("RTM_GETLINK failed (%s), obtaining netdev stats "
746                       "via proc (you are probably running a pre-2.6.19 "
747                       "kernel)", strerror(error));
748             return false;
749         }
750     }
751 }
752
753 /* Brings the 'is_internal' and 'is_tap' members of 'netdev_dev' up-to-date. */
754 static void
755 netdev_linux_update_is_pseudo(struct netdev_dev_linux *netdev_dev)
756 {
757     if (!(netdev_dev->cache_valid & VALID_IS_PSEUDO)) {
758         const char *name = netdev_dev_get_name(&netdev_dev->netdev_dev);
759         const char *type = netdev_dev_get_type(&netdev_dev->netdev_dev);
760         
761         netdev_dev->is_tap = !strcmp(type, "tap");
762         netdev_dev->is_internal = false;
763         if (!netdev_dev->is_tap) {
764             struct ethtool_drvinfo drvinfo;
765             int error;
766
767             memset(&drvinfo, 0, sizeof drvinfo);
768             error = netdev_linux_do_ethtool(name,
769                                             (struct ethtool_cmd *)&drvinfo,
770                                             ETHTOOL_GDRVINFO,
771                                             "ETHTOOL_GDRVINFO");
772
773             if (!error && !strcmp(drvinfo.driver, "openvswitch")) {
774                 netdev_dev->is_internal = true;
775             }
776         }
777
778         netdev_dev->cache_valid |= VALID_IS_PSEUDO;
779     }
780 }
781
782 static void
783 swap_uint64(uint64_t *a, uint64_t *b)
784 {
785     *a ^= *b;
786     *b ^= *a;
787     *a ^= *b;
788 }
789
790 /* Retrieves current device stats for 'netdev'.
791  *
792  * XXX All of the members of struct netdev_stats are 64 bits wide, but on
793  * 32-bit architectures the Linux network stats are only 32 bits. */
794 static int
795 netdev_linux_get_stats(const struct netdev *netdev_,
796                        struct netdev_stats *stats)
797 {
798     struct netdev_dev_linux *netdev_dev =
799                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
800     static int use_netlink_stats = -1;
801     int error;
802
803     COVERAGE_INC(netdev_get_stats);
804
805     if (use_netlink_stats < 0) {
806         use_netlink_stats = check_for_working_netlink_stats();
807     }
808     if (use_netlink_stats) {
809         int ifindex;
810
811         error = get_ifindex(netdev_, &ifindex);
812         if (!error) {
813             error = get_stats_via_netlink(ifindex, stats);
814         }
815     } else {
816         error = get_stats_via_proc(netdev_get_name(netdev_), stats);
817     }
818
819     /* If this port is an internal port then the transmit and receive stats
820      * will appear to be swapped relative to the other ports since we are the
821      * one sending the data, not a remote computer.  For consistency, we swap
822      * them back here. */
823     netdev_linux_update_is_pseudo(netdev_dev);
824     if (!error && (netdev_dev->is_internal || netdev_dev->is_tap)) {
825         swap_uint64(&stats->rx_packets, &stats->tx_packets);
826         swap_uint64(&stats->rx_bytes, &stats->tx_bytes);
827         swap_uint64(&stats->rx_errors, &stats->tx_errors);
828         swap_uint64(&stats->rx_dropped, &stats->tx_dropped);
829         stats->rx_length_errors = 0;
830         stats->rx_over_errors = 0;
831         stats->rx_crc_errors = 0;
832         stats->rx_frame_errors = 0;
833         stats->rx_fifo_errors = 0;
834         stats->rx_missed_errors = 0;
835         stats->tx_aborted_errors = 0;
836         stats->tx_carrier_errors = 0;
837         stats->tx_fifo_errors = 0;
838         stats->tx_heartbeat_errors = 0;
839         stats->tx_window_errors = 0;
840     }
841
842     return error;
843 }
844
845 static int
846 netdev_linux_set_stats(struct netdev *netdev,
847                        const struct netdev_stats *stats)
848 {
849     struct netdev_dev_linux *netdev_dev =
850         netdev_dev_linux_cast(netdev_get_dev(netdev));
851     struct internal_dev_stats dp_dev_stats;
852     struct ifreq ifr;
853
854     /* We must reject this call if 'netdev' is not an Open vSwitch internal
855      * port, because the ioctl that we are about to execute is in the "device
856      * private ioctls" range, which means that executing it on a device that
857      * is not the type we expect could do any random thing.
858      *
859      * (Amusingly, these ioctl numbers are commented "THESE IOCTLS ARE
860      * _DEPRECATED_ AND WILL DISAPPEAR IN 2.5.X" in linux/sockios.h.  I guess
861      * DaveM is a little behind on that.) */
862     netdev_linux_update_is_pseudo(netdev_dev);
863     if (!netdev_dev->is_internal) {
864         return EOPNOTSUPP;
865     }
866
867     /* This actually only sets the *offset* that the dp_dev applies, but in our
868      * usage for fake bond devices the dp_dev never has any traffic of it own
869      * so it has the same effect. */
870     dp_dev_stats.rx_packets = stats->rx_packets;
871     dp_dev_stats.rx_bytes = stats->rx_bytes;
872     dp_dev_stats.tx_packets = stats->tx_packets;
873     dp_dev_stats.tx_bytes = stats->tx_bytes;
874     ifr.ifr_data = (void *) &dp_dev_stats;
875     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr,
876                                  INTERNAL_DEV_SET_STATS,
877                                  "INTERNAL_DEV_SET_STATS");
878 }
879
880 /* Stores the features supported by 'netdev' into each of '*current',
881  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
882  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
883  * successful, otherwise a positive errno value. */
884 static int
885 netdev_linux_get_features(struct netdev *netdev,
886                           uint32_t *current, uint32_t *advertised,
887                           uint32_t *supported, uint32_t *peer)
888 {
889     struct ethtool_cmd ecmd;
890     int error;
891
892     memset(&ecmd, 0, sizeof ecmd);
893     error = netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
894                                     ETHTOOL_GSET, "ETHTOOL_GSET");
895     if (error) {
896         return error;
897     }
898
899     /* Supported features. */
900     *supported = 0;
901     if (ecmd.supported & SUPPORTED_10baseT_Half) {
902         *supported |= OFPPF_10MB_HD;
903     }
904     if (ecmd.supported & SUPPORTED_10baseT_Full) {
905         *supported |= OFPPF_10MB_FD;
906     }
907     if (ecmd.supported & SUPPORTED_100baseT_Half)  {
908         *supported |= OFPPF_100MB_HD;
909     }
910     if (ecmd.supported & SUPPORTED_100baseT_Full) {
911         *supported |= OFPPF_100MB_FD;
912     }
913     if (ecmd.supported & SUPPORTED_1000baseT_Half) {
914         *supported |= OFPPF_1GB_HD;
915     }
916     if (ecmd.supported & SUPPORTED_1000baseT_Full) {
917         *supported |= OFPPF_1GB_FD;
918     }
919     if (ecmd.supported & SUPPORTED_10000baseT_Full) {
920         *supported |= OFPPF_10GB_FD;
921     }
922     if (ecmd.supported & SUPPORTED_TP) {
923         *supported |= OFPPF_COPPER;
924     }
925     if (ecmd.supported & SUPPORTED_FIBRE) {
926         *supported |= OFPPF_FIBER;
927     }
928     if (ecmd.supported & SUPPORTED_Autoneg) {
929         *supported |= OFPPF_AUTONEG;
930     }
931     if (ecmd.supported & SUPPORTED_Pause) {
932         *supported |= OFPPF_PAUSE;
933     }
934     if (ecmd.supported & SUPPORTED_Asym_Pause) {
935         *supported |= OFPPF_PAUSE_ASYM;
936     }
937
938     /* Advertised features. */
939     *advertised = 0;
940     if (ecmd.advertising & ADVERTISED_10baseT_Half) {
941         *advertised |= OFPPF_10MB_HD;
942     }
943     if (ecmd.advertising & ADVERTISED_10baseT_Full) {
944         *advertised |= OFPPF_10MB_FD;
945     }
946     if (ecmd.advertising & ADVERTISED_100baseT_Half) {
947         *advertised |= OFPPF_100MB_HD;
948     }
949     if (ecmd.advertising & ADVERTISED_100baseT_Full) {
950         *advertised |= OFPPF_100MB_FD;
951     }
952     if (ecmd.advertising & ADVERTISED_1000baseT_Half) {
953         *advertised |= OFPPF_1GB_HD;
954     }
955     if (ecmd.advertising & ADVERTISED_1000baseT_Full) {
956         *advertised |= OFPPF_1GB_FD;
957     }
958     if (ecmd.advertising & ADVERTISED_10000baseT_Full) {
959         *advertised |= OFPPF_10GB_FD;
960     }
961     if (ecmd.advertising & ADVERTISED_TP) {
962         *advertised |= OFPPF_COPPER;
963     }
964     if (ecmd.advertising & ADVERTISED_FIBRE) {
965         *advertised |= OFPPF_FIBER;
966     }
967     if (ecmd.advertising & ADVERTISED_Autoneg) {
968         *advertised |= OFPPF_AUTONEG;
969     }
970     if (ecmd.advertising & ADVERTISED_Pause) {
971         *advertised |= OFPPF_PAUSE;
972     }
973     if (ecmd.advertising & ADVERTISED_Asym_Pause) {
974         *advertised |= OFPPF_PAUSE_ASYM;
975     }
976
977     /* Current settings. */
978     if (ecmd.speed == SPEED_10) {
979         *current = ecmd.duplex ? OFPPF_10MB_FD : OFPPF_10MB_HD;
980     } else if (ecmd.speed == SPEED_100) {
981         *current = ecmd.duplex ? OFPPF_100MB_FD : OFPPF_100MB_HD;
982     } else if (ecmd.speed == SPEED_1000) {
983         *current = ecmd.duplex ? OFPPF_1GB_FD : OFPPF_1GB_HD;
984     } else if (ecmd.speed == SPEED_10000) {
985         *current = OFPPF_10GB_FD;
986     } else {
987         *current = 0;
988     }
989
990     if (ecmd.port == PORT_TP) {
991         *current |= OFPPF_COPPER;
992     } else if (ecmd.port == PORT_FIBRE) {
993         *current |= OFPPF_FIBER;
994     }
995
996     if (ecmd.autoneg) {
997         *current |= OFPPF_AUTONEG;
998     }
999
1000     /* Peer advertisements. */
1001     *peer = 0;                  /* XXX */
1002
1003     return 0;
1004 }
1005
1006 /* Set the features advertised by 'netdev' to 'advertise'. */
1007 static int
1008 netdev_linux_set_advertisements(struct netdev *netdev, uint32_t advertise)
1009 {
1010     struct ethtool_cmd ecmd;
1011     int error;
1012
1013     memset(&ecmd, 0, sizeof ecmd);
1014     error = netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1015                                     ETHTOOL_GSET, "ETHTOOL_GSET");
1016     if (error) {
1017         return error;
1018     }
1019
1020     ecmd.advertising = 0;
1021     if (advertise & OFPPF_10MB_HD) {
1022         ecmd.advertising |= ADVERTISED_10baseT_Half;
1023     }
1024     if (advertise & OFPPF_10MB_FD) {
1025         ecmd.advertising |= ADVERTISED_10baseT_Full;
1026     }
1027     if (advertise & OFPPF_100MB_HD) {
1028         ecmd.advertising |= ADVERTISED_100baseT_Half;
1029     }
1030     if (advertise & OFPPF_100MB_FD) {
1031         ecmd.advertising |= ADVERTISED_100baseT_Full;
1032     }
1033     if (advertise & OFPPF_1GB_HD) {
1034         ecmd.advertising |= ADVERTISED_1000baseT_Half;
1035     }
1036     if (advertise & OFPPF_1GB_FD) {
1037         ecmd.advertising |= ADVERTISED_1000baseT_Full;
1038     }
1039     if (advertise & OFPPF_10GB_FD) {
1040         ecmd.advertising |= ADVERTISED_10000baseT_Full;
1041     }
1042     if (advertise & OFPPF_COPPER) {
1043         ecmd.advertising |= ADVERTISED_TP;
1044     }
1045     if (advertise & OFPPF_FIBER) {
1046         ecmd.advertising |= ADVERTISED_FIBRE;
1047     }
1048     if (advertise & OFPPF_AUTONEG) {
1049         ecmd.advertising |= ADVERTISED_Autoneg;
1050     }
1051     if (advertise & OFPPF_PAUSE) {
1052         ecmd.advertising |= ADVERTISED_Pause;
1053     }
1054     if (advertise & OFPPF_PAUSE_ASYM) {
1055         ecmd.advertising |= ADVERTISED_Asym_Pause;
1056     }
1057     return netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1058                                    ETHTOOL_SSET, "ETHTOOL_SSET");
1059 }
1060
1061 /* If 'netdev_name' is the name of a VLAN network device (e.g. one created with
1062  * vconfig(8)), sets '*vlan_vid' to the VLAN VID associated with that device
1063  * and returns 0.  Otherwise returns a errno value (specifically ENOENT if
1064  * 'netdev_name' is the name of a network device that is not a VLAN device) and
1065  * sets '*vlan_vid' to -1. */
1066 static int
1067 netdev_linux_get_vlan_vid(const struct netdev *netdev, int *vlan_vid)
1068 {
1069     const char *netdev_name = netdev_get_name(netdev);
1070     struct ds line = DS_EMPTY_INITIALIZER;
1071     FILE *stream = NULL;
1072     int error;
1073     char *fn;
1074
1075     COVERAGE_INC(netdev_get_vlan_vid);
1076     fn = xasprintf("/proc/net/vlan/%s", netdev_name);
1077     stream = fopen(fn, "r");
1078     if (!stream) {
1079         error = errno;
1080         goto done;
1081     }
1082
1083     if (ds_get_line(&line, stream)) {
1084         if (ferror(stream)) {
1085             error = errno;
1086             VLOG_ERR_RL(&rl, "error reading \"%s\": %s", fn, strerror(errno));
1087         } else {
1088             error = EPROTO;
1089             VLOG_ERR_RL(&rl, "unexpected end of file reading \"%s\"", fn);
1090         }
1091         goto done;
1092     }
1093
1094     if (!sscanf(ds_cstr(&line), "%*s VID: %d", vlan_vid)) {
1095         error = EPROTO;
1096         VLOG_ERR_RL(&rl, "parse error reading \"%s\" line 1: \"%s\"",
1097                     fn, ds_cstr(&line));
1098         goto done;
1099     }
1100
1101     error = 0;
1102
1103 done:
1104     free(fn);
1105     if (stream) {
1106         fclose(stream);
1107     }
1108     ds_destroy(&line);
1109     if (error) {
1110         *vlan_vid = -1;
1111     }
1112     return error;
1113 }
1114
1115 #define POLICE_ADD_CMD "/sbin/tc qdisc add dev %s handle ffff: ingress"
1116 #define POLICE_CONFIG_CMD "/sbin/tc filter add dev %s parent ffff: protocol ip prio 50 u32 match ip src 0.0.0.0/0 police rate %dkbit burst %dk mtu 65535 drop flowid :1"
1117
1118 /* Remove ingress policing from 'netdev'.  Returns 0 if successful, otherwise a
1119  * positive errno value.
1120  *
1121  * This function is equivalent to running
1122  *     /sbin/tc qdisc del dev %s handle ffff: ingress
1123  * but it is much, much faster.
1124  */
1125 static int
1126 netdev_linux_remove_policing(struct netdev *netdev)
1127 {
1128     struct netdev_dev_linux *netdev_dev =
1129         netdev_dev_linux_cast(netdev_get_dev(netdev));
1130     const char *netdev_name = netdev_get_name(netdev);
1131
1132     struct ofpbuf request;
1133     struct ofpbuf *reply;
1134     struct tcmsg *tcmsg;
1135     struct nl_sock *rtnl_sock;
1136     int ifindex;
1137     int error;
1138
1139     error = get_ifindex(netdev, &ifindex);
1140     if (error) {
1141         return error;
1142     }
1143
1144     error = get_rtnl_sock(&rtnl_sock);
1145     if (error) {
1146         return error;
1147     }
1148
1149     ofpbuf_init(&request, 0);
1150     nl_msg_put_nlmsghdr(&request, rtnl_sock, sizeof *tcmsg,
1151                         RTM_DELQDISC, NLM_F_REQUEST);
1152     tcmsg = ofpbuf_put_zeros(&request, sizeof *tcmsg);
1153     tcmsg->tcm_family = AF_UNSPEC;
1154     tcmsg->tcm_ifindex = ifindex;
1155     tcmsg->tcm_handle = 0xffff0000;
1156     tcmsg->tcm_parent = TC_H_INGRESS;
1157     nl_msg_put_string(&request, TCA_KIND, "ingress");
1158     nl_msg_put_unspec(&request, TCA_OPTIONS, NULL, 0);
1159     error = nl_sock_transact(rtnl_sock, &request, &reply);
1160     ofpbuf_uninit(&request);
1161     ofpbuf_delete(reply);
1162     if (error && error != ENOENT && error != EINVAL) {
1163         VLOG_WARN_RL(&rl, "%s: removing policing failed: %s",
1164                      netdev_name, strerror(error));
1165         return error;
1166     }
1167
1168     netdev_dev->kbits_rate = 0;
1169     netdev_dev->kbits_burst = 0;
1170     netdev_dev->cache_valid |= VALID_POLICING;
1171     return 0;
1172 }
1173
1174 /* Attempts to set input rate limiting (policing) policy. */
1175 static int
1176 netdev_linux_set_policing(struct netdev *netdev,
1177                           uint32_t kbits_rate, uint32_t kbits_burst)
1178 {
1179     struct netdev_dev_linux *netdev_dev =
1180         netdev_dev_linux_cast(netdev_get_dev(netdev));
1181     const char *netdev_name = netdev_get_name(netdev);
1182     char command[1024];
1183
1184     COVERAGE_INC(netdev_set_policing);
1185
1186     kbits_burst = (!kbits_rate ? 0       /* Force to 0 if no rate specified. */
1187                    : !kbits_burst ? 1000 /* Default to 1000 kbits if 0. */
1188                    : kbits_burst);       /* Stick with user-specified value. */
1189
1190     if (netdev_dev->cache_valid & VALID_POLICING
1191         && netdev_dev->kbits_rate == kbits_rate
1192         && netdev_dev->kbits_burst == kbits_burst) {
1193         /* Assume that settings haven't changed since we last set them. */
1194         return 0;
1195     }
1196
1197     netdev_linux_remove_policing(netdev);
1198     if (kbits_rate) {
1199         snprintf(command, sizeof(command), POLICE_ADD_CMD, netdev_name);
1200         if (system(command) != 0) {
1201             VLOG_WARN_RL(&rl, "%s: problem adding policing", netdev_name);
1202             return -1;
1203         }
1204
1205         snprintf(command, sizeof(command), POLICE_CONFIG_CMD, netdev_name,
1206                 kbits_rate, kbits_burst);
1207         if (system(command) != 0) {
1208             VLOG_WARN_RL(&rl, "%s: problem configuring policing",
1209                     netdev_name);
1210             return -1;
1211         }
1212
1213         netdev_dev->kbits_rate = kbits_rate;
1214         netdev_dev->kbits_burst = kbits_burst;
1215         netdev_dev->cache_valid |= VALID_POLICING;
1216     }
1217
1218     return 0;
1219 }
1220
1221 static int
1222 netdev_linux_get_in4(const struct netdev *netdev_,
1223                      struct in_addr *address, struct in_addr *netmask)
1224 {
1225     struct netdev_dev_linux *netdev_dev =
1226                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1227
1228     if (!(netdev_dev->cache_valid & VALID_IN4)) {
1229         int error;
1230
1231         error = netdev_linux_get_ipv4(netdev_, &netdev_dev->address,
1232                                       SIOCGIFADDR, "SIOCGIFADDR");
1233         if (error) {
1234             return error;
1235         }
1236
1237         error = netdev_linux_get_ipv4(netdev_, &netdev_dev->netmask,
1238                                       SIOCGIFNETMASK, "SIOCGIFNETMASK");
1239         if (error) {
1240             return error;
1241         }
1242
1243         netdev_dev->cache_valid |= VALID_IN4;
1244     }
1245     *address = netdev_dev->address;
1246     *netmask = netdev_dev->netmask;
1247     return address->s_addr == INADDR_ANY ? EADDRNOTAVAIL : 0;
1248 }
1249
1250 static int
1251 netdev_linux_set_in4(struct netdev *netdev_, struct in_addr address,
1252                      struct in_addr netmask)
1253 {
1254     struct netdev_dev_linux *netdev_dev =
1255                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1256     int error;
1257
1258     error = do_set_addr(netdev_, SIOCSIFADDR, "SIOCSIFADDR", address);
1259     if (!error) {
1260         netdev_dev->cache_valid |= VALID_IN4;
1261         netdev_dev->address = address;
1262         netdev_dev->netmask = netmask;
1263         if (address.s_addr != INADDR_ANY) {
1264             error = do_set_addr(netdev_, SIOCSIFNETMASK,
1265                                 "SIOCSIFNETMASK", netmask);
1266         }
1267     }
1268     return error;
1269 }
1270
1271 static bool
1272 parse_if_inet6_line(const char *line,
1273                     struct in6_addr *in6, char ifname[16 + 1])
1274 {
1275     uint8_t *s6 = in6->s6_addr;
1276 #define X8 "%2"SCNx8
1277     return sscanf(line,
1278                   " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
1279                   "%*x %*x %*x %*x %16s\n",
1280                   &s6[0], &s6[1], &s6[2], &s6[3],
1281                   &s6[4], &s6[5], &s6[6], &s6[7],
1282                   &s6[8], &s6[9], &s6[10], &s6[11],
1283                   &s6[12], &s6[13], &s6[14], &s6[15],
1284                   ifname) == 17;
1285 }
1286
1287 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
1288  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
1289 static int
1290 netdev_linux_get_in6(const struct netdev *netdev_, struct in6_addr *in6)
1291 {
1292     struct netdev_dev_linux *netdev_dev =
1293                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1294     if (!(netdev_dev->cache_valid & VALID_IN6)) {
1295         FILE *file;
1296         char line[128];
1297
1298         netdev_dev->in6 = in6addr_any;
1299
1300         file = fopen("/proc/net/if_inet6", "r");
1301         if (file != NULL) {
1302             const char *name = netdev_get_name(netdev_);
1303             while (fgets(line, sizeof line, file)) {
1304                 struct in6_addr in6;
1305                 char ifname[16 + 1];
1306                 if (parse_if_inet6_line(line, &in6, ifname)
1307                     && !strcmp(name, ifname))
1308                 {
1309                     netdev_dev->in6 = in6;
1310                     break;
1311                 }
1312             }
1313             fclose(file);
1314         }
1315         netdev_dev->cache_valid |= VALID_IN6;
1316     }
1317     *in6 = netdev_dev->in6;
1318     return 0;
1319 }
1320
1321 static void
1322 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
1323 {
1324     struct sockaddr_in sin;
1325     memset(&sin, 0, sizeof sin);
1326     sin.sin_family = AF_INET;
1327     sin.sin_addr = addr;
1328     sin.sin_port = 0;
1329
1330     memset(sa, 0, sizeof *sa);
1331     memcpy(sa, &sin, sizeof sin);
1332 }
1333
1334 static int
1335 do_set_addr(struct netdev *netdev,
1336             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
1337 {
1338     struct ifreq ifr;
1339     strncpy(ifr.ifr_name, netdev_get_name(netdev), sizeof ifr.ifr_name);
1340     make_in4_sockaddr(&ifr.ifr_addr, addr);
1341
1342     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, ioctl_nr,
1343                                  ioctl_name);
1344 }
1345
1346 /* Adds 'router' as a default IP gateway. */
1347 static int
1348 netdev_linux_add_router(struct netdev *netdev OVS_UNUSED, struct in_addr router)
1349 {
1350     struct in_addr any = { INADDR_ANY };
1351     struct rtentry rt;
1352     int error;
1353
1354     memset(&rt, 0, sizeof rt);
1355     make_in4_sockaddr(&rt.rt_dst, any);
1356     make_in4_sockaddr(&rt.rt_gateway, router);
1357     make_in4_sockaddr(&rt.rt_genmask, any);
1358     rt.rt_flags = RTF_UP | RTF_GATEWAY;
1359     COVERAGE_INC(netdev_add_router);
1360     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
1361     if (error) {
1362         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
1363     }
1364     return error;
1365 }
1366
1367 static int
1368 netdev_linux_get_next_hop(const struct in_addr *host, struct in_addr *next_hop,
1369                           char **netdev_name)
1370 {
1371     static const char fn[] = "/proc/net/route";
1372     FILE *stream;
1373     char line[256];
1374     int ln;
1375
1376     *netdev_name = NULL;
1377     stream = fopen(fn, "r");
1378     if (stream == NULL) {
1379         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1380         return errno;
1381     }
1382
1383     ln = 0;
1384     while (fgets(line, sizeof line, stream)) {
1385         if (++ln >= 2) {
1386             char iface[17];
1387             uint32_t dest, gateway, mask;
1388             int refcnt, metric, mtu;
1389             unsigned int flags, use, window, irtt;
1390
1391             if (sscanf(line,
1392                        "%16s %"SCNx32" %"SCNx32" %04X %d %u %d %"SCNx32
1393                        " %d %u %u\n",
1394                        iface, &dest, &gateway, &flags, &refcnt,
1395                        &use, &metric, &mask, &mtu, &window, &irtt) != 11) {
1396
1397                 VLOG_WARN_RL(&rl, "%s: could not parse line %d: %s", 
1398                         fn, ln, line);
1399                 continue;
1400             }
1401             if (!(flags & RTF_UP)) {
1402                 /* Skip routes that aren't up. */
1403                 continue;
1404             }
1405
1406             /* The output of 'dest', 'mask', and 'gateway' were given in
1407              * network byte order, so we don't need need any endian 
1408              * conversions here. */
1409             if ((dest & mask) == (host->s_addr & mask)) {
1410                 if (!gateway) {
1411                     /* The host is directly reachable. */
1412                     next_hop->s_addr = 0;
1413                 } else {
1414                     /* To reach the host, we must go through a gateway. */
1415                     next_hop->s_addr = gateway;
1416                 }
1417                 *netdev_name = xstrdup(iface);
1418                 fclose(stream);
1419                 return 0;
1420             }
1421         }
1422     }
1423
1424     fclose(stream);
1425     return ENXIO;
1426 }
1427
1428 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
1429  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
1430  * returns 0.  Otherwise, it returns a positive errno value; in particular,
1431  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
1432 static int
1433 netdev_linux_arp_lookup(const struct netdev *netdev,
1434                         uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
1435 {
1436     struct arpreq r;
1437     struct sockaddr_in sin;
1438     int retval;
1439
1440     memset(&r, 0, sizeof r);
1441     sin.sin_family = AF_INET;
1442     sin.sin_addr.s_addr = ip;
1443     sin.sin_port = 0;
1444     memcpy(&r.arp_pa, &sin, sizeof sin);
1445     r.arp_ha.sa_family = ARPHRD_ETHER;
1446     r.arp_flags = 0;
1447     strncpy(r.arp_dev, netdev_get_name(netdev), sizeof r.arp_dev);
1448     COVERAGE_INC(netdev_arp_lookup);
1449     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
1450     if (!retval) {
1451         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
1452     } else if (retval != ENXIO) {
1453         VLOG_WARN_RL(&rl, "%s: could not look up ARP entry for "IP_FMT": %s",
1454                      netdev_get_name(netdev), IP_ARGS(&ip), strerror(retval));
1455     }
1456     return retval;
1457 }
1458
1459 static int
1460 nd_to_iff_flags(enum netdev_flags nd)
1461 {
1462     int iff = 0;
1463     if (nd & NETDEV_UP) {
1464         iff |= IFF_UP;
1465     }
1466     if (nd & NETDEV_PROMISC) {
1467         iff |= IFF_PROMISC;
1468     }
1469     return iff;
1470 }
1471
1472 static int
1473 iff_to_nd_flags(int iff)
1474 {
1475     enum netdev_flags nd = 0;
1476     if (iff & IFF_UP) {
1477         nd |= NETDEV_UP;
1478     }
1479     if (iff & IFF_PROMISC) {
1480         nd |= NETDEV_PROMISC;
1481     }
1482     return nd;
1483 }
1484
1485 static int
1486 netdev_linux_update_flags(struct netdev *netdev, enum netdev_flags off,
1487                           enum netdev_flags on, enum netdev_flags *old_flagsp)
1488 {
1489     int old_flags, new_flags;
1490     int error;
1491
1492     error = get_flags(netdev, &old_flags);
1493     if (!error) {
1494         *old_flagsp = iff_to_nd_flags(old_flags);
1495         new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
1496         if (new_flags != old_flags) {
1497             error = set_flags(netdev, new_flags);
1498         }
1499     }
1500     return error;
1501 }
1502
1503 static void
1504 poll_notify(struct list *list)
1505 {
1506     struct netdev_linux_notifier *notifier;
1507     LIST_FOR_EACH (notifier, struct netdev_linux_notifier, node, list) {
1508         struct netdev_notifier *n = &notifier->notifier;
1509         n->cb(n);
1510     }
1511 }
1512
1513 static void
1514 netdev_linux_poll_cb(const struct rtnetlink_change *change,
1515                      void *aux OVS_UNUSED)
1516 {
1517     if (change) {
1518         struct list *list = shash_find_data(&netdev_linux_notifiers,
1519                                             change->ifname);
1520         if (list) {
1521             poll_notify(list);
1522         }
1523     } else {
1524         struct shash_node *node;
1525         SHASH_FOR_EACH (node, &netdev_linux_notifiers) {
1526             poll_notify(node->data);
1527         }
1528     }
1529 }
1530
1531 static int
1532 netdev_linux_poll_add(struct netdev *netdev,
1533                       void (*cb)(struct netdev_notifier *), void *aux,
1534                       struct netdev_notifier **notifierp)
1535 {
1536     const char *netdev_name = netdev_get_name(netdev);
1537     struct netdev_linux_notifier *notifier;
1538     struct list *list;
1539
1540     if (shash_is_empty(&netdev_linux_notifiers)) {
1541         int error = rtnetlink_notifier_register(&netdev_linux_poll_notifier,
1542                                                    netdev_linux_poll_cb, NULL);
1543         if (error) {
1544             return error;
1545         }
1546     }
1547
1548     list = shash_find_data(&netdev_linux_notifiers, netdev_name);
1549     if (!list) {
1550         list = xmalloc(sizeof *list);
1551         list_init(list);
1552         shash_add(&netdev_linux_notifiers, netdev_name, list);
1553     }
1554
1555     notifier = xmalloc(sizeof *notifier);
1556     netdev_notifier_init(&notifier->notifier, netdev, cb, aux);
1557     list_push_back(list, &notifier->node);
1558     *notifierp = &notifier->notifier;
1559     return 0;
1560 }
1561
1562 static void
1563 netdev_linux_poll_remove(struct netdev_notifier *notifier_)
1564 {
1565     struct netdev_linux_notifier *notifier =
1566         CONTAINER_OF(notifier_, struct netdev_linux_notifier, notifier);
1567     struct list *list;
1568
1569     /* Remove 'notifier' from its list. */
1570     list = list_remove(&notifier->node);
1571     if (list_is_empty(list)) {
1572         /* The list is now empty.  Remove it from the hash and free it. */
1573         const char *netdev_name = netdev_get_name(notifier->notifier.netdev);
1574         shash_delete(&netdev_linux_notifiers,
1575                      shash_find(&netdev_linux_notifiers, netdev_name));
1576         free(list);
1577     }
1578     free(notifier);
1579
1580     /* If that was the last notifier, unregister. */
1581     if (shash_is_empty(&netdev_linux_notifiers)) {
1582         rtnetlink_notifier_unregister(&netdev_linux_poll_notifier);
1583     }
1584 }
1585
1586 const struct netdev_class netdev_linux_class = {
1587     "system",
1588
1589     netdev_linux_init,
1590     netdev_linux_run,
1591     netdev_linux_wait,
1592
1593     netdev_linux_create_system,
1594     netdev_linux_destroy,
1595     NULL,                       /* reconfigure */
1596
1597     netdev_linux_open,
1598     netdev_linux_close,
1599
1600     netdev_linux_enumerate,
1601
1602     netdev_linux_recv,
1603     netdev_linux_recv_wait,
1604     netdev_linux_drain,
1605
1606     netdev_linux_send,
1607     netdev_linux_send_wait,
1608
1609     netdev_linux_set_etheraddr,
1610     netdev_linux_get_etheraddr,
1611     netdev_linux_get_mtu,
1612     netdev_linux_get_ifindex,
1613     netdev_linux_get_carrier,
1614     netdev_linux_get_stats,
1615     netdev_linux_set_stats,
1616
1617     netdev_linux_get_features,
1618     netdev_linux_set_advertisements,
1619     netdev_linux_get_vlan_vid,
1620     netdev_linux_set_policing,
1621
1622     netdev_linux_get_in4,
1623     netdev_linux_set_in4,
1624     netdev_linux_get_in6,
1625     netdev_linux_add_router,
1626     netdev_linux_get_next_hop,
1627     netdev_linux_arp_lookup,
1628
1629     netdev_linux_update_flags,
1630
1631     netdev_linux_poll_add,
1632     netdev_linux_poll_remove,
1633 };
1634
1635 const struct netdev_class netdev_tap_class = {
1636     "tap",
1637
1638     netdev_linux_init,
1639     netdev_linux_run,
1640     netdev_linux_wait,
1641
1642     netdev_linux_create_tap,
1643     netdev_linux_destroy,
1644     NULL,                       /* reconfigure */
1645
1646     netdev_linux_open,
1647     netdev_linux_close,
1648
1649     NULL,                       /* enumerate */
1650
1651     netdev_linux_recv,
1652     netdev_linux_recv_wait,
1653     netdev_linux_drain,
1654
1655     netdev_linux_send,
1656     netdev_linux_send_wait,
1657
1658     netdev_linux_set_etheraddr,
1659     netdev_linux_get_etheraddr,
1660     netdev_linux_get_mtu,
1661     netdev_linux_get_ifindex,
1662     netdev_linux_get_carrier,
1663     netdev_linux_get_stats,
1664     NULL,                       /* set_stats */
1665
1666     netdev_linux_get_features,
1667     netdev_linux_set_advertisements,
1668     netdev_linux_get_vlan_vid,
1669     netdev_linux_set_policing,
1670
1671     netdev_linux_get_in4,
1672     netdev_linux_set_in4,
1673     netdev_linux_get_in6,
1674     netdev_linux_add_router,
1675     netdev_linux_get_next_hop,
1676     netdev_linux_arp_lookup,
1677
1678     netdev_linux_update_flags,
1679
1680     netdev_linux_poll_add,
1681     netdev_linux_poll_remove,
1682 };
1683
1684 \f
1685 static int
1686 get_stats_via_netlink(int ifindex, struct netdev_stats *stats)
1687 {
1688     /* Policy for RTNLGRP_LINK messages.
1689      *
1690      * There are *many* more fields in these messages, but currently we only
1691      * care about these fields. */
1692     static const struct nl_policy rtnlgrp_link_policy[] = {
1693         [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
1694         [IFLA_STATS] = { .type = NL_A_UNSPEC, .optional = true,
1695                          .min_len = sizeof(struct rtnl_link_stats) },
1696     };
1697
1698     struct nl_sock *rtnl_sock;
1699     struct ofpbuf request;
1700     struct ofpbuf *reply;
1701     struct ifinfomsg *ifi;
1702     const struct rtnl_link_stats *rtnl_stats;
1703     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
1704     int error;
1705
1706     error = get_rtnl_sock(&rtnl_sock);
1707     if (error) {
1708         return error;
1709     }
1710
1711     ofpbuf_init(&request, 0);
1712     nl_msg_put_nlmsghdr(&request, rtnl_sock, sizeof *ifi,
1713                         RTM_GETLINK, NLM_F_REQUEST);
1714     ifi = ofpbuf_put_zeros(&request, sizeof *ifi);
1715     ifi->ifi_family = PF_UNSPEC;
1716     ifi->ifi_index = ifindex;
1717     error = nl_sock_transact(rtnl_sock, &request, &reply);
1718     ofpbuf_uninit(&request);
1719     if (error) {
1720         return error;
1721     }
1722
1723     if (!nl_policy_parse(reply, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
1724                          rtnlgrp_link_policy,
1725                          attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
1726         ofpbuf_delete(reply);
1727         return EPROTO;
1728     }
1729
1730     if (!attrs[IFLA_STATS]) {
1731         VLOG_WARN_RL(&rl, "RTM_GETLINK reply lacks stats");
1732         ofpbuf_delete(reply);
1733         return EPROTO;
1734     }
1735
1736     rtnl_stats = nl_attr_get(attrs[IFLA_STATS]);
1737     stats->rx_packets = rtnl_stats->rx_packets;
1738     stats->tx_packets = rtnl_stats->tx_packets;
1739     stats->rx_bytes = rtnl_stats->rx_bytes;
1740     stats->tx_bytes = rtnl_stats->tx_bytes;
1741     stats->rx_errors = rtnl_stats->rx_errors;
1742     stats->tx_errors = rtnl_stats->tx_errors;
1743     stats->rx_dropped = rtnl_stats->rx_dropped;
1744     stats->tx_dropped = rtnl_stats->tx_dropped;
1745     stats->multicast = rtnl_stats->multicast;
1746     stats->collisions = rtnl_stats->collisions;
1747     stats->rx_length_errors = rtnl_stats->rx_length_errors;
1748     stats->rx_over_errors = rtnl_stats->rx_over_errors;
1749     stats->rx_crc_errors = rtnl_stats->rx_crc_errors;
1750     stats->rx_frame_errors = rtnl_stats->rx_frame_errors;
1751     stats->rx_fifo_errors = rtnl_stats->rx_fifo_errors;
1752     stats->rx_missed_errors = rtnl_stats->rx_missed_errors;
1753     stats->tx_aborted_errors = rtnl_stats->tx_aborted_errors;
1754     stats->tx_carrier_errors = rtnl_stats->tx_carrier_errors;
1755     stats->tx_fifo_errors = rtnl_stats->tx_fifo_errors;
1756     stats->tx_heartbeat_errors = rtnl_stats->tx_heartbeat_errors;
1757     stats->tx_window_errors = rtnl_stats->tx_window_errors;
1758
1759     ofpbuf_delete(reply);
1760
1761     return 0;
1762 }
1763
1764 static int
1765 get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats)
1766 {
1767     static const char fn[] = "/proc/net/dev";
1768     char line[1024];
1769     FILE *stream;
1770     int ln;
1771
1772     stream = fopen(fn, "r");
1773     if (!stream) {
1774         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1775         return errno;
1776     }
1777
1778     ln = 0;
1779     while (fgets(line, sizeof line, stream)) {
1780         if (++ln >= 3) {
1781             char devname[16];
1782 #define X64 "%"SCNu64
1783             if (sscanf(line,
1784                        " %15[^:]:"
1785                        X64 X64 X64 X64 X64 X64 X64 "%*u"
1786                        X64 X64 X64 X64 X64 X64 X64 "%*u",
1787                        devname,
1788                        &stats->rx_bytes,
1789                        &stats->rx_packets,
1790                        &stats->rx_errors,
1791                        &stats->rx_dropped,
1792                        &stats->rx_fifo_errors,
1793                        &stats->rx_frame_errors,
1794                        &stats->multicast,
1795                        &stats->tx_bytes,
1796                        &stats->tx_packets,
1797                        &stats->tx_errors,
1798                        &stats->tx_dropped,
1799                        &stats->tx_fifo_errors,
1800                        &stats->collisions,
1801                        &stats->tx_carrier_errors) != 15) {
1802                 VLOG_WARN_RL(&rl, "%s:%d: parse error", fn, ln);
1803             } else if (!strcmp(devname, netdev_name)) {
1804                 stats->rx_length_errors = UINT64_MAX;
1805                 stats->rx_over_errors = UINT64_MAX;
1806                 stats->rx_crc_errors = UINT64_MAX;
1807                 stats->rx_missed_errors = UINT64_MAX;
1808                 stats->tx_aborted_errors = UINT64_MAX;
1809                 stats->tx_heartbeat_errors = UINT64_MAX;
1810                 stats->tx_window_errors = UINT64_MAX;
1811                 fclose(stream);
1812                 return 0;
1813             }
1814         }
1815     }
1816     VLOG_WARN_RL(&rl, "%s: no stats for %s", fn, netdev_name);
1817     fclose(stream);
1818     return ENODEV;
1819 }
1820 \f
1821 static int
1822 get_flags(const struct netdev *netdev, int *flags)
1823 {
1824     struct ifreq ifr;
1825     int error;
1826
1827     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCGIFFLAGS,
1828                                   "SIOCGIFFLAGS");
1829     *flags = ifr.ifr_flags;
1830     return error;
1831 }
1832
1833 static int
1834 set_flags(struct netdev *netdev, int flags)
1835 {
1836     struct ifreq ifr;
1837
1838     ifr.ifr_flags = flags;
1839     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCSIFFLAGS,
1840                                  "SIOCSIFFLAGS");
1841 }
1842
1843 static int
1844 do_get_ifindex(const char *netdev_name)
1845 {
1846     struct ifreq ifr;
1847
1848     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1849     COVERAGE_INC(netdev_get_ifindex);
1850     if (ioctl(af_inet_sock, SIOCGIFINDEX, &ifr) < 0) {
1851         VLOG_WARN_RL(&rl, "ioctl(SIOCGIFINDEX) on %s device failed: %s",
1852                      netdev_name, strerror(errno));
1853         return -errno;
1854     }
1855     return ifr.ifr_ifindex;
1856 }
1857
1858 static int
1859 get_ifindex(const struct netdev *netdev_, int *ifindexp)
1860 {
1861     struct netdev_dev_linux *netdev_dev =
1862                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1863     *ifindexp = 0;
1864     if (!(netdev_dev->cache_valid & VALID_IFINDEX)) {
1865         int ifindex = do_get_ifindex(netdev_get_name(netdev_));
1866         if (ifindex < 0) {
1867             return -ifindex;
1868         }
1869         netdev_dev->cache_valid |= VALID_IFINDEX;
1870         netdev_dev->ifindex = ifindex;
1871     }
1872     *ifindexp = netdev_dev->ifindex;
1873     return 0;
1874 }
1875
1876 static int
1877 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
1878 {
1879     struct ifreq ifr;
1880     int hwaddr_family;
1881
1882     memset(&ifr, 0, sizeof ifr);
1883     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1884     COVERAGE_INC(netdev_get_hwaddr);
1885     if (ioctl(af_inet_sock, SIOCGIFHWADDR, &ifr) < 0) {
1886         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
1887                  netdev_name, strerror(errno));
1888         return errno;
1889     }
1890     hwaddr_family = ifr.ifr_hwaddr.sa_family;
1891     if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
1892         VLOG_WARN("%s device has unknown hardware address family %d",
1893                   netdev_name, hwaddr_family);
1894     }
1895     memcpy(ea, ifr.ifr_hwaddr.sa_data, ETH_ADDR_LEN);
1896     return 0;
1897 }
1898
1899 static int
1900 set_etheraddr(const char *netdev_name, int hwaddr_family,
1901               const uint8_t mac[ETH_ADDR_LEN])
1902 {
1903     struct ifreq ifr;
1904
1905     memset(&ifr, 0, sizeof ifr);
1906     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1907     ifr.ifr_hwaddr.sa_family = hwaddr_family;
1908     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
1909     COVERAGE_INC(netdev_set_hwaddr);
1910     if (ioctl(af_inet_sock, SIOCSIFHWADDR, &ifr) < 0) {
1911         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
1912                  netdev_name, strerror(errno));
1913         return errno;
1914     }
1915     return 0;
1916 }
1917
1918 static int
1919 netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *ecmd,
1920                         int cmd, const char *cmd_name)
1921 {
1922     struct ifreq ifr;
1923
1924     memset(&ifr, 0, sizeof ifr);
1925     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
1926     ifr.ifr_data = (caddr_t) ecmd;
1927
1928     ecmd->cmd = cmd;
1929     COVERAGE_INC(netdev_ethtool);
1930     if (ioctl(af_inet_sock, SIOCETHTOOL, &ifr) == 0) {
1931         return 0;
1932     } else {
1933         if (errno != EOPNOTSUPP) {
1934             VLOG_WARN_RL(&rl, "ethtool command %s on network device %s "
1935                          "failed: %s", cmd_name, name, strerror(errno));
1936         } else {
1937             /* The device doesn't support this operation.  That's pretty
1938              * common, so there's no point in logging anything. */
1939         }
1940         return errno;
1941     }
1942 }
1943
1944 static int
1945 netdev_linux_do_ioctl(const char *name, struct ifreq *ifr, int cmd,
1946                       const char *cmd_name)
1947 {
1948     strncpy(ifr->ifr_name, name, sizeof ifr->ifr_name);
1949     if (ioctl(af_inet_sock, cmd, ifr) == -1) {
1950         VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s", name, cmd_name,
1951                      strerror(errno));
1952         return errno;
1953     }
1954     return 0;
1955 }
1956
1957 static int
1958 netdev_linux_get_ipv4(const struct netdev *netdev, struct in_addr *ip,
1959                       int cmd, const char *cmd_name)
1960 {
1961     struct ifreq ifr;
1962     int error;
1963
1964     ifr.ifr_addr.sa_family = AF_INET;
1965     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, cmd, cmd_name);
1966     if (!error) {
1967         const struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
1968         *ip = sin->sin_addr;
1969     }
1970     return error;
1971 }
1972
1973 /* Obtains a Netlink routing socket that is not subscribed to any multicast
1974  * groups.  Returns 0 if successful, otherwise a positive errno value.  Stores
1975  * the socket in '*rtnl_sockp' if successful, otherwise a null pointer. */
1976 static int
1977 get_rtnl_sock(struct nl_sock **rtnl_sockp)
1978 {
1979     static struct nl_sock *sock;
1980     int error;
1981
1982     if (!sock) {
1983         error = nl_sock_create(NETLINK_ROUTE, 0, 0, 0, &sock);
1984         if (error) {
1985             VLOG_ERR_RL(&rl, "failed to create rtnetlink socket: %s",
1986                         strerror(error));
1987         }
1988     } else {
1989         error = 0;
1990     }
1991
1992     *rtnl_sockp = sock;
1993     return error;
1994 }