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