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