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