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