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