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