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