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