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