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