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