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