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