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