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