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