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