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