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