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