001f9f68dcd3c71321d46a138119802fabac7f06
[sliver-openvswitch.git] / vswitchd / bridge.c
1 /* Copyright (c) 2008, 2009, 2010, 2011 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 "byte-order.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <arpa/inet.h>
22 #include <ctype.h>
23 #include <inttypes.h>
24 #include <sys/socket.h>
25 #include <net/if.h>
26 #include <openflow/openflow.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <strings.h>
30 #include <sys/stat.h>
31 #include <sys/socket.h>
32 #include <sys/types.h>
33 #include <unistd.h>
34 #include "bitmap.h"
35 #include "cfm.h"
36 #include "classifier.h"
37 #include "coverage.h"
38 #include "daemon.h"
39 #include "dirs.h"
40 #include "dpif.h"
41 #include "dynamic-string.h"
42 #include "flow.h"
43 #include "hash.h"
44 #include "hmap.h"
45 #include "jsonrpc.h"
46 #include "lacp.h"
47 #include "list.h"
48 #include "mac-learning.h"
49 #include "netdev.h"
50 #include "netlink.h"
51 #include "odp-util.h"
52 #include "ofp-print.h"
53 #include "ofpbuf.h"
54 #include "ofproto/netflow.h"
55 #include "ofproto/ofproto.h"
56 #include "ovsdb-data.h"
57 #include "packets.h"
58 #include "poll-loop.h"
59 #include "process.h"
60 #include "sha1.h"
61 #include "shash.h"
62 #include "socket-util.h"
63 #include "stream-ssl.h"
64 #include "sset.h"
65 #include "svec.h"
66 #include "system-stats.h"
67 #include "timeval.h"
68 #include "util.h"
69 #include "unixctl.h"
70 #include "vconn.h"
71 #include "vswitchd/vswitch-idl.h"
72 #include "xenserver.h"
73 #include "vlog.h"
74 #include "sflow_api.h"
75
76 VLOG_DEFINE_THIS_MODULE(bridge);
77
78 COVERAGE_DEFINE(bridge_flush);
79 COVERAGE_DEFINE(bridge_process_flow);
80 COVERAGE_DEFINE(bridge_process_cfm);
81 COVERAGE_DEFINE(bridge_process_lacp);
82 COVERAGE_DEFINE(bridge_reconfigure);
83 COVERAGE_DEFINE(bridge_lacp_update);
84
85 struct dst {
86     uint16_t vlan;
87     uint16_t dp_ifidx;
88 };
89
90 struct dst_set {
91     struct dst builtin[32];
92     struct dst *dsts;
93     size_t n, allocated;
94 };
95
96 static void dst_set_init(struct dst_set *);
97 static void dst_set_add(struct dst_set *, const struct dst *);
98 static void dst_set_free(struct dst_set *);
99
100 struct iface {
101     /* These members are always valid. */
102     struct list port_elem;      /* Element in struct port's "ifaces" list. */
103     struct port *port;          /* Containing port. */
104     char *name;                 /* Host network device name. */
105     tag_type tag;               /* Tag associated with this interface. */
106     long long delay_expires;    /* Time after which 'enabled' may change. */
107
108     /* These members are valid only after bridge_reconfigure() causes them to
109      * be initialized. */
110     struct hmap_node dp_ifidx_node; /* In struct bridge's "ifaces" hmap. */
111     int dp_ifidx;               /* Index within kernel datapath. */
112     struct netdev *netdev;      /* Network device. */
113     bool enabled;               /* May be chosen for flows? */
114     bool up;                    /* Is the interface up? */
115     const char *type;           /* Usually same as cfg->type. */
116     const struct ovsrec_interface *cfg;
117
118     /* LACP information. */
119     uint16_t lacp_priority;     /* LACP port priority. */
120 };
121
122 #define BOND_MASK 0xff
123 struct bond_entry {
124     struct iface *iface;        /* Assigned iface, or NULL if none. */
125     uint64_t tx_bytes;          /* Count of bytes recently transmitted. */
126     tag_type tag;               /* Tag for bond_entry<->iface association. */
127 };
128
129 enum bond_mode {
130     BM_TCP, /* Transport Layer Load Balance. */
131     BM_SLB, /* Source Load Balance. */
132     BM_AB   /* Active Backup. */
133 };
134
135 #define MAX_MIRRORS 32
136 typedef uint32_t mirror_mask_t;
137 #define MIRROR_MASK_C(X) UINT32_C(X)
138 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
139 struct mirror {
140     struct bridge *bridge;
141     size_t idx;
142     char *name;
143     struct uuid uuid;           /* UUID of this "mirror" record in database. */
144
145     /* Selection criteria. */
146     struct sset src_ports;      /* Source port names. */
147     struct sset dst_ports;      /* Destination port names. */
148     int *vlans;
149     size_t n_vlans;
150
151     /* Output. */
152     struct port *out_port;
153     int out_vlan;
154 };
155
156 #define FLOOD_PORT ((struct port *) 1) /* The 'flood' output port. */
157 struct port {
158     struct bridge *bridge;
159     struct hmap_node hmap_node; /* Element in struct bridge's "ports" hmap. */
160     char *name;
161
162     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
163     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
164                                  * NULL if all VLANs are trunked. */
165     const struct ovsrec_port *cfg;
166
167     /* Monitoring. */
168     struct netdev_monitor *monitor;   /* Tracks carrier. NULL if miimon. */
169     long long int miimon_interval;    /* Miimon status refresh interval. */
170     long long int miimon_next_update; /* Time of next miimon update. */
171
172     /* An ordinary bridge port has 1 interface.
173      * A bridge port for bonding has at least 2 interfaces. */
174     struct list ifaces;         /* List of "struct iface"s. */
175     size_t n_ifaces;            /* list_size(ifaces). */
176
177     /* Bonding info. */
178     enum bond_mode bond_mode;   /* Type of the bond. BM_SLB is the default. */
179     struct iface *active_iface; /* iface on which bcasts accepted, or NULL. */
180     tag_type no_ifaces_tag;     /* Tag for flows when all ifaces disabled. */
181     int updelay, downdelay;     /* Delay before iface goes up/down, in ms. */
182     bool bond_fake_iface;       /* Fake a bond interface for legacy compat? */
183     long long int bond_next_fake_iface_update; /* Time of next update. */
184
185     /* LACP information. */
186     struct lacp *lacp;          /* LACP object. NULL if LACP is disabled. */
187     bool lacp_active;           /* True if LACP is active */
188     bool lacp_fast;             /* True if LACP is in fast mode. */
189     uint16_t lacp_priority;     /* LACP system priority. */
190
191     /* SLB specific bonding info. */
192     struct bond_entry *bond_hash; /* An array of (BOND_MASK + 1) elements. */
193     int bond_rebalance_interval; /* Interval between rebalances, in ms. */
194     long long int bond_next_rebalance; /* Next rebalancing time. */
195
196     /* Port mirroring info. */
197     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
198     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
199     bool is_mirror_output_port; /* Does port mirroring send frames here? */
200 };
201
202 struct bridge {
203     struct list node;           /* Node in global list of bridges. */
204     char *name;                 /* User-specified arbitrary name. */
205     struct mac_learning *ml;    /* MAC learning table. */
206     uint8_t ea[ETH_ADDR_LEN];   /* Bridge Ethernet Address. */
207     uint8_t default_ea[ETH_ADDR_LEN]; /* Default MAC. */
208     const struct ovsrec_bridge *cfg;
209
210     /* OpenFlow switch processing. */
211     struct ofproto *ofproto;    /* OpenFlow switch. */
212
213     /* Kernel datapath information. */
214     struct dpif *dpif;          /* Datapath. */
215     struct hmap ifaces;         /* Contains "struct iface"s. */
216
217     /* Bridge ports. */
218     struct hmap ports;          /* "struct port"s indexed by name. */
219     struct shash iface_by_name; /* "struct iface"s indexed by name. */
220
221     /* Bonding. */
222     bool has_bonded_ports;
223
224     /* Flow tracking. */
225     bool flush;
226
227     /* Port mirroring. */
228     struct mirror *mirrors[MAX_MIRRORS];
229 };
230
231 /* List of all bridges. */
232 static struct list all_bridges = LIST_INITIALIZER(&all_bridges);
233
234 /* OVSDB IDL used to obtain configuration. */
235 static struct ovsdb_idl *idl;
236
237 /* Each time this timer expires, the bridge fetches systems and interface
238  * statistics and pushes them into the database. */
239 #define STATS_INTERVAL (5 * 1000) /* In milliseconds. */
240 static long long int stats_timer = LLONG_MIN;
241
242 /* Stores the time after which CFM statistics may be written to the database.
243  * Only updated when changes to the database require rate limiting. */
244 #define CFM_LIMIT_INTERVAL (1 * 1000) /* In milliseconds. */
245 static long long int cfm_limiter = LLONG_MIN;
246
247 static struct bridge *bridge_create(const struct ovsrec_bridge *br_cfg);
248 static void bridge_destroy(struct bridge *);
249 static struct bridge *bridge_lookup(const char *name);
250 static unixctl_cb_func bridge_unixctl_dump_flows;
251 static unixctl_cb_func bridge_unixctl_reconnect;
252 static int bridge_run_one(struct bridge *);
253 static size_t bridge_get_controllers(const struct bridge *br,
254                                      struct ovsrec_controller ***controllersp);
255 static void bridge_reconfigure_one(struct bridge *);
256 static void bridge_reconfigure_remotes(struct bridge *,
257                                        const struct sockaddr_in *managers,
258                                        size_t n_managers);
259 static void bridge_get_all_ifaces(const struct bridge *, struct shash *ifaces);
260 static void bridge_fetch_dp_ifaces(struct bridge *);
261 static void bridge_flush(struct bridge *);
262 static void bridge_pick_local_hw_addr(struct bridge *,
263                                       uint8_t ea[ETH_ADDR_LEN],
264                                       struct iface **hw_addr_iface);
265 static uint64_t bridge_pick_datapath_id(struct bridge *,
266                                         const uint8_t bridge_ea[ETH_ADDR_LEN],
267                                         struct iface *hw_addr_iface);
268 static uint64_t dpid_from_hash(const void *, size_t nbytes);
269
270 static unixctl_cb_func bridge_unixctl_fdb_show;
271 static unixctl_cb_func cfm_unixctl_show;
272 static unixctl_cb_func qos_unixctl_show;
273
274 static void bond_init(void);
275 static void bond_run(struct port *);
276 static void bond_wait(struct port *);
277 static void bond_rebalance_port(struct port *);
278 static void bond_send_learning_packets(struct port *);
279 static void bond_enable_slave(struct iface *iface, bool enable);
280
281 static void port_run(struct port *);
282 static void port_wait(struct port *);
283 static struct port *port_create(struct bridge *, const char *name);
284 static void port_reconfigure(struct port *, const struct ovsrec_port *);
285 static void port_del_ifaces(struct port *, const struct ovsrec_port *);
286 static void port_destroy(struct port *);
287 static struct port *port_lookup(const struct bridge *, const char *name);
288 static struct iface *port_lookup_iface(const struct port *, const char *name);
289 static struct iface *port_get_an_iface(const struct port *);
290 static struct port *port_from_dp_ifidx(const struct bridge *,
291                                        uint16_t dp_ifidx);
292 static void port_update_bonding(struct port *);
293 static void port_update_lacp(struct port *);
294
295 static void mirror_create(struct bridge *, struct ovsrec_mirror *);
296 static void mirror_destroy(struct mirror *);
297 static void mirror_reconfigure(struct bridge *);
298 static void mirror_reconfigure_one(struct mirror *, struct ovsrec_mirror *);
299 static bool vlan_is_mirrored(const struct mirror *, int vlan);
300
301 static struct iface *iface_create(struct port *port,
302                                   const struct ovsrec_interface *if_cfg);
303 static void iface_destroy(struct iface *);
304 static struct iface *iface_lookup(const struct bridge *, const char *name);
305 static struct iface *iface_find(const char *name);
306 static struct iface *iface_from_dp_ifidx(const struct bridge *,
307                                          uint16_t dp_ifidx);
308 static void iface_set_mac(struct iface *);
309 static void iface_set_ofport(const struct ovsrec_interface *, int64_t ofport);
310 static void iface_update_qos(struct iface *, const struct ovsrec_qos *);
311 static void iface_update_cfm(struct iface *);
312 static bool iface_refresh_cfm_stats(struct iface *iface);
313 static void iface_update_carrier(struct iface *);
314 static bool iface_get_carrier(const struct iface *);
315
316 static void shash_from_ovs_idl_map(char **keys, char **values, size_t n,
317                                    struct shash *);
318 static void shash_to_ovs_idl_map(struct shash *,
319                                  char ***keys, char ***values, size_t *n);
320
321 /* Hooks into ofproto processing. */
322 static struct ofhooks bridge_ofhooks;
323 \f
324 /* Public functions. */
325
326 /* Initializes the bridge module, configuring it to obtain its configuration
327  * from an OVSDB server accessed over 'remote', which should be a string in a
328  * form acceptable to ovsdb_idl_create(). */
329 void
330 bridge_init(const char *remote)
331 {
332     /* Create connection to database. */
333     idl = ovsdb_idl_create(remote, &ovsrec_idl_class, true);
334
335     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_cur_cfg);
336     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_statistics);
337     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_external_ids);
338
339     ovsdb_idl_omit(idl, &ovsrec_bridge_col_external_ids);
340
341     ovsdb_idl_omit(idl, &ovsrec_port_col_external_ids);
342     ovsdb_idl_omit(idl, &ovsrec_port_col_fake_bridge);
343
344     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_ofport);
345     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_statistics);
346     ovsdb_idl_omit(idl, &ovsrec_interface_col_external_ids);
347
348     /* Register unixctl commands. */
349     unixctl_command_register("fdb/show", bridge_unixctl_fdb_show, NULL);
350     unixctl_command_register("cfm/show", cfm_unixctl_show, NULL);
351     unixctl_command_register("qos/show", qos_unixctl_show, NULL);
352     unixctl_command_register("bridge/dump-flows", bridge_unixctl_dump_flows,
353                              NULL);
354     unixctl_command_register("bridge/reconnect", bridge_unixctl_reconnect,
355                              NULL);
356     lacp_init();
357     bond_init();
358 }
359
360 void
361 bridge_exit(void)
362 {
363     struct bridge *br, *next_br;
364
365     LIST_FOR_EACH_SAFE (br, next_br, node, &all_bridges) {
366         bridge_destroy(br);
367     }
368     ovsdb_idl_destroy(idl);
369 }
370
371 /* Performs configuration that is only necessary once at ovs-vswitchd startup,
372  * but for which the ovs-vswitchd configuration 'cfg' is required. */
373 static void
374 bridge_configure_once(const struct ovsrec_open_vswitch *cfg)
375 {
376     static bool already_configured_once;
377     struct sset bridge_names;
378     struct sset dpif_names, dpif_types;
379     const char *type;
380     size_t i;
381
382     /* Only do this once per ovs-vswitchd run. */
383     if (already_configured_once) {
384         return;
385     }
386     already_configured_once = true;
387
388     stats_timer = time_msec() + STATS_INTERVAL;
389
390     /* Get all the configured bridges' names from 'cfg' into 'bridge_names'. */
391     sset_init(&bridge_names);
392     for (i = 0; i < cfg->n_bridges; i++) {
393         sset_add(&bridge_names, cfg->bridges[i]->name);
394     }
395
396     /* Iterate over all system dpifs and delete any of them that do not appear
397      * in 'cfg'. */
398     sset_init(&dpif_names);
399     sset_init(&dpif_types);
400     dp_enumerate_types(&dpif_types);
401     SSET_FOR_EACH (type, &dpif_types) {
402         const char *name;
403
404         dp_enumerate_names(type, &dpif_names);
405
406         /* Delete each dpif whose name is not in 'bridge_names'. */
407         SSET_FOR_EACH (name, &dpif_names) {
408             if (!sset_contains(&bridge_names, name)) {
409                 struct dpif *dpif;
410                 int retval;
411
412                 retval = dpif_open(name, type, &dpif);
413                 if (!retval) {
414                     dpif_delete(dpif);
415                     dpif_close(dpif);
416                 }
417             }
418         }
419     }
420     sset_destroy(&bridge_names);
421     sset_destroy(&dpif_names);
422     sset_destroy(&dpif_types);
423 }
424
425 /* Callback for iterate_and_prune_ifaces(). */
426 static bool
427 check_iface(struct bridge *br, struct iface *iface, void *aux OVS_UNUSED)
428 {
429     if (!iface->netdev) {
430         /* We already reported a related error, don't bother duplicating it. */
431         return false;
432     }
433
434     if (iface->dp_ifidx < 0) {
435         VLOG_ERR("%s interface not in %s, dropping",
436                  iface->name, dpif_name(br->dpif));
437         return false;
438     }
439
440     VLOG_DBG("%s has interface %s on port %d", dpif_name(br->dpif),
441              iface->name, iface->dp_ifidx);
442     return true;
443 }
444
445 /* Callback for iterate_and_prune_ifaces(). */
446 static bool
447 set_iface_properties(struct bridge *br OVS_UNUSED, struct iface *iface,
448                      void *aux OVS_UNUSED)
449 {
450     /* Set policing attributes. */
451     netdev_set_policing(iface->netdev,
452                         iface->cfg->ingress_policing_rate,
453                         iface->cfg->ingress_policing_burst);
454
455     /* Set MAC address of internal interfaces other than the local
456      * interface. */
457     if (iface->dp_ifidx != ODPP_LOCAL && !strcmp(iface->type, "internal")) {
458         iface_set_mac(iface);
459     }
460
461     return true;
462 }
463
464 /* Calls 'cb' for each interfaces in 'br', passing along the 'aux' argument.
465  * Deletes from 'br' all the interfaces for which 'cb' returns false, and then
466  * deletes from 'br' any ports that no longer have any interfaces. */
467 static void
468 iterate_and_prune_ifaces(struct bridge *br,
469                          bool (*cb)(struct bridge *, struct iface *,
470                                     void *aux),
471                          void *aux)
472 {
473     struct port *port, *next_port;
474
475     HMAP_FOR_EACH_SAFE (port, next_port, hmap_node, &br->ports) {
476         struct iface *iface, *next_iface;
477
478         LIST_FOR_EACH_SAFE (iface, next_iface, port_elem, &port->ifaces) {
479             if (!cb(br, iface, aux)) {
480                 iface_set_ofport(iface->cfg, -1);
481                 iface_destroy(iface);
482             }
483         }
484
485         if (!port->n_ifaces) {
486             VLOG_WARN("%s port has no interfaces, dropping", port->name);
487             port_destroy(port);
488         }
489     }
490 }
491
492 /* Looks at the list of managers in 'ovs_cfg' and extracts their remote IP
493  * addresses and ports into '*managersp' and '*n_managersp'.  The caller is
494  * responsible for freeing '*managersp' (with free()).
495  *
496  * You may be asking yourself "why does ovs-vswitchd care?", because
497  * ovsdb-server is responsible for connecting to the managers, and ovs-vswitchd
498  * should not be and in fact is not directly involved in that.  But
499  * ovs-vswitchd needs to make sure that ovsdb-server can reach the managers, so
500  * it has to tell in-band control where the managers are to enable that.
501  * (Thus, only managers connected in-band are collected.)
502  */
503 static void
504 collect_in_band_managers(const struct ovsrec_open_vswitch *ovs_cfg,
505                          struct sockaddr_in **managersp, size_t *n_managersp)
506 {
507     struct sockaddr_in *managers = NULL;
508     size_t n_managers = 0;
509     struct sset targets;
510     size_t i;
511
512     /* Collect all of the potential targets from the "targets" columns of the
513      * rows pointed to by "manager_options", excluding any that are
514      * out-of-band. */
515     sset_init(&targets);
516     for (i = 0; i < ovs_cfg->n_manager_options; i++) {
517         struct ovsrec_manager *m = ovs_cfg->manager_options[i];
518
519         if (m->connection_mode && !strcmp(m->connection_mode, "out-of-band")) {
520             sset_find_and_delete(&targets, m->target);
521         } else {
522             sset_add(&targets, m->target);
523         }
524     }
525
526     /* Now extract the targets' IP addresses. */
527     if (!sset_is_empty(&targets)) {
528         const char *target;
529
530         managers = xmalloc(sset_count(&targets) * sizeof *managers);
531         SSET_FOR_EACH (target, &targets) {
532             struct sockaddr_in *sin = &managers[n_managers];
533
534             if ((!strncmp(target, "tcp:", 4)
535                  && inet_parse_active(target + 4, JSONRPC_TCP_PORT, sin)) ||
536                 (!strncmp(target, "ssl:", 4)
537                  && inet_parse_active(target + 4, JSONRPC_SSL_PORT, sin))) {
538                 n_managers++;
539             }
540         }
541     }
542     sset_destroy(&targets);
543
544     *managersp = managers;
545     *n_managersp = n_managers;
546 }
547
548 static void
549 bridge_reconfigure(const struct ovsrec_open_vswitch *ovs_cfg)
550 {
551     struct shash old_br, new_br;
552     struct shash_node *node;
553     struct bridge *br, *next;
554     struct sockaddr_in *managers;
555     size_t n_managers;
556     size_t i;
557     int sflow_bridge_number;
558
559     COVERAGE_INC(bridge_reconfigure);
560
561     collect_in_band_managers(ovs_cfg, &managers, &n_managers);
562
563     /* Collect old and new bridges. */
564     shash_init(&old_br);
565     shash_init(&new_br);
566     LIST_FOR_EACH (br, node, &all_bridges) {
567         shash_add(&old_br, br->name, br);
568     }
569     for (i = 0; i < ovs_cfg->n_bridges; i++) {
570         const struct ovsrec_bridge *br_cfg = ovs_cfg->bridges[i];
571         if (!shash_add_once(&new_br, br_cfg->name, br_cfg)) {
572             VLOG_WARN("more than one bridge named %s", br_cfg->name);
573         }
574     }
575
576     /* Get rid of deleted bridges and add new bridges. */
577     LIST_FOR_EACH_SAFE (br, next, node, &all_bridges) {
578         struct ovsrec_bridge *br_cfg = shash_find_data(&new_br, br->name);
579         if (br_cfg) {
580             br->cfg = br_cfg;
581         } else {
582             bridge_destroy(br);
583         }
584     }
585     SHASH_FOR_EACH (node, &new_br) {
586         const char *br_name = node->name;
587         const struct ovsrec_bridge *br_cfg = node->data;
588         br = shash_find_data(&old_br, br_name);
589         if (br) {
590             /* If the bridge datapath type has changed, we need to tear it
591              * down and recreate. */
592             if (strcmp(br->cfg->datapath_type, br_cfg->datapath_type)) {
593                 bridge_destroy(br);
594                 bridge_create(br_cfg);
595             }
596         } else {
597             bridge_create(br_cfg);
598         }
599     }
600     shash_destroy(&old_br);
601     shash_destroy(&new_br);
602
603     /* Reconfigure all bridges. */
604     LIST_FOR_EACH (br, node, &all_bridges) {
605         bridge_reconfigure_one(br);
606     }
607
608     /* Add and delete ports on all datapaths.
609      *
610      * The kernel will reject any attempt to add a given port to a datapath if
611      * that port already belongs to a different datapath, so we must do all
612      * port deletions before any port additions. */
613     LIST_FOR_EACH (br, node, &all_bridges) {
614         struct dpif_port_dump dump;
615         struct shash want_ifaces;
616         struct dpif_port dpif_port;
617
618         bridge_get_all_ifaces(br, &want_ifaces);
619         DPIF_PORT_FOR_EACH (&dpif_port, &dump, br->dpif) {
620             if (!shash_find(&want_ifaces, dpif_port.name)
621                 && strcmp(dpif_port.name, br->name)) {
622                 int retval = dpif_port_del(br->dpif, dpif_port.port_no);
623                 if (retval) {
624                     VLOG_WARN("failed to remove %s interface from %s: %s",
625                               dpif_port.name, dpif_name(br->dpif),
626                               strerror(retval));
627                 }
628             }
629         }
630         shash_destroy(&want_ifaces);
631     }
632     LIST_FOR_EACH (br, node, &all_bridges) {
633         struct shash cur_ifaces, want_ifaces;
634         struct dpif_port_dump dump;
635         struct dpif_port dpif_port;
636
637         /* Get the set of interfaces currently in this datapath. */
638         shash_init(&cur_ifaces);
639         DPIF_PORT_FOR_EACH (&dpif_port, &dump, br->dpif) {
640             struct dpif_port *port_info = xmalloc(sizeof *port_info);
641             dpif_port_clone(port_info, &dpif_port);
642             shash_add(&cur_ifaces, dpif_port.name, port_info);
643         }
644
645         /* Get the set of interfaces we want on this datapath. */
646         bridge_get_all_ifaces(br, &want_ifaces);
647
648         hmap_clear(&br->ifaces);
649         SHASH_FOR_EACH (node, &want_ifaces) {
650             const char *if_name = node->name;
651             struct iface *iface = node->data;
652             struct dpif_port *dpif_port;
653             const char *type;
654             int error;
655
656             type = iface ? iface->type : "internal";
657             dpif_port = shash_find_data(&cur_ifaces, if_name);
658
659             /* If we have a port or a netdev already, and it's not the type we
660              * want, then delete the port (if any) and close the netdev (if
661              * any). */
662             if ((dpif_port && strcmp(dpif_port->type, type))
663                 || (iface && iface->netdev
664                     && strcmp(type, netdev_get_type(iface->netdev)))) {
665                 if (dpif_port) {
666                     error = ofproto_port_del(br->ofproto, dpif_port->port_no);
667                     if (error) {
668                         continue;
669                     }
670                     dpif_port = NULL;
671                 }
672                 if (iface) {
673                     netdev_close(iface->netdev);
674                     iface->netdev = NULL;
675                 }
676             }
677
678             /* If the port doesn't exist or we don't have the netdev open,
679              * we need to do more work. */
680             if (!dpif_port || (iface && !iface->netdev)) {
681                 struct netdev_options options;
682                 struct netdev *netdev;
683                 struct shash args;
684
685                 /* First open the network device. */
686                 options.name = if_name;
687                 options.type = type;
688                 options.args = &args;
689                 options.ethertype = NETDEV_ETH_TYPE_NONE;
690
691                 shash_init(&args);
692                 if (iface) {
693                     shash_from_ovs_idl_map(iface->cfg->key_options,
694                                            iface->cfg->value_options,
695                                            iface->cfg->n_options, &args);
696                 }
697                 error = netdev_open(&options, &netdev);
698                 shash_destroy(&args);
699
700                 if (error) {
701                     VLOG_WARN("could not open network device %s (%s)",
702                               if_name, strerror(error));
703                     continue;
704                 }
705
706                 /* Then add the port if we haven't already. */
707                 if (!dpif_port) {
708                     error = dpif_port_add(br->dpif, netdev, NULL);
709                     if (error) {
710                         netdev_close(netdev);
711                         if (error == EFBIG) {
712                             VLOG_ERR("ran out of valid port numbers on %s",
713                                      dpif_name(br->dpif));
714                             break;
715                         } else {
716                             VLOG_WARN("failed to add %s interface to %s: %s",
717                                       if_name, dpif_name(br->dpif),
718                                       strerror(error));
719                             continue;
720                         }
721                     }
722                 }
723
724                 /* Update 'iface'. */
725                 if (iface) {
726                     iface->netdev = netdev;
727                     iface->enabled = iface_get_carrier(iface);
728                     iface->up = iface->enabled;
729                 }
730             } else if (iface && iface->netdev) {
731                 struct shash args;
732
733                 shash_init(&args);
734                 shash_from_ovs_idl_map(iface->cfg->key_options,
735                                        iface->cfg->value_options,
736                                        iface->cfg->n_options, &args);
737                 netdev_set_config(iface->netdev, &args);
738                 shash_destroy(&args);
739             }
740         }
741         shash_destroy(&want_ifaces);
742
743         SHASH_FOR_EACH (node, &cur_ifaces) {
744             struct dpif_port *port_info = node->data;
745             dpif_port_destroy(port_info);
746             free(port_info);
747         }
748         shash_destroy(&cur_ifaces);
749     }
750     sflow_bridge_number = 0;
751     LIST_FOR_EACH (br, node, &all_bridges) {
752         uint8_t ea[8];
753         uint64_t dpid;
754         struct iface *local_iface;
755         struct iface *hw_addr_iface;
756         char *dpid_string;
757
758         bridge_fetch_dp_ifaces(br);
759
760         iterate_and_prune_ifaces(br, check_iface, NULL);
761
762         /* Pick local port hardware address, datapath ID. */
763         bridge_pick_local_hw_addr(br, ea, &hw_addr_iface);
764         local_iface = iface_from_dp_ifidx(br, ODPP_LOCAL);
765         if (local_iface) {
766             int error = netdev_set_etheraddr(local_iface->netdev, ea);
767             if (error) {
768                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
769                 VLOG_ERR_RL(&rl, "bridge %s: failed to set bridge "
770                             "Ethernet address: %s",
771                             br->name, strerror(error));
772             }
773         }
774         memcpy(br->ea, ea, ETH_ADDR_LEN);
775
776         dpid = bridge_pick_datapath_id(br, ea, hw_addr_iface);
777         ofproto_set_datapath_id(br->ofproto, dpid);
778
779         dpid_string = xasprintf("%016"PRIx64, dpid);
780         ovsrec_bridge_set_datapath_id(br->cfg, dpid_string);
781         free(dpid_string);
782
783         /* Set NetFlow configuration on this bridge. */
784         if (br->cfg->netflow) {
785             struct ovsrec_netflow *nf_cfg = br->cfg->netflow;
786             struct netflow_options opts;
787
788             memset(&opts, 0, sizeof opts);
789
790             dpif_get_netflow_ids(br->dpif, &opts.engine_type, &opts.engine_id);
791             if (nf_cfg->engine_type) {
792                 opts.engine_type = *nf_cfg->engine_type;
793             }
794             if (nf_cfg->engine_id) {
795                 opts.engine_id = *nf_cfg->engine_id;
796             }
797
798             opts.active_timeout = nf_cfg->active_timeout;
799             if (!opts.active_timeout) {
800                 opts.active_timeout = -1;
801             } else if (opts.active_timeout < 0) {
802                 VLOG_WARN("bridge %s: active timeout interval set to negative "
803                           "value, using default instead (%d seconds)", br->name,
804                           NF_ACTIVE_TIMEOUT_DEFAULT);
805                 opts.active_timeout = -1;
806             }
807
808             opts.add_id_to_iface = nf_cfg->add_id_to_interface;
809             if (opts.add_id_to_iface) {
810                 if (opts.engine_id > 0x7f) {
811                     VLOG_WARN("bridge %s: netflow port mangling may conflict "
812                               "with another vswitch, choose an engine id less "
813                               "than 128", br->name);
814                 }
815                 if (hmap_count(&br->ports) > 508) {
816                     VLOG_WARN("bridge %s: netflow port mangling will conflict "
817                               "with another port when more than 508 ports are "
818                               "used", br->name);
819                 }
820             }
821
822             sset_init(&opts.collectors);
823             sset_add_array(&opts.collectors,
824                            nf_cfg->targets, nf_cfg->n_targets);
825             if (ofproto_set_netflow(br->ofproto, &opts)) {
826                 VLOG_ERR("bridge %s: problem setting netflow collectors",
827                          br->name);
828             }
829             sset_destroy(&opts.collectors);
830         } else {
831             ofproto_set_netflow(br->ofproto, NULL);
832         }
833
834         /* Set sFlow configuration on this bridge. */
835         if (br->cfg->sflow) {
836             const struct ovsrec_sflow *sflow_cfg = br->cfg->sflow;
837             struct ovsrec_controller **controllers;
838             struct ofproto_sflow_options oso;
839             size_t n_controllers;
840
841             memset(&oso, 0, sizeof oso);
842
843             sset_init(&oso.targets);
844             sset_add_array(&oso.targets,
845                            sflow_cfg->targets, sflow_cfg->n_targets);
846
847             oso.sampling_rate = SFL_DEFAULT_SAMPLING_RATE;
848             if (sflow_cfg->sampling) {
849                 oso.sampling_rate = *sflow_cfg->sampling;
850             }
851
852             oso.polling_interval = SFL_DEFAULT_POLLING_INTERVAL;
853             if (sflow_cfg->polling) {
854                 oso.polling_interval = *sflow_cfg->polling;
855             }
856
857             oso.header_len = SFL_DEFAULT_HEADER_SIZE;
858             if (sflow_cfg->header) {
859                 oso.header_len = *sflow_cfg->header;
860             }
861
862             oso.sub_id = sflow_bridge_number++;
863             oso.agent_device = sflow_cfg->agent;
864
865             oso.control_ip = NULL;
866             n_controllers = bridge_get_controllers(br, &controllers);
867             for (i = 0; i < n_controllers; i++) {
868                 if (controllers[i]->local_ip) {
869                     oso.control_ip = controllers[i]->local_ip;
870                     break;
871                 }
872             }
873             ofproto_set_sflow(br->ofproto, &oso);
874
875             sset_destroy(&oso.targets);
876         } else {
877             ofproto_set_sflow(br->ofproto, NULL);
878         }
879
880         /* Update the controller and related settings.  It would be more
881          * straightforward to call this from bridge_reconfigure_one(), but we
882          * can't do it there for two reasons.  First, and most importantly, at
883          * that point we don't know the dp_ifidx of any interfaces that have
884          * been added to the bridge (because we haven't actually added them to
885          * the datapath).  Second, at that point we haven't set the datapath ID
886          * yet; when a controller is configured, resetting the datapath ID will
887          * immediately disconnect from the controller, so it's better to set
888          * the datapath ID before the controller. */
889         bridge_reconfigure_remotes(br, managers, n_managers);
890     }
891     LIST_FOR_EACH (br, node, &all_bridges) {
892         struct port *port;
893
894         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
895             struct iface *iface;
896
897             if (port->monitor) {
898                 LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
899                     netdev_monitor_add(port->monitor, iface->netdev);
900                 }
901             } else {
902                 port->miimon_next_update = 0;
903             }
904
905             port_update_lacp(port);
906             port_update_bonding(port);
907
908             LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
909                 iface_update_qos(iface, port->cfg->qos);
910             }
911         }
912     }
913     LIST_FOR_EACH (br, node, &all_bridges) {
914         iterate_and_prune_ifaces(br, set_iface_properties, NULL);
915     }
916
917     LIST_FOR_EACH (br, node, &all_bridges) {
918         struct iface *iface;
919         HMAP_FOR_EACH (iface, dp_ifidx_node, &br->ifaces) {
920             iface_update_cfm(iface);
921         }
922     }
923
924     free(managers);
925
926     /* ovs-vswitchd has completed initialization, so allow the process that
927      * forked us to exit successfully. */
928     daemonize_complete();
929 }
930
931 static const char *
932 get_ovsrec_key_value(const struct ovsdb_idl_row *row,
933                      const struct ovsdb_idl_column *column,
934                      const char *key)
935 {
936     const struct ovsdb_datum *datum;
937     union ovsdb_atom atom;
938     unsigned int idx;
939
940     datum = ovsdb_idl_get(row, column, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
941     atom.string = (char *) key;
942     idx = ovsdb_datum_find_key(datum, &atom, OVSDB_TYPE_STRING);
943     return idx == UINT_MAX ? NULL : datum->values[idx].string;
944 }
945
946 static const char *
947 bridge_get_other_config(const struct ovsrec_bridge *br_cfg, const char *key)
948 {
949     return get_ovsrec_key_value(&br_cfg->header_,
950                                 &ovsrec_bridge_col_other_config, key);
951 }
952
953 static void
954 bridge_pick_local_hw_addr(struct bridge *br, uint8_t ea[ETH_ADDR_LEN],
955                           struct iface **hw_addr_iface)
956 {
957     const char *hwaddr;
958     struct port *port;
959     int error;
960
961     *hw_addr_iface = NULL;
962
963     /* Did the user request a particular MAC? */
964     hwaddr = bridge_get_other_config(br->cfg, "hwaddr");
965     if (hwaddr && eth_addr_from_string(hwaddr, ea)) {
966         if (eth_addr_is_multicast(ea)) {
967             VLOG_ERR("bridge %s: cannot set MAC address to multicast "
968                      "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
969         } else if (eth_addr_is_zero(ea)) {
970             VLOG_ERR("bridge %s: cannot set MAC address to zero", br->name);
971         } else {
972             return;
973         }
974     }
975
976     /* Otherwise choose the minimum non-local MAC address among all of the
977      * interfaces. */
978     memset(ea, 0xff, ETH_ADDR_LEN);
979     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
980         uint8_t iface_ea[ETH_ADDR_LEN];
981         struct iface *candidate;
982         struct iface *iface;
983
984         /* Mirror output ports don't participate. */
985         if (port->is_mirror_output_port) {
986             continue;
987         }
988
989         /* Choose the MAC address to represent the port. */
990         iface = NULL;
991         if (port->cfg->mac && eth_addr_from_string(port->cfg->mac, iface_ea)) {
992             /* Find the interface with this Ethernet address (if any) so that
993              * we can provide the correct devname to the caller. */
994             LIST_FOR_EACH (candidate, port_elem, &port->ifaces) {
995                 uint8_t candidate_ea[ETH_ADDR_LEN];
996                 if (!netdev_get_etheraddr(candidate->netdev, candidate_ea)
997                     && eth_addr_equals(iface_ea, candidate_ea)) {
998                     iface = candidate;
999                 }
1000             }
1001         } else {
1002             /* Choose the interface whose MAC address will represent the port.
1003              * The Linux kernel bonding code always chooses the MAC address of
1004              * the first slave added to a bond, and the Fedora networking
1005              * scripts always add slaves to a bond in alphabetical order, so
1006              * for compatibility we choose the interface with the name that is
1007              * first in alphabetical order. */
1008             LIST_FOR_EACH (candidate, port_elem, &port->ifaces) {
1009                 if (!iface || strcmp(candidate->name, iface->name) < 0) {
1010                     iface = candidate;
1011                 }
1012             }
1013
1014             /* The local port doesn't count (since we're trying to choose its
1015              * MAC address anyway). */
1016             if (iface->dp_ifidx == ODPP_LOCAL) {
1017                 continue;
1018             }
1019
1020             /* Grab MAC. */
1021             error = netdev_get_etheraddr(iface->netdev, iface_ea);
1022             if (error) {
1023                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1024                 VLOG_ERR_RL(&rl, "failed to obtain Ethernet address of %s: %s",
1025                             iface->name, strerror(error));
1026                 continue;
1027             }
1028         }
1029
1030         /* Compare against our current choice. */
1031         if (!eth_addr_is_multicast(iface_ea) &&
1032             !eth_addr_is_local(iface_ea) &&
1033             !eth_addr_is_reserved(iface_ea) &&
1034             !eth_addr_is_zero(iface_ea) &&
1035             eth_addr_compare_3way(iface_ea, ea) < 0)
1036         {
1037             memcpy(ea, iface_ea, ETH_ADDR_LEN);
1038             *hw_addr_iface = iface;
1039         }
1040     }
1041     if (eth_addr_is_multicast(ea)) {
1042         memcpy(ea, br->default_ea, ETH_ADDR_LEN);
1043         *hw_addr_iface = NULL;
1044         VLOG_WARN("bridge %s: using default bridge Ethernet "
1045                   "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
1046     } else {
1047         VLOG_DBG("bridge %s: using bridge Ethernet address "ETH_ADDR_FMT,
1048                  br->name, ETH_ADDR_ARGS(ea));
1049     }
1050 }
1051
1052 /* Choose and returns the datapath ID for bridge 'br' given that the bridge
1053  * Ethernet address is 'bridge_ea'.  If 'bridge_ea' is the Ethernet address of
1054  * an interface on 'br', then that interface must be passed in as
1055  * 'hw_addr_iface'; if 'bridge_ea' was derived some other way, then
1056  * 'hw_addr_iface' must be passed in as a null pointer. */
1057 static uint64_t
1058 bridge_pick_datapath_id(struct bridge *br,
1059                         const uint8_t bridge_ea[ETH_ADDR_LEN],
1060                         struct iface *hw_addr_iface)
1061 {
1062     /*
1063      * The procedure for choosing a bridge MAC address will, in the most
1064      * ordinary case, also choose a unique MAC that we can use as a datapath
1065      * ID.  In some special cases, though, multiple bridges will end up with
1066      * the same MAC address.  This is OK for the bridges, but it will confuse
1067      * the OpenFlow controller, because each datapath needs a unique datapath
1068      * ID.
1069      *
1070      * Datapath IDs must be unique.  It is also very desirable that they be
1071      * stable from one run to the next, so that policy set on a datapath
1072      * "sticks".
1073      */
1074     const char *datapath_id;
1075     uint64_t dpid;
1076
1077     datapath_id = bridge_get_other_config(br->cfg, "datapath-id");
1078     if (datapath_id && dpid_from_string(datapath_id, &dpid)) {
1079         return dpid;
1080     }
1081
1082     if (hw_addr_iface) {
1083         int vlan;
1084         if (!netdev_get_vlan_vid(hw_addr_iface->netdev, &vlan)) {
1085             /*
1086              * A bridge whose MAC address is taken from a VLAN network device
1087              * (that is, a network device created with vconfig(8) or similar
1088              * tool) will have the same MAC address as a bridge on the VLAN
1089              * device's physical network device.
1090              *
1091              * Handle this case by hashing the physical network device MAC
1092              * along with the VLAN identifier.
1093              */
1094             uint8_t buf[ETH_ADDR_LEN + 2];
1095             memcpy(buf, bridge_ea, ETH_ADDR_LEN);
1096             buf[ETH_ADDR_LEN] = vlan >> 8;
1097             buf[ETH_ADDR_LEN + 1] = vlan;
1098             return dpid_from_hash(buf, sizeof buf);
1099         } else {
1100             /*
1101              * Assume that this bridge's MAC address is unique, since it
1102              * doesn't fit any of the cases we handle specially.
1103              */
1104         }
1105     } else {
1106         /*
1107          * A purely internal bridge, that is, one that has no non-virtual
1108          * network devices on it at all, is more difficult because it has no
1109          * natural unique identifier at all.
1110          *
1111          * When the host is a XenServer, we handle this case by hashing the
1112          * host's UUID with the name of the bridge.  Names of bridges are
1113          * persistent across XenServer reboots, although they can be reused if
1114          * an internal network is destroyed and then a new one is later
1115          * created, so this is fairly effective.
1116          *
1117          * When the host is not a XenServer, we punt by using a random MAC
1118          * address on each run.
1119          */
1120         const char *host_uuid = xenserver_get_host_uuid();
1121         if (host_uuid) {
1122             char *combined = xasprintf("%s,%s", host_uuid, br->name);
1123             dpid = dpid_from_hash(combined, strlen(combined));
1124             free(combined);
1125             return dpid;
1126         }
1127     }
1128
1129     return eth_addr_to_uint64(bridge_ea);
1130 }
1131
1132 static uint64_t
1133 dpid_from_hash(const void *data, size_t n)
1134 {
1135     uint8_t hash[SHA1_DIGEST_SIZE];
1136
1137     BUILD_ASSERT_DECL(sizeof hash >= ETH_ADDR_LEN);
1138     sha1_bytes(data, n, hash);
1139     eth_addr_mark_random(hash);
1140     return eth_addr_to_uint64(hash);
1141 }
1142
1143 static void
1144 iface_refresh_status(struct iface *iface)
1145 {
1146     struct shash sh;
1147
1148     enum netdev_flags flags;
1149     uint32_t current;
1150     int64_t bps;
1151     int mtu;
1152     int64_t mtu_64;
1153     int error;
1154
1155     shash_init(&sh);
1156
1157     if (!netdev_get_status(iface->netdev, &sh)) {
1158         size_t n;
1159         char **keys, **values;
1160
1161         shash_to_ovs_idl_map(&sh, &keys, &values, &n);
1162         ovsrec_interface_set_status(iface->cfg, keys, values, n);
1163
1164         free(keys);
1165         free(values);
1166     } else {
1167         ovsrec_interface_set_status(iface->cfg, NULL, NULL, 0);
1168     }
1169
1170     shash_destroy_free_data(&sh);
1171
1172     error = netdev_get_flags(iface->netdev, &flags);
1173     if (!error) {
1174         ovsrec_interface_set_admin_state(iface->cfg, flags & NETDEV_UP ? "up" : "down");
1175     }
1176     else {
1177         ovsrec_interface_set_admin_state(iface->cfg, NULL);
1178     }
1179
1180     error = netdev_get_features(iface->netdev, &current, NULL, NULL, NULL);
1181     if (!error) {
1182         ovsrec_interface_set_duplex(iface->cfg,
1183                                     netdev_features_is_full_duplex(current)
1184                                     ? "full" : "half");
1185         /* warning: uint64_t -> int64_t conversion */
1186         bps = netdev_features_to_bps(current);
1187         ovsrec_interface_set_link_speed(iface->cfg, &bps, 1);
1188     }
1189     else {
1190         ovsrec_interface_set_duplex(iface->cfg, NULL);
1191         ovsrec_interface_set_link_speed(iface->cfg, NULL, 0);
1192     }
1193
1194
1195     ovsrec_interface_set_link_state(iface->cfg,
1196                                     iface_get_carrier(iface) ? "up" : "down");
1197
1198     error = netdev_get_mtu(iface->netdev, &mtu);
1199     if (!error && mtu != INT_MAX) {
1200         mtu_64 = mtu;
1201         ovsrec_interface_set_mtu(iface->cfg, &mtu_64, 1);
1202     }
1203     else {
1204         ovsrec_interface_set_mtu(iface->cfg, NULL, 0);
1205     }
1206 }
1207
1208 /* Writes 'iface''s CFM statistics to the database.  Returns true if anything
1209  * changed, false otherwise. */
1210 static bool
1211 iface_refresh_cfm_stats(struct iface *iface)
1212 {
1213     const struct ovsrec_monitor *mon;
1214     const struct cfm *cfm;
1215     bool changed = false;
1216     size_t i;
1217
1218     mon = iface->cfg->monitor;
1219     cfm = ofproto_iface_get_cfm(iface->port->bridge->ofproto, iface->dp_ifidx);
1220
1221     if (!cfm || !mon) {
1222         return false;
1223     }
1224
1225     for (i = 0; i < mon->n_remote_mps; i++) {
1226         const struct ovsrec_maintenance_point *mp;
1227         const struct remote_mp *rmp;
1228
1229         mp = mon->remote_mps[i];
1230         rmp = cfm_get_remote_mp(cfm, mp->mpid);
1231
1232         if (mp->n_fault != 1 || mp->fault[0] != rmp->fault) {
1233             ovsrec_maintenance_point_set_fault(mp, &rmp->fault, 1);
1234             changed = true;
1235         }
1236     }
1237
1238     if (mon->n_fault != 1 || mon->fault[0] != cfm->fault) {
1239         ovsrec_monitor_set_fault(mon, &cfm->fault, 1);
1240         changed = true;
1241     }
1242
1243     return changed;
1244 }
1245
1246 static void
1247 iface_refresh_stats(struct iface *iface)
1248 {
1249     struct iface_stat {
1250         char *name;
1251         int offset;
1252     };
1253     static const struct iface_stat iface_stats[] = {
1254         { "rx_packets", offsetof(struct netdev_stats, rx_packets) },
1255         { "tx_packets", offsetof(struct netdev_stats, tx_packets) },
1256         { "rx_bytes", offsetof(struct netdev_stats, rx_bytes) },
1257         { "tx_bytes", offsetof(struct netdev_stats, tx_bytes) },
1258         { "rx_dropped", offsetof(struct netdev_stats, rx_dropped) },
1259         { "tx_dropped", offsetof(struct netdev_stats, tx_dropped) },
1260         { "rx_errors", offsetof(struct netdev_stats, rx_errors) },
1261         { "tx_errors", offsetof(struct netdev_stats, tx_errors) },
1262         { "rx_frame_err", offsetof(struct netdev_stats, rx_frame_errors) },
1263         { "rx_over_err", offsetof(struct netdev_stats, rx_over_errors) },
1264         { "rx_crc_err", offsetof(struct netdev_stats, rx_crc_errors) },
1265         { "collisions", offsetof(struct netdev_stats, collisions) },
1266     };
1267     enum { N_STATS = ARRAY_SIZE(iface_stats) };
1268     const struct iface_stat *s;
1269
1270     char *keys[N_STATS];
1271     int64_t values[N_STATS];
1272     int n;
1273
1274     struct netdev_stats stats;
1275
1276     /* Intentionally ignore return value, since errors will set 'stats' to
1277      * all-1s, and we will deal with that correctly below. */
1278     netdev_get_stats(iface->netdev, &stats);
1279
1280     n = 0;
1281     for (s = iface_stats; s < &iface_stats[N_STATS]; s++) {
1282         uint64_t value = *(uint64_t *) (((char *) &stats) + s->offset);
1283         if (value != UINT64_MAX) {
1284             keys[n] = s->name;
1285             values[n] = value;
1286             n++;
1287         }
1288     }
1289
1290     ovsrec_interface_set_statistics(iface->cfg, keys, values, n);
1291 }
1292
1293 static void
1294 refresh_system_stats(const struct ovsrec_open_vswitch *cfg)
1295 {
1296     struct ovsdb_datum datum;
1297     struct shash stats;
1298
1299     shash_init(&stats);
1300     get_system_stats(&stats);
1301
1302     ovsdb_datum_from_shash(&datum, &stats);
1303     ovsdb_idl_txn_write(&cfg->header_, &ovsrec_open_vswitch_col_statistics,
1304                         &datum);
1305 }
1306
1307 static inline const char *
1308 nx_role_to_str(enum nx_role role)
1309 {
1310     switch (role) {
1311     case NX_ROLE_OTHER:
1312         return "other";
1313     case NX_ROLE_MASTER:
1314         return "master";
1315     case NX_ROLE_SLAVE:
1316         return "slave";
1317     default:
1318         return "*** INVALID ROLE ***";
1319     }
1320 }
1321
1322 static void
1323 bridge_refresh_controller_status(const struct bridge *br)
1324 {
1325     struct shash info;
1326     const struct ovsrec_controller *cfg;
1327
1328     ofproto_get_ofproto_controller_info(br->ofproto, &info);
1329
1330     OVSREC_CONTROLLER_FOR_EACH(cfg, idl) {
1331         struct ofproto_controller_info *cinfo =
1332             shash_find_data(&info, cfg->target);
1333
1334         if (cinfo) {
1335             ovsrec_controller_set_is_connected(cfg, cinfo->is_connected);
1336             ovsrec_controller_set_role(cfg, nx_role_to_str(cinfo->role));
1337             ovsrec_controller_set_status(cfg, (char **) cinfo->pairs.keys,
1338                                          (char **) cinfo->pairs.values,
1339                                          cinfo->pairs.n);
1340         } else {
1341             ovsrec_controller_set_is_connected(cfg, false);
1342             ovsrec_controller_set_role(cfg, NULL);
1343             ovsrec_controller_set_status(cfg, NULL, NULL, 0);
1344         }
1345     }
1346
1347     ofproto_free_ofproto_controller_info(&info);
1348 }
1349
1350 void
1351 bridge_run(void)
1352 {
1353     const struct ovsrec_open_vswitch *cfg;
1354
1355     bool datapath_destroyed;
1356     bool database_changed;
1357     struct bridge *br;
1358
1359     /* Let each bridge do the work that it needs to do. */
1360     datapath_destroyed = false;
1361     LIST_FOR_EACH (br, node, &all_bridges) {
1362         int error = bridge_run_one(br);
1363         if (error) {
1364             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1365             VLOG_ERR_RL(&rl, "bridge %s: datapath was destroyed externally, "
1366                         "forcing reconfiguration", br->name);
1367             datapath_destroyed = true;
1368         }
1369     }
1370
1371     /* (Re)configure if necessary. */
1372     database_changed = ovsdb_idl_run(idl);
1373     cfg = ovsrec_open_vswitch_first(idl);
1374 #ifdef HAVE_OPENSSL
1375     /* Re-configure SSL.  We do this on every trip through the main loop,
1376      * instead of just when the database changes, because the contents of the
1377      * key and certificate files can change without the database changing.
1378      *
1379      * We do this before bridge_reconfigure() because that function might
1380      * initiate SSL connections and thus requires SSL to be configured. */
1381     if (cfg && cfg->ssl) {
1382         const struct ovsrec_ssl *ssl = cfg->ssl;
1383
1384         stream_ssl_set_key_and_cert(ssl->private_key, ssl->certificate);
1385         stream_ssl_set_ca_cert_file(ssl->ca_cert, ssl->bootstrap_ca_cert);
1386     }
1387 #endif
1388     if (database_changed || datapath_destroyed) {
1389         if (cfg) {
1390             struct ovsdb_idl_txn *txn = ovsdb_idl_txn_create(idl);
1391
1392             bridge_configure_once(cfg);
1393             bridge_reconfigure(cfg);
1394
1395             ovsrec_open_vswitch_set_cur_cfg(cfg, cfg->next_cfg);
1396             ovsdb_idl_txn_commit(txn);
1397             ovsdb_idl_txn_destroy(txn); /* XXX */
1398         } else {
1399             /* We still need to reconfigure to avoid dangling pointers to
1400              * now-destroyed ovsrec structures inside bridge data. */
1401             static const struct ovsrec_open_vswitch null_cfg;
1402
1403             bridge_reconfigure(&null_cfg);
1404         }
1405     }
1406
1407     /* Refresh system and interface stats if necessary. */
1408     if (time_msec() >= stats_timer) {
1409         if (cfg) {
1410             struct ovsdb_idl_txn *txn;
1411
1412             txn = ovsdb_idl_txn_create(idl);
1413             LIST_FOR_EACH (br, node, &all_bridges) {
1414                 struct port *port;
1415
1416                 HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1417                     struct iface *iface;
1418
1419                     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1420                         iface_refresh_stats(iface);
1421                         iface_refresh_status(iface);
1422                     }
1423                 }
1424                 bridge_refresh_controller_status(br);
1425             }
1426             refresh_system_stats(cfg);
1427             ovsdb_idl_txn_commit(txn);
1428             ovsdb_idl_txn_destroy(txn); /* XXX */
1429         }
1430
1431         stats_timer = time_msec() + STATS_INTERVAL;
1432     }
1433
1434     if (time_msec() >= cfm_limiter) {
1435         struct ovsdb_idl_txn *txn;
1436         bool changed = false;
1437
1438         txn = ovsdb_idl_txn_create(idl);
1439         LIST_FOR_EACH (br, node, &all_bridges) {
1440             struct port *port;
1441
1442             HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1443                 struct iface *iface;
1444
1445                 LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1446                     changed = iface_refresh_cfm_stats(iface) || changed;
1447                 }
1448             }
1449         }
1450
1451         if (changed) {
1452             cfm_limiter = time_msec() + CFM_LIMIT_INTERVAL;
1453         }
1454
1455         ovsdb_idl_txn_commit(txn);
1456         ovsdb_idl_txn_destroy(txn);
1457     }
1458 }
1459
1460 void
1461 bridge_wait(void)
1462 {
1463     struct bridge *br;
1464
1465     LIST_FOR_EACH (br, node, &all_bridges) {
1466         struct port *port;
1467
1468         ofproto_wait(br->ofproto);
1469         mac_learning_wait(br->ml);
1470         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1471             port_wait(port);
1472         }
1473     }
1474     ovsdb_idl_wait(idl);
1475     poll_timer_wait_until(stats_timer);
1476
1477     if (cfm_limiter > time_msec()) {
1478         poll_timer_wait_until(cfm_limiter);
1479     }
1480 }
1481
1482 /* Forces 'br' to revalidate all of its flows.  This is appropriate when 'br''s
1483  * configuration changes.  */
1484 static void
1485 bridge_flush(struct bridge *br)
1486 {
1487     COVERAGE_INC(bridge_flush);
1488     br->flush = true;
1489 }
1490 \f
1491 /* Bridge unixctl user interface functions. */
1492 static void
1493 bridge_unixctl_fdb_show(struct unixctl_conn *conn,
1494                         const char *args, void *aux OVS_UNUSED)
1495 {
1496     struct ds ds = DS_EMPTY_INITIALIZER;
1497     const struct bridge *br;
1498     const struct mac_entry *e;
1499
1500     br = bridge_lookup(args);
1501     if (!br) {
1502         unixctl_command_reply(conn, 501, "no such bridge");
1503         return;
1504     }
1505
1506     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
1507     LIST_FOR_EACH (e, lru_node, &br->ml->lrus) {
1508         struct port *port = e->port.p;
1509         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
1510                       port_get_an_iface(port)->dp_ifidx,
1511                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
1512     }
1513     unixctl_command_reply(conn, 200, ds_cstr(&ds));
1514     ds_destroy(&ds);
1515 }
1516 \f
1517 /* CFM unixctl user interface functions. */
1518 static void
1519 cfm_unixctl_show(struct unixctl_conn *conn,
1520                  const char *args, void *aux OVS_UNUSED)
1521 {
1522     struct ds ds = DS_EMPTY_INITIALIZER;
1523     struct iface *iface;
1524     const struct cfm *cfm;
1525
1526     iface = iface_find(args);
1527     if (!iface) {
1528         unixctl_command_reply(conn, 501, "no such interface");
1529         return;
1530     }
1531
1532     cfm = ofproto_iface_get_cfm(iface->port->bridge->ofproto, iface->dp_ifidx);
1533
1534     if (!cfm) {
1535         unixctl_command_reply(conn, 501, "CFM not enabled");
1536         return;
1537     }
1538
1539     cfm_dump_ds(cfm, &ds);
1540     unixctl_command_reply(conn, 200, ds_cstr(&ds));
1541     ds_destroy(&ds);
1542 }
1543 \f
1544 /* QoS unixctl user interface functions. */
1545
1546 struct qos_unixctl_show_cbdata {
1547     struct ds *ds;
1548     struct iface *iface;
1549 };
1550
1551 static void
1552 qos_unixctl_show_cb(unsigned int queue_id,
1553                     const struct shash *details,
1554                     void *aux)
1555 {
1556     struct qos_unixctl_show_cbdata *data = aux;
1557     struct ds *ds = data->ds;
1558     struct iface *iface = data->iface;
1559     struct netdev_queue_stats stats;
1560     struct shash_node *node;
1561     int error;
1562
1563     ds_put_cstr(ds, "\n");
1564     if (queue_id) {
1565         ds_put_format(ds, "Queue %u:\n", queue_id);
1566     } else {
1567         ds_put_cstr(ds, "Default:\n");
1568     }
1569
1570     SHASH_FOR_EACH (node, details) {
1571         ds_put_format(ds, "\t%s: %s\n", node->name, (char *)node->data);
1572     }
1573
1574     error = netdev_get_queue_stats(iface->netdev, queue_id, &stats);
1575     if (!error) {
1576         if (stats.tx_packets != UINT64_MAX) {
1577             ds_put_format(ds, "\ttx_packets: %"PRIu64"\n", stats.tx_packets);
1578         }
1579
1580         if (stats.tx_bytes != UINT64_MAX) {
1581             ds_put_format(ds, "\ttx_bytes: %"PRIu64"\n", stats.tx_bytes);
1582         }
1583
1584         if (stats.tx_errors != UINT64_MAX) {
1585             ds_put_format(ds, "\ttx_errors: %"PRIu64"\n", stats.tx_errors);
1586         }
1587     } else {
1588         ds_put_format(ds, "\tFailed to get statistics for queue %u: %s",
1589                       queue_id, strerror(error));
1590     }
1591 }
1592
1593 static void
1594 qos_unixctl_show(struct unixctl_conn *conn,
1595                  const char *args, void *aux OVS_UNUSED)
1596 {
1597     struct ds ds = DS_EMPTY_INITIALIZER;
1598     struct shash sh = SHASH_INITIALIZER(&sh);
1599     struct iface *iface;
1600     const char *type;
1601     struct shash_node *node;
1602     struct qos_unixctl_show_cbdata data;
1603     int error;
1604
1605     iface = iface_find(args);
1606     if (!iface) {
1607         unixctl_command_reply(conn, 501, "no such interface");
1608         return;
1609     }
1610
1611     netdev_get_qos(iface->netdev, &type, &sh);
1612
1613     if (*type != '\0') {
1614         ds_put_format(&ds, "QoS: %s %s\n", iface->name, type);
1615
1616         SHASH_FOR_EACH (node, &sh) {
1617             ds_put_format(&ds, "%s: %s\n", node->name, (char *)node->data);
1618         }
1619
1620         data.ds = &ds;
1621         data.iface = iface;
1622         error = netdev_dump_queues(iface->netdev, qos_unixctl_show_cb, &data);
1623
1624         if (error) {
1625             ds_put_format(&ds, "failed to dump queues: %s", strerror(error));
1626         }
1627         unixctl_command_reply(conn, 200, ds_cstr(&ds));
1628     } else {
1629         ds_put_format(&ds, "QoS not configured on %s\n", iface->name);
1630         unixctl_command_reply(conn, 501, ds_cstr(&ds));
1631     }
1632
1633     shash_destroy_free_data(&sh);
1634     ds_destroy(&ds);
1635 }
1636 \f
1637 /* Bridge reconfiguration functions. */
1638 static struct bridge *
1639 bridge_create(const struct ovsrec_bridge *br_cfg)
1640 {
1641     struct bridge *br;
1642     int error;
1643
1644     assert(!bridge_lookup(br_cfg->name));
1645     br = xzalloc(sizeof *br);
1646
1647     error = dpif_create_and_open(br_cfg->name, br_cfg->datapath_type,
1648                                  &br->dpif);
1649     if (error) {
1650         free(br);
1651         return NULL;
1652     }
1653     dpif_flow_flush(br->dpif);
1654
1655     error = ofproto_create(br_cfg->name, br_cfg->datapath_type, &bridge_ofhooks,
1656                            br, &br->ofproto);
1657     if (error) {
1658         VLOG_ERR("failed to create switch %s: %s", br_cfg->name,
1659                  strerror(error));
1660         dpif_delete(br->dpif);
1661         dpif_close(br->dpif);
1662         free(br);
1663         return NULL;
1664     }
1665
1666     br->name = xstrdup(br_cfg->name);
1667     br->cfg = br_cfg;
1668     br->ml = mac_learning_create();
1669     eth_addr_nicira_random(br->default_ea);
1670
1671     hmap_init(&br->ports);
1672     hmap_init(&br->ifaces);
1673     shash_init(&br->iface_by_name);
1674
1675     br->flush = false;
1676
1677     list_push_back(&all_bridges, &br->node);
1678
1679     VLOG_INFO("created bridge %s on %s", br->name, dpif_name(br->dpif));
1680
1681     return br;
1682 }
1683
1684 static void
1685 bridge_destroy(struct bridge *br)
1686 {
1687     if (br) {
1688         struct port *port, *next;
1689         int error;
1690
1691         HMAP_FOR_EACH_SAFE (port, next, hmap_node, &br->ports) {
1692             port_destroy(port);
1693         }
1694         list_remove(&br->node);
1695         ofproto_destroy(br->ofproto);
1696         error = dpif_delete(br->dpif);
1697         if (error && error != ENOENT) {
1698             VLOG_ERR("failed to delete %s: %s",
1699                      dpif_name(br->dpif), strerror(error));
1700         }
1701         dpif_close(br->dpif);
1702         mac_learning_destroy(br->ml);
1703         hmap_destroy(&br->ifaces);
1704         hmap_destroy(&br->ports);
1705         shash_destroy(&br->iface_by_name);
1706         free(br->name);
1707         free(br);
1708     }
1709 }
1710
1711 static struct bridge *
1712 bridge_lookup(const char *name)
1713 {
1714     struct bridge *br;
1715
1716     LIST_FOR_EACH (br, node, &all_bridges) {
1717         if (!strcmp(br->name, name)) {
1718             return br;
1719         }
1720     }
1721     return NULL;
1722 }
1723
1724 /* Handle requests for a listing of all flows known by the OpenFlow
1725  * stack, including those normally hidden. */
1726 static void
1727 bridge_unixctl_dump_flows(struct unixctl_conn *conn,
1728                           const char *args, void *aux OVS_UNUSED)
1729 {
1730     struct bridge *br;
1731     struct ds results;
1732
1733     br = bridge_lookup(args);
1734     if (!br) {
1735         unixctl_command_reply(conn, 501, "Unknown bridge");
1736         return;
1737     }
1738
1739     ds_init(&results);
1740     ofproto_get_all_flows(br->ofproto, &results);
1741
1742     unixctl_command_reply(conn, 200, ds_cstr(&results));
1743     ds_destroy(&results);
1744 }
1745
1746 /* "bridge/reconnect [BRIDGE]": makes BRIDGE drop all of its controller
1747  * connections and reconnect.  If BRIDGE is not specified, then all bridges
1748  * drop their controller connections and reconnect. */
1749 static void
1750 bridge_unixctl_reconnect(struct unixctl_conn *conn,
1751                          const char *args, void *aux OVS_UNUSED)
1752 {
1753     struct bridge *br;
1754     if (args[0] != '\0') {
1755         br = bridge_lookup(args);
1756         if (!br) {
1757             unixctl_command_reply(conn, 501, "Unknown bridge");
1758             return;
1759         }
1760         ofproto_reconnect_controllers(br->ofproto);
1761     } else {
1762         LIST_FOR_EACH (br, node, &all_bridges) {
1763             ofproto_reconnect_controllers(br->ofproto);
1764         }
1765     }
1766     unixctl_command_reply(conn, 200, NULL);
1767 }
1768
1769 static int
1770 bridge_run_one(struct bridge *br)
1771 {
1772     struct port *port;
1773     int error;
1774
1775     error = ofproto_run1(br->ofproto);
1776     if (error) {
1777         return error;
1778     }
1779
1780     mac_learning_run(br->ml, ofproto_get_revalidate_set(br->ofproto));
1781
1782     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1783         port_run(port);
1784     }
1785
1786     error = ofproto_run2(br->ofproto, br->flush);
1787     br->flush = false;
1788
1789     return error;
1790 }
1791
1792 static size_t
1793 bridge_get_controllers(const struct bridge *br,
1794                        struct ovsrec_controller ***controllersp)
1795 {
1796     struct ovsrec_controller **controllers;
1797     size_t n_controllers;
1798
1799     controllers = br->cfg->controller;
1800     n_controllers = br->cfg->n_controller;
1801
1802     if (n_controllers == 1 && !strcmp(controllers[0]->target, "none")) {
1803         controllers = NULL;
1804         n_controllers = 0;
1805     }
1806
1807     if (controllersp) {
1808         *controllersp = controllers;
1809     }
1810     return n_controllers;
1811 }
1812
1813 static void
1814 bridge_reconfigure_one(struct bridge *br)
1815 {
1816     enum ofproto_fail_mode fail_mode;
1817     struct port *port, *next;
1818     struct shash_node *node;
1819     struct shash new_ports;
1820     size_t i;
1821
1822     /* Collect new ports. */
1823     shash_init(&new_ports);
1824     for (i = 0; i < br->cfg->n_ports; i++) {
1825         const char *name = br->cfg->ports[i]->name;
1826         if (!shash_add_once(&new_ports, name, br->cfg->ports[i])) {
1827             VLOG_WARN("bridge %s: %s specified twice as bridge port",
1828                       br->name, name);
1829         }
1830     }
1831
1832     /* If we have a controller, then we need a local port.  Complain if the
1833      * user didn't specify one.
1834      *
1835      * XXX perhaps we should synthesize a port ourselves in this case. */
1836     if (bridge_get_controllers(br, NULL)) {
1837         char local_name[IF_NAMESIZE];
1838         int error;
1839
1840         error = dpif_port_get_name(br->dpif, ODPP_LOCAL,
1841                                    local_name, sizeof local_name);
1842         if (!error && !shash_find(&new_ports, local_name)) {
1843             VLOG_WARN("bridge %s: controller specified but no local port "
1844                       "(port named %s) defined",
1845                       br->name, local_name);
1846         }
1847     }
1848
1849     /* Get rid of deleted ports.
1850      * Get rid of deleted interfaces on ports that still exist. */
1851     HMAP_FOR_EACH_SAFE (port, next, hmap_node, &br->ports) {
1852         const struct ovsrec_port *port_cfg;
1853
1854         port_cfg = shash_find_data(&new_ports, port->name);
1855         if (!port_cfg) {
1856             port_destroy(port);
1857         } else {
1858             port_del_ifaces(port, port_cfg);
1859         }
1860     }
1861
1862     /* Create new ports.
1863      * Add new interfaces to existing ports.
1864      * Reconfigure existing ports. */
1865     SHASH_FOR_EACH (node, &new_ports) {
1866         struct port *port = port_lookup(br, node->name);
1867         if (!port) {
1868             port = port_create(br, node->name);
1869         }
1870
1871         port_reconfigure(port, node->data);
1872         if (!port->n_ifaces) {
1873             VLOG_WARN("bridge %s: port %s has no interfaces, dropping",
1874                       br->name, port->name);
1875             port_destroy(port);
1876         }
1877     }
1878     shash_destroy(&new_ports);
1879
1880     /* Set the fail-mode */
1881     fail_mode = !br->cfg->fail_mode
1882                 || !strcmp(br->cfg->fail_mode, "standalone")
1883                     ? OFPROTO_FAIL_STANDALONE
1884                     : OFPROTO_FAIL_SECURE;
1885     if (ofproto_get_fail_mode(br->ofproto) != fail_mode
1886         && !ofproto_has_primary_controller(br->ofproto)) {
1887         ofproto_flush_flows(br->ofproto);
1888     }
1889     ofproto_set_fail_mode(br->ofproto, fail_mode);
1890
1891     /* Delete all flows if we're switching from connected to standalone or vice
1892      * versa.  (XXX Should we delete all flows if we are switching from one
1893      * controller to another?) */
1894
1895     /* Configure OpenFlow controller connection snooping. */
1896     if (!ofproto_has_snoops(br->ofproto)) {
1897         struct sset snoops;
1898
1899         sset_init(&snoops);
1900         sset_add_and_free(&snoops, xasprintf("punix:%s/%s.snoop",
1901                                              ovs_rundir(), br->name));
1902         ofproto_set_snoops(br->ofproto, &snoops);
1903         sset_destroy(&snoops);
1904     }
1905
1906     mirror_reconfigure(br);
1907 }
1908
1909 /* Initializes 'oc' appropriately as a management service controller for
1910  * 'br'.
1911  *
1912  * The caller must free oc->target when it is no longer needed. */
1913 static void
1914 bridge_ofproto_controller_for_mgmt(const struct bridge *br,
1915                                    struct ofproto_controller *oc)
1916 {
1917     oc->target = xasprintf("punix:%s/%s.mgmt", ovs_rundir(), br->name);
1918     oc->max_backoff = 0;
1919     oc->probe_interval = 60;
1920     oc->band = OFPROTO_OUT_OF_BAND;
1921     oc->rate_limit = 0;
1922     oc->burst_limit = 0;
1923 }
1924
1925 /* Converts ovsrec_controller 'c' into an ofproto_controller in 'oc'.  */
1926 static void
1927 bridge_ofproto_controller_from_ovsrec(const struct ovsrec_controller *c,
1928                                       struct ofproto_controller *oc)
1929 {
1930     oc->target = c->target;
1931     oc->max_backoff = c->max_backoff ? *c->max_backoff / 1000 : 8;
1932     oc->probe_interval = c->inactivity_probe ? *c->inactivity_probe / 1000 : 5;
1933     oc->band = (!c->connection_mode || !strcmp(c->connection_mode, "in-band")
1934                 ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
1935     oc->rate_limit = c->controller_rate_limit ? *c->controller_rate_limit : 0;
1936     oc->burst_limit = (c->controller_burst_limit
1937                        ? *c->controller_burst_limit : 0);
1938 }
1939
1940 /* Configures the IP stack for 'br''s local interface properly according to the
1941  * configuration in 'c'.  */
1942 static void
1943 bridge_configure_local_iface_netdev(struct bridge *br,
1944                                     struct ovsrec_controller *c)
1945 {
1946     struct netdev *netdev;
1947     struct in_addr mask, gateway;
1948
1949     struct iface *local_iface;
1950     struct in_addr ip;
1951
1952     /* If there's no local interface or no IP address, give up. */
1953     local_iface = iface_from_dp_ifidx(br, ODPP_LOCAL);
1954     if (!local_iface || !c->local_ip || !inet_aton(c->local_ip, &ip)) {
1955         return;
1956     }
1957
1958     /* Bring up the local interface. */
1959     netdev = local_iface->netdev;
1960     netdev_turn_flags_on(netdev, NETDEV_UP, true);
1961
1962     /* Configure the IP address and netmask. */
1963     if (!c->local_netmask
1964         || !inet_aton(c->local_netmask, &mask)
1965         || !mask.s_addr) {
1966         mask.s_addr = guess_netmask(ip.s_addr);
1967     }
1968     if (!netdev_set_in4(netdev, ip, mask)) {
1969         VLOG_INFO("bridge %s: configured IP address "IP_FMT", netmask "IP_FMT,
1970                   br->name, IP_ARGS(&ip.s_addr), IP_ARGS(&mask.s_addr));
1971     }
1972
1973     /* Configure the default gateway. */
1974     if (c->local_gateway
1975         && inet_aton(c->local_gateway, &gateway)
1976         && gateway.s_addr) {
1977         if (!netdev_add_router(netdev, gateway)) {
1978             VLOG_INFO("bridge %s: configured gateway "IP_FMT,
1979                       br->name, IP_ARGS(&gateway.s_addr));
1980         }
1981     }
1982 }
1983
1984 static void
1985 bridge_reconfigure_remotes(struct bridge *br,
1986                            const struct sockaddr_in *managers,
1987                            size_t n_managers)
1988 {
1989     const char *disable_ib_str, *queue_id_str;
1990     bool disable_in_band = false;
1991     int queue_id;
1992
1993     struct ovsrec_controller **controllers;
1994     size_t n_controllers;
1995     bool had_primary;
1996
1997     struct ofproto_controller *ocs;
1998     size_t n_ocs;
1999     size_t i;
2000
2001     /* Check if we should disable in-band control on this bridge. */
2002     disable_ib_str = bridge_get_other_config(br->cfg, "disable-in-band");
2003     if (disable_ib_str && !strcmp(disable_ib_str, "true")) {
2004         disable_in_band = true;
2005     }
2006
2007     /* Set OpenFlow queue ID for in-band control. */
2008     queue_id_str = bridge_get_other_config(br->cfg, "in-band-queue");
2009     queue_id = queue_id_str ? strtol(queue_id_str, NULL, 10) : -1;
2010     ofproto_set_in_band_queue(br->ofproto, queue_id);
2011
2012     if (disable_in_band) {
2013         ofproto_set_extra_in_band_remotes(br->ofproto, NULL, 0);
2014     } else {
2015         ofproto_set_extra_in_band_remotes(br->ofproto, managers, n_managers);
2016     }
2017     had_primary = ofproto_has_primary_controller(br->ofproto);
2018
2019     n_controllers = bridge_get_controllers(br, &controllers);
2020
2021     ocs = xmalloc((n_controllers + 1) * sizeof *ocs);
2022     n_ocs = 0;
2023
2024     bridge_ofproto_controller_for_mgmt(br, &ocs[n_ocs++]);
2025     for (i = 0; i < n_controllers; i++) {
2026         struct ovsrec_controller *c = controllers[i];
2027
2028         if (!strncmp(c->target, "punix:", 6)
2029             || !strncmp(c->target, "unix:", 5)) {
2030             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2031
2032             /* Prevent remote ovsdb-server users from accessing arbitrary Unix
2033              * domain sockets and overwriting arbitrary local files. */
2034             VLOG_ERR_RL(&rl, "%s: not adding Unix domain socket controller "
2035                         "\"%s\" due to possibility for remote exploit",
2036                         dpif_name(br->dpif), c->target);
2037             continue;
2038         }
2039
2040         bridge_configure_local_iface_netdev(br, c);
2041         bridge_ofproto_controller_from_ovsrec(c, &ocs[n_ocs]);
2042         if (disable_in_band) {
2043             ocs[n_ocs].band = OFPROTO_OUT_OF_BAND;
2044         }
2045         n_ocs++;
2046     }
2047
2048     ofproto_set_controllers(br->ofproto, ocs, n_ocs);
2049     free(ocs[0].target); /* From bridge_ofproto_controller_for_mgmt(). */
2050     free(ocs);
2051
2052     if (had_primary != ofproto_has_primary_controller(br->ofproto)) {
2053         ofproto_flush_flows(br->ofproto);
2054     }
2055
2056     /* If there are no controllers and the bridge is in standalone
2057      * mode, set up a flow that matches every packet and directs
2058      * them to OFPP_NORMAL (which goes to us).  Otherwise, the
2059      * switch is in secure mode and we won't pass any traffic until
2060      * a controller has been defined and it tells us to do so. */
2061     if (!n_controllers
2062         && ofproto_get_fail_mode(br->ofproto) == OFPROTO_FAIL_STANDALONE) {
2063         union ofp_action action;
2064         struct cls_rule rule;
2065
2066         memset(&action, 0, sizeof action);
2067         action.type = htons(OFPAT_OUTPUT);
2068         action.output.len = htons(sizeof action);
2069         action.output.port = htons(OFPP_NORMAL);
2070         cls_rule_init_catchall(&rule, 0);
2071         ofproto_add_flow(br->ofproto, &rule, &action, 1);
2072     }
2073 }
2074
2075 static void
2076 bridge_get_all_ifaces(const struct bridge *br, struct shash *ifaces)
2077 {
2078     struct port *port;
2079
2080     shash_init(ifaces);
2081     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2082         struct iface *iface;
2083
2084         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2085             shash_add_once(ifaces, iface->name, iface);
2086         }
2087         if (port->n_ifaces > 1 && port->cfg->bond_fake_iface) {
2088             shash_add_once(ifaces, port->name, NULL);
2089         }
2090     }
2091 }
2092
2093 /* For robustness, in case the administrator moves around datapath ports behind
2094  * our back, we re-check all the datapath port numbers here.
2095  *
2096  * This function will set the 'dp_ifidx' members of interfaces that have
2097  * disappeared to -1, so only call this function from a context where those
2098  * 'struct iface's will be removed from the bridge.  Otherwise, the -1
2099  * 'dp_ifidx'es will cause trouble later when we try to send them to the
2100  * datapath, which doesn't support UINT16_MAX+1 ports. */
2101 static void
2102 bridge_fetch_dp_ifaces(struct bridge *br)
2103 {
2104     struct dpif_port_dump dump;
2105     struct dpif_port dpif_port;
2106     struct port *port;
2107
2108     /* Reset all interface numbers. */
2109     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2110         struct iface *iface;
2111
2112         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2113             iface->dp_ifidx = -1;
2114         }
2115     }
2116     hmap_clear(&br->ifaces);
2117
2118     DPIF_PORT_FOR_EACH (&dpif_port, &dump, br->dpif) {
2119         struct iface *iface = iface_lookup(br, dpif_port.name);
2120         if (iface) {
2121             if (iface->dp_ifidx >= 0) {
2122                 VLOG_WARN("%s reported interface %s twice",
2123                           dpif_name(br->dpif), dpif_port.name);
2124             } else if (iface_from_dp_ifidx(br, dpif_port.port_no)) {
2125                 VLOG_WARN("%s reported interface %"PRIu16" twice",
2126                           dpif_name(br->dpif), dpif_port.port_no);
2127             } else {
2128                 iface->dp_ifidx = dpif_port.port_no;
2129                 hmap_insert(&br->ifaces, &iface->dp_ifidx_node,
2130                             hash_int(iface->dp_ifidx, 0));
2131             }
2132
2133             iface_set_ofport(iface->cfg,
2134                              (iface->dp_ifidx >= 0
2135                               ? odp_port_to_ofp_port(iface->dp_ifidx)
2136                               : -1));
2137         }
2138     }
2139 }
2140 \f
2141 /* Bridge packet processing functions. */
2142
2143 static bool
2144 bond_is_tcp_hash(const struct port *port)
2145 {
2146     return port->bond_mode == BM_TCP && lacp_negotiated(port->lacp);
2147 }
2148
2149 static int
2150 bond_hash_src(const uint8_t mac[ETH_ADDR_LEN], uint16_t vlan)
2151 {
2152     return hash_bytes(mac, ETH_ADDR_LEN, vlan) & BOND_MASK;
2153 }
2154
2155 static int bond_hash_tcp(const struct flow *flow, uint16_t vlan)
2156 {
2157     struct flow hash_flow;
2158
2159     memcpy(&hash_flow, flow, sizeof hash_flow);
2160     hash_flow.vlan_tci = 0;
2161
2162     /* The symmetric quality of this hash function is not required, but
2163      * flow_hash_symmetric_l4 already exists, and is sufficient for our
2164      * purposes, so we use it out of convenience. */
2165     return flow_hash_symmetric_l4(&hash_flow, vlan) & BOND_MASK;
2166 }
2167
2168 static struct bond_entry *
2169 lookup_bond_entry(const struct port *port, const struct flow *flow,
2170                   uint16_t vlan)
2171 {
2172     assert(port->bond_mode != BM_AB);
2173
2174     if (bond_is_tcp_hash(port)) {
2175         return &port->bond_hash[bond_hash_tcp(flow, vlan)];
2176     } else {
2177         return &port->bond_hash[bond_hash_src(flow->dl_src, vlan)];
2178     }
2179 }
2180
2181 static struct iface *
2182 bond_choose_iface(const struct port *port)
2183 {
2184     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
2185     struct iface *best_down_slave;
2186     struct iface *iface;
2187
2188     best_down_slave = NULL;
2189     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2190         if (iface->enabled) {
2191             return iface;
2192         } else if ((!best_down_slave
2193                     || iface->delay_expires < best_down_slave->delay_expires)
2194                    && lacp_slave_may_enable(port->lacp, iface)) {
2195             best_down_slave = iface;
2196         }
2197     }
2198
2199     if (best_down_slave) {
2200         VLOG_INFO_RL(&rl, "interface %s: skipping remaining %lli ms updelay "
2201                      "since no other interface is up",
2202                      best_down_slave->name,
2203                      best_down_slave->delay_expires - time_msec());
2204         bond_enable_slave(best_down_slave, true);
2205     }
2206
2207     return best_down_slave;
2208 }
2209
2210 static bool
2211 choose_output_iface(const struct port *port, const struct flow *flow,
2212                     uint16_t vlan, uint16_t *dp_ifidx, tag_type *tags)
2213 {
2214     struct iface *iface;
2215
2216     assert(port->n_ifaces);
2217     if (port->n_ifaces == 1) {
2218         iface = port_get_an_iface(port);
2219     } else if (port->bond_mode == BM_AB) {
2220         iface = port->active_iface;
2221         if (!iface) {
2222             *tags |= port->no_ifaces_tag;
2223             return false;
2224         }
2225     } else {
2226         struct bond_entry *e = lookup_bond_entry(port, flow, vlan);
2227         if (!e->iface || !e->iface->enabled) {
2228             /* XXX select interface properly.  The current interface selection
2229              * is only good for testing the rebalancing code. */
2230             e->iface = bond_choose_iface(port);
2231             if (!e->iface) {
2232                 *tags |= port->no_ifaces_tag;
2233                 return false;
2234             }
2235             e->tag = tag_create_random();
2236         }
2237         *tags |= e->tag;
2238         iface = e->iface;
2239     }
2240     *dp_ifidx = iface->dp_ifidx;
2241     *tags |= iface->tag;        /* Currently only used for bonding. */
2242     return true;
2243 }
2244
2245 static void
2246 bond_link_status_update(struct iface *iface)
2247 {
2248     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
2249     struct port *port = iface->port;
2250     bool up = iface->up && lacp_slave_may_enable(port->lacp, iface);
2251     int updelay, downdelay;
2252
2253     updelay = port->updelay;
2254     downdelay = port->downdelay;
2255
2256     if (lacp_negotiated(port->lacp)) {
2257         downdelay = 0;
2258         updelay = 0;
2259     }
2260
2261     if ((up == iface->enabled) == (iface->delay_expires == LLONG_MAX)) {
2262         /* Nothing to do. */
2263         return;
2264     }
2265     VLOG_INFO_RL(&rl, "interface %s: link state %s",
2266                  iface->name, up ? "up" : "down");
2267     if (up == iface->enabled) {
2268         iface->delay_expires = LLONG_MAX;
2269         VLOG_INFO_RL(&rl, "interface %s: will not be %s",
2270                      iface->name, up ? "disabled" : "enabled");
2271     } else if (up && !port->active_iface) {
2272         bond_enable_slave(iface, true);
2273         if (updelay) {
2274             VLOG_INFO_RL(&rl, "interface %s: skipping %d ms updelay since no "
2275                          "other interface is up", iface->name, updelay);
2276         }
2277     } else {
2278         int delay = up ? updelay : downdelay;
2279         iface->delay_expires = time_msec() + delay;
2280         if (delay) {
2281             VLOG_INFO_RL(&rl,
2282                          "interface %s: will be %s if it stays %s for %d ms",
2283                          iface->name,
2284                          up ? "enabled" : "disabled",
2285                          up ? "up" : "down",
2286                          delay);
2287         }
2288     }
2289 }
2290
2291 static void
2292 bond_choose_active_iface(struct port *port)
2293 {
2294     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 20);
2295
2296     port->active_iface = bond_choose_iface(port);
2297     if (port->active_iface) {
2298         VLOG_INFO_RL(&rl, "port %s: active interface is now %s",
2299                      port->name, port->active_iface->name);
2300     } else {
2301         VLOG_WARN_RL(&rl, "port %s: all ports disabled, no active interface",
2302                      port->name);
2303     }
2304 }
2305
2306 static void
2307 bond_enable_slave(struct iface *iface, bool enable)
2308 {
2309     struct port *port = iface->port;
2310     struct bridge *br = port->bridge;
2311
2312     /* This acts as a recursion check.  If the act of disabling a slave
2313      * causes a different slave to be enabled, the flag will allow us to
2314      * skip redundant work when we reenter this function.  It must be
2315      * cleared on exit to keep things safe with multiple bonds. */
2316     static bool moving_active_iface = false;
2317
2318     iface->delay_expires = LLONG_MAX;
2319     if (enable == iface->enabled) {
2320         return;
2321     }
2322
2323     iface->enabled = enable;
2324     if (!iface->enabled) {
2325         VLOG_WARN("interface %s: disabled", iface->name);
2326         ofproto_revalidate(br->ofproto, iface->tag);
2327         if (iface == port->active_iface) {
2328             /* Disabling a slave can lead to another slave being immediately
2329              * enabled if there will be no active slaves but one is waiting
2330              * on an updelay.  In this case we do not need to run most of the
2331              * code for the newly enabled slave since there was no period
2332              * without an active slave and it is redundant with the disabling
2333              * path. */
2334             moving_active_iface = true;
2335             bond_choose_active_iface(port);
2336         }
2337         bond_send_learning_packets(port);
2338     } else {
2339         VLOG_WARN("interface %s: enabled", iface->name);
2340         if (!port->active_iface && !moving_active_iface) {
2341             ofproto_revalidate(br->ofproto, port->no_ifaces_tag);
2342             bond_choose_active_iface(port);
2343             bond_send_learning_packets(port);
2344         }
2345         iface->tag = tag_create_random();
2346     }
2347
2348     moving_active_iface = false;
2349 }
2350
2351 /* Attempts to make the sum of the bond slaves' statistics appear on the fake
2352  * bond interface. */
2353 static void
2354 bond_update_fake_iface_stats(struct port *port)
2355 {
2356     struct netdev_stats bond_stats;
2357     struct netdev *bond_dev;
2358     struct iface *iface;
2359
2360     memset(&bond_stats, 0, sizeof bond_stats);
2361
2362     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2363         struct netdev_stats slave_stats;
2364
2365         if (!netdev_get_stats(iface->netdev, &slave_stats)) {
2366             /* XXX: We swap the stats here because they are swapped back when
2367              * reported by the internal device.  The reason for this is
2368              * internal devices normally represent packets going into the system
2369              * but when used as fake bond device they represent packets leaving
2370              * the system.  We really should do this in the internal device
2371              * itself because changing it here reverses the counts from the
2372              * perspective of the switch.  However, the internal device doesn't
2373              * know what type of device it represents so we have to do it here
2374              * for now. */
2375             bond_stats.tx_packets += slave_stats.rx_packets;
2376             bond_stats.tx_bytes += slave_stats.rx_bytes;
2377             bond_stats.rx_packets += slave_stats.tx_packets;
2378             bond_stats.rx_bytes += slave_stats.tx_bytes;
2379         }
2380     }
2381
2382     if (!netdev_open_default(port->name, &bond_dev)) {
2383         netdev_set_stats(bond_dev, &bond_stats);
2384         netdev_close(bond_dev);
2385     }
2386 }
2387
2388 static void
2389 bond_run(struct port *port)
2390 {
2391     struct iface *iface;
2392
2393     if (port->n_ifaces < 2) {
2394         return;
2395     }
2396
2397     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2398         bond_link_status_update(iface);
2399     }
2400
2401     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2402         if (time_msec() >= iface->delay_expires) {
2403             bond_enable_slave(iface, !iface->enabled);
2404         }
2405     }
2406
2407     if (port->bond_fake_iface
2408         && time_msec() >= port->bond_next_fake_iface_update) {
2409         bond_update_fake_iface_stats(port);
2410         port->bond_next_fake_iface_update = time_msec() + 1000;
2411     }
2412 }
2413
2414 static void
2415 bond_wait(struct port *port)
2416 {
2417     struct iface *iface;
2418
2419     if (port->n_ifaces < 2) {
2420         return;
2421     }
2422
2423     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2424         if (iface->delay_expires != LLONG_MAX) {
2425             poll_timer_wait_until(iface->delay_expires);
2426         }
2427     }
2428
2429     if (port->bond_fake_iface) {
2430         poll_timer_wait_until(port->bond_next_fake_iface_update);
2431     }
2432 }
2433
2434 static bool
2435 set_dst(struct dst *dst, const struct flow *flow,
2436         const struct port *in_port, const struct port *out_port,
2437         tag_type *tags)
2438 {
2439     dst->vlan = (out_port->vlan >= 0 ? OFP_VLAN_NONE
2440               : in_port->vlan >= 0 ? in_port->vlan
2441               : flow->vlan_tci == 0 ? OFP_VLAN_NONE
2442               : vlan_tci_to_vid(flow->vlan_tci));
2443     return choose_output_iface(out_port, flow, dst->vlan,
2444                                &dst->dp_ifidx, tags);
2445 }
2446
2447 static void
2448 swap_dst(struct dst *p, struct dst *q)
2449 {
2450     struct dst tmp = *p;
2451     *p = *q;
2452     *q = tmp;
2453 }
2454
2455 /* Moves all the dsts with vlan == 'vlan' to the front of the 'n_dsts' in
2456  * 'dsts'.  (This may help performance by reducing the number of VLAN changes
2457  * that we push to the datapath.  We could in fact fully sort the array by
2458  * vlan, but in most cases there are at most two different vlan tags so that's
2459  * possibly overkill.) */
2460 static void
2461 partition_dsts(struct dst_set *set, int vlan)
2462 {
2463     struct dst *first = set->dsts;
2464     struct dst *last = set->dsts + set->n;
2465
2466     while (first != last) {
2467         /* Invariants:
2468          *      - All dsts < first have vlan == 'vlan'.
2469          *      - All dsts >= last have vlan != 'vlan'.
2470          *      - first < last. */
2471         while (first->vlan == vlan) {
2472             if (++first == last) {
2473                 return;
2474             }
2475         }
2476
2477         /* Same invariants, plus one additional:
2478          *      - first->vlan != vlan.
2479          */
2480         while (last[-1].vlan != vlan) {
2481             if (--last == first) {
2482                 return;
2483             }
2484         }
2485
2486         /* Same invariants, plus one additional:
2487          *      - last[-1].vlan == vlan.*/
2488         swap_dst(first++, --last);
2489     }
2490 }
2491
2492 static int
2493 mirror_mask_ffs(mirror_mask_t mask)
2494 {
2495     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
2496     return ffs(mask);
2497 }
2498
2499 static void
2500 dst_set_init(struct dst_set *set)
2501 {
2502     set->dsts = set->builtin;
2503     set->n = 0;
2504     set->allocated = ARRAY_SIZE(set->builtin);
2505 }
2506
2507 static void
2508 dst_set_add(struct dst_set *set, const struct dst *dst)
2509 {
2510     if (set->n >= set->allocated) {
2511         size_t new_allocated;
2512         struct dst *new_dsts;
2513
2514         new_allocated = set->allocated * 2;
2515         new_dsts = xmalloc(new_allocated * sizeof *new_dsts);
2516         memcpy(new_dsts, set->dsts, set->n * sizeof *new_dsts);
2517
2518         dst_set_free(set);
2519
2520         set->dsts = new_dsts;
2521         set->allocated = new_allocated;
2522     }
2523     set->dsts[set->n++] = *dst;
2524 }
2525
2526 static void
2527 dst_set_free(struct dst_set *set)
2528 {
2529     if (set->dsts != set->builtin) {
2530         free(set->dsts);
2531     }
2532 }
2533
2534 static bool
2535 dst_is_duplicate(const struct dst_set *set, const struct dst *test)
2536 {
2537     size_t i;
2538     for (i = 0; i < set->n; i++) {
2539         if (set->dsts[i].vlan == test->vlan
2540             && set->dsts[i].dp_ifidx == test->dp_ifidx) {
2541             return true;
2542         }
2543     }
2544     return false;
2545 }
2546
2547 static bool
2548 port_trunks_vlan(const struct port *port, uint16_t vlan)
2549 {
2550     return (port->vlan < 0
2551             && (!port->trunks || bitmap_is_set(port->trunks, vlan)));
2552 }
2553
2554 static bool
2555 port_includes_vlan(const struct port *port, uint16_t vlan)
2556 {
2557     return vlan == port->vlan || port_trunks_vlan(port, vlan);
2558 }
2559
2560 static bool
2561 port_is_floodable(const struct port *port)
2562 {
2563     struct iface *iface;
2564
2565     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2566         if (!ofproto_port_is_floodable(port->bridge->ofproto,
2567                                        iface->dp_ifidx)) {
2568             return false;
2569         }
2570     }
2571     return true;
2572 }
2573
2574 /* Returns the tag for 'port''s active iface, or 'port''s no_ifaces_tag if
2575  * there is no active iface. */
2576 static tag_type
2577 port_get_active_iface_tag(const struct port *port)
2578 {
2579     return (port->active_iface
2580             ? port->active_iface->tag
2581             : port->no_ifaces_tag);
2582 }
2583
2584 /* Returns an arbitrary interface within 'port'.
2585  *
2586  * 'port' must have at least one interface. */
2587 static struct iface *
2588 port_get_an_iface(const struct port *port)
2589 {
2590     return CONTAINER_OF(list_front(&port->ifaces), struct iface, port_elem);
2591 }
2592
2593 static void
2594 compose_dsts(const struct bridge *br, const struct flow *flow, uint16_t vlan,
2595              const struct port *in_port, const struct port *out_port,
2596              struct dst_set *set, tag_type *tags, uint16_t *nf_output_iface)
2597 {
2598     mirror_mask_t mirrors = in_port->src_mirrors;
2599     struct dst dst;
2600     int flow_vlan;
2601
2602     flow_vlan = vlan_tci_to_vid(flow->vlan_tci);
2603     if (flow_vlan == 0) {
2604         flow_vlan = OFP_VLAN_NONE;
2605     }
2606
2607     if (out_port == FLOOD_PORT) {
2608         struct port *port;
2609
2610         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2611             if (port != in_port
2612                 && port_is_floodable(port)
2613                 && port_includes_vlan(port, vlan)
2614                 && !port->is_mirror_output_port
2615                 && set_dst(&dst, flow, in_port, port, tags)) {
2616                 mirrors |= port->dst_mirrors;
2617                 dst_set_add(set, &dst);
2618             }
2619         }
2620         *nf_output_iface = NF_OUT_FLOOD;
2621     } else if (out_port && set_dst(&dst, flow, in_port, out_port, tags)) {
2622         dst_set_add(set, &dst);
2623         *nf_output_iface = dst.dp_ifidx;
2624         mirrors |= out_port->dst_mirrors;
2625     }
2626
2627     while (mirrors) {
2628         struct mirror *m = br->mirrors[mirror_mask_ffs(mirrors) - 1];
2629         if (!m->n_vlans || vlan_is_mirrored(m, vlan)) {
2630             if (m->out_port) {
2631                 if (set_dst(&dst, flow, in_port, m->out_port, tags)
2632                     && !dst_is_duplicate(set, &dst)) {
2633                     dst_set_add(set, &dst);
2634                 }
2635             } else {
2636                 struct port *port;
2637
2638                 HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2639                     if (port_includes_vlan(port, m->out_vlan)
2640                         && set_dst(&dst, flow, in_port, port, tags))
2641                     {
2642                         if (port->vlan < 0) {
2643                             dst.vlan = m->out_vlan;
2644                         }
2645                         if (dst_is_duplicate(set, &dst)) {
2646                             continue;
2647                         }
2648
2649                         /* Use the vlan tag on the original flow instead of
2650                          * the one passed in the vlan parameter.  This ensures
2651                          * that we compare the vlan from before any implicit
2652                          * tagging tags place. This is necessary because
2653                          * dst->vlan is the final vlan, after removing implicit
2654                          * tags. */
2655                         if (port == in_port && dst.vlan == flow_vlan) {
2656                             /* Don't send out input port on same VLAN. */
2657                             continue;
2658                         }
2659                         dst_set_add(set, &dst);
2660                     }
2661                 }
2662             }
2663         }
2664         mirrors &= mirrors - 1;
2665     }
2666
2667     partition_dsts(set, flow_vlan);
2668 }
2669
2670 static void OVS_UNUSED
2671 print_dsts(const struct dst_set *set)
2672 {
2673     size_t i;
2674
2675     for (i = 0; i < set->n; i++) {
2676         const struct dst *dst = &set->dsts[i];
2677
2678         printf(">p%"PRIu16, dst->dp_ifidx);
2679         if (dst->vlan != OFP_VLAN_NONE) {
2680             printf("v%"PRIu16, dst->vlan);
2681         }
2682     }
2683 }
2684
2685 static void
2686 compose_actions(struct bridge *br, const struct flow *flow, uint16_t vlan,
2687                 const struct port *in_port, const struct port *out_port,
2688                 tag_type *tags, struct ofpbuf *actions,
2689                 uint16_t *nf_output_iface)
2690 {
2691     struct dst_set set;
2692     uint16_t cur_vlan;
2693     size_t i;
2694
2695     dst_set_init(&set);
2696     compose_dsts(br, flow, vlan, in_port, out_port, &set, tags,
2697                  nf_output_iface);
2698
2699     cur_vlan = vlan_tci_to_vid(flow->vlan_tci);
2700     if (cur_vlan == 0) {
2701         cur_vlan = OFP_VLAN_NONE;
2702     }
2703     for (i = 0; i < set.n; i++) {
2704         const struct dst *dst = &set.dsts[i];
2705         if (dst->vlan != cur_vlan) {
2706             if (dst->vlan == OFP_VLAN_NONE) {
2707                 nl_msg_put_flag(actions, ODP_ACTION_ATTR_STRIP_VLAN);
2708             } else {
2709                 ovs_be16 tci;
2710                 tci = htons(dst->vlan & VLAN_VID_MASK);
2711                 tci |= flow->vlan_tci & htons(VLAN_PCP_MASK);
2712                 nl_msg_put_be16(actions, ODP_ACTION_ATTR_SET_DL_TCI, tci);
2713             }
2714             cur_vlan = dst->vlan;
2715         }
2716         nl_msg_put_u32(actions, ODP_ACTION_ATTR_OUTPUT, dst->dp_ifidx);
2717     }
2718     dst_set_free(&set);
2719 }
2720
2721 /* Returns the effective vlan of a packet, taking into account both the
2722  * 802.1Q header and implicitly tagged ports.  A value of 0 indicates that
2723  * the packet is untagged and -1 indicates it has an invalid header and
2724  * should be dropped. */
2725 static int flow_get_vlan(struct bridge *br, const struct flow *flow,
2726                          struct port *in_port, bool have_packet)
2727 {
2728     int vlan = vlan_tci_to_vid(flow->vlan_tci);
2729     if (in_port->vlan >= 0) {
2730         if (vlan) {
2731             /* XXX support double tagging? */
2732             if (have_packet) {
2733                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2734                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
2735                              "packet received on port %s configured with "
2736                              "implicit VLAN %"PRIu16,
2737                              br->name, vlan, in_port->name, in_port->vlan);
2738             }
2739             return -1;
2740         }
2741         vlan = in_port->vlan;
2742     } else {
2743         if (!port_includes_vlan(in_port, vlan)) {
2744             if (have_packet) {
2745                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2746                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
2747                              "packet received on port %s not configured for "
2748                              "trunking VLAN %d",
2749                              br->name, vlan, in_port->name, vlan);
2750             }
2751             return -1;
2752         }
2753     }
2754
2755     return vlan;
2756 }
2757
2758 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
2759  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
2760  * indicate this; newer upstream kernels use gratuitous ARP requests. */
2761 static bool
2762 is_gratuitous_arp(const struct flow *flow)
2763 {
2764     return (flow->dl_type == htons(ETH_TYPE_ARP)
2765             && eth_addr_is_broadcast(flow->dl_dst)
2766             && (flow->nw_proto == ARP_OP_REPLY
2767                 || (flow->nw_proto == ARP_OP_REQUEST
2768                     && flow->nw_src == flow->nw_dst)));
2769 }
2770
2771 static void
2772 update_learning_table(struct bridge *br, const struct flow *flow, int vlan,
2773                       struct port *in_port)
2774 {
2775     struct mac_entry *mac;
2776
2777     if (!mac_learning_may_learn(br->ml, flow->dl_src, vlan)) {
2778         return;
2779     }
2780
2781     mac = mac_learning_insert(br->ml, flow->dl_src, vlan);
2782     if (is_gratuitous_arp(flow)) {
2783         /* We don't want to learn from gratuitous ARP packets that are
2784          * reflected back over bond slaves so we lock the learning table. */
2785         if (in_port->n_ifaces == 1) {
2786             mac_entry_set_grat_arp_lock(mac);
2787         } else if (mac_entry_is_grat_arp_locked(mac)) {
2788             return;
2789         }
2790     }
2791
2792     if (mac_entry_is_new(mac) || mac->port.p != in_port) {
2793         /* The log messages here could actually be useful in debugging,
2794          * so keep the rate limit relatively high. */
2795         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
2796         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
2797                     "on port %s in VLAN %d",
2798                     br->name, ETH_ADDR_ARGS(flow->dl_src),
2799                     in_port->name, vlan);
2800
2801         mac->port.p = in_port;
2802         ofproto_revalidate(br->ofproto, mac_learning_changed(br->ml, mac));
2803     }
2804 }
2805
2806 /* Determines whether packets in 'flow' within 'br' should be forwarded or
2807  * dropped.  Returns true if they may be forwarded, false if they should be
2808  * dropped.
2809  *
2810  * If 'have_packet' is true, it indicates that the caller is processing a
2811  * received packet.  If 'have_packet' is false, then the caller is just
2812  * revalidating an existing flow because configuration has changed.  Either
2813  * way, 'have_packet' only affects logging (there is no point in logging errors
2814  * during revalidation).
2815  *
2816  * Sets '*in_portp' to the input port.  This will be a null pointer if
2817  * flow->in_port does not designate a known input port (in which case
2818  * is_admissible() returns false).
2819  *
2820  * When returning true, sets '*vlanp' to the effective VLAN of the input
2821  * packet, as returned by flow_get_vlan().
2822  *
2823  * May also add tags to '*tags', although the current implementation only does
2824  * so in one special case.
2825  */
2826 static bool
2827 is_admissible(struct bridge *br, const struct flow *flow, bool have_packet,
2828               tag_type *tags, int *vlanp, struct port **in_portp)
2829 {
2830     struct iface *in_iface;
2831     struct port *in_port;
2832     int vlan;
2833
2834     /* Find the interface and port structure for the received packet. */
2835     in_iface = iface_from_dp_ifidx(br, flow->in_port);
2836     if (!in_iface) {
2837         /* No interface?  Something fishy... */
2838         if (have_packet) {
2839             /* Odd.  A few possible reasons here:
2840              *
2841              * - We deleted an interface but there are still a few packets
2842              *   queued up from it.
2843              *
2844              * - Someone externally added an interface (e.g. with "ovs-dpctl
2845              *   add-if") that we don't know about.
2846              *
2847              * - Packet arrived on the local port but the local port is not
2848              *   one of our bridge ports.
2849              */
2850             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2851
2852             VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
2853                          "interface %"PRIu16, br->name, flow->in_port);
2854         }
2855
2856         *in_portp = NULL;
2857         return false;
2858     }
2859     *in_portp = in_port = in_iface->port;
2860     *vlanp = vlan = flow_get_vlan(br, flow, in_port, have_packet);
2861     if (vlan < 0) {
2862         return false;
2863     }
2864
2865     /* Drop frames for reserved multicast addresses. */
2866     if (eth_addr_is_reserved(flow->dl_dst)) {
2867         return false;
2868     }
2869
2870     /* Drop frames on ports reserved for mirroring. */
2871     if (in_port->is_mirror_output_port) {
2872         if (have_packet) {
2873             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2874             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
2875                          "%s, which is reserved exclusively for mirroring",
2876                          br->name, in_port->name);
2877         }
2878         return false;
2879     }
2880
2881     /* When using LACP, do not accept packets from disabled interfaces. */
2882     if (lacp_negotiated(in_port->lacp) && !in_iface->enabled) {
2883         return false;
2884     }
2885
2886     /* Packets received on non-LACP bonds need special attention to avoid
2887      * duplicates. */
2888     if (in_port->n_ifaces > 1 && !lacp_negotiated(in_port->lacp)) {
2889         struct mac_entry *mac;
2890
2891         if (eth_addr_is_multicast(flow->dl_dst)) {
2892             *tags |= port_get_active_iface_tag(in_port);
2893             if (in_port->active_iface != in_iface) {
2894                 /* Drop all multicast packets on inactive slaves. */
2895                 return false;
2896             }
2897         }
2898
2899         /* Drop all packets for which we have learned a different input
2900          * port, because we probably sent the packet on one slave and got
2901          * it back on the other.  Gratuitous ARP packets are an exception
2902          * to this rule: the host has moved to another switch.  The exception
2903          * to the exception is if we locked the learning table to avoid
2904          * reflections on bond slaves.  If this is the case, just drop the
2905          * packet now. */
2906         mac = mac_learning_lookup(br->ml, flow->dl_src, vlan, NULL);
2907         if (mac && mac->port.p != in_port &&
2908             (!is_gratuitous_arp(flow) || mac_entry_is_grat_arp_locked(mac))) {
2909                 return false;
2910         }
2911     }
2912
2913     return true;
2914 }
2915
2916 /* If the composed actions may be applied to any packet in the given 'flow',
2917  * returns true.  Otherwise, the actions should only be applied to 'packet', or
2918  * not at all, if 'packet' was NULL. */
2919 static bool
2920 process_flow(struct bridge *br, const struct flow *flow,
2921              const struct ofpbuf *packet, struct ofpbuf *actions,
2922              tag_type *tags, uint16_t *nf_output_iface)
2923 {
2924     struct port *in_port;
2925     struct port *out_port;
2926     struct mac_entry *mac;
2927     int vlan;
2928
2929     /* Check whether we should drop packets in this flow. */
2930     if (!is_admissible(br, flow, packet != NULL, tags, &vlan, &in_port)) {
2931         out_port = NULL;
2932         goto done;
2933     }
2934
2935     /* Learn source MAC (but don't try to learn from revalidation). */
2936     if (packet) {
2937         update_learning_table(br, flow, vlan, in_port);
2938     }
2939
2940     /* Determine output port. */
2941     mac = mac_learning_lookup(br->ml, flow->dl_dst, vlan, tags);
2942     if (mac) {
2943         out_port = mac->port.p;
2944     } else if (!packet && !eth_addr_is_multicast(flow->dl_dst)) {
2945         /* If we are revalidating but don't have a learning entry then
2946          * eject the flow.  Installing a flow that floods packets opens
2947          * up a window of time where we could learn from a packet reflected
2948          * on a bond and blackhole packets before the learning table is
2949          * updated to reflect the correct port. */
2950         return false;
2951     } else {
2952         out_port = FLOOD_PORT;
2953     }
2954
2955     /* Don't send packets out their input ports. */
2956     if (in_port == out_port) {
2957         out_port = NULL;
2958     }
2959
2960 done:
2961     if (in_port) {
2962         compose_actions(br, flow, vlan, in_port, out_port, tags, actions,
2963                         nf_output_iface);
2964     }
2965
2966     return true;
2967 }
2968
2969 static bool
2970 bridge_normal_ofhook_cb(const struct flow *flow, const struct ofpbuf *packet,
2971                         struct ofpbuf *actions, tag_type *tags,
2972                         uint16_t *nf_output_iface, void *br_)
2973 {
2974     struct bridge *br = br_;
2975
2976     COVERAGE_INC(bridge_process_flow);
2977     return process_flow(br, flow, packet, actions, tags, nf_output_iface);
2978 }
2979
2980 static bool
2981 bridge_special_ofhook_cb(const struct flow *flow,
2982                          const struct ofpbuf *packet, void *br_)
2983 {
2984     struct iface *iface;
2985     struct bridge *br = br_;
2986
2987     iface = iface_from_dp_ifidx(br, flow->in_port);
2988
2989     if (flow->dl_type == htons(ETH_TYPE_LACP)) {
2990
2991         if (iface && iface->port->lacp && packet) {
2992             const struct lacp_pdu *pdu = parse_lacp_packet(packet);
2993
2994             if (pdu) {
2995                 COVERAGE_INC(bridge_process_lacp);
2996                 lacp_process_pdu(iface->port->lacp, iface, pdu);
2997             }
2998         }
2999         return false;
3000     }
3001
3002     return true;
3003 }
3004
3005 static void
3006 bridge_account_flow_ofhook_cb(const struct flow *flow, tag_type tags,
3007                               const struct nlattr *actions,
3008                               size_t actions_len,
3009                               uint64_t n_bytes, void *br_)
3010 {
3011     struct bridge *br = br_;
3012     const struct nlattr *a;
3013     struct port *in_port;
3014     tag_type dummy = 0;
3015     unsigned int left;
3016     int vlan;
3017
3018     /* Feed information from the active flows back into the learning table to
3019      * ensure that table is always in sync with what is actually flowing
3020      * through the datapath.
3021      *
3022      * We test that 'tags' is nonzero to ensure that only flows that include an
3023      * OFPP_NORMAL action are used for learning.  This works because
3024      * bridge_normal_ofhook_cb() always sets a nonzero tag value. */
3025     if (tags && is_admissible(br, flow, false, &dummy, &vlan, &in_port)) {
3026         update_learning_table(br, flow, vlan, in_port);
3027     }
3028
3029     /* Account for bond slave utilization. */
3030     if (!br->has_bonded_ports) {
3031         return;
3032     }
3033     NL_ATTR_FOR_EACH_UNSAFE (a, left, actions, actions_len) {
3034         if (nl_attr_type(a) == ODP_ACTION_ATTR_OUTPUT) {
3035             struct port *out_port = port_from_dp_ifidx(br, nl_attr_get_u32(a));
3036             if (out_port && out_port->n_ifaces >= 2 &&
3037                 out_port->bond_mode != BM_AB) {
3038                 uint16_t vlan = (flow->vlan_tci
3039                                  ? vlan_tci_to_vid(flow->vlan_tci)
3040                                  : OFP_VLAN_NONE);
3041                 struct bond_entry *e = lookup_bond_entry(out_port, flow, vlan);
3042                 e->tx_bytes += n_bytes;
3043             }
3044         }
3045     }
3046 }
3047
3048 static void
3049 bridge_account_checkpoint_ofhook_cb(void *br_)
3050 {
3051     struct bridge *br = br_;
3052     struct port *port;
3053     long long int now;
3054
3055     if (!br->has_bonded_ports) {
3056         return;
3057     }
3058
3059     now = time_msec();
3060     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
3061         if (port->n_ifaces > 1 && port->bond_mode != BM_AB
3062             && now >= port->bond_next_rebalance) {
3063             port->bond_next_rebalance = now + port->bond_rebalance_interval;
3064             bond_rebalance_port(port);
3065         }
3066     }
3067 }
3068
3069 static struct ofhooks bridge_ofhooks = {
3070     bridge_normal_ofhook_cb,
3071     bridge_special_ofhook_cb,
3072     bridge_account_flow_ofhook_cb,
3073     bridge_account_checkpoint_ofhook_cb,
3074 };
3075 \f
3076 /* Bonding functions. */
3077
3078 /* Statistics for a single interface on a bonded port, used for load-based
3079  * bond rebalancing.  */
3080 struct slave_balance {
3081     struct iface *iface;        /* The interface. */
3082     uint64_t tx_bytes;          /* Sum of hashes[*]->tx_bytes. */
3083
3084     /* All the "bond_entry"s that are assigned to this interface, in order of
3085      * increasing tx_bytes. */
3086     struct bond_entry **hashes;
3087     size_t n_hashes;
3088 };
3089
3090 static const char *
3091 bond_mode_to_string(enum bond_mode bm) {
3092     static char *bm_slb = "balance-slb";
3093     static char *bm_ab  = "active-backup";
3094     static char *bm_tcp = "balance-tcp";
3095
3096     switch (bm) {
3097     case BM_SLB: return bm_slb;
3098     case BM_AB:  return bm_ab;
3099     case BM_TCP: return bm_tcp;
3100     }
3101
3102     NOT_REACHED();
3103     return NULL;
3104 }
3105
3106 /* Sorts pointers to pointers to bond_entries in ascending order by the
3107  * interface to which they are assigned, and within a single interface in
3108  * ascending order of bytes transmitted. */
3109 static int
3110 compare_bond_entries(const void *a_, const void *b_)
3111 {
3112     const struct bond_entry *const *ap = a_;
3113     const struct bond_entry *const *bp = b_;
3114     const struct bond_entry *a = *ap;
3115     const struct bond_entry *b = *bp;
3116     if (a->iface != b->iface) {
3117         return a->iface > b->iface ? 1 : -1;
3118     } else if (a->tx_bytes != b->tx_bytes) {
3119         return a->tx_bytes > b->tx_bytes ? 1 : -1;
3120     } else {
3121         return 0;
3122     }
3123 }
3124
3125 /* Sorts slave_balances so that enabled ports come first, and otherwise in
3126  * *descending* order by number of bytes transmitted. */
3127 static int
3128 compare_slave_balance(const void *a_, const void *b_)
3129 {
3130     const struct slave_balance *a = a_;
3131     const struct slave_balance *b = b_;
3132     if (a->iface->enabled != b->iface->enabled) {
3133         return a->iface->enabled ? -1 : 1;
3134     } else if (a->tx_bytes != b->tx_bytes) {
3135         return a->tx_bytes > b->tx_bytes ? -1 : 1;
3136     } else {
3137         return 0;
3138     }
3139 }
3140
3141 static void
3142 swap_bals(struct slave_balance *a, struct slave_balance *b)
3143 {
3144     struct slave_balance tmp = *a;
3145     *a = *b;
3146     *b = tmp;
3147 }
3148
3149 /* Restores the 'n_bals' slave_balance structures in 'bals' to sorted order
3150  * given that 'p' (and only 'p') might be in the wrong location.
3151  *
3152  * This function invalidates 'p', since it might now be in a different memory
3153  * location. */
3154 static void
3155 resort_bals(struct slave_balance *p,
3156             struct slave_balance bals[], size_t n_bals)
3157 {
3158     if (n_bals > 1) {
3159         for (; p > bals && p->tx_bytes > p[-1].tx_bytes; p--) {
3160             swap_bals(p, p - 1);
3161         }
3162         for (; p < &bals[n_bals - 1] && p->tx_bytes < p[1].tx_bytes; p++) {
3163             swap_bals(p, p + 1);
3164         }
3165     }
3166 }
3167
3168 static void
3169 log_bals(const struct slave_balance *bals, size_t n_bals, struct port *port)
3170 {
3171     if (VLOG_IS_DBG_ENABLED()) {
3172         struct ds ds = DS_EMPTY_INITIALIZER;
3173         const struct slave_balance *b;
3174
3175         for (b = bals; b < bals + n_bals; b++) {
3176             size_t i;
3177
3178             if (b > bals) {
3179                 ds_put_char(&ds, ',');
3180             }
3181             ds_put_format(&ds, " %s %"PRIu64"kB",
3182                           b->iface->name, b->tx_bytes / 1024);
3183
3184             if (!b->iface->enabled) {
3185                 ds_put_cstr(&ds, " (disabled)");
3186             }
3187             if (b->n_hashes > 0) {
3188                 ds_put_cstr(&ds, " (");
3189                 for (i = 0; i < b->n_hashes; i++) {
3190                     const struct bond_entry *e = b->hashes[i];
3191                     if (i > 0) {
3192                         ds_put_cstr(&ds, " + ");
3193                     }
3194                     ds_put_format(&ds, "h%td: %"PRIu64"kB",
3195                                   e - port->bond_hash, e->tx_bytes / 1024);
3196                 }
3197                 ds_put_cstr(&ds, ")");
3198             }
3199         }
3200         VLOG_DBG("bond %s:%s", port->name, ds_cstr(&ds));
3201         ds_destroy(&ds);
3202     }
3203 }
3204
3205 /* Shifts 'hash' from 'from' to 'to' within 'port'. */
3206 static void
3207 bond_shift_load(struct slave_balance *from, struct slave_balance *to,
3208                 int hash_idx)
3209 {
3210     struct bond_entry *hash = from->hashes[hash_idx];
3211     struct port *port = from->iface->port;
3212     uint64_t delta = hash->tx_bytes;
3213
3214     assert(port->bond_mode != BM_AB);
3215
3216     VLOG_INFO("bond %s: shift %"PRIu64"kB of load (with hash %td) "
3217               "from %s to %s (now carrying %"PRIu64"kB and "
3218               "%"PRIu64"kB load, respectively)",
3219               port->name, delta / 1024, hash - port->bond_hash,
3220               from->iface->name, to->iface->name,
3221               (from->tx_bytes - delta) / 1024,
3222               (to->tx_bytes + delta) / 1024);
3223
3224     /* Delete element from from->hashes.
3225      *
3226      * We don't bother to add the element to to->hashes because not only would
3227      * it require more work, the only purpose it would be to allow that hash to
3228      * be migrated to another slave in this rebalancing run, and there is no
3229      * point in doing that.  */
3230     if (hash_idx == 0) {
3231         from->hashes++;
3232     } else {
3233         memmove(from->hashes + hash_idx, from->hashes + hash_idx + 1,
3234                 (from->n_hashes - (hash_idx + 1)) * sizeof *from->hashes);
3235     }
3236     from->n_hashes--;
3237
3238     /* Shift load away from 'from' to 'to'. */
3239     from->tx_bytes -= delta;
3240     to->tx_bytes += delta;
3241
3242     /* Arrange for flows to be revalidated. */
3243     ofproto_revalidate(port->bridge->ofproto, hash->tag);
3244     hash->iface = to->iface;
3245     hash->tag = tag_create_random();
3246 }
3247
3248 static void
3249 bond_rebalance_port(struct port *port)
3250 {
3251     struct slave_balance *bals;
3252     size_t n_bals;
3253     struct bond_entry *hashes[BOND_MASK + 1];
3254     struct slave_balance *b, *from, *to;
3255     struct bond_entry *e;
3256     struct iface *iface;
3257     size_t i;
3258
3259     assert(port->bond_mode != BM_AB);
3260
3261     /* Sets up 'bals' to describe each of the port's interfaces, sorted in
3262      * descending order of tx_bytes, so that bals[0] represents the most
3263      * heavily loaded slave and bals[n_bals - 1] represents the least heavily
3264      * loaded slave.
3265      *
3266      * The code is a bit tricky: to avoid dynamically allocating a 'hashes'
3267      * array for each slave_balance structure, we sort our local array of
3268      * hashes in order by slave, so that all of the hashes for a given slave
3269      * become contiguous in memory, and then we point each 'hashes' members of
3270      * a slave_balance structure to the start of a contiguous group. */
3271     n_bals = port->n_ifaces;
3272     b = bals = xmalloc(n_bals * sizeof *bals);
3273     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
3274         b->iface = iface;
3275         b->tx_bytes = 0;
3276         b->hashes = NULL;
3277         b->n_hashes = 0;
3278         b++;
3279     }
3280     assert(b == &bals[n_bals]);
3281     for (i = 0; i <= BOND_MASK; i++) {
3282         hashes[i] = &port->bond_hash[i];
3283     }
3284     qsort(hashes, BOND_MASK + 1, sizeof *hashes, compare_bond_entries);
3285     for (i = 0; i <= BOND_MASK; i++) {
3286         e = hashes[i];
3287         if (!e->iface) {
3288             continue;
3289         }
3290
3291         for (b = bals; b < &bals[n_bals]; b++) {
3292             if (b->iface == e->iface) {
3293                 b->tx_bytes += e->tx_bytes;
3294                 if (!b->hashes) {
3295                     b->hashes = &hashes[i];
3296                 }
3297                 b->n_hashes++;
3298                 break;
3299             }
3300         }
3301     }
3302     qsort(bals, n_bals, sizeof *bals, compare_slave_balance);
3303     log_bals(bals, n_bals, port);
3304
3305     /* Discard slaves that aren't enabled (which were sorted to the back of the
3306      * array earlier). */
3307     while (!bals[n_bals - 1].iface->enabled) {
3308         n_bals--;
3309         if (!n_bals) {
3310             goto exit;
3311         }
3312     }
3313
3314     /* Shift load from the most-loaded slaves to the least-loaded slaves. */
3315     to = &bals[n_bals - 1];
3316     for (from = bals; from < to; ) {
3317         uint64_t overload = from->tx_bytes - to->tx_bytes;
3318         if (overload < to->tx_bytes >> 5 || overload < 100000) {
3319             /* The extra load on 'from' (and all less-loaded slaves), compared
3320              * to that of 'to' (the least-loaded slave), is less than ~3%, or
3321              * it is less than ~1Mbps.  No point in rebalancing. */
3322             break;
3323         } else if (from->n_hashes == 1) {
3324             /* 'from' only carries a single MAC hash, so we can't shift any
3325              * load away from it, even though we want to. */
3326             from++;
3327         } else {
3328             /* 'from' is carrying significantly more load than 'to', and that
3329              * load is split across at least two different hashes.  Pick a hash
3330              * to migrate to 'to' (the least-loaded slave), given that doing so
3331              * must decrease the ratio of the load on the two slaves by at
3332              * least 0.1.
3333              *
3334              * The sort order we use means that we prefer to shift away the
3335              * smallest hashes instead of the biggest ones.  There is little
3336              * reason behind this decision; we could use the opposite sort
3337              * order to shift away big hashes ahead of small ones. */
3338             bool order_swapped;
3339
3340             for (i = 0; i < from->n_hashes; i++) {
3341                 double old_ratio, new_ratio;
3342                 uint64_t delta = from->hashes[i]->tx_bytes;
3343
3344                 if (delta == 0 || from->tx_bytes - delta == 0) {
3345                     /* Pointless move. */
3346                     continue;
3347                 }
3348
3349                 order_swapped = from->tx_bytes - delta < to->tx_bytes + delta;
3350
3351                 if (to->tx_bytes == 0) {
3352                     /* Nothing on the new slave, move it. */
3353                     break;
3354                 }
3355
3356                 old_ratio = (double)from->tx_bytes / to->tx_bytes;
3357                 new_ratio = (double)(from->tx_bytes - delta) /
3358                             (to->tx_bytes + delta);
3359
3360                 if (new_ratio == 0) {
3361                     /* Should already be covered but check to prevent division
3362                      * by zero. */
3363                     continue;
3364                 }
3365
3366                 if (new_ratio < 1) {
3367                     new_ratio = 1 / new_ratio;
3368                 }
3369
3370                 if (old_ratio - new_ratio > 0.1) {
3371                     /* Would decrease the ratio, move it. */
3372                     break;
3373                 }
3374             }
3375             if (i < from->n_hashes) {
3376                 bond_shift_load(from, to, i);
3377
3378                 /* If the result of the migration changed the relative order of
3379                  * 'from' and 'to' swap them back to maintain invariants. */
3380                 if (order_swapped) {
3381                     swap_bals(from, to);
3382                 }
3383
3384                 /* Re-sort 'bals'.  Note that this may make 'from' and 'to'
3385                  * point to different slave_balance structures.  It is only
3386                  * valid to do these two operations in a row at all because we
3387                  * know that 'from' will not move past 'to' and vice versa. */
3388                 resort_bals(from, bals, n_bals);
3389                 resort_bals(to, bals, n_bals);
3390             } else {
3391                 from++;
3392             }
3393         }
3394     }
3395
3396     /* Implement exponentially weighted moving average.  A weight of 1/2 causes
3397      * historical data to decay to <1% in 7 rebalancing runs.  */
3398     for (e = &port->bond_hash[0]; e <= &port->bond_hash[BOND_MASK]; e++) {
3399         e->tx_bytes /= 2;
3400         if (!e->tx_bytes) {
3401             e->iface = NULL;
3402         }
3403     }
3404
3405 exit:
3406     free(bals);
3407 }
3408
3409 static void
3410 bond_send_learning_packets(struct port *port)
3411 {
3412     struct bridge *br = port->bridge;
3413     struct mac_entry *e;
3414     struct ofpbuf packet;
3415     int error, n_packets, n_errors;
3416
3417     if (!port->n_ifaces || !port->active_iface || bond_is_tcp_hash(port)) {
3418         return;
3419     }
3420
3421     ofpbuf_init(&packet, 128);
3422     error = n_packets = n_errors = 0;
3423     LIST_FOR_EACH (e, lru_node, &br->ml->lrus) {
3424         tag_type tags = 0;
3425         uint16_t dp_ifidx;
3426         struct flow flow;
3427         int retval;
3428
3429         if (e->port.p == port) {
3430             continue;
3431         }
3432
3433         compose_benign_packet(&packet, "Open vSwitch Bond Failover", 0xf177,
3434                               e->mac);
3435         flow_extract(&packet, 0, ODPP_NONE, &flow);
3436
3437         if (!choose_output_iface(port, &flow, e->vlan, &dp_ifidx, &tags)) {
3438             continue;
3439         }
3440
3441         /* Send packet. */
3442         n_packets++;
3443         retval = ofproto_send_packet(br->ofproto, dp_ifidx, e->vlan, &packet);
3444         if (retval) {
3445             error = retval;
3446             n_errors++;
3447         }
3448     }
3449     ofpbuf_uninit(&packet);
3450
3451     if (n_errors) {
3452         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3453         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
3454                      "packets, last error was: %s",
3455                      port->name, n_errors, n_packets, strerror(error));
3456     } else {
3457         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
3458                  port->name, n_packets);
3459     }
3460 }
3461 \f
3462 /* Bonding unixctl user interface functions. */
3463
3464 static void
3465 bond_unixctl_list(struct unixctl_conn *conn,
3466                   const char *args OVS_UNUSED, void *aux OVS_UNUSED)
3467 {
3468     struct ds ds = DS_EMPTY_INITIALIZER;
3469     const struct bridge *br;
3470
3471     ds_put_cstr(&ds, "bridge\tbond\ttype\tslaves\n");
3472
3473     LIST_FOR_EACH (br, node, &all_bridges) {
3474         struct port *port;
3475
3476         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
3477             if (port->n_ifaces > 1) {
3478                 struct iface *iface;
3479
3480                 ds_put_format(&ds, "%s\t%s\t%s\t", br->name, port->name,
3481                               bond_mode_to_string(port->bond_mode));
3482                 LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
3483                     if (&iface->port_elem != list_front(&port->ifaces)) {
3484                         ds_put_cstr(&ds, ", ");
3485                     }
3486                     ds_put_cstr(&ds, iface->name);
3487                 }
3488                 ds_put_char(&ds, '\n');
3489             }
3490         }
3491     }
3492     unixctl_command_reply(conn, 200, ds_cstr(&ds));
3493     ds_destroy(&ds);
3494 }
3495
3496 static struct port *
3497 bond_find(const char *name)
3498 {
3499     const struct bridge *br;
3500
3501     LIST_FOR_EACH (br, node, &all_bridges) {
3502         struct port *port;
3503
3504         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
3505             if (!strcmp(port->name, name) && port->n_ifaces > 1) {
3506                 return port;
3507             }
3508         }
3509     }
3510     return NULL;
3511 }
3512
3513 static void
3514 bond_unixctl_show(struct unixctl_conn *conn,
3515                   const char *args, void *aux OVS_UNUSED)
3516 {
3517     struct ds ds = DS_EMPTY_INITIALIZER;
3518     const struct port *port;
3519     struct iface *iface;
3520
3521     port = bond_find(args);
3522     if (!port) {
3523         unixctl_command_reply(conn, 501, "no such bond");
3524         return;
3525     }
3526
3527     ds_put_format(&ds, "bond_mode: %s\n",
3528                   bond_mode_to_string(port->bond_mode));
3529
3530     if (port->lacp) {
3531         ds_put_format(&ds, "lacp: %s\n",
3532                       port->lacp_active ? "active" : "passive");
3533     } else {
3534         ds_put_cstr(&ds, "lacp: off\n");
3535     }
3536
3537     if (port->bond_mode != BM_AB) {
3538         ds_put_format(&ds, "bond-hash-algorithm: %s\n",
3539                       bond_is_tcp_hash(port) ? "balance-tcp" : "balance-slb");
3540     }
3541
3542
3543     ds_put_format(&ds, "bond-detect-mode: %s\n",
3544                   port->monitor ? "carrier" : "miimon");
3545
3546     if (!port->monitor) {
3547         ds_put_format(&ds, "bond-miimon-interval: %lld\n",
3548                       port->miimon_interval);
3549     }
3550
3551     ds_put_format(&ds, "updelay: %d ms\n", port->updelay);
3552     ds_put_format(&ds, "downdelay: %d ms\n", port->downdelay);
3553
3554     if (port->bond_mode != BM_AB) {
3555         ds_put_format(&ds, "next rebalance: %lld ms\n",
3556                       port->bond_next_rebalance - time_msec());
3557     }
3558
3559     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
3560         struct bond_entry *be;
3561         struct flow flow;
3562
3563         /* Basic info. */
3564         ds_put_format(&ds, "\nslave %s: %s\n",
3565                       iface->name, iface->enabled ? "enabled" : "disabled");
3566         if (iface == port->active_iface) {
3567             ds_put_cstr(&ds, "\tactive slave\n");
3568         }
3569         if (iface->delay_expires != LLONG_MAX) {
3570             ds_put_format(&ds, "\t%s expires in %lld ms\n",
3571                           iface->enabled ? "downdelay" : "updelay",
3572                           iface->delay_expires - time_msec());
3573         }
3574
3575         if (port->bond_mode == BM_AB) {
3576             continue;
3577         }
3578
3579         /* Hashes. */
3580         memset(&flow, 0, sizeof flow);
3581         for (be = port->bond_hash; be <= &port->bond_hash[BOND_MASK]; be++) {
3582             int hash = be - port->bond_hash;
3583             struct mac_entry *me;
3584
3585             if (be->iface != iface) {
3586                 continue;
3587             }
3588
3589             ds_put_format(&ds, "\thash %d: %"PRIu64" kB load\n",
3590                           hash, be->tx_bytes / 1024);
3591
3592             if (port->bond_mode != BM_SLB) {
3593                 continue;
3594             }
3595
3596             /* MACs. */
3597             LIST_FOR_EACH (me, lru_node, &port->bridge->ml->lrus) {
3598                 uint16_t dp_ifidx;
3599                 tag_type tags = 0;
3600
3601                 memcpy(flow.dl_src, me->mac, ETH_ADDR_LEN);
3602                 if (bond_hash_src(me->mac, me->vlan) == hash
3603                     && me->port.p != port
3604                     && choose_output_iface(port, &flow, me->vlan,
3605                                            &dp_ifidx, &tags)
3606                     && dp_ifidx == iface->dp_ifidx)
3607                 {
3608                     ds_put_format(&ds, "\t\t"ETH_ADDR_FMT"\n",
3609                                   ETH_ADDR_ARGS(me->mac));
3610                 }
3611             }
3612         }
3613     }
3614     unixctl_command_reply(conn, 200, ds_cstr(&ds));
3615     ds_destroy(&ds);
3616 }
3617
3618 static void
3619 bond_unixctl_migrate(struct unixctl_conn *conn, const char *args_,
3620                      void *aux OVS_UNUSED)
3621 {
3622     char *args = (char *) args_;
3623     char *save_ptr = NULL;
3624     char *bond_s, *hash_s, *slave_s;
3625     struct port *port;
3626     struct iface *iface;
3627     struct bond_entry *entry;
3628     int hash;
3629
3630     bond_s = strtok_r(args, " ", &save_ptr);
3631     hash_s = strtok_r(NULL, " ", &save_ptr);
3632     slave_s = strtok_r(NULL, " ", &save_ptr);
3633     if (!slave_s) {
3634         unixctl_command_reply(conn, 501,
3635                               "usage: bond/migrate BOND HASH SLAVE");
3636         return;
3637     }
3638
3639     port = bond_find(bond_s);
3640     if (!port) {
3641         unixctl_command_reply(conn, 501, "no such bond");
3642         return;
3643     }
3644
3645     if (port->bond_mode != BM_SLB) {
3646         unixctl_command_reply(conn, 501, "not an SLB bond");
3647         return;
3648     }
3649
3650     if (strspn(hash_s, "0123456789") == strlen(hash_s)) {
3651         hash = atoi(hash_s) & BOND_MASK;
3652     } else {
3653         unixctl_command_reply(conn, 501, "bad hash");
3654         return;
3655     }
3656
3657     iface = port_lookup_iface(port, slave_s);
3658     if (!iface) {
3659         unixctl_command_reply(conn, 501, "no such slave");
3660         return;
3661     }
3662
3663     if (!iface->enabled) {
3664         unixctl_command_reply(conn, 501, "cannot migrate to disabled slave");
3665         return;
3666     }
3667
3668     entry = &port->bond_hash[hash];
3669     ofproto_revalidate(port->bridge->ofproto, entry->tag);
3670     entry->iface = iface;
3671     entry->tag = tag_create_random();
3672     unixctl_command_reply(conn, 200, "migrated");
3673 }
3674
3675 static void
3676 bond_unixctl_set_active_slave(struct unixctl_conn *conn, const char *args_,
3677                               void *aux OVS_UNUSED)
3678 {
3679     char *args = (char *) args_;
3680     char *save_ptr = NULL;
3681     char *bond_s, *slave_s;
3682     struct port *port;
3683     struct iface *iface;
3684
3685     bond_s = strtok_r(args, " ", &save_ptr);
3686     slave_s = strtok_r(NULL, " ", &save_ptr);
3687     if (!slave_s) {
3688         unixctl_command_reply(conn, 501,
3689                               "usage: bond/set-active-slave BOND SLAVE");
3690         return;
3691     }
3692
3693     port = bond_find(bond_s);
3694     if (!port) {
3695         unixctl_command_reply(conn, 501, "no such bond");
3696         return;
3697     }
3698
3699     iface = port_lookup_iface(port, slave_s);
3700     if (!iface) {
3701         unixctl_command_reply(conn, 501, "no such slave");
3702         return;
3703     }
3704
3705     if (!iface->enabled) {
3706         unixctl_command_reply(conn, 501, "cannot make disabled slave active");
3707         return;
3708     }
3709
3710     if (port->active_iface != iface) {
3711         ofproto_revalidate(port->bridge->ofproto,
3712                            port_get_active_iface_tag(port));
3713         port->active_iface = iface;
3714         VLOG_INFO("port %s: active interface is now %s",
3715                   port->name, iface->name);
3716         bond_send_learning_packets(port);
3717         unixctl_command_reply(conn, 200, "done");
3718     } else {
3719         unixctl_command_reply(conn, 200, "no change");
3720     }
3721 }
3722
3723 static void
3724 enable_slave(struct unixctl_conn *conn, const char *args_, bool enable)
3725 {
3726     char *args = (char *) args_;
3727     char *save_ptr = NULL;
3728     char *bond_s, *slave_s;
3729     struct port *port;
3730     struct iface *iface;
3731
3732     bond_s = strtok_r(args, " ", &save_ptr);
3733     slave_s = strtok_r(NULL, " ", &save_ptr);
3734     if (!slave_s) {
3735         unixctl_command_reply(conn, 501,
3736                               "usage: bond/enable/disable-slave BOND SLAVE");
3737         return;
3738     }
3739
3740     port = bond_find(bond_s);
3741     if (!port) {
3742         unixctl_command_reply(conn, 501, "no such bond");
3743         return;
3744     }
3745
3746     iface = port_lookup_iface(port, slave_s);
3747     if (!iface) {
3748         unixctl_command_reply(conn, 501, "no such slave");
3749         return;
3750     }
3751
3752     bond_enable_slave(iface, enable);
3753     unixctl_command_reply(conn, 501, enable ? "enabled" : "disabled");
3754 }
3755
3756 static void
3757 bond_unixctl_enable_slave(struct unixctl_conn *conn, const char *args,
3758                           void *aux OVS_UNUSED)
3759 {
3760     enable_slave(conn, args, true);
3761 }
3762
3763 static void
3764 bond_unixctl_disable_slave(struct unixctl_conn *conn, const char *args,
3765                            void *aux OVS_UNUSED)
3766 {
3767     enable_slave(conn, args, false);
3768 }
3769
3770 static void
3771 bond_unixctl_hash(struct unixctl_conn *conn, const char *args_,
3772                   void *aux OVS_UNUSED)
3773 {
3774     char *args = (char *) args_;
3775     uint8_t mac[ETH_ADDR_LEN];
3776     uint8_t hash;
3777     char *hash_cstr;
3778     unsigned int vlan;
3779     char *mac_s, *vlan_s;
3780     char *save_ptr = NULL;
3781
3782     mac_s  = strtok_r(args, " ", &save_ptr);
3783     vlan_s = strtok_r(NULL, " ", &save_ptr);
3784
3785     if (vlan_s) {
3786         if (sscanf(vlan_s, "%u", &vlan) != 1) {
3787             unixctl_command_reply(conn, 501, "invalid vlan");
3788             return;
3789         }
3790     } else {
3791         vlan = OFP_VLAN_NONE;
3792     }
3793
3794     if (sscanf(mac_s, ETH_ADDR_SCAN_FMT, ETH_ADDR_SCAN_ARGS(mac))
3795         == ETH_ADDR_SCAN_COUNT) {
3796         hash = bond_hash_src(mac, vlan);
3797
3798         hash_cstr = xasprintf("%u", hash);
3799         unixctl_command_reply(conn, 200, hash_cstr);
3800         free(hash_cstr);
3801     } else {
3802         unixctl_command_reply(conn, 501, "invalid mac");
3803     }
3804 }
3805
3806 static void
3807 bond_init(void)
3808 {
3809     unixctl_command_register("bond/list", bond_unixctl_list, NULL);
3810     unixctl_command_register("bond/show", bond_unixctl_show, NULL);
3811     unixctl_command_register("bond/migrate", bond_unixctl_migrate, NULL);
3812     unixctl_command_register("bond/set-active-slave",
3813                              bond_unixctl_set_active_slave, NULL);
3814     unixctl_command_register("bond/enable-slave", bond_unixctl_enable_slave,
3815                              NULL);
3816     unixctl_command_register("bond/disable-slave", bond_unixctl_disable_slave,
3817                              NULL);
3818     unixctl_command_register("bond/hash", bond_unixctl_hash, NULL);
3819 }
3820 \f
3821 /* Port functions. */
3822
3823 static void
3824 lacp_send_pdu_cb(void *aux, const struct lacp_pdu *pdu)
3825 {
3826     struct iface *iface = aux;
3827     uint8_t ea[ETH_ADDR_LEN];
3828     int error;
3829
3830     error = netdev_get_etheraddr(iface->netdev, ea);
3831     if (!error) {
3832         struct ofpbuf packet;
3833         struct lacp_pdu *packet_pdu;
3834
3835         ofpbuf_init(&packet, 0);
3836         packet_pdu = compose_packet(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
3837                                     sizeof *packet_pdu);
3838         memcpy(packet_pdu, pdu, sizeof *packet_pdu);
3839         ofproto_send_packet(iface->port->bridge->ofproto,
3840                             iface->dp_ifidx, 0, &packet);
3841         ofpbuf_uninit(&packet);
3842     } else {
3843         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
3844         VLOG_ERR_RL(&rl, "iface %s: failed to obtain Ethernet address "
3845                     "(%s)", iface->name, strerror(error));
3846     }
3847 }
3848
3849 static void
3850 port_run(struct port *port)
3851 {
3852     if (port->monitor) {
3853         char *devname;
3854
3855         /* Track carrier going up and down on interfaces. */
3856         while (!netdev_monitor_poll(port->monitor, &devname)) {
3857             struct iface *iface;
3858
3859             iface = port_lookup_iface(port, devname);
3860             if (iface) {
3861                 iface_update_carrier(iface);
3862             }
3863             free(devname);
3864         }
3865     } else if (time_msec() >= port->miimon_next_update) {
3866         struct iface *iface;
3867
3868         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
3869             iface_update_carrier(iface);
3870         }
3871         port->miimon_next_update = time_msec() + port->miimon_interval;
3872     }
3873
3874     if (port->lacp) {
3875         struct iface *iface;
3876
3877         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
3878             lacp_slave_enable(port->lacp, iface, iface->enabled);
3879         }
3880
3881         lacp_run(port->lacp, lacp_send_pdu_cb);
3882     }
3883
3884     bond_run(port);
3885 }
3886
3887 static void
3888 port_wait(struct port *port)
3889 {
3890     if (port->monitor) {
3891         netdev_monitor_poll_wait(port->monitor);
3892     } else {
3893         poll_timer_wait_until(port->miimon_next_update);
3894     }
3895
3896     if (port->lacp) {
3897         lacp_wait(port->lacp);
3898     }
3899
3900     bond_wait(port);
3901 }
3902
3903 static struct port *
3904 port_create(struct bridge *br, const char *name)
3905 {
3906     struct port *port;
3907
3908     port = xzalloc(sizeof *port);
3909     port->bridge = br;
3910     port->vlan = -1;
3911     port->trunks = NULL;
3912     port->name = xstrdup(name);
3913     port->active_iface = NULL;
3914     list_init(&port->ifaces);
3915
3916     hmap_insert(&br->ports, &port->hmap_node, hash_string(port->name, 0));
3917
3918     VLOG_INFO("created port %s on bridge %s", port->name, br->name);
3919     bridge_flush(br);
3920
3921     return port;
3922 }
3923
3924 static const char *
3925 get_port_other_config(const struct ovsrec_port *port, const char *key,
3926                       const char *default_value)
3927 {
3928     const char *value;
3929
3930     value = get_ovsrec_key_value(&port->header_, &ovsrec_port_col_other_config,
3931                                  key);
3932     return value ? value : default_value;
3933 }
3934
3935 static const char *
3936 get_interface_other_config(const struct ovsrec_interface *iface,
3937                            const char *key, const char *default_value)
3938 {
3939     const char *value;
3940
3941     value = get_ovsrec_key_value(&iface->header_,
3942                                  &ovsrec_interface_col_other_config, key);
3943     return value ? value : default_value;
3944 }
3945
3946 static void
3947 port_del_ifaces(struct port *port, const struct ovsrec_port *cfg)
3948 {
3949     struct iface *iface, *next;
3950     struct sset new_ifaces;
3951     size_t i;
3952
3953     /* Collect list of new interfaces. */
3954     sset_init(&new_ifaces);
3955     for (i = 0; i < cfg->n_interfaces; i++) {
3956         const char *name = cfg->interfaces[i]->name;
3957         sset_add(&new_ifaces, name);
3958     }
3959
3960     /* Get rid of deleted interfaces. */
3961     LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
3962         if (!sset_contains(&new_ifaces, iface->name)) {
3963             iface_destroy(iface);
3964         }
3965     }
3966
3967     sset_destroy(&new_ifaces);
3968 }
3969
3970 /* Expires all MAC learning entries associated with 'port' and forces ofproto
3971  * to revalidate every flow. */
3972 static void
3973 port_flush_macs(struct port *port)
3974 {
3975     struct bridge *br = port->bridge;
3976     struct mac_learning *ml = br->ml;
3977     struct mac_entry *mac, *next_mac;
3978
3979     bridge_flush(br);
3980     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
3981         if (mac->port.p == port) {
3982             mac_learning_expire(ml, mac);
3983         }
3984     }
3985 }
3986
3987 static void
3988 port_reconfigure(struct port *port, const struct ovsrec_port *cfg)
3989 {
3990     const char *detect_mode;
3991     struct sset new_ifaces;
3992     long long int next_rebalance, miimon_next_update, lacp_priority;
3993     bool need_flush = false;
3994     unsigned long *trunks;
3995     int vlan;
3996     size_t i;
3997
3998     port->cfg = cfg;
3999
4000     /* Update settings. */
4001     port->updelay = cfg->bond_updelay;
4002     if (port->updelay < 0) {
4003         port->updelay = 0;
4004     }
4005     port->downdelay = cfg->bond_downdelay;
4006     if (port->downdelay < 0) {
4007         port->downdelay = 0;
4008     }
4009     port->bond_rebalance_interval = atoi(
4010         get_port_other_config(cfg, "bond-rebalance-interval", "10000"));
4011     if (port->bond_rebalance_interval < 1000) {
4012         port->bond_rebalance_interval = 1000;
4013     }
4014     next_rebalance = time_msec() + port->bond_rebalance_interval;
4015     if (port->bond_next_rebalance > next_rebalance) {
4016         port->bond_next_rebalance = next_rebalance;
4017     }
4018
4019     detect_mode = get_port_other_config(cfg, "bond-detect-mode",
4020                                         "carrier");
4021
4022     netdev_monitor_destroy(port->monitor);
4023     port->monitor = NULL;
4024
4025     if (strcmp(detect_mode, "miimon")) {
4026         port->monitor = netdev_monitor_create();
4027
4028         if (strcmp(detect_mode, "carrier")) {
4029             VLOG_WARN("port %s: unsupported bond-detect-mode %s, "
4030                       "defaulting to carrier", port->name, detect_mode);
4031         }
4032     }
4033
4034     port->miimon_interval = atoi(
4035         get_port_other_config(cfg, "bond-miimon-interval", "200"));
4036     if (port->miimon_interval < 100) {
4037         port->miimon_interval = 100;
4038     }
4039     miimon_next_update = time_msec() + port->miimon_interval;
4040     if (port->miimon_next_update > miimon_next_update) {
4041         port->miimon_next_update = miimon_next_update;
4042     }
4043
4044     if (!port->cfg->bond_mode ||
4045         !strcmp(port->cfg->bond_mode, bond_mode_to_string(BM_SLB))) {
4046         port->bond_mode = BM_SLB;
4047     } else if (!strcmp(port->cfg->bond_mode, bond_mode_to_string(BM_AB))) {
4048         port->bond_mode = BM_AB;
4049     } else if (!strcmp(port->cfg->bond_mode, bond_mode_to_string(BM_TCP))) {
4050         port->bond_mode = BM_TCP;
4051     } else {
4052         port->bond_mode = BM_SLB;
4053         VLOG_WARN("port %s: unknown bond_mode %s, defaulting to %s",
4054                   port->name, port->cfg->bond_mode,
4055                   bond_mode_to_string(port->bond_mode));
4056     }
4057
4058     /* Add new interfaces and update 'cfg' member of existing ones. */
4059     sset_init(&new_ifaces);
4060     for (i = 0; i < cfg->n_interfaces; i++) {
4061         const struct ovsrec_interface *if_cfg = cfg->interfaces[i];
4062         struct iface *iface;
4063
4064         if (!sset_add(&new_ifaces, if_cfg->name)) {
4065             VLOG_WARN("port %s: %s specified twice as port interface",
4066                       port->name, if_cfg->name);
4067             iface_set_ofport(if_cfg, -1);
4068             continue;
4069         }
4070
4071         iface = iface_lookup(port->bridge, if_cfg->name);
4072         if (iface) {
4073             if (iface->port != port) {
4074                 VLOG_ERR("bridge %s: %s interface is on multiple ports, "
4075                          "removing from %s",
4076                          port->bridge->name, if_cfg->name, iface->port->name);
4077                 continue;
4078             }
4079             iface->cfg = if_cfg;
4080         } else {
4081             iface = iface_create(port, if_cfg);
4082         }
4083
4084         /* Determine interface type.  The local port always has type
4085          * "internal".  Other ports take their type from the database and
4086          * default to "system" if none is specified. */
4087         iface->type = (!strcmp(if_cfg->name, port->bridge->name) ? "internal"
4088                        : if_cfg->type[0] ? if_cfg->type
4089                        : "system");
4090
4091         lacp_priority =
4092             atoi(get_interface_other_config(if_cfg, "lacp-port-priority",
4093                                             "0"));
4094
4095         if (lacp_priority <= 0 || lacp_priority > UINT16_MAX) {
4096             iface->lacp_priority = UINT16_MAX;
4097         } else {
4098             iface->lacp_priority = lacp_priority;
4099         }
4100     }
4101     sset_destroy(&new_ifaces);
4102
4103     port->lacp_fast = !strcmp(get_port_other_config(cfg, "lacp-time", "slow"),
4104                              "fast");
4105
4106     lacp_priority =
4107         atoi(get_port_other_config(cfg, "lacp-system-priority", "0"));
4108
4109     if (lacp_priority <= 0 || lacp_priority > UINT16_MAX) {
4110         /* Prefer bondable links if unspecified. */
4111         port->lacp_priority = port->n_ifaces > 1 ? UINT16_MAX - 1 : UINT16_MAX;
4112     } else {
4113         port->lacp_priority = lacp_priority;
4114     }
4115
4116     if (!port->cfg->lacp) {
4117         /* XXX when LACP implementation has been sufficiently tested, enable by
4118          * default and make active on bonded ports. */
4119         lacp_destroy(port->lacp);
4120         port->lacp = NULL;
4121     } else if (!strcmp(port->cfg->lacp, "off")) {
4122         lacp_destroy(port->lacp);
4123         port->lacp = NULL;
4124     } else if (!strcmp(port->cfg->lacp, "active")) {
4125         if (!port->lacp) {
4126             port->lacp = lacp_create();
4127         }
4128         port->lacp_active = true;
4129     } else if (!strcmp(port->cfg->lacp, "passive")) {
4130         if (!port->lacp) {
4131             port->lacp = lacp_create();
4132         }
4133         port->lacp_active = false;
4134     } else {
4135         VLOG_WARN("port %s: unknown LACP mode %s",
4136                   port->name, port->cfg->lacp);
4137         lacp_destroy(port->lacp);
4138         port->lacp = NULL;
4139     }
4140
4141     /* Get VLAN tag. */
4142     vlan = -1;
4143     if (cfg->tag) {
4144         if (port->n_ifaces < 2) {
4145             vlan = *cfg->tag;
4146             if (vlan >= 0 && vlan <= 4095) {
4147                 VLOG_DBG("port %s: assigning VLAN tag %d", port->name, vlan);
4148             } else {
4149                 vlan = -1;
4150             }
4151         } else {
4152             /* It's possible that bonded, VLAN-tagged ports make sense.  Maybe
4153              * they even work as-is.  But they have not been tested. */
4154             VLOG_WARN("port %s: VLAN tags not supported on bonded ports",
4155                       port->name);
4156         }
4157     }
4158     if (port->vlan != vlan) {
4159         port->vlan = vlan;
4160         need_flush = true;
4161     }
4162
4163     /* Get trunked VLANs. */
4164     trunks = NULL;
4165     if (vlan < 0 && cfg->n_trunks) {
4166         size_t n_errors;
4167
4168         trunks = bitmap_allocate(4096);
4169         n_errors = 0;
4170         for (i = 0; i < cfg->n_trunks; i++) {
4171             int trunk = cfg->trunks[i];
4172             if (trunk >= 0) {
4173                 bitmap_set1(trunks, trunk);
4174             } else {
4175                 n_errors++;
4176             }
4177         }
4178         if (n_errors) {
4179             VLOG_ERR("port %s: invalid values for %zu trunk VLANs",
4180                      port->name, cfg->n_trunks);
4181         }
4182         if (n_errors == cfg->n_trunks) {
4183             VLOG_ERR("port %s: no valid trunks, trunking all VLANs",
4184                      port->name);
4185             bitmap_free(trunks);
4186             trunks = NULL;
4187         }
4188     } else if (vlan >= 0 && cfg->n_trunks) {
4189         VLOG_ERR("port %s: ignoring trunks in favor of implicit vlan",
4190                  port->name);
4191     }
4192     if (trunks == NULL
4193         ? port->trunks != NULL
4194         : port->trunks == NULL || !bitmap_equal(trunks, port->trunks, 4096)) {
4195         need_flush = true;
4196     }
4197     bitmap_free(port->trunks);
4198     port->trunks = trunks;
4199
4200     if (need_flush) {
4201         port_flush_macs(port);
4202     }
4203 }
4204
4205 static void
4206 port_destroy(struct port *port)
4207 {
4208     if (port) {
4209         struct bridge *br = port->bridge;
4210         struct iface *iface, *next;
4211         int i;
4212
4213         for (i = 0; i < MAX_MIRRORS; i++) {
4214             struct mirror *m = br->mirrors[i];
4215             if (m && m->out_port == port) {
4216                 mirror_destroy(m);
4217             }
4218         }
4219
4220         LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
4221             iface_destroy(iface);
4222         }
4223
4224         hmap_remove(&br->ports, &port->hmap_node);
4225
4226         VLOG_INFO("destroyed port %s on bridge %s", port->name, br->name);
4227
4228         port_flush_macs(port);
4229
4230         lacp_destroy(port->lacp);
4231         netdev_monitor_destroy(port->monitor);
4232         bitmap_free(port->trunks);
4233         free(port->bond_hash);
4234         free(port->name);
4235         free(port);
4236     }
4237 }
4238
4239 static struct port *
4240 port_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
4241 {
4242     struct iface *iface = iface_from_dp_ifidx(br, dp_ifidx);
4243     return iface ? iface->port : NULL;
4244 }
4245
4246 static struct port *
4247 port_lookup(const struct bridge *br, const char *name)
4248 {
4249     struct port *port;
4250
4251     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_string(name, 0),
4252                              &br->ports) {
4253         if (!strcmp(port->name, name)) {
4254             return port;
4255         }
4256     }
4257     return NULL;
4258 }
4259
4260 static struct iface *
4261 port_lookup_iface(const struct port *port, const char *name)
4262 {
4263     struct iface *iface = iface_lookup(port->bridge, name);
4264     return iface && iface->port == port ? iface : NULL;
4265 }
4266
4267 static void
4268 port_update_lacp(struct port *port)
4269 {
4270     if (port->lacp) {
4271         struct iface *iface;
4272
4273         lacp_configure(port->lacp, port->name,
4274                        port->bridge->ea, port->lacp_priority,
4275                        port->lacp_active, port->lacp_fast);
4276
4277         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
4278             lacp_slave_register(port->lacp, iface, iface->name,
4279                                 iface->dp_ifidx, iface->lacp_priority);
4280         }
4281     }
4282 }
4283
4284 static void
4285 port_update_bonding(struct port *port)
4286 {
4287     if (port->n_ifaces < 2) {
4288         /* Not a bonded port. */
4289         free(port->bond_hash);
4290         port->bond_hash = NULL;
4291         port->bond_fake_iface = false;
4292         port->active_iface = NULL;
4293         port->no_ifaces_tag = 0;
4294     } else {
4295         size_t i;
4296
4297         if (port->bond_mode != BM_AB && !port->bond_hash) {
4298             port->bond_hash = xcalloc(BOND_MASK + 1, sizeof *port->bond_hash);
4299             for (i = 0; i <= BOND_MASK; i++) {
4300                 struct bond_entry *e = &port->bond_hash[i];
4301                 e->iface = NULL;
4302                 e->tx_bytes = 0;
4303             }
4304             port->bond_next_rebalance
4305                 = time_msec() + port->bond_rebalance_interval;
4306         } else if (port->bond_mode == BM_AB) {
4307             free(port->bond_hash);
4308             port->bond_hash = NULL;
4309         }
4310
4311         if (!port->no_ifaces_tag) {
4312             port->no_ifaces_tag = tag_create_random();
4313         }
4314
4315         if (!port->active_iface) {
4316             bond_choose_active_iface(port);
4317         }
4318
4319         port->bond_fake_iface = port->cfg->bond_fake_iface;
4320         if (port->bond_fake_iface) {
4321             port->bond_next_fake_iface_update = time_msec();
4322         }
4323
4324     }
4325 }
4326 \f
4327 /* Interface functions. */
4328
4329 static struct iface *
4330 iface_create(struct port *port, const struct ovsrec_interface *if_cfg)
4331 {
4332     struct bridge *br = port->bridge;
4333     struct iface *iface;
4334     char *name = if_cfg->name;
4335
4336     iface = xzalloc(sizeof *iface);
4337     iface->port = port;
4338     iface->name = xstrdup(name);
4339     iface->dp_ifidx = -1;
4340     iface->tag = tag_create_random();
4341     iface->delay_expires = LLONG_MAX;
4342     iface->netdev = NULL;
4343     iface->cfg = if_cfg;
4344
4345     shash_add_assert(&br->iface_by_name, iface->name, iface);
4346
4347     list_push_back(&port->ifaces, &iface->port_elem);
4348     port->n_ifaces++;
4349
4350     if (port->n_ifaces > 1) {
4351         br->has_bonded_ports = true;
4352     }
4353
4354     VLOG_DBG("attached network device %s to port %s", iface->name, port->name);
4355
4356     bridge_flush(br);
4357
4358     return iface;
4359 }
4360
4361 static void
4362 iface_destroy(struct iface *iface)
4363 {
4364     if (iface) {
4365         struct port *port = iface->port;
4366         struct bridge *br = port->bridge;
4367         bool del_active = port->active_iface == iface;
4368
4369         if (port->bond_hash) {
4370             struct bond_entry *e;
4371             for (e = port->bond_hash; e <= &port->bond_hash[BOND_MASK]; e++) {
4372                 if (e->iface == iface) {
4373                     e->iface = NULL;
4374                 }
4375             }
4376         }
4377
4378         if (iface->port->lacp) {
4379             lacp_slave_unregister(iface->port->lacp, iface);
4380         }
4381
4382         if (port->monitor && iface->netdev) {
4383             netdev_monitor_remove(port->monitor, iface->netdev);
4384         }
4385
4386         shash_find_and_delete_assert(&br->iface_by_name, iface->name);
4387
4388         if (iface->dp_ifidx >= 0) {
4389             hmap_remove(&br->ifaces, &iface->dp_ifidx_node);
4390         }
4391
4392         list_remove(&iface->port_elem);
4393         port->n_ifaces--;
4394
4395         netdev_close(iface->netdev);
4396
4397         if (del_active) {
4398             bond_choose_active_iface(port);
4399             bond_send_learning_packets(port);
4400         }
4401
4402         free(iface->name);
4403         free(iface);
4404
4405         bridge_flush(port->bridge);
4406     }
4407 }
4408
4409 static struct iface *
4410 iface_lookup(const struct bridge *br, const char *name)
4411 {
4412     return shash_find_data(&br->iface_by_name, name);
4413 }
4414
4415 static struct iface *
4416 iface_find(const char *name)
4417 {
4418     const struct bridge *br;
4419
4420     LIST_FOR_EACH (br, node, &all_bridges) {
4421         struct iface *iface = iface_lookup(br, name);
4422
4423         if (iface) {
4424             return iface;
4425         }
4426     }
4427     return NULL;
4428 }
4429
4430 static struct iface *
4431 iface_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
4432 {
4433     struct iface *iface;
4434
4435     HMAP_FOR_EACH_IN_BUCKET (iface, dp_ifidx_node,
4436                              hash_int(dp_ifidx, 0), &br->ifaces) {
4437         if (iface->dp_ifidx == dp_ifidx) {
4438             return iface;
4439         }
4440     }
4441     return NULL;
4442 }
4443
4444 /* Set Ethernet address of 'iface', if one is specified in the configuration
4445  * file. */
4446 static void
4447 iface_set_mac(struct iface *iface)
4448 {
4449     uint8_t ea[ETH_ADDR_LEN];
4450
4451     if (iface->cfg->mac && eth_addr_from_string(iface->cfg->mac, ea)) {
4452         if (eth_addr_is_multicast(ea)) {
4453             VLOG_ERR("interface %s: cannot set MAC to multicast address",
4454                      iface->name);
4455         } else if (iface->dp_ifidx == ODPP_LOCAL) {
4456             VLOG_ERR("ignoring iface.%s.mac; use bridge.%s.mac instead",
4457                      iface->name, iface->name);
4458         } else {
4459             int error = netdev_set_etheraddr(iface->netdev, ea);
4460             if (error) {
4461                 VLOG_ERR("interface %s: setting MAC failed (%s)",
4462                          iface->name, strerror(error));
4463             }
4464         }
4465     }
4466 }
4467
4468 /* Sets the ofport column of 'if_cfg' to 'ofport'. */
4469 static void
4470 iface_set_ofport(const struct ovsrec_interface *if_cfg, int64_t ofport)
4471 {
4472     if (if_cfg) {
4473         ovsrec_interface_set_ofport(if_cfg, &ofport, 1);
4474     }
4475 }
4476
4477 /* Adds the 'n' key-value pairs in 'keys' in 'values' to 'shash'.
4478  *
4479  * The value strings in '*shash' are taken directly from values[], not copied,
4480  * so the caller should not modify or free them. */
4481 static void
4482 shash_from_ovs_idl_map(char **keys, char **values, size_t n,
4483                        struct shash *shash)
4484 {
4485     size_t i;
4486
4487     shash_init(shash);
4488     for (i = 0; i < n; i++) {
4489         shash_add(shash, keys[i], values[i]);
4490     }
4491 }
4492
4493 /* Creates 'keys' and 'values' arrays from 'shash'.
4494  *
4495  * Sets 'keys' and 'values' to heap allocated arrays representing the key-value
4496  * pairs in 'shash'.  The caller takes ownership of 'keys' and 'values'.  They
4497  * are populated with with strings taken directly from 'shash' and thus have
4498  * the same ownership of the key-value pairs in shash.
4499  */
4500 static void
4501 shash_to_ovs_idl_map(struct shash *shash,
4502                      char ***keys, char ***values, size_t *n)
4503 {
4504     size_t i, count;
4505     char **k, **v;
4506     struct shash_node *sn;
4507
4508     count = shash_count(shash);
4509
4510     k = xmalloc(count * sizeof *k);
4511     v = xmalloc(count * sizeof *v);
4512
4513     i = 0;
4514     SHASH_FOR_EACH(sn, shash) {
4515         k[i] = sn->name;
4516         v[i] = sn->data;
4517         i++;
4518     }
4519
4520     *n      = count;
4521     *keys   = k;
4522     *values = v;
4523 }
4524
4525 struct iface_delete_queues_cbdata {
4526     struct netdev *netdev;
4527     const struct ovsdb_datum *queues;
4528 };
4529
4530 static bool
4531 queue_ids_include(const struct ovsdb_datum *queues, int64_t target)
4532 {
4533     union ovsdb_atom atom;
4534
4535     atom.integer = target;
4536     return ovsdb_datum_find_key(queues, &atom, OVSDB_TYPE_INTEGER) != UINT_MAX;
4537 }
4538
4539 static void
4540 iface_delete_queues(unsigned int queue_id,
4541                     const struct shash *details OVS_UNUSED, void *cbdata_)
4542 {
4543     struct iface_delete_queues_cbdata *cbdata = cbdata_;
4544
4545     if (!queue_ids_include(cbdata->queues, queue_id)) {
4546         netdev_delete_queue(cbdata->netdev, queue_id);
4547     }
4548 }
4549
4550 static void
4551 iface_update_carrier(struct iface *iface)
4552 {
4553     bool carrier = iface_get_carrier(iface);
4554     if (carrier == iface->up) {
4555         return;
4556     }
4557
4558     iface->up = carrier;
4559     if (iface->port->lacp) {
4560         lacp_slave_carrier_changed(iface->port->lacp, iface);
4561     }
4562 }
4563
4564 static void
4565 iface_update_qos(struct iface *iface, const struct ovsrec_qos *qos)
4566 {
4567     if (!qos || qos->type[0] == '\0') {
4568         netdev_set_qos(iface->netdev, NULL, NULL);
4569     } else {
4570         struct iface_delete_queues_cbdata cbdata;
4571         struct shash details;
4572         size_t i;
4573
4574         /* Configure top-level Qos for 'iface'. */
4575         shash_from_ovs_idl_map(qos->key_other_config, qos->value_other_config,
4576                                qos->n_other_config, &details);
4577         netdev_set_qos(iface->netdev, qos->type, &details);
4578         shash_destroy(&details);
4579
4580         /* Deconfigure queues that were deleted. */
4581         cbdata.netdev = iface->netdev;
4582         cbdata.queues = ovsrec_qos_get_queues(qos, OVSDB_TYPE_INTEGER,
4583                                               OVSDB_TYPE_UUID);
4584         netdev_dump_queues(iface->netdev, iface_delete_queues, &cbdata);
4585
4586         /* Configure queues for 'iface'. */
4587         for (i = 0; i < qos->n_queues; i++) {
4588             const struct ovsrec_queue *queue = qos->value_queues[i];
4589             unsigned int queue_id = qos->key_queues[i];
4590
4591             shash_from_ovs_idl_map(queue->key_other_config,
4592                                    queue->value_other_config,
4593                                    queue->n_other_config, &details);
4594             netdev_set_queue(iface->netdev, queue_id, &details);
4595             shash_destroy(&details);
4596         }
4597     }
4598 }
4599
4600 static void
4601 iface_update_cfm(struct iface *iface)
4602 {
4603     size_t i;
4604     struct cfm cfm;
4605     uint16_t *remote_mps;
4606     struct ovsrec_monitor *mon;
4607     uint8_t maid[CCM_MAID_LEN];
4608
4609     mon = iface->cfg->monitor;
4610
4611     if (!mon) {
4612         ofproto_iface_clear_cfm(iface->port->bridge->ofproto, iface->dp_ifidx);
4613         return;
4614     }
4615
4616     if (!cfm_generate_maid(mon->md_name, mon->ma_name, maid)) {
4617         VLOG_WARN("interface %s: Failed to generate MAID.", iface->name);
4618         return;
4619     }
4620
4621     cfm.mpid     = mon->mpid;
4622     cfm.interval = mon->interval ? *mon->interval : 1000;
4623
4624     memcpy(cfm.maid, maid, sizeof cfm.maid);
4625
4626     remote_mps = xzalloc(mon->n_remote_mps * sizeof *remote_mps);
4627     for(i = 0; i < mon->n_remote_mps; i++) {
4628         remote_mps[i] = mon->remote_mps[i]->mpid;
4629     }
4630
4631     ofproto_iface_set_cfm(iface->port->bridge->ofproto, iface->dp_ifidx,
4632                           &cfm, remote_mps, mon->n_remote_mps);
4633     free(remote_mps);
4634 }
4635
4636 /* Read carrier or miimon status directly from 'iface''s netdev, according to
4637  * how 'iface''s port is configured.
4638  *
4639  * Returns true if 'iface' is up, false otherwise. */
4640 static bool
4641 iface_get_carrier(const struct iface *iface)
4642 {
4643     return (iface->port->monitor
4644             ? netdev_get_carrier(iface->netdev)
4645             : netdev_get_miimon(iface->netdev));
4646 }
4647 \f
4648 /* Port mirroring. */
4649
4650 static struct mirror *
4651 mirror_find_by_uuid(struct bridge *br, const struct uuid *uuid)
4652 {
4653     int i;
4654
4655     for (i = 0; i < MAX_MIRRORS; i++) {
4656         struct mirror *m = br->mirrors[i];
4657         if (m && uuid_equals(uuid, &m->uuid)) {
4658             return m;
4659         }
4660     }
4661     return NULL;
4662 }
4663
4664 static void
4665 mirror_reconfigure(struct bridge *br)
4666 {
4667     unsigned long *rspan_vlans;
4668     struct port *port;
4669     int i;
4670
4671     /* Get rid of deleted mirrors. */
4672     for (i = 0; i < MAX_MIRRORS; i++) {
4673         struct mirror *m = br->mirrors[i];
4674         if (m) {
4675             const struct ovsdb_datum *mc;
4676             union ovsdb_atom atom;
4677
4678             mc = ovsrec_bridge_get_mirrors(br->cfg, OVSDB_TYPE_UUID);
4679             atom.uuid = br->mirrors[i]->uuid;
4680             if (ovsdb_datum_find_key(mc, &atom, OVSDB_TYPE_UUID) == UINT_MAX) {
4681                 mirror_destroy(m);
4682             }
4683         }
4684     }
4685
4686     /* Add new mirrors and reconfigure existing ones. */
4687     for (i = 0; i < br->cfg->n_mirrors; i++) {
4688         struct ovsrec_mirror *cfg = br->cfg->mirrors[i];
4689         struct mirror *m = mirror_find_by_uuid(br, &cfg->header_.uuid);
4690         if (m) {
4691             mirror_reconfigure_one(m, cfg);
4692         } else {
4693             mirror_create(br, cfg);
4694         }
4695     }
4696
4697     /* Update port reserved status. */
4698     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
4699         port->is_mirror_output_port = false;
4700     }
4701     for (i = 0; i < MAX_MIRRORS; i++) {
4702         struct mirror *m = br->mirrors[i];
4703         if (m && m->out_port) {
4704             m->out_port->is_mirror_output_port = true;
4705         }
4706     }
4707
4708     /* Update flooded vlans (for RSPAN). */
4709     rspan_vlans = NULL;
4710     if (br->cfg->n_flood_vlans) {
4711         rspan_vlans = bitmap_allocate(4096);
4712
4713         for (i = 0; i < br->cfg->n_flood_vlans; i++) {
4714             int64_t vlan = br->cfg->flood_vlans[i];
4715             if (vlan >= 0 && vlan < 4096) {
4716                 bitmap_set1(rspan_vlans, vlan);
4717                 VLOG_INFO("bridge %s: disabling learning on vlan %"PRId64,
4718                           br->name, vlan);
4719             } else {
4720                 VLOG_ERR("bridge %s: invalid value %"PRId64 "for flood VLAN",
4721                          br->name, vlan);
4722             }
4723         }
4724     }
4725     if (mac_learning_set_flood_vlans(br->ml, rspan_vlans)) {
4726         bridge_flush(br);
4727         mac_learning_flush(br->ml);
4728     }
4729 }
4730
4731 static void
4732 mirror_create(struct bridge *br, struct ovsrec_mirror *cfg)
4733 {
4734     struct mirror *m;
4735     size_t i;
4736
4737     for (i = 0; ; i++) {
4738         if (i >= MAX_MIRRORS) {
4739             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
4740                       "cannot create %s", br->name, MAX_MIRRORS, cfg->name);
4741             return;
4742         }
4743         if (!br->mirrors[i]) {
4744             break;
4745         }
4746     }
4747
4748     VLOG_INFO("created port mirror %s on bridge %s", cfg->name, br->name);
4749     bridge_flush(br);
4750     mac_learning_flush(br->ml);
4751
4752     br->mirrors[i] = m = xzalloc(sizeof *m);
4753     m->bridge = br;
4754     m->idx = i;
4755     m->name = xstrdup(cfg->name);
4756     sset_init(&m->src_ports);
4757     sset_init(&m->dst_ports);
4758     m->vlans = NULL;
4759     m->n_vlans = 0;
4760     m->out_vlan = -1;
4761     m->out_port = NULL;
4762
4763     mirror_reconfigure_one(m, cfg);
4764 }
4765
4766 static void
4767 mirror_destroy(struct mirror *m)
4768 {
4769     if (m) {
4770         struct bridge *br = m->bridge;
4771         struct port *port;
4772
4773         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
4774             port->src_mirrors &= ~(MIRROR_MASK_C(1) << m->idx);
4775             port->dst_mirrors &= ~(MIRROR_MASK_C(1) << m->idx);
4776         }
4777
4778         sset_destroy(&m->src_ports);
4779         sset_destroy(&m->dst_ports);
4780         free(m->vlans);
4781
4782         m->bridge->mirrors[m->idx] = NULL;
4783         free(m->name);
4784         free(m);
4785
4786         bridge_flush(br);
4787         mac_learning_flush(br->ml);
4788     }
4789 }
4790
4791 static void
4792 mirror_collect_ports(struct mirror *m, struct ovsrec_port **ports, int n_ports,
4793                      struct sset *names)
4794 {
4795     size_t i;
4796
4797     for (i = 0; i < n_ports; i++) {
4798         const char *name = ports[i]->name;
4799         if (port_lookup(m->bridge, name)) {
4800             sset_add(names, name);
4801         } else {
4802             VLOG_WARN("bridge %s: mirror %s cannot match on nonexistent "
4803                       "port %s", m->bridge->name, m->name, name);
4804         }
4805     }
4806 }
4807
4808 static size_t
4809 mirror_collect_vlans(struct mirror *m, const struct ovsrec_mirror *cfg,
4810                      int **vlans)
4811 {
4812     size_t n_vlans;
4813     size_t i;
4814
4815     *vlans = xmalloc(sizeof **vlans * cfg->n_select_vlan);
4816     n_vlans = 0;
4817     for (i = 0; i < cfg->n_select_vlan; i++) {
4818         int64_t vlan = cfg->select_vlan[i];
4819         if (vlan < 0 || vlan > 4095) {
4820             VLOG_WARN("bridge %s: mirror %s selects invalid VLAN %"PRId64,
4821                       m->bridge->name, m->name, vlan);
4822         } else {
4823             (*vlans)[n_vlans++] = vlan;
4824         }
4825     }
4826     return n_vlans;
4827 }
4828
4829 static bool
4830 vlan_is_mirrored(const struct mirror *m, int vlan)
4831 {
4832     size_t i;
4833
4834     for (i = 0; i < m->n_vlans; i++) {
4835         if (m->vlans[i] == vlan) {
4836             return true;
4837         }
4838     }
4839     return false;
4840 }
4841
4842 static bool
4843 port_trunks_any_mirrored_vlan(const struct mirror *m, const struct port *p)
4844 {
4845     size_t i;
4846
4847     for (i = 0; i < m->n_vlans; i++) {
4848         if (port_trunks_vlan(p, m->vlans[i])) {
4849             return true;
4850         }
4851     }
4852     return false;
4853 }
4854
4855 static void
4856 mirror_reconfigure_one(struct mirror *m, struct ovsrec_mirror *cfg)
4857 {
4858     struct sset src_ports, dst_ports;
4859     mirror_mask_t mirror_bit;
4860     struct port *out_port;
4861     struct port *port;
4862     int out_vlan;
4863     size_t n_vlans;
4864     int *vlans;
4865
4866     /* Set name. */
4867     if (strcmp(cfg->name, m->name)) {
4868         free(m->name);
4869         m->name = xstrdup(cfg->name);
4870     }
4871
4872     /* Get output port. */
4873     if (cfg->output_port) {
4874         out_port = port_lookup(m->bridge, cfg->output_port->name);
4875         if (!out_port) {
4876             VLOG_ERR("bridge %s: mirror %s outputs to port not on bridge",
4877                      m->bridge->name, m->name);
4878             mirror_destroy(m);
4879             return;
4880         }
4881         out_vlan = -1;
4882
4883         if (cfg->output_vlan) {
4884             VLOG_ERR("bridge %s: mirror %s specifies both output port and "
4885                      "output vlan; ignoring output vlan",
4886                      m->bridge->name, m->name);
4887         }
4888     } else if (cfg->output_vlan) {
4889         out_port = NULL;
4890         out_vlan = *cfg->output_vlan;
4891     } else {
4892         VLOG_ERR("bridge %s: mirror %s does not specify output; ignoring",
4893                  m->bridge->name, m->name);
4894         mirror_destroy(m);
4895         return;
4896     }
4897
4898     sset_init(&src_ports);
4899     sset_init(&dst_ports);
4900     if (cfg->select_all) {
4901         HMAP_FOR_EACH (port, hmap_node, &m->bridge->ports) {
4902             sset_add(&src_ports, port->name);
4903             sset_add(&dst_ports, port->name);
4904         }
4905         vlans = NULL;
4906         n_vlans = 0;
4907     } else {
4908         /* Get ports, and drop duplicates and ports that don't exist. */
4909         mirror_collect_ports(m, cfg->select_src_port, cfg->n_select_src_port,
4910                              &src_ports);
4911         mirror_collect_ports(m, cfg->select_dst_port, cfg->n_select_dst_port,
4912                              &dst_ports);
4913
4914         /* Get all the vlans, and drop duplicate and invalid vlans. */
4915         n_vlans = mirror_collect_vlans(m, cfg, &vlans);
4916     }
4917
4918     /* Update mirror data. */
4919     if (!sset_equals(&m->src_ports, &src_ports)
4920         || !sset_equals(&m->dst_ports, &dst_ports)
4921         || m->n_vlans != n_vlans
4922         || memcmp(m->vlans, vlans, sizeof *vlans * n_vlans)
4923         || m->out_port != out_port
4924         || m->out_vlan != out_vlan) {
4925         bridge_flush(m->bridge);
4926         mac_learning_flush(m->bridge->ml);
4927     }
4928     sset_swap(&m->src_ports, &src_ports);
4929     sset_swap(&m->dst_ports, &dst_ports);
4930     free(m->vlans);
4931     m->vlans = vlans;
4932     m->n_vlans = n_vlans;
4933     m->out_port = out_port;
4934     m->out_vlan = out_vlan;
4935
4936     /* Update ports. */
4937     mirror_bit = MIRROR_MASK_C(1) << m->idx;
4938     HMAP_FOR_EACH (port, hmap_node, &m->bridge->ports) {
4939         if (sset_contains(&m->src_ports, port->name)
4940             || (m->n_vlans
4941                 && (!port->vlan
4942                     ? port_trunks_any_mirrored_vlan(m, port)
4943                     : vlan_is_mirrored(m, port->vlan)))) {
4944             port->src_mirrors |= mirror_bit;
4945         } else {
4946             port->src_mirrors &= ~mirror_bit;
4947         }
4948
4949         if (sset_contains(&m->dst_ports, port->name)) {
4950             port->dst_mirrors |= mirror_bit;
4951         } else {
4952             port->dst_mirrors &= ~mirror_bit;
4953         }
4954     }
4955
4956     /* Clean up. */
4957     sset_destroy(&src_ports);
4958     sset_destroy(&dst_ports);
4959 }