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