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