netdev: Really set output values to 0 on failure in netdev_get_features().
[sliver-openvswitch.git] / lib / netdev-linux.c
1 /*
2  * Copyright (c) 2009 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/types.h>
25 #include <linux/ethtool.h>
26 #include <linux/rtnetlink.h>
27 #include <linux/sockios.h>
28 #include <linux/version.h>
29 #include <sys/types.h>
30 #include <sys/ioctl.h>
31 #include <sys/socket.h>
32 #include <netpacket/packet.h>
33 #include <net/ethernet.h>
34 #include <net/if.h>
35 #include <net/if_arp.h>
36 #include <net/if_packet.h>
37 #include <net/route.h>
38 #include <netinet/in.h>
39 #include <poll.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43
44 #include "coverage.h"
45 #include "dynamic-string.h"
46 #include "fatal-signal.h"
47 #include "netdev-provider.h"
48 #include "netlink.h"
49 #include "ofpbuf.h"
50 #include "openflow/openflow.h"
51 #include "packets.h"
52 #include "poll-loop.h"
53 #include "rtnetlink.h"
54 #include "socket-util.h"
55 #include "shash.h"
56 #include "svec.h"
57
58 #define THIS_MODULE VLM_netdev_linux
59 #include "vlog.h"
60 \f
61 /* These were introduced in Linux 2.6.14, so they might be missing if we have
62  * old headers. */
63 #ifndef ADVERTISED_Pause
64 #define ADVERTISED_Pause                (1 << 13)
65 #endif
66 #ifndef ADVERTISED_Asym_Pause
67 #define ADVERTISED_Asym_Pause           (1 << 14)
68 #endif
69
70 struct netdev_linux {
71     struct netdev netdev;
72
73     /* File descriptors.  For ordinary network devices, the two fds below are
74      * the same; for tap devices, they differ. */
75     int netdev_fd;              /* Network device. */
76     int tap_fd;                 /* TAP character device, if any, otherwise the
77                                  * network device. */
78
79     struct netdev_linux_cache *cache;
80 };
81
82 enum {
83     VALID_IFINDEX = 1 << 0,
84     VALID_ETHERADDR = 1 << 1,
85     VALID_IN4 = 1 << 2,
86     VALID_IN6 = 1 << 3,
87     VALID_MTU = 1 << 4,
88     VALID_CARRIER = 1 << 5,
89     VALID_IS_INTERNAL = 1 << 6
90 };
91
92 /* Cached network device information. */
93 struct netdev_linux_cache {
94     struct shash_node *shash_node;
95     unsigned int valid;
96     int ref_cnt;
97
98     int ifindex;
99     uint8_t etheraddr[ETH_ADDR_LEN];
100     struct in_addr address, netmask;
101     struct in6_addr in6;
102     int mtu;
103     int carrier;
104     bool is_internal;
105 };
106
107 static struct shash cache_map = SHASH_INITIALIZER(&cache_map);
108 static struct rtnetlink_notifier netdev_linux_cache_notifier;
109
110 /* An AF_INET socket (used for ioctl operations). */
111 static int af_inet_sock = -1;
112
113 struct netdev_linux_notifier {
114     struct netdev_notifier notifier;
115     struct list node;
116 };
117
118 static struct shash netdev_linux_notifiers =
119     SHASH_INITIALIZER(&netdev_linux_notifiers);
120 static struct rtnetlink_notifier netdev_linux_poll_notifier;
121
122 /* This is set pretty low because we probably won't learn anything from the
123  * additional log messages. */
124 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
125
126 static int netdev_linux_do_ethtool(struct netdev *, struct ethtool_cmd *,
127                                    int cmd, const char *cmd_name);
128 static int netdev_linux_do_ioctl(const struct netdev *, struct ifreq *,
129                                  int cmd, const char *cmd_name);
130 static int netdev_linux_get_ipv4(const struct netdev *, struct in_addr *,
131                                  int cmd, const char *cmd_name);
132 static int get_flags(const struct netdev *, int *flagsp);
133 static int set_flags(struct netdev *, int flags);
134 static int do_get_ifindex(const char *netdev_name);
135 static int get_ifindex(const struct netdev *, int *ifindexp);
136 static int do_set_addr(struct netdev *netdev,
137                        int ioctl_nr, const char *ioctl_name,
138                        struct in_addr addr);
139 static int get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN]);
140 static int set_etheraddr(const char *netdev_name, int hwaddr_family,
141                          const uint8_t[ETH_ADDR_LEN]);
142 static int get_stats_via_netlink(int ifindex, struct netdev_stats *stats);
143 static int get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats);
144
145 static struct netdev_linux *
146 netdev_linux_cast(const struct netdev *netdev)
147 {
148     netdev_assert_class(netdev, &netdev_linux_class);
149     return CONTAINER_OF(netdev, struct netdev_linux, netdev);
150 }
151
152 static int
153 netdev_linux_init(void)
154 {
155     static int status = -1;
156     if (status < 0) {
157         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
158         status = af_inet_sock >= 0 ? 0 : errno;
159         if (status) {
160             VLOG_ERR("failed to create inet socket: %s", strerror(status));
161         }
162     }
163     return status;
164 }
165
166 static void
167 netdev_linux_run(void)
168 {
169     rtnetlink_notifier_run();
170 }
171
172 static void
173 netdev_linux_wait(void)
174 {
175     rtnetlink_notifier_wait();
176 }
177
178 static void
179 netdev_linux_cache_cb(const struct rtnetlink_change *change,
180                       void *aux UNUSED)
181 {
182     struct netdev_linux_cache *cache;
183     if (change) {
184         cache = shash_find_data(&cache_map, change->ifname);
185         if (cache) {
186             cache->valid = 0;
187         }
188     } else {
189         struct shash_node *node;
190         SHASH_FOR_EACH (node, &cache_map) {
191             cache = node->data;
192             cache->valid = 0;
193         }
194     }
195 }
196
197 static int
198 netdev_linux_open(const char *name, char *suffix, int ethertype,
199                   struct netdev **netdevp)
200 {
201     struct netdev_linux *netdev;
202     enum netdev_flags flags;
203     int error;
204
205     /* Allocate network device. */
206     netdev = xcalloc(1, sizeof *netdev);
207     netdev_init(&netdev->netdev, suffix, &netdev_linux_class);
208     netdev->netdev_fd = -1;
209     netdev->tap_fd = -1;
210     netdev->cache = shash_find_data(&cache_map, suffix);
211     if (!netdev->cache) {
212         if (shash_is_empty(&cache_map)) {
213             int error = rtnetlink_notifier_register(
214                 &netdev_linux_cache_notifier, netdev_linux_cache_cb, NULL);
215             if (error) {
216                 netdev_close(&netdev->netdev);
217                 return error;
218             }
219         }
220         netdev->cache = xmalloc(sizeof *netdev->cache);
221         netdev->cache->shash_node = shash_add(&cache_map, suffix,
222                                               netdev->cache);
223         netdev->cache->valid = 0;
224         netdev->cache->ref_cnt = 0;
225     }
226     netdev->cache->ref_cnt++;
227
228     if (!strncmp(name, "tap:", 4)) {
229         static const char tap_dev[] = "/dev/net/tun";
230         struct ifreq ifr;
231
232         /* Open tap device. */
233         netdev->tap_fd = open(tap_dev, O_RDWR);
234         if (netdev->tap_fd < 0) {
235             error = errno;
236             VLOG_WARN("opening \"%s\" failed: %s", tap_dev, strerror(error));
237             goto error;
238         }
239
240         /* Create tap device. */
241         ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
242         strncpy(ifr.ifr_name, suffix, sizeof ifr.ifr_name);
243         if (ioctl(netdev->tap_fd, TUNSETIFF, &ifr) == -1) {
244             VLOG_WARN("%s: creating tap device failed: %s", suffix,
245                       strerror(errno));
246             error = errno;
247             goto error;
248         }
249
250         /* Make non-blocking. */
251         error = set_nonblocking(netdev->tap_fd);
252         if (error) {
253             goto error;
254         }
255     }
256
257     error = netdev_get_flags(&netdev->netdev, &flags);
258     if (error == ENODEV) {
259         goto error;
260     }
261
262     if (netdev->tap_fd >= 0 || ethertype != NETDEV_ETH_TYPE_NONE) {
263         struct sockaddr_ll sll;
264         int protocol;
265         int ifindex;
266
267         /* Create file descriptor. */
268         protocol = (ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
269                     : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
270                     : ethertype);
271         netdev->netdev_fd = socket(PF_PACKET, SOCK_RAW, htons(protocol));
272         if (netdev->netdev_fd < 0) {
273             error = errno;
274             goto error;
275         }
276         if (netdev->tap_fd < 0) {
277             netdev->tap_fd = netdev->netdev_fd;
278         }
279
280         /* Set non-blocking mode. */
281         error = set_nonblocking(netdev->netdev_fd);
282         if (error) {
283             goto error;
284         }
285
286         /* Get ethernet device index. */
287         error = get_ifindex(&netdev->netdev, &ifindex);
288         if (error) {
289             goto error;
290         }
291
292         /* Bind to specific ethernet device. */
293         memset(&sll, 0, sizeof sll);
294         sll.sll_family = AF_PACKET;
295         sll.sll_ifindex = ifindex;
296         if (bind(netdev->netdev_fd,
297                  (struct sockaddr *) &sll, sizeof sll) < 0) {
298             error = errno;
299             VLOG_ERR("bind to %s failed: %s", suffix, strerror(error));
300             goto error;
301         }
302
303         /* Between the socket() and bind() calls above, the socket receives all
304          * packets of the requested type on all system interfaces.  We do not
305          * want to receive that data, but there is no way to avoid it.  So we
306          * must now drain out the receive queue. */
307         error = drain_rcvbuf(netdev->netdev_fd);
308         if (error) {
309             goto error;
310         }
311     }
312
313     *netdevp = &netdev->netdev;
314     return 0;
315
316 error:
317     netdev_close(&netdev->netdev);
318     return error;
319 }
320
321 /* Closes and destroys 'netdev'. */
322 static void
323 netdev_linux_close(struct netdev *netdev_)
324 {
325     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
326
327     if (netdev->cache && !--netdev->cache->ref_cnt) {
328         shash_delete(&cache_map, netdev->cache->shash_node);
329         free(netdev->cache);
330
331         if (shash_is_empty(&cache_map)) {
332             rtnetlink_notifier_unregister(&netdev_linux_cache_notifier);
333         }
334     }
335     if (netdev->netdev_fd >= 0) {
336         close(netdev->netdev_fd);
337     }
338     if (netdev->tap_fd >= 0 && netdev->netdev_fd != netdev->tap_fd) {
339         close(netdev->tap_fd);
340     }
341     free(netdev);
342 }
343
344 /* Initializes 'svec' with a list of the names of all known network devices. */
345 static int
346 netdev_linux_enumerate(struct svec *svec)
347 {
348     struct if_nameindex *names;
349
350     names = if_nameindex();
351     if (names) {
352         size_t i;
353
354         for (i = 0; names[i].if_name != NULL; i++) {
355             svec_add(svec, names[i].if_name);
356         }
357         if_freenameindex(names);
358         return 0;
359     } else {
360         VLOG_WARN("could not obtain list of network device names: %s",
361                   strerror(errno));
362         return errno;
363     }
364 }
365
366 static int
367 netdev_linux_recv(struct netdev *netdev_, void *data, size_t size)
368 {
369     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
370
371     if (netdev->tap_fd < 0) {
372         /* Device was opened with NETDEV_ETH_TYPE_NONE. */
373         return -EAGAIN;
374     }
375
376     for (;;) {
377         ssize_t retval = read(netdev->tap_fd, data, size);
378         if (retval >= 0) {
379             return retval;
380         } else if (errno != EINTR) {
381             if (errno != EAGAIN) {
382                 VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
383                              strerror(errno), netdev_get_name(netdev_));
384             }
385             return -errno;
386         }
387     }
388 }
389
390 /* Registers with the poll loop to wake up from the next call to poll_block()
391  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
392 static void
393 netdev_linux_recv_wait(struct netdev *netdev_)
394 {
395     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
396     if (netdev->tap_fd >= 0) {
397         poll_fd_wait(netdev->tap_fd, POLLIN);
398     }
399 }
400
401 /* Discards all packets waiting to be received from 'netdev'. */
402 static int
403 netdev_linux_drain(struct netdev *netdev_)
404 {
405     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
406     if (netdev->tap_fd < 0 && netdev->netdev_fd < 0) {
407         return 0;
408     } else if (netdev->tap_fd != netdev->netdev_fd) {
409         struct ifreq ifr;
410         int error = netdev_linux_do_ioctl(netdev_, &ifr,
411                                           SIOCGIFTXQLEN, "SIOCGIFTXQLEN");
412         if (error) {
413             return error;
414         }
415         drain_fd(netdev->tap_fd, ifr.ifr_qlen);
416         return 0;
417     } else {
418         return drain_rcvbuf(netdev->netdev_fd);
419     }
420 }
421
422 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
423  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
424  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
425  * the packet is too big or too small to transmit on the device.
426  *
427  * The caller retains ownership of 'buffer' in all cases.
428  *
429  * The kernel maintains a packet transmission queue, so the caller is not
430  * expected to do additional queuing of packets. */
431 static int
432 netdev_linux_send(struct netdev *netdev_, const void *data, size_t size)
433 {
434     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
435
436     /* XXX should support sending even if 'ethertype' was NETDEV_ETH_TYPE_NONE.
437      */
438     if (netdev->tap_fd < 0) {
439         return EPIPE;
440     }
441
442     for (;;) {
443         ssize_t retval = write(netdev->tap_fd, data, size);
444         if (retval < 0) {
445             /* The Linux AF_PACKET implementation never blocks waiting for room
446              * for packets, instead returning ENOBUFS.  Translate this into
447              * EAGAIN for the caller. */
448             if (errno == ENOBUFS) {
449                 return EAGAIN;
450             } else if (errno == EINTR) {
451                 continue;
452             } else if (errno != EAGAIN) {
453                 VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: %s",
454                              netdev_get_name(netdev_), strerror(errno));
455             }
456             return errno;
457         } else if (retval != size) {
458             VLOG_WARN_RL(&rl, "sent partial Ethernet packet (%zd bytes of "
459                          "%zu) on %s", retval, size, netdev_get_name(netdev_));
460             return EMSGSIZE;
461         } else {
462             return 0;
463         }
464     }
465 }
466
467 /* Registers with the poll loop to wake up from the next call to poll_block()
468  * when the packet transmission queue has sufficient room to transmit a packet
469  * with netdev_send().
470  *
471  * The kernel maintains a packet transmission queue, so the client is not
472  * expected to do additional queuing of packets.  Thus, this function is
473  * unlikely to ever be used.  It is included for completeness. */
474 static void
475 netdev_linux_send_wait(struct netdev *netdev_)
476 {
477     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
478     if (netdev->tap_fd < 0 && netdev->netdev_fd < 0) {
479         /* Nothing to do. */
480     } else if (netdev->tap_fd == netdev->netdev_fd) {
481         poll_fd_wait(netdev->tap_fd, POLLOUT);
482     } else {
483         /* TAP device always accepts packets.*/
484         poll_immediate_wake();
485     }
486 }
487
488 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
489  * otherwise a positive errno value. */
490 static int
491 netdev_linux_set_etheraddr(struct netdev *netdev_,
492                            const uint8_t mac[ETH_ADDR_LEN])
493 {
494     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
495     int error;
496
497     if (!(netdev->cache->valid & VALID_ETHERADDR)
498         || !eth_addr_equals(netdev->cache->etheraddr, mac)) {
499         error = set_etheraddr(netdev_get_name(netdev_), ARPHRD_ETHER, mac);
500         if (!error) {
501             netdev->cache->valid |= VALID_ETHERADDR;
502             memcpy(netdev->cache->etheraddr, mac, ETH_ADDR_LEN);
503         }
504     } else {
505         error = 0;
506     }
507     return error;
508 }
509
510 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
511  * free the returned buffer. */
512 static int
513 netdev_linux_get_etheraddr(const struct netdev *netdev_,
514                            uint8_t mac[ETH_ADDR_LEN])
515 {
516     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
517     if (!(netdev->cache->valid & VALID_ETHERADDR)) {
518         int error = get_etheraddr(netdev_get_name(netdev_),
519                                   netdev->cache->etheraddr);
520         if (error) {
521             return error;
522         }
523         netdev->cache->valid |= VALID_ETHERADDR;
524     }
525     memcpy(mac, netdev->cache->etheraddr, ETH_ADDR_LEN);
526     return 0;
527 }
528
529 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
530  * in bytes, not including the hardware header; thus, this is typically 1500
531  * bytes for Ethernet devices. */
532 static int
533 netdev_linux_get_mtu(const struct netdev *netdev_, int *mtup)
534 {
535     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
536     if (!(netdev->cache->valid & VALID_MTU)) {
537         struct ifreq ifr;
538         int error;
539
540         error = netdev_linux_do_ioctl(netdev_, &ifr, SIOCGIFMTU, "SIOCGIFMTU");
541         if (error) {
542             return error;
543         }
544         netdev->cache->mtu = ifr.ifr_mtu;
545         netdev->cache->valid |= VALID_MTU;
546     }
547     *mtup = netdev->cache->mtu;
548     return 0;
549 }
550
551 static int
552 netdev_linux_get_carrier(const struct netdev *netdev_, bool *carrier)
553 {
554     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
555     int error = 0;
556     char *fn = NULL;
557     int fd = -1;
558
559     if (!(netdev->cache->valid & VALID_CARRIER)) {
560         char line[8];
561         int retval;
562
563         fn = xasprintf("/sys/class/net/%s/carrier", netdev_get_name(netdev_));
564         fd = open(fn, O_RDONLY);
565         if (fd < 0) {
566             error = errno;
567             VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(error));
568             goto exit;
569         }
570
571         retval = read(fd, line, sizeof line);
572         if (retval < 0) {
573             error = errno;
574             if (error == EINVAL) {
575                 /* This is the normal return value when we try to check carrier
576                  * if the network device is not up. */
577             } else {
578                 VLOG_WARN_RL(&rl, "%s: read failed: %s", fn, strerror(error));
579             }
580             goto exit;
581         } else if (retval == 0) {
582             error = EPROTO;
583             VLOG_WARN_RL(&rl, "%s: unexpected end of file", fn);
584             goto exit;
585         }
586
587         if (line[0] != '0' && line[0] != '1') {
588             error = EPROTO;
589             VLOG_WARN_RL(&rl, "%s: value is %c (expected 0 or 1)",
590                          fn, line[0]);
591             goto exit;
592         }
593         netdev->cache->carrier = line[0] != '0';
594         netdev->cache->valid |= VALID_CARRIER;
595     }
596     *carrier = netdev->cache->carrier;
597     error = 0;
598
599 exit:
600     if (fd >= 0) {
601         close(fd);
602     }
603     free(fn);
604     return error;
605 }
606
607 /* Check whether we can we use RTM_GETLINK to get network device statistics.
608  * In pre-2.6.19 kernels, this was only available if wireless extensions were
609  * enabled. */
610 static bool
611 check_for_working_netlink_stats(void)
612 {
613     /* Decide on the netdev_get_stats() implementation to use.  Netlink is
614      * preferable, so if that works, we'll use it. */
615     int ifindex = do_get_ifindex("lo");
616     if (ifindex < 0) {
617         VLOG_WARN("failed to get ifindex for lo, "
618                   "obtaining netdev stats from proc");
619         return false;
620     } else {
621         struct netdev_stats stats;
622         int error = get_stats_via_netlink(ifindex, &stats);
623         if (!error) {
624             VLOG_DBG("obtaining netdev stats via rtnetlink");
625             return true;
626         } else {
627             VLOG_INFO("RTM_GETLINK failed (%s), obtaining netdev stats "
628                       "via proc (you are probably running a pre-2.6.19 "
629                       "kernel)", strerror(error));
630             return false;
631         }
632     }
633 }
634
635 /* Retrieves current device stats for 'netdev'.
636  *
637  * XXX All of the members of struct netdev_stats are 64 bits wide, but on
638  * 32-bit architectures the Linux network stats are only 32 bits. */
639 static int
640 netdev_linux_get_stats(const struct netdev *netdev_, struct netdev_stats *stats)
641 {
642     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
643     static int use_netlink_stats = -1;
644     int error;
645     struct netdev_stats raw_stats;
646     struct netdev_stats *collect_stats = stats;
647
648     COVERAGE_INC(netdev_get_stats);
649
650     if (!(netdev->cache->valid & VALID_IS_INTERNAL)) {
651         netdev->cache->is_internal = (netdev->tap_fd != -1);
652
653         if (!netdev->cache->is_internal) {
654             struct ethtool_drvinfo drvinfo;
655
656             memset(&drvinfo, 0, sizeof drvinfo);
657             error = netdev_linux_do_ethtool(&netdev->netdev,
658                                             (struct ethtool_cmd *)&drvinfo,
659                                             ETHTOOL_GDRVINFO,
660                                             "ETHTOOL_GDRVINFO");
661
662             if (!error) {
663                 netdev->cache->is_internal = !strcmp(drvinfo.driver,
664                                                      "openvswitch");
665             }
666         }
667
668         netdev->cache->valid |= VALID_IS_INTERNAL;
669     }
670
671     if (netdev->cache->is_internal) {
672         collect_stats = &raw_stats;
673     }
674
675     if (use_netlink_stats < 0) {
676         use_netlink_stats = check_for_working_netlink_stats();
677     }
678     if (use_netlink_stats) {
679         int ifindex;
680
681         error = get_ifindex(&netdev->netdev, &ifindex);
682         if (!error) {
683             error = get_stats_via_netlink(ifindex, collect_stats);
684         }
685     } else {
686         error = get_stats_via_proc(netdev->netdev.name, collect_stats);
687     }
688
689     /* If this port is an internal port then the transmit and receive stats
690      * will appear to be swapped relative to the other ports since we are the
691      * one sending the data, not a remote computer.  For consistency, we swap
692      * them back here. */
693     if (netdev->cache->is_internal) {
694         stats->rx_packets = raw_stats.tx_packets;
695         stats->tx_packets = raw_stats.rx_packets;
696         stats->rx_bytes = raw_stats.tx_bytes;
697         stats->tx_bytes = raw_stats.rx_bytes;
698         stats->rx_errors = raw_stats.tx_errors;
699         stats->tx_errors = raw_stats.rx_errors;
700         stats->rx_dropped = raw_stats.tx_dropped;
701         stats->tx_dropped = raw_stats.rx_dropped;
702         stats->multicast = raw_stats.multicast;
703         stats->collisions = raw_stats.collisions;
704         stats->rx_length_errors = 0;
705         stats->rx_over_errors = 0;
706         stats->rx_crc_errors = 0;
707         stats->rx_frame_errors = 0;
708         stats->rx_fifo_errors = 0;
709         stats->rx_missed_errors = 0;
710         stats->tx_aborted_errors = 0;
711         stats->tx_carrier_errors = 0;
712         stats->tx_fifo_errors = 0;
713         stats->tx_heartbeat_errors = 0;
714         stats->tx_window_errors = 0;
715     }
716
717     return error;
718 }
719
720 /* Stores the features supported by 'netdev' into each of '*current',
721  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
722  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
723  * successful, otherwise a positive errno value. */
724 static int
725 netdev_linux_get_features(struct netdev *netdev,
726                           uint32_t *current, uint32_t *advertised,
727                           uint32_t *supported, uint32_t *peer)
728 {
729     struct ethtool_cmd ecmd;
730     int error;
731
732     memset(&ecmd, 0, sizeof ecmd);
733     error = netdev_linux_do_ethtool(netdev, &ecmd,
734                                     ETHTOOL_GSET, "ETHTOOL_GSET");
735     if (error) {
736         return error;
737     }
738
739     /* Supported features. */
740     *supported = 0;
741     if (ecmd.supported & SUPPORTED_10baseT_Half) {
742         *supported |= OFPPF_10MB_HD;
743     }
744     if (ecmd.supported & SUPPORTED_10baseT_Full) {
745         *supported |= OFPPF_10MB_FD;
746     }
747     if (ecmd.supported & SUPPORTED_100baseT_Half)  {
748         *supported |= OFPPF_100MB_HD;
749     }
750     if (ecmd.supported & SUPPORTED_100baseT_Full) {
751         *supported |= OFPPF_100MB_FD;
752     }
753     if (ecmd.supported & SUPPORTED_1000baseT_Half) {
754         *supported |= OFPPF_1GB_HD;
755     }
756     if (ecmd.supported & SUPPORTED_1000baseT_Full) {
757         *supported |= OFPPF_1GB_FD;
758     }
759     if (ecmd.supported & SUPPORTED_10000baseT_Full) {
760         *supported |= OFPPF_10GB_FD;
761     }
762     if (ecmd.supported & SUPPORTED_TP) {
763         *supported |= OFPPF_COPPER;
764     }
765     if (ecmd.supported & SUPPORTED_FIBRE) {
766         *supported |= OFPPF_FIBER;
767     }
768     if (ecmd.supported & SUPPORTED_Autoneg) {
769         *supported |= OFPPF_AUTONEG;
770     }
771     if (ecmd.supported & SUPPORTED_Pause) {
772         *supported |= OFPPF_PAUSE;
773     }
774     if (ecmd.supported & SUPPORTED_Asym_Pause) {
775         *supported |= OFPPF_PAUSE_ASYM;
776     }
777
778     /* Advertised features. */
779     *advertised = 0;
780     if (ecmd.advertising & ADVERTISED_10baseT_Half) {
781         *advertised |= OFPPF_10MB_HD;
782     }
783     if (ecmd.advertising & ADVERTISED_10baseT_Full) {
784         *advertised |= OFPPF_10MB_FD;
785     }
786     if (ecmd.advertising & ADVERTISED_100baseT_Half) {
787         *advertised |= OFPPF_100MB_HD;
788     }
789     if (ecmd.advertising & ADVERTISED_100baseT_Full) {
790         *advertised |= OFPPF_100MB_FD;
791     }
792     if (ecmd.advertising & ADVERTISED_1000baseT_Half) {
793         *advertised |= OFPPF_1GB_HD;
794     }
795     if (ecmd.advertising & ADVERTISED_1000baseT_Full) {
796         *advertised |= OFPPF_1GB_FD;
797     }
798     if (ecmd.advertising & ADVERTISED_10000baseT_Full) {
799         *advertised |= OFPPF_10GB_FD;
800     }
801     if (ecmd.advertising & ADVERTISED_TP) {
802         *advertised |= OFPPF_COPPER;
803     }
804     if (ecmd.advertising & ADVERTISED_FIBRE) {
805         *advertised |= OFPPF_FIBER;
806     }
807     if (ecmd.advertising & ADVERTISED_Autoneg) {
808         *advertised |= OFPPF_AUTONEG;
809     }
810     if (ecmd.advertising & ADVERTISED_Pause) {
811         *advertised |= OFPPF_PAUSE;
812     }
813     if (ecmd.advertising & ADVERTISED_Asym_Pause) {
814         *advertised |= OFPPF_PAUSE_ASYM;
815     }
816
817     /* Current settings. */
818     if (ecmd.speed == SPEED_10) {
819         *current = ecmd.duplex ? OFPPF_10MB_FD : OFPPF_10MB_HD;
820     } else if (ecmd.speed == SPEED_100) {
821         *current = ecmd.duplex ? OFPPF_100MB_FD : OFPPF_100MB_HD;
822     } else if (ecmd.speed == SPEED_1000) {
823         *current = ecmd.duplex ? OFPPF_1GB_FD : OFPPF_1GB_HD;
824     } else if (ecmd.speed == SPEED_10000) {
825         *current = OFPPF_10GB_FD;
826     } else {
827         *current = 0;
828     }
829
830     if (ecmd.port == PORT_TP) {
831         *current |= OFPPF_COPPER;
832     } else if (ecmd.port == PORT_FIBRE) {
833         *current |= OFPPF_FIBER;
834     }
835
836     if (ecmd.autoneg) {
837         *current |= OFPPF_AUTONEG;
838     }
839
840     /* Peer advertisements. */
841     *peer = 0;                  /* XXX */
842
843     return 0;
844 }
845
846 /* Set the features advertised by 'netdev' to 'advertise'. */
847 static int
848 netdev_linux_set_advertisements(struct netdev *netdev, uint32_t advertise)
849 {
850     struct ethtool_cmd ecmd;
851     int error;
852
853     memset(&ecmd, 0, sizeof ecmd);
854     error = netdev_linux_do_ethtool(netdev, &ecmd,
855                                     ETHTOOL_GSET, "ETHTOOL_GSET");
856     if (error) {
857         return error;
858     }
859
860     ecmd.advertising = 0;
861     if (advertise & OFPPF_10MB_HD) {
862         ecmd.advertising |= ADVERTISED_10baseT_Half;
863     }
864     if (advertise & OFPPF_10MB_FD) {
865         ecmd.advertising |= ADVERTISED_10baseT_Full;
866     }
867     if (advertise & OFPPF_100MB_HD) {
868         ecmd.advertising |= ADVERTISED_100baseT_Half;
869     }
870     if (advertise & OFPPF_100MB_FD) {
871         ecmd.advertising |= ADVERTISED_100baseT_Full;
872     }
873     if (advertise & OFPPF_1GB_HD) {
874         ecmd.advertising |= ADVERTISED_1000baseT_Half;
875     }
876     if (advertise & OFPPF_1GB_FD) {
877         ecmd.advertising |= ADVERTISED_1000baseT_Full;
878     }
879     if (advertise & OFPPF_10GB_FD) {
880         ecmd.advertising |= ADVERTISED_10000baseT_Full;
881     }
882     if (advertise & OFPPF_COPPER) {
883         ecmd.advertising |= ADVERTISED_TP;
884     }
885     if (advertise & OFPPF_FIBER) {
886         ecmd.advertising |= ADVERTISED_FIBRE;
887     }
888     if (advertise & OFPPF_AUTONEG) {
889         ecmd.advertising |= ADVERTISED_Autoneg;
890     }
891     if (advertise & OFPPF_PAUSE) {
892         ecmd.advertising |= ADVERTISED_Pause;
893     }
894     if (advertise & OFPPF_PAUSE_ASYM) {
895         ecmd.advertising |= ADVERTISED_Asym_Pause;
896     }
897     return netdev_linux_do_ethtool(netdev, &ecmd,
898                                    ETHTOOL_SSET, "ETHTOOL_SSET");
899 }
900
901 /* If 'netdev_name' is the name of a VLAN network device (e.g. one created with
902  * vconfig(8)), sets '*vlan_vid' to the VLAN VID associated with that device
903  * and returns 0.  Otherwise returns a errno value (specifically ENOENT if
904  * 'netdev_name' is the name of a network device that is not a VLAN device) and
905  * sets '*vlan_vid' to -1. */
906 static int
907 netdev_linux_get_vlan_vid(const struct netdev *netdev, int *vlan_vid)
908 {
909     const char *netdev_name = netdev_get_name(netdev);
910     struct ds line = DS_EMPTY_INITIALIZER;
911     FILE *stream = NULL;
912     int error;
913     char *fn;
914
915     COVERAGE_INC(netdev_get_vlan_vid);
916     fn = xasprintf("/proc/net/vlan/%s", netdev_name);
917     stream = fopen(fn, "r");
918     if (!stream) {
919         error = errno;
920         goto done;
921     }
922
923     if (ds_get_line(&line, stream)) {
924         if (ferror(stream)) {
925             error = errno;
926             VLOG_ERR_RL(&rl, "error reading \"%s\": %s", fn, strerror(errno));
927         } else {
928             error = EPROTO;
929             VLOG_ERR_RL(&rl, "unexpected end of file reading \"%s\"", fn);
930         }
931         goto done;
932     }
933
934     if (!sscanf(ds_cstr(&line), "%*s VID: %d", vlan_vid)) {
935         error = EPROTO;
936         VLOG_ERR_RL(&rl, "parse error reading \"%s\" line 1: \"%s\"",
937                     fn, ds_cstr(&line));
938         goto done;
939     }
940
941     error = 0;
942
943 done:
944     free(fn);
945     if (stream) {
946         fclose(stream);
947     }
948     ds_destroy(&line);
949     if (error) {
950         *vlan_vid = -1;
951     }
952     return error;
953 }
954
955 #define POLICE_ADD_CMD "/sbin/tc qdisc add dev %s handle ffff: ingress"
956 #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"
957 /* We redirect stderr to /dev/null because we often want to remove all
958  * traffic control configuration on a port so its in a known state.  If
959  * this done when there is no such configuration, tc complains, so we just
960  * always ignore it.
961  */
962 #define POLICE_DEL_CMD "/sbin/tc qdisc del dev %s handle ffff: ingress 2>/dev/null"
963
964 /* Attempts to set input rate limiting (policing) policy. */
965 static int
966 netdev_linux_set_policing(struct netdev *netdev,
967                           uint32_t kbits_rate, uint32_t kbits_burst)
968 {
969     const char *netdev_name = netdev_get_name(netdev);
970     char command[1024];
971
972     COVERAGE_INC(netdev_set_policing);
973     if (kbits_rate) {
974         if (!kbits_burst) {
975             /* Default to 10 kilobits if not specified. */
976             kbits_burst = 10;
977         }
978
979         /* xxx This should be more careful about only adding if it
980          * xxx actually exists, as opposed to always deleting it. */
981         snprintf(command, sizeof(command), POLICE_DEL_CMD, netdev_name);
982         if (system(command) == -1) {
983             VLOG_WARN_RL(&rl, "%s: problem removing policing", netdev_name);
984         }
985
986         snprintf(command, sizeof(command), POLICE_ADD_CMD, netdev_name);
987         if (system(command) != 0) {
988             VLOG_WARN_RL(&rl, "%s: problem adding policing", netdev_name);
989             return -1;
990         }
991
992         snprintf(command, sizeof(command), POLICE_CONFIG_CMD, netdev_name,
993                 kbits_rate, kbits_burst);
994         if (system(command) != 0) {
995             VLOG_WARN_RL(&rl, "%s: problem configuring policing",
996                     netdev_name);
997             return -1;
998         }
999     } else {
1000         snprintf(command, sizeof(command), POLICE_DEL_CMD, netdev_name);
1001         if (system(command) == -1) {
1002             VLOG_WARN_RL(&rl, "%s: problem removing policing", netdev_name);
1003         }
1004     }
1005
1006     return 0;
1007 }
1008
1009 static int
1010 netdev_linux_get_in4(const struct netdev *netdev_,
1011                      struct in_addr *address, struct in_addr *netmask)
1012 {
1013     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
1014     if (!(netdev->cache->valid & VALID_IN4)) {
1015         int error;
1016
1017         error = netdev_linux_get_ipv4(netdev_, &netdev->cache->address,
1018                                       SIOCGIFADDR, "SIOCGIFADDR");
1019         if (error) {
1020             return error;
1021         }
1022
1023         error = netdev_linux_get_ipv4(netdev_, &netdev->cache->netmask,
1024                                       SIOCGIFNETMASK, "SIOCGIFNETMASK");
1025         if (error) {
1026             return error;
1027         }
1028
1029         netdev->cache->valid |= VALID_IN4;
1030     }
1031     *address = netdev->cache->address;
1032     *netmask = netdev->cache->netmask;
1033     return address->s_addr == INADDR_ANY ? EADDRNOTAVAIL : 0;
1034 }
1035
1036 static int
1037 netdev_linux_set_in4(struct netdev *netdev_, struct in_addr address,
1038                      struct in_addr netmask)
1039 {
1040     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
1041     int error;
1042
1043     error = do_set_addr(netdev_, SIOCSIFADDR, "SIOCSIFADDR", address);
1044     if (!error) {
1045         netdev->cache->valid |= VALID_IN4;
1046         netdev->cache->address = address;
1047         netdev->cache->netmask = netmask;
1048         if (address.s_addr != INADDR_ANY) {
1049             error = do_set_addr(netdev_, SIOCSIFNETMASK,
1050                                 "SIOCSIFNETMASK", netmask);
1051         }
1052     }
1053     return error;
1054 }
1055
1056 static bool
1057 parse_if_inet6_line(const char *line,
1058                     struct in6_addr *in6, char ifname[16 + 1])
1059 {
1060     uint8_t *s6 = in6->s6_addr;
1061 #define X8 "%2"SCNx8
1062     return sscanf(line,
1063                   " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
1064                   "%*x %*x %*x %*x %16s\n",
1065                   &s6[0], &s6[1], &s6[2], &s6[3],
1066                   &s6[4], &s6[5], &s6[6], &s6[7],
1067                   &s6[8], &s6[9], &s6[10], &s6[11],
1068                   &s6[12], &s6[13], &s6[14], &s6[15],
1069                   ifname) == 17;
1070 }
1071
1072 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
1073  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
1074 static int
1075 netdev_linux_get_in6(const struct netdev *netdev_, struct in6_addr *in6)
1076 {
1077     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
1078     if (!(netdev->cache->valid & VALID_IN6)) {
1079         FILE *file;
1080         char line[128];
1081
1082         netdev->cache->in6 = in6addr_any;
1083
1084         file = fopen("/proc/net/if_inet6", "r");
1085         if (file != NULL) {
1086             const char *name = netdev_get_name(netdev_);
1087             while (fgets(line, sizeof line, file)) {
1088                 struct in6_addr in6;
1089                 char ifname[16 + 1];
1090                 if (parse_if_inet6_line(line, &in6, ifname)
1091                     && !strcmp(name, ifname))
1092                 {
1093                     netdev->cache->in6 = in6;
1094                     break;
1095                 }
1096             }
1097             fclose(file);
1098         }
1099         netdev->cache->valid |= VALID_IN6;
1100     }
1101     *in6 = netdev->cache->in6;
1102     return 0;
1103 }
1104
1105 static void
1106 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
1107 {
1108     struct sockaddr_in sin;
1109     memset(&sin, 0, sizeof sin);
1110     sin.sin_family = AF_INET;
1111     sin.sin_addr = addr;
1112     sin.sin_port = 0;
1113
1114     memset(sa, 0, sizeof *sa);
1115     memcpy(sa, &sin, sizeof sin);
1116 }
1117
1118 static int
1119 do_set_addr(struct netdev *netdev,
1120             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
1121 {
1122     struct ifreq ifr;
1123     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
1124     make_in4_sockaddr(&ifr.ifr_addr, addr);
1125     return netdev_linux_do_ioctl(netdev, &ifr, ioctl_nr, ioctl_name);
1126 }
1127
1128 /* Adds 'router' as a default IP gateway. */
1129 static int
1130 netdev_linux_add_router(struct netdev *netdev UNUSED, struct in_addr router)
1131 {
1132     struct in_addr any = { INADDR_ANY };
1133     struct rtentry rt;
1134     int error;
1135
1136     memset(&rt, 0, sizeof rt);
1137     make_in4_sockaddr(&rt.rt_dst, any);
1138     make_in4_sockaddr(&rt.rt_gateway, router);
1139     make_in4_sockaddr(&rt.rt_genmask, any);
1140     rt.rt_flags = RTF_UP | RTF_GATEWAY;
1141     COVERAGE_INC(netdev_add_router);
1142     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
1143     if (error) {
1144         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
1145     }
1146     return error;
1147 }
1148
1149 static int
1150 netdev_linux_get_next_hop(const struct in_addr *host, struct in_addr *next_hop,
1151                           char **netdev_name)
1152 {
1153     static const char fn[] = "/proc/net/route";
1154     FILE *stream;
1155     char line[256];
1156     int ln;
1157
1158     *netdev_name = NULL;
1159     stream = fopen(fn, "r");
1160     if (stream == NULL) {
1161         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1162         return errno;
1163     }
1164
1165     ln = 0;
1166     while (fgets(line, sizeof line, stream)) {
1167         if (++ln >= 2) {
1168             char iface[17];
1169             uint32_t dest, gateway, mask;
1170             int refcnt, metric, mtu;
1171             unsigned int flags, use, window, irtt;
1172
1173             if (sscanf(line,
1174                        "%16s %"SCNx32" %"SCNx32" %04X %d %u %d %"SCNx32
1175                        " %d %u %u\n",
1176                        iface, &dest, &gateway, &flags, &refcnt,
1177                        &use, &metric, &mask, &mtu, &window, &irtt) != 11) {
1178
1179                 VLOG_WARN_RL(&rl, "%s: could not parse line %d: %s", 
1180                         fn, ln, line);
1181                 continue;
1182             }
1183             if (!(flags & RTF_UP)) {
1184                 /* Skip routes that aren't up. */
1185                 continue;
1186             }
1187
1188             /* The output of 'dest', 'mask', and 'gateway' were given in
1189              * network byte order, so we don't need need any endian 
1190              * conversions here. */
1191             if ((dest & mask) == (host->s_addr & mask)) {
1192                 if (!gateway) {
1193                     /* The host is directly reachable. */
1194                     next_hop->s_addr = 0;
1195                 } else {
1196                     /* To reach the host, we must go through a gateway. */
1197                     next_hop->s_addr = gateway;
1198                 }
1199                 *netdev_name = xstrdup(iface);
1200                 fclose(stream);
1201                 return 0;
1202             }
1203         }
1204     }
1205
1206     fclose(stream);
1207     return ENXIO;
1208 }
1209
1210 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
1211  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
1212  * returns 0.  Otherwise, it returns a positive errno value; in particular,
1213  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
1214 static int
1215 netdev_linux_arp_lookup(const struct netdev *netdev,
1216                         uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
1217 {
1218     struct arpreq r;
1219     struct sockaddr_in *pa;
1220     int retval;
1221
1222     memset(&r, 0, sizeof r);
1223     pa = (struct sockaddr_in *) &r.arp_pa;
1224     pa->sin_family = AF_INET;
1225     pa->sin_addr.s_addr = ip;
1226     pa->sin_port = 0;
1227     r.arp_ha.sa_family = ARPHRD_ETHER;
1228     r.arp_flags = 0;
1229     strncpy(r.arp_dev, netdev->name, sizeof r.arp_dev);
1230     COVERAGE_INC(netdev_arp_lookup);
1231     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
1232     if (!retval) {
1233         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
1234     } else if (retval != ENXIO) {
1235         VLOG_WARN_RL(&rl, "%s: could not look up ARP entry for "IP_FMT": %s",
1236                      netdev->name, IP_ARGS(&ip), strerror(retval));
1237     }
1238     return retval;
1239 }
1240
1241 static int
1242 nd_to_iff_flags(enum netdev_flags nd)
1243 {
1244     int iff = 0;
1245     if (nd & NETDEV_UP) {
1246         iff |= IFF_UP;
1247     }
1248     if (nd & NETDEV_PROMISC) {
1249         iff |= IFF_PROMISC;
1250     }
1251     return iff;
1252 }
1253
1254 static int
1255 iff_to_nd_flags(int iff)
1256 {
1257     enum netdev_flags nd = 0;
1258     if (iff & IFF_UP) {
1259         nd |= NETDEV_UP;
1260     }
1261     if (iff & IFF_PROMISC) {
1262         nd |= NETDEV_PROMISC;
1263     }
1264     return nd;
1265 }
1266
1267 static int
1268 netdev_linux_update_flags(struct netdev *netdev, enum netdev_flags off,
1269                           enum netdev_flags on, enum netdev_flags *old_flagsp)
1270 {
1271     int old_flags, new_flags;
1272     int error;
1273
1274     error = get_flags(netdev, &old_flags);
1275     if (!error) {
1276         *old_flagsp = iff_to_nd_flags(old_flags);
1277         new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
1278         if (new_flags != old_flags) {
1279             error = set_flags(netdev, new_flags);
1280         }
1281     }
1282     return error;
1283 }
1284
1285 static void
1286 poll_notify(struct list *list)
1287 {
1288     struct netdev_linux_notifier *notifier;
1289     LIST_FOR_EACH (notifier, struct netdev_linux_notifier, node, list) {
1290         struct netdev_notifier *n = &notifier->notifier;
1291         n->cb(n);
1292     }
1293 }
1294
1295 static void
1296 netdev_linux_poll_cb(const struct rtnetlink_change *change,
1297                      void *aux UNUSED)
1298 {
1299     if (change) {
1300         struct list *list = shash_find_data(&netdev_linux_notifiers,
1301                                             change->ifname);
1302         if (list) {
1303             poll_notify(list);
1304         }
1305     } else {
1306         struct shash_node *node;
1307         SHASH_FOR_EACH (node, &netdev_linux_notifiers) {
1308             poll_notify(node->data);
1309         }
1310     }
1311 }
1312
1313 static int
1314 netdev_linux_poll_add(struct netdev *netdev,
1315                       void (*cb)(struct netdev_notifier *), void *aux,
1316                       struct netdev_notifier **notifierp)
1317 {
1318     const char *netdev_name = netdev_get_name(netdev);
1319     struct netdev_linux_notifier *notifier;
1320     struct list *list;
1321
1322     if (shash_is_empty(&netdev_linux_notifiers)) {
1323         int error = rtnetlink_notifier_register(&netdev_linux_poll_notifier,
1324                                                    netdev_linux_poll_cb, NULL);
1325         if (error) {
1326             return error;
1327         }
1328     }
1329
1330     list = shash_find_data(&netdev_linux_notifiers, netdev_name);
1331     if (!list) {
1332         list = xmalloc(sizeof *list);
1333         list_init(list);
1334         shash_add(&netdev_linux_notifiers, netdev_name, list);
1335     }
1336
1337     notifier = xmalloc(sizeof *notifier);
1338     netdev_notifier_init(&notifier->notifier, netdev, cb, aux);
1339     list_push_back(list, &notifier->node);
1340     *notifierp = &notifier->notifier;
1341     return 0;
1342 }
1343
1344 static void
1345 netdev_linux_poll_remove(struct netdev_notifier *notifier_)
1346 {
1347     struct netdev_linux_notifier *notifier =
1348         CONTAINER_OF(notifier_, struct netdev_linux_notifier, notifier);
1349     struct list *list;
1350
1351     /* Remove 'notifier' from its list. */
1352     list = list_remove(&notifier->node);
1353     if (list_is_empty(list)) {
1354         /* The list is now empty.  Remove it from the hash and free it. */
1355         const char *netdev_name = netdev_get_name(notifier->notifier.netdev);
1356         shash_delete(&netdev_linux_notifiers,
1357                      shash_find(&netdev_linux_notifiers, netdev_name));
1358         free(list);
1359     }
1360     free(notifier);
1361
1362     /* If that was the last notifier, unregister. */
1363     if (shash_is_empty(&netdev_linux_notifiers)) {
1364         rtnetlink_notifier_unregister(&netdev_linux_poll_notifier);
1365     }
1366 }
1367
1368 const struct netdev_class netdev_linux_class = {
1369     "",                         /* prefix */
1370     "linux",                    /* name */
1371
1372     netdev_linux_init,
1373     netdev_linux_run,
1374     netdev_linux_wait,
1375
1376     netdev_linux_open,
1377     netdev_linux_close,
1378
1379     netdev_linux_enumerate,
1380
1381     netdev_linux_recv,
1382     netdev_linux_recv_wait,
1383     netdev_linux_drain,
1384
1385     netdev_linux_send,
1386     netdev_linux_send_wait,
1387
1388     netdev_linux_set_etheraddr,
1389     netdev_linux_get_etheraddr,
1390     netdev_linux_get_mtu,
1391     netdev_linux_get_carrier,
1392     netdev_linux_get_stats,
1393
1394     netdev_linux_get_features,
1395     netdev_linux_set_advertisements,
1396     netdev_linux_get_vlan_vid,
1397     netdev_linux_set_policing,
1398
1399     netdev_linux_get_in4,
1400     netdev_linux_set_in4,
1401     netdev_linux_get_in6,
1402     netdev_linux_add_router,
1403     netdev_linux_get_next_hop,
1404     netdev_linux_arp_lookup,
1405
1406     netdev_linux_update_flags,
1407
1408     netdev_linux_poll_add,
1409     netdev_linux_poll_remove,
1410 };
1411
1412 const struct netdev_class netdev_tap_class = {
1413     "tap",                      /* prefix */
1414     "tap",                      /* name */
1415
1416     netdev_linux_init,
1417     NULL,                       /* run */
1418     NULL,                       /* wait */
1419
1420     netdev_linux_open,
1421     netdev_linux_close,
1422
1423     netdev_linux_enumerate,
1424
1425     netdev_linux_recv,
1426     netdev_linux_recv_wait,
1427     netdev_linux_drain,
1428
1429     netdev_linux_send,
1430     netdev_linux_send_wait,
1431
1432     netdev_linux_set_etheraddr,
1433     netdev_linux_get_etheraddr,
1434     netdev_linux_get_mtu,
1435     netdev_linux_get_carrier,
1436     netdev_linux_get_stats,
1437
1438     netdev_linux_get_features,
1439     netdev_linux_set_advertisements,
1440     netdev_linux_get_vlan_vid,
1441     netdev_linux_set_policing,
1442
1443     netdev_linux_get_in4,
1444     netdev_linux_set_in4,
1445     netdev_linux_get_in6,
1446     netdev_linux_add_router,
1447     netdev_linux_get_next_hop,
1448     netdev_linux_arp_lookup,
1449
1450     netdev_linux_update_flags,
1451
1452     netdev_linux_poll_add,
1453     netdev_linux_poll_remove,
1454 };
1455 \f
1456 static int
1457 get_stats_via_netlink(int ifindex, struct netdev_stats *stats)
1458 {
1459     /* Policy for RTNLGRP_LINK messages.
1460      *
1461      * There are *many* more fields in these messages, but currently we only
1462      * care about these fields. */
1463     static const struct nl_policy rtnlgrp_link_policy[] = {
1464         [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
1465         [IFLA_STATS] = { .type = NL_A_UNSPEC, .optional = true,
1466                          .min_len = sizeof(struct rtnl_link_stats) },
1467     };
1468
1469
1470     static struct nl_sock *rtnl_sock;
1471     struct ofpbuf request;
1472     struct ofpbuf *reply;
1473     struct ifinfomsg *ifi;
1474     const struct rtnl_link_stats *rtnl_stats;
1475     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
1476     int error;
1477
1478     if (!rtnl_sock) {
1479         error = nl_sock_create(NETLINK_ROUTE, 0, 0, 0, &rtnl_sock);
1480         if (error) {
1481             VLOG_ERR_RL(&rl, "failed to create rtnetlink socket: %s",
1482                         strerror(error));
1483             return error;
1484         }
1485     }
1486
1487     ofpbuf_init(&request, 0);
1488     nl_msg_put_nlmsghdr(&request, rtnl_sock, sizeof *ifi,
1489                         RTM_GETLINK, NLM_F_REQUEST);
1490     ifi = ofpbuf_put_zeros(&request, sizeof *ifi);
1491     ifi->ifi_family = PF_UNSPEC;
1492     ifi->ifi_index = ifindex;
1493     error = nl_sock_transact(rtnl_sock, &request, &reply);
1494     ofpbuf_uninit(&request);
1495     if (error) {
1496         return error;
1497     }
1498
1499     if (!nl_policy_parse(reply, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
1500                          rtnlgrp_link_policy,
1501                          attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
1502         ofpbuf_delete(reply);
1503         return EPROTO;
1504     }
1505
1506     if (!attrs[IFLA_STATS]) {
1507         VLOG_WARN_RL(&rl, "RTM_GETLINK reply lacks stats");
1508         ofpbuf_delete(reply);
1509         return EPROTO;
1510     }
1511
1512     rtnl_stats = nl_attr_get(attrs[IFLA_STATS]);
1513     stats->rx_packets = rtnl_stats->rx_packets;
1514     stats->tx_packets = rtnl_stats->tx_packets;
1515     stats->rx_bytes = rtnl_stats->rx_bytes;
1516     stats->tx_bytes = rtnl_stats->tx_bytes;
1517     stats->rx_errors = rtnl_stats->rx_errors;
1518     stats->tx_errors = rtnl_stats->tx_errors;
1519     stats->rx_dropped = rtnl_stats->rx_dropped;
1520     stats->tx_dropped = rtnl_stats->tx_dropped;
1521     stats->multicast = rtnl_stats->multicast;
1522     stats->collisions = rtnl_stats->collisions;
1523     stats->rx_length_errors = rtnl_stats->rx_length_errors;
1524     stats->rx_over_errors = rtnl_stats->rx_over_errors;
1525     stats->rx_crc_errors = rtnl_stats->rx_crc_errors;
1526     stats->rx_frame_errors = rtnl_stats->rx_frame_errors;
1527     stats->rx_fifo_errors = rtnl_stats->rx_fifo_errors;
1528     stats->rx_missed_errors = rtnl_stats->rx_missed_errors;
1529     stats->tx_aborted_errors = rtnl_stats->tx_aborted_errors;
1530     stats->tx_carrier_errors = rtnl_stats->tx_carrier_errors;
1531     stats->tx_fifo_errors = rtnl_stats->tx_fifo_errors;
1532     stats->tx_heartbeat_errors = rtnl_stats->tx_heartbeat_errors;
1533     stats->tx_window_errors = rtnl_stats->tx_window_errors;
1534
1535     ofpbuf_delete(reply);
1536
1537     return 0;
1538 }
1539
1540 static int
1541 get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats)
1542 {
1543     static const char fn[] = "/proc/net/dev";
1544     char line[1024];
1545     FILE *stream;
1546     int ln;
1547
1548     stream = fopen(fn, "r");
1549     if (!stream) {
1550         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1551         return errno;
1552     }
1553
1554     ln = 0;
1555     while (fgets(line, sizeof line, stream)) {
1556         if (++ln >= 3) {
1557             char devname[16];
1558 #define X64 "%"SCNu64
1559             if (sscanf(line,
1560                        " %15[^:]:"
1561                        X64 X64 X64 X64 X64 X64 X64 "%*u"
1562                        X64 X64 X64 X64 X64 X64 X64 "%*u",
1563                        devname,
1564                        &stats->rx_bytes,
1565                        &stats->rx_packets,
1566                        &stats->rx_errors,
1567                        &stats->rx_dropped,
1568                        &stats->rx_fifo_errors,
1569                        &stats->rx_frame_errors,
1570                        &stats->multicast,
1571                        &stats->tx_bytes,
1572                        &stats->tx_packets,
1573                        &stats->tx_errors,
1574                        &stats->tx_dropped,
1575                        &stats->tx_fifo_errors,
1576                        &stats->collisions,
1577                        &stats->tx_carrier_errors) != 15) {
1578                 VLOG_WARN_RL(&rl, "%s:%d: parse error", fn, ln);
1579             } else if (!strcmp(devname, netdev_name)) {
1580                 stats->rx_length_errors = UINT64_MAX;
1581                 stats->rx_over_errors = UINT64_MAX;
1582                 stats->rx_crc_errors = UINT64_MAX;
1583                 stats->rx_missed_errors = UINT64_MAX;
1584                 stats->tx_aborted_errors = UINT64_MAX;
1585                 stats->tx_heartbeat_errors = UINT64_MAX;
1586                 stats->tx_window_errors = UINT64_MAX;
1587                 fclose(stream);
1588                 return 0;
1589             }
1590         }
1591     }
1592     VLOG_WARN_RL(&rl, "%s: no stats for %s", fn, netdev_name);
1593     fclose(stream);
1594     return ENODEV;
1595 }
1596 \f
1597 static int
1598 get_flags(const struct netdev *netdev, int *flags)
1599 {
1600     struct ifreq ifr;
1601     int error;
1602
1603     error = netdev_linux_do_ioctl(netdev, &ifr, SIOCGIFFLAGS, "SIOCGIFFLAGS");
1604     *flags = ifr.ifr_flags;
1605     return error;
1606 }
1607
1608 static int
1609 set_flags(struct netdev *netdev, int flags)
1610 {
1611     struct ifreq ifr;
1612
1613     ifr.ifr_flags = flags;
1614     return netdev_linux_do_ioctl(netdev, &ifr, SIOCSIFFLAGS, "SIOCSIFFLAGS");
1615 }
1616
1617 static int
1618 do_get_ifindex(const char *netdev_name)
1619 {
1620     struct ifreq ifr;
1621
1622     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1623     COVERAGE_INC(netdev_get_ifindex);
1624     if (ioctl(af_inet_sock, SIOCGIFINDEX, &ifr) < 0) {
1625         VLOG_WARN_RL(&rl, "ioctl(SIOCGIFINDEX) on %s device failed: %s",
1626                      netdev_name, strerror(errno));
1627         return -errno;
1628     }
1629     return ifr.ifr_ifindex;
1630 }
1631
1632 static int
1633 get_ifindex(const struct netdev *netdev_, int *ifindexp)
1634 {
1635     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
1636     *ifindexp = 0;
1637     if (!(netdev->cache->valid & VALID_IFINDEX)) {
1638         int ifindex = do_get_ifindex(netdev_get_name(netdev_));
1639         if (ifindex < 0) {
1640             return -ifindex;
1641         }
1642         netdev->cache->valid |= VALID_IFINDEX;
1643         netdev->cache->ifindex = ifindex;
1644     }
1645     *ifindexp = netdev->cache->ifindex;
1646     return 0;
1647 }
1648
1649 static int
1650 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
1651 {
1652     struct ifreq ifr;
1653     int hwaddr_family;
1654
1655     memset(&ifr, 0, sizeof ifr);
1656     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1657     COVERAGE_INC(netdev_get_hwaddr);
1658     if (ioctl(af_inet_sock, SIOCGIFHWADDR, &ifr) < 0) {
1659         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
1660                  netdev_name, strerror(errno));
1661         return errno;
1662     }
1663     hwaddr_family = ifr.ifr_hwaddr.sa_family;
1664     if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
1665         VLOG_WARN("%s device has unknown hardware address family %d",
1666                   netdev_name, hwaddr_family);
1667     }
1668     memcpy(ea, ifr.ifr_hwaddr.sa_data, ETH_ADDR_LEN);
1669     return 0;
1670 }
1671
1672 static int
1673 set_etheraddr(const char *netdev_name, int hwaddr_family,
1674               const uint8_t mac[ETH_ADDR_LEN])
1675 {
1676     struct ifreq ifr;
1677
1678     memset(&ifr, 0, sizeof ifr);
1679     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1680     ifr.ifr_hwaddr.sa_family = hwaddr_family;
1681     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
1682     COVERAGE_INC(netdev_set_hwaddr);
1683     if (ioctl(af_inet_sock, SIOCSIFHWADDR, &ifr) < 0) {
1684         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
1685                  netdev_name, strerror(errno));
1686         return errno;
1687     }
1688     return 0;
1689 }
1690
1691 static int
1692 netdev_linux_do_ethtool(struct netdev *netdev, struct ethtool_cmd *ecmd,
1693                         int cmd, const char *cmd_name)
1694 {
1695     struct ifreq ifr;
1696
1697     memset(&ifr, 0, sizeof ifr);
1698     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
1699     ifr.ifr_data = (caddr_t) ecmd;
1700
1701     ecmd->cmd = cmd;
1702     COVERAGE_INC(netdev_ethtool);
1703     if (ioctl(af_inet_sock, SIOCETHTOOL, &ifr) == 0) {
1704         return 0;
1705     } else {
1706         if (errno != EOPNOTSUPP) {
1707             VLOG_WARN_RL(&rl, "ethtool command %s on network device %s "
1708                          "failed: %s", cmd_name, netdev->name,
1709                          strerror(errno));
1710         } else {
1711             /* The device doesn't support this operation.  That's pretty
1712              * common, so there's no point in logging anything. */
1713         }
1714         return errno;
1715     }
1716 }
1717
1718 static int
1719 netdev_linux_do_ioctl(const struct netdev *netdev, struct ifreq *ifr,
1720                       int cmd, const char *cmd_name)
1721 {
1722     strncpy(ifr->ifr_name, netdev_get_name(netdev), sizeof ifr->ifr_name);
1723     if (ioctl(af_inet_sock, cmd, ifr) == -1) {
1724         VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s",
1725                     netdev_get_name(netdev), cmd_name, strerror(errno));
1726         return errno;
1727     }
1728     return 0;
1729 }
1730
1731 static int
1732 netdev_linux_get_ipv4(const struct netdev *netdev, struct in_addr *ip,
1733                       int cmd, const char *cmd_name)
1734 {
1735     struct ifreq ifr;
1736     int error;
1737
1738     ifr.ifr_addr.sa_family = AF_INET;
1739     error = netdev_linux_do_ioctl(netdev, &ifr, cmd, cmd_name);
1740     if (!error) {
1741         const struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
1742         *ip = sin->sin_addr;
1743     }
1744     return error;
1745 }