bond: Revalidate when lacp_negotiated status changes.
[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 "shash.h"
36 #include "tag.h"
37 #include "timeval.h"
38 #include "unixctl.h"
39 #include "vlog.h"
40
41 VLOG_DEFINE_THIS_MODULE(bond);
42
43 /* Bit-mask for hashing a flow down to a bucket.
44  * There are (BOND_MASK + 1) buckets. */
45 #define BOND_MASK 0xff
46
47 /* A hash bucket for mapping a flow to a slave.
48  * "struct bond" has an array of (BOND_MASK + 1) of these. */
49 struct bond_entry {
50     struct bond_slave *slave;   /* Assigned slave, NULL if unassigned. */
51     uint64_t tx_bytes;          /* Count of bytes recently transmitted. */
52     tag_type tag;               /* Tag for entry<->slave association. */
53     struct list list_node;      /* In bond_slave's 'entries' list. */
54 };
55
56 /* A bond slave, that is, one of the links comprising a bond. */
57 struct bond_slave {
58     struct hmap_node hmap_node; /* In struct bond's slaves hmap. */
59     struct bond *bond;          /* The bond that contains this slave. */
60     void *aux;                  /* Client-provided handle for this slave. */
61
62     struct netdev *netdev;      /* Network device, owned by the client. */
63     unsigned int change_seq;    /* Tracks changes in 'netdev'. */
64     char *name;                 /* Name (a copy of netdev_get_name(netdev)). */
65
66     /* Link status. */
67     long long delay_expires;    /* Time after which 'enabled' may change. */
68     bool enabled;               /* May be chosen for flows? */
69     bool may_enable;            /* Client considers this slave bondable. */
70     tag_type tag;               /* Tag associated with this slave. */
71
72     /* Rebalancing info.  Used only by bond_rebalance(). */
73     struct list bal_node;       /* In bond_rebalance()'s 'bals' list. */
74     struct list entries;        /* 'struct bond_entry's assigned here. */
75     uint64_t tx_bytes;          /* Sum across 'tx_bytes' of entries. */
76
77     /* BM_STABLE specific bonding info. */
78     uint32_t stb_id;            /* ID used for 'stb_slaves' ordering. */
79 };
80
81 /* A bond, that is, a set of network devices grouped to improve performance or
82  * robustness.  */
83 struct bond {
84     struct hmap_node hmap_node; /* In 'all_bonds' hmap. */
85     char *name;                 /* Name provided by client. */
86
87     /* Slaves. */
88     struct hmap slaves;
89
90     /* Bonding info. */
91     enum bond_mode balance;     /* Balancing mode, one of BM_*. */
92     struct bond_slave *active_slave;
93     tag_type no_slaves_tag;     /* Tag for flows when all slaves disabled. */
94     int updelay, downdelay;     /* Delay before slave goes up/down, in ms. */
95     bool lacp_negotiated;       /* LACP negotiations were successful. */
96     bool bond_revalidate;       /* True if flows need revalidation. */
97     uint32_t basis;             /* Basis for flow hash function. */
98
99     /* SLB specific bonding info. */
100     struct bond_entry *hash;     /* An array of (BOND_MASK + 1) elements. */
101     int rebalance_interval;      /* Interval between rebalances, in ms. */
102     long long int next_rebalance; /* Next rebalancing time. */
103     bool send_learning_packets;
104
105     /* BM_STABLE specific bonding info. */
106     tag_type stb_tag;               /* Tag associated with this bond. */
107
108     /* Legacy compatibility. */
109     long long int next_fake_iface_update; /* LLONG_MAX if disabled. */
110
111     /* Tag set saved for next bond_run().  This tag set is a kluge for cases
112      * where we can't otherwise provide revalidation feedback to the client.
113      * That's only unixctl commands now; I hope no other cases will arise. */
114     struct tag_set unixctl_tags;
115 };
116
117 static struct hmap all_bonds = HMAP_INITIALIZER(&all_bonds);
118
119 static void bond_entry_reset(struct bond *);
120 static struct bond_slave *bond_slave_lookup(struct bond *, const void *slave_);
121 static void bond_enable_slave(struct bond_slave *, bool enable,
122                               struct tag_set *);
123 static void bond_link_status_update(struct bond_slave *, struct tag_set *);
124 static void bond_choose_active_slave(struct bond *, struct tag_set *);
125 static bool bond_is_tcp_hash(const struct bond *);
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, bool lacp_negotiated)
406 {
407     struct bond_slave *slave;
408     bool is_tcp_hash = bond_is_tcp_hash(bond);
409
410     if (bond->lacp_negotiated != lacp_negotiated) {
411         bond->lacp_negotiated = lacp_negotiated;
412         bond->bond_revalidate = true;
413     }
414
415     /* Enable slaves based on link status and LACP feedback. */
416     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
417         bond_link_status_update(slave, tags);
418         slave->change_seq = netdev_change_seq(slave->netdev);
419     }
420     if (!bond->active_slave || !bond->active_slave->enabled) {
421         bond_choose_active_slave(bond, tags);
422     }
423
424     /* Update fake bond interface stats. */
425     if (time_msec() >= bond->next_fake_iface_update) {
426         bond_update_fake_slave_stats(bond);
427         bond->next_fake_iface_update = time_msec() + 1000;
428     }
429
430     if (is_tcp_hash != bond_is_tcp_hash(bond)) {
431         bond->bond_revalidate = true;
432     }
433
434     if (bond->bond_revalidate) {
435         bond->bond_revalidate = false;
436
437         bond_entry_reset(bond);
438         if (bond->balance != BM_STABLE) {
439             struct bond_slave *slave;
440
441             HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
442                 tag_set_add(tags, slave->tag);
443             }
444         } else {
445             tag_set_add(tags, bond->stb_tag);
446         }
447         tag_set_add(tags, bond->no_slaves_tag);
448     }
449
450     /* Invalidate any tags required by  */
451     tag_set_union(tags, &bond->unixctl_tags);
452     tag_set_init(&bond->unixctl_tags);
453 }
454
455 /* Causes poll_block() to wake up when 'bond' needs something to be done. */
456 void
457 bond_wait(struct bond *bond)
458 {
459     struct bond_slave *slave;
460
461     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
462         if (slave->delay_expires != LLONG_MAX) {
463             poll_timer_wait_until(slave->delay_expires);
464         }
465
466         if (slave->change_seq != netdev_change_seq(slave->netdev)) {
467             poll_immediate_wake();
468         }
469     }
470
471     if (bond->next_fake_iface_update != LLONG_MAX) {
472         poll_timer_wait_until(bond->next_fake_iface_update);
473     }
474
475     /* Ensure that any saved tags get revalidated right away. */
476     if (!tag_set_is_empty(&bond->unixctl_tags)) {
477         poll_immediate_wake();
478     }
479
480     /* We don't wait for bond->next_rebalance because rebalancing can only run
481      * at a flow account checkpoint.  ofproto does checkpointing on its own
482      * schedule and bond_rebalance() gets called afterward, so we'd just be
483      * waking up for no purpose. */
484 }
485 \f
486 /* MAC learning table interaction. */
487
488 static bool
489 may_send_learning_packets(const struct bond *bond)
490 {
491     return !bond->lacp_negotiated && bond->balance != BM_AB &&
492            bond->active_slave;
493 }
494
495 /* Returns true if 'bond' needs the client to send out packets to assist with
496  * MAC learning on 'bond'.  If this function returns true, then the client
497  * should iterate through its MAC learning table for the bridge on which 'bond'
498  * is located.  For each MAC that has been learned on a port other than 'bond',
499  * it should call bond_compose_learning_packet().
500  *
501  * This function will only return true if 'bond' is in SLB mode and LACP is not
502  * negotiated.  Otherwise sending learning packets isn't necessary.
503  *
504  * Calling this function resets the state that it checks. */
505 bool
506 bond_should_send_learning_packets(struct bond *bond)
507 {
508     bool send = bond->send_learning_packets && may_send_learning_packets(bond);
509     bond->send_learning_packets = false;
510     return send;
511 }
512
513 /* Sends a gratuitous learning packet on 'bond' from 'eth_src' on 'vlan'.
514  *
515  * See bond_should_send_learning_packets() for description of usage. The
516  * caller should send the composed packet on the port associated with
517  * port_aux and takes ownership of the returned ofpbuf. */
518 struct ofpbuf *
519 bond_compose_learning_packet(struct bond *bond,
520                              const uint8_t eth_src[ETH_ADDR_LEN],
521                              uint16_t vlan, void **port_aux)
522 {
523     struct bond_slave *slave;
524     struct ofpbuf *packet;
525     struct flow flow;
526
527     assert(may_send_learning_packets(bond));
528
529     memset(&flow, 0, sizeof flow);
530     memcpy(flow.dl_src, eth_src, ETH_ADDR_LEN);
531     slave = choose_output_slave(bond, &flow, vlan);
532
533     packet = ofpbuf_new(0);
534     compose_benign_packet(packet, "Open vSwitch Bond Failover", 0xf177,
535                           eth_src);
536     if (vlan) {
537         eth_push_vlan(packet, htons(vlan));
538     }
539
540     *port_aux = slave->aux;
541     return packet;
542 }
543 \f
544 /* Checks whether a packet that arrived on 'slave_' within 'bond', with an
545  * Ethernet destination address of 'eth_dst', should be admitted.
546  *
547  * The return value is one of the following:
548  *
549  *    - BV_ACCEPT: Admit the packet.
550  *
551  *    - BV_DROP: Drop the packet.
552  *
553  *    - BV_DROP_IF_MOVED: Consult the MAC learning table for the packet's
554  *      Ethernet source address and VLAN.  If there is none, or if the packet
555  *      is on the learned port, then admit the packet.  If a different port has
556  *      been learned, however, drop the packet (and do not use it for MAC
557  *      learning).
558  */
559 enum bond_verdict
560 bond_check_admissibility(struct bond *bond, const void *slave_,
561                          const uint8_t eth_dst[ETH_ADDR_LEN], tag_type *tags)
562 {
563     struct bond_slave *slave = bond_slave_lookup(bond, slave_);
564
565     /* LACP bonds have very loose admissibility restrictions because we can
566      * assume the remote switch is aware of the bond and will "do the right
567      * thing".  However, as a precaution we drop packets on disabled slaves
568      * because no correctly implemented partner switch should be sending
569      * packets to them. */
570     if (bond->lacp_negotiated) {
571         return slave->enabled ? BV_ACCEPT : BV_DROP;
572     }
573
574     /* Drop all multicast packets on inactive slaves. */
575     if (eth_addr_is_multicast(eth_dst)) {
576         *tags |= bond_get_active_slave_tag(bond);
577         if (bond->active_slave != bond_slave_lookup(bond, slave_)) {
578             return BV_DROP;
579         }
580     }
581
582     switch (bond->balance) {
583     case BM_AB:
584         /* Drop all packets which arrive on backup slaves.  This is similar to
585          * how Linux bonding handles active-backup bonds. */
586         *tags |= bond_get_active_slave_tag(bond);
587         if (bond->active_slave != slave) {
588             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
589
590             VLOG_DBG_RL(&rl, "active-backup bond received packet on backup"
591                         " slave (%s) destined for " ETH_ADDR_FMT,
592                         slave->name, ETH_ADDR_ARGS(eth_dst));
593             return BV_DROP;
594         }
595         return BV_ACCEPT;
596
597     case BM_TCP:
598         /* TCP balancing has degraded to SLB (otherwise the
599          * bond->lacp_negotiated check above would have processed this).
600          *
601          * Fall through. */
602     case BM_SLB:
603         /* Drop all packets for which we have learned a different input port,
604          * because we probably sent the packet on one slave and got it back on
605          * the other.  Gratuitous ARP packets are an exception to this rule:
606          * the host has moved to another switch.  The exception to the
607          * exception is if we locked the learning table to avoid reflections on
608          * bond slaves. */
609         return BV_DROP_IF_MOVED;
610
611     case BM_STABLE:
612         return BV_ACCEPT;
613     }
614
615     NOT_REACHED();
616 }
617
618 /* Returns the slave (registered on 'bond' by bond_slave_register()) to which
619  * a packet with the given 'flow' and 'vlan' should be forwarded.  Returns
620  * NULL if the packet should be dropped because no slaves are enabled.
621  *
622  * 'vlan' is not necessarily the same as 'flow->vlan_tci'.  First, 'vlan'
623  * should be a VID only (i.e. excluding the PCP bits).  Second,
624  * 'flow->vlan_tci' is the VLAN TCI that appeared on the packet (so it will be
625  * nonzero only for trunk ports), whereas 'vlan' is the logical VLAN that the
626  * packet belongs to (so for an access port it will be the access port's VLAN).
627  *
628  * Adds a tag to '*tags' that associates the flow with the returned slave.
629  */
630 void *
631 bond_choose_output_slave(struct bond *bond, const struct flow *flow,
632                          uint16_t vlan, tag_type *tags)
633 {
634     struct bond_slave *slave = choose_output_slave(bond, flow, vlan);
635     if (slave) {
636         *tags |= bond->balance == BM_STABLE ? bond->stb_tag : slave->tag;
637         return slave->aux;
638     } else {
639         *tags |= bond->no_slaves_tag;
640         return NULL;
641     }
642 }
643 \f
644 /* Rebalancing. */
645
646 static bool
647 bond_is_balanced(const struct bond *bond)
648 {
649     return bond->balance == BM_SLB || bond->balance == BM_TCP;
650 }
651
652 /* Notifies 'bond' that 'n_bytes' bytes were sent in 'flow' within 'vlan'. */
653 void
654 bond_account(struct bond *bond, const struct flow *flow, uint16_t vlan,
655              uint64_t n_bytes)
656 {
657     if (bond_is_balanced(bond)) {
658         lookup_bond_entry(bond, flow, vlan)->tx_bytes += n_bytes;
659     }
660 }
661
662 static struct bond_slave *
663 bond_slave_from_bal_node(struct list *bal)
664 {
665     return CONTAINER_OF(bal, struct bond_slave, bal_node);
666 }
667
668 static void
669 log_bals(struct bond *bond, const struct list *bals)
670 {
671     if (VLOG_IS_DBG_ENABLED()) {
672         struct ds ds = DS_EMPTY_INITIALIZER;
673         const struct bond_slave *slave;
674
675         LIST_FOR_EACH (slave, bal_node, bals) {
676             if (ds.length) {
677                 ds_put_char(&ds, ',');
678             }
679             ds_put_format(&ds, " %s %"PRIu64"kB",
680                           slave->name, slave->tx_bytes / 1024);
681
682             if (!slave->enabled) {
683                 ds_put_cstr(&ds, " (disabled)");
684             }
685             if (!list_is_empty(&slave->entries)) {
686                 struct bond_entry *e;
687
688                 ds_put_cstr(&ds, " (");
689                 LIST_FOR_EACH (e, list_node, &slave->entries) {
690                     if (&e->list_node != list_front(&slave->entries)) {
691                         ds_put_cstr(&ds, " + ");
692                     }
693                     ds_put_format(&ds, "h%td: %"PRIu64"kB",
694                                   e - bond->hash, e->tx_bytes / 1024);
695                 }
696                 ds_put_cstr(&ds, ")");
697             }
698         }
699         VLOG_DBG("bond %s:%s", bond->name, ds_cstr(&ds));
700         ds_destroy(&ds);
701     }
702 }
703
704 /* Shifts 'hash' from its current slave to 'to'. */
705 static void
706 bond_shift_load(struct bond_entry *hash, struct bond_slave *to,
707                 struct tag_set *set)
708 {
709     struct bond_slave *from = hash->slave;
710     struct bond *bond = from->bond;
711     uint64_t delta = hash->tx_bytes;
712
713     VLOG_INFO("bond %s: shift %"PRIu64"kB of load (with hash %td) "
714               "from %s to %s (now carrying %"PRIu64"kB and "
715               "%"PRIu64"kB load, respectively)",
716               bond->name, delta / 1024, hash - bond->hash,
717               from->name, to->name,
718               (from->tx_bytes - delta) / 1024,
719               (to->tx_bytes + delta) / 1024);
720
721     /* Shift load away from 'from' to 'to'. */
722     from->tx_bytes -= delta;
723     to->tx_bytes += delta;
724
725     /* Arrange for flows to be revalidated. */
726     tag_set_add(set, hash->tag);
727     hash->slave = to;
728     hash->tag = tag_create_random();
729 }
730
731 /* Pick and returns a bond_entry to migrate to 'to' (the least-loaded slave),
732  * given that doing so must decrease the ratio of the load on the two slaves by
733  * at least 0.1.  Returns NULL if there is no appropriate entry.
734  *
735  * The list of entries isn't sorted.  I don't know of a reason to prefer to
736  * shift away small hashes or large hashes. */
737 static struct bond_entry *
738 choose_entry_to_migrate(const struct bond_slave *from, uint64_t to_tx_bytes)
739 {
740     struct bond_entry *e;
741
742     if (list_is_short(&from->entries)) {
743         /* 'from' carries no more than one MAC hash, so shifting load away from
744          * it would be pointless. */
745         return NULL;
746     }
747
748     LIST_FOR_EACH (e, list_node, &from->entries) {
749         double old_ratio, new_ratio;
750         uint64_t delta;
751
752         if (to_tx_bytes == 0) {
753             /* Nothing on the new slave, move it. */
754             return e;
755         }
756
757         delta = e->tx_bytes;
758         old_ratio = (double)from->tx_bytes / to_tx_bytes;
759         new_ratio = (double)(from->tx_bytes - delta) / (to_tx_bytes + delta);
760         if (old_ratio - new_ratio > 0.1) {
761             /* Would decrease the ratio, move it. */
762             return e;
763         }
764     }
765
766     return NULL;
767 }
768
769 /* Inserts 'slave' into 'bals' so that descending order of 'tx_bytes' is
770  * maintained. */
771 static void
772 insert_bal(struct list *bals, struct bond_slave *slave)
773 {
774     struct bond_slave *pos;
775
776     LIST_FOR_EACH (pos, bal_node, bals) {
777         if (slave->tx_bytes > pos->tx_bytes) {
778             break;
779         }
780     }
781     list_insert(&pos->bal_node, &slave->bal_node);
782 }
783
784 /* Removes 'slave' from its current list and then inserts it into 'bals' so
785  * that descending order of 'tx_bytes' is maintained. */
786 static void
787 reinsert_bal(struct list *bals, struct bond_slave *slave)
788 {
789     list_remove(&slave->bal_node);
790     insert_bal(bals, slave);
791 }
792
793 /* If 'bond' needs rebalancing, does so.
794  *
795  * The caller should have called bond_account() for each active flow, to ensure
796  * that flow data is consistently accounted at this point. */
797 void
798 bond_rebalance(struct bond *bond, struct tag_set *tags)
799 {
800     struct bond_slave *slave;
801     struct bond_entry *e;
802     struct list bals;
803
804     if (!bond_is_balanced(bond) || time_msec() < bond->next_rebalance) {
805         return;
806     }
807     bond->next_rebalance = time_msec() + bond->rebalance_interval;
808
809     /* Add each bond_entry to its slave's 'entries' list.
810      * Compute each slave's tx_bytes as the sum of its entries' tx_bytes. */
811     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
812         slave->tx_bytes = 0;
813         list_init(&slave->entries);
814     }
815     for (e = &bond->hash[0]; e <= &bond->hash[BOND_MASK]; e++) {
816         if (e->slave && e->tx_bytes) {
817             e->slave->tx_bytes += e->tx_bytes;
818             list_push_back(&e->slave->entries, &e->list_node);
819         }
820     }
821
822     /* Add enabled slaves to 'bals' in descending order of tx_bytes.
823      *
824      * XXX This is O(n**2) in the number of slaves but it could be O(n lg n)
825      * with a proper list sort algorithm. */
826     list_init(&bals);
827     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
828         if (slave->enabled) {
829             insert_bal(&bals, slave);
830         }
831     }
832     log_bals(bond, &bals);
833
834     /* Shift load from the most-loaded slaves to the least-loaded slaves. */
835     while (!list_is_short(&bals)) {
836         struct bond_slave *from = bond_slave_from_bal_node(list_front(&bals));
837         struct bond_slave *to = bond_slave_from_bal_node(list_back(&bals));
838         uint64_t overload;
839
840         overload = from->tx_bytes - to->tx_bytes;
841         if (overload < to->tx_bytes >> 5 || overload < 100000) {
842             /* The extra load on 'from' (and all less-loaded slaves), compared
843              * to that of 'to' (the least-loaded slave), is less than ~3%, or
844              * it is less than ~1Mbps.  No point in rebalancing. */
845             break;
846         }
847
848         /* 'from' is carrying significantly more load than 'to', and that load
849          * is split across at least two different hashes. */
850         e = choose_entry_to_migrate(from, to->tx_bytes);
851         if (e) {
852             bond_shift_load(e, to, tags);
853
854             /* Delete element from from->entries.
855              *
856              * We don't add the element to to->hashes.  That would only allow
857              * 'e' to be migrated to another slave in this rebalancing run, and
858              * there is no point in doing that. */
859             list_remove(&e->list_node);
860
861             /* Re-sort 'bals'. */
862             reinsert_bal(&bals, from);
863             reinsert_bal(&bals, to);
864         } else {
865             /* Can't usefully migrate anything away from 'from'.
866              * Don't reconsider it. */
867             list_remove(&from->bal_node);
868         }
869     }
870
871     /* Implement exponentially weighted moving average.  A weight of 1/2 causes
872      * historical data to decay to <1% in 7 rebalancing runs.  1,000,000 bytes
873      * take 20 rebalancing runs to decay to 0 and get deleted entirely. */
874     for (e = &bond->hash[0]; e <= &bond->hash[BOND_MASK]; e++) {
875         e->tx_bytes /= 2;
876         if (!e->tx_bytes) {
877             e->slave = NULL;
878         }
879     }
880 }
881 \f
882 /* Bonding unixctl user interface functions. */
883
884 static struct bond *
885 bond_find(const char *name)
886 {
887     struct bond *bond;
888
889     HMAP_FOR_EACH_WITH_HASH (bond, hmap_node, hash_string(name, 0),
890                              &all_bonds) {
891         if (!strcmp(bond->name, name)) {
892             return bond;
893         }
894     }
895     return NULL;
896 }
897
898 static struct bond_slave *
899 bond_lookup_slave(struct bond *bond, const char *slave_name)
900 {
901     struct bond_slave *slave;
902
903     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
904         if (!strcmp(slave->name, slave_name)) {
905             return slave;
906         }
907     }
908     return NULL;
909 }
910
911 static void
912 bond_unixctl_list(struct unixctl_conn *conn,
913                   int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
914                   void *aux OVS_UNUSED)
915 {
916     struct ds ds = DS_EMPTY_INITIALIZER;
917     const struct bond *bond;
918
919     ds_put_cstr(&ds, "bond\ttype\tslaves\n");
920
921     HMAP_FOR_EACH (bond, hmap_node, &all_bonds) {
922         const struct bond_slave *slave;
923         size_t i;
924
925         ds_put_format(&ds, "%s\t%s\t",
926                       bond->name, bond_mode_to_string(bond->balance));
927
928         i = 0;
929         HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
930             if (i++ > 0) {
931                 ds_put_cstr(&ds, ", ");
932             }
933             ds_put_cstr(&ds, slave->name);
934         }
935         ds_put_char(&ds, '\n');
936     }
937     unixctl_command_reply(conn, 200, ds_cstr(&ds));
938     ds_destroy(&ds);
939 }
940
941 static void
942 bond_print_details(struct ds *ds, const struct bond *bond)
943 {
944     struct shash slave_shash = SHASH_INITIALIZER(&slave_shash);
945     const struct shash_node **sorted_slaves = NULL;
946     const struct bond_slave *slave;
947     int i;
948
949     ds_put_format(ds, "---- %s ----\n", bond->name);
950     ds_put_format(ds, "bond_mode: %s\n",
951                   bond_mode_to_string(bond->balance));
952
953     if (bond->balance != BM_AB) {
954         ds_put_format(ds, "bond-hash-algorithm: %s\n",
955                       bond_is_tcp_hash(bond) ? "balance-tcp" : "balance-slb");
956     }
957
958     ds_put_format(ds, "bond-hash-basis: %"PRIu32"\n", bond->basis);
959
960     ds_put_format(ds, "updelay: %d ms\n", bond->updelay);
961     ds_put_format(ds, "downdelay: %d ms\n", bond->downdelay);
962
963     if (bond_is_balanced(bond)) {
964         ds_put_format(ds, "next rebalance: %lld ms\n",
965                       bond->next_rebalance - time_msec());
966     }
967
968     ds_put_format(ds, "lacp_negotiated: %s\n",
969                   bond->lacp_negotiated ? "true" : "false");
970
971     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
972         shash_add(&slave_shash, slave->name, slave);
973     }
974     sorted_slaves = shash_sort(&slave_shash);
975
976     for (i = 0; i < shash_count(&slave_shash); i++) {
977         struct bond_entry *be;
978
979         slave = sorted_slaves[i]->data;
980
981         /* Basic info. */
982         ds_put_format(ds, "\nslave %s: %s\n",
983                       slave->name, slave->enabled ? "enabled" : "disabled");
984         if (slave == bond->active_slave) {
985             ds_put_cstr(ds, "\tactive slave\n");
986         }
987         if (slave->delay_expires != LLONG_MAX) {
988             ds_put_format(ds, "\t%s expires in %lld ms\n",
989                           slave->enabled ? "downdelay" : "updelay",
990                           slave->delay_expires - time_msec());
991         }
992
993         ds_put_format(ds, "\tmay_enable: %s\n",
994                       slave->may_enable ? "true" : "false");
995
996         if (!bond_is_balanced(bond)) {
997             continue;
998         }
999
1000         /* Hashes. */
1001         for (be = bond->hash; be <= &bond->hash[BOND_MASK]; be++) {
1002             int hash = be - bond->hash;
1003
1004             if (be->slave != slave) {
1005                 continue;
1006             }
1007
1008             ds_put_format(ds, "\thash %d: %"PRIu64" kB load\n",
1009                           hash, be->tx_bytes / 1024);
1010
1011             /* XXX How can we list the MACs assigned to hashes of SLB bonds? */
1012         }
1013     }
1014     shash_destroy(&slave_shash);
1015     free(sorted_slaves);
1016     ds_put_cstr(ds, "\n");
1017 }
1018
1019 static void
1020 bond_unixctl_show(struct unixctl_conn *conn,
1021                   int argc, const char *argv[],
1022                   void *aux OVS_UNUSED)
1023 {
1024     struct ds ds = DS_EMPTY_INITIALIZER;
1025
1026     if (argc > 1) {
1027         const struct bond *bond = bond_find(argv[1]);
1028
1029         if (!bond) {
1030             unixctl_command_reply(conn, 501, "no such bond");
1031             return;
1032         }
1033         bond_print_details(&ds, bond);
1034     } else {
1035         const struct bond *bond;
1036
1037         HMAP_FOR_EACH (bond, hmap_node, &all_bonds) {
1038             bond_print_details(&ds, bond);
1039         }
1040     }
1041
1042     unixctl_command_reply(conn, 200, ds_cstr(&ds));
1043     ds_destroy(&ds);
1044 }
1045
1046 static void
1047 bond_unixctl_migrate(struct unixctl_conn *conn,
1048                      int argc OVS_UNUSED, const char *argv[],
1049                      void *aux OVS_UNUSED)
1050 {
1051     const char *bond_s = argv[1];
1052     const char *hash_s = argv[2];
1053     const char *slave_s = argv[3];
1054     struct bond *bond;
1055     struct bond_slave *slave;
1056     struct bond_entry *entry;
1057     int hash;
1058
1059     bond = bond_find(bond_s);
1060     if (!bond) {
1061         unixctl_command_reply(conn, 501, "no such bond");
1062         return;
1063     }
1064
1065     if (bond->balance != BM_SLB) {
1066         unixctl_command_reply(conn, 501, "not an SLB bond");
1067         return;
1068     }
1069
1070     if (strspn(hash_s, "0123456789") == strlen(hash_s)) {
1071         hash = atoi(hash_s) & BOND_MASK;
1072     } else {
1073         unixctl_command_reply(conn, 501, "bad hash");
1074         return;
1075     }
1076
1077     slave = bond_lookup_slave(bond, slave_s);
1078     if (!slave) {
1079         unixctl_command_reply(conn, 501, "no such slave");
1080         return;
1081     }
1082
1083     if (!slave->enabled) {
1084         unixctl_command_reply(conn, 501, "cannot migrate to disabled slave");
1085         return;
1086     }
1087
1088     entry = &bond->hash[hash];
1089     tag_set_add(&bond->unixctl_tags, entry->tag);
1090     entry->slave = slave;
1091     entry->tag = tag_create_random();
1092     unixctl_command_reply(conn, 200, "migrated");
1093 }
1094
1095 static void
1096 bond_unixctl_set_active_slave(struct unixctl_conn *conn,
1097                               int argc OVS_UNUSED, const char *argv[],
1098                               void *aux OVS_UNUSED)
1099 {
1100     const char *bond_s = argv[1];
1101     const char *slave_s = argv[2];
1102     struct bond *bond;
1103     struct bond_slave *slave;
1104
1105     bond = bond_find(bond_s);
1106     if (!bond) {
1107         unixctl_command_reply(conn, 501, "no such bond");
1108         return;
1109     }
1110
1111     slave = bond_lookup_slave(bond, slave_s);
1112     if (!slave) {
1113         unixctl_command_reply(conn, 501, "no such slave");
1114         return;
1115     }
1116
1117     if (!slave->enabled) {
1118         unixctl_command_reply(conn, 501, "cannot make disabled slave active");
1119         return;
1120     }
1121
1122     if (bond->active_slave != slave) {
1123         tag_set_add(&bond->unixctl_tags, bond_get_active_slave_tag(bond));
1124         bond->active_slave = slave;
1125         bond->active_slave->tag = tag_create_random();
1126         VLOG_INFO("bond %s: active interface is now %s",
1127                   bond->name, slave->name);
1128         bond->send_learning_packets = true;
1129         unixctl_command_reply(conn, 200, "done");
1130     } else {
1131         unixctl_command_reply(conn, 200, "no change");
1132     }
1133 }
1134
1135 static void
1136 enable_slave(struct unixctl_conn *conn, const char *argv[], bool enable)
1137 {
1138     const char *bond_s = argv[1];
1139     const char *slave_s = argv[2];
1140     struct bond *bond;
1141     struct bond_slave *slave;
1142
1143     bond = bond_find(bond_s);
1144     if (!bond) {
1145         unixctl_command_reply(conn, 501, "no such bond");
1146         return;
1147     }
1148
1149     slave = bond_lookup_slave(bond, slave_s);
1150     if (!slave) {
1151         unixctl_command_reply(conn, 501, "no such slave");
1152         return;
1153     }
1154
1155     bond_enable_slave(slave, enable, &bond->unixctl_tags);
1156     unixctl_command_reply(conn, 501, enable ? "enabled" : "disabled");
1157 }
1158
1159 static void
1160 bond_unixctl_enable_slave(struct unixctl_conn *conn,
1161                           int argc OVS_UNUSED, const char *argv[],
1162                           void *aux OVS_UNUSED)
1163 {
1164     enable_slave(conn, argv, true);
1165 }
1166
1167 static void
1168 bond_unixctl_disable_slave(struct unixctl_conn *conn,
1169                            int argc OVS_UNUSED, const char *argv[],
1170                            void *aux OVS_UNUSED)
1171 {
1172     enable_slave(conn, argv, false);
1173 }
1174
1175 static void
1176 bond_unixctl_hash(struct unixctl_conn *conn, int argc, const char *argv[],
1177                   void *aux OVS_UNUSED)
1178 {
1179     const char *mac_s = argv[1];
1180     const char *vlan_s = argc > 2 ? argv[2] : NULL;
1181     const char *basis_s = argc > 3 ? argv[3] : NULL;
1182     uint8_t mac[ETH_ADDR_LEN];
1183     uint8_t hash;
1184     char *hash_cstr;
1185     unsigned int vlan;
1186     uint32_t basis;
1187
1188     if (vlan_s) {
1189         if (sscanf(vlan_s, "%u", &vlan) != 1) {
1190             unixctl_command_reply(conn, 501, "invalid vlan");
1191             return;
1192         }
1193     } else {
1194         vlan = 0;
1195     }
1196
1197     if (basis_s) {
1198         if (sscanf(basis_s, "%"PRIu32, &basis) != 1) {
1199             unixctl_command_reply(conn, 501, "invalid basis");
1200             return;
1201         }
1202     } else {
1203         basis = 0;
1204     }
1205
1206     if (sscanf(mac_s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
1207         == ETH_ADDR_SCAN_COUNT) {
1208         hash = bond_hash_src(mac, vlan, basis) & BOND_MASK;
1209
1210         hash_cstr = xasprintf("%u", hash);
1211         unixctl_command_reply(conn, 200, hash_cstr);
1212         free(hash_cstr);
1213     } else {
1214         unixctl_command_reply(conn, 501, "invalid mac");
1215     }
1216 }
1217
1218 void
1219 bond_init(void)
1220 {
1221     unixctl_command_register("bond/list", "", 0, 0, bond_unixctl_list, NULL);
1222     unixctl_command_register("bond/show", "[port]", 0, 1, bond_unixctl_show,
1223                              NULL);
1224     unixctl_command_register("bond/migrate", "port hash slave", 3, 3,
1225                              bond_unixctl_migrate, NULL);
1226     unixctl_command_register("bond/set-active-slave", "port slave", 2, 2,
1227                              bond_unixctl_set_active_slave, NULL);
1228     unixctl_command_register("bond/enable-slave", "port slave", 2, 2,
1229                              bond_unixctl_enable_slave, NULL);
1230     unixctl_command_register("bond/disable-slave", "port slave", 2, 2,
1231                              bond_unixctl_disable_slave, NULL);
1232     unixctl_command_register("bond/hash", "mac [vlan] [basis]", 1, 3,
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 }