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