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