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