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