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