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