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