bond: Sort slaves in ovs-appctl bond/show.
[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     bond->lacp_negotiated = lacp_negotiated;
411
412     /* Enable slaves based on link status and LACP feedback. */
413     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
414         bond_link_status_update(slave, tags);
415         slave->change_seq = netdev_change_seq(slave->netdev);
416     }
417     if (!bond->active_slave || !bond->active_slave->enabled) {
418         bond_choose_active_slave(bond, tags);
419     }
420
421     /* Update fake bond interface stats. */
422     if (time_msec() >= bond->next_fake_iface_update) {
423         bond_update_fake_slave_stats(bond);
424         bond->next_fake_iface_update = time_msec() + 1000;
425     }
426
427     if (is_tcp_hash != bond_is_tcp_hash(bond)) {
428         bond->bond_revalidate = true;
429     }
430
431     if (bond->bond_revalidate) {
432         bond->bond_revalidate = false;
433
434         bond_entry_reset(bond);
435         if (bond->balance != BM_STABLE) {
436             struct bond_slave *slave;
437
438             HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
439                 tag_set_add(tags, slave->tag);
440             }
441         } else {
442             tag_set_add(tags, bond->stb_tag);
443         }
444         tag_set_add(tags, bond->no_slaves_tag);
445     }
446
447     /* Invalidate any tags required by  */
448     tag_set_union(tags, &bond->unixctl_tags);
449     tag_set_init(&bond->unixctl_tags);
450 }
451
452 /* Causes poll_block() to wake up when 'bond' needs something to be done. */
453 void
454 bond_wait(struct bond *bond)
455 {
456     struct bond_slave *slave;
457
458     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
459         if (slave->delay_expires != LLONG_MAX) {
460             poll_timer_wait_until(slave->delay_expires);
461         }
462
463         if (slave->change_seq != netdev_change_seq(slave->netdev)) {
464             poll_immediate_wake();
465         }
466     }
467
468     if (bond->next_fake_iface_update != LLONG_MAX) {
469         poll_timer_wait_until(bond->next_fake_iface_update);
470     }
471
472     /* Ensure that any saved tags get revalidated right away. */
473     if (!tag_set_is_empty(&bond->unixctl_tags)) {
474         poll_immediate_wake();
475     }
476
477     /* We don't wait for bond->next_rebalance because rebalancing can only run
478      * at a flow account checkpoint.  ofproto does checkpointing on its own
479      * schedule and bond_rebalance() gets called afterward, so we'd just be
480      * waking up for no purpose. */
481 }
482 \f
483 /* MAC learning table interaction. */
484
485 static bool
486 may_send_learning_packets(const struct bond *bond)
487 {
488     return !bond->lacp_negotiated && bond->balance != BM_AB &&
489            bond->active_slave;
490 }
491
492 /* Returns true if 'bond' needs the client to send out packets to assist with
493  * MAC learning on 'bond'.  If this function returns true, then the client
494  * should iterate through its MAC learning table for the bridge on which 'bond'
495  * is located.  For each MAC that has been learned on a port other than 'bond',
496  * it should call bond_compose_learning_packet().
497  *
498  * This function will only return true if 'bond' is in SLB mode and LACP is not
499  * negotiated.  Otherwise sending learning packets isn't necessary.
500  *
501  * Calling this function resets the state that it checks. */
502 bool
503 bond_should_send_learning_packets(struct bond *bond)
504 {
505     bool send = bond->send_learning_packets && may_send_learning_packets(bond);
506     bond->send_learning_packets = false;
507     return send;
508 }
509
510 /* Sends a gratuitous learning packet on 'bond' from 'eth_src' on 'vlan'.
511  *
512  * See bond_should_send_learning_packets() for description of usage. The
513  * caller should send the composed packet on the port associated with
514  * port_aux and takes ownership of the returned ofpbuf. */
515 struct ofpbuf *
516 bond_compose_learning_packet(struct bond *bond,
517                              const uint8_t eth_src[ETH_ADDR_LEN],
518                              uint16_t vlan, void **port_aux)
519 {
520     struct bond_slave *slave;
521     struct ofpbuf *packet;
522     struct flow flow;
523
524     assert(may_send_learning_packets(bond));
525
526     memset(&flow, 0, sizeof flow);
527     memcpy(flow.dl_src, eth_src, ETH_ADDR_LEN);
528     slave = choose_output_slave(bond, &flow, vlan);
529
530     packet = ofpbuf_new(0);
531     compose_benign_packet(packet, "Open vSwitch Bond Failover", 0xf177,
532                           eth_src);
533     if (vlan) {
534         eth_push_vlan(packet, htons(vlan));
535     }
536
537     *port_aux = slave->aux;
538     return packet;
539 }
540 \f
541 /* Checks whether a packet that arrived on 'slave_' within 'bond', with an
542  * Ethernet destination address of 'eth_dst', should be admitted.
543  *
544  * The return value is one of the following:
545  *
546  *    - BV_ACCEPT: Admit the packet.
547  *
548  *    - BV_DROP: Drop the packet.
549  *
550  *    - BV_DROP_IF_MOVED: Consult the MAC learning table for the packet's
551  *      Ethernet source address and VLAN.  If there is none, or if the packet
552  *      is on the learned port, then admit the packet.  If a different port has
553  *      been learned, however, drop the packet (and do not use it for MAC
554  *      learning).
555  */
556 enum bond_verdict
557 bond_check_admissibility(struct bond *bond, const void *slave_,
558                          const uint8_t eth_dst[ETH_ADDR_LEN], tag_type *tags)
559 {
560     struct bond_slave *slave = bond_slave_lookup(bond, slave_);
561
562     /* LACP bonds have very loose admissibility restrictions because we can
563      * assume the remote switch is aware of the bond and will "do the right
564      * thing".  However, as a precaution we drop packets on disabled slaves
565      * because no correctly implemented partner switch should be sending
566      * packets to them. */
567     if (bond->lacp_negotiated) {
568         return slave->enabled ? BV_ACCEPT : BV_DROP;
569     }
570
571     /* Drop all multicast packets on inactive slaves. */
572     if (eth_addr_is_multicast(eth_dst)) {
573         *tags |= bond_get_active_slave_tag(bond);
574         if (bond->active_slave != bond_slave_lookup(bond, slave_)) {
575             return BV_DROP;
576         }
577     }
578
579     switch (bond->balance) {
580     case BM_AB:
581         /* Drop all packets which arrive on backup slaves.  This is similar to
582          * how Linux bonding handles active-backup bonds. */
583         *tags |= bond_get_active_slave_tag(bond);
584         if (bond->active_slave != slave) {
585             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
586
587             VLOG_DBG_RL(&rl, "active-backup bond received packet on backup"
588                         " slave (%s) destined for " ETH_ADDR_FMT,
589                         slave->name, ETH_ADDR_ARGS(eth_dst));
590             return BV_DROP;
591         }
592         return BV_ACCEPT;
593
594     case BM_TCP:
595         /* TCP balancing has degraded to SLB (otherwise the
596          * bond->lacp_negotiated check above would have processed this).
597          *
598          * Fall through. */
599     case BM_SLB:
600         /* Drop all packets for which we have learned a different input port,
601          * because we probably sent the packet on one slave and got it back on
602          * the other.  Gratuitous ARP packets are an exception to this rule:
603          * the host has moved to another switch.  The exception to the
604          * exception is if we locked the learning table to avoid reflections on
605          * bond slaves. */
606         return BV_DROP_IF_MOVED;
607
608     case BM_STABLE:
609         return BV_ACCEPT;
610     }
611
612     NOT_REACHED();
613 }
614
615 /* Returns the slave (registered on 'bond' by bond_slave_register()) to which
616  * a packet with the given 'flow' and 'vlan' should be forwarded.  Returns
617  * NULL if the packet should be dropped because no slaves are enabled.
618  *
619  * 'vlan' is not necessarily the same as 'flow->vlan_tci'.  First, 'vlan'
620  * should be a VID only (i.e. excluding the PCP bits).  Second,
621  * 'flow->vlan_tci' is the VLAN TCI that appeared on the packet (so it will be
622  * nonzero only for trunk ports), whereas 'vlan' is the logical VLAN that the
623  * packet belongs to (so for an access port it will be the access port's VLAN).
624  *
625  * Adds a tag to '*tags' that associates the flow with the returned slave.
626  */
627 void *
628 bond_choose_output_slave(struct bond *bond, const struct flow *flow,
629                          uint16_t vlan, tag_type *tags)
630 {
631     struct bond_slave *slave = choose_output_slave(bond, flow, vlan);
632     if (slave) {
633         *tags |= bond->balance == BM_STABLE ? bond->stb_tag : slave->tag;
634         return slave->aux;
635     } else {
636         *tags |= bond->no_slaves_tag;
637         return NULL;
638     }
639 }
640 \f
641 /* Rebalancing. */
642
643 static bool
644 bond_is_balanced(const struct bond *bond)
645 {
646     return bond->balance == BM_SLB || bond->balance == BM_TCP;
647 }
648
649 /* Notifies 'bond' that 'n_bytes' bytes were sent in 'flow' within 'vlan'. */
650 void
651 bond_account(struct bond *bond, const struct flow *flow, uint16_t vlan,
652              uint64_t n_bytes)
653 {
654     if (bond_is_balanced(bond)) {
655         lookup_bond_entry(bond, flow, vlan)->tx_bytes += n_bytes;
656     }
657 }
658
659 static struct bond_slave *
660 bond_slave_from_bal_node(struct list *bal)
661 {
662     return CONTAINER_OF(bal, struct bond_slave, bal_node);
663 }
664
665 static void
666 log_bals(struct bond *bond, const struct list *bals)
667 {
668     if (VLOG_IS_DBG_ENABLED()) {
669         struct ds ds = DS_EMPTY_INITIALIZER;
670         const struct bond_slave *slave;
671
672         LIST_FOR_EACH (slave, bal_node, bals) {
673             if (ds.length) {
674                 ds_put_char(&ds, ',');
675             }
676             ds_put_format(&ds, " %s %"PRIu64"kB",
677                           slave->name, slave->tx_bytes / 1024);
678
679             if (!slave->enabled) {
680                 ds_put_cstr(&ds, " (disabled)");
681             }
682             if (!list_is_empty(&slave->entries)) {
683                 struct bond_entry *e;
684
685                 ds_put_cstr(&ds, " (");
686                 LIST_FOR_EACH (e, list_node, &slave->entries) {
687                     if (&e->list_node != list_front(&slave->entries)) {
688                         ds_put_cstr(&ds, " + ");
689                     }
690                     ds_put_format(&ds, "h%td: %"PRIu64"kB",
691                                   e - bond->hash, e->tx_bytes / 1024);
692                 }
693                 ds_put_cstr(&ds, ")");
694             }
695         }
696         VLOG_DBG("bond %s:%s", bond->name, ds_cstr(&ds));
697         ds_destroy(&ds);
698     }
699 }
700
701 /* Shifts 'hash' from its current slave to 'to'. */
702 static void
703 bond_shift_load(struct bond_entry *hash, struct bond_slave *to,
704                 struct tag_set *set)
705 {
706     struct bond_slave *from = hash->slave;
707     struct bond *bond = from->bond;
708     uint64_t delta = hash->tx_bytes;
709
710     VLOG_INFO("bond %s: shift %"PRIu64"kB of load (with hash %td) "
711               "from %s to %s (now carrying %"PRIu64"kB and "
712               "%"PRIu64"kB load, respectively)",
713               bond->name, delta / 1024, hash - bond->hash,
714               from->name, to->name,
715               (from->tx_bytes - delta) / 1024,
716               (to->tx_bytes + delta) / 1024);
717
718     /* Shift load away from 'from' to 'to'. */
719     from->tx_bytes -= delta;
720     to->tx_bytes += delta;
721
722     /* Arrange for flows to be revalidated. */
723     tag_set_add(set, hash->tag);
724     hash->slave = to;
725     hash->tag = tag_create_random();
726 }
727
728 /* Pick and returns a bond_entry to migrate to 'to' (the least-loaded slave),
729  * given that doing so must decrease the ratio of the load on the two slaves by
730  * at least 0.1.  Returns NULL if there is no appropriate entry.
731  *
732  * The list of entries isn't sorted.  I don't know of a reason to prefer to
733  * shift away small hashes or large hashes. */
734 static struct bond_entry *
735 choose_entry_to_migrate(const struct bond_slave *from, uint64_t to_tx_bytes)
736 {
737     struct bond_entry *e;
738
739     if (list_is_short(&from->entries)) {
740         /* 'from' carries no more than one MAC hash, so shifting load away from
741          * it would be pointless. */
742         return NULL;
743     }
744
745     LIST_FOR_EACH (e, list_node, &from->entries) {
746         double old_ratio, new_ratio;
747         uint64_t delta;
748
749         if (to_tx_bytes == 0) {
750             /* Nothing on the new slave, move it. */
751             return e;
752         }
753
754         delta = e->tx_bytes;
755         old_ratio = (double)from->tx_bytes / to_tx_bytes;
756         new_ratio = (double)(from->tx_bytes - delta) / (to_tx_bytes + delta);
757         if (old_ratio - new_ratio > 0.1) {
758             /* Would decrease the ratio, move it. */
759             return e;
760         }
761     }
762
763     return NULL;
764 }
765
766 /* Inserts 'slave' into 'bals' so that descending order of 'tx_bytes' is
767  * maintained. */
768 static void
769 insert_bal(struct list *bals, struct bond_slave *slave)
770 {
771     struct bond_slave *pos;
772
773     LIST_FOR_EACH (pos, bal_node, bals) {
774         if (slave->tx_bytes > pos->tx_bytes) {
775             break;
776         }
777     }
778     list_insert(&pos->bal_node, &slave->bal_node);
779 }
780
781 /* Removes 'slave' from its current list and then inserts it into 'bals' so
782  * that descending order of 'tx_bytes' is maintained. */
783 static void
784 reinsert_bal(struct list *bals, struct bond_slave *slave)
785 {
786     list_remove(&slave->bal_node);
787     insert_bal(bals, slave);
788 }
789
790 /* If 'bond' needs rebalancing, does so.
791  *
792  * The caller should have called bond_account() for each active flow, to ensure
793  * that flow data is consistently accounted at this point. */
794 void
795 bond_rebalance(struct bond *bond, struct tag_set *tags)
796 {
797     struct bond_slave *slave;
798     struct bond_entry *e;
799     struct list bals;
800
801     if (!bond_is_balanced(bond) || time_msec() < bond->next_rebalance) {
802         return;
803     }
804     bond->next_rebalance = time_msec() + bond->rebalance_interval;
805
806     /* Add each bond_entry to its slave's 'entries' list.
807      * Compute each slave's tx_bytes as the sum of its entries' tx_bytes. */
808     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
809         slave->tx_bytes = 0;
810         list_init(&slave->entries);
811     }
812     for (e = &bond->hash[0]; e <= &bond->hash[BOND_MASK]; e++) {
813         if (e->slave && e->tx_bytes) {
814             e->slave->tx_bytes += e->tx_bytes;
815             list_push_back(&e->slave->entries, &e->list_node);
816         }
817     }
818
819     /* Add enabled slaves to 'bals' in descending order of tx_bytes.
820      *
821      * XXX This is O(n**2) in the number of slaves but it could be O(n lg n)
822      * with a proper list sort algorithm. */
823     list_init(&bals);
824     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
825         if (slave->enabled) {
826             insert_bal(&bals, slave);
827         }
828     }
829     log_bals(bond, &bals);
830
831     /* Shift load from the most-loaded slaves to the least-loaded slaves. */
832     while (!list_is_short(&bals)) {
833         struct bond_slave *from = bond_slave_from_bal_node(list_front(&bals));
834         struct bond_slave *to = bond_slave_from_bal_node(list_back(&bals));
835         uint64_t overload;
836
837         overload = from->tx_bytes - to->tx_bytes;
838         if (overload < to->tx_bytes >> 5 || overload < 100000) {
839             /* The extra load on 'from' (and all less-loaded slaves), compared
840              * to that of 'to' (the least-loaded slave), is less than ~3%, or
841              * it is less than ~1Mbps.  No point in rebalancing. */
842             break;
843         }
844
845         /* 'from' is carrying significantly more load than 'to', and that load
846          * is split across at least two different hashes. */
847         e = choose_entry_to_migrate(from, to->tx_bytes);
848         if (e) {
849             bond_shift_load(e, to, tags);
850
851             /* Delete element from from->entries.
852              *
853              * We don't add the element to to->hashes.  That would only allow
854              * 'e' to be migrated to another slave in this rebalancing run, and
855              * there is no point in doing that. */
856             list_remove(&e->list_node);
857
858             /* Re-sort 'bals'. */
859             reinsert_bal(&bals, from);
860             reinsert_bal(&bals, to);
861         } else {
862             /* Can't usefully migrate anything away from 'from'.
863              * Don't reconsider it. */
864             list_remove(&from->bal_node);
865         }
866     }
867
868     /* Implement exponentially weighted moving average.  A weight of 1/2 causes
869      * historical data to decay to <1% in 7 rebalancing runs.  1,000,000 bytes
870      * take 20 rebalancing runs to decay to 0 and get deleted entirely. */
871     for (e = &bond->hash[0]; e <= &bond->hash[BOND_MASK]; e++) {
872         e->tx_bytes /= 2;
873         if (!e->tx_bytes) {
874             e->slave = NULL;
875         }
876     }
877 }
878 \f
879 /* Bonding unixctl user interface functions. */
880
881 static struct bond *
882 bond_find(const char *name)
883 {
884     struct bond *bond;
885
886     HMAP_FOR_EACH_WITH_HASH (bond, hmap_node, hash_string(name, 0),
887                              &all_bonds) {
888         if (!strcmp(bond->name, name)) {
889             return bond;
890         }
891     }
892     return NULL;
893 }
894
895 static struct bond_slave *
896 bond_lookup_slave(struct bond *bond, const char *slave_name)
897 {
898     struct bond_slave *slave;
899
900     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
901         if (!strcmp(slave->name, slave_name)) {
902             return slave;
903         }
904     }
905     return NULL;
906 }
907
908 static void
909 bond_unixctl_list(struct unixctl_conn *conn,
910                   int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
911                   void *aux OVS_UNUSED)
912 {
913     struct ds ds = DS_EMPTY_INITIALIZER;
914     const struct bond *bond;
915
916     ds_put_cstr(&ds, "bond\ttype\tslaves\n");
917
918     HMAP_FOR_EACH (bond, hmap_node, &all_bonds) {
919         const struct bond_slave *slave;
920         size_t i;
921
922         ds_put_format(&ds, "%s\t%s\t",
923                       bond->name, bond_mode_to_string(bond->balance));
924
925         i = 0;
926         HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
927             if (i++ > 0) {
928                 ds_put_cstr(&ds, ", ");
929             }
930             ds_put_cstr(&ds, slave->name);
931         }
932         ds_put_char(&ds, '\n');
933     }
934     unixctl_command_reply(conn, 200, ds_cstr(&ds));
935     ds_destroy(&ds);
936 }
937
938 static void
939 bond_print_details(struct ds *ds, const struct bond *bond)
940 {
941     struct shash slave_shash = SHASH_INITIALIZER(&slave_shash);
942     const struct shash_node **sorted_slaves = NULL;
943     const struct bond_slave *slave;
944     int i;
945
946     ds_put_format(ds, "---- %s ----\n", bond->name);
947     ds_put_format(ds, "bond_mode: %s\n",
948                   bond_mode_to_string(bond->balance));
949
950     if (bond->balance != BM_AB) {
951         ds_put_format(ds, "bond-hash-algorithm: %s\n",
952                       bond_is_tcp_hash(bond) ? "balance-tcp" : "balance-slb");
953     }
954
955     ds_put_format(ds, "bond-hash-basis: %"PRIu32"\n", bond->basis);
956
957     ds_put_format(ds, "updelay: %d ms\n", bond->updelay);
958     ds_put_format(ds, "downdelay: %d ms\n", bond->downdelay);
959
960     if (bond_is_balanced(bond)) {
961         ds_put_format(ds, "next rebalance: %lld ms\n",
962                       bond->next_rebalance - time_msec());
963     }
964
965     ds_put_format(ds, "lacp_negotiated: %s\n",
966                   bond->lacp_negotiated ? "true" : "false");
967
968     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
969         shash_add(&slave_shash, slave->name, slave);
970     }
971     sorted_slaves = shash_sort(&slave_shash);
972
973     for (i = 0; i < shash_count(&slave_shash); i++) {
974         struct bond_entry *be;
975
976         slave = sorted_slaves[i]->data;
977
978         /* Basic info. */
979         ds_put_format(ds, "\nslave %s: %s\n",
980                       slave->name, slave->enabled ? "enabled" : "disabled");
981         if (slave == bond->active_slave) {
982             ds_put_cstr(ds, "\tactive slave\n");
983         }
984         if (slave->delay_expires != LLONG_MAX) {
985             ds_put_format(ds, "\t%s expires in %lld ms\n",
986                           slave->enabled ? "downdelay" : "updelay",
987                           slave->delay_expires - time_msec());
988         }
989
990         ds_put_format(ds, "\tmay_enable: %s\n",
991                       slave->may_enable ? "true" : "false");
992
993         if (!bond_is_balanced(bond)) {
994             continue;
995         }
996
997         /* Hashes. */
998         for (be = bond->hash; be <= &bond->hash[BOND_MASK]; be++) {
999             int hash = be - bond->hash;
1000
1001             if (be->slave != slave) {
1002                 continue;
1003             }
1004
1005             ds_put_format(ds, "\thash %d: %"PRIu64" kB load\n",
1006                           hash, be->tx_bytes / 1024);
1007
1008             /* XXX How can we list the MACs assigned to hashes of SLB bonds? */
1009         }
1010     }
1011     shash_destroy(&slave_shash);
1012     free(sorted_slaves);
1013     ds_put_cstr(ds, "\n");
1014 }
1015
1016 static void
1017 bond_unixctl_show(struct unixctl_conn *conn,
1018                   int argc, const char *argv[],
1019                   void *aux OVS_UNUSED)
1020 {
1021     struct ds ds = DS_EMPTY_INITIALIZER;
1022
1023     if (argc > 1) {
1024         const struct bond *bond = bond_find(argv[1]);
1025
1026         if (!bond) {
1027             unixctl_command_reply(conn, 501, "no such bond");
1028             return;
1029         }
1030         bond_print_details(&ds, bond);
1031     } else {
1032         const struct bond *bond;
1033
1034         HMAP_FOR_EACH (bond, hmap_node, &all_bonds) {
1035             bond_print_details(&ds, bond);
1036         }
1037     }
1038
1039     unixctl_command_reply(conn, 200, ds_cstr(&ds));
1040     ds_destroy(&ds);
1041 }
1042
1043 static void
1044 bond_unixctl_migrate(struct unixctl_conn *conn,
1045                      int argc OVS_UNUSED, const char *argv[],
1046                      void *aux OVS_UNUSED)
1047 {
1048     const char *bond_s = argv[1];
1049     const char *hash_s = argv[2];
1050     const char *slave_s = argv[3];
1051     struct bond *bond;
1052     struct bond_slave *slave;
1053     struct bond_entry *entry;
1054     int hash;
1055
1056     bond = bond_find(bond_s);
1057     if (!bond) {
1058         unixctl_command_reply(conn, 501, "no such bond");
1059         return;
1060     }
1061
1062     if (bond->balance != BM_SLB) {
1063         unixctl_command_reply(conn, 501, "not an SLB bond");
1064         return;
1065     }
1066
1067     if (strspn(hash_s, "0123456789") == strlen(hash_s)) {
1068         hash = atoi(hash_s) & BOND_MASK;
1069     } else {
1070         unixctl_command_reply(conn, 501, "bad hash");
1071         return;
1072     }
1073
1074     slave = bond_lookup_slave(bond, slave_s);
1075     if (!slave) {
1076         unixctl_command_reply(conn, 501, "no such slave");
1077         return;
1078     }
1079
1080     if (!slave->enabled) {
1081         unixctl_command_reply(conn, 501, "cannot migrate to disabled slave");
1082         return;
1083     }
1084
1085     entry = &bond->hash[hash];
1086     tag_set_add(&bond->unixctl_tags, entry->tag);
1087     entry->slave = slave;
1088     entry->tag = tag_create_random();
1089     unixctl_command_reply(conn, 200, "migrated");
1090 }
1091
1092 static void
1093 bond_unixctl_set_active_slave(struct unixctl_conn *conn,
1094                               int argc OVS_UNUSED, const char *argv[],
1095                               void *aux OVS_UNUSED)
1096 {
1097     const char *bond_s = argv[1];
1098     const char *slave_s = argv[2];
1099     struct bond *bond;
1100     struct bond_slave *slave;
1101
1102     bond = bond_find(bond_s);
1103     if (!bond) {
1104         unixctl_command_reply(conn, 501, "no such bond");
1105         return;
1106     }
1107
1108     slave = bond_lookup_slave(bond, slave_s);
1109     if (!slave) {
1110         unixctl_command_reply(conn, 501, "no such slave");
1111         return;
1112     }
1113
1114     if (!slave->enabled) {
1115         unixctl_command_reply(conn, 501, "cannot make disabled slave active");
1116         return;
1117     }
1118
1119     if (bond->active_slave != slave) {
1120         tag_set_add(&bond->unixctl_tags, bond_get_active_slave_tag(bond));
1121         bond->active_slave = slave;
1122         bond->active_slave->tag = tag_create_random();
1123         VLOG_INFO("bond %s: active interface is now %s",
1124                   bond->name, slave->name);
1125         bond->send_learning_packets = true;
1126         unixctl_command_reply(conn, 200, "done");
1127     } else {
1128         unixctl_command_reply(conn, 200, "no change");
1129     }
1130 }
1131
1132 static void
1133 enable_slave(struct unixctl_conn *conn, const char *argv[], bool enable)
1134 {
1135     const char *bond_s = argv[1];
1136     const char *slave_s = argv[2];
1137     struct bond *bond;
1138     struct bond_slave *slave;
1139
1140     bond = bond_find(bond_s);
1141     if (!bond) {
1142         unixctl_command_reply(conn, 501, "no such bond");
1143         return;
1144     }
1145
1146     slave = bond_lookup_slave(bond, slave_s);
1147     if (!slave) {
1148         unixctl_command_reply(conn, 501, "no such slave");
1149         return;
1150     }
1151
1152     bond_enable_slave(slave, enable, &bond->unixctl_tags);
1153     unixctl_command_reply(conn, 501, enable ? "enabled" : "disabled");
1154 }
1155
1156 static void
1157 bond_unixctl_enable_slave(struct unixctl_conn *conn,
1158                           int argc OVS_UNUSED, const char *argv[],
1159                           void *aux OVS_UNUSED)
1160 {
1161     enable_slave(conn, argv, true);
1162 }
1163
1164 static void
1165 bond_unixctl_disable_slave(struct unixctl_conn *conn,
1166                            int argc OVS_UNUSED, const char *argv[],
1167                            void *aux OVS_UNUSED)
1168 {
1169     enable_slave(conn, argv, false);
1170 }
1171
1172 static void
1173 bond_unixctl_hash(struct unixctl_conn *conn, int argc, const char *argv[],
1174                   void *aux OVS_UNUSED)
1175 {
1176     const char *mac_s = argv[1];
1177     const char *vlan_s = argc > 2 ? argv[2] : NULL;
1178     const char *basis_s = argc > 3 ? argv[3] : NULL;
1179     uint8_t mac[ETH_ADDR_LEN];
1180     uint8_t hash;
1181     char *hash_cstr;
1182     unsigned int vlan;
1183     uint32_t basis;
1184
1185     if (vlan_s) {
1186         if (sscanf(vlan_s, "%u", &vlan) != 1) {
1187             unixctl_command_reply(conn, 501, "invalid vlan");
1188             return;
1189         }
1190     } else {
1191         vlan = 0;
1192     }
1193
1194     if (basis_s) {
1195         if (sscanf(basis_s, "%"PRIu32, &basis) != 1) {
1196             unixctl_command_reply(conn, 501, "invalid basis");
1197             return;
1198         }
1199     } else {
1200         basis = 0;
1201     }
1202
1203     if (sscanf(mac_s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
1204         == ETH_ADDR_SCAN_COUNT) {
1205         hash = bond_hash_src(mac, vlan, basis) & BOND_MASK;
1206
1207         hash_cstr = xasprintf("%u", hash);
1208         unixctl_command_reply(conn, 200, hash_cstr);
1209         free(hash_cstr);
1210     } else {
1211         unixctl_command_reply(conn, 501, "invalid mac");
1212     }
1213 }
1214
1215 void
1216 bond_init(void)
1217 {
1218     unixctl_command_register("bond/list", "", 0, 0, bond_unixctl_list, NULL);
1219     unixctl_command_register("bond/show", "[port]", 0, 1, bond_unixctl_show,
1220                              NULL);
1221     unixctl_command_register("bond/migrate", "port hash slave", 3, 3,
1222                              bond_unixctl_migrate, NULL);
1223     unixctl_command_register("bond/set-active-slave", "port slave", 2, 2,
1224                              bond_unixctl_set_active_slave, NULL);
1225     unixctl_command_register("bond/enable-slave", "port slave", 2, 2,
1226                              bond_unixctl_enable_slave, NULL);
1227     unixctl_command_register("bond/disable-slave", "port slave", 2, 2,
1228                              bond_unixctl_disable_slave, NULL);
1229     unixctl_command_register("bond/hash", "mac [vlan] [basis]", 1, 3,
1230                              bond_unixctl_hash, NULL);
1231 }
1232 \f
1233 static void
1234 bond_entry_reset(struct bond *bond)
1235 {
1236     if (bond->balance != BM_AB) {
1237         size_t hash_len = (BOND_MASK + 1) * sizeof *bond->hash;
1238
1239         if (!bond->hash) {
1240             bond->hash = xmalloc(hash_len);
1241         }
1242         memset(bond->hash, 0, hash_len);
1243
1244         bond->next_rebalance = time_msec() + bond->rebalance_interval;
1245     } else {
1246         free(bond->hash);
1247         bond->hash = NULL;
1248     }
1249 }
1250
1251 static struct bond_slave *
1252 bond_slave_lookup(struct bond *bond, const void *slave_)
1253 {
1254     struct bond_slave *slave;
1255
1256     HMAP_FOR_EACH_IN_BUCKET (slave, hmap_node, hash_pointer(slave_, 0),
1257                              &bond->slaves) {
1258         if (slave->aux == slave_) {
1259             return slave;
1260         }
1261     }
1262
1263     return NULL;
1264 }
1265
1266 static void
1267 bond_enable_slave(struct bond_slave *slave, bool enable, struct tag_set *tags)
1268 {
1269     struct bond *bond = slave->bond;
1270     slave->delay_expires = LLONG_MAX;
1271     if (enable != slave->enabled) {
1272         slave->enabled = enable;
1273         if (!slave->enabled) {
1274             VLOG_WARN("interface %s: disabled", slave->name);
1275             if (tags) {
1276                 tag_set_add(tags, slave->tag);
1277             }
1278         } else {
1279             VLOG_WARN("interface %s: enabled", slave->name);
1280             slave->tag = tag_create_random();
1281         }
1282
1283         if (bond->balance == BM_STABLE) {
1284             bond->bond_revalidate = true;
1285         }
1286     }
1287 }
1288
1289 static void
1290 bond_link_status_update(struct bond_slave *slave, struct tag_set *tags)
1291 {
1292     struct bond *bond = slave->bond;
1293     bool up;
1294
1295     up = netdev_get_carrier(slave->netdev) && slave->may_enable;
1296     if ((up == slave->enabled) != (slave->delay_expires == LLONG_MAX)) {
1297         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1298         VLOG_INFO_RL(&rl, "interface %s: link state %s",
1299                      slave->name, up ? "up" : "down");
1300         if (up == slave->enabled) {
1301             slave->delay_expires = LLONG_MAX;
1302             VLOG_INFO_RL(&rl, "interface %s: will not be %s",
1303                          slave->name, up ? "disabled" : "enabled");
1304         } else {
1305             int delay = (bond->lacp_negotiated ? 0
1306                          : up ? bond->updelay : bond->downdelay);
1307             slave->delay_expires = time_msec() + delay;
1308             if (delay) {
1309                 VLOG_INFO_RL(&rl, "interface %s: will be %s if it stays %s "
1310                              "for %d ms",
1311                              slave->name,
1312                              up ? "enabled" : "disabled",
1313                              up ? "up" : "down",
1314                              delay);
1315             }
1316         }
1317     }
1318
1319     if (time_msec() >= slave->delay_expires) {
1320         bond_enable_slave(slave, up, tags);
1321     }
1322 }
1323
1324 static bool
1325 bond_is_tcp_hash(const struct bond *bond)
1326 {
1327     return (bond->balance == BM_TCP && bond->lacp_negotiated)
1328         || bond->balance == BM_STABLE;
1329 }
1330
1331 static unsigned int
1332 bond_hash_src(const uint8_t mac[ETH_ADDR_LEN], uint16_t vlan, uint32_t basis)
1333 {
1334     return hash_3words(hash_bytes(mac, ETH_ADDR_LEN, 0), vlan, basis);
1335 }
1336
1337 static unsigned int
1338 bond_hash_tcp(const struct flow *flow, uint16_t vlan, uint32_t basis)
1339 {
1340     struct flow hash_flow = *flow;
1341     hash_flow.vlan_tci = htons(vlan);
1342
1343     /* The symmetric quality of this hash function is not required, but
1344      * flow_hash_symmetric_l4 already exists, and is sufficient for our
1345      * purposes, so we use it out of convenience. */
1346     return flow_hash_symmetric_l4(&hash_flow, basis);
1347 }
1348
1349 static unsigned int
1350 bond_hash(const struct bond *bond, const struct flow *flow, uint16_t vlan)
1351 {
1352     assert(bond->balance != BM_AB);
1353
1354     return (bond_is_tcp_hash(bond)
1355             ? bond_hash_tcp(flow, vlan, bond->basis)
1356             : bond_hash_src(flow->dl_src, vlan, bond->basis));
1357 }
1358
1359 static struct bond_entry *
1360 lookup_bond_entry(const struct bond *bond, const struct flow *flow,
1361                   uint16_t vlan)
1362 {
1363     return &bond->hash[bond_hash(bond, flow, vlan) & BOND_MASK];
1364 }
1365
1366 /* This function uses Highest Random Weight hashing to choose an output slave.
1367  * This approach only reassigns a minimal number of flows when slaves are
1368  * enabled or disabled.  Unfortunately, it has O(n) performance against the
1369  * number of slaves.  There exist algorithms which are O(1), but have slightly
1370  * more complex implementations and require the use of memory.  This may need
1371  * to be reimplemented if it becomes a performance bottleneck. */
1372 static struct bond_slave *
1373 choose_stb_slave(const struct bond *bond, const struct flow *flow,
1374                  uint16_t vlan)
1375 {
1376     struct bond_slave *best, *slave;
1377     uint32_t best_hash, flow_hash;
1378
1379     best = NULL;
1380     best_hash = 0;
1381     flow_hash = bond_hash(bond, flow, vlan);
1382     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1383         if (slave->enabled) {
1384             uint32_t hash;
1385
1386             hash = hash_2words(flow_hash, slave->stb_id);
1387             if (!best || hash > best_hash) {
1388                 best = slave;
1389                 best_hash = hash;
1390             }
1391         }
1392     }
1393
1394     return best;
1395 }
1396
1397 static struct bond_slave *
1398 choose_output_slave(const struct bond *bond, const struct flow *flow,
1399                     uint16_t vlan)
1400 {
1401     struct bond_entry *e;
1402
1403     switch (bond->balance) {
1404     case BM_AB:
1405         return bond->active_slave;
1406
1407     case BM_STABLE:
1408         return choose_stb_slave(bond, flow, vlan);
1409     case BM_SLB:
1410     case BM_TCP:
1411         e = lookup_bond_entry(bond, flow, vlan);
1412         if (!e->slave || !e->slave->enabled) {
1413             e->slave = CONTAINER_OF(hmap_random_node(&bond->slaves),
1414                                     struct bond_slave, hmap_node);
1415             if (!e->slave->enabled) {
1416                 e->slave = bond->active_slave;
1417             }
1418             e->tag = tag_create_random();
1419         }
1420         return e->slave;
1421
1422     default:
1423         NOT_REACHED();
1424     }
1425 }
1426
1427 static struct bond_slave *
1428 bond_choose_slave(const struct bond *bond)
1429 {
1430     struct bond_slave *slave, *best;
1431
1432     /* Find an enabled slave. */
1433     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1434         if (slave->enabled) {
1435             return slave;
1436         }
1437     }
1438
1439     /* All interfaces are disabled.  Find an interface that will be enabled
1440      * after its updelay expires.  */
1441     best = NULL;
1442     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1443         if (slave->delay_expires != LLONG_MAX
1444             && slave->may_enable
1445             && (!best || slave->delay_expires < best->delay_expires)) {
1446             best = slave;
1447         }
1448     }
1449     return best;
1450 }
1451
1452 static void
1453 bond_choose_active_slave(struct bond *bond, struct tag_set *tags)
1454 {
1455     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1456     struct bond_slave *old_active_slave = bond->active_slave;
1457
1458     bond->active_slave = bond_choose_slave(bond);
1459     if (bond->active_slave) {
1460         if (bond->active_slave->enabled) {
1461             VLOG_INFO_RL(&rl, "bond %s: active interface is now %s",
1462                          bond->name, bond->active_slave->name);
1463         } else {
1464             VLOG_INFO_RL(&rl, "bond %s: active interface is now %s, skipping "
1465                          "remaining %lld ms updelay (since no interface was "
1466                          "enabled)", bond->name, bond->active_slave->name,
1467                          bond->active_slave->delay_expires - time_msec());
1468             bond_enable_slave(bond->active_slave, true, tags);
1469         }
1470
1471         if (!old_active_slave) {
1472             tag_set_add(tags, bond->no_slaves_tag);
1473         }
1474
1475         bond->send_learning_packets = true;
1476     } else if (old_active_slave) {
1477         VLOG_WARN_RL(&rl, "bond %s: all interfaces disabled", bond->name);
1478     }
1479 }
1480
1481 /* Returns the tag for 'bond''s active slave, or 'bond''s no_slaves_tag if
1482  * there is no active slave. */
1483 static tag_type
1484 bond_get_active_slave_tag(const struct bond *bond)
1485 {
1486     return (bond->active_slave
1487             ? bond->active_slave->tag
1488             : bond->no_slaves_tag);
1489 }
1490
1491 /* Attempts to make the sum of the bond slaves' statistics appear on the fake
1492  * bond interface. */
1493 static void
1494 bond_update_fake_slave_stats(struct bond *bond)
1495 {
1496     struct netdev_stats bond_stats;
1497     struct bond_slave *slave;
1498     struct netdev *bond_dev;
1499
1500     memset(&bond_stats, 0, sizeof bond_stats);
1501
1502     HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1503         struct netdev_stats slave_stats;
1504
1505         if (!netdev_get_stats(slave->netdev, &slave_stats)) {
1506             /* XXX: We swap the stats here because they are swapped back when
1507              * reported by the internal device.  The reason for this is
1508              * internal devices normally represent packets going into the
1509              * system but when used as fake bond device they represent packets
1510              * leaving the system.  We really should do this in the internal
1511              * device itself because changing it here reverses the counts from
1512              * the perspective of the switch.  However, the internal device
1513              * doesn't know what type of device it represents so we have to do
1514              * it here for now. */
1515             bond_stats.tx_packets += slave_stats.rx_packets;
1516             bond_stats.tx_bytes += slave_stats.rx_bytes;
1517             bond_stats.rx_packets += slave_stats.tx_packets;
1518             bond_stats.rx_bytes += slave_stats.tx_bytes;
1519         }
1520     }
1521
1522     if (!netdev_open(bond->name, "system", &bond_dev)) {
1523         netdev_set_stats(bond_dev, &bond_stats);
1524         netdev_close(bond_dev);
1525     }
1526 }