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