vswitchd: Remove default controller config from Open_vSwitch table
[openvswitch] / vswitchd / bridge.c
1 /* Copyright (c) 2008, 2009, 2010 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 <sys/socket.h>
24 #include <net/if.h>
25 #include <openflow/openflow.h>
26 #include <signal.h>
27 #include <stdlib.h>
28 #include <strings.h>
29 #include <sys/stat.h>
30 #include <sys/socket.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include "bitmap.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 "jsonrpc.h"
41 #include "list.h"
42 #include "mac-learning.h"
43 #include "netdev.h"
44 #include "odp-util.h"
45 #include "ofp-print.h"
46 #include "ofpbuf.h"
47 #include "ofproto/netflow.h"
48 #include "ofproto/ofproto.h"
49 #include "ovsdb-data.h"
50 #include "packets.h"
51 #include "poll-loop.h"
52 #include "port-array.h"
53 #include "proc-net-compat.h"
54 #include "process.h"
55 #include "sha1.h"
56 #include "shash.h"
57 #include "socket-util.h"
58 #include "stream-ssl.h"
59 #include "svec.h"
60 #include "timeval.h"
61 #include "util.h"
62 #include "unixctl.h"
63 #include "vconn.h"
64 #include "vswitchd/vswitch-idl.h"
65 #include "xenserver.h"
66 #include "vlog.h"
67 #include "xtoxll.h"
68 #include "sflow_api.h"
69
70 VLOG_DEFINE_THIS_MODULE(bridge)
71
72 struct dst {
73     uint16_t vlan;
74     uint16_t dp_ifidx;
75 };
76
77 struct iface {
78     /* These members are always valid. */
79     struct port *port;          /* Containing port. */
80     size_t port_ifidx;          /* Index within containing port. */
81     char *name;                 /* Host network device name. */
82     tag_type tag;               /* Tag associated with this interface. */
83     long long delay_expires;    /* Time after which 'enabled' may change. */
84
85     /* These members are valid only after bridge_reconfigure() causes them to
86      * be initialized. */
87     int dp_ifidx;               /* Index within kernel datapath. */
88     struct netdev *netdev;      /* Network device. */
89     bool enabled;               /* May be chosen for flows? */
90     const struct ovsrec_interface *cfg;
91 };
92
93 #define BOND_MASK 0xff
94 struct bond_entry {
95     int iface_idx;              /* Index of assigned iface, or -1 if none. */
96     uint64_t tx_bytes;          /* Count of bytes recently transmitted. */
97     tag_type iface_tag;         /* Tag associated with iface_idx. */
98 };
99
100 #define MAX_MIRRORS 32
101 typedef uint32_t mirror_mask_t;
102 #define MIRROR_MASK_C(X) UINT32_C(X)
103 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
104 struct mirror {
105     struct bridge *bridge;
106     size_t idx;
107     char *name;
108     struct uuid uuid;           /* UUID of this "mirror" record in database. */
109
110     /* Selection criteria. */
111     struct shash src_ports;     /* Name is port name; data is always NULL. */
112     struct shash dst_ports;     /* Name is port name; data is always NULL. */
113     int *vlans;
114     size_t n_vlans;
115
116     /* Output. */
117     struct port *out_port;
118     int out_vlan;
119 };
120
121 #define FLOOD_PORT ((struct port *) 1) /* The 'flood' output port. */
122 struct port {
123     struct bridge *bridge;
124     size_t port_idx;
125     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
126     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
127                                  * NULL if all VLANs are trunked. */
128     const struct ovsrec_port *cfg;
129     char *name;
130
131     /* An ordinary bridge port has 1 interface.
132      * A bridge port for bonding has at least 2 interfaces. */
133     struct iface **ifaces;
134     size_t n_ifaces, allocated_ifaces;
135
136     /* Bonding info. */
137     struct bond_entry *bond_hash; /* An array of (BOND_MASK + 1) elements. */
138     int active_iface;           /* Ifidx on which bcasts accepted, or -1. */
139     tag_type active_iface_tag;  /* Tag for bcast flows. */
140     tag_type no_ifaces_tag;     /* Tag for flows when all ifaces disabled. */
141     int updelay, downdelay;     /* Delay before iface goes up/down, in ms. */
142     bool bond_compat_is_stale;  /* Need to call port_update_bond_compat()? */
143     bool bond_fake_iface;       /* Fake a bond interface for legacy compat? */
144     long bond_next_fake_iface_update; /* Next update to fake bond stats. */
145     int bond_rebalance_interval; /* Interval between rebalances, in ms. */
146     long long int bond_next_rebalance; /* Next rebalancing time. */
147
148     /* Port mirroring info. */
149     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
150     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
151     bool is_mirror_output_port; /* Does port mirroring send frames here? */
152 };
153
154 #define DP_MAX_PORTS 255
155 struct bridge {
156     struct list node;           /* Node in global list of bridges. */
157     char *name;                 /* User-specified arbitrary name. */
158     struct mac_learning *ml;    /* MAC learning table. */
159     uint8_t default_ea[ETH_ADDR_LEN]; /* Default MAC. */
160     const struct ovsrec_bridge *cfg;
161
162     /* OpenFlow switch processing. */
163     struct ofproto *ofproto;    /* OpenFlow switch. */
164
165     /* Kernel datapath information. */
166     struct dpif *dpif;          /* Datapath. */
167     struct port_array ifaces;   /* Indexed by kernel datapath port number. */
168
169     /* Bridge ports. */
170     struct port **ports;
171     size_t n_ports, allocated_ports;
172     struct shash iface_by_name; /* "struct iface"s indexed by name. */
173     struct shash port_by_name;  /* "struct port"s indexed by name. */
174
175     /* Bonding. */
176     bool has_bonded_ports;
177
178     /* Flow tracking. */
179     bool flush;
180
181     /* Port mirroring. */
182     struct mirror *mirrors[MAX_MIRRORS];
183 };
184
185 /* List of all bridges. */
186 static struct list all_bridges = LIST_INITIALIZER(&all_bridges);
187
188 /* OVSDB IDL used to obtain configuration. */
189 static struct ovsdb_idl *idl;
190
191 /* Each time this timer expires, the bridge fetches statistics for every
192  * interface and pushes them into the database. */
193 #define IFACE_STATS_INTERVAL (5 * 1000) /* In milliseconds. */
194 static long long int iface_stats_timer = LLONG_MIN;
195
196 static struct bridge *bridge_create(const struct ovsrec_bridge *br_cfg);
197 static void bridge_destroy(struct bridge *);
198 static struct bridge *bridge_lookup(const char *name);
199 static unixctl_cb_func bridge_unixctl_dump_flows;
200 static unixctl_cb_func bridge_unixctl_reconnect;
201 static int bridge_run_one(struct bridge *);
202 static size_t bridge_get_controllers(const struct bridge *br,
203                                      struct ovsrec_controller ***controllersp);
204 static void bridge_reconfigure_one(struct bridge *);
205 static void bridge_reconfigure_remotes(struct bridge *,
206                                        const struct sockaddr_in *managers,
207                                        size_t n_managers);
208 static void bridge_get_all_ifaces(const struct bridge *, struct shash *ifaces);
209 static void bridge_fetch_dp_ifaces(struct bridge *);
210 static void bridge_flush(struct bridge *);
211 static void bridge_pick_local_hw_addr(struct bridge *,
212                                       uint8_t ea[ETH_ADDR_LEN],
213                                       struct iface **hw_addr_iface);
214 static uint64_t bridge_pick_datapath_id(struct bridge *,
215                                         const uint8_t bridge_ea[ETH_ADDR_LEN],
216                                         struct iface *hw_addr_iface);
217 static struct iface *bridge_get_local_iface(struct bridge *);
218 static uint64_t dpid_from_hash(const void *, size_t nbytes);
219
220 static unixctl_cb_func bridge_unixctl_fdb_show;
221
222 static void bond_init(void);
223 static void bond_run(struct bridge *);
224 static void bond_wait(struct bridge *);
225 static void bond_rebalance_port(struct port *);
226 static void bond_send_learning_packets(struct port *);
227 static void bond_enable_slave(struct iface *iface, bool enable);
228
229 static struct port *port_create(struct bridge *, const char *name);
230 static void port_reconfigure(struct port *, const struct ovsrec_port *);
231 static void port_del_ifaces(struct port *, const struct ovsrec_port *);
232 static void port_destroy(struct port *);
233 static struct port *port_lookup(const struct bridge *, const char *name);
234 static struct iface *port_lookup_iface(const struct port *, const char *name);
235 static struct port *port_from_dp_ifidx(const struct bridge *,
236                                        uint16_t dp_ifidx);
237 static void port_update_bond_compat(struct port *);
238 static void port_update_vlan_compat(struct port *);
239 static void port_update_bonding(struct port *);
240
241 static void mirror_create(struct bridge *, struct ovsrec_mirror *);
242 static void mirror_destroy(struct mirror *);
243 static void mirror_reconfigure(struct bridge *);
244 static void mirror_reconfigure_one(struct mirror *, struct ovsrec_mirror *);
245 static bool vlan_is_mirrored(const struct mirror *, int vlan);
246
247 static struct iface *iface_create(struct port *port, 
248                                   const struct ovsrec_interface *if_cfg);
249 static void iface_destroy(struct iface *);
250 static struct iface *iface_lookup(const struct bridge *, const char *name);
251 static struct iface *iface_from_dp_ifidx(const struct bridge *,
252                                          uint16_t dp_ifidx);
253 static bool iface_is_internal(const struct bridge *, const char *name);
254 static void iface_set_mac(struct iface *);
255 static void iface_update_qos(struct iface *, const struct ovsrec_qos *);
256
257 /* Hooks into ofproto processing. */
258 static struct ofhooks bridge_ofhooks;
259 \f
260 /* Public functions. */
261
262 /* Initializes the bridge module, configuring it to obtain its configuration
263  * from an OVSDB server accessed over 'remote', which should be a string in a
264  * form acceptable to ovsdb_idl_create(). */
265 void
266 bridge_init(const char *remote)
267 {
268     /* Create connection to database. */
269     idl = ovsdb_idl_create(remote, &ovsrec_idl_class);
270
271     /* Register unixctl commands. */
272     unixctl_command_register("fdb/show", bridge_unixctl_fdb_show, NULL);
273     unixctl_command_register("bridge/dump-flows", bridge_unixctl_dump_flows,
274                              NULL);
275     unixctl_command_register("bridge/reconnect", bridge_unixctl_reconnect,
276                              NULL);
277     bond_init();
278 }
279
280 /* Performs configuration that is only necessary once at ovs-vswitchd startup,
281  * but for which the ovs-vswitchd configuration 'cfg' is required. */
282 static void
283 bridge_configure_once(const struct ovsrec_open_vswitch *cfg)
284 {
285     static bool already_configured_once;
286     struct svec bridge_names;
287     struct svec dpif_names, dpif_types;
288     size_t i;
289
290     /* Only do this once per ovs-vswitchd run. */
291     if (already_configured_once) {
292         return;
293     }
294     already_configured_once = true;
295
296     iface_stats_timer = time_msec() + IFACE_STATS_INTERVAL;
297
298     /* Get all the configured bridges' names from 'cfg' into 'bridge_names'. */
299     svec_init(&bridge_names);
300     for (i = 0; i < cfg->n_bridges; i++) {
301         svec_add(&bridge_names, cfg->bridges[i]->name);
302     }
303     svec_sort(&bridge_names);
304
305     /* Iterate over all system dpifs and delete any of them that do not appear
306      * in 'cfg'. */
307     svec_init(&dpif_names);
308     svec_init(&dpif_types);
309     dp_enumerate_types(&dpif_types);
310     for (i = 0; i < dpif_types.n; i++) {
311         struct dpif *dpif;
312         int retval;
313         size_t j;
314
315         dp_enumerate_names(dpif_types.names[i], &dpif_names);
316
317         /* For each dpif... */
318         for (j = 0; j < dpif_names.n; j++) {
319             retval = dpif_open(dpif_names.names[j], dpif_types.names[i], &dpif);
320             if (!retval) {
321                 struct svec all_names;
322                 size_t k;
323
324                 /* ...check whether any of its names is in 'bridge_names'. */
325                 svec_init(&all_names);
326                 dpif_get_all_names(dpif, &all_names);
327                 for (k = 0; k < all_names.n; k++) {
328                     if (svec_contains(&bridge_names, all_names.names[k])) {
329                         goto found;
330                     }
331                 }
332
333                 /* No.  Delete the dpif. */
334                 dpif_delete(dpif);
335
336             found:
337                 svec_destroy(&all_names);
338                 dpif_close(dpif);
339             }
340         }
341     }
342     svec_destroy(&bridge_names);
343     svec_destroy(&dpif_names);
344     svec_destroy(&dpif_types);
345 }
346
347 #ifdef HAVE_OPENSSL
348 static void
349 bridge_configure_ssl(const struct ovsrec_ssl *ssl)
350 {
351     /* XXX SSL should be configurable on a per-bridge basis. */
352     if (ssl) {
353         stream_ssl_set_private_key_file(ssl->private_key);
354         stream_ssl_set_certificate_file(ssl->certificate);
355         stream_ssl_set_ca_cert_file(ssl->ca_cert, ssl->bootstrap_ca_cert);
356     }
357 }
358 #endif
359
360 /* Attempt to create the network device 'iface_name' through the netdev
361  * library. */
362 static int
363 set_up_iface(const struct ovsrec_interface *iface_cfg, struct iface *iface,
364              bool create)
365 {
366     struct shash options;
367     int error = 0;
368     size_t i;
369
370     shash_init(&options);
371     for (i = 0; i < iface_cfg->n_options; i++) {
372         shash_add(&options, iface_cfg->key_options[i],
373                   xstrdup(iface_cfg->value_options[i]));
374     }
375
376     if (create) {
377         struct netdev_options netdev_options;
378
379         memset(&netdev_options, 0, sizeof netdev_options);
380         netdev_options.name = iface_cfg->name;
381         if (!strcmp(iface_cfg->type, "internal")) {
382             /* An "internal" config type maps to a netdev "system" type. */
383             netdev_options.type = "system";
384         } else {
385             netdev_options.type = iface_cfg->type;
386         }
387         netdev_options.args = &options;
388         netdev_options.ethertype = NETDEV_ETH_TYPE_NONE;
389
390         error = netdev_open(&netdev_options, &iface->netdev);
391
392         if (iface->netdev) {
393             netdev_get_carrier(iface->netdev, &iface->enabled);
394         }
395     } else if (iface->netdev) {
396         const char *netdev_type = netdev_get_type(iface->netdev);
397         const char *iface_type = iface_cfg->type && strlen(iface_cfg->type)
398                                   ? iface_cfg->type : NULL;
399
400         /* An "internal" config type maps to a netdev "system" type. */
401         if (iface_type && !strcmp(iface_type, "internal")) {
402             iface_type = "system";
403         }
404
405         if (!iface_type || !strcmp(netdev_type, iface_type)) {
406             error = netdev_reconfigure(iface->netdev, &options);
407         } else {
408             VLOG_WARN("%s: attempting change device type from %s to %s",
409                       iface_cfg->name, netdev_type, iface_type);
410             error = EINVAL;
411         }
412     }
413     shash_destroy_free_data(&options);
414
415     return error;
416 }
417
418 static int
419 reconfigure_iface(const struct ovsrec_interface *iface_cfg, struct iface *iface)
420 {
421     return set_up_iface(iface_cfg, iface, false);
422 }
423
424 static bool
425 check_iface_netdev(struct bridge *br OVS_UNUSED, struct iface *iface,
426                    void *aux OVS_UNUSED)
427 {
428     if (!iface->netdev) {
429         int error = set_up_iface(iface->cfg, iface, true);
430         if (error) {
431             VLOG_WARN("could not open netdev on %s, dropping: %s", iface->name,
432                                                                strerror(error));
433             return false;
434         }
435     }
436
437     return true;
438 }
439
440 static bool
441 check_iface_dp_ifidx(struct bridge *br, struct iface *iface,
442                      void *aux OVS_UNUSED)
443 {
444     if (iface->dp_ifidx >= 0) {
445         VLOG_DBG("%s has interface %s on port %d",
446                  dpif_name(br->dpif),
447                  iface->name, iface->dp_ifidx);
448         return true;
449     } else {
450         VLOG_ERR("%s interface not in %s, dropping",
451                  iface->name, dpif_name(br->dpif));
452         return false;
453     }
454 }
455
456 static bool
457 set_iface_properties(struct bridge *br OVS_UNUSED, struct iface *iface,
458                      void *aux OVS_UNUSED)
459 {
460     /* Set policing attributes. */
461     netdev_set_policing(iface->netdev,
462                         iface->cfg->ingress_policing_rate,
463                         iface->cfg->ingress_policing_burst);
464
465     /* Set MAC address of internal interfaces other than the local
466      * interface. */
467     if (iface->dp_ifidx != ODPP_LOCAL
468         && iface_is_internal(br, iface->name)) {
469         iface_set_mac(iface);
470     }
471
472     return true;
473 }
474
475 /* Calls 'cb' for each interfaces in 'br', passing along the 'aux' argument.
476  * Deletes from 'br' all the interfaces for which 'cb' returns false, and then
477  * deletes from 'br' any ports that no longer have any interfaces. */
478 static void
479 iterate_and_prune_ifaces(struct bridge *br,
480                          bool (*cb)(struct bridge *, struct iface *,
481                                     void *aux),
482                          void *aux)
483 {
484     size_t i, j;
485
486     for (i = 0; i < br->n_ports; ) {
487         struct port *port = br->ports[i];
488         for (j = 0; j < port->n_ifaces; ) {
489             struct iface *iface = port->ifaces[j];
490             if (cb(br, iface, aux)) {
491                 j++;
492             } else {
493                 iface_destroy(iface);
494             }
495         }
496
497         if (port->n_ifaces) {
498             i++;
499         } else  {
500             VLOG_ERR("%s port has no interfaces, dropping", port->name);
501             port_destroy(port);
502         }
503     }
504 }
505
506 /* Looks at the list of managers in 'ovs_cfg' and extracts their remote IP
507  * addresses and ports into '*managersp' and '*n_managersp'.  The caller is
508  * responsible for freeing '*managersp' (with free()).
509  *
510  * You may be asking yourself "why does ovs-vswitchd care?", because
511  * ovsdb-server is responsible for connecting to the managers, and ovs-vswitchd
512  * should not be and in fact is not directly involved in that.  But
513  * ovs-vswitchd needs to make sure that ovsdb-server can reach the managers, so
514  * it has to tell in-band control where the managers are to enable that.
515  */
516 static void
517 collect_managers(const struct ovsrec_open_vswitch *ovs_cfg,
518                  struct sockaddr_in **managersp, size_t *n_managersp)
519 {
520     struct sockaddr_in *managers = NULL;
521     size_t n_managers = 0;
522
523     if (ovs_cfg->n_managers > 0) {
524         size_t i;
525
526         managers = xmalloc(ovs_cfg->n_managers * sizeof *managers);
527         for (i = 0; i < ovs_cfg->n_managers; i++) {
528             const char *name = ovs_cfg->managers[i];
529             struct sockaddr_in *sin = &managers[i];
530
531             if ((!strncmp(name, "tcp:", 4)
532                  && inet_parse_active(name + 4, JSONRPC_TCP_PORT, sin)) ||
533                 (!strncmp(name, "ssl:", 4)
534                  && inet_parse_active(name + 4, JSONRPC_SSL_PORT, sin))) {
535                 n_managers++;
536             }
537         }
538     }
539
540     *managersp = managers;
541     *n_managersp = n_managers;
542 }
543
544 static void
545 bridge_reconfigure(const struct ovsrec_open_vswitch *ovs_cfg)
546 {
547     struct shash old_br, new_br;
548     struct shash_node *node;
549     struct bridge *br, *next;
550     struct sockaddr_in *managers;
551     size_t n_managers;
552     size_t i;
553     int sflow_bridge_number;
554
555     COVERAGE_INC(bridge_reconfigure);
556
557     collect_managers(ovs_cfg, &managers, &n_managers);
558
559     /* Collect old and new bridges. */
560     shash_init(&old_br);
561     shash_init(&new_br);
562     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
563         shash_add(&old_br, br->name, br);
564     }
565     for (i = 0; i < ovs_cfg->n_bridges; i++) {
566         const struct ovsrec_bridge *br_cfg = ovs_cfg->bridges[i];
567         if (!shash_add_once(&new_br, br_cfg->name, br_cfg)) {
568             VLOG_WARN("more than one bridge named %s", br_cfg->name);
569         }
570     }
571
572     /* Get rid of deleted bridges and add new bridges. */
573     LIST_FOR_EACH_SAFE (br, next, struct bridge, node, &all_bridges) {
574         struct ovsrec_bridge *br_cfg = shash_find_data(&new_br, br->name);
575         if (br_cfg) {
576             br->cfg = br_cfg;
577         } else {
578             bridge_destroy(br);
579         }
580     }
581     SHASH_FOR_EACH (node, &new_br) {
582         const char *br_name = node->name;
583         const struct ovsrec_bridge *br_cfg = node->data;
584         br = shash_find_data(&old_br, br_name);
585         if (br) {
586             /* If the bridge datapath type has changed, we need to tear it
587              * down and recreate. */
588             if (strcmp(br->cfg->datapath_type, br_cfg->datapath_type)) {
589                 bridge_destroy(br);
590                 bridge_create(br_cfg);
591             }
592         } else {
593             bridge_create(br_cfg);
594         }
595     }
596     shash_destroy(&old_br);
597     shash_destroy(&new_br);
598
599 #ifdef HAVE_OPENSSL
600     /* Configure SSL. */
601     bridge_configure_ssl(ovs_cfg->ssl);
602 #endif
603
604     /* Reconfigure all bridges. */
605     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
606         bridge_reconfigure_one(br);
607     }
608
609     /* Add and delete ports on all datapaths.
610      *
611      * The kernel will reject any attempt to add a given port to a datapath if
612      * that port already belongs to a different datapath, so we must do all
613      * port deletions before any port additions. */
614     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
615         struct odp_port *dpif_ports;
616         size_t n_dpif_ports;
617         struct shash want_ifaces;
618
619         dpif_port_list(br->dpif, &dpif_ports, &n_dpif_ports);
620         bridge_get_all_ifaces(br, &want_ifaces);
621         for (i = 0; i < n_dpif_ports; i++) {
622             const struct odp_port *p = &dpif_ports[i];
623             if (!shash_find(&want_ifaces, p->devname)
624                 && strcmp(p->devname, br->name)) {
625                 int retval = dpif_port_del(br->dpif, p->port);
626                 if (retval) {
627                     VLOG_ERR("failed to remove %s interface from %s: %s",
628                              p->devname, dpif_name(br->dpif),
629                              strerror(retval));
630                 }
631             }
632         }
633         shash_destroy(&want_ifaces);
634         free(dpif_ports);
635     }
636     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
637         struct odp_port *dpif_ports;
638         size_t n_dpif_ports;
639         struct shash cur_ifaces, want_ifaces;
640         struct shash_node *node;
641
642         /* Get the set of interfaces currently in this datapath. */
643         dpif_port_list(br->dpif, &dpif_ports, &n_dpif_ports);
644         shash_init(&cur_ifaces);
645         for (i = 0; i < n_dpif_ports; i++) {
646             const char *name = dpif_ports[i].devname;
647             shash_add_once(&cur_ifaces, name, NULL);
648         }
649         free(dpif_ports);
650
651         /* Get the set of interfaces we want on this datapath. */
652         bridge_get_all_ifaces(br, &want_ifaces);
653
654         SHASH_FOR_EACH (node, &want_ifaces) {
655             const char *if_name = node->name;
656             struct iface *iface = node->data;
657
658             if (shash_find(&cur_ifaces, if_name)) {
659                 /* Already exists, just reconfigure it. */
660                 if (iface) {
661                     reconfigure_iface(iface->cfg, iface);
662                 }
663             } else {
664                 /* Need to add to datapath. */
665                 bool internal;
666                 int error;
667
668                 /* Add to datapath. */
669                 internal = iface_is_internal(br, if_name);
670                 error = dpif_port_add(br->dpif, if_name,
671                                       internal ? ODP_PORT_INTERNAL : 0, NULL);
672                 if (error == EFBIG) {
673                     VLOG_ERR("ran out of valid port numbers on %s",
674                              dpif_name(br->dpif));
675                     break;
676                 } else if (error) {
677                     VLOG_ERR("failed to add %s interface to %s: %s",
678                              if_name, dpif_name(br->dpif), strerror(error));
679                 }
680             }
681         }
682         shash_destroy(&cur_ifaces);
683         shash_destroy(&want_ifaces);
684     }
685     sflow_bridge_number = 0;
686     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
687         uint8_t ea[8];
688         uint64_t dpid;
689         struct iface *local_iface;
690         struct iface *hw_addr_iface;
691         char *dpid_string;
692
693         bridge_fetch_dp_ifaces(br);
694
695         iterate_and_prune_ifaces(br, check_iface_netdev, NULL);
696         iterate_and_prune_ifaces(br, check_iface_dp_ifidx, NULL);
697
698         /* Pick local port hardware address, datapath ID. */
699         bridge_pick_local_hw_addr(br, ea, &hw_addr_iface);
700         local_iface = bridge_get_local_iface(br);
701         if (local_iface) {
702             int error = netdev_set_etheraddr(local_iface->netdev, ea);
703             if (error) {
704                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
705                 VLOG_ERR_RL(&rl, "bridge %s: failed to set bridge "
706                             "Ethernet address: %s",
707                             br->name, strerror(error));
708             }
709         }
710
711         dpid = bridge_pick_datapath_id(br, ea, hw_addr_iface);
712         ofproto_set_datapath_id(br->ofproto, dpid);
713
714         dpid_string = xasprintf("%016"PRIx64, dpid);
715         ovsrec_bridge_set_datapath_id(br->cfg, dpid_string);
716         free(dpid_string);
717
718         /* Set NetFlow configuration on this bridge. */
719         if (br->cfg->netflow) {
720             struct ovsrec_netflow *nf_cfg = br->cfg->netflow;
721             struct netflow_options opts;
722
723             memset(&opts, 0, sizeof opts);
724
725             dpif_get_netflow_ids(br->dpif, &opts.engine_type, &opts.engine_id);
726             if (nf_cfg->engine_type) {
727                 opts.engine_type = *nf_cfg->engine_type;
728             }
729             if (nf_cfg->engine_id) {
730                 opts.engine_id = *nf_cfg->engine_id;
731             }
732
733             opts.active_timeout = nf_cfg->active_timeout;
734             if (!opts.active_timeout) {
735                 opts.active_timeout = -1;
736             } else if (opts.active_timeout < 0) {
737                 VLOG_WARN("bridge %s: active timeout interval set to negative "
738                           "value, using default instead (%d seconds)", br->name,
739                           NF_ACTIVE_TIMEOUT_DEFAULT);
740                 opts.active_timeout = -1;
741             }
742
743             opts.add_id_to_iface = nf_cfg->add_id_to_interface;
744             if (opts.add_id_to_iface) {
745                 if (opts.engine_id > 0x7f) {
746                     VLOG_WARN("bridge %s: netflow port mangling may conflict "
747                               "with another vswitch, choose an engine id less "
748                               "than 128", br->name);
749                 }
750                 if (br->n_ports > 508) {
751                     VLOG_WARN("bridge %s: netflow port mangling will conflict "
752                               "with another port when more than 508 ports are "
753                               "used", br->name);
754                 }
755             }
756
757             opts.collectors.n = nf_cfg->n_targets;
758             opts.collectors.names = nf_cfg->targets;
759             if (ofproto_set_netflow(br->ofproto, &opts)) {
760                 VLOG_ERR("bridge %s: problem setting netflow collectors", 
761                          br->name);
762             }
763         } else {
764             ofproto_set_netflow(br->ofproto, NULL);
765         }
766
767         /* Set sFlow configuration on this bridge. */
768         if (br->cfg->sflow) {
769             const struct ovsrec_sflow *sflow_cfg = br->cfg->sflow;
770             struct ovsrec_controller **controllers;
771             struct ofproto_sflow_options oso;
772             size_t n_controllers;
773             size_t i;
774
775             memset(&oso, 0, sizeof oso);
776
777             oso.targets.n = sflow_cfg->n_targets;
778             oso.targets.names = sflow_cfg->targets;
779
780             oso.sampling_rate = SFL_DEFAULT_SAMPLING_RATE;
781             if (sflow_cfg->sampling) {
782                 oso.sampling_rate = *sflow_cfg->sampling;
783             }
784
785             oso.polling_interval = SFL_DEFAULT_POLLING_INTERVAL;
786             if (sflow_cfg->polling) {
787                 oso.polling_interval = *sflow_cfg->polling;
788             }
789
790             oso.header_len = SFL_DEFAULT_HEADER_SIZE;
791             if (sflow_cfg->header) {
792                 oso.header_len = *sflow_cfg->header;
793             }
794
795             oso.sub_id = sflow_bridge_number++;
796             oso.agent_device = sflow_cfg->agent;
797
798             oso.control_ip = NULL;
799             n_controllers = bridge_get_controllers(br, &controllers);
800             for (i = 0; i < n_controllers; i++) {
801                 if (controllers[i]->local_ip) {
802                     oso.control_ip = controllers[i]->local_ip;
803                     break;
804                 }
805             }
806             ofproto_set_sflow(br->ofproto, &oso);
807
808             /* Do not destroy oso.targets because it is owned by sflow_cfg. */
809         } else {
810             ofproto_set_sflow(br->ofproto, NULL);
811         }
812
813         /* Update the controller and related settings.  It would be more
814          * straightforward to call this from bridge_reconfigure_one(), but we
815          * can't do it there for two reasons.  First, and most importantly, at
816          * that point we don't know the dp_ifidx of any interfaces that have
817          * been added to the bridge (because we haven't actually added them to
818          * the datapath).  Second, at that point we haven't set the datapath ID
819          * yet; when a controller is configured, resetting the datapath ID will
820          * immediately disconnect from the controller, so it's better to set
821          * the datapath ID before the controller. */
822         bridge_reconfigure_remotes(br, managers, n_managers);
823     }
824     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
825         for (i = 0; i < br->n_ports; i++) {
826             struct port *port = br->ports[i];
827             int j;
828
829             port_update_vlan_compat(port);
830             port_update_bonding(port);
831
832             for (j = 0; j < port->n_ifaces; j++) {
833                 iface_update_qos(port->ifaces[j], port->cfg->qos);
834             }
835         }
836     }
837     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
838         iterate_and_prune_ifaces(br, set_iface_properties, NULL);
839     }
840
841     free(managers);
842 }
843
844 static const char *
845 get_ovsrec_key_value(const struct ovsdb_idl_row *row,
846                      const struct ovsdb_idl_column *column,
847                      const char *key)
848 {
849     const struct ovsdb_datum *datum;
850     union ovsdb_atom atom;
851     unsigned int idx;
852
853     datum = ovsdb_idl_get(row, column, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
854     atom.string = (char *) key;
855     idx = ovsdb_datum_find_key(datum, &atom, OVSDB_TYPE_STRING);
856     return idx == UINT_MAX ? NULL : datum->values[idx].string;
857 }
858
859 static const char *
860 bridge_get_other_config(const struct ovsrec_bridge *br_cfg, const char *key)
861 {
862     return get_ovsrec_key_value(&br_cfg->header_,
863                                 &ovsrec_bridge_col_other_config, key);
864 }
865
866 static void
867 bridge_pick_local_hw_addr(struct bridge *br, uint8_t ea[ETH_ADDR_LEN],
868                           struct iface **hw_addr_iface)
869 {
870     const char *hwaddr;
871     size_t i, j;
872     int error;
873
874     *hw_addr_iface = NULL;
875
876     /* Did the user request a particular MAC? */
877     hwaddr = bridge_get_other_config(br->cfg, "hwaddr");
878     if (hwaddr && eth_addr_from_string(hwaddr, ea)) {
879         if (eth_addr_is_multicast(ea)) {
880             VLOG_ERR("bridge %s: cannot set MAC address to multicast "
881                      "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
882         } else if (eth_addr_is_zero(ea)) {
883             VLOG_ERR("bridge %s: cannot set MAC address to zero", br->name);
884         } else {
885             return;
886         }
887     }
888
889     /* Otherwise choose the minimum non-local MAC address among all of the
890      * interfaces. */
891     memset(ea, 0xff, sizeof ea);
892     for (i = 0; i < br->n_ports; i++) {
893         struct port *port = br->ports[i];
894         uint8_t iface_ea[ETH_ADDR_LEN];
895         struct iface *iface;
896
897         /* Mirror output ports don't participate. */
898         if (port->is_mirror_output_port) {
899             continue;
900         }
901
902         /* Choose the MAC address to represent the port. */
903         if (port->cfg->mac && eth_addr_from_string(port->cfg->mac, iface_ea)) {
904             /* Find the interface with this Ethernet address (if any) so that
905              * we can provide the correct devname to the caller. */
906             iface = NULL;
907             for (j = 0; j < port->n_ifaces; j++) {
908                 struct iface *candidate = port->ifaces[j];
909                 uint8_t candidate_ea[ETH_ADDR_LEN];
910                 if (!netdev_get_etheraddr(candidate->netdev, candidate_ea)
911                     && eth_addr_equals(iface_ea, candidate_ea)) {
912                     iface = candidate;
913                 }
914             }
915         } else {
916             /* Choose the interface whose MAC address will represent the port.
917              * The Linux kernel bonding code always chooses the MAC address of
918              * the first slave added to a bond, and the Fedora networking
919              * scripts always add slaves to a bond in alphabetical order, so
920              * for compatibility we choose the interface with the name that is
921              * first in alphabetical order. */
922             iface = port->ifaces[0];
923             for (j = 1; j < port->n_ifaces; j++) {
924                 struct iface *candidate = port->ifaces[j];
925                 if (strcmp(candidate->name, iface->name) < 0) {
926                     iface = candidate;
927                 }
928             }
929
930             /* The local port doesn't count (since we're trying to choose its
931              * MAC address anyway). */
932             if (iface->dp_ifidx == ODPP_LOCAL) {
933                 continue;
934             }
935
936             /* Grab MAC. */
937             error = netdev_get_etheraddr(iface->netdev, iface_ea);
938             if (error) {
939                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
940                 VLOG_ERR_RL(&rl, "failed to obtain Ethernet address of %s: %s",
941                             iface->name, strerror(error));
942                 continue;
943             }
944         }
945
946         /* Compare against our current choice. */
947         if (!eth_addr_is_multicast(iface_ea) &&
948             !eth_addr_is_local(iface_ea) &&
949             !eth_addr_is_reserved(iface_ea) &&
950             !eth_addr_is_zero(iface_ea) &&
951             memcmp(iface_ea, ea, ETH_ADDR_LEN) < 0)
952         {
953             memcpy(ea, iface_ea, ETH_ADDR_LEN);
954             *hw_addr_iface = iface;
955         }
956     }
957     if (eth_addr_is_multicast(ea)) {
958         memcpy(ea, br->default_ea, ETH_ADDR_LEN);
959         *hw_addr_iface = NULL;
960         VLOG_WARN("bridge %s: using default bridge Ethernet "
961                   "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
962     } else {
963         VLOG_DBG("bridge %s: using bridge Ethernet address "ETH_ADDR_FMT,
964                  br->name, ETH_ADDR_ARGS(ea));
965     }
966 }
967
968 /* Choose and returns the datapath ID for bridge 'br' given that the bridge
969  * Ethernet address is 'bridge_ea'.  If 'bridge_ea' is the Ethernet address of
970  * an interface on 'br', then that interface must be passed in as
971  * 'hw_addr_iface'; if 'bridge_ea' was derived some other way, then
972  * 'hw_addr_iface' must be passed in as a null pointer. */
973 static uint64_t
974 bridge_pick_datapath_id(struct bridge *br,
975                         const uint8_t bridge_ea[ETH_ADDR_LEN],
976                         struct iface *hw_addr_iface)
977 {
978     /*
979      * The procedure for choosing a bridge MAC address will, in the most
980      * ordinary case, also choose a unique MAC that we can use as a datapath
981      * ID.  In some special cases, though, multiple bridges will end up with
982      * the same MAC address.  This is OK for the bridges, but it will confuse
983      * the OpenFlow controller, because each datapath needs a unique datapath
984      * ID.
985      *
986      * Datapath IDs must be unique.  It is also very desirable that they be
987      * stable from one run to the next, so that policy set on a datapath
988      * "sticks".
989      */
990     const char *datapath_id;
991     uint64_t dpid;
992
993     datapath_id = bridge_get_other_config(br->cfg, "datapath-id");
994     if (datapath_id && dpid_from_string(datapath_id, &dpid)) {
995         return dpid;
996     }
997
998     if (hw_addr_iface) {
999         int vlan;
1000         if (!netdev_get_vlan_vid(hw_addr_iface->netdev, &vlan)) {
1001             /*
1002              * A bridge whose MAC address is taken from a VLAN network device
1003              * (that is, a network device created with vconfig(8) or similar
1004              * tool) will have the same MAC address as a bridge on the VLAN
1005              * device's physical network device.
1006              *
1007              * Handle this case by hashing the physical network device MAC
1008              * along with the VLAN identifier.
1009              */
1010             uint8_t buf[ETH_ADDR_LEN + 2];
1011             memcpy(buf, bridge_ea, ETH_ADDR_LEN);
1012             buf[ETH_ADDR_LEN] = vlan >> 8;
1013             buf[ETH_ADDR_LEN + 1] = vlan;
1014             return dpid_from_hash(buf, sizeof buf);
1015         } else {
1016             /*
1017              * Assume that this bridge's MAC address is unique, since it
1018              * doesn't fit any of the cases we handle specially.
1019              */
1020         }
1021     } else {
1022         /*
1023          * A purely internal bridge, that is, one that has no non-virtual
1024          * network devices on it at all, is more difficult because it has no
1025          * natural unique identifier at all.
1026          *
1027          * When the host is a XenServer, we handle this case by hashing the
1028          * host's UUID with the name of the bridge.  Names of bridges are
1029          * persistent across XenServer reboots, although they can be reused if
1030          * an internal network is destroyed and then a new one is later
1031          * created, so this is fairly effective.
1032          *
1033          * When the host is not a XenServer, we punt by using a random MAC
1034          * address on each run.
1035          */
1036         const char *host_uuid = xenserver_get_host_uuid();
1037         if (host_uuid) {
1038             char *combined = xasprintf("%s,%s", host_uuid, br->name);
1039             dpid = dpid_from_hash(combined, strlen(combined));
1040             free(combined);
1041             return dpid;
1042         }
1043     }
1044
1045     return eth_addr_to_uint64(bridge_ea);
1046 }
1047
1048 static uint64_t
1049 dpid_from_hash(const void *data, size_t n)
1050 {
1051     uint8_t hash[SHA1_DIGEST_SIZE];
1052
1053     BUILD_ASSERT_DECL(sizeof hash >= ETH_ADDR_LEN);
1054     sha1_bytes(data, n, hash);
1055     eth_addr_mark_random(hash);
1056     return eth_addr_to_uint64(hash);
1057 }
1058
1059 static void
1060 iface_refresh_stats(struct iface *iface)
1061 {
1062     struct iface_stat {
1063         char *name;
1064         int offset;
1065     };
1066     static const struct iface_stat iface_stats[] = {
1067         { "rx_packets", offsetof(struct netdev_stats, rx_packets) },
1068         { "tx_packets", offsetof(struct netdev_stats, tx_packets) },
1069         { "rx_bytes", offsetof(struct netdev_stats, rx_bytes) },
1070         { "tx_bytes", offsetof(struct netdev_stats, tx_bytes) },
1071         { "rx_dropped", offsetof(struct netdev_stats, rx_dropped) },
1072         { "tx_dropped", offsetof(struct netdev_stats, tx_dropped) },
1073         { "rx_errors", offsetof(struct netdev_stats, rx_errors) },
1074         { "tx_errors", offsetof(struct netdev_stats, tx_errors) },
1075         { "rx_frame_err", offsetof(struct netdev_stats, rx_frame_errors) },
1076         { "rx_over_err", offsetof(struct netdev_stats, rx_over_errors) },
1077         { "rx_crc_err", offsetof(struct netdev_stats, rx_crc_errors) },
1078         { "collisions", offsetof(struct netdev_stats, collisions) },
1079     };
1080     enum { N_STATS = ARRAY_SIZE(iface_stats) };
1081     const struct iface_stat *s;
1082
1083     char *keys[N_STATS];
1084     int64_t values[N_STATS];
1085     int n;
1086
1087     struct netdev_stats stats;
1088
1089     /* Intentionally ignore return value, since errors will set 'stats' to
1090      * all-1s, and we will deal with that correctly below. */
1091     netdev_get_stats(iface->netdev, &stats);
1092
1093     n = 0;
1094     for (s = iface_stats; s < &iface_stats[N_STATS]; s++) {
1095         uint64_t value = *(uint64_t *) (((char *) &stats) + s->offset);
1096         if (value != UINT64_MAX) {
1097             keys[n] = s->name;
1098             values[n] = value;
1099             n++;
1100         }
1101     }
1102
1103     ovsrec_interface_set_statistics(iface->cfg, keys, values, n);
1104 }
1105
1106 void
1107 bridge_run(void)
1108 {
1109     bool datapath_destroyed;
1110     struct bridge *br;
1111
1112     /* Let each bridge do the work that it needs to do. */
1113     datapath_destroyed = false;
1114     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
1115         int error = bridge_run_one(br);
1116         if (error) {
1117             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1118             VLOG_ERR_RL(&rl, "bridge %s: datapath was destroyed externally, "
1119                         "forcing reconfiguration", br->name);
1120             datapath_destroyed = true;
1121         }
1122     }
1123
1124     /* (Re)configure if necessary. */
1125     if (ovsdb_idl_run(idl) || datapath_destroyed) {
1126         const struct ovsrec_open_vswitch *cfg = ovsrec_open_vswitch_first(idl);
1127         if (cfg) {
1128             struct ovsdb_idl_txn *txn = ovsdb_idl_txn_create(idl);
1129
1130             bridge_configure_once(cfg);
1131             bridge_reconfigure(cfg);
1132
1133             ovsrec_open_vswitch_set_cur_cfg(cfg, cfg->next_cfg);
1134             ovsdb_idl_txn_commit(txn);
1135             ovsdb_idl_txn_destroy(txn); /* XXX */
1136         } else {
1137             /* We still need to reconfigure to avoid dangling pointers to
1138              * now-destroyed ovsrec structures inside bridge data. */
1139             static const struct ovsrec_open_vswitch null_cfg;
1140
1141             bridge_reconfigure(&null_cfg);
1142         }
1143     }
1144
1145     /* Refresh interface stats if necessary. */
1146     if (time_msec() >= iface_stats_timer) {
1147         struct ovsdb_idl_txn *txn;
1148
1149         txn = ovsdb_idl_txn_create(idl);
1150         LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
1151             size_t i;
1152
1153             for (i = 0; i < br->n_ports; i++) {
1154                 struct port *port = br->ports[i];
1155                 size_t j;
1156
1157                 for (j = 0; j < port->n_ifaces; j++) {
1158                     struct iface *iface = port->ifaces[j];
1159                     iface_refresh_stats(iface);
1160                 }
1161             }
1162         }
1163         ovsdb_idl_txn_commit(txn);
1164         ovsdb_idl_txn_destroy(txn); /* XXX */
1165
1166         iface_stats_timer = time_msec() + IFACE_STATS_INTERVAL;
1167     }
1168 }
1169
1170 void
1171 bridge_wait(void)
1172 {
1173     struct bridge *br;
1174
1175     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
1176         ofproto_wait(br->ofproto);
1177         if (ofproto_has_controller(br->ofproto)) {
1178             continue;
1179         }
1180
1181         mac_learning_wait(br->ml);
1182         bond_wait(br);
1183     }
1184     ovsdb_idl_wait(idl);
1185     poll_timer_wait_until(iface_stats_timer);
1186 }
1187
1188 /* Forces 'br' to revalidate all of its flows.  This is appropriate when 'br''s
1189  * configuration changes.  */
1190 static void
1191 bridge_flush(struct bridge *br)
1192 {
1193     COVERAGE_INC(bridge_flush);
1194     br->flush = true;
1195     mac_learning_flush(br->ml);
1196 }
1197
1198 /* Returns the 'br' interface for the ODPP_LOCAL port, or null if 'br' has no
1199  * such interface. */
1200 static struct iface *
1201 bridge_get_local_iface(struct bridge *br)
1202 {
1203     size_t i, j;
1204
1205     for (i = 0; i < br->n_ports; i++) {
1206         struct port *port = br->ports[i];
1207         for (j = 0; j < port->n_ifaces; j++) {
1208             struct iface *iface = port->ifaces[j];
1209             if (iface->dp_ifidx == ODPP_LOCAL) {
1210                 return iface;
1211             }
1212         }
1213     }
1214
1215     return NULL;
1216 }
1217 \f
1218 /* Bridge unixctl user interface functions. */
1219 static void
1220 bridge_unixctl_fdb_show(struct unixctl_conn *conn,
1221                         const char *args, void *aux OVS_UNUSED)
1222 {
1223     struct ds ds = DS_EMPTY_INITIALIZER;
1224     const struct bridge *br;
1225     const struct mac_entry *e;
1226
1227     br = bridge_lookup(args);
1228     if (!br) {
1229         unixctl_command_reply(conn, 501, "no such bridge");
1230         return;
1231     }
1232
1233     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
1234     LIST_FOR_EACH (e, struct mac_entry, lru_node, &br->ml->lrus) {
1235         if (e->port < 0 || e->port >= br->n_ports) {
1236             continue;
1237         }
1238         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
1239                       br->ports[e->port]->ifaces[0]->dp_ifidx,
1240                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
1241     }
1242     unixctl_command_reply(conn, 200, ds_cstr(&ds));
1243     ds_destroy(&ds);
1244 }
1245 \f
1246 /* Bridge reconfiguration functions. */
1247 static struct bridge *
1248 bridge_create(const struct ovsrec_bridge *br_cfg)
1249 {
1250     struct bridge *br;
1251     int error;
1252
1253     assert(!bridge_lookup(br_cfg->name));
1254     br = xzalloc(sizeof *br);
1255
1256     error = dpif_create_and_open(br_cfg->name, br_cfg->datapath_type,
1257                                  &br->dpif);
1258     if (error) {
1259         free(br);
1260         return NULL;
1261     }
1262     dpif_flow_flush(br->dpif);
1263
1264     error = ofproto_create(br_cfg->name, br_cfg->datapath_type, &bridge_ofhooks,
1265                            br, &br->ofproto);
1266     if (error) {
1267         VLOG_ERR("failed to create switch %s: %s", br_cfg->name,
1268                  strerror(error));
1269         dpif_delete(br->dpif);
1270         dpif_close(br->dpif);
1271         free(br);
1272         return NULL;
1273     }
1274
1275     br->name = xstrdup(br_cfg->name);
1276     br->cfg = br_cfg;
1277     br->ml = mac_learning_create();
1278     eth_addr_nicira_random(br->default_ea);
1279
1280     port_array_init(&br->ifaces);
1281
1282     shash_init(&br->port_by_name);
1283     shash_init(&br->iface_by_name);
1284
1285     br->flush = false;
1286
1287     list_push_back(&all_bridges, &br->node);
1288
1289     VLOG_INFO("created bridge %s on %s", br->name, dpif_name(br->dpif));
1290
1291     return br;
1292 }
1293
1294 static void
1295 bridge_destroy(struct bridge *br)
1296 {
1297     if (br) {
1298         int error;
1299
1300         while (br->n_ports > 0) {
1301             port_destroy(br->ports[br->n_ports - 1]);
1302         }
1303         list_remove(&br->node);
1304         error = dpif_delete(br->dpif);
1305         if (error && error != ENOENT) {
1306             VLOG_ERR("failed to delete %s: %s",
1307                      dpif_name(br->dpif), strerror(error));
1308         }
1309         dpif_close(br->dpif);
1310         ofproto_destroy(br->ofproto);
1311         mac_learning_destroy(br->ml);
1312         port_array_destroy(&br->ifaces);
1313         shash_destroy(&br->port_by_name);
1314         shash_destroy(&br->iface_by_name);
1315         free(br->ports);
1316         free(br->name);
1317         free(br);
1318     }
1319 }
1320
1321 static struct bridge *
1322 bridge_lookup(const char *name)
1323 {
1324     struct bridge *br;
1325
1326     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
1327         if (!strcmp(br->name, name)) {
1328             return br;
1329         }
1330     }
1331     return NULL;
1332 }
1333
1334 /* Handle requests for a listing of all flows known by the OpenFlow
1335  * stack, including those normally hidden. */
1336 static void
1337 bridge_unixctl_dump_flows(struct unixctl_conn *conn,
1338                           const char *args, void *aux OVS_UNUSED)
1339 {
1340     struct bridge *br;
1341     struct ds results;
1342     
1343     br = bridge_lookup(args);
1344     if (!br) {
1345         unixctl_command_reply(conn, 501, "Unknown bridge");
1346         return;
1347     }
1348
1349     ds_init(&results);
1350     ofproto_get_all_flows(br->ofproto, &results);
1351
1352     unixctl_command_reply(conn, 200, ds_cstr(&results));
1353     ds_destroy(&results);
1354 }
1355
1356 /* "bridge/reconnect [BRIDGE]": makes BRIDGE drop all of its controller
1357  * connections and reconnect.  If BRIDGE is not specified, then all bridges
1358  * drop their controller connections and reconnect. */
1359 static void
1360 bridge_unixctl_reconnect(struct unixctl_conn *conn,
1361                          const char *args, void *aux OVS_UNUSED)
1362 {
1363     struct bridge *br;
1364     if (args[0] != '\0') {
1365         br = bridge_lookup(args);
1366         if (!br) {
1367             unixctl_command_reply(conn, 501, "Unknown bridge");
1368             return;
1369         }
1370         ofproto_reconnect_controllers(br->ofproto);
1371     } else {
1372         LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
1373             ofproto_reconnect_controllers(br->ofproto);
1374         }
1375     }
1376     unixctl_command_reply(conn, 200, NULL);
1377 }
1378
1379 static int
1380 bridge_run_one(struct bridge *br)
1381 {
1382     int error;
1383
1384     error = ofproto_run1(br->ofproto);
1385     if (error) {
1386         return error;
1387     }
1388
1389     mac_learning_run(br->ml, ofproto_get_revalidate_set(br->ofproto));
1390     bond_run(br);
1391
1392     error = ofproto_run2(br->ofproto, br->flush);
1393     br->flush = false;
1394
1395     return error;
1396 }
1397
1398 static size_t
1399 bridge_get_controllers(const struct bridge *br,
1400                        struct ovsrec_controller ***controllersp)
1401 {
1402     struct ovsrec_controller **controllers;
1403     size_t n_controllers;
1404
1405     controllers = br->cfg->controller;
1406     n_controllers = br->cfg->n_controller;
1407
1408     if (n_controllers == 1 && !strcmp(controllers[0]->target, "none")) {
1409         controllers = NULL;
1410         n_controllers = 0;
1411     }
1412
1413     if (controllersp) {
1414         *controllersp = controllers;
1415     }
1416     return n_controllers;
1417 }
1418
1419 static void
1420 bridge_reconfigure_one(struct bridge *br)
1421 {
1422     struct shash old_ports, new_ports;
1423     struct svec listeners, old_listeners;
1424     struct svec snoops, old_snoops;
1425     struct shash_node *node;
1426     size_t i;
1427
1428     /* Collect old ports. */
1429     shash_init(&old_ports);
1430     for (i = 0; i < br->n_ports; i++) {
1431         shash_add(&old_ports, br->ports[i]->name, br->ports[i]);
1432     }
1433
1434     /* Collect new ports. */
1435     shash_init(&new_ports);
1436     for (i = 0; i < br->cfg->n_ports; i++) {
1437         const char *name = br->cfg->ports[i]->name;
1438         if (!shash_add_once(&new_ports, name, br->cfg->ports[i])) {
1439             VLOG_WARN("bridge %s: %s specified twice as bridge port",
1440                       br->name, name);
1441         }
1442     }
1443
1444     /* If we have a controller, then we need a local port.  Complain if the
1445      * user didn't specify one.
1446      *
1447      * XXX perhaps we should synthesize a port ourselves in this case. */
1448     if (bridge_get_controllers(br, NULL)) {
1449         char local_name[IF_NAMESIZE];
1450         int error;
1451
1452         error = dpif_port_get_name(br->dpif, ODPP_LOCAL,
1453                                    local_name, sizeof local_name);
1454         if (!error && !shash_find(&new_ports, local_name)) {
1455             VLOG_WARN("bridge %s: controller specified but no local port "
1456                       "(port named %s) defined",
1457                       br->name, local_name);
1458         }
1459     }
1460
1461     /* Get rid of deleted ports.
1462      * Get rid of deleted interfaces on ports that still exist. */
1463     SHASH_FOR_EACH (node, &old_ports) {
1464         struct port *port = node->data;
1465         const struct ovsrec_port *port_cfg;
1466
1467         port_cfg = shash_find_data(&new_ports, node->name);
1468         if (!port_cfg) {
1469             port_destroy(port);
1470         } else {
1471             port_del_ifaces(port, port_cfg);
1472         }
1473     }
1474
1475     /* Create new ports.
1476      * Add new interfaces to existing ports.
1477      * Reconfigure existing ports. */
1478     SHASH_FOR_EACH (node, &new_ports) {
1479         struct port *port = shash_find_data(&old_ports, node->name);
1480         if (!port) {
1481             port = port_create(br, node->name);
1482         }
1483
1484         port_reconfigure(port, node->data);
1485         if (!port->n_ifaces) {
1486             VLOG_WARN("bridge %s: port %s has no interfaces, dropping",
1487                       br->name, port->name);
1488             port_destroy(port);
1489         }
1490     }
1491     shash_destroy(&old_ports);
1492     shash_destroy(&new_ports);
1493
1494     /* Delete all flows if we're switching from connected to standalone or vice
1495      * versa.  (XXX Should we delete all flows if we are switching from one
1496      * controller to another?) */
1497
1498     /* Configure OpenFlow management listener. */
1499     svec_init(&listeners);
1500     svec_add_nocopy(&listeners, xasprintf("punix:%s/%s.mgmt",
1501                                           ovs_rundir, br->name));
1502     svec_init(&old_listeners);
1503     ofproto_get_listeners(br->ofproto, &old_listeners);
1504     if (!svec_equal(&listeners, &old_listeners)) {
1505         ofproto_set_listeners(br->ofproto, &listeners);
1506     }
1507     svec_destroy(&listeners);
1508     svec_destroy(&old_listeners);
1509
1510     /* Configure OpenFlow controller connection snooping. */
1511     svec_init(&snoops);
1512     svec_add_nocopy(&snoops, xasprintf("punix:%s/%s.snoop",
1513                                        ovs_rundir, br->name));
1514     svec_init(&old_snoops);
1515     ofproto_get_snoops(br->ofproto, &old_snoops);
1516     if (!svec_equal(&snoops, &old_snoops)) {
1517         ofproto_set_snoops(br->ofproto, &snoops);
1518     }
1519     svec_destroy(&snoops);
1520     svec_destroy(&old_snoops);
1521
1522     mirror_reconfigure(br);
1523 }
1524
1525 static void
1526 bridge_reconfigure_remotes(struct bridge *br,
1527                            const struct sockaddr_in *managers,
1528                            size_t n_managers)
1529 {
1530     struct ovsrec_controller **controllers;
1531     size_t n_controllers;
1532
1533     ofproto_set_extra_in_band_remotes(br->ofproto, managers, n_managers);
1534
1535     n_controllers = bridge_get_controllers(br, &controllers);
1536     if (ofproto_has_controller(br->ofproto) != (n_controllers != 0)) {
1537         ofproto_flush_flows(br->ofproto);
1538     }
1539
1540     if (!n_controllers) {
1541         union ofp_action action;
1542         flow_t flow;
1543
1544         /* Clear out controllers. */
1545         ofproto_set_controllers(br->ofproto, NULL, 0);
1546
1547         /* Set up a flow that matches every packet and directs them to
1548          * OFPP_NORMAL (which goes to us). */
1549         memset(&action, 0, sizeof action);
1550         action.type = htons(OFPAT_OUTPUT);
1551         action.output.len = htons(sizeof action);
1552         action.output.port = htons(OFPP_NORMAL);
1553         memset(&flow, 0, sizeof flow);
1554         ofproto_add_flow(br->ofproto, &flow, OVSFW_ALL, 0, &action, 1, 0);
1555     } else {
1556         struct ofproto_controller *ocs;
1557         size_t i;
1558
1559         ocs = xmalloc(n_controllers * sizeof *ocs);
1560         for (i = 0; i < n_controllers; i++) {
1561             struct ovsrec_controller *c = controllers[i];
1562             struct ofproto_controller *oc = &ocs[i];
1563
1564             if (strcmp(c->target, "discover")) {
1565                 struct iface *local_iface;
1566                 struct in_addr ip;
1567
1568                 local_iface = bridge_get_local_iface(br);
1569                 if (local_iface && c->local_ip
1570                     && inet_aton(c->local_ip, &ip)) {
1571                     struct netdev *netdev = local_iface->netdev;
1572                     struct in_addr mask, gateway;
1573
1574                     if (!c->local_netmask
1575                         || !inet_aton(c->local_netmask, &mask)) {
1576                         mask.s_addr = 0;
1577                     }
1578                     if (!c->local_gateway
1579                         || !inet_aton(c->local_gateway, &gateway)) {
1580                         gateway.s_addr = 0;
1581                     }
1582
1583                     netdev_turn_flags_on(netdev, NETDEV_UP, true);
1584                     if (!mask.s_addr) {
1585                         mask.s_addr = guess_netmask(ip.s_addr);
1586                     }
1587                     if (!netdev_set_in4(netdev, ip, mask)) {
1588                         VLOG_INFO("bridge %s: configured IP address "IP_FMT", "
1589                                   "netmask "IP_FMT,
1590                                   br->name, IP_ARGS(&ip.s_addr),
1591                                   IP_ARGS(&mask.s_addr));
1592                     }
1593
1594                     if (gateway.s_addr) {
1595                         if (!netdev_add_router(netdev, gateway)) {
1596                             VLOG_INFO("bridge %s: configured gateway "IP_FMT,
1597                                       br->name, IP_ARGS(&gateway.s_addr));
1598                         }
1599                     }
1600                 }
1601             }
1602
1603             oc->target = c->target;
1604             oc->max_backoff = c->max_backoff ? *c->max_backoff / 1000 : 8;
1605             oc->probe_interval = (c->inactivity_probe
1606                                  ? *c->inactivity_probe / 1000 : 5);
1607             oc->fail = (!c->fail_mode
1608                        || !strcmp(c->fail_mode, "standalone")
1609                        || !strcmp(c->fail_mode, "open")
1610                        ? OFPROTO_FAIL_STANDALONE
1611                        : OFPROTO_FAIL_SECURE);
1612             oc->band = (!c->connection_mode
1613                        || !strcmp(c->connection_mode, "in-band")
1614                        ? OFPROTO_IN_BAND
1615                        : OFPROTO_OUT_OF_BAND);
1616             oc->accept_re = c->discover_accept_regex;
1617             oc->update_resolv_conf = c->discover_update_resolv_conf;
1618             oc->rate_limit = (c->controller_rate_limit
1619                              ? *c->controller_rate_limit : 0);
1620             oc->burst_limit = (c->controller_burst_limit
1621                               ? *c->controller_burst_limit : 0);
1622         }
1623         ofproto_set_controllers(br->ofproto, ocs, n_controllers);
1624         free(ocs);
1625     }
1626 }
1627
1628 static void
1629 bridge_get_all_ifaces(const struct bridge *br, struct shash *ifaces)
1630 {
1631     size_t i, j;
1632
1633     shash_init(ifaces);
1634     for (i = 0; i < br->n_ports; i++) {
1635         struct port *port = br->ports[i];
1636         for (j = 0; j < port->n_ifaces; j++) {
1637             struct iface *iface = port->ifaces[j];
1638             shash_add_once(ifaces, iface->name, iface);
1639         }
1640         if (port->n_ifaces > 1 && port->cfg->bond_fake_iface) {
1641             shash_add_once(ifaces, port->name, NULL);
1642         }
1643     }
1644 }
1645
1646 /* For robustness, in case the administrator moves around datapath ports behind
1647  * our back, we re-check all the datapath port numbers here.
1648  *
1649  * This function will set the 'dp_ifidx' members of interfaces that have
1650  * disappeared to -1, so only call this function from a context where those
1651  * 'struct iface's will be removed from the bridge.  Otherwise, the -1
1652  * 'dp_ifidx'es will cause trouble later when we try to send them to the
1653  * datapath, which doesn't support UINT16_MAX+1 ports. */
1654 static void
1655 bridge_fetch_dp_ifaces(struct bridge *br)
1656 {
1657     struct odp_port *dpif_ports;
1658     size_t n_dpif_ports;
1659     size_t i, j;
1660
1661     /* Reset all interface numbers. */
1662     for (i = 0; i < br->n_ports; i++) {
1663         struct port *port = br->ports[i];
1664         for (j = 0; j < port->n_ifaces; j++) {
1665             struct iface *iface = port->ifaces[j];
1666             iface->dp_ifidx = -1;
1667         }
1668     }
1669     port_array_clear(&br->ifaces);
1670
1671     dpif_port_list(br->dpif, &dpif_ports, &n_dpif_ports);
1672     for (i = 0; i < n_dpif_ports; i++) {
1673         struct odp_port *p = &dpif_ports[i];
1674         struct iface *iface = iface_lookup(br, p->devname);
1675         if (iface) {
1676             if (iface->dp_ifidx >= 0) {
1677                 VLOG_WARN("%s reported interface %s twice",
1678                           dpif_name(br->dpif), p->devname);
1679             } else if (iface_from_dp_ifidx(br, p->port)) {
1680                 VLOG_WARN("%s reported interface %"PRIu16" twice",
1681                           dpif_name(br->dpif), p->port);
1682             } else {
1683                 port_array_set(&br->ifaces, p->port, iface);
1684                 iface->dp_ifidx = p->port;
1685             }
1686
1687             if (iface->cfg) {
1688                 int64_t ofport = (iface->dp_ifidx >= 0
1689                                   ? odp_port_to_ofp_port(iface->dp_ifidx)
1690                                   : -1);
1691                 ovsrec_interface_set_ofport(iface->cfg, &ofport, 1);
1692             }
1693         }
1694     }
1695     free(dpif_ports);
1696 }
1697 \f
1698 /* Bridge packet processing functions. */
1699
1700 static int
1701 bond_hash(const uint8_t mac[ETH_ADDR_LEN])
1702 {
1703     return hash_bytes(mac, ETH_ADDR_LEN, 0) & BOND_MASK;
1704 }
1705
1706 static struct bond_entry *
1707 lookup_bond_entry(const struct port *port, const uint8_t mac[ETH_ADDR_LEN])
1708 {
1709     return &port->bond_hash[bond_hash(mac)];
1710 }
1711
1712 static int
1713 bond_choose_iface(const struct port *port)
1714 {
1715     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1716     size_t i, best_down_slave = -1;
1717     long long next_delay_expiration = LLONG_MAX;
1718
1719     for (i = 0; i < port->n_ifaces; i++) {
1720         struct iface *iface = port->ifaces[i];
1721
1722         if (iface->enabled) {
1723             return i;
1724         } else if (iface->delay_expires < next_delay_expiration) {
1725             best_down_slave = i;
1726             next_delay_expiration = iface->delay_expires;
1727         }
1728     }
1729
1730     if (best_down_slave != -1) {
1731         struct iface *iface = port->ifaces[best_down_slave];
1732
1733         VLOG_INFO_RL(&rl, "interface %s: skipping remaining %lli ms updelay "
1734                      "since no other interface is up", iface->name,
1735                      iface->delay_expires - time_msec());
1736         bond_enable_slave(iface, true);
1737     }
1738
1739     return best_down_slave;
1740 }
1741
1742 static bool
1743 choose_output_iface(const struct port *port, const uint8_t *dl_src,
1744                     uint16_t *dp_ifidx, tag_type *tags)
1745 {
1746     struct iface *iface;
1747
1748     assert(port->n_ifaces);
1749     if (port->n_ifaces == 1) {
1750         iface = port->ifaces[0];
1751     } else {
1752         struct bond_entry *e = lookup_bond_entry(port, dl_src);
1753         if (e->iface_idx < 0 || e->iface_idx >= port->n_ifaces
1754             || !port->ifaces[e->iface_idx]->enabled) {
1755             /* XXX select interface properly.  The current interface selection
1756              * is only good for testing the rebalancing code. */
1757             e->iface_idx = bond_choose_iface(port);
1758             if (e->iface_idx < 0) {
1759                 *tags |= port->no_ifaces_tag;
1760                 return false;
1761             }
1762             e->iface_tag = tag_create_random();
1763             ((struct port *) port)->bond_compat_is_stale = true;
1764         }
1765         *tags |= e->iface_tag;
1766         iface = port->ifaces[e->iface_idx];
1767     }
1768     *dp_ifidx = iface->dp_ifidx;
1769     *tags |= iface->tag;        /* Currently only used for bonding. */
1770     return true;
1771 }
1772
1773 static void
1774 bond_link_status_update(struct iface *iface, bool carrier)
1775 {
1776     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1777     struct port *port = iface->port;
1778
1779     if ((carrier == iface->enabled) == (iface->delay_expires == LLONG_MAX)) {
1780         /* Nothing to do. */
1781         return;
1782     }
1783     VLOG_INFO_RL(&rl, "interface %s: carrier %s",
1784                  iface->name, carrier ? "detected" : "dropped");
1785     if (carrier == iface->enabled) {
1786         iface->delay_expires = LLONG_MAX;
1787         VLOG_INFO_RL(&rl, "interface %s: will not be %s",
1788                      iface->name, carrier ? "disabled" : "enabled");
1789     } else if (carrier && port->active_iface < 0) {
1790         bond_enable_slave(iface, true);
1791         if (port->updelay) {
1792             VLOG_INFO_RL(&rl, "interface %s: skipping %d ms updelay since no "
1793                          "other interface is up", iface->name, port->updelay);
1794         }
1795     } else {
1796         int delay = carrier ? port->updelay : port->downdelay;
1797         iface->delay_expires = time_msec() + delay;
1798         if (delay) {
1799             VLOG_INFO_RL(&rl,
1800                          "interface %s: will be %s if it stays %s for %d ms",
1801                          iface->name,
1802                          carrier ? "enabled" : "disabled",
1803                          carrier ? "up" : "down",
1804                          delay);
1805         }
1806     }
1807 }
1808
1809 static void
1810 bond_choose_active_iface(struct port *port)
1811 {
1812     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
1813
1814     port->active_iface = bond_choose_iface(port);
1815     port->active_iface_tag = tag_create_random();
1816     if (port->active_iface >= 0) {
1817         VLOG_INFO_RL(&rl, "port %s: active interface is now %s",
1818                      port->name, port->ifaces[port->active_iface]->name);
1819     } else {
1820         VLOG_WARN_RL(&rl, "port %s: all ports disabled, no active interface",
1821                      port->name);
1822     }
1823 }
1824
1825 static void
1826 bond_enable_slave(struct iface *iface, bool enable)
1827 {
1828     struct port *port = iface->port;
1829     struct bridge *br = port->bridge;
1830
1831     /* This acts as a recursion check.  If the act of disabling a slave
1832      * causes a different slave to be enabled, the flag will allow us to
1833      * skip redundant work when we reenter this function.  It must be
1834      * cleared on exit to keep things safe with multiple bonds. */
1835     static bool moving_active_iface = false;
1836
1837     iface->delay_expires = LLONG_MAX;
1838     if (enable == iface->enabled) {
1839         return;
1840     }
1841
1842     iface->enabled = enable;
1843     if (!iface->enabled) {
1844         VLOG_WARN("interface %s: disabled", iface->name);
1845         ofproto_revalidate(br->ofproto, iface->tag);
1846         if (iface->port_ifidx == port->active_iface) {
1847             ofproto_revalidate(br->ofproto,
1848                                port->active_iface_tag);
1849
1850             /* Disabling a slave can lead to another slave being immediately
1851              * enabled if there will be no active slaves but one is waiting
1852              * on an updelay.  In this case we do not need to run most of the
1853              * code for the newly enabled slave since there was no period
1854              * without an active slave and it is redundant with the disabling
1855              * path. */
1856             moving_active_iface = true;
1857             bond_choose_active_iface(port);
1858         }
1859         bond_send_learning_packets(port);
1860     } else {
1861         VLOG_WARN("interface %s: enabled", iface->name);
1862         if (port->active_iface < 0 && !moving_active_iface) {
1863             ofproto_revalidate(br->ofproto, port->no_ifaces_tag);
1864             bond_choose_active_iface(port);
1865             bond_send_learning_packets(port);
1866         }
1867         iface->tag = tag_create_random();
1868     }
1869
1870     moving_active_iface = false;
1871     port->bond_compat_is_stale = true;
1872 }
1873
1874 /* Attempts to make the sum of the bond slaves' statistics appear on the fake
1875  * bond interface. */
1876 static void
1877 bond_update_fake_iface_stats(struct port *port)
1878 {
1879     struct netdev_stats bond_stats;
1880     struct netdev *bond_dev;
1881     size_t i;
1882
1883     memset(&bond_stats, 0, sizeof bond_stats);
1884
1885     for (i = 0; i < port->n_ifaces; i++) {
1886         struct netdev_stats slave_stats;
1887
1888         if (!netdev_get_stats(port->ifaces[i]->netdev, &slave_stats)) {
1889             /* XXX: We swap the stats here because they are swapped back when
1890              * reported by the internal device.  The reason for this is
1891              * internal devices normally represent packets going into the system
1892              * but when used as fake bond device they represent packets leaving
1893              * the system.  We really should do this in the internal device
1894              * itself because changing it here reverses the counts from the
1895              * perspective of the switch.  However, the internal device doesn't
1896              * know what type of device it represents so we have to do it here
1897              * for now. */
1898             bond_stats.tx_packets += slave_stats.rx_packets;
1899             bond_stats.tx_bytes += slave_stats.rx_bytes;
1900             bond_stats.rx_packets += slave_stats.tx_packets;
1901             bond_stats.rx_bytes += slave_stats.tx_bytes;
1902         }
1903     }
1904
1905     if (!netdev_open_default(port->name, &bond_dev)) {
1906         netdev_set_stats(bond_dev, &bond_stats);
1907         netdev_close(bond_dev);
1908     }
1909 }
1910
1911 static void
1912 bond_run(struct bridge *br)
1913 {
1914     size_t i, j;
1915
1916     for (i = 0; i < br->n_ports; i++) {
1917         struct port *port = br->ports[i];
1918
1919         if (port->n_ifaces >= 2) {
1920             for (j = 0; j < port->n_ifaces; j++) {
1921                 struct iface *iface = port->ifaces[j];
1922                 if (time_msec() >= iface->delay_expires) {
1923                     bond_enable_slave(iface, !iface->enabled);
1924                 }
1925             }
1926
1927             if (port->bond_fake_iface
1928                 && time_msec() >= port->bond_next_fake_iface_update) {
1929                 bond_update_fake_iface_stats(port);
1930                 port->bond_next_fake_iface_update = time_msec() + 1000;
1931             }
1932         }
1933
1934         if (port->bond_compat_is_stale) {
1935             port->bond_compat_is_stale = false;
1936             port_update_bond_compat(port);
1937         }
1938     }
1939 }
1940
1941 static void
1942 bond_wait(struct bridge *br)
1943 {
1944     size_t i, j;
1945
1946     for (i = 0; i < br->n_ports; i++) {
1947         struct port *port = br->ports[i];
1948         if (port->n_ifaces < 2) {
1949             continue;
1950         }
1951         for (j = 0; j < port->n_ifaces; j++) {
1952             struct iface *iface = port->ifaces[j];
1953             if (iface->delay_expires != LLONG_MAX) {
1954                 poll_timer_wait_until(iface->delay_expires);
1955             }
1956         }
1957         if (port->bond_fake_iface) {
1958             poll_timer_wait_until(port->bond_next_fake_iface_update);
1959         }
1960     }
1961 }
1962
1963 static bool
1964 set_dst(struct dst *p, const flow_t *flow,
1965         const struct port *in_port, const struct port *out_port,
1966         tag_type *tags)
1967 {
1968     p->vlan = (out_port->vlan >= 0 ? OFP_VLAN_NONE
1969               : in_port->vlan >= 0 ? in_port->vlan
1970               : ntohs(flow->dl_vlan));
1971     return choose_output_iface(out_port, flow->dl_src, &p->dp_ifidx, tags);
1972 }
1973
1974 static void
1975 swap_dst(struct dst *p, struct dst *q)
1976 {
1977     struct dst tmp = *p;
1978     *p = *q;
1979     *q = tmp;
1980 }
1981
1982 /* Moves all the dsts with vlan == 'vlan' to the front of the 'n_dsts' in
1983  * 'dsts'.  (This may help performance by reducing the number of VLAN changes
1984  * that we push to the datapath.  We could in fact fully sort the array by
1985  * vlan, but in most cases there are at most two different vlan tags so that's
1986  * possibly overkill.) */
1987 static void
1988 partition_dsts(struct dst *dsts, size_t n_dsts, int vlan)
1989 {
1990     struct dst *first = dsts;
1991     struct dst *last = dsts + n_dsts;
1992
1993     while (first != last) {
1994         /* Invariants:
1995          *      - All dsts < first have vlan == 'vlan'.
1996          *      - All dsts >= last have vlan != 'vlan'.
1997          *      - first < last. */
1998         while (first->vlan == vlan) {
1999             if (++first == last) {
2000                 return;
2001             }
2002         }
2003
2004         /* Same invariants, plus one additional:
2005          *      - first->vlan != vlan.
2006          */
2007         while (last[-1].vlan != vlan) {
2008             if (--last == first) {
2009                 return;
2010             }
2011         }
2012
2013         /* Same invariants, plus one additional:
2014          *      - last[-1].vlan == vlan.*/
2015         swap_dst(first++, --last);
2016     }
2017 }
2018
2019 static int
2020 mirror_mask_ffs(mirror_mask_t mask)
2021 {
2022     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
2023     return ffs(mask);
2024 }
2025
2026 static bool
2027 dst_is_duplicate(const struct dst *dsts, size_t n_dsts,
2028                  const struct dst *test)
2029 {
2030     size_t i;
2031     for (i = 0; i < n_dsts; i++) {
2032         if (dsts[i].vlan == test->vlan && dsts[i].dp_ifidx == test->dp_ifidx) {
2033             return true;
2034         }
2035     }
2036     return false;
2037 }
2038
2039 static bool
2040 port_trunks_vlan(const struct port *port, uint16_t vlan)
2041 {
2042     return (port->vlan < 0
2043             && (!port->trunks || bitmap_is_set(port->trunks, vlan)));
2044 }
2045
2046 static bool
2047 port_includes_vlan(const struct port *port, uint16_t vlan)
2048 {
2049     return vlan == port->vlan || port_trunks_vlan(port, vlan);
2050 }
2051
2052 static size_t
2053 compose_dsts(const struct bridge *br, const flow_t *flow, uint16_t vlan,
2054              const struct port *in_port, const struct port *out_port,
2055              struct dst dsts[], tag_type *tags, uint16_t *nf_output_iface)
2056 {
2057     mirror_mask_t mirrors = in_port->src_mirrors;
2058     struct dst *dst = dsts;
2059     size_t i;
2060
2061     if (out_port == FLOOD_PORT) {
2062         /* XXX use ODP_FLOOD if no vlans or bonding. */
2063         /* XXX even better, define each VLAN as a datapath port group */
2064         for (i = 0; i < br->n_ports; i++) {
2065             struct port *port = br->ports[i];
2066             if (port != in_port && port_includes_vlan(port, vlan)
2067                 && !port->is_mirror_output_port
2068                 && set_dst(dst, flow, in_port, port, tags)) {
2069                 mirrors |= port->dst_mirrors;
2070                 dst++;
2071             }
2072         }
2073         *nf_output_iface = NF_OUT_FLOOD;
2074     } else if (out_port && set_dst(dst, flow, in_port, out_port, tags)) {
2075         *nf_output_iface = dst->dp_ifidx;
2076         mirrors |= out_port->dst_mirrors;
2077         dst++;
2078     }
2079
2080     while (mirrors) {
2081         struct mirror *m = br->mirrors[mirror_mask_ffs(mirrors) - 1];
2082         if (!m->n_vlans || vlan_is_mirrored(m, vlan)) {
2083             if (m->out_port) {
2084                 if (set_dst(dst, flow, in_port, m->out_port, tags)
2085                     && !dst_is_duplicate(dsts, dst - dsts, dst)) {
2086                     dst++;
2087                 }
2088             } else {
2089                 for (i = 0; i < br->n_ports; i++) {
2090                     struct port *port = br->ports[i];
2091                     if (port_includes_vlan(port, m->out_vlan)
2092                         && set_dst(dst, flow, in_port, port, tags))
2093                     {
2094                         int flow_vlan;
2095
2096                         if (port->vlan < 0) {
2097                             dst->vlan = m->out_vlan;
2098                         }
2099                         if (dst_is_duplicate(dsts, dst - dsts, dst)) {
2100                             continue;
2101                         }
2102
2103                         /* Use the vlan tag on the original flow instead of
2104                          * the one passed in the vlan parameter.  This ensures
2105                          * that we compare the vlan from before any implicit
2106                          * tagging tags place. This is necessary because
2107                          * dst->vlan is the final vlan, after removing implicit
2108                          * tags. */
2109                         flow_vlan = ntohs(flow->dl_vlan);
2110                         if (flow_vlan == 0) {
2111                             flow_vlan = OFP_VLAN_NONE;
2112                         }
2113                         if (port == in_port && dst->vlan == flow_vlan) {
2114                             /* Don't send out input port on same VLAN. */
2115                             continue;
2116                         }
2117                         dst++;
2118                     }
2119                 }
2120             }
2121         }
2122         mirrors &= mirrors - 1;
2123     }
2124
2125     partition_dsts(dsts, dst - dsts, ntohs(flow->dl_vlan));
2126     return dst - dsts;
2127 }
2128
2129 static void OVS_UNUSED
2130 print_dsts(const struct dst *dsts, size_t n)
2131 {
2132     for (; n--; dsts++) {
2133         printf(">p%"PRIu16, dsts->dp_ifidx);
2134         if (dsts->vlan != OFP_VLAN_NONE) {
2135             printf("v%"PRIu16, dsts->vlan);
2136         }
2137     }
2138 }
2139
2140 static void
2141 compose_actions(struct bridge *br, const flow_t *flow, uint16_t vlan,
2142                 const struct port *in_port, const struct port *out_port,
2143                 tag_type *tags, struct odp_actions *actions,
2144                 uint16_t *nf_output_iface)
2145 {
2146     struct dst dsts[DP_MAX_PORTS * (MAX_MIRRORS + 1)];
2147     size_t n_dsts;
2148     const struct dst *p;
2149     uint16_t cur_vlan;
2150
2151     n_dsts = compose_dsts(br, flow, vlan, in_port, out_port, dsts, tags,
2152                           nf_output_iface);
2153
2154     cur_vlan = ntohs(flow->dl_vlan);
2155     for (p = dsts; p < &dsts[n_dsts]; p++) {
2156         union odp_action *a;
2157         if (p->vlan != cur_vlan) {
2158             if (p->vlan == OFP_VLAN_NONE) {
2159                 odp_actions_add(actions, ODPAT_STRIP_VLAN);
2160             } else {
2161                 a = odp_actions_add(actions, ODPAT_SET_VLAN_VID);
2162                 a->vlan_vid.vlan_vid = htons(p->vlan);
2163             }
2164             cur_vlan = p->vlan;
2165         }
2166         a = odp_actions_add(actions, ODPAT_OUTPUT);
2167         a->output.port = p->dp_ifidx;
2168     }
2169 }
2170
2171 /* Returns the effective vlan of a packet, taking into account both the
2172  * 802.1Q header and implicitly tagged ports.  A value of 0 indicates that
2173  * the packet is untagged and -1 indicates it has an invalid header and
2174  * should be dropped. */
2175 static int flow_get_vlan(struct bridge *br, const flow_t *flow,
2176                          struct port *in_port, bool have_packet)
2177 {
2178     /* Note that dl_vlan of 0 and of OFP_VLAN_NONE both mean that the packet
2179      * belongs to VLAN 0, so we should treat both cases identically.  (In the
2180      * former case, the packet has an 802.1Q header that specifies VLAN 0,
2181      * presumably to allow a priority to be specified.  In the latter case, the
2182      * packet does not have any 802.1Q header.) */
2183     int vlan = ntohs(flow->dl_vlan);
2184     if (vlan == OFP_VLAN_NONE) {
2185         vlan = 0;
2186     }
2187     if (in_port->vlan >= 0) {
2188         if (vlan) {
2189             /* XXX support double tagging? */
2190             if (have_packet) {
2191                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2192                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" tagged "
2193                              "packet received on port %s configured with "
2194                              "implicit VLAN %"PRIu16,
2195                              br->name, ntohs(flow->dl_vlan),
2196                              in_port->name, in_port->vlan);
2197             }
2198             return -1;
2199         }
2200         vlan = in_port->vlan;
2201     } else {
2202         if (!port_includes_vlan(in_port, vlan)) {
2203             if (have_packet) {
2204                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2205                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
2206                              "packet received on port %s not configured for "
2207                              "trunking VLAN %d",
2208                              br->name, vlan, in_port->name, vlan);
2209             }
2210             return -1;
2211         }
2212     }
2213
2214     return vlan;
2215 }
2216
2217 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
2218  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
2219  * indicate this; newer upstream kernels use gratuitous ARP requests. */
2220 static bool
2221 is_gratuitous_arp(const flow_t *flow)
2222 {
2223     return (flow->dl_type == htons(ETH_TYPE_ARP)
2224             && eth_addr_is_broadcast(flow->dl_dst)
2225             && (flow->nw_proto == ARP_OP_REPLY
2226                 || (flow->nw_proto == ARP_OP_REQUEST
2227                     && flow->nw_src == flow->nw_dst)));
2228 }
2229
2230 static void
2231 update_learning_table(struct bridge *br, const flow_t *flow, int vlan,
2232                       struct port *in_port)
2233 {
2234     enum grat_arp_lock_type lock_type;
2235     tag_type rev_tag;
2236
2237     /* We don't want to learn from gratuitous ARP packets that are reflected
2238      * back over bond slaves so we lock the learning table. */
2239     lock_type = !is_gratuitous_arp(flow) ? GRAT_ARP_LOCK_NONE :
2240                     (in_port->n_ifaces == 1) ? GRAT_ARP_LOCK_SET :
2241                                                GRAT_ARP_LOCK_CHECK;
2242
2243     rev_tag = mac_learning_learn(br->ml, flow->dl_src, vlan, in_port->port_idx,
2244                                  lock_type);
2245     if (rev_tag) {
2246         /* The log messages here could actually be useful in debugging,
2247          * so keep the rate limit relatively high. */
2248         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30,
2249                                                                 300);
2250         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
2251                     "on port %s in VLAN %d",
2252                     br->name, ETH_ADDR_ARGS(flow->dl_src),
2253                     in_port->name, vlan);
2254         ofproto_revalidate(br->ofproto, rev_tag);
2255     }
2256 }
2257
2258 /* Determines whether packets in 'flow' within 'br' should be forwarded or
2259  * dropped.  Returns true if they may be forwarded, false if they should be
2260  * dropped.
2261  *
2262  * If 'have_packet' is true, it indicates that the caller is processing a
2263  * received packet.  If 'have_packet' is false, then the caller is just
2264  * revalidating an existing flow because configuration has changed.  Either
2265  * way, 'have_packet' only affects logging (there is no point in logging errors
2266  * during revalidation).
2267  *
2268  * Sets '*in_portp' to the input port.  This will be a null pointer if
2269  * flow->in_port does not designate a known input port (in which case
2270  * is_admissible() returns false).
2271  *
2272  * When returning true, sets '*vlanp' to the effective VLAN of the input
2273  * packet, as returned by flow_get_vlan().
2274  *
2275  * May also add tags to '*tags', although the current implementation only does
2276  * so in one special case.
2277  */
2278 static bool
2279 is_admissible(struct bridge *br, const flow_t *flow, bool have_packet,
2280               tag_type *tags, int *vlanp, struct port **in_portp)
2281 {
2282     struct iface *in_iface;
2283     struct port *in_port;
2284     int vlan;
2285
2286     /* Find the interface and port structure for the received packet. */
2287     in_iface = iface_from_dp_ifidx(br, flow->in_port);
2288     if (!in_iface) {
2289         /* No interface?  Something fishy... */
2290         if (have_packet) {
2291             /* Odd.  A few possible reasons here:
2292              *
2293              * - We deleted an interface but there are still a few packets
2294              *   queued up from it.
2295              *
2296              * - Someone externally added an interface (e.g. with "ovs-dpctl
2297              *   add-if") that we don't know about.
2298              *
2299              * - Packet arrived on the local port but the local port is not
2300              *   one of our bridge ports.
2301              */
2302             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2303
2304             VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
2305                          "interface %"PRIu16, br->name, flow->in_port); 
2306         }
2307
2308         *in_portp = NULL;
2309         return false;
2310     }
2311     *in_portp = in_port = in_iface->port;
2312     *vlanp = vlan = flow_get_vlan(br, flow, in_port, have_packet);
2313     if (vlan < 0) {
2314         return false;
2315     }
2316
2317     /* Drop frames for reserved multicast addresses. */
2318     if (eth_addr_is_reserved(flow->dl_dst)) {
2319         return false;
2320     }
2321
2322     /* Drop frames on ports reserved for mirroring. */
2323     if (in_port->is_mirror_output_port) {
2324         if (have_packet) {
2325             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2326             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
2327                          "%s, which is reserved exclusively for mirroring",
2328                          br->name, in_port->name);
2329         }
2330         return false;
2331     }
2332
2333     /* Packets received on bonds need special attention to avoid duplicates. */
2334     if (in_port->n_ifaces > 1) {
2335         int src_idx;
2336         bool is_grat_arp_locked;
2337
2338         if (eth_addr_is_multicast(flow->dl_dst)) {
2339             *tags |= in_port->active_iface_tag;
2340             if (in_port->active_iface != in_iface->port_ifidx) {
2341                 /* Drop all multicast packets on inactive slaves. */
2342                 return false;
2343             }
2344         }
2345
2346         /* Drop all packets for which we have learned a different input
2347          * port, because we probably sent the packet on one slave and got
2348          * it back on the other.  Gratuitous ARP packets are an exception
2349          * to this rule: the host has moved to another switch.  The exception
2350          * to the exception is if we locked the learning table to avoid
2351          * reflections on bond slaves.  If this is the case, just drop the
2352          * packet now. */
2353         src_idx = mac_learning_lookup(br->ml, flow->dl_src, vlan,
2354                                       &is_grat_arp_locked);
2355         if (src_idx != -1 && src_idx != in_port->port_idx &&
2356             (!is_gratuitous_arp(flow) || is_grat_arp_locked)) {
2357                 return false;
2358         }
2359     }
2360
2361     return true;
2362 }
2363
2364 /* If the composed actions may be applied to any packet in the given 'flow',
2365  * returns true.  Otherwise, the actions should only be applied to 'packet', or
2366  * not at all, if 'packet' was NULL. */
2367 static bool
2368 process_flow(struct bridge *br, const flow_t *flow,
2369              const struct ofpbuf *packet, struct odp_actions *actions,
2370              tag_type *tags, uint16_t *nf_output_iface)
2371 {
2372     struct port *in_port;
2373     struct port *out_port;
2374     int vlan;
2375     int out_port_idx;
2376
2377     /* Check whether we should drop packets in this flow. */
2378     if (!is_admissible(br, flow, packet != NULL, tags, &vlan, &in_port)) {
2379         out_port = NULL;
2380         goto done;
2381     }
2382
2383     /* Learn source MAC (but don't try to learn from revalidation). */
2384     if (packet) {
2385         update_learning_table(br, flow, vlan, in_port);
2386     }
2387
2388     /* Determine output port. */
2389     out_port_idx = mac_learning_lookup_tag(br->ml, flow->dl_dst, vlan, tags,
2390                                            NULL);
2391     if (out_port_idx >= 0 && out_port_idx < br->n_ports) {
2392         out_port = br->ports[out_port_idx];
2393     } else if (!packet && !eth_addr_is_multicast(flow->dl_dst)) {
2394         /* If we are revalidating but don't have a learning entry then
2395          * eject the flow.  Installing a flow that floods packets opens
2396          * up a window of time where we could learn from a packet reflected
2397          * on a bond and blackhole packets before the learning table is
2398          * updated to reflect the correct port. */
2399         return false;
2400     } else {
2401         out_port = FLOOD_PORT;
2402     }
2403
2404     /* Don't send packets out their input ports. */
2405     if (in_port == out_port) {
2406         out_port = NULL;
2407     }
2408
2409 done:
2410     if (in_port) {
2411         compose_actions(br, flow, vlan, in_port, out_port, tags, actions,
2412                         nf_output_iface);
2413     }
2414
2415     return true;
2416 }
2417
2418 /* Careful: 'opp' is in host byte order and opp->port_no is an OFP port
2419  * number. */
2420 static void
2421 bridge_port_changed_ofhook_cb(enum ofp_port_reason reason,
2422                               const struct ofp_phy_port *opp,
2423                               void *br_)
2424 {
2425     struct bridge *br = br_;
2426     struct iface *iface;
2427     struct port *port;
2428
2429     iface = iface_from_dp_ifidx(br, ofp_port_to_odp_port(opp->port_no));
2430     if (!iface) {
2431         return;
2432     }
2433     port = iface->port;
2434
2435     if (reason == OFPPR_DELETE) {
2436         VLOG_WARN("bridge %s: interface %s deleted unexpectedly",
2437                   br->name, iface->name);
2438         iface_destroy(iface);
2439         if (!port->n_ifaces) {
2440             VLOG_WARN("bridge %s: port %s has no interfaces, dropping",
2441                       br->name, port->name);
2442             port_destroy(port);
2443         }
2444
2445         bridge_flush(br);
2446     } else {
2447         if (port->n_ifaces > 1) {
2448             bool up = !(opp->state & OFPPS_LINK_DOWN);
2449             bond_link_status_update(iface, up);
2450             port_update_bond_compat(port);
2451         }
2452     }
2453 }
2454
2455 static bool
2456 bridge_normal_ofhook_cb(const flow_t *flow, const struct ofpbuf *packet,
2457                         struct odp_actions *actions, tag_type *tags,
2458                         uint16_t *nf_output_iface, void *br_)
2459 {
2460     struct bridge *br = br_;
2461
2462     COVERAGE_INC(bridge_process_flow);
2463     return process_flow(br, flow, packet, actions, tags, nf_output_iface);
2464 }
2465
2466 static void
2467 bridge_account_flow_ofhook_cb(const flow_t *flow,
2468                               const union odp_action *actions,
2469                               size_t n_actions, unsigned long long int n_bytes,
2470                               void *br_)
2471 {
2472     struct bridge *br = br_;
2473     const union odp_action *a;
2474     struct port *in_port;
2475     tag_type tags = 0;
2476     int vlan;
2477
2478     /* Feed information from the active flows back into the learning table
2479      * to ensure that table is always in sync with what is actually flowing
2480      * through the datapath. */
2481     if (is_admissible(br, flow, false, &tags, &vlan, &in_port)) {
2482         update_learning_table(br, flow, vlan, in_port);
2483     }
2484
2485     if (!br->has_bonded_ports) {
2486         return;
2487     }
2488
2489     for (a = actions; a < &actions[n_actions]; a++) {
2490         if (a->type == ODPAT_OUTPUT) {
2491             struct port *out_port = port_from_dp_ifidx(br, a->output.port);
2492             if (out_port && out_port->n_ifaces >= 2) {
2493                 struct bond_entry *e = lookup_bond_entry(out_port,
2494                                                          flow->dl_src);
2495                 e->tx_bytes += n_bytes;
2496             }
2497         }
2498     }
2499 }
2500
2501 static void
2502 bridge_account_checkpoint_ofhook_cb(void *br_)
2503 {
2504     struct bridge *br = br_;
2505     long long int now;
2506     size_t i;
2507
2508     if (!br->has_bonded_ports) {
2509         return;
2510     }
2511
2512     now = time_msec();
2513     for (i = 0; i < br->n_ports; i++) {
2514         struct port *port = br->ports[i];
2515         if (port->n_ifaces > 1 && now >= port->bond_next_rebalance) {
2516             port->bond_next_rebalance = now + port->bond_rebalance_interval;
2517             bond_rebalance_port(port);
2518         }
2519     }
2520 }
2521
2522 static struct ofhooks bridge_ofhooks = {
2523     bridge_port_changed_ofhook_cb,
2524     bridge_normal_ofhook_cb,
2525     bridge_account_flow_ofhook_cb,
2526     bridge_account_checkpoint_ofhook_cb,
2527 };
2528 \f
2529 /* Bonding functions. */
2530
2531 /* Statistics for a single interface on a bonded port, used for load-based
2532  * bond rebalancing.  */
2533 struct slave_balance {
2534     struct iface *iface;        /* The interface. */
2535     uint64_t tx_bytes;          /* Sum of hashes[*]->tx_bytes. */
2536
2537     /* All the "bond_entry"s that are assigned to this interface, in order of
2538      * increasing tx_bytes. */
2539     struct bond_entry **hashes;
2540     size_t n_hashes;
2541 };
2542
2543 /* Sorts pointers to pointers to bond_entries in ascending order by the
2544  * interface to which they are assigned, and within a single interface in
2545  * ascending order of bytes transmitted. */
2546 static int
2547 compare_bond_entries(const void *a_, const void *b_)
2548 {
2549     const struct bond_entry *const *ap = a_;
2550     const struct bond_entry *const *bp = b_;
2551     const struct bond_entry *a = *ap;
2552     const struct bond_entry *b = *bp;
2553     if (a->iface_idx != b->iface_idx) {
2554         return a->iface_idx > b->iface_idx ? 1 : -1;
2555     } else if (a->tx_bytes != b->tx_bytes) {
2556         return a->tx_bytes > b->tx_bytes ? 1 : -1;
2557     } else {
2558         return 0;
2559     }
2560 }
2561
2562 /* Sorts slave_balances so that enabled ports come first, and otherwise in
2563  * *descending* order by number of bytes transmitted. */
2564 static int
2565 compare_slave_balance(const void *a_, const void *b_)
2566 {
2567     const struct slave_balance *a = a_;
2568     const struct slave_balance *b = b_;
2569     if (a->iface->enabled != b->iface->enabled) {
2570         return a->iface->enabled ? -1 : 1;
2571     } else if (a->tx_bytes != b->tx_bytes) {
2572         return a->tx_bytes > b->tx_bytes ? -1 : 1;
2573     } else {
2574         return 0;
2575     }
2576 }
2577
2578 static void
2579 swap_bals(struct slave_balance *a, struct slave_balance *b)
2580 {
2581     struct slave_balance tmp = *a;
2582     *a = *b;
2583     *b = tmp;
2584 }
2585
2586 /* Restores the 'n_bals' slave_balance structures in 'bals' to sorted order
2587  * given that 'p' (and only 'p') might be in the wrong location.
2588  *
2589  * This function invalidates 'p', since it might now be in a different memory
2590  * location. */
2591 static void
2592 resort_bals(struct slave_balance *p,
2593             struct slave_balance bals[], size_t n_bals)
2594 {
2595     if (n_bals > 1) {
2596         for (; p > bals && p->tx_bytes > p[-1].tx_bytes; p--) {
2597             swap_bals(p, p - 1);
2598         }
2599         for (; p < &bals[n_bals - 1] && p->tx_bytes < p[1].tx_bytes; p++) {
2600             swap_bals(p, p + 1);
2601         }
2602     }
2603 }
2604
2605 static void
2606 log_bals(const struct slave_balance *bals, size_t n_bals, struct port *port)
2607 {
2608     if (VLOG_IS_DBG_ENABLED()) {
2609         struct ds ds = DS_EMPTY_INITIALIZER;
2610         const struct slave_balance *b;
2611
2612         for (b = bals; b < bals + n_bals; b++) {
2613             size_t i;
2614
2615             if (b > bals) {
2616                 ds_put_char(&ds, ',');
2617             }
2618             ds_put_format(&ds, " %s %"PRIu64"kB",
2619                           b->iface->name, b->tx_bytes / 1024);
2620
2621             if (!b->iface->enabled) {
2622                 ds_put_cstr(&ds, " (disabled)");
2623             }
2624             if (b->n_hashes > 0) {
2625                 ds_put_cstr(&ds, " (");
2626                 for (i = 0; i < b->n_hashes; i++) {
2627                     const struct bond_entry *e = b->hashes[i];
2628                     if (i > 0) {
2629                         ds_put_cstr(&ds, " + ");
2630                     }
2631                     ds_put_format(&ds, "h%td: %"PRIu64"kB",
2632                                   e - port->bond_hash, e->tx_bytes / 1024);
2633                 }
2634                 ds_put_cstr(&ds, ")");
2635             }
2636         }
2637         VLOG_DBG("bond %s:%s", port->name, ds_cstr(&ds));
2638         ds_destroy(&ds);
2639     }
2640 }
2641
2642 /* Shifts 'hash' from 'from' to 'to' within 'port'. */
2643 static void
2644 bond_shift_load(struct slave_balance *from, struct slave_balance *to,
2645                 int hash_idx)
2646 {
2647     struct bond_entry *hash = from->hashes[hash_idx];
2648     struct port *port = from->iface->port;
2649     uint64_t delta = hash->tx_bytes;
2650
2651     VLOG_INFO("bond %s: shift %"PRIu64"kB of load (with hash %td) "
2652               "from %s to %s (now carrying %"PRIu64"kB and "
2653               "%"PRIu64"kB load, respectively)",
2654               port->name, delta / 1024, hash - port->bond_hash,
2655               from->iface->name, to->iface->name,
2656               (from->tx_bytes - delta) / 1024,
2657               (to->tx_bytes + delta) / 1024);
2658
2659     /* Delete element from from->hashes.
2660      *
2661      * We don't bother to add the element to to->hashes because not only would
2662      * it require more work, the only purpose it would be to allow that hash to
2663      * be migrated to another slave in this rebalancing run, and there is no
2664      * point in doing that.  */
2665     if (hash_idx == 0) {
2666         from->hashes++;
2667     } else {
2668         memmove(from->hashes + hash_idx, from->hashes + hash_idx + 1,
2669                 (from->n_hashes - (hash_idx + 1)) * sizeof *from->hashes);
2670     }
2671     from->n_hashes--;
2672
2673     /* Shift load away from 'from' to 'to'. */
2674     from->tx_bytes -= delta;
2675     to->tx_bytes += delta;
2676
2677     /* Arrange for flows to be revalidated. */
2678     ofproto_revalidate(port->bridge->ofproto, hash->iface_tag);
2679     hash->iface_idx = to->iface->port_ifidx;
2680     hash->iface_tag = tag_create_random();
2681 }
2682
2683 static void
2684 bond_rebalance_port(struct port *port)
2685 {
2686     struct slave_balance bals[DP_MAX_PORTS];
2687     size_t n_bals;
2688     struct bond_entry *hashes[BOND_MASK + 1];
2689     struct slave_balance *b, *from, *to;
2690     struct bond_entry *e;
2691     size_t i;
2692
2693     /* Sets up 'bals' to describe each of the port's interfaces, sorted in
2694      * descending order of tx_bytes, so that bals[0] represents the most
2695      * heavily loaded slave and bals[n_bals - 1] represents the least heavily
2696      * loaded slave.
2697      *
2698      * The code is a bit tricky: to avoid dynamically allocating a 'hashes'
2699      * array for each slave_balance structure, we sort our local array of
2700      * hashes in order by slave, so that all of the hashes for a given slave
2701      * become contiguous in memory, and then we point each 'hashes' members of
2702      * a slave_balance structure to the start of a contiguous group. */
2703     n_bals = port->n_ifaces;
2704     for (b = bals; b < &bals[n_bals]; b++) {
2705         b->iface = port->ifaces[b - bals];
2706         b->tx_bytes = 0;
2707         b->hashes = NULL;
2708         b->n_hashes = 0;
2709     }
2710     for (i = 0; i <= BOND_MASK; i++) {
2711         hashes[i] = &port->bond_hash[i];
2712     }
2713     qsort(hashes, BOND_MASK + 1, sizeof *hashes, compare_bond_entries);
2714     for (i = 0; i <= BOND_MASK; i++) {
2715         e = hashes[i];
2716         if (e->iface_idx >= 0 && e->iface_idx < port->n_ifaces) {
2717             b = &bals[e->iface_idx];
2718             b->tx_bytes += e->tx_bytes;
2719             if (!b->hashes) {
2720                 b->hashes = &hashes[i];
2721             }
2722             b->n_hashes++;
2723         }
2724     }
2725     qsort(bals, n_bals, sizeof *bals, compare_slave_balance);
2726     log_bals(bals, n_bals, port);
2727
2728     /* Discard slaves that aren't enabled (which were sorted to the back of the
2729      * array earlier). */
2730     while (!bals[n_bals - 1].iface->enabled) {
2731         n_bals--;
2732         if (!n_bals) {
2733             return;
2734         }
2735     }
2736
2737     /* Shift load from the most-loaded slaves to the least-loaded slaves. */
2738     to = &bals[n_bals - 1];
2739     for (from = bals; from < to; ) {
2740         uint64_t overload = from->tx_bytes - to->tx_bytes;
2741         if (overload < to->tx_bytes >> 5 || overload < 100000) {
2742             /* The extra load on 'from' (and all less-loaded slaves), compared
2743              * to that of 'to' (the least-loaded slave), is less than ~3%, or
2744              * it is less than ~1Mbps.  No point in rebalancing. */
2745             break;
2746         } else if (from->n_hashes == 1) {
2747             /* 'from' only carries a single MAC hash, so we can't shift any
2748              * load away from it, even though we want to. */
2749             from++;
2750         } else {
2751             /* 'from' is carrying significantly more load than 'to', and that
2752              * load is split across at least two different hashes.  Pick a hash
2753              * to migrate to 'to' (the least-loaded slave), given that doing so
2754              * must decrease the ratio of the load on the two slaves by at
2755              * least 0.1.
2756              *
2757              * The sort order we use means that we prefer to shift away the
2758              * smallest hashes instead of the biggest ones.  There is little
2759              * reason behind this decision; we could use the opposite sort
2760              * order to shift away big hashes ahead of small ones. */
2761             size_t i;
2762             bool order_swapped;
2763
2764             for (i = 0; i < from->n_hashes; i++) {
2765                 double old_ratio, new_ratio;
2766                 uint64_t delta = from->hashes[i]->tx_bytes;
2767
2768                 if (delta == 0 || from->tx_bytes - delta == 0) {
2769                     /* Pointless move. */
2770                     continue;
2771                 }
2772
2773                 order_swapped = from->tx_bytes - delta < to->tx_bytes + delta;
2774
2775                 if (to->tx_bytes == 0) {
2776                     /* Nothing on the new slave, move it. */
2777                     break;
2778                 }
2779
2780                 old_ratio = (double)from->tx_bytes / to->tx_bytes;
2781                 new_ratio = (double)(from->tx_bytes - delta) /
2782                             (to->tx_bytes + delta);
2783
2784                 if (new_ratio == 0) {
2785                     /* Should already be covered but check to prevent division
2786                      * by zero. */
2787                     continue;
2788                 }
2789
2790                 if (new_ratio < 1) {
2791                     new_ratio = 1 / new_ratio;
2792                 }
2793
2794                 if (old_ratio - new_ratio > 0.1) {
2795                     /* Would decrease the ratio, move it. */
2796                     break;
2797                 }
2798             }
2799             if (i < from->n_hashes) {
2800                 bond_shift_load(from, to, i);
2801                 port->bond_compat_is_stale = true;
2802
2803                 /* If the result of the migration changed the relative order of
2804                  * 'from' and 'to' swap them back to maintain invariants. */
2805                 if (order_swapped) {
2806                     swap_bals(from, to);
2807                 }
2808
2809                 /* Re-sort 'bals'.  Note that this may make 'from' and 'to'
2810                  * point to different slave_balance structures.  It is only
2811                  * valid to do these two operations in a row at all because we
2812                  * know that 'from' will not move past 'to' and vice versa. */
2813                 resort_bals(from, bals, n_bals);
2814                 resort_bals(to, bals, n_bals);
2815             } else {
2816                 from++;
2817             }
2818         }
2819     }
2820
2821     /* Implement exponentially weighted moving average.  A weight of 1/2 causes
2822      * historical data to decay to <1% in 7 rebalancing runs.  */
2823     for (e = &port->bond_hash[0]; e <= &port->bond_hash[BOND_MASK]; e++) {
2824         e->tx_bytes /= 2;
2825     }
2826 }
2827
2828 static void
2829 bond_send_learning_packets(struct port *port)
2830 {
2831     struct bridge *br = port->bridge;
2832     struct mac_entry *e;
2833     struct ofpbuf packet;
2834     int error, n_packets, n_errors;
2835
2836     if (!port->n_ifaces || port->active_iface < 0) {
2837         return;
2838     }
2839
2840     ofpbuf_init(&packet, 128);
2841     error = n_packets = n_errors = 0;
2842     LIST_FOR_EACH (e, struct mac_entry, lru_node, &br->ml->lrus) {
2843         union ofp_action actions[2], *a;
2844         uint16_t dp_ifidx;
2845         tag_type tags = 0;
2846         flow_t flow;
2847         int retval;
2848
2849         if (e->port == port->port_idx
2850             || !choose_output_iface(port, e->mac, &dp_ifidx, &tags)) {
2851             continue;
2852         }
2853
2854         /* Compose actions. */
2855         memset(actions, 0, sizeof actions);
2856         a = actions;
2857         if (e->vlan) {
2858             a->vlan_vid.type = htons(OFPAT_SET_VLAN_VID);
2859             a->vlan_vid.len = htons(sizeof *a);
2860             a->vlan_vid.vlan_vid = htons(e->vlan);
2861             a++;
2862         }
2863         a->output.type = htons(OFPAT_OUTPUT);
2864         a->output.len = htons(sizeof *a);
2865         a->output.port = htons(odp_port_to_ofp_port(dp_ifidx));
2866         a++;
2867
2868         /* Send packet. */
2869         n_packets++;
2870         compose_benign_packet(&packet, "Open vSwitch Bond Failover", 0xf177,
2871                               e->mac);
2872         flow_extract(&packet, 0, ODPP_NONE, &flow);
2873         retval = ofproto_send_packet(br->ofproto, &flow, actions, a - actions,
2874                                      &packet);
2875         if (retval) {
2876             error = retval;
2877             n_errors++;
2878         }
2879     }
2880     ofpbuf_uninit(&packet);
2881
2882     if (n_errors) {
2883         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2884         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
2885                      "packets, last error was: %s",
2886                      port->name, n_errors, n_packets, strerror(error));
2887     } else {
2888         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
2889                  port->name, n_packets);
2890     }
2891 }
2892 \f
2893 /* Bonding unixctl user interface functions. */
2894
2895 static void
2896 bond_unixctl_list(struct unixctl_conn *conn,
2897                   const char *args OVS_UNUSED, void *aux OVS_UNUSED)
2898 {
2899     struct ds ds = DS_EMPTY_INITIALIZER;
2900     const struct bridge *br;
2901
2902     ds_put_cstr(&ds, "bridge\tbond\tslaves\n");
2903
2904     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
2905         size_t i;
2906
2907         for (i = 0; i < br->n_ports; i++) {
2908             const struct port *port = br->ports[i];
2909             if (port->n_ifaces > 1) {
2910                 size_t j;
2911
2912                 ds_put_format(&ds, "%s\t%s\t", br->name, port->name);
2913                 for (j = 0; j < port->n_ifaces; j++) {
2914                     const struct iface *iface = port->ifaces[j];
2915                     if (j) {
2916                         ds_put_cstr(&ds, ", ");
2917                     }
2918                     ds_put_cstr(&ds, iface->name);
2919                 }
2920                 ds_put_char(&ds, '\n');
2921             }
2922         }
2923     }
2924     unixctl_command_reply(conn, 200, ds_cstr(&ds));
2925     ds_destroy(&ds);
2926 }
2927
2928 static struct port *
2929 bond_find(const char *name)
2930 {
2931     const struct bridge *br;
2932
2933     LIST_FOR_EACH (br, struct bridge, node, &all_bridges) {
2934         size_t i;
2935
2936         for (i = 0; i < br->n_ports; i++) {
2937             struct port *port = br->ports[i];
2938             if (!strcmp(port->name, name) && port->n_ifaces > 1) {
2939                 return port;
2940             }
2941         }
2942     }
2943     return NULL;
2944 }
2945
2946 static void
2947 bond_unixctl_show(struct unixctl_conn *conn,
2948                   const char *args, void *aux OVS_UNUSED)
2949 {
2950     struct ds ds = DS_EMPTY_INITIALIZER;
2951     const struct port *port;
2952     size_t j;
2953
2954     port = bond_find(args);
2955     if (!port) {
2956         unixctl_command_reply(conn, 501, "no such bond");
2957         return;
2958     }
2959
2960     ds_put_format(&ds, "updelay: %d ms\n", port->updelay);
2961     ds_put_format(&ds, "downdelay: %d ms\n", port->downdelay);
2962     ds_put_format(&ds, "next rebalance: %lld ms\n",
2963                   port->bond_next_rebalance - time_msec());
2964     for (j = 0; j < port->n_ifaces; j++) {
2965         const struct iface *iface = port->ifaces[j];
2966         struct bond_entry *be;
2967
2968         /* Basic info. */
2969         ds_put_format(&ds, "slave %s: %s\n",
2970                       iface->name, iface->enabled ? "enabled" : "disabled");
2971         if (j == port->active_iface) {
2972             ds_put_cstr(&ds, "\tactive slave\n");
2973         }
2974         if (iface->delay_expires != LLONG_MAX) {
2975             ds_put_format(&ds, "\t%s expires in %lld ms\n",
2976                           iface->enabled ? "downdelay" : "updelay",
2977                           iface->delay_expires - time_msec());
2978         }
2979
2980         /* Hashes. */
2981         for (be = port->bond_hash; be <= &port->bond_hash[BOND_MASK]; be++) {
2982             int hash = be - port->bond_hash;
2983             struct mac_entry *me;
2984
2985             if (be->iface_idx != j) {
2986                 continue;
2987             }
2988
2989             ds_put_format(&ds, "\thash %d: %"PRIu64" kB load\n",
2990                           hash, be->tx_bytes / 1024);
2991
2992             /* MACs. */
2993             LIST_FOR_EACH (me, struct mac_entry, lru_node,
2994                            &port->bridge->ml->lrus) {
2995                 uint16_t dp_ifidx;
2996                 tag_type tags = 0;
2997                 if (bond_hash(me->mac) == hash
2998                     && me->port != port->port_idx
2999                     && choose_output_iface(port, me->mac, &dp_ifidx, &tags)
3000                     && dp_ifidx == iface->dp_ifidx)
3001                 {
3002                     ds_put_format(&ds, "\t\t"ETH_ADDR_FMT"\n",
3003                                   ETH_ADDR_ARGS(me->mac));
3004                 }
3005             }
3006         }
3007     }
3008     unixctl_command_reply(conn, 200, ds_cstr(&ds));
3009     ds_destroy(&ds);
3010 }
3011
3012 static void
3013 bond_unixctl_migrate(struct unixctl_conn *conn, const char *args_,
3014                      void *aux OVS_UNUSED)
3015 {
3016     char *args = (char *) args_;
3017     char *save_ptr = NULL;
3018     char *bond_s, *hash_s, *slave_s;
3019     uint8_t mac[ETH_ADDR_LEN];
3020     struct port *port;
3021     struct iface *iface;
3022     struct bond_entry *entry;
3023     int hash;
3024
3025     bond_s = strtok_r(args, " ", &save_ptr);
3026     hash_s = strtok_r(NULL, " ", &save_ptr);
3027     slave_s = strtok_r(NULL, " ", &save_ptr);
3028     if (!slave_s) {
3029         unixctl_command_reply(conn, 501,
3030                               "usage: bond/migrate BOND HASH SLAVE");
3031         return;
3032     }
3033
3034     port = bond_find(bond_s);
3035     if (!port) {
3036         unixctl_command_reply(conn, 501, "no such bond");
3037         return;
3038     }
3039
3040     if (sscanf(hash_s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
3041         == ETH_ADDR_SCAN_COUNT) {
3042         hash = bond_hash(mac);
3043     } else if (strspn(hash_s, "0123456789") == strlen(hash_s)) {
3044         hash = atoi(hash_s) & BOND_MASK;
3045     } else {
3046         unixctl_command_reply(conn, 501, "bad hash");
3047         return;
3048     }
3049
3050     iface = port_lookup_iface(port, slave_s);
3051     if (!iface) {
3052         unixctl_command_reply(conn, 501, "no such slave");
3053         return;
3054     }
3055
3056     if (!iface->enabled) {
3057         unixctl_command_reply(conn, 501, "cannot migrate to disabled slave");
3058         return;
3059     }
3060
3061     entry = &port->bond_hash[hash];
3062     ofproto_revalidate(port->bridge->ofproto, entry->iface_tag);
3063     entry->iface_idx = iface->port_ifidx;
3064     entry->iface_tag = tag_create_random();
3065     port->bond_compat_is_stale = true;
3066     unixctl_command_reply(conn, 200, "migrated");
3067 }
3068
3069 static void
3070 bond_unixctl_set_active_slave(struct unixctl_conn *conn, const char *args_,
3071                               void *aux OVS_UNUSED)
3072 {
3073     char *args = (char *) args_;
3074     char *save_ptr = NULL;
3075     char *bond_s, *slave_s;
3076     struct port *port;
3077     struct iface *iface;
3078
3079     bond_s = strtok_r(args, " ", &save_ptr);
3080     slave_s = strtok_r(NULL, " ", &save_ptr);
3081     if (!slave_s) {
3082         unixctl_command_reply(conn, 501,
3083                               "usage: bond/set-active-slave BOND SLAVE");
3084         return;
3085     }
3086
3087     port = bond_find(bond_s);
3088     if (!port) {
3089         unixctl_command_reply(conn, 501, "no such bond");
3090         return;
3091     }
3092
3093     iface = port_lookup_iface(port, slave_s);
3094     if (!iface) {
3095         unixctl_command_reply(conn, 501, "no such slave");
3096         return;
3097     }
3098
3099     if (!iface->enabled) {
3100         unixctl_command_reply(conn, 501, "cannot make disabled slave active");
3101         return;
3102     }
3103
3104     if (port->active_iface != iface->port_ifidx) {
3105         ofproto_revalidate(port->bridge->ofproto, port->active_iface_tag);
3106         port->active_iface = iface->port_ifidx;
3107         port->active_iface_tag = tag_create_random();
3108         VLOG_INFO("port %s: active interface is now %s",
3109                   port->name, iface->name);
3110         bond_send_learning_packets(port);
3111         unixctl_command_reply(conn, 200, "done");
3112     } else {
3113         unixctl_command_reply(conn, 200, "no change");
3114     }
3115 }
3116
3117 static void
3118 enable_slave(struct unixctl_conn *conn, const char *args_, bool enable)
3119 {
3120     char *args = (char *) args_;
3121     char *save_ptr = NULL;
3122     char *bond_s, *slave_s;
3123     struct port *port;
3124     struct iface *iface;
3125
3126     bond_s = strtok_r(args, " ", &save_ptr);
3127     slave_s = strtok_r(NULL, " ", &save_ptr);
3128     if (!slave_s) {
3129         unixctl_command_reply(conn, 501,
3130                               "usage: bond/enable/disable-slave BOND SLAVE");
3131         return;
3132     }
3133
3134     port = bond_find(bond_s);
3135     if (!port) {
3136         unixctl_command_reply(conn, 501, "no such bond");
3137         return;
3138     }
3139
3140     iface = port_lookup_iface(port, slave_s);
3141     if (!iface) {
3142         unixctl_command_reply(conn, 501, "no such slave");
3143         return;
3144     }
3145
3146     bond_enable_slave(iface, enable);
3147     unixctl_command_reply(conn, 501, enable ? "enabled" : "disabled");
3148 }
3149
3150 static void
3151 bond_unixctl_enable_slave(struct unixctl_conn *conn, const char *args,
3152                           void *aux OVS_UNUSED)
3153 {
3154     enable_slave(conn, args, true);
3155 }
3156
3157 static void
3158 bond_unixctl_disable_slave(struct unixctl_conn *conn, const char *args,
3159                            void *aux OVS_UNUSED)
3160 {
3161     enable_slave(conn, args, false);
3162 }
3163
3164 static void
3165 bond_unixctl_hash(struct unixctl_conn *conn, const char *args,
3166                   void *aux OVS_UNUSED)
3167 {
3168         uint8_t mac[ETH_ADDR_LEN];
3169         uint8_t hash;
3170         char *hash_cstr;
3171
3172         if (sscanf(args, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
3173             == ETH_ADDR_SCAN_COUNT) {
3174                 hash = bond_hash(mac);
3175
3176                 hash_cstr = xasprintf("%u", hash);
3177                 unixctl_command_reply(conn, 200, hash_cstr);
3178                 free(hash_cstr);
3179         } else {
3180                 unixctl_command_reply(conn, 501, "invalid mac");
3181         }
3182 }
3183
3184 static void
3185 bond_init(void)
3186 {
3187     unixctl_command_register("bond/list", bond_unixctl_list, NULL);
3188     unixctl_command_register("bond/show", bond_unixctl_show, NULL);
3189     unixctl_command_register("bond/migrate", bond_unixctl_migrate, NULL);
3190     unixctl_command_register("bond/set-active-slave",
3191                              bond_unixctl_set_active_slave, NULL);
3192     unixctl_command_register("bond/enable-slave", bond_unixctl_enable_slave,
3193                              NULL);
3194     unixctl_command_register("bond/disable-slave", bond_unixctl_disable_slave,
3195                              NULL);
3196     unixctl_command_register("bond/hash", bond_unixctl_hash, NULL);
3197 }
3198 \f
3199 /* Port functions. */
3200
3201 static struct port *
3202 port_create(struct bridge *br, const char *name)
3203 {
3204     struct port *port;
3205
3206     port = xzalloc(sizeof *port);
3207     port->bridge = br;
3208     port->port_idx = br->n_ports;
3209     port->vlan = -1;
3210     port->trunks = NULL;
3211     port->name = xstrdup(name);
3212     port->active_iface = -1;
3213
3214     if (br->n_ports >= br->allocated_ports) {
3215         br->ports = x2nrealloc(br->ports, &br->allocated_ports,
3216                                sizeof *br->ports);
3217     }
3218     br->ports[br->n_ports++] = port;
3219     shash_add_assert(&br->port_by_name, port->name, port);
3220
3221     VLOG_INFO("created port %s on bridge %s", port->name, br->name);
3222     bridge_flush(br);
3223
3224     return port;
3225 }
3226
3227 static const char *
3228 get_port_other_config(const struct ovsrec_port *port, const char *key,
3229                       const char *default_value)
3230 {
3231     const char *value;
3232
3233     value = get_ovsrec_key_value(&port->header_, &ovsrec_port_col_other_config,
3234                                  key);
3235     return value ? value : default_value;
3236 }
3237
3238 static void
3239 port_del_ifaces(struct port *port, const struct ovsrec_port *cfg)
3240 {
3241     struct shash new_ifaces;
3242     size_t i;
3243
3244     /* Collect list of new interfaces. */
3245     shash_init(&new_ifaces);
3246     for (i = 0; i < cfg->n_interfaces; i++) {
3247         const char *name = cfg->interfaces[i]->name;
3248         shash_add_once(&new_ifaces, name, NULL);
3249     }
3250
3251     /* Get rid of deleted interfaces. */
3252     for (i = 0; i < port->n_ifaces; ) {
3253         if (!shash_find(&new_ifaces, cfg->interfaces[i]->name)) {
3254             iface_destroy(port->ifaces[i]);
3255         } else {
3256             i++;
3257         }
3258     }
3259
3260     shash_destroy(&new_ifaces);
3261 }
3262
3263 static void
3264 port_reconfigure(struct port *port, const struct ovsrec_port *cfg)
3265 {
3266     struct shash new_ifaces;
3267     long long int next_rebalance;
3268     unsigned long *trunks;
3269     int vlan;
3270     size_t i;
3271
3272     port->cfg = cfg;
3273
3274     /* Update settings. */
3275     port->updelay = cfg->bond_updelay;
3276     if (port->updelay < 0) {
3277         port->updelay = 0;
3278     }
3279     port->updelay = cfg->bond_downdelay;
3280     if (port->downdelay < 0) {
3281         port->downdelay = 0;
3282     }
3283     port->bond_rebalance_interval = atoi(
3284         get_port_other_config(cfg, "bond-rebalance-interval", "10000"));
3285     if (port->bond_rebalance_interval < 1000) {
3286         port->bond_rebalance_interval = 1000;
3287     }
3288     next_rebalance = time_msec() + port->bond_rebalance_interval;
3289     if (port->bond_next_rebalance > next_rebalance) {
3290         port->bond_next_rebalance = next_rebalance;
3291     }
3292
3293     /* Add new interfaces and update 'cfg' member of existing ones. */
3294     shash_init(&new_ifaces);
3295     for (i = 0; i < cfg->n_interfaces; i++) {
3296         const struct ovsrec_interface *if_cfg = cfg->interfaces[i];
3297         struct iface *iface;
3298
3299         if (!shash_add_once(&new_ifaces, if_cfg->name, NULL)) {
3300             VLOG_WARN("port %s: %s specified twice as port interface",
3301                       port->name, if_cfg->name);
3302             continue;
3303         }
3304
3305         iface = iface_lookup(port->bridge, if_cfg->name);
3306         if (iface) {
3307             if (iface->port != port) {
3308                 VLOG_ERR("bridge %s: %s interface is on multiple ports, "
3309                          "removing from %s",
3310                          port->bridge->name, if_cfg->name, iface->port->name);
3311                 continue;
3312             }
3313             iface->cfg = if_cfg;
3314         } else {
3315             iface_create(port, if_cfg);
3316         }
3317     }
3318     shash_destroy(&new_ifaces);
3319
3320     /* Get VLAN tag. */
3321     vlan = -1;
3322     if (cfg->tag) {
3323         if (port->n_ifaces < 2) {
3324             vlan = *cfg->tag;
3325             if (vlan >= 0 && vlan <= 4095) {
3326                 VLOG_DBG("port %s: assigning VLAN tag %d", port->name, vlan);
3327             } else {
3328                 vlan = -1;
3329             }
3330         } else {
3331             /* It's possible that bonded, VLAN-tagged ports make sense.  Maybe
3332              * they even work as-is.  But they have not been tested. */
3333             VLOG_WARN("port %s: VLAN tags not supported on bonded ports",
3334                       port->name);
3335         }
3336     }
3337     if (port->vlan != vlan) {
3338         port->vlan = vlan;
3339         bridge_flush(port->bridge);
3340     }
3341
3342     /* Get trunked VLANs. */
3343     trunks = NULL;
3344     if (vlan < 0 && cfg->n_trunks) {
3345         size_t n_errors;
3346         size_t i;
3347
3348         trunks = bitmap_allocate(4096);
3349         n_errors = 0;
3350         for (i = 0; i < cfg->n_trunks; i++) {
3351             int trunk = cfg->trunks[i];
3352             if (trunk >= 0) {
3353                 bitmap_set1(trunks, trunk);
3354             } else {
3355                 n_errors++;
3356             }
3357         }
3358         if (n_errors) {
3359             VLOG_ERR("port %s: invalid values for %zu trunk VLANs",
3360                      port->name, cfg->n_trunks);
3361         }
3362         if (n_errors == cfg->n_trunks) {
3363             VLOG_ERR("port %s: no valid trunks, trunking all VLANs",
3364                      port->name);
3365             bitmap_free(trunks);
3366             trunks = NULL;
3367         }
3368     } else if (vlan >= 0 && cfg->n_trunks) {
3369         VLOG_ERR("port %s: ignoring trunks in favor of implicit vlan",
3370                  port->name);
3371     }
3372     if (trunks == NULL
3373         ? port->trunks != NULL
3374         : port->trunks == NULL || !bitmap_equal(trunks, port->trunks, 4096)) {
3375         bridge_flush(port->bridge);
3376     }
3377     bitmap_free(port->trunks);
3378     port->trunks = trunks;
3379 }
3380
3381 static void
3382 port_destroy(struct port *port)
3383 {
3384     if (port) {
3385         struct bridge *br = port->bridge;
3386         struct port *del;
3387         int i;
3388
3389         proc_net_compat_update_vlan(port->name, NULL, 0);
3390         proc_net_compat_update_bond(port->name, NULL);
3391
3392         for (i = 0; i < MAX_MIRRORS; i++) {
3393             struct mirror *m = br->mirrors[i];
3394             if (m && m->out_port == port) {
3395                 mirror_destroy(m);
3396             }
3397         }
3398
3399         while (port->n_ifaces > 0) {
3400             iface_destroy(port->ifaces[port->n_ifaces - 1]);
3401         }
3402
3403         shash_find_and_delete_assert(&br->port_by_name, port->name);
3404
3405         del = br->ports[port->port_idx] = br->ports[--br->n_ports];
3406         del->port_idx = port->port_idx;
3407
3408         free(port->ifaces);
3409         bitmap_free(port->trunks);
3410         free(port->name);
3411         free(port);
3412         bridge_flush(br);
3413     }
3414 }
3415
3416 static struct port *
3417 port_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
3418 {
3419     struct iface *iface = iface_from_dp_ifidx(br, dp_ifidx);
3420     return iface ? iface->port : NULL;
3421 }
3422
3423 static struct port *
3424 port_lookup(const struct bridge *br, const char *name)
3425 {
3426     return shash_find_data(&br->port_by_name, name);
3427 }
3428
3429 static struct iface *
3430 port_lookup_iface(const struct port *port, const char *name)
3431 {
3432     struct iface *iface = iface_lookup(port->bridge, name);
3433     return iface && iface->port == port ? iface : NULL;
3434 }
3435
3436 static void
3437 port_update_bonding(struct port *port)
3438 {
3439     if (port->n_ifaces < 2) {
3440         /* Not a bonded port. */
3441         if (port->bond_hash) {
3442             free(port->bond_hash);
3443             port->bond_hash = NULL;
3444             port->bond_compat_is_stale = true;
3445             port->bond_fake_iface = false;
3446         }
3447     } else {
3448         if (!port->bond_hash) {
3449             size_t i;
3450
3451             port->bond_hash = xcalloc(BOND_MASK + 1, sizeof *port->bond_hash);
3452             for (i = 0; i <= BOND_MASK; i++) {
3453                 struct bond_entry *e = &port->bond_hash[i];
3454                 e->iface_idx = -1;
3455                 e->tx_bytes = 0;
3456             }
3457             port->no_ifaces_tag = tag_create_random();
3458             bond_choose_active_iface(port);
3459             port->bond_next_rebalance
3460                 = time_msec() + port->bond_rebalance_interval;
3461
3462             if (port->cfg->bond_fake_iface) {
3463                 port->bond_next_fake_iface_update = time_msec();
3464             }
3465         }
3466         port->bond_compat_is_stale = true;
3467         port->bond_fake_iface = port->cfg->bond_fake_iface;
3468     }
3469 }
3470
3471 static void
3472 port_update_bond_compat(struct port *port)
3473 {
3474     struct compat_bond_hash compat_hashes[BOND_MASK + 1];
3475     struct compat_bond bond;
3476     size_t i;
3477
3478     if (port->n_ifaces < 2) {
3479         proc_net_compat_update_bond(port->name, NULL);
3480         return;
3481     }
3482
3483     bond.up = false;
3484     bond.updelay = port->updelay;
3485     bond.downdelay = port->downdelay;
3486
3487     bond.n_hashes = 0;
3488     bond.hashes = compat_hashes;
3489     if (port->bond_hash) {
3490         const struct bond_entry *e;
3491         for (e = port->bond_hash; e <= &port->bond_hash[BOND_MASK]; e++) {
3492             if (e->iface_idx >= 0 && e->iface_idx < port->n_ifaces) {
3493                 struct compat_bond_hash *cbh = &bond.hashes[bond.n_hashes++];
3494                 cbh->hash = e - port->bond_hash;
3495                 cbh->netdev_name = port->ifaces[e->iface_idx]->name;
3496             }
3497         }
3498     }
3499
3500     bond.n_slaves = port->n_ifaces;
3501     bond.slaves = xmalloc(port->n_ifaces * sizeof *bond.slaves);
3502     for (i = 0; i < port->n_ifaces; i++) {
3503         struct iface *iface = port->ifaces[i];
3504         struct compat_bond_slave *slave = &bond.slaves[i];
3505         slave->name = iface->name;
3506
3507         /* We need to make the same determination as the Linux bonding
3508          * code to determine whether a slave should be consider "up".
3509          * The Linux function bond_miimon_inspect() supports four 
3510          * BOND_LINK_* states:
3511          *      
3512          *    - BOND_LINK_UP: carrier detected, updelay has passed.
3513          *    - BOND_LINK_FAIL: carrier lost, downdelay in progress.
3514          *    - BOND_LINK_DOWN: carrier lost, downdelay has passed.
3515          *    - BOND_LINK_BACK: carrier detected, updelay in progress.
3516          *
3517          * The function bond_info_show_slave() only considers BOND_LINK_UP 
3518          * to be "up" and anything else to be "down".
3519          */
3520         slave->up = iface->enabled && iface->delay_expires == LLONG_MAX;
3521         if (slave->up) {
3522             bond.up = true;
3523         }
3524         netdev_get_etheraddr(iface->netdev, slave->mac);
3525     }
3526
3527     if (port->bond_fake_iface) {
3528         struct netdev *bond_netdev;
3529
3530         if (!netdev_open_default(port->name, &bond_netdev)) {
3531             if (bond.up) {
3532                 netdev_turn_flags_on(bond_netdev, NETDEV_UP, true);
3533             } else {
3534                 netdev_turn_flags_off(bond_netdev, NETDEV_UP, true);
3535             }
3536             netdev_close(bond_netdev);
3537         }
3538     }
3539
3540     proc_net_compat_update_bond(port->name, &bond);
3541     free(bond.slaves);
3542 }
3543
3544 static void
3545 port_update_vlan_compat(struct port *port)
3546 {
3547     struct bridge *br = port->bridge;
3548     char *vlandev_name = NULL;
3549
3550     if (port->vlan > 0) {
3551         /* Figure out the name that the VLAN device should actually have, if it
3552          * existed.  This takes some work because the VLAN device would not
3553          * have port->name in its name; rather, it would have the trunk port's
3554          * name, and 'port' would be attached to a bridge that also had the
3555          * VLAN device one of its ports.  So we need to find a trunk port that
3556          * includes port->vlan.
3557          *
3558          * There might be more than one candidate.  This doesn't happen on
3559          * XenServer, so if it happens we just pick the first choice in
3560          * alphabetical order instead of creating multiple VLAN devices. */
3561         size_t i;
3562         for (i = 0; i < br->n_ports; i++) {
3563             struct port *p = br->ports[i];
3564             if (port_trunks_vlan(p, port->vlan)
3565                 && p->n_ifaces
3566                 && (!vlandev_name || strcmp(p->name, vlandev_name) <= 0))
3567             {
3568                 uint8_t ea[ETH_ADDR_LEN];
3569                 netdev_get_etheraddr(p->ifaces[0]->netdev, ea);
3570                 if (!eth_addr_is_multicast(ea) &&
3571                     !eth_addr_is_reserved(ea) &&
3572                     !eth_addr_is_zero(ea)) {
3573                     vlandev_name = p->name;
3574                 }
3575             }
3576         }
3577     }
3578     proc_net_compat_update_vlan(port->name, vlandev_name, port->vlan);
3579 }
3580 \f
3581 /* Interface functions. */
3582
3583 static struct iface *
3584 iface_create(struct port *port, const struct ovsrec_interface *if_cfg)
3585 {
3586     struct bridge *br = port->bridge;
3587     struct iface *iface;
3588     char *name = if_cfg->name;
3589     int error;
3590
3591     iface = xzalloc(sizeof *iface);
3592     iface->port = port;
3593     iface->port_ifidx = port->n_ifaces;
3594     iface->name = xstrdup(name);
3595     iface->dp_ifidx = -1;
3596     iface->tag = tag_create_random();
3597     iface->delay_expires = LLONG_MAX;
3598     iface->netdev = NULL;
3599     iface->cfg = if_cfg;
3600
3601     shash_add_assert(&br->iface_by_name, iface->name, iface);
3602
3603     /* Attempt to create the network interface in case it doesn't exist yet. */
3604     if (!iface_is_internal(br, iface->name)) {
3605         error = set_up_iface(if_cfg, iface, true);
3606         if (error) {
3607             VLOG_WARN("could not create iface %s: %s", iface->name,
3608                       strerror(error));
3609
3610             shash_find_and_delete_assert(&br->iface_by_name, iface->name);
3611             free(iface->name);
3612             free(iface);
3613             return NULL;
3614         }
3615     }
3616
3617     if (port->n_ifaces >= port->allocated_ifaces) {
3618         port->ifaces = x2nrealloc(port->ifaces, &port->allocated_ifaces,
3619                                   sizeof *port->ifaces);
3620     }
3621     port->ifaces[port->n_ifaces++] = iface;
3622     if (port->n_ifaces > 1) {
3623         br->has_bonded_ports = true;
3624     }
3625
3626     VLOG_DBG("attached network device %s to port %s", iface->name, port->name);
3627
3628     bridge_flush(br);
3629
3630     return iface;
3631 }
3632
3633 static void
3634 iface_destroy(struct iface *iface)
3635 {
3636     if (iface) {
3637         struct port *port = iface->port;
3638         struct bridge *br = port->bridge;
3639         bool del_active = port->active_iface == iface->port_ifidx;
3640         struct iface *del;
3641
3642         shash_find_and_delete_assert(&br->iface_by_name, iface->name);
3643
3644         if (iface->dp_ifidx >= 0) {
3645             port_array_set(&br->ifaces, iface->dp_ifidx, NULL);
3646         }
3647
3648         del = port->ifaces[iface->port_ifidx] = port->ifaces[--port->n_ifaces];
3649         del->port_ifidx = iface->port_ifidx;
3650
3651         netdev_close(iface->netdev);
3652
3653         if (del_active) {
3654             ofproto_revalidate(port->bridge->ofproto, port->active_iface_tag);
3655             bond_choose_active_iface(port);
3656             bond_send_learning_packets(port);
3657         }
3658
3659         free(iface->name);
3660         free(iface);
3661
3662         bridge_flush(port->bridge);
3663     }
3664 }
3665
3666 static struct iface *
3667 iface_lookup(const struct bridge *br, const char *name)
3668 {
3669     return shash_find_data(&br->iface_by_name, name);
3670 }
3671
3672 static struct iface *
3673 iface_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
3674 {
3675     return port_array_get(&br->ifaces, dp_ifidx);
3676 }
3677
3678 /* Returns true if 'iface' is the name of an "internal" interface on bridge
3679  * 'br', that is, an interface that is entirely simulated within the datapath.
3680  * The local port (ODPP_LOCAL) is always an internal interface.  Other local
3681  * interfaces are created by setting "iface.<iface>.internal = true".
3682  *
3683  * In addition, we have a kluge-y feature that creates an internal port with
3684  * the name of a bonded port if "bonding.<bondname>.fake-iface = true" is set.
3685  * This feature needs to go away in the long term.  Until then, this is one
3686  * reason why this function takes a name instead of a struct iface: the fake
3687  * interfaces created this way do not have a struct iface. */
3688 static bool
3689 iface_is_internal(const struct bridge *br, const char *if_name)
3690 {
3691     struct iface *iface;
3692     struct port *port;
3693
3694     if (!strcmp(if_name, br->name)) {
3695         return true;
3696     }
3697
3698     iface = iface_lookup(br, if_name);
3699     if (iface && !strcmp(iface->cfg->type, "internal")) {
3700         return true;
3701     }
3702
3703     port = port_lookup(br, if_name);
3704     if (port && port->n_ifaces > 1 && port->cfg->bond_fake_iface) {
3705         return true;
3706     }
3707     return false;
3708 }
3709
3710 /* Set Ethernet address of 'iface', if one is specified in the configuration
3711  * file. */
3712 static void
3713 iface_set_mac(struct iface *iface)
3714 {
3715     uint8_t ea[ETH_ADDR_LEN];
3716
3717     if (iface->cfg->mac && eth_addr_from_string(iface->cfg->mac, ea)) {
3718         if (eth_addr_is_multicast(ea)) {
3719             VLOG_ERR("interface %s: cannot set MAC to multicast address",
3720                      iface->name);
3721         } else if (iface->dp_ifidx == ODPP_LOCAL) {
3722             VLOG_ERR("ignoring iface.%s.mac; use bridge.%s.mac instead",
3723                      iface->name, iface->name);
3724         } else {
3725             int error = netdev_set_etheraddr(iface->netdev, ea);
3726             if (error) {
3727                 VLOG_ERR("interface %s: setting MAC failed (%s)",
3728                          iface->name, strerror(error));
3729             }
3730         }
3731     }
3732 }
3733
3734 static void
3735 shash_from_ovs_idl_map(char **keys, char **values, size_t n,
3736                        struct shash *shash)
3737 {
3738     size_t i;
3739
3740     shash_init(shash);
3741     for (i = 0; i < n; i++) {
3742         shash_add(shash, keys[i], values[i]);
3743     }
3744 }
3745
3746 struct iface_delete_queues_cbdata {
3747     struct netdev *netdev;
3748     const struct ovsdb_datum *queues;
3749 };
3750
3751 static bool
3752 queue_ids_include(const struct ovsdb_datum *queues, int64_t target)
3753 {
3754     union ovsdb_atom atom;
3755
3756     atom.integer = target;
3757     return ovsdb_datum_find_key(queues, &atom, OVSDB_TYPE_INTEGER) != UINT_MAX;
3758 }
3759
3760 static void
3761 iface_delete_queues(unsigned int queue_id,
3762                     const struct shash *details OVS_UNUSED, void *cbdata_)
3763 {
3764     struct iface_delete_queues_cbdata *cbdata = cbdata_;
3765
3766     if (!queue_ids_include(cbdata->queues, queue_id)) {
3767         netdev_delete_queue(cbdata->netdev, queue_id);
3768     }
3769 }
3770
3771 static void
3772 iface_update_qos(struct iface *iface, const struct ovsrec_qos *qos)
3773 {
3774     if (!qos || qos->type[0] == '\0') {
3775         netdev_set_qos(iface->netdev, NULL, NULL);
3776     } else {
3777         struct iface_delete_queues_cbdata cbdata;
3778         struct shash details;
3779         size_t i;
3780
3781         /* Configure top-level Qos for 'iface'. */
3782         shash_from_ovs_idl_map(qos->key_other_config, qos->value_other_config,
3783                                qos->n_other_config, &details);
3784         netdev_set_qos(iface->netdev, qos->type, &details);
3785         shash_destroy(&details);
3786
3787         /* Deconfigure queues that were deleted. */
3788         cbdata.netdev = iface->netdev;
3789         cbdata.queues = ovsrec_qos_get_queues(qos, OVSDB_TYPE_INTEGER,
3790                                               OVSDB_TYPE_UUID);
3791         netdev_dump_queues(iface->netdev, iface_delete_queues, &cbdata);
3792
3793         /* Configure queues for 'iface'. */
3794         for (i = 0; i < qos->n_queues; i++) {
3795             const struct ovsrec_queue *queue = qos->value_queues[i];
3796             unsigned int queue_id = qos->key_queues[i];
3797
3798             shash_from_ovs_idl_map(queue->key_other_config,
3799                                    queue->value_other_config,
3800                                    queue->n_other_config, &details);
3801             netdev_set_queue(iface->netdev, queue_id, &details);
3802             shash_destroy(&details);
3803         }
3804     }
3805 }
3806 \f
3807 /* Port mirroring. */
3808
3809 static struct mirror *
3810 mirror_find_by_uuid(struct bridge *br, const struct uuid *uuid)
3811 {
3812     int i;
3813
3814     for (i = 0; i < MAX_MIRRORS; i++) {
3815         struct mirror *m = br->mirrors[i];
3816         if (m && uuid_equals(uuid, &m->uuid)) {
3817             return m;
3818         }
3819     }
3820     return NULL;
3821 }
3822
3823 static void
3824 mirror_reconfigure(struct bridge *br)
3825 {
3826     unsigned long *rspan_vlans;
3827     int i;
3828
3829     /* Get rid of deleted mirrors. */
3830     for (i = 0; i < MAX_MIRRORS; i++) {
3831         struct mirror *m = br->mirrors[i];
3832         if (m) {
3833             const struct ovsdb_datum *mc;
3834             union ovsdb_atom atom;
3835
3836             mc = ovsrec_bridge_get_mirrors(br->cfg, OVSDB_TYPE_UUID);
3837             atom.uuid = br->mirrors[i]->uuid;
3838             if (ovsdb_datum_find_key(mc, &atom, OVSDB_TYPE_UUID) == UINT_MAX) {
3839                 mirror_destroy(m);
3840             }
3841         }
3842     }
3843
3844     /* Add new mirrors and reconfigure existing ones. */
3845     for (i = 0; i < br->cfg->n_mirrors; i++) {
3846         struct ovsrec_mirror *cfg = br->cfg->mirrors[i];
3847         struct mirror *m = mirror_find_by_uuid(br, &cfg->header_.uuid);
3848         if (m) {
3849             mirror_reconfigure_one(m, cfg);
3850         } else {
3851             mirror_create(br, cfg);
3852         }
3853     }
3854
3855     /* Update port reserved status. */
3856     for (i = 0; i < br->n_ports; i++) {
3857         br->ports[i]->is_mirror_output_port = false;
3858     }
3859     for (i = 0; i < MAX_MIRRORS; i++) {
3860         struct mirror *m = br->mirrors[i];
3861         if (m && m->out_port) {
3862             m->out_port->is_mirror_output_port = true;
3863         }
3864     }
3865
3866     /* Update flooded vlans (for RSPAN). */
3867     rspan_vlans = NULL;
3868     if (br->cfg->n_flood_vlans) {
3869         rspan_vlans = bitmap_allocate(4096);
3870
3871         for (i = 0; i < br->cfg->n_flood_vlans; i++) {
3872             int64_t vlan = br->cfg->flood_vlans[i];
3873             if (vlan >= 0 && vlan < 4096) {
3874                 bitmap_set1(rspan_vlans, vlan);
3875                 VLOG_INFO("bridge %s: disabling learning on vlan %"PRId64,
3876                           br->name, vlan);
3877             } else {
3878                 VLOG_ERR("bridge %s: invalid value %"PRId64 "for flood VLAN",
3879                          br->name, vlan);
3880             }
3881         }
3882     }
3883     if (mac_learning_set_flood_vlans(br->ml, rspan_vlans)) {
3884         bridge_flush(br);
3885     }
3886 }
3887
3888 static void
3889 mirror_create(struct bridge *br, struct ovsrec_mirror *cfg)
3890 {
3891     struct mirror *m;
3892     size_t i;
3893
3894     for (i = 0; ; i++) {
3895         if (i >= MAX_MIRRORS) {
3896             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
3897                       "cannot create %s", br->name, MAX_MIRRORS, cfg->name);
3898             return;
3899         }
3900         if (!br->mirrors[i]) {
3901             break;
3902         }
3903     }
3904
3905     VLOG_INFO("created port mirror %s on bridge %s", cfg->name, br->name);
3906     bridge_flush(br);
3907
3908     br->mirrors[i] = m = xzalloc(sizeof *m);
3909     m->bridge = br;
3910     m->idx = i;
3911     m->name = xstrdup(cfg->name);
3912     shash_init(&m->src_ports);
3913     shash_init(&m->dst_ports);
3914     m->vlans = NULL;
3915     m->n_vlans = 0;
3916     m->out_vlan = -1;
3917     m->out_port = NULL;
3918
3919     mirror_reconfigure_one(m, cfg);
3920 }
3921
3922 static void
3923 mirror_destroy(struct mirror *m)
3924 {
3925     if (m) {
3926         struct bridge *br = m->bridge;
3927         size_t i;
3928
3929         for (i = 0; i < br->n_ports; i++) {
3930             br->ports[i]->src_mirrors &= ~(MIRROR_MASK_C(1) << m->idx);
3931             br->ports[i]->dst_mirrors &= ~(MIRROR_MASK_C(1) << m->idx);
3932         }
3933
3934         shash_destroy(&m->src_ports);
3935         shash_destroy(&m->dst_ports);
3936         free(m->vlans);
3937
3938         m->bridge->mirrors[m->idx] = NULL;
3939         free(m->name);
3940         free(m);
3941
3942         bridge_flush(br);
3943     }
3944 }
3945
3946 static void
3947 mirror_collect_ports(struct mirror *m, struct ovsrec_port **ports, int n_ports,
3948                      struct shash *names)
3949 {
3950     size_t i;
3951
3952     for (i = 0; i < n_ports; i++) {
3953         const char *name = ports[i]->name;
3954         if (port_lookup(m->bridge, name)) {
3955             shash_add_once(names, name, NULL);
3956         } else {
3957             VLOG_WARN("bridge %s: mirror %s cannot match on nonexistent "
3958                       "port %s", m->bridge->name, m->name, name);
3959         }
3960     }
3961 }
3962
3963 static size_t
3964 mirror_collect_vlans(struct mirror *m, const struct ovsrec_mirror *cfg,
3965                      int **vlans)
3966 {
3967     size_t n_vlans;
3968     size_t i;
3969
3970     *vlans = xmalloc(sizeof **vlans * cfg->n_select_vlan);
3971     n_vlans = 0;
3972     for (i = 0; i < cfg->n_select_vlan; i++) {
3973         int64_t vlan = cfg->select_vlan[i];
3974         if (vlan < 0 || vlan > 4095) {
3975             VLOG_WARN("bridge %s: mirror %s selects invalid VLAN %"PRId64,
3976                       m->bridge->name, m->name, vlan);
3977         } else {
3978             (*vlans)[n_vlans++] = vlan;
3979         }
3980     }
3981     return n_vlans;
3982 }
3983
3984 static bool
3985 vlan_is_mirrored(const struct mirror *m, int vlan)
3986 {
3987     size_t i;
3988
3989     for (i = 0; i < m->n_vlans; i++) {
3990         if (m->vlans[i] == vlan) {
3991             return true;
3992         }
3993     }
3994     return false;
3995 }
3996
3997 static bool
3998 port_trunks_any_mirrored_vlan(const struct mirror *m, const struct port *p)
3999 {
4000     size_t i;
4001
4002     for (i = 0; i < m->n_vlans; i++) {
4003         if (port_trunks_vlan(p, m->vlans[i])) {
4004             return true;
4005         }
4006     }
4007     return false;
4008 }
4009
4010 static void
4011 mirror_reconfigure_one(struct mirror *m, struct ovsrec_mirror *cfg)
4012 {
4013     struct shash src_ports, dst_ports;
4014     mirror_mask_t mirror_bit;
4015     struct port *out_port;
4016     int out_vlan;
4017     size_t n_vlans;
4018     int *vlans;
4019     size_t i;
4020
4021     /* Set name. */
4022     if (strcmp(cfg->name, m->name)) {
4023         free(m->name);
4024         m->name = xstrdup(cfg->name);
4025     }
4026
4027     /* Get output port. */
4028     if (cfg->output_port) {
4029         out_port = port_lookup(m->bridge, cfg->output_port->name);
4030         if (!out_port) {
4031             VLOG_ERR("bridge %s: mirror %s outputs to port not on bridge",
4032                      m->bridge->name, m->name);
4033             mirror_destroy(m);
4034             return;
4035         }
4036         out_vlan = -1;
4037
4038         if (cfg->output_vlan) {
4039             VLOG_ERR("bridge %s: mirror %s specifies both output port and "
4040                      "output vlan; ignoring output vlan",
4041                      m->bridge->name, m->name);
4042         }
4043     } else if (cfg->output_vlan) {
4044         out_port = NULL;
4045         out_vlan = *cfg->output_vlan;
4046     } else {
4047         VLOG_ERR("bridge %s: mirror %s does not specify output; ignoring",
4048                  m->bridge->name, m->name);
4049         mirror_destroy(m);
4050         return;
4051     }
4052
4053     shash_init(&src_ports);
4054     shash_init(&dst_ports);
4055     if (cfg->select_all) {
4056         for (i = 0; i < m->bridge->n_ports; i++) {
4057             const char *name = m->bridge->ports[i]->name;
4058             shash_add_once(&src_ports, name, NULL);
4059             shash_add_once(&dst_ports, name, NULL);
4060         }
4061         vlans = NULL;
4062         n_vlans = 0;
4063     } else {
4064         /* Get ports, and drop duplicates and ports that don't exist. */
4065         mirror_collect_ports(m, cfg->select_src_port, cfg->n_select_src_port,
4066                              &src_ports);
4067         mirror_collect_ports(m, cfg->select_dst_port, cfg->n_select_dst_port,
4068                              &dst_ports);
4069
4070         /* Get all the vlans, and drop duplicate and invalid vlans. */
4071         n_vlans = mirror_collect_vlans(m, cfg, &vlans);
4072     }
4073
4074     /* Update mirror data. */
4075     if (!shash_equal_keys(&m->src_ports, &src_ports)
4076         || !shash_equal_keys(&m->dst_ports, &dst_ports)
4077         || m->n_vlans != n_vlans
4078         || memcmp(m->vlans, vlans, sizeof *vlans * n_vlans)
4079         || m->out_port != out_port
4080         || m->out_vlan != out_vlan) {
4081         bridge_flush(m->bridge);
4082     }
4083     shash_swap(&m->src_ports, &src_ports);
4084     shash_swap(&m->dst_ports, &dst_ports);
4085     free(m->vlans);
4086     m->vlans = vlans;
4087     m->n_vlans = n_vlans;
4088     m->out_port = out_port;
4089     m->out_vlan = out_vlan;
4090
4091     /* Update ports. */
4092     mirror_bit = MIRROR_MASK_C(1) << m->idx;
4093     for (i = 0; i < m->bridge->n_ports; i++) {
4094         struct port *port = m->bridge->ports[i];
4095
4096         if (shash_find(&m->src_ports, port->name)
4097             || (m->n_vlans
4098                 && (!port->vlan
4099                     ? port_trunks_any_mirrored_vlan(m, port)
4100                     : vlan_is_mirrored(m, port->vlan)))) {
4101             port->src_mirrors |= mirror_bit;
4102         } else {
4103             port->src_mirrors &= ~mirror_bit;
4104         }
4105
4106         if (shash_find(&m->dst_ports, port->name)) {
4107             port->dst_mirrors |= mirror_bit;
4108         } else {
4109             port->dst_mirrors &= ~mirror_bit;
4110         }
4111     }
4112
4113     /* Clean up. */
4114     shash_destroy(&src_ports);
4115     shash_destroy(&dst_ports);
4116 }