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