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