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