netdev-linux: Dump all queues, not just direct children of the root.
[sliver-openvswitch.git] / lib / netdev-linux.c
1 /*
2  * Copyright (c) 2009, 2010 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 #include <assert.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <arpa/inet.h>
22 #include <inttypes.h>
23 #include <linux/gen_stats.h>
24 #include <linux/if_tun.h>
25 #include <linux/ip.h>
26 #include <linux/types.h>
27 #include <linux/ethtool.h>
28 #include <linux/pkt_sched.h>
29 #include <linux/rtnetlink.h>
30 #include <linux/sockios.h>
31 #include <linux/version.h>
32 #include <sys/types.h>
33 #include <sys/ioctl.h>
34 #include <sys/socket.h>
35 #include <netpacket/packet.h>
36 #include <net/ethernet.h>
37 #include <net/if.h>
38 #include <linux/if_tunnel.h>
39 #include <net/if_arp.h>
40 #include <net/if_packet.h>
41 #include <net/route.h>
42 #include <netinet/in.h>
43 #include <poll.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47
48 #include "coverage.h"
49 #include "dynamic-string.h"
50 #include "fatal-signal.h"
51 #include "netdev-provider.h"
52 #include "netdev-vport.h"
53 #include "netlink.h"
54 #include "ofpbuf.h"
55 #include "openflow/openflow.h"
56 #include "openvswitch/gre.h"
57 #include "packets.h"
58 #include "poll-loop.h"
59 #include "port-array.h"
60 #include "rtnetlink.h"
61 #include "socket-util.h"
62 #include "shash.h"
63 #include "svec.h"
64
65 #define THIS_MODULE VLM_netdev_linux
66 #include "vlog.h"
67 \f
68 /* These were introduced in Linux 2.6.14, so they might be missing if we have
69  * old headers. */
70 #ifndef ADVERTISED_Pause
71 #define ADVERTISED_Pause                (1 << 13)
72 #endif
73 #ifndef ADVERTISED_Asym_Pause
74 #define ADVERTISED_Asym_Pause           (1 << 14)
75 #endif
76
77 /* This was introduced in Linux 2.6.25, so it might be missing if we have old
78  * headers. */
79 #ifndef TC_RTAB_SIZE
80 #define TC_RTAB_SIZE 1024
81 #endif
82
83 static struct rtnetlink_notifier netdev_linux_cache_notifier;
84 static int cache_notifier_refcount;
85
86 enum {
87     VALID_IFINDEX           = 1 << 0,
88     VALID_ETHERADDR         = 1 << 1,
89     VALID_IN4               = 1 << 2,
90     VALID_IN6               = 1 << 3,
91     VALID_MTU               = 1 << 4,
92     VALID_CARRIER           = 1 << 5,
93     VALID_IS_PSEUDO         = 1 << 6, /* Represents is_internal and is_tap. */
94     VALID_POLICING          = 1 << 7,
95     VALID_HAVE_VPORT_STATS  = 1 << 8
96 };
97
98 struct tap_state {
99     int fd;
100     bool opened;
101 };
102 \f
103 /* Traffic control. */
104
105 /* An instance of a traffic control class.  Always associated with a particular
106  * network device. */
107 struct tc {
108     const struct tc_ops *ops;
109
110     /* Maps from queue ID to tc-specific data.
111      *
112      * The generic netdev TC layer uses this to the following extent: if an
113      * entry is nonnull, then the queue whose ID is the index is assumed to
114      * exist; if an entry is null, then that queue is assumed not to exist.
115      * Implementations must adhere to this scheme, although they may store
116      * whatever they like as data.
117      */
118     struct port_array queues;
119 };
120
121 /* A particular kind of traffic control.  Each implementation generally maps to
122  * one particular Linux qdisc class.
123  *
124  * The functions below return 0 if successful or a positive errno value on
125  * failure, except where otherwise noted.  All of them must be provided, except
126  * where otherwise noted. */
127 struct tc_ops {
128     /* Name used by kernel in the TCA_KIND attribute of tcmsg, e.g. "htb".
129      * This is null for tc_ops_default and tc_ops_other, for which there are no
130      * appropriate values. */
131     const char *linux_name;
132
133     /* Name used in OVS database, e.g. "linux-htb".  Must be nonnull. */
134     const char *ovs_name;
135
136     /* Number of supported OpenFlow queues, 0 for qdiscs that have no
137      * queues.  The queues are numbered 0 through n_queues - 1. */
138     unsigned int n_queues;
139
140     /* Called to install this TC class on 'netdev'.  The implementation should
141      * make the Netlink calls required to set up 'netdev' with the right qdisc
142      * and configure it according to 'details'.  The implementation may assume
143      * that the current qdisc is the default; that is, there is no need for it
144      * to delete the current qdisc before installing itself.
145      *
146      * The contents of 'details' should be documented as valid for 'ovs_name'
147      * in the "other_config" column in the "QoS" table in vswitchd/vswitch.xml
148      * (which is built as ovs-vswitchd.conf.db(8)).
149      *
150      * This function must return 0 if and only if it sets 'netdev->tc' to an
151      * initialized 'struct tc'.
152      *
153      * (This function is null for tc_ops_other, which cannot be installed.  For
154      * other TC classes it should always be nonnull.) */
155     int (*tc_install)(struct netdev *netdev, const struct shash *details);
156
157     /* Called when the netdev code determines (through a Netlink query) that
158      * this TC class's qdisc is installed on 'netdev', but we didn't install
159      * it ourselves and so don't know any of the details.
160      *
161      * 'nlmsg' is the kernel reply to a RTM_GETQDISC Netlink message for
162      * 'netdev'.  The TCA_KIND attribute of 'nlmsg' is 'linux_name'.  The
163      * implementation should parse the other attributes of 'nlmsg' as
164      * necessary to determine its configuration.  If necessary it should also
165      * use Netlink queries to determine the configuration of queues on
166      * 'netdev'.
167      *
168      * This function must return 0 if and only if it sets 'netdev->tc' to an
169      * initialized 'struct tc'. */
170     int (*tc_load)(struct netdev *netdev, struct ofpbuf *nlmsg);
171
172     /* Destroys the data structures allocated by the implementation as part of
173      * 'tc'.  (This includes destroying 'tc->queues' by calling
174      * tc_destroy(tc).
175      *
176      * The implementation should not need to perform any Netlink calls.  If
177      * desirable, the caller is responsible for deconfiguring the kernel qdisc.
178      * (But it may not be desirable.)
179      *
180      * This function may be null if 'tc' is trivial. */
181     void (*tc_destroy)(struct tc *tc);
182
183     /* Retrieves details of 'netdev->tc' configuration into 'details'.
184      *
185      * The implementation should not need to perform any Netlink calls, because
186      * the 'tc_install' or 'tc_load' that instantiated 'netdev->tc' should have
187      * cached the configuration.
188      *
189      * The contents of 'details' should be documented as valid for 'ovs_name'
190      * in the "other_config" column in the "QoS" table in vswitchd/vswitch.xml
191      * (which is built as ovs-vswitchd.conf.db(8)).
192      *
193      * This function may be null if 'tc' is not configurable.
194      */
195     int (*qdisc_get)(const struct netdev *netdev, struct shash *details);
196
197     /* Reconfigures 'netdev->tc' according to 'details', performing any
198      * required Netlink calls to complete the reconfiguration.
199      *
200      * The contents of 'details' should be documented as valid for 'ovs_name'
201      * in the "other_config" column in the "QoS" table in vswitchd/vswitch.xml
202      * (which is built as ovs-vswitchd.conf.db(8)).
203      *
204      * This function may be null if 'tc' is not configurable.
205      */
206     int (*qdisc_set)(struct netdev *, const struct shash *details);
207
208     /* Retrieves details of 'queue_id' on 'netdev->tc' into 'details'.  The
209      * caller ensures that 'queues' has a nonnull value for index 'queue_id.
210      *
211      * The contents of 'details' should be documented as valid for 'ovs_name'
212      * in the "other_config" column in the "Queue" table in
213      * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
214      *
215      * The implementation should not need to perform any Netlink calls, because
216      * the 'tc_install' or 'tc_load' that instantiated 'netdev->tc' should have
217      * cached the queue configuration.
218      *
219      * This function may be null if 'tc' does not have queues ('n_queues' is
220      * 0). */
221     int (*class_get)(const struct netdev *netdev, unsigned int queue_id,
222                      struct shash *details);
223
224     /* Configures or reconfigures 'queue_id' on 'netdev->tc' according to
225      * 'details', perfoming any required Netlink calls to complete the
226      * reconfiguration.  The caller ensures that 'queue_id' is less than
227      * 'n_queues'.
228      *
229      * The contents of 'details' should be documented as valid for 'ovs_name'
230      * in the "other_config" column in the "Queue" table in
231      * vswitchd/vswitch.xml (which is built as ovs-vswitchd.conf.db(8)).
232      *
233      * This function may be null if 'tc' does not have queues or its queues are
234      * not configurable. */
235     int (*class_set)(struct netdev *, unsigned int queue_id,
236                      const struct shash *details);
237
238     /* Deletes 'queue_id' from 'netdev->tc'.  The caller ensures that 'queues'
239      * has a nonnull value for index 'queue_id.
240      *
241      * This function may be null if 'tc' does not have queues or its queues
242      * cannot be deleted. */
243     int (*class_delete)(struct netdev *, unsigned int queue_id);
244
245     /* Obtains stats for 'queue' from 'netdev->tc'.  The caller ensures that
246      * 'queues' has a nonnull value for index 'queue_id.
247      *
248      * On success, initializes '*stats'.
249      *
250      * This function may be null if 'tc' does not have queues or if it cannot
251      * report queue statistics. */
252     int (*class_get_stats)(const struct netdev *netdev, unsigned int queue_id,
253                            struct netdev_queue_stats *stats);
254
255     /* Extracts queue stats from 'nlmsg', which is a response to a
256      * RTM_GETTCLASS message, and passes them to 'cb' along with 'aux'.
257      *
258      * This function may be null if 'tc' does not have queues or if it cannot
259      * report queue statistics. */
260     int (*class_dump_stats)(const struct netdev *netdev,
261                             const struct ofpbuf *nlmsg,
262                             netdev_dump_queue_stats_cb *cb, void *aux);
263 };
264
265 static void
266 tc_init(struct tc *tc, const struct tc_ops *ops)
267 {
268     tc->ops = ops;
269     port_array_init(&tc->queues);
270 }
271
272 static void
273 tc_destroy(struct tc *tc)
274 {
275     port_array_destroy(&tc->queues);
276 }
277
278 static const struct tc_ops tc_ops_htb;
279 static const struct tc_ops tc_ops_default;
280 static const struct tc_ops tc_ops_other;
281
282 static const struct tc_ops *tcs[] = {
283     &tc_ops_htb,                /* Hierarchy token bucket (see tc-htb(8)). */
284     &tc_ops_default,            /* Default qdisc (see tc-pfifo_fast(8)). */
285     &tc_ops_other,              /* Some other qdisc. */
286     NULL
287 };
288
289 static unsigned int tc_make_handle(unsigned int major, unsigned int minor);
290 static unsigned int tc_get_major(unsigned int handle);
291 static unsigned int tc_get_minor(unsigned int handle);
292
293 static unsigned int tc_ticks_to_bytes(unsigned int rate, unsigned int ticks);
294 static unsigned int tc_bytes_to_ticks(unsigned int rate, unsigned int size);
295 static unsigned int tc_buffer_per_jiffy(unsigned int rate);
296
297 static struct tcmsg *tc_make_request(const struct netdev *, int type,
298                                      unsigned int flags, struct ofpbuf *);
299 static int tc_transact(struct ofpbuf *request, struct ofpbuf **replyp);
300
301 static int tc_parse_qdisc(const struct ofpbuf *, const char **kind,
302                           struct nlattr **options);
303 static int tc_parse_class(const struct ofpbuf *, unsigned int *queue_id,
304                           struct nlattr **options,
305                           struct netdev_queue_stats *);
306 static int tc_query_class(const struct netdev *,
307                           unsigned int handle, unsigned int parent,
308                           struct ofpbuf **replyp);
309 static int tc_delete_class(const struct netdev *, unsigned int handle);
310
311 static int tc_del_qdisc(struct netdev *netdev);
312 static int tc_query_qdisc(const struct netdev *netdev);
313
314 static int tc_calc_cell_log(unsigned int mtu);
315 static void tc_fill_rate(struct tc_ratespec *rate, uint64_t bps, int mtu);
316 static void tc_put_rtab(struct ofpbuf *, uint16_t type,
317                         const struct tc_ratespec *rate);
318 static int tc_calc_buffer(unsigned int Bps, int mtu, uint64_t burst_bytes);
319 \f
320 struct netdev_dev_linux {
321     struct netdev_dev netdev_dev;
322
323     struct shash_node *shash_node;
324     unsigned int cache_valid;
325
326     /* The following are figured out "on demand" only.  They are only valid
327      * when the corresponding VALID_* bit in 'cache_valid' is set. */
328     int ifindex;
329     uint8_t etheraddr[ETH_ADDR_LEN];
330     struct in_addr address, netmask;
331     struct in6_addr in6;
332     int mtu;
333     int carrier;
334     bool is_internal;           /* Is this an openvswitch internal device? */
335     bool is_tap;                /* Is this a tuntap device? */
336     uint32_t kbits_rate;        /* Policing data. */
337     uint32_t kbits_burst;
338     bool have_vport_stats;
339     struct tc *tc;
340
341     union {
342         struct tap_state tap;
343     } state;
344 };
345
346 struct netdev_linux {
347     struct netdev netdev;
348     int fd;
349 };
350
351 /* An AF_INET socket (used for ioctl operations). */
352 static int af_inet_sock = -1;
353
354 /* A Netlink routing socket that is not subscribed to any multicast groups. */
355 static struct nl_sock *rtnl_sock;
356
357 struct netdev_linux_notifier {
358     struct netdev_notifier notifier;
359     struct list node;
360 };
361
362 static struct shash netdev_linux_notifiers =
363     SHASH_INITIALIZER(&netdev_linux_notifiers);
364 static struct rtnetlink_notifier netdev_linux_poll_notifier;
365
366 /* This is set pretty low because we probably won't learn anything from the
367  * additional log messages. */
368 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
369
370 static int netdev_linux_init(void);
371
372 static int netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *,
373                                    int cmd, const char *cmd_name);
374 static int netdev_linux_do_ioctl(const char *name, struct ifreq *, int cmd,
375                                  const char *cmd_name);
376 static int netdev_linux_get_ipv4(const struct netdev *, struct in_addr *,
377                                  int cmd, const char *cmd_name);
378 static int get_flags(const struct netdev *, int *flagsp);
379 static int set_flags(struct netdev *, int flags);
380 static int do_get_ifindex(const char *netdev_name);
381 static int get_ifindex(const struct netdev *, int *ifindexp);
382 static int do_set_addr(struct netdev *netdev,
383                        int ioctl_nr, const char *ioctl_name,
384                        struct in_addr addr);
385 static int get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN]);
386 static int set_etheraddr(const char *netdev_name, int hwaddr_family,
387                          const uint8_t[ETH_ADDR_LEN]);
388 static int get_stats_via_netlink(int ifindex, struct netdev_stats *stats);
389 static int get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats);
390
391 static bool
392 is_netdev_linux_class(const struct netdev_class *netdev_class)
393 {
394     return netdev_class->init == netdev_linux_init;
395 }
396
397 static struct netdev_dev_linux *
398 netdev_dev_linux_cast(const struct netdev_dev *netdev_dev)
399 {
400     const struct netdev_class *netdev_class = netdev_dev_get_class(netdev_dev);
401     assert(is_netdev_linux_class(netdev_class));
402
403     return CONTAINER_OF(netdev_dev, struct netdev_dev_linux, netdev_dev);
404 }
405
406 static struct netdev_linux *
407 netdev_linux_cast(const struct netdev *netdev)
408 {
409     struct netdev_dev *netdev_dev = netdev_get_dev(netdev);
410     const struct netdev_class *netdev_class = netdev_dev_get_class(netdev_dev);
411     assert(is_netdev_linux_class(netdev_class));
412
413     return CONTAINER_OF(netdev, struct netdev_linux, netdev);
414 }
415 \f
416 static int
417 netdev_linux_init(void)
418 {
419     static int status = -1;
420     if (status < 0) {
421         /* Create AF_INET socket. */
422         af_inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
423         status = af_inet_sock >= 0 ? 0 : errno;
424         if (status) {
425             VLOG_ERR("failed to create inet socket: %s", strerror(status));
426         }
427
428         /* Create rtnetlink socket. */
429         if (!status) {
430             status = nl_sock_create(NETLINK_ROUTE, 0, 0, 0, &rtnl_sock);
431             if (status) {
432                 VLOG_ERR_RL(&rl, "failed to create rtnetlink socket: %s",
433                             strerror(status));
434             }
435         }
436     }
437     return status;
438 }
439
440 static void
441 netdev_linux_run(void)
442 {
443     rtnetlink_notifier_run();
444 }
445
446 static void
447 netdev_linux_wait(void)
448 {
449     rtnetlink_notifier_wait();
450 }
451
452 static void
453 netdev_linux_cache_cb(const struct rtnetlink_change *change,
454                       void *aux OVS_UNUSED)
455 {
456     struct netdev_dev_linux *dev;
457     if (change) {
458         struct netdev_dev *base_dev = netdev_dev_from_name(change->ifname);
459         if (base_dev) {
460             const struct netdev_class *netdev_class =
461                                                 netdev_dev_get_class(base_dev);
462
463             if (is_netdev_linux_class(netdev_class)) {
464                 dev = netdev_dev_linux_cast(base_dev);
465                 dev->cache_valid = 0;
466             }
467         }
468     } else {
469         struct shash device_shash;
470         struct shash_node *node;
471
472         shash_init(&device_shash);
473         netdev_dev_get_devices(&netdev_linux_class, &device_shash);
474         SHASH_FOR_EACH (node, &device_shash) {
475             dev = node->data;
476             dev->cache_valid = 0;
477         }
478         shash_destroy(&device_shash);
479     }
480 }
481
482 /* Creates the netdev device of 'type' with 'name'. */
483 static int
484 netdev_linux_create_system(const char *name, const char *type OVS_UNUSED,
485                     const struct shash *args, struct netdev_dev **netdev_devp)
486 {
487     struct netdev_dev_linux *netdev_dev;
488     int error;
489
490     if (!shash_is_empty(args)) {
491         VLOG_WARN("%s: arguments for system devices should be empty", name);
492     }
493
494     if (!cache_notifier_refcount) {
495         error = rtnetlink_notifier_register(&netdev_linux_cache_notifier,
496                                             netdev_linux_cache_cb, NULL);
497         if (error) {
498             return error;
499         }
500     }
501     cache_notifier_refcount++;
502
503     netdev_dev = xzalloc(sizeof *netdev_dev);
504     netdev_dev_init(&netdev_dev->netdev_dev, name, &netdev_linux_class);
505
506     *netdev_devp = &netdev_dev->netdev_dev;
507     return 0;
508 }
509
510 /* For most types of netdevs we open the device for each call of
511  * netdev_open().  However, this is not the case with tap devices,
512  * since it is only possible to open the device once.  In this
513  * situation we share a single file descriptor, and consequently
514  * buffers, across all readers.  Therefore once data is read it will
515  * be unavailable to other reads for tap devices. */
516 static int
517 netdev_linux_create_tap(const char *name, const char *type OVS_UNUSED,
518                     const struct shash *args, struct netdev_dev **netdev_devp)
519 {
520     struct netdev_dev_linux *netdev_dev;
521     struct tap_state *state;
522     static const char tap_dev[] = "/dev/net/tun";
523     struct ifreq ifr;
524     int error;
525
526     if (!shash_is_empty(args)) {
527         VLOG_WARN("%s: arguments for TAP devices should be empty", name);
528     }
529
530     netdev_dev = xzalloc(sizeof *netdev_dev);
531     state = &netdev_dev->state.tap;
532
533     /* Open tap device. */
534     state->fd = open(tap_dev, O_RDWR);
535     if (state->fd < 0) {
536         error = errno;
537         VLOG_WARN("opening \"%s\" failed: %s", tap_dev, strerror(error));
538         goto error;
539     }
540
541     /* Create tap device. */
542     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
543     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
544     if (ioctl(state->fd, TUNSETIFF, &ifr) == -1) {
545         VLOG_WARN("%s: creating tap device failed: %s", name,
546                   strerror(errno));
547         error = errno;
548         goto error;
549     }
550
551     /* Make non-blocking. */
552     error = set_nonblocking(state->fd);
553     if (error) {
554         goto error;
555     }
556
557     netdev_dev_init(&netdev_dev->netdev_dev, name, &netdev_tap_class);
558     *netdev_devp = &netdev_dev->netdev_dev;
559     return 0;
560
561 error:
562     free(netdev_dev);
563     return error;
564 }
565
566 static void
567 destroy_tap(struct netdev_dev_linux *netdev_dev)
568 {
569     struct tap_state *state = &netdev_dev->state.tap;
570
571     if (state->fd >= 0) {
572         close(state->fd);
573     }
574 }
575
576 /* Destroys the netdev device 'netdev_dev_'. */
577 static void
578 netdev_linux_destroy(struct netdev_dev *netdev_dev_)
579 {
580     struct netdev_dev_linux *netdev_dev = netdev_dev_linux_cast(netdev_dev_);
581     const char *type = netdev_dev_get_type(netdev_dev_);
582
583     if (netdev_dev->tc && netdev_dev->tc->ops->tc_destroy) {
584         netdev_dev->tc->ops->tc_destroy(netdev_dev->tc);
585     }
586
587     if (!strcmp(type, "system")) {
588         cache_notifier_refcount--;
589
590         if (!cache_notifier_refcount) {
591             rtnetlink_notifier_unregister(&netdev_linux_cache_notifier);
592         }
593     } else if (!strcmp(type, "tap")) {
594         destroy_tap(netdev_dev);
595     }
596
597     free(netdev_dev);
598 }
599
600 static int
601 netdev_linux_open(struct netdev_dev *netdev_dev_, int ethertype,
602                   struct netdev **netdevp)
603 {
604     struct netdev_dev_linux *netdev_dev = netdev_dev_linux_cast(netdev_dev_);
605     struct netdev_linux *netdev;
606     enum netdev_flags flags;
607     int error;
608
609     /* Allocate network device. */
610     netdev = xzalloc(sizeof *netdev);
611     netdev->fd = -1;
612     netdev_init(&netdev->netdev, netdev_dev_);
613
614     error = netdev_get_flags(&netdev->netdev, &flags);
615     if (error == ENODEV) {
616         goto error;
617     }
618
619     if (!strcmp(netdev_dev_get_type(netdev_dev_), "tap") &&
620         !netdev_dev->state.tap.opened) {
621
622         /* We assume that the first user of the tap device is the primary user
623          * and give them the tap FD.  Subsequent users probably just expect
624          * this to be a system device so open it normally to avoid send/receive
625          * directions appearing to be reversed. */
626         netdev->fd = netdev_dev->state.tap.fd;
627         netdev_dev->state.tap.opened = true;
628     } else if (ethertype != NETDEV_ETH_TYPE_NONE) {
629         struct sockaddr_ll sll;
630         int protocol;
631         int ifindex;
632
633         /* Create file descriptor. */
634         protocol = (ethertype == NETDEV_ETH_TYPE_ANY ? ETH_P_ALL
635                     : ethertype == NETDEV_ETH_TYPE_802_2 ? ETH_P_802_2
636                     : ethertype);
637         netdev->fd = socket(PF_PACKET, SOCK_RAW, htons(protocol));
638         if (netdev->fd < 0) {
639             error = errno;
640             goto error;
641         }
642
643         /* Set non-blocking mode. */
644         error = set_nonblocking(netdev->fd);
645         if (error) {
646             goto error;
647         }
648
649         /* Get ethernet device index. */
650         error = get_ifindex(&netdev->netdev, &ifindex);
651         if (error) {
652             goto error;
653         }
654
655         /* Bind to specific ethernet device. */
656         memset(&sll, 0, sizeof sll);
657         sll.sll_family = AF_PACKET;
658         sll.sll_ifindex = ifindex;
659         if (bind(netdev->fd,
660                  (struct sockaddr *) &sll, sizeof sll) < 0) {
661             error = errno;
662             VLOG_ERR("bind to %s failed: %s", netdev_dev_get_name(netdev_dev_),
663                      strerror(error));
664             goto error;
665         }
666
667         /* Between the socket() and bind() calls above, the socket receives all
668          * packets of the requested type on all system interfaces.  We do not
669          * want to receive that data, but there is no way to avoid it.  So we
670          * must now drain out the receive queue. */
671         error = drain_rcvbuf(netdev->fd);
672         if (error) {
673             goto error;
674         }
675     }
676
677     *netdevp = &netdev->netdev;
678     return 0;
679
680 error:
681     netdev_uninit(&netdev->netdev, true);
682     return error;
683 }
684
685 /* Closes and destroys 'netdev'. */
686 static void
687 netdev_linux_close(struct netdev *netdev_)
688 {
689     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
690
691     if (netdev->fd > 0 && strcmp(netdev_get_type(netdev_), "tap")) {
692         close(netdev->fd);
693     }
694     free(netdev);
695 }
696
697 /* Initializes 'svec' with a list of the names of all known network devices. */
698 static int
699 netdev_linux_enumerate(struct svec *svec)
700 {
701     struct if_nameindex *names;
702
703     names = if_nameindex();
704     if (names) {
705         size_t i;
706
707         for (i = 0; names[i].if_name != NULL; i++) {
708             svec_add(svec, names[i].if_name);
709         }
710         if_freenameindex(names);
711         return 0;
712     } else {
713         VLOG_WARN("could not obtain list of network device names: %s",
714                   strerror(errno));
715         return errno;
716     }
717 }
718
719 static int
720 netdev_linux_recv(struct netdev *netdev_, void *data, size_t size)
721 {
722     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
723
724     if (netdev->fd < 0) {
725         /* Device was opened with NETDEV_ETH_TYPE_NONE. */
726         return -EAGAIN;
727     }
728
729     for (;;) {
730         ssize_t retval = read(netdev->fd, data, size);
731         if (retval >= 0) {
732             return retval;
733         } else if (errno != EINTR) {
734             if (errno != EAGAIN) {
735                 VLOG_WARN_RL(&rl, "error receiving Ethernet packet on %s: %s",
736                              strerror(errno), netdev_get_name(netdev_));
737             }
738             return -errno;
739         }
740     }
741 }
742
743 /* Registers with the poll loop to wake up from the next call to poll_block()
744  * when a packet is ready to be received with netdev_recv() on 'netdev'. */
745 static void
746 netdev_linux_recv_wait(struct netdev *netdev_)
747 {
748     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
749     if (netdev->fd >= 0) {
750         poll_fd_wait(netdev->fd, POLLIN);
751     }
752 }
753
754 /* Discards all packets waiting to be received from 'netdev'. */
755 static int
756 netdev_linux_drain(struct netdev *netdev_)
757 {
758     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
759     if (netdev->fd < 0) {
760         return 0;
761     } else if (!strcmp(netdev_get_type(netdev_), "tap")) {
762         struct ifreq ifr;
763         int error = netdev_linux_do_ioctl(netdev_get_name(netdev_), &ifr,
764                                           SIOCGIFTXQLEN, "SIOCGIFTXQLEN");
765         if (error) {
766             return error;
767         }
768         drain_fd(netdev->fd, ifr.ifr_qlen);
769         return 0;
770     } else {
771         return drain_rcvbuf(netdev->fd);
772     }
773 }
774
775 /* Sends 'buffer' on 'netdev'.  Returns 0 if successful, otherwise a positive
776  * errno value.  Returns EAGAIN without blocking if the packet cannot be queued
777  * immediately.  Returns EMSGSIZE if a partial packet was transmitted or if
778  * the packet is too big or too small to transmit on the device.
779  *
780  * The caller retains ownership of 'buffer' in all cases.
781  *
782  * The kernel maintains a packet transmission queue, so the caller is not
783  * expected to do additional queuing of packets. */
784 static int
785 netdev_linux_send(struct netdev *netdev_, const void *data, size_t size)
786 {
787     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
788
789     /* XXX should support sending even if 'ethertype' was NETDEV_ETH_TYPE_NONE.
790      */
791     if (netdev->fd < 0) {
792         return EPIPE;
793     }
794
795     for (;;) {
796         ssize_t retval = write(netdev->fd, data, size);
797         if (retval < 0) {
798             /* The Linux AF_PACKET implementation never blocks waiting for room
799              * for packets, instead returning ENOBUFS.  Translate this into
800              * EAGAIN for the caller. */
801             if (errno == ENOBUFS) {
802                 return EAGAIN;
803             } else if (errno == EINTR) {
804                 continue;
805             } else if (errno != EAGAIN) {
806                 VLOG_WARN_RL(&rl, "error sending Ethernet packet on %s: %s",
807                              netdev_get_name(netdev_), strerror(errno));
808             }
809             return errno;
810         } else if (retval != size) {
811             VLOG_WARN_RL(&rl, "sent partial Ethernet packet (%zd bytes of "
812                          "%zu) on %s", retval, size, netdev_get_name(netdev_));
813             return EMSGSIZE;
814         } else {
815             return 0;
816         }
817     }
818 }
819
820 /* Registers with the poll loop to wake up from the next call to poll_block()
821  * when the packet transmission queue has sufficient room to transmit a packet
822  * with netdev_send().
823  *
824  * The kernel maintains a packet transmission queue, so the client is not
825  * expected to do additional queuing of packets.  Thus, this function is
826  * unlikely to ever be used.  It is included for completeness. */
827 static void
828 netdev_linux_send_wait(struct netdev *netdev_)
829 {
830     struct netdev_linux *netdev = netdev_linux_cast(netdev_);
831     if (netdev->fd < 0) {
832         /* Nothing to do. */
833     } else if (strcmp(netdev_get_type(netdev_), "tap")) {
834         poll_fd_wait(netdev->fd, POLLOUT);
835     } else {
836         /* TAP device always accepts packets.*/
837         poll_immediate_wake();
838     }
839 }
840
841 /* Attempts to set 'netdev''s MAC address to 'mac'.  Returns 0 if successful,
842  * otherwise a positive errno value. */
843 static int
844 netdev_linux_set_etheraddr(struct netdev *netdev_,
845                            const uint8_t mac[ETH_ADDR_LEN])
846 {
847     struct netdev_dev_linux *netdev_dev =
848                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
849     int error;
850
851     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)
852         || !eth_addr_equals(netdev_dev->etheraddr, mac)) {
853         error = set_etheraddr(netdev_get_name(netdev_), ARPHRD_ETHER, mac);
854         if (!error) {
855             netdev_dev->cache_valid |= VALID_ETHERADDR;
856             memcpy(netdev_dev->etheraddr, mac, ETH_ADDR_LEN);
857         }
858     } else {
859         error = 0;
860     }
861     return error;
862 }
863
864 /* Returns a pointer to 'netdev''s MAC address.  The caller must not modify or
865  * free the returned buffer. */
866 static int
867 netdev_linux_get_etheraddr(const struct netdev *netdev_,
868                            uint8_t mac[ETH_ADDR_LEN])
869 {
870     struct netdev_dev_linux *netdev_dev =
871                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
872     if (!(netdev_dev->cache_valid & VALID_ETHERADDR)) {
873         int error = get_etheraddr(netdev_get_name(netdev_),
874                                   netdev_dev->etheraddr);
875         if (error) {
876             return error;
877         }
878         netdev_dev->cache_valid |= VALID_ETHERADDR;
879     }
880     memcpy(mac, netdev_dev->etheraddr, ETH_ADDR_LEN);
881     return 0;
882 }
883
884 /* Returns the maximum size of transmitted (and received) packets on 'netdev',
885  * in bytes, not including the hardware header; thus, this is typically 1500
886  * bytes for Ethernet devices. */
887 static int
888 netdev_linux_get_mtu(const struct netdev *netdev_, int *mtup)
889 {
890     struct netdev_dev_linux *netdev_dev =
891                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
892     if (!(netdev_dev->cache_valid & VALID_MTU)) {
893         struct ifreq ifr;
894         int error;
895
896         error = netdev_linux_do_ioctl(netdev_get_name(netdev_), &ifr,
897                                       SIOCGIFMTU, "SIOCGIFMTU");
898         if (error) {
899             return error;
900         }
901         netdev_dev->mtu = ifr.ifr_mtu;
902         netdev_dev->cache_valid |= VALID_MTU;
903     }
904     *mtup = netdev_dev->mtu;
905     return 0;
906 }
907
908 /* Returns the ifindex of 'netdev', if successful, as a positive number.
909  * On failure, returns a negative errno value. */
910 static int
911 netdev_linux_get_ifindex(const struct netdev *netdev)
912 {
913     int ifindex, error;
914
915     error = get_ifindex(netdev, &ifindex);
916     return error ? -error : ifindex;
917 }
918
919 static int
920 netdev_linux_get_carrier(const struct netdev *netdev_, bool *carrier)
921 {
922     struct netdev_dev_linux *netdev_dev =
923                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
924     int error = 0;
925     char *fn = NULL;
926     int fd = -1;
927
928     if (!(netdev_dev->cache_valid & VALID_CARRIER)) {
929         char line[8];
930         int retval;
931
932         fn = xasprintf("/sys/class/net/%s/carrier",
933                        netdev_get_name(netdev_));
934         fd = open(fn, O_RDONLY);
935         if (fd < 0) {
936             error = errno;
937             VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(error));
938             goto exit;
939         }
940
941         retval = read(fd, line, sizeof line);
942         if (retval < 0) {
943             error = errno;
944             if (error == EINVAL) {
945                 /* This is the normal return value when we try to check carrier
946                  * if the network device is not up. */
947             } else {
948                 VLOG_WARN_RL(&rl, "%s: read failed: %s", fn, strerror(error));
949             }
950             goto exit;
951         } else if (retval == 0) {
952             error = EPROTO;
953             VLOG_WARN_RL(&rl, "%s: unexpected end of file", fn);
954             goto exit;
955         }
956
957         if (line[0] != '0' && line[0] != '1') {
958             error = EPROTO;
959             VLOG_WARN_RL(&rl, "%s: value is %c (expected 0 or 1)",
960                          fn, line[0]);
961             goto exit;
962         }
963         netdev_dev->carrier = line[0] != '0';
964         netdev_dev->cache_valid |= VALID_CARRIER;
965     }
966     *carrier = netdev_dev->carrier;
967     error = 0;
968
969 exit:
970     if (fd >= 0) {
971         close(fd);
972     }
973     free(fn);
974     return error;
975 }
976
977 /* Check whether we can we use RTM_GETLINK to get network device statistics.
978  * In pre-2.6.19 kernels, this was only available if wireless extensions were
979  * enabled. */
980 static bool
981 check_for_working_netlink_stats(void)
982 {
983     /* Decide on the netdev_get_stats() implementation to use.  Netlink is
984      * preferable, so if that works, we'll use it. */
985     int ifindex = do_get_ifindex("lo");
986     if (ifindex < 0) {
987         VLOG_WARN("failed to get ifindex for lo, "
988                   "obtaining netdev stats from proc");
989         return false;
990     } else {
991         struct netdev_stats stats;
992         int error = get_stats_via_netlink(ifindex, &stats);
993         if (!error) {
994             VLOG_DBG("obtaining netdev stats via rtnetlink");
995             return true;
996         } else {
997             VLOG_INFO("RTM_GETLINK failed (%s), obtaining netdev stats "
998                       "via proc (you are probably running a pre-2.6.19 "
999                       "kernel)", strerror(error));
1000             return false;
1001         }
1002     }
1003 }
1004
1005 /* Brings the 'is_internal' and 'is_tap' members of 'netdev_dev' up-to-date. */
1006 static void
1007 netdev_linux_update_is_pseudo(struct netdev_dev_linux *netdev_dev)
1008 {
1009     if (!(netdev_dev->cache_valid & VALID_IS_PSEUDO)) {
1010         const char *name = netdev_dev_get_name(&netdev_dev->netdev_dev);
1011         const char *type = netdev_dev_get_type(&netdev_dev->netdev_dev);
1012         
1013         netdev_dev->is_tap = !strcmp(type, "tap");
1014         netdev_dev->is_internal = false;
1015         if (!netdev_dev->is_tap) {
1016             struct ethtool_drvinfo drvinfo;
1017             int error;
1018
1019             memset(&drvinfo, 0, sizeof drvinfo);
1020             error = netdev_linux_do_ethtool(name,
1021                                             (struct ethtool_cmd *)&drvinfo,
1022                                             ETHTOOL_GDRVINFO,
1023                                             "ETHTOOL_GDRVINFO");
1024
1025             if (!error && !strcmp(drvinfo.driver, "openvswitch")) {
1026                 netdev_dev->is_internal = true;
1027             }
1028         }
1029
1030         netdev_dev->cache_valid |= VALID_IS_PSEUDO;
1031     }
1032 }
1033
1034 static void
1035 swap_uint64(uint64_t *a, uint64_t *b)
1036 {
1037     *a ^= *b;
1038     *b ^= *a;
1039     *a ^= *b;
1040 }
1041
1042 /* Retrieves current device stats for 'netdev'. */
1043 static int
1044 netdev_linux_get_stats(const struct netdev *netdev_,
1045                        struct netdev_stats *stats)
1046 {
1047     struct netdev_dev_linux *netdev_dev =
1048                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1049     static int use_netlink_stats = -1;
1050     int error;
1051
1052     COVERAGE_INC(netdev_get_stats);
1053
1054     if (netdev_dev->have_vport_stats ||
1055         !(netdev_dev->cache_valid & VALID_HAVE_VPORT_STATS)) {
1056
1057         error = netdev_vport_get_stats(netdev_, stats);
1058         netdev_dev->have_vport_stats = !error;
1059         netdev_dev->cache_valid |= VALID_HAVE_VPORT_STATS;
1060     }
1061
1062     if (!netdev_dev->have_vport_stats) {
1063         if (use_netlink_stats < 0) {
1064             use_netlink_stats = check_for_working_netlink_stats();
1065         }
1066         if (use_netlink_stats) {
1067             int ifindex;
1068
1069             error = get_ifindex(netdev_, &ifindex);
1070             if (!error) {
1071                 error = get_stats_via_netlink(ifindex, stats);
1072             }
1073         } else {
1074             error = get_stats_via_proc(netdev_get_name(netdev_), stats);
1075         }
1076     }
1077
1078     /* If this port is an internal port then the transmit and receive stats
1079      * will appear to be swapped relative to the other ports since we are the
1080      * one sending the data, not a remote computer.  For consistency, we swap
1081      * them back here. This does not apply if we are getting stats from the
1082      * vport layer because it always tracks stats from the perspective of the
1083      * switch. */
1084     netdev_linux_update_is_pseudo(netdev_dev);
1085     if (!error && !netdev_dev->have_vport_stats &&
1086         (netdev_dev->is_internal || netdev_dev->is_tap)) {
1087         swap_uint64(&stats->rx_packets, &stats->tx_packets);
1088         swap_uint64(&stats->rx_bytes, &stats->tx_bytes);
1089         swap_uint64(&stats->rx_errors, &stats->tx_errors);
1090         swap_uint64(&stats->rx_dropped, &stats->tx_dropped);
1091         stats->rx_length_errors = 0;
1092         stats->rx_over_errors = 0;
1093         stats->rx_crc_errors = 0;
1094         stats->rx_frame_errors = 0;
1095         stats->rx_fifo_errors = 0;
1096         stats->rx_missed_errors = 0;
1097         stats->tx_aborted_errors = 0;
1098         stats->tx_carrier_errors = 0;
1099         stats->tx_fifo_errors = 0;
1100         stats->tx_heartbeat_errors = 0;
1101         stats->tx_window_errors = 0;
1102     }
1103
1104     return error;
1105 }
1106
1107 /* Stores the features supported by 'netdev' into each of '*current',
1108  * '*advertised', '*supported', and '*peer' that are non-null.  Each value is a
1109  * bitmap of "enum ofp_port_features" bits, in host byte order.  Returns 0 if
1110  * successful, otherwise a positive errno value. */
1111 static int
1112 netdev_linux_get_features(struct netdev *netdev,
1113                           uint32_t *current, uint32_t *advertised,
1114                           uint32_t *supported, uint32_t *peer)
1115 {
1116     struct ethtool_cmd ecmd;
1117     int error;
1118
1119     memset(&ecmd, 0, sizeof ecmd);
1120     error = netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1121                                     ETHTOOL_GSET, "ETHTOOL_GSET");
1122     if (error) {
1123         return error;
1124     }
1125
1126     /* Supported features. */
1127     *supported = 0;
1128     if (ecmd.supported & SUPPORTED_10baseT_Half) {
1129         *supported |= OFPPF_10MB_HD;
1130     }
1131     if (ecmd.supported & SUPPORTED_10baseT_Full) {
1132         *supported |= OFPPF_10MB_FD;
1133     }
1134     if (ecmd.supported & SUPPORTED_100baseT_Half)  {
1135         *supported |= OFPPF_100MB_HD;
1136     }
1137     if (ecmd.supported & SUPPORTED_100baseT_Full) {
1138         *supported |= OFPPF_100MB_FD;
1139     }
1140     if (ecmd.supported & SUPPORTED_1000baseT_Half) {
1141         *supported |= OFPPF_1GB_HD;
1142     }
1143     if (ecmd.supported & SUPPORTED_1000baseT_Full) {
1144         *supported |= OFPPF_1GB_FD;
1145     }
1146     if (ecmd.supported & SUPPORTED_10000baseT_Full) {
1147         *supported |= OFPPF_10GB_FD;
1148     }
1149     if (ecmd.supported & SUPPORTED_TP) {
1150         *supported |= OFPPF_COPPER;
1151     }
1152     if (ecmd.supported & SUPPORTED_FIBRE) {
1153         *supported |= OFPPF_FIBER;
1154     }
1155     if (ecmd.supported & SUPPORTED_Autoneg) {
1156         *supported |= OFPPF_AUTONEG;
1157     }
1158     if (ecmd.supported & SUPPORTED_Pause) {
1159         *supported |= OFPPF_PAUSE;
1160     }
1161     if (ecmd.supported & SUPPORTED_Asym_Pause) {
1162         *supported |= OFPPF_PAUSE_ASYM;
1163     }
1164
1165     /* Advertised features. */
1166     *advertised = 0;
1167     if (ecmd.advertising & ADVERTISED_10baseT_Half) {
1168         *advertised |= OFPPF_10MB_HD;
1169     }
1170     if (ecmd.advertising & ADVERTISED_10baseT_Full) {
1171         *advertised |= OFPPF_10MB_FD;
1172     }
1173     if (ecmd.advertising & ADVERTISED_100baseT_Half) {
1174         *advertised |= OFPPF_100MB_HD;
1175     }
1176     if (ecmd.advertising & ADVERTISED_100baseT_Full) {
1177         *advertised |= OFPPF_100MB_FD;
1178     }
1179     if (ecmd.advertising & ADVERTISED_1000baseT_Half) {
1180         *advertised |= OFPPF_1GB_HD;
1181     }
1182     if (ecmd.advertising & ADVERTISED_1000baseT_Full) {
1183         *advertised |= OFPPF_1GB_FD;
1184     }
1185     if (ecmd.advertising & ADVERTISED_10000baseT_Full) {
1186         *advertised |= OFPPF_10GB_FD;
1187     }
1188     if (ecmd.advertising & ADVERTISED_TP) {
1189         *advertised |= OFPPF_COPPER;
1190     }
1191     if (ecmd.advertising & ADVERTISED_FIBRE) {
1192         *advertised |= OFPPF_FIBER;
1193     }
1194     if (ecmd.advertising & ADVERTISED_Autoneg) {
1195         *advertised |= OFPPF_AUTONEG;
1196     }
1197     if (ecmd.advertising & ADVERTISED_Pause) {
1198         *advertised |= OFPPF_PAUSE;
1199     }
1200     if (ecmd.advertising & ADVERTISED_Asym_Pause) {
1201         *advertised |= OFPPF_PAUSE_ASYM;
1202     }
1203
1204     /* Current settings. */
1205     if (ecmd.speed == SPEED_10) {
1206         *current = ecmd.duplex ? OFPPF_10MB_FD : OFPPF_10MB_HD;
1207     } else if (ecmd.speed == SPEED_100) {
1208         *current = ecmd.duplex ? OFPPF_100MB_FD : OFPPF_100MB_HD;
1209     } else if (ecmd.speed == SPEED_1000) {
1210         *current = ecmd.duplex ? OFPPF_1GB_FD : OFPPF_1GB_HD;
1211     } else if (ecmd.speed == SPEED_10000) {
1212         *current = OFPPF_10GB_FD;
1213     } else {
1214         *current = 0;
1215     }
1216
1217     if (ecmd.port == PORT_TP) {
1218         *current |= OFPPF_COPPER;
1219     } else if (ecmd.port == PORT_FIBRE) {
1220         *current |= OFPPF_FIBER;
1221     }
1222
1223     if (ecmd.autoneg) {
1224         *current |= OFPPF_AUTONEG;
1225     }
1226
1227     /* Peer advertisements. */
1228     *peer = 0;                  /* XXX */
1229
1230     return 0;
1231 }
1232
1233 /* Set the features advertised by 'netdev' to 'advertise'. */
1234 static int
1235 netdev_linux_set_advertisements(struct netdev *netdev, uint32_t advertise)
1236 {
1237     struct ethtool_cmd ecmd;
1238     int error;
1239
1240     memset(&ecmd, 0, sizeof ecmd);
1241     error = netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1242                                     ETHTOOL_GSET, "ETHTOOL_GSET");
1243     if (error) {
1244         return error;
1245     }
1246
1247     ecmd.advertising = 0;
1248     if (advertise & OFPPF_10MB_HD) {
1249         ecmd.advertising |= ADVERTISED_10baseT_Half;
1250     }
1251     if (advertise & OFPPF_10MB_FD) {
1252         ecmd.advertising |= ADVERTISED_10baseT_Full;
1253     }
1254     if (advertise & OFPPF_100MB_HD) {
1255         ecmd.advertising |= ADVERTISED_100baseT_Half;
1256     }
1257     if (advertise & OFPPF_100MB_FD) {
1258         ecmd.advertising |= ADVERTISED_100baseT_Full;
1259     }
1260     if (advertise & OFPPF_1GB_HD) {
1261         ecmd.advertising |= ADVERTISED_1000baseT_Half;
1262     }
1263     if (advertise & OFPPF_1GB_FD) {
1264         ecmd.advertising |= ADVERTISED_1000baseT_Full;
1265     }
1266     if (advertise & OFPPF_10GB_FD) {
1267         ecmd.advertising |= ADVERTISED_10000baseT_Full;
1268     }
1269     if (advertise & OFPPF_COPPER) {
1270         ecmd.advertising |= ADVERTISED_TP;
1271     }
1272     if (advertise & OFPPF_FIBER) {
1273         ecmd.advertising |= ADVERTISED_FIBRE;
1274     }
1275     if (advertise & OFPPF_AUTONEG) {
1276         ecmd.advertising |= ADVERTISED_Autoneg;
1277     }
1278     if (advertise & OFPPF_PAUSE) {
1279         ecmd.advertising |= ADVERTISED_Pause;
1280     }
1281     if (advertise & OFPPF_PAUSE_ASYM) {
1282         ecmd.advertising |= ADVERTISED_Asym_Pause;
1283     }
1284     return netdev_linux_do_ethtool(netdev_get_name(netdev), &ecmd,
1285                                    ETHTOOL_SSET, "ETHTOOL_SSET");
1286 }
1287
1288 /* If 'netdev_name' is the name of a VLAN network device (e.g. one created with
1289  * vconfig(8)), sets '*vlan_vid' to the VLAN VID associated with that device
1290  * and returns 0.  Otherwise returns a errno value (specifically ENOENT if
1291  * 'netdev_name' is the name of a network device that is not a VLAN device) and
1292  * sets '*vlan_vid' to -1. */
1293 static int
1294 netdev_linux_get_vlan_vid(const struct netdev *netdev, int *vlan_vid)
1295 {
1296     const char *netdev_name = netdev_get_name(netdev);
1297     struct ds line = DS_EMPTY_INITIALIZER;
1298     FILE *stream = NULL;
1299     int error;
1300     char *fn;
1301
1302     COVERAGE_INC(netdev_get_vlan_vid);
1303     fn = xasprintf("/proc/net/vlan/%s", netdev_name);
1304     stream = fopen(fn, "r");
1305     if (!stream) {
1306         error = errno;
1307         goto done;
1308     }
1309
1310     if (ds_get_line(&line, stream)) {
1311         if (ferror(stream)) {
1312             error = errno;
1313             VLOG_ERR_RL(&rl, "error reading \"%s\": %s", fn, strerror(errno));
1314         } else {
1315             error = EPROTO;
1316             VLOG_ERR_RL(&rl, "unexpected end of file reading \"%s\"", fn);
1317         }
1318         goto done;
1319     }
1320
1321     if (!sscanf(ds_cstr(&line), "%*s VID: %d", vlan_vid)) {
1322         error = EPROTO;
1323         VLOG_ERR_RL(&rl, "parse error reading \"%s\" line 1: \"%s\"",
1324                     fn, ds_cstr(&line));
1325         goto done;
1326     }
1327
1328     error = 0;
1329
1330 done:
1331     free(fn);
1332     if (stream) {
1333         fclose(stream);
1334     }
1335     ds_destroy(&line);
1336     if (error) {
1337         *vlan_vid = -1;
1338     }
1339     return error;
1340 }
1341
1342 #define POLICE_ADD_CMD "/sbin/tc qdisc add dev %s handle ffff: ingress"
1343 #define POLICE_CONFIG_CMD "/sbin/tc filter add dev %s parent ffff: protocol ip prio 50 u32 match ip src 0.0.0.0/0 police rate %dkbit burst %dk mtu 65535 drop flowid :1"
1344
1345 /* Remove ingress policing from 'netdev'.  Returns 0 if successful, otherwise a
1346  * positive errno value.
1347  *
1348  * This function is equivalent to running
1349  *     /sbin/tc qdisc del dev %s handle ffff: ingress
1350  * but it is much, much faster.
1351  */
1352 static int
1353 netdev_linux_remove_policing(struct netdev *netdev)
1354 {
1355     struct netdev_dev_linux *netdev_dev =
1356         netdev_dev_linux_cast(netdev_get_dev(netdev));
1357     const char *netdev_name = netdev_get_name(netdev);
1358
1359     struct ofpbuf request;
1360     struct tcmsg *tcmsg;
1361     int error;
1362
1363     tcmsg = tc_make_request(netdev, RTM_DELQDISC, 0, &request);
1364     tcmsg->tcm_handle = tc_make_handle(0xffff, 0);
1365     tcmsg->tcm_parent = TC_H_INGRESS;
1366     nl_msg_put_string(&request, TCA_KIND, "ingress");
1367     nl_msg_put_unspec(&request, TCA_OPTIONS, NULL, 0);
1368
1369     error = tc_transact(&request, NULL);
1370     if (error && error != ENOENT && error != EINVAL) {
1371         VLOG_WARN_RL(&rl, "%s: removing policing failed: %s",
1372                      netdev_name, strerror(error));
1373         return error;
1374     }
1375
1376     netdev_dev->kbits_rate = 0;
1377     netdev_dev->kbits_burst = 0;
1378     netdev_dev->cache_valid |= VALID_POLICING;
1379     return 0;
1380 }
1381
1382 /* Attempts to set input rate limiting (policing) policy. */
1383 static int
1384 netdev_linux_set_policing(struct netdev *netdev,
1385                           uint32_t kbits_rate, uint32_t kbits_burst)
1386 {
1387     struct netdev_dev_linux *netdev_dev =
1388         netdev_dev_linux_cast(netdev_get_dev(netdev));
1389     const char *netdev_name = netdev_get_name(netdev);
1390     char command[1024];
1391
1392     COVERAGE_INC(netdev_set_policing);
1393
1394     kbits_burst = (!kbits_rate ? 0       /* Force to 0 if no rate specified. */
1395                    : !kbits_burst ? 1000 /* Default to 1000 kbits if 0. */
1396                    : kbits_burst);       /* Stick with user-specified value. */
1397
1398     if (netdev_dev->cache_valid & VALID_POLICING
1399         && netdev_dev->kbits_rate == kbits_rate
1400         && netdev_dev->kbits_burst == kbits_burst) {
1401         /* Assume that settings haven't changed since we last set them. */
1402         return 0;
1403     }
1404
1405     netdev_linux_remove_policing(netdev);
1406     if (kbits_rate) {
1407         snprintf(command, sizeof(command), POLICE_ADD_CMD, netdev_name);
1408         if (system(command) != 0) {
1409             VLOG_WARN_RL(&rl, "%s: problem adding policing", netdev_name);
1410             return -1;
1411         }
1412
1413         snprintf(command, sizeof(command), POLICE_CONFIG_CMD, netdev_name,
1414                 kbits_rate, kbits_burst);
1415         if (system(command) != 0) {
1416             VLOG_WARN_RL(&rl, "%s: problem configuring policing",
1417                     netdev_name);
1418             return -1;
1419         }
1420
1421         netdev_dev->kbits_rate = kbits_rate;
1422         netdev_dev->kbits_burst = kbits_burst;
1423         netdev_dev->cache_valid |= VALID_POLICING;
1424     }
1425
1426     return 0;
1427 }
1428
1429 static int
1430 netdev_linux_get_qos_types(const struct netdev *netdev OVS_UNUSED,
1431                            struct svec *types)
1432 {
1433     const struct tc_ops **opsp;
1434
1435     for (opsp = tcs; *opsp != NULL; opsp++) {
1436         const struct tc_ops *ops = *opsp;
1437         if (ops->tc_install && ops->ovs_name[0] != '\0') {
1438             svec_add(types, ops->ovs_name);
1439         }
1440     }
1441     return 0;
1442 }
1443
1444 static const struct tc_ops *
1445 tc_lookup_ovs_name(const char *name)
1446 {
1447     const struct tc_ops **opsp;
1448
1449     for (opsp = tcs; *opsp != NULL; opsp++) {
1450         const struct tc_ops *ops = *opsp;
1451         if (!strcmp(name, ops->ovs_name)) {
1452             return ops;
1453         }
1454     }
1455     return NULL;
1456 }
1457
1458 static const struct tc_ops *
1459 tc_lookup_linux_name(const char *name)
1460 {
1461     const struct tc_ops **opsp;
1462
1463     for (opsp = tcs; *opsp != NULL; opsp++) {
1464         const struct tc_ops *ops = *opsp;
1465         if (ops->linux_name && !strcmp(name, ops->linux_name)) {
1466             return ops;
1467         }
1468     }
1469     return NULL;
1470 }
1471
1472 static int
1473 netdev_linux_get_qos_capabilities(const struct netdev *netdev OVS_UNUSED,
1474                                   const char *type,
1475                                   struct netdev_qos_capabilities *caps)
1476 {
1477     const struct tc_ops *ops = tc_lookup_ovs_name(type);
1478     if (!ops) {
1479         return EOPNOTSUPP;
1480     }
1481     caps->n_queues = ops->n_queues;
1482     return 0;
1483 }
1484
1485 static int
1486 netdev_linux_get_qos(const struct netdev *netdev,
1487                      const char **typep, struct shash *details)
1488 {
1489     struct netdev_dev_linux *netdev_dev =
1490                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1491     int error;
1492
1493     error = tc_query_qdisc(netdev);
1494     if (error) {
1495         return error;
1496     }
1497
1498     *typep = netdev_dev->tc->ops->ovs_name;
1499     return (netdev_dev->tc->ops->qdisc_get
1500             ? netdev_dev->tc->ops->qdisc_get(netdev, details)
1501             : 0);
1502 }
1503
1504 static int
1505 netdev_linux_set_qos(struct netdev *netdev,
1506                      const char *type, const struct shash *details)
1507 {
1508     struct netdev_dev_linux *netdev_dev =
1509                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1510     const struct tc_ops *new_ops;
1511     int error;
1512
1513     new_ops = tc_lookup_ovs_name(type);
1514     if (!new_ops || !new_ops->tc_install) {
1515         return EOPNOTSUPP;
1516     }
1517
1518     error = tc_query_qdisc(netdev);
1519     if (error) {
1520         return error;
1521     }
1522
1523     if (new_ops == netdev_dev->tc->ops) {
1524         return new_ops->qdisc_set ? new_ops->qdisc_set(netdev, details) : 0;
1525     } else {
1526         /* Delete existing qdisc. */
1527         error = tc_del_qdisc(netdev);
1528         if (error) {
1529             return error;
1530         }
1531         assert(netdev_dev->tc == NULL);
1532
1533         /* Install new qdisc. */
1534         error = new_ops->tc_install(netdev, details);
1535         assert((error == 0) == (netdev_dev->tc != NULL));
1536
1537         return error;
1538     }
1539 }
1540
1541 static int
1542 netdev_linux_get_queue(const struct netdev *netdev,
1543                        unsigned int queue_id, struct shash *details)
1544 {
1545     struct netdev_dev_linux *netdev_dev =
1546                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1547     int error;
1548
1549     error = tc_query_qdisc(netdev);
1550     if (error) {
1551         return error;
1552     } else if (queue_id > UINT16_MAX
1553                || !port_array_get(&netdev_dev->tc->queues, queue_id)) {
1554         return ENOENT;
1555     }
1556
1557     return netdev_dev->tc->ops->class_get(netdev, queue_id, details);
1558 }
1559
1560 static int
1561 netdev_linux_set_queue(struct netdev *netdev,
1562                        unsigned int queue_id, const struct shash *details)
1563 {
1564     struct netdev_dev_linux *netdev_dev =
1565                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1566     int error;
1567
1568     error = tc_query_qdisc(netdev);
1569     if (error) {
1570         return error;
1571     } else if (queue_id >= netdev_dev->tc->ops->n_queues
1572                || !netdev_dev->tc->ops->class_set) {
1573         return EINVAL;
1574     }
1575
1576     return netdev_dev->tc->ops->class_set(netdev, queue_id, details);
1577 }
1578
1579 static int
1580 netdev_linux_delete_queue(struct netdev *netdev, unsigned int queue_id)
1581 {
1582     struct netdev_dev_linux *netdev_dev =
1583                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1584     int error;
1585
1586     error = tc_query_qdisc(netdev);
1587     if (error) {
1588         return error;
1589     } else if (!netdev_dev->tc->ops->class_delete) {
1590         return EINVAL;
1591     } else if (queue_id > UINT16_MAX
1592                || !port_array_get(&netdev_dev->tc->queues, queue_id)) {
1593         return ENOENT;
1594     }
1595
1596     return netdev_dev->tc->ops->class_delete(netdev, queue_id);
1597 }
1598
1599 static int
1600 netdev_linux_get_queue_stats(const struct netdev *netdev,
1601                              unsigned int queue_id,
1602                              struct netdev_queue_stats *stats)
1603 {
1604     struct netdev_dev_linux *netdev_dev =
1605                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1606     int error;
1607
1608     error = tc_query_qdisc(netdev);
1609     if (error) {
1610         return error;
1611     } else if (queue_id > UINT16_MAX
1612                || !port_array_get(&netdev_dev->tc->queues, queue_id)) {
1613         return ENOENT;
1614     } else if (!netdev_dev->tc->ops->class_get_stats) {
1615         return EOPNOTSUPP;
1616     }
1617
1618     return netdev_dev->tc->ops->class_get_stats(netdev, queue_id, stats);
1619 }
1620
1621 static void
1622 start_queue_dump(const struct netdev *netdev, struct nl_dump *dump)
1623 {
1624     struct ofpbuf request;
1625     struct tcmsg *tcmsg;
1626
1627     tcmsg = tc_make_request(netdev, RTM_GETTCLASS, 0, &request);
1628     tcmsg->tcm_parent = 0;
1629     nl_dump_start(dump, rtnl_sock, &request);
1630     ofpbuf_uninit(&request);
1631 }
1632
1633 static int
1634 netdev_linux_dump_queues(const struct netdev *netdev,
1635                          netdev_dump_queues_cb *cb, void *aux)
1636 {
1637     struct netdev_dev_linux *netdev_dev =
1638                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1639     unsigned int queue_id;
1640     struct shash details;
1641     int last_error;
1642     void *queue;
1643     int error;
1644
1645     error = tc_query_qdisc(netdev);
1646     if (error) {
1647         return error;
1648     } else if (!netdev_dev->tc->ops->class_get) {
1649         return EOPNOTSUPP;
1650     }
1651
1652     last_error = 0;
1653     shash_init(&details);
1654     PORT_ARRAY_FOR_EACH (queue, &netdev_dev->tc->queues, queue_id) {
1655         shash_clear(&details);
1656
1657         error = netdev_dev->tc->ops->class_get(netdev, queue_id, &details);
1658         if (!error) {
1659             (*cb)(queue_id, &details, aux);
1660         } else {
1661             last_error = error;
1662         }
1663     }
1664     shash_destroy(&details);
1665
1666     return last_error;
1667 }
1668
1669 static int
1670 netdev_linux_dump_queue_stats(const struct netdev *netdev,
1671                               netdev_dump_queue_stats_cb *cb, void *aux)
1672 {
1673     struct netdev_dev_linux *netdev_dev =
1674                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
1675     struct nl_dump dump;
1676     struct ofpbuf msg;
1677     int last_error;
1678     int error;
1679
1680     error = tc_query_qdisc(netdev);
1681     if (error) {
1682         return error;
1683     } else if (!netdev_dev->tc->ops->class_dump_stats) {
1684         return EOPNOTSUPP;
1685     }
1686
1687     last_error = 0;
1688     start_queue_dump(netdev, &dump);
1689     while (nl_dump_next(&dump, &msg)) {
1690         error = netdev_dev->tc->ops->class_dump_stats(netdev, &msg, cb, aux);
1691         if (error) {
1692             last_error = error;
1693         }
1694     }
1695
1696     error = nl_dump_done(&dump);
1697     return error ? error : last_error;
1698 }
1699
1700 static int
1701 netdev_linux_get_in4(const struct netdev *netdev_,
1702                      struct in_addr *address, struct in_addr *netmask)
1703 {
1704     struct netdev_dev_linux *netdev_dev =
1705                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1706
1707     if (!(netdev_dev->cache_valid & VALID_IN4)) {
1708         int error;
1709
1710         error = netdev_linux_get_ipv4(netdev_, &netdev_dev->address,
1711                                       SIOCGIFADDR, "SIOCGIFADDR");
1712         if (error) {
1713             return error;
1714         }
1715
1716         error = netdev_linux_get_ipv4(netdev_, &netdev_dev->netmask,
1717                                       SIOCGIFNETMASK, "SIOCGIFNETMASK");
1718         if (error) {
1719             return error;
1720         }
1721
1722         netdev_dev->cache_valid |= VALID_IN4;
1723     }
1724     *address = netdev_dev->address;
1725     *netmask = netdev_dev->netmask;
1726     return address->s_addr == INADDR_ANY ? EADDRNOTAVAIL : 0;
1727 }
1728
1729 static int
1730 netdev_linux_set_in4(struct netdev *netdev_, struct in_addr address,
1731                      struct in_addr netmask)
1732 {
1733     struct netdev_dev_linux *netdev_dev =
1734                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1735     int error;
1736
1737     error = do_set_addr(netdev_, SIOCSIFADDR, "SIOCSIFADDR", address);
1738     if (!error) {
1739         netdev_dev->cache_valid |= VALID_IN4;
1740         netdev_dev->address = address;
1741         netdev_dev->netmask = netmask;
1742         if (address.s_addr != INADDR_ANY) {
1743             error = do_set_addr(netdev_, SIOCSIFNETMASK,
1744                                 "SIOCSIFNETMASK", netmask);
1745         }
1746     }
1747     return error;
1748 }
1749
1750 static bool
1751 parse_if_inet6_line(const char *line,
1752                     struct in6_addr *in6, char ifname[16 + 1])
1753 {
1754     uint8_t *s6 = in6->s6_addr;
1755 #define X8 "%2"SCNx8
1756     return sscanf(line,
1757                   " "X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8 X8
1758                   "%*x %*x %*x %*x %16s\n",
1759                   &s6[0], &s6[1], &s6[2], &s6[3],
1760                   &s6[4], &s6[5], &s6[6], &s6[7],
1761                   &s6[8], &s6[9], &s6[10], &s6[11],
1762                   &s6[12], &s6[13], &s6[14], &s6[15],
1763                   ifname) == 17;
1764 }
1765
1766 /* If 'netdev' has an assigned IPv6 address, sets '*in6' to that address (if
1767  * 'in6' is non-null) and returns true.  Otherwise, returns false. */
1768 static int
1769 netdev_linux_get_in6(const struct netdev *netdev_, struct in6_addr *in6)
1770 {
1771     struct netdev_dev_linux *netdev_dev =
1772                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
1773     if (!(netdev_dev->cache_valid & VALID_IN6)) {
1774         FILE *file;
1775         char line[128];
1776
1777         netdev_dev->in6 = in6addr_any;
1778
1779         file = fopen("/proc/net/if_inet6", "r");
1780         if (file != NULL) {
1781             const char *name = netdev_get_name(netdev_);
1782             while (fgets(line, sizeof line, file)) {
1783                 struct in6_addr in6;
1784                 char ifname[16 + 1];
1785                 if (parse_if_inet6_line(line, &in6, ifname)
1786                     && !strcmp(name, ifname))
1787                 {
1788                     netdev_dev->in6 = in6;
1789                     break;
1790                 }
1791             }
1792             fclose(file);
1793         }
1794         netdev_dev->cache_valid |= VALID_IN6;
1795     }
1796     *in6 = netdev_dev->in6;
1797     return 0;
1798 }
1799
1800 static void
1801 make_in4_sockaddr(struct sockaddr *sa, struct in_addr addr)
1802 {
1803     struct sockaddr_in sin;
1804     memset(&sin, 0, sizeof sin);
1805     sin.sin_family = AF_INET;
1806     sin.sin_addr = addr;
1807     sin.sin_port = 0;
1808
1809     memset(sa, 0, sizeof *sa);
1810     memcpy(sa, &sin, sizeof sin);
1811 }
1812
1813 static int
1814 do_set_addr(struct netdev *netdev,
1815             int ioctl_nr, const char *ioctl_name, struct in_addr addr)
1816 {
1817     struct ifreq ifr;
1818     strncpy(ifr.ifr_name, netdev_get_name(netdev), sizeof ifr.ifr_name);
1819     make_in4_sockaddr(&ifr.ifr_addr, addr);
1820
1821     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, ioctl_nr,
1822                                  ioctl_name);
1823 }
1824
1825 /* Adds 'router' as a default IP gateway. */
1826 static int
1827 netdev_linux_add_router(struct netdev *netdev OVS_UNUSED, struct in_addr router)
1828 {
1829     struct in_addr any = { INADDR_ANY };
1830     struct rtentry rt;
1831     int error;
1832
1833     memset(&rt, 0, sizeof rt);
1834     make_in4_sockaddr(&rt.rt_dst, any);
1835     make_in4_sockaddr(&rt.rt_gateway, router);
1836     make_in4_sockaddr(&rt.rt_genmask, any);
1837     rt.rt_flags = RTF_UP | RTF_GATEWAY;
1838     COVERAGE_INC(netdev_add_router);
1839     error = ioctl(af_inet_sock, SIOCADDRT, &rt) < 0 ? errno : 0;
1840     if (error) {
1841         VLOG_WARN("ioctl(SIOCADDRT): %s", strerror(error));
1842     }
1843     return error;
1844 }
1845
1846 static int
1847 netdev_linux_get_next_hop(const struct in_addr *host, struct in_addr *next_hop,
1848                           char **netdev_name)
1849 {
1850     static const char fn[] = "/proc/net/route";
1851     FILE *stream;
1852     char line[256];
1853     int ln;
1854
1855     *netdev_name = NULL;
1856     stream = fopen(fn, "r");
1857     if (stream == NULL) {
1858         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
1859         return errno;
1860     }
1861
1862     ln = 0;
1863     while (fgets(line, sizeof line, stream)) {
1864         if (++ln >= 2) {
1865             char iface[17];
1866             uint32_t dest, gateway, mask;
1867             int refcnt, metric, mtu;
1868             unsigned int flags, use, window, irtt;
1869
1870             if (sscanf(line,
1871                        "%16s %"SCNx32" %"SCNx32" %04X %d %u %d %"SCNx32
1872                        " %d %u %u\n",
1873                        iface, &dest, &gateway, &flags, &refcnt,
1874                        &use, &metric, &mask, &mtu, &window, &irtt) != 11) {
1875
1876                 VLOG_WARN_RL(&rl, "%s: could not parse line %d: %s", 
1877                         fn, ln, line);
1878                 continue;
1879             }
1880             if (!(flags & RTF_UP)) {
1881                 /* Skip routes that aren't up. */
1882                 continue;
1883             }
1884
1885             /* The output of 'dest', 'mask', and 'gateway' were given in
1886              * network byte order, so we don't need need any endian 
1887              * conversions here. */
1888             if ((dest & mask) == (host->s_addr & mask)) {
1889                 if (!gateway) {
1890                     /* The host is directly reachable. */
1891                     next_hop->s_addr = 0;
1892                 } else {
1893                     /* To reach the host, we must go through a gateway. */
1894                     next_hop->s_addr = gateway;
1895                 }
1896                 *netdev_name = xstrdup(iface);
1897                 fclose(stream);
1898                 return 0;
1899             }
1900         }
1901     }
1902
1903     fclose(stream);
1904     return ENXIO;
1905 }
1906
1907 /* Looks up the ARP table entry for 'ip' on 'netdev'.  If one exists and can be
1908  * successfully retrieved, it stores the corresponding MAC address in 'mac' and
1909  * returns 0.  Otherwise, it returns a positive errno value; in particular,
1910  * ENXIO indicates that there is not ARP table entry for 'ip' on 'netdev'. */
1911 static int
1912 netdev_linux_arp_lookup(const struct netdev *netdev,
1913                         uint32_t ip, uint8_t mac[ETH_ADDR_LEN])
1914 {
1915     struct arpreq r;
1916     struct sockaddr_in sin;
1917     int retval;
1918
1919     memset(&r, 0, sizeof r);
1920     sin.sin_family = AF_INET;
1921     sin.sin_addr.s_addr = ip;
1922     sin.sin_port = 0;
1923     memcpy(&r.arp_pa, &sin, sizeof sin);
1924     r.arp_ha.sa_family = ARPHRD_ETHER;
1925     r.arp_flags = 0;
1926     strncpy(r.arp_dev, netdev_get_name(netdev), sizeof r.arp_dev);
1927     COVERAGE_INC(netdev_arp_lookup);
1928     retval = ioctl(af_inet_sock, SIOCGARP, &r) < 0 ? errno : 0;
1929     if (!retval) {
1930         memcpy(mac, r.arp_ha.sa_data, ETH_ADDR_LEN);
1931     } else if (retval != ENXIO) {
1932         VLOG_WARN_RL(&rl, "%s: could not look up ARP entry for "IP_FMT": %s",
1933                      netdev_get_name(netdev), IP_ARGS(&ip), strerror(retval));
1934     }
1935     return retval;
1936 }
1937
1938 static int
1939 nd_to_iff_flags(enum netdev_flags nd)
1940 {
1941     int iff = 0;
1942     if (nd & NETDEV_UP) {
1943         iff |= IFF_UP;
1944     }
1945     if (nd & NETDEV_PROMISC) {
1946         iff |= IFF_PROMISC;
1947     }
1948     return iff;
1949 }
1950
1951 static int
1952 iff_to_nd_flags(int iff)
1953 {
1954     enum netdev_flags nd = 0;
1955     if (iff & IFF_UP) {
1956         nd |= NETDEV_UP;
1957     }
1958     if (iff & IFF_PROMISC) {
1959         nd |= NETDEV_PROMISC;
1960     }
1961     return nd;
1962 }
1963
1964 static int
1965 netdev_linux_update_flags(struct netdev *netdev, enum netdev_flags off,
1966                           enum netdev_flags on, enum netdev_flags *old_flagsp)
1967 {
1968     int old_flags, new_flags;
1969     int error;
1970
1971     error = get_flags(netdev, &old_flags);
1972     if (!error) {
1973         *old_flagsp = iff_to_nd_flags(old_flags);
1974         new_flags = (old_flags & ~nd_to_iff_flags(off)) | nd_to_iff_flags(on);
1975         if (new_flags != old_flags) {
1976             error = set_flags(netdev, new_flags);
1977         }
1978     }
1979     return error;
1980 }
1981
1982 static void
1983 poll_notify(struct list *list)
1984 {
1985     struct netdev_linux_notifier *notifier;
1986     LIST_FOR_EACH (notifier, struct netdev_linux_notifier, node, list) {
1987         struct netdev_notifier *n = &notifier->notifier;
1988         n->cb(n);
1989     }
1990 }
1991
1992 static void
1993 netdev_linux_poll_cb(const struct rtnetlink_change *change,
1994                      void *aux OVS_UNUSED)
1995 {
1996     if (change) {
1997         struct list *list = shash_find_data(&netdev_linux_notifiers,
1998                                             change->ifname);
1999         if (list) {
2000             poll_notify(list);
2001         }
2002     } else {
2003         struct shash_node *node;
2004         SHASH_FOR_EACH (node, &netdev_linux_notifiers) {
2005             poll_notify(node->data);
2006         }
2007     }
2008 }
2009
2010 static int
2011 netdev_linux_poll_add(struct netdev *netdev,
2012                       void (*cb)(struct netdev_notifier *), void *aux,
2013                       struct netdev_notifier **notifierp)
2014 {
2015     const char *netdev_name = netdev_get_name(netdev);
2016     struct netdev_linux_notifier *notifier;
2017     struct list *list;
2018
2019     if (shash_is_empty(&netdev_linux_notifiers)) {
2020         int error = rtnetlink_notifier_register(&netdev_linux_poll_notifier,
2021                                                    netdev_linux_poll_cb, NULL);
2022         if (error) {
2023             return error;
2024         }
2025     }
2026
2027     list = shash_find_data(&netdev_linux_notifiers, netdev_name);
2028     if (!list) {
2029         list = xmalloc(sizeof *list);
2030         list_init(list);
2031         shash_add(&netdev_linux_notifiers, netdev_name, list);
2032     }
2033
2034     notifier = xmalloc(sizeof *notifier);
2035     netdev_notifier_init(&notifier->notifier, netdev, cb, aux);
2036     list_push_back(list, &notifier->node);
2037     *notifierp = &notifier->notifier;
2038     return 0;
2039 }
2040
2041 static void
2042 netdev_linux_poll_remove(struct netdev_notifier *notifier_)
2043 {
2044     struct netdev_linux_notifier *notifier =
2045         CONTAINER_OF(notifier_, struct netdev_linux_notifier, notifier);
2046     struct list *list;
2047
2048     /* Remove 'notifier' from its list. */
2049     list = list_remove(&notifier->node);
2050     if (list_is_empty(list)) {
2051         /* The list is now empty.  Remove it from the hash and free it. */
2052         const char *netdev_name = netdev_get_name(notifier->notifier.netdev);
2053         shash_delete(&netdev_linux_notifiers,
2054                      shash_find(&netdev_linux_notifiers, netdev_name));
2055         free(list);
2056     }
2057     free(notifier);
2058
2059     /* If that was the last notifier, unregister. */
2060     if (shash_is_empty(&netdev_linux_notifiers)) {
2061         rtnetlink_notifier_unregister(&netdev_linux_poll_notifier);
2062     }
2063 }
2064
2065 const struct netdev_class netdev_linux_class = {
2066     "system",
2067
2068     netdev_linux_init,
2069     netdev_linux_run,
2070     netdev_linux_wait,
2071
2072     netdev_linux_create_system,
2073     netdev_linux_destroy,
2074     NULL,                       /* reconfigure */
2075
2076     netdev_linux_open,
2077     netdev_linux_close,
2078
2079     netdev_linux_enumerate,
2080
2081     netdev_linux_recv,
2082     netdev_linux_recv_wait,
2083     netdev_linux_drain,
2084
2085     netdev_linux_send,
2086     netdev_linux_send_wait,
2087
2088     netdev_linux_set_etheraddr,
2089     netdev_linux_get_etheraddr,
2090     netdev_linux_get_mtu,
2091     netdev_linux_get_ifindex,
2092     netdev_linux_get_carrier,
2093     netdev_linux_get_stats,
2094     netdev_vport_set_stats,
2095
2096     netdev_linux_get_features,
2097     netdev_linux_set_advertisements,
2098     netdev_linux_get_vlan_vid,
2099
2100     netdev_linux_set_policing,
2101     netdev_linux_get_qos_types,
2102     netdev_linux_get_qos_capabilities,
2103     netdev_linux_get_qos,
2104     netdev_linux_set_qos,
2105     netdev_linux_get_queue,
2106     netdev_linux_set_queue,
2107     netdev_linux_delete_queue,
2108     netdev_linux_get_queue_stats,
2109     netdev_linux_dump_queues,
2110     netdev_linux_dump_queue_stats,
2111
2112     netdev_linux_get_in4,
2113     netdev_linux_set_in4,
2114     netdev_linux_get_in6,
2115     netdev_linux_add_router,
2116     netdev_linux_get_next_hop,
2117     netdev_linux_arp_lookup,
2118
2119     netdev_linux_update_flags,
2120
2121     netdev_linux_poll_add,
2122     netdev_linux_poll_remove,
2123 };
2124
2125 const struct netdev_class netdev_tap_class = {
2126     "tap",
2127
2128     netdev_linux_init,
2129     netdev_linux_run,
2130     netdev_linux_wait,
2131
2132     netdev_linux_create_tap,
2133     netdev_linux_destroy,
2134     NULL,                       /* reconfigure */
2135
2136     netdev_linux_open,
2137     netdev_linux_close,
2138
2139     NULL,                       /* enumerate */
2140
2141     netdev_linux_recv,
2142     netdev_linux_recv_wait,
2143     netdev_linux_drain,
2144
2145     netdev_linux_send,
2146     netdev_linux_send_wait,
2147
2148     netdev_linux_set_etheraddr,
2149     netdev_linux_get_etheraddr,
2150     netdev_linux_get_mtu,
2151     netdev_linux_get_ifindex,
2152     netdev_linux_get_carrier,
2153     netdev_linux_get_stats,
2154     NULL,                       /* set_stats */
2155
2156     netdev_linux_get_features,
2157     netdev_linux_set_advertisements,
2158     netdev_linux_get_vlan_vid,
2159
2160     netdev_linux_set_policing,
2161     netdev_linux_get_qos_types,
2162     netdev_linux_get_qos_capabilities,
2163     netdev_linux_get_qos,
2164     netdev_linux_set_qos,
2165     netdev_linux_get_queue,
2166     netdev_linux_set_queue,
2167     netdev_linux_delete_queue,
2168     netdev_linux_get_queue_stats,
2169     netdev_linux_dump_queues,
2170     netdev_linux_dump_queue_stats,
2171
2172     netdev_linux_get_in4,
2173     netdev_linux_set_in4,
2174     netdev_linux_get_in6,
2175     netdev_linux_add_router,
2176     netdev_linux_get_next_hop,
2177     netdev_linux_arp_lookup,
2178
2179     netdev_linux_update_flags,
2180
2181     netdev_linux_poll_add,
2182     netdev_linux_poll_remove,
2183 };
2184 \f
2185 /* HTB traffic control class. */
2186
2187 #define HTB_N_QUEUES 0xf000
2188
2189 struct htb {
2190     struct tc tc;
2191     unsigned int max_rate;      /* In bytes/s. */
2192 };
2193
2194 struct htb_class {
2195     unsigned int min_rate;      /* In bytes/s. */
2196     unsigned int max_rate;      /* In bytes/s. */
2197     unsigned int burst;         /* In bytes. */
2198     unsigned int priority;      /* Lower values are higher priorities. */
2199 };
2200
2201 static struct htb *
2202 htb_get__(const struct netdev *netdev)
2203 {
2204     struct netdev_dev_linux *netdev_dev =
2205                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
2206     return CONTAINER_OF(netdev_dev->tc, struct htb, tc);
2207 }
2208
2209 static struct htb *
2210 htb_install__(struct netdev *netdev, uint64_t max_rate)
2211 {
2212     struct netdev_dev_linux *netdev_dev =
2213                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
2214     struct htb *htb;
2215
2216     htb = xmalloc(sizeof *htb);
2217     tc_init(&htb->tc, &tc_ops_htb);
2218     htb->max_rate = max_rate;
2219
2220     netdev_dev->tc = &htb->tc;
2221
2222     return htb;
2223 }
2224
2225 /* Create an HTB qdisc.
2226  *
2227  * Equivalent to "tc qdisc add dev <dev> root handle 1: htb default
2228  * 0". */
2229 static int
2230 htb_setup_qdisc__(struct netdev *netdev)
2231 {
2232     size_t opt_offset;
2233     struct tc_htb_glob opt;
2234     struct ofpbuf request;
2235     struct tcmsg *tcmsg;
2236
2237     tc_del_qdisc(netdev);
2238
2239     tcmsg = tc_make_request(netdev, RTM_NEWQDISC,
2240                             NLM_F_EXCL | NLM_F_CREATE, &request);
2241     tcmsg->tcm_handle = tc_make_handle(1, 0);
2242     tcmsg->tcm_parent = TC_H_ROOT;
2243
2244     nl_msg_put_string(&request, TCA_KIND, "htb");
2245
2246     memset(&opt, 0, sizeof opt);
2247     opt.rate2quantum = 10;
2248     opt.version = 3;
2249     opt.defcls = 0;
2250
2251     opt_offset = nl_msg_start_nested(&request, TCA_OPTIONS);
2252     nl_msg_put_unspec(&request, TCA_HTB_INIT, &opt, sizeof opt);
2253     nl_msg_end_nested(&request, opt_offset);
2254
2255     return tc_transact(&request, NULL);
2256 }
2257
2258 /* Equivalent to "tc class replace <dev> classid <handle> parent <parent> htb
2259  * rate <min_rate>bps ceil <max_rate>bps burst <burst>b prio <priority>". */
2260 static int
2261 htb_setup_class__(struct netdev *netdev, unsigned int handle,
2262                   unsigned int parent, struct htb_class *class)
2263 {
2264     size_t opt_offset;
2265     struct tc_htb_opt opt;
2266     struct ofpbuf request;
2267     struct tcmsg *tcmsg;
2268     int error;
2269     int mtu;
2270
2271     netdev_get_mtu(netdev, &mtu);
2272
2273     memset(&opt, 0, sizeof opt);
2274     tc_fill_rate(&opt.rate, class->min_rate, mtu);
2275     tc_fill_rate(&opt.ceil, class->max_rate, mtu);
2276     opt.buffer = tc_calc_buffer(opt.rate.rate, mtu, class->burst);
2277     opt.cbuffer = tc_calc_buffer(opt.ceil.rate, mtu, class->burst);
2278     opt.prio = class->priority;
2279
2280     tcmsg = tc_make_request(netdev, RTM_NEWTCLASS, NLM_F_CREATE, &request);
2281     tcmsg->tcm_handle = handle;
2282     tcmsg->tcm_parent = parent;
2283
2284     nl_msg_put_string(&request, TCA_KIND, "htb");
2285     opt_offset = nl_msg_start_nested(&request, TCA_OPTIONS);
2286     nl_msg_put_unspec(&request, TCA_HTB_PARMS, &opt, sizeof opt);
2287     tc_put_rtab(&request, TCA_HTB_RTAB, &opt.rate);
2288     tc_put_rtab(&request, TCA_HTB_CTAB, &opt.ceil);
2289     nl_msg_end_nested(&request, opt_offset);
2290
2291     error = tc_transact(&request, NULL);
2292     if (error) {
2293         VLOG_WARN_RL(&rl, "failed to replace %s class %u:%u, parent %u:%u, "
2294                      "min_rate=%u max_rate=%u burst=%u prio=%u (%s)",
2295                      netdev_get_name(netdev),
2296                      tc_get_major(handle), tc_get_minor(handle),
2297                      tc_get_major(parent), tc_get_minor(parent),
2298                      class->min_rate, class->max_rate,
2299                      class->burst, class->priority, strerror(error));
2300     }
2301     return error;
2302 }
2303
2304 /* Parses Netlink attributes in 'options' for HTB parameters and stores a
2305  * description of them into 'details'.  The description complies with the
2306  * specification given in the vswitch database documentation for linux-htb
2307  * queue details. */
2308 static int
2309 htb_parse_tca_options__(struct nlattr *nl_options, struct htb_class *class)
2310 {
2311     static const struct nl_policy tca_htb_policy[] = {
2312         [TCA_HTB_PARMS] = { .type = NL_A_UNSPEC, .optional = false,
2313                             .min_len = sizeof(struct tc_htb_opt) },
2314     };
2315
2316     struct nlattr *attrs[ARRAY_SIZE(tca_htb_policy)];
2317     const struct tc_htb_opt *htb;
2318
2319     if (!nl_parse_nested(nl_options, tca_htb_policy,
2320                          attrs, ARRAY_SIZE(tca_htb_policy))) {
2321         VLOG_WARN_RL(&rl, "failed to parse HTB class options");
2322         return EPROTO;
2323     }
2324
2325     htb = nl_attr_get(attrs[TCA_HTB_PARMS]);
2326     class->min_rate = htb->rate.rate;
2327     class->max_rate = htb->ceil.rate;
2328     class->burst = tc_ticks_to_bytes(htb->rate.rate, htb->buffer);
2329     class->priority = htb->prio;
2330     return 0;
2331 }
2332
2333 static int
2334 htb_parse_tcmsg__(struct ofpbuf *tcmsg, unsigned int *queue_id,
2335                   struct htb_class *options,
2336                   struct netdev_queue_stats *stats)
2337 {
2338     struct nlattr *nl_options;
2339     unsigned int handle;
2340     int error;
2341
2342     error = tc_parse_class(tcmsg, &handle, &nl_options, stats);
2343     if (!error && queue_id) {
2344         if (tc_get_major(handle) == 1 && tc_get_minor(handle) < HTB_N_QUEUES) {
2345             *queue_id = tc_get_minor(handle);
2346         } else {
2347             error = EPROTO;
2348         }
2349     }
2350     if (!error && options) {
2351         error = htb_parse_tca_options__(nl_options, options);
2352     }
2353     return error;
2354 }
2355
2356 static void
2357 htb_parse_qdisc_details__(struct netdev *netdev,
2358                           const struct shash *details, struct htb_class *hc)
2359 {
2360     const char *max_rate_s;
2361
2362     max_rate_s = shash_find_data(details, "max-rate");
2363     hc->max_rate = max_rate_s ? strtoull(max_rate_s, NULL, 10) / 8 : 0;
2364     if (!hc->max_rate) {
2365         uint32_t current;
2366
2367         netdev_get_features(netdev, &current, NULL, NULL, NULL);
2368         hc->max_rate = netdev_features_to_bps(current) / 8;
2369     }
2370     hc->min_rate = hc->max_rate;
2371     hc->burst = 0;
2372     hc->priority = 0;
2373 }
2374
2375 static int
2376 htb_parse_class_details__(struct netdev *netdev,
2377                           const struct shash *details, struct htb_class *hc)
2378 {
2379     const struct htb *htb = htb_get__(netdev);
2380     const char *min_rate_s = shash_find_data(details, "min-rate");
2381     const char *max_rate_s = shash_find_data(details, "max-rate");
2382     const char *burst_s = shash_find_data(details, "burst");
2383     const char *priority_s = shash_find_data(details, "priority");
2384     int mtu;
2385
2386     /* min-rate */
2387     if (!min_rate_s) {
2388         /* min-rate is required. */
2389         return EINVAL;
2390     }
2391     hc->min_rate = strtoull(min_rate_s, NULL, 10) / 8;
2392     hc->min_rate = MAX(hc->min_rate, 0);
2393     hc->min_rate = MIN(hc->min_rate, htb->max_rate);
2394
2395     /* max-rate */
2396     hc->max_rate = (max_rate_s
2397                     ? strtoull(max_rate_s, NULL, 10) / 8
2398                     : htb->max_rate);
2399     hc->max_rate = MAX(hc->max_rate, hc->min_rate);
2400     hc->max_rate = MIN(hc->max_rate, htb->max_rate);
2401
2402     /* burst
2403      *
2404      * According to hints in the documentation that I've read, it is important
2405      * that 'burst' be at least as big as the largest frame that might be
2406      * transmitted.  Also, making 'burst' a bit bigger than necessary is OK,
2407      * but having it a bit too small is a problem.  Since netdev_get_mtu()
2408      * doesn't include the Ethernet header, we need to add at least 14 (18?) to
2409      * the MTU.  We actually add 64, instead of 14, as a guard against
2410      * additional headers get tacked on somewhere that we're not aware of. */
2411     netdev_get_mtu(netdev, &mtu);
2412     hc->burst = burst_s ? strtoull(burst_s, NULL, 10) / 8 : 0;
2413     hc->burst = MAX(hc->burst, mtu + 64);
2414
2415     /* priority */
2416     hc->priority = priority_s ? strtoul(priority_s, NULL, 10) : 0;
2417
2418     return 0;
2419 }
2420
2421 static int
2422 htb_query_class__(const struct netdev *netdev, unsigned int handle,
2423                   unsigned int parent, struct htb_class *options,
2424                   struct netdev_queue_stats *stats)
2425 {
2426     struct ofpbuf *reply;
2427     int error;
2428
2429     error = tc_query_class(netdev, handle, parent, &reply);
2430     if (!error) {
2431         error = htb_parse_tcmsg__(reply, NULL, options, stats);
2432         ofpbuf_delete(reply);
2433     }
2434     return error;
2435 }
2436
2437 static int
2438 htb_tc_install(struct netdev *netdev, const struct shash *details)
2439 {
2440     int error;
2441
2442     error = htb_setup_qdisc__(netdev);
2443     if (!error) {
2444         struct htb_class hc;
2445
2446         htb_parse_qdisc_details__(netdev, details, &hc);
2447         error = htb_setup_class__(netdev, tc_make_handle(1, 0xfffe),
2448                                   tc_make_handle(1, 0), &hc);
2449         if (!error) {
2450             htb_install__(netdev, hc.max_rate);
2451         }
2452     }
2453     return error;
2454 }
2455
2456 static void
2457 htb_update_queue__(struct netdev *netdev, unsigned int queue_id,
2458                    const struct htb_class *hc)
2459 {
2460     struct htb *htb = htb_get__(netdev);
2461     struct htb_class *hcp;
2462
2463     hcp = port_array_get(&htb->tc.queues, queue_id);
2464     if (!hcp) {
2465         hcp = xmalloc(sizeof *hcp);
2466         port_array_set(&htb->tc.queues, queue_id, hcp);
2467     }
2468     *hcp = *hc;
2469 }
2470
2471 static int
2472 htb_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
2473 {
2474     struct shash details = SHASH_INITIALIZER(&details);
2475     struct ofpbuf msg;
2476     struct nl_dump dump;
2477     struct htb_class hc;
2478     struct htb *htb;
2479
2480     /* Get qdisc options. */
2481     hc.max_rate = 0;
2482     htb_query_class__(netdev, tc_make_handle(1, 0xfffe), 0, &hc, NULL);
2483     htb = htb_install__(netdev, hc.max_rate);
2484
2485     /* Get queues. */
2486     start_queue_dump(netdev, &dump);
2487     shash_init(&details);
2488     while (nl_dump_next(&dump, &msg)) {
2489         unsigned int queue_id;
2490
2491         if (!htb_parse_tcmsg__(&msg, &queue_id, &hc, NULL)) {
2492             htb_update_queue__(netdev, queue_id, &hc);
2493         }
2494     }
2495     nl_dump_done(&dump);
2496
2497     return 0;
2498 }
2499
2500 static void
2501 htb_tc_destroy(struct tc *tc)
2502 {
2503     struct htb *htb = CONTAINER_OF(tc, struct htb, tc);
2504     unsigned int queue_id;
2505     struct htb_class *hc;
2506
2507     PORT_ARRAY_FOR_EACH (hc, &htb->tc.queues, queue_id) {
2508         free(hc);
2509     }
2510     tc_destroy(tc);
2511     free(htb);
2512 }
2513
2514 static int
2515 htb_qdisc_get(const struct netdev *netdev, struct shash *details)
2516 {
2517     const struct htb *htb = htb_get__(netdev);
2518     shash_add(details, "max-rate", xasprintf("%llu", 8ULL * htb->max_rate));
2519     return 0;
2520 }
2521
2522 static int
2523 htb_qdisc_set(struct netdev *netdev, const struct shash *details)
2524 {
2525     struct htb_class hc;
2526     int error;
2527
2528     htb_parse_qdisc_details__(netdev, details, &hc);
2529     error = htb_setup_class__(netdev, tc_make_handle(1, 0xfffe),
2530                               tc_make_handle(1, 0), &hc);
2531     if (!error) {
2532         htb_get__(netdev)->max_rate = hc.max_rate;
2533     }
2534     return error;
2535 }
2536
2537 static int
2538 htb_class_get(const struct netdev *netdev, unsigned int queue_id,
2539               struct shash *details)
2540 {
2541     const struct htb *htb = htb_get__(netdev);
2542     const struct htb_class *hc;
2543
2544     hc = port_array_get(&htb->tc.queues, queue_id);
2545     assert(hc != NULL);
2546
2547     shash_add(details, "min-rate", xasprintf("%llu", 8ULL * hc->min_rate));
2548     if (hc->min_rate != hc->max_rate) {
2549         shash_add(details, "max-rate", xasprintf("%llu", 8ULL * hc->max_rate));
2550     }
2551     shash_add(details, "burst", xasprintf("%llu", 8ULL * hc->burst));
2552     if (hc->priority) {
2553         shash_add(details, "priority", xasprintf("%u", hc->priority));
2554     }
2555     return 0;
2556 }
2557
2558 static int
2559 htb_class_set(struct netdev *netdev, unsigned int queue_id,
2560               const struct shash *details)
2561 {
2562     struct htb_class hc;
2563     int error;
2564
2565     error = htb_parse_class_details__(netdev, details, &hc);
2566     if (error) {
2567         return error;
2568     }
2569
2570     error = htb_setup_class__(netdev, tc_make_handle(1, queue_id),
2571                               tc_make_handle(1, 0xfffe), &hc);
2572     if (error) {
2573         return error;
2574     }
2575
2576     htb_update_queue__(netdev, queue_id, &hc);
2577     return 0;
2578 }
2579
2580 static int
2581 htb_class_delete(struct netdev *netdev, unsigned int queue_id)
2582 {
2583     struct htb *htb = htb_get__(netdev);
2584     struct htb_class *hc;
2585     int error;
2586
2587     hc = port_array_get(&htb->tc.queues, queue_id);
2588     assert(hc != NULL);
2589
2590     error = tc_delete_class(netdev, tc_make_handle(1, queue_id));
2591     if (!error) {
2592         free(hc);
2593         port_array_delete(&htb->tc.queues, queue_id);
2594     }
2595     return error;
2596 }
2597
2598 static int
2599 htb_class_get_stats(const struct netdev *netdev, unsigned int queue_id,
2600                     struct netdev_queue_stats *stats)
2601 {
2602     return htb_query_class__(netdev, tc_make_handle(1, queue_id),
2603                              tc_make_handle(1, 0xfffe), NULL, stats);
2604 }
2605
2606 static int
2607 htb_class_dump_stats(const struct netdev *netdev OVS_UNUSED,
2608                      const struct ofpbuf *nlmsg,
2609                      netdev_dump_queue_stats_cb *cb, void *aux)
2610 {
2611     struct netdev_queue_stats stats;
2612     unsigned int handle;
2613     int error;
2614
2615     error = tc_parse_class(nlmsg, &handle, NULL, &stats);
2616     if (error) {
2617         return error;
2618     }
2619
2620     if (tc_get_major(handle) == 1 && tc_get_minor(handle) < HTB_N_QUEUES) {
2621         (*cb)(tc_get_minor(handle), &stats, aux);
2622     }
2623     return 0;
2624 }
2625
2626 static const struct tc_ops tc_ops_htb = {
2627     "htb",                      /* linux_name */
2628     "linux-htb",                /* ovs_name */
2629     HTB_N_QUEUES,               /* n_queues */
2630     htb_tc_install,
2631     htb_tc_load,
2632     htb_tc_destroy,
2633     htb_qdisc_get,
2634     htb_qdisc_set,
2635     htb_class_get,
2636     htb_class_set,
2637     htb_class_delete,
2638     htb_class_get_stats,
2639     htb_class_dump_stats
2640 };
2641 \f
2642 /* "linux-default" traffic control class.
2643  *
2644  * This class represents the default, unnamed Linux qdisc.  It corresponds to
2645  * the "" (empty string) QoS type in the OVS database. */
2646
2647 static void
2648 default_install__(struct netdev *netdev)
2649 {
2650     struct netdev_dev_linux *netdev_dev =
2651                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
2652     static struct tc *tc;
2653
2654     if (!tc) {
2655         tc = xmalloc(sizeof *tc);
2656         tc_init(tc, &tc_ops_default);
2657     }
2658     netdev_dev->tc = tc;
2659 }
2660
2661 static int
2662 default_tc_install(struct netdev *netdev,
2663                    const struct shash *details OVS_UNUSED)
2664 {
2665     default_install__(netdev);
2666     return 0;
2667 }
2668
2669 static int
2670 default_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
2671 {
2672     default_install__(netdev);
2673     return 0;
2674 }
2675
2676 static const struct tc_ops tc_ops_default = {
2677     NULL,                       /* linux_name */
2678     "",                         /* ovs_name */
2679     0,                          /* n_queues */
2680     default_tc_install,
2681     default_tc_load,
2682     NULL,                       /* tc_destroy */
2683     NULL,                       /* qdisc_get */
2684     NULL,                       /* qdisc_set */
2685     NULL,                       /* class_get */
2686     NULL,                       /* class_set */
2687     NULL,                       /* class_delete */
2688     NULL,                       /* class_get_stats */
2689     NULL                        /* class_dump_stats */
2690 };
2691 \f
2692 /* "linux-other" traffic control class.
2693  *
2694  * */
2695
2696 static int
2697 other_tc_load(struct netdev *netdev, struct ofpbuf *nlmsg OVS_UNUSED)
2698 {
2699     struct netdev_dev_linux *netdev_dev =
2700                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
2701     static struct tc *tc;
2702
2703     if (!tc) {
2704         tc = xmalloc(sizeof *tc);
2705         tc_init(tc, &tc_ops_other);
2706     }
2707     netdev_dev->tc = tc;
2708     return 0;
2709 }
2710
2711 static const struct tc_ops tc_ops_other = {
2712     NULL,                       /* linux_name */
2713     "linux-other",              /* ovs_name */
2714     0,                          /* n_queues */
2715     NULL,                       /* tc_install */
2716     other_tc_load,
2717     NULL,                       /* tc_destroy */
2718     NULL,                       /* qdisc_get */
2719     NULL,                       /* qdisc_set */
2720     NULL,                       /* class_get */
2721     NULL,                       /* class_set */
2722     NULL,                       /* class_delete */
2723     NULL,                       /* class_get_stats */
2724     NULL                        /* class_dump_stats */
2725 };
2726 \f
2727 /* Traffic control. */
2728
2729 /* Number of kernel "tc" ticks per second. */
2730 static double ticks_per_s;
2731
2732 /* Number of kernel "jiffies" per second.  This is used for the purpose of
2733  * computing buffer sizes.  Generally kernel qdiscs need to be able to buffer
2734  * one jiffy's worth of data.
2735  *
2736  * There are two possibilities here:
2737  *
2738  *    - 'buffer_hz' is the kernel's real timer tick rate, a small number in the
2739  *      approximate range of 100 to 1024.  That means that we really need to
2740  *      make sure that the qdisc can buffer that much data.
2741  *
2742  *    - 'buffer_hz' is an absurdly large number.  That means that the kernel
2743  *      has finely granular timers and there's no need to fudge additional room
2744  *      for buffers.  (There's no extra effort needed to implement that: the
2745  *      large 'buffer_hz' is used as a divisor, so practically any number will
2746  *      come out as 0 in the division.  Small integer results in the case of
2747  *      really high dividends won't have any real effect anyhow.)
2748  */
2749 static unsigned int buffer_hz;
2750
2751 /* Returns tc handle 'major':'minor'. */
2752 static unsigned int
2753 tc_make_handle(unsigned int major, unsigned int minor)
2754 {
2755     return TC_H_MAKE(major << 16, minor);
2756 }
2757
2758 /* Returns the major number from 'handle'. */
2759 static unsigned int
2760 tc_get_major(unsigned int handle)
2761 {
2762     return TC_H_MAJ(handle) >> 16;
2763 }
2764
2765 /* Returns the minor number from 'handle'. */
2766 static unsigned int
2767 tc_get_minor(unsigned int handle)
2768 {
2769     return TC_H_MIN(handle);
2770 }
2771
2772 static struct tcmsg *
2773 tc_make_request(const struct netdev *netdev, int type, unsigned int flags,
2774                 struct ofpbuf *request)
2775 {
2776     struct tcmsg *tcmsg;
2777     int ifindex;
2778     int error;
2779
2780     error = get_ifindex(netdev, &ifindex);
2781     if (error) {
2782         return NULL;
2783     }
2784
2785     ofpbuf_init(request, 512);
2786     nl_msg_put_nlmsghdr(request, sizeof *tcmsg, type, NLM_F_REQUEST | flags);
2787     tcmsg = ofpbuf_put_zeros(request, sizeof *tcmsg);
2788     tcmsg->tcm_family = AF_UNSPEC;
2789     tcmsg->tcm_ifindex = ifindex;
2790     /* Caller should fill in tcmsg->tcm_handle. */
2791     /* Caller should fill in tcmsg->tcm_parent. */
2792
2793     return tcmsg;
2794 }
2795
2796 static int
2797 tc_transact(struct ofpbuf *request, struct ofpbuf **replyp)
2798 {
2799     int error = nl_sock_transact(rtnl_sock, request, replyp);
2800     ofpbuf_uninit(request);
2801     return error;
2802 }
2803
2804 static void
2805 read_psched(void)
2806 {
2807     /* The values in psched are not individually very meaningful, but they are
2808      * important.  The tables below show some values seen in the wild.
2809      *
2810      * Some notes:
2811      *
2812      *   - "c" has always been a constant 1000000 since at least Linux 2.4.14.
2813      *     (Before that, there are hints that it was 1000000000.)
2814      *
2815      *   - "d" can be unrealistically large, see the comment on 'buffer_hz'
2816      *     above.
2817      *
2818      *                        /proc/net/psched
2819      *     -----------------------------------
2820      * [1] 000c8000 000f4240 000f4240 00000064
2821      * [2] 000003e8 00000400 000f4240 3b9aca00
2822      * [3] 000003e8 00000400 000f4240 3b9aca00
2823      * [4] 000003e8 00000400 000f4240 00000064
2824      * [5] 000003e8 00000040 000f4240 3b9aca00
2825      * [6] 000003e8 00000040 000f4240 000000f9
2826      *
2827      *           a         b          c             d ticks_per_s     buffer_hz
2828      *     ------- --------- ---------- ------------- ----------- -------------
2829      * [1] 819,200 1,000,000  1,000,000           100     819,200           100
2830      * [2]   1,000     1,024  1,000,000 1,000,000,000     976,562 1,000,000,000
2831      * [3]   1,000     1,024  1,000,000 1,000,000,000     976,562 1,000,000,000
2832      * [4]   1,000     1,024  1,000,000           100     976,562           100
2833      * [5]   1,000        64  1,000,000 1,000,000,000  15,625,000 1,000,000,000
2834      * [6]   1,000        64  1,000,000           249  15,625,000           249
2835      *
2836      * [1] 2.6.18-128.1.6.el5.xs5.5.0.505.1024xen from XenServer 5.5.0-24648p
2837      * [2] 2.6.26-1-686-bigmem from Debian lenny
2838      * [3] 2.6.26-2-sparc64 from Debian lenny
2839      * [4] 2.6.27.42-0.1.1.xs5.6.810.44.111163xen from XenServer 5.6.810-31078p
2840      * [5] 2.6.32.21.22 (approx.) from Ubuntu 10.04 on VMware Fusion
2841      * [6] 2.6.34 from kernel.org on KVM
2842      */
2843     static const char fn[] = "/proc/net/psched";
2844     unsigned int a, b, c, d;
2845     FILE *stream;
2846
2847     ticks_per_s = 1.0;
2848     buffer_hz = 100;
2849
2850     stream = fopen(fn, "r");
2851     if (!stream) {
2852         VLOG_WARN("%s: open failed: %s", fn, strerror(errno));
2853         return;
2854     }
2855
2856     if (fscanf(stream, "%x %x %x %x", &a, &b, &c, &d) != 4) {
2857         VLOG_WARN("%s: read failed", fn);
2858         fclose(stream);
2859         return;
2860     }
2861     VLOG_DBG("%s: psched parameters are: %u %u %u %u", fn, a, b, c, d);
2862     fclose(stream);
2863
2864     if (!a || !c) {
2865         VLOG_WARN("%s: invalid scheduler parameters", fn);
2866         return;
2867     }
2868
2869     ticks_per_s = (double) a * c / b;
2870     if (c == 1000000) {
2871         buffer_hz = d;
2872     } else {
2873         VLOG_WARN("%s: unexpected psched parameters: %u %u %u %u",
2874                   fn, a, b, c, d);
2875     }
2876     VLOG_DBG("%s: ticks_per_s=%f buffer_hz=%u", fn, ticks_per_s, buffer_hz);
2877 }
2878
2879 /* Returns the number of bytes that can be transmitted in 'ticks' ticks at a
2880  * rate of 'rate' bytes per second. */
2881 static unsigned int
2882 tc_ticks_to_bytes(unsigned int rate, unsigned int ticks)
2883 {
2884     if (!buffer_hz) {
2885         read_psched();
2886     }
2887     return (rate * ticks) / ticks_per_s;
2888 }
2889
2890 /* Returns the number of ticks that it would take to transmit 'size' bytes at a
2891  * rate of 'rate' bytes per second. */
2892 static unsigned int
2893 tc_bytes_to_ticks(unsigned int rate, unsigned int size)
2894 {
2895     if (!buffer_hz) {
2896         read_psched();
2897     }
2898     return ((unsigned long long int) ticks_per_s * size) / rate;
2899 }
2900
2901 /* Returns the number of bytes that need to be reserved for qdisc buffering at
2902  * a transmission rate of 'rate' bytes per second. */
2903 static unsigned int
2904 tc_buffer_per_jiffy(unsigned int rate)
2905 {
2906     if (!buffer_hz) {
2907         read_psched();
2908     }
2909     return rate / buffer_hz;
2910 }
2911
2912 /* Given Netlink 'msg' that describes a qdisc, extracts the name of the qdisc,
2913  * e.g. "htb", into '*kind' (if it is nonnull).  If 'options' is nonnull,
2914  * extracts 'msg''s TCA_OPTIONS attributes into '*options' if it is present or
2915  * stores NULL into it if it is absent.
2916  *
2917  * '*kind' and '*options' point into 'msg', so they are owned by whoever owns
2918  * 'msg'.
2919  *
2920  * Returns 0 if successful, otherwise a positive errno value. */
2921 static int
2922 tc_parse_qdisc(const struct ofpbuf *msg, const char **kind,
2923                struct nlattr **options)
2924 {
2925     static const struct nl_policy tca_policy[] = {
2926         [TCA_KIND] = { .type = NL_A_STRING, .optional = false },
2927         [TCA_OPTIONS] = { .type = NL_A_NESTED, .optional = true },
2928     };
2929     struct nlattr *ta[ARRAY_SIZE(tca_policy)];
2930
2931     if (!nl_policy_parse(msg, NLMSG_HDRLEN + sizeof(struct tcmsg),
2932                          tca_policy, ta, ARRAY_SIZE(ta))) {
2933         VLOG_WARN_RL(&rl, "failed to parse qdisc message");
2934         goto error;
2935     }
2936
2937     if (kind) {
2938         *kind = nl_attr_get_string(ta[TCA_KIND]);
2939     }
2940
2941     if (options) {
2942         *options = ta[TCA_OPTIONS];
2943     }
2944
2945     return 0;
2946
2947 error:
2948     if (kind) {
2949         *kind = NULL;
2950     }
2951     if (options) {
2952         *options = NULL;
2953     }
2954     return EPROTO;
2955 }
2956
2957 /* Given Netlink 'msg' that describes a class, extracts the queue ID (e.g. the
2958  * minor number of its class ID) into '*queue_id', its TCA_OPTIONS attribute
2959  * into '*options', and its queue statistics into '*stats'.  Any of the output
2960  * arguments may be null.
2961  *
2962  * Returns 0 if successful, otherwise a positive errno value. */
2963 static int
2964 tc_parse_class(const struct ofpbuf *msg, unsigned int *handlep,
2965                struct nlattr **options, struct netdev_queue_stats *stats)
2966 {
2967     static const struct nl_policy tca_policy[] = {
2968         [TCA_OPTIONS] = { .type = NL_A_NESTED, .optional = false },
2969         [TCA_STATS2] = { .type = NL_A_NESTED, .optional = false },
2970     };
2971     struct nlattr *ta[ARRAY_SIZE(tca_policy)];
2972
2973     if (!nl_policy_parse(msg, NLMSG_HDRLEN + sizeof(struct tcmsg),
2974                          tca_policy, ta, ARRAY_SIZE(ta))) {
2975         VLOG_WARN_RL(&rl, "failed to parse class message");
2976         goto error;
2977     }
2978
2979     if (handlep) {
2980         struct tcmsg *tc = ofpbuf_at_assert(msg, NLMSG_HDRLEN, sizeof *tc);
2981         *handlep = tc->tcm_handle;
2982     }
2983
2984     if (options) {
2985         *options = ta[TCA_OPTIONS];
2986     }
2987
2988     if (stats) {
2989         const struct gnet_stats_queue *gsq;
2990         struct gnet_stats_basic gsb;
2991
2992         static const struct nl_policy stats_policy[] = {
2993             [TCA_STATS_BASIC] = { .type = NL_A_UNSPEC, .optional = false,
2994                                   .min_len = sizeof gsb },
2995             [TCA_STATS_QUEUE] = { .type = NL_A_UNSPEC, .optional = false,
2996                                   .min_len = sizeof *gsq },
2997         };
2998         struct nlattr *sa[ARRAY_SIZE(stats_policy)];
2999
3000         if (!nl_parse_nested(ta[TCA_STATS2], stats_policy,
3001                              sa, ARRAY_SIZE(sa))) {
3002             VLOG_WARN_RL(&rl, "failed to parse class stats");
3003             goto error;
3004         }
3005
3006         /* Alignment issues screw up the length of struct gnet_stats_basic on
3007          * some arch/bitsize combinations.  Newer versions of Linux have a
3008          * struct gnet_stats_basic_packed, but we can't depend on that.  The
3009          * easiest thing to do is just to make a copy. */
3010         memset(&gsb, 0, sizeof gsb);
3011         memcpy(&gsb, nl_attr_get(sa[TCA_STATS_BASIC]),
3012                MIN(nl_attr_get_size(sa[TCA_STATS_BASIC]), sizeof gsb));
3013         stats->tx_bytes = gsb.bytes;
3014         stats->tx_packets = gsb.packets;
3015
3016         gsq = nl_attr_get(sa[TCA_STATS_QUEUE]);
3017         stats->tx_errors = gsq->drops;
3018     }
3019
3020     return 0;
3021
3022 error:
3023     if (options) {
3024         *options = NULL;
3025     }
3026     if (stats) {
3027         memset(stats, 0, sizeof *stats);
3028     }
3029     return EPROTO;
3030 }
3031
3032 /* Queries the kernel for class with identifier 'handle' and parent 'parent'
3033  * on 'netdev'. */
3034 static int
3035 tc_query_class(const struct netdev *netdev,
3036                unsigned int handle, unsigned int parent,
3037                struct ofpbuf **replyp)
3038 {
3039     struct ofpbuf request;
3040     struct tcmsg *tcmsg;
3041     int error;
3042
3043     tcmsg = tc_make_request(netdev, RTM_GETTCLASS, NLM_F_ECHO, &request);
3044     tcmsg->tcm_handle = handle;
3045     tcmsg->tcm_parent = parent;
3046
3047     error = tc_transact(&request, replyp);
3048     if (error) {
3049         VLOG_WARN_RL(&rl, "query %s class %u:%u (parent %u:%u) failed (%s)",
3050                      netdev_get_name(netdev),
3051                      tc_get_major(handle), tc_get_minor(handle),
3052                      tc_get_major(parent), tc_get_minor(parent),
3053                      strerror(error));
3054     }
3055     return error;
3056 }
3057
3058 /* Equivalent to "tc class del dev <name> handle <handle>". */
3059 static int
3060 tc_delete_class(const struct netdev *netdev, unsigned int handle)
3061 {
3062     struct ofpbuf request;
3063     struct tcmsg *tcmsg;
3064     int error;
3065
3066     tcmsg = tc_make_request(netdev, RTM_DELTCLASS, 0, &request);
3067     tcmsg->tcm_handle = handle;
3068     tcmsg->tcm_parent = 0;
3069
3070     error = tc_transact(&request, NULL);
3071     if (error) {
3072         VLOG_WARN_RL(&rl, "delete %s class %u:%u failed (%s)",
3073                      netdev_get_name(netdev),
3074                      tc_get_major(handle), tc_get_minor(handle),
3075                      strerror(error));
3076     }
3077     return error;
3078 }
3079
3080 /* Equivalent to "tc qdisc del dev <name> root". */
3081 static int
3082 tc_del_qdisc(struct netdev *netdev)
3083 {
3084     struct netdev_dev_linux *netdev_dev =
3085                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
3086     struct ofpbuf request;
3087     struct tcmsg *tcmsg;
3088     int error;
3089
3090     tcmsg = tc_make_request(netdev, RTM_DELQDISC, 0, &request);
3091     tcmsg->tcm_handle = tc_make_handle(1, 0);
3092     tcmsg->tcm_parent = TC_H_ROOT;
3093
3094     error = tc_transact(&request, NULL);
3095     if (error == EINVAL) {
3096         /* EINVAL probably means that the default qdisc was in use, in which
3097          * case we've accomplished our purpose. */
3098         error = 0;
3099     }
3100     if (!error && netdev_dev->tc) {
3101         if (netdev_dev->tc->ops->tc_destroy) {
3102             netdev_dev->tc->ops->tc_destroy(netdev_dev->tc);
3103         }
3104         netdev_dev->tc = NULL;
3105     }
3106     return error;
3107 }
3108
3109 /* If 'netdev''s qdisc type and parameters are not yet known, queries the
3110  * kernel to determine what they are.  Returns 0 if successful, otherwise a
3111  * positive errno value. */
3112 static int
3113 tc_query_qdisc(const struct netdev *netdev)
3114 {
3115     struct netdev_dev_linux *netdev_dev =
3116                                 netdev_dev_linux_cast(netdev_get_dev(netdev));
3117     struct ofpbuf request, *qdisc;
3118     const struct tc_ops *ops;
3119     struct tcmsg *tcmsg;
3120     int load_error;
3121     int error;
3122
3123     if (netdev_dev->tc) {
3124         return 0;
3125     }
3126
3127     /* This RTM_GETQDISC is crafted to avoid OOPSing kernels that do not have
3128      * commit 53b0f08 "net_sched: Fix qdisc_notify()", which is anything before
3129      * 2.6.35 without that fix backported to it.
3130      *
3131      * To avoid the OOPS, we must not make a request that would attempt to dump
3132      * a "built-in" qdisc, that is, the default pfifo_fast qdisc or one of a
3133      * few others.  There are a few ways that I can see to do this, but most of
3134      * them seem to be racy (and if you lose the race the kernel OOPSes).  The
3135      * technique chosen here is to assume that any non-default qdisc that we
3136      * create will have a class with handle 1:0.  The built-in qdiscs only have
3137      * a class with handle 0:0.
3138      *
3139      * We could check for Linux 2.6.35+ and use a more straightforward method
3140      * there. */
3141     tcmsg = tc_make_request(netdev, RTM_GETQDISC, NLM_F_ECHO, &request);
3142     tcmsg->tcm_handle = tc_make_handle(1, 0);
3143     tcmsg->tcm_parent = 0;
3144
3145     /* Figure out what tc class to instantiate. */
3146     error = tc_transact(&request, &qdisc);
3147     if (!error) {
3148         const char *kind;
3149
3150         error = tc_parse_qdisc(qdisc, &kind, NULL);
3151         if (error) {
3152             ops = &tc_ops_other;
3153         } else {
3154             ops = tc_lookup_linux_name(kind);
3155             if (!ops) {
3156                 static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 1);
3157                 VLOG_INFO_RL(&rl2, "unknown qdisc \"%s\"", kind);
3158
3159                 ops = &tc_ops_other;
3160             }
3161         }
3162     } else if (error == ENOENT) {
3163         /* Either it's a built-in qdisc, or it's a qdisc set up by some
3164          * other entity that doesn't have a handle 1:0.  We will assume
3165          * that it's the system default qdisc. */
3166         ops = &tc_ops_default;
3167         error = 0;
3168     } else {
3169         /* Who knows?  Maybe the device got deleted. */
3170         VLOG_WARN_RL(&rl, "query %s qdisc failed (%s)",
3171                      netdev_get_name(netdev), strerror(error));
3172         ops = &tc_ops_other;
3173     }
3174
3175     /* Instantiate it. */
3176     load_error = ops->tc_load((struct netdev *) netdev, qdisc);
3177     assert((load_error == 0) == (netdev_dev->tc != NULL));
3178     ofpbuf_delete(qdisc);
3179
3180     return error ? error : load_error;
3181 }
3182
3183 /* Linux traffic control uses tables with 256 entries ("rtab" tables) to
3184    approximate the time to transmit packets of various lengths.  For an MTU of
3185    256 or less, each entry is exact; for an MTU of 257 through 512, each entry
3186    represents two possible packet lengths; for a MTU of 513 through 1024, four
3187    possible lengths; and so on.
3188
3189    Returns, for the specified 'mtu', the number of bits that packet lengths
3190    need to be shifted right to fit within such a 256-entry table. */
3191 static int
3192 tc_calc_cell_log(unsigned int mtu)
3193 {
3194     int cell_log;
3195
3196     if (!mtu) {
3197         mtu = ETH_PAYLOAD_MAX;
3198     }
3199     mtu += ETH_HEADER_LEN + VLAN_HEADER_LEN;
3200
3201     for (cell_log = 0; mtu >= 256; cell_log++) {
3202         mtu >>= 1;
3203     }
3204
3205     return cell_log;
3206 }
3207
3208 /* Initializes 'rate' properly for a rate of 'Bps' bytes per second with an MTU
3209  * of 'mtu'. */
3210 static void
3211 tc_fill_rate(struct tc_ratespec *rate, uint64_t Bps, int mtu)
3212 {
3213     memset(rate, 0, sizeof *rate);
3214     rate->cell_log = tc_calc_cell_log(mtu);
3215     /* rate->overhead = 0; */           /* New in 2.6.24, not yet in some */
3216     /* rate->cell_align = 0; */         /* distro headers. */
3217     rate->mpu = ETH_TOTAL_MIN;
3218     rate->rate = Bps;
3219 }
3220
3221 /* Appends to 'msg' an "rtab" table for the specified 'rate' as a Netlink
3222  * attribute of the specified "type".
3223  *
3224  * See tc_calc_cell_log() above for a description of "rtab"s. */
3225 static void
3226 tc_put_rtab(struct ofpbuf *msg, uint16_t type, const struct tc_ratespec *rate)
3227 {
3228     uint32_t *rtab;
3229     unsigned int i;
3230
3231     rtab = nl_msg_put_unspec_uninit(msg, type, TC_RTAB_SIZE);
3232     for (i = 0; i < TC_RTAB_SIZE / sizeof *rtab; i++) {
3233         unsigned packet_size = (i + 1) << rate->cell_log;
3234         if (packet_size < rate->mpu) {
3235             packet_size = rate->mpu;
3236         }
3237         rtab[i] = tc_bytes_to_ticks(rate->rate, packet_size);
3238     }
3239 }
3240
3241 /* Calculates the proper value of 'buffer' or 'cbuffer' in HTB options given a
3242  * rate of 'Bps' bytes per second, the specified 'mtu', and a user-requested
3243  * burst size of 'burst_bytes'.  (If no value was requested, a 'burst_bytes' of
3244  * 0 is fine.)
3245  *
3246  * This */
3247 static int
3248 tc_calc_buffer(unsigned int Bps, int mtu, uint64_t burst_bytes)
3249 {
3250     unsigned int min_burst = tc_buffer_per_jiffy(Bps) + mtu;
3251     return tc_bytes_to_ticks(Bps, MAX(burst_bytes, min_burst));
3252 }
3253
3254 \f
3255 /* Utility functions. */
3256
3257 static int
3258 get_stats_via_netlink(int ifindex, struct netdev_stats *stats)
3259 {
3260     /* Policy for RTNLGRP_LINK messages.
3261      *
3262      * There are *many* more fields in these messages, but currently we only
3263      * care about these fields. */
3264     static const struct nl_policy rtnlgrp_link_policy[] = {
3265         [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
3266         [IFLA_STATS] = { .type = NL_A_UNSPEC, .optional = true,
3267                          .min_len = sizeof(struct rtnl_link_stats) },
3268     };
3269
3270     struct ofpbuf request;
3271     struct ofpbuf *reply;
3272     struct ifinfomsg *ifi;
3273     const struct rtnl_link_stats *rtnl_stats;
3274     struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
3275     int error;
3276
3277     ofpbuf_init(&request, 0);
3278     nl_msg_put_nlmsghdr(&request, sizeof *ifi, RTM_GETLINK, NLM_F_REQUEST);
3279     ifi = ofpbuf_put_zeros(&request, sizeof *ifi);
3280     ifi->ifi_family = PF_UNSPEC;
3281     ifi->ifi_index = ifindex;
3282     error = nl_sock_transact(rtnl_sock, &request, &reply);
3283     ofpbuf_uninit(&request);
3284     if (error) {
3285         return error;
3286     }
3287
3288     if (!nl_policy_parse(reply, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
3289                          rtnlgrp_link_policy,
3290                          attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
3291         ofpbuf_delete(reply);
3292         return EPROTO;
3293     }
3294
3295     if (!attrs[IFLA_STATS]) {
3296         VLOG_WARN_RL(&rl, "RTM_GETLINK reply lacks stats");
3297         ofpbuf_delete(reply);
3298         return EPROTO;
3299     }
3300
3301     rtnl_stats = nl_attr_get(attrs[IFLA_STATS]);
3302     stats->rx_packets = rtnl_stats->rx_packets;
3303     stats->tx_packets = rtnl_stats->tx_packets;
3304     stats->rx_bytes = rtnl_stats->rx_bytes;
3305     stats->tx_bytes = rtnl_stats->tx_bytes;
3306     stats->rx_errors = rtnl_stats->rx_errors;
3307     stats->tx_errors = rtnl_stats->tx_errors;
3308     stats->rx_dropped = rtnl_stats->rx_dropped;
3309     stats->tx_dropped = rtnl_stats->tx_dropped;
3310     stats->multicast = rtnl_stats->multicast;
3311     stats->collisions = rtnl_stats->collisions;
3312     stats->rx_length_errors = rtnl_stats->rx_length_errors;
3313     stats->rx_over_errors = rtnl_stats->rx_over_errors;
3314     stats->rx_crc_errors = rtnl_stats->rx_crc_errors;
3315     stats->rx_frame_errors = rtnl_stats->rx_frame_errors;
3316     stats->rx_fifo_errors = rtnl_stats->rx_fifo_errors;
3317     stats->rx_missed_errors = rtnl_stats->rx_missed_errors;
3318     stats->tx_aborted_errors = rtnl_stats->tx_aborted_errors;
3319     stats->tx_carrier_errors = rtnl_stats->tx_carrier_errors;
3320     stats->tx_fifo_errors = rtnl_stats->tx_fifo_errors;
3321     stats->tx_heartbeat_errors = rtnl_stats->tx_heartbeat_errors;
3322     stats->tx_window_errors = rtnl_stats->tx_window_errors;
3323
3324     ofpbuf_delete(reply);
3325
3326     return 0;
3327 }
3328
3329 static int
3330 get_stats_via_proc(const char *netdev_name, struct netdev_stats *stats)
3331 {
3332     static const char fn[] = "/proc/net/dev";
3333     char line[1024];
3334     FILE *stream;
3335     int ln;
3336
3337     stream = fopen(fn, "r");
3338     if (!stream) {
3339         VLOG_WARN_RL(&rl, "%s: open failed: %s", fn, strerror(errno));
3340         return errno;
3341     }
3342
3343     ln = 0;
3344     while (fgets(line, sizeof line, stream)) {
3345         if (++ln >= 3) {
3346             char devname[16];
3347 #define X64 "%"SCNu64
3348             if (sscanf(line,
3349                        " %15[^:]:"
3350                        X64 X64 X64 X64 X64 X64 X64 "%*u"
3351                        X64 X64 X64 X64 X64 X64 X64 "%*u",
3352                        devname,
3353                        &stats->rx_bytes,
3354                        &stats->rx_packets,
3355                        &stats->rx_errors,
3356                        &stats->rx_dropped,
3357                        &stats->rx_fifo_errors,
3358                        &stats->rx_frame_errors,
3359                        &stats->multicast,
3360                        &stats->tx_bytes,
3361                        &stats->tx_packets,
3362                        &stats->tx_errors,
3363                        &stats->tx_dropped,
3364                        &stats->tx_fifo_errors,
3365                        &stats->collisions,
3366                        &stats->tx_carrier_errors) != 15) {
3367                 VLOG_WARN_RL(&rl, "%s:%d: parse error", fn, ln);
3368             } else if (!strcmp(devname, netdev_name)) {
3369                 stats->rx_length_errors = UINT64_MAX;
3370                 stats->rx_over_errors = UINT64_MAX;
3371                 stats->rx_crc_errors = UINT64_MAX;
3372                 stats->rx_missed_errors = UINT64_MAX;
3373                 stats->tx_aborted_errors = UINT64_MAX;
3374                 stats->tx_heartbeat_errors = UINT64_MAX;
3375                 stats->tx_window_errors = UINT64_MAX;
3376                 fclose(stream);
3377                 return 0;
3378             }
3379         }
3380     }
3381     VLOG_WARN_RL(&rl, "%s: no stats for %s", fn, netdev_name);
3382     fclose(stream);
3383     return ENODEV;
3384 }
3385
3386 static int
3387 get_flags(const struct netdev *netdev, int *flags)
3388 {
3389     struct ifreq ifr;
3390     int error;
3391
3392     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCGIFFLAGS,
3393                                   "SIOCGIFFLAGS");
3394     *flags = ifr.ifr_flags;
3395     return error;
3396 }
3397
3398 static int
3399 set_flags(struct netdev *netdev, int flags)
3400 {
3401     struct ifreq ifr;
3402
3403     ifr.ifr_flags = flags;
3404     return netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, SIOCSIFFLAGS,
3405                                  "SIOCSIFFLAGS");
3406 }
3407
3408 static int
3409 do_get_ifindex(const char *netdev_name)
3410 {
3411     struct ifreq ifr;
3412
3413     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
3414     COVERAGE_INC(netdev_get_ifindex);
3415     if (ioctl(af_inet_sock, SIOCGIFINDEX, &ifr) < 0) {
3416         VLOG_WARN_RL(&rl, "ioctl(SIOCGIFINDEX) on %s device failed: %s",
3417                      netdev_name, strerror(errno));
3418         return -errno;
3419     }
3420     return ifr.ifr_ifindex;
3421 }
3422
3423 static int
3424 get_ifindex(const struct netdev *netdev_, int *ifindexp)
3425 {
3426     struct netdev_dev_linux *netdev_dev =
3427                                 netdev_dev_linux_cast(netdev_get_dev(netdev_));
3428     *ifindexp = 0;
3429     if (!(netdev_dev->cache_valid & VALID_IFINDEX)) {
3430         int ifindex = do_get_ifindex(netdev_get_name(netdev_));
3431         if (ifindex < 0) {
3432             return -ifindex;
3433         }
3434         netdev_dev->cache_valid |= VALID_IFINDEX;
3435         netdev_dev->ifindex = ifindex;
3436     }
3437     *ifindexp = netdev_dev->ifindex;
3438     return 0;
3439 }
3440
3441 static int
3442 get_etheraddr(const char *netdev_name, uint8_t ea[ETH_ADDR_LEN])
3443 {
3444     struct ifreq ifr;
3445     int hwaddr_family;
3446
3447     memset(&ifr, 0, sizeof ifr);
3448     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
3449     COVERAGE_INC(netdev_get_hwaddr);
3450     if (ioctl(af_inet_sock, SIOCGIFHWADDR, &ifr) < 0) {
3451         VLOG_ERR("ioctl(SIOCGIFHWADDR) on %s device failed: %s",
3452                  netdev_name, strerror(errno));
3453         return errno;
3454     }
3455     hwaddr_family = ifr.ifr_hwaddr.sa_family;
3456     if (hwaddr_family != AF_UNSPEC && hwaddr_family != ARPHRD_ETHER) {
3457         VLOG_WARN("%s device has unknown hardware address family %d",
3458                   netdev_name, hwaddr_family);
3459     }
3460     memcpy(ea, ifr.ifr_hwaddr.sa_data, ETH_ADDR_LEN);
3461     return 0;
3462 }
3463
3464 static int
3465 set_etheraddr(const char *netdev_name, int hwaddr_family,
3466               const uint8_t mac[ETH_ADDR_LEN])
3467 {
3468     struct ifreq ifr;
3469
3470     memset(&ifr, 0, sizeof ifr);
3471     strncpy(ifr.ifr_name, netdev_name, sizeof ifr.ifr_name);
3472     ifr.ifr_hwaddr.sa_family = hwaddr_family;
3473     memcpy(ifr.ifr_hwaddr.sa_data, mac, ETH_ADDR_LEN);
3474     COVERAGE_INC(netdev_set_hwaddr);
3475     if (ioctl(af_inet_sock, SIOCSIFHWADDR, &ifr) < 0) {
3476         VLOG_ERR("ioctl(SIOCSIFHWADDR) on %s device failed: %s",
3477                  netdev_name, strerror(errno));
3478         return errno;
3479     }
3480     return 0;
3481 }
3482
3483 static int
3484 netdev_linux_do_ethtool(const char *name, struct ethtool_cmd *ecmd,
3485                         int cmd, const char *cmd_name)
3486 {
3487     struct ifreq ifr;
3488
3489     memset(&ifr, 0, sizeof ifr);
3490     strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
3491     ifr.ifr_data = (caddr_t) ecmd;
3492
3493     ecmd->cmd = cmd;
3494     COVERAGE_INC(netdev_ethtool);
3495     if (ioctl(af_inet_sock, SIOCETHTOOL, &ifr) == 0) {
3496         return 0;
3497     } else {
3498         if (errno != EOPNOTSUPP) {
3499             VLOG_WARN_RL(&rl, "ethtool command %s on network device %s "
3500                          "failed: %s", cmd_name, name, strerror(errno));
3501         } else {
3502             /* The device doesn't support this operation.  That's pretty
3503              * common, so there's no point in logging anything. */
3504         }
3505         return errno;
3506     }
3507 }
3508
3509 static int
3510 netdev_linux_do_ioctl(const char *name, struct ifreq *ifr, int cmd,
3511                       const char *cmd_name)
3512 {
3513     strncpy(ifr->ifr_name, name, sizeof ifr->ifr_name);
3514     if (ioctl(af_inet_sock, cmd, ifr) == -1) {
3515         VLOG_DBG_RL(&rl, "%s: ioctl(%s) failed: %s", name, cmd_name,
3516                      strerror(errno));
3517         return errno;
3518     }
3519     return 0;
3520 }
3521
3522 static int
3523 netdev_linux_get_ipv4(const struct netdev *netdev, struct in_addr *ip,
3524                       int cmd, const char *cmd_name)
3525 {
3526     struct ifreq ifr;
3527     int error;
3528
3529     ifr.ifr_addr.sa_family = AF_INET;
3530     error = netdev_linux_do_ioctl(netdev_get_name(netdev), &ifr, cmd, cmd_name);
3531     if (!error) {
3532         const struct sockaddr_in *sin = (struct sockaddr_in *) &ifr.ifr_addr;
3533         *ip = sin->sin_addr;
3534     }
3535     return error;
3536 }