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