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