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