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