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