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