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