2 * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
26 #include "dynamic-string.h"
35 #include "poll-loop.h"
42 VLOG_DEFINE_THIS_MODULE(bond);
44 /* Bit-mask for hashing a flow down to a bucket.
45 * There are (BOND_MASK + 1) buckets. */
46 #define BOND_MASK 0xff
48 /* A hash bucket for mapping a flow to a slave.
49 * "struct bond" has an array of (BOND_MASK + 1) of these. */
51 struct bond_slave *slave; /* Assigned slave, NULL if unassigned. */
52 uint64_t tx_bytes; /* Count of bytes recently transmitted. */
53 tag_type tag; /* Tag for entry<->slave association. */
54 struct list list_node; /* In bond_slave's 'entries' list. */
57 /* A bond slave, that is, one of the links comprising a bond. */
59 struct hmap_node hmap_node; /* In struct bond's slaves hmap. */
60 struct bond *bond; /* The bond that contains this slave. */
61 void *aux; /* Client-provided handle for this slave. */
63 struct netdev *netdev; /* Network device, owned by the client. */
64 unsigned int change_seq; /* Tracks changes in 'netdev'. */
65 char *name; /* Name (a copy of netdev_get_name(netdev)). */
68 long long delay_expires; /* Time after which 'enabled' may change. */
69 bool enabled; /* May be chosen for flows? */
70 bool may_enable; /* Client considers this slave bondable. */
71 tag_type tag; /* Tag associated with this slave. */
73 /* Rebalancing info. Used only by bond_rebalance(). */
74 struct list bal_node; /* In bond_rebalance()'s 'bals' list. */
75 struct list entries; /* 'struct bond_entry's assigned here. */
76 uint64_t tx_bytes; /* Sum across 'tx_bytes' of entries. */
78 /* BM_STABLE specific bonding info. */
79 uint32_t stb_id; /* ID used for 'stb_slaves' ordering. */
82 /* A bond, that is, a set of network devices grouped to improve performance or
85 struct hmap_node hmap_node; /* In 'all_bonds' hmap. */
86 char *name; /* Name provided by client. */
92 enum bond_mode balance; /* Balancing mode, one of BM_*. */
93 struct bond_slave *active_slave;
94 tag_type no_slaves_tag; /* Tag for flows when all slaves disabled. */
95 int updelay, downdelay; /* Delay before slave goes up/down, in ms. */
96 enum lacp_status lacp_status; /* Status of LACP negotiations. */
97 bool bond_revalidate; /* True if flows need revalidation. */
98 uint32_t basis; /* Basis for flow hash function. */
100 /* SLB specific bonding info. */
101 struct bond_entry *hash; /* An array of (BOND_MASK + 1) elements. */
102 int rebalance_interval; /* Interval between rebalances, in ms. */
103 long long int next_rebalance; /* Next rebalancing time. */
104 bool send_learning_packets;
106 /* BM_STABLE specific bonding info. */
107 tag_type stb_tag; /* Tag associated with this bond. */
109 /* Legacy compatibility. */
110 long long int next_fake_iface_update; /* LLONG_MAX if disabled. */
112 /* Tag set saved for next bond_run(). This tag set is a kluge for cases
113 * where we can't otherwise provide revalidation feedback to the client.
114 * That's only unixctl commands now; I hope no other cases will arise. */
115 struct tag_set unixctl_tags;
118 static struct hmap all_bonds = HMAP_INITIALIZER(&all_bonds);
120 static void bond_entry_reset(struct bond *);
121 static struct bond_slave *bond_slave_lookup(struct bond *, const void *slave_);
122 static void bond_enable_slave(struct bond_slave *, bool enable,
124 static void bond_link_status_update(struct bond_slave *, struct tag_set *);
125 static void bond_choose_active_slave(struct bond *, struct tag_set *);
126 static unsigned int bond_hash_src(const uint8_t mac[ETH_ADDR_LEN],
127 uint16_t vlan, uint32_t basis);
128 static unsigned int bond_hash_tcp(const struct flow *, uint16_t vlan,
130 static struct bond_entry *lookup_bond_entry(const struct bond *,
133 static tag_type bond_get_active_slave_tag(const struct bond *);
134 static struct bond_slave *choose_output_slave(const struct bond *,
137 static void bond_update_fake_slave_stats(struct bond *);
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'. */
143 bond_mode_from_string(enum bond_mode *balance, const char *s)
145 if (!strcmp(s, bond_mode_to_string(BM_TCP))) {
147 } else if (!strcmp(s, bond_mode_to_string(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))) {
159 /* Returns a string representing 'balance'. */
161 bond_mode_to_string(enum bond_mode balance) {
164 return "balance-tcp";
166 return "balance-slb";
170 return "active-backup";
176 /* Creates and returns a new bond whose configuration is initially taken from
179 * The caller should register each slave on the new bond by calling
180 * bond_slave_register(). */
182 bond_create(const struct bond_settings *s)
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;
192 bond_reconfigure(bond, s);
194 tag_set_init(&bond->unixctl_tags);
201 bond_destroy(struct bond *bond)
203 struct bond_slave *slave, *next_slave;
209 hmap_remove(&all_bonds, &bond->hmap_node);
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'. */
217 hmap_destroy(&bond->slaves);
224 /* Updates 'bond''s overall configuration to 's'.
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.
230 * Returns true if the configuration has changed in such a way that requires
234 bond_reconfigure(struct bond *bond, const struct bond_settings *s)
236 bool revalidate = false;
238 if (!bond->name || strcmp(bond->name, s->name)) {
240 hmap_remove(&all_bonds, &bond->hmap_node);
243 bond->name = xstrdup(s->name);
244 hmap_insert(&all_bonds, &bond->hmap_node, hash_string(bond->name, 0));
247 bond->updelay = s->up_delay;
248 bond->downdelay = s->down_delay;
249 bond->rebalance_interval = s->rebalance_interval;
251 if (bond->balance != s->balance) {
252 bond->balance = s->balance;
256 if (bond->basis != s->basis) {
257 bond->basis = s->basis;
262 if (bond->next_fake_iface_update == LLONG_MAX) {
263 bond->next_fake_iface_update = time_msec();
266 bond->next_fake_iface_update = LLONG_MAX;
269 if (bond->bond_revalidate) {
271 bond->bond_revalidate = false;
274 if (bond->balance == BM_AB || !bond->hash || revalidate) {
275 bond_entry_reset(bond);
282 bond_slave_set_netdev__(struct bond_slave *slave, struct netdev *netdev)
284 if (slave->netdev != netdev) {
285 slave->netdev = netdev;
286 slave->change_seq = 0;
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.
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.
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'.
304 bond_slave_register(struct bond *bond, void *slave_, uint32_t stb_id,
305 struct netdev *netdev)
307 struct bond_slave *slave = bond_slave_lookup(bond, slave_);
310 slave = xzalloc(sizeof *slave);
312 hmap_insert(&bond->slaves, &slave->hmap_node, hash_pointer(slave_, 0));
315 slave->delay_expires = LLONG_MAX;
316 slave->name = xstrdup(netdev_get_name(netdev));
317 bond->bond_revalidate = true;
319 slave->enabled = false;
320 bond_enable_slave(slave, netdev_get_carrier(netdev), NULL);
323 if (slave->stb_id != stb_id) {
324 slave->stb_id = stb_id;
325 bond->bond_revalidate = true;
328 bond_slave_set_netdev__(slave, netdev);
331 slave->name = xstrdup(netdev_get_name(netdev));
334 /* Updates the network device to be used with 'slave_' to 'netdev'.
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
340 bond_slave_set_netdev(struct bond *bond, void *slave_, struct netdev *netdev)
342 struct bond_slave *slave = bond_slave_lookup(bond, slave_);
344 bond_slave_set_netdev__(slave, netdev);
348 /* Unregisters 'slave_' from 'bond'. If 'bond' does not contain such a slave
349 * then this function has no effect.
351 * Unregistering a slave invalidates all flows. */
353 bond_slave_unregister(struct bond *bond, const void *slave_)
355 struct bond_slave *slave = bond_slave_lookup(bond, slave_);
362 bond_enable_slave(slave, false, NULL);
364 del_active = bond->active_slave == slave;
366 struct bond_entry *e;
367 for (e = bond->hash; e <= &bond->hash[BOND_MASK]; e++) {
368 if (e->slave == slave) {
376 hmap_remove(&bond->slaves, &slave->hmap_node);
377 /* Client owns 'slave->netdev'. */
384 bond_choose_active_slave(bond, &tags);
385 bond->send_learning_packets = true;
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. */
395 bond_slave_set_may_enable(struct bond *bond, void *slave_, bool may_enable)
397 bond_slave_lookup(bond, slave_)->may_enable = may_enable;
400 /* Performs periodic maintenance on 'bond'. The caller must provide 'tags' to
401 * allow tagged flows to be invalidated.
403 * The caller should check bond_should_send_learning_packets() afterward. */
405 bond_run(struct bond *bond, struct tag_set *tags, enum lacp_status lacp_status)
407 struct bond_slave *slave;
409 if (bond->lacp_status != lacp_status) {
410 bond->lacp_status = lacp_status;
411 bond->bond_revalidate = true;
414 /* Enable slaves based on link status and LACP feedback. */
415 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
416 bond_link_status_update(slave, tags);
417 slave->change_seq = netdev_change_seq(slave->netdev);
419 if (!bond->active_slave || !bond->active_slave->enabled) {
420 bond_choose_active_slave(bond, tags);
423 /* Update fake bond interface stats. */
424 if (time_msec() >= bond->next_fake_iface_update) {
425 bond_update_fake_slave_stats(bond);
426 bond->next_fake_iface_update = time_msec() + 1000;
429 if (bond->bond_revalidate) {
430 bond->bond_revalidate = false;
432 bond_entry_reset(bond);
433 if (bond->balance != BM_STABLE) {
434 struct bond_slave *slave;
436 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
437 tag_set_add(tags, slave->tag);
440 tag_set_add(tags, bond->stb_tag);
442 tag_set_add(tags, bond->no_slaves_tag);
445 /* Invalidate any tags required by */
446 tag_set_union(tags, &bond->unixctl_tags);
447 tag_set_init(&bond->unixctl_tags);
450 /* Causes poll_block() to wake up when 'bond' needs something to be done. */
452 bond_wait(struct bond *bond)
454 struct bond_slave *slave;
456 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
457 if (slave->delay_expires != LLONG_MAX) {
458 poll_timer_wait_until(slave->delay_expires);
461 if (slave->change_seq != netdev_change_seq(slave->netdev)) {
462 poll_immediate_wake();
466 if (bond->next_fake_iface_update != LLONG_MAX) {
467 poll_timer_wait_until(bond->next_fake_iface_update);
470 /* Ensure that any saved tags get revalidated right away. */
471 if (!tag_set_is_empty(&bond->unixctl_tags)) {
472 poll_immediate_wake();
475 /* We don't wait for bond->next_rebalance because rebalancing can only run
476 * at a flow account checkpoint. ofproto does checkpointing on its own
477 * schedule and bond_rebalance() gets called afterward, so we'd just be
478 * waking up for no purpose. */
481 /* MAC learning table interaction. */
484 may_send_learning_packets(const struct bond *bond)
486 return bond->lacp_status == LACP_DISABLED
487 && bond->balance != BM_AB
488 && bond->active_slave;
491 /* Returns true if 'bond' needs the client to send out packets to assist with
492 * MAC learning on 'bond'. If this function returns true, then the client
493 * should iterate through its MAC learning table for the bridge on which 'bond'
494 * is located. For each MAC that has been learned on a port other than 'bond',
495 * it should call bond_compose_learning_packet().
497 * This function will only return true if 'bond' is in SLB mode and LACP is not
498 * negotiated. Otherwise sending learning packets isn't necessary.
500 * Calling this function resets the state that it checks. */
502 bond_should_send_learning_packets(struct bond *bond)
504 bool send = bond->send_learning_packets && may_send_learning_packets(bond);
505 bond->send_learning_packets = false;
509 /* Sends a gratuitous learning packet on 'bond' from 'eth_src' on 'vlan'.
511 * See bond_should_send_learning_packets() for description of usage. The
512 * caller should send the composed packet on the port associated with
513 * port_aux and takes ownership of the returned ofpbuf. */
515 bond_compose_learning_packet(struct bond *bond,
516 const uint8_t eth_src[ETH_ADDR_LEN],
517 uint16_t vlan, void **port_aux)
519 struct bond_slave *slave;
520 struct ofpbuf *packet;
523 assert(may_send_learning_packets(bond));
525 memset(&flow, 0, sizeof flow);
526 memcpy(flow.dl_src, eth_src, ETH_ADDR_LEN);
527 slave = choose_output_slave(bond, &flow, vlan);
529 packet = ofpbuf_new(0);
530 compose_benign_packet(packet, "Open vSwitch Bond Failover", 0xf177,
533 eth_push_vlan(packet, htons(vlan));
536 *port_aux = slave->aux;
540 /* Checks whether a packet that arrived on 'slave_' within 'bond', with an
541 * Ethernet destination address of 'eth_dst', should be admitted.
543 * The return value is one of the following:
545 * - BV_ACCEPT: Admit the packet.
547 * - BV_DROP: Drop the packet.
549 * - BV_DROP_IF_MOVED: Consult the MAC learning table for the packet's
550 * Ethernet source address and VLAN. If there is none, or if the packet
551 * is on the learned port, then admit the packet. If a different port has
552 * been learned, however, drop the packet (and do not use it for MAC
556 bond_check_admissibility(struct bond *bond, const void *slave_,
557 const uint8_t eth_dst[ETH_ADDR_LEN], tag_type *tags)
559 struct bond_slave *slave = bond_slave_lookup(bond, slave_);
561 /* LACP bonds have very loose admissibility restrictions because we can
562 * assume the remote switch is aware of the bond and will "do the right
563 * thing". However, as a precaution we drop packets on disabled slaves
564 * because no correctly implemented partner switch should be sending
567 * If LACP is configured, but LACP negotiations have been unsuccessful, we
568 * drop all incoming traffic. */
569 switch (bond->lacp_status) {
570 case LACP_NEGOTIATED: return slave->enabled ? BV_ACCEPT : BV_DROP;
571 case LACP_CONFIGURED: return BV_DROP;
572 case LACP_DISABLED: break;
575 /* Drop all multicast packets on inactive slaves. */
576 if (eth_addr_is_multicast(eth_dst)) {
577 *tags |= bond_get_active_slave_tag(bond);
578 if (bond->active_slave != bond_slave_lookup(bond, slave_)) {
583 switch (bond->balance) {
585 /* Drop all packets which arrive on backup slaves. This is similar to
586 * how Linux bonding handles active-backup bonds. */
587 *tags |= bond_get_active_slave_tag(bond);
588 if (bond->active_slave != slave) {
589 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
591 VLOG_DBG_RL(&rl, "active-backup bond received packet on backup"
592 " slave (%s) destined for " ETH_ADDR_FMT,
593 slave->name, ETH_ADDR_ARGS(eth_dst));
599 /* TCP balanced bonds require successful LACP negotiated. Based on the
600 * above check, LACP is off on this bond. Therfore, we drop all
601 * incoming traffic. */
605 /* Drop all packets for which we have learned a different input port,
606 * because we probably sent the packet on one slave and got it back on
607 * the other. Gratuitous ARP packets are an exception to this rule:
608 * the host has moved to another switch. The exception to the
609 * exception is if we locked the learning table to avoid reflections on
611 return BV_DROP_IF_MOVED;
620 /* Returns the slave (registered on 'bond' by bond_slave_register()) to which
621 * a packet with the given 'flow' and 'vlan' should be forwarded. Returns
622 * NULL if the packet should be dropped because no slaves are enabled.
624 * 'vlan' is not necessarily the same as 'flow->vlan_tci'. First, 'vlan'
625 * should be a VID only (i.e. excluding the PCP bits). Second,
626 * 'flow->vlan_tci' is the VLAN TCI that appeared on the packet (so it will be
627 * nonzero only for trunk ports), whereas 'vlan' is the logical VLAN that the
628 * packet belongs to (so for an access port it will be the access port's VLAN).
630 * Adds a tag to '*tags' that associates the flow with the returned slave.
633 bond_choose_output_slave(struct bond *bond, const struct flow *flow,
634 uint16_t vlan, tag_type *tags)
636 struct bond_slave *slave = choose_output_slave(bond, flow, vlan);
638 *tags |= bond->balance == BM_STABLE ? bond->stb_tag : slave->tag;
641 *tags |= bond->no_slaves_tag;
649 bond_is_balanced(const struct bond *bond)
651 return bond->balance == BM_SLB || bond->balance == BM_TCP;
654 /* Notifies 'bond' that 'n_bytes' bytes were sent in 'flow' within 'vlan'. */
656 bond_account(struct bond *bond, const struct flow *flow, uint16_t vlan,
659 if (bond_is_balanced(bond)) {
660 lookup_bond_entry(bond, flow, vlan)->tx_bytes += n_bytes;
664 static struct bond_slave *
665 bond_slave_from_bal_node(struct list *bal)
667 return CONTAINER_OF(bal, struct bond_slave, bal_node);
671 log_bals(struct bond *bond, const struct list *bals)
673 if (VLOG_IS_DBG_ENABLED()) {
674 struct ds ds = DS_EMPTY_INITIALIZER;
675 const struct bond_slave *slave;
677 LIST_FOR_EACH (slave, bal_node, bals) {
679 ds_put_char(&ds, ',');
681 ds_put_format(&ds, " %s %"PRIu64"kB",
682 slave->name, slave->tx_bytes / 1024);
684 if (!slave->enabled) {
685 ds_put_cstr(&ds, " (disabled)");
687 if (!list_is_empty(&slave->entries)) {
688 struct bond_entry *e;
690 ds_put_cstr(&ds, " (");
691 LIST_FOR_EACH (e, list_node, &slave->entries) {
692 if (&e->list_node != list_front(&slave->entries)) {
693 ds_put_cstr(&ds, " + ");
695 ds_put_format(&ds, "h%td: %"PRIu64"kB",
696 e - bond->hash, e->tx_bytes / 1024);
698 ds_put_cstr(&ds, ")");
701 VLOG_DBG("bond %s:%s", bond->name, ds_cstr(&ds));
706 /* Shifts 'hash' from its current slave to 'to'. */
708 bond_shift_load(struct bond_entry *hash, struct bond_slave *to,
711 struct bond_slave *from = hash->slave;
712 struct bond *bond = from->bond;
713 uint64_t delta = hash->tx_bytes;
715 VLOG_INFO("bond %s: shift %"PRIu64"kB of load (with hash %td) "
716 "from %s to %s (now carrying %"PRIu64"kB and "
717 "%"PRIu64"kB load, respectively)",
718 bond->name, delta / 1024, hash - bond->hash,
719 from->name, to->name,
720 (from->tx_bytes - delta) / 1024,
721 (to->tx_bytes + delta) / 1024);
723 /* Shift load away from 'from' to 'to'. */
724 from->tx_bytes -= delta;
725 to->tx_bytes += delta;
727 /* Arrange for flows to be revalidated. */
728 tag_set_add(set, hash->tag);
730 hash->tag = tag_create_random();
733 /* Pick and returns a bond_entry to migrate to 'to' (the least-loaded slave),
734 * given that doing so must decrease the ratio of the load on the two slaves by
735 * at least 0.1. Returns NULL if there is no appropriate entry.
737 * The list of entries isn't sorted. I don't know of a reason to prefer to
738 * shift away small hashes or large hashes. */
739 static struct bond_entry *
740 choose_entry_to_migrate(const struct bond_slave *from, uint64_t to_tx_bytes)
742 struct bond_entry *e;
744 if (list_is_short(&from->entries)) {
745 /* 'from' carries no more than one MAC hash, so shifting load away from
746 * it would be pointless. */
750 LIST_FOR_EACH (e, list_node, &from->entries) {
751 double old_ratio, new_ratio;
754 if (to_tx_bytes == 0) {
755 /* Nothing on the new slave, move it. */
760 old_ratio = (double)from->tx_bytes / to_tx_bytes;
761 new_ratio = (double)(from->tx_bytes - delta) / (to_tx_bytes + delta);
762 if (old_ratio - new_ratio > 0.1) {
763 /* Would decrease the ratio, move it. */
771 /* Inserts 'slave' into 'bals' so that descending order of 'tx_bytes' is
774 insert_bal(struct list *bals, struct bond_slave *slave)
776 struct bond_slave *pos;
778 LIST_FOR_EACH (pos, bal_node, bals) {
779 if (slave->tx_bytes > pos->tx_bytes) {
783 list_insert(&pos->bal_node, &slave->bal_node);
786 /* Removes 'slave' from its current list and then inserts it into 'bals' so
787 * that descending order of 'tx_bytes' is maintained. */
789 reinsert_bal(struct list *bals, struct bond_slave *slave)
791 list_remove(&slave->bal_node);
792 insert_bal(bals, slave);
795 /* If 'bond' needs rebalancing, does so.
797 * The caller should have called bond_account() for each active flow, to ensure
798 * that flow data is consistently accounted at this point. */
800 bond_rebalance(struct bond *bond, struct tag_set *tags)
802 struct bond_slave *slave;
803 struct bond_entry *e;
806 if (!bond_is_balanced(bond) || time_msec() < bond->next_rebalance) {
809 bond->next_rebalance = time_msec() + bond->rebalance_interval;
811 /* Add each bond_entry to its slave's 'entries' list.
812 * Compute each slave's tx_bytes as the sum of its entries' tx_bytes. */
813 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
815 list_init(&slave->entries);
817 for (e = &bond->hash[0]; e <= &bond->hash[BOND_MASK]; e++) {
818 if (e->slave && e->tx_bytes) {
819 e->slave->tx_bytes += e->tx_bytes;
820 list_push_back(&e->slave->entries, &e->list_node);
824 /* Add enabled slaves to 'bals' in descending order of tx_bytes.
826 * XXX This is O(n**2) in the number of slaves but it could be O(n lg n)
827 * with a proper list sort algorithm. */
829 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
830 if (slave->enabled) {
831 insert_bal(&bals, slave);
834 log_bals(bond, &bals);
836 /* Shift load from the most-loaded slaves to the least-loaded slaves. */
837 while (!list_is_short(&bals)) {
838 struct bond_slave *from = bond_slave_from_bal_node(list_front(&bals));
839 struct bond_slave *to = bond_slave_from_bal_node(list_back(&bals));
842 overload = from->tx_bytes - to->tx_bytes;
843 if (overload < to->tx_bytes >> 5 || overload < 100000) {
844 /* The extra load on 'from' (and all less-loaded slaves), compared
845 * to that of 'to' (the least-loaded slave), is less than ~3%, or
846 * it is less than ~1Mbps. No point in rebalancing. */
850 /* 'from' is carrying significantly more load than 'to', and that load
851 * is split across at least two different hashes. */
852 e = choose_entry_to_migrate(from, to->tx_bytes);
854 bond_shift_load(e, to, tags);
856 /* Delete element from from->entries.
858 * We don't add the element to to->hashes. That would only allow
859 * 'e' to be migrated to another slave in this rebalancing run, and
860 * there is no point in doing that. */
861 list_remove(&e->list_node);
863 /* Re-sort 'bals'. */
864 reinsert_bal(&bals, from);
865 reinsert_bal(&bals, to);
867 /* Can't usefully migrate anything away from 'from'.
868 * Don't reconsider it. */
869 list_remove(&from->bal_node);
873 /* Implement exponentially weighted moving average. A weight of 1/2 causes
874 * historical data to decay to <1% in 7 rebalancing runs. 1,000,000 bytes
875 * take 20 rebalancing runs to decay to 0 and get deleted entirely. */
876 for (e = &bond->hash[0]; e <= &bond->hash[BOND_MASK]; e++) {
884 /* Bonding unixctl user interface functions. */
887 bond_find(const char *name)
891 HMAP_FOR_EACH_WITH_HASH (bond, hmap_node, hash_string(name, 0),
893 if (!strcmp(bond->name, name)) {
900 static struct bond_slave *
901 bond_lookup_slave(struct bond *bond, const char *slave_name)
903 struct bond_slave *slave;
905 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
906 if (!strcmp(slave->name, slave_name)) {
914 bond_unixctl_list(struct unixctl_conn *conn,
915 int argc OVS_UNUSED, const char *argv[] OVS_UNUSED,
916 void *aux OVS_UNUSED)
918 struct ds ds = DS_EMPTY_INITIALIZER;
919 const struct bond *bond;
921 ds_put_cstr(&ds, "bond\ttype\tslaves\n");
923 HMAP_FOR_EACH (bond, hmap_node, &all_bonds) {
924 const struct bond_slave *slave;
927 ds_put_format(&ds, "%s\t%s\t",
928 bond->name, bond_mode_to_string(bond->balance));
931 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
933 ds_put_cstr(&ds, ", ");
935 ds_put_cstr(&ds, slave->name);
937 ds_put_char(&ds, '\n');
939 unixctl_command_reply(conn, 200, ds_cstr(&ds));
944 bond_print_details(struct ds *ds, const struct bond *bond)
946 struct shash slave_shash = SHASH_INITIALIZER(&slave_shash);
947 const struct shash_node **sorted_slaves = NULL;
948 const struct bond_slave *slave;
951 ds_put_format(ds, "---- %s ----\n", bond->name);
952 ds_put_format(ds, "bond_mode: %s\n",
953 bond_mode_to_string(bond->balance));
955 ds_put_format(ds, "bond-hash-basis: %"PRIu32"\n", bond->basis);
957 ds_put_format(ds, "updelay: %d ms\n", bond->updelay);
958 ds_put_format(ds, "downdelay: %d ms\n", bond->downdelay);
960 if (bond_is_balanced(bond)) {
961 ds_put_format(ds, "next rebalance: %lld ms\n",
962 bond->next_rebalance - time_msec());
965 ds_put_cstr(ds, "lacp_status: ");
966 switch (bond->lacp_status) {
967 case LACP_NEGOTIATED:
968 ds_put_cstr(ds, "negotiated\n");
970 case LACP_CONFIGURED:
971 ds_put_cstr(ds, "configured\n");
974 ds_put_cstr(ds, "off\n");
977 ds_put_cstr(ds, "<unknown>\n");
981 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
982 shash_add(&slave_shash, slave->name, slave);
984 sorted_slaves = shash_sort(&slave_shash);
986 for (i = 0; i < shash_count(&slave_shash); i++) {
987 struct bond_entry *be;
989 slave = sorted_slaves[i]->data;
992 ds_put_format(ds, "\nslave %s: %s\n",
993 slave->name, slave->enabled ? "enabled" : "disabled");
994 if (slave == bond->active_slave) {
995 ds_put_cstr(ds, "\tactive slave\n");
997 if (slave->delay_expires != LLONG_MAX) {
998 ds_put_format(ds, "\t%s expires in %lld ms\n",
999 slave->enabled ? "downdelay" : "updelay",
1000 slave->delay_expires - time_msec());
1003 ds_put_format(ds, "\tmay_enable: %s\n",
1004 slave->may_enable ? "true" : "false");
1006 if (!bond_is_balanced(bond)) {
1011 for (be = bond->hash; be <= &bond->hash[BOND_MASK]; be++) {
1012 int hash = be - bond->hash;
1014 if (be->slave != slave) {
1018 ds_put_format(ds, "\thash %d: %"PRIu64" kB load\n",
1019 hash, be->tx_bytes / 1024);
1021 /* XXX How can we list the MACs assigned to hashes of SLB bonds? */
1024 shash_destroy(&slave_shash);
1025 free(sorted_slaves);
1026 ds_put_cstr(ds, "\n");
1030 bond_unixctl_show(struct unixctl_conn *conn,
1031 int argc, const char *argv[],
1032 void *aux OVS_UNUSED)
1034 struct ds ds = DS_EMPTY_INITIALIZER;
1037 const struct bond *bond = bond_find(argv[1]);
1040 unixctl_command_reply(conn, 501, "no such bond");
1043 bond_print_details(&ds, bond);
1045 const struct bond *bond;
1047 HMAP_FOR_EACH (bond, hmap_node, &all_bonds) {
1048 bond_print_details(&ds, bond);
1052 unixctl_command_reply(conn, 200, ds_cstr(&ds));
1057 bond_unixctl_migrate(struct unixctl_conn *conn,
1058 int argc OVS_UNUSED, const char *argv[],
1059 void *aux OVS_UNUSED)
1061 const char *bond_s = argv[1];
1062 const char *hash_s = argv[2];
1063 const char *slave_s = argv[3];
1065 struct bond_slave *slave;
1066 struct bond_entry *entry;
1069 bond = bond_find(bond_s);
1071 unixctl_command_reply(conn, 501, "no such bond");
1075 if (bond->balance != BM_SLB) {
1076 unixctl_command_reply(conn, 501, "not an SLB bond");
1080 if (strspn(hash_s, "0123456789") == strlen(hash_s)) {
1081 hash = atoi(hash_s) & BOND_MASK;
1083 unixctl_command_reply(conn, 501, "bad hash");
1087 slave = bond_lookup_slave(bond, slave_s);
1089 unixctl_command_reply(conn, 501, "no such slave");
1093 if (!slave->enabled) {
1094 unixctl_command_reply(conn, 501, "cannot migrate to disabled slave");
1098 entry = &bond->hash[hash];
1099 tag_set_add(&bond->unixctl_tags, entry->tag);
1100 entry->slave = slave;
1101 entry->tag = tag_create_random();
1102 unixctl_command_reply(conn, 200, "migrated");
1106 bond_unixctl_set_active_slave(struct unixctl_conn *conn,
1107 int argc OVS_UNUSED, const char *argv[],
1108 void *aux OVS_UNUSED)
1110 const char *bond_s = argv[1];
1111 const char *slave_s = argv[2];
1113 struct bond_slave *slave;
1115 bond = bond_find(bond_s);
1117 unixctl_command_reply(conn, 501, "no such bond");
1121 slave = bond_lookup_slave(bond, slave_s);
1123 unixctl_command_reply(conn, 501, "no such slave");
1127 if (!slave->enabled) {
1128 unixctl_command_reply(conn, 501, "cannot make disabled slave active");
1132 if (bond->active_slave != slave) {
1133 tag_set_add(&bond->unixctl_tags, bond_get_active_slave_tag(bond));
1134 bond->active_slave = slave;
1135 bond->active_slave->tag = tag_create_random();
1136 VLOG_INFO("bond %s: active interface is now %s",
1137 bond->name, slave->name);
1138 bond->send_learning_packets = true;
1139 unixctl_command_reply(conn, 200, "done");
1141 unixctl_command_reply(conn, 200, "no change");
1146 enable_slave(struct unixctl_conn *conn, const char *argv[], bool enable)
1148 const char *bond_s = argv[1];
1149 const char *slave_s = argv[2];
1151 struct bond_slave *slave;
1153 bond = bond_find(bond_s);
1155 unixctl_command_reply(conn, 501, "no such bond");
1159 slave = bond_lookup_slave(bond, slave_s);
1161 unixctl_command_reply(conn, 501, "no such slave");
1165 bond_enable_slave(slave, enable, &bond->unixctl_tags);
1166 unixctl_command_reply(conn, 501, enable ? "enabled" : "disabled");
1170 bond_unixctl_enable_slave(struct unixctl_conn *conn,
1171 int argc OVS_UNUSED, const char *argv[],
1172 void *aux OVS_UNUSED)
1174 enable_slave(conn, argv, true);
1178 bond_unixctl_disable_slave(struct unixctl_conn *conn,
1179 int argc OVS_UNUSED, const char *argv[],
1180 void *aux OVS_UNUSED)
1182 enable_slave(conn, argv, false);
1186 bond_unixctl_hash(struct unixctl_conn *conn, int argc, const char *argv[],
1187 void *aux OVS_UNUSED)
1189 const char *mac_s = argv[1];
1190 const char *vlan_s = argc > 2 ? argv[2] : NULL;
1191 const char *basis_s = argc > 3 ? argv[3] : NULL;
1192 uint8_t mac[ETH_ADDR_LEN];
1199 if (sscanf(vlan_s, "%u", &vlan) != 1) {
1200 unixctl_command_reply(conn, 501, "invalid vlan");
1208 if (sscanf(basis_s, "%"PRIu32, &basis) != 1) {
1209 unixctl_command_reply(conn, 501, "invalid basis");
1216 if (sscanf(mac_s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
1217 == ETH_ADDR_SCAN_COUNT) {
1218 hash = bond_hash_src(mac, vlan, basis) & BOND_MASK;
1220 hash_cstr = xasprintf("%u", hash);
1221 unixctl_command_reply(conn, 200, hash_cstr);
1224 unixctl_command_reply(conn, 501, "invalid mac");
1231 unixctl_command_register("bond/list", "", 0, 0, bond_unixctl_list, NULL);
1232 unixctl_command_register("bond/show", "[port]", 0, 1, bond_unixctl_show,
1234 unixctl_command_register("bond/migrate", "port hash slave", 3, 3,
1235 bond_unixctl_migrate, NULL);
1236 unixctl_command_register("bond/set-active-slave", "port slave", 2, 2,
1237 bond_unixctl_set_active_slave, NULL);
1238 unixctl_command_register("bond/enable-slave", "port slave", 2, 2,
1239 bond_unixctl_enable_slave, NULL);
1240 unixctl_command_register("bond/disable-slave", "port slave", 2, 2,
1241 bond_unixctl_disable_slave, NULL);
1242 unixctl_command_register("bond/hash", "mac [vlan] [basis]", 1, 3,
1243 bond_unixctl_hash, NULL);
1247 bond_entry_reset(struct bond *bond)
1249 if (bond->balance != BM_AB) {
1250 size_t hash_len = (BOND_MASK + 1) * sizeof *bond->hash;
1253 bond->hash = xmalloc(hash_len);
1255 memset(bond->hash, 0, hash_len);
1257 bond->next_rebalance = time_msec() + bond->rebalance_interval;
1264 static struct bond_slave *
1265 bond_slave_lookup(struct bond *bond, const void *slave_)
1267 struct bond_slave *slave;
1269 HMAP_FOR_EACH_IN_BUCKET (slave, hmap_node, hash_pointer(slave_, 0),
1271 if (slave->aux == slave_) {
1280 bond_enable_slave(struct bond_slave *slave, bool enable, struct tag_set *tags)
1282 struct bond *bond = slave->bond;
1283 slave->delay_expires = LLONG_MAX;
1284 if (enable != slave->enabled) {
1285 slave->enabled = enable;
1286 if (!slave->enabled) {
1287 VLOG_WARN("interface %s: disabled", slave->name);
1289 tag_set_add(tags, slave->tag);
1292 VLOG_WARN("interface %s: enabled", slave->name);
1293 slave->tag = tag_create_random();
1296 if (bond->balance == BM_STABLE) {
1297 bond->bond_revalidate = true;
1303 bond_link_status_update(struct bond_slave *slave, struct tag_set *tags)
1305 struct bond *bond = slave->bond;
1308 up = netdev_get_carrier(slave->netdev) && slave->may_enable;
1309 if ((up == slave->enabled) != (slave->delay_expires == LLONG_MAX)) {
1310 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1311 VLOG_INFO_RL(&rl, "interface %s: link state %s",
1312 slave->name, up ? "up" : "down");
1313 if (up == slave->enabled) {
1314 slave->delay_expires = LLONG_MAX;
1315 VLOG_INFO_RL(&rl, "interface %s: will not be %s",
1316 slave->name, up ? "disabled" : "enabled");
1318 int delay = (bond->lacp_status != LACP_DISABLED ? 0
1319 : up ? bond->updelay : bond->downdelay);
1320 slave->delay_expires = time_msec() + delay;
1322 VLOG_INFO_RL(&rl, "interface %s: will be %s if it stays %s "
1325 up ? "enabled" : "disabled",
1332 if (time_msec() >= slave->delay_expires) {
1333 bond_enable_slave(slave, up, tags);
1338 bond_hash_src(const uint8_t mac[ETH_ADDR_LEN], uint16_t vlan, uint32_t basis)
1340 return hash_3words(hash_bytes(mac, ETH_ADDR_LEN, 0), vlan, basis);
1344 bond_hash_tcp(const struct flow *flow, uint16_t vlan, uint32_t basis)
1346 struct flow hash_flow = *flow;
1347 hash_flow.vlan_tci = htons(vlan);
1349 /* The symmetric quality of this hash function is not required, but
1350 * flow_hash_symmetric_l4 already exists, and is sufficient for our
1351 * purposes, so we use it out of convenience. */
1352 return flow_hash_symmetric_l4(&hash_flow, basis);
1356 bond_hash(const struct bond *bond, const struct flow *flow, uint16_t vlan)
1358 assert(bond->balance == BM_TCP || bond->balance == BM_SLB);
1360 return (bond->balance == BM_TCP
1361 ? bond_hash_tcp(flow, vlan, bond->basis)
1362 : bond_hash_src(flow->dl_src, vlan, bond->basis));
1365 static struct bond_entry *
1366 lookup_bond_entry(const struct bond *bond, const struct flow *flow,
1369 return &bond->hash[bond_hash(bond, flow, vlan) & BOND_MASK];
1372 /* This function uses Highest Random Weight hashing to choose an output slave.
1373 * This approach only reassigns a minimal number of flows when slaves are
1374 * enabled or disabled. Unfortunately, it has O(n) performance against the
1375 * number of slaves. There exist algorithms which are O(1), but have slightly
1376 * more complex implementations and require the use of memory. This may need
1377 * to be reimplemented if it becomes a performance bottleneck. */
1378 static struct bond_slave *
1379 choose_stb_slave(const struct bond *bond, const struct flow *flow,
1382 struct bond_slave *best, *slave;
1383 uint32_t best_hash, flow_hash;
1387 flow_hash = bond_hash_tcp(flow, vlan, bond->basis);
1388 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1389 if (slave->enabled) {
1392 hash = hash_2words(flow_hash, slave->stb_id);
1393 if (!best || hash > best_hash) {
1403 static struct bond_slave *
1404 choose_output_slave(const struct bond *bond, const struct flow *flow,
1407 struct bond_entry *e;
1409 if (bond->lacp_status == LACP_CONFIGURED) {
1410 /* LACP has been configured on this bond but negotiations were
1411 * unsuccussful. Drop all traffic. */
1415 switch (bond->balance) {
1417 return bond->active_slave;
1420 return choose_stb_slave(bond, flow, vlan);
1423 if (bond->lacp_status != LACP_NEGOTIATED) {
1424 /* Must have LACP negotiations for TCP balanced bonds. */
1429 e = lookup_bond_entry(bond, flow, vlan);
1430 if (!e->slave || !e->slave->enabled) {
1431 e->slave = CONTAINER_OF(hmap_random_node(&bond->slaves),
1432 struct bond_slave, hmap_node);
1433 if (!e->slave->enabled) {
1434 e->slave = bond->active_slave;
1436 e->tag = tag_create_random();
1445 static struct bond_slave *
1446 bond_choose_slave(const struct bond *bond)
1448 struct bond_slave *slave, *best;
1450 /* Find an enabled slave. */
1451 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1452 if (slave->enabled) {
1457 /* All interfaces are disabled. Find an interface that will be enabled
1458 * after its updelay expires. */
1460 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1461 if (slave->delay_expires != LLONG_MAX
1462 && slave->may_enable
1463 && (!best || slave->delay_expires < best->delay_expires)) {
1471 bond_choose_active_slave(struct bond *bond, struct tag_set *tags)
1473 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1474 struct bond_slave *old_active_slave = bond->active_slave;
1476 bond->active_slave = bond_choose_slave(bond);
1477 if (bond->active_slave) {
1478 if (bond->active_slave->enabled) {
1479 VLOG_INFO_RL(&rl, "bond %s: active interface is now %s",
1480 bond->name, bond->active_slave->name);
1482 VLOG_INFO_RL(&rl, "bond %s: active interface is now %s, skipping "
1483 "remaining %lld ms updelay (since no interface was "
1484 "enabled)", bond->name, bond->active_slave->name,
1485 bond->active_slave->delay_expires - time_msec());
1486 bond_enable_slave(bond->active_slave, true, tags);
1489 if (!old_active_slave) {
1490 tag_set_add(tags, bond->no_slaves_tag);
1493 bond->send_learning_packets = true;
1494 } else if (old_active_slave) {
1495 VLOG_WARN_RL(&rl, "bond %s: all interfaces disabled", bond->name);
1499 /* Returns the tag for 'bond''s active slave, or 'bond''s no_slaves_tag if
1500 * there is no active slave. */
1502 bond_get_active_slave_tag(const struct bond *bond)
1504 return (bond->active_slave
1505 ? bond->active_slave->tag
1506 : bond->no_slaves_tag);
1509 /* Attempts to make the sum of the bond slaves' statistics appear on the fake
1510 * bond interface. */
1512 bond_update_fake_slave_stats(struct bond *bond)
1514 struct netdev_stats bond_stats;
1515 struct bond_slave *slave;
1516 struct netdev *bond_dev;
1518 memset(&bond_stats, 0, sizeof bond_stats);
1520 HMAP_FOR_EACH (slave, hmap_node, &bond->slaves) {
1521 struct netdev_stats slave_stats;
1523 if (!netdev_get_stats(slave->netdev, &slave_stats)) {
1524 /* XXX: We swap the stats here because they are swapped back when
1525 * reported by the internal device. The reason for this is
1526 * internal devices normally represent packets going into the
1527 * system but when used as fake bond device they represent packets
1528 * leaving the system. We really should do this in the internal
1529 * device itself because changing it here reverses the counts from
1530 * the perspective of the switch. However, the internal device
1531 * doesn't know what type of device it represents so we have to do
1532 * it here for now. */
1533 bond_stats.tx_packets += slave_stats.rx_packets;
1534 bond_stats.tx_bytes += slave_stats.rx_bytes;
1535 bond_stats.rx_packets += slave_stats.tx_packets;
1536 bond_stats.rx_bytes += slave_stats.tx_bytes;
1540 if (!netdev_open(bond->name, "system", &bond_dev)) {
1541 netdev_set_stats(bond_dev, &bond_stats);
1542 netdev_close(bond_dev);