7f9a8e32fd9bc50ccb7e721b48055fd6f264b1f9
[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     netdev_linux_arp_lookup,                                    \
2180                                                                 \
2181     netdev_linux_update_flags,                                  \
2182                                                                 \
2183     netdev_linux_poll_add,                                      \
2184     netdev_linux_poll_remove                                    \
2185 }
2186
2187 const struct netdev_class netdev_linux_class =
2188     NETDEV_LINUX_CLASS(
2189         "system",
2190         netdev_linux_create,
2191         netdev_linux_enumerate,
2192         NULL);                  /* set_stats */
2193
2194 const struct netdev_class netdev_tap_class =
2195     NETDEV_LINUX_CLASS(
2196         "tap",
2197         netdev_linux_create_tap,
2198         NULL,                   /* enumerate */
2199         NULL);                  /* set_stats */
2200
2201 const struct netdev_class netdev_internal_class =
2202     NETDEV_LINUX_CLASS(
2203         "internal",
2204         netdev_linux_create,
2205         NULL,                    /* enumerate */
2206         netdev_vport_set_stats);
2207 \f
2208 /* HTB traffic control class. */
2209
2210 #define HTB_N_QUEUES 0xf000
2211
2212 struct htb {
2213     struct tc tc;
2214     unsigned int max_rate;      /* In bytes/s. */
2215 };
2216
2217 struct htb_class {
2218     struct tc_queue tc_queue;
2219     unsigned int min_rate;      /* In bytes/s. */
2220     unsigned int max_rate;      /* In bytes/s. */
2221     unsigned int burst;         /* In bytes. */
2222     unsigned int priority;      /* Lower values are higher priorities. */
2223 };
2224
2225 static struct htb *
2226 htb_get__(const struct netdev *netdev)
2227 {
2228     struct netdev_dev_linux *netdev_dev =
2229                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
2230     return CONTAINER_OF(netdev_dev->tc, struct htb, tc);
2231 }
2232
2233 static struct htb *
2234 htb_install__(struct netdev *netdev, uint64_t max_rate)
2235 {
2236     struct netdev_dev_linux *netdev_dev =
2237                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
2238     struct htb *htb;
2239
2240     htb = xmalloc(sizeof *htb);
2241     tc_init(&htb->tc, &tc_ops_htb);
2242     htb->max_rate = max_rate;
2243
2244     netdev_dev->tc = &htb->tc;
2245
2246     return htb;
2247 }
2248
2249 /* Create an HTB qdisc.
2250  *
2251  * Equivalent to "tc qdisc add dev <dev> root handle 1: htb default 1". */
2252 static int
2253 htb_setup_qdisc__(struct netdev *netdev)
2254 {
2255     size_t opt_offset;
2256     struct tc_htb_glob opt;
2257     struct ofpbuf request;
2258     struct tcmsg *tcmsg;
2259
2260     tc_del_qdisc(netdev);
2261
2262     tcmsg = tc_make_request(netdev, RTM_NEWQDISC,
2263                             NLM_F_EXCL | NLM_F_CREATE, &request);
2264     if (!tcmsg) {
2265         return ENODEV;
2266     }
2267     tcmsg->tcm_handle = tc_make_handle(1, 0);
2268     tcmsg->tcm_parent = TC_H_ROOT;
2269
2270     nl_msg_put_string(&request, TCA_KIND, "htb");
2271
2272     memset(&opt, 0, sizeof opt);
2273     opt.rate2quantum = 10;
2274     opt.version = 3;
2275     opt.defcls = 1;
2276
2277     opt_offset = nl_msg_start_nested(&request, TCA_OPTIONS);
2278     nl_msg_put_unspec(&request, TCA_HTB_INIT, &opt, sizeof opt);
2279     nl_msg_end_nested(&request, opt_offset);
2280
2281     return tc_transact(&request, NULL);
2282 }
2283
2284 /* Equivalent to "tc class replace <dev> classid <handle> parent <parent> htb
2285  * rate <min_rate>bps ceil <max_rate>bps burst <burst>b prio <priority>". */
2286 static int
2287 htb_setup_class__(struct netdev *netdev, unsigned int handle,
2288                   unsigned int parent, struct htb_class *class)
2289 {
2290     size_t opt_offset;
2291     struct tc_htb_opt opt;
2292     struct ofpbuf request;
2293     struct tcmsg *tcmsg;
2294     int error;
2295     int mtu;
2296
2297     netdev_get_mtu(netdev, &mtu);
2298
2299     memset(&opt, 0, sizeof opt);
2300     tc_fill_rate(&opt.rate, class->min_rate, mtu);
2301     tc_fill_rate(&opt.ceil, class->max_rate, mtu);
2302     opt.buffer = tc_calc_buffer(opt.rate.rate, mtu, class->burst);
2303     opt.cbuffer = tc_calc_buffer(opt.ceil.rate, mtu, class->burst);
2304     opt.prio = class->priority;
2305
2306     tcmsg = tc_make_request(netdev, RTM_NEWTCLASS, NLM_F_CREATE, &request);
2307     if (!tcmsg) {
2308         return ENODEV;
2309     }
2310     tcmsg->tcm_handle = handle;
2311     tcmsg->tcm_parent = parent;
2312
2313     nl_msg_put_string(&request, TCA_KIND, "htb");
2314     opt_offset = nl_msg_start_nested(&request, TCA_OPTIONS);
2315     nl_msg_put_unspec(&request, TCA_HTB_PARMS, &opt, sizeof opt);
2316     tc_put_rtab(&request, TCA_HTB_RTAB, &opt.rate);
2317     tc_put_rtab(&request, TCA_HTB_CTAB, &opt.ceil);
2318     nl_msg_end_nested(&request, opt_offset);
2319
2320     error = tc_transact(&request, NULL);
2321     if (error) {
2322         VLOG_WARN_RL(&rl, "failed to replace %s class %u:%u, parent %u:%u, "
2323                      "min_rate=%u max_rate=%u burst=%u prio=%u (%s)",
2324                      netdev_get_name(netdev),
2325                      tc_get_major(handle), tc_get_minor(handle),
2326                      tc_get_major(parent), tc_get_minor(parent),
2327                      class->min_rate, class->max_rate,
2328                      class->burst, class->priority, strerror(error));
2329     }
2330     return error;
2331 }
2332
2333 /* Parses Netlink attributes in 'options' for HTB parameters and stores a
2334  * description of them into 'details'.  The description complies with the
2335  * specification given in the vswitch database documentation for linux-htb
2336  * queue details. */
2337 static int
2338 htb_parse_tca_options__(struct nlattr *nl_options, struct htb_class *class)
2339 {
2340     static const struct nl_policy tca_htb_policy[] = {
2341         [TCA_HTB_PARMS] = { .type = NL_A_UNSPEC, .optional = false,
2342                             .min_len = sizeof(struct tc_htb_opt) },
2343     };
2344
2345     struct nlattr *attrs[ARRAY_SIZE(tca_htb_policy)];
2346     const struct tc_htb_opt *htb;
2347
2348     if (!nl_parse_nested(nl_options, tca_htb_policy,
2349                          attrs, ARRAY_SIZE(tca_htb_policy))) {
2350         VLOG_WARN_RL(&rl, "failed to parse HTB class options");
2351         return EPROTO;
2352     }
2353
2354     htb = nl_attr_get(attrs[TCA_HTB_PARMS]);
2355     class->min_rate = htb->rate.rate;
2356     class->max_rate = htb->ceil.rate;
2357     class->burst = tc_ticks_to_bytes(htb->rate.rate, htb->buffer);
2358     class->priority = htb->prio;
2359     return 0;
2360 }
2361
2362 static int
2363 htb_parse_tcmsg__(struct ofpbuf *tcmsg, unsigned int *queue_id,
2364                   struct htb_class *options,
2365                   struct netdev_queue_stats *stats)
2366 {
2367     struct nlattr *nl_options;
2368     unsigned int handle;
2369     int error;
2370
2371     error = tc_parse_class(tcmsg, &handle, &nl_options, stats);
2372     if (!error && queue_id) {
2373         unsigned int major = tc_get_major(handle);
2374         unsigned int minor = tc_get_minor(handle);
2375         if (major == 1 && minor > 0 && minor <= HTB_N_QUEUES) {
2376             *queue_id = minor - 1;
2377         } else {
2378             error = EPROTO;
2379         }
2380     }
2381     if (!error && options) {
2382         error = htb_parse_tca_options__(nl_options, options);
2383     }
2384     return error;
2385 }
2386
2387 static void
2388 htb_parse_qdisc_details__(struct netdev *netdev,
2389                           const struct shash *details, struct htb_class *hc)
2390 {
2391     const char *max_rate_s;
2392
2393     max_rate_s = shash_find_data(details, "max-rate");
2394     hc->max_rate = max_rate_s ? strtoull(max_rate_s, NULL, 10) / 8 : 0;
2395     if (!hc->max_rate) {
2396         uint32_t current;
2397
2398         netdev_get_features(netdev, &current, NULL, NULL, NULL);
2399         hc->max_rate = netdev_features_to_bps(current) / 8;
2400     }
2401     hc->min_rate = hc->max_rate;
2402     hc->burst = 0;
2403     hc->priority = 0;
2404 }
2405
2406 static int
2407 htb_parse_class_details__(struct netdev *netdev,
2408                           const struct shash *details, struct htb_class *hc)
2409 {
2410     const struct htb *htb = htb_get__(netdev);
2411     const char *min_rate_s = shash_find_data(details, "min-rate");
2412     const char *max_rate_s = shash_find_data(details, "max-rate");
2413     const char *burst_s = shash_find_data(details, "burst");
2414     const char *priority_s = shash_find_data(details, "priority");
2415     int mtu;
2416
2417     /* min-rate.  Don't allow a min-rate below 1500 bytes/s. */
2418     if (!min_rate_s) {
2419         /* min-rate is required. */
2420         return EINVAL;
2421     }
2422     hc->min_rate = strtoull(min_rate_s, NULL, 10) / 8;
2423     hc->min_rate = MAX(hc->min_rate, 1500);
2424     hc->min_rate = MIN(hc->min_rate, htb->max_rate);
2425
2426     /* max-rate */
2427     hc->max_rate = (max_rate_s
2428                     ? strtoull(max_rate_s, NULL, 10) / 8
2429                     : htb->max_rate);
2430     hc->max_rate = MAX(hc->max_rate, hc->min_rate);
2431     hc->max_rate = MIN(hc->max_rate, htb->max_rate);
2432
2433     /* burst
2434      *
2435      * According to hints in the documentation that I've read, it is important
2436      * that 'burst' be at least as big as the largest frame that might be
2437      * transmitted.  Also, making 'burst' a bit bigger than necessary is OK,
2438      * but having it a bit too small is a problem.  Since netdev_get_mtu()
2439      * doesn't include the Ethernet header, we need to add at least 14 (18?) to
2440      * the MTU.  We actually add 64, instead of 14, as a guard against
2441      * additional headers get tacked on somewhere that we're not aware of. */
2442     netdev_get_mtu(netdev, &mtu);
2443     hc->burst = burst_s ? strtoull(burst_s, NULL, 10) / 8 : 0;
2444     hc->burst = MAX(hc->burst, mtu + 64);
2445
2446     /* priority */
2447     hc->priority = priority_s ? strtoul(priority_s, NULL, 10) : 0;
2448
2449     return 0;
2450 }
2451
2452 static int
2453 htb_query_class__(const struct netdev *netdev, unsigned int handle,
2454                   unsigned int parent, struct htb_class *options,
2455                   struct netdev_queue_stats *stats)
2456 {
2457     struct ofpbuf *reply;
2458     int error;
2459
2460     error = tc_query_class(netdev, handle, parent, &reply);
2461     if (!error) {
2462         error = htb_parse_tcmsg__(reply, NULL, options, stats);
2463         ofpbuf_delete(reply);
2464     }
2465     return error;
2466 }
2467
2468 static int
2469 htb_tc_install(struct netdev *netdev, const struct shash *details)
2470 {
2471     int error;
2472
2473     error = htb_setup_qdisc__(netdev);
2474     if (!error) {
2475         struct htb_class hc;
2476
2477         htb_parse_qdisc_details__(netdev, details, &hc);
2478         error = htb_setup_class__(netdev, tc_make_handle(1, 0xfffe),
2479                                   tc_make_handle(1, 0), &hc);
2480         if (!error) {
2481             htb_install__(netdev, hc.max_rate);
2482         }
2483     }
2484     return error;
2485 }
2486
2487 static struct htb_class *
2488 htb_class_cast__(const struct tc_queue *queue)
2489 {
2490     return CONTAINER_OF(queue, struct htb_class, tc_queue);
2491 }
2492
2493 static void
2494 htb_update_queue__(struct netdev *netdev, unsigned int queue_id,
2495                    const struct htb_class *hc)
2496 {
2497     struct htb *htb = htb_get__(netdev);
2498     size_t hash = hash_int(queue_id, 0);
2499     struct tc_queue *queue;
2500     struct htb_class *hcp;
2501
2502     queue = tc_find_queue__(netdev, queue_id, hash);
2503     if (queue) {
2504         hcp = htb_class_cast__(queue);
2505     } else {
2506         hcp = xmalloc(sizeof *hcp);
2507         queue = &hcp->tc_queue;
2508         queue->queue_id = queue_id;
2509         hmap_insert(&htb->tc.queues, &queue->hmap_node, hash);
2510     }
2511
2512     hcp->min_rate = hc->min_rate;
2513     hcp->max_rate = hc->max_rate;
2514     hcp->burst = hc->burst;
2515     hcp->priority = hc->priority;
2516 }
2517
2518 static int
2519 htb_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
2520 {
2521     struct ofpbuf msg;
2522     struct nl_dump dump;
2523     struct htb_class hc;
2524     struct htb *htb;
2525
2526     /* Get qdisc options. */
2527     hc.max_rate = 0;
2528     htb_query_class__(netdev, tc_make_handle(1, 0xfffe), 0, &hc, NULL);
2529     htb = htb_install__(netdev, hc.max_rate);
2530
2531     /* Get queues. */
2532     if (!start_queue_dump(netdev, &dump)) {
2533         return ENODEV;
2534     }
2535     while (nl_dump_next(&dump, &msg)) {
2536         unsigned int queue_id;
2537
2538         if (!htb_parse_tcmsg__(&msg, &queue_id, &hc, NULL)) {
2539             htb_update_queue__(netdev, queue_id, &hc);
2540         }
2541     }
2542     nl_dump_done(&dump);
2543
2544     return 0;
2545 }
2546
2547 static void
2548 htb_tc_destroy(struct tc *tc)
2549 {
2550     struct htb *htb = CONTAINER_OF(tc, struct htb, tc);
2551     struct htb_class *hc, *next;
2552
2553     HMAP_FOR_EACH_SAFE (hc, next, tc_queue.hmap_node, &htb->tc.queues) {
2554         hmap_remove(&htb->tc.queues, &hc->tc_queue.hmap_node);
2555         free(hc);
2556     }
2557     tc_destroy(tc);
2558     free(htb);
2559 }
2560
2561 static int
2562 htb_qdisc_get(const struct netdev *netdev, struct shash *details)
2563 {
2564     const struct htb *htb = htb_get__(netdev);
2565     shash_add(details, "max-rate", xasprintf("%llu", 8ULL * htb->max_rate));
2566     return 0;
2567 }
2568
2569 static int
2570 htb_qdisc_set(struct netdev *netdev, const struct shash *details)
2571 {
2572     struct htb_class hc;
2573     int error;
2574
2575     htb_parse_qdisc_details__(netdev, details, &hc);
2576     error = htb_setup_class__(netdev, tc_make_handle(1, 0xfffe),
2577                               tc_make_handle(1, 0), &hc);
2578     if (!error) {
2579         htb_get__(netdev)->max_rate = hc.max_rate;
2580     }
2581     return error;
2582 }
2583
2584 static int
2585 htb_class_get(const struct netdev *netdev OVS_UNUSED,
2586               const struct tc_queue *queue, struct shash *details)
2587 {
2588     const struct htb_class *hc = htb_class_cast__(queue);
2589
2590     shash_add(details, "min-rate", xasprintf("%llu", 8ULL * hc->min_rate));
2591     if (hc->min_rate != hc->max_rate) {
2592         shash_add(details, "max-rate", xasprintf("%llu", 8ULL * hc->max_rate));
2593     }
2594     shash_add(details, "burst", xasprintf("%llu", 8ULL * hc->burst));
2595     if (hc->priority) {
2596         shash_add(details, "priority", xasprintf("%u", hc->priority));
2597     }
2598     return 0;
2599 }
2600
2601 static int
2602 htb_class_set(struct netdev *netdev, unsigned int queue_id,
2603               const struct shash *details)
2604 {
2605     struct htb_class hc;
2606     int error;
2607
2608     error = htb_parse_class_details__(netdev, details, &hc);
2609     if (error) {
2610         return error;
2611     }
2612
2613     error = htb_setup_class__(netdev, tc_make_handle(1, queue_id + 1),
2614                               tc_make_handle(1, 0xfffe), &hc);
2615     if (error) {
2616         return error;
2617     }
2618
2619     htb_update_queue__(netdev, queue_id, &hc);
2620     return 0;
2621 }
2622
2623 static int
2624 htb_class_delete(struct netdev *netdev, struct tc_queue *queue)
2625 {
2626     struct htb_class *hc = htb_class_cast__(queue);
2627     struct htb *htb = htb_get__(netdev);
2628     int error;
2629
2630     error = tc_delete_class(netdev, tc_make_handle(1, queue->queue_id + 1));
2631     if (!error) {
2632         hmap_remove(&htb->tc.queues, &hc->tc_queue.hmap_node);
2633         free(hc);
2634     }
2635     return error;
2636 }
2637
2638 static int
2639 htb_class_get_stats(const struct netdev *netdev, const struct tc_queue *queue,
2640                     struct netdev_queue_stats *stats)
2641 {
2642     return htb_query_class__(netdev, tc_make_handle(1, queue->queue_id + 1),
2643                              tc_make_handle(1, 0xfffe), NULL, stats);
2644 }
2645
2646 static int
2647 htb_class_dump_stats(const struct netdev *netdev OVS_UNUSED,
2648                      const struct ofpbuf *nlmsg,
2649                      netdev_dump_queue_stats_cb *cb, void *aux)
2650 {
2651     struct netdev_queue_stats stats;
2652     unsigned int handle, major, minor;
2653     int error;
2654
2655     error = tc_parse_class(nlmsg, &handle, NULL, &stats);
2656     if (error) {
2657         return error;
2658     }
2659
2660     major = tc_get_major(handle);
2661     minor = tc_get_minor(handle);
2662     if (major == 1 && minor > 0 && minor <= HTB_N_QUEUES) {
2663         (*cb)(minor - 1, &stats, aux);
2664     }
2665     return 0;
2666 }
2667
2668 static const struct tc_ops tc_ops_htb = {
2669     "htb",                      /* linux_name */
2670     "linux-htb",                /* ovs_name */
2671     HTB_N_QUEUES,               /* n_queues */
2672     htb_tc_install,
2673     htb_tc_load,
2674     htb_tc_destroy,
2675     htb_qdisc_get,
2676     htb_qdisc_set,
2677     htb_class_get,
2678     htb_class_set,
2679     htb_class_delete,
2680     htb_class_get_stats,
2681     htb_class_dump_stats
2682 };
2683 \f
2684 /* "linux-hfsc" traffic control class. */
2685
2686 #define HFSC_N_QUEUES 0xf000
2687
2688 struct hfsc {
2689     struct tc tc;
2690     uint32_t max_rate;
2691 };
2692
2693 struct hfsc_class {
2694     struct tc_queue tc_queue;
2695     uint32_t min_rate;
2696     uint32_t max_rate;
2697 };
2698
2699 static struct hfsc *
2700 hfsc_get__(const struct netdev *netdev)
2701 {
2702     struct netdev_dev_linux *netdev_dev;
2703     netdev_dev = netdev_dev_linux_cast(netdev_get_dev(netdev));
2704     return CONTAINER_OF(netdev_dev->tc, struct hfsc, tc);
2705 }
2706
2707 static struct hfsc_class *
2708 hfsc_class_cast__(const struct tc_queue *queue)
2709 {
2710     return CONTAINER_OF(queue, struct hfsc_class, tc_queue);
2711 }
2712
2713 static struct hfsc *
2714 hfsc_install__(struct netdev *netdev, uint32_t max_rate)
2715 {
2716     struct netdev_dev_linux * netdev_dev;
2717     struct hfsc *hfsc;
2718
2719     netdev_dev = netdev_dev_linux_cast(netdev_get_dev(netdev));
2720     hfsc = xmalloc(sizeof *hfsc);
2721     tc_init(&hfsc->tc, &tc_ops_hfsc);
2722     hfsc->max_rate = max_rate;
2723     netdev_dev->tc = &hfsc->tc;
2724
2725     return hfsc;
2726 }
2727
2728 static void
2729 hfsc_update_queue__(struct netdev *netdev, unsigned int queue_id,
2730                     const struct hfsc_class *hc)
2731 {
2732     size_t hash;
2733     struct hfsc *hfsc;
2734     struct hfsc_class *hcp;
2735     struct tc_queue *queue;
2736
2737     hfsc = hfsc_get__(netdev);
2738     hash = hash_int(queue_id, 0);
2739
2740     queue = tc_find_queue__(netdev, queue_id, hash);
2741     if (queue) {
2742         hcp = hfsc_class_cast__(queue);
2743     } else {
2744         hcp             = xmalloc(sizeof *hcp);
2745         queue           = &hcp->tc_queue;
2746         queue->queue_id = queue_id;
2747         hmap_insert(&hfsc->tc.queues, &queue->hmap_node, hash);
2748     }
2749
2750     hcp->min_rate = hc->min_rate;
2751     hcp->max_rate = hc->max_rate;
2752 }
2753
2754 static int
2755 hfsc_parse_tca_options__(struct nlattr *nl_options, struct hfsc_class *class)
2756 {
2757     const struct tc_service_curve *rsc, *fsc, *usc;
2758     static const struct nl_policy tca_hfsc_policy[] = {
2759         [TCA_HFSC_RSC] = {
2760             .type      = NL_A_UNSPEC,
2761             .optional  = false,
2762             .min_len   = sizeof(struct tc_service_curve),
2763         },
2764         [TCA_HFSC_FSC] = {
2765             .type      = NL_A_UNSPEC,
2766             .optional  = false,
2767             .min_len   = sizeof(struct tc_service_curve),
2768         },
2769         [TCA_HFSC_USC] = {
2770             .type      = NL_A_UNSPEC,
2771             .optional  = false,
2772             .min_len   = sizeof(struct tc_service_curve),
2773         },
2774     };
2775     struct nlattr *attrs[ARRAY_SIZE(tca_hfsc_policy)];
2776
2777     if (!nl_parse_nested(nl_options, tca_hfsc_policy,
2778                          attrs, ARRAY_SIZE(tca_hfsc_policy))) {
2779         VLOG_WARN_RL(&rl, "failed to parse HFSC class options");
2780         return EPROTO;
2781     }
2782
2783     rsc = nl_attr_get(attrs[TCA_HFSC_RSC]);
2784     fsc = nl_attr_get(attrs[TCA_HFSC_FSC]);
2785     usc = nl_attr_get(attrs[TCA_HFSC_USC]);
2786
2787     if (rsc->m1 != 0 || rsc->d != 0 ||
2788         fsc->m1 != 0 || fsc->d != 0 ||
2789         usc->m1 != 0 || usc->d != 0) {
2790         VLOG_WARN_RL(&rl, "failed to parse HFSC class options. "
2791                      "Non-linear service curves are not supported.");
2792         return EPROTO;
2793     }
2794
2795     if (rsc->m2 != fsc->m2) {
2796         VLOG_WARN_RL(&rl, "failed to parse HFSC class options. "
2797                      "Real-time service curves are not supported ");
2798         return EPROTO;
2799     }
2800
2801     if (rsc->m2 > usc->m2) {
2802         VLOG_WARN_RL(&rl, "failed to parse HFSC class options. "
2803                      "Min-rate service curve is greater than "
2804                      "the max-rate service curve.");
2805         return EPROTO;
2806     }
2807
2808     class->min_rate = fsc->m2;
2809     class->max_rate = usc->m2;
2810     return 0;
2811 }
2812
2813 static int
2814 hfsc_parse_tcmsg__(struct ofpbuf *tcmsg, unsigned int *queue_id,
2815                    struct hfsc_class *options,
2816                    struct netdev_queue_stats *stats)
2817 {
2818     int error;
2819     unsigned int handle;
2820     struct nlattr *nl_options;
2821
2822     error = tc_parse_class(tcmsg, &handle, &nl_options, stats);
2823     if (error) {
2824         return error;
2825     }
2826
2827     if (queue_id) {
2828         unsigned int major, minor;
2829
2830         major = tc_get_major(handle);
2831         minor = tc_get_minor(handle);
2832         if (major == 1 && minor > 0 && minor <= HFSC_N_QUEUES) {
2833             *queue_id = minor - 1;
2834         } else {
2835             return EPROTO;
2836         }
2837     }
2838
2839     if (options) {
2840         error = hfsc_parse_tca_options__(nl_options, options);
2841     }
2842
2843     return error;
2844 }
2845
2846 static int
2847 hfsc_query_class__(const struct netdev *netdev, unsigned int handle,
2848                    unsigned int parent, struct hfsc_class *options,
2849                    struct netdev_queue_stats *stats)
2850 {
2851     int error;
2852     struct ofpbuf *reply;
2853
2854     error = tc_query_class(netdev, handle, parent, &reply);
2855     if (error) {
2856         return error;
2857     }
2858
2859     error = hfsc_parse_tcmsg__(reply, NULL, options, stats);
2860     ofpbuf_delete(reply);
2861     return error;
2862 }
2863
2864 static void
2865 hfsc_parse_qdisc_details__(struct netdev *netdev, const struct shash *details,
2866                            struct hfsc_class *class)
2867 {
2868     uint32_t max_rate;
2869     const char *max_rate_s;
2870
2871     max_rate_s = shash_find_data(details, "max-rate");
2872     max_rate   = max_rate_s ? strtoull(max_rate_s, NULL, 10) / 8 : 0;
2873
2874     if (!max_rate) {
2875         uint32_t current;
2876
2877         netdev_get_features(netdev, &current, NULL, NULL, NULL);
2878         max_rate = netdev_features_to_bps(current) / 8;
2879     }
2880
2881     class->min_rate = max_rate;
2882     class->max_rate = max_rate;
2883 }
2884
2885 static int
2886 hfsc_parse_class_details__(struct netdev *netdev,
2887                            const struct shash *details,
2888                            struct hfsc_class * class)
2889 {
2890     const struct hfsc *hfsc;
2891     uint32_t min_rate, max_rate;
2892     const char *min_rate_s, *max_rate_s;
2893
2894     hfsc       = hfsc_get__(netdev);
2895     min_rate_s = shash_find_data(details, "min-rate");
2896     max_rate_s = shash_find_data(details, "max-rate");
2897
2898     if (!min_rate_s) {
2899         return EINVAL;
2900     }
2901
2902     min_rate = strtoull(min_rate_s, NULL, 10) / 8;
2903     min_rate = MAX(min_rate, 1500);
2904     min_rate = MIN(min_rate, hfsc->max_rate);
2905
2906     max_rate = (max_rate_s
2907                 ? strtoull(max_rate_s, NULL, 10) / 8
2908                 : hfsc->max_rate);
2909     max_rate = MAX(max_rate, min_rate);
2910     max_rate = MIN(max_rate, hfsc->max_rate);
2911
2912     class->min_rate = min_rate;
2913     class->max_rate = max_rate;
2914
2915     return 0;
2916 }
2917
2918 /* Create an HFSC qdisc.
2919  *
2920  * Equivalent to "tc qdisc add dev <dev> root handle 1: hfsc default 1". */
2921 static int
2922 hfsc_setup_qdisc__(struct netdev * netdev)
2923 {
2924     struct tcmsg *tcmsg;
2925     struct ofpbuf request;
2926     struct tc_hfsc_qopt opt;
2927
2928     tc_del_qdisc(netdev);
2929
2930     tcmsg = tc_make_request(netdev, RTM_NEWQDISC,
2931                             NLM_F_EXCL | NLM_F_CREATE, &request);
2932
2933     if (!tcmsg) {
2934         return ENODEV;
2935     }
2936
2937     tcmsg->tcm_handle = tc_make_handle(1, 0);
2938     tcmsg->tcm_parent = TC_H_ROOT;
2939
2940     memset(&opt, 0, sizeof opt);
2941     opt.defcls = 1;
2942
2943     nl_msg_put_string(&request, TCA_KIND, "hfsc");
2944     nl_msg_put_unspec(&request, TCA_OPTIONS, &opt, sizeof opt);
2945
2946     return tc_transact(&request, NULL);
2947 }
2948
2949 /* Create an HFSC class.
2950  *
2951  * Equivalent to "tc class add <dev> parent <parent> classid <handle> hfsc
2952  * sc rate <min_rate> ul rate <max_rate>" */
2953 static int
2954 hfsc_setup_class__(struct netdev *netdev, unsigned int handle,
2955                    unsigned int parent, struct hfsc_class *class)
2956 {
2957     int error;
2958     size_t opt_offset;
2959     struct tcmsg *tcmsg;
2960     struct ofpbuf request;
2961     struct tc_service_curve min, max;
2962
2963     tcmsg = tc_make_request(netdev, RTM_NEWTCLASS, NLM_F_CREATE, &request);
2964
2965     if (!tcmsg) {
2966         return ENODEV;
2967     }
2968
2969     tcmsg->tcm_handle = handle;
2970     tcmsg->tcm_parent = parent;
2971
2972     min.m1 = 0;
2973     min.d  = 0;
2974     min.m2 = class->min_rate;
2975
2976     max.m1 = 0;
2977     max.d  = 0;
2978     max.m2 = class->max_rate;
2979
2980     nl_msg_put_string(&request, TCA_KIND, "hfsc");
2981     opt_offset = nl_msg_start_nested(&request, TCA_OPTIONS);
2982     nl_msg_put_unspec(&request, TCA_HFSC_RSC, &min, sizeof min);
2983     nl_msg_put_unspec(&request, TCA_HFSC_FSC, &min, sizeof min);
2984     nl_msg_put_unspec(&request, TCA_HFSC_USC, &max, sizeof max);
2985     nl_msg_end_nested(&request, opt_offset);
2986
2987     error = tc_transact(&request, NULL);
2988     if (error) {
2989         VLOG_WARN_RL(&rl, "failed to replace %s class %u:%u, parent %u:%u, "
2990                      "min-rate %ubps, max-rate %ubps (%s)",
2991                      netdev_get_name(netdev),
2992                      tc_get_major(handle), tc_get_minor(handle),
2993                      tc_get_major(parent), tc_get_minor(parent),
2994                      class->min_rate, class->max_rate, strerror(error));
2995     }
2996
2997     return error;
2998 }
2999
3000 static int
3001 hfsc_tc_install(struct netdev *netdev, const struct shash *details)
3002 {
3003     int error;
3004     struct hfsc_class class;
3005
3006     error = hfsc_setup_qdisc__(netdev);
3007
3008     if (error) {
3009         return error;
3010     }
3011
3012     hfsc_parse_qdisc_details__(netdev, details, &class);
3013     error = hfsc_setup_class__(netdev, tc_make_handle(1, 0xfffe),
3014                                tc_make_handle(1, 0), &class);
3015
3016     if (error) {
3017         return error;
3018     }
3019
3020     hfsc_install__(netdev, class.max_rate);
3021     return 0;
3022 }
3023
3024 static int
3025 hfsc_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
3026 {
3027     struct ofpbuf msg;
3028     struct hfsc *hfsc;
3029     struct nl_dump dump;
3030     struct hfsc_class hc;
3031
3032     hc.max_rate = 0;
3033     hfsc_query_class__(netdev, tc_make_handle(1, 0xfffe), 0, &hc, NULL);
3034     hfsc = hfsc_install__(netdev, hc.max_rate);
3035
3036     if (!start_queue_dump(netdev, &dump)) {
3037         return ENODEV;
3038     }
3039
3040     while (nl_dump_next(&dump, &msg)) {
3041         unsigned int queue_id;
3042
3043         if (!hfsc_parse_tcmsg__(&msg, &queue_id, &hc, NULL)) {
3044             hfsc_update_queue__(netdev, queue_id, &hc);
3045         }
3046     }
3047
3048     nl_dump_done(&dump);
3049     return 0;
3050 }
3051
3052 static void
3053 hfsc_tc_destroy(struct tc *tc)
3054 {
3055     struct hfsc *hfsc;
3056     struct hfsc_class *hc, *next;
3057
3058     hfsc = CONTAINER_OF(tc, struct hfsc, tc);
3059
3060     HMAP_FOR_EACH_SAFE (hc, next, tc_queue.hmap_node, &hfsc->tc.queues) {
3061         hmap_remove(&hfsc->tc.queues, &hc->tc_queue.hmap_node);
3062         free(hc);
3063     }
3064
3065     tc_destroy(tc);
3066     free(hfsc);
3067 }
3068
3069 static int
3070 hfsc_qdisc_get(const struct netdev *netdev, struct shash *details)
3071 {
3072     const struct hfsc *hfsc;
3073     hfsc = hfsc_get__(netdev);
3074     shash_add(details, "max-rate", xasprintf("%llu", 8ULL * hfsc->max_rate));
3075     return 0;
3076 }
3077
3078 static int
3079 hfsc_qdisc_set(struct netdev *netdev, const struct shash *details)
3080 {
3081     int error;
3082     struct hfsc_class class;
3083
3084     hfsc_parse_qdisc_details__(netdev, details, &class);
3085     error = hfsc_setup_class__(netdev, tc_make_handle(1, 0xfffe),
3086                                tc_make_handle(1, 0), &class);
3087
3088     if (!error) {
3089         hfsc_get__(netdev)->max_rate = class.max_rate;
3090     }
3091
3092     return error;
3093 }
3094
3095 static int
3096 hfsc_class_get(const struct netdev *netdev OVS_UNUSED,
3097               const struct tc_queue *queue, struct shash *details)
3098 {
3099     const struct hfsc_class *hc;
3100
3101     hc = hfsc_class_cast__(queue);
3102     shash_add(details, "min-rate", xasprintf("%llu", 8ULL * hc->min_rate));
3103     if (hc->min_rate != hc->max_rate) {
3104         shash_add(details, "max-rate", xasprintf("%llu", 8ULL * hc->max_rate));
3105     }
3106     return 0;
3107 }
3108
3109 static int
3110 hfsc_class_set(struct netdev *netdev, unsigned int queue_id,
3111                const struct shash *details)
3112 {
3113     int error;
3114     struct hfsc_class class;
3115
3116     error = hfsc_parse_class_details__(netdev, details, &class);
3117     if (error) {
3118         return error;
3119     }
3120
3121     error = hfsc_setup_class__(netdev, tc_make_handle(1, queue_id + 1),
3122                                tc_make_handle(1, 0xfffe), &class);
3123     if (error) {
3124         return error;
3125     }
3126
3127     hfsc_update_queue__(netdev, queue_id, &class);
3128     return 0;
3129 }
3130
3131 static int
3132 hfsc_class_delete(struct netdev *netdev, struct tc_queue *queue)
3133 {
3134     int error;
3135     struct hfsc *hfsc;
3136     struct hfsc_class *hc;
3137
3138     hc   = hfsc_class_cast__(queue);
3139     hfsc = hfsc_get__(netdev);
3140
3141     error = tc_delete_class(netdev, tc_make_handle(1, queue->queue_id + 1));
3142     if (!error) {
3143         hmap_remove(&hfsc->tc.queues, &hc->tc_queue.hmap_node);
3144         free(hc);
3145     }
3146     return error;
3147 }
3148
3149 static int
3150 hfsc_class_get_stats(const struct netdev *netdev, const struct tc_queue *queue,
3151                      struct netdev_queue_stats *stats)
3152 {
3153     return hfsc_query_class__(netdev, tc_make_handle(1, queue->queue_id + 1),
3154                              tc_make_handle(1, 0xfffe), NULL, stats);
3155 }
3156
3157 static int
3158 hfsc_class_dump_stats(const struct netdev *netdev OVS_UNUSED,
3159                       const struct ofpbuf *nlmsg,
3160                       netdev_dump_queue_stats_cb *cb, void *aux)
3161 {
3162     struct netdev_queue_stats stats;
3163     unsigned int handle, major, minor;
3164     int error;
3165
3166     error = tc_parse_class(nlmsg, &handle, NULL, &stats);
3167     if (error) {
3168         return error;
3169     }
3170
3171     major = tc_get_major(handle);
3172     minor = tc_get_minor(handle);
3173     if (major == 1 && minor > 0 && minor <= HFSC_N_QUEUES) {
3174         (*cb)(minor - 1, &stats, aux);
3175     }
3176     return 0;
3177 }
3178
3179 static const struct tc_ops tc_ops_hfsc = {
3180     "hfsc",                     /* linux_name */
3181     "linux-hfsc",               /* ovs_name */
3182     HFSC_N_QUEUES,              /* n_queues */
3183     hfsc_tc_install,            /* tc_install */
3184     hfsc_tc_load,               /* tc_load */
3185     hfsc_tc_destroy,            /* tc_destroy */
3186     hfsc_qdisc_get,             /* qdisc_get */
3187     hfsc_qdisc_set,             /* qdisc_set */
3188     hfsc_class_get,             /* class_get */
3189     hfsc_class_set,             /* class_set */
3190     hfsc_class_delete,          /* class_delete */
3191     hfsc_class_get_stats,       /* class_get_stats */
3192     hfsc_class_dump_stats       /* class_dump_stats */
3193 };
3194 \f
3195 /* "linux-default" traffic control class.
3196  *
3197  * This class represents the default, unnamed Linux qdisc.  It corresponds to
3198  * the "" (empty string) QoS type in the OVS database. */
3199
3200 static void
3201 default_install__(struct netdev *netdev)
3202 {
3203     struct netdev_dev_linux *netdev_dev =
3204                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
3205     static struct tc *tc;
3206
3207     if (!tc) {
3208         tc = xmalloc(sizeof *tc);
3209         tc_init(tc, &tc_ops_default);
3210     }
3211     netdev_dev->tc = tc;
3212 }
3213
3214 static int
3215 default_tc_install(struct netdev *netdev,
3216                    const struct shash *details OVS_UNUSED)
3217 {
3218     default_install__(netdev);
3219     return 0;
3220 }
3221
3222 static int
3223 default_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
3224 {
3225     default_install__(netdev);
3226     return 0;
3227 }
3228
3229 static const struct tc_ops tc_ops_default = {
3230     NULL,                       /* linux_name */
3231     "",                         /* ovs_name */
3232     0,                          /* n_queues */
3233     default_tc_install,
3234     default_tc_load,
3235     NULL,                       /* tc_destroy */
3236     NULL,                       /* qdisc_get */
3237     NULL,                       /* qdisc_set */
3238     NULL,                       /* class_get */
3239     NULL,                       /* class_set */
3240     NULL,                       /* class_delete */
3241     NULL,                       /* class_get_stats */
3242     NULL                        /* class_dump_stats */
3243 };
3244 \f
3245 /* "linux-other" traffic control class.
3246  *
3247  * */
3248
3249 static int
3250 other_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
3251 {
3252     struct netdev_dev_linux *netdev_dev =
3253                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
3254     static struct tc *tc;
3255
3256     if (!tc) {
3257         tc = xmalloc(sizeof *tc);
3258         tc_init(tc, &tc_ops_other);
3259     }
3260     netdev_dev->tc = tc;
3261     return 0;
3262 }
3263
3264 static const struct tc_ops tc_ops_other = {
3265     NULL,                       /* linux_name */
3266     "linux-other",              /* ovs_name */
3267     0,                          /* n_queues */
3268     NULL,                       /* tc_install */
3269     other_tc_load,
3270     NULL,                       /* tc_destroy */
3271     NULL,                       /* qdisc_get */
3272     NULL,                       /* qdisc_set */
3273     NULL,                       /* class_get */
3274     NULL,                       /* class_set */
3275     NULL,                       /* class_delete */
3276     NULL,                       /* class_get_stats */
3277     NULL                        /* class_dump_stats */
3278 };
3279 \f
3280 /* Traffic control. */
3281
3282 /* Number of kernel "tc" ticks per second. */
3283 static double ticks_per_s;
3284
3285 /* Number of kernel "jiffies" per second.  This is used for the purpose of
3286  * computing buffer sizes.  Generally kernel qdiscs need to be able to buffer
3287  * one jiffy's worth of data.
3288  *
3289  * There are two possibilities here:
3290  *
3291  *    - 'buffer_hz' is the kernel's real timer tick rate, a small number in the
3292  *      approximate range of 100 to 1024.  That means that we really need to
3293  *      make sure that the qdisc can buffer that much data.
3294  *
3295  *    - 'buffer_hz' is an absurdly large number.  That means that the kernel
3296  *      has finely granular timers and there's no need to fudge additional room
3297  *      for buffers.  (There's no extra effort needed to implement that: the
3298  *      large 'buffer_hz' is used as a divisor, so practically any number will
3299  *      come out as 0 in the division.  Small integer results in the case of
3300  *      really high dividends won't have any real effect anyhow.)
3301  */
3302 static unsigned int buffer_hz;
3303
3304 /* Returns tc handle 'major':'minor'. */
3305 static unsigned int
3306 tc_make_handle(unsigned int major, unsigned int minor)
3307 {
3308     return TC_H_MAKE(major << 16, minor);
3309 }
3310
3311 /* Returns the major number from 'handle'. */
3312 static unsigned int
3313 tc_get_major(unsigned int handle)
3314 {
3315     return TC_H_MAJ(handle) >> 16;
3316 }
3317
3318 /* Returns the minor number from 'handle'. */
3319 static unsigned int
3320 tc_get_minor(unsigned int handle)
3321 {
3322     return TC_H_MIN(handle);
3323 }
3324
3325 static struct tcmsg *
3326 tc_make_request(const struct netdev *netdev, int type, unsigned int flags,
3327                 struct ofpbuf *request)
3328 {
3329     struct tcmsg *tcmsg;
3330     int ifindex;
3331     int error;
3332
3333     error = get_ifindex(netdev, &ifindex);
3334     if (error) {
3335         return NULL;
3336     }
3337
3338     ofpbuf_init(request, 512);
3339     nl_msg_put_nlmsghdr(request, sizeof *tcmsg, type, NLM_F_REQUEST | flags);
3340     tcmsg = ofpbuf_put_zeros(request, sizeof *tcmsg);
3341     tcmsg->tcm_family = AF_UNSPEC;
3342     tcmsg->tcm_ifindex = ifindex;
3343     /* Caller should fill in tcmsg->tcm_handle. */
3344     /* Caller should fill in tcmsg->tcm_parent. */
3345
3346     return tcmsg;
3347 }
3348
3349 static int
3350 tc_transact(struct ofpbuf *request, struct ofpbuf **replyp)
3351 {
3352     int error = nl_sock_transact(rtnl_sock, request, replyp);
3353     ofpbuf_uninit(request);
3354     return error;
3355 }
3356
3357 static void
3358 read_psched(void)
3359 {
3360     /* The values in psched are not individually very meaningful, but they are
3361      * important.  The tables below show some values seen in the wild.
3362      *
3363      * Some notes:
3364      *
3365      *   - "c" has always been a constant 1000000 since at least Linux 2.4.14.
3366      *     (Before that, there are hints that it was 1000000000.)
3367      *
3368      *   - "d" can be unrealistically large, see the comment on 'buffer_hz'
3369      *     above.
3370      *
3371      *                        /proc/net/psched
3372      *     -----------------------------------
3373      * [1] 000c8000 000f4240 000f4240 00000064
3374      * [2] 000003e8 00000400 000f4240 3b9aca00
3375      * [3] 000003e8 00000400 000f4240 3b9aca00
3376      * [4] 000003e8 00000400 000f4240 00000064
3377      * [5] 000003e8 00000040 000f4240 3b9aca00
3378      * [6] 000003e8 00000040 000f4240 000000f9
3379      *
3380      *           a         b          c             d ticks_per_s     buffer_hz
3381      *     ------- --------- ---------- ------------- ----------- -------------
3382      * [1] 819,200 1,000,000  1,000,000           100     819,200           100
3383      * [2]   1,000     1,024  1,000,000 1,000,000,000     976,562 1,000,000,000
3384      * [3]   1,000     1,024  1,000,000 1,000,000,000     976,562 1,000,000,000
3385      * [4]   1,000     1,024  1,000,000           100     976,562           100
3386      * [5]   1,000        64  1,000,000 1,000,000,000  15,625,000 1,000,000,000
3387      * [6]   1,000        64  1,000,000           249  15,625,000           249
3388      *
3389      * [1] 2.6.18-128.1.6.el5.xs5.5.0.505.1024xen from XenServer 5.5.0-24648p
3390      * [2] 2.6.26-1-686-bigmem from Debian lenny
3391      * [3] 2.6.26-2-sparc64 from Debian lenny
3392      * [4] 2.6.27.42-0.1.1.xs5.6.810.44.111163xen from XenServer 5.6.810-31078p
3393      * [5] 2.6.32.21.22 (approx.) from Ubuntu 10.04 on VMware Fusion
3394      * [6] 2.6.34 from kernel.org on KVM
3395      */
3396     static const char fn[] = "/proc/net/psched";
3397     unsigned int a, b, c, d;
3398     FILE *stream;
3399
3400     ticks_per_s = 1.0;
3401     buffer_hz = 100;
3402
3403     stream = fopen(fn, "r");
3404     if (!stream) {
3405         VLOG_WARN("%s: open failed: %s", fn, strerror(errno));
3406         return;
3407     }
3408
3409     if (fscanf(stream, "%x %x %x %x", &a, &b, &c, &d) != 4) {
3410         VLOG_WARN("%s: read failed", fn);
3411         fclose(stream);
3412         return;
3413     }
3414     VLOG_DBG("%s: psched parameters are: %u %u %u %u", fn, a, b, c, d);
3415     fclose(stream);
3416
3417     if (!a || !c) {
3418         VLOG_WARN("%s: invalid scheduler parameters", fn);
3419         return;
3420     }
3421
3422     ticks_per_s = (double) a * c / b;
3423     if (c == 1000000) {
3424         buffer_hz = d;
3425     } else {
3426         VLOG_WARN("%s: unexpected psched parameters: %u %u %u %u",
3427                   fn, a, b, c, d);
3428     }
3429     VLOG_DBG("%s: ticks_per_s=%f buffer_hz=%u", fn, ticks_per_s, buffer_hz);
3430 }
3431
3432 /* Returns the number of bytes that can be transmitted in 'ticks' ticks at a
3433  * rate of 'rate' bytes per second. */
3434 static unsigned int
3435 tc_ticks_to_bytes(unsigned int rate, unsigned int ticks)
3436 {
3437     if (!buffer_hz) {
3438         read_psched();
3439     }
3440     return (rate * ticks) / ticks_per_s;
3441 }
3442
3443 /* Returns the number of ticks that it would take to transmit 'size' bytes at a
3444  * rate of 'rate' bytes per second. */
3445 static unsigned int
3446 tc_bytes_to_ticks(unsigned int rate, unsigned int size)
3447 {
3448     if (!buffer_hz) {
3449         read_psched();
3450     }
3451     return rate ? ((unsigned long long int) ticks_per_s * size) / rate : 0;
3452 }
3453
3454 /* Returns the number of bytes that need to be reserved for qdisc buffering at
3455  * a transmission rate of 'rate' bytes per second. */
3456 static unsigned int
3457 tc_buffer_per_jiffy(unsigned int rate)
3458 {
3459     if (!buffer_hz) {
3460         read_psched();
3461     }
3462     return rate / buffer_hz;
3463 }
3464
3465 /* Given Netlink 'msg' that describes a qdisc, extracts the name of the qdisc,
3466  * e.g. "htb", into '*kind' (if it is nonnull).  If 'options' is nonnull,
3467  * extracts 'msg''s TCA_OPTIONS attributes into '*options' if it is present or
3468  * stores NULL into it if it is absent.
3469  *
3470  * '*kind' and '*options' point into 'msg', so they are owned by whoever owns
3471  * 'msg'.
3472  *
3473  * Returns 0 if successful, otherwise a positive errno value. */
3474 static int
3475 tc_parse_qdisc(const struct ofpbuf *msg, const char **kind,
3476                struct nlattr **options)
3477 {
3478     static const struct nl_policy tca_policy[] = {
3479         [TCA_KIND] = { .type = NL_A_STRING, .optional = false },
3480         [TCA_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
3481     };
3482     struct nlattr *ta[ARRAY_SIZE(tca_policy)];
3483
3484     if (!nl_policy_parse(msg, NLMSG_HDRLEN + sizeof(struct tcmsg),
3485                          tca_policy, ta, ARRAY_SIZE(ta))) {
3486         VLOG_WARN_RL(&rl, "failed to parse qdisc message");
3487         goto error;
3488     }
3489
3490     if (kind) {
3491         *kind = nl_attr_get_string(ta[TCA_KIND]);
3492     }
3493
3494     if (options) {
3495         *options = ta[TCA_OPTIONS];
3496     }
3497
3498     return 0;
3499
3500 error:
3501     if (kind) {
3502         *kind = NULL;
3503     }
3504     if (options) {
3505         *options = NULL;
3506     }
3507     return EPROTO;
3508 }
3509
3510 /* Given Netlink 'msg' that describes a class, extracts the queue ID (e.g. the
3511  * minor number of its class ID) into '*queue_id', its TCA_OPTIONS attribute
3512  * into '*options', and its queue statistics into '*stats'.  Any of the output
3513  * arguments may be null.
3514  *
3515  * Returns 0 if successful, otherwise a positive errno value. */
3516 static int
3517 tc_parse_class(const struct ofpbuf *msg, unsigned int *handlep,
3518                struct nlattr **options, struct netdev_queue_stats *stats)
3519 {
3520     static const struct nl_policy tca_policy[] = {
3521         [TCA_OPTIONS] = { .type = NL_A_NESTED, .optional = false },
3522         [TCA_STATS2] = { .type = NL_A_NESTED, .optional = false },
3523     };
3524     struct nlattr *ta[ARRAY_SIZE(tca_policy)];
3525
3526     if (!nl_policy_parse(msg, NLMSG_HDRLEN + sizeof(struct tcmsg),
3527                          tca_policy, ta, ARRAY_SIZE(ta))) {
3528         VLOG_WARN_RL(&rl, "failed to parse class message");
3529         goto error;
3530     }
3531
3532     if (handlep) {
3533         struct tcmsg *tc = ofpbuf_at_assert(msg, NLMSG_HDRLEN, sizeof *tc);
3534         *handlep = tc->tcm_handle;
3535     }
3536
3537     if (options) {
3538         *options = ta[TCA_OPTIONS];
3539     }
3540
3541     if (stats) {
3542         const struct gnet_stats_queue *gsq;
3543         struct gnet_stats_basic gsb;
3544
3545         static const struct nl_policy stats_policy[] = {
3546             [TCA_STATS_BASIC] = { .type = NL_A_UNSPEC, .optional = false,
3547                                   .min_len = sizeof gsb },
3548             [TCA_STATS_QUEUE] = { .type = NL_A_UNSPEC, .optional = false,
3549                                   .min_len = sizeof *gsq },
3550         };
3551         struct nlattr *sa[ARRAY_SIZE(stats_policy)];
3552
3553         if (!nl_parse_nested(ta[TCA_STATS2], stats_policy,
3554                              sa, ARRAY_SIZE(sa))) {
3555             VLOG_WARN_RL(&rl, "failed to parse class stats");
3556             goto error;
3557         }
3558
3559         /* Alignment issues screw up the length of struct gnet_stats_basic on
3560          * some arch/bitsize combinations.  Newer versions of Linux have a
3561          * struct gnet_stats_basic_packed, but we can't depend on that.  The
3562          * easiest thing to do is just to make a copy. */
3563         memset(&gsb, 0, sizeof gsb);
3564         memcpy(&gsb, nl_attr_get(sa[TCA_STATS_BASIC]),
3565                MIN(nl_attr_get_size(sa[TCA_STATS_BASIC]), sizeof gsb));
3566         stats->tx_bytes = gsb.bytes;
3567         stats->tx_packets = gsb.packets;
3568
3569         gsq = nl_attr_get(sa[TCA_STATS_QUEUE]);
3570         stats->tx_errors = gsq->drops;
3571     }
3572
3573     return 0;
3574
3575 error:
3576     if (options) {
3577         *options = NULL;
3578     }
3579     if (stats) {
3580         memset(stats, 0, sizeof *stats);
3581     }
3582     return EPROTO;
3583 }
3584
3585 /* Queries the kernel for class with identifier 'handle' and parent 'parent'
3586  * on 'netdev'. */
3587 static int
3588 tc_query_class(const struct netdev *netdev,
3589                unsigned int handle, unsigned int parent,
3590                struct ofpbuf **replyp)
3591 {
3592     struct ofpbuf request;
3593     struct tcmsg *tcmsg;
3594     int error;
3595
3596     tcmsg = tc_make_request(netdev, RTM_GETTCLASS, NLM_F_ECHO, &request);
3597     if (!tcmsg) {
3598         return ENODEV;
3599     }
3600     tcmsg->tcm_handle = handle;
3601     tcmsg->tcm_parent = parent;
3602
3603     error = tc_transact(&request, replyp);
3604     if (error) {
3605         VLOG_WARN_RL(&rl, "query %s class %u:%u (parent %u:%u) failed (%s)",
3606                      netdev_get_name(netdev),
3607                      tc_get_major(handle), tc_get_minor(handle),
3608                      tc_get_major(parent), tc_get_minor(parent),
3609                      strerror(error));
3610     }
3611     return error;
3612 }
3613
3614 /* Equivalent to "tc class del dev <name> handle <handle>". */
3615 static int
3616 tc_delete_class(const struct netdev *netdev, unsigned int handle)
3617 {
3618     struct ofpbuf request;
3619     struct tcmsg *tcmsg;
3620     int error;
3621
3622     tcmsg = tc_make_request(netdev, RTM_DELTCLASS, 0, &request);
3623     if (!tcmsg) {
3624         return ENODEV;
3625     }
3626     tcmsg->tcm_handle = handle;
3627     tcmsg->tcm_parent = 0;
3628
3629     error = tc_transact(&request, NULL);
3630     if (error) {
3631         VLOG_WARN_RL(&rl, "delete %s class %u:%u failed (%s)",
3632                      netdev_get_name(netdev),
3633                      tc_get_major(handle), tc_get_minor(handle),
3634                      strerror(error));
3635     }
3636     return error;
3637 }
3638
3639 /* Equivalent to "tc qdisc del dev <name> root". */
3640 static int
3641 tc_del_qdisc(struct netdev *netdev)
3642 {
3643     struct netdev_dev_linux *netdev_dev =
3644                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
3645     struct ofpbuf request;
3646     struct tcmsg *tcmsg;
3647     int error;
3648
3649     tcmsg = tc_make_request(netdev, RTM_DELQDISC, 0, &request);
3650     if (!tcmsg) {
3651         return ENODEV;
3652     }
3653     tcmsg->tcm_handle = tc_make_handle(1, 0);
3654     tcmsg->tcm_parent = TC_H_ROOT;
3655
3656     error = tc_transact(&request, NULL);
3657     if (error == EINVAL) {
3658         /* EINVAL probably means that the default qdisc was in use, in which
3659          * case we've accomplished our purpose. */
3660         error = 0;
3661     }
3662     if (!error && netdev_dev->tc) {
3663         if (netdev_dev->tc->ops->tc_destroy) {
3664             netdev_dev->tc->ops->tc_destroy(netdev_dev->tc);
3665         }
3666         netdev_dev->tc = NULL;
3667     }
3668     return error;
3669 }
3670
3671 /* If 'netdev''s qdisc type and parameters are not yet known, queries the
3672  * kernel to determine what they are.  Returns 0 if successful, otherwise a
3673  * positive errno value. */
3674 static int
3675 tc_query_qdisc(const struct netdev *netdev)
3676 {
3677     struct netdev_dev_linux *netdev_dev =
3678                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
3679     struct ofpbuf request, *qdisc;
3680     const struct tc_ops *ops;
3681     struct tcmsg *tcmsg;
3682     int load_error;
3683     int error;
3684
3685     if (netdev_dev->tc) {
3686         return 0;
3687     }
3688
3689     /* This RTM_GETQDISC is crafted to avoid OOPSing kernels that do not have
3690      * commit 53b0f08 "net_sched: Fix qdisc_notify()", which is anything before
3691      * 2.6.35 without that fix backported to it.
3692      *
3693      * To avoid the OOPS, we must not make a request that would attempt to dump
3694      * a "built-in" qdisc, that is, the default pfifo_fast qdisc or one of a
3695      * few others.  There are a few ways that I can see to do this, but most of
3696      * them seem to be racy (and if you lose the race the kernel OOPSes).  The
3697      * technique chosen here is to assume that any non-default qdisc that we
3698      * create will have a class with handle 1:0.  The built-in qdiscs only have
3699      * a class with handle 0:0.
3700      *
3701      * We could check for Linux 2.6.35+ and use a more straightforward method
3702      * there. */
3703     tcmsg = tc_make_request(netdev, RTM_GETQDISC, NLM_F_ECHO, &request);
3704     if (!tcmsg) {
3705         return ENODEV;
3706     }
3707     tcmsg->tcm_handle = tc_make_handle(1, 0);
3708     tcmsg->tcm_parent = 0;
3709
3710     /* Figure out what tc class to instantiate. */
3711     error = tc_transact(&request, &qdisc);
3712     if (!error) {
3713         const char *kind;
3714
3715         error = tc_parse_qdisc(qdisc, &kind, NULL);
3716         if (error) {
3717             ops = &tc_ops_other;
3718         } else {
3719             ops = tc_lookup_linux_name(kind);
3720             if (!ops) {
3721                 static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 1);
3722                 VLOG_INFO_RL(&rl2, "unknown qdisc \"%s\"", kind);
3723
3724                 ops = &tc_ops_other;
3725             }
3726         }
3727     } else if (error == ENOENT) {
3728         /* Either it's a built-in qdisc, or it's a qdisc set up by some
3729          * other entity that doesn't have a handle 1:0.  We will assume
3730          * that it's the system default qdisc. */
3731         ops = &tc_ops_default;
3732         error = 0;
3733     } else {
3734         /* Who knows?  Maybe the device got deleted. */
3735         VLOG_WARN_RL(&rl, "query %s qdisc failed (%s)",
3736                      netdev_get_name(netdev), strerror(error));
3737         ops = &tc_ops_other;
3738     }
3739
3740     /* Instantiate it. */
3741     load_error = ops->tc_load((struct netdev *) netdev, qdisc);
3742     assert((load_error == 0) == (netdev_dev->tc != NULL));
3743     ofpbuf_delete(qdisc);
3744
3745     return error ? error : load_error;
3746 }
3747
3748 /* Linux traffic control uses tables with 256 entries ("rtab" tables) to
3749    approximate the time to transmit packets of various lengths.  For an MTU of
3750    256 or less, each entry is exact; for an MTU of 257 through 512, each entry
3751    represents two possible packet lengths; for a MTU of 513 through 1024, four
3752    possible lengths; and so on.
3753
3754    Returns, for the specified 'mtu', the number of bits that packet lengths
3755    need to be shifted right to fit within such a 256-entry table. */
3756 static int
3757 tc_calc_cell_log(unsigned int mtu)
3758 {
3759     int cell_log;
3760
3761     if (!mtu) {
3762         mtu = ETH_PAYLOAD_MAX;
3763     }
3764     mtu += ETH_HEADER_LEN + VLAN_HEADER_LEN;
3765
3766     for (cell_log = 0; mtu >= 256; cell_log++) {
3767         mtu >>= 1;
3768     }
3769
3770     return cell_log;
3771 }
3772
3773 /* Initializes 'rate' properly for a rate of 'Bps' bytes per second with an MTU
3774  * of 'mtu'. */
3775 static void
3776 tc_fill_rate(struct tc_ratespec *rate, uint64_t Bps, int mtu)
3777 {
3778     memset(rate, 0, sizeof *rate);
3779     rate->cell_log = tc_calc_cell_log(mtu);
3780     /* rate->overhead = 0; */           /* New in 2.6.24, not yet in some */
3781     /* rate->cell_align = 0; */         /* distro headers. */
3782     rate->mpu = ETH_TOTAL_MIN;
3783     rate->rate = Bps;
3784 }
3785
3786 /* Appends to 'msg' an "rtab" table for the specified 'rate' as a Netlink
3787  * attribute of the specified "type".
3788  *
3789  * See tc_calc_cell_log() above for a description of "rtab"s. */
3790 static void
3791 tc_put_rtab(struct ofpbuf *msg, uint16_t type, const struct tc_ratespec *rate)
3792 {
3793     uint32_t *rtab;
3794     unsigned int i;
3795
3796     rtab = nl_msg_put_unspec_uninit(msg, type, TC_RTAB_SIZE);
3797     for (i = 0; i < TC_RTAB_SIZE / sizeof *rtab; i++) {
3798         unsigned packet_size = (i + 1) << rate->cell_log;
3799         if (packet_size < rate->mpu) {
3800             packet_size = rate->mpu;
3801         }
3802         rtab[i] = tc_bytes_to_ticks(rate->rate, packet_size);
3803     }
3804 }
3805
3806 /* Calculates the proper value of 'buffer' or 'cbuffer' in HTB options given a
3807  * rate of 'Bps' bytes per second, the specified 'mtu', and a user-requested
3808  * burst size of 'burst_bytes'.  (If no value was requested, a 'burst_bytes' of
3809  * 0 is fine.) */
3810 static int
3811 tc_calc_buffer(unsigned int Bps, int mtu, uint64_t burst_bytes)
3812 {
3813     unsigned int min_burst = tc_buffer_per_jiffy(Bps) + mtu;
3814     return tc_bytes_to_ticks(Bps, MAX(burst_bytes, min_burst));
3815 }
3816
3817 \f
3818 /* Utility functions. */
3819
3820 static int
3821 get_stats_via_netlink(int ifindex, struct netdev_stats *stats)
3822 {
3823     /* Policy for RTNLGRP_LINK messages.
3824      *
3825      * There are *many* more fields in these messages, but currently we only
3826      * care about these fields. */
3827     static const struct nl_policy rtnlgrp_link_policy[] = {
3828         [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
3829         [IFLA_STATS] = { .type = NL_A_UNSPEC, .optional = true,
3830                          .min_len = sizeof(struct rtnl_link_stats) },
3831     };
3832
3833     struct ofpbuf request;
3834     struct ofpbuf *reply;
3835     struct ifinfomsg *ifi;
3836     const struct rtnl_link_stats *rtnl_stats;
3837     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
3838     int error;
3839
3840     ofpbuf_init(&request, 0);
3841     nl_msg_put_nlmsghdr(&request, sizeof *ifi, RTM_GETLINK, NLM_F_REQUEST);
3842     ifi = ofpbuf_put_zeros(&request, sizeof *ifi);
3843     ifi->ifi_family = PF_UNSPEC;
3844     ifi->ifi_index = ifindex;
3845     error = nl_sock_transact(rtnl_sock, &request, &reply);
3846     ofpbuf_uninit(&request);
3847     if (error) {
3848         return error;
3849     }
3850
3851     if (!nl_policy_parse(reply, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
3852                          rtnlgrp_link_policy,
3853                          attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
3854         ofpbuf_delete(reply);
3855         return EPROTO;
3856     }
3857
3858     if (!attrs[IFLA_STATS]) {
3859         VLOG_WARN_RL(&rl, "RTM_GETLINK reply lacks stats");
3860         ofpbuf_delete(reply);
3861         return EPROTO;
3862     }
3863
3864     rtnl_stats = nl_attr_get(attrs[IFLA_STATS]);
3865     stats->rx_packets = rtnl_stats->rx_packets;
3866     stats->tx_packets = rtnl_stats->tx_packets;
3867     stats->rx_bytes = rtnl_stats->rx_bytes;
3868     stats->tx_bytes = rtnl_stats->tx_bytes;
3869     stats->rx_errors = rtnl_stats->rx_errors;
3870     stats->tx_errors = rtnl_stats->tx_errors;
3871     stats->rx_dropped = rtnl_stats->rx_dropped;
3872     stats->tx_dropped = rtnl_stats->tx_dropped;
3873     stats->multicast = rtnl_stats->multicast;
3874     stats->collisions = rtnl_stats->collisions;
3875     stats->rx_length_errors = rtnl_stats->rx_length_errors;
3876     stats->rx_over_errors = rtnl_stats->rx_over_errors;
3877     stats->rx_crc_errors = rtnl_stats->rx_crc_errors;
3878     stats->rx_frame_errors = rtnl_stats->rx_frame_errors;
3879     stats->rx_fifo_errors = rtnl_stats->rx_fifo_errors;
3880     stats->rx_missed_errors = rtnl_stats->rx_missed_errors;
3881     stats->tx_aborted_errors = rtnl_stats->tx_aborted_errors;
3882     stats->tx_carrier_errors = rtnl_stats->tx_carrier_errors;
3883     stats->tx_fifo_errors = rtnl_stats->tx_fifo_errors;
3884     stats->tx_heartbeat_errors = rtnl_stats->tx_heartbeat_errors;
3885     stats->tx_window_errors = rtnl_stats->tx_window_errors;
3886
3887     ofpbuf_delete(reply);
3888
3889     return 0;
3890 }
3891
3892 static int
3893 get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats)
3894 {
3895     static const char fn[] = "/proc/net/dev";
3896     char line[1024];
3897     FILE *stream;
3898     int ln;
3899
3900     stream = fopen(fn, "r");
3901     if (!stream) {
3902         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
3903         return errno;
3904     }
3905
3906     ln = 0;
3907     while (fgets(line, sizeof line, stream)) {
3908         if (++ln >= 3) {
3909             char devname[16];
3910 #define X64 "%"SCNu64
3911             if (sscanf(line,
3912                        " %15[^:]:"
3913                        X64 X64 X64 X64 X64 X64 X64 "%*u"
3914                        X64 X64 X64 X64 X64 X64 X64 "%*u",
3915                        devname,
3916                        &stats->rx_bytes,
3917                        &stats->rx_packets,
3918                        &stats->rx_errors,
3919                        &stats->rx_dropped,
3920                        &stats->rx_fifo_errors,
3921                        &stats->rx_frame_errors,
3922                        &stats->multicast,
3923                        &stats->tx_bytes,
3924                        &stats->tx_packets,
3925                        &stats->tx_errors,
3926                        &stats->tx_dropped,
3927                        &stats->tx_fifo_errors,
3928                        &stats->collisions,
3929                        &stats->tx_carrier_errors) != 15) {
3930                 VLOG_WARN_RL(&rl, "%s:%d: parse error", fn, ln);
3931             } else if (!strcmp(devname, netdev_name)) {
3932                 stats->rx_length_errors = UINT64_MAX;
3933                 stats->rx_over_errors = UINT64_MAX;
3934                 stats->rx_crc_errors = UINT64_MAX;
3935                 stats->rx_missed_errors = UINT64_MAX;
3936                 stats->tx_aborted_errors = UINT64_MAX;
3937                 stats->tx_heartbeat_errors = UINT64_MAX;
3938                 stats->tx_window_errors = UINT64_MAX;
3939                 fclose(stream);
3940                 return 0;
3941             }
3942         }
3943     }
3944     VLOG_WARN_RL(&rl, "%s: no stats for %s", fn, netdev_name);
3945     fclose(stream);
3946     return ENODEV;
3947 }
3948
3949 static int
3950 get_flags(const struct netdev *netdev, int *flags)
3951 {
3952     struct ifreq ifr;
3953     int error;
3954
3955     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCGIFFLAGS,
3956                                   "SIOCGIFFLAGS");
3957     *flags = ifr.ifr_flags;
3958     return error;
3959 }
3960
3961 static int
3962 set_flags(struct netdev *netdev, int flags)
3963 {
3964     struct ifreq ifr;
3965
3966     ifr.ifr_flags = flags;
3967     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCSIFFLAGS,
3968                                  "SIOCSIFFLAGS");
3969 }
3970
3971 static int
3972 do_get_ifindex(const char *netdev_name)
3973 {
3974     struct ifreq ifr;
3975
3976     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
3977     COVERAGE_INC(netdev_get_ifindex);
3978     if (ioctl(af_inet_sock, SIOCGIFINDEX, &ifr) < 0) {
3979         VLOG_WARN_RL(&rl, "ioctl(SIOCGIFINDEX) on %s device failed: %s",
3980                      netdev_name, strerror(errno));
3981         return -errno;
3982     }
3983     return ifr.ifr_ifindex;
3984 }
3985
3986 static int
3987 get_ifindex(const struct netdev *netdev_, int *ifindexp)
3988 {
3989     struct netdev_dev_linux *netdev_dev =
3990                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
3991     *ifindexp = 0;
3992     if (!(netdev_dev->cache_valid & VALID_IFINDEX)) {
3993         int ifindex = do_get_ifindex(netdev_get_name(netdev_));
3994         if (ifindex < 0) {
3995             return -ifindex;
3996         }
3997         netdev_dev->cache_valid |= VALID_IFINDEX;
3998         netdev_dev->ifindex = ifindex;
3999     }
4000     *ifindexp = netdev_dev->ifindex;
4001     return 0;
4002 }
4003
4004 static int
4005 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
4006 {
4007     struct ifreq ifr;
4008     int hwaddr_family;
4009
4010     memset(&ifr, 0, sizeof ifr);
4011     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
4012     COVERAGE_INC(netdev_get_hwaddr);
4013     if (ioctl(af_inet_sock, SIOCGIFHWADDR, &ifr) < 0) {
4014         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
4015                  netdev_name, strerror(errno));
4016         return errno;
4017     }
4018     hwaddr_family = ifr.ifr_hwaddr.sa_family;
4019     if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
4020         VLOG_WARN("%s device has unknown hardware address family %d",
4021                   netdev_name, hwaddr_family);
4022     }
4023     memcpy(ea, ifr.ifr_hwaddr.sa_data, ETH_ADDR_LEN);
4024     return 0;
4025 }
4026
4027 static int
4028 set_etheraddr(const char *netdev_name, int hwaddr_family,
4029               const uint8_t mac[ETH_ADDR_LEN])
4030 {
4031     struct ifreq ifr;
4032
4033     memset(&ifr, 0, sizeof ifr);
4034     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
4035     ifr.ifr_hwaddr.sa_family = hwaddr_family;
4036     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
4037     COVERAGE_INC(netdev_set_hwaddr);
4038     if (ioctl(af_inet_sock, SIOCSIFHWADDR, &ifr) < 0) {
4039         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
4040                  netdev_name, strerror(errno));
4041         return errno;
4042     }
4043     return 0;
4044 }
4045
4046 static int
4047 netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *ecmd,
4048                         int cmd, const char *cmd_name)
4049 {
4050     struct ifreq ifr;
4051
4052     memset(&ifr, 0, sizeof ifr);
4053     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
4054     ifr.ifr_data = (caddr_t) ecmd;
4055
4056     ecmd->cmd = cmd;
4057     COVERAGE_INC(netdev_ethtool);
4058     if (ioctl(af_inet_sock, SIOCETHTOOL, &ifr) == 0) {
4059         return 0;
4060     } else {
4061         if (errno != EOPNOTSUPP) {
4062             VLOG_WARN_RL(&rl, "ethtool command %s on network device %s "
4063                          "failed: %s", cmd_name, name, strerror(errno));
4064         } else {
4065             /* The device doesn't support this operation.  That's pretty
4066              * common, so there's no point in logging anything. */
4067         }
4068         return errno;
4069     }
4070 }
4071
4072 static int
4073 netdev_linux_do_ioctl(const char *name, struct ifreq *ifr, int cmd,
4074                       const char *cmd_name)
4075 {
4076     strncpy(ifr->ifr_name, name, sizeof ifr->ifr_name);
4077     if (ioctl(af_inet_sock, cmd, ifr) == -1) {
4078         VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s", name, cmd_name,
4079                      strerror(errno));
4080         return errno;
4081     }
4082     return 0;
4083 }
4084
4085 static int
4086 netdev_linux_get_ipv4(const struct netdev *netdev, struct in_addr *ip,
4087                       int cmd, const char *cmd_name)
4088 {
4089     struct ifreq ifr;
4090     int error;
4091
4092     ifr.ifr_addr.sa_family = AF_INET;
4093     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, cmd, cmd_name);
4094     if (!error) {
4095         const struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
4096         *ip = sin->sin_addr;
4097     }
4098     return error;
4099 }