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