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