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