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