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