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