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