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