netdev: New function netdev_get_ifindex().
[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 /* Returns the ifindex of 'netdev', if successful, as a positive number.
552  * On failure, returns a negative errno value. */
553 static int
554 netdev_linux_get_ifindex(const struct netdev *netdev)
555 {
556     int ifindex, error;
557
558     error = get_ifindex(netdev, &ifindex);
559     return error ? -error : ifindex;
560 }
561
562 static int
563 netdev_linux_get_carrier(const struct netdev *netdev_, bool *carrier)
564 {
565     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
566     int error = 0;
567     char *fn = NULL;
568     int fd = -1;
569
570     if (!(netdev->cache->valid & VALID_CARRIER)) {
571         char line[8];
572         int retval;
573
574         fn = xasprintf("/sys/class/net/%s/carrier", netdev_get_name(netdev_));
575         fd = open(fn, O_RDONLY);
576         if (fd < 0) {
577             error = errno;
578             VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(error));
579             goto exit;
580         }
581
582         retval = read(fd, line, sizeof line);
583         if (retval < 0) {
584             error = errno;
585             if (error == EINVAL) {
586                 /* This is the normal return value when we try to check carrier
587                  * if the network device is not up. */
588             } else {
589                 VLOG_WARN_RL(&rl, "%s: read failed: %s", fn, strerror(error));
590             }
591             goto exit;
592         } else if (retval == 0) {
593             error = EPROTO;
594             VLOG_WARN_RL(&rl, "%s: unexpected end of file", fn);
595             goto exit;
596         }
597
598         if (line[0] != '0' && line[0] != '1') {
599             error = EPROTO;
600             VLOG_WARN_RL(&rl, "%s: value is %c (expected 0 or 1)",
601                          fn, line[0]);
602             goto exit;
603         }
604         netdev->cache->carrier = line[0] != '0';
605         netdev->cache->valid |= VALID_CARRIER;
606     }
607     *carrier = netdev->cache->carrier;
608     error = 0;
609
610 exit:
611     if (fd >= 0) {
612         close(fd);
613     }
614     free(fn);
615     return error;
616 }
617
618 /* Check whether we can we use RTM_GETLINK to get network device statistics.
619  * In pre-2.6.19 kernels, this was only available if wireless extensions were
620  * enabled. */
621 static bool
622 check_for_working_netlink_stats(void)
623 {
624     /* Decide on the netdev_get_stats() implementation to use.  Netlink is
625      * preferable, so if that works, we'll use it. */
626     int ifindex = do_get_ifindex("lo");
627     if (ifindex < 0) {
628         VLOG_WARN("failed to get ifindex for lo, "
629                   "obtaining netdev stats from proc");
630         return false;
631     } else {
632         struct netdev_stats stats;
633         int error = get_stats_via_netlink(ifindex, &stats);
634         if (!error) {
635             VLOG_DBG("obtaining netdev stats via rtnetlink");
636             return true;
637         } else {
638             VLOG_INFO("RTM_GETLINK failed (%s), obtaining netdev stats "
639                       "via proc (you are probably running a pre-2.6.19 "
640                       "kernel)", strerror(error));
641             return false;
642         }
643     }
644 }
645
646 /* Retrieves current device stats for 'netdev'.
647  *
648  * XXX All of the members of struct netdev_stats are 64 bits wide, but on
649  * 32-bit architectures the Linux network stats are only 32 bits. */
650 static int
651 netdev_linux_get_stats(const struct netdev *netdev_, struct netdev_stats *stats)
652 {
653     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
654     static int use_netlink_stats = -1;
655     int error;
656     struct netdev_stats raw_stats;
657     struct netdev_stats *collect_stats = stats;
658
659     COVERAGE_INC(netdev_get_stats);
660
661     if (!(netdev->cache->valid & VALID_IS_INTERNAL)) {
662         netdev->cache->is_internal = (netdev->tap_fd != -1);
663
664         if (!netdev->cache->is_internal) {
665             struct ethtool_drvinfo drvinfo;
666
667             memset(&drvinfo, 0, sizeof drvinfo);
668             error = netdev_linux_do_ethtool(&netdev->netdev,
669                                             (struct ethtool_cmd *)&drvinfo,
670                                             ETHTOOL_GDRVINFO,
671                                             "ETHTOOL_GDRVINFO");
672
673             if (!error) {
674                 netdev->cache->is_internal = !strcmp(drvinfo.driver,
675                                                      "openvswitch");
676             }
677         }
678
679         netdev->cache->valid |= VALID_IS_INTERNAL;
680     }
681
682     if (netdev->cache->is_internal) {
683         collect_stats = &raw_stats;
684     }
685
686     if (use_netlink_stats < 0) {
687         use_netlink_stats = check_for_working_netlink_stats();
688     }
689     if (use_netlink_stats) {
690         int ifindex;
691
692         error = get_ifindex(&netdev->netdev, &ifindex);
693         if (!error) {
694             error = get_stats_via_netlink(ifindex, collect_stats);
695         }
696     } else {
697         error = get_stats_via_proc(netdev->netdev.name, collect_stats);
698     }
699
700     /* If this port is an internal port then the transmit and receive stats
701      * will appear to be swapped relative to the other ports since we are the
702      * one sending the data, not a remote computer.  For consistency, we swap
703      * them back here. */
704     if (netdev->cache->is_internal) {
705         stats->rx_packets = raw_stats.tx_packets;
706         stats->tx_packets = raw_stats.rx_packets;
707         stats->rx_bytes = raw_stats.tx_bytes;
708         stats->tx_bytes = raw_stats.rx_bytes;
709         stats->rx_errors = raw_stats.tx_errors;
710         stats->tx_errors = raw_stats.rx_errors;
711         stats->rx_dropped = raw_stats.tx_dropped;
712         stats->tx_dropped = raw_stats.rx_dropped;
713         stats->multicast = raw_stats.multicast;
714         stats->collisions = raw_stats.collisions;
715         stats->rx_length_errors = 0;
716         stats->rx_over_errors = 0;
717         stats->rx_crc_errors = 0;
718         stats->rx_frame_errors = 0;
719         stats->rx_fifo_errors = 0;
720         stats->rx_missed_errors = 0;
721         stats->tx_aborted_errors = 0;
722         stats->tx_carrier_errors = 0;
723         stats->tx_fifo_errors = 0;
724         stats->tx_heartbeat_errors = 0;
725         stats->tx_window_errors = 0;
726     }
727
728     return error;
729 }
730
731 /* Stores the features supported by 'netdev' into each of '*current',
732  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
733  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
734  * successful, otherwise a positive errno value. */
735 static int
736 netdev_linux_get_features(struct netdev *netdev,
737                           uint32_t *current, uint32_t *advertised,
738                           uint32_t *supported, uint32_t *peer)
739 {
740     struct ethtool_cmd ecmd;
741     int error;
742
743     memset(&ecmd, 0, sizeof ecmd);
744     error = netdev_linux_do_ethtool(netdev, &ecmd,
745                                     ETHTOOL_GSET, "ETHTOOL_GSET");
746     if (error) {
747         return error;
748     }
749
750     /* Supported features. */
751     *supported = 0;
752     if (ecmd.supported & SUPPORTED_10baseT_Half) {
753         *supported |= OFPPF_10MB_HD;
754     }
755     if (ecmd.supported & SUPPORTED_10baseT_Full) {
756         *supported |= OFPPF_10MB_FD;
757     }
758     if (ecmd.supported & SUPPORTED_100baseT_Half)  {
759         *supported |= OFPPF_100MB_HD;
760     }
761     if (ecmd.supported & SUPPORTED_100baseT_Full) {
762         *supported |= OFPPF_100MB_FD;
763     }
764     if (ecmd.supported & SUPPORTED_1000baseT_Half) {
765         *supported |= OFPPF_1GB_HD;
766     }
767     if (ecmd.supported & SUPPORTED_1000baseT_Full) {
768         *supported |= OFPPF_1GB_FD;
769     }
770     if (ecmd.supported & SUPPORTED_10000baseT_Full) {
771         *supported |= OFPPF_10GB_FD;
772     }
773     if (ecmd.supported & SUPPORTED_TP) {
774         *supported |= OFPPF_COPPER;
775     }
776     if (ecmd.supported & SUPPORTED_FIBRE) {
777         *supported |= OFPPF_FIBER;
778     }
779     if (ecmd.supported & SUPPORTED_Autoneg) {
780         *supported |= OFPPF_AUTONEG;
781     }
782     if (ecmd.supported & SUPPORTED_Pause) {
783         *supported |= OFPPF_PAUSE;
784     }
785     if (ecmd.supported & SUPPORTED_Asym_Pause) {
786         *supported |= OFPPF_PAUSE_ASYM;
787     }
788
789     /* Advertised features. */
790     *advertised = 0;
791     if (ecmd.advertising & ADVERTISED_10baseT_Half) {
792         *advertised |= OFPPF_10MB_HD;
793     }
794     if (ecmd.advertising & ADVERTISED_10baseT_Full) {
795         *advertised |= OFPPF_10MB_FD;
796     }
797     if (ecmd.advertising & ADVERTISED_100baseT_Half) {
798         *advertised |= OFPPF_100MB_HD;
799     }
800     if (ecmd.advertising & ADVERTISED_100baseT_Full) {
801         *advertised |= OFPPF_100MB_FD;
802     }
803     if (ecmd.advertising & ADVERTISED_1000baseT_Half) {
804         *advertised |= OFPPF_1GB_HD;
805     }
806     if (ecmd.advertising & ADVERTISED_1000baseT_Full) {
807         *advertised |= OFPPF_1GB_FD;
808     }
809     if (ecmd.advertising & ADVERTISED_10000baseT_Full) {
810         *advertised |= OFPPF_10GB_FD;
811     }
812     if (ecmd.advertising & ADVERTISED_TP) {
813         *advertised |= OFPPF_COPPER;
814     }
815     if (ecmd.advertising & ADVERTISED_FIBRE) {
816         *advertised |= OFPPF_FIBER;
817     }
818     if (ecmd.advertising & ADVERTISED_Autoneg) {
819         *advertised |= OFPPF_AUTONEG;
820     }
821     if (ecmd.advertising & ADVERTISED_Pause) {
822         *advertised |= OFPPF_PAUSE;
823     }
824     if (ecmd.advertising & ADVERTISED_Asym_Pause) {
825         *advertised |= OFPPF_PAUSE_ASYM;
826     }
827
828     /* Current settings. */
829     if (ecmd.speed == SPEED_10) {
830         *current = ecmd.duplex ? OFPPF_10MB_FD : OFPPF_10MB_HD;
831     } else if (ecmd.speed == SPEED_100) {
832         *current = ecmd.duplex ? OFPPF_100MB_FD : OFPPF_100MB_HD;
833     } else if (ecmd.speed == SPEED_1000) {
834         *current = ecmd.duplex ? OFPPF_1GB_FD : OFPPF_1GB_HD;
835     } else if (ecmd.speed == SPEED_10000) {
836         *current = OFPPF_10GB_FD;
837     } else {
838         *current = 0;
839     }
840
841     if (ecmd.port == PORT_TP) {
842         *current |= OFPPF_COPPER;
843     } else if (ecmd.port == PORT_FIBRE) {
844         *current |= OFPPF_FIBER;
845     }
846
847     if (ecmd.autoneg) {
848         *current |= OFPPF_AUTONEG;
849     }
850
851     /* Peer advertisements. */
852     *peer = 0;                  /* XXX */
853
854     return 0;
855 }
856
857 /* Set the features advertised by 'netdev' to 'advertise'. */
858 static int
859 netdev_linux_set_advertisements(struct netdev *netdev, uint32_t advertise)
860 {
861     struct ethtool_cmd ecmd;
862     int error;
863
864     memset(&ecmd, 0, sizeof ecmd);
865     error = netdev_linux_do_ethtool(netdev, &ecmd,
866                                     ETHTOOL_GSET, "ETHTOOL_GSET");
867     if (error) {
868         return error;
869     }
870
871     ecmd.advertising = 0;
872     if (advertise & OFPPF_10MB_HD) {
873         ecmd.advertising |= ADVERTISED_10baseT_Half;
874     }
875     if (advertise & OFPPF_10MB_FD) {
876         ecmd.advertising |= ADVERTISED_10baseT_Full;
877     }
878     if (advertise & OFPPF_100MB_HD) {
879         ecmd.advertising |= ADVERTISED_100baseT_Half;
880     }
881     if (advertise & OFPPF_100MB_FD) {
882         ecmd.advertising |= ADVERTISED_100baseT_Full;
883     }
884     if (advertise & OFPPF_1GB_HD) {
885         ecmd.advertising |= ADVERTISED_1000baseT_Half;
886     }
887     if (advertise & OFPPF_1GB_FD) {
888         ecmd.advertising |= ADVERTISED_1000baseT_Full;
889     }
890     if (advertise & OFPPF_10GB_FD) {
891         ecmd.advertising |= ADVERTISED_10000baseT_Full;
892     }
893     if (advertise & OFPPF_COPPER) {
894         ecmd.advertising |= ADVERTISED_TP;
895     }
896     if (advertise & OFPPF_FIBER) {
897         ecmd.advertising |= ADVERTISED_FIBRE;
898     }
899     if (advertise & OFPPF_AUTONEG) {
900         ecmd.advertising |= ADVERTISED_Autoneg;
901     }
902     if (advertise & OFPPF_PAUSE) {
903         ecmd.advertising |= ADVERTISED_Pause;
904     }
905     if (advertise & OFPPF_PAUSE_ASYM) {
906         ecmd.advertising |= ADVERTISED_Asym_Pause;
907     }
908     return netdev_linux_do_ethtool(netdev, &ecmd,
909                                    ETHTOOL_SSET, "ETHTOOL_SSET");
910 }
911
912 /* If 'netdev_name' is the name of a VLAN network device (e.g. one created with
913  * vconfig(8)), sets '*vlan_vid' to the VLAN VID associated with that device
914  * and returns 0.  Otherwise returns a errno value (specifically ENOENT if
915  * 'netdev_name' is the name of a network device that is not a VLAN device) and
916  * sets '*vlan_vid' to -1. */
917 static int
918 netdev_linux_get_vlan_vid(const struct netdev *netdev, int *vlan_vid)
919 {
920     const char *netdev_name = netdev_get_name(netdev);
921     struct ds line = DS_EMPTY_INITIALIZER;
922     FILE *stream = NULL;
923     int error;
924     char *fn;
925
926     COVERAGE_INC(netdev_get_vlan_vid);
927     fn = xasprintf("/proc/net/vlan/%s", netdev_name);
928     stream = fopen(fn, "r");
929     if (!stream) {
930         error = errno;
931         goto done;
932     }
933
934     if (ds_get_line(&line, stream)) {
935         if (ferror(stream)) {
936             error = errno;
937             VLOG_ERR_RL(&rl, "error reading \"%s\": %s", fn, strerror(errno));
938         } else {
939             error = EPROTO;
940             VLOG_ERR_RL(&rl, "unexpected end of file reading \"%s\"", fn);
941         }
942         goto done;
943     }
944
945     if (!sscanf(ds_cstr(&line), "%*s VID: %d", vlan_vid)) {
946         error = EPROTO;
947         VLOG_ERR_RL(&rl, "parse error reading \"%s\" line 1: \"%s\"",
948                     fn, ds_cstr(&line));
949         goto done;
950     }
951
952     error = 0;
953
954 done:
955     free(fn);
956     if (stream) {
957         fclose(stream);
958     }
959     ds_destroy(&line);
960     if (error) {
961         *vlan_vid = -1;
962     }
963     return error;
964 }
965
966 #define POLICE_ADD_CMD "/sbin/tc qdisc add dev %s handle ffff: ingress"
967 #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"
968 /* We redirect stderr to /dev/null because we often want to remove all
969  * traffic control configuration on a port so its in a known state.  If
970  * this done when there is no such configuration, tc complains, so we just
971  * always ignore it.
972  */
973 #define POLICE_DEL_CMD "/sbin/tc qdisc del dev %s handle ffff: ingress 2>/dev/null"
974
975 /* Attempts to set input rate limiting (policing) policy. */
976 static int
977 netdev_linux_set_policing(struct netdev *netdev,
978                           uint32_t kbits_rate, uint32_t kbits_burst)
979 {
980     const char *netdev_name = netdev_get_name(netdev);
981     char command[1024];
982
983     COVERAGE_INC(netdev_set_policing);
984     if (kbits_rate) {
985         if (!kbits_burst) {
986             /* Default to 10 kilobits if not specified. */
987             kbits_burst = 10;
988         }
989
990         /* xxx This should be more careful about only adding if it
991          * xxx actually exists, as opposed to always deleting it. */
992         snprintf(command, sizeof(command), POLICE_DEL_CMD, netdev_name);
993         if (system(command) == -1) {
994             VLOG_WARN_RL(&rl, "%s: problem removing policing", netdev_name);
995         }
996
997         snprintf(command, sizeof(command), POLICE_ADD_CMD, netdev_name);
998         if (system(command) != 0) {
999             VLOG_WARN_RL(&rl, "%s: problem adding policing", netdev_name);
1000             return -1;
1001         }
1002
1003         snprintf(command, sizeof(command), POLICE_CONFIG_CMD, netdev_name,
1004                 kbits_rate, kbits_burst);
1005         if (system(command) != 0) {
1006             VLOG_WARN_RL(&rl, "%s: problem configuring policing",
1007                     netdev_name);
1008             return -1;
1009         }
1010     } else {
1011         snprintf(command, sizeof(command), POLICE_DEL_CMD, netdev_name);
1012         if (system(command) == -1) {
1013             VLOG_WARN_RL(&rl, "%s: problem removing policing", netdev_name);
1014         }
1015     }
1016
1017     return 0;
1018 }
1019
1020 static int
1021 netdev_linux_get_in4(const struct netdev *netdev_,
1022                      struct in_addr *address, struct in_addr *netmask)
1023 {
1024     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
1025     if (!(netdev->cache->valid & VALID_IN4)) {
1026         int error;
1027
1028         error = netdev_linux_get_ipv4(netdev_, &netdev->cache->address,
1029                                       SIOCGIFADDR, "SIOCGIFADDR");
1030         if (error) {
1031             return error;
1032         }
1033
1034         error = netdev_linux_get_ipv4(netdev_, &netdev->cache->netmask,
1035                                       SIOCGIFNETMASK, "SIOCGIFNETMASK");
1036         if (error) {
1037             return error;
1038         }
1039
1040         netdev->cache->valid |= VALID_IN4;
1041     }
1042     *address = netdev->cache->address;
1043     *netmask = netdev->cache->netmask;
1044     return address->s_addr == INADDR_ANY ? EADDRNOTAVAIL : 0;
1045 }
1046
1047 static int
1048 netdev_linux_set_in4(struct netdev *netdev_, struct in_addr address,
1049                      struct in_addr netmask)
1050 {
1051     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
1052     int error;
1053
1054     error = do_set_addr(netdev_, SIOCSIFADDR, "SIOCSIFADDR", address);
1055     if (!error) {
1056         netdev->cache->valid |= VALID_IN4;
1057         netdev->cache->address = address;
1058         netdev->cache->netmask = netmask;
1059         if (address.s_addr != INADDR_ANY) {
1060             error = do_set_addr(netdev_, SIOCSIFNETMASK,
1061                                 "SIOCSIFNETMASK", netmask);
1062         }
1063     }
1064     return error;
1065 }
1066
1067 static bool
1068 parse_if_inet6_line(const char *line,
1069                     struct in6_addr *in6, char ifname[16 + 1])
1070 {
1071     uint8_t *s6 = in6->s6_addr;
1072 #define X8 "%2"SCNx8
1073     return sscanf(line,
1074                   " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
1075                   "%*x %*x %*x %*x %16s\n",
1076                   &s6[0], &s6[1], &s6[2], &s6[3],
1077                   &s6[4], &s6[5], &s6[6], &s6[7],
1078                   &s6[8], &s6[9], &s6[10], &s6[11],
1079                   &s6[12], &s6[13], &s6[14], &s6[15],
1080                   ifname) == 17;
1081 }
1082
1083 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
1084  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
1085 static int
1086 netdev_linux_get_in6(const struct netdev *netdev_, struct in6_addr *in6)
1087 {
1088     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
1089     if (!(netdev->cache->valid & VALID_IN6)) {
1090         FILE *file;
1091         char line[128];
1092
1093         netdev->cache->in6 = in6addr_any;
1094
1095         file = fopen("/proc/net/if_inet6", "r");
1096         if (file != NULL) {
1097             const char *name = netdev_get_name(netdev_);
1098             while (fgets(line, sizeof line, file)) {
1099                 struct in6_addr in6;
1100                 char ifname[16 + 1];
1101                 if (parse_if_inet6_line(line, &in6, ifname)
1102                     && !strcmp(name, ifname))
1103                 {
1104                     netdev->cache->in6 = in6;
1105                     break;
1106                 }
1107             }
1108             fclose(file);
1109         }
1110         netdev->cache->valid |= VALID_IN6;
1111     }
1112     *in6 = netdev->cache->in6;
1113     return 0;
1114 }
1115
1116 static void
1117 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
1118 {
1119     struct sockaddr_in sin;
1120     memset(&sin, 0, sizeof sin);
1121     sin.sin_family = AF_INET;
1122     sin.sin_addr = addr;
1123     sin.sin_port = 0;
1124
1125     memset(sa, 0, sizeof *sa);
1126     memcpy(sa, &sin, sizeof sin);
1127 }
1128
1129 static int
1130 do_set_addr(struct netdev *netdev,
1131             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
1132 {
1133     struct ifreq ifr;
1134     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
1135     make_in4_sockaddr(&ifr.ifr_addr, addr);
1136     return netdev_linux_do_ioctl(netdev, &ifr, ioctl_nr, ioctl_name);
1137 }
1138
1139 /* Adds 'router' as a default IP gateway. */
1140 static int
1141 netdev_linux_add_router(struct netdev *netdev UNUSED, struct in_addr router)
1142 {
1143     struct in_addr any = { INADDR_ANY };
1144     struct rtentry rt;
1145     int error;
1146
1147     memset(&rt, 0, sizeof rt);
1148     make_in4_sockaddr(&rt.rt_dst, any);
1149     make_in4_sockaddr(&rt.rt_gateway, router);
1150     make_in4_sockaddr(&rt.rt_genmask, any);
1151     rt.rt_flags = RTF_UP | RTF_GATEWAY;
1152     COVERAGE_INC(netdev_add_router);
1153     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
1154     if (error) {
1155         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
1156     }
1157     return error;
1158 }
1159
1160 static int
1161 netdev_linux_get_next_hop(const struct in_addr *host, struct in_addr *next_hop,
1162                           char **netdev_name)
1163 {
1164     static const char fn[] = "/proc/net/route";
1165     FILE *stream;
1166     char line[256];
1167     int ln;
1168
1169     *netdev_name = NULL;
1170     stream = fopen(fn, "r");
1171     if (stream == NULL) {
1172         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1173         return errno;
1174     }
1175
1176     ln = 0;
1177     while (fgets(line, sizeof line, stream)) {
1178         if (++ln >= 2) {
1179             char iface[17];
1180             uint32_t dest, gateway, mask;
1181             int refcnt, metric, mtu;
1182             unsigned int flags, use, window, irtt;
1183
1184             if (sscanf(line,
1185                        "%16s %"SCNx32" %"SCNx32" %04X %d %u %d %"SCNx32
1186                        " %d %u %u\n",
1187                        iface, &dest, &gateway, &flags, &refcnt,
1188                        &use, &metric, &mask, &mtu, &window, &irtt) != 11) {
1189
1190                 VLOG_WARN_RL(&rl, "%s: could not parse line %d: %s", 
1191                         fn, ln, line);
1192                 continue;
1193             }
1194             if (!(flags & RTF_UP)) {
1195                 /* Skip routes that aren't up. */
1196                 continue;
1197             }
1198
1199             /* The output of 'dest', 'mask', and 'gateway' were given in
1200              * network byte order, so we don't need need any endian 
1201              * conversions here. */
1202             if ((dest & mask) == (host->s_addr & mask)) {
1203                 if (!gateway) {
1204                     /* The host is directly reachable. */
1205                     next_hop->s_addr = 0;
1206                 } else {
1207                     /* To reach the host, we must go through a gateway. */
1208                     next_hop->s_addr = gateway;
1209                 }
1210                 *netdev_name = xstrdup(iface);
1211                 fclose(stream);
1212                 return 0;
1213             }
1214         }
1215     }
1216
1217     fclose(stream);
1218     return ENXIO;
1219 }
1220
1221 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
1222  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
1223  * returns 0.  Otherwise, it returns a positive errno value; in particular,
1224  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
1225 static int
1226 netdev_linux_arp_lookup(const struct netdev *netdev,
1227                         uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
1228 {
1229     struct arpreq r;
1230     struct sockaddr_in *pa;
1231     int retval;
1232
1233     memset(&r, 0, sizeof r);
1234     pa = (struct sockaddr_in *) &r.arp_pa;
1235     pa->sin_family = AF_INET;
1236     pa->sin_addr.s_addr = ip;
1237     pa->sin_port = 0;
1238     r.arp_ha.sa_family = ARPHRD_ETHER;
1239     r.arp_flags = 0;
1240     strncpy(r.arp_dev, netdev->name, sizeof r.arp_dev);
1241     COVERAGE_INC(netdev_arp_lookup);
1242     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
1243     if (!retval) {
1244         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
1245     } else if (retval != ENXIO) {
1246         VLOG_WARN_RL(&rl, "%s: could not look up ARP entry for "IP_FMT": %s",
1247                      netdev->name, IP_ARGS(&ip), strerror(retval));
1248     }
1249     return retval;
1250 }
1251
1252 static int
1253 nd_to_iff_flags(enum netdev_flags nd)
1254 {
1255     int iff = 0;
1256     if (nd & NETDEV_UP) {
1257         iff |= IFF_UP;
1258     }
1259     if (nd & NETDEV_PROMISC) {
1260         iff |= IFF_PROMISC;
1261     }
1262     return iff;
1263 }
1264
1265 static int
1266 iff_to_nd_flags(int iff)
1267 {
1268     enum netdev_flags nd = 0;
1269     if (iff & IFF_UP) {
1270         nd |= NETDEV_UP;
1271     }
1272     if (iff & IFF_PROMISC) {
1273         nd |= NETDEV_PROMISC;
1274     }
1275     return nd;
1276 }
1277
1278 static int
1279 netdev_linux_update_flags(struct netdev *netdev, enum netdev_flags off,
1280                           enum netdev_flags on, enum netdev_flags *old_flagsp)
1281 {
1282     int old_flags, new_flags;
1283     int error;
1284
1285     error = get_flags(netdev, &old_flags);
1286     if (!error) {
1287         *old_flagsp = iff_to_nd_flags(old_flags);
1288         new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
1289         if (new_flags != old_flags) {
1290             error = set_flags(netdev, new_flags);
1291         }
1292     }
1293     return error;
1294 }
1295
1296 static void
1297 poll_notify(struct list *list)
1298 {
1299     struct netdev_linux_notifier *notifier;
1300     LIST_FOR_EACH (notifier, struct netdev_linux_notifier, node, list) {
1301         struct netdev_notifier *n = &notifier->notifier;
1302         n->cb(n);
1303     }
1304 }
1305
1306 static void
1307 netdev_linux_poll_cb(const struct rtnetlink_change *change,
1308                      void *aux UNUSED)
1309 {
1310     if (change) {
1311         struct list *list = shash_find_data(&netdev_linux_notifiers,
1312                                             change->ifname);
1313         if (list) {
1314             poll_notify(list);
1315         }
1316     } else {
1317         struct shash_node *node;
1318         SHASH_FOR_EACH (node, &netdev_linux_notifiers) {
1319             poll_notify(node->data);
1320         }
1321     }
1322 }
1323
1324 static int
1325 netdev_linux_poll_add(struct netdev *netdev,
1326                       void (*cb)(struct netdev_notifier *), void *aux,
1327                       struct netdev_notifier **notifierp)
1328 {
1329     const char *netdev_name = netdev_get_name(netdev);
1330     struct netdev_linux_notifier *notifier;
1331     struct list *list;
1332
1333     if (shash_is_empty(&netdev_linux_notifiers)) {
1334         int error = rtnetlink_notifier_register(&netdev_linux_poll_notifier,
1335                                                    netdev_linux_poll_cb, NULL);
1336         if (error) {
1337             return error;
1338         }
1339     }
1340
1341     list = shash_find_data(&netdev_linux_notifiers, netdev_name);
1342     if (!list) {
1343         list = xmalloc(sizeof *list);
1344         list_init(list);
1345         shash_add(&netdev_linux_notifiers, netdev_name, list);
1346     }
1347
1348     notifier = xmalloc(sizeof *notifier);
1349     netdev_notifier_init(&notifier->notifier, netdev, cb, aux);
1350     list_push_back(list, &notifier->node);
1351     *notifierp = &notifier->notifier;
1352     return 0;
1353 }
1354
1355 static void
1356 netdev_linux_poll_remove(struct netdev_notifier *notifier_)
1357 {
1358     struct netdev_linux_notifier *notifier =
1359         CONTAINER_OF(notifier_, struct netdev_linux_notifier, notifier);
1360     struct list *list;
1361
1362     /* Remove 'notifier' from its list. */
1363     list = list_remove(&notifier->node);
1364     if (list_is_empty(list)) {
1365         /* The list is now empty.  Remove it from the hash and free it. */
1366         const char *netdev_name = netdev_get_name(notifier->notifier.netdev);
1367         shash_delete(&netdev_linux_notifiers,
1368                      shash_find(&netdev_linux_notifiers, netdev_name));
1369         free(list);
1370     }
1371     free(notifier);
1372
1373     /* If that was the last notifier, unregister. */
1374     if (shash_is_empty(&netdev_linux_notifiers)) {
1375         rtnetlink_notifier_unregister(&netdev_linux_poll_notifier);
1376     }
1377 }
1378
1379 const struct netdev_class netdev_linux_class = {
1380     "",                         /* prefix */
1381     "linux",                    /* name */
1382
1383     netdev_linux_init,
1384     netdev_linux_run,
1385     netdev_linux_wait,
1386
1387     netdev_linux_open,
1388     netdev_linux_close,
1389
1390     netdev_linux_enumerate,
1391
1392     netdev_linux_recv,
1393     netdev_linux_recv_wait,
1394     netdev_linux_drain,
1395
1396     netdev_linux_send,
1397     netdev_linux_send_wait,
1398
1399     netdev_linux_set_etheraddr,
1400     netdev_linux_get_etheraddr,
1401     netdev_linux_get_mtu,
1402     netdev_linux_get_ifindex,
1403     netdev_linux_get_carrier,
1404     netdev_linux_get_stats,
1405
1406     netdev_linux_get_features,
1407     netdev_linux_set_advertisements,
1408     netdev_linux_get_vlan_vid,
1409     netdev_linux_set_policing,
1410
1411     netdev_linux_get_in4,
1412     netdev_linux_set_in4,
1413     netdev_linux_get_in6,
1414     netdev_linux_add_router,
1415     netdev_linux_get_next_hop,
1416     netdev_linux_arp_lookup,
1417
1418     netdev_linux_update_flags,
1419
1420     netdev_linux_poll_add,
1421     netdev_linux_poll_remove,
1422 };
1423
1424 const struct netdev_class netdev_tap_class = {
1425     "tap",                      /* prefix */
1426     "tap",                      /* name */
1427
1428     netdev_linux_init,
1429     NULL,                       /* run */
1430     NULL,                       /* wait */
1431
1432     netdev_linux_open,
1433     netdev_linux_close,
1434
1435     netdev_linux_enumerate,
1436
1437     netdev_linux_recv,
1438     netdev_linux_recv_wait,
1439     netdev_linux_drain,
1440
1441     netdev_linux_send,
1442     netdev_linux_send_wait,
1443
1444     netdev_linux_set_etheraddr,
1445     netdev_linux_get_etheraddr,
1446     netdev_linux_get_mtu,
1447     netdev_linux_get_ifindex,
1448     netdev_linux_get_carrier,
1449     netdev_linux_get_stats,
1450
1451     netdev_linux_get_features,
1452     netdev_linux_set_advertisements,
1453     netdev_linux_get_vlan_vid,
1454     netdev_linux_set_policing,
1455
1456     netdev_linux_get_in4,
1457     netdev_linux_set_in4,
1458     netdev_linux_get_in6,
1459     netdev_linux_add_router,
1460     netdev_linux_get_next_hop,
1461     netdev_linux_arp_lookup,
1462
1463     netdev_linux_update_flags,
1464
1465     netdev_linux_poll_add,
1466     netdev_linux_poll_remove,
1467 };
1468 \f
1469 static int
1470 get_stats_via_netlink(int ifindex, struct netdev_stats *stats)
1471 {
1472     /* Policy for RTNLGRP_LINK messages.
1473      *
1474      * There are *many* more fields in these messages, but currently we only
1475      * care about these fields. */
1476     static const struct nl_policy rtnlgrp_link_policy[] = {
1477         [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
1478         [IFLA_STATS] = { .type = NL_A_UNSPEC, .optional = true,
1479                          .min_len = sizeof(struct rtnl_link_stats) },
1480     };
1481
1482
1483     static struct nl_sock *rtnl_sock;
1484     struct ofpbuf request;
1485     struct ofpbuf *reply;
1486     struct ifinfomsg *ifi;
1487     const struct rtnl_link_stats *rtnl_stats;
1488     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
1489     int error;
1490
1491     if (!rtnl_sock) {
1492         error = nl_sock_create(NETLINK_ROUTE, 0, 0, 0, &rtnl_sock);
1493         if (error) {
1494             VLOG_ERR_RL(&rl, "failed to create rtnetlink socket: %s",
1495                         strerror(error));
1496             return error;
1497         }
1498     }
1499
1500     ofpbuf_init(&request, 0);
1501     nl_msg_put_nlmsghdr(&request, rtnl_sock, sizeof *ifi,
1502                         RTM_GETLINK, NLM_F_REQUEST);
1503     ifi = ofpbuf_put_zeros(&request, sizeof *ifi);
1504     ifi->ifi_family = PF_UNSPEC;
1505     ifi->ifi_index = ifindex;
1506     error = nl_sock_transact(rtnl_sock, &request, &reply);
1507     ofpbuf_uninit(&request);
1508     if (error) {
1509         return error;
1510     }
1511
1512     if (!nl_policy_parse(reply, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
1513                          rtnlgrp_link_policy,
1514                          attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
1515         ofpbuf_delete(reply);
1516         return EPROTO;
1517     }
1518
1519     if (!attrs[IFLA_STATS]) {
1520         VLOG_WARN_RL(&rl, "RTM_GETLINK reply lacks stats");
1521         ofpbuf_delete(reply);
1522         return EPROTO;
1523     }
1524
1525     rtnl_stats = nl_attr_get(attrs[IFLA_STATS]);
1526     stats->rx_packets = rtnl_stats->rx_packets;
1527     stats->tx_packets = rtnl_stats->tx_packets;
1528     stats->rx_bytes = rtnl_stats->rx_bytes;
1529     stats->tx_bytes = rtnl_stats->tx_bytes;
1530     stats->rx_errors = rtnl_stats->rx_errors;
1531     stats->tx_errors = rtnl_stats->tx_errors;
1532     stats->rx_dropped = rtnl_stats->rx_dropped;
1533     stats->tx_dropped = rtnl_stats->tx_dropped;
1534     stats->multicast = rtnl_stats->multicast;
1535     stats->collisions = rtnl_stats->collisions;
1536     stats->rx_length_errors = rtnl_stats->rx_length_errors;
1537     stats->rx_over_errors = rtnl_stats->rx_over_errors;
1538     stats->rx_crc_errors = rtnl_stats->rx_crc_errors;
1539     stats->rx_frame_errors = rtnl_stats->rx_frame_errors;
1540     stats->rx_fifo_errors = rtnl_stats->rx_fifo_errors;
1541     stats->rx_missed_errors = rtnl_stats->rx_missed_errors;
1542     stats->tx_aborted_errors = rtnl_stats->tx_aborted_errors;
1543     stats->tx_carrier_errors = rtnl_stats->tx_carrier_errors;
1544     stats->tx_fifo_errors = rtnl_stats->tx_fifo_errors;
1545     stats->tx_heartbeat_errors = rtnl_stats->tx_heartbeat_errors;
1546     stats->tx_window_errors = rtnl_stats->tx_window_errors;
1547
1548     ofpbuf_delete(reply);
1549
1550     return 0;
1551 }
1552
1553 static int
1554 get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats)
1555 {
1556     static const char fn[] = "/proc/net/dev";
1557     char line[1024];
1558     FILE *stream;
1559     int ln;
1560
1561     stream = fopen(fn, "r");
1562     if (!stream) {
1563         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1564         return errno;
1565     }
1566
1567     ln = 0;
1568     while (fgets(line, sizeof line, stream)) {
1569         if (++ln >= 3) {
1570             char devname[16];
1571 #define X64 "%"SCNu64
1572             if (sscanf(line,
1573                        " %15[^:]:"
1574                        X64 X64 X64 X64 X64 X64 X64 "%*u"
1575                        X64 X64 X64 X64 X64 X64 X64 "%*u",
1576                        devname,
1577                        &stats->rx_bytes,
1578                        &stats->rx_packets,
1579                        &stats->rx_errors,
1580                        &stats->rx_dropped,
1581                        &stats->rx_fifo_errors,
1582                        &stats->rx_frame_errors,
1583                        &stats->multicast,
1584                        &stats->tx_bytes,
1585                        &stats->tx_packets,
1586                        &stats->tx_errors,
1587                        &stats->tx_dropped,
1588                        &stats->tx_fifo_errors,
1589                        &stats->collisions,
1590                        &stats->tx_carrier_errors) != 15) {
1591                 VLOG_WARN_RL(&rl, "%s:%d: parse error", fn, ln);
1592             } else if (!strcmp(devname, netdev_name)) {
1593                 stats->rx_length_errors = UINT64_MAX;
1594                 stats->rx_over_errors = UINT64_MAX;
1595                 stats->rx_crc_errors = UINT64_MAX;
1596                 stats->rx_missed_errors = UINT64_MAX;
1597                 stats->tx_aborted_errors = UINT64_MAX;
1598                 stats->tx_heartbeat_errors = UINT64_MAX;
1599                 stats->tx_window_errors = UINT64_MAX;
1600                 fclose(stream);
1601                 return 0;
1602             }
1603         }
1604     }
1605     VLOG_WARN_RL(&rl, "%s: no stats for %s", fn, netdev_name);
1606     fclose(stream);
1607     return ENODEV;
1608 }
1609 \f
1610 static int
1611 get_flags(const struct netdev *netdev, int *flags)
1612 {
1613     struct ifreq ifr;
1614     int error;
1615
1616     error = netdev_linux_do_ioctl(netdev, &ifr, SIOCGIFFLAGS, "SIOCGIFFLAGS");
1617     *flags = ifr.ifr_flags;
1618     return error;
1619 }
1620
1621 static int
1622 set_flags(struct netdev *netdev, int flags)
1623 {
1624     struct ifreq ifr;
1625
1626     ifr.ifr_flags = flags;
1627     return netdev_linux_do_ioctl(netdev, &ifr, SIOCSIFFLAGS, "SIOCSIFFLAGS");
1628 }
1629
1630 static int
1631 do_get_ifindex(const char *netdev_name)
1632 {
1633     struct ifreq ifr;
1634
1635     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1636     COVERAGE_INC(netdev_get_ifindex);
1637     if (ioctl(af_inet_sock, SIOCGIFINDEX, &ifr) < 0) {
1638         VLOG_WARN_RL(&rl, "ioctl(SIOCGIFINDEX) on %s device failed: %s",
1639                      netdev_name, strerror(errno));
1640         return -errno;
1641     }
1642     return ifr.ifr_ifindex;
1643 }
1644
1645 static int
1646 get_ifindex(const struct netdev *netdev_, int *ifindexp)
1647 {
1648     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
1649     *ifindexp = 0;
1650     if (!(netdev->cache->valid & VALID_IFINDEX)) {
1651         int ifindex = do_get_ifindex(netdev_get_name(netdev_));
1652         if (ifindex < 0) {
1653             return -ifindex;
1654         }
1655         netdev->cache->valid |= VALID_IFINDEX;
1656         netdev->cache->ifindex = ifindex;
1657     }
1658     *ifindexp = netdev->cache->ifindex;
1659     return 0;
1660 }
1661
1662 static int
1663 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
1664 {
1665     struct ifreq ifr;
1666     int hwaddr_family;
1667
1668     memset(&ifr, 0, sizeof ifr);
1669     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1670     COVERAGE_INC(netdev_get_hwaddr);
1671     if (ioctl(af_inet_sock, SIOCGIFHWADDR, &ifr) < 0) {
1672         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
1673                  netdev_name, strerror(errno));
1674         return errno;
1675     }
1676     hwaddr_family = ifr.ifr_hwaddr.sa_family;
1677     if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
1678         VLOG_WARN("%s device has unknown hardware address family %d",
1679                   netdev_name, hwaddr_family);
1680     }
1681     memcpy(ea, ifr.ifr_hwaddr.sa_data, ETH_ADDR_LEN);
1682     return 0;
1683 }
1684
1685 static int
1686 set_etheraddr(const char *netdev_name, int hwaddr_family,
1687               const uint8_t mac[ETH_ADDR_LEN])
1688 {
1689     struct ifreq ifr;
1690
1691     memset(&ifr, 0, sizeof ifr);
1692     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
1693     ifr.ifr_hwaddr.sa_family = hwaddr_family;
1694     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
1695     COVERAGE_INC(netdev_set_hwaddr);
1696     if (ioctl(af_inet_sock, SIOCSIFHWADDR, &ifr) < 0) {
1697         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
1698                  netdev_name, strerror(errno));
1699         return errno;
1700     }
1701     return 0;
1702 }
1703
1704 static int
1705 netdev_linux_do_ethtool(struct netdev *netdev, struct ethtool_cmd *ecmd,
1706                         int cmd, const char *cmd_name)
1707 {
1708     struct ifreq ifr;
1709
1710     memset(&ifr, 0, sizeof ifr);
1711     strncpy(ifr.ifr_name, netdev->name, sizeof ifr.ifr_name);
1712     ifr.ifr_data = (caddr_t) ecmd;
1713
1714     ecmd->cmd = cmd;
1715     COVERAGE_INC(netdev_ethtool);
1716     if (ioctl(af_inet_sock, SIOCETHTOOL, &ifr) == 0) {
1717         return 0;
1718     } else {
1719         if (errno != EOPNOTSUPP) {
1720             VLOG_WARN_RL(&rl, "ethtool command %s on network device %s "
1721                          "failed: %s", cmd_name, netdev->name,
1722                          strerror(errno));
1723         } else {
1724             /* The device doesn't support this operation.  That's pretty
1725              * common, so there's no point in logging anything. */
1726         }
1727         return errno;
1728     }
1729 }
1730
1731 static int
1732 netdev_linux_do_ioctl(const struct netdev *netdev, struct ifreq *ifr,
1733                       int cmd, const char *cmd_name)
1734 {
1735     strncpy(ifr->ifr_name, netdev_get_name(netdev), sizeof ifr->ifr_name);
1736     if (ioctl(af_inet_sock, cmd, ifr) == -1) {
1737         VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s",
1738                     netdev_get_name(netdev), cmd_name, strerror(errno));
1739         return errno;
1740     }
1741     return 0;
1742 }
1743
1744 static int
1745 netdev_linux_get_ipv4(const struct netdev *netdev, struct in_addr *ip,
1746                       int cmd, const char *cmd_name)
1747 {
1748     struct ifreq ifr;
1749     int error;
1750
1751     ifr.ifr_addr.sa_family = AF_INET;
1752     error = netdev_linux_do_ioctl(netdev, &ifr, cmd, cmd_name);
1753     if (!error) {
1754         const struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
1755         *ip = sin->sin_addr;
1756     }
1757     return error;
1758 }