8d0a2ef6ec06c5101d7ae35f8d462f6f7bae43f1
[sliver-openvswitch.git] / vswitchd / bridge.c
1 /* Copyright (c) 2008, 2009 Nicira Networks
2  * 
3  * This program is free software: you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation, either version 3 of the License, or
6  * (at your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  * In addition, as a special exception, Nicira Networks gives permission
17  * to link the code of its release of vswitchd with the OpenSSL project's
18  * "OpenSSL" library (or with modified versions of it that use the same
19  * license as the "OpenSSL" library), and distribute the linked
20  * executables.  You must obey the GNU General Public License in all
21  * respects for all of the code used other than "OpenSSL".  If you modify
22  * this file, you may extend this exception to your version of the file,
23  * but you are not obligated to do so.  If you do not wish to do so,
24  * delete this exception statement from your version.
25  *
26  */
27
28 #include <config.h>
29 #include "bridge.h"
30 #include <assert.h>
31 #include <errno.h>
32 #include <arpa/inet.h>
33 #include <ctype.h>
34 #include <inttypes.h>
35 #include <net/if.h>
36 #include <openflow/openflow.h>
37 #include <signal.h>
38 #include <stdlib.h>
39 #include <strings.h>
40 #include <sys/stat.h>
41 #include <sys/socket.h>
42 #include <unistd.h>
43 #include "bitmap.h"
44 #include "cfg.h"
45 #include "coverage.h"
46 #include "dirs.h"
47 #include "dpif.h"
48 #include "dynamic-string.h"
49 #include "flow.h"
50 #include "hash.h"
51 #include "list.h"
52 #include "mac-learning.h"
53 #include "netdev.h"
54 #include "odp-util.h"
55 #include "ofp-print.h"
56 #include "ofpbuf.h"
57 #include "poll-loop.h"
58 #include "port-array.h"
59 #include "proc-net-compat.h"
60 #include "process.h"
61 #include "secchan/ofproto.h"
62 #include "socket-util.h"
63 #include "stp.h"
64 #include "svec.h"
65 #include "timeval.h"
66 #include "util.h"
67 #include "vconn.h"
68 #include "vconn-ssl.h"
69 #include "xenserver.h"
70 #include "xtoxll.h"
71
72 #define THIS_MODULE VLM_bridge
73 #include "vlog.h"
74
75 struct dst {
76     uint16_t vlan;
77     uint16_t dp_ifidx;
78 };
79
80 extern uint64_t mgmt_id;
81
82 struct iface {
83     struct port *port;          /* Containing port. */
84     size_t port_ifidx;          /* Index within containing port. */
85
86     char *name;                 /* Host network device name. */
87     int dp_ifidx;               /* Index within kernel datapath. */
88
89     uint8_t mac[ETH_ADDR_LEN];  /* Ethernet address (all zeros if unknowns). */
90
91     tag_type tag;               /* Tag associated with this interface. */
92     bool enabled;               /* May be chosen for flows? */
93     long long delay_expires;    /* Time after which 'enabled' may change. */
94 };
95
96 #define BOND_MASK 0xff
97 struct bond_entry {
98     int iface_idx;              /* Index of assigned iface, or -1 if none. */
99     uint64_t tx_bytes;          /* Count of bytes recently transmitted. */
100     tag_type iface_tag;         /* Tag associated with iface_idx. */
101 };
102
103 #define MAX_MIRRORS 32
104 typedef uint32_t mirror_mask_t;
105 #define MIRROR_MASK_C(X) UINT32_C(X)
106 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
107 struct mirror {
108     struct bridge *bridge;
109     size_t idx;
110     char *name;
111
112     /* Selection criteria. */
113     struct svec src_ports;
114     struct svec dst_ports;
115     int *vlans;
116     size_t n_vlans;
117
118     /* Output. */
119     struct port *out_port;
120     int out_vlan;
121 };
122
123 #define FLOOD_PORT ((struct port *) 1) /* The 'flood' output port. */
124 struct port {
125     struct bridge *bridge;
126     size_t port_idx;
127     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
128     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1. */
129     char *name;
130
131     /* An ordinary bridge port has 1 interface.
132      * A bridge port for bonding has at least 2 interfaces. */
133     struct iface **ifaces;
134     size_t n_ifaces, allocated_ifaces;
135
136     /* Bonding info. */
137     struct bond_entry *bond_hash; /* An array of (BOND_MASK + 1) elements. */
138     int active_iface;           /* Ifidx on which bcasts accepted, or -1. */
139     tag_type active_iface_tag;  /* Tag for bcast flows. */
140     tag_type no_ifaces_tag;     /* Tag for flows when all ifaces disabled. */
141     int updelay, downdelay;     /* Delay before iface goes up/down, in ms. */
142
143     /* Port mirroring info. */
144     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
145     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
146     bool is_mirror_output_port; /* Does port mirroring send frames here? */
147
148     /* Spanning tree info. */
149     enum stp_state stp_state;   /* Always STP_FORWARDING if STP not in use. */
150     tag_type stp_state_tag;     /* Tag for STP state change. */
151 };
152
153 #define DP_MAX_PORTS 255
154 struct bridge {
155     struct list node;           /* Node in global list of bridges. */
156     char *name;                 /* User-specified arbitrary name. */
157     struct mac_learning *ml;    /* MAC learning table, or null not to learn. */
158     bool sent_config_request;   /* Successfully sent config request? */
159     uint8_t default_ea[ETH_ADDR_LEN]; /* Default MAC. */
160
161     /* Support for remote controllers. */
162     char *controller;           /* NULL if there is no remote controller;
163                                  * "discover" to do controller discovery;
164                                  * otherwise a vconn name. */
165
166     /* OpenFlow switch processing. */
167     struct ofproto *ofproto;    /* OpenFlow switch. */
168
169     /* Kernel datapath information. */
170     struct dpif dpif;           /* Kernel datapath. */
171     struct port_array ifaces;   /* Indexed by kernel datapath port number. */
172
173     /* Bridge ports. */
174     struct port **ports;
175     size_t n_ports, allocated_ports;
176
177     /* Bonding. */
178     bool has_bonded_ports;
179     long long int bond_next_rebalance;
180
181     /* Flow tracking. */
182     bool flush;
183
184     /* Flow statistics gathering. */
185     time_t next_stats_request;
186
187     /* Port mirroring. */
188     struct mirror *mirrors[MAX_MIRRORS];
189
190     /* Spanning tree. */
191     struct stp *stp;
192     long long int stp_last_tick;
193 };
194
195 /* List of all bridges. */
196 static struct list all_bridges = LIST_INITIALIZER(&all_bridges);
197
198 /* Maximum number of datapaths. */
199 enum { DP_MAX = 256 };
200
201 static struct bridge *bridge_create(const char *name);
202 static void bridge_destroy(struct bridge *);
203 static struct bridge *bridge_lookup(const char *name);
204 static int bridge_run_one(struct bridge *);
205 static void bridge_reconfigure_one(struct bridge *);
206 static void bridge_reconfigure_controller(struct bridge *);
207 static void bridge_get_all_ifaces(const struct bridge *, struct svec *ifaces);
208 static void bridge_fetch_dp_ifaces(struct bridge *);
209 static void bridge_flush(struct bridge *);
210 static void bridge_pick_local_hw_addr(struct bridge *,
211                                       uint8_t ea[ETH_ADDR_LEN],
212                                       const char **devname);
213 static uint64_t bridge_pick_datapath_id(struct bridge *,
214                                         const uint8_t bridge_ea[ETH_ADDR_LEN],
215                                         const char *devname);
216 static uint64_t dpid_from_hash(const void *, size_t nbytes);
217
218 static void bond_run(struct bridge *);
219 static void bond_wait(struct bridge *);
220 static void bond_rebalance_port(struct port *);
221 static void bond_send_learning_packets(struct port *);
222
223 static void port_create(struct bridge *, const char *name);
224 static void port_reconfigure(struct port *);
225 static void port_destroy(struct port *);
226 static struct port *port_lookup(const struct bridge *, const char *name);
227 static struct port *port_from_dp_ifidx(const struct bridge *,
228                                        uint16_t dp_ifidx);
229 static void port_update_bond_compat(struct port *);
230 static void port_update_vlan_compat(struct port *);
231
232 static void mirror_create(struct bridge *, const char *name);
233 static void mirror_destroy(struct mirror *);
234 static void mirror_reconfigure(struct bridge *);
235 static void mirror_reconfigure_one(struct mirror *);
236 static bool vlan_is_mirrored(const struct mirror *, int vlan);
237
238 static void brstp_reconfigure(struct bridge *);
239 static void brstp_adjust_timers(struct bridge *);
240 static void brstp_run(struct bridge *);
241 static void brstp_wait(struct bridge *);
242
243 static void iface_create(struct port *, const char *name);
244 static void iface_destroy(struct iface *);
245 static struct iface *iface_lookup(const struct bridge *, const char *name);
246 static struct iface *iface_from_dp_ifidx(const struct bridge *,
247                                          uint16_t dp_ifidx);
248
249 /* Hooks into ofproto processing. */
250 static struct ofhooks bridge_ofhooks;
251 \f
252 /* Public functions. */
253
254 /* Adds the name of each interface used by a bridge, including local and
255  * internal ports, to 'svec'. */
256 void
257 bridge_get_ifaces(struct svec *svec) 
258 {
259     struct bridge *br, *next;
260     size_t i, j;
261
262     LIST_FOR_EACH_SAFE (br, next, struct bridge, node, &all_bridges) {
263         for (i = 0; i < br->n_ports; i++) {
264             struct port *port = br->ports[i];
265
266             for (j = 0; j < port->n_ifaces; j++) {
267                 struct iface *iface = port->ifaces[j];
268                 if (iface->dp_ifidx < 0) {
269                     VLOG_ERR("%s interface not in dp%u, ignoring",
270                              iface->name, dpif_id(&br->dpif));
271                 } else {
272                     if (iface->dp_ifidx != ODPP_LOCAL) {
273                         svec_add(svec, iface->name);
274                     }
275                 }
276             }
277         }
278     }
279 }
280
281 /* The caller must already have called cfg_read(). */
282 void
283 bridge_init(void)
284 {
285     int retval;
286     int i;
287
288     for (i = 0; i < DP_MAX; i++) {
289         struct dpif dpif;
290         char devname[16];
291
292         sprintf(devname, "dp%d", i);
293         retval = dpif_open(devname, &dpif);
294         if (!retval) {
295             char dpif_name[IF_NAMESIZE];
296             if (dpif_get_name(&dpif, dpif_name, sizeof dpif_name)
297                 || !cfg_has("bridge.%s.port", dpif_name)) {
298                 dpif_delete(&dpif);
299             }
300             dpif_close(&dpif);
301         } else if (retval != ENODEV) {
302             VLOG_ERR("failed to delete datapath dp%d: %s",
303                      i, strerror(retval));
304         }
305     }
306
307     bridge_reconfigure();
308 }
309
310 #ifdef HAVE_OPENSSL
311 static bool
312 config_string_change(const char *key, char **valuep)
313 {
314     const char *value = cfg_get_string(0, "%s", key);
315     if (value && (!*valuep || strcmp(value, *valuep))) {
316         free(*valuep);
317         *valuep = xstrdup(value);
318         return true;
319     } else {
320         return false;
321     }
322 }
323
324 static void
325 bridge_configure_ssl(void)
326 {
327     /* XXX SSL should be configurable on a per-bridge basis.
328      * XXX should be possible to de-configure SSL. */
329     static char *private_key_file;
330     static char *certificate_file;
331     static char *cacert_file;
332
333     if (config_string_change("ssl.private-key", &private_key_file)) {
334         vconn_ssl_set_private_key_file(private_key_file);
335     }
336
337     if (config_string_change("ssl.certificate", &certificate_file)) {
338         vconn_ssl_set_certificate_file(certificate_file);
339     }
340
341     if (config_string_change("ssl.ca-cert", &cacert_file)) {
342         vconn_ssl_set_ca_cert_file(cacert_file,
343                                    cfg_get_bool(0, "ssl.bootstrap-ca-cert"));
344     }
345 }
346 #endif
347
348 void
349 bridge_reconfigure(void)
350 {
351     struct svec old_br, new_br, raw_new_br;
352     struct bridge *br, *next;
353     size_t i, j;
354
355     COVERAGE_INC(bridge_reconfigure);
356
357     /* Collect old bridges. */
358     svec_init(&old_br);
359     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
360         svec_add(&old_br, br->name);
361     }
362
363     /* Collect new bridges. */
364     svec_init(&raw_new_br);
365     cfg_get_subsections(&raw_new_br, "bridge");
366     svec_init(&new_br);
367     for (i = 0; i < raw_new_br.n; i++) {
368         const char *name = raw_new_br.names[i];
369         if ((!strncmp(name, "dp", 2) && isdigit(name[2])) ||
370             (!strncmp(name, "nl:", 3) && isdigit(name[3]))) {
371             VLOG_ERR("%s is not a valid bridge name (bridges may not be "
372                      "named \"dp\" or \"nl:\" followed by a digit)", name);
373         } else {
374             svec_add(&new_br, name);
375         }
376     }
377     svec_destroy(&raw_new_br);
378
379     /* Get rid of deleted bridges and add new bridges. */
380     svec_sort(&old_br);
381     svec_sort(&new_br);
382     assert(svec_is_unique(&old_br));
383     assert(svec_is_unique(&new_br));
384     LIST_FOR_EACH_SAFE (br, next, struct bridge, node, &all_bridges) {
385         if (!svec_contains(&new_br, br->name)) {
386             bridge_destroy(br);
387         }
388     }
389     for (i = 0; i < new_br.n; i++) {
390         const char *name = new_br.names[i];
391         if (!svec_contains(&old_br, name)) {
392             bridge_create(name);
393         }
394     }
395     svec_destroy(&old_br);
396     svec_destroy(&new_br);
397
398 #ifdef HAVE_OPENSSL
399     /* Configure SSL. */
400     bridge_configure_ssl();
401 #endif
402
403     /* Reconfigure all bridges. */
404     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
405         bridge_reconfigure_one(br);
406     }
407
408     /* Add and delete ports on all datapaths.
409      *
410      * The kernel will reject any attempt to add a given port to a datapath if
411      * that port already belongs to a different datapath, so we must do all
412      * port deletions before any port additions. */
413     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
414         struct odp_port *dpif_ports;
415         size_t n_dpif_ports;
416         struct svec want_ifaces;
417
418         dpif_port_list(&br->dpif, &dpif_ports, &n_dpif_ports);
419         bridge_get_all_ifaces(br, &want_ifaces);
420         for (i = 0; i < n_dpif_ports; i++) {
421             const struct odp_port *p = &dpif_ports[i];
422             if (!svec_contains(&want_ifaces, p->devname)
423                 && strcmp(p->devname, br->name)) {
424                 int retval = dpif_port_del(&br->dpif, p->port);
425                 if (retval) {
426                     VLOG_ERR("failed to remove %s interface from dp%u: %s",
427                              p->devname, dpif_id(&br->dpif), strerror(retval));
428                 }
429             }
430         }
431         svec_destroy(&want_ifaces);
432         free(dpif_ports);
433     }
434     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
435         struct odp_port *dpif_ports;
436         size_t n_dpif_ports;
437         struct svec cur_ifaces, want_ifaces, add_ifaces;
438         int next_port_no;
439
440         dpif_port_list(&br->dpif, &dpif_ports, &n_dpif_ports);
441         svec_init(&cur_ifaces);
442         for (i = 0; i < n_dpif_ports; i++) {
443             svec_add(&cur_ifaces, dpif_ports[i].devname);
444         }
445         free(dpif_ports);
446         svec_sort_unique(&cur_ifaces);
447         bridge_get_all_ifaces(br, &want_ifaces);
448         svec_diff(&want_ifaces, &cur_ifaces, &add_ifaces, NULL, NULL);
449
450         next_port_no = 1;
451         for (i = 0; i < add_ifaces.n; i++) {
452             const char *if_name = add_ifaces.names[i];
453             for (;;) {
454                 int internal = cfg_get_bool(0, "iface.%s.internal", if_name);
455                 int error = dpif_port_add(&br->dpif, if_name, next_port_no++,
456                                           internal ? ODP_PORT_INTERNAL : 0);
457                 if (error != EEXIST) {
458                     if (next_port_no >= 256) {
459                         VLOG_ERR("ran out of valid port numbers on dp%u",
460                                  dpif_id(&br->dpif));
461                         goto out;
462                     }
463                     if (error) {
464                         VLOG_ERR("failed to add %s interface to dp%u: %s",
465                                  if_name, dpif_id(&br->dpif), strerror(error));
466                     }
467                     break;
468                 }
469             }
470         }
471     out:
472         svec_destroy(&cur_ifaces);
473         svec_destroy(&want_ifaces);
474         svec_destroy(&add_ifaces);
475     }
476     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
477         uint8_t ea[8];
478         uint64_t dpid;
479         struct iface *local_iface = NULL;
480         const char *devname;
481         uint8_t engine_type = br->dpif.minor;
482         uint8_t engine_id = br->dpif.minor;
483         bool add_id_to_iface = false;
484         struct svec nf_hosts;
485
486         bridge_fetch_dp_ifaces(br);
487         for (i = 0; i < br->n_ports; ) {
488             struct port *port = br->ports[i];
489
490             for (j = 0; j < port->n_ifaces; ) {
491                 struct iface *iface = port->ifaces[j];
492                 if (iface->dp_ifidx < 0) {
493                     VLOG_ERR("%s interface not in dp%u, dropping",
494                              iface->name, dpif_id(&br->dpif));
495                     iface_destroy(iface);
496                 } else {
497                     if (iface->dp_ifidx == ODPP_LOCAL) {
498                         local_iface = iface;
499                     }
500                     VLOG_DBG("dp%u has interface %s on port %d",
501                              dpif_id(&br->dpif), iface->name, iface->dp_ifidx);
502                     j++;
503                 }
504             }
505             if (!port->n_ifaces) {
506                 VLOG_ERR("%s port has no interfaces, dropping", port->name);
507                 port_destroy(port);
508                 continue;
509             }
510             i++;
511         }
512
513         /* Pick local port hardware address, datapath ID. */
514         bridge_pick_local_hw_addr(br, ea, &devname);
515         if (local_iface) {
516             int error = netdev_nodev_set_etheraddr(local_iface->name, ea);
517             if (error) {
518                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
519                 VLOG_ERR_RL(&rl, "bridge %s: failed to set bridge "
520                             "Ethernet address: %s",
521                             br->name, strerror(error));
522             }
523         }
524
525         dpid = bridge_pick_datapath_id(br, ea, devname);
526         ofproto_set_datapath_id(br->ofproto, dpid);
527
528         /* Set NetFlow configuration on this bridge. */
529         if (cfg_has("netflow.%s.engine-type", br->name)) {
530             engine_type = cfg_get_int(0, "netflow.%s.engine-type", 
531                     br->name);
532         }
533         if (cfg_has("netflow.%s.engine-id", br->name)) {
534             engine_id = cfg_get_int(0, "netflow.%s.engine-id", br->name);
535         }
536         if (cfg_has("netflow.%s.add-id-to-iface", br->name)) {
537             add_id_to_iface = cfg_get_bool(0, "netflow.%s.add-id-to-iface",
538                     br->name);
539         }
540         if (add_id_to_iface && engine_id > 0x7f) {
541             VLOG_WARN("bridge %s: netflow port mangling may conflict with "
542                     "another vswitch, choose an engine id less than 128", 
543                     br->name);
544         }
545         if (add_id_to_iface && br->n_ports > 0x1ff) {
546             VLOG_WARN("bridge %s: netflow port mangling will conflict with "
547                     "another port when 512 or more ports are used", 
548                     br->name);
549         }
550         svec_init(&nf_hosts);
551         cfg_get_all_keys(&nf_hosts, "netflow.%s.host", br->name);
552         if (ofproto_set_netflow(br->ofproto, &nf_hosts,  engine_type, 
553                     engine_id, add_id_to_iface)) {
554             VLOG_ERR("bridge %s: problem setting netflow collectors", 
555                     br->name);
556         }
557
558         /* Update the controller and related settings.  It would be more
559          * straightforward to call this from bridge_reconfigure_one(), but we
560          * can't do it there for two reasons.  First, and most importantly, at
561          * that point we don't know the dp_ifidx of any interfaces that have
562          * been added to the bridge (because we haven't actually added them to
563          * the datapath).  Second, at that point we haven't set the datapath ID
564          * yet; when a controller is configured, resetting the datapath ID will
565          * immediately disconnect from the controller, so it's better to set
566          * the datapath ID before the controller. */
567         bridge_reconfigure_controller(br);
568     }
569     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
570         for (i = 0; i < br->n_ports; i++) {
571             struct port *port = br->ports[i];
572             port_update_vlan_compat(port);
573         }
574     }
575     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
576         brstp_reconfigure(br);
577     }
578 }
579
580 static void
581 bridge_pick_local_hw_addr(struct bridge *br, uint8_t ea[ETH_ADDR_LEN],
582                           const char **devname)
583 {
584     uint64_t requested_ea;
585     size_t i, j;
586     int error;
587
588     *devname = NULL;
589
590     /* Did the user request a particular MAC? */
591     requested_ea = cfg_get_mac(0, "bridge.%s.mac", br->name);
592     if (requested_ea) {
593         eth_addr_from_uint64(requested_ea, ea);
594         if (eth_addr_is_multicast(ea)) {
595             VLOG_ERR("bridge %s: cannot set MAC address to multicast "
596                      "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
597         } else if (eth_addr_is_zero(ea)) {
598             VLOG_ERR("bridge %s: cannot set MAC address to zero", br->name);
599         } else {
600             return;
601         }
602     }
603
604     /* Otherwise choose the minimum MAC address among all of the interfaces.
605      * (Xen uses FE:FF:FF:FF:FF:FF for virtual interfaces so this will get the
606      * MAC of the physical interface in such an environment.) */
607     memset(ea, 0xff, sizeof ea);
608     for (i = 0; i < br->n_ports; i++) {
609         struct port *port = br->ports[i];
610         if (port->is_mirror_output_port) {
611             continue;
612         }
613         for (j = 0; j < port->n_ifaces; j++) {
614             struct iface *iface = port->ifaces[j];
615             uint8_t iface_ea[ETH_ADDR_LEN];
616             if (iface->dp_ifidx == ODPP_LOCAL
617                 || cfg_get_bool(0, "iface.%s.internal", iface->name)) {
618                 continue;
619             }
620             error = netdev_nodev_get_etheraddr(iface->name, iface_ea);
621             if (!error) {
622                 if (!eth_addr_is_multicast(iface_ea) &&
623                     !eth_addr_is_reserved(iface_ea) &&
624                     !eth_addr_is_zero(iface_ea) &&
625                     memcmp(iface_ea, ea, ETH_ADDR_LEN) < 0) {
626                     memcpy(ea, iface_ea, ETH_ADDR_LEN);
627                     *devname = iface->name;
628                 }
629             } else {
630                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
631                 VLOG_ERR_RL(&rl, "failed to obtain Ethernet address of %s: %s",
632                             iface->name, strerror(error));
633             }
634         }
635     }
636     if (eth_addr_is_multicast(ea) || eth_addr_is_vif(ea)) {
637         memcpy(ea, br->default_ea, ETH_ADDR_LEN);
638         *devname = NULL;
639         VLOG_WARN("bridge %s: using default bridge Ethernet "
640                   "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
641     } else {
642         VLOG_DBG("bridge %s: using bridge Ethernet address "ETH_ADDR_FMT,
643                  br->name, ETH_ADDR_ARGS(ea));
644     }
645 }
646
647 /* Choose and returns the datapath ID for bridge 'br' given that the bridge
648  * Ethernet address is 'bridge_ea'.  If 'bridge_ea' is the Ethernet address of
649  * a network device, then that network device's name must be passed in as
650  * 'devname'; if 'bridge_ea' was derived some other way, then 'devname' must be
651  * passed in as a null pointer. */
652 static uint64_t
653 bridge_pick_datapath_id(struct bridge *br,
654                         const uint8_t bridge_ea[ETH_ADDR_LEN],
655                         const char *devname)
656 {
657     /*
658      * The procedure for choosing a bridge MAC address will, in the most
659      * ordinary case, also choose a unique MAC that we can use as a datapath
660      * ID.  In some special cases, though, multiple bridges will end up with
661      * the same MAC address.  This is OK for the bridges, but it will confuse
662      * the OpenFlow controller, because each datapath needs a unique datapath
663      * ID.
664      *
665      * Datapath IDs must be unique.  It is also very desirable that they be
666      * stable from one run to the next, so that policy set on a datapath
667      * "sticks".
668      */
669     uint64_t dpid;
670
671     dpid = cfg_get_dpid(0, "bridge.%s.datapath-id", br->name);
672     if (dpid) {
673         return dpid;
674     }
675
676     if (devname) {
677         int vlan;
678         if (!netdev_get_vlan_vid(devname, &vlan)) {
679             /*
680              * A bridge whose MAC address is taken from a VLAN network device
681              * (that is, a network device created with vconfig(8) or similar
682              * tool) will have the same MAC address as a bridge on the VLAN
683              * device's physical network device.
684              *
685              * Handle this case by hashing the physical network device MAC
686              * along with the VLAN identifier.
687              */
688             uint8_t buf[ETH_ADDR_LEN + 2];
689             memcpy(buf, bridge_ea, ETH_ADDR_LEN);
690             buf[ETH_ADDR_LEN] = vlan >> 8;
691             buf[ETH_ADDR_LEN + 1] = vlan;
692             return dpid_from_hash(buf, sizeof buf);
693         } else {
694             /*
695              * Assume that this bridge's MAC address is unique, since it
696              * doesn't fit any of the cases we handle specially.
697              */
698         }
699     } else {
700         /*
701          * A purely internal bridge, that is, one that has no non-virtual
702          * network devices on it at all, is more difficult because it has no
703          * natural unique identifier at all.
704          *
705          * When the host is a XenServer, we handle this case by hashing the
706          * host's UUID with the name of the bridge.  Names of bridges are
707          * persistent across XenServer reboots, although they can be reused if
708          * an internal network is destroyed and then a new one is later
709          * created, so this is fairly effective.
710          *
711          * When the host is not a XenServer, we punt by using a random MAC
712          * address on each run.
713          */
714         const char *host_uuid = xenserver_get_host_uuid();
715         if (host_uuid) {
716             char *combined = xasprintf("%s,%s", host_uuid, br->name);
717             dpid = dpid_from_hash(combined, strlen(combined));
718             free(combined);
719             return dpid;
720         }
721     }
722
723     return eth_addr_to_uint64(bridge_ea);
724 }
725
726 static uint64_t
727 dpid_from_hash(const void *data, size_t n)
728 {
729     uint8_t hash[SHA1HashSize];
730
731     BUILD_ASSERT_DECL(sizeof hash >= ETH_ADDR_LEN);
732     SHA1Bytes(data, n, hash);
733     eth_addr_mark_random(hash);
734     return eth_addr_to_uint64(hash);
735 }
736
737 int
738 bridge_run(void)
739 {
740     struct bridge *br, *next;
741     int retval;
742
743     retval = 0;
744     LIST_FOR_EACH_SAFE (br, next, struct bridge, node, &all_bridges) {
745         int error = bridge_run_one(br);
746         if (error) {
747             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
748             VLOG_ERR_RL(&rl, "bridge %s: datapath was destroyed externally, "
749                         "forcing reconfiguration", br->name);
750             if (!retval) {
751                 retval = error;
752             }
753         }
754     }
755     return retval;
756 }
757
758 void
759 bridge_wait(void)
760 {
761     struct bridge *br;
762
763     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
764         ofproto_wait(br->ofproto);
765         if (br->controller) {
766             continue;
767         }
768
769         if (br->ml) {
770             mac_learning_wait(br->ml);
771         }
772         bond_wait(br);
773         brstp_wait(br);
774     }
775 }
776
777 /* Forces 'br' to revalidate all of its flows.  This is appropriate when 'br''s
778  * configuration changes.  */
779 static void
780 bridge_flush(struct bridge *br)
781 {
782     COVERAGE_INC(bridge_flush);
783     br->flush = true;
784     if (br->ml) {
785         mac_learning_flush(br->ml);
786     }
787 }
788 \f
789 /* Bridge reconfiguration functions. */
790
791 static struct bridge *
792 bridge_create(const char *name)
793 {
794     struct bridge *br;
795     int error;
796
797     assert(!bridge_lookup(name));
798     br = xcalloc(1, sizeof *br);
799
800     error = dpif_create(name, &br->dpif);
801     if (error == EEXIST) {
802         error = dpif_open(name, &br->dpif);
803         if (error) {
804             VLOG_ERR("datapath %s already exists but cannot be opened: %s",
805                      name, strerror(error));
806             free(br);
807             return NULL;
808         }
809         dpif_flow_flush(&br->dpif);
810     } else if (error) {
811         VLOG_ERR("failed to create datapath %s: %s", name, strerror(error));
812         free(br);
813         return NULL;
814     }
815
816     error = ofproto_create(name, &bridge_ofhooks, br, &br->ofproto);
817     if (error) {
818         VLOG_ERR("failed to create switch %s: %s", name, strerror(error));
819         dpif_delete(&br->dpif);
820         dpif_close(&br->dpif);
821         free(br);
822         return NULL;
823     }
824
825     br->name = xstrdup(name);
826     br->ml = mac_learning_create();
827     br->sent_config_request = false;
828     eth_addr_random(br->default_ea);
829
830     port_array_init(&br->ifaces);
831
832     br->flush = false;
833     br->bond_next_rebalance = time_msec() + 10000;
834
835     list_push_back(&all_bridges, &br->node);
836
837     VLOG_INFO("created bridge %s on dp%u", br->name, dpif_id(&br->dpif));
838
839     return br;
840 }
841
842 static void
843 bridge_destroy(struct bridge *br)
844 {
845     if (br) {
846         int error;
847
848         while (br->n_ports > 0) {
849             port_destroy(br->ports[br->n_ports - 1]);
850         }
851         list_remove(&br->node);
852         error = dpif_delete(&br->dpif);
853         if (error && error != ENOENT) {
854             VLOG_ERR("failed to delete dp%u: %s",
855                      dpif_id(&br->dpif), strerror(error));
856         }
857         dpif_close(&br->dpif);
858         ofproto_destroy(br->ofproto);
859         free(br->controller);
860         mac_learning_destroy(br->ml);
861         port_array_destroy(&br->ifaces);
862         free(br->ports);
863         free(br->name);
864         free(br);
865     }
866 }
867
868 static struct bridge *
869 bridge_lookup(const char *name)
870 {
871     struct bridge *br;
872
873     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
874         if (!strcmp(br->name, name)) {
875             return br;
876         }
877     }
878     return NULL;
879 }
880
881 bool
882 bridge_exists(const char *name)
883 {
884     return bridge_lookup(name) ? true : false;
885 }
886
887 uint64_t
888 bridge_get_datapathid(const char *name)
889 {
890     struct bridge *br = bridge_lookup(name);
891     return br ? ofproto_get_datapath_id(br->ofproto) : 0;
892 }
893
894 static int
895 bridge_run_one(struct bridge *br)
896 {
897     int error;
898
899     error = ofproto_run1(br->ofproto);
900     if (error) {
901         return error;
902     }
903
904     if (br->ml) {
905         mac_learning_run(br->ml, ofproto_get_revalidate_set(br->ofproto));
906     }
907     bond_run(br);
908     brstp_run(br);
909
910     error = ofproto_run2(br->ofproto, br->flush);
911     br->flush = false;
912
913     return error;
914 }
915
916 static const char *
917 bridge_get_controller(const struct bridge *br)
918 {
919     const char *controller;
920
921     controller = cfg_get_string(0, "bridge.%s.controller", br->name);
922     if (!controller) {
923         controller = cfg_get_string(0, "mgmt.controller");
924     }
925     return controller && controller[0] ? controller : NULL;
926 }
927
928 static void
929 bridge_reconfigure_one(struct bridge *br)
930 {
931     struct svec old_ports, new_ports, ifaces;
932     struct svec listeners, old_listeners;
933     struct svec snoops, old_snoops;
934     size_t i, j;
935
936     /* Collect old ports. */
937     svec_init(&old_ports);
938     for (i = 0; i < br->n_ports; i++) {
939         svec_add(&old_ports, br->ports[i]->name);
940     }
941     svec_sort(&old_ports);
942     assert(svec_is_unique(&old_ports));
943
944     /* Collect new ports. */
945     svec_init(&new_ports);
946     cfg_get_all_keys(&new_ports, "bridge.%s.port", br->name);
947     svec_sort(&new_ports);
948     if (bridge_get_controller(br) && !svec_contains(&new_ports, br->name)) {
949         svec_add(&new_ports, br->name);
950         svec_sort(&new_ports);
951     }
952     if (!svec_is_unique(&new_ports)) {
953         VLOG_WARN("bridge %s: %s specified twice as bridge port",
954                   br->name, svec_get_duplicate(&new_ports));
955         svec_unique(&new_ports);
956     }
957
958     ofproto_set_mgmt_id(br->ofproto, mgmt_id);
959
960     /* Get rid of deleted ports and add new ports. */
961     for (i = 0; i < br->n_ports; ) {
962         struct port *port = br->ports[i];
963         if (!svec_contains(&new_ports, port->name)) {
964             port_destroy(port);
965         } else {
966             i++;
967         }
968     }
969     for (i = 0; i < new_ports.n; i++) {
970         const char *name = new_ports.names[i];
971         if (!svec_contains(&old_ports, name)) {
972             port_create(br, name);
973         }
974     }
975     svec_destroy(&old_ports);
976     svec_destroy(&new_ports);
977
978     /* Reconfigure all ports. */
979     for (i = 0; i < br->n_ports; i++) {
980         port_reconfigure(br->ports[i]);
981     }
982
983     /* Check and delete duplicate interfaces. */
984     svec_init(&ifaces);
985     for (i = 0; i < br->n_ports; ) {
986         struct port *port = br->ports[i];
987         for (j = 0; j < port->n_ifaces; ) {
988             struct iface *iface = port->ifaces[j];
989             if (svec_contains(&ifaces, iface->name)) {
990                 VLOG_ERR("bridge %s: %s interface is on multiple ports, "
991                          "removing from %s",
992                          br->name, iface->name, port->name);
993                 iface_destroy(iface);
994             } else {
995                 svec_add(&ifaces, iface->name);
996                 svec_sort(&ifaces);
997                 j++;
998             }
999         }
1000         if (!port->n_ifaces) {
1001             VLOG_ERR("%s port has no interfaces, dropping", port->name);
1002             port_destroy(port);
1003         } else {
1004             i++;
1005         }
1006     }
1007     svec_destroy(&ifaces);
1008
1009     /* Delete all flows if we're switching from connected to standalone or vice
1010      * versa.  (XXX Should we delete all flows if we are switching from one
1011      * controller to another?) */
1012
1013     /* Configure OpenFlow management listeners. */
1014     svec_init(&listeners);
1015     cfg_get_all_strings(&listeners, "bridge.%s.openflow.listeners", br->name);
1016     if (!listeners.n) {
1017         svec_add_nocopy(&listeners, xasprintf("punix:%s/%s.mgmt",
1018                                               ovs_rundir, br->name));
1019     } else if (listeners.n == 1 && !strcmp(listeners.names[0], "none")) {
1020         svec_clear(&listeners);
1021     }
1022     svec_sort_unique(&listeners);
1023
1024     svec_init(&old_listeners);
1025     ofproto_get_listeners(br->ofproto, &old_listeners);
1026     svec_sort_unique(&old_listeners);
1027
1028     if (!svec_equal(&listeners, &old_listeners)) {
1029         ofproto_set_listeners(br->ofproto, &listeners);
1030     }
1031     svec_destroy(&listeners);
1032     svec_destroy(&old_listeners);
1033
1034     /* Configure OpenFlow controller connection snooping. */
1035     svec_init(&snoops);
1036     cfg_get_all_strings(&snoops, "bridge.%s.openflow.snoops", br->name);
1037     if (!snoops.n) {
1038         svec_add_nocopy(&snoops, xasprintf("punix:%s/%s.snoop",
1039                                            ovs_rundir, br->name));
1040     } else if (snoops.n == 1 && !strcmp(snoops.names[0], "none")) {
1041         svec_clear(&snoops);
1042     }
1043     svec_sort_unique(&snoops);
1044
1045     svec_init(&old_snoops);
1046     ofproto_get_snoops(br->ofproto, &old_snoops);
1047     svec_sort_unique(&old_snoops);
1048
1049     if (!svec_equal(&snoops, &old_snoops)) {
1050         ofproto_set_snoops(br->ofproto, &snoops);
1051     }
1052     svec_destroy(&snoops);
1053     svec_destroy(&old_snoops);
1054
1055     mirror_reconfigure(br);
1056 }
1057
1058 static void
1059 bridge_reconfigure_controller(struct bridge *br)
1060 {
1061     char *pfx = xasprintf("bridge.%s.controller", br->name);
1062     const char *controller;
1063
1064     controller = bridge_get_controller(br);
1065     if ((br->controller != NULL) != (controller != NULL)) {
1066         ofproto_flush_flows(br->ofproto);
1067     }
1068     free(br->controller);
1069     br->controller = controller ? xstrdup(controller) : NULL;
1070
1071     if (controller) {
1072         const char *fail_mode;
1073         int max_backoff, probe;
1074         int rate_limit, burst_limit;
1075
1076         if (!strcmp(controller, "discover")) {
1077             ofproto_set_discovery(br->ofproto, true,
1078                                   cfg_get_string(0, "%s.accept-regex", pfx),
1079                                   cfg_get_bool(0, "%s.update-resolv.conf",
1080                                                pfx));
1081         } else {
1082             struct netdev *netdev;
1083             bool in_band;
1084             int error;
1085
1086             in_band = (!cfg_is_valid(CFG_BOOL | CFG_REQUIRED,
1087                                      "%s.in-band", pfx)
1088                        || cfg_get_bool(0, "%s.in-band", pfx));
1089             ofproto_set_discovery(br->ofproto, false, NULL, NULL);
1090             ofproto_set_in_band(br->ofproto, in_band);
1091
1092             error = netdev_open(br->name, NETDEV_ETH_TYPE_NONE, &netdev);
1093             if (!error) {
1094                 if (cfg_is_valid(CFG_IP | CFG_REQUIRED, "%s.ip", pfx)) {
1095                     struct in_addr ip, mask, gateway;
1096                     ip.s_addr = cfg_get_ip(0, "%s.ip", pfx);
1097                     mask.s_addr = cfg_get_ip(0, "%s.netmask", pfx);
1098                     gateway.s_addr = cfg_get_ip(0, "%s.gateway", pfx);
1099
1100                     netdev_turn_flags_on(netdev, NETDEV_UP, true);
1101                     if (!mask.s_addr) {
1102                         mask.s_addr = guess_netmask(ip.s_addr);
1103                     }
1104                     if (!netdev_set_in4(netdev, ip, mask)) {
1105                         VLOG_INFO("bridge %s: configured IP address "IP_FMT", "
1106                                   "netmask "IP_FMT,
1107                                   br->name, IP_ARGS(&ip.s_addr),
1108                                   IP_ARGS(&mask.s_addr));
1109                     }
1110
1111                     if (gateway.s_addr) {
1112                         if (!netdev_add_router(gateway)) {
1113                             VLOG_INFO("bridge %s: configured gateway "IP_FMT,
1114                                       br->name, IP_ARGS(&gateway.s_addr));
1115                         }
1116                     }
1117                 }
1118                 netdev_close(netdev);
1119             }
1120         }
1121
1122         fail_mode = cfg_get_string(0, "%s.fail-mode", pfx);
1123         if (!fail_mode) {
1124             fail_mode = cfg_get_string(0, "mgmt.fail-mode");
1125         }
1126         ofproto_set_failure(br->ofproto,
1127                             (!fail_mode
1128                              || !strcmp(fail_mode, "standalone")
1129                              || !strcmp(fail_mode, "open")));
1130
1131         probe = cfg_get_int(0, "%s.inactivity-probe", pfx);
1132         ofproto_set_probe_interval(br->ofproto,
1133                                    probe ? probe : cfg_get_int(0, "mgmt.inactivity-probe"));
1134
1135         max_backoff = cfg_get_int(0, "%s.max-backoff", pfx);
1136         if (!max_backoff) {
1137             max_backoff = cfg_get_int(0, "mgmt.max-backoff");
1138             if (!max_backoff) {
1139                 max_backoff = 15;
1140             }
1141         }
1142         ofproto_set_max_backoff(br->ofproto, max_backoff);
1143
1144         rate_limit = cfg_get_int(0, "%s.rate-limit", pfx);
1145         if (!rate_limit) {
1146             rate_limit = cfg_get_int(0, "mgmt.rate-limit");
1147         }
1148         burst_limit = cfg_get_int(0, "%s.burst-limit", pfx);
1149         if (!burst_limit) {
1150             burst_limit = cfg_get_int(0, "mgmt.burst-limit");
1151         }
1152         ofproto_set_rate_limit(br->ofproto, rate_limit, burst_limit);
1153
1154         ofproto_set_stp(br->ofproto, cfg_get_bool(0, "%s.stp", pfx));
1155
1156         if (cfg_has("%s.commands.acl", pfx)) {
1157             struct svec command_acls;
1158             char *command_acl;
1159
1160             svec_init(&command_acls);
1161             cfg_get_all_strings(&command_acls, "%s.commands.acl", pfx);
1162             command_acl = svec_join(&command_acls, ",", "");
1163
1164             ofproto_set_remote_execution(br->ofproto, command_acl,
1165                                          cfg_get_string(0, "%s.commands.dir",
1166                                                         pfx));
1167
1168             svec_destroy(&command_acls);
1169             free(command_acl);
1170         } else {
1171             ofproto_set_remote_execution(br->ofproto, NULL, NULL);
1172         }
1173     } else {
1174         union ofp_action action;
1175         flow_t flow;
1176
1177         /* Set up a flow that matches every packet and directs them to
1178          * OFPP_NORMAL (which goes to us). */
1179         memset(&action, 0, sizeof action);
1180         action.type = htons(OFPAT_OUTPUT);
1181         action.output.len = htons(sizeof action);
1182         action.output.port = htons(OFPP_NORMAL);
1183         memset(&flow, 0, sizeof flow);
1184         ofproto_add_flow(br->ofproto, &flow, OFPFW_ALL, 0,
1185                          &action, 1, 0);
1186
1187         ofproto_set_in_band(br->ofproto, false);
1188         ofproto_set_max_backoff(br->ofproto, 1);
1189         ofproto_set_probe_interval(br->ofproto, 5);
1190         ofproto_set_failure(br->ofproto, false);
1191         ofproto_set_stp(br->ofproto, false);
1192     }
1193     free(pfx);
1194
1195     ofproto_set_controller(br->ofproto, br->controller);
1196 }
1197
1198 static void
1199 bridge_get_all_ifaces(const struct bridge *br, struct svec *ifaces)
1200 {
1201     size_t i, j;
1202
1203     svec_init(ifaces);
1204     for (i = 0; i < br->n_ports; i++) {
1205         struct port *port = br->ports[i];
1206         for (j = 0; j < port->n_ifaces; j++) {
1207             struct iface *iface = port->ifaces[j];
1208             svec_add(ifaces, iface->name);
1209         }
1210     }
1211     svec_sort(ifaces);
1212     assert(svec_is_unique(ifaces));
1213 }
1214
1215 /* For robustness, in case the administrator moves around datapath ports behind
1216  * our back, we re-check all the datapath port numbers here.
1217  *
1218  * This function will set the 'dp_ifidx' members of interfaces that have
1219  * disappeared to -1, so only call this function from a context where those
1220  * 'struct iface's will be removed from the bridge.  Otherwise, the -1
1221  * 'dp_ifidx'es will cause trouble later when we try to send them to the
1222  * datapath, which doesn't support UINT16_MAX+1 ports. */
1223 static void
1224 bridge_fetch_dp_ifaces(struct bridge *br)
1225 {
1226     struct odp_port *dpif_ports;
1227     size_t n_dpif_ports;
1228     size_t i, j;
1229
1230     /* Reset all interface numbers. */
1231     for (i = 0; i < br->n_ports; i++) {
1232         struct port *port = br->ports[i];
1233         for (j = 0; j < port->n_ifaces; j++) {
1234             struct iface *iface = port->ifaces[j];
1235             iface->dp_ifidx = -1;
1236         }
1237     }
1238     port_array_clear(&br->ifaces);
1239
1240     dpif_port_list(&br->dpif, &dpif_ports, &n_dpif_ports);
1241     for (i = 0; i < n_dpif_ports; i++) {
1242         struct odp_port *p = &dpif_ports[i];
1243         struct iface *iface = iface_lookup(br, p->devname);
1244         if (iface) {
1245             if (iface->dp_ifidx >= 0) {
1246                 VLOG_WARN("dp%u reported interface %s twice",
1247                           dpif_id(&br->dpif), p->devname);
1248             } else if (iface_from_dp_ifidx(br, p->port)) {
1249                 VLOG_WARN("dp%u reported interface %"PRIu16" twice",
1250                           dpif_id(&br->dpif), p->port);
1251             } else {
1252                 port_array_set(&br->ifaces, p->port, iface);
1253                 iface->dp_ifidx = p->port;
1254             }
1255         }
1256     }
1257     free(dpif_ports);
1258 }
1259 \f
1260 /* Bridge packet processing functions. */
1261
1262 static struct bond_entry *
1263 lookup_bond_entry(const struct port *port, const uint8_t mac[ETH_ADDR_LEN])
1264 {
1265     size_t h = hash_bytes(mac, ETH_ADDR_LEN, 0);
1266     return &port->bond_hash[h & BOND_MASK];
1267 }
1268
1269 static int
1270 bond_choose_iface(const struct port *port)
1271 {
1272     size_t i;
1273     for (i = 0; i < port->n_ifaces; i++) {
1274         if (port->ifaces[i]->enabled) {
1275             return i;
1276         }
1277     }
1278     return -1;
1279 }
1280
1281 static bool
1282 choose_output_iface(const struct port *port, const uint8_t *dl_src,
1283                     uint16_t *dp_ifidx, tag_type *tags)
1284 {
1285     struct iface *iface;
1286
1287     assert(port->n_ifaces);
1288     if (port->n_ifaces == 1) {
1289         iface = port->ifaces[0];
1290     } else {
1291         struct bond_entry *e = lookup_bond_entry(port, dl_src);
1292         if (e->iface_idx < 0 || e->iface_idx >= port->n_ifaces
1293             || !port->ifaces[e->iface_idx]->enabled) {
1294             /* XXX select interface properly.  The current interface selection
1295              * is only good for testing the rebalancing code. */
1296             e->iface_idx = bond_choose_iface(port);
1297             if (e->iface_idx < 0) {
1298                 *tags |= port->no_ifaces_tag;
1299                 return false;
1300             }
1301             e->iface_tag = tag_create_random();
1302         }
1303         *tags |= e->iface_tag;
1304         iface = port->ifaces[e->iface_idx];
1305     }
1306     *dp_ifidx = iface->dp_ifidx;
1307     *tags |= iface->tag;        /* Currently only used for bonding. */
1308     return true;
1309 }
1310
1311 static void
1312 bond_link_status_update(struct iface *iface, bool carrier)
1313 {
1314     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1315     struct port *port = iface->port;
1316
1317     if ((carrier == iface->enabled) == (iface->delay_expires == LLONG_MAX)) {
1318         /* Nothing to do. */
1319         return;
1320     }
1321     VLOG_INFO_RL(&rl, "interface %s: carrier %s",
1322                  iface->name, carrier ? "detected" : "dropped");
1323     if (carrier == iface->enabled) {
1324         iface->delay_expires = LLONG_MAX;
1325         VLOG_INFO_RL(&rl, "interface %s: will not be %s",
1326                      iface->name, carrier ? "disabled" : "enabled");
1327     } else {
1328         int delay = carrier ? port->updelay : port->downdelay;
1329         iface->delay_expires = time_msec() + delay;
1330         if (delay) {
1331             VLOG_INFO_RL(&rl,
1332                          "interface %s: will be %s if it stays %s for %d ms",
1333                          iface->name,
1334                          carrier ? "enabled" : "disabled",
1335                          carrier ? "up" : "down",
1336                          delay);
1337         }
1338     }
1339 }
1340
1341 static void
1342 bond_choose_active_iface(struct port *port)
1343 {
1344     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1345
1346     port->active_iface = bond_choose_iface(port);
1347     port->active_iface_tag = tag_create_random();
1348     if (port->active_iface >= 0) {
1349         VLOG_INFO_RL(&rl, "port %s: active interface is now %s",
1350                      port->name, port->ifaces[port->active_iface]->name);
1351     } else {
1352         VLOG_WARN_RL(&rl, "port %s: all ports disabled, no active interface",
1353                      port->name);
1354     }
1355 }
1356
1357 static void
1358 bond_run(struct bridge *br)
1359 {
1360     size_t i, j;
1361
1362     for (i = 0; i < br->n_ports; i++) {
1363         struct port *port = br->ports[i];
1364         if (port->n_ifaces < 2) {
1365             continue;
1366         }
1367         for (j = 0; j < port->n_ifaces; j++) {
1368             struct iface *iface = port->ifaces[j];
1369             if (time_msec() >= iface->delay_expires) {
1370                 iface->delay_expires = LLONG_MAX;
1371                 iface->enabled = !iface->enabled;
1372                 VLOG_WARN("interface %s: %s",
1373                           iface->name,
1374                           iface->enabled ? "enabled" : "disabled");
1375                 if (!iface->enabled) {
1376                     ofproto_revalidate(br->ofproto, iface->tag);
1377                     if (iface->port_ifidx == port->active_iface) {
1378                         ofproto_revalidate(br->ofproto,
1379                                            port->active_iface_tag);
1380                         bond_choose_active_iface(port);
1381                     }
1382                     bond_send_learning_packets(port);
1383                 } else {
1384                     if (port->active_iface < 0) {
1385                         ofproto_revalidate(br->ofproto, port->no_ifaces_tag);
1386                         bond_choose_active_iface(port);
1387                         bond_send_learning_packets(port);
1388                     }
1389                     iface->tag = tag_create_random();
1390                 }
1391             }
1392         }
1393     }
1394 }
1395
1396 static void
1397 bond_wait(struct bridge *br)
1398 {
1399     size_t i, j;
1400
1401     for (i = 0; i < br->n_ports; i++) {
1402         struct port *port = br->ports[i];
1403         if (port->n_ifaces < 2) {
1404             continue;
1405         }
1406         for (j = 0; j < port->n_ifaces; j++) {
1407             struct iface *iface = port->ifaces[j];
1408             if (iface->delay_expires != LLONG_MAX) {
1409                 poll_timer_wait(iface->delay_expires - time_msec());
1410             }
1411         }
1412     }
1413 }
1414
1415 static bool
1416 set_dst(struct dst *p, const flow_t *flow,
1417         const struct port *in_port, const struct port *out_port,
1418         tag_type *tags)
1419 {
1420     /* STP handling.
1421      *
1422      * XXX This uses too many tags: any broadcast flow will get one tag per
1423      * destination port, and thus a broadcast on a switch of any size is likely
1424      * to have all tag bits set.  We should figure out a way to be smarter.
1425      *
1426      * This is OK when STP is disabled, because stp_state_tag is 0 then. */
1427     *tags |= out_port->stp_state_tag;
1428     if (!(out_port->stp_state & (STP_DISABLED | STP_FORWARDING))) {
1429         return false;
1430     }
1431
1432     p->vlan = (out_port->vlan >= 0 ? OFP_VLAN_NONE
1433               : in_port->vlan >= 0 ? in_port->vlan
1434               : ntohs(flow->dl_vlan));
1435     return choose_output_iface(out_port, flow->dl_src, &p->dp_ifidx, tags);
1436 }
1437
1438 static void
1439 swap_dst(struct dst *p, struct dst *q)
1440 {
1441     struct dst tmp = *p;
1442     *p = *q;
1443     *q = tmp;
1444 }
1445
1446 /* Moves all the dsts with vlan == 'vlan' to the front of the 'n_dsts' in
1447  * 'dsts'.  (This may help performance by reducing the number of VLAN changes
1448  * that we push to the datapath.  We could in fact fully sort the array by
1449  * vlan, but in most cases there are at most two different vlan tags so that's
1450  * possibly overkill.) */
1451 static void
1452 partition_dsts(struct dst *dsts, size_t n_dsts, int vlan)
1453 {
1454     struct dst *first = dsts;
1455     struct dst *last = dsts + n_dsts;
1456
1457     while (first != last) {
1458         /* Invariants:
1459          *      - All dsts < first have vlan == 'vlan'.
1460          *      - All dsts >= last have vlan != 'vlan'.
1461          *      - first < last. */
1462         while (first->vlan == vlan) {
1463             if (++first == last) {
1464                 return;
1465             }
1466         }
1467
1468         /* Same invariants, plus one additional:
1469          *      - first->vlan != vlan.
1470          */
1471         while (last[-1].vlan != vlan) {
1472             if (--last == first) {
1473                 return;
1474             }
1475         }
1476
1477         /* Same invariants, plus one additional:
1478          *      - last[-1].vlan == vlan.*/
1479         swap_dst(first++, --last);
1480     }
1481 }
1482
1483 static int
1484 mirror_mask_ffs(mirror_mask_t mask)
1485 {
1486     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
1487     return ffs(mask);
1488 }
1489
1490 static bool
1491 dst_is_duplicate(const struct dst *dsts, size_t n_dsts,
1492                  const struct dst *test)
1493 {
1494     size_t i;
1495     for (i = 0; i < n_dsts; i++) {
1496         if (dsts[i].vlan == test->vlan && dsts[i].dp_ifidx == test->dp_ifidx) {
1497             return true;
1498         }
1499     }
1500     return false;
1501 }
1502
1503 static bool
1504 port_trunks_vlan(const struct port *port, uint16_t vlan)
1505 {
1506     return port->vlan < 0 && bitmap_is_set(port->trunks, vlan);
1507 }
1508
1509 static bool
1510 port_includes_vlan(const struct port *port, uint16_t vlan)
1511 {
1512     return vlan == port->vlan || port_trunks_vlan(port, vlan);
1513 }
1514
1515 static size_t
1516 compose_dsts(const struct bridge *br, const flow_t *flow, uint16_t vlan,
1517              const struct port *in_port, const struct port *out_port,
1518              struct dst dsts[], tag_type *tags)
1519 {
1520     mirror_mask_t mirrors = in_port->src_mirrors;
1521     struct dst *dst = dsts;
1522     size_t i;
1523
1524     *tags |= in_port->stp_state_tag;
1525     if (out_port == FLOOD_PORT) {
1526         /* XXX use ODP_FLOOD if no vlans or bonding. */
1527         /* XXX even better, define each VLAN as a datapath port group */
1528         for (i = 0; i < br->n_ports; i++) {
1529             struct port *port = br->ports[i];
1530             if (port != in_port && port_includes_vlan(port, vlan)
1531                 && !port->is_mirror_output_port
1532                 && set_dst(dst, flow, in_port, port, tags)) {
1533                 mirrors |= port->dst_mirrors;
1534                 dst++;
1535             }
1536         }
1537     } else if (out_port && set_dst(dst, flow, in_port, out_port, tags)) {
1538         mirrors |= out_port->dst_mirrors;
1539         dst++;
1540     }
1541
1542     while (mirrors) {
1543         struct mirror *m = br->mirrors[mirror_mask_ffs(mirrors) - 1];
1544         if (!m->n_vlans || vlan_is_mirrored(m, vlan)) {
1545             if (m->out_port) {
1546                 if (set_dst(dst, flow, in_port, m->out_port, tags)
1547                     && !dst_is_duplicate(dsts, dst - dsts, dst)) {
1548                     dst++;
1549                 }
1550             } else {
1551                 for (i = 0; i < br->n_ports; i++) {
1552                     struct port *port = br->ports[i];
1553                     if (port_includes_vlan(port, m->out_vlan)
1554                         && set_dst(dst, flow, in_port, port, tags)
1555                         && !dst_is_duplicate(dsts, dst - dsts, dst))
1556                     {
1557                         if (port->vlan < 0) {
1558                             dst->vlan = m->out_vlan;
1559                         }
1560                         if (dst->dp_ifidx == flow->in_port
1561                             && dst->vlan == vlan) {
1562                             /* Don't send out input port on same VLAN. */
1563                             continue;
1564                         }
1565                         dst++;
1566                     }
1567                 }
1568             }
1569         }
1570         mirrors &= mirrors - 1;
1571     }
1572
1573     partition_dsts(dsts, dst - dsts, ntohs(flow->dl_vlan));
1574     return dst - dsts;
1575 }
1576
1577 static void UNUSED
1578 print_dsts(const struct dst *dsts, size_t n)
1579 {
1580     for (; n--; dsts++) {
1581         printf(">p%"PRIu16, dsts->dp_ifidx);
1582         if (dsts->vlan != OFP_VLAN_NONE) {
1583             printf("v%"PRIu16, dsts->vlan);
1584         }
1585     }
1586 }
1587
1588 static void
1589 compose_actions(struct bridge *br, const flow_t *flow, uint16_t vlan,
1590                 const struct port *in_port, const struct port *out_port,
1591                 tag_type *tags, struct odp_actions *actions)
1592 {
1593     struct dst dsts[DP_MAX_PORTS * (MAX_MIRRORS + 1)];
1594     size_t n_dsts;
1595     const struct dst *p;
1596     uint16_t cur_vlan;
1597
1598     n_dsts = compose_dsts(br, flow, vlan, in_port, out_port, dsts, tags);
1599
1600     cur_vlan = ntohs(flow->dl_vlan);
1601     for (p = dsts; p < &dsts[n_dsts]; p++) {
1602         union odp_action *a;
1603         if (p->vlan != cur_vlan) {
1604             if (p->vlan == OFP_VLAN_NONE) {
1605                 odp_actions_add(actions, ODPAT_STRIP_VLAN);
1606             } else {
1607                 a = odp_actions_add(actions, ODPAT_SET_VLAN_VID);
1608                 a->vlan_vid.vlan_vid = htons(p->vlan);
1609             }
1610             cur_vlan = p->vlan;
1611         }
1612         a = odp_actions_add(actions, ODPAT_OUTPUT);
1613         a->output.port = p->dp_ifidx;
1614     }
1615 }
1616
1617 static bool
1618 is_bcast_arp_reply(const flow_t *flow, const struct ofpbuf *packet)
1619 {
1620     struct arp_eth_header *arp = (struct arp_eth_header *) packet->data;
1621     return (flow->dl_type == htons(ETH_TYPE_ARP)
1622             && eth_addr_is_broadcast(flow->dl_dst)
1623             && packet->size >= sizeof(struct arp_eth_header)
1624             && arp->ar_op == ARP_OP_REQUEST);
1625 }
1626
1627 /* If the composed actions may be applied to any packet in the given 'flow',
1628  * returns true.  Otherwise, the actions should only be applied to 'packet', or
1629  * not at all, if 'packet' was NULL. */
1630 static bool
1631 process_flow(struct bridge *br, const flow_t *flow,
1632              const struct ofpbuf *packet, struct odp_actions *actions,
1633              tag_type *tags)
1634 {
1635     struct iface *in_iface;
1636     struct port *in_port;
1637     struct port *out_port = NULL; /* By default, drop the packet/flow. */
1638     int vlan;
1639
1640     /* Find the interface and port structure for the received packet. */
1641     in_iface = iface_from_dp_ifidx(br, flow->in_port);
1642     if (!in_iface) {
1643         /* No interface?  Something fishy... */
1644         if (packet != NULL) {
1645             /* Odd.  A few possible reasons here:
1646              *
1647              * - We deleted an interface but there are still a few packets
1648              *   queued up from it.
1649              *
1650              * - Someone externally added an interface (e.g. with "ovs-dpctl
1651              *   add-if") that we don't know about.
1652              *
1653              * - Packet arrived on the local port but the local port is not
1654              *   one of our bridge ports.
1655              */
1656             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1657
1658             VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
1659                          "interface %"PRIu16, br->name, flow->in_port); 
1660         }
1661
1662         /* Return without adding any actions, to drop packets on this flow. */
1663         return true;
1664     }
1665     in_port = in_iface->port;
1666
1667     /* Figure out what VLAN this packet belongs to.
1668      *
1669      * Note that dl_vlan of 0 and of OFP_VLAN_NONE both mean that the packet
1670      * belongs to VLAN 0, so we should treat both cases identically.  (In the
1671      * former case, the packet has an 802.1Q header that specifies VLAN 0,
1672      * presumably to allow a priority to be specified.  In the latter case, the
1673      * packet does not have any 802.1Q header.) */
1674     vlan = ntohs(flow->dl_vlan);
1675     if (vlan == OFP_VLAN_NONE) {
1676         vlan = 0;
1677     }
1678     if (in_port->vlan >= 0) {
1679         if (vlan) {
1680             /* XXX support double tagging? */
1681             if (packet != NULL) {
1682                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1683                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" tagged "
1684                              "packet received on port %s configured with "
1685                              "implicit VLAN %"PRIu16,
1686                              br->name, ntohs(flow->dl_vlan),
1687                              in_port->name, in_port->vlan);
1688             }
1689             goto done;
1690         }
1691         vlan = in_port->vlan;
1692     } else {
1693         if (!port_includes_vlan(in_port, vlan)) {
1694             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1695             VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
1696                          "packet received on port %s not configured for "
1697                          "trunking VLAN %d",
1698                          br->name, vlan, in_port->name, vlan);
1699             goto done;
1700         }
1701     }
1702
1703     /* Drop frames for ports that STP wants entirely killed (both for
1704      * forwarding and for learning).  Later, after we do learning, we'll drop
1705      * the frames that STP wants to do learning but not forwarding on. */
1706     if (in_port->stp_state & (STP_LISTENING | STP_BLOCKING)) {
1707         goto done;
1708     }
1709
1710     /* Drop frames for reserved multicast addresses. */
1711     if (eth_addr_is_reserved(flow->dl_dst)) {
1712         goto done;
1713     }
1714
1715     /* Drop frames on ports reserved for mirroring. */
1716     if (in_port->is_mirror_output_port) {
1717         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1718         VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port %s, "
1719                      "which is reserved exclusively for mirroring",
1720                      br->name, in_port->name);
1721         goto done;
1722     }
1723
1724     /* Drop multicast and broadcast packets on inactive bonded interfaces, to
1725      * avoid receiving duplicates. */
1726     if (in_port->n_ifaces > 1 && eth_addr_is_multicast(flow->dl_dst)) {
1727         *tags |= in_port->active_iface_tag;
1728         if (in_port->active_iface != in_iface->port_ifidx) {
1729             goto done;
1730         }
1731     }
1732
1733     /* MAC learning. */
1734     out_port = FLOOD_PORT;
1735     if (br->ml) {
1736         int out_port_idx;
1737         bool may_learn;
1738
1739         if (!packet) {
1740             /* Don't try to learn from revalidation. */
1741             may_learn = false;
1742         } else if (in_port->n_ifaces > 1) {
1743             /* If the packet arrived on a bonded port, don't learn from it
1744              * unless we haven't learned any port at all for that address
1745              * (because we probably sent the packet on one bonded interface and
1746              * got it back on the other).  Broadcast ARP replies are an
1747              * exception to this rule: the host has moved to another switch. */
1748             int src_idx = mac_learning_lookup(br->ml, flow->dl_src, vlan);
1749             may_learn = (src_idx < 0
1750                          || src_idx == in_port->port_idx
1751                          || is_bcast_arp_reply(flow, packet));
1752         } else {
1753             may_learn = true;
1754         }
1755
1756         /* Learn source MAC. */
1757         if (may_learn) {
1758             tag_type rev_tag = mac_learning_learn(br->ml, flow->dl_src,
1759                                                   vlan, in_port->port_idx);
1760             if (rev_tag) {
1761                 /* The log messages here could actually be useful in debugging,
1762                  * so keep the rate limit relatively high. */
1763                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30,
1764                                                                         300);
1765                 VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
1766                             "on port %s in VLAN %d",
1767                             br->name, ETH_ADDR_ARGS(flow->dl_src),
1768                             in_port->name, vlan);
1769                 ofproto_revalidate(br->ofproto, rev_tag);
1770             }
1771         }
1772
1773         /* Determine output port. */
1774         out_port_idx = mac_learning_lookup_tag(br->ml, flow->dl_dst, vlan,
1775                                                tags);
1776         if (out_port_idx >= 0 && out_port_idx < br->n_ports) {
1777             out_port = br->ports[out_port_idx];
1778         }
1779     }
1780
1781     /* Don't send packets out their input ports.  Don't forward frames that STP
1782      * wants us to discard. */
1783     if (in_port == out_port || in_port->stp_state == STP_LEARNING) {
1784         out_port = NULL;
1785     }
1786
1787 done:
1788     compose_actions(br, flow, vlan, in_port, out_port, tags, actions);
1789
1790     /*
1791      * We send out only a single packet, instead of setting up a flow, if the
1792      * packet is an ARP directed to broadcast that arrived on a bonded
1793      * interface.  In such a situation ARP requests and replies must be handled
1794      * differently, but OpenFlow unfortunately can't distinguish them.
1795      */
1796     return (in_port->n_ifaces < 2
1797             || flow->dl_type != htons(ETH_TYPE_ARP)
1798             || !eth_addr_is_broadcast(flow->dl_dst));
1799 }
1800
1801 /* Careful: 'opp' is in host byte order and opp->port_no is an OFP port
1802  * number. */
1803 static void
1804 bridge_port_changed_ofhook_cb(enum ofp_port_reason reason,
1805                               const struct ofp_phy_port *opp,
1806                               void *br_)
1807 {
1808     struct bridge *br = br_;
1809     struct iface *iface;
1810     struct port *port;
1811
1812     iface = iface_from_dp_ifidx(br, ofp_port_to_odp_port(opp->port_no));
1813     if (!iface) {
1814         return;
1815     }
1816     port = iface->port;
1817
1818     if (reason == OFPPR_DELETE) {
1819         VLOG_WARN("bridge %s: interface %s deleted unexpectedly",
1820                   br->name, iface->name);
1821         iface_destroy(iface);
1822         if (!port->n_ifaces) {
1823             VLOG_WARN("bridge %s: port %s has no interfaces, dropping",
1824                       br->name, port->name);
1825             port_destroy(port);
1826         }
1827
1828         bridge_flush(br);
1829     } else {
1830         memcpy(iface->mac, opp->hw_addr, ETH_ADDR_LEN);
1831         if (port->n_ifaces > 1) {
1832             bool up = !(opp->state & OFPPS_LINK_DOWN);
1833             bond_link_status_update(iface, up);
1834             port_update_bond_compat(port);
1835         }
1836     }
1837 }
1838
1839 static bool
1840 bridge_normal_ofhook_cb(const flow_t *flow, const struct ofpbuf *packet,
1841                         struct odp_actions *actions, tag_type *tags, void *br_)
1842 {
1843     struct bridge *br = br_;
1844
1845 #if 0
1846     if (flow->dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
1847         && eth_addr_equals(flow->dl_dst, stp_eth_addr)) {
1848         brstp_receive(br, flow, payload);
1849         return true;
1850     }
1851 #endif
1852
1853     COVERAGE_INC(bridge_process_flow);
1854     return process_flow(br, flow, packet, actions, tags);
1855 }
1856
1857 static void
1858 bridge_account_flow_ofhook_cb(const flow_t *flow,
1859                               const union odp_action *actions,
1860                               size_t n_actions, unsigned long long int n_bytes,
1861                               void *br_)
1862 {
1863     struct bridge *br = br_;
1864     const union odp_action *a;
1865
1866     if (!br->has_bonded_ports) {
1867         return;
1868     }
1869
1870     for (a = actions; a < &actions[n_actions]; a++) {
1871         if (a->type == ODPAT_OUTPUT) {
1872             struct port *port = port_from_dp_ifidx(br, a->output.port);
1873             if (port && port->n_ifaces >= 2) {
1874                 struct bond_entry *e = lookup_bond_entry(port, flow->dl_src);
1875                 e->tx_bytes += n_bytes;
1876             }
1877         }
1878     }
1879 }
1880
1881 static void
1882 bridge_account_checkpoint_ofhook_cb(void *br_)
1883 {
1884     struct bridge *br = br_;
1885     size_t i;
1886
1887     if (!br->has_bonded_ports) {
1888         return;
1889     }
1890
1891     /* The current ofproto implementation calls this callback at least once a
1892      * second, so this timer implementation is sufficient. */
1893     if (time_msec() < br->bond_next_rebalance) {
1894         return;
1895     }
1896     br->bond_next_rebalance = time_msec() + 10000;
1897
1898     for (i = 0; i < br->n_ports; i++) {
1899         struct port *port = br->ports[i];
1900         if (port->n_ifaces > 1) {
1901             bond_rebalance_port(port);
1902         }
1903     }
1904 }
1905
1906 static struct ofhooks bridge_ofhooks = {
1907     bridge_port_changed_ofhook_cb,
1908     bridge_normal_ofhook_cb,
1909     bridge_account_flow_ofhook_cb,
1910     bridge_account_checkpoint_ofhook_cb,
1911 };
1912 \f
1913 /* Bonding functions. */
1914
1915 /* Statistics for a single interface on a bonded port, used for load-based
1916  * bond rebalancing.  */
1917 struct slave_balance {
1918     struct iface *iface;        /* The interface. */
1919     uint64_t tx_bytes;          /* Sum of hashes[*]->tx_bytes. */
1920
1921     /* All the "bond_entry"s that are assigned to this interface, in order of
1922      * increasing tx_bytes. */
1923     struct bond_entry **hashes;
1924     size_t n_hashes;
1925 };
1926
1927 /* Sorts pointers to pointers to bond_entries in ascending order by the
1928  * interface to which they are assigned, and within a single interface in
1929  * ascending order of bytes transmitted. */
1930 static int
1931 compare_bond_entries(const void *a_, const void *b_)
1932 {
1933     const struct bond_entry *const *ap = a_;
1934     const struct bond_entry *const *bp = b_;
1935     const struct bond_entry *a = *ap;
1936     const struct bond_entry *b = *bp;
1937     if (a->iface_idx != b->iface_idx) {
1938         return a->iface_idx > b->iface_idx ? 1 : -1;
1939     } else if (a->tx_bytes != b->tx_bytes) {
1940         return a->tx_bytes > b->tx_bytes ? 1 : -1;
1941     } else {
1942         return 0;
1943     }
1944 }
1945
1946 /* Sorts slave_balances so that enabled ports come first, and otherwise in
1947  * *descending* order by number of bytes transmitted. */
1948 static int
1949 compare_slave_balance(const void *a_, const void *b_)
1950 {
1951     const struct slave_balance *a = a_;
1952     const struct slave_balance *b = b_;
1953     if (a->iface->enabled != b->iface->enabled) {
1954         return a->iface->enabled ? -1 : 1;
1955     } else if (a->tx_bytes != b->tx_bytes) {
1956         return a->tx_bytes > b->tx_bytes ? -1 : 1;
1957     } else {
1958         return 0;
1959     }
1960 }
1961
1962 static void
1963 swap_bals(struct slave_balance *a, struct slave_balance *b)
1964 {
1965     struct slave_balance tmp = *a;
1966     *a = *b;
1967     *b = tmp;
1968 }
1969
1970 /* Restores the 'n_bals' slave_balance structures in 'bals' to sorted order
1971  * given that 'p' (and only 'p') might be in the wrong location.
1972  *
1973  * This function invalidates 'p', since it might now be in a different memory
1974  * location. */
1975 static void
1976 resort_bals(struct slave_balance *p,
1977             struct slave_balance bals[], size_t n_bals)
1978 {
1979     if (n_bals > 1) {
1980         for (; p > bals && p->tx_bytes > p[-1].tx_bytes; p--) {
1981             swap_bals(p, p - 1);
1982         }
1983         for (; p < &bals[n_bals - 1] && p->tx_bytes < p[1].tx_bytes; p++) {
1984             swap_bals(p, p + 1);
1985         }
1986     }
1987 }
1988
1989 static void
1990 log_bals(const struct slave_balance *bals, size_t n_bals, struct port *port)
1991 {
1992     if (VLOG_IS_DBG_ENABLED()) {
1993         struct ds ds = DS_EMPTY_INITIALIZER;
1994         const struct slave_balance *b;
1995
1996         for (b = bals; b < bals + n_bals; b++) {
1997             size_t i;
1998
1999             if (b > bals) {
2000                 ds_put_char(&ds, ',');
2001             }
2002             ds_put_format(&ds, " %s %"PRIu64"kB",
2003                           b->iface->name, b->tx_bytes / 1024);
2004
2005             if (!b->iface->enabled) {
2006                 ds_put_cstr(&ds, " (disabled)");
2007             }
2008             if (b->n_hashes > 0) {
2009                 ds_put_cstr(&ds, " (");
2010                 for (i = 0; i < b->n_hashes; i++) {
2011                     const struct bond_entry *e = b->hashes[i];
2012                     if (i > 0) {
2013                         ds_put_cstr(&ds, " + ");
2014                     }
2015                     ds_put_format(&ds, "h%td: %"PRIu64"kB",
2016                                   e - port->bond_hash, e->tx_bytes / 1024);
2017                 }
2018                 ds_put_cstr(&ds, ")");
2019             }
2020         }
2021         VLOG_DBG("bond %s:%s", port->name, ds_cstr(&ds));
2022         ds_destroy(&ds);
2023     }
2024 }
2025
2026 /* Shifts 'hash' from 'from' to 'to' within 'port'. */
2027 static void
2028 bond_shift_load(struct slave_balance *from, struct slave_balance *to,
2029                 struct bond_entry *hash)
2030 {
2031     struct port *port = from->iface->port;
2032     uint64_t delta = hash->tx_bytes;
2033
2034     VLOG_INFO("bond %s: shift %"PRIu64"kB of load (with hash %td) "
2035               "from %s to %s (now carrying %"PRIu64"kB and "
2036               "%"PRIu64"kB load, respectively)",
2037               port->name, delta / 1024, hash - port->bond_hash,
2038               from->iface->name, to->iface->name,
2039               (from->tx_bytes - delta) / 1024,
2040               (to->tx_bytes + delta) / 1024);
2041
2042     /* Delete element from from->hashes.
2043      *
2044      * We don't bother to add the element to to->hashes because not only would
2045      * it require more work, the only purpose it would be to allow that hash to
2046      * be migrated to another slave in this rebalancing run, and there is no
2047      * point in doing that.  */
2048     if (from->hashes[0] == hash) {
2049         from->hashes++;
2050     } else {
2051         int i = hash - from->hashes[0];
2052         memmove(from->hashes + i, from->hashes + i + 1,
2053                 (from->n_hashes - (i + 1)) * sizeof *from->hashes);
2054     }
2055     from->n_hashes--;
2056
2057     /* Shift load away from 'from' to 'to'. */
2058     from->tx_bytes -= delta;
2059     to->tx_bytes += delta;
2060
2061     /* Arrange for flows to be revalidated. */
2062     ofproto_revalidate(port->bridge->ofproto, hash->iface_tag);
2063     hash->iface_idx = to->iface->port_ifidx;
2064     hash->iface_tag = tag_create_random();
2065
2066 }
2067
2068 static void
2069 bond_rebalance_port(struct port *port)
2070 {
2071     struct slave_balance bals[DP_MAX_PORTS];
2072     size_t n_bals;
2073     struct bond_entry *hashes[BOND_MASK + 1];
2074     struct slave_balance *b, *from, *to;
2075     struct bond_entry *e;
2076     size_t i;
2077
2078     /* Sets up 'bals' to describe each of the port's interfaces, sorted in
2079      * descending order of tx_bytes, so that bals[0] represents the most
2080      * heavily loaded slave and bals[n_bals - 1] represents the least heavily
2081      * loaded slave.
2082      *
2083      * The code is a bit tricky: to avoid dynamically allocating a 'hashes'
2084      * array for each slave_balance structure, we sort our local array of
2085      * hashes in order by slave, so that all of the hashes for a given slave
2086      * become contiguous in memory, and then we point each 'hashes' members of
2087      * a slave_balance structure to the start of a contiguous group. */
2088     n_bals = port->n_ifaces;
2089     for (b = bals; b < &bals[n_bals]; b++) {
2090         b->iface = port->ifaces[b - bals];
2091         b->tx_bytes = 0;
2092         b->hashes = NULL;
2093         b->n_hashes = 0;
2094     }
2095     for (i = 0; i <= BOND_MASK; i++) {
2096         hashes[i] = &port->bond_hash[i];
2097     }
2098     qsort(hashes, BOND_MASK + 1, sizeof *hashes, compare_bond_entries);
2099     for (i = 0; i <= BOND_MASK; i++) {
2100         e = hashes[i];
2101         if (e->iface_idx >= 0 && e->iface_idx < port->n_ifaces) {
2102             b = &bals[e->iface_idx];
2103             b->tx_bytes += e->tx_bytes;
2104             if (!b->hashes) {
2105                 b->hashes = &hashes[i];
2106             }
2107             b->n_hashes++;
2108         }
2109     }
2110     qsort(bals, n_bals, sizeof *bals, compare_slave_balance);
2111     log_bals(bals, n_bals, port);
2112
2113     /* Discard slaves that aren't enabled (which were sorted to the back of the
2114      * array earlier). */
2115     while (!bals[n_bals - 1].iface->enabled) {
2116         n_bals--;
2117         if (!n_bals) {
2118             return;
2119         }
2120     }
2121
2122     /* Shift load from the most-loaded slaves to the least-loaded slaves. */
2123     to = &bals[n_bals - 1];
2124     for (from = bals; from < to; ) {
2125         uint64_t overload = from->tx_bytes - to->tx_bytes;
2126         if (overload < to->tx_bytes >> 5 || overload < 100000) {
2127             /* The extra load on 'from' (and all less-loaded slaves), compared
2128              * to that of 'to' (the least-loaded slave), is less than ~3%, or
2129              * it is less than ~1Mbps.  No point in rebalancing. */
2130             break;
2131         } else if (from->n_hashes == 1) {
2132             /* 'from' only carries a single MAC hash, so we can't shift any
2133              * load away from it, even though we want to. */
2134             from++;
2135         } else {
2136             /* 'from' is carrying significantly more load than 'to', and that
2137              * load is split across at least two different hashes.  Pick a hash
2138              * to migrate to 'to' (the least-loaded slave), given that doing so
2139              * must not cause 'to''s load to exceed 'from''s load.
2140              *
2141              * The sort order we use means that we prefer to shift away the
2142              * smallest hashes instead of the biggest ones.  There is little
2143              * reason behind this decision; we could use the opposite sort
2144              * order to shift away big hashes ahead of small ones. */
2145             size_t i;
2146
2147             for (i = 0; i < from->n_hashes; i++) {
2148                 uint64_t delta = from->hashes[i]->tx_bytes;
2149                 if (to->tx_bytes + delta < from->tx_bytes - delta) {
2150                     break;
2151                 }
2152             }
2153             if (i < from->n_hashes) {
2154                 bond_shift_load(from, to, from->hashes[i]);
2155
2156                 /* Re-sort 'bals'.  Note that this may make 'from' and 'to'
2157                  * point to different slave_balance structures.  It is only
2158                  * valid to do these two operations in a row at all because we
2159                  * know that 'from' will not move past 'to' and vice versa. */
2160                 resort_bals(from, bals, n_bals);
2161                 resort_bals(to, bals, n_bals);
2162             } else {
2163                 from++;
2164             }
2165         }
2166     }
2167
2168     /* Implement exponentially weighted moving average.  A weight of 1/2 causes
2169      * historical data to decay to <1% in 7 rebalancing runs.  */
2170     for (e = &port->bond_hash[0]; e <= &port->bond_hash[BOND_MASK]; e++) {
2171         e->tx_bytes /= 2;
2172     }
2173 }
2174
2175 static void
2176 bond_send_learning_packets(struct port *port)
2177 {
2178     struct bridge *br = port->bridge;
2179     struct mac_entry *e;
2180     struct ofpbuf packet;
2181     int error, n_packets, n_errors;
2182
2183     if (!port->n_ifaces || port->active_iface < 0 || !br->ml) {
2184         return;
2185     }
2186
2187     ofpbuf_init(&packet, 128);
2188     error = n_packets = n_errors = 0;
2189     LIST_FOR_EACH (e, struct mac_entry, lru_node, &br->ml->lrus) {
2190         static const char s[] = "Open vSwitch Bond Failover";
2191         union ofp_action actions[2], *a;
2192         struct eth_header *eth;
2193         struct llc_snap_header *llc_snap;
2194         uint16_t dp_ifidx;
2195         tag_type tags = 0;
2196         flow_t flow;
2197         int retval;
2198
2199         if (e->port == port->port_idx
2200             || !choose_output_iface(port, e->mac, &dp_ifidx, &tags)) {
2201             continue;
2202         }
2203
2204         /* Compose packet to send. */
2205         ofpbuf_clear(&packet);
2206         eth = ofpbuf_put_zeros(&packet, ETH_HEADER_LEN);
2207         llc_snap = ofpbuf_put_zeros(&packet, LLC_SNAP_HEADER_LEN);
2208         ofpbuf_put(&packet, s, sizeof s); /* Includes null byte. */
2209         ofpbuf_put(&packet, e->mac, ETH_ADDR_LEN);
2210
2211         memcpy(eth->eth_dst, eth_addr_broadcast, ETH_ADDR_LEN);
2212         memcpy(eth->eth_src, e->mac, ETH_ADDR_LEN);
2213         eth->eth_type = htons(packet.size - ETH_HEADER_LEN);
2214
2215         llc_snap->llc.llc_dsap = LLC_DSAP_SNAP;
2216         llc_snap->llc.llc_ssap = LLC_SSAP_SNAP;
2217         llc_snap->llc.llc_cntl = LLC_CNTL_SNAP;
2218         memcpy(llc_snap->snap.snap_org, "\x00\x23\x20", 3);
2219         llc_snap->snap.snap_type = htons(0xf177); /* Random number. */
2220
2221         /* Compose actions. */
2222         memset(actions, 0, sizeof actions);
2223         a = actions;
2224         if (e->vlan) {
2225             a->vlan_vid.type = htons(OFPAT_SET_VLAN_VID);
2226             a->vlan_vid.len = htons(sizeof *a);
2227             a->vlan_vid.vlan_vid = htons(e->vlan);
2228             a++;
2229         }
2230         a->output.type = htons(OFPAT_OUTPUT);
2231         a->output.len = htons(sizeof *a);
2232         a->output.port = htons(odp_port_to_ofp_port(dp_ifidx));
2233         a++;
2234
2235         /* Send packet. */
2236         n_packets++;
2237         flow_extract(&packet, ODPP_NONE, &flow);
2238         retval = ofproto_send_packet(br->ofproto, &flow, actions, a - actions,
2239                                      &packet);
2240         if (retval) {
2241             error = retval;
2242             n_errors++;
2243         }
2244     }
2245     ofpbuf_uninit(&packet);
2246
2247     if (n_errors) {
2248         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2249         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
2250                      "packets, last error was: %s",
2251                      port->name, n_errors, n_packets, strerror(error));
2252     } else {
2253         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
2254                  port->name, n_packets);
2255     }
2256 }
2257 \f
2258 /* Port functions. */
2259
2260 static void
2261 port_create(struct bridge *br, const char *name)
2262 {
2263     struct port *port;
2264
2265     port = xcalloc(1, sizeof *port);
2266     port->bridge = br;
2267     port->port_idx = br->n_ports;
2268     port->vlan = -1;
2269     port->trunks = NULL;
2270     port->name = xstrdup(name);
2271     port->active_iface = -1;
2272     port->stp_state = STP_DISABLED;
2273     port->stp_state_tag = 0;
2274
2275     if (br->n_ports >= br->allocated_ports) {
2276         br->ports = x2nrealloc(br->ports, &br->allocated_ports,
2277                                sizeof *br->ports);
2278     }
2279     br->ports[br->n_ports++] = port;
2280
2281     VLOG_INFO("created port %s on bridge %s", port->name, br->name);
2282     bridge_flush(br);
2283 }
2284
2285 static void
2286 port_reconfigure(struct port *port)
2287 {
2288     bool bonded = cfg_has_section("bonding.%s", port->name);
2289     struct svec old_ifaces, new_ifaces;
2290     unsigned long *trunks;
2291     int vlan;
2292     size_t i;
2293
2294     /* Collect old and new interfaces. */
2295     svec_init(&old_ifaces);
2296     svec_init(&new_ifaces);
2297     for (i = 0; i < port->n_ifaces; i++) {
2298         svec_add(&old_ifaces, port->ifaces[i]->name);
2299     }
2300     svec_sort(&old_ifaces);
2301     if (bonded) {
2302         cfg_get_all_keys(&new_ifaces, "bonding.%s.slave", port->name);
2303         if (!new_ifaces.n) {
2304             VLOG_ERR("port %s: no interfaces specified for bonded port",
2305                      port->name);
2306         } else if (new_ifaces.n == 1) {
2307             VLOG_WARN("port %s: only 1 interface specified for bonded port",
2308                       port->name);
2309         }
2310
2311         port->updelay = cfg_get_int(0, "bonding.%s.updelay", port->name);
2312         if (port->updelay < 0) {
2313             port->updelay = 0;
2314         }
2315         port->downdelay = cfg_get_int(0, "bonding.%s.downdelay", port->name);
2316         if (port->downdelay < 0) {
2317             port->downdelay = 0;
2318         }
2319     } else {
2320         svec_init(&new_ifaces);
2321         svec_add(&new_ifaces, port->name);
2322     }
2323
2324     /* Get rid of deleted interfaces and add new interfaces. */
2325     for (i = 0; i < port->n_ifaces; i++) {
2326         struct iface *iface = port->ifaces[i];
2327         if (!svec_contains(&new_ifaces, iface->name)) {
2328             iface_destroy(iface);
2329         } else {
2330             i++;
2331         }
2332     }
2333     for (i = 0; i < new_ifaces.n; i++) {
2334         const char *name = new_ifaces.names[i];
2335         if (!svec_contains(&old_ifaces, name)) {
2336             iface_create(port, name);
2337         }
2338     }
2339
2340     /* Get VLAN tag. */
2341     vlan = -1;
2342     if (cfg_has("vlan.%s.tag", port->name)) {
2343         if (!bonded) {
2344             vlan = cfg_get_vlan(0, "vlan.%s.tag", port->name);
2345             if (vlan >= 0 && vlan <= 4095) {
2346                 VLOG_DBG("port %s: assigning VLAN tag %d", port->name, vlan);
2347             }
2348         } else {
2349             /* It's possible that bonded, VLAN-tagged ports make sense.  Maybe
2350              * they even work as-is.  But they have not been tested. */
2351             VLOG_WARN("port %s: VLAN tags not supported on bonded ports",
2352                       port->name);
2353         }
2354     }
2355     if (port->vlan != vlan) {
2356         port->vlan = vlan;
2357         bridge_flush(port->bridge);
2358     }
2359
2360     /* Get trunked VLANs. */
2361     trunks = NULL;
2362     if (vlan < 0) {
2363         size_t n_trunks, n_errors;
2364         size_t i;
2365
2366         trunks = bitmap_allocate(4096);
2367         n_trunks = cfg_count("vlan.%s.trunks", port->name);
2368         n_errors = 0;
2369         for (i = 0; i < n_trunks; i++) {
2370             int trunk = cfg_get_vlan(i, "vlan.%s.trunks", port->name);
2371             if (trunk >= 0) {
2372                 bitmap_set1(trunks, trunk);
2373             } else {
2374                 n_errors++;
2375             }
2376         }
2377         if (n_errors) {
2378             VLOG_ERR("port %s: invalid values for %zu trunk VLANs",
2379                      port->name, n_trunks);
2380         }
2381         if (n_errors == n_trunks) {
2382             if (n_errors) {
2383                 VLOG_ERR("port %s: no valid trunks, trunking all VLANs",
2384                          port->name);
2385             }
2386             bitmap_set_multiple(trunks, 0, 4096, 1);
2387         }
2388     } else {
2389         if (cfg_has("vlan.%s.trunks", port->name)) {
2390             VLOG_ERR("ignoring vlan.%s.trunks in favor of vlan.%s.vlan",
2391                      port->name, port->name);
2392         }
2393     }
2394     if (trunks == NULL
2395         ? port->trunks != NULL
2396         : port->trunks == NULL || !bitmap_equal(trunks, port->trunks, 4096)) {
2397         bridge_flush(port->bridge);
2398     }
2399     bitmap_free(port->trunks);
2400     port->trunks = trunks;
2401
2402     svec_destroy(&old_ifaces);
2403     svec_destroy(&new_ifaces);
2404 }
2405
2406 static void
2407 port_destroy(struct port *port)
2408 {
2409     if (port) {
2410         struct bridge *br = port->bridge;
2411         struct port *del;
2412         size_t i;
2413
2414         proc_net_compat_update_vlan(port->name, NULL, 0);
2415
2416         for (i = 0; i < MAX_MIRRORS; i++) {
2417             struct mirror *m = br->mirrors[i];
2418             if (m && m->out_port == port) {
2419                 mirror_destroy(m);
2420             }
2421         }
2422
2423         while (port->n_ifaces > 0) {
2424             iface_destroy(port->ifaces[port->n_ifaces - 1]);
2425         }
2426
2427         del = br->ports[port->port_idx] = br->ports[--br->n_ports];
2428         del->port_idx = port->port_idx;
2429
2430         free(port->ifaces);
2431         bitmap_free(port->trunks);
2432         free(port->name);
2433         free(port);
2434         bridge_flush(br);
2435     }
2436 }
2437
2438 static struct port *
2439 port_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
2440 {
2441     struct iface *iface = iface_from_dp_ifidx(br, dp_ifidx);
2442     return iface ? iface->port : NULL;
2443 }
2444
2445 static struct port *
2446 port_lookup(const struct bridge *br, const char *name)
2447 {
2448     size_t i;
2449
2450     for (i = 0; i < br->n_ports; i++) {
2451         struct port *port = br->ports[i];
2452         if (!strcmp(port->name, name)) {
2453             return port;
2454         }
2455     }
2456     return NULL;
2457 }
2458
2459 static void
2460 port_update_bonding(struct port *port)
2461 {
2462     if (port->n_ifaces < 2) {
2463         /* Not a bonded port. */
2464         if (port->bond_hash) {
2465             free(port->bond_hash);
2466             port->bond_hash = NULL;
2467             proc_net_compat_update_bond(port->name, NULL);
2468         }
2469     } else {
2470         if (!port->bond_hash) {
2471             size_t i;
2472
2473             port->bond_hash = xcalloc(BOND_MASK + 1, sizeof *port->bond_hash);
2474             for (i = 0; i <= BOND_MASK; i++) {
2475                 struct bond_entry *e = &port->bond_hash[i];
2476                 e->iface_idx = -1;
2477                 e->tx_bytes = 0;
2478             }
2479             port->no_ifaces_tag = tag_create_random();
2480             bond_choose_active_iface(port);
2481         }
2482         port_update_bond_compat(port);
2483     }
2484 }
2485
2486 static void
2487 port_update_bond_compat(struct port *port)
2488 {
2489     struct compat_bond bond;
2490     size_t i;
2491
2492     if (port->n_ifaces < 2) {
2493         return;
2494     }
2495
2496     bond.up = false;
2497     bond.updelay = port->updelay;
2498     bond.downdelay = port->downdelay;
2499     bond.n_slaves = port->n_ifaces;
2500     bond.slaves = xmalloc(port->n_ifaces * sizeof *bond.slaves);
2501     for (i = 0; i < port->n_ifaces; i++) {
2502         struct iface *iface = port->ifaces[i];
2503         struct compat_bond_slave *slave = &bond.slaves[i];
2504         slave->name = iface->name;
2505         slave->up = ((iface->enabled && iface->delay_expires == LLONG_MAX) ||
2506                      (!iface->enabled && iface->delay_expires != LLONG_MAX));
2507         if (slave->up) {
2508             bond.up = true;
2509         }
2510         memcpy(slave->mac, iface->mac, ETH_ADDR_LEN);
2511     }
2512     proc_net_compat_update_bond(port->name, &bond);
2513     free(bond.slaves);
2514 }
2515
2516 static void
2517 port_update_vlan_compat(struct port *port)
2518 {
2519     struct bridge *br = port->bridge;
2520     char *vlandev_name = NULL;
2521
2522     if (port->vlan > 0) {
2523         /* Figure out the name that the VLAN device should actually have, if it
2524          * existed.  This takes some work because the VLAN device would not
2525          * have port->name in its name; rather, it would have the trunk port's
2526          * name, and 'port' would be attached to a bridge that also had the
2527          * VLAN device one of its ports.  So we need to find a trunk port that
2528          * includes port->vlan.
2529          *
2530          * There might be more than one candidate.  This doesn't happen on
2531          * XenServer, so if it happens we just pick the first choice in
2532          * alphabetical order instead of creating multiple VLAN devices. */
2533         size_t i;
2534         for (i = 0; i < br->n_ports; i++) {
2535             struct port *p = br->ports[i];
2536             if (port_trunks_vlan(p, port->vlan)
2537                 && p->n_ifaces
2538                 && (!vlandev_name || strcmp(p->name, vlandev_name) <= 0))
2539             {
2540                 const uint8_t *ea = p->ifaces[0]->mac;
2541                 if (!eth_addr_is_multicast(ea) &&
2542                     !eth_addr_is_reserved(ea) &&
2543                     !eth_addr_is_zero(ea)) {
2544                     vlandev_name = p->name;
2545                 }
2546             }
2547         }
2548     }
2549     proc_net_compat_update_vlan(port->name, vlandev_name, port->vlan);
2550 }
2551 \f
2552 /* Interface functions. */
2553
2554 static void
2555 iface_create(struct port *port, const char *name)
2556 {
2557     struct iface *iface;
2558
2559     iface = xcalloc(1, sizeof *iface);
2560     iface->port = port;
2561     iface->port_ifidx = port->n_ifaces;
2562     iface->name = xstrdup(name);
2563     iface->dp_ifidx = -1;
2564     iface->tag = tag_create_random();
2565     iface->delay_expires = LLONG_MAX;
2566
2567     netdev_nodev_get_etheraddr(name, iface->mac);
2568     netdev_nodev_get_carrier(name, &iface->enabled);
2569
2570     if (port->n_ifaces >= port->allocated_ifaces) {
2571         port->ifaces = x2nrealloc(port->ifaces, &port->allocated_ifaces,
2572                                   sizeof *port->ifaces);
2573     }
2574     port->ifaces[port->n_ifaces++] = iface;
2575     if (port->n_ifaces > 1) {
2576         port->bridge->has_bonded_ports = true;
2577     }
2578
2579     VLOG_DBG("attached network device %s to port %s", iface->name, port->name);
2580
2581     port_update_bonding(port);
2582     bridge_flush(port->bridge);
2583 }
2584
2585 static void
2586 iface_destroy(struct iface *iface)
2587 {
2588     if (iface) {
2589         struct port *port = iface->port;
2590         struct bridge *br = port->bridge;
2591         bool del_active = port->active_iface == iface->port_ifidx;
2592         struct iface *del;
2593
2594         if (iface->dp_ifidx >= 0) {
2595             port_array_set(&br->ifaces, iface->dp_ifidx, NULL);
2596         }
2597
2598         del = port->ifaces[iface->port_ifidx] = port->ifaces[--port->n_ifaces];
2599         del->port_ifidx = iface->port_ifidx;
2600
2601         free(iface->name);
2602         free(iface);
2603
2604         if (del_active) {
2605             ofproto_revalidate(port->bridge->ofproto, port->active_iface_tag);
2606             bond_choose_active_iface(port);
2607             bond_send_learning_packets(port);
2608         }
2609
2610         port_update_bonding(port);
2611         bridge_flush(port->bridge);
2612     }
2613 }
2614
2615 static struct iface *
2616 iface_lookup(const struct bridge *br, const char *name)
2617 {
2618     size_t i, j;
2619
2620     for (i = 0; i < br->n_ports; i++) {
2621         struct port *port = br->ports[i];
2622         for (j = 0; j < port->n_ifaces; j++) {
2623             struct iface *iface = port->ifaces[j];
2624             if (!strcmp(iface->name, name)) {
2625                 return iface;
2626             }
2627         }
2628     }
2629     return NULL;
2630 }
2631
2632 static struct iface *
2633 iface_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
2634 {
2635     return port_array_get(&br->ifaces, dp_ifidx);
2636 }
2637 \f
2638 /* Port mirroring. */
2639
2640 static void
2641 mirror_reconfigure(struct bridge *br)
2642 {
2643     struct svec old_mirrors, new_mirrors;
2644     size_t i;
2645
2646     /* Collect old and new mirrors. */
2647     svec_init(&old_mirrors);
2648     svec_init(&new_mirrors);
2649     cfg_get_subsections(&new_mirrors, "mirror.%s", br->name);
2650     for (i = 0; i < MAX_MIRRORS; i++) {
2651         if (br->mirrors[i]) {
2652             svec_add(&old_mirrors, br->mirrors[i]->name);
2653         }
2654     }
2655
2656     /* Get rid of deleted mirrors and add new mirrors. */
2657     svec_sort(&old_mirrors);
2658     assert(svec_is_unique(&old_mirrors));
2659     svec_sort(&new_mirrors);
2660     assert(svec_is_unique(&new_mirrors));
2661     for (i = 0; i < MAX_MIRRORS; i++) {
2662         struct mirror *m = br->mirrors[i];
2663         if (m && !svec_contains(&new_mirrors, m->name)) {
2664             mirror_destroy(m);
2665         }
2666     }
2667     for (i = 0; i < new_mirrors.n; i++) {
2668         const char *name = new_mirrors.names[i];
2669         if (!svec_contains(&old_mirrors, name)) {
2670             mirror_create(br, name);
2671         }
2672     }
2673     svec_destroy(&old_mirrors);
2674     svec_destroy(&new_mirrors);
2675
2676     /* Reconfigure all mirrors. */
2677     for (i = 0; i < MAX_MIRRORS; i++) {
2678         if (br->mirrors[i]) {
2679             mirror_reconfigure_one(br->mirrors[i]);
2680         }
2681     }
2682
2683     /* Update port reserved status. */
2684     for (i = 0; i < br->n_ports; i++) {
2685         br->ports[i]->is_mirror_output_port = false;
2686     }
2687     for (i = 0; i < MAX_MIRRORS; i++) {
2688         struct mirror *m = br->mirrors[i];
2689         if (m && m->out_port) {
2690             m->out_port->is_mirror_output_port = true;
2691         }
2692     }
2693 }
2694
2695 static void
2696 mirror_create(struct bridge *br, const char *name)
2697 {
2698     struct mirror *m;
2699     size_t i;
2700
2701     for (i = 0; ; i++) {
2702         if (i >= MAX_MIRRORS) {
2703             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
2704                       "cannot create %s", br->name, MAX_MIRRORS, name);
2705             return;
2706         }
2707         if (!br->mirrors[i]) {
2708             break;
2709         }
2710     }
2711
2712     VLOG_INFO("created port mirror %s on bridge %s", name, br->name);
2713     bridge_flush(br);
2714
2715     br->mirrors[i] = m = xcalloc(1, sizeof *m);
2716     m->bridge = br;
2717     m->idx = i;
2718     m->name = xstrdup(name);
2719     svec_init(&m->src_ports);
2720     svec_init(&m->dst_ports);
2721     m->vlans = NULL;
2722     m->n_vlans = 0;
2723     m->out_vlan = -1;
2724     m->out_port = NULL;
2725 }
2726
2727 static void
2728 mirror_destroy(struct mirror *m)
2729 {
2730     if (m) {
2731         struct bridge *br = m->bridge;
2732         size_t i;
2733
2734         for (i = 0; i < br->n_ports; i++) {
2735             br->ports[i]->src_mirrors &= ~(MIRROR_MASK_C(1) << m->idx);
2736             br->ports[i]->dst_mirrors &= ~(MIRROR_MASK_C(1) << m->idx);
2737         }
2738
2739         svec_destroy(&m->src_ports);
2740         svec_destroy(&m->dst_ports);
2741         free(m->vlans);
2742
2743         m->bridge->mirrors[m->idx] = NULL;
2744         free(m);
2745
2746         bridge_flush(br);
2747     }
2748 }
2749
2750 static void
2751 prune_ports(struct mirror *m, struct svec *ports)
2752 {
2753     struct svec tmp;
2754     size_t i;
2755
2756     svec_sort_unique(ports);
2757
2758     svec_init(&tmp);
2759     for (i = 0; i < ports->n; i++) {
2760         const char *name = ports->names[i];
2761         if (port_lookup(m->bridge, name)) {
2762             svec_add(&tmp, name);
2763         } else {
2764             VLOG_WARN("mirror.%s.%s: cannot match on nonexistent port %s",
2765                       m->bridge->name, m->name, name);
2766         }
2767     }
2768     svec_swap(ports, &tmp);
2769     svec_destroy(&tmp);
2770 }
2771
2772 static size_t
2773 prune_vlans(struct mirror *m, struct svec *vlan_strings, int **vlans)
2774 {
2775     size_t n_vlans, i;
2776
2777     /* This isn't perfect: it won't combine "0" and "00", and the textual sort
2778      * order won't give us numeric sort order.  But that's good enough for what
2779      * we need right now. */
2780     svec_sort_unique(vlan_strings);
2781
2782     *vlans = xmalloc(sizeof *vlans * vlan_strings->n);
2783     n_vlans = 0;
2784     for (i = 0; i < vlan_strings->n; i++) {
2785         const char *name = vlan_strings->names[i];
2786         int vlan;
2787         if (!str_to_int(name, 10, &vlan) || vlan < 0 || vlan > 4095) {
2788             VLOG_WARN("mirror.%s.%s.select.vlan: ignoring invalid VLAN %s",
2789                       m->bridge->name, m->name, name);
2790         } else {
2791             (*vlans)[n_vlans++] = vlan;
2792         }
2793     }
2794     return n_vlans;
2795 }
2796
2797 static bool
2798 vlan_is_mirrored(const struct mirror *m, int vlan)
2799 {
2800     size_t i;
2801
2802     for (i = 0; i < m->n_vlans; i++) {
2803         if (m->vlans[i] == vlan) {
2804             return true;
2805         }
2806     }
2807     return false;
2808 }
2809
2810 static bool
2811 port_trunks_any_mirrored_vlan(const struct mirror *m, const struct port *p)
2812 {
2813     size_t i;
2814
2815     for (i = 0; i < m->n_vlans; i++) {
2816         if (port_trunks_vlan(p, m->vlans[i])) {
2817             return true;
2818         }
2819     }
2820     return false;
2821 }
2822
2823 static void
2824 mirror_reconfigure_one(struct mirror *m)
2825 {
2826     char *pfx = xasprintf("mirror.%s.%s", m->bridge->name, m->name);
2827     struct svec src_ports, dst_ports, ports;
2828     struct svec vlan_strings;
2829     mirror_mask_t mirror_bit;
2830     const char *out_port_name;
2831     struct port *out_port;
2832     int out_vlan;
2833     size_t n_vlans;
2834     int *vlans;
2835     size_t i;
2836     bool mirror_all_ports;
2837
2838     /* Get output port. */
2839     out_port_name = cfg_get_key(0, "mirror.%s.%s.output.port",
2840                                 m->bridge->name, m->name);
2841     if (out_port_name) {
2842         out_port = port_lookup(m->bridge, out_port_name);
2843         if (!out_port) {
2844             VLOG_ERR("%s.output.port: bridge %s does not have a port "
2845                       "named %s", pfx, m->bridge->name, out_port_name);
2846             mirror_destroy(m);
2847             free(pfx);
2848             return;
2849         }
2850         out_vlan = -1;
2851
2852         if (cfg_has("%s.output.vlan", pfx)) {
2853             VLOG_ERR("%s.output.port and %s.output.vlan both specified; "
2854                      "ignoring %s.output.vlan", pfx, pfx, pfx);
2855         }
2856     } else if (cfg_has("%s.output.vlan", pfx)) {
2857         out_port = NULL;
2858         out_vlan = cfg_get_vlan(0, "%s.output.vlan", pfx);
2859     } else {
2860         VLOG_ERR("%s: neither %s.output.port nor %s.output.vlan specified, "
2861                  "but exactly one is required; disabling port mirror %s",
2862                  pfx, pfx, pfx, pfx);
2863         mirror_destroy(m);
2864         free(pfx);
2865         return;
2866     }
2867
2868     /* Get all the ports, and drop duplicates and ports that don't exist. */
2869     svec_init(&src_ports);
2870     svec_init(&dst_ports);
2871     svec_init(&ports);
2872     cfg_get_all_keys(&src_ports, "%s.select.src-port", pfx);
2873     cfg_get_all_keys(&dst_ports, "%s.select.dst-port", pfx);
2874     cfg_get_all_keys(&ports, "%s.select.port", pfx);
2875     svec_append(&src_ports, &ports);
2876     svec_append(&dst_ports, &ports);
2877     svec_destroy(&ports);
2878     prune_ports(m, &src_ports);
2879     prune_ports(m, &dst_ports);
2880
2881     /* Get all the vlans, and drop duplicate and invalid vlans. */
2882     svec_init(&vlan_strings);
2883     cfg_get_all_keys(&vlan_strings, "%s.select.vlan", pfx);
2884     n_vlans = prune_vlans(m, &vlan_strings, &vlans);
2885     svec_destroy(&vlan_strings);
2886
2887     /* Update mirror data. */
2888     if (!svec_equal(&m->src_ports, &src_ports)
2889         || !svec_equal(&m->dst_ports, &dst_ports)
2890         || m->n_vlans != n_vlans
2891         || memcmp(m->vlans, vlans, sizeof *vlans * n_vlans)
2892         || m->out_port != out_port
2893         || m->out_vlan != out_vlan) {
2894         bridge_flush(m->bridge);
2895     }
2896     svec_swap(&m->src_ports, &src_ports);
2897     svec_swap(&m->dst_ports, &dst_ports);
2898     free(m->vlans);
2899     m->vlans = vlans;
2900     m->n_vlans = n_vlans;
2901     m->out_port = out_port;
2902     m->out_vlan = out_vlan;
2903
2904     /* If no selection criteria have been given, mirror for all ports. */
2905     mirror_all_ports = (!m->src_ports.n) && (!m->dst_ports.n) && (!m->n_vlans);
2906
2907     /* Update ports. */
2908     mirror_bit = MIRROR_MASK_C(1) << m->idx;
2909     for (i = 0; i < m->bridge->n_ports; i++) {
2910         struct port *port = m->bridge->ports[i];
2911
2912         if (mirror_all_ports
2913             || svec_contains(&m->src_ports, port->name)
2914             || (m->n_vlans
2915                 && (!port->vlan
2916                     ? port_trunks_any_mirrored_vlan(m, port)
2917                     : vlan_is_mirrored(m, port->vlan)))) {
2918             port->src_mirrors |= mirror_bit;
2919         } else {
2920             port->src_mirrors &= ~mirror_bit;
2921         }
2922
2923         if (mirror_all_ports || svec_contains(&m->dst_ports, port->name)) {
2924             port->dst_mirrors |= mirror_bit;
2925         } else {
2926             port->dst_mirrors &= ~mirror_bit;
2927         }
2928     }
2929
2930     /* Clean up. */
2931     svec_destroy(&src_ports);
2932     svec_destroy(&dst_ports);
2933     free(pfx);
2934 }
2935 \f
2936 /* Spanning tree protocol. */
2937
2938 static void brstp_update_port_state(struct port *);
2939
2940 static void
2941 brstp_send_bpdu(struct ofpbuf *pkt, int port_no, void *br_)
2942 {
2943     struct bridge *br = br_;
2944     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2945     struct iface *iface = iface_from_dp_ifidx(br, port_no);
2946     if (!iface) {
2947         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
2948                      br->name, port_no);
2949     } else if (eth_addr_is_zero(iface->mac)) {
2950         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d with unknown MAC",
2951                      br->name, port_no);
2952     } else {
2953         union ofp_action action;
2954         struct eth_header *eth = pkt->l2;
2955         flow_t flow;
2956
2957         memcpy(eth->eth_src, iface->mac, ETH_ADDR_LEN);
2958
2959         memset(&action, 0, sizeof action);
2960         action.type = htons(OFPAT_OUTPUT);
2961         action.output.len = htons(sizeof action);
2962         action.output.port = htons(port_no);
2963
2964         flow_extract(pkt, ODPP_NONE, &flow);
2965         ofproto_send_packet(br->ofproto, &flow, &action, 1, pkt);
2966     }
2967     ofpbuf_delete(pkt);
2968 }
2969
2970 static void
2971 brstp_reconfigure(struct bridge *br)
2972 {
2973     size_t i;
2974
2975     if (!cfg_get_bool(0, "stp.%s.enabled", br->name)) {
2976         if (br->stp) {
2977             stp_destroy(br->stp);
2978             br->stp = NULL;
2979
2980             bridge_flush(br);
2981         }
2982     } else {
2983         uint64_t bridge_address, bridge_id;
2984         int bridge_priority;
2985
2986         bridge_address = cfg_get_mac(0, "stp.%s.address", br->name);
2987         if (!bridge_address) {
2988             if (br->stp) {
2989                 bridge_address = (stp_get_bridge_id(br->stp)
2990                                   & ((UINT64_C(1) << 48) - 1));
2991             } else {
2992                 uint8_t mac[ETH_ADDR_LEN];
2993                 eth_addr_random(mac);
2994                 bridge_address = eth_addr_to_uint64(mac);
2995             }
2996         }
2997
2998         if (cfg_is_valid(CFG_INT | CFG_REQUIRED, "stp.%s.priority",
2999                          br->name)) {
3000             bridge_priority = cfg_get_int(0, "stp.%s.priority", br->name);
3001         } else {
3002             bridge_priority = STP_DEFAULT_BRIDGE_PRIORITY;
3003         }
3004
3005         bridge_id = bridge_address | ((uint64_t) bridge_priority << 48);
3006         if (!br->stp) {
3007             br->stp = stp_create(br->name, bridge_id, brstp_send_bpdu, br);
3008             br->stp_last_tick = time_msec();
3009             bridge_flush(br);
3010         } else {
3011             if (bridge_id != stp_get_bridge_id(br->stp)) {
3012                 stp_set_bridge_id(br->stp, bridge_id);
3013                 bridge_flush(br);
3014             }
3015         }
3016
3017         for (i = 0; i < br->n_ports; i++) {
3018             struct port *p = br->ports[i];
3019             int dp_ifidx;
3020             struct stp_port *sp;
3021             int path_cost, priority;
3022             bool enable;
3023
3024             if (!p->n_ifaces) {
3025                 continue;
3026             }
3027             dp_ifidx = p->ifaces[0]->dp_ifidx;
3028             if (dp_ifidx < 0 || dp_ifidx >= STP_MAX_PORTS) {
3029                 continue;
3030             }
3031
3032             sp = stp_get_port(br->stp, dp_ifidx);
3033             enable = (!cfg_is_valid(CFG_BOOL | CFG_REQUIRED,
3034                                     "stp.%s.port.%s.enabled",
3035                                     br->name, p->name)
3036                       || cfg_get_bool(0, "stp.%s.port.%s.enabled",
3037                                       br->name, p->name));
3038             if (p->is_mirror_output_port) {
3039                 enable = false;
3040             }
3041             if (enable != (stp_port_get_state(sp) != STP_DISABLED)) {
3042                 bridge_flush(br); /* Might not be necessary. */
3043                 if (enable) {
3044                     stp_port_enable(sp);
3045                 } else {
3046                     stp_port_disable(sp);
3047                 }
3048             }
3049
3050             path_cost = cfg_get_int(0, "stp.%s.port.%s.path-cost",
3051                                     br->name, p->name);
3052             stp_port_set_path_cost(sp, path_cost ? path_cost : 19 /* XXX */);
3053
3054             priority = (cfg_is_valid(CFG_INT | CFG_REQUIRED,
3055                                      "stp.%s.port.%s.priority",
3056                                      br->name, p->name)
3057                         ? cfg_get_int(0, "stp.%s.port.%s.priority",
3058                                       br->name, p->name)
3059                         : STP_DEFAULT_PORT_PRIORITY);
3060             stp_port_set_priority(sp, priority);
3061         }
3062
3063         brstp_adjust_timers(br);
3064     }
3065     for (i = 0; i < br->n_ports; i++) {
3066         brstp_update_port_state(br->ports[i]);
3067     }
3068 }
3069
3070 static void
3071 brstp_update_port_state(struct port *p)
3072 {
3073     struct bridge *br = p->bridge;
3074     enum stp_state state;
3075
3076     /* Figure out new state. */
3077     state = STP_DISABLED;
3078     if (br->stp && p->n_ifaces > 0) {
3079         int dp_ifidx = p->ifaces[0]->dp_ifidx;
3080         if (dp_ifidx >= 0 && dp_ifidx < STP_MAX_PORTS) {
3081             state = stp_port_get_state(stp_get_port(br->stp, dp_ifidx));
3082         }
3083     }
3084
3085     /* Update state. */
3086     if (p->stp_state != state) {
3087         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 10);
3088         VLOG_INFO_RL(&rl, "port %s: STP state changed from %s to %s",
3089                      p->name, stp_state_name(p->stp_state),
3090                      stp_state_name(state));
3091         if (p->stp_state == STP_DISABLED) {
3092             bridge_flush(br);
3093         } else {
3094             ofproto_revalidate(p->bridge->ofproto, p->stp_state_tag);
3095         }
3096         p->stp_state = state;
3097         p->stp_state_tag = (p->stp_state == STP_DISABLED ? 0
3098                             : tag_create_random());
3099     }
3100 }
3101
3102 static void
3103 brstp_adjust_timers(struct bridge *br)
3104 {
3105     int hello_time = cfg_get_int(0, "stp.%s.hello-time", br->name);
3106     int max_age = cfg_get_int(0, "stp.%s.max-age", br->name);
3107     int forward_delay = cfg_get_int(0, "stp.%s.forward-delay", br->name);
3108
3109     stp_set_hello_time(br->stp, hello_time ? hello_time : 2000);
3110     stp_set_max_age(br->stp, max_age ? max_age : 20000);
3111     stp_set_forward_delay(br->stp, forward_delay ? forward_delay : 15000);
3112 }
3113
3114 static void
3115 brstp_run(struct bridge *br)
3116 {
3117     if (br->stp) {
3118         long long int now = time_msec();
3119         long long int elapsed = now - br->stp_last_tick;
3120         struct stp_port *sp;
3121
3122         if (elapsed > 0) {
3123             stp_tick(br->stp, MIN(INT_MAX, elapsed));
3124             br->stp_last_tick = now;
3125         }
3126         while (stp_get_changed_port(br->stp, &sp)) {
3127             struct port *p = port_from_dp_ifidx(br, stp_port_no(sp));
3128             if (p) {
3129                 brstp_update_port_state(p);
3130             }
3131         }
3132     }
3133 }
3134
3135 static void
3136 brstp_wait(struct bridge *br)
3137 {
3138     if (br->stp) {
3139         poll_timer_wait(1000);
3140     }
3141 }