e9fabc5b8083b067a23ae94b7405fba5e8c4fe50
[sliver-openvswitch.git] / lib / netdev-linux.c
1 /*
2  * Copyright (c) 2009, 2010 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/ip.h>
25 #include <linux/types.h>
26 #include <linux/ethtool.h>
27 #include <linux/pkt_sched.h>
28 #include <linux/rtnetlink.h>
29 #include <linux/sockios.h>
30 #include <linux/version.h>
31 #include <sys/types.h>
32 #include <sys/ioctl.h>
33 #include <sys/socket.h>
34 #include <netpacket/packet.h>
35 #include <net/ethernet.h>
36 #include <net/if.h>
37 #include <linux/if_tunnel.h>
38 #include <net/if_arp.h>
39 #include <net/if_packet.h>
40 #include <net/route.h>
41 #include <netinet/in.h>
42 #include <poll.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46
47 #include "coverage.h"
48 #include "dynamic-string.h"
49 #include "fatal-signal.h"
50 #include "netdev-provider.h"
51 #include "netlink.h"
52 #include "ofpbuf.h"
53 #include "openflow/openflow.h"
54 #include "openvswitch/internal_dev.h"
55 #include "openvswitch/gre.h"
56 #include "packets.h"
57 #include "poll-loop.h"
58 #include "rtnetlink.h"
59 #include "socket-util.h"
60 #include "shash.h"
61 #include "svec.h"
62
63 #define THIS_MODULE VLM_netdev_linux
64 #include "vlog.h"
65 \f
66 /* These were introduced in Linux 2.6.14, so they might be missing if we have
67  * old headers. */
68 #ifndef ADVERTISED_Pause
69 #define ADVERTISED_Pause                (1 << 13)
70 #endif
71 #ifndef ADVERTISED_Asym_Pause
72 #define ADVERTISED_Asym_Pause           (1 << 14)
73 #endif
74
75 static struct rtnetlink_notifier netdev_linux_cache_notifier;
76 static int cache_notifier_refcount;
77
78 enum {
79     VALID_IFINDEX = 1 << 0,
80     VALID_ETHERADDR = 1 << 1,
81     VALID_IN4 = 1 << 2,
82     VALID_IN6 = 1 << 3,
83     VALID_MTU = 1 << 4,
84     VALID_CARRIER = 1 << 5,
85     VALID_IS_PSEUDO = 1 << 6,       /* Represents is_internal and is_tap. */
86     VALID_POLICING = 1 << 7
87 };
88
89 struct tap_state {
90     int fd;
91 };
92
93 struct patch_state {
94     char *peer;
95 };
96
97 struct netdev_dev_linux {
98     struct netdev_dev netdev_dev;
99
100     struct shash_node *shash_node;
101     unsigned int cache_valid;
102
103     /* The following are figured out "on demand" only.  They are only valid
104      * when the corresponding VALID_* bit in 'cache_valid' is set. */
105     int ifindex;
106     uint8_t etheraddr[ETH_ADDR_LEN];
107     struct in_addr address, netmask;
108     struct in6_addr in6;
109     int mtu;
110     int carrier;
111     bool is_internal;           /* Is this an openvswitch internal device? */
112     bool is_tap;                /* Is this a tuntap device? */
113     uint32_t kbits_rate;        /* Policing data. */
114     uint32_t kbits_burst;
115
116     union {
117         struct tap_state tap;
118         struct patch_state patch;
119     } state;
120 };
121
122 struct netdev_linux {
123     struct netdev netdev;
124     int fd;
125 };
126
127 /* An AF_INET socket (used for ioctl operations). */
128 static int af_inet_sock = -1;
129
130 struct netdev_linux_notifier {
131     struct netdev_notifier notifier;
132     struct list node;
133 };
134
135 static struct shash netdev_linux_notifiers =
136     SHASH_INITIALIZER(&netdev_linux_notifiers);
137 static struct rtnetlink_notifier netdev_linux_poll_notifier;
138
139 /* This is set pretty low because we probably won't learn anything from the
140  * additional log messages. */
141 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
142
143 static int netdev_linux_init(void);
144
145 static int netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *,
146                                    int cmd, const char *cmd_name);
147 static int netdev_linux_do_ioctl(const char *name, struct ifreq *, int cmd,
148                                  const char *cmd_name);
149 static int netdev_linux_get_ipv4(const struct netdev *, struct in_addr *,
150                                  int cmd, const char *cmd_name);
151 static int get_flags(const struct netdev *, int *flagsp);
152 static int set_flags(struct netdev *, int flags);
153 static int do_get_ifindex(const char *netdev_name);
154 static int get_ifindex(const struct netdev *, int *ifindexp);
155 static int do_set_addr(struct netdev *netdev,
156                        int ioctl_nr, const char *ioctl_name,
157                        struct in_addr addr);
158 static int get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN]);
159 static int set_etheraddr(const char *netdev_name, int hwaddr_family,
160                          const uint8_t[ETH_ADDR_LEN]);
161 static int get_stats_via_netlink(int ifindex, struct netdev_stats *stats);
162 static int get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats);
163 static int get_rtnl_sock(struct nl_sock **);
164
165 static bool
166 is_netdev_linux_class(const struct netdev_class *netdev_class)
167 {
168     return netdev_class->init == netdev_linux_init;
169 }
170
171 static struct netdev_dev_linux *
172 netdev_dev_linux_cast(const struct netdev_dev *netdev_dev)
173 {
174     const struct netdev_class *netdev_class = netdev_dev_get_class(netdev_dev);
175     assert(is_netdev_linux_class(netdev_class));
176
177     return CONTAINER_OF(netdev_dev, struct netdev_dev_linux, netdev_dev);
178 }
179
180 static struct netdev_linux *
181 netdev_linux_cast(const struct netdev *netdev)
182 {
183     struct netdev_dev *netdev_dev = netdev_get_dev(netdev);
184     const struct netdev_class *netdev_class = netdev_dev_get_class(netdev_dev);
185     assert(is_netdev_linux_class(netdev_class));
186
187     return CONTAINER_OF(netdev, struct netdev_linux, netdev);
188 }
189
190 static int
191 netdev_linux_init(void)
192 {
193     static int status = -1;
194     if (status < 0) {
195         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
196         status = af_inet_sock >= 0 ? 0 : errno;
197         if (status) {
198             VLOG_ERR("failed to create inet socket: %s", strerror(status));
199         }
200     }
201     return status;
202 }
203
204 static void
205 netdev_linux_run(void)
206 {
207     rtnetlink_notifier_run();
208 }
209
210 static void
211 netdev_linux_wait(void)
212 {
213     rtnetlink_notifier_wait();
214 }
215
216 static void
217 netdev_linux_cache_cb(const struct rtnetlink_change *change,
218                       void *aux OVS_UNUSED)
219 {
220     struct netdev_dev_linux *dev;
221     if (change) {
222         struct netdev_dev *base_dev = netdev_dev_from_name(change->ifname);
223         if (base_dev) {
224             const struct netdev_class *netdev_class =
225                                                 netdev_dev_get_class(base_dev);
226
227             if (is_netdev_linux_class(netdev_class)) {
228                 dev = netdev_dev_linux_cast(base_dev);
229                 dev->cache_valid = 0;
230             }
231         }
232     } else {
233         struct shash device_shash;
234         struct shash_node *node;
235
236         shash_init(&device_shash);
237         netdev_dev_get_devices(&netdev_linux_class, &device_shash);
238         SHASH_FOR_EACH (node, &device_shash) {
239             dev = node->data;
240             dev->cache_valid = 0;
241         }
242         shash_destroy(&device_shash);
243     }
244 }
245
246 static int
247 if_up(const char *name)
248 {
249     struct ifreq ifr;
250
251     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
252     ifr.ifr_flags = IFF_UP;
253
254     if (ioctl(af_inet_sock, SIOCSIFFLAGS, &ifr) == -1) {
255         VLOG_DBG_RL(&rl, "%s: failed to bring device up: %s",
256                     name, strerror(errno));
257         return errno;
258     }
259
260     return 0;
261 }
262
263 /* A veth may be created using the 'command' "+<name>,<peer>". A veth may 
264  * be destroyed by using the 'command' "-<name>", where <name> can be 
265  * either side of the device.
266  */
267 static int
268 modify_veth(const char *format, ...)
269 {
270     FILE *veth_file;
271     va_list args;
272     int retval;
273
274     veth_file = fopen("/sys/class/net/veth_pairs", "w");
275     if (!veth_file) {
276         VLOG_WARN_RL(&rl, "could not open veth device.  Are you running a "
277                 "supported XenServer with the kernel module loaded?");
278         return ENODEV;
279     }
280     setvbuf(veth_file, NULL, _IONBF, 0);
281
282     va_start(args, format);
283     retval = vfprintf(veth_file, format, args);
284     va_end(args);
285
286     fclose(veth_file);
287     if (retval < 0) {
288         VLOG_WARN_RL(&rl, "could not destroy patch: %s", strerror(errno));
289         return errno;
290     }
291
292     return 0;
293 }
294
295 static int
296 create_patch(const char *name, const char *peer)
297 {
298     int retval;
299     struct netdev_dev *peer_nd;
300
301
302     /* Only create the veth if the peer didn't already do it. */
303     peer_nd = netdev_dev_from_name(peer);
304     if (peer_nd) {
305         if (!strcmp("patch", netdev_dev_get_type(peer_nd))) {
306             struct netdev_dev_linux *ndl = netdev_dev_linux_cast(peer_nd);
307             if (!strcmp(name, ndl->state.patch.peer)) {
308                 return 0;
309             } else {
310                 VLOG_WARN_RL(&rl, "peer '%s' already paired with '%s'", 
311                         peer, ndl->state.patch.peer);
312                 return EINVAL;
313             }
314         } else {
315             VLOG_WARN_RL(&rl, "peer '%s' exists and is not a patch", peer);
316             return EINVAL;
317         }
318     }
319
320     retval = modify_veth("+%s,%s", name, peer);
321     if (retval) {
322         return retval;
323     }
324
325     retval = if_up(name);
326     if (retval) {
327         return retval;
328     }
329
330     retval = if_up(peer);
331     if (retval) {
332         return retval;
333     }
334
335     return 0;
336 }
337
338 static int
339 setup_patch(const char *name, const struct shash *args, char **peer_)
340 {
341     const char *peer;
342
343     peer = shash_find_data(args, "peer");
344     if (!peer) {
345         VLOG_WARN("patch type requires valid 'peer' argument");
346         return EINVAL;
347     }
348
349     if (shash_count(args) > 1) {
350         VLOG_WARN("patch type takes only a 'peer' argument");
351         return EINVAL;
352     }
353
354     if (strlen(peer) >= IFNAMSIZ) {
355         VLOG_WARN_RL(&rl, "patch 'peer' arg too long");
356         return EINVAL;
357     }
358
359     *peer_ = xstrdup(peer);
360     return create_patch(name, peer);
361 }
362
363 /* Creates the netdev device of 'type' with 'name'. */
364 static int
365 netdev_linux_create_system(const char *name, const char *type OVS_UNUSED,
366                     const struct shash *args, struct netdev_dev **netdev_devp)
367 {
368     struct netdev_dev_linux *netdev_dev;
369     int error;
370
371     if (!shash_is_empty(args)) {
372         VLOG_WARN("%s: arguments for system devices should be empty", name);
373     }
374
375     if (!cache_notifier_refcount) {
376         error = rtnetlink_notifier_register(&netdev_linux_cache_notifier,
377                                             netdev_linux_cache_cb, NULL);
378         if (error) {
379             return error;
380         }
381     }
382     cache_notifier_refcount++;
383
384     netdev_dev = xzalloc(sizeof *netdev_dev);
385     netdev_dev_init(&netdev_dev->netdev_dev, name, &netdev_linux_class);
386
387     *netdev_devp = &netdev_dev->netdev_dev;
388     return 0;
389 }
390
391 /* For most types of netdevs we open the device for each call of
392  * netdev_open().  However, this is not the case with tap devices,
393  * since it is only possible to open the device once.  In this
394  * situation we share a single file descriptor, and consequently
395  * buffers, across all readers.  Therefore once data is read it will
396  * be unavailable to other reads for tap devices. */
397 static int
398 netdev_linux_create_tap(const char *name, const char *type OVS_UNUSED,
399                     const struct shash *args, struct netdev_dev **netdev_devp)
400 {
401     struct netdev_dev_linux *netdev_dev;
402     struct tap_state *state;
403     static const char tap_dev[] = "/dev/net/tun";
404     struct ifreq ifr;
405     int error;
406
407     if (!shash_is_empty(args)) {
408         VLOG_WARN("%s: arguments for TAP devices should be empty", name);
409     }
410
411     netdev_dev = xzalloc(sizeof *netdev_dev);
412     state = &netdev_dev->state.tap;
413
414     /* Open tap device. */
415     state->fd = open(tap_dev, O_RDWR);
416     if (state->fd < 0) {
417         error = errno;
418         VLOG_WARN("opening \"%s\" failed: %s", tap_dev, strerror(error));
419         goto error;
420     }
421
422     /* Create tap device. */
423     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
424     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
425     if (ioctl(state->fd, TUNSETIFF, &ifr) == -1) {
426         VLOG_WARN("%s: creating tap device failed: %s", name,
427                   strerror(errno));
428         error = errno;
429         goto error;
430     }
431
432     /* Make non-blocking. */
433     error = set_nonblocking(state->fd);
434     if (error) {
435         goto error;
436     }
437
438     netdev_dev_init(&netdev_dev->netdev_dev, name, &netdev_tap_class);
439     *netdev_devp = &netdev_dev->netdev_dev;
440     return 0;
441
442 error:
443     free(netdev_dev);
444     return error;
445 }
446
447 static int
448 netdev_linux_create_patch(const char *name, const char *type OVS_UNUSED,
449                     const struct shash *args, struct netdev_dev **netdev_devp)
450 {
451     struct netdev_dev_linux *netdev_dev;
452     char *peer = NULL;
453     int error;
454
455     error = setup_patch(name, args, &peer);
456     if (error) {
457         free(peer);
458         return error;
459     }
460
461     netdev_dev = xzalloc(sizeof *netdev_dev);
462     netdev_dev->state.patch.peer = peer;
463     netdev_dev_init(&netdev_dev->netdev_dev, name, &netdev_patch_class);
464     *netdev_devp = &netdev_dev->netdev_dev;
465
466     return 0;
467 }
468
469 static void
470 destroy_tap(struct netdev_dev_linux *netdev_dev)
471 {
472     struct tap_state *state = &netdev_dev->state.tap;
473
474     if (state->fd >= 0) {
475         close(state->fd);
476     }
477 }
478
479 static void
480 destroy_patch(struct netdev_dev_linux *netdev_dev)
481 {
482     const char *name = netdev_dev_get_name(&netdev_dev->netdev_dev);
483     struct patch_state *state = &netdev_dev->state.patch;
484
485     /* Only destroy veth if 'peer' doesn't exist as an existing netdev. */
486     if (!netdev_dev_from_name(state->peer)) {
487         modify_veth("-%s", name);
488     }
489     free(state->peer);
490 }
491
492 /* Destroys the netdev device 'netdev_dev_'. */
493 static void
494 netdev_linux_destroy(struct netdev_dev *netdev_dev_)
495 {
496     struct netdev_dev_linux *netdev_dev = netdev_dev_linux_cast(netdev_dev_);
497     const char *type = netdev_dev_get_type(netdev_dev_);
498
499     if (!strcmp(type, "system")) {
500         cache_notifier_refcount--;
501
502         if (!cache_notifier_refcount) {
503             rtnetlink_notifier_unregister(&netdev_linux_cache_notifier);
504         }
505     } else if (!strcmp(type, "tap")) {
506         destroy_tap(netdev_dev);
507     } else if (!strcmp(type, "patch")) {
508         destroy_patch(netdev_dev);
509     }
510
511     free(netdev_dev);
512 }
513
514 static int
515 netdev_linux_open(struct netdev_dev *netdev_dev_, int ethertype,
516                   struct netdev **netdevp)
517 {
518     struct netdev_dev_linux *netdev_dev = netdev_dev_linux_cast(netdev_dev_);
519     struct netdev_linux *netdev;
520     enum netdev_flags flags;
521     int error;
522
523     /* Allocate network device. */
524     netdev = xzalloc(sizeof *netdev);
525     netdev->fd = -1;
526     netdev_init(&netdev->netdev, netdev_dev_);
527
528     error = netdev_get_flags(&netdev->netdev, &flags);
529     if (error == ENODEV) {
530         goto error;
531     }
532
533     if (!strcmp(netdev_dev_get_type(netdev_dev_), "tap")) {
534         netdev->fd = netdev_dev->state.tap.fd;
535     } else if (ethertype != NETDEV_ETH_TYPE_NONE) {
536         struct sockaddr_ll sll;
537         int protocol;
538         int ifindex;
539
540         /* Create file descriptor. */
541         protocol = (ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
542                     : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
543                     : ethertype);
544         netdev->fd = socket(PF_PACKET, SOCK_RAW, htons(protocol));
545         if (netdev->fd < 0) {
546             error = errno;
547             goto error;
548         }
549
550         /* Set non-blocking mode. */
551         error = set_nonblocking(netdev->fd);
552         if (error) {
553             goto error;
554         }
555
556         /* Get ethernet device index. */
557         error = get_ifindex(&netdev->netdev, &ifindex);
558         if (error) {
559             goto error;
560         }
561
562         /* Bind to specific ethernet device. */
563         memset(&sll, 0, sizeof sll);
564         sll.sll_family = AF_PACKET;
565         sll.sll_ifindex = ifindex;
566         if (bind(netdev->fd,
567                  (struct sockaddr *) &sll, sizeof sll) < 0) {
568             error = errno;
569             VLOG_ERR("bind to %s failed: %s", netdev_dev_get_name(netdev_dev_),
570                      strerror(error));
571             goto error;
572         }
573
574         /* Between the socket() and bind() calls above, the socket receives all
575          * packets of the requested type on all system interfaces.  We do not
576          * want to receive that data, but there is no way to avoid it.  So we
577          * must now drain out the receive queue. */
578         error = drain_rcvbuf(netdev->fd);
579         if (error) {
580             goto error;
581         }
582     }
583
584     *netdevp = &netdev->netdev;
585     return 0;
586
587 error:
588     netdev_uninit(&netdev->netdev, true);
589     return error;
590 }
591
592 /* Closes and destroys 'netdev'. */
593 static void
594 netdev_linux_close(struct netdev *netdev_)
595 {
596     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
597
598     if (netdev->fd > 0 && strcmp(netdev_get_type(netdev_), "tap")) {
599         close(netdev->fd);
600     }
601     free(netdev);
602 }
603
604 /* Initializes 'svec' with a list of the names of all known network devices. */
605 static int
606 netdev_linux_enumerate(struct svec *svec)
607 {
608     struct if_nameindex *names;
609
610     names = if_nameindex();
611     if (names) {
612         size_t i;
613
614         for (i = 0; names[i].if_name != NULL; i++) {
615             svec_add(svec, names[i].if_name);
616         }
617         if_freenameindex(names);
618         return 0;
619     } else {
620         VLOG_WARN("could not obtain list of network device names: %s",
621                   strerror(errno));
622         return errno;
623     }
624 }
625
626 static int
627 netdev_linux_recv(struct netdev *netdev_, void *data, size_t size)
628 {
629     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
630
631     if (netdev->fd < 0) {
632         /* Device was opened with NETDEV_ETH_TYPE_NONE. */
633         return -EAGAIN;
634     }
635
636     for (;;) {
637         ssize_t retval = read(netdev->fd, data, size);
638         if (retval >= 0) {
639             return retval;
640         } else if (errno != EINTR) {
641             if (errno != EAGAIN) {
642                 VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
643                              strerror(errno), netdev_get_name(netdev_));
644             }
645             return -errno;
646         }
647     }
648 }
649
650 /* Registers with the poll loop to wake up from the next call to poll_block()
651  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
652 static void
653 netdev_linux_recv_wait(struct netdev *netdev_)
654 {
655     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
656     if (netdev->fd >= 0) {
657         poll_fd_wait(netdev->fd, POLLIN);
658     }
659 }
660
661 /* Discards all packets waiting to be received from 'netdev'. */
662 static int
663 netdev_linux_drain(struct netdev *netdev_)
664 {
665     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
666     if (netdev->fd < 0) {
667         return 0;
668     } else if (!strcmp(netdev_get_type(netdev_), "tap")) {
669         struct ifreq ifr;
670         int error = netdev_linux_do_ioctl(netdev_get_name(netdev_), &ifr,
671                                           SIOCGIFTXQLEN, "SIOCGIFTXQLEN");
672         if (error) {
673             return error;
674         }
675         drain_fd(netdev->fd, ifr.ifr_qlen);
676         return 0;
677     } else {
678         return drain_rcvbuf(netdev->fd);
679     }
680 }
681
682 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
683  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
684  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
685  * the packet is too big or too small to transmit on the device.
686  *
687  * The caller retains ownership of 'buffer' in all cases.
688  *
689  * The kernel maintains a packet transmission queue, so the caller is not
690  * expected to do additional queuing of packets. */
691 static int
692 netdev_linux_send(struct netdev *netdev_, const void *data, size_t size)
693 {
694     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
695
696     /* XXX should support sending even if 'ethertype' was NETDEV_ETH_TYPE_NONE.
697      */
698     if (netdev->fd < 0) {
699         return EPIPE;
700     }
701
702     for (;;) {
703         ssize_t retval = write(netdev->fd, data, size);
704         if (retval < 0) {
705             /* The Linux AF_PACKET implementation never blocks waiting for room
706              * for packets, instead returning ENOBUFS.  Translate this into
707              * EAGAIN for the caller. */
708             if (errno == ENOBUFS) {
709                 return EAGAIN;
710             } else if (errno == EINTR) {
711                 continue;
712             } else if (errno != EAGAIN) {
713                 VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: %s",
714                              netdev_get_name(netdev_), strerror(errno));
715             }
716             return errno;
717         } else if (retval != size) {
718             VLOG_WARN_RL(&rl, "sent partial Ethernet packet (%zd bytes of "
719                          "%zu) on %s", retval, size, netdev_get_name(netdev_));
720             return EMSGSIZE;
721         } else {
722             return 0;
723         }
724     }
725 }
726
727 /* Registers with the poll loop to wake up from the next call to poll_block()
728  * when the packet transmission queue has sufficient room to transmit a packet
729  * with netdev_send().
730  *
731  * The kernel maintains a packet transmission queue, so the client is not
732  * expected to do additional queuing of packets.  Thus, this function is
733  * unlikely to ever be used.  It is included for completeness. */
734 static void
735 netdev_linux_send_wait(struct netdev *netdev_)
736 {
737     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
738     if (netdev->fd < 0) {
739         /* Nothing to do. */
740     } else if (strcmp(netdev_get_type(netdev_), "tap")) {
741         poll_fd_wait(netdev->fd, POLLOUT);
742     } else {
743         /* TAP device always accepts packets.*/
744         poll_immediate_wake();
745     }
746 }
747
748 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
749  * otherwise a positive errno value. */
750 static int
751 netdev_linux_set_etheraddr(struct netdev *netdev_,
752                            const uint8_t mac[ETH_ADDR_LEN])
753 {
754     struct netdev_dev_linux *netdev_dev =
755                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
756     int error;
757
758     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)
759         || !eth_addr_equals(netdev_dev->etheraddr, mac)) {
760         error = set_etheraddr(netdev_get_name(netdev_), ARPHRD_ETHER, mac);
761         if (!error) {
762             netdev_dev->cache_valid |= VALID_ETHERADDR;
763             memcpy(netdev_dev->etheraddr, mac, ETH_ADDR_LEN);
764         }
765     } else {
766         error = 0;
767     }
768     return error;
769 }
770
771 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
772  * free the returned buffer. */
773 static int
774 netdev_linux_get_etheraddr(const struct netdev *netdev_,
775                            uint8_t mac[ETH_ADDR_LEN])
776 {
777     struct netdev_dev_linux *netdev_dev =
778                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
779     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)) {
780         int error = get_etheraddr(netdev_get_name(netdev_),
781                                   netdev_dev->etheraddr);
782         if (error) {
783             return error;
784         }
785         netdev_dev->cache_valid |= VALID_ETHERADDR;
786     }
787     memcpy(mac, netdev_dev->etheraddr, ETH_ADDR_LEN);
788     return 0;
789 }
790
791 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
792  * in bytes, not including the hardware header; thus, this is typically 1500
793  * bytes for Ethernet devices. */
794 static int
795 netdev_linux_get_mtu(const struct netdev *netdev_, int *mtup)
796 {
797     struct netdev_dev_linux *netdev_dev =
798                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
799     if (!(netdev_dev->cache_valid & VALID_MTU)) {
800         struct ifreq ifr;
801         int error;
802
803         error = netdev_linux_do_ioctl(netdev_get_name(netdev_), &ifr,
804                                       SIOCGIFMTU, "SIOCGIFMTU");
805         if (error) {
806             return error;
807         }
808         netdev_dev->mtu = ifr.ifr_mtu;
809         netdev_dev->cache_valid |= VALID_MTU;
810     }
811     *mtup = netdev_dev->mtu;
812     return 0;
813 }
814
815 /* Returns the ifindex of 'netdev', if successful, as a positive number.
816  * On failure, returns a negative errno value. */
817 static int
818 netdev_linux_get_ifindex(const struct netdev *netdev)
819 {
820     int ifindex, error;
821
822     error = get_ifindex(netdev, &ifindex);
823     return error ? -error : ifindex;
824 }
825
826 static int
827 netdev_linux_get_carrier(const struct netdev *netdev_, bool *carrier)
828 {
829     struct netdev_dev_linux *netdev_dev =
830                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
831     int error = 0;
832     char *fn = NULL;
833     int fd = -1;
834
835     if (!(netdev_dev->cache_valid & VALID_CARRIER)) {
836         char line[8];
837         int retval;
838
839         fn = xasprintf("/sys/class/net/%s/carrier",
840                        netdev_get_name(netdev_));
841         fd = open(fn, O_RDONLY);
842         if (fd < 0) {
843             error = errno;
844             VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(error));
845             goto exit;
846         }
847
848         retval = read(fd, line, sizeof line);
849         if (retval < 0) {
850             error = errno;
851             if (error == EINVAL) {
852                 /* This is the normal return value when we try to check carrier
853                  * if the network device is not up. */
854             } else {
855                 VLOG_WARN_RL(&rl, "%s: read failed: %s", fn, strerror(error));
856             }
857             goto exit;
858         } else if (retval == 0) {
859             error = EPROTO;
860             VLOG_WARN_RL(&rl, "%s: unexpected end of file", fn);
861             goto exit;
862         }
863
864         if (line[0] != '0' && line[0] != '1') {
865             error = EPROTO;
866             VLOG_WARN_RL(&rl, "%s: value is %c (expected 0 or 1)",
867                          fn, line[0]);
868             goto exit;
869         }
870         netdev_dev->carrier = line[0] != '0';
871         netdev_dev->cache_valid |= VALID_CARRIER;
872     }
873     *carrier = netdev_dev->carrier;
874     error = 0;
875
876 exit:
877     if (fd >= 0) {
878         close(fd);
879     }
880     free(fn);
881     return error;
882 }
883
884 /* Check whether we can we use RTM_GETLINK to get network device statistics.
885  * In pre-2.6.19 kernels, this was only available if wireless extensions were
886  * enabled. */
887 static bool
888 check_for_working_netlink_stats(void)
889 {
890     /* Decide on the netdev_get_stats() implementation to use.  Netlink is
891      * preferable, so if that works, we'll use it. */
892     int ifindex = do_get_ifindex("lo");
893     if (ifindex < 0) {
894         VLOG_WARN("failed to get ifindex for lo, "
895                   "obtaining netdev stats from proc");
896         return false;
897     } else {
898         struct netdev_stats stats;
899         int error = get_stats_via_netlink(ifindex, &stats);
900         if (!error) {
901             VLOG_DBG("obtaining netdev stats via rtnetlink");
902             return true;
903         } else {
904             VLOG_INFO("RTM_GETLINK failed (%s), obtaining netdev stats "
905                       "via proc (you are probably running a pre-2.6.19 "
906                       "kernel)", strerror(error));
907             return false;
908         }
909     }
910 }
911
912 /* Brings the 'is_internal' and 'is_tap' members of 'netdev_dev' up-to-date. */
913 static void
914 netdev_linux_update_is_pseudo(struct netdev_dev_linux *netdev_dev)
915 {
916     if (!(netdev_dev->cache_valid & VALID_IS_PSEUDO)) {
917         const char *name = netdev_dev_get_name(&netdev_dev->netdev_dev);
918         const char *type = netdev_dev_get_type(&netdev_dev->netdev_dev);
919         
920         netdev_dev->is_tap = !strcmp(type, "tap");
921         netdev_dev->is_internal = false;
922         if (!netdev_dev->is_tap) {
923             struct ethtool_drvinfo drvinfo;
924             int error;
925
926             memset(&drvinfo, 0, sizeof drvinfo);
927             error = netdev_linux_do_ethtool(name,
928                                             (struct ethtool_cmd *)&drvinfo,
929                                             ETHTOOL_GDRVINFO,
930                                             "ETHTOOL_GDRVINFO");
931
932             if (!error && !strcmp(drvinfo.driver, "openvswitch")) {
933                 netdev_dev->is_internal = true;
934             }
935         }
936
937         netdev_dev->cache_valid |= VALID_IS_PSEUDO;
938     }
939 }
940
941 /* Retrieves current device stats for 'netdev'.
942  *
943  * XXX All of the members of struct netdev_stats are 64 bits wide, but on
944  * 32-bit architectures the Linux network stats are only 32 bits. */
945 static int
946 netdev_linux_get_stats(const struct netdev *netdev_,
947                        struct netdev_stats *stats)
948 {
949     struct netdev_dev_linux *netdev_dev =
950                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
951     static int use_netlink_stats = -1;
952     int error;
953     struct netdev_stats raw_stats;
954     struct netdev_stats *collect_stats = stats;
955
956     COVERAGE_INC(netdev_get_stats);
957
958     netdev_linux_update_is_pseudo(netdev_dev);
959     if (netdev_dev->is_internal) {
960         collect_stats = &raw_stats;
961     }
962
963     if (use_netlink_stats < 0) {
964         use_netlink_stats = check_for_working_netlink_stats();
965     }
966     if (use_netlink_stats) {
967         int ifindex;
968
969         error = get_ifindex(netdev_, &ifindex);
970         if (!error) {
971             error = get_stats_via_netlink(ifindex, collect_stats);
972         }
973     } else {
974         error = get_stats_via_proc(netdev_get_name(netdev_), collect_stats);
975     }
976
977     /* If this port is an internal port then the transmit and receive stats
978      * will appear to be swapped relative to the other ports since we are the
979      * one sending the data, not a remote computer.  For consistency, we swap
980      * them back here. */
981     if (!error && (netdev_dev->is_internal || netdev_dev->is_tap)) {
982         stats->rx_packets = raw_stats.tx_packets;
983         stats->tx_packets = raw_stats.rx_packets;
984         stats->rx_bytes = raw_stats.tx_bytes;
985         stats->tx_bytes = raw_stats.rx_bytes;
986         stats->rx_errors = raw_stats.tx_errors;
987         stats->tx_errors = raw_stats.rx_errors;
988         stats->rx_dropped = raw_stats.tx_dropped;
989         stats->tx_dropped = raw_stats.rx_dropped;
990         stats->multicast = raw_stats.multicast;
991         stats->collisions = raw_stats.collisions;
992         stats->rx_length_errors = 0;
993         stats->rx_over_errors = 0;
994         stats->rx_crc_errors = 0;
995         stats->rx_frame_errors = 0;
996         stats->rx_fifo_errors = 0;
997         stats->rx_missed_errors = 0;
998         stats->tx_aborted_errors = 0;
999         stats->tx_carrier_errors = 0;
1000         stats->tx_fifo_errors = 0;
1001         stats->tx_heartbeat_errors = 0;
1002         stats->tx_window_errors = 0;
1003     }
1004
1005     return error;
1006 }
1007
1008 static int
1009 netdev_linux_set_stats(struct netdev *netdev,
1010                        const struct netdev_stats *stats)
1011 {
1012     struct netdev_dev_linux *netdev_dev =
1013         netdev_dev_linux_cast(netdev_get_dev(netdev));
1014     struct internal_dev_stats dp_dev_stats;
1015     struct ifreq ifr;
1016
1017     /* We must reject this call if 'netdev' is not an Open vSwitch internal
1018      * port, because the ioctl that we are about to execute is in the "device
1019      * private ioctls" range, which means that executing it on a device that
1020      * is not the type we expect could do any random thing.
1021      *
1022      * (Amusingly, these ioctl numbers are commented "THESE IOCTLS ARE
1023      * _DEPRECATED_ AND WILL DISAPPEAR IN 2.5.X" in linux/sockios.h.  I guess
1024      * DaveM is a little behind on that.) */
1025     netdev_linux_update_is_pseudo(netdev_dev);
1026     if (!netdev_dev->is_internal) {
1027         return EOPNOTSUPP;
1028     }
1029
1030     /* This actually only sets the *offset* that the dp_dev applies, but in our
1031      * usage for fake bond devices the dp_dev never has any traffic of it own
1032      * so it has the same effect. */
1033     dp_dev_stats.rx_packets = stats->rx_packets;
1034     dp_dev_stats.rx_bytes = stats->rx_bytes;
1035     dp_dev_stats.tx_packets = stats->tx_packets;
1036     dp_dev_stats.tx_bytes = stats->tx_bytes;
1037     ifr.ifr_data = (void *) &dp_dev_stats;
1038     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr,
1039                                  INTERNAL_DEV_SET_STATS,
1040                                  "INTERNAL_DEV_SET_STATS");
1041 }
1042
1043 /* Stores the features supported by 'netdev' into each of '*current',
1044  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
1045  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
1046  * successful, otherwise a positive errno value. */
1047 static int
1048 netdev_linux_get_features(struct netdev *netdev,
1049                           uint32_t *current, uint32_t *advertised,
1050                           uint32_t *supported, uint32_t *peer)
1051 {
1052     struct ethtool_cmd ecmd;
1053     int error;
1054
1055     memset(&ecmd, 0, sizeof ecmd);
1056     error = netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1057                                     ETHTOOL_GSET, "ETHTOOL_GSET");
1058     if (error) {
1059         return error;
1060     }
1061
1062     /* Supported features. */
1063     *supported = 0;
1064     if (ecmd.supported & SUPPORTED_10baseT_Half) {
1065         *supported |= OFPPF_10MB_HD;
1066     }
1067     if (ecmd.supported & SUPPORTED_10baseT_Full) {
1068         *supported |= OFPPF_10MB_FD;
1069     }
1070     if (ecmd.supported & SUPPORTED_100baseT_Half)  {
1071         *supported |= OFPPF_100MB_HD;
1072     }
1073     if (ecmd.supported & SUPPORTED_100baseT_Full) {
1074         *supported |= OFPPF_100MB_FD;
1075     }
1076     if (ecmd.supported & SUPPORTED_1000baseT_Half) {
1077         *supported |= OFPPF_1GB_HD;
1078     }
1079     if (ecmd.supported & SUPPORTED_1000baseT_Full) {
1080         *supported |= OFPPF_1GB_FD;
1081     }
1082     if (ecmd.supported & SUPPORTED_10000baseT_Full) {
1083         *supported |= OFPPF_10GB_FD;
1084     }
1085     if (ecmd.supported & SUPPORTED_TP) {
1086         *supported |= OFPPF_COPPER;
1087     }
1088     if (ecmd.supported & SUPPORTED_FIBRE) {
1089         *supported |= OFPPF_FIBER;
1090     }
1091     if (ecmd.supported & SUPPORTED_Autoneg) {
1092         *supported |= OFPPF_AUTONEG;
1093     }
1094     if (ecmd.supported & SUPPORTED_Pause) {
1095         *supported |= OFPPF_PAUSE;
1096     }
1097     if (ecmd.supported & SUPPORTED_Asym_Pause) {
1098         *supported |= OFPPF_PAUSE_ASYM;
1099     }
1100
1101     /* Advertised features. */
1102     *advertised = 0;
1103     if (ecmd.advertising & ADVERTISED_10baseT_Half) {
1104         *advertised |= OFPPF_10MB_HD;
1105     }
1106     if (ecmd.advertising & ADVERTISED_10baseT_Full) {
1107         *advertised |= OFPPF_10MB_FD;
1108     }
1109     if (ecmd.advertising & ADVERTISED_100baseT_Half) {
1110         *advertised |= OFPPF_100MB_HD;
1111     }
1112     if (ecmd.advertising & ADVERTISED_100baseT_Full) {
1113         *advertised |= OFPPF_100MB_FD;
1114     }
1115     if (ecmd.advertising & ADVERTISED_1000baseT_Half) {
1116         *advertised |= OFPPF_1GB_HD;
1117     }
1118     if (ecmd.advertising & ADVERTISED_1000baseT_Full) {
1119         *advertised |= OFPPF_1GB_FD;
1120     }
1121     if (ecmd.advertising & ADVERTISED_10000baseT_Full) {
1122         *advertised |= OFPPF_10GB_FD;
1123     }
1124     if (ecmd.advertising & ADVERTISED_TP) {
1125         *advertised |= OFPPF_COPPER;
1126     }
1127     if (ecmd.advertising & ADVERTISED_FIBRE) {
1128         *advertised |= OFPPF_FIBER;
1129     }
1130     if (ecmd.advertising & ADVERTISED_Autoneg) {
1131         *advertised |= OFPPF_AUTONEG;
1132     }
1133     if (ecmd.advertising & ADVERTISED_Pause) {
1134         *advertised |= OFPPF_PAUSE;
1135     }
1136     if (ecmd.advertising & ADVERTISED_Asym_Pause) {
1137         *advertised |= OFPPF_PAUSE_ASYM;
1138     }
1139
1140     /* Current settings. */
1141     if (ecmd.speed == SPEED_10) {
1142         *current = ecmd.duplex ? OFPPF_10MB_FD : OFPPF_10MB_HD;
1143     } else if (ecmd.speed == SPEED_100) {
1144         *current = ecmd.duplex ? OFPPF_100MB_FD : OFPPF_100MB_HD;
1145     } else if (ecmd.speed == SPEED_1000) {
1146         *current = ecmd.duplex ? OFPPF_1GB_FD : OFPPF_1GB_HD;
1147     } else if (ecmd.speed == SPEED_10000) {
1148         *current = OFPPF_10GB_FD;
1149     } else {
1150         *current = 0;
1151     }
1152
1153     if (ecmd.port == PORT_TP) {
1154         *current |= OFPPF_COPPER;
1155     } else if (ecmd.port == PORT_FIBRE) {
1156         *current |= OFPPF_FIBER;
1157     }
1158
1159     if (ecmd.autoneg) {
1160         *current |= OFPPF_AUTONEG;
1161     }
1162
1163     /* Peer advertisements. */
1164     *peer = 0;                  /* XXX */
1165
1166     return 0;
1167 }
1168
1169 /* Set the features advertised by 'netdev' to 'advertise'. */
1170 static int
1171 netdev_linux_set_advertisements(struct netdev *netdev, uint32_t advertise)
1172 {
1173     struct ethtool_cmd ecmd;
1174     int error;
1175
1176     memset(&ecmd, 0, sizeof ecmd);
1177     error = netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1178                                     ETHTOOL_GSET, "ETHTOOL_GSET");
1179     if (error) {
1180         return error;
1181     }
1182
1183     ecmd.advertising = 0;
1184     if (advertise & OFPPF_10MB_HD) {
1185         ecmd.advertising |= ADVERTISED_10baseT_Half;
1186     }
1187     if (advertise & OFPPF_10MB_FD) {
1188         ecmd.advertising |= ADVERTISED_10baseT_Full;
1189     }
1190     if (advertise & OFPPF_100MB_HD) {
1191         ecmd.advertising |= ADVERTISED_100baseT_Half;
1192     }
1193     if (advertise & OFPPF_100MB_FD) {
1194         ecmd.advertising |= ADVERTISED_100baseT_Full;
1195     }
1196     if (advertise & OFPPF_1GB_HD) {
1197         ecmd.advertising |= ADVERTISED_1000baseT_Half;
1198     }
1199     if (advertise & OFPPF_1GB_FD) {
1200         ecmd.advertising |= ADVERTISED_1000baseT_Full;
1201     }
1202     if (advertise & OFPPF_10GB_FD) {
1203         ecmd.advertising |= ADVERTISED_10000baseT_Full;
1204     }
1205     if (advertise & OFPPF_COPPER) {
1206         ecmd.advertising |= ADVERTISED_TP;
1207     }
1208     if (advertise & OFPPF_FIBER) {
1209         ecmd.advertising |= ADVERTISED_FIBRE;
1210     }
1211     if (advertise & OFPPF_AUTONEG) {
1212         ecmd.advertising |= ADVERTISED_Autoneg;
1213     }
1214     if (advertise & OFPPF_PAUSE) {
1215         ecmd.advertising |= ADVERTISED_Pause;
1216     }
1217     if (advertise & OFPPF_PAUSE_ASYM) {
1218         ecmd.advertising |= ADVERTISED_Asym_Pause;
1219     }
1220     return netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1221                                    ETHTOOL_SSET, "ETHTOOL_SSET");
1222 }
1223
1224 /* If 'netdev_name' is the name of a VLAN network device (e.g. one created with
1225  * vconfig(8)), sets '*vlan_vid' to the VLAN VID associated with that device
1226  * and returns 0.  Otherwise returns a errno value (specifically ENOENT if
1227  * 'netdev_name' is the name of a network device that is not a VLAN device) and
1228  * sets '*vlan_vid' to -1. */
1229 static int
1230 netdev_linux_get_vlan_vid(const struct netdev *netdev, int *vlan_vid)
1231 {
1232     const char *netdev_name = netdev_get_name(netdev);
1233     struct ds line = DS_EMPTY_INITIALIZER;
1234     FILE *stream = NULL;
1235     int error;
1236     char *fn;
1237
1238     COVERAGE_INC(netdev_get_vlan_vid);
1239     fn = xasprintf("/proc/net/vlan/%s", netdev_name);
1240     stream = fopen(fn, "r");
1241     if (!stream) {
1242         error = errno;
1243         goto done;
1244     }
1245
1246     if (ds_get_line(&line, stream)) {
1247         if (ferror(stream)) {
1248             error = errno;
1249             VLOG_ERR_RL(&rl, "error reading \"%s\": %s", fn, strerror(errno));
1250         } else {
1251             error = EPROTO;
1252             VLOG_ERR_RL(&rl, "unexpected end of file reading \"%s\"", fn);
1253         }
1254         goto done;
1255     }
1256
1257     if (!sscanf(ds_cstr(&line), "%*s VID: %d", vlan_vid)) {
1258         error = EPROTO;
1259         VLOG_ERR_RL(&rl, "parse error reading \"%s\" line 1: \"%s\"",
1260                     fn, ds_cstr(&line));
1261         goto done;
1262     }
1263
1264     error = 0;
1265
1266 done:
1267     free(fn);
1268     if (stream) {
1269         fclose(stream);
1270     }
1271     ds_destroy(&line);
1272     if (error) {
1273         *vlan_vid = -1;
1274     }
1275     return error;
1276 }
1277
1278 #define POLICE_ADD_CMD "/sbin/tc qdisc add dev %s handle ffff: ingress"
1279 #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"
1280
1281 /* Remove ingress policing from 'netdev'.  Returns 0 if successful, otherwise a
1282  * positive errno value.
1283  *
1284  * This function is equivalent to running
1285  *     /sbin/tc qdisc del dev %s handle ffff: ingress
1286  * but it is much, much faster.
1287  */
1288 static int
1289 netdev_linux_remove_policing(struct netdev *netdev)
1290 {
1291     struct netdev_dev_linux *netdev_dev =
1292         netdev_dev_linux_cast(netdev_get_dev(netdev));
1293     const char *netdev_name = netdev_get_name(netdev);
1294
1295     struct ofpbuf request;
1296     struct ofpbuf *reply;
1297     struct tcmsg *tcmsg;
1298     struct nl_sock *rtnl_sock;
1299     int ifindex;
1300     int error;
1301
1302     error = get_ifindex(netdev, &ifindex);
1303     if (error) {
1304         return error;
1305     }
1306
1307     error = get_rtnl_sock(&rtnl_sock);
1308     if (error) {
1309         return error;
1310     }
1311
1312     ofpbuf_init(&request, 0);
1313     nl_msg_put_nlmsghdr(&request, rtnl_sock, sizeof *tcmsg,
1314                         RTM_DELQDISC, NLM_F_REQUEST);
1315     tcmsg = ofpbuf_put_zeros(&request, sizeof *tcmsg);
1316     tcmsg->tcm_family = AF_UNSPEC;
1317     tcmsg->tcm_ifindex = ifindex;
1318     tcmsg->tcm_handle = 0xffff0000;
1319     tcmsg->tcm_parent = TC_H_INGRESS;
1320     nl_msg_put_string(&request, TCA_KIND, "ingress");
1321     nl_msg_put_unspec(&request, TCA_OPTIONS, NULL, 0);
1322     error = nl_sock_transact(rtnl_sock, &request, &reply);
1323     ofpbuf_uninit(&request);
1324     ofpbuf_delete(reply);
1325     if (error && error != ENOENT) {
1326         VLOG_WARN_RL(&rl, "%s: removing policing failed: %s",
1327                      netdev_name, strerror(error));
1328         return error;
1329     }
1330
1331     netdev_dev->kbits_rate = 0;
1332     netdev_dev->kbits_burst = 0;
1333     netdev_dev->cache_valid |= VALID_POLICING;
1334     return 0;
1335 }
1336
1337 /* Attempts to set input rate limiting (policing) policy. */
1338 static int
1339 netdev_linux_set_policing(struct netdev *netdev,
1340                           uint32_t kbits_rate, uint32_t kbits_burst)
1341 {
1342     struct netdev_dev_linux *netdev_dev =
1343         netdev_dev_linux_cast(netdev_get_dev(netdev));
1344     const char *netdev_name = netdev_get_name(netdev);
1345     char command[1024];
1346
1347     COVERAGE_INC(netdev_set_policing);
1348
1349     kbits_burst = (!kbits_rate ? 0       /* Force to 0 if no rate specified. */
1350                    : !kbits_burst ? 1000 /* Default to 1000 kbits if 0. */
1351                    : kbits_burst);       /* Stick with user-specified value. */
1352
1353     if (netdev_dev->cache_valid & VALID_POLICING
1354         && netdev_dev->kbits_rate == kbits_rate
1355         && netdev_dev->kbits_burst == kbits_burst) {
1356         /* Assume that settings haven't changed since we last set them. */
1357         return 0;
1358     }
1359
1360     netdev_linux_remove_policing(netdev);
1361     if (kbits_rate) {
1362         snprintf(command, sizeof(command), POLICE_ADD_CMD, netdev_name);
1363         if (system(command) != 0) {
1364             VLOG_WARN_RL(&rl, "%s: problem adding policing", netdev_name);
1365             return -1;
1366         }
1367
1368         snprintf(command, sizeof(command), POLICE_CONFIG_CMD, netdev_name,
1369                 kbits_rate, kbits_burst);
1370         if (system(command) != 0) {
1371             VLOG_WARN_RL(&rl, "%s: problem configuring policing",
1372                     netdev_name);
1373             return -1;
1374         }
1375
1376         netdev_dev->kbits_rate = kbits_rate;
1377         netdev_dev->kbits_burst = kbits_burst;
1378         netdev_dev->cache_valid |= VALID_POLICING;
1379     }
1380
1381     return 0;
1382 }
1383
1384 static int
1385 netdev_linux_get_in4(const struct netdev *netdev_,
1386                      struct in_addr *address, struct in_addr *netmask)
1387 {
1388     struct netdev_dev_linux *netdev_dev =
1389                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1390
1391     if (!(netdev_dev->cache_valid & VALID_IN4)) {
1392         int error;
1393
1394         error = netdev_linux_get_ipv4(netdev_, &netdev_dev->address,
1395                                       SIOCGIFADDR, "SIOCGIFADDR");
1396         if (error) {
1397             return error;
1398         }
1399
1400         error = netdev_linux_get_ipv4(netdev_, &netdev_dev->netmask,
1401                                       SIOCGIFNETMASK, "SIOCGIFNETMASK");
1402         if (error) {
1403             return error;
1404         }
1405
1406         netdev_dev->cache_valid |= VALID_IN4;
1407     }
1408     *address = netdev_dev->address;
1409     *netmask = netdev_dev->netmask;
1410     return address->s_addr == INADDR_ANY ? EADDRNOTAVAIL : 0;
1411 }
1412
1413 static int
1414 netdev_linux_set_in4(struct netdev *netdev_, struct in_addr address,
1415                      struct in_addr netmask)
1416 {
1417     struct netdev_dev_linux *netdev_dev =
1418                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1419     int error;
1420
1421     error = do_set_addr(netdev_, SIOCSIFADDR, "SIOCSIFADDR", address);
1422     if (!error) {
1423         netdev_dev->cache_valid |= VALID_IN4;
1424         netdev_dev->address = address;
1425         netdev_dev->netmask = netmask;
1426         if (address.s_addr != INADDR_ANY) {
1427             error = do_set_addr(netdev_, SIOCSIFNETMASK,
1428                                 "SIOCSIFNETMASK", netmask);
1429         }
1430     }
1431     return error;
1432 }
1433
1434 static bool
1435 parse_if_inet6_line(const char *line,
1436                     struct in6_addr *in6, char ifname[16 + 1])
1437 {
1438     uint8_t *s6 = in6->s6_addr;
1439 #define X8 "%2"SCNx8
1440     return sscanf(line,
1441                   " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
1442                   "%*x %*x %*x %*x %16s\n",
1443                   &s6[0], &s6[1], &s6[2], &s6[3],
1444                   &s6[4], &s6[5], &s6[6], &s6[7],
1445                   &s6[8], &s6[9], &s6[10], &s6[11],
1446                   &s6[12], &s6[13], &s6[14], &s6[15],
1447                   ifname) == 17;
1448 }
1449
1450 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
1451  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
1452 static int
1453 netdev_linux_get_in6(const struct netdev *netdev_, struct in6_addr *in6)
1454 {
1455     struct netdev_dev_linux *netdev_dev =
1456                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1457     if (!(netdev_dev->cache_valid & VALID_IN6)) {
1458         FILE *file;
1459         char line[128];
1460
1461         netdev_dev->in6 = in6addr_any;
1462
1463         file = fopen("/proc/net/if_inet6", "r");
1464         if (file != NULL) {
1465             const char *name = netdev_get_name(netdev_);
1466             while (fgets(line, sizeof line, file)) {
1467                 struct in6_addr in6;
1468                 char ifname[16 + 1];
1469                 if (parse_if_inet6_line(line, &in6, ifname)
1470                     && !strcmp(name, ifname))
1471                 {
1472                     netdev_dev->in6 = in6;
1473                     break;
1474                 }
1475             }
1476             fclose(file);
1477         }
1478         netdev_dev->cache_valid |= VALID_IN6;
1479     }
1480     *in6 = netdev_dev->in6;
1481     return 0;
1482 }
1483
1484 static void
1485 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
1486 {
1487     struct sockaddr_in sin;
1488     memset(&sin, 0, sizeof sin);
1489     sin.sin_family = AF_INET;
1490     sin.sin_addr = addr;
1491     sin.sin_port = 0;
1492
1493     memset(sa, 0, sizeof *sa);
1494     memcpy(sa, &sin, sizeof sin);
1495 }
1496
1497 static int
1498 do_set_addr(struct netdev *netdev,
1499             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
1500 {
1501     struct ifreq ifr;
1502     strncpy(ifr.ifr_name, netdev_get_name(netdev), sizeof ifr.ifr_name);
1503     make_in4_sockaddr(&ifr.ifr_addr, addr);
1504
1505     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, ioctl_nr,
1506                                  ioctl_name);
1507 }
1508
1509 /* Adds 'router' as a default IP gateway. */
1510 static int
1511 netdev_linux_add_router(struct netdev *netdev OVS_UNUSED, struct in_addr router)
1512 {
1513     struct in_addr any = { INADDR_ANY };
1514     struct rtentry rt;
1515     int error;
1516
1517     memset(&rt, 0, sizeof rt);
1518     make_in4_sockaddr(&rt.rt_dst, any);
1519     make_in4_sockaddr(&rt.rt_gateway, router);
1520     make_in4_sockaddr(&rt.rt_genmask, any);
1521     rt.rt_flags = RTF_UP | RTF_GATEWAY;
1522     COVERAGE_INC(netdev_add_router);
1523     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
1524     if (error) {
1525         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
1526     }
1527     return error;
1528 }
1529
1530 static int
1531 netdev_linux_get_next_hop(const struct in_addr *host, struct in_addr *next_hop,
1532                           char **netdev_name)
1533 {
1534     static const char fn[] = "/proc/net/route";
1535     FILE *stream;
1536     char line[256];
1537     int ln;
1538
1539     *netdev_name = NULL;
1540     stream = fopen(fn, "r");
1541     if (stream == NULL) {
1542         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1543         return errno;
1544     }
1545
1546     ln = 0;
1547     while (fgets(line, sizeof line, stream)) {
1548         if (++ln >= 2) {
1549             char iface[17];
1550             uint32_t dest, gateway, mask;
1551             int refcnt, metric, mtu;
1552             unsigned int flags, use, window, irtt;
1553
1554             if (sscanf(line,
1555                        "%16s %"SCNx32" %"SCNx32" %04X %d %u %d %"SCNx32
1556                        " %d %u %u\n",
1557                        iface, &dest, &gateway, &flags, &refcnt,
1558                        &use, &metric, &mask, &mtu, &window, &irtt) != 11) {
1559
1560                 VLOG_WARN_RL(&rl, "%s: could not parse line %d: %s", 
1561                         fn, ln, line);
1562                 continue;
1563             }
1564             if (!(flags & RTF_UP)) {
1565                 /* Skip routes that aren't up. */
1566                 continue;
1567             }
1568
1569             /* The output of 'dest', 'mask', and 'gateway' were given in
1570              * network byte order, so we don't need need any endian 
1571              * conversions here. */
1572             if ((dest & mask) == (host->s_addr & mask)) {
1573                 if (!gateway) {
1574                     /* The host is directly reachable. */
1575                     next_hop->s_addr = 0;
1576                 } else {
1577                     /* To reach the host, we must go through a gateway. */
1578                     next_hop->s_addr = gateway;
1579                 }
1580                 *netdev_name = xstrdup(iface);
1581                 fclose(stream);
1582                 return 0;
1583             }
1584         }
1585     }
1586
1587     fclose(stream);
1588     return ENXIO;
1589 }
1590
1591 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
1592  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
1593  * returns 0.  Otherwise, it returns a positive errno value; in particular,
1594  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
1595 static int
1596 netdev_linux_arp_lookup(const struct netdev *netdev,
1597                         uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
1598 {
1599     struct arpreq r;
1600     struct sockaddr_in sin;
1601     int retval;
1602
1603     memset(&r, 0, sizeof r);
1604     sin.sin_family = AF_INET;
1605     sin.sin_addr.s_addr = ip;
1606     sin.sin_port = 0;
1607     memcpy(&r.arp_pa, &sin, sizeof sin);
1608     r.arp_ha.sa_family = ARPHRD_ETHER;
1609     r.arp_flags = 0;
1610     strncpy(r.arp_dev, netdev_get_name(netdev), sizeof r.arp_dev);
1611     COVERAGE_INC(netdev_arp_lookup);
1612     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
1613     if (!retval) {
1614         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
1615     } else if (retval != ENXIO) {
1616         VLOG_WARN_RL(&rl, "%s: could not look up ARP entry for "IP_FMT": %s",
1617                      netdev_get_name(netdev), IP_ARGS(&ip), strerror(retval));
1618     }
1619     return retval;
1620 }
1621
1622 static int
1623 nd_to_iff_flags(enum netdev_flags nd)
1624 {
1625     int iff = 0;
1626     if (nd & NETDEV_UP) {
1627         iff |= IFF_UP;
1628     }
1629     if (nd & NETDEV_PROMISC) {
1630         iff |= IFF_PROMISC;
1631     }
1632     return iff;
1633 }
1634
1635 static int
1636 iff_to_nd_flags(int iff)
1637 {
1638     enum netdev_flags nd = 0;
1639     if (iff & IFF_UP) {
1640         nd |= NETDEV_UP;
1641     }
1642     if (iff & IFF_PROMISC) {
1643         nd |= NETDEV_PROMISC;
1644     }
1645     return nd;
1646 }
1647
1648 static int
1649 netdev_linux_update_flags(struct netdev *netdev, enum netdev_flags off,
1650                           enum netdev_flags on, enum netdev_flags *old_flagsp)
1651 {
1652     int old_flags, new_flags;
1653     int error;
1654
1655     error = get_flags(netdev, &old_flags);
1656     if (!error) {
1657         *old_flagsp = iff_to_nd_flags(old_flags);
1658         new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
1659         if (new_flags != old_flags) {
1660             error = set_flags(netdev, new_flags);
1661         }
1662     }
1663     return error;
1664 }
1665
1666 static void
1667 poll_notify(struct list *list)
1668 {
1669     struct netdev_linux_notifier *notifier;
1670     LIST_FOR_EACH (notifier, struct netdev_linux_notifier, node, list) {
1671         struct netdev_notifier *n = &notifier->notifier;
1672         n->cb(n);
1673     }
1674 }
1675
1676 static void
1677 netdev_linux_poll_cb(const struct rtnetlink_change *change,
1678                      void *aux OVS_UNUSED)
1679 {
1680     if (change) {
1681         struct list *list = shash_find_data(&netdev_linux_notifiers,
1682                                             change->ifname);
1683         if (list) {
1684             poll_notify(list);
1685         }
1686     } else {
1687         struct shash_node *node;
1688         SHASH_FOR_EACH (node, &netdev_linux_notifiers) {
1689             poll_notify(node->data);
1690         }
1691     }
1692 }
1693
1694 static int
1695 netdev_linux_poll_add(struct netdev *netdev,
1696                       void (*cb)(struct netdev_notifier *), void *aux,
1697                       struct netdev_notifier **notifierp)
1698 {
1699     const char *netdev_name = netdev_get_name(netdev);
1700     struct netdev_linux_notifier *notifier;
1701     struct list *list;
1702
1703     if (shash_is_empty(&netdev_linux_notifiers)) {
1704         int error = rtnetlink_notifier_register(&netdev_linux_poll_notifier,
1705                                                    netdev_linux_poll_cb, NULL);
1706         if (error) {
1707             return error;
1708         }
1709     }
1710
1711     list = shash_find_data(&netdev_linux_notifiers, netdev_name);
1712     if (!list) {
1713         list = xmalloc(sizeof *list);
1714         list_init(list);
1715         shash_add(&netdev_linux_notifiers, netdev_name, list);
1716     }
1717
1718     notifier = xmalloc(sizeof *notifier);
1719     netdev_notifier_init(&notifier->notifier, netdev, cb, aux);
1720     list_push_back(list, &notifier->node);
1721     *notifierp = &notifier->notifier;
1722     return 0;
1723 }
1724
1725 static void
1726 netdev_linux_poll_remove(struct netdev_notifier *notifier_)
1727 {
1728     struct netdev_linux_notifier *notifier =
1729         CONTAINER_OF(notifier_, struct netdev_linux_notifier, notifier);
1730     struct list *list;
1731
1732     /* Remove 'notifier' from its list. */
1733     list = list_remove(&notifier->node);
1734     if (list_is_empty(list)) {
1735         /* The list is now empty.  Remove it from the hash and free it. */
1736         const char *netdev_name = netdev_get_name(notifier->notifier.netdev);
1737         shash_delete(&netdev_linux_notifiers,
1738                      shash_find(&netdev_linux_notifiers, netdev_name));
1739         free(list);
1740     }
1741     free(notifier);
1742
1743     /* If that was the last notifier, unregister. */
1744     if (shash_is_empty(&netdev_linux_notifiers)) {
1745         rtnetlink_notifier_unregister(&netdev_linux_poll_notifier);
1746     }
1747 }
1748
1749 const struct netdev_class netdev_linux_class = {
1750     "system",
1751
1752     netdev_linux_init,
1753     netdev_linux_run,
1754     netdev_linux_wait,
1755
1756     netdev_linux_create_system,
1757     netdev_linux_destroy,
1758     NULL,                       /* reconfigure */
1759
1760     netdev_linux_open,
1761     netdev_linux_close,
1762
1763     netdev_linux_enumerate,
1764
1765     netdev_linux_recv,
1766     netdev_linux_recv_wait,
1767     netdev_linux_drain,
1768
1769     netdev_linux_send,
1770     netdev_linux_send_wait,
1771
1772     netdev_linux_set_etheraddr,
1773     netdev_linux_get_etheraddr,
1774     netdev_linux_get_mtu,
1775     netdev_linux_get_ifindex,
1776     netdev_linux_get_carrier,
1777     netdev_linux_get_stats,
1778     netdev_linux_set_stats,
1779
1780     netdev_linux_get_features,
1781     netdev_linux_set_advertisements,
1782     netdev_linux_get_vlan_vid,
1783     netdev_linux_set_policing,
1784
1785     netdev_linux_get_in4,
1786     netdev_linux_set_in4,
1787     netdev_linux_get_in6,
1788     netdev_linux_add_router,
1789     netdev_linux_get_next_hop,
1790     netdev_linux_arp_lookup,
1791
1792     netdev_linux_update_flags,
1793
1794     netdev_linux_poll_add,
1795     netdev_linux_poll_remove,
1796 };
1797
1798 const struct netdev_class netdev_tap_class = {
1799     "tap",
1800
1801     netdev_linux_init,
1802     netdev_linux_run,
1803     netdev_linux_wait,
1804
1805     netdev_linux_create_tap,
1806     netdev_linux_destroy,
1807     NULL,                       /* reconfigure */
1808
1809     netdev_linux_open,
1810     netdev_linux_close,
1811
1812     NULL,                       /* enumerate */
1813
1814     netdev_linux_recv,
1815     netdev_linux_recv_wait,
1816     netdev_linux_drain,
1817
1818     netdev_linux_send,
1819     netdev_linux_send_wait,
1820
1821     netdev_linux_set_etheraddr,
1822     netdev_linux_get_etheraddr,
1823     netdev_linux_get_mtu,
1824     netdev_linux_get_ifindex,
1825     netdev_linux_get_carrier,
1826     netdev_linux_get_stats,
1827     NULL,                       /* set_stats */
1828
1829     netdev_linux_get_features,
1830     netdev_linux_set_advertisements,
1831     netdev_linux_get_vlan_vid,
1832     netdev_linux_set_policing,
1833
1834     netdev_linux_get_in4,
1835     netdev_linux_set_in4,
1836     netdev_linux_get_in6,
1837     netdev_linux_add_router,
1838     netdev_linux_get_next_hop,
1839     netdev_linux_arp_lookup,
1840
1841     netdev_linux_update_flags,
1842
1843     netdev_linux_poll_add,
1844     netdev_linux_poll_remove,
1845 };
1846
1847 const struct netdev_class netdev_patch_class = {
1848     "patch",
1849
1850     netdev_linux_init,
1851     netdev_linux_run,
1852     netdev_linux_wait,
1853
1854     netdev_linux_create_patch,
1855     netdev_linux_destroy,
1856     NULL,                       /* reconfigure */
1857
1858     netdev_linux_open,
1859     netdev_linux_close,
1860
1861     NULL,                       /* enumerate */
1862
1863     netdev_linux_recv,
1864     netdev_linux_recv_wait,
1865     netdev_linux_drain,
1866
1867     netdev_linux_send,
1868     netdev_linux_send_wait,
1869
1870     netdev_linux_set_etheraddr,
1871     netdev_linux_get_etheraddr,
1872     netdev_linux_get_mtu,
1873     netdev_linux_get_ifindex,
1874     netdev_linux_get_carrier,
1875     netdev_linux_get_stats,
1876     NULL,                       /* set_stats */
1877
1878     netdev_linux_get_features,
1879     netdev_linux_set_advertisements,
1880     netdev_linux_get_vlan_vid,
1881     netdev_linux_set_policing,
1882
1883     netdev_linux_get_in4,
1884     netdev_linux_set_in4,
1885     netdev_linux_get_in6,
1886     netdev_linux_add_router,
1887     netdev_linux_get_next_hop,
1888     netdev_linux_arp_lookup,
1889
1890     netdev_linux_update_flags,
1891
1892     netdev_linux_poll_add,
1893     netdev_linux_poll_remove,
1894 };
1895
1896 \f
1897 static int
1898 get_stats_via_netlink(int ifindex, struct netdev_stats *stats)
1899 {
1900     /* Policy for RTNLGRP_LINK messages.
1901      *
1902      * There are *many* more fields in these messages, but currently we only
1903      * care about these fields. */
1904     static const struct nl_policy rtnlgrp_link_policy[] = {
1905         [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
1906         [IFLA_STATS] = { .type = NL_A_UNSPEC, .optional = true,
1907                          .min_len = sizeof(struct rtnl_link_stats) },
1908     };
1909
1910     struct nl_sock *rtnl_sock;
1911     struct ofpbuf request;
1912     struct ofpbuf *reply;
1913     struct ifinfomsg *ifi;
1914     const struct rtnl_link_stats *rtnl_stats;
1915     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
1916     int error;
1917
1918     error = get_rtnl_sock(&rtnl_sock);
1919     if (error) {
1920         return error;
1921     }
1922
1923     ofpbuf_init(&request, 0);
1924     nl_msg_put_nlmsghdr(&request, rtnl_sock, sizeof *ifi,
1925                         RTM_GETLINK, NLM_F_REQUEST);
1926     ifi = ofpbuf_put_zeros(&request, sizeof *ifi);
1927     ifi->ifi_family = PF_UNSPEC;
1928     ifi->ifi_index = ifindex;
1929     error = nl_sock_transact(rtnl_sock, &request, &reply);
1930     ofpbuf_uninit(&request);
1931     if (error) {
1932         return error;
1933     }
1934
1935     if (!nl_policy_parse(reply, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
1936                          rtnlgrp_link_policy,
1937                          attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
1938         ofpbuf_delete(reply);
1939         return EPROTO;
1940     }
1941
1942     if (!attrs[IFLA_STATS]) {
1943         VLOG_WARN_RL(&rl, "RTM_GETLINK reply lacks stats");
1944         ofpbuf_delete(reply);
1945         return EPROTO;
1946     }
1947
1948     rtnl_stats = nl_attr_get(attrs[IFLA_STATS]);
1949     stats->rx_packets = rtnl_stats->rx_packets;
1950     stats->tx_packets = rtnl_stats->tx_packets;
1951     stats->rx_bytes = rtnl_stats->rx_bytes;
1952     stats->tx_bytes = rtnl_stats->tx_bytes;
1953     stats->rx_errors = rtnl_stats->rx_errors;
1954     stats->tx_errors = rtnl_stats->tx_errors;
1955     stats->rx_dropped = rtnl_stats->rx_dropped;
1956     stats->tx_dropped = rtnl_stats->tx_dropped;
1957     stats->multicast = rtnl_stats->multicast;
1958     stats->collisions = rtnl_stats->collisions;
1959     stats->rx_length_errors = rtnl_stats->rx_length_errors;
1960     stats->rx_over_errors = rtnl_stats->rx_over_errors;
1961     stats->rx_crc_errors = rtnl_stats->rx_crc_errors;
1962     stats->rx_frame_errors = rtnl_stats->rx_frame_errors;
1963     stats->rx_fifo_errors = rtnl_stats->rx_fifo_errors;
1964     stats->rx_missed_errors = rtnl_stats->rx_missed_errors;
1965     stats->tx_aborted_errors = rtnl_stats->tx_aborted_errors;
1966     stats->tx_carrier_errors = rtnl_stats->tx_carrier_errors;
1967     stats->tx_fifo_errors = rtnl_stats->tx_fifo_errors;
1968     stats->tx_heartbeat_errors = rtnl_stats->tx_heartbeat_errors;
1969     stats->tx_window_errors = rtnl_stats->tx_window_errors;
1970
1971     ofpbuf_delete(reply);
1972
1973     return 0;
1974 }
1975
1976 static int
1977 get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats)
1978 {
1979     static const char fn[] = "/proc/net/dev";
1980     char line[1024];
1981     FILE *stream;
1982     int ln;
1983
1984     stream = fopen(fn, "r");
1985     if (!stream) {
1986         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1987         return errno;
1988     }
1989
1990     ln = 0;
1991     while (fgets(line, sizeof line, stream)) {
1992         if (++ln >= 3) {
1993             char devname[16];
1994 #define X64 "%"SCNu64
1995             if (sscanf(line,
1996                        " %15[^:]:"
1997                        X64 X64 X64 X64 X64 X64 X64 "%*u"
1998                        X64 X64 X64 X64 X64 X64 X64 "%*u",
1999                        devname,
2000                        &stats->rx_bytes,
2001                        &stats->rx_packets,
2002                        &stats->rx_errors,
2003                        &stats->rx_dropped,
2004                        &stats->rx_fifo_errors,
2005                        &stats->rx_frame_errors,
2006                        &stats->multicast,
2007                        &stats->tx_bytes,
2008                        &stats->tx_packets,
2009                        &stats->tx_errors,
2010                        &stats->tx_dropped,
2011                        &stats->tx_fifo_errors,
2012                        &stats->collisions,
2013                        &stats->tx_carrier_errors) != 15) {
2014                 VLOG_WARN_RL(&rl, "%s:%d: parse error", fn, ln);
2015             } else if (!strcmp(devname, netdev_name)) {
2016                 stats->rx_length_errors = UINT64_MAX;
2017                 stats->rx_over_errors = UINT64_MAX;
2018                 stats->rx_crc_errors = UINT64_MAX;
2019                 stats->rx_missed_errors = UINT64_MAX;
2020                 stats->tx_aborted_errors = UINT64_MAX;
2021                 stats->tx_heartbeat_errors = UINT64_MAX;
2022                 stats->tx_window_errors = UINT64_MAX;
2023                 fclose(stream);
2024                 return 0;
2025             }
2026         }
2027     }
2028     VLOG_WARN_RL(&rl, "%s: no stats for %s", fn, netdev_name);
2029     fclose(stream);
2030     return ENODEV;
2031 }
2032 \f
2033 static int
2034 get_flags(const struct netdev *netdev, int *flags)
2035 {
2036     struct ifreq ifr;
2037     int error;
2038
2039     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCGIFFLAGS,
2040                                   "SIOCGIFFLAGS");
2041     *flags = ifr.ifr_flags;
2042     return error;
2043 }
2044
2045 static int
2046 set_flags(struct netdev *netdev, int flags)
2047 {
2048     struct ifreq ifr;
2049
2050     ifr.ifr_flags = flags;
2051     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCSIFFLAGS,
2052                                  "SIOCSIFFLAGS");
2053 }
2054
2055 static int
2056 do_get_ifindex(const char *netdev_name)
2057 {
2058     struct ifreq ifr;
2059
2060     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
2061     COVERAGE_INC(netdev_get_ifindex);
2062     if (ioctl(af_inet_sock, SIOCGIFINDEX, &ifr) < 0) {
2063         VLOG_WARN_RL(&rl, "ioctl(SIOCGIFINDEX) on %s device failed: %s",
2064                      netdev_name, strerror(errno));
2065         return -errno;
2066     }
2067     return ifr.ifr_ifindex;
2068 }
2069
2070 static int
2071 get_ifindex(const struct netdev *netdev_, int *ifindexp)
2072 {
2073     struct netdev_dev_linux *netdev_dev =
2074                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
2075     *ifindexp = 0;
2076     if (!(netdev_dev->cache_valid & VALID_IFINDEX)) {
2077         int ifindex = do_get_ifindex(netdev_get_name(netdev_));
2078         if (ifindex < 0) {
2079             return -ifindex;
2080         }
2081         netdev_dev->cache_valid |= VALID_IFINDEX;
2082         netdev_dev->ifindex = ifindex;
2083     }
2084     *ifindexp = netdev_dev->ifindex;
2085     return 0;
2086 }
2087
2088 static int
2089 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
2090 {
2091     struct ifreq ifr;
2092     int hwaddr_family;
2093
2094     memset(&ifr, 0, sizeof ifr);
2095     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
2096     COVERAGE_INC(netdev_get_hwaddr);
2097     if (ioctl(af_inet_sock, SIOCGIFHWADDR, &ifr) < 0) {
2098         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
2099                  netdev_name, strerror(errno));
2100         return errno;
2101     }
2102     hwaddr_family = ifr.ifr_hwaddr.sa_family;
2103     if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
2104         VLOG_WARN("%s device has unknown hardware address family %d",
2105                   netdev_name, hwaddr_family);
2106     }
2107     memcpy(ea, ifr.ifr_hwaddr.sa_data, ETH_ADDR_LEN);
2108     return 0;
2109 }
2110
2111 static int
2112 set_etheraddr(const char *netdev_name, int hwaddr_family,
2113               const uint8_t mac[ETH_ADDR_LEN])
2114 {
2115     struct ifreq ifr;
2116
2117     memset(&ifr, 0, sizeof ifr);
2118     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
2119     ifr.ifr_hwaddr.sa_family = hwaddr_family;
2120     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
2121     COVERAGE_INC(netdev_set_hwaddr);
2122     if (ioctl(af_inet_sock, SIOCSIFHWADDR, &ifr) < 0) {
2123         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
2124                  netdev_name, strerror(errno));
2125         return errno;
2126     }
2127     return 0;
2128 }
2129
2130 static int
2131 netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *ecmd,
2132                         int cmd, const char *cmd_name)
2133 {
2134     struct ifreq ifr;
2135
2136     memset(&ifr, 0, sizeof ifr);
2137     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
2138     ifr.ifr_data = (caddr_t) ecmd;
2139
2140     ecmd->cmd = cmd;
2141     COVERAGE_INC(netdev_ethtool);
2142     if (ioctl(af_inet_sock, SIOCETHTOOL, &ifr) == 0) {
2143         return 0;
2144     } else {
2145         if (errno != EOPNOTSUPP) {
2146             VLOG_WARN_RL(&rl, "ethtool command %s on network device %s "
2147                          "failed: %s", cmd_name, name, strerror(errno));
2148         } else {
2149             /* The device doesn't support this operation.  That's pretty
2150              * common, so there's no point in logging anything. */
2151         }
2152         return errno;
2153     }
2154 }
2155
2156 static int
2157 netdev_linux_do_ioctl(const char *name, struct ifreq *ifr, int cmd,
2158                       const char *cmd_name)
2159 {
2160     strncpy(ifr->ifr_name, name, sizeof ifr->ifr_name);
2161     if (ioctl(af_inet_sock, cmd, ifr) == -1) {
2162         VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s", name, cmd_name,
2163                      strerror(errno));
2164         return errno;
2165     }
2166     return 0;
2167 }
2168
2169 static int
2170 netdev_linux_get_ipv4(const struct netdev *netdev, struct in_addr *ip,
2171                       int cmd, const char *cmd_name)
2172 {
2173     struct ifreq ifr;
2174     int error;
2175
2176     ifr.ifr_addr.sa_family = AF_INET;
2177     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, cmd, cmd_name);
2178     if (!error) {
2179         const struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
2180         *ip = sin->sin_addr;
2181     }
2182     return error;
2183 }
2184
2185 /* Obtains a Netlink routing socket that is not subscribed to any multicast
2186  * groups.  Returns 0 if successful, otherwise a positive errno value.  Stores
2187  * the socket in '*rtnl_sockp' if successful, otherwise a null pointer. */
2188 static int
2189 get_rtnl_sock(struct nl_sock **rtnl_sockp)
2190 {
2191     static struct nl_sock *sock;
2192     int error;
2193
2194     if (!sock) {
2195         error = nl_sock_create(NETLINK_ROUTE, 0, 0, 0, &sock);
2196         if (error) {
2197             VLOG_ERR_RL(&rl, "failed to create rtnetlink socket: %s",
2198                         strerror(error));
2199         }
2200     } else {
2201         error = 0;
2202     }
2203
2204     *rtnl_sockp = sock;
2205     return error;
2206 }