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