bond: Give bridge control over LACP module.
[sliver-openvswitch.git] / lib / bond.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "bond.h"
20
21 #include <limits.h>
22 #include <stdint.h>
23 #include <stdlib.h>
24
25 #include "coverage.h"
26 #include "dynamic-string.h"
27 #include "flow.h"
28 #include "hmap.h"
29 #include "lacp.h"
30 #include "list.h"
31 #include "netdev.h"
32 #include "odp-util.h"
33 #include "ofpbuf.h"
34 #include "packets.h"
35 #include "poll-loop.h"
36 #include "tag.h"
37 #include "timeval.h"
38 #include "unixctl.h"
39 #include "vlog.h"
40
41 VLOG_DEFINE_THIS_MODULE(bond);
42
43 /* Bit-mask for hashing a flow down to a bucket.
44  * There are (BOND_MASK + 1) buckets. */
45 #define BOND_MASK 0xff
46
47 /* A hash bucket for mapping a flow to a slave.
48  * "struct bond" has an array of (BOND_MASK + 1) of these. */
49 struct bond_entry {
50     struct bond_slave *slave;   /* Assigned slave, NULL if unassigned. */
51     uint64_t tx_bytes;          /* Count of bytes recently transmitted. */
52     tag_type tag;               /* Tag for entry<->slave association. */
53     struct list list_node;      /* In bond_slave's 'entries' list. */
54 };
55
56 /* A bond slave, that is, one of the links comprising a bond. */
57 struct bond_slave {
58     struct hmap_node hmap_node; /* In struct bond's slaves hmap. */
59     struct bond *bond;          /* The bond that contains this slave. */
60     void *aux;                  /* Client-provided handle for this slave. */
61
62     struct netdev *netdev;      /* Network device, owned by the client. */
63     char *name;                 /* Name (a copy of netdev_get_name(netdev)). */
64
65     /* Link status. */
66     long long delay_expires;    /* Time after which 'enabled' may change. */
67     bool up;                    /* Last link status read from netdev. */
68     bool enabled;               /* May be chosen for flows? */
69     tag_type tag;               /* Tag associated with this slave. */
70
71     /* Rebalancing info.  Used only by bond_rebalance(). */
72     struct list bal_node;       /* In bond_rebalance()'s 'bals' list. */
73     struct list entries;        /* 'struct bond_entry's assigned here. */
74     uint64_t tx_bytes;          /* Sum across 'tx_bytes' of entries. */
75
76     /* BM_STABLE specific bonding info. */
77     size_t stb_idx;             /* Index in 'bond''s 'stb_slaves' array.
78                                    Undefined value if participating in a
79                                    BTM_STABLE bond or not enabled. */
80 };
81
82 /* A bond, that is, a set of network devices grouped to improve performance or
83  * robustness.  */
84 struct bond {
85     struct hmap_node hmap_node; /* In 'all_bonds' hmap. */
86     char *name;                 /* Name provided by client. */
87
88     /* Slaves. */
89     struct hmap slaves;
90
91     /* Bonding info. */
92     enum bond_mode balance;     /* Balancing mode, one of BM_*. */
93     struct bond_slave *active_slave;
94     tag_type no_slaves_tag;     /* Tag for flows when all slaves disabled. */
95     int updelay, downdelay;     /* Delay before slave goes up/down, in ms. */
96
97     /* SLB specific bonding info. */
98     struct bond_entry *hash;     /* An array of (BOND_MASK + 1) elements. */
99     int rebalance_interval;      /* Interval between rebalances, in ms. */
100     long long int next_rebalance; /* Next rebalancing time. */
101     bool send_learning_packets;
102
103     /* BM_STABLE specific bonding info. */
104     struct bond_slave **stb_slaves; /* Ordered list of enabled slaves. */
105     size_t n_stb_slaves;            /* Number of slaves in 'stb_slaves'. */
106     size_t len_stb_slaves;          /* Slaves allocated in 'stb_slaves'. */
107     bool stb_need_sort;             /* True if stb_slaves is not sorted. */
108
109     /* LACP. */
110     const struct lacp *lacp;        /* Client provided LACP handle. */
111
112     /* Monitoring. */
113     enum bond_detect_mode detect;     /* Link status mode, one of BLSM_*. */
114     struct netdev_monitor *monitor;   /* detect == BLSM_CARRIER only. */
115     long long int miimon_interval;    /* Miimon status refresh interval. */
116     long long int miimon_next_update; /* Time of next miimon update. */
117
118     /* Legacy compatibility. */
119     long long int next_fake_iface_update; /* LLONG_MAX if disabled. */
120
121     /* Tag set saved for next bond_run().  This tag set is a kluge for cases
122      * where we can't otherwise provide revalidation feedback to the client.
123      * That's only unixctl commands now; I hope no other cases will arise. */
124     struct tag_set unixctl_tags;
125 };
126
127 static struct hmap all_bonds = HMAP_INITIALIZER(&all_bonds);
128
129 static void bond_entry_reset(struct bond *);
130 static struct bond_slave *bond_slave_lookup(struct bond *, const void *slave_);
131 static bool bond_is_link_up(struct bond *, struct netdev *);
132 static void bond_enable_slave(struct bond_slave *, bool enable,
133                               struct tag_set *);
134 static bool bond_stb_sort(struct bond *);
135 static void bond_stb_enable_slave(struct bond_slave *);
136 static void bond_link_status_update(struct bond_slave *, struct tag_set *);
137 static void bond_choose_active_slave(struct bond *, struct tag_set *);
138 static bool bond_is_tcp_hash(const struct bond *);
139 static unsigned int bond_hash_src(const uint8_t mac[ETH_ADDR_LEN],
140                                   uint16_t vlan);
141 static unsigned int bond_hash_tcp(const struct flow *, uint16_t vlan);
142 static struct bond_entry *lookup_bond_entry(const struct bond *,
143                                             const struct flow *,
144                                             uint16_t vlan);
145 static tag_type bond_get_active_slave_tag(const struct bond *);
146 static struct bond_slave *choose_output_slave(const struct bond *,
147                                               const struct flow *,
148                                               uint16_t vlan);
149 static void bond_update_fake_slave_stats(struct bond *);
150
151 /* Attempts to parse 's' as the name of a bond balancing mode.  If successful,
152  * stores the mode in '*balance' and returns true.  Otherwise returns false
153  * without modifying '*balance'. */
154 bool
155 bond_mode_from_string(enum bond_mode *balance, const char *s)
156 {
157     if (!strcmp(s, bond_mode_to_string(BM_TCP))) {
158         *balance = BM_TCP;
159     } else if (!strcmp(s, bond_mode_to_string(BM_SLB))) {
160         *balance = BM_SLB;
161     } else if (!strcmp(s, bond_mode_to_string(BM_STABLE))) {
162         *balance = BM_STABLE;
163     } else if (!strcmp(s, bond_mode_to_string(BM_AB))) {
164         *balance = BM_AB;
165     } else {
166         return false;
167     }
168     return true;
169 }
170
171 /* Returns a string representing 'balance'. */
172 const char *
173 bond_mode_to_string(enum bond_mode balance) {
174     switch (balance) {
175     case BM_TCP:
176         return "balance-tcp";
177     case BM_SLB:
178         return "balance-slb";
179     case BM_STABLE:
180         return "stable";
181     case BM_AB:
182         return "active-backup";
183     }
184     NOT_REACHED();
185 }
186
187 /* Attempts to parse 's' as the name of a bond link status detection mode.  If
188  * successful, stores the mode in '*detect' and returns true.  Otherwise
189  * returns false without modifying '*detect'. */
190 bool
191 bond_detect_mode_from_string(enum bond_detect_mode *detect, const char *s)
192 {
193     if (!strcmp(s, bond_detect_mode_to_string(BLSM_CARRIER))) {
194         *detect = BLSM_CARRIER;
195     } else if (!strcmp(s, bond_detect_mode_to_string(BLSM_MIIMON))) {
196         *detect = BLSM_MIIMON;
197     } else {
198         return false;
199     }
200     return true;
201 }
202
203 /* Returns a string representing 'detect'. */
204 const char *
205 bond_detect_mode_to_string(enum bond_detect_mode detect)
206 {
207     switch (detect) {
208     case BLSM_CARRIER:
209         return "carrier";
210     case BLSM_MIIMON:
211         return "miimon";
212     }
213     NOT_REACHED();
214 }
215 \f
216 /* Creates and returns a new bond whose configuration is initially taken from
217  * 's'.
218  *
219  * The caller should register each slave on the new bond by calling
220  * bond_slave_register().  */
221 struct bond *
222 bond_create(const struct bond_settings *s)
223 {
224     struct bond *bond;
225
226     bond = xzalloc(sizeof *bond);
227     hmap_init(&bond->slaves);
228     bond->no_slaves_tag = tag_create_random();
229     bond->miimon_next_update = LLONG_MAX;
230     bond->next_fake_iface_update = LLONG_MAX;
231
232     bond_reconfigure(bond, s);
233
234     tag_set_init(&bond->unixctl_tags);
235
236     return bond;
237 }
238
239 /* Frees 'bond'. */
240 void
241 bond_destroy(struct bond *bond)
242 {
243     struct bond_slave *slave, *next_slave;
244
245     if (!bond) {
246         return;
247     }
248
249     hmap_remove(&all_bonds, &bond->hmap_node);
250
251     HMAP_FOR_EACH_SAFE (slave, next_slave, hmap_node, &bond->slaves) {
252         hmap_remove(&bond->slaves, &slave->hmap_node);
253         /* Client owns 'slave->netdev'. */
254         free(slave->name);
255         free(slave);
256     }
257     hmap_destroy(&bond->slaves);
258
259     free(bond->hash);
260
261     netdev_monitor_destroy(bond->monitor);
262
263     free(bond->name);
264     free(bond);
265 }
266
267 /* Updates 'bond''s overall configuration to 's'.
268  *
269  * The caller should register each slave on 'bond' by calling
270  * bond_slave_register().  This is optional if none of the slaves'
271  * configuration has changed, except that it is mandatory if 's' enables LACP
272  * and 'bond' previously didn't have LACP enabled.  In any case it can't
273  * hurt.
274  *
275  * Returns true if the configuration has changed in such a way that requires
276  * flow revalidation.
277  * */
278 bool
279 bond_reconfigure(struct bond *bond, const struct bond_settings *s)
280 {
281     bool revalidate = false;
282
283     if (!bond->name || strcmp(bond->name, s->name)) {
284         if (bond->name) {
285             hmap_remove(&all_bonds, &bond->hmap_node);
286             free(bond->name);
287         }
288         bond->name = xstrdup(s->name);
289         hmap_insert(&all_bonds, &bond->hmap_node, hash_string(bond->name, 0));
290     }
291
292     bond->lacp = s->lacp;
293     bond->detect = s->detect;
294     bond->miimon_interval = s->miimon_interval;
295     bond->updelay = s->up_delay;
296     bond->downdelay = s->down_delay;
297     bond->rebalance_interval = s->rebalance_interval;
298
299     if (bond->balance != s->balance) {
300         bond->balance = s->balance;
301         revalidate = true;
302     }
303
304     if (bond->detect == BLSM_CARRIER) {
305         struct bond_slave *slave;
306
307         if (!bond->monitor) {
308             bond->monitor = netdev_monitor_create();
309         }
310
311         HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
312             netdev_monitor_add(bond->monitor, slave->netdev);
313         }
314     } else {
315         netdev_monitor_destroy(bond->monitor);
316         bond->monitor = NULL;
317
318         if (bond->miimon_next_update == LLONG_MAX) {
319             bond->miimon_next_update = time_msec() + bond->miimon_interval;
320         }
321     }
322
323     if (s->fake_iface) {
324         if (bond->next_fake_iface_update == LLONG_MAX) {
325             bond->next_fake_iface_update = time_msec();
326         }
327     } else {
328         bond->next_fake_iface_update = LLONG_MAX;
329     }
330
331     if (bond->balance != BM_STABLE) {
332         free(bond->stb_slaves);
333         bond->stb_slaves = NULL;
334     } else if (!bond->stb_slaves) {
335         struct bond_slave *slave;
336
337         bond->n_stb_slaves = 0;
338         bond->len_stb_slaves = 0;
339         bond->stb_slaves = NULL;
340
341         HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
342             if (slave->enabled) {
343                 bond_stb_enable_slave(slave);
344             }
345         }
346     }
347
348     if (bond->balance == BM_AB || !bond->hash || revalidate) {
349         bond_entry_reset(bond);
350     }
351
352     return revalidate;
353 }
354
355 /* Registers 'slave_' as a slave of 'bond'.  The 'slave_' pointer is an
356  * arbitrary client-provided pointer that uniquely identifies a slave within a
357  * bond.  If 'slave_' already exists within 'bond' then this function
358  * reconfigures the existing slave.
359  *
360  * 'netdev' must be the network device that 'slave_' represents.  It is owned
361  * by the client, so the client must not close it before either unregistering
362  * 'slave_' or destroying 'bond'.
363  *
364  * If 'bond' has a LACP configuration then 'slave_' should be the same handle
365  * used in the LACP module. */
366 void
367 bond_slave_register(struct bond *bond, void *slave_, struct netdev *netdev)
368 {
369     struct bond_slave *slave = bond_slave_lookup(bond, slave_);
370
371     if (!slave) {
372         slave = xzalloc(sizeof *slave);
373
374         hmap_insert(&bond->slaves, &slave->hmap_node, hash_pointer(slave_, 0));
375         slave->bond = bond;
376         slave->aux = slave_;
377         slave->delay_expires = LLONG_MAX;
378         slave->up = bond_is_link_up(bond, netdev);
379         slave->enabled = false;
380         bond_enable_slave(slave, slave->up, NULL);
381     }
382
383     slave->netdev = netdev;
384     free(slave->name);
385     slave->name = xstrdup(netdev_get_name(netdev));
386 }
387
388 /* Unregisters 'slave_' from 'bond'.  If 'bond' does not contain such a slave
389  * then this function has no effect.
390  *
391  * Unregistering a slave invalidates all flows. */
392 void
393 bond_slave_unregister(struct bond *bond, const void *slave_)
394 {
395     struct bond_slave *slave = bond_slave_lookup(bond, slave_);
396     bool del_active;
397
398     if (!slave) {
399         return;
400     }
401
402     bond_enable_slave(slave, false, NULL);
403
404     del_active = bond->active_slave == slave;
405     if (bond->hash) {
406         struct bond_entry *e;
407         for (e = bond->hash; e <= &bond->hash[BOND_MASK]; e++) {
408             if (e->slave == slave) {
409                 e->slave = NULL;
410             }
411         }
412     }
413
414     free(slave->name);
415
416     hmap_remove(&bond->slaves, &slave->hmap_node);
417     /* Client owns 'slave->netdev'. */
418     free(slave);
419
420     if (del_active) {
421         struct tag_set tags;
422
423         tag_set_init(&tags);
424         bond_choose_active_slave(bond, &tags);
425         bond->send_learning_packets = true;
426     }
427 }
428
429 /* Performs periodic maintenance on 'bond'.  The caller must provide 'tags' to
430  * allow tagged flows to be invalidated.
431  *
432  * The caller should check bond_should_send_learning_packets() afterward. */
433 void
434 bond_run(struct bond *bond, struct tag_set *tags)
435 {
436     struct bond_slave *slave;
437     bool is_tcp_hash = bond_is_tcp_hash(bond);
438
439     /* Update link status. */
440     if (bond->detect == BLSM_CARRIER
441         || time_msec() >= bond->miimon_next_update)
442     {
443         HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
444             slave->up = bond_is_link_up(bond, slave->netdev);
445         }
446         bond->miimon_next_update = time_msec() + bond->miimon_interval;
447     }
448
449     /* Enable slaves based on link status and LACP feedback. */
450     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
451         bond_link_status_update(slave, tags);
452     }
453     if (!bond->active_slave || !bond->active_slave->enabled) {
454         bond_choose_active_slave(bond, tags);
455     }
456
457     /* Update fake bond interface stats. */
458     if (time_msec() >= bond->next_fake_iface_update) {
459         bond_update_fake_slave_stats(bond);
460         bond->next_fake_iface_update = time_msec() + 1000;
461     }
462
463     if (bond_stb_sort(bond) || is_tcp_hash != bond_is_tcp_hash(bond)) {
464         struct bond_slave *slave;
465
466         bond_entry_reset(bond);
467         HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
468             tag_set_add(tags, slave->tag);
469         }
470     }
471
472     /* Invalidate any tags required by  */
473     tag_set_union(tags, &bond->unixctl_tags);
474     tag_set_init(&bond->unixctl_tags);
475 }
476
477 /* Causes poll_block() to wake up when 'bond' needs something to be done. */
478 void
479 bond_wait(struct bond *bond)
480 {
481     struct bond_slave *slave;
482
483     if (bond->detect == BLSM_CARRIER) {
484         netdev_monitor_poll_wait(bond->monitor);
485     } else {
486         poll_timer_wait_until(bond->miimon_next_update);
487     }
488
489     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
490         if (slave->delay_expires != LLONG_MAX) {
491             poll_timer_wait_until(slave->delay_expires);
492         }
493     }
494
495     if (bond->next_fake_iface_update != LLONG_MAX) {
496         poll_timer_wait_until(bond->next_fake_iface_update);
497     }
498
499     /* Ensure that any saved tags get revalidated right away. */
500     if (!tag_set_is_empty(&bond->unixctl_tags)) {
501         poll_immediate_wake();
502     }
503
504     /* We don't wait for bond->next_rebalance because rebalancing can only run
505      * at a flow account checkpoint.  ofproto does checkpointing on its own
506      * schedule and bond_rebalance() gets called afterward, so we'd just be
507      * waking up for no purpose. */
508 }
509 \f
510 /* MAC learning table interaction. */
511
512 static bool
513 may_send_learning_packets(const struct bond *bond)
514 {
515     return !lacp_negotiated(bond->lacp) && bond->balance != BM_AB;
516 }
517
518 /* Returns true if 'bond' needs the client to send out packets to assist with
519  * MAC learning on 'bond'.  If this function returns true, then the client
520  * should iterate through its MAC learning table for the bridge on which 'bond'
521  * is located.  For each MAC that has been learned on a port other than 'bond',
522  * it should call bond_send_learning_packet().
523  *
524  * This function will only return true if 'bond' is in SLB mode and LACP is not
525  * negotiated.  Otherwise sending learning packets isn't necessary.
526  *
527  * Calling this function resets the state that it checks. */
528 bool
529 bond_should_send_learning_packets(struct bond *bond)
530 {
531     bool send = bond->send_learning_packets && may_send_learning_packets(bond);
532     bond->send_learning_packets = false;
533     return send;
534 }
535
536 /* Sends a gratuitous learning packet on 'bond' from 'eth_src' on 'vlan'.
537  *
538  * See bond_should_send_learning_packets() for description of usage. */
539 int
540 bond_send_learning_packet(struct bond *bond,
541                           const uint8_t eth_src[ETH_ADDR_LEN],
542                           uint16_t vlan)
543 {
544     struct bond_slave *slave;
545     struct ofpbuf packet;
546     struct flow flow;
547     int error;
548
549     assert(may_send_learning_packets(bond));
550     if (!bond->active_slave) {
551         /* Nowhere to send the learning packet. */
552         return 0;
553     }
554
555     memset(&flow, 0, sizeof flow);
556     memcpy(flow.dl_src, eth_src, ETH_ADDR_LEN);
557     slave = choose_output_slave(bond, &flow, vlan);
558
559     ofpbuf_init(&packet, 0);
560     compose_benign_packet(&packet, "Open vSwitch Bond Failover", 0xf177,
561                           eth_src);
562     if (vlan) {
563         eth_set_vlan_tci(&packet, htons(vlan));
564     }
565     error = netdev_send(slave->netdev, &packet);
566     ofpbuf_uninit(&packet);
567
568     return error;
569 }
570 \f
571 /* Checks whether a packet that arrived on 'slave_' within 'bond', with an
572  * Ethernet destination address of 'eth_dst', should be admitted.
573  *
574  * The return value is one of the following:
575  *
576  *    - BV_ACCEPT: Admit the packet.
577  *
578  *    - BV_DROP: Drop the packet.
579  *
580  *    - BV_DROP_IF_MOVED: Consult the MAC learning table for the packet's
581  *      Ethernet source address and VLAN.  If there is none, or if the packet
582  *      is on the learned port, then admit the packet.  If a different port has
583  *      been learned, however, drop the packet (and do not use it for MAC
584  *      learning).
585  */
586 enum bond_verdict
587 bond_check_admissibility(struct bond *bond, const void *slave_,
588                          const uint8_t eth_dst[ETH_ADDR_LEN], tag_type *tags)
589 {
590     /* Admit all packets if LACP has been negotiated, because that means that
591      * the remote switch is aware of the bond and will "do the right thing". */
592     if (lacp_negotiated(bond->lacp)) {
593         return BV_ACCEPT;
594     }
595
596     /* Drop all multicast packets on inactive slaves. */
597     if (eth_addr_is_multicast(eth_dst)) {
598         *tags |= bond_get_active_slave_tag(bond);
599         if (bond->active_slave != bond_slave_lookup(bond, slave_)) {
600             return BV_DROP;
601         }
602     }
603
604     /* Drop all packets for which we have learned a different input port,
605      * because we probably sent the packet on one slave and got it back on the
606      * other.  Gratuitous ARP packets are an exception to this rule: the host
607      * has moved to another switch.  The exception to the exception is if we
608      * locked the learning table to avoid reflections on bond slaves. */
609     return BV_DROP_IF_MOVED;
610 }
611
612 /* Returns the slave (registered on 'bond' by bond_slave_register()) to which
613  * a packet with the given 'flow' and 'vlan' should be forwarded.  Returns
614  * NULL if the packet should be dropped because no slaves are enabled.
615  *
616  * 'vlan' is not necessarily the same as 'flow->vlan_tci'.  First, 'vlan'
617  * should be a VID only (i.e. excluding the PCP bits).  Second,
618  * 'flow->vlan_tci' is the VLAN TCI that appeared on the packet (so it will be
619  * nonzero only for trunk ports), whereas 'vlan' is the logical VLAN that the
620  * packet belongs to (so for an access port it will be the access port's VLAN).
621  *
622  * Adds a tag to '*tags' that associates the flow with the returned slave.
623  */
624 void *
625 bond_choose_output_slave(struct bond *bond, const struct flow *flow,
626                          uint16_t vlan, tag_type *tags)
627 {
628     struct bond_slave *slave = choose_output_slave(bond, flow, vlan);
629     if (slave) {
630         *tags |= slave->tag;
631         return slave->aux;
632     } else {
633         *tags |= bond->no_slaves_tag;
634         return NULL;
635     }
636 }
637 \f
638 /* Rebalancing. */
639
640 static bool
641 bond_is_balanced(const struct bond *bond)
642 {
643     return bond->balance == BM_SLB || bond->balance == BM_TCP;
644 }
645
646 /* Notifies 'bond' that 'n_bytes' bytes were sent in 'flow' within 'vlan'. */
647 void
648 bond_account(struct bond *bond, const struct flow *flow, uint16_t vlan,
649              uint64_t n_bytes)
650 {
651
652     if (bond_is_balanced(bond)) {
653         lookup_bond_entry(bond, flow, vlan)->tx_bytes += n_bytes;
654     }
655 }
656
657 static struct bond_slave *
658 bond_slave_from_bal_node(struct list *bal)
659 {
660     return CONTAINER_OF(bal, struct bond_slave, bal_node);
661 }
662
663 static void
664 log_bals(struct bond *bond, const struct list *bals)
665 {
666     if (VLOG_IS_DBG_ENABLED()) {
667         struct ds ds = DS_EMPTY_INITIALIZER;
668         const struct bond_slave *slave;
669
670         LIST_FOR_EACH (slave, bal_node, bals) {
671             if (ds.length) {
672                 ds_put_char(&ds, ',');
673             }
674             ds_put_format(&ds, " %s %"PRIu64"kB",
675                           slave->name, slave->tx_bytes / 1024);
676
677             if (!slave->enabled) {
678                 ds_put_cstr(&ds, " (disabled)");
679             }
680             if (!list_is_empty(&slave->entries)) {
681                 struct bond_entry *e;
682
683                 ds_put_cstr(&ds, " (");
684                 LIST_FOR_EACH (e, list_node, &slave->entries) {
685                     if (&e->list_node != list_front(&slave->entries)) {
686                         ds_put_cstr(&ds, " + ");
687                     }
688                     ds_put_format(&ds, "h%td: %"PRIu64"kB",
689                                   e - bond->hash, e->tx_bytes / 1024);
690                 }
691                 ds_put_cstr(&ds, ")");
692             }
693         }
694         VLOG_DBG("bond %s:%s", bond->name, ds_cstr(&ds));
695         ds_destroy(&ds);
696     }
697 }
698
699 /* Shifts 'hash' from its current slave to 'to'. */
700 static void
701 bond_shift_load(struct bond_entry *hash, struct bond_slave *to,
702                 struct tag_set *set)
703 {
704     struct bond_slave *from = hash->slave;
705     struct bond *bond = from->bond;
706     uint64_t delta = hash->tx_bytes;
707
708     VLOG_INFO("bond %s: shift %"PRIu64"kB of load (with hash %td) "
709               "from %s to %s (now carrying %"PRIu64"kB and "
710               "%"PRIu64"kB load, respectively)",
711               bond->name, delta / 1024, hash - bond->hash,
712               from->name, to->name,
713               (from->tx_bytes - delta) / 1024,
714               (to->tx_bytes + delta) / 1024);
715
716     /* Shift load away from 'from' to 'to'. */
717     from->tx_bytes -= delta;
718     to->tx_bytes += delta;
719
720     /* Arrange for flows to be revalidated. */
721     tag_set_add(set, hash->tag);
722     hash->slave = to;
723     hash->tag = tag_create_random();
724 }
725
726 /* Pick and returns a bond_entry to migrate to 'to' (the least-loaded slave),
727  * given that doing so must decrease the ratio of the load on the two slaves by
728  * at least 0.1.  Returns NULL if there is no appropriate entry.
729  *
730  * The list of entries isn't sorted.  I don't know of a reason to prefer to
731  * shift away small hashes or large hashes. */
732 static struct bond_entry *
733 choose_entry_to_migrate(const struct bond_slave *from, uint64_t to_tx_bytes)
734 {
735     struct bond_entry *e;
736
737     if (list_is_short(&from->entries)) {
738         /* 'from' carries no more than one MAC hash, so shifting load away from
739          * it would be pointless. */
740         return NULL;
741     }
742
743     LIST_FOR_EACH (e, list_node, &from->entries) {
744         double old_ratio, new_ratio;
745         uint64_t delta;
746
747         if (to_tx_bytes == 0) {
748             /* Nothing on the new slave, move it. */
749             return e;
750         }
751
752         delta = e->tx_bytes;
753         old_ratio = (double)from->tx_bytes / to_tx_bytes;
754         new_ratio = (double)(from->tx_bytes - delta) / (to_tx_bytes + delta);
755         if (old_ratio - new_ratio > 0.1) {
756             /* Would decrease the ratio, move it. */
757             return e;
758         }
759     }
760
761     return NULL;
762 }
763
764 /* Inserts 'slave' into 'bals' so that descending order of 'tx_bytes' is
765  * maintained. */
766 static void
767 insert_bal(struct list *bals, struct bond_slave *slave)
768 {
769     struct bond_slave *pos;
770
771     LIST_FOR_EACH (pos, bal_node, bals) {
772         if (slave->tx_bytes > pos->tx_bytes) {
773             break;
774         }
775     }
776     list_insert(&pos->bal_node, &slave->bal_node);
777 }
778
779 /* Removes 'slave' from its current list and then inserts it into 'bals' so
780  * that descending order of 'tx_bytes' is maintained. */
781 static void
782 reinsert_bal(struct list *bals, struct bond_slave *slave)
783 {
784     list_remove(&slave->bal_node);
785     insert_bal(bals, slave);
786 }
787
788 /* If 'bond' needs rebalancing, does so.
789  *
790  * The caller should have called bond_account() for each active flow, to ensure
791  * that flow data is consistently accounted at this point. */
792 void
793 bond_rebalance(struct bond *bond, struct tag_set *tags)
794 {
795     struct bond_slave *slave;
796     struct bond_entry *e;
797     struct list bals;
798
799     if (!bond_is_balanced(bond) || time_msec() < bond->next_rebalance) {
800         return;
801     }
802     bond->next_rebalance = time_msec() + bond->rebalance_interval;
803
804     /* Add each bond_entry to its slave's 'entries' list.
805      * Compute each slave's tx_bytes as the sum of its entries' tx_bytes. */
806     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
807         slave->tx_bytes = 0;
808         list_init(&slave->entries);
809     }
810     for (e = &bond->hash[0]; e <= &bond->hash[BOND_MASK]; e++) {
811         if (e->slave && e->tx_bytes) {
812             e->slave->tx_bytes += e->tx_bytes;
813             list_push_back(&e->slave->entries, &e->list_node);
814         }
815     }
816
817     /* Add enabled slaves to 'bals' in descending order of tx_bytes.
818      *
819      * XXX This is O(n**2) in the number of slaves but it could be O(n lg n)
820      * with a proper list sort algorithm. */
821     list_init(&bals);
822     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
823         if (slave->enabled) {
824             insert_bal(&bals, slave);
825         }
826     }
827     log_bals(bond, &bals);
828
829     /* Shift load from the most-loaded slaves to the least-loaded slaves. */
830     while (!list_is_short(&bals)) {
831         struct bond_slave *from = bond_slave_from_bal_node(list_front(&bals));
832         struct bond_slave *to = bond_slave_from_bal_node(list_back(&bals));
833         uint64_t overload;
834
835         overload = from->tx_bytes - to->tx_bytes;
836         if (overload < to->tx_bytes >> 5 || overload < 100000) {
837             /* The extra load on 'from' (and all less-loaded slaves), compared
838              * to that of 'to' (the least-loaded slave), is less than ~3%, or
839              * it is less than ~1Mbps.  No point in rebalancing. */
840             break;
841         }
842
843         /* 'from' is carrying significantly more load than 'to', and that load
844          * is split across at least two different hashes. */
845         e = choose_entry_to_migrate(from, to->tx_bytes);
846         if (e) {
847             bond_shift_load(e, to, tags);
848
849             /* Delete element from from->entries.
850              *
851              * We don't add the element to to->hashes.  That would only allow
852              * 'e' to be migrated to another slave in this rebalancing run, and
853              * there is no point in doing that. */
854             list_remove(&e->list_node);
855
856             /* Re-sort 'bals'. */
857             reinsert_bal(&bals, from);
858             reinsert_bal(&bals, to);
859         } else {
860             /* Can't usefully migrate anything away from 'from'.
861              * Don't reconsider it. */
862             list_remove(&from->bal_node);
863         }
864     }
865
866     /* Implement exponentially weighted moving average.  A weight of 1/2 causes
867      * historical data to decay to <1% in 7 rebalancing runs.  1,000,000 bytes
868      * take 20 rebalancing runs to decay to 0 and get deleted entirely. */
869     for (e = &bond->hash[0]; e <= &bond->hash[BOND_MASK]; e++) {
870         e->tx_bytes /= 2;
871         if (!e->tx_bytes) {
872             e->slave = NULL;
873         }
874     }
875 }
876 \f
877 /* Bonding unixctl user interface functions. */
878
879 static struct bond *
880 bond_find(const char *name)
881 {
882     struct bond *bond;
883
884     HMAP_FOR_EACH_WITH_HASH (bond, hmap_node, hash_string(name, 0),
885                              &all_bonds) {
886         if (!strcmp(bond->name, name)) {
887             return bond;
888         }
889     }
890     return NULL;
891 }
892
893 static struct bond_slave *
894 bond_lookup_slave(struct bond *bond, const char *slave_name)
895 {
896     struct bond_slave *slave;
897
898     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
899         if (!strcmp(slave->name, slave_name)) {
900             return slave;
901         }
902     }
903     return NULL;
904 }
905
906 static void
907 bond_unixctl_list(struct unixctl_conn *conn,
908                   const char *args OVS_UNUSED, void *aux OVS_UNUSED)
909 {
910     struct ds ds = DS_EMPTY_INITIALIZER;
911     const struct bond *bond;
912
913     ds_put_cstr(&ds, "bond\ttype\tslaves\n");
914
915     HMAP_FOR_EACH (bond, hmap_node, &all_bonds) {
916         const struct bond_slave *slave;
917         size_t i;
918
919         ds_put_format(&ds, "%s\t%s\t",
920                       bond->name, bond_mode_to_string(bond->balance));
921
922         i = 0;
923         HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
924             if (i++ > 0) {
925                 ds_put_cstr(&ds, ", ");
926             }
927             ds_put_cstr(&ds, slave->name);
928         }
929         ds_put_char(&ds, '\n');
930     }
931     unixctl_command_reply(conn, 200, ds_cstr(&ds));
932     ds_destroy(&ds);
933 }
934
935 static void
936 bond_unixctl_show(struct unixctl_conn *conn,
937                   const char *args, void *aux OVS_UNUSED)
938 {
939     struct ds ds = DS_EMPTY_INITIALIZER;
940     const struct bond_slave *slave;
941     const struct bond *bond;
942
943     bond = bond_find(args);
944     if (!bond) {
945         unixctl_command_reply(conn, 501, "no such bond");
946         return;
947     }
948
949     ds_put_format(&ds, "bond_mode: %s\n",
950                   bond_mode_to_string(bond->balance));
951
952     if (bond->lacp) {
953         ds_put_format(&ds, "lacp: %s\n",
954                       lacp_is_active(bond->lacp) ? "active" : "passive");
955     } else {
956         ds_put_cstr(&ds, "lacp: off\n");
957     }
958
959     if (bond->balance != BM_AB) {
960         ds_put_format(&ds, "bond-hash-algorithm: %s\n",
961                       bond_is_tcp_hash(bond) ? "balance-tcp" : "balance-slb");
962     }
963
964     ds_put_format(&ds, "bond-detect-mode: %s\n",
965                   bond->monitor ? "carrier" : "miimon");
966
967     if (!bond->monitor) {
968         ds_put_format(&ds, "bond-miimon-interval: %lld\n",
969                       bond->miimon_interval);
970     }
971
972     ds_put_format(&ds, "updelay: %d ms\n", bond->updelay);
973     ds_put_format(&ds, "downdelay: %d ms\n", bond->downdelay);
974
975     if (bond_is_balanced(bond)) {
976         ds_put_format(&ds, "next rebalance: %lld ms\n",
977                       bond->next_rebalance - time_msec());
978     }
979
980     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
981         struct bond_entry *be;
982         struct flow flow;
983
984         /* Basic info. */
985         ds_put_format(&ds, "\nslave %s: %s\n",
986                       slave->name, slave->enabled ? "enabled" : "disabled");
987         if (slave == bond->active_slave) {
988             ds_put_cstr(&ds, "\tactive slave\n");
989         }
990         if (slave->delay_expires != LLONG_MAX) {
991             ds_put_format(&ds, "\t%s expires in %lld ms\n",
992                           slave->enabled ? "downdelay" : "updelay",
993                           slave->delay_expires - time_msec());
994         }
995
996         if (!bond_is_balanced(bond)) {
997             continue;
998         }
999
1000         /* Hashes. */
1001         memset(&flow, 0, sizeof flow);
1002         for (be = bond->hash; be <= &bond->hash[BOND_MASK]; be++) {
1003             int hash = be - bond->hash;
1004
1005             if (be->slave != slave) {
1006                 continue;
1007             }
1008
1009             ds_put_format(&ds, "\thash %d: %"PRIu64" kB load\n",
1010                           hash, be->tx_bytes / 1024);
1011
1012             if (bond->balance != BM_SLB) {
1013                 continue;
1014             }
1015
1016             /* XXX How can we list the MACs assigned to hashes? */
1017         }
1018     }
1019     unixctl_command_reply(conn, 200, ds_cstr(&ds));
1020     ds_destroy(&ds);
1021 }
1022
1023 static void
1024 bond_unixctl_migrate(struct unixctl_conn *conn, const char *args_,
1025                      void *aux OVS_UNUSED)
1026 {
1027     char *args = (char *) args_;
1028     char *save_ptr = NULL;
1029     char *bond_s, *hash_s, *slave_s;
1030     struct bond *bond;
1031     struct bond_slave *slave;
1032     struct bond_entry *entry;
1033     int hash;
1034
1035     bond_s = strtok_r(args, " ", &save_ptr);
1036     hash_s = strtok_r(NULL, " ", &save_ptr);
1037     slave_s = strtok_r(NULL, " ", &save_ptr);
1038     if (!slave_s) {
1039         unixctl_command_reply(conn, 501,
1040                               "usage: bond/migrate BOND HASH SLAVE");
1041         return;
1042     }
1043
1044     bond = bond_find(bond_s);
1045     if (!bond) {
1046         unixctl_command_reply(conn, 501, "no such bond");
1047         return;
1048     }
1049
1050     if (bond->balance != BM_SLB) {
1051         unixctl_command_reply(conn, 501, "not an SLB bond");
1052         return;
1053     }
1054
1055     if (strspn(hash_s, "0123456789") == strlen(hash_s)) {
1056         hash = atoi(hash_s) & BOND_MASK;
1057     } else {
1058         unixctl_command_reply(conn, 501, "bad hash");
1059         return;
1060     }
1061
1062     slave = bond_lookup_slave(bond, slave_s);
1063     if (!slave) {
1064         unixctl_command_reply(conn, 501, "no such slave");
1065         return;
1066     }
1067
1068     if (!slave->enabled) {
1069         unixctl_command_reply(conn, 501, "cannot migrate to disabled slave");
1070         return;
1071     }
1072
1073     entry = &bond->hash[hash];
1074     tag_set_add(&bond->unixctl_tags, entry->tag);
1075     entry->slave = slave;
1076     entry->tag = tag_create_random();
1077     unixctl_command_reply(conn, 200, "migrated");
1078 }
1079
1080 static void
1081 bond_unixctl_set_active_slave(struct unixctl_conn *conn, const char *args_,
1082                               void *aux OVS_UNUSED)
1083 {
1084     char *args = (char *) args_;
1085     char *save_ptr = NULL;
1086     char *bond_s, *slave_s;
1087     struct bond *bond;
1088     struct bond_slave *slave;
1089
1090     bond_s = strtok_r(args, " ", &save_ptr);
1091     slave_s = strtok_r(NULL, " ", &save_ptr);
1092     if (!slave_s) {
1093         unixctl_command_reply(conn, 501,
1094                               "usage: bond/set-active-slave BOND SLAVE");
1095         return;
1096     }
1097
1098     bond = bond_find(bond_s);
1099     if (!bond) {
1100         unixctl_command_reply(conn, 501, "no such bond");
1101         return;
1102     }
1103
1104     slave = bond_lookup_slave(bond, slave_s);
1105     if (!slave) {
1106         unixctl_command_reply(conn, 501, "no such slave");
1107         return;
1108     }
1109
1110     if (!slave->enabled) {
1111         unixctl_command_reply(conn, 501, "cannot make disabled slave active");
1112         return;
1113     }
1114
1115     if (bond->active_slave != slave) {
1116         tag_set_add(&bond->unixctl_tags, bond_get_active_slave_tag(bond));
1117         bond->active_slave = slave;
1118         bond->active_slave->tag = tag_create_random();
1119         VLOG_INFO("bond %s: active interface is now %s",
1120                   bond->name, slave->name);
1121         bond->send_learning_packets = true;
1122         unixctl_command_reply(conn, 200, "done");
1123     } else {
1124         unixctl_command_reply(conn, 200, "no change");
1125     }
1126 }
1127
1128 static void
1129 enable_slave(struct unixctl_conn *conn, const char *args_, bool enable)
1130 {
1131     char *args = (char *) args_;
1132     char *save_ptr = NULL;
1133     char *bond_s, *slave_s;
1134     struct bond *bond;
1135     struct bond_slave *slave;
1136
1137     bond_s = strtok_r(args, " ", &save_ptr);
1138     slave_s = strtok_r(NULL, " ", &save_ptr);
1139     if (!slave_s) {
1140         char *usage = xasprintf("usage: bond/%s-slave BOND SLAVE",
1141                                 enable ? "enable" : "disable");
1142         unixctl_command_reply(conn, 501, usage);
1143         free(usage);
1144         return;
1145     }
1146
1147     bond = bond_find(bond_s);
1148     if (!bond) {
1149         unixctl_command_reply(conn, 501, "no such bond");
1150         return;
1151     }
1152
1153     slave = bond_lookup_slave(bond, slave_s);
1154     if (!slave) {
1155         unixctl_command_reply(conn, 501, "no such slave");
1156         return;
1157     }
1158
1159     bond_enable_slave(slave, enable, &bond->unixctl_tags);
1160     unixctl_command_reply(conn, 501, enable ? "enabled" : "disabled");
1161 }
1162
1163 static void
1164 bond_unixctl_enable_slave(struct unixctl_conn *conn, const char *args,
1165                           void *aux OVS_UNUSED)
1166 {
1167     enable_slave(conn, args, true);
1168 }
1169
1170 static void
1171 bond_unixctl_disable_slave(struct unixctl_conn *conn, const char *args,
1172                            void *aux OVS_UNUSED)
1173 {
1174     enable_slave(conn, args, false);
1175 }
1176
1177 static void
1178 bond_unixctl_hash(struct unixctl_conn *conn, const char *args_,
1179                   void *aux OVS_UNUSED)
1180 {
1181     char *args = (char *) args_;
1182     uint8_t mac[ETH_ADDR_LEN];
1183     uint8_t hash;
1184     char *hash_cstr;
1185     unsigned int vlan;
1186     char *mac_s, *vlan_s;
1187     char *save_ptr = NULL;
1188
1189     mac_s  = strtok_r(args, " ", &save_ptr);
1190     vlan_s = strtok_r(NULL, " ", &save_ptr);
1191
1192     if (vlan_s) {
1193         if (sscanf(vlan_s, "%u", &vlan) != 1) {
1194             unixctl_command_reply(conn, 501, "invalid vlan");
1195             return;
1196         }
1197     } else {
1198         vlan = OFP_VLAN_NONE;
1199     }
1200
1201     if (sscanf(mac_s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
1202         == ETH_ADDR_SCAN_COUNT) {
1203         hash = bond_hash_src(mac, vlan) & BOND_MASK;
1204
1205         hash_cstr = xasprintf("%u", hash);
1206         unixctl_command_reply(conn, 200, hash_cstr);
1207         free(hash_cstr);
1208     } else {
1209         unixctl_command_reply(conn, 501, "invalid mac");
1210     }
1211 }
1212
1213 void
1214 bond_init(void)
1215 {
1216     unixctl_command_register("bond/list", bond_unixctl_list, NULL);
1217     unixctl_command_register("bond/show", bond_unixctl_show, NULL);
1218     unixctl_command_register("bond/migrate", bond_unixctl_migrate, NULL);
1219     unixctl_command_register("bond/set-active-slave",
1220                              bond_unixctl_set_active_slave, NULL);
1221     unixctl_command_register("bond/enable-slave", bond_unixctl_enable_slave,
1222                              NULL);
1223     unixctl_command_register("bond/disable-slave", bond_unixctl_disable_slave,
1224                              NULL);
1225     unixctl_command_register("bond/hash", bond_unixctl_hash, NULL);
1226 }
1227 \f
1228 static void
1229 bond_entry_reset(struct bond *bond)
1230 {
1231     if (bond->balance != BM_AB) {
1232         size_t hash_len = (BOND_MASK + 1) * sizeof *bond->hash;
1233
1234         if (!bond->hash) {
1235             bond->hash = xmalloc(hash_len);
1236         }
1237         memset(bond->hash, 0, hash_len);
1238
1239         bond->next_rebalance = time_msec() + bond->rebalance_interval;
1240     } else {
1241         free(bond->hash);
1242         bond->hash = NULL;
1243     }
1244 }
1245
1246 static struct bond_slave *
1247 bond_slave_lookup(struct bond *bond, const void *slave_)
1248 {
1249     struct bond_slave *slave;
1250
1251     HMAP_FOR_EACH_IN_BUCKET (slave, hmap_node, hash_pointer(slave_, 0),
1252                              &bond->slaves) {
1253         if (slave->aux == slave_) {
1254             return slave;
1255         }
1256     }
1257
1258     return NULL;
1259 }
1260
1261 static bool
1262 bond_is_link_up(struct bond *bond, struct netdev *netdev)
1263 {
1264     return (bond->detect == BLSM_CARRIER
1265             ? netdev_get_carrier(netdev)
1266             : netdev_get_miimon(netdev));
1267 }
1268
1269 static int
1270 bond_stb_sort_cmp__(const void *a_, const void *b_)
1271 {
1272     const struct bond_slave *const *ap = a_;
1273     const struct bond_slave *const *bp = b_;
1274     const struct bond_slave *a = *ap;
1275     const struct bond_slave *b = *bp;
1276     const struct lacp *lacp = a->bond->lacp;
1277     int a_id, b_id;
1278
1279     if (lacp) {
1280         a_id = lacp_slave_get_port_id(lacp, a->aux);
1281         b_id = lacp_slave_get_port_id(lacp, b->aux);
1282     } else {
1283         a_id = netdev_get_ifindex(a->netdev);
1284         b_id = netdev_get_ifindex(b->netdev);
1285     }
1286
1287     return (a_id == b_id ? 0 : (a_id < b_id ? -1 : 1));
1288 }
1289
1290 static bool
1291 bond_stb_sort(struct bond *bond)
1292 {
1293     size_t i;
1294
1295     if (!bond->stb_slaves || !bond->stb_need_sort) {
1296         return false;
1297     }
1298     bond->stb_need_sort = false;
1299
1300     qsort(bond->stb_slaves, bond->n_stb_slaves, sizeof *bond->stb_slaves,
1301           bond_stb_sort_cmp__);
1302
1303     for (i = 0; i < bond->n_stb_slaves; i++) {
1304         bond->stb_slaves[i]->stb_idx = i;
1305     }
1306
1307     return true;
1308 }
1309
1310 static void
1311 bond_stb_enable_slave(struct bond_slave *slave)
1312 {
1313     struct bond *bond = slave->bond;
1314
1315     if (!bond->stb_slaves) {
1316         return;
1317     }
1318
1319     bond->stb_need_sort = true;
1320
1321     if (slave->enabled) {
1322         if (bond->len_stb_slaves <= bond->n_stb_slaves) {
1323             bond->stb_slaves = x2nrealloc(bond->stb_slaves,
1324                                           &bond->len_stb_slaves,
1325                                           sizeof *bond->stb_slaves);
1326         }
1327
1328         slave->stb_idx = bond->n_stb_slaves++;
1329         bond->stb_slaves[slave->stb_idx] = slave;
1330     } else {
1331         size_t index = slave->stb_idx;
1332         bond->stb_slaves[index] = bond->stb_slaves[--bond->n_stb_slaves];
1333         bond->stb_slaves[index]->stb_idx = index;
1334     }
1335 }
1336
1337 static void
1338 bond_enable_slave(struct bond_slave *slave, bool enable, struct tag_set *tags)
1339 {
1340     slave->delay_expires = LLONG_MAX;
1341     if (enable != slave->enabled) {
1342         slave->enabled = enable;
1343         if (!slave->enabled) {
1344             VLOG_WARN("interface %s: disabled", slave->name);
1345             if (tags) {
1346                 tag_set_add(tags, slave->tag);
1347             }
1348         } else {
1349             VLOG_WARN("interface %s: enabled", slave->name);
1350             slave->tag = tag_create_random();
1351         }
1352         bond_stb_enable_slave(slave);
1353     }
1354 }
1355
1356 static void
1357 bond_link_status_update(struct bond_slave *slave, struct tag_set *tags)
1358 {
1359     struct bond *bond = slave->bond;
1360     bool up;
1361
1362     up = slave->up && lacp_slave_may_enable(bond->lacp, slave->aux);
1363     if ((up == slave->enabled) != (slave->delay_expires == LLONG_MAX)) {
1364         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1365         VLOG_INFO_RL(&rl, "interface %s: link state %s",
1366                      slave->name, up ? "up" : "down");
1367         if (up == slave->enabled) {
1368             slave->delay_expires = LLONG_MAX;
1369             VLOG_INFO_RL(&rl, "interface %s: will not be %s",
1370                          slave->name, up ? "disabled" : "enabled");
1371         } else {
1372             int delay = (lacp_negotiated(bond->lacp) ? 0
1373                          : up ? bond->updelay : bond->downdelay);
1374             slave->delay_expires = time_msec() + delay;
1375             if (delay) {
1376                 VLOG_INFO_RL(&rl, "interface %s: will be %s if it stays %s "
1377                              "for %d ms",
1378                              slave->name,
1379                              up ? "enabled" : "disabled",
1380                              up ? "up" : "down",
1381                              delay);
1382             }
1383         }
1384     }
1385
1386     if (time_msec() >= slave->delay_expires) {
1387         bond_enable_slave(slave, up, tags);
1388     }
1389 }
1390
1391 static bool
1392 bond_is_tcp_hash(const struct bond *bond)
1393 {
1394     return (bond->balance == BM_TCP || bond->balance == BM_STABLE)
1395         && lacp_negotiated(bond->lacp);
1396 }
1397
1398 static unsigned int
1399 bond_hash_src(const uint8_t mac[ETH_ADDR_LEN], uint16_t vlan)
1400 {
1401     return hash_bytes(mac, ETH_ADDR_LEN, vlan);
1402 }
1403
1404 static unsigned int
1405 bond_hash_tcp(const struct flow *flow, uint16_t vlan)
1406 {
1407     struct flow hash_flow = *flow;
1408     hash_flow.vlan_tci = vlan;
1409
1410     /* The symmetric quality of this hash function is not required, but
1411      * flow_hash_symmetric_l4 already exists, and is sufficient for our
1412      * purposes, so we use it out of convenience. */
1413     return flow_hash_symmetric_l4(&hash_flow, 0);
1414 }
1415
1416 static unsigned int
1417 bond_hash(const struct bond *bond, const struct flow *flow, uint16_t vlan)
1418 {
1419     assert(bond->balance != BM_AB);
1420
1421     return (bond_is_tcp_hash(bond)
1422             ? bond_hash_tcp(flow, vlan)
1423             : bond_hash_src(flow->dl_src, vlan));
1424 }
1425
1426 static struct bond_entry *
1427 lookup_bond_entry(const struct bond *bond, const struct flow *flow,
1428                   uint16_t vlan)
1429 {
1430     return &bond->hash[bond_hash(bond, flow, vlan) & BOND_MASK];
1431 }
1432
1433 static struct bond_slave *
1434 choose_output_slave(const struct bond *bond, const struct flow *flow,
1435                     uint16_t vlan)
1436 {
1437     struct bond_entry *e;
1438
1439     switch (bond->balance) {
1440     case BM_AB:
1441         return bond->active_slave;
1442
1443     case BM_STABLE:
1444         if (bond->n_stb_slaves) {
1445             return bond->stb_slaves[bond_hash(bond, flow, vlan)
1446                 % bond->n_stb_slaves];
1447         } else {
1448             return bond->active_slave;
1449         }
1450
1451     case BM_SLB:
1452     case BM_TCP:
1453         e = lookup_bond_entry(bond, flow, vlan);
1454         if (!e->slave || !e->slave->enabled) {
1455             e->slave = CONTAINER_OF(hmap_random_node(&bond->slaves),
1456                                     struct bond_slave, hmap_node);
1457             if (!e->slave->enabled) {
1458                 e->slave = bond->active_slave;
1459             }
1460             e->tag = tag_create_random();
1461         }
1462         return e->slave;
1463
1464     default:
1465         NOT_REACHED();
1466     }
1467 }
1468
1469 static struct bond_slave *
1470 bond_choose_slave(const struct bond *bond)
1471 {
1472     struct bond_slave *slave, *best;
1473
1474     /* Find an enabled slave. */
1475     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1476         if (slave->enabled) {
1477             return slave;
1478         }
1479     }
1480
1481     /* All interfaces are disabled.  Find an interface that will be enabled
1482      * after its updelay expires.  */
1483     best = NULL;
1484     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1485         if (slave->delay_expires != LLONG_MAX
1486             && lacp_slave_may_enable(bond->lacp, slave->aux)
1487             && (!best || slave->delay_expires < best->delay_expires)) {
1488             best = slave;
1489         }
1490     }
1491     return best;
1492 }
1493
1494 static void
1495 bond_choose_active_slave(struct bond *bond, struct tag_set *tags)
1496 {
1497     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1498     struct bond_slave *old_active_slave = bond->active_slave;
1499
1500     bond->active_slave = bond_choose_slave(bond);
1501     if (bond->active_slave) {
1502         if (bond->active_slave->enabled) {
1503             VLOG_INFO_RL(&rl, "bond %s: active interface is now %s",
1504                          bond->name, bond->active_slave->name);
1505         } else {
1506             VLOG_INFO_RL(&rl, "bond %s: active interface is now %s, skipping "
1507                          "remaining %lld ms updelay (since no interface was "
1508                          "enabled)", bond->name, bond->active_slave->name,
1509                          bond->active_slave->delay_expires - time_msec());
1510             bond_enable_slave(bond->active_slave, true, tags);
1511         }
1512
1513         if (!old_active_slave) {
1514             tag_set_add(tags, bond->no_slaves_tag);
1515         }
1516
1517         bond->send_learning_packets = true;
1518     } else if (old_active_slave) {
1519         VLOG_WARN_RL(&rl, "bond %s: all interfaces disabled", bond->name);
1520     }
1521 }
1522
1523 /* Returns the tag for 'bond''s active slave, or 'bond''s no_slaves_tag if
1524  * there is no active slave. */
1525 static tag_type
1526 bond_get_active_slave_tag(const struct bond *bond)
1527 {
1528     return (bond->active_slave
1529             ? bond->active_slave->tag
1530             : bond->no_slaves_tag);
1531 }
1532
1533 /* Attempts to make the sum of the bond slaves' statistics appear on the fake
1534  * bond interface. */
1535 static void
1536 bond_update_fake_slave_stats(struct bond *bond)
1537 {
1538     struct netdev_stats bond_stats;
1539     struct bond_slave *slave;
1540     struct netdev *bond_dev;
1541
1542     memset(&bond_stats, 0, sizeof bond_stats);
1543
1544     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1545         struct netdev_stats slave_stats;
1546
1547         if (!netdev_get_stats(slave->netdev, &slave_stats)) {
1548             /* XXX: We swap the stats here because they are swapped back when
1549              * reported by the internal device.  The reason for this is
1550              * internal devices normally represent packets going into the
1551              * system but when used as fake bond device they represent packets
1552              * leaving the system.  We really should do this in the internal
1553              * device itself because changing it here reverses the counts from
1554              * the perspective of the switch.  However, the internal device
1555              * doesn't know what type of device it represents so we have to do
1556              * it here for now. */
1557             bond_stats.tx_packets += slave_stats.rx_packets;
1558             bond_stats.tx_bytes += slave_stats.rx_bytes;
1559             bond_stats.rx_packets += slave_stats.tx_packets;
1560             bond_stats.rx_bytes += slave_stats.tx_bytes;
1561         }
1562     }
1563
1564     if (!netdev_open_default(bond->name, &bond_dev)) {
1565         netdev_set_stats(bond_dev, &bond_stats);
1566         netdev_close(bond_dev);
1567     }
1568 }