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