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