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