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