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