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