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