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