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