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