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