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