lib: Show tunnel egress interface in ovsdb
[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/gen_stats.h>
24 #include <linux/if_tun.h>
25 #include <linux/ip.h>
26 #include <linux/types.h>
27 #include <linux/ethtool.h>
28 #include <linux/pkt_sched.h>
29 #include <linux/rtnetlink.h>
30 #include <linux/sockios.h>
31 #include <linux/version.h>
32 #include <sys/types.h>
33 #include <sys/ioctl.h>
34 #include <sys/socket.h>
35 #include <netpacket/packet.h>
36 #include <net/ethernet.h>
37 #include <net/if.h>
38 #include <linux/if_tunnel.h>
39 #include <net/if_arp.h>
40 #include <net/if_packet.h>
41 #include <net/route.h>
42 #include <netinet/in.h>
43 #include <poll.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47
48 #include "coverage.h"
49 #include "dynamic-string.h"
50 #include "fatal-signal.h"
51 #include "hash.h"
52 #include "hmap.h"
53 #include "netdev-provider.h"
54 #include "netdev-vport.h"
55 #include "netlink.h"
56 #include "netlink-socket.h"
57 #include "ofpbuf.h"
58 #include "openflow/openflow.h"
59 #include "packets.h"
60 #include "poll-loop.h"
61 #include "rtnetlink.h"
62 #include "rtnetlink-link.h"
63 #include "socket-util.h"
64 #include "shash.h"
65 #include "svec.h"
66 #include "vlog.h"
67
68 VLOG_DEFINE_THIS_MODULE(netdev_linux);
69
70 COVERAGE_DEFINE(netdev_get_vlan_vid);
71 COVERAGE_DEFINE(netdev_set_policing);
72 COVERAGE_DEFINE(netdev_arp_lookup);
73 COVERAGE_DEFINE(netdev_get_ifindex);
74 COVERAGE_DEFINE(netdev_get_hwaddr);
75 COVERAGE_DEFINE(netdev_set_hwaddr);
76 COVERAGE_DEFINE(netdev_ethtool);
77 \f
78 /* These were introduced in Linux 2.6.14, so they might be missing if we have
79  * old headers. */
80 #ifndef ADVERTISED_Pause
81 #define ADVERTISED_Pause                (1 << 13)
82 #endif
83 #ifndef ADVERTISED_Asym_Pause
84 #define ADVERTISED_Asym_Pause           (1 << 14)
85 #endif
86
87 /* This was introduced in Linux 2.6.25, so it might be missing if we have old
88  * headers. */
89 #ifndef TC_RTAB_SIZE
90 #define TC_RTAB_SIZE 1024
91 #endif
92
93 static struct rtnetlink_notifier netdev_linux_cache_notifier;
94 static int cache_notifier_refcount;
95
96 enum {
97     VALID_IFINDEX           = 1 << 0,
98     VALID_ETHERADDR         = 1 << 1,
99     VALID_IN4               = 1 << 2,
100     VALID_IN6               = 1 << 3,
101     VALID_MTU               = 1 << 4,
102     VALID_CARRIER           = 1 << 5,
103     VALID_IS_PSEUDO         = 1 << 6, /* Represents is_internal and is_tap. */
104     VALID_POLICING          = 1 << 7,
105     VALID_HAVE_VPORT_STATS  = 1 << 8
106 };
107
108 struct tap_state {
109     int fd;
110     bool opened;
111 };
112 \f
113 /* Traffic control. */
114
115 /* An instance of a traffic control class.  Always associated with a particular
116  * network device.
117  *
118  * Each TC implementation subclasses this with whatever additional data it
119  * needs. */
120 struct tc {
121     const struct tc_ops *ops;
122     struct hmap queues;         /* Contains "struct tc_queue"s.
123                                  * Read by generic TC layer.
124                                  * Written only by TC implementation. */
125 };
126
127 /* One traffic control queue.
128  *
129  * Each TC implementation subclasses this with whatever additional data it
130  * needs. */
131 struct tc_queue {
132     struct hmap_node hmap_node; /* In struct tc's "queues" hmap. */
133     unsigned int queue_id;      /* OpenFlow queue ID. */
134 };
135
136 /* A particular kind of traffic control.  Each implementation generally maps to
137  * one particular Linux qdisc class.
138  *
139  * The functions below return 0 if successful or a positive errno value on
140  * failure, except where otherwise noted.  All of them must be provided, except
141  * where otherwise noted. */
142 struct tc_ops {
143     /* Name used by kernel in the TCA_KIND attribute of tcmsg, e.g. "htb".
144      * This is null for tc_ops_default and tc_ops_other, for which there are no
145      * appropriate values. */
146     const char *linux_name;
147
148     /* Name used in OVS database, e.g. "linux-htb".  Must be nonnull. */
149     const char *ovs_name;
150
151     /* Number of supported OpenFlow queues, 0 for qdiscs that have no
152      * queues.  The queues are numbered 0 through n_queues - 1. */
153     unsigned int n_queues;
154
155     /* Called to install this TC class on 'netdev'.  The implementation should
156      * make the Netlink calls required to set up 'netdev' with the right qdisc
157      * and configure it according to 'details'.  The implementation may assume
158      * that the current qdisc is the default; that is, there is no need for it
159      * to delete the current qdisc before installing itself.
160      *
161      * The contents of 'details' should be documented as valid for 'ovs_name'
162      * in the "other_config" column in the "QoS" table in vswitchd/vswitch.xml
163      * (which is built as ovs-vswitchd.conf.db(8)).
164      *
165      * This function must return 0 if and only if it sets 'netdev->tc' to an
166      * initialized 'struct tc'.
167      *
168      * (This function is null for tc_ops_other, which cannot be installed.  For
169      * other TC classes it should always be nonnull.) */
170     int (*tc_install)(struct netdev *netdev, const struct shash *details);
171
172     /* Called when the netdev code determines (through a Netlink query) that
173      * this TC class's qdisc is installed on 'netdev', but we didn't install
174      * it ourselves and so don't know any of the details.
175      *
176      * 'nlmsg' is the kernel reply to a RTM_GETQDISC Netlink message for
177      * 'netdev'.  The TCA_KIND attribute of 'nlmsg' is 'linux_name'.  The
178      * implementation should parse the other attributes of 'nlmsg' as
179      * necessary to determine its configuration.  If necessary it should also
180      * use Netlink queries to determine the configuration of queues on
181      * 'netdev'.
182      *
183      * This function must return 0 if and only if it sets 'netdev->tc' to an
184      * initialized 'struct tc'. */
185     int (*tc_load)(struct netdev *netdev, struct ofpbuf *nlmsg);
186
187     /* Destroys the data structures allocated by the implementation as part of
188      * 'tc'.  (This includes destroying 'tc->queues' by calling
189      * tc_destroy(tc).
190      *
191      * The implementation should not need to perform any Netlink calls.  If
192      * desirable, the caller is responsible for deconfiguring the kernel qdisc.
193      * (But it may not be desirable.)
194      *
195      * This function may be null if 'tc' is trivial. */
196     void (*tc_destroy)(struct tc *tc);
197
198     /* Retrieves details of 'netdev->tc' configuration into 'details'.
199      *
200      * The implementation should not need to perform any Netlink calls, because
201      * the 'tc_install' or 'tc_load' that instantiated 'netdev->tc' should have
202      * cached the configuration.
203      *
204      * The contents of 'details' should be documented as valid for 'ovs_name'
205      * in the "other_config" column in the "QoS" table in vswitchd/vswitch.xml
206      * (which is built as ovs-vswitchd.conf.db(8)).
207      *
208      * This function may be null if 'tc' is not configurable.
209      */
210     int (*qdisc_get)(const struct netdev *netdev, struct shash *details);
211
212     /* Reconfigures 'netdev->tc' according to 'details', performing any
213      * required Netlink calls to complete the reconfiguration.
214      *
215      * The contents of 'details' should be documented as valid for 'ovs_name'
216      * in the "other_config" column in the "QoS" table in vswitchd/vswitch.xml
217      * (which is built as ovs-vswitchd.conf.db(8)).
218      *
219      * This function may be null if 'tc' is not configurable.
220      */
221     int (*qdisc_set)(struct netdev *, const struct shash *details);
222
223     /* Retrieves details of 'queue' on 'netdev->tc' into 'details'.  'queue' is
224      * one of the 'struct tc_queue's within 'netdev->tc->queues'.
225      *
226      * The contents of 'details' should be documented as valid for 'ovs_name'
227      * in the "other_config" column in the "Queue" table in
228      * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
229      *
230      * The implementation should not need to perform any Netlink calls, because
231      * the 'tc_install' or 'tc_load' that instantiated 'netdev->tc' should have
232      * cached the queue configuration.
233      *
234      * This function may be null if 'tc' does not have queues ('n_queues' is
235      * 0). */
236     int (*class_get)(const struct netdev *netdev, const struct tc_queue *queue,
237                      struct shash *details);
238
239     /* Configures or reconfigures 'queue_id' on 'netdev->tc' according to
240      * 'details', perfoming any required Netlink calls to complete the
241      * reconfiguration.  The caller ensures that 'queue_id' is less than
242      * 'n_queues'.
243      *
244      * The contents of 'details' should be documented as valid for 'ovs_name'
245      * in the "other_config" column in the "Queue" table in
246      * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
247      *
248      * This function may be null if 'tc' does not have queues or its queues are
249      * not configurable. */
250     int (*class_set)(struct netdev *, unsigned int queue_id,
251                      const struct shash *details);
252
253     /* Deletes 'queue' from 'netdev->tc'.  'queue' is one of the 'struct
254      * tc_queue's within 'netdev->tc->queues'.
255      *
256      * This function may be null if 'tc' does not have queues or its queues
257      * cannot be deleted. */
258     int (*class_delete)(struct netdev *, struct tc_queue *queue);
259
260     /* Obtains stats for 'queue' from 'netdev->tc'.  'queue' is one of the
261      * 'struct tc_queue's within 'netdev->tc->queues'.
262      *
263      * On success, initializes '*stats'.
264      *
265      * This function may be null if 'tc' does not have queues or if it cannot
266      * report queue statistics. */
267     int (*class_get_stats)(const struct netdev *netdev,
268                            const struct tc_queue *queue,
269                            struct netdev_queue_stats *stats);
270
271     /* Extracts queue stats from 'nlmsg', which is a response to a
272      * RTM_GETTCLASS message, and passes them to 'cb' along with 'aux'.
273      *
274      * This function may be null if 'tc' does not have queues or if it cannot
275      * report queue statistics. */
276     int (*class_dump_stats)(const struct netdev *netdev,
277                             const struct ofpbuf *nlmsg,
278                             netdev_dump_queue_stats_cb *cb, void *aux);
279 };
280
281 static void
282 tc_init(struct tc *tc, const struct tc_ops *ops)
283 {
284     tc->ops = ops;
285     hmap_init(&tc->queues);
286 }
287
288 static void
289 tc_destroy(struct tc *tc)
290 {
291     hmap_destroy(&tc->queues);
292 }
293
294 static const struct tc_ops tc_ops_htb;
295 static const struct tc_ops tc_ops_hfsc;
296 static const struct tc_ops tc_ops_default;
297 static const struct tc_ops tc_ops_other;
298
299 static const struct tc_ops *tcs[] = {
300     &tc_ops_htb,                /* Hierarchy token bucket (see tc-htb(8)). */
301     &tc_ops_hfsc,               /* Hierarchical fair service curve. */
302     &tc_ops_default,            /* Default qdisc (see tc-pfifo_fast(8)). */
303     &tc_ops_other,              /* Some other qdisc. */
304     NULL
305 };
306
307 static unsigned int tc_make_handle(unsigned int major, unsigned int minor);
308 static unsigned int tc_get_major(unsigned int handle);
309 static unsigned int tc_get_minor(unsigned int handle);
310
311 static unsigned int tc_ticks_to_bytes(unsigned int rate, unsigned int ticks);
312 static unsigned int tc_bytes_to_ticks(unsigned int rate, unsigned int size);
313 static unsigned int tc_buffer_per_jiffy(unsigned int rate);
314
315 static struct tcmsg *tc_make_request(const struct netdev *, int type,
316                                      unsigned int flags, struct ofpbuf *);
317 static int tc_transact(struct ofpbuf *request, struct ofpbuf **replyp);
318
319 static int tc_parse_qdisc(const struct ofpbuf *, const char **kind,
320                           struct nlattr **options);
321 static int tc_parse_class(const struct ofpbuf *, unsigned int *queue_id,
322                           struct nlattr **options,
323                           struct netdev_queue_stats *);
324 static int tc_query_class(const struct netdev *,
325                           unsigned int handle, unsigned int parent,
326                           struct ofpbuf **replyp);
327 static int tc_delete_class(const struct netdev *, unsigned int handle);
328
329 static int tc_del_qdisc(struct netdev *netdev);
330 static int tc_query_qdisc(const struct netdev *netdev);
331
332 static int tc_calc_cell_log(unsigned int mtu);
333 static void tc_fill_rate(struct tc_ratespec *rate, uint64_t bps, int mtu);
334 static void tc_put_rtab(struct ofpbuf *, uint16_t type,
335                         const struct tc_ratespec *rate);
336 static int tc_calc_buffer(unsigned int Bps, int mtu, uint64_t burst_bytes);
337 \f
338 struct netdev_dev_linux {
339     struct netdev_dev netdev_dev;
340
341     struct shash_node *shash_node;
342     unsigned int cache_valid;
343
344     /* The following are figured out "on demand" only.  They are only valid
345      * when the corresponding VALID_* bit in 'cache_valid' is set. */
346     int ifindex;
347     uint8_t etheraddr[ETH_ADDR_LEN];
348     struct in_addr address, netmask;
349     struct in6_addr in6;
350     int mtu;
351     int carrier;
352     bool is_internal;           /* Is this an openvswitch internal device? */
353     bool is_tap;                /* Is this a tuntap device? */
354     uint32_t kbits_rate;        /* Policing data. */
355     uint32_t kbits_burst;
356     bool have_vport_stats;
357     struct tc *tc;
358
359     union {
360         struct tap_state tap;
361     } state;
362 };
363
364 struct netdev_linux {
365     struct netdev netdev;
366     int fd;
367 };
368
369 /* An AF_INET socket (used for ioctl operations). */
370 static int af_inet_sock = -1;
371
372 /* A Netlink routing socket that is not subscribed to any multicast groups. */
373 static struct nl_sock *rtnl_sock;
374
375 struct netdev_linux_notifier {
376     struct netdev_notifier notifier;
377     struct list node;
378 };
379
380 static struct shash netdev_linux_notifiers =
381     SHASH_INITIALIZER(&netdev_linux_notifiers);
382 static struct rtnetlink_notifier netdev_linux_poll_notifier;
383
384 /* This is set pretty low because we probably won't learn anything from the
385  * additional log messages. */
386 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
387
388 static int netdev_linux_init(void);
389
390 static int netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *,
391                                    int cmd, const char *cmd_name);
392 static int netdev_linux_do_ioctl(const char *name, struct ifreq *, int cmd,
393                                  const char *cmd_name);
394 static int netdev_linux_get_ipv4(const struct netdev *, struct in_addr *,
395                                  int cmd, const char *cmd_name);
396 static int get_flags(const struct netdev *, int *flagsp);
397 static int set_flags(struct netdev *, int flags);
398 static int do_get_ifindex(const char *netdev_name);
399 static int get_ifindex(const struct netdev *, int *ifindexp);
400 static int do_set_addr(struct netdev *netdev,
401                        int ioctl_nr, const char *ioctl_name,
402                        struct in_addr addr);
403 static int get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN]);
404 static int set_etheraddr(const char *netdev_name, int hwaddr_family,
405                          const uint8_t[ETH_ADDR_LEN]);
406 static int get_stats_via_netlink(int ifindex, struct netdev_stats *stats);
407 static int get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats);
408
409 static bool
410 is_netdev_linux_class(const struct netdev_class *netdev_class)
411 {
412     return netdev_class->init == netdev_linux_init;
413 }
414
415 static struct netdev_dev_linux *
416 netdev_dev_linux_cast(const struct netdev_dev *netdev_dev)
417 {
418     const struct netdev_class *netdev_class = netdev_dev_get_class(netdev_dev);
419     assert(is_netdev_linux_class(netdev_class));
420
421     return CONTAINER_OF(netdev_dev, struct netdev_dev_linux, netdev_dev);
422 }
423
424 static struct netdev_linux *
425 netdev_linux_cast(const struct netdev *netdev)
426 {
427     struct netdev_dev *netdev_dev = netdev_get_dev(netdev);
428     const struct netdev_class *netdev_class = netdev_dev_get_class(netdev_dev);
429     assert(is_netdev_linux_class(netdev_class));
430
431     return CONTAINER_OF(netdev, struct netdev_linux, netdev);
432 }
433 \f
434 static int
435 netdev_linux_init(void)
436 {
437     static int status = -1;
438     if (status < 0) {
439         /* Create AF_INET socket. */
440         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
441         status = af_inet_sock >= 0 ? 0 : errno;
442         if (status) {
443             VLOG_ERR("failed to create inet socket: %s", strerror(status));
444         }
445
446         /* Create rtnetlink socket. */
447         if (!status) {
448             status = nl_sock_create(NETLINK_ROUTE, 0, 0, 0, &rtnl_sock);
449             if (status) {
450                 VLOG_ERR_RL(&rl, "failed to create rtnetlink socket: %s",
451                             strerror(status));
452             }
453         }
454     }
455     return status;
456 }
457
458 static void
459 netdev_linux_run(void)
460 {
461     rtnetlink_link_notifier_run();
462 }
463
464 static void
465 netdev_linux_wait(void)
466 {
467     rtnetlink_link_notifier_wait();
468 }
469
470 static void
471 netdev_linux_cache_cb(const struct rtnetlink_link_change *change,
472                       void *aux OVS_UNUSED)
473 {
474     struct netdev_dev_linux *dev;
475     if (change) {
476         struct netdev_dev *base_dev = netdev_dev_from_name(change->ifname);
477         if (base_dev) {
478             const struct netdev_class *netdev_class =
479                                                 netdev_dev_get_class(base_dev);
480
481             if (is_netdev_linux_class(netdev_class)) {
482                 dev = netdev_dev_linux_cast(base_dev);
483                 dev->cache_valid = 0;
484             }
485         }
486     } else {
487         struct shash device_shash;
488         struct shash_node *node;
489
490         shash_init(&device_shash);
491         netdev_dev_get_devices(&netdev_linux_class, &device_shash);
492         SHASH_FOR_EACH (node, &device_shash) {
493             dev = node->data;
494             dev->cache_valid = 0;
495         }
496         shash_destroy(&device_shash);
497     }
498 }
499
500 /* Creates system and internal devices. */
501 static int
502 netdev_linux_create(const struct netdev_class *class,
503                            const char *name, const struct shash *args,
504                            struct netdev_dev **netdev_devp)
505 {
506     struct netdev_dev_linux *netdev_dev;
507     int error;
508
509     if (!shash_is_empty(args)) {
510         VLOG_WARN("%s: arguments for %s devices should be empty",
511                   name, class->type);
512     }
513
514     if (!cache_notifier_refcount) {
515         error = rtnetlink_link_notifier_register(&netdev_linux_cache_notifier,
516                                                  netdev_linux_cache_cb, NULL);
517         if (error) {
518             return error;
519         }
520     }
521     cache_notifier_refcount++;
522
523     netdev_dev = xzalloc(sizeof *netdev_dev);
524     netdev_dev_init(&netdev_dev->netdev_dev, name, class);
525
526     *netdev_devp = &netdev_dev->netdev_dev;
527     return 0;
528 }
529
530 /* For most types of netdevs we open the device for each call of
531  * netdev_open().  However, this is not the case with tap devices,
532  * since it is only possible to open the device once.  In this
533  * situation we share a single file descriptor, and consequently
534  * buffers, across all readers.  Therefore once data is read it will
535  * be unavailable to other reads for tap devices. */
536 static int
537 netdev_linux_create_tap(const struct netdev_class *class OVS_UNUSED,
538                         const char *name, const struct shash *args,
539                         struct netdev_dev **netdev_devp)
540 {
541     struct netdev_dev_linux *netdev_dev;
542     struct tap_state *state;
543     static const char tap_dev[] = "/dev/net/tun";
544     struct ifreq ifr;
545     int error;
546
547     if (!shash_is_empty(args)) {
548         VLOG_WARN("%s: arguments for TAP devices should be empty", name);
549     }
550
551     netdev_dev = xzalloc(sizeof *netdev_dev);
552     state = &netdev_dev->state.tap;
553
554     /* Open tap device. */
555     state->fd = open(tap_dev, O_RDWR);
556     if (state->fd < 0) {
557         error = errno;
558         VLOG_WARN("opening \"%s\" failed: %s", tap_dev, strerror(error));
559         goto error;
560     }
561
562     /* Create tap device. */
563     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
564     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
565     if (ioctl(state->fd, TUNSETIFF, &ifr) == -1) {
566         VLOG_WARN("%s: creating tap device failed: %s", name,
567                   strerror(errno));
568         error = errno;
569         goto error;
570     }
571
572     /* Make non-blocking. */
573     error = set_nonblocking(state->fd);
574     if (error) {
575         goto error;
576     }
577
578     netdev_dev_init(&netdev_dev->netdev_dev, name, &netdev_tap_class);
579     *netdev_devp = &netdev_dev->netdev_dev;
580     return 0;
581
582 error:
583     free(netdev_dev);
584     return error;
585 }
586
587 static void
588 destroy_tap(struct netdev_dev_linux *netdev_dev)
589 {
590     struct tap_state *state = &netdev_dev->state.tap;
591
592     if (state->fd >= 0) {
593         close(state->fd);
594     }
595 }
596
597 /* Destroys the netdev device 'netdev_dev_'. */
598 static void
599 netdev_linux_destroy(struct netdev_dev *netdev_dev_)
600 {
601     struct netdev_dev_linux *netdev_dev = netdev_dev_linux_cast(netdev_dev_);
602     const struct netdev_class *class = netdev_dev_get_class(netdev_dev_);
603
604     if (netdev_dev->tc && netdev_dev->tc->ops->tc_destroy) {
605         netdev_dev->tc->ops->tc_destroy(netdev_dev->tc);
606     }
607
608     if (class == &netdev_linux_class || class == &netdev_internal_class) {
609         cache_notifier_refcount--;
610
611         if (!cache_notifier_refcount) {
612             rtnetlink_link_notifier_unregister(&netdev_linux_cache_notifier);
613         }
614     } else if (class == &netdev_tap_class) {
615         destroy_tap(netdev_dev);
616     } else {
617         NOT_REACHED();
618     }
619
620     free(netdev_dev);
621 }
622
623 static int
624 netdev_linux_open(struct netdev_dev *netdev_dev_, int ethertype,
625                   struct netdev **netdevp)
626 {
627     struct netdev_dev_linux *netdev_dev = netdev_dev_linux_cast(netdev_dev_);
628     struct netdev_linux *netdev;
629     enum netdev_flags flags;
630     int error;
631
632     /* Allocate network device. */
633     netdev = xzalloc(sizeof *netdev);
634     netdev->fd = -1;
635     netdev_init(&netdev->netdev, netdev_dev_);
636
637     /* Verify that the device really exists, by attempting to read its flags.
638      * (The flags might be cached, in which case this won't actually do an
639      * ioctl.)
640      *
641      * Don't do this for "internal" netdevs, though, because those have to be
642      * created as netdev objects before they exist in the kernel, because
643      * creating them in the kernel happens by passing a netdev object to
644      * dpif_port_add(). */
645     if (netdev_dev_get_class(netdev_dev_) != &netdev_internal_class) {
646         error = netdev_get_flags(&netdev->netdev, &flags);
647         if (error == ENODEV) {
648             goto error;
649         }
650     }
651
652     if (!strcmp(netdev_dev_get_type(netdev_dev_), "tap") &&
653         !netdev_dev->state.tap.opened) {
654
655         /* We assume that the first user of the tap device is the primary user
656          * and give them the tap FD.  Subsequent users probably just expect
657          * this to be a system device so open it normally to avoid send/receive
658          * directions appearing to be reversed. */
659         netdev->fd = netdev_dev->state.tap.fd;
660         netdev_dev->state.tap.opened = true;
661     } else if (ethertype != NETDEV_ETH_TYPE_NONE) {
662         struct sockaddr_ll sll;
663         int protocol;
664         int ifindex;
665
666         /* Create file descriptor. */
667         protocol = (ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
668                     : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
669                     : ethertype);
670         netdev->fd = socket(PF_PACKET, SOCK_RAW, htons(protocol));
671         if (netdev->fd < 0) {
672             error = errno;
673             goto error;
674         }
675
676         /* Set non-blocking mode. */
677         error = set_nonblocking(netdev->fd);
678         if (error) {
679             goto error;
680         }
681
682         /* Get ethernet device index. */
683         error = get_ifindex(&netdev->netdev, &ifindex);
684         if (error) {
685             goto error;
686         }
687
688         /* Bind to specific ethernet device. */
689         memset(&sll, 0, sizeof sll);
690         sll.sll_family = AF_PACKET;
691         sll.sll_ifindex = ifindex;
692         if (bind(netdev->fd,
693                  (struct sockaddr *) &sll, sizeof sll) < 0) {
694             error = errno;
695             VLOG_ERR("bind to %s failed: %s", netdev_dev_get_name(netdev_dev_),
696                      strerror(error));
697             goto error;
698         }
699
700         /* Between the socket() and bind() calls above, the socket receives all
701          * packets of the requested type on all system interfaces.  We do not
702          * want to receive that data, but there is no way to avoid it.  So we
703          * must now drain out the receive queue. */
704         error = drain_rcvbuf(netdev->fd);
705         if (error) {
706             goto error;
707         }
708     }
709
710     *netdevp = &netdev->netdev;
711     return 0;
712
713 error:
714     netdev_uninit(&netdev->netdev, true);
715     return error;
716 }
717
718 /* Closes and destroys 'netdev'. */
719 static void
720 netdev_linux_close(struct netdev *netdev_)
721 {
722     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
723
724     if (netdev->fd > 0 && strcmp(netdev_get_type(netdev_), "tap")) {
725         close(netdev->fd);
726     }
727     free(netdev);
728 }
729
730 /* Initializes 'svec' with a list of the names of all known network devices. */
731 static int
732 netdev_linux_enumerate(struct svec *svec)
733 {
734     struct if_nameindex *names;
735
736     names = if_nameindex();
737     if (names) {
738         size_t i;
739
740         for (i = 0; names[i].if_name != NULL; i++) {
741             svec_add(svec, names[i].if_name);
742         }
743         if_freenameindex(names);
744         return 0;
745     } else {
746         VLOG_WARN("could not obtain list of network device names: %s",
747                   strerror(errno));
748         return errno;
749     }
750 }
751
752 static int
753 netdev_linux_recv(struct netdev *netdev_, void *data, size_t size)
754 {
755     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
756
757     if (netdev->fd < 0) {
758         /* Device was opened with NETDEV_ETH_TYPE_NONE. */
759         return -EAGAIN;
760     }
761
762     for (;;) {
763         ssize_t retval = read(netdev->fd, data, size);
764         if (retval >= 0) {
765             return retval;
766         } else if (errno != EINTR) {
767             if (errno != EAGAIN) {
768                 VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
769                              strerror(errno), netdev_get_name(netdev_));
770             }
771             return -errno;
772         }
773     }
774 }
775
776 /* Registers with the poll loop to wake up from the next call to poll_block()
777  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
778 static void
779 netdev_linux_recv_wait(struct netdev *netdev_)
780 {
781     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
782     if (netdev->fd >= 0) {
783         poll_fd_wait(netdev->fd, POLLIN);
784     }
785 }
786
787 /* Discards all packets waiting to be received from 'netdev'. */
788 static int
789 netdev_linux_drain(struct netdev *netdev_)
790 {
791     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
792     if (netdev->fd < 0) {
793         return 0;
794     } else if (!strcmp(netdev_get_type(netdev_), "tap")) {
795         struct ifreq ifr;
796         int error = netdev_linux_do_ioctl(netdev_get_name(netdev_), &ifr,
797                                           SIOCGIFTXQLEN, "SIOCGIFTXQLEN");
798         if (error) {
799             return error;
800         }
801         drain_fd(netdev->fd, ifr.ifr_qlen);
802         return 0;
803     } else {
804         return drain_rcvbuf(netdev->fd);
805     }
806 }
807
808 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
809  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
810  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
811  * the packet is too big or too small to transmit on the device.
812  *
813  * The caller retains ownership of 'buffer' in all cases.
814  *
815  * The kernel maintains a packet transmission queue, so the caller is not
816  * expected to do additional queuing of packets. */
817 static int
818 netdev_linux_send(struct netdev *netdev_, const void *data, size_t size)
819 {
820     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
821
822     /* XXX should support sending even if 'ethertype' was NETDEV_ETH_TYPE_NONE.
823      */
824     if (netdev->fd < 0) {
825         return EPIPE;
826     }
827
828     for (;;) {
829         ssize_t retval = write(netdev->fd, data, size);
830         if (retval < 0) {
831             /* The Linux AF_PACKET implementation never blocks waiting for room
832              * for packets, instead returning ENOBUFS.  Translate this into
833              * EAGAIN for the caller. */
834             if (errno == ENOBUFS) {
835                 return EAGAIN;
836             } else if (errno == EINTR) {
837                 continue;
838             } else if (errno != EAGAIN) {
839                 VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: %s",
840                              netdev_get_name(netdev_), strerror(errno));
841             }
842             return errno;
843         } else if (retval != size) {
844             VLOG_WARN_RL(&rl, "sent partial Ethernet packet (%zd bytes of "
845                          "%zu) on %s", retval, size, netdev_get_name(netdev_));
846             return EMSGSIZE;
847         } else {
848             return 0;
849         }
850     }
851 }
852
853 /* Registers with the poll loop to wake up from the next call to poll_block()
854  * when the packet transmission queue has sufficient room to transmit a packet
855  * with netdev_send().
856  *
857  * The kernel maintains a packet transmission queue, so the client is not
858  * expected to do additional queuing of packets.  Thus, this function is
859  * unlikely to ever be used.  It is included for completeness. */
860 static void
861 netdev_linux_send_wait(struct netdev *netdev_)
862 {
863     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
864     if (netdev->fd < 0) {
865         /* Nothing to do. */
866     } else if (strcmp(netdev_get_type(netdev_), "tap")) {
867         poll_fd_wait(netdev->fd, POLLOUT);
868     } else {
869         /* TAP device always accepts packets.*/
870         poll_immediate_wake();
871     }
872 }
873
874 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
875  * otherwise a positive errno value. */
876 static int
877 netdev_linux_set_etheraddr(struct netdev *netdev_,
878                            const uint8_t mac[ETH_ADDR_LEN])
879 {
880     struct netdev_dev_linux *netdev_dev =
881                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
882     int error;
883
884     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)
885         || !eth_addr_equals(netdev_dev->etheraddr, mac)) {
886         error = set_etheraddr(netdev_get_name(netdev_), ARPHRD_ETHER, mac);
887         if (!error) {
888             netdev_dev->cache_valid |= VALID_ETHERADDR;
889             memcpy(netdev_dev->etheraddr, mac, ETH_ADDR_LEN);
890         }
891     } else {
892         error = 0;
893     }
894     return error;
895 }
896
897 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
898  * free the returned buffer. */
899 static int
900 netdev_linux_get_etheraddr(const struct netdev *netdev_,
901                            uint8_t mac[ETH_ADDR_LEN])
902 {
903     struct netdev_dev_linux *netdev_dev =
904                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
905     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)) {
906         int error = get_etheraddr(netdev_get_name(netdev_),
907                                   netdev_dev->etheraddr);
908         if (error) {
909             return error;
910         }
911         netdev_dev->cache_valid |= VALID_ETHERADDR;
912     }
913     memcpy(mac, netdev_dev->etheraddr, ETH_ADDR_LEN);
914     return 0;
915 }
916
917 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
918  * in bytes, not including the hardware header; thus, this is typically 1500
919  * bytes for Ethernet devices. */
920 static int
921 netdev_linux_get_mtu(const struct netdev *netdev_, int *mtup)
922 {
923     struct netdev_dev_linux *netdev_dev =
924                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
925     if (!(netdev_dev->cache_valid & VALID_MTU)) {
926         struct ifreq ifr;
927         int error;
928
929         error = netdev_linux_do_ioctl(netdev_get_name(netdev_), &ifr,
930                                       SIOCGIFMTU, "SIOCGIFMTU");
931         if (error) {
932             return error;
933         }
934         netdev_dev->mtu = ifr.ifr_mtu;
935         netdev_dev->cache_valid |= VALID_MTU;
936     }
937     *mtup = netdev_dev->mtu;
938     return 0;
939 }
940
941 /* Returns the ifindex of 'netdev', if successful, as a positive number.
942  * On failure, returns a negative errno value. */
943 static int
944 netdev_linux_get_ifindex(const struct netdev *netdev)
945 {
946     int ifindex, error;
947
948     error = get_ifindex(netdev, &ifindex);
949     return error ? -error : ifindex;
950 }
951
952 static int
953 netdev_linux_get_carrier(const struct netdev *netdev_, bool *carrier)
954 {
955     struct netdev_dev_linux *netdev_dev =
956                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
957     int error = 0;
958     char *fn = NULL;
959     int fd = -1;
960
961     if (!(netdev_dev->cache_valid & VALID_CARRIER)) {
962         char line[8];
963         int retval;
964
965         fn = xasprintf("/sys/class/net/%s/carrier",
966                        netdev_get_name(netdev_));
967         fd = open(fn, O_RDONLY);
968         if (fd < 0) {
969             error = errno;
970             VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(error));
971             goto exit;
972         }
973
974         retval = read(fd, line, sizeof line);
975         if (retval < 0) {
976             error = errno;
977             if (error == EINVAL) {
978                 /* This is the normal return value when we try to check carrier
979                  * if the network device is not up. */
980             } else {
981                 VLOG_WARN_RL(&rl, "%s: read failed: %s", fn, strerror(error));
982             }
983             goto exit;
984         } else if (retval == 0) {
985             error = EPROTO;
986             VLOG_WARN_RL(&rl, "%s: unexpected end of file", fn);
987             goto exit;
988         }
989
990         if (line[0] != '0' && line[0] != '1') {
991             error = EPROTO;
992             VLOG_WARN_RL(&rl, "%s: value is %c (expected 0 or 1)",
993                          fn, line[0]);
994             goto exit;
995         }
996         netdev_dev->carrier = line[0] != '0';
997         netdev_dev->cache_valid |= VALID_CARRIER;
998     }
999     *carrier = netdev_dev->carrier;
1000     error = 0;
1001
1002 exit:
1003     if (fd >= 0) {
1004         close(fd);
1005     }
1006     free(fn);
1007     return error;
1008 }
1009
1010 /* Check whether we can we use RTM_GETLINK to get network device statistics.
1011  * In pre-2.6.19 kernels, this was only available if wireless extensions were
1012  * enabled. */
1013 static bool
1014 check_for_working_netlink_stats(void)
1015 {
1016     /* Decide on the netdev_get_stats() implementation to use.  Netlink is
1017      * preferable, so if that works, we'll use it. */
1018     int ifindex = do_get_ifindex("lo");
1019     if (ifindex < 0) {
1020         VLOG_WARN("failed to get ifindex for lo, "
1021                   "obtaining netdev stats from proc");
1022         return false;
1023     } else {
1024         struct netdev_stats stats;
1025         int error = get_stats_via_netlink(ifindex, &stats);
1026         if (!error) {
1027             VLOG_DBG("obtaining netdev stats via rtnetlink");
1028             return true;
1029         } else {
1030             VLOG_INFO("RTM_GETLINK failed (%s), obtaining netdev stats "
1031                       "via proc (you are probably running a pre-2.6.19 "
1032                       "kernel)", strerror(error));
1033             return false;
1034         }
1035     }
1036 }
1037
1038 /* Brings the 'is_internal' and 'is_tap' members of 'netdev_dev' up-to-date. */
1039 static void
1040 netdev_linux_update_is_pseudo(struct netdev_dev_linux *netdev_dev)
1041 {
1042     if (!(netdev_dev->cache_valid & VALID_IS_PSEUDO)) {
1043         const char *name = netdev_dev_get_name(&netdev_dev->netdev_dev);
1044         const char *type = netdev_dev_get_type(&netdev_dev->netdev_dev);
1045
1046         netdev_dev->is_tap = !strcmp(type, "tap");
1047         netdev_dev->is_internal = false;
1048         if (!netdev_dev->is_tap) {
1049             struct ethtool_drvinfo drvinfo;
1050             int error;
1051
1052             memset(&drvinfo, 0, sizeof drvinfo);
1053             error = netdev_linux_do_ethtool(name,
1054                                             (struct ethtool_cmd *)&drvinfo,
1055                                             ETHTOOL_GDRVINFO,
1056                                             "ETHTOOL_GDRVINFO");
1057
1058             if (!error && !strcmp(drvinfo.driver, "openvswitch")) {
1059                 netdev_dev->is_internal = true;
1060             }
1061         }
1062
1063         netdev_dev->cache_valid |= VALID_IS_PSEUDO;
1064     }
1065 }
1066
1067 static void
1068 swap_uint64(uint64_t *a, uint64_t *b)
1069 {
1070     *a ^= *b;
1071     *b ^= *a;
1072     *a ^= *b;
1073 }
1074
1075 /* Retrieves current device stats for 'netdev'. */
1076 static int
1077 netdev_linux_get_stats(const struct netdev *netdev_,
1078                        struct netdev_stats *stats)
1079 {
1080     struct netdev_dev_linux *netdev_dev =
1081                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1082     static int use_netlink_stats = -1;
1083     int error;
1084
1085     if (netdev_dev->have_vport_stats ||
1086         !(netdev_dev->cache_valid & VALID_HAVE_VPORT_STATS)) {
1087
1088         error = netdev_vport_get_stats(netdev_, stats);
1089         netdev_dev->have_vport_stats = !error;
1090         netdev_dev->cache_valid |= VALID_HAVE_VPORT_STATS;
1091     }
1092
1093     if (!netdev_dev->have_vport_stats) {
1094         if (use_netlink_stats < 0) {
1095             use_netlink_stats = check_for_working_netlink_stats();
1096         }
1097         if (use_netlink_stats) {
1098             int ifindex;
1099
1100             error = get_ifindex(netdev_, &ifindex);
1101             if (!error) {
1102                 error = get_stats_via_netlink(ifindex, stats);
1103             }
1104         } else {
1105             error = get_stats_via_proc(netdev_get_name(netdev_), stats);
1106         }
1107     }
1108
1109     /* If this port is an internal port then the transmit and receive stats
1110      * will appear to be swapped relative to the other ports since we are the
1111      * one sending the data, not a remote computer.  For consistency, we swap
1112      * them back here. This does not apply if we are getting stats from the
1113      * vport layer because it always tracks stats from the perspective of the
1114      * switch. */
1115     netdev_linux_update_is_pseudo(netdev_dev);
1116     if (!error && !netdev_dev->have_vport_stats &&
1117         (netdev_dev->is_internal || netdev_dev->is_tap)) {
1118         swap_uint64(&stats->rx_packets, &stats->tx_packets);
1119         swap_uint64(&stats->rx_bytes, &stats->tx_bytes);
1120         swap_uint64(&stats->rx_errors, &stats->tx_errors);
1121         swap_uint64(&stats->rx_dropped, &stats->tx_dropped);
1122         stats->rx_length_errors = 0;
1123         stats->rx_over_errors = 0;
1124         stats->rx_crc_errors = 0;
1125         stats->rx_frame_errors = 0;
1126         stats->rx_fifo_errors = 0;
1127         stats->rx_missed_errors = 0;
1128         stats->tx_aborted_errors = 0;
1129         stats->tx_carrier_errors = 0;
1130         stats->tx_fifo_errors = 0;
1131         stats->tx_heartbeat_errors = 0;
1132         stats->tx_window_errors = 0;
1133     }
1134
1135     return error;
1136 }
1137
1138 /* Stores the features supported by 'netdev' into each of '*current',
1139  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
1140  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
1141  * successful, otherwise a positive errno value. */
1142 static int
1143 netdev_linux_get_features(struct netdev *netdev,
1144                           uint32_t *current, uint32_t *advertised,
1145                           uint32_t *supported, uint32_t *peer)
1146 {
1147     struct ethtool_cmd ecmd;
1148     int error;
1149
1150     memset(&ecmd, 0, sizeof ecmd);
1151     error = netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1152                                     ETHTOOL_GSET, "ETHTOOL_GSET");
1153     if (error) {
1154         return error;
1155     }
1156
1157     /* Supported features. */
1158     *supported = 0;
1159     if (ecmd.supported & SUPPORTED_10baseT_Half) {
1160         *supported |= OFPPF_10MB_HD;
1161     }
1162     if (ecmd.supported & SUPPORTED_10baseT_Full) {
1163         *supported |= OFPPF_10MB_FD;
1164     }
1165     if (ecmd.supported & SUPPORTED_100baseT_Half)  {
1166         *supported |= OFPPF_100MB_HD;
1167     }
1168     if (ecmd.supported & SUPPORTED_100baseT_Full) {
1169         *supported |= OFPPF_100MB_FD;
1170     }
1171     if (ecmd.supported & SUPPORTED_1000baseT_Half) {
1172         *supported |= OFPPF_1GB_HD;
1173     }
1174     if (ecmd.supported & SUPPORTED_1000baseT_Full) {
1175         *supported |= OFPPF_1GB_FD;
1176     }
1177     if (ecmd.supported & SUPPORTED_10000baseT_Full) {
1178         *supported |= OFPPF_10GB_FD;
1179     }
1180     if (ecmd.supported & SUPPORTED_TP) {
1181         *supported |= OFPPF_COPPER;
1182     }
1183     if (ecmd.supported & SUPPORTED_FIBRE) {
1184         *supported |= OFPPF_FIBER;
1185     }
1186     if (ecmd.supported & SUPPORTED_Autoneg) {
1187         *supported |= OFPPF_AUTONEG;
1188     }
1189     if (ecmd.supported & SUPPORTED_Pause) {
1190         *supported |= OFPPF_PAUSE;
1191     }
1192     if (ecmd.supported & SUPPORTED_Asym_Pause) {
1193         *supported |= OFPPF_PAUSE_ASYM;
1194     }
1195
1196     /* Advertised features. */
1197     *advertised = 0;
1198     if (ecmd.advertising & ADVERTISED_10baseT_Half) {
1199         *advertised |= OFPPF_10MB_HD;
1200     }
1201     if (ecmd.advertising & ADVERTISED_10baseT_Full) {
1202         *advertised |= OFPPF_10MB_FD;
1203     }
1204     if (ecmd.advertising & ADVERTISED_100baseT_Half) {
1205         *advertised |= OFPPF_100MB_HD;
1206     }
1207     if (ecmd.advertising & ADVERTISED_100baseT_Full) {
1208         *advertised |= OFPPF_100MB_FD;
1209     }
1210     if (ecmd.advertising & ADVERTISED_1000baseT_Half) {
1211         *advertised |= OFPPF_1GB_HD;
1212     }
1213     if (ecmd.advertising & ADVERTISED_1000baseT_Full) {
1214         *advertised |= OFPPF_1GB_FD;
1215     }
1216     if (ecmd.advertising & ADVERTISED_10000baseT_Full) {
1217         *advertised |= OFPPF_10GB_FD;
1218     }
1219     if (ecmd.advertising & ADVERTISED_TP) {
1220         *advertised |= OFPPF_COPPER;
1221     }
1222     if (ecmd.advertising & ADVERTISED_FIBRE) {
1223         *advertised |= OFPPF_FIBER;
1224     }
1225     if (ecmd.advertising & ADVERTISED_Autoneg) {
1226         *advertised |= OFPPF_AUTONEG;
1227     }
1228     if (ecmd.advertising & ADVERTISED_Pause) {
1229         *advertised |= OFPPF_PAUSE;
1230     }
1231     if (ecmd.advertising & ADVERTISED_Asym_Pause) {
1232         *advertised |= OFPPF_PAUSE_ASYM;
1233     }
1234
1235     /* Current settings. */
1236     if (ecmd.speed == SPEED_10) {
1237         *current = ecmd.duplex ? OFPPF_10MB_FD : OFPPF_10MB_HD;
1238     } else if (ecmd.speed == SPEED_100) {
1239         *current = ecmd.duplex ? OFPPF_100MB_FD : OFPPF_100MB_HD;
1240     } else if (ecmd.speed == SPEED_1000) {
1241         *current = ecmd.duplex ? OFPPF_1GB_FD : OFPPF_1GB_HD;
1242     } else if (ecmd.speed == SPEED_10000) {
1243         *current = OFPPF_10GB_FD;
1244     } else {
1245         *current = 0;
1246     }
1247
1248     if (ecmd.port == PORT_TP) {
1249         *current |= OFPPF_COPPER;
1250     } else if (ecmd.port == PORT_FIBRE) {
1251         *current |= OFPPF_FIBER;
1252     }
1253
1254     if (ecmd.autoneg) {
1255         *current |= OFPPF_AUTONEG;
1256     }
1257
1258     /* Peer advertisements. */
1259     *peer = 0;                  /* XXX */
1260
1261     return 0;
1262 }
1263
1264 /* Set the features advertised by 'netdev' to 'advertise'. */
1265 static int
1266 netdev_linux_set_advertisements(struct netdev *netdev, uint32_t advertise)
1267 {
1268     struct ethtool_cmd ecmd;
1269     int error;
1270
1271     memset(&ecmd, 0, sizeof ecmd);
1272     error = netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1273                                     ETHTOOL_GSET, "ETHTOOL_GSET");
1274     if (error) {
1275         return error;
1276     }
1277
1278     ecmd.advertising = 0;
1279     if (advertise & OFPPF_10MB_HD) {
1280         ecmd.advertising |= ADVERTISED_10baseT_Half;
1281     }
1282     if (advertise & OFPPF_10MB_FD) {
1283         ecmd.advertising |= ADVERTISED_10baseT_Full;
1284     }
1285     if (advertise & OFPPF_100MB_HD) {
1286         ecmd.advertising |= ADVERTISED_100baseT_Half;
1287     }
1288     if (advertise & OFPPF_100MB_FD) {
1289         ecmd.advertising |= ADVERTISED_100baseT_Full;
1290     }
1291     if (advertise & OFPPF_1GB_HD) {
1292         ecmd.advertising |= ADVERTISED_1000baseT_Half;
1293     }
1294     if (advertise & OFPPF_1GB_FD) {
1295         ecmd.advertising |= ADVERTISED_1000baseT_Full;
1296     }
1297     if (advertise & OFPPF_10GB_FD) {
1298         ecmd.advertising |= ADVERTISED_10000baseT_Full;
1299     }
1300     if (advertise & OFPPF_COPPER) {
1301         ecmd.advertising |= ADVERTISED_TP;
1302     }
1303     if (advertise & OFPPF_FIBER) {
1304         ecmd.advertising |= ADVERTISED_FIBRE;
1305     }
1306     if (advertise & OFPPF_AUTONEG) {
1307         ecmd.advertising |= ADVERTISED_Autoneg;
1308     }
1309     if (advertise & OFPPF_PAUSE) {
1310         ecmd.advertising |= ADVERTISED_Pause;
1311     }
1312     if (advertise & OFPPF_PAUSE_ASYM) {
1313         ecmd.advertising |= ADVERTISED_Asym_Pause;
1314     }
1315     return netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1316                                    ETHTOOL_SSET, "ETHTOOL_SSET");
1317 }
1318
1319 /* If 'netdev_name' is the name of a VLAN network device (e.g. one created with
1320  * vconfig(8)), sets '*vlan_vid' to the VLAN VID associated with that device
1321  * and returns 0.  Otherwise returns a errno value (specifically ENOENT if
1322  * 'netdev_name' is the name of a network device that is not a VLAN device) and
1323  * sets '*vlan_vid' to -1. */
1324 static int
1325 netdev_linux_get_vlan_vid(const struct netdev *netdev, int *vlan_vid)
1326 {
1327     const char *netdev_name = netdev_get_name(netdev);
1328     struct ds line = DS_EMPTY_INITIALIZER;
1329     FILE *stream = NULL;
1330     int error;
1331     char *fn;
1332
1333     COVERAGE_INC(netdev_get_vlan_vid);
1334     fn = xasprintf("/proc/net/vlan/%s", netdev_name);
1335     stream = fopen(fn, "r");
1336     if (!stream) {
1337         error = errno;
1338         goto done;
1339     }
1340
1341     if (ds_get_line(&line, stream)) {
1342         if (ferror(stream)) {
1343             error = errno;
1344             VLOG_ERR_RL(&rl, "error reading \"%s\": %s", fn, strerror(errno));
1345         } else {
1346             error = EPROTO;
1347             VLOG_ERR_RL(&rl, "unexpected end of file reading \"%s\"", fn);
1348         }
1349         goto done;
1350     }
1351
1352     if (!sscanf(ds_cstr(&line), "%*s VID: %d", vlan_vid)) {
1353         error = EPROTO;
1354         VLOG_ERR_RL(&rl, "parse error reading \"%s\" line 1: \"%s\"",
1355                     fn, ds_cstr(&line));
1356         goto done;
1357     }
1358
1359     error = 0;
1360
1361 done:
1362     free(fn);
1363     if (stream) {
1364         fclose(stream);
1365     }
1366     ds_destroy(&line);
1367     if (error) {
1368         *vlan_vid = -1;
1369     }
1370     return error;
1371 }
1372
1373 #define POLICE_ADD_CMD "/sbin/tc qdisc add dev %s handle ffff: ingress"
1374 #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"
1375
1376 /* Remove ingress policing from 'netdev'.  Returns 0 if successful, otherwise a
1377  * positive errno value.
1378  *
1379  * This function is equivalent to running
1380  *     /sbin/tc qdisc del dev %s handle ffff: ingress
1381  * but it is much, much faster.
1382  */
1383 static int
1384 netdev_linux_remove_policing(struct netdev *netdev)
1385 {
1386     struct netdev_dev_linux *netdev_dev =
1387         netdev_dev_linux_cast(netdev_get_dev(netdev));
1388     const char *netdev_name = netdev_get_name(netdev);
1389
1390     struct ofpbuf request;
1391     struct tcmsg *tcmsg;
1392     int error;
1393
1394     tcmsg = tc_make_request(netdev, RTM_DELQDISC, 0, &request);
1395     if (!tcmsg) {
1396         return ENODEV;
1397     }
1398     tcmsg->tcm_handle = tc_make_handle(0xffff, 0);
1399     tcmsg->tcm_parent = TC_H_INGRESS;
1400     nl_msg_put_string(&request, TCA_KIND, "ingress");
1401     nl_msg_put_unspec(&request, TCA_OPTIONS, NULL, 0);
1402
1403     error = tc_transact(&request, NULL);
1404     if (error && error != ENOENT && error != EINVAL) {
1405         VLOG_WARN_RL(&rl, "%s: removing policing failed: %s",
1406                      netdev_name, strerror(error));
1407         return error;
1408     }
1409
1410     netdev_dev->kbits_rate = 0;
1411     netdev_dev->kbits_burst = 0;
1412     netdev_dev->cache_valid |= VALID_POLICING;
1413     return 0;
1414 }
1415
1416 /* Attempts to set input rate limiting (policing) policy. */
1417 static int
1418 netdev_linux_set_policing(struct netdev *netdev,
1419                           uint32_t kbits_rate, uint32_t kbits_burst)
1420 {
1421     struct netdev_dev_linux *netdev_dev =
1422         netdev_dev_linux_cast(netdev_get_dev(netdev));
1423     const char *netdev_name = netdev_get_name(netdev);
1424     char command[1024];
1425
1426     COVERAGE_INC(netdev_set_policing);
1427
1428     kbits_burst = (!kbits_rate ? 0       /* Force to 0 if no rate specified. */
1429                    : !kbits_burst ? 1000 /* Default to 1000 kbits if 0. */
1430                    : kbits_burst);       /* Stick with user-specified value. */
1431
1432     if (netdev_dev->cache_valid & VALID_POLICING
1433         && netdev_dev->kbits_rate == kbits_rate
1434         && netdev_dev->kbits_burst == kbits_burst) {
1435         /* Assume that settings haven't changed since we last set them. */
1436         return 0;
1437     }
1438
1439     netdev_linux_remove_policing(netdev);
1440     if (kbits_rate) {
1441         snprintf(command, sizeof(command), POLICE_ADD_CMD, netdev_name);
1442         if (system(command) != 0) {
1443             VLOG_WARN_RL(&rl, "%s: problem adding policing", netdev_name);
1444             return -1;
1445         }
1446
1447         snprintf(command, sizeof(command), POLICE_CONFIG_CMD, netdev_name,
1448                 kbits_rate, kbits_burst);
1449         if (system(command) != 0) {
1450             VLOG_WARN_RL(&rl, "%s: problem configuring policing",
1451                     netdev_name);
1452             return -1;
1453         }
1454
1455         netdev_dev->kbits_rate = kbits_rate;
1456         netdev_dev->kbits_burst = kbits_burst;
1457         netdev_dev->cache_valid |= VALID_POLICING;
1458     }
1459
1460     return 0;
1461 }
1462
1463 static int
1464 netdev_linux_get_qos_types(const struct netdev *netdev OVS_UNUSED,
1465                            struct svec *types)
1466 {
1467     const struct tc_ops **opsp;
1468
1469     for (opsp = tcs; *opsp != NULL; opsp++) {
1470         const struct tc_ops *ops = *opsp;
1471         if (ops->tc_install && ops->ovs_name[0] != '\0') {
1472             svec_add(types, ops->ovs_name);
1473         }
1474     }
1475     return 0;
1476 }
1477
1478 static const struct tc_ops *
1479 tc_lookup_ovs_name(const char *name)
1480 {
1481     const struct tc_ops **opsp;
1482
1483     for (opsp = tcs; *opsp != NULL; opsp++) {
1484         const struct tc_ops *ops = *opsp;
1485         if (!strcmp(name, ops->ovs_name)) {
1486             return ops;
1487         }
1488     }
1489     return NULL;
1490 }
1491
1492 static const struct tc_ops *
1493 tc_lookup_linux_name(const char *name)
1494 {
1495     const struct tc_ops **opsp;
1496
1497     for (opsp = tcs; *opsp != NULL; opsp++) {
1498         const struct tc_ops *ops = *opsp;
1499         if (ops->linux_name && !strcmp(name, ops->linux_name)) {
1500             return ops;
1501         }
1502     }
1503     return NULL;
1504 }
1505
1506 static struct tc_queue *
1507 tc_find_queue__(const struct netdev *netdev, unsigned int queue_id,
1508                 size_t hash)
1509 {
1510     struct netdev_dev_linux *netdev_dev =
1511                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1512     struct tc_queue *queue;
1513
1514     HMAP_FOR_EACH_IN_BUCKET (queue, hmap_node, hash, &netdev_dev->tc->queues) {
1515         if (queue->queue_id == queue_id) {
1516             return queue;
1517         }
1518     }
1519     return NULL;
1520 }
1521
1522 static struct tc_queue *
1523 tc_find_queue(const struct netdev *netdev, unsigned int queue_id)
1524 {
1525     return tc_find_queue__(netdev, queue_id, hash_int(queue_id, 0));
1526 }
1527
1528 static int
1529 netdev_linux_get_qos_capabilities(const struct netdev *netdev OVS_UNUSED,
1530                                   const char *type,
1531                                   struct netdev_qos_capabilities *caps)
1532 {
1533     const struct tc_ops *ops = tc_lookup_ovs_name(type);
1534     if (!ops) {
1535         return EOPNOTSUPP;
1536     }
1537     caps->n_queues = ops->n_queues;
1538     return 0;
1539 }
1540
1541 static int
1542 netdev_linux_get_qos(const struct netdev *netdev,
1543                      const char **typep, struct shash *details)
1544 {
1545     struct netdev_dev_linux *netdev_dev =
1546                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1547     int error;
1548
1549     error = tc_query_qdisc(netdev);
1550     if (error) {
1551         return error;
1552     }
1553
1554     *typep = netdev_dev->tc->ops->ovs_name;
1555     return (netdev_dev->tc->ops->qdisc_get
1556             ? netdev_dev->tc->ops->qdisc_get(netdev, details)
1557             : 0);
1558 }
1559
1560 static int
1561 netdev_linux_set_qos(struct netdev *netdev,
1562                      const char *type, const struct shash *details)
1563 {
1564     struct netdev_dev_linux *netdev_dev =
1565                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1566     const struct tc_ops *new_ops;
1567     int error;
1568
1569     new_ops = tc_lookup_ovs_name(type);
1570     if (!new_ops || !new_ops->tc_install) {
1571         return EOPNOTSUPP;
1572     }
1573
1574     error = tc_query_qdisc(netdev);
1575     if (error) {
1576         return error;
1577     }
1578
1579     if (new_ops == netdev_dev->tc->ops) {
1580         return new_ops->qdisc_set ? new_ops->qdisc_set(netdev, details) : 0;
1581     } else {
1582         /* Delete existing qdisc. */
1583         error = tc_del_qdisc(netdev);
1584         if (error) {
1585             return error;
1586         }
1587         assert(netdev_dev->tc == NULL);
1588
1589         /* Install new qdisc. */
1590         error = new_ops->tc_install(netdev, details);
1591         assert((error == 0) == (netdev_dev->tc != NULL));
1592
1593         return error;
1594     }
1595 }
1596
1597 static int
1598 netdev_linux_get_queue(const struct netdev *netdev,
1599                        unsigned int queue_id, struct shash *details)
1600 {
1601     struct netdev_dev_linux *netdev_dev =
1602                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1603     int error;
1604
1605     error = tc_query_qdisc(netdev);
1606     if (error) {
1607         return error;
1608     } else {
1609         struct tc_queue *queue = tc_find_queue(netdev, queue_id);
1610         return (queue
1611                 ? netdev_dev->tc->ops->class_get(netdev, queue, details)
1612                 : ENOENT);
1613     }
1614 }
1615
1616 static int
1617 netdev_linux_set_queue(struct netdev *netdev,
1618                        unsigned int queue_id, const struct shash *details)
1619 {
1620     struct netdev_dev_linux *netdev_dev =
1621                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1622     int error;
1623
1624     error = tc_query_qdisc(netdev);
1625     if (error) {
1626         return error;
1627     } else if (queue_id >= netdev_dev->tc->ops->n_queues
1628                || !netdev_dev->tc->ops->class_set) {
1629         return EINVAL;
1630     }
1631
1632     return netdev_dev->tc->ops->class_set(netdev, queue_id, details);
1633 }
1634
1635 static int
1636 netdev_linux_delete_queue(struct netdev *netdev, unsigned int queue_id)
1637 {
1638     struct netdev_dev_linux *netdev_dev =
1639                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1640     int error;
1641
1642     error = tc_query_qdisc(netdev);
1643     if (error) {
1644         return error;
1645     } else if (!netdev_dev->tc->ops->class_delete) {
1646         return EINVAL;
1647     } else {
1648         struct tc_queue *queue = tc_find_queue(netdev, queue_id);
1649         return (queue
1650                 ? netdev_dev->tc->ops->class_delete(netdev, queue)
1651                 : ENOENT);
1652     }
1653 }
1654
1655 static int
1656 netdev_linux_get_queue_stats(const struct netdev *netdev,
1657                              unsigned int queue_id,
1658                              struct netdev_queue_stats *stats)
1659 {
1660     struct netdev_dev_linux *netdev_dev =
1661                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1662     int error;
1663
1664     error = tc_query_qdisc(netdev);
1665     if (error) {
1666         return error;
1667     } else if (!netdev_dev->tc->ops->class_get_stats) {
1668         return EOPNOTSUPP;
1669     } else {
1670         const struct tc_queue *queue = tc_find_queue(netdev, queue_id);
1671         return (queue
1672                 ? netdev_dev->tc->ops->class_get_stats(netdev, queue, stats)
1673                 : ENOENT);
1674     }
1675 }
1676
1677 static bool
1678 start_queue_dump(const struct netdev *netdev, struct nl_dump *dump)
1679 {
1680     struct ofpbuf request;
1681     struct tcmsg *tcmsg;
1682
1683     tcmsg = tc_make_request(netdev, RTM_GETTCLASS, 0, &request);
1684     if (!tcmsg) {
1685         return false;
1686     }
1687     tcmsg->tcm_parent = 0;
1688     nl_dump_start(dump, rtnl_sock, &request);
1689     ofpbuf_uninit(&request);
1690     return true;
1691 }
1692
1693 static int
1694 netdev_linux_dump_queues(const struct netdev *netdev,
1695                          netdev_dump_queues_cb *cb, void *aux)
1696 {
1697     struct netdev_dev_linux *netdev_dev =
1698                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1699     struct tc_queue *queue;
1700     struct shash details;
1701     int last_error;
1702     int error;
1703
1704     error = tc_query_qdisc(netdev);
1705     if (error) {
1706         return error;
1707     } else if (!netdev_dev->tc->ops->class_get) {
1708         return EOPNOTSUPP;
1709     }
1710
1711     last_error = 0;
1712     shash_init(&details);
1713     HMAP_FOR_EACH (queue, hmap_node, &netdev_dev->tc->queues) {
1714         shash_clear(&details);
1715
1716         error = netdev_dev->tc->ops->class_get(netdev, queue, &details);
1717         if (!error) {
1718             (*cb)(queue->queue_id, &details, aux);
1719         } else {
1720             last_error = error;
1721         }
1722     }
1723     shash_destroy(&details);
1724
1725     return last_error;
1726 }
1727
1728 static int
1729 netdev_linux_dump_queue_stats(const struct netdev *netdev,
1730                               netdev_dump_queue_stats_cb *cb, void *aux)
1731 {
1732     struct netdev_dev_linux *netdev_dev =
1733                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1734     struct nl_dump dump;
1735     struct ofpbuf msg;
1736     int last_error;
1737     int error;
1738
1739     error = tc_query_qdisc(netdev);
1740     if (error) {
1741         return error;
1742     } else if (!netdev_dev->tc->ops->class_dump_stats) {
1743         return EOPNOTSUPP;
1744     }
1745
1746     last_error = 0;
1747     if (!start_queue_dump(netdev, &dump)) {
1748         return ENODEV;
1749     }
1750     while (nl_dump_next(&dump, &msg)) {
1751         error = netdev_dev->tc->ops->class_dump_stats(netdev, &msg, cb, aux);
1752         if (error) {
1753             last_error = error;
1754         }
1755     }
1756
1757     error = nl_dump_done(&dump);
1758     return error ? error : last_error;
1759 }
1760
1761 static int
1762 netdev_linux_get_in4(const struct netdev *netdev_,
1763                      struct in_addr *address, struct in_addr *netmask)
1764 {
1765     struct netdev_dev_linux *netdev_dev =
1766                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1767
1768     if (!(netdev_dev->cache_valid & VALID_IN4)) {
1769         int error;
1770
1771         error = netdev_linux_get_ipv4(netdev_, &netdev_dev->address,
1772                                       SIOCGIFADDR, "SIOCGIFADDR");
1773         if (error) {
1774             return error;
1775         }
1776
1777         error = netdev_linux_get_ipv4(netdev_, &netdev_dev->netmask,
1778                                       SIOCGIFNETMASK, "SIOCGIFNETMASK");
1779         if (error) {
1780             return error;
1781         }
1782
1783         netdev_dev->cache_valid |= VALID_IN4;
1784     }
1785     *address = netdev_dev->address;
1786     *netmask = netdev_dev->netmask;
1787     return address->s_addr == INADDR_ANY ? EADDRNOTAVAIL : 0;
1788 }
1789
1790 static int
1791 netdev_linux_set_in4(struct netdev *netdev_, struct in_addr address,
1792                      struct in_addr netmask)
1793 {
1794     struct netdev_dev_linux *netdev_dev =
1795                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1796     int error;
1797
1798     error = do_set_addr(netdev_, SIOCSIFADDR, "SIOCSIFADDR", address);
1799     if (!error) {
1800         netdev_dev->cache_valid |= VALID_IN4;
1801         netdev_dev->address = address;
1802         netdev_dev->netmask = netmask;
1803         if (address.s_addr != INADDR_ANY) {
1804             error = do_set_addr(netdev_, SIOCSIFNETMASK,
1805                                 "SIOCSIFNETMASK", netmask);
1806         }
1807     }
1808     return error;
1809 }
1810
1811 static bool
1812 parse_if_inet6_line(const char *line,
1813                     struct in6_addr *in6, char ifname[16 + 1])
1814 {
1815     uint8_t *s6 = in6->s6_addr;
1816 #define X8 "%2"SCNx8
1817     return sscanf(line,
1818                   " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
1819                   "%*x %*x %*x %*x %16s\n",
1820                   &s6[0], &s6[1], &s6[2], &s6[3],
1821                   &s6[4], &s6[5], &s6[6], &s6[7],
1822                   &s6[8], &s6[9], &s6[10], &s6[11],
1823                   &s6[12], &s6[13], &s6[14], &s6[15],
1824                   ifname) == 17;
1825 }
1826
1827 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
1828  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
1829 static int
1830 netdev_linux_get_in6(const struct netdev *netdev_, struct in6_addr *in6)
1831 {
1832     struct netdev_dev_linux *netdev_dev =
1833                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1834     if (!(netdev_dev->cache_valid & VALID_IN6)) {
1835         FILE *file;
1836         char line[128];
1837
1838         netdev_dev->in6 = in6addr_any;
1839
1840         file = fopen("/proc/net/if_inet6", "r");
1841         if (file != NULL) {
1842             const char *name = netdev_get_name(netdev_);
1843             while (fgets(line, sizeof line, file)) {
1844                 struct in6_addr in6_tmp;
1845                 char ifname[16 + 1];
1846                 if (parse_if_inet6_line(line, &in6_tmp, ifname)
1847                     && !strcmp(name, ifname))
1848                 {
1849                     netdev_dev->in6 = in6_tmp;
1850                     break;
1851                 }
1852             }
1853             fclose(file);
1854         }
1855         netdev_dev->cache_valid |= VALID_IN6;
1856     }
1857     *in6 = netdev_dev->in6;
1858     return 0;
1859 }
1860
1861 static void
1862 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
1863 {
1864     struct sockaddr_in sin;
1865     memset(&sin, 0, sizeof sin);
1866     sin.sin_family = AF_INET;
1867     sin.sin_addr = addr;
1868     sin.sin_port = 0;
1869
1870     memset(sa, 0, sizeof *sa);
1871     memcpy(sa, &sin, sizeof sin);
1872 }
1873
1874 static int
1875 do_set_addr(struct netdev *netdev,
1876             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
1877 {
1878     struct ifreq ifr;
1879     strncpy(ifr.ifr_name, netdev_get_name(netdev), sizeof ifr.ifr_name);
1880     make_in4_sockaddr(&ifr.ifr_addr, addr);
1881
1882     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, ioctl_nr,
1883                                  ioctl_name);
1884 }
1885
1886 /* Adds 'router' as a default IP gateway. */
1887 static int
1888 netdev_linux_add_router(struct netdev *netdev OVS_UNUSED, struct in_addr router)
1889 {
1890     struct in_addr any = { INADDR_ANY };
1891     struct rtentry rt;
1892     int error;
1893
1894     memset(&rt, 0, sizeof rt);
1895     make_in4_sockaddr(&rt.rt_dst, any);
1896     make_in4_sockaddr(&rt.rt_gateway, router);
1897     make_in4_sockaddr(&rt.rt_genmask, any);
1898     rt.rt_flags = RTF_UP | RTF_GATEWAY;
1899     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
1900     if (error) {
1901         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
1902     }
1903     return error;
1904 }
1905
1906 static int
1907 netdev_linux_get_next_hop(const struct in_addr *host, struct in_addr *next_hop,
1908                           char **netdev_name)
1909 {
1910     static const char fn[] = "/proc/net/route";
1911     FILE *stream;
1912     char line[256];
1913     int ln;
1914
1915     *netdev_name = NULL;
1916     stream = fopen(fn, "r");
1917     if (stream == NULL) {
1918         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1919         return errno;
1920     }
1921
1922     ln = 0;
1923     while (fgets(line, sizeof line, stream)) {
1924         if (++ln >= 2) {
1925             char iface[17];
1926             uint32_t dest, gateway, mask;
1927             int refcnt, metric, mtu;
1928             unsigned int flags, use, window, irtt;
1929
1930             if (sscanf(line,
1931                        "%16s %"SCNx32" %"SCNx32" %04X %d %u %d %"SCNx32
1932                        " %d %u %u\n",
1933                        iface, &dest, &gateway, &flags, &refcnt,
1934                        &use, &metric, &mask, &mtu, &window, &irtt) != 11) {
1935
1936                 VLOG_WARN_RL(&rl, "%s: could not parse line %d: %s",
1937                         fn, ln, line);
1938                 continue;
1939             }
1940             if (!(flags & RTF_UP)) {
1941                 /* Skip routes that aren't up. */
1942                 continue;
1943             }
1944
1945             /* The output of 'dest', 'mask', and 'gateway' were given in
1946              * network byte order, so we don't need need any endian
1947              * conversions here. */
1948             if ((dest & mask) == (host->s_addr & mask)) {
1949                 if (!gateway) {
1950                     /* The host is directly reachable. */
1951                     next_hop->s_addr = 0;
1952                 } else {
1953                     /* To reach the host, we must go through a gateway. */
1954                     next_hop->s_addr = gateway;
1955                 }
1956                 *netdev_name = xstrdup(iface);
1957                 fclose(stream);
1958                 return 0;
1959             }
1960         }
1961     }
1962
1963     fclose(stream);
1964     return ENXIO;
1965 }
1966
1967 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
1968  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
1969  * returns 0.  Otherwise, it returns a positive errno value; in particular,
1970  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
1971 static int
1972 netdev_linux_arp_lookup(const struct netdev *netdev,
1973                         uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
1974 {
1975     struct arpreq r;
1976     struct sockaddr_in sin;
1977     int retval;
1978
1979     memset(&r, 0, sizeof r);
1980     sin.sin_family = AF_INET;
1981     sin.sin_addr.s_addr = ip;
1982     sin.sin_port = 0;
1983     memcpy(&r.arp_pa, &sin, sizeof sin);
1984     r.arp_ha.sa_family = ARPHRD_ETHER;
1985     r.arp_flags = 0;
1986     strncpy(r.arp_dev, netdev_get_name(netdev), sizeof r.arp_dev);
1987     COVERAGE_INC(netdev_arp_lookup);
1988     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
1989     if (!retval) {
1990         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
1991     } else if (retval != ENXIO) {
1992         VLOG_WARN_RL(&rl, "%s: could not look up ARP entry for "IP_FMT": %s",
1993                      netdev_get_name(netdev), IP_ARGS(&ip), strerror(retval));
1994     }
1995     return retval;
1996 }
1997
1998 static int
1999 nd_to_iff_flags(enum netdev_flags nd)
2000 {
2001     int iff = 0;
2002     if (nd & NETDEV_UP) {
2003         iff |= IFF_UP;
2004     }
2005     if (nd & NETDEV_PROMISC) {
2006         iff |= IFF_PROMISC;
2007     }
2008     return iff;
2009 }
2010
2011 static int
2012 iff_to_nd_flags(int iff)
2013 {
2014     enum netdev_flags nd = 0;
2015     if (iff & IFF_UP) {
2016         nd |= NETDEV_UP;
2017     }
2018     if (iff & IFF_PROMISC) {
2019         nd |= NETDEV_PROMISC;
2020     }
2021     return nd;
2022 }
2023
2024 static int
2025 netdev_linux_update_flags(struct netdev *netdev, enum netdev_flags off,
2026                           enum netdev_flags on, enum netdev_flags *old_flagsp)
2027 {
2028     int old_flags, new_flags;
2029     int error;
2030
2031     error = get_flags(netdev, &old_flags);
2032     if (!error) {
2033         *old_flagsp = iff_to_nd_flags(old_flags);
2034         new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
2035         if (new_flags != old_flags) {
2036             error = set_flags(netdev, new_flags);
2037         }
2038     }
2039     return error;
2040 }
2041
2042 static void
2043 poll_notify(struct list *list)
2044 {
2045     struct netdev_linux_notifier *notifier;
2046     LIST_FOR_EACH (notifier, node, list) {
2047         struct netdev_notifier *n = &notifier->notifier;
2048         n->cb(n);
2049     }
2050 }
2051
2052 static void
2053 netdev_linux_poll_cb(const struct rtnetlink_link_change *change,
2054                      void *aux OVS_UNUSED)
2055 {
2056     if (change) {
2057         struct list *list = shash_find_data(&netdev_linux_notifiers,
2058                                             change->ifname);
2059         if (list) {
2060             poll_notify(list);
2061         }
2062     } else {
2063         struct shash_node *node;
2064         SHASH_FOR_EACH (node, &netdev_linux_notifiers) {
2065             poll_notify(node->data);
2066         }
2067     }
2068 }
2069
2070 static int
2071 netdev_linux_poll_add(struct netdev *netdev,
2072                       void (*cb)(struct netdev_notifier *), void *aux,
2073                       struct netdev_notifier **notifierp)
2074 {
2075     const char *netdev_name = netdev_get_name(netdev);
2076     struct netdev_linux_notifier *notifier;
2077     struct list *list;
2078
2079     if (shash_is_empty(&netdev_linux_notifiers)) {
2080         int error;
2081         error = rtnetlink_link_notifier_register(&netdev_linux_poll_notifier,
2082                                                  netdev_linux_poll_cb, NULL);
2083         if (error) {
2084             return error;
2085         }
2086     }
2087
2088     list = shash_find_data(&netdev_linux_notifiers, netdev_name);
2089     if (!list) {
2090         list = xmalloc(sizeof *list);
2091         list_init(list);
2092         shash_add(&netdev_linux_notifiers, netdev_name, list);
2093     }
2094
2095     notifier = xmalloc(sizeof *notifier);
2096     netdev_notifier_init(&notifier->notifier, netdev, cb, aux);
2097     list_push_back(list, &notifier->node);
2098     *notifierp = &notifier->notifier;
2099     return 0;
2100 }
2101
2102 static void
2103 netdev_linux_poll_remove(struct netdev_notifier *notifier_)
2104 {
2105     struct netdev_linux_notifier *notifier =
2106         CONTAINER_OF(notifier_, struct netdev_linux_notifier, notifier);
2107     struct list *list;
2108
2109     /* Remove 'notifier' from its list. */
2110     list = list_remove(&notifier->node);
2111     if (list_is_empty(list)) {
2112         /* The list is now empty.  Remove it from the hash and free it. */
2113         const char *netdev_name = netdev_get_name(notifier->notifier.netdev);
2114         shash_delete(&netdev_linux_notifiers,
2115                      shash_find(&netdev_linux_notifiers, netdev_name));
2116         free(list);
2117     }
2118     free(notifier);
2119
2120     /* If that was the last notifier, unregister. */
2121     if (shash_is_empty(&netdev_linux_notifiers)) {
2122         rtnetlink_link_notifier_unregister(&netdev_linux_poll_notifier);
2123     }
2124 }
2125
2126 #define NETDEV_LINUX_CLASS(NAME, CREATE, ENUMERATE, SET_STATS)  \
2127 {                                                               \
2128     NAME,                                                       \
2129                                                                 \
2130     netdev_linux_init,                                          \
2131     netdev_linux_run,                                           \
2132     netdev_linux_wait,                                          \
2133                                                                 \
2134     CREATE,                                                     \
2135     netdev_linux_destroy,                                       \
2136     NULL,                       /* reconfigure */               \
2137                                                                 \
2138     netdev_linux_open,                                          \
2139     netdev_linux_close,                                         \
2140                                                                 \
2141     ENUMERATE,                                                  \
2142                                                                 \
2143     netdev_linux_recv,                                          \
2144     netdev_linux_recv_wait,                                     \
2145     netdev_linux_drain,                                         \
2146                                                                 \
2147     netdev_linux_send,                                          \
2148     netdev_linux_send_wait,                                     \
2149                                                                 \
2150     netdev_linux_set_etheraddr,                                 \
2151     netdev_linux_get_etheraddr,                                 \
2152     netdev_linux_get_mtu,                                       \
2153     netdev_linux_get_ifindex,                                   \
2154     netdev_linux_get_carrier,                                   \
2155     netdev_linux_get_stats,                                     \
2156     SET_STATS,                                                  \
2157                                                                 \
2158     netdev_linux_get_features,                                  \
2159     netdev_linux_set_advertisements,                            \
2160     netdev_linux_get_vlan_vid,                                  \
2161                                                                 \
2162     netdev_linux_set_policing,                                  \
2163     netdev_linux_get_qos_types,                                 \
2164     netdev_linux_get_qos_capabilities,                          \
2165     netdev_linux_get_qos,                                       \
2166     netdev_linux_set_qos,                                       \
2167     netdev_linux_get_queue,                                     \
2168     netdev_linux_set_queue,                                     \
2169     netdev_linux_delete_queue,                                  \
2170     netdev_linux_get_queue_stats,                               \
2171     netdev_linux_dump_queues,                                   \
2172     netdev_linux_dump_queue_stats,                              \
2173                                                                 \
2174     netdev_linux_get_in4,                                       \
2175     netdev_linux_set_in4,                                       \
2176     netdev_linux_get_in6,                                       \
2177     netdev_linux_add_router,                                    \
2178     netdev_linux_get_next_hop,                                  \
2179     NULL,                       /* get_tnl_iface */             \
2180     netdev_linux_arp_lookup,                                    \
2181                                                                 \
2182     netdev_linux_update_flags,                                  \
2183                                                                 \
2184     netdev_linux_poll_add,                                      \
2185     netdev_linux_poll_remove                                    \
2186 }
2187
2188 const struct netdev_class netdev_linux_class =
2189     NETDEV_LINUX_CLASS(
2190         "system",
2191         netdev_linux_create,
2192         netdev_linux_enumerate,
2193         NULL);                  /* set_stats */
2194
2195 const struct netdev_class netdev_tap_class =
2196     NETDEV_LINUX_CLASS(
2197         "tap",
2198         netdev_linux_create_tap,
2199         NULL,                   /* enumerate */
2200         NULL);                  /* set_stats */
2201
2202 const struct netdev_class netdev_internal_class =
2203     NETDEV_LINUX_CLASS(
2204         "internal",
2205         netdev_linux_create,
2206         NULL,                    /* enumerate */
2207         netdev_vport_set_stats);
2208 \f
2209 /* HTB traffic control class. */
2210
2211 #define HTB_N_QUEUES 0xf000
2212
2213 struct htb {
2214     struct tc tc;
2215     unsigned int max_rate;      /* In bytes/s. */
2216 };
2217
2218 struct htb_class {
2219     struct tc_queue tc_queue;
2220     unsigned int min_rate;      /* In bytes/s. */
2221     unsigned int max_rate;      /* In bytes/s. */
2222     unsigned int burst;         /* In bytes. */
2223     unsigned int priority;      /* Lower values are higher priorities. */
2224 };
2225
2226 static struct htb *
2227 htb_get__(const struct netdev *netdev)
2228 {
2229     struct netdev_dev_linux *netdev_dev =
2230                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
2231     return CONTAINER_OF(netdev_dev->tc, struct htb, tc);
2232 }
2233
2234 static struct htb *
2235 htb_install__(struct netdev *netdev, uint64_t max_rate)
2236 {
2237     struct netdev_dev_linux *netdev_dev =
2238                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
2239     struct htb *htb;
2240
2241     htb = xmalloc(sizeof *htb);
2242     tc_init(&htb->tc, &tc_ops_htb);
2243     htb->max_rate = max_rate;
2244
2245     netdev_dev->tc = &htb->tc;
2246
2247     return htb;
2248 }
2249
2250 /* Create an HTB qdisc.
2251  *
2252  * Equivalent to "tc qdisc add dev <dev> root handle 1: htb default 1". */
2253 static int
2254 htb_setup_qdisc__(struct netdev *netdev)
2255 {
2256     size_t opt_offset;
2257     struct tc_htb_glob opt;
2258     struct ofpbuf request;
2259     struct tcmsg *tcmsg;
2260
2261     tc_del_qdisc(netdev);
2262
2263     tcmsg = tc_make_request(netdev, RTM_NEWQDISC,
2264                             NLM_F_EXCL | NLM_F_CREATE, &request);
2265     if (!tcmsg) {
2266         return ENODEV;
2267     }
2268     tcmsg->tcm_handle = tc_make_handle(1, 0);
2269     tcmsg->tcm_parent = TC_H_ROOT;
2270
2271     nl_msg_put_string(&request, TCA_KIND, "htb");
2272
2273     memset(&opt, 0, sizeof opt);
2274     opt.rate2quantum = 10;
2275     opt.version = 3;
2276     opt.defcls = 1;
2277
2278     opt_offset = nl_msg_start_nested(&request, TCA_OPTIONS);
2279     nl_msg_put_unspec(&request, TCA_HTB_INIT, &opt, sizeof opt);
2280     nl_msg_end_nested(&request, opt_offset);
2281
2282     return tc_transact(&request, NULL);
2283 }
2284
2285 /* Equivalent to "tc class replace <dev> classid <handle> parent <parent> htb
2286  * rate <min_rate>bps ceil <max_rate>bps burst <burst>b prio <priority>". */
2287 static int
2288 htb_setup_class__(struct netdev *netdev, unsigned int handle,
2289                   unsigned int parent, struct htb_class *class)
2290 {
2291     size_t opt_offset;
2292     struct tc_htb_opt opt;
2293     struct ofpbuf request;
2294     struct tcmsg *tcmsg;
2295     int error;
2296     int mtu;
2297
2298     netdev_get_mtu(netdev, &mtu);
2299
2300     memset(&opt, 0, sizeof opt);
2301     tc_fill_rate(&opt.rate, class->min_rate, mtu);
2302     tc_fill_rate(&opt.ceil, class->max_rate, mtu);
2303     opt.buffer = tc_calc_buffer(opt.rate.rate, mtu, class->burst);
2304     opt.cbuffer = tc_calc_buffer(opt.ceil.rate, mtu, class->burst);
2305     opt.prio = class->priority;
2306
2307     tcmsg = tc_make_request(netdev, RTM_NEWTCLASS, NLM_F_CREATE, &request);
2308     if (!tcmsg) {
2309         return ENODEV;
2310     }
2311     tcmsg->tcm_handle = handle;
2312     tcmsg->tcm_parent = parent;
2313
2314     nl_msg_put_string(&request, TCA_KIND, "htb");
2315     opt_offset = nl_msg_start_nested(&request, TCA_OPTIONS);
2316     nl_msg_put_unspec(&request, TCA_HTB_PARMS, &opt, sizeof opt);
2317     tc_put_rtab(&request, TCA_HTB_RTAB, &opt.rate);
2318     tc_put_rtab(&request, TCA_HTB_CTAB, &opt.ceil);
2319     nl_msg_end_nested(&request, opt_offset);
2320
2321     error = tc_transact(&request, NULL);
2322     if (error) {
2323         VLOG_WARN_RL(&rl, "failed to replace %s class %u:%u, parent %u:%u, "
2324                      "min_rate=%u max_rate=%u burst=%u prio=%u (%s)",
2325                      netdev_get_name(netdev),
2326                      tc_get_major(handle), tc_get_minor(handle),
2327                      tc_get_major(parent), tc_get_minor(parent),
2328                      class->min_rate, class->max_rate,
2329                      class->burst, class->priority, strerror(error));
2330     }
2331     return error;
2332 }
2333
2334 /* Parses Netlink attributes in 'options' for HTB parameters and stores a
2335  * description of them into 'details'.  The description complies with the
2336  * specification given in the vswitch database documentation for linux-htb
2337  * queue details. */
2338 static int
2339 htb_parse_tca_options__(struct nlattr *nl_options, struct htb_class *class)
2340 {
2341     static const struct nl_policy tca_htb_policy[] = {
2342         [TCA_HTB_PARMS] = { .type = NL_A_UNSPEC, .optional = false,
2343                             .min_len = sizeof(struct tc_htb_opt) },
2344     };
2345
2346     struct nlattr *attrs[ARRAY_SIZE(tca_htb_policy)];
2347     const struct tc_htb_opt *htb;
2348
2349     if (!nl_parse_nested(nl_options, tca_htb_policy,
2350                          attrs, ARRAY_SIZE(tca_htb_policy))) {
2351         VLOG_WARN_RL(&rl, "failed to parse HTB class options");
2352         return EPROTO;
2353     }
2354
2355     htb = nl_attr_get(attrs[TCA_HTB_PARMS]);
2356     class->min_rate = htb->rate.rate;
2357     class->max_rate = htb->ceil.rate;
2358     class->burst = tc_ticks_to_bytes(htb->rate.rate, htb->buffer);
2359     class->priority = htb->prio;
2360     return 0;
2361 }
2362
2363 static int
2364 htb_parse_tcmsg__(struct ofpbuf *tcmsg, unsigned int *queue_id,
2365                   struct htb_class *options,
2366                   struct netdev_queue_stats *stats)
2367 {
2368     struct nlattr *nl_options;
2369     unsigned int handle;
2370     int error;
2371
2372     error = tc_parse_class(tcmsg, &handle, &nl_options, stats);
2373     if (!error && queue_id) {
2374         unsigned int major = tc_get_major(handle);
2375         unsigned int minor = tc_get_minor(handle);
2376         if (major == 1 && minor > 0 && minor <= HTB_N_QUEUES) {
2377             *queue_id = minor - 1;
2378         } else {
2379             error = EPROTO;
2380         }
2381     }
2382     if (!error && options) {
2383         error = htb_parse_tca_options__(nl_options, options);
2384     }
2385     return error;
2386 }
2387
2388 static void
2389 htb_parse_qdisc_details__(struct netdev *netdev,
2390                           const struct shash *details, struct htb_class *hc)
2391 {
2392     const char *max_rate_s;
2393
2394     max_rate_s = shash_find_data(details, "max-rate");
2395     hc->max_rate = max_rate_s ? strtoull(max_rate_s, NULL, 10) / 8 : 0;
2396     if (!hc->max_rate) {
2397         uint32_t current;
2398
2399         netdev_get_features(netdev, &current, NULL, NULL, NULL);
2400         hc->max_rate = netdev_features_to_bps(current) / 8;
2401     }
2402     hc->min_rate = hc->max_rate;
2403     hc->burst = 0;
2404     hc->priority = 0;
2405 }
2406
2407 static int
2408 htb_parse_class_details__(struct netdev *netdev,
2409                           const struct shash *details, struct htb_class *hc)
2410 {
2411     const struct htb *htb = htb_get__(netdev);
2412     const char *min_rate_s = shash_find_data(details, "min-rate");
2413     const char *max_rate_s = shash_find_data(details, "max-rate");
2414     const char *burst_s = shash_find_data(details, "burst");
2415     const char *priority_s = shash_find_data(details, "priority");
2416     int mtu;
2417
2418     /* min-rate.  Don't allow a min-rate below 1500 bytes/s. */
2419     if (!min_rate_s) {
2420         /* min-rate is required. */
2421         return EINVAL;
2422     }
2423     hc->min_rate = strtoull(min_rate_s, NULL, 10) / 8;
2424     hc->min_rate = MAX(hc->min_rate, 1500);
2425     hc->min_rate = MIN(hc->min_rate, htb->max_rate);
2426
2427     /* max-rate */
2428     hc->max_rate = (max_rate_s
2429                     ? strtoull(max_rate_s, NULL, 10) / 8
2430                     : htb->max_rate);
2431     hc->max_rate = MAX(hc->max_rate, hc->min_rate);
2432     hc->max_rate = MIN(hc->max_rate, htb->max_rate);
2433
2434     /* burst
2435      *
2436      * According to hints in the documentation that I've read, it is important
2437      * that 'burst' be at least as big as the largest frame that might be
2438      * transmitted.  Also, making 'burst' a bit bigger than necessary is OK,
2439      * but having it a bit too small is a problem.  Since netdev_get_mtu()
2440      * doesn't include the Ethernet header, we need to add at least 14 (18?) to
2441      * the MTU.  We actually add 64, instead of 14, as a guard against
2442      * additional headers get tacked on somewhere that we're not aware of. */
2443     netdev_get_mtu(netdev, &mtu);
2444     hc->burst = burst_s ? strtoull(burst_s, NULL, 10) / 8 : 0;
2445     hc->burst = MAX(hc->burst, mtu + 64);
2446
2447     /* priority */
2448     hc->priority = priority_s ? strtoul(priority_s, NULL, 10) : 0;
2449
2450     return 0;
2451 }
2452
2453 static int
2454 htb_query_class__(const struct netdev *netdev, unsigned int handle,
2455                   unsigned int parent, struct htb_class *options,
2456                   struct netdev_queue_stats *stats)
2457 {
2458     struct ofpbuf *reply;
2459     int error;
2460
2461     error = tc_query_class(netdev, handle, parent, &reply);
2462     if (!error) {
2463         error = htb_parse_tcmsg__(reply, NULL, options, stats);
2464         ofpbuf_delete(reply);
2465     }
2466     return error;
2467 }
2468
2469 static int
2470 htb_tc_install(struct netdev *netdev, const struct shash *details)
2471 {
2472     int error;
2473
2474     error = htb_setup_qdisc__(netdev);
2475     if (!error) {
2476         struct htb_class hc;
2477
2478         htb_parse_qdisc_details__(netdev, details, &hc);
2479         error = htb_setup_class__(netdev, tc_make_handle(1, 0xfffe),
2480                                   tc_make_handle(1, 0), &hc);
2481         if (!error) {
2482             htb_install__(netdev, hc.max_rate);
2483         }
2484     }
2485     return error;
2486 }
2487
2488 static struct htb_class *
2489 htb_class_cast__(const struct tc_queue *queue)
2490 {
2491     return CONTAINER_OF(queue, struct htb_class, tc_queue);
2492 }
2493
2494 static void
2495 htb_update_queue__(struct netdev *netdev, unsigned int queue_id,
2496                    const struct htb_class *hc)
2497 {
2498     struct htb *htb = htb_get__(netdev);
2499     size_t hash = hash_int(queue_id, 0);
2500     struct tc_queue *queue;
2501     struct htb_class *hcp;
2502
2503     queue = tc_find_queue__(netdev, queue_id, hash);
2504     if (queue) {
2505         hcp = htb_class_cast__(queue);
2506     } else {
2507         hcp = xmalloc(sizeof *hcp);
2508         queue = &hcp->tc_queue;
2509         queue->queue_id = queue_id;
2510         hmap_insert(&htb->tc.queues, &queue->hmap_node, hash);
2511     }
2512
2513     hcp->min_rate = hc->min_rate;
2514     hcp->max_rate = hc->max_rate;
2515     hcp->burst = hc->burst;
2516     hcp->priority = hc->priority;
2517 }
2518
2519 static int
2520 htb_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
2521 {
2522     struct ofpbuf msg;
2523     struct nl_dump dump;
2524     struct htb_class hc;
2525     struct htb *htb;
2526
2527     /* Get qdisc options. */
2528     hc.max_rate = 0;
2529     htb_query_class__(netdev, tc_make_handle(1, 0xfffe), 0, &hc, NULL);
2530     htb = htb_install__(netdev, hc.max_rate);
2531
2532     /* Get queues. */
2533     if (!start_queue_dump(netdev, &dump)) {
2534         return ENODEV;
2535     }
2536     while (nl_dump_next(&dump, &msg)) {
2537         unsigned int queue_id;
2538
2539         if (!htb_parse_tcmsg__(&msg, &queue_id, &hc, NULL)) {
2540             htb_update_queue__(netdev, queue_id, &hc);
2541         }
2542     }
2543     nl_dump_done(&dump);
2544
2545     return 0;
2546 }
2547
2548 static void
2549 htb_tc_destroy(struct tc *tc)
2550 {
2551     struct htb *htb = CONTAINER_OF(tc, struct htb, tc);
2552     struct htb_class *hc, *next;
2553
2554     HMAP_FOR_EACH_SAFE (hc, next, tc_queue.hmap_node, &htb->tc.queues) {
2555         hmap_remove(&htb->tc.queues, &hc->tc_queue.hmap_node);
2556         free(hc);
2557     }
2558     tc_destroy(tc);
2559     free(htb);
2560 }
2561
2562 static int
2563 htb_qdisc_get(const struct netdev *netdev, struct shash *details)
2564 {
2565     const struct htb *htb = htb_get__(netdev);
2566     shash_add(details, "max-rate", xasprintf("%llu", 8ULL * htb->max_rate));
2567     return 0;
2568 }
2569
2570 static int
2571 htb_qdisc_set(struct netdev *netdev, const struct shash *details)
2572 {
2573     struct htb_class hc;
2574     int error;
2575
2576     htb_parse_qdisc_details__(netdev, details, &hc);
2577     error = htb_setup_class__(netdev, tc_make_handle(1, 0xfffe),
2578                               tc_make_handle(1, 0), &hc);
2579     if (!error) {
2580         htb_get__(netdev)->max_rate = hc.max_rate;
2581     }
2582     return error;
2583 }
2584
2585 static int
2586 htb_class_get(const struct netdev *netdev OVS_UNUSED,
2587               const struct tc_queue *queue, struct shash *details)
2588 {
2589     const struct htb_class *hc = htb_class_cast__(queue);
2590
2591     shash_add(details, "min-rate", xasprintf("%llu", 8ULL * hc->min_rate));
2592     if (hc->min_rate != hc->max_rate) {
2593         shash_add(details, "max-rate", xasprintf("%llu", 8ULL * hc->max_rate));
2594     }
2595     shash_add(details, "burst", xasprintf("%llu", 8ULL * hc->burst));
2596     if (hc->priority) {
2597         shash_add(details, "priority", xasprintf("%u", hc->priority));
2598     }
2599     return 0;
2600 }
2601
2602 static int
2603 htb_class_set(struct netdev *netdev, unsigned int queue_id,
2604               const struct shash *details)
2605 {
2606     struct htb_class hc;
2607     int error;
2608
2609     error = htb_parse_class_details__(netdev, details, &hc);
2610     if (error) {
2611         return error;
2612     }
2613
2614     error = htb_setup_class__(netdev, tc_make_handle(1, queue_id + 1),
2615                               tc_make_handle(1, 0xfffe), &hc);
2616     if (error) {
2617         return error;
2618     }
2619
2620     htb_update_queue__(netdev, queue_id, &hc);
2621     return 0;
2622 }
2623
2624 static int
2625 htb_class_delete(struct netdev *netdev, struct tc_queue *queue)
2626 {
2627     struct htb_class *hc = htb_class_cast__(queue);
2628     struct htb *htb = htb_get__(netdev);
2629     int error;
2630
2631     error = tc_delete_class(netdev, tc_make_handle(1, queue->queue_id + 1));
2632     if (!error) {
2633         hmap_remove(&htb->tc.queues, &hc->tc_queue.hmap_node);
2634         free(hc);
2635     }
2636     return error;
2637 }
2638
2639 static int
2640 htb_class_get_stats(const struct netdev *netdev, const struct tc_queue *queue,
2641                     struct netdev_queue_stats *stats)
2642 {
2643     return htb_query_class__(netdev, tc_make_handle(1, queue->queue_id + 1),
2644                              tc_make_handle(1, 0xfffe), NULL, stats);
2645 }
2646
2647 static int
2648 htb_class_dump_stats(const struct netdev *netdev OVS_UNUSED,
2649                      const struct ofpbuf *nlmsg,
2650                      netdev_dump_queue_stats_cb *cb, void *aux)
2651 {
2652     struct netdev_queue_stats stats;
2653     unsigned int handle, major, minor;
2654     int error;
2655
2656     error = tc_parse_class(nlmsg, &handle, NULL, &stats);
2657     if (error) {
2658         return error;
2659     }
2660
2661     major = tc_get_major(handle);
2662     minor = tc_get_minor(handle);
2663     if (major == 1 && minor > 0 && minor <= HTB_N_QUEUES) {
2664         (*cb)(minor - 1, &stats, aux);
2665     }
2666     return 0;
2667 }
2668
2669 static const struct tc_ops tc_ops_htb = {
2670     "htb",                      /* linux_name */
2671     "linux-htb",                /* ovs_name */
2672     HTB_N_QUEUES,               /* n_queues */
2673     htb_tc_install,
2674     htb_tc_load,
2675     htb_tc_destroy,
2676     htb_qdisc_get,
2677     htb_qdisc_set,
2678     htb_class_get,
2679     htb_class_set,
2680     htb_class_delete,
2681     htb_class_get_stats,
2682     htb_class_dump_stats
2683 };
2684 \f
2685 /* "linux-hfsc" traffic control class. */
2686
2687 #define HFSC_N_QUEUES 0xf000
2688
2689 struct hfsc {
2690     struct tc tc;
2691     uint32_t max_rate;
2692 };
2693
2694 struct hfsc_class {
2695     struct tc_queue tc_queue;
2696     uint32_t min_rate;
2697     uint32_t max_rate;
2698 };
2699
2700 static struct hfsc *
2701 hfsc_get__(const struct netdev *netdev)
2702 {
2703     struct netdev_dev_linux *netdev_dev;
2704     netdev_dev = netdev_dev_linux_cast(netdev_get_dev(netdev));
2705     return CONTAINER_OF(netdev_dev->tc, struct hfsc, tc);
2706 }
2707
2708 static struct hfsc_class *
2709 hfsc_class_cast__(const struct tc_queue *queue)
2710 {
2711     return CONTAINER_OF(queue, struct hfsc_class, tc_queue);
2712 }
2713
2714 static struct hfsc *
2715 hfsc_install__(struct netdev *netdev, uint32_t max_rate)
2716 {
2717     struct netdev_dev_linux * netdev_dev;
2718     struct hfsc *hfsc;
2719
2720     netdev_dev = netdev_dev_linux_cast(netdev_get_dev(netdev));
2721     hfsc = xmalloc(sizeof *hfsc);
2722     tc_init(&hfsc->tc, &tc_ops_hfsc);
2723     hfsc->max_rate = max_rate;
2724     netdev_dev->tc = &hfsc->tc;
2725
2726     return hfsc;
2727 }
2728
2729 static void
2730 hfsc_update_queue__(struct netdev *netdev, unsigned int queue_id,
2731                     const struct hfsc_class *hc)
2732 {
2733     size_t hash;
2734     struct hfsc *hfsc;
2735     struct hfsc_class *hcp;
2736     struct tc_queue *queue;
2737
2738     hfsc = hfsc_get__(netdev);
2739     hash = hash_int(queue_id, 0);
2740
2741     queue = tc_find_queue__(netdev, queue_id, hash);
2742     if (queue) {
2743         hcp = hfsc_class_cast__(queue);
2744     } else {
2745         hcp             = xmalloc(sizeof *hcp);
2746         queue           = &hcp->tc_queue;
2747         queue->queue_id = queue_id;
2748         hmap_insert(&hfsc->tc.queues, &queue->hmap_node, hash);
2749     }
2750
2751     hcp->min_rate = hc->min_rate;
2752     hcp->max_rate = hc->max_rate;
2753 }
2754
2755 static int
2756 hfsc_parse_tca_options__(struct nlattr *nl_options, struct hfsc_class *class)
2757 {
2758     const struct tc_service_curve *rsc, *fsc, *usc;
2759     static const struct nl_policy tca_hfsc_policy[] = {
2760         [TCA_HFSC_RSC] = {
2761             .type      = NL_A_UNSPEC,
2762             .optional  = false,
2763             .min_len   = sizeof(struct tc_service_curve),
2764         },
2765         [TCA_HFSC_FSC] = {
2766             .type      = NL_A_UNSPEC,
2767             .optional  = false,
2768             .min_len   = sizeof(struct tc_service_curve),
2769         },
2770         [TCA_HFSC_USC] = {
2771             .type      = NL_A_UNSPEC,
2772             .optional  = false,
2773             .min_len   = sizeof(struct tc_service_curve),
2774         },
2775     };
2776     struct nlattr *attrs[ARRAY_SIZE(tca_hfsc_policy)];
2777
2778     if (!nl_parse_nested(nl_options, tca_hfsc_policy,
2779                          attrs, ARRAY_SIZE(tca_hfsc_policy))) {
2780         VLOG_WARN_RL(&rl, "failed to parse HFSC class options");
2781         return EPROTO;
2782     }
2783
2784     rsc = nl_attr_get(attrs[TCA_HFSC_RSC]);
2785     fsc = nl_attr_get(attrs[TCA_HFSC_FSC]);
2786     usc = nl_attr_get(attrs[TCA_HFSC_USC]);
2787
2788     if (rsc->m1 != 0 || rsc->d != 0 ||
2789         fsc->m1 != 0 || fsc->d != 0 ||
2790         usc->m1 != 0 || usc->d != 0) {
2791         VLOG_WARN_RL(&rl, "failed to parse HFSC class options. "
2792                      "Non-linear service curves are not supported.");
2793         return EPROTO;
2794     }
2795
2796     if (rsc->m2 != fsc->m2) {
2797         VLOG_WARN_RL(&rl, "failed to parse HFSC class options. "
2798                      "Real-time service curves are not supported ");
2799         return EPROTO;
2800     }
2801
2802     if (rsc->m2 > usc->m2) {
2803         VLOG_WARN_RL(&rl, "failed to parse HFSC class options. "
2804                      "Min-rate service curve is greater than "
2805                      "the max-rate service curve.");
2806         return EPROTO;
2807     }
2808
2809     class->min_rate = fsc->m2;
2810     class->max_rate = usc->m2;
2811     return 0;
2812 }
2813
2814 static int
2815 hfsc_parse_tcmsg__(struct ofpbuf *tcmsg, unsigned int *queue_id,
2816                    struct hfsc_class *options,
2817                    struct netdev_queue_stats *stats)
2818 {
2819     int error;
2820     unsigned int handle;
2821     struct nlattr *nl_options;
2822
2823     error = tc_parse_class(tcmsg, &handle, &nl_options, stats);
2824     if (error) {
2825         return error;
2826     }
2827
2828     if (queue_id) {
2829         unsigned int major, minor;
2830
2831         major = tc_get_major(handle);
2832         minor = tc_get_minor(handle);
2833         if (major == 1 && minor > 0 && minor <= HFSC_N_QUEUES) {
2834             *queue_id = minor - 1;
2835         } else {
2836             return EPROTO;
2837         }
2838     }
2839
2840     if (options) {
2841         error = hfsc_parse_tca_options__(nl_options, options);
2842     }
2843
2844     return error;
2845 }
2846
2847 static int
2848 hfsc_query_class__(const struct netdev *netdev, unsigned int handle,
2849                    unsigned int parent, struct hfsc_class *options,
2850                    struct netdev_queue_stats *stats)
2851 {
2852     int error;
2853     struct ofpbuf *reply;
2854
2855     error = tc_query_class(netdev, handle, parent, &reply);
2856     if (error) {
2857         return error;
2858     }
2859
2860     error = hfsc_parse_tcmsg__(reply, NULL, options, stats);
2861     ofpbuf_delete(reply);
2862     return error;
2863 }
2864
2865 static void
2866 hfsc_parse_qdisc_details__(struct netdev *netdev, const struct shash *details,
2867                            struct hfsc_class *class)
2868 {
2869     uint32_t max_rate;
2870     const char *max_rate_s;
2871
2872     max_rate_s = shash_find_data(details, "max-rate");
2873     max_rate   = max_rate_s ? strtoull(max_rate_s, NULL, 10) / 8 : 0;
2874
2875     if (!max_rate) {
2876         uint32_t current;
2877
2878         netdev_get_features(netdev, &current, NULL, NULL, NULL);
2879         max_rate = netdev_features_to_bps(current) / 8;
2880     }
2881
2882     class->min_rate = max_rate;
2883     class->max_rate = max_rate;
2884 }
2885
2886 static int
2887 hfsc_parse_class_details__(struct netdev *netdev,
2888                            const struct shash *details,
2889                            struct hfsc_class * class)
2890 {
2891     const struct hfsc *hfsc;
2892     uint32_t min_rate, max_rate;
2893     const char *min_rate_s, *max_rate_s;
2894
2895     hfsc       = hfsc_get__(netdev);
2896     min_rate_s = shash_find_data(details, "min-rate");
2897     max_rate_s = shash_find_data(details, "max-rate");
2898
2899     if (!min_rate_s) {
2900         return EINVAL;
2901     }
2902
2903     min_rate = strtoull(min_rate_s, NULL, 10) / 8;
2904     min_rate = MAX(min_rate, 1500);
2905     min_rate = MIN(min_rate, hfsc->max_rate);
2906
2907     max_rate = (max_rate_s
2908                 ? strtoull(max_rate_s, NULL, 10) / 8
2909                 : hfsc->max_rate);
2910     max_rate = MAX(max_rate, min_rate);
2911     max_rate = MIN(max_rate, hfsc->max_rate);
2912
2913     class->min_rate = min_rate;
2914     class->max_rate = max_rate;
2915
2916     return 0;
2917 }
2918
2919 /* Create an HFSC qdisc.
2920  *
2921  * Equivalent to "tc qdisc add dev <dev> root handle 1: hfsc default 1". */
2922 static int
2923 hfsc_setup_qdisc__(struct netdev * netdev)
2924 {
2925     struct tcmsg *tcmsg;
2926     struct ofpbuf request;
2927     struct tc_hfsc_qopt opt;
2928
2929     tc_del_qdisc(netdev);
2930
2931     tcmsg = tc_make_request(netdev, RTM_NEWQDISC,
2932                             NLM_F_EXCL | NLM_F_CREATE, &request);
2933
2934     if (!tcmsg) {
2935         return ENODEV;
2936     }
2937
2938     tcmsg->tcm_handle = tc_make_handle(1, 0);
2939     tcmsg->tcm_parent = TC_H_ROOT;
2940
2941     memset(&opt, 0, sizeof opt);
2942     opt.defcls = 1;
2943
2944     nl_msg_put_string(&request, TCA_KIND, "hfsc");
2945     nl_msg_put_unspec(&request, TCA_OPTIONS, &opt, sizeof opt);
2946
2947     return tc_transact(&request, NULL);
2948 }
2949
2950 /* Create an HFSC class.
2951  *
2952  * Equivalent to "tc class add <dev> parent <parent> classid <handle> hfsc
2953  * sc rate <min_rate> ul rate <max_rate>" */
2954 static int
2955 hfsc_setup_class__(struct netdev *netdev, unsigned int handle,
2956                    unsigned int parent, struct hfsc_class *class)
2957 {
2958     int error;
2959     size_t opt_offset;
2960     struct tcmsg *tcmsg;
2961     struct ofpbuf request;
2962     struct tc_service_curve min, max;
2963
2964     tcmsg = tc_make_request(netdev, RTM_NEWTCLASS, NLM_F_CREATE, &request);
2965
2966     if (!tcmsg) {
2967         return ENODEV;
2968     }
2969
2970     tcmsg->tcm_handle = handle;
2971     tcmsg->tcm_parent = parent;
2972
2973     min.m1 = 0;
2974     min.d  = 0;
2975     min.m2 = class->min_rate;
2976
2977     max.m1 = 0;
2978     max.d  = 0;
2979     max.m2 = class->max_rate;
2980
2981     nl_msg_put_string(&request, TCA_KIND, "hfsc");
2982     opt_offset = nl_msg_start_nested(&request, TCA_OPTIONS);
2983     nl_msg_put_unspec(&request, TCA_HFSC_RSC, &min, sizeof min);
2984     nl_msg_put_unspec(&request, TCA_HFSC_FSC, &min, sizeof min);
2985     nl_msg_put_unspec(&request, TCA_HFSC_USC, &max, sizeof max);
2986     nl_msg_end_nested(&request, opt_offset);
2987
2988     error = tc_transact(&request, NULL);
2989     if (error) {
2990         VLOG_WARN_RL(&rl, "failed to replace %s class %u:%u, parent %u:%u, "
2991                      "min-rate %ubps, max-rate %ubps (%s)",
2992                      netdev_get_name(netdev),
2993                      tc_get_major(handle), tc_get_minor(handle),
2994                      tc_get_major(parent), tc_get_minor(parent),
2995                      class->min_rate, class->max_rate, strerror(error));
2996     }
2997
2998     return error;
2999 }
3000
3001 static int
3002 hfsc_tc_install(struct netdev *netdev, const struct shash *details)
3003 {
3004     int error;
3005     struct hfsc_class class;
3006
3007     error = hfsc_setup_qdisc__(netdev);
3008
3009     if (error) {
3010         return error;
3011     }
3012
3013     hfsc_parse_qdisc_details__(netdev, details, &class);
3014     error = hfsc_setup_class__(netdev, tc_make_handle(1, 0xfffe),
3015                                tc_make_handle(1, 0), &class);
3016
3017     if (error) {
3018         return error;
3019     }
3020
3021     hfsc_install__(netdev, class.max_rate);
3022     return 0;
3023 }
3024
3025 static int
3026 hfsc_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
3027 {
3028     struct ofpbuf msg;
3029     struct hfsc *hfsc;
3030     struct nl_dump dump;
3031     struct hfsc_class hc;
3032
3033     hc.max_rate = 0;
3034     hfsc_query_class__(netdev, tc_make_handle(1, 0xfffe), 0, &hc, NULL);
3035     hfsc = hfsc_install__(netdev, hc.max_rate);
3036
3037     if (!start_queue_dump(netdev, &dump)) {
3038         return ENODEV;
3039     }
3040
3041     while (nl_dump_next(&dump, &msg)) {
3042         unsigned int queue_id;
3043
3044         if (!hfsc_parse_tcmsg__(&msg, &queue_id, &hc, NULL)) {
3045             hfsc_update_queue__(netdev, queue_id, &hc);
3046         }
3047     }
3048
3049     nl_dump_done(&dump);
3050     return 0;
3051 }
3052
3053 static void
3054 hfsc_tc_destroy(struct tc *tc)
3055 {
3056     struct hfsc *hfsc;
3057     struct hfsc_class *hc, *next;
3058
3059     hfsc = CONTAINER_OF(tc, struct hfsc, tc);
3060
3061     HMAP_FOR_EACH_SAFE (hc, next, tc_queue.hmap_node, &hfsc->tc.queues) {
3062         hmap_remove(&hfsc->tc.queues, &hc->tc_queue.hmap_node);
3063         free(hc);
3064     }
3065
3066     tc_destroy(tc);
3067     free(hfsc);
3068 }
3069
3070 static int
3071 hfsc_qdisc_get(const struct netdev *netdev, struct shash *details)
3072 {
3073     const struct hfsc *hfsc;
3074     hfsc = hfsc_get__(netdev);
3075     shash_add(details, "max-rate", xasprintf("%llu", 8ULL * hfsc->max_rate));
3076     return 0;
3077 }
3078
3079 static int
3080 hfsc_qdisc_set(struct netdev *netdev, const struct shash *details)
3081 {
3082     int error;
3083     struct hfsc_class class;
3084
3085     hfsc_parse_qdisc_details__(netdev, details, &class);
3086     error = hfsc_setup_class__(netdev, tc_make_handle(1, 0xfffe),
3087                                tc_make_handle(1, 0), &class);
3088
3089     if (!error) {
3090         hfsc_get__(netdev)->max_rate = class.max_rate;
3091     }
3092
3093     return error;
3094 }
3095
3096 static int
3097 hfsc_class_get(const struct netdev *netdev OVS_UNUSED,
3098               const struct tc_queue *queue, struct shash *details)
3099 {
3100     const struct hfsc_class *hc;
3101
3102     hc = hfsc_class_cast__(queue);
3103     shash_add(details, "min-rate", xasprintf("%llu", 8ULL * hc->min_rate));
3104     if (hc->min_rate != hc->max_rate) {
3105         shash_add(details, "max-rate", xasprintf("%llu", 8ULL * hc->max_rate));
3106     }
3107     return 0;
3108 }
3109
3110 static int
3111 hfsc_class_set(struct netdev *netdev, unsigned int queue_id,
3112                const struct shash *details)
3113 {
3114     int error;
3115     struct hfsc_class class;
3116
3117     error = hfsc_parse_class_details__(netdev, details, &class);
3118     if (error) {
3119         return error;
3120     }
3121
3122     error = hfsc_setup_class__(netdev, tc_make_handle(1, queue_id + 1),
3123                                tc_make_handle(1, 0xfffe), &class);
3124     if (error) {
3125         return error;
3126     }
3127
3128     hfsc_update_queue__(netdev, queue_id, &class);
3129     return 0;
3130 }
3131
3132 static int
3133 hfsc_class_delete(struct netdev *netdev, struct tc_queue *queue)
3134 {
3135     int error;
3136     struct hfsc *hfsc;
3137     struct hfsc_class *hc;
3138
3139     hc   = hfsc_class_cast__(queue);
3140     hfsc = hfsc_get__(netdev);
3141
3142     error = tc_delete_class(netdev, tc_make_handle(1, queue->queue_id + 1));
3143     if (!error) {
3144         hmap_remove(&hfsc->tc.queues, &hc->tc_queue.hmap_node);
3145         free(hc);
3146     }
3147     return error;
3148 }
3149
3150 static int
3151 hfsc_class_get_stats(const struct netdev *netdev, const struct tc_queue *queue,
3152                      struct netdev_queue_stats *stats)
3153 {
3154     return hfsc_query_class__(netdev, tc_make_handle(1, queue->queue_id + 1),
3155                              tc_make_handle(1, 0xfffe), NULL, stats);
3156 }
3157
3158 static int
3159 hfsc_class_dump_stats(const struct netdev *netdev OVS_UNUSED,
3160                       const struct ofpbuf *nlmsg,
3161                       netdev_dump_queue_stats_cb *cb, void *aux)
3162 {
3163     struct netdev_queue_stats stats;
3164     unsigned int handle, major, minor;
3165     int error;
3166
3167     error = tc_parse_class(nlmsg, &handle, NULL, &stats);
3168     if (error) {
3169         return error;
3170     }
3171
3172     major = tc_get_major(handle);
3173     minor = tc_get_minor(handle);
3174     if (major == 1 && minor > 0 && minor <= HFSC_N_QUEUES) {
3175         (*cb)(minor - 1, &stats, aux);
3176     }
3177     return 0;
3178 }
3179
3180 static const struct tc_ops tc_ops_hfsc = {
3181     "hfsc",                     /* linux_name */
3182     "linux-hfsc",               /* ovs_name */
3183     HFSC_N_QUEUES,              /* n_queues */
3184     hfsc_tc_install,            /* tc_install */
3185     hfsc_tc_load,               /* tc_load */
3186     hfsc_tc_destroy,            /* tc_destroy */
3187     hfsc_qdisc_get,             /* qdisc_get */
3188     hfsc_qdisc_set,             /* qdisc_set */
3189     hfsc_class_get,             /* class_get */
3190     hfsc_class_set,             /* class_set */
3191     hfsc_class_delete,          /* class_delete */
3192     hfsc_class_get_stats,       /* class_get_stats */
3193     hfsc_class_dump_stats       /* class_dump_stats */
3194 };
3195 \f
3196 /* "linux-default" traffic control class.
3197  *
3198  * This class represents the default, unnamed Linux qdisc.  It corresponds to
3199  * the "" (empty string) QoS type in the OVS database. */
3200
3201 static void
3202 default_install__(struct netdev *netdev)
3203 {
3204     struct netdev_dev_linux *netdev_dev =
3205                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
3206     static struct tc *tc;
3207
3208     if (!tc) {
3209         tc = xmalloc(sizeof *tc);
3210         tc_init(tc, &tc_ops_default);
3211     }
3212     netdev_dev->tc = tc;
3213 }
3214
3215 static int
3216 default_tc_install(struct netdev *netdev,
3217                    const struct shash *details OVS_UNUSED)
3218 {
3219     default_install__(netdev);
3220     return 0;
3221 }
3222
3223 static int
3224 default_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
3225 {
3226     default_install__(netdev);
3227     return 0;
3228 }
3229
3230 static const struct tc_ops tc_ops_default = {
3231     NULL,                       /* linux_name */
3232     "",                         /* ovs_name */
3233     0,                          /* n_queues */
3234     default_tc_install,
3235     default_tc_load,
3236     NULL,                       /* tc_destroy */
3237     NULL,                       /* qdisc_get */
3238     NULL,                       /* qdisc_set */
3239     NULL,                       /* class_get */
3240     NULL,                       /* class_set */
3241     NULL,                       /* class_delete */
3242     NULL,                       /* class_get_stats */
3243     NULL                        /* class_dump_stats */
3244 };
3245 \f
3246 /* "linux-other" traffic control class.
3247  *
3248  * */
3249
3250 static int
3251 other_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
3252 {
3253     struct netdev_dev_linux *netdev_dev =
3254                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
3255     static struct tc *tc;
3256
3257     if (!tc) {
3258         tc = xmalloc(sizeof *tc);
3259         tc_init(tc, &tc_ops_other);
3260     }
3261     netdev_dev->tc = tc;
3262     return 0;
3263 }
3264
3265 static const struct tc_ops tc_ops_other = {
3266     NULL,                       /* linux_name */
3267     "linux-other",              /* ovs_name */
3268     0,                          /* n_queues */
3269     NULL,                       /* tc_install */
3270     other_tc_load,
3271     NULL,                       /* tc_destroy */
3272     NULL,                       /* qdisc_get */
3273     NULL,                       /* qdisc_set */
3274     NULL,                       /* class_get */
3275     NULL,                       /* class_set */
3276     NULL,                       /* class_delete */
3277     NULL,                       /* class_get_stats */
3278     NULL                        /* class_dump_stats */
3279 };
3280 \f
3281 /* Traffic control. */
3282
3283 /* Number of kernel "tc" ticks per second. */
3284 static double ticks_per_s;
3285
3286 /* Number of kernel "jiffies" per second.  This is used for the purpose of
3287  * computing buffer sizes.  Generally kernel qdiscs need to be able to buffer
3288  * one jiffy's worth of data.
3289  *
3290  * There are two possibilities here:
3291  *
3292  *    - 'buffer_hz' is the kernel's real timer tick rate, a small number in the
3293  *      approximate range of 100 to 1024.  That means that we really need to
3294  *      make sure that the qdisc can buffer that much data.
3295  *
3296  *    - 'buffer_hz' is an absurdly large number.  That means that the kernel
3297  *      has finely granular timers and there's no need to fudge additional room
3298  *      for buffers.  (There's no extra effort needed to implement that: the
3299  *      large 'buffer_hz' is used as a divisor, so practically any number will
3300  *      come out as 0 in the division.  Small integer results in the case of
3301  *      really high dividends won't have any real effect anyhow.)
3302  */
3303 static unsigned int buffer_hz;
3304
3305 /* Returns tc handle 'major':'minor'. */
3306 static unsigned int
3307 tc_make_handle(unsigned int major, unsigned int minor)
3308 {
3309     return TC_H_MAKE(major << 16, minor);
3310 }
3311
3312 /* Returns the major number from 'handle'. */
3313 static unsigned int
3314 tc_get_major(unsigned int handle)
3315 {
3316     return TC_H_MAJ(handle) >> 16;
3317 }
3318
3319 /* Returns the minor number from 'handle'. */
3320 static unsigned int
3321 tc_get_minor(unsigned int handle)
3322 {
3323     return TC_H_MIN(handle);
3324 }
3325
3326 static struct tcmsg *
3327 tc_make_request(const struct netdev *netdev, int type, unsigned int flags,
3328                 struct ofpbuf *request)
3329 {
3330     struct tcmsg *tcmsg;
3331     int ifindex;
3332     int error;
3333
3334     error = get_ifindex(netdev, &ifindex);
3335     if (error) {
3336         return NULL;
3337     }
3338
3339     ofpbuf_init(request, 512);
3340     nl_msg_put_nlmsghdr(request, sizeof *tcmsg, type, NLM_F_REQUEST | flags);
3341     tcmsg = ofpbuf_put_zeros(request, sizeof *tcmsg);
3342     tcmsg->tcm_family = AF_UNSPEC;
3343     tcmsg->tcm_ifindex = ifindex;
3344     /* Caller should fill in tcmsg->tcm_handle. */
3345     /* Caller should fill in tcmsg->tcm_parent. */
3346
3347     return tcmsg;
3348 }
3349
3350 static int
3351 tc_transact(struct ofpbuf *request, struct ofpbuf **replyp)
3352 {
3353     int error = nl_sock_transact(rtnl_sock, request, replyp);
3354     ofpbuf_uninit(request);
3355     return error;
3356 }
3357
3358 static void
3359 read_psched(void)
3360 {
3361     /* The values in psched are not individually very meaningful, but they are
3362      * important.  The tables below show some values seen in the wild.
3363      *
3364      * Some notes:
3365      *
3366      *   - "c" has always been a constant 1000000 since at least Linux 2.4.14.
3367      *     (Before that, there are hints that it was 1000000000.)
3368      *
3369      *   - "d" can be unrealistically large, see the comment on 'buffer_hz'
3370      *     above.
3371      *
3372      *                        /proc/net/psched
3373      *     -----------------------------------
3374      * [1] 000c8000 000f4240 000f4240 00000064
3375      * [2] 000003e8 00000400 000f4240 3b9aca00
3376      * [3] 000003e8 00000400 000f4240 3b9aca00
3377      * [4] 000003e8 00000400 000f4240 00000064
3378      * [5] 000003e8 00000040 000f4240 3b9aca00
3379      * [6] 000003e8 00000040 000f4240 000000f9
3380      *
3381      *           a         b          c             d ticks_per_s     buffer_hz
3382      *     ------- --------- ---------- ------------- ----------- -------------
3383      * [1] 819,200 1,000,000  1,000,000           100     819,200           100
3384      * [2]   1,000     1,024  1,000,000 1,000,000,000     976,562 1,000,000,000
3385      * [3]   1,000     1,024  1,000,000 1,000,000,000     976,562 1,000,000,000
3386      * [4]   1,000     1,024  1,000,000           100     976,562           100
3387      * [5]   1,000        64  1,000,000 1,000,000,000  15,625,000 1,000,000,000
3388      * [6]   1,000        64  1,000,000           249  15,625,000           249
3389      *
3390      * [1] 2.6.18-128.1.6.el5.xs5.5.0.505.1024xen from XenServer 5.5.0-24648p
3391      * [2] 2.6.26-1-686-bigmem from Debian lenny
3392      * [3] 2.6.26-2-sparc64 from Debian lenny
3393      * [4] 2.6.27.42-0.1.1.xs5.6.810.44.111163xen from XenServer 5.6.810-31078p
3394      * [5] 2.6.32.21.22 (approx.) from Ubuntu 10.04 on VMware Fusion
3395      * [6] 2.6.34 from kernel.org on KVM
3396      */
3397     static const char fn[] = "/proc/net/psched";
3398     unsigned int a, b, c, d;
3399     FILE *stream;
3400
3401     ticks_per_s = 1.0;
3402     buffer_hz = 100;
3403
3404     stream = fopen(fn, "r");
3405     if (!stream) {
3406         VLOG_WARN("%s: open failed: %s", fn, strerror(errno));
3407         return;
3408     }
3409
3410     if (fscanf(stream, "%x %x %x %x", &a, &b, &c, &d) != 4) {
3411         VLOG_WARN("%s: read failed", fn);
3412         fclose(stream);
3413         return;
3414     }
3415     VLOG_DBG("%s: psched parameters are: %u %u %u %u", fn, a, b, c, d);
3416     fclose(stream);
3417
3418     if (!a || !c) {
3419         VLOG_WARN("%s: invalid scheduler parameters", fn);
3420         return;
3421     }
3422
3423     ticks_per_s = (double) a * c / b;
3424     if (c == 1000000) {
3425         buffer_hz = d;
3426     } else {
3427         VLOG_WARN("%s: unexpected psched parameters: %u %u %u %u",
3428                   fn, a, b, c, d);
3429     }
3430     VLOG_DBG("%s: ticks_per_s=%f buffer_hz=%u", fn, ticks_per_s, buffer_hz);
3431 }
3432
3433 /* Returns the number of bytes that can be transmitted in 'ticks' ticks at a
3434  * rate of 'rate' bytes per second. */
3435 static unsigned int
3436 tc_ticks_to_bytes(unsigned int rate, unsigned int ticks)
3437 {
3438     if (!buffer_hz) {
3439         read_psched();
3440     }
3441     return (rate * ticks) / ticks_per_s;
3442 }
3443
3444 /* Returns the number of ticks that it would take to transmit 'size' bytes at a
3445  * rate of 'rate' bytes per second. */
3446 static unsigned int
3447 tc_bytes_to_ticks(unsigned int rate, unsigned int size)
3448 {
3449     if (!buffer_hz) {
3450         read_psched();
3451     }
3452     return rate ? ((unsigned long long int) ticks_per_s * size) / rate : 0;
3453 }
3454
3455 /* Returns the number of bytes that need to be reserved for qdisc buffering at
3456  * a transmission rate of 'rate' bytes per second. */
3457 static unsigned int
3458 tc_buffer_per_jiffy(unsigned int rate)
3459 {
3460     if (!buffer_hz) {
3461         read_psched();
3462     }
3463     return rate / buffer_hz;
3464 }
3465
3466 /* Given Netlink 'msg' that describes a qdisc, extracts the name of the qdisc,
3467  * e.g. "htb", into '*kind' (if it is nonnull).  If 'options' is nonnull,
3468  * extracts 'msg''s TCA_OPTIONS attributes into '*options' if it is present or
3469  * stores NULL into it if it is absent.
3470  *
3471  * '*kind' and '*options' point into 'msg', so they are owned by whoever owns
3472  * 'msg'.
3473  *
3474  * Returns 0 if successful, otherwise a positive errno value. */
3475 static int
3476 tc_parse_qdisc(const struct ofpbuf *msg, const char **kind,
3477                struct nlattr **options)
3478 {
3479     static const struct nl_policy tca_policy[] = {
3480         [TCA_KIND] = { .type = NL_A_STRING, .optional = false },
3481         [TCA_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
3482     };
3483     struct nlattr *ta[ARRAY_SIZE(tca_policy)];
3484
3485     if (!nl_policy_parse(msg, NLMSG_HDRLEN + sizeof(struct tcmsg),
3486                          tca_policy, ta, ARRAY_SIZE(ta))) {
3487         VLOG_WARN_RL(&rl, "failed to parse qdisc message");
3488         goto error;
3489     }
3490
3491     if (kind) {
3492         *kind = nl_attr_get_string(ta[TCA_KIND]);
3493     }
3494
3495     if (options) {
3496         *options = ta[TCA_OPTIONS];
3497     }
3498
3499     return 0;
3500
3501 error:
3502     if (kind) {
3503         *kind = NULL;
3504     }
3505     if (options) {
3506         *options = NULL;
3507     }
3508     return EPROTO;
3509 }
3510
3511 /* Given Netlink 'msg' that describes a class, extracts the queue ID (e.g. the
3512  * minor number of its class ID) into '*queue_id', its TCA_OPTIONS attribute
3513  * into '*options', and its queue statistics into '*stats'.  Any of the output
3514  * arguments may be null.
3515  *
3516  * Returns 0 if successful, otherwise a positive errno value. */
3517 static int
3518 tc_parse_class(const struct ofpbuf *msg, unsigned int *handlep,
3519                struct nlattr **options, struct netdev_queue_stats *stats)
3520 {
3521     static const struct nl_policy tca_policy[] = {
3522         [TCA_OPTIONS] = { .type = NL_A_NESTED, .optional = false },
3523         [TCA_STATS2] = { .type = NL_A_NESTED, .optional = false },
3524     };
3525     struct nlattr *ta[ARRAY_SIZE(tca_policy)];
3526
3527     if (!nl_policy_parse(msg, NLMSG_HDRLEN + sizeof(struct tcmsg),
3528                          tca_policy, ta, ARRAY_SIZE(ta))) {
3529         VLOG_WARN_RL(&rl, "failed to parse class message");
3530         goto error;
3531     }
3532
3533     if (handlep) {
3534         struct tcmsg *tc = ofpbuf_at_assert(msg, NLMSG_HDRLEN, sizeof *tc);
3535         *handlep = tc->tcm_handle;
3536     }
3537
3538     if (options) {
3539         *options = ta[TCA_OPTIONS];
3540     }
3541
3542     if (stats) {
3543         const struct gnet_stats_queue *gsq;
3544         struct gnet_stats_basic gsb;
3545
3546         static const struct nl_policy stats_policy[] = {
3547             [TCA_STATS_BASIC] = { .type = NL_A_UNSPEC, .optional = false,
3548                                   .min_len = sizeof gsb },
3549             [TCA_STATS_QUEUE] = { .type = NL_A_UNSPEC, .optional = false,
3550                                   .min_len = sizeof *gsq },
3551         };
3552         struct nlattr *sa[ARRAY_SIZE(stats_policy)];
3553
3554         if (!nl_parse_nested(ta[TCA_STATS2], stats_policy,
3555                              sa, ARRAY_SIZE(sa))) {
3556             VLOG_WARN_RL(&rl, "failed to parse class stats");
3557             goto error;
3558         }
3559
3560         /* Alignment issues screw up the length of struct gnet_stats_basic on
3561          * some arch/bitsize combinations.  Newer versions of Linux have a
3562          * struct gnet_stats_basic_packed, but we can't depend on that.  The
3563          * easiest thing to do is just to make a copy. */
3564         memset(&gsb, 0, sizeof gsb);
3565         memcpy(&gsb, nl_attr_get(sa[TCA_STATS_BASIC]),
3566                MIN(nl_attr_get_size(sa[TCA_STATS_BASIC]), sizeof gsb));
3567         stats->tx_bytes = gsb.bytes;
3568         stats->tx_packets = gsb.packets;
3569
3570         gsq = nl_attr_get(sa[TCA_STATS_QUEUE]);
3571         stats->tx_errors = gsq->drops;
3572     }
3573
3574     return 0;
3575
3576 error:
3577     if (options) {
3578         *options = NULL;
3579     }
3580     if (stats) {
3581         memset(stats, 0, sizeof *stats);
3582     }
3583     return EPROTO;
3584 }
3585
3586 /* Queries the kernel for class with identifier 'handle' and parent 'parent'
3587  * on 'netdev'. */
3588 static int
3589 tc_query_class(const struct netdev *netdev,
3590                unsigned int handle, unsigned int parent,
3591                struct ofpbuf **replyp)
3592 {
3593     struct ofpbuf request;
3594     struct tcmsg *tcmsg;
3595     int error;
3596
3597     tcmsg = tc_make_request(netdev, RTM_GETTCLASS, NLM_F_ECHO, &request);
3598     if (!tcmsg) {
3599         return ENODEV;
3600     }
3601     tcmsg->tcm_handle = handle;
3602     tcmsg->tcm_parent = parent;
3603
3604     error = tc_transact(&request, replyp);
3605     if (error) {
3606         VLOG_WARN_RL(&rl, "query %s class %u:%u (parent %u:%u) failed (%s)",
3607                      netdev_get_name(netdev),
3608                      tc_get_major(handle), tc_get_minor(handle),
3609                      tc_get_major(parent), tc_get_minor(parent),
3610                      strerror(error));
3611     }
3612     return error;
3613 }
3614
3615 /* Equivalent to "tc class del dev <name> handle <handle>". */
3616 static int
3617 tc_delete_class(const struct netdev *netdev, unsigned int handle)
3618 {
3619     struct ofpbuf request;
3620     struct tcmsg *tcmsg;
3621     int error;
3622
3623     tcmsg = tc_make_request(netdev, RTM_DELTCLASS, 0, &request);
3624     if (!tcmsg) {
3625         return ENODEV;
3626     }
3627     tcmsg->tcm_handle = handle;
3628     tcmsg->tcm_parent = 0;
3629
3630     error = tc_transact(&request, NULL);
3631     if (error) {
3632         VLOG_WARN_RL(&rl, "delete %s class %u:%u failed (%s)",
3633                      netdev_get_name(netdev),
3634                      tc_get_major(handle), tc_get_minor(handle),
3635                      strerror(error));
3636     }
3637     return error;
3638 }
3639
3640 /* Equivalent to "tc qdisc del dev <name> root". */
3641 static int
3642 tc_del_qdisc(struct netdev *netdev)
3643 {
3644     struct netdev_dev_linux *netdev_dev =
3645                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
3646     struct ofpbuf request;
3647     struct tcmsg *tcmsg;
3648     int error;
3649
3650     tcmsg = tc_make_request(netdev, RTM_DELQDISC, 0, &request);
3651     if (!tcmsg) {
3652         return ENODEV;
3653     }
3654     tcmsg->tcm_handle = tc_make_handle(1, 0);
3655     tcmsg->tcm_parent = TC_H_ROOT;
3656
3657     error = tc_transact(&request, NULL);
3658     if (error == EINVAL) {
3659         /* EINVAL probably means that the default qdisc was in use, in which
3660          * case we've accomplished our purpose. */
3661         error = 0;
3662     }
3663     if (!error && netdev_dev->tc) {
3664         if (netdev_dev->tc->ops->tc_destroy) {
3665             netdev_dev->tc->ops->tc_destroy(netdev_dev->tc);
3666         }
3667         netdev_dev->tc = NULL;
3668     }
3669     return error;
3670 }
3671
3672 /* If 'netdev''s qdisc type and parameters are not yet known, queries the
3673  * kernel to determine what they are.  Returns 0 if successful, otherwise a
3674  * positive errno value. */
3675 static int
3676 tc_query_qdisc(const struct netdev *netdev)
3677 {
3678     struct netdev_dev_linux *netdev_dev =
3679                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
3680     struct ofpbuf request, *qdisc;
3681     const struct tc_ops *ops;
3682     struct tcmsg *tcmsg;
3683     int load_error;
3684     int error;
3685
3686     if (netdev_dev->tc) {
3687         return 0;
3688     }
3689
3690     /* This RTM_GETQDISC is crafted to avoid OOPSing kernels that do not have
3691      * commit 53b0f08 "net_sched: Fix qdisc_notify()", which is anything before
3692      * 2.6.35 without that fix backported to it.
3693      *
3694      * To avoid the OOPS, we must not make a request that would attempt to dump
3695      * a "built-in" qdisc, that is, the default pfifo_fast qdisc or one of a
3696      * few others.  There are a few ways that I can see to do this, but most of
3697      * them seem to be racy (and if you lose the race the kernel OOPSes).  The
3698      * technique chosen here is to assume that any non-default qdisc that we
3699      * create will have a class with handle 1:0.  The built-in qdiscs only have
3700      * a class with handle 0:0.
3701      *
3702      * We could check for Linux 2.6.35+ and use a more straightforward method
3703      * there. */
3704     tcmsg = tc_make_request(netdev, RTM_GETQDISC, NLM_F_ECHO, &request);
3705     if (!tcmsg) {
3706         return ENODEV;
3707     }
3708     tcmsg->tcm_handle = tc_make_handle(1, 0);
3709     tcmsg->tcm_parent = 0;
3710
3711     /* Figure out what tc class to instantiate. */
3712     error = tc_transact(&request, &qdisc);
3713     if (!error) {
3714         const char *kind;
3715
3716         error = tc_parse_qdisc(qdisc, &kind, NULL);
3717         if (error) {
3718             ops = &tc_ops_other;
3719         } else {
3720             ops = tc_lookup_linux_name(kind);
3721             if (!ops) {
3722                 static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 1);
3723                 VLOG_INFO_RL(&rl2, "unknown qdisc \"%s\"", kind);
3724
3725                 ops = &tc_ops_other;
3726             }
3727         }
3728     } else if (error == ENOENT) {
3729         /* Either it's a built-in qdisc, or it's a qdisc set up by some
3730          * other entity that doesn't have a handle 1:0.  We will assume
3731          * that it's the system default qdisc. */
3732         ops = &tc_ops_default;
3733         error = 0;
3734     } else {
3735         /* Who knows?  Maybe the device got deleted. */
3736         VLOG_WARN_RL(&rl, "query %s qdisc failed (%s)",
3737                      netdev_get_name(netdev), strerror(error));
3738         ops = &tc_ops_other;
3739     }
3740
3741     /* Instantiate it. */
3742     load_error = ops->tc_load((struct netdev *) netdev, qdisc);
3743     assert((load_error == 0) == (netdev_dev->tc != NULL));
3744     ofpbuf_delete(qdisc);
3745
3746     return error ? error : load_error;
3747 }
3748
3749 /* Linux traffic control uses tables with 256 entries ("rtab" tables) to
3750    approximate the time to transmit packets of various lengths.  For an MTU of
3751    256 or less, each entry is exact; for an MTU of 257 through 512, each entry
3752    represents two possible packet lengths; for a MTU of 513 through 1024, four
3753    possible lengths; and so on.
3754
3755    Returns, for the specified 'mtu', the number of bits that packet lengths
3756    need to be shifted right to fit within such a 256-entry table. */
3757 static int
3758 tc_calc_cell_log(unsigned int mtu)
3759 {
3760     int cell_log;
3761
3762     if (!mtu) {
3763         mtu = ETH_PAYLOAD_MAX;
3764     }
3765     mtu += ETH_HEADER_LEN + VLAN_HEADER_LEN;
3766
3767     for (cell_log = 0; mtu >= 256; cell_log++) {
3768         mtu >>= 1;
3769     }
3770
3771     return cell_log;
3772 }
3773
3774 /* Initializes 'rate' properly for a rate of 'Bps' bytes per second with an MTU
3775  * of 'mtu'. */
3776 static void
3777 tc_fill_rate(struct tc_ratespec *rate, uint64_t Bps, int mtu)
3778 {
3779     memset(rate, 0, sizeof *rate);
3780     rate->cell_log = tc_calc_cell_log(mtu);
3781     /* rate->overhead = 0; */           /* New in 2.6.24, not yet in some */
3782     /* rate->cell_align = 0; */         /* distro headers. */
3783     rate->mpu = ETH_TOTAL_MIN;
3784     rate->rate = Bps;
3785 }
3786
3787 /* Appends to 'msg' an "rtab" table for the specified 'rate' as a Netlink
3788  * attribute of the specified "type".
3789  *
3790  * See tc_calc_cell_log() above for a description of "rtab"s. */
3791 static void
3792 tc_put_rtab(struct ofpbuf *msg, uint16_t type, const struct tc_ratespec *rate)
3793 {
3794     uint32_t *rtab;
3795     unsigned int i;
3796
3797     rtab = nl_msg_put_unspec_uninit(msg, type, TC_RTAB_SIZE);
3798     for (i = 0; i < TC_RTAB_SIZE / sizeof *rtab; i++) {
3799         unsigned packet_size = (i + 1) << rate->cell_log;
3800         if (packet_size < rate->mpu) {
3801             packet_size = rate->mpu;
3802         }
3803         rtab[i] = tc_bytes_to_ticks(rate->rate, packet_size);
3804     }
3805 }
3806
3807 /* Calculates the proper value of 'buffer' or 'cbuffer' in HTB options given a
3808  * rate of 'Bps' bytes per second, the specified 'mtu', and a user-requested
3809  * burst size of 'burst_bytes'.  (If no value was requested, a 'burst_bytes' of
3810  * 0 is fine.) */
3811 static int
3812 tc_calc_buffer(unsigned int Bps, int mtu, uint64_t burst_bytes)
3813 {
3814     unsigned int min_burst = tc_buffer_per_jiffy(Bps) + mtu;
3815     return tc_bytes_to_ticks(Bps, MAX(burst_bytes, min_burst));
3816 }
3817
3818 \f
3819 /* Utility functions. */
3820
3821 static int
3822 get_stats_via_netlink(int ifindex, struct netdev_stats *stats)
3823 {
3824     /* Policy for RTNLGRP_LINK messages.
3825      *
3826      * There are *many* more fields in these messages, but currently we only
3827      * care about these fields. */
3828     static const struct nl_policy rtnlgrp_link_policy[] = {
3829         [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
3830         [IFLA_STATS] = { .type = NL_A_UNSPEC, .optional = true,
3831                          .min_len = sizeof(struct rtnl_link_stats) },
3832     };
3833
3834     struct ofpbuf request;
3835     struct ofpbuf *reply;
3836     struct ifinfomsg *ifi;
3837     const struct rtnl_link_stats *rtnl_stats;
3838     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
3839     int error;
3840
3841     ofpbuf_init(&request, 0);
3842     nl_msg_put_nlmsghdr(&request, sizeof *ifi, RTM_GETLINK, NLM_F_REQUEST);
3843     ifi = ofpbuf_put_zeros(&request, sizeof *ifi);
3844     ifi->ifi_family = PF_UNSPEC;
3845     ifi->ifi_index = ifindex;
3846     error = nl_sock_transact(rtnl_sock, &request, &reply);
3847     ofpbuf_uninit(&request);
3848     if (error) {
3849         return error;
3850     }
3851
3852     if (!nl_policy_parse(reply, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
3853                          rtnlgrp_link_policy,
3854                          attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
3855         ofpbuf_delete(reply);
3856         return EPROTO;
3857     }
3858
3859     if (!attrs[IFLA_STATS]) {
3860         VLOG_WARN_RL(&rl, "RTM_GETLINK reply lacks stats");
3861         ofpbuf_delete(reply);
3862         return EPROTO;
3863     }
3864
3865     rtnl_stats = nl_attr_get(attrs[IFLA_STATS]);
3866     stats->rx_packets = rtnl_stats->rx_packets;
3867     stats->tx_packets = rtnl_stats->tx_packets;
3868     stats->rx_bytes = rtnl_stats->rx_bytes;
3869     stats->tx_bytes = rtnl_stats->tx_bytes;
3870     stats->rx_errors = rtnl_stats->rx_errors;
3871     stats->tx_errors = rtnl_stats->tx_errors;
3872     stats->rx_dropped = rtnl_stats->rx_dropped;
3873     stats->tx_dropped = rtnl_stats->tx_dropped;
3874     stats->multicast = rtnl_stats->multicast;
3875     stats->collisions = rtnl_stats->collisions;
3876     stats->rx_length_errors = rtnl_stats->rx_length_errors;
3877     stats->rx_over_errors = rtnl_stats->rx_over_errors;
3878     stats->rx_crc_errors = rtnl_stats->rx_crc_errors;
3879     stats->rx_frame_errors = rtnl_stats->rx_frame_errors;
3880     stats->rx_fifo_errors = rtnl_stats->rx_fifo_errors;
3881     stats->rx_missed_errors = rtnl_stats->rx_missed_errors;
3882     stats->tx_aborted_errors = rtnl_stats->tx_aborted_errors;
3883     stats->tx_carrier_errors = rtnl_stats->tx_carrier_errors;
3884     stats->tx_fifo_errors = rtnl_stats->tx_fifo_errors;
3885     stats->tx_heartbeat_errors = rtnl_stats->tx_heartbeat_errors;
3886     stats->tx_window_errors = rtnl_stats->tx_window_errors;
3887
3888     ofpbuf_delete(reply);
3889
3890     return 0;
3891 }
3892
3893 static int
3894 get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats)
3895 {
3896     static const char fn[] = "/proc/net/dev";
3897     char line[1024];
3898     FILE *stream;
3899     int ln;
3900
3901     stream = fopen(fn, "r");
3902     if (!stream) {
3903         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
3904         return errno;
3905     }
3906
3907     ln = 0;
3908     while (fgets(line, sizeof line, stream)) {
3909         if (++ln >= 3) {
3910             char devname[16];
3911 #define X64 "%"SCNu64
3912             if (sscanf(line,
3913                        " %15[^:]:"
3914                        X64 X64 X64 X64 X64 X64 X64 "%*u"
3915                        X64 X64 X64 X64 X64 X64 X64 "%*u",
3916                        devname,
3917                        &stats->rx_bytes,
3918                        &stats->rx_packets,
3919                        &stats->rx_errors,
3920                        &stats->rx_dropped,
3921                        &stats->rx_fifo_errors,
3922                        &stats->rx_frame_errors,
3923                        &stats->multicast,
3924                        &stats->tx_bytes,
3925                        &stats->tx_packets,
3926                        &stats->tx_errors,
3927                        &stats->tx_dropped,
3928                        &stats->tx_fifo_errors,
3929                        &stats->collisions,
3930                        &stats->tx_carrier_errors) != 15) {
3931                 VLOG_WARN_RL(&rl, "%s:%d: parse error", fn, ln);
3932             } else if (!strcmp(devname, netdev_name)) {
3933                 stats->rx_length_errors = UINT64_MAX;
3934                 stats->rx_over_errors = UINT64_MAX;
3935                 stats->rx_crc_errors = UINT64_MAX;
3936                 stats->rx_missed_errors = UINT64_MAX;
3937                 stats->tx_aborted_errors = UINT64_MAX;
3938                 stats->tx_heartbeat_errors = UINT64_MAX;
3939                 stats->tx_window_errors = UINT64_MAX;
3940                 fclose(stream);
3941                 return 0;
3942             }
3943         }
3944     }
3945     VLOG_WARN_RL(&rl, "%s: no stats for %s", fn, netdev_name);
3946     fclose(stream);
3947     return ENODEV;
3948 }
3949
3950 static int
3951 get_flags(const struct netdev *netdev, int *flags)
3952 {
3953     struct ifreq ifr;
3954     int error;
3955
3956     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCGIFFLAGS,
3957                                   "SIOCGIFFLAGS");
3958     *flags = ifr.ifr_flags;
3959     return error;
3960 }
3961
3962 static int
3963 set_flags(struct netdev *netdev, int flags)
3964 {
3965     struct ifreq ifr;
3966
3967     ifr.ifr_flags = flags;
3968     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCSIFFLAGS,
3969                                  "SIOCSIFFLAGS");
3970 }
3971
3972 static int
3973 do_get_ifindex(const char *netdev_name)
3974 {
3975     struct ifreq ifr;
3976
3977     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
3978     COVERAGE_INC(netdev_get_ifindex);
3979     if (ioctl(af_inet_sock, SIOCGIFINDEX, &ifr) < 0) {
3980         VLOG_WARN_RL(&rl, "ioctl(SIOCGIFINDEX) on %s device failed: %s",
3981                      netdev_name, strerror(errno));
3982         return -errno;
3983     }
3984     return ifr.ifr_ifindex;
3985 }
3986
3987 static int
3988 get_ifindex(const struct netdev *netdev_, int *ifindexp)
3989 {
3990     struct netdev_dev_linux *netdev_dev =
3991                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
3992     *ifindexp = 0;
3993     if (!(netdev_dev->cache_valid & VALID_IFINDEX)) {
3994         int ifindex = do_get_ifindex(netdev_get_name(netdev_));
3995         if (ifindex < 0) {
3996             return -ifindex;
3997         }
3998         netdev_dev->cache_valid |= VALID_IFINDEX;
3999         netdev_dev->ifindex = ifindex;
4000     }
4001     *ifindexp = netdev_dev->ifindex;
4002     return 0;
4003 }
4004
4005 static int
4006 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
4007 {
4008     struct ifreq ifr;
4009     int hwaddr_family;
4010
4011     memset(&ifr, 0, sizeof ifr);
4012     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
4013     COVERAGE_INC(netdev_get_hwaddr);
4014     if (ioctl(af_inet_sock, SIOCGIFHWADDR, &ifr) < 0) {
4015         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
4016                  netdev_name, strerror(errno));
4017         return errno;
4018     }
4019     hwaddr_family = ifr.ifr_hwaddr.sa_family;
4020     if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
4021         VLOG_WARN("%s device has unknown hardware address family %d",
4022                   netdev_name, hwaddr_family);
4023     }
4024     memcpy(ea, ifr.ifr_hwaddr.sa_data, ETH_ADDR_LEN);
4025     return 0;
4026 }
4027
4028 static int
4029 set_etheraddr(const char *netdev_name, int hwaddr_family,
4030               const uint8_t mac[ETH_ADDR_LEN])
4031 {
4032     struct ifreq ifr;
4033
4034     memset(&ifr, 0, sizeof ifr);
4035     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
4036     ifr.ifr_hwaddr.sa_family = hwaddr_family;
4037     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
4038     COVERAGE_INC(netdev_set_hwaddr);
4039     if (ioctl(af_inet_sock, SIOCSIFHWADDR, &ifr) < 0) {
4040         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
4041                  netdev_name, strerror(errno));
4042         return errno;
4043     }
4044     return 0;
4045 }
4046
4047 static int
4048 netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *ecmd,
4049                         int cmd, const char *cmd_name)
4050 {
4051     struct ifreq ifr;
4052
4053     memset(&ifr, 0, sizeof ifr);
4054     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
4055     ifr.ifr_data = (caddr_t) ecmd;
4056
4057     ecmd->cmd = cmd;
4058     COVERAGE_INC(netdev_ethtool);
4059     if (ioctl(af_inet_sock, SIOCETHTOOL, &ifr) == 0) {
4060         return 0;
4061     } else {
4062         if (errno != EOPNOTSUPP) {
4063             VLOG_WARN_RL(&rl, "ethtool command %s on network device %s "
4064                          "failed: %s", cmd_name, name, strerror(errno));
4065         } else {
4066             /* The device doesn't support this operation.  That's pretty
4067              * common, so there's no point in logging anything. */
4068         }
4069         return errno;
4070     }
4071 }
4072
4073 static int
4074 netdev_linux_do_ioctl(const char *name, struct ifreq *ifr, int cmd,
4075                       const char *cmd_name)
4076 {
4077     strncpy(ifr->ifr_name, name, sizeof ifr->ifr_name);
4078     if (ioctl(af_inet_sock, cmd, ifr) == -1) {
4079         VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s", name, cmd_name,
4080                      strerror(errno));
4081         return errno;
4082     }
4083     return 0;
4084 }
4085
4086 static int
4087 netdev_linux_get_ipv4(const struct netdev *netdev, struct in_addr *ip,
4088                       int cmd, const char *cmd_name)
4089 {
4090     struct ifreq ifr;
4091     int error;
4092
4093     ifr.ifr_addr.sa_family = AF_INET;
4094     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, cmd, cmd_name);
4095     if (!error) {
4096         const struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
4097         *ip = sin->sin_addr;
4098     }
4099     return error;
4100 }