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