bridge: Break bonding implementation out into library.
[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 "bond.h"
36 #include "cfm.h"
37 #include "classifier.h"
38 #include "coverage.h"
39 #include "daemon.h"
40 #include "dirs.h"
41 #include "dpif.h"
42 #include "dynamic-string.h"
43 #include "flow.h"
44 #include "hash.h"
45 #include "hmap.h"
46 #include "jsonrpc.h"
47 #include "lacp.h"
48 #include "list.h"
49 #include "mac-learning.h"
50 #include "netdev.h"
51 #include "netlink.h"
52 #include "odp-util.h"
53 #include "ofp-print.h"
54 #include "ofpbuf.h"
55 #include "ofproto/netflow.h"
56 #include "ofproto/ofproto.h"
57 #include "ovsdb-data.h"
58 #include "packets.h"
59 #include "poll-loop.h"
60 #include "process.h"
61 #include "sha1.h"
62 #include "shash.h"
63 #include "socket-util.h"
64 #include "stream-ssl.h"
65 #include "sset.h"
66 #include "svec.h"
67 #include "system-stats.h"
68 #include "timeval.h"
69 #include "util.h"
70 #include "unixctl.h"
71 #include "vconn.h"
72 #include "vswitchd/vswitch-idl.h"
73 #include "xenserver.h"
74 #include "vlog.h"
75 #include "sflow_api.h"
76
77 VLOG_DEFINE_THIS_MODULE(bridge);
78
79 COVERAGE_DEFINE(bridge_flush);
80 COVERAGE_DEFINE(bridge_process_flow);
81 COVERAGE_DEFINE(bridge_reconfigure);
82
83 struct dst {
84     uint16_t vlan;
85     uint16_t dp_ifidx;
86 };
87
88 struct dst_set {
89     struct dst builtin[32];
90     struct dst *dsts;
91     size_t n, allocated;
92 };
93
94 static void dst_set_init(struct dst_set *);
95 static void dst_set_add(struct dst_set *, const struct dst *);
96 static void dst_set_free(struct dst_set *);
97
98 struct iface {
99     /* These members are always valid. */
100     struct list port_elem;      /* Element in struct port's "ifaces" list. */
101     struct port *port;          /* Containing port. */
102     char *name;                 /* Host network device name. */
103     tag_type tag;               /* Tag associated with this interface. */
104
105     /* These members are valid only after bridge_reconfigure() causes them to
106      * be initialized. */
107     struct hmap_node dp_ifidx_node; /* In struct bridge's "ifaces" hmap. */
108     int dp_ifidx;               /* Index within kernel datapath. */
109     struct netdev *netdev;      /* Network device. */
110     const char *type;           /* Usually same as cfg->type. */
111     const struct ovsrec_interface *cfg;
112 };
113
114 #define MAX_MIRRORS 32
115 typedef uint32_t mirror_mask_t;
116 #define MIRROR_MASK_C(X) UINT32_C(X)
117 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
118 struct mirror {
119     struct bridge *bridge;
120     size_t idx;
121     char *name;
122     struct uuid uuid;           /* UUID of this "mirror" record in database. */
123
124     /* Selection criteria. */
125     struct sset src_ports;      /* Source port names. */
126     struct sset dst_ports;      /* Destination port names. */
127     int *vlans;
128     size_t n_vlans;
129
130     /* Output. */
131     struct port *out_port;
132     int out_vlan;
133 };
134
135 #define FLOOD_PORT ((struct port *) 1) /* The 'flood' output port. */
136 struct port {
137     struct bridge *bridge;
138     struct hmap_node hmap_node; /* Element in struct bridge's "ports" hmap. */
139     char *name;
140
141     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
142     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
143                                  * NULL if all VLANs are trunked. */
144     const struct ovsrec_port *cfg;
145
146     /* An ordinary bridge port has 1 interface.
147      * A bridge port for bonding has at least 2 interfaces. */
148     struct list ifaces;         /* List of "struct iface"s. */
149     size_t n_ifaces;            /* list_size(ifaces). */
150
151     /* Bonding info. */
152     struct bond *bond;
153
154     /* Port mirroring info. */
155     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
156     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
157     bool is_mirror_output_port; /* Does port mirroring send frames here? */
158 };
159
160 struct bridge {
161     struct list node;           /* Node in global list of bridges. */
162     char *name;                 /* User-specified arbitrary name. */
163     struct mac_learning *ml;    /* MAC learning table. */
164     uint8_t ea[ETH_ADDR_LEN];   /* Bridge Ethernet Address. */
165     uint8_t default_ea[ETH_ADDR_LEN]; /* Default MAC. */
166     const struct ovsrec_bridge *cfg;
167
168     /* OpenFlow switch processing. */
169     struct ofproto *ofproto;    /* OpenFlow switch. */
170
171     /* Kernel datapath information. */
172     struct dpif *dpif;          /* Datapath. */
173     struct hmap ifaces;         /* "struct iface"s indexed by dp_ifidx. */
174
175     /* Bridge ports. */
176     struct hmap ports;          /* "struct port"s indexed by name. */
177     struct shash iface_by_name; /* "struct iface"s indexed by name. */
178
179     /* Bonding. */
180     bool has_bonded_ports;
181
182     /* Flow tracking. */
183     bool flush;
184
185     /* Port mirroring. */
186     struct mirror *mirrors[MAX_MIRRORS];
187 };
188
189 /* List of all bridges. */
190 static struct list all_bridges = LIST_INITIALIZER(&all_bridges);
191
192 /* OVSDB IDL used to obtain configuration. */
193 static struct ovsdb_idl *idl;
194
195 /* Each time this timer expires, the bridge fetches systems and interface
196  * statistics and pushes them into the database. */
197 #define STATS_INTERVAL (5 * 1000) /* In milliseconds. */
198 static long long int stats_timer = LLONG_MIN;
199
200 /* Stores the time after which CFM statistics may be written to the database.
201  * Only updated when changes to the database require rate limiting. */
202 #define CFM_LIMIT_INTERVAL (1 * 1000) /* In milliseconds. */
203 static long long int cfm_limiter = LLONG_MIN;
204
205 static struct bridge *bridge_create(const struct ovsrec_bridge *br_cfg);
206 static void bridge_destroy(struct bridge *);
207 static struct bridge *bridge_lookup(const char *name);
208 static unixctl_cb_func bridge_unixctl_dump_flows;
209 static unixctl_cb_func bridge_unixctl_reconnect;
210 static int bridge_run_one(struct bridge *);
211 static size_t bridge_get_controllers(const struct bridge *br,
212                                      struct ovsrec_controller ***controllersp);
213 static void bridge_reconfigure_one(struct bridge *);
214 static void bridge_reconfigure_remotes(struct bridge *,
215                                        const struct sockaddr_in *managers,
216                                        size_t n_managers);
217 static void bridge_get_all_ifaces(const struct bridge *, struct shash *ifaces);
218 static void bridge_fetch_dp_ifaces(struct bridge *);
219 static void bridge_flush(struct bridge *);
220 static void bridge_pick_local_hw_addr(struct bridge *,
221                                       uint8_t ea[ETH_ADDR_LEN],
222                                       struct iface **hw_addr_iface);
223 static uint64_t bridge_pick_datapath_id(struct bridge *,
224                                         const uint8_t bridge_ea[ETH_ADDR_LEN],
225                                         struct iface *hw_addr_iface);
226 static uint64_t dpid_from_hash(const void *, size_t nbytes);
227
228 static unixctl_cb_func bridge_unixctl_fdb_show;
229 static unixctl_cb_func cfm_unixctl_show;
230 static unixctl_cb_func qos_unixctl_show;
231
232 static void port_run(struct port *);
233 static void port_wait(struct port *);
234 static struct port *port_create(struct bridge *, const char *name);
235 static void port_reconfigure(struct port *, const struct ovsrec_port *);
236 static void port_del_ifaces(struct port *, const struct ovsrec_port *);
237 static void port_destroy(struct port *);
238 static struct port *port_lookup(const struct bridge *, const char *name);
239 static struct iface *port_get_an_iface(const struct port *);
240 static struct port *port_from_dp_ifidx(const struct bridge *,
241                                        uint16_t dp_ifidx);
242 static void port_reconfigure_bond(struct port *);
243 static void port_send_learning_packets(struct port *);
244
245 static void mirror_create(struct bridge *, struct ovsrec_mirror *);
246 static void mirror_destroy(struct mirror *);
247 static void mirror_reconfigure(struct bridge *);
248 static void mirror_reconfigure_one(struct mirror *, struct ovsrec_mirror *);
249 static bool vlan_is_mirrored(const struct mirror *, int vlan);
250
251 static struct iface *iface_create(struct port *port,
252                                   const struct ovsrec_interface *if_cfg);
253 static void iface_destroy(struct iface *);
254 static struct iface *iface_lookup(const struct bridge *, const char *name);
255 static struct iface *iface_find(const char *name);
256 static struct iface *iface_from_dp_ifidx(const struct bridge *,
257                                          uint16_t dp_ifidx);
258 static void iface_set_mac(struct iface *);
259 static void iface_set_ofport(const struct ovsrec_interface *, int64_t ofport);
260 static void iface_update_qos(struct iface *, const struct ovsrec_qos *);
261 static void iface_update_cfm(struct iface *);
262 static bool iface_refresh_cfm_stats(struct iface *iface);
263 static bool iface_get_carrier(const struct iface *);
264
265 static void shash_from_ovs_idl_map(char **keys, char **values, size_t n,
266                                    struct shash *);
267 static void shash_to_ovs_idl_map(struct shash *,
268                                  char ***keys, char ***values, size_t *n);
269
270 /* Hooks into ofproto processing. */
271 static struct ofhooks bridge_ofhooks;
272 \f
273 /* Public functions. */
274
275 /* Initializes the bridge module, configuring it to obtain its configuration
276  * from an OVSDB server accessed over 'remote', which should be a string in a
277  * form acceptable to ovsdb_idl_create(). */
278 void
279 bridge_init(const char *remote)
280 {
281     /* Create connection to database. */
282     idl = ovsdb_idl_create(remote, &ovsrec_idl_class, true);
283
284     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_cur_cfg);
285     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_statistics);
286     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_external_ids);
287
288     ovsdb_idl_omit(idl, &ovsrec_bridge_col_external_ids);
289
290     ovsdb_idl_omit(idl, &ovsrec_port_col_external_ids);
291     ovsdb_idl_omit(idl, &ovsrec_port_col_fake_bridge);
292
293     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_ofport);
294     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_statistics);
295     ovsdb_idl_omit(idl, &ovsrec_interface_col_external_ids);
296
297     /* Register unixctl commands. */
298     unixctl_command_register("fdb/show", bridge_unixctl_fdb_show, NULL);
299     unixctl_command_register("cfm/show", cfm_unixctl_show, NULL);
300     unixctl_command_register("qos/show", qos_unixctl_show, NULL);
301     unixctl_command_register("bridge/dump-flows", bridge_unixctl_dump_flows,
302                              NULL);
303     unixctl_command_register("bridge/reconnect", bridge_unixctl_reconnect,
304                              NULL);
305     bond_init();
306 }
307
308 void
309 bridge_exit(void)
310 {
311     struct bridge *br, *next_br;
312
313     LIST_FOR_EACH_SAFE (br, next_br, node, &all_bridges) {
314         bridge_destroy(br);
315     }
316     ovsdb_idl_destroy(idl);
317 }
318
319 /* Performs configuration that is only necessary once at ovs-vswitchd startup,
320  * but for which the ovs-vswitchd configuration 'cfg' is required. */
321 static void
322 bridge_configure_once(const struct ovsrec_open_vswitch *cfg)
323 {
324     static bool already_configured_once;
325     struct sset bridge_names;
326     struct sset dpif_names, dpif_types;
327     const char *type;
328     size_t i;
329
330     /* Only do this once per ovs-vswitchd run. */
331     if (already_configured_once) {
332         return;
333     }
334     already_configured_once = true;
335
336     stats_timer = time_msec() + STATS_INTERVAL;
337
338     /* Get all the configured bridges' names from 'cfg' into 'bridge_names'. */
339     sset_init(&bridge_names);
340     for (i = 0; i < cfg->n_bridges; i++) {
341         sset_add(&bridge_names, cfg->bridges[i]->name);
342     }
343
344     /* Iterate over all system dpifs and delete any of them that do not appear
345      * in 'cfg'. */
346     sset_init(&dpif_names);
347     sset_init(&dpif_types);
348     dp_enumerate_types(&dpif_types);
349     SSET_FOR_EACH (type, &dpif_types) {
350         const char *name;
351
352         dp_enumerate_names(type, &dpif_names);
353
354         /* Delete each dpif whose name is not in 'bridge_names'. */
355         SSET_FOR_EACH (name, &dpif_names) {
356             if (!sset_contains(&bridge_names, name)) {
357                 struct dpif *dpif;
358                 int retval;
359
360                 retval = dpif_open(name, type, &dpif);
361                 if (!retval) {
362                     dpif_delete(dpif);
363                     dpif_close(dpif);
364                 }
365             }
366         }
367     }
368     sset_destroy(&bridge_names);
369     sset_destroy(&dpif_names);
370     sset_destroy(&dpif_types);
371 }
372
373 /* Callback for iterate_and_prune_ifaces(). */
374 static bool
375 check_iface(struct bridge *br, struct iface *iface, void *aux OVS_UNUSED)
376 {
377     if (!iface->netdev) {
378         /* We already reported a related error, don't bother duplicating it. */
379         return false;
380     }
381
382     if (iface->dp_ifidx < 0) {
383         VLOG_ERR("%s interface not in %s, dropping",
384                  iface->name, dpif_name(br->dpif));
385         return false;
386     }
387
388     VLOG_DBG("%s has interface %s on port %d", dpif_name(br->dpif),
389              iface->name, iface->dp_ifidx);
390     return true;
391 }
392
393 /* Callback for iterate_and_prune_ifaces(). */
394 static bool
395 set_iface_properties(struct bridge *br OVS_UNUSED, struct iface *iface,
396                      void *aux OVS_UNUSED)
397 {
398     /* Set policing attributes. */
399     netdev_set_policing(iface->netdev,
400                         iface->cfg->ingress_policing_rate,
401                         iface->cfg->ingress_policing_burst);
402
403     /* Set MAC address of internal interfaces other than the local
404      * interface. */
405     if (iface->dp_ifidx != ODPP_LOCAL && !strcmp(iface->type, "internal")) {
406         iface_set_mac(iface);
407     }
408
409     return true;
410 }
411
412 /* Calls 'cb' for each interfaces in 'br', passing along the 'aux' argument.
413  * Deletes from 'br' all the interfaces for which 'cb' returns false, and then
414  * deletes from 'br' any ports that no longer have any interfaces. */
415 static void
416 iterate_and_prune_ifaces(struct bridge *br,
417                          bool (*cb)(struct bridge *, struct iface *,
418                                     void *aux),
419                          void *aux)
420 {
421     struct port *port, *next_port;
422
423     HMAP_FOR_EACH_SAFE (port, next_port, hmap_node, &br->ports) {
424         struct iface *iface, *next_iface;
425
426         LIST_FOR_EACH_SAFE (iface, next_iface, port_elem, &port->ifaces) {
427             if (!cb(br, iface, aux)) {
428                 iface_set_ofport(iface->cfg, -1);
429                 iface_destroy(iface);
430             }
431         }
432
433         if (!port->n_ifaces) {
434             VLOG_WARN("%s port has no interfaces, dropping", port->name);
435             port_destroy(port);
436         }
437     }
438 }
439
440 /* Looks at the list of managers in 'ovs_cfg' and extracts their remote IP
441  * addresses and ports into '*managersp' and '*n_managersp'.  The caller is
442  * responsible for freeing '*managersp' (with free()).
443  *
444  * You may be asking yourself "why does ovs-vswitchd care?", because
445  * ovsdb-server is responsible for connecting to the managers, and ovs-vswitchd
446  * should not be and in fact is not directly involved in that.  But
447  * ovs-vswitchd needs to make sure that ovsdb-server can reach the managers, so
448  * it has to tell in-band control where the managers are to enable that.
449  * (Thus, only managers connected in-band are collected.)
450  */
451 static void
452 collect_in_band_managers(const struct ovsrec_open_vswitch *ovs_cfg,
453                          struct sockaddr_in **managersp, size_t *n_managersp)
454 {
455     struct sockaddr_in *managers = NULL;
456     size_t n_managers = 0;
457     struct sset targets;
458     size_t i;
459
460     /* Collect all of the potential targets from the "targets" columns of the
461      * rows pointed to by "manager_options", excluding any that are
462      * out-of-band. */
463     sset_init(&targets);
464     for (i = 0; i < ovs_cfg->n_manager_options; i++) {
465         struct ovsrec_manager *m = ovs_cfg->manager_options[i];
466
467         if (m->connection_mode && !strcmp(m->connection_mode, "out-of-band")) {
468             sset_find_and_delete(&targets, m->target);
469         } else {
470             sset_add(&targets, m->target);
471         }
472     }
473
474     /* Now extract the targets' IP addresses. */
475     if (!sset_is_empty(&targets)) {
476         const char *target;
477
478         managers = xmalloc(sset_count(&targets) * sizeof *managers);
479         SSET_FOR_EACH (target, &targets) {
480             struct sockaddr_in *sin = &managers[n_managers];
481
482             if ((!strncmp(target, "tcp:", 4)
483                  && inet_parse_active(target + 4, JSONRPC_TCP_PORT, sin)) ||
484                 (!strncmp(target, "ssl:", 4)
485                  && inet_parse_active(target + 4, JSONRPC_SSL_PORT, sin))) {
486                 n_managers++;
487             }
488         }
489     }
490     sset_destroy(&targets);
491
492     *managersp = managers;
493     *n_managersp = n_managers;
494 }
495
496 static void
497 bridge_reconfigure(const struct ovsrec_open_vswitch *ovs_cfg)
498 {
499     struct shash old_br, new_br;
500     struct shash_node *node;
501     struct bridge *br, *next;
502     struct sockaddr_in *managers;
503     size_t n_managers;
504     size_t i;
505     int sflow_bridge_number;
506
507     COVERAGE_INC(bridge_reconfigure);
508
509     collect_in_band_managers(ovs_cfg, &managers, &n_managers);
510
511     /* Collect old and new bridges. */
512     shash_init(&old_br);
513     shash_init(&new_br);
514     LIST_FOR_EACH (br, node, &all_bridges) {
515         shash_add(&old_br, br->name, br);
516     }
517     for (i = 0; i < ovs_cfg->n_bridges; i++) {
518         const struct ovsrec_bridge *br_cfg = ovs_cfg->bridges[i];
519         if (!shash_add_once(&new_br, br_cfg->name, br_cfg)) {
520             VLOG_WARN("more than one bridge named %s", br_cfg->name);
521         }
522     }
523
524     /* Get rid of deleted bridges and add new bridges. */
525     LIST_FOR_EACH_SAFE (br, next, node, &all_bridges) {
526         struct ovsrec_bridge *br_cfg = shash_find_data(&new_br, br->name);
527         if (br_cfg) {
528             br->cfg = br_cfg;
529         } else {
530             bridge_destroy(br);
531         }
532     }
533     SHASH_FOR_EACH (node, &new_br) {
534         const char *br_name = node->name;
535         const struct ovsrec_bridge *br_cfg = node->data;
536         br = shash_find_data(&old_br, br_name);
537         if (br) {
538             /* If the bridge datapath type has changed, we need to tear it
539              * down and recreate. */
540             if (strcmp(br->cfg->datapath_type, br_cfg->datapath_type)) {
541                 bridge_destroy(br);
542                 bridge_create(br_cfg);
543             }
544         } else {
545             bridge_create(br_cfg);
546         }
547     }
548     shash_destroy(&old_br);
549     shash_destroy(&new_br);
550
551     /* Reconfigure all bridges. */
552     LIST_FOR_EACH (br, node, &all_bridges) {
553         bridge_reconfigure_one(br);
554     }
555
556     /* Add and delete ports on all datapaths.
557      *
558      * The kernel will reject any attempt to add a given port to a datapath if
559      * that port already belongs to a different datapath, so we must do all
560      * port deletions before any port additions. */
561     LIST_FOR_EACH (br, node, &all_bridges) {
562         struct dpif_port_dump dump;
563         struct shash want_ifaces;
564         struct dpif_port dpif_port;
565
566         bridge_get_all_ifaces(br, &want_ifaces);
567         DPIF_PORT_FOR_EACH (&dpif_port, &dump, br->dpif) {
568             if (!shash_find(&want_ifaces, dpif_port.name)
569                 && strcmp(dpif_port.name, br->name)) {
570                 int retval = dpif_port_del(br->dpif, dpif_port.port_no);
571                 if (retval) {
572                     VLOG_WARN("failed to remove %s interface from %s: %s",
573                               dpif_port.name, dpif_name(br->dpif),
574                               strerror(retval));
575                 }
576             }
577         }
578         shash_destroy(&want_ifaces);
579     }
580     LIST_FOR_EACH (br, node, &all_bridges) {
581         struct shash cur_ifaces, want_ifaces;
582         struct dpif_port_dump dump;
583         struct dpif_port dpif_port;
584
585         /* Get the set of interfaces currently in this datapath. */
586         shash_init(&cur_ifaces);
587         DPIF_PORT_FOR_EACH (&dpif_port, &dump, br->dpif) {
588             struct dpif_port *port_info = xmalloc(sizeof *port_info);
589             dpif_port_clone(port_info, &dpif_port);
590             shash_add(&cur_ifaces, dpif_port.name, port_info);
591         }
592
593         /* Get the set of interfaces we want on this datapath. */
594         bridge_get_all_ifaces(br, &want_ifaces);
595
596         hmap_clear(&br->ifaces);
597         SHASH_FOR_EACH (node, &want_ifaces) {
598             const char *if_name = node->name;
599             struct iface *iface = node->data;
600             struct dpif_port *dpif_port;
601             const char *type;
602             int error;
603
604             type = iface ? iface->type : "internal";
605             dpif_port = shash_find_data(&cur_ifaces, if_name);
606
607             /* If we have a port or a netdev already, and it's not the type we
608              * want, then delete the port (if any) and close the netdev (if
609              * any). */
610             if ((dpif_port && strcmp(dpif_port->type, type))
611                 || (iface && iface->netdev
612                     && strcmp(type, netdev_get_type(iface->netdev)))) {
613                 if (dpif_port) {
614                     error = ofproto_port_del(br->ofproto, dpif_port->port_no);
615                     if (error) {
616                         continue;
617                     }
618                     dpif_port = NULL;
619                 }
620                 if (iface) {
621                     netdev_close(iface->netdev);
622                     iface->netdev = NULL;
623                 }
624             }
625
626             /* If the port doesn't exist or we don't have the netdev open,
627              * we need to do more work. */
628             if (!dpif_port || (iface && !iface->netdev)) {
629                 struct netdev_options options;
630                 struct netdev *netdev;
631                 struct shash args;
632
633                 /* First open the network device. */
634                 options.name = if_name;
635                 options.type = type;
636                 options.args = &args;
637                 options.ethertype = NETDEV_ETH_TYPE_NONE;
638
639                 shash_init(&args);
640                 if (iface) {
641                     shash_from_ovs_idl_map(iface->cfg->key_options,
642                                            iface->cfg->value_options,
643                                            iface->cfg->n_options, &args);
644                 }
645                 error = netdev_open(&options, &netdev);
646                 shash_destroy(&args);
647
648                 if (error) {
649                     VLOG_WARN("could not open network device %s (%s)",
650                               if_name, strerror(error));
651                     continue;
652                 }
653
654                 /* Then add the port if we haven't already. */
655                 if (!dpif_port) {
656                     error = dpif_port_add(br->dpif, netdev, NULL);
657                     if (error) {
658                         netdev_close(netdev);
659                         if (error == EFBIG) {
660                             VLOG_ERR("ran out of valid port numbers on %s",
661                                      dpif_name(br->dpif));
662                             break;
663                         } else {
664                             VLOG_WARN("failed to add %s interface to %s: %s",
665                                       if_name, dpif_name(br->dpif),
666                                       strerror(error));
667                             continue;
668                         }
669                     }
670                 }
671
672                 /* Update 'iface'. */
673                 if (iface) {
674                     iface->netdev = netdev;
675                 }
676             } else if (iface && iface->netdev) {
677                 struct shash args;
678
679                 shash_init(&args);
680                 shash_from_ovs_idl_map(iface->cfg->key_options,
681                                        iface->cfg->value_options,
682                                        iface->cfg->n_options, &args);
683                 netdev_set_config(iface->netdev, &args);
684                 shash_destroy(&args);
685             }
686         }
687         shash_destroy(&want_ifaces);
688
689         SHASH_FOR_EACH (node, &cur_ifaces) {
690             struct dpif_port *port_info = node->data;
691             dpif_port_destroy(port_info);
692             free(port_info);
693         }
694         shash_destroy(&cur_ifaces);
695     }
696     sflow_bridge_number = 0;
697     LIST_FOR_EACH (br, node, &all_bridges) {
698         uint8_t ea[ETH_ADDR_LEN];
699         uint64_t dpid;
700         struct iface *local_iface;
701         struct iface *hw_addr_iface;
702         char *dpid_string;
703
704         bridge_fetch_dp_ifaces(br);
705
706         /* Delete interfaces that cannot be opened.
707          *
708          * From this point forward we are guaranteed that every "struct iface"
709          * has nonnull 'netdev' and correct 'dp_ifidx'. */
710         iterate_and_prune_ifaces(br, check_iface, NULL);
711
712         /* Pick local port hardware address, datapath ID. */
713         bridge_pick_local_hw_addr(br, ea, &hw_addr_iface);
714         local_iface = iface_from_dp_ifidx(br, ODPP_LOCAL);
715         if (local_iface) {
716             int error = netdev_set_etheraddr(local_iface->netdev, ea);
717             if (error) {
718                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
719                 VLOG_ERR_RL(&rl, "bridge %s: failed to set bridge "
720                             "Ethernet address: %s",
721                             br->name, strerror(error));
722             }
723         }
724         memcpy(br->ea, ea, ETH_ADDR_LEN);
725
726         dpid = bridge_pick_datapath_id(br, ea, hw_addr_iface);
727         ofproto_set_datapath_id(br->ofproto, dpid);
728
729         dpid_string = xasprintf("%016"PRIx64, dpid);
730         ovsrec_bridge_set_datapath_id(br->cfg, dpid_string);
731         free(dpid_string);
732
733         /* Set NetFlow configuration on this bridge. */
734         if (br->cfg->netflow) {
735             struct ovsrec_netflow *nf_cfg = br->cfg->netflow;
736             struct netflow_options opts;
737
738             memset(&opts, 0, sizeof opts);
739
740             dpif_get_netflow_ids(br->dpif, &opts.engine_type, &opts.engine_id);
741             if (nf_cfg->engine_type) {
742                 opts.engine_type = *nf_cfg->engine_type;
743             }
744             if (nf_cfg->engine_id) {
745                 opts.engine_id = *nf_cfg->engine_id;
746             }
747
748             opts.active_timeout = nf_cfg->active_timeout;
749             if (!opts.active_timeout) {
750                 opts.active_timeout = -1;
751             } else if (opts.active_timeout < 0) {
752                 VLOG_WARN("bridge %s: active timeout interval set to negative "
753                           "value, using default instead (%d seconds)", br->name,
754                           NF_ACTIVE_TIMEOUT_DEFAULT);
755                 opts.active_timeout = -1;
756             }
757
758             opts.add_id_to_iface = nf_cfg->add_id_to_interface;
759             if (opts.add_id_to_iface) {
760                 if (opts.engine_id > 0x7f) {
761                     VLOG_WARN("bridge %s: netflow port mangling may conflict "
762                               "with another vswitch, choose an engine id less "
763                               "than 128", br->name);
764                 }
765                 if (hmap_count(&br->ports) > 508) {
766                     VLOG_WARN("bridge %s: netflow port mangling will conflict "
767                               "with another port when more than 508 ports are "
768                               "used", br->name);
769                 }
770             }
771
772             sset_init(&opts.collectors);
773             sset_add_array(&opts.collectors,
774                            nf_cfg->targets, nf_cfg->n_targets);
775             if (ofproto_set_netflow(br->ofproto, &opts)) {
776                 VLOG_ERR("bridge %s: problem setting netflow collectors",
777                          br->name);
778             }
779             sset_destroy(&opts.collectors);
780         } else {
781             ofproto_set_netflow(br->ofproto, NULL);
782         }
783
784         /* Set sFlow configuration on this bridge. */
785         if (br->cfg->sflow) {
786             const struct ovsrec_sflow *sflow_cfg = br->cfg->sflow;
787             struct ovsrec_controller **controllers;
788             struct ofproto_sflow_options oso;
789             size_t n_controllers;
790
791             memset(&oso, 0, sizeof oso);
792
793             sset_init(&oso.targets);
794             sset_add_array(&oso.targets,
795                            sflow_cfg->targets, sflow_cfg->n_targets);
796
797             oso.sampling_rate = SFL_DEFAULT_SAMPLING_RATE;
798             if (sflow_cfg->sampling) {
799                 oso.sampling_rate = *sflow_cfg->sampling;
800             }
801
802             oso.polling_interval = SFL_DEFAULT_POLLING_INTERVAL;
803             if (sflow_cfg->polling) {
804                 oso.polling_interval = *sflow_cfg->polling;
805             }
806
807             oso.header_len = SFL_DEFAULT_HEADER_SIZE;
808             if (sflow_cfg->header) {
809                 oso.header_len = *sflow_cfg->header;
810             }
811
812             oso.sub_id = sflow_bridge_number++;
813             oso.agent_device = sflow_cfg->agent;
814
815             oso.control_ip = NULL;
816             n_controllers = bridge_get_controllers(br, &controllers);
817             for (i = 0; i < n_controllers; i++) {
818                 if (controllers[i]->local_ip) {
819                     oso.control_ip = controllers[i]->local_ip;
820                     break;
821                 }
822             }
823             ofproto_set_sflow(br->ofproto, &oso);
824
825             sset_destroy(&oso.targets);
826         } else {
827             ofproto_set_sflow(br->ofproto, NULL);
828         }
829
830         /* Update the controller and related settings.  It would be more
831          * straightforward to call this from bridge_reconfigure_one(), but we
832          * can't do it there for two reasons.  First, and most importantly, at
833          * that point we don't know the dp_ifidx of any interfaces that have
834          * been added to the bridge (because we haven't actually added them to
835          * the datapath).  Second, at that point we haven't set the datapath ID
836          * yet; when a controller is configured, resetting the datapath ID will
837          * immediately disconnect from the controller, so it's better to set
838          * the datapath ID before the controller. */
839         bridge_reconfigure_remotes(br, managers, n_managers);
840     }
841     LIST_FOR_EACH (br, node, &all_bridges) {
842         struct port *port;
843
844         br->has_bonded_ports = false;
845         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
846             struct iface *iface;
847
848             port_reconfigure_bond(port);
849
850             LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
851                 iface_update_qos(iface, port->cfg->qos);
852             }
853         }
854     }
855     LIST_FOR_EACH (br, node, &all_bridges) {
856         iterate_and_prune_ifaces(br, set_iface_properties, NULL);
857     }
858
859     LIST_FOR_EACH (br, node, &all_bridges) {
860         struct iface *iface;
861         HMAP_FOR_EACH (iface, dp_ifidx_node, &br->ifaces) {
862             iface_update_cfm(iface);
863         }
864     }
865
866     free(managers);
867
868     /* ovs-vswitchd has completed initialization, so allow the process that
869      * forked us to exit successfully. */
870     daemonize_complete();
871 }
872
873 static const char *
874 get_ovsrec_key_value(const struct ovsdb_idl_row *row,
875                      const struct ovsdb_idl_column *column,
876                      const char *key)
877 {
878     const struct ovsdb_datum *datum;
879     union ovsdb_atom atom;
880     unsigned int idx;
881
882     datum = ovsdb_idl_get(row, column, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
883     atom.string = (char *) key;
884     idx = ovsdb_datum_find_key(datum, &atom, OVSDB_TYPE_STRING);
885     return idx == UINT_MAX ? NULL : datum->values[idx].string;
886 }
887
888 static const char *
889 bridge_get_other_config(const struct ovsrec_bridge *br_cfg, const char *key)
890 {
891     return get_ovsrec_key_value(&br_cfg->header_,
892                                 &ovsrec_bridge_col_other_config, key);
893 }
894
895 static void
896 bridge_pick_local_hw_addr(struct bridge *br, uint8_t ea[ETH_ADDR_LEN],
897                           struct iface **hw_addr_iface)
898 {
899     const char *hwaddr;
900     struct port *port;
901     int error;
902
903     *hw_addr_iface = NULL;
904
905     /* Did the user request a particular MAC? */
906     hwaddr = bridge_get_other_config(br->cfg, "hwaddr");
907     if (hwaddr && eth_addr_from_string(hwaddr, ea)) {
908         if (eth_addr_is_multicast(ea)) {
909             VLOG_ERR("bridge %s: cannot set MAC address to multicast "
910                      "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
911         } else if (eth_addr_is_zero(ea)) {
912             VLOG_ERR("bridge %s: cannot set MAC address to zero", br->name);
913         } else {
914             return;
915         }
916     }
917
918     /* Otherwise choose the minimum non-local MAC address among all of the
919      * interfaces. */
920     memset(ea, 0xff, ETH_ADDR_LEN);
921     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
922         uint8_t iface_ea[ETH_ADDR_LEN];
923         struct iface *candidate;
924         struct iface *iface;
925
926         /* Mirror output ports don't participate. */
927         if (port->is_mirror_output_port) {
928             continue;
929         }
930
931         /* Choose the MAC address to represent the port. */
932         iface = NULL;
933         if (port->cfg->mac && eth_addr_from_string(port->cfg->mac, iface_ea)) {
934             /* Find the interface with this Ethernet address (if any) so that
935              * we can provide the correct devname to the caller. */
936             LIST_FOR_EACH (candidate, port_elem, &port->ifaces) {
937                 uint8_t candidate_ea[ETH_ADDR_LEN];
938                 if (!netdev_get_etheraddr(candidate->netdev, candidate_ea)
939                     && eth_addr_equals(iface_ea, candidate_ea)) {
940                     iface = candidate;
941                 }
942             }
943         } else {
944             /* Choose the interface whose MAC address will represent the port.
945              * The Linux kernel bonding code always chooses the MAC address of
946              * the first slave added to a bond, and the Fedora networking
947              * scripts always add slaves to a bond in alphabetical order, so
948              * for compatibility we choose the interface with the name that is
949              * first in alphabetical order. */
950             LIST_FOR_EACH (candidate, port_elem, &port->ifaces) {
951                 if (!iface || strcmp(candidate->name, iface->name) < 0) {
952                     iface = candidate;
953                 }
954             }
955
956             /* The local port doesn't count (since we're trying to choose its
957              * MAC address anyway). */
958             if (iface->dp_ifidx == ODPP_LOCAL) {
959                 continue;
960             }
961
962             /* Grab MAC. */
963             error = netdev_get_etheraddr(iface->netdev, iface_ea);
964             if (error) {
965                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
966                 VLOG_ERR_RL(&rl, "failed to obtain Ethernet address of %s: %s",
967                             iface->name, strerror(error));
968                 continue;
969             }
970         }
971
972         /* Compare against our current choice. */
973         if (!eth_addr_is_multicast(iface_ea) &&
974             !eth_addr_is_local(iface_ea) &&
975             !eth_addr_is_reserved(iface_ea) &&
976             !eth_addr_is_zero(iface_ea) &&
977             eth_addr_compare_3way(iface_ea, ea) < 0)
978         {
979             memcpy(ea, iface_ea, ETH_ADDR_LEN);
980             *hw_addr_iface = iface;
981         }
982     }
983     if (eth_addr_is_multicast(ea)) {
984         memcpy(ea, br->default_ea, ETH_ADDR_LEN);
985         *hw_addr_iface = NULL;
986         VLOG_WARN("bridge %s: using default bridge Ethernet "
987                   "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
988     } else {
989         VLOG_DBG("bridge %s: using bridge Ethernet address "ETH_ADDR_FMT,
990                  br->name, ETH_ADDR_ARGS(ea));
991     }
992 }
993
994 /* Choose and returns the datapath ID for bridge 'br' given that the bridge
995  * Ethernet address is 'bridge_ea'.  If 'bridge_ea' is the Ethernet address of
996  * an interface on 'br', then that interface must be passed in as
997  * 'hw_addr_iface'; if 'bridge_ea' was derived some other way, then
998  * 'hw_addr_iface' must be passed in as a null pointer. */
999 static uint64_t
1000 bridge_pick_datapath_id(struct bridge *br,
1001                         const uint8_t bridge_ea[ETH_ADDR_LEN],
1002                         struct iface *hw_addr_iface)
1003 {
1004     /*
1005      * The procedure for choosing a bridge MAC address will, in the most
1006      * ordinary case, also choose a unique MAC that we can use as a datapath
1007      * ID.  In some special cases, though, multiple bridges will end up with
1008      * the same MAC address.  This is OK for the bridges, but it will confuse
1009      * the OpenFlow controller, because each datapath needs a unique datapath
1010      * ID.
1011      *
1012      * Datapath IDs must be unique.  It is also very desirable that they be
1013      * stable from one run to the next, so that policy set on a datapath
1014      * "sticks".
1015      */
1016     const char *datapath_id;
1017     uint64_t dpid;
1018
1019     datapath_id = bridge_get_other_config(br->cfg, "datapath-id");
1020     if (datapath_id && dpid_from_string(datapath_id, &dpid)) {
1021         return dpid;
1022     }
1023
1024     if (hw_addr_iface) {
1025         int vlan;
1026         if (!netdev_get_vlan_vid(hw_addr_iface->netdev, &vlan)) {
1027             /*
1028              * A bridge whose MAC address is taken from a VLAN network device
1029              * (that is, a network device created with vconfig(8) or similar
1030              * tool) will have the same MAC address as a bridge on the VLAN
1031              * device's physical network device.
1032              *
1033              * Handle this case by hashing the physical network device MAC
1034              * along with the VLAN identifier.
1035              */
1036             uint8_t buf[ETH_ADDR_LEN + 2];
1037             memcpy(buf, bridge_ea, ETH_ADDR_LEN);
1038             buf[ETH_ADDR_LEN] = vlan >> 8;
1039             buf[ETH_ADDR_LEN + 1] = vlan;
1040             return dpid_from_hash(buf, sizeof buf);
1041         } else {
1042             /*
1043              * Assume that this bridge's MAC address is unique, since it
1044              * doesn't fit any of the cases we handle specially.
1045              */
1046         }
1047     } else {
1048         /*
1049          * A purely internal bridge, that is, one that has no non-virtual
1050          * network devices on it at all, is more difficult because it has no
1051          * natural unique identifier at all.
1052          *
1053          * When the host is a XenServer, we handle this case by hashing the
1054          * host's UUID with the name of the bridge.  Names of bridges are
1055          * persistent across XenServer reboots, although they can be reused if
1056          * an internal network is destroyed and then a new one is later
1057          * created, so this is fairly effective.
1058          *
1059          * When the host is not a XenServer, we punt by using a random MAC
1060          * address on each run.
1061          */
1062         const char *host_uuid = xenserver_get_host_uuid();
1063         if (host_uuid) {
1064             char *combined = xasprintf("%s,%s", host_uuid, br->name);
1065             dpid = dpid_from_hash(combined, strlen(combined));
1066             free(combined);
1067             return dpid;
1068         }
1069     }
1070
1071     return eth_addr_to_uint64(bridge_ea);
1072 }
1073
1074 static uint64_t
1075 dpid_from_hash(const void *data, size_t n)
1076 {
1077     uint8_t hash[SHA1_DIGEST_SIZE];
1078
1079     BUILD_ASSERT_DECL(sizeof hash >= ETH_ADDR_LEN);
1080     sha1_bytes(data, n, hash);
1081     eth_addr_mark_random(hash);
1082     return eth_addr_to_uint64(hash);
1083 }
1084
1085 static void
1086 iface_refresh_status(struct iface *iface)
1087 {
1088     struct shash sh;
1089
1090     enum netdev_flags flags;
1091     uint32_t current;
1092     int64_t bps;
1093     int mtu;
1094     int64_t mtu_64;
1095     int error;
1096
1097     shash_init(&sh);
1098
1099     if (!netdev_get_status(iface->netdev, &sh)) {
1100         size_t n;
1101         char **keys, **values;
1102
1103         shash_to_ovs_idl_map(&sh, &keys, &values, &n);
1104         ovsrec_interface_set_status(iface->cfg, keys, values, n);
1105
1106         free(keys);
1107         free(values);
1108     } else {
1109         ovsrec_interface_set_status(iface->cfg, NULL, NULL, 0);
1110     }
1111
1112     shash_destroy_free_data(&sh);
1113
1114     error = netdev_get_flags(iface->netdev, &flags);
1115     if (!error) {
1116         ovsrec_interface_set_admin_state(iface->cfg, flags & NETDEV_UP ? "up" : "down");
1117     }
1118     else {
1119         ovsrec_interface_set_admin_state(iface->cfg, NULL);
1120     }
1121
1122     error = netdev_get_features(iface->netdev, &current, NULL, NULL, NULL);
1123     if (!error) {
1124         ovsrec_interface_set_duplex(iface->cfg,
1125                                     netdev_features_is_full_duplex(current)
1126                                     ? "full" : "half");
1127         /* warning: uint64_t -> int64_t conversion */
1128         bps = netdev_features_to_bps(current);
1129         ovsrec_interface_set_link_speed(iface->cfg, &bps, 1);
1130     }
1131     else {
1132         ovsrec_interface_set_duplex(iface->cfg, NULL);
1133         ovsrec_interface_set_link_speed(iface->cfg, NULL, 0);
1134     }
1135
1136
1137     ovsrec_interface_set_link_state(iface->cfg,
1138                                     iface_get_carrier(iface) ? "up" : "down");
1139
1140     error = netdev_get_mtu(iface->netdev, &mtu);
1141     if (!error && mtu != INT_MAX) {
1142         mtu_64 = mtu;
1143         ovsrec_interface_set_mtu(iface->cfg, &mtu_64, 1);
1144     }
1145     else {
1146         ovsrec_interface_set_mtu(iface->cfg, NULL, 0);
1147     }
1148 }
1149
1150 /* Writes 'iface''s CFM statistics to the database.  Returns true if anything
1151  * changed, false otherwise. */
1152 static bool
1153 iface_refresh_cfm_stats(struct iface *iface)
1154 {
1155     const struct ovsrec_monitor *mon;
1156     const struct cfm *cfm;
1157     bool changed = false;
1158     size_t i;
1159
1160     mon = iface->cfg->monitor;
1161     cfm = ofproto_iface_get_cfm(iface->port->bridge->ofproto, iface->dp_ifidx);
1162
1163     if (!cfm || !mon) {
1164         return false;
1165     }
1166
1167     for (i = 0; i < mon->n_remote_mps; i++) {
1168         const struct ovsrec_maintenance_point *mp;
1169         const struct remote_mp *rmp;
1170
1171         mp = mon->remote_mps[i];
1172         rmp = cfm_get_remote_mp(cfm, mp->mpid);
1173
1174         if (mp->n_fault != 1 || mp->fault[0] != rmp->fault) {
1175             ovsrec_maintenance_point_set_fault(mp, &rmp->fault, 1);
1176             changed = true;
1177         }
1178     }
1179
1180     if (mon->n_fault != 1 || mon->fault[0] != cfm->fault) {
1181         ovsrec_monitor_set_fault(mon, &cfm->fault, 1);
1182         changed = true;
1183     }
1184
1185     return changed;
1186 }
1187
1188 static void
1189 iface_refresh_stats(struct iface *iface)
1190 {
1191     struct iface_stat {
1192         char *name;
1193         int offset;
1194     };
1195     static const struct iface_stat iface_stats[] = {
1196         { "rx_packets", offsetof(struct netdev_stats, rx_packets) },
1197         { "tx_packets", offsetof(struct netdev_stats, tx_packets) },
1198         { "rx_bytes", offsetof(struct netdev_stats, rx_bytes) },
1199         { "tx_bytes", offsetof(struct netdev_stats, tx_bytes) },
1200         { "rx_dropped", offsetof(struct netdev_stats, rx_dropped) },
1201         { "tx_dropped", offsetof(struct netdev_stats, tx_dropped) },
1202         { "rx_errors", offsetof(struct netdev_stats, rx_errors) },
1203         { "tx_errors", offsetof(struct netdev_stats, tx_errors) },
1204         { "rx_frame_err", offsetof(struct netdev_stats, rx_frame_errors) },
1205         { "rx_over_err", offsetof(struct netdev_stats, rx_over_errors) },
1206         { "rx_crc_err", offsetof(struct netdev_stats, rx_crc_errors) },
1207         { "collisions", offsetof(struct netdev_stats, collisions) },
1208     };
1209     enum { N_STATS = ARRAY_SIZE(iface_stats) };
1210     const struct iface_stat *s;
1211
1212     char *keys[N_STATS];
1213     int64_t values[N_STATS];
1214     int n;
1215
1216     struct netdev_stats stats;
1217
1218     /* Intentionally ignore return value, since errors will set 'stats' to
1219      * all-1s, and we will deal with that correctly below. */
1220     netdev_get_stats(iface->netdev, &stats);
1221
1222     n = 0;
1223     for (s = iface_stats; s < &iface_stats[N_STATS]; s++) {
1224         uint64_t value = *(uint64_t *) (((char *) &stats) + s->offset);
1225         if (value != UINT64_MAX) {
1226             keys[n] = s->name;
1227             values[n] = value;
1228             n++;
1229         }
1230     }
1231
1232     ovsrec_interface_set_statistics(iface->cfg, keys, values, n);
1233 }
1234
1235 static void
1236 refresh_system_stats(const struct ovsrec_open_vswitch *cfg)
1237 {
1238     struct ovsdb_datum datum;
1239     struct shash stats;
1240
1241     shash_init(&stats);
1242     get_system_stats(&stats);
1243
1244     ovsdb_datum_from_shash(&datum, &stats);
1245     ovsdb_idl_txn_write(&cfg->header_, &ovsrec_open_vswitch_col_statistics,
1246                         &datum);
1247 }
1248
1249 static inline const char *
1250 nx_role_to_str(enum nx_role role)
1251 {
1252     switch (role) {
1253     case NX_ROLE_OTHER:
1254         return "other";
1255     case NX_ROLE_MASTER:
1256         return "master";
1257     case NX_ROLE_SLAVE:
1258         return "slave";
1259     default:
1260         return "*** INVALID ROLE ***";
1261     }
1262 }
1263
1264 static void
1265 bridge_refresh_controller_status(const struct bridge *br)
1266 {
1267     struct shash info;
1268     const struct ovsrec_controller *cfg;
1269
1270     ofproto_get_ofproto_controller_info(br->ofproto, &info);
1271
1272     OVSREC_CONTROLLER_FOR_EACH(cfg, idl) {
1273         struct ofproto_controller_info *cinfo =
1274             shash_find_data(&info, cfg->target);
1275
1276         if (cinfo) {
1277             ovsrec_controller_set_is_connected(cfg, cinfo->is_connected);
1278             ovsrec_controller_set_role(cfg, nx_role_to_str(cinfo->role));
1279             ovsrec_controller_set_status(cfg, (char **) cinfo->pairs.keys,
1280                                          (char **) cinfo->pairs.values,
1281                                          cinfo->pairs.n);
1282         } else {
1283             ovsrec_controller_set_is_connected(cfg, false);
1284             ovsrec_controller_set_role(cfg, NULL);
1285             ovsrec_controller_set_status(cfg, NULL, NULL, 0);
1286         }
1287     }
1288
1289     ofproto_free_ofproto_controller_info(&info);
1290 }
1291
1292 void
1293 bridge_run(void)
1294 {
1295     const struct ovsrec_open_vswitch *cfg;
1296
1297     bool datapath_destroyed;
1298     bool database_changed;
1299     struct bridge *br;
1300
1301     /* Let each bridge do the work that it needs to do. */
1302     datapath_destroyed = false;
1303     LIST_FOR_EACH (br, node, &all_bridges) {
1304         int error = bridge_run_one(br);
1305         if (error) {
1306             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1307             VLOG_ERR_RL(&rl, "bridge %s: datapath was destroyed externally, "
1308                         "forcing reconfiguration", br->name);
1309             datapath_destroyed = true;
1310         }
1311     }
1312
1313     /* (Re)configure if necessary. */
1314     database_changed = ovsdb_idl_run(idl);
1315     cfg = ovsrec_open_vswitch_first(idl);
1316 #ifdef HAVE_OPENSSL
1317     /* Re-configure SSL.  We do this on every trip through the main loop,
1318      * instead of just when the database changes, because the contents of the
1319      * key and certificate files can change without the database changing.
1320      *
1321      * We do this before bridge_reconfigure() because that function might
1322      * initiate SSL connections and thus requires SSL to be configured. */
1323     if (cfg && cfg->ssl) {
1324         const struct ovsrec_ssl *ssl = cfg->ssl;
1325
1326         stream_ssl_set_key_and_cert(ssl->private_key, ssl->certificate);
1327         stream_ssl_set_ca_cert_file(ssl->ca_cert, ssl->bootstrap_ca_cert);
1328     }
1329 #endif
1330     if (database_changed || datapath_destroyed) {
1331         if (cfg) {
1332             struct ovsdb_idl_txn *txn = ovsdb_idl_txn_create(idl);
1333
1334             bridge_configure_once(cfg);
1335             bridge_reconfigure(cfg);
1336
1337             ovsrec_open_vswitch_set_cur_cfg(cfg, cfg->next_cfg);
1338             ovsdb_idl_txn_commit(txn);
1339             ovsdb_idl_txn_destroy(txn); /* XXX */
1340         } else {
1341             /* We still need to reconfigure to avoid dangling pointers to
1342              * now-destroyed ovsrec structures inside bridge data. */
1343             static const struct ovsrec_open_vswitch null_cfg;
1344
1345             bridge_reconfigure(&null_cfg);
1346         }
1347     }
1348
1349     /* Refresh system and interface stats if necessary. */
1350     if (time_msec() >= stats_timer) {
1351         if (cfg) {
1352             struct ovsdb_idl_txn *txn;
1353
1354             txn = ovsdb_idl_txn_create(idl);
1355             LIST_FOR_EACH (br, node, &all_bridges) {
1356                 struct port *port;
1357
1358                 HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1359                     struct iface *iface;
1360
1361                     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1362                         iface_refresh_stats(iface);
1363                         iface_refresh_status(iface);
1364                     }
1365                 }
1366                 bridge_refresh_controller_status(br);
1367             }
1368             refresh_system_stats(cfg);
1369             ovsdb_idl_txn_commit(txn);
1370             ovsdb_idl_txn_destroy(txn); /* XXX */
1371         }
1372
1373         stats_timer = time_msec() + STATS_INTERVAL;
1374     }
1375
1376     if (time_msec() >= cfm_limiter) {
1377         struct ovsdb_idl_txn *txn;
1378         bool changed = false;
1379
1380         txn = ovsdb_idl_txn_create(idl);
1381         LIST_FOR_EACH (br, node, &all_bridges) {
1382             struct port *port;
1383
1384             HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1385                 struct iface *iface;
1386
1387                 LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1388                     changed = iface_refresh_cfm_stats(iface) || changed;
1389                 }
1390             }
1391         }
1392
1393         if (changed) {
1394             cfm_limiter = time_msec() + CFM_LIMIT_INTERVAL;
1395         }
1396
1397         ovsdb_idl_txn_commit(txn);
1398         ovsdb_idl_txn_destroy(txn);
1399     }
1400 }
1401
1402 void
1403 bridge_wait(void)
1404 {
1405     struct bridge *br;
1406
1407     LIST_FOR_EACH (br, node, &all_bridges) {
1408         struct port *port;
1409
1410         ofproto_wait(br->ofproto);
1411         mac_learning_wait(br->ml);
1412         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1413             port_wait(port);
1414         }
1415     }
1416     ovsdb_idl_wait(idl);
1417     poll_timer_wait_until(stats_timer);
1418
1419     if (cfm_limiter > time_msec()) {
1420         poll_timer_wait_until(cfm_limiter);
1421     }
1422 }
1423
1424 /* Forces 'br' to revalidate all of its flows.  This is appropriate when 'br''s
1425  * configuration changes.  */
1426 static void
1427 bridge_flush(struct bridge *br)
1428 {
1429     COVERAGE_INC(bridge_flush);
1430     br->flush = true;
1431 }
1432 \f
1433 /* Bridge unixctl user interface functions. */
1434 static void
1435 bridge_unixctl_fdb_show(struct unixctl_conn *conn,
1436                         const char *args, void *aux OVS_UNUSED)
1437 {
1438     struct ds ds = DS_EMPTY_INITIALIZER;
1439     const struct bridge *br;
1440     const struct mac_entry *e;
1441
1442     br = bridge_lookup(args);
1443     if (!br) {
1444         unixctl_command_reply(conn, 501, "no such bridge");
1445         return;
1446     }
1447
1448     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
1449     LIST_FOR_EACH (e, lru_node, &br->ml->lrus) {
1450         struct port *port = e->port.p;
1451         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
1452                       port_get_an_iface(port)->dp_ifidx,
1453                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
1454     }
1455     unixctl_command_reply(conn, 200, ds_cstr(&ds));
1456     ds_destroy(&ds);
1457 }
1458 \f
1459 /* CFM unixctl user interface functions. */
1460 static void
1461 cfm_unixctl_show(struct unixctl_conn *conn,
1462                  const char *args, void *aux OVS_UNUSED)
1463 {
1464     struct ds ds = DS_EMPTY_INITIALIZER;
1465     struct iface *iface;
1466     const struct cfm *cfm;
1467
1468     iface = iface_find(args);
1469     if (!iface) {
1470         unixctl_command_reply(conn, 501, "no such interface");
1471         return;
1472     }
1473
1474     cfm = ofproto_iface_get_cfm(iface->port->bridge->ofproto, iface->dp_ifidx);
1475
1476     if (!cfm) {
1477         unixctl_command_reply(conn, 501, "CFM not enabled");
1478         return;
1479     }
1480
1481     cfm_dump_ds(cfm, &ds);
1482     unixctl_command_reply(conn, 200, ds_cstr(&ds));
1483     ds_destroy(&ds);
1484 }
1485 \f
1486 /* QoS unixctl user interface functions. */
1487
1488 struct qos_unixctl_show_cbdata {
1489     struct ds *ds;
1490     struct iface *iface;
1491 };
1492
1493 static void
1494 qos_unixctl_show_cb(unsigned int queue_id,
1495                     const struct shash *details,
1496                     void *aux)
1497 {
1498     struct qos_unixctl_show_cbdata *data = aux;
1499     struct ds *ds = data->ds;
1500     struct iface *iface = data->iface;
1501     struct netdev_queue_stats stats;
1502     struct shash_node *node;
1503     int error;
1504
1505     ds_put_cstr(ds, "\n");
1506     if (queue_id) {
1507         ds_put_format(ds, "Queue %u:\n", queue_id);
1508     } else {
1509         ds_put_cstr(ds, "Default:\n");
1510     }
1511
1512     SHASH_FOR_EACH (node, details) {
1513         ds_put_format(ds, "\t%s: %s\n", node->name, (char *)node->data);
1514     }
1515
1516     error = netdev_get_queue_stats(iface->netdev, queue_id, &stats);
1517     if (!error) {
1518         if (stats.tx_packets != UINT64_MAX) {
1519             ds_put_format(ds, "\ttx_packets: %"PRIu64"\n", stats.tx_packets);
1520         }
1521
1522         if (stats.tx_bytes != UINT64_MAX) {
1523             ds_put_format(ds, "\ttx_bytes: %"PRIu64"\n", stats.tx_bytes);
1524         }
1525
1526         if (stats.tx_errors != UINT64_MAX) {
1527             ds_put_format(ds, "\ttx_errors: %"PRIu64"\n", stats.tx_errors);
1528         }
1529     } else {
1530         ds_put_format(ds, "\tFailed to get statistics for queue %u: %s",
1531                       queue_id, strerror(error));
1532     }
1533 }
1534
1535 static void
1536 qos_unixctl_show(struct unixctl_conn *conn,
1537                  const char *args, void *aux OVS_UNUSED)
1538 {
1539     struct ds ds = DS_EMPTY_INITIALIZER;
1540     struct shash sh = SHASH_INITIALIZER(&sh);
1541     struct iface *iface;
1542     const char *type;
1543     struct shash_node *node;
1544     struct qos_unixctl_show_cbdata data;
1545     int error;
1546
1547     iface = iface_find(args);
1548     if (!iface) {
1549         unixctl_command_reply(conn, 501, "no such interface");
1550         return;
1551     }
1552
1553     netdev_get_qos(iface->netdev, &type, &sh);
1554
1555     if (*type != '\0') {
1556         ds_put_format(&ds, "QoS: %s %s\n", iface->name, type);
1557
1558         SHASH_FOR_EACH (node, &sh) {
1559             ds_put_format(&ds, "%s: %s\n", node->name, (char *)node->data);
1560         }
1561
1562         data.ds = &ds;
1563         data.iface = iface;
1564         error = netdev_dump_queues(iface->netdev, qos_unixctl_show_cb, &data);
1565
1566         if (error) {
1567             ds_put_format(&ds, "failed to dump queues: %s", strerror(error));
1568         }
1569         unixctl_command_reply(conn, 200, ds_cstr(&ds));
1570     } else {
1571         ds_put_format(&ds, "QoS not configured on %s\n", iface->name);
1572         unixctl_command_reply(conn, 501, ds_cstr(&ds));
1573     }
1574
1575     shash_destroy_free_data(&sh);
1576     ds_destroy(&ds);
1577 }
1578 \f
1579 /* Bridge reconfiguration functions. */
1580 static struct bridge *
1581 bridge_create(const struct ovsrec_bridge *br_cfg)
1582 {
1583     struct bridge *br;
1584     int error;
1585
1586     assert(!bridge_lookup(br_cfg->name));
1587     br = xzalloc(sizeof *br);
1588
1589     error = dpif_create_and_open(br_cfg->name, br_cfg->datapath_type,
1590                                  &br->dpif);
1591     if (error) {
1592         free(br);
1593         return NULL;
1594     }
1595
1596     error = ofproto_create(br_cfg->name, br_cfg->datapath_type, &bridge_ofhooks,
1597                            br, &br->ofproto);
1598     if (error) {
1599         VLOG_ERR("failed to create switch %s: %s", br_cfg->name,
1600                  strerror(error));
1601         dpif_delete(br->dpif);
1602         dpif_close(br->dpif);
1603         free(br);
1604         return NULL;
1605     }
1606
1607     br->name = xstrdup(br_cfg->name);
1608     br->cfg = br_cfg;
1609     br->ml = mac_learning_create();
1610     eth_addr_nicira_random(br->default_ea);
1611
1612     hmap_init(&br->ports);
1613     hmap_init(&br->ifaces);
1614     shash_init(&br->iface_by_name);
1615
1616     br->flush = false;
1617
1618     list_push_back(&all_bridges, &br->node);
1619
1620     VLOG_INFO("created bridge %s on %s", br->name, dpif_name(br->dpif));
1621
1622     return br;
1623 }
1624
1625 static void
1626 bridge_destroy(struct bridge *br)
1627 {
1628     if (br) {
1629         struct port *port, *next;
1630         int error;
1631
1632         HMAP_FOR_EACH_SAFE (port, next, hmap_node, &br->ports) {
1633             port_destroy(port);
1634         }
1635         list_remove(&br->node);
1636         ofproto_destroy(br->ofproto);
1637         error = dpif_delete(br->dpif);
1638         if (error && error != ENOENT) {
1639             VLOG_ERR("failed to delete %s: %s",
1640                      dpif_name(br->dpif), strerror(error));
1641         }
1642         dpif_close(br->dpif);
1643         mac_learning_destroy(br->ml);
1644         hmap_destroy(&br->ifaces);
1645         hmap_destroy(&br->ports);
1646         shash_destroy(&br->iface_by_name);
1647         free(br->name);
1648         free(br);
1649     }
1650 }
1651
1652 static struct bridge *
1653 bridge_lookup(const char *name)
1654 {
1655     struct bridge *br;
1656
1657     LIST_FOR_EACH (br, node, &all_bridges) {
1658         if (!strcmp(br->name, name)) {
1659             return br;
1660         }
1661     }
1662     return NULL;
1663 }
1664
1665 /* Handle requests for a listing of all flows known by the OpenFlow
1666  * stack, including those normally hidden. */
1667 static void
1668 bridge_unixctl_dump_flows(struct unixctl_conn *conn,
1669                           const char *args, void *aux OVS_UNUSED)
1670 {
1671     struct bridge *br;
1672     struct ds results;
1673
1674     br = bridge_lookup(args);
1675     if (!br) {
1676         unixctl_command_reply(conn, 501, "Unknown bridge");
1677         return;
1678     }
1679
1680     ds_init(&results);
1681     ofproto_get_all_flows(br->ofproto, &results);
1682
1683     unixctl_command_reply(conn, 200, ds_cstr(&results));
1684     ds_destroy(&results);
1685 }
1686
1687 /* "bridge/reconnect [BRIDGE]": makes BRIDGE drop all of its controller
1688  * connections and reconnect.  If BRIDGE is not specified, then all bridges
1689  * drop their controller connections and reconnect. */
1690 static void
1691 bridge_unixctl_reconnect(struct unixctl_conn *conn,
1692                          const char *args, void *aux OVS_UNUSED)
1693 {
1694     struct bridge *br;
1695     if (args[0] != '\0') {
1696         br = bridge_lookup(args);
1697         if (!br) {
1698             unixctl_command_reply(conn, 501, "Unknown bridge");
1699             return;
1700         }
1701         ofproto_reconnect_controllers(br->ofproto);
1702     } else {
1703         LIST_FOR_EACH (br, node, &all_bridges) {
1704             ofproto_reconnect_controllers(br->ofproto);
1705         }
1706     }
1707     unixctl_command_reply(conn, 200, NULL);
1708 }
1709
1710 static int
1711 bridge_run_one(struct bridge *br)
1712 {
1713     struct port *port;
1714     int error;
1715
1716     error = ofproto_run1(br->ofproto);
1717     if (error) {
1718         return error;
1719     }
1720
1721     mac_learning_run(br->ml, ofproto_get_revalidate_set(br->ofproto));
1722
1723     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1724         port_run(port);
1725     }
1726
1727     error = ofproto_run2(br->ofproto, br->flush);
1728     br->flush = false;
1729
1730     return error;
1731 }
1732
1733 static size_t
1734 bridge_get_controllers(const struct bridge *br,
1735                        struct ovsrec_controller ***controllersp)
1736 {
1737     struct ovsrec_controller **controllers;
1738     size_t n_controllers;
1739
1740     controllers = br->cfg->controller;
1741     n_controllers = br->cfg->n_controller;
1742
1743     if (n_controllers == 1 && !strcmp(controllers[0]->target, "none")) {
1744         controllers = NULL;
1745         n_controllers = 0;
1746     }
1747
1748     if (controllersp) {
1749         *controllersp = controllers;
1750     }
1751     return n_controllers;
1752 }
1753
1754 static void
1755 bridge_reconfigure_one(struct bridge *br)
1756 {
1757     enum ofproto_fail_mode fail_mode;
1758     struct port *port, *next;
1759     struct shash_node *node;
1760     struct shash new_ports;
1761     size_t i;
1762
1763     /* Collect new ports. */
1764     shash_init(&new_ports);
1765     for (i = 0; i < br->cfg->n_ports; i++) {
1766         const char *name = br->cfg->ports[i]->name;
1767         if (!shash_add_once(&new_ports, name, br->cfg->ports[i])) {
1768             VLOG_WARN("bridge %s: %s specified twice as bridge port",
1769                       br->name, name);
1770         }
1771     }
1772
1773     /* If we have a controller, then we need a local port.  Complain if the
1774      * user didn't specify one.
1775      *
1776      * XXX perhaps we should synthesize a port ourselves in this case. */
1777     if (bridge_get_controllers(br, NULL)) {
1778         char local_name[IF_NAMESIZE];
1779         int error;
1780
1781         error = dpif_port_get_name(br->dpif, ODPP_LOCAL,
1782                                    local_name, sizeof local_name);
1783         if (!error && !shash_find(&new_ports, local_name)) {
1784             VLOG_WARN("bridge %s: controller specified but no local port "
1785                       "(port named %s) defined",
1786                       br->name, local_name);
1787         }
1788     }
1789
1790     /* Get rid of deleted ports.
1791      * Get rid of deleted interfaces on ports that still exist. */
1792     HMAP_FOR_EACH_SAFE (port, next, hmap_node, &br->ports) {
1793         const struct ovsrec_port *port_cfg;
1794
1795         port_cfg = shash_find_data(&new_ports, port->name);
1796         if (!port_cfg) {
1797             port_destroy(port);
1798         } else {
1799             port_del_ifaces(port, port_cfg);
1800         }
1801     }
1802
1803     /* Create new ports.
1804      * Add new interfaces to existing ports.
1805      * Reconfigure existing ports. */
1806     SHASH_FOR_EACH (node, &new_ports) {
1807         struct port *port = port_lookup(br, node->name);
1808         if (!port) {
1809             port = port_create(br, node->name);
1810         }
1811
1812         port_reconfigure(port, node->data);
1813         if (!port->n_ifaces) {
1814             VLOG_WARN("bridge %s: port %s has no interfaces, dropping",
1815                       br->name, port->name);
1816             port_destroy(port);
1817         }
1818     }
1819     shash_destroy(&new_ports);
1820
1821     /* Set the fail-mode */
1822     fail_mode = !br->cfg->fail_mode
1823                 || !strcmp(br->cfg->fail_mode, "standalone")
1824                     ? OFPROTO_FAIL_STANDALONE
1825                     : OFPROTO_FAIL_SECURE;
1826     if (ofproto_get_fail_mode(br->ofproto) != fail_mode
1827         && !ofproto_has_primary_controller(br->ofproto)) {
1828         ofproto_flush_flows(br->ofproto);
1829     }
1830     ofproto_set_fail_mode(br->ofproto, fail_mode);
1831
1832     /* Delete all flows if we're switching from connected to standalone or vice
1833      * versa.  (XXX Should we delete all flows if we are switching from one
1834      * controller to another?) */
1835
1836     /* Configure OpenFlow controller connection snooping. */
1837     if (!ofproto_has_snoops(br->ofproto)) {
1838         struct sset snoops;
1839
1840         sset_init(&snoops);
1841         sset_add_and_free(&snoops, xasprintf("punix:%s/%s.snoop",
1842                                              ovs_rundir(), br->name));
1843         ofproto_set_snoops(br->ofproto, &snoops);
1844         sset_destroy(&snoops);
1845     }
1846
1847     mirror_reconfigure(br);
1848 }
1849
1850 /* Initializes 'oc' appropriately as a management service controller for
1851  * 'br'.
1852  *
1853  * The caller must free oc->target when it is no longer needed. */
1854 static void
1855 bridge_ofproto_controller_for_mgmt(const struct bridge *br,
1856                                    struct ofproto_controller *oc)
1857 {
1858     oc->target = xasprintf("punix:%s/%s.mgmt", ovs_rundir(), br->name);
1859     oc->max_backoff = 0;
1860     oc->probe_interval = 60;
1861     oc->band = OFPROTO_OUT_OF_BAND;
1862     oc->rate_limit = 0;
1863     oc->burst_limit = 0;
1864 }
1865
1866 /* Converts ovsrec_controller 'c' into an ofproto_controller in 'oc'.  */
1867 static void
1868 bridge_ofproto_controller_from_ovsrec(const struct ovsrec_controller *c,
1869                                       struct ofproto_controller *oc)
1870 {
1871     oc->target = c->target;
1872     oc->max_backoff = c->max_backoff ? *c->max_backoff / 1000 : 8;
1873     oc->probe_interval = c->inactivity_probe ? *c->inactivity_probe / 1000 : 5;
1874     oc->band = (!c->connection_mode || !strcmp(c->connection_mode, "in-band")
1875                 ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
1876     oc->rate_limit = c->controller_rate_limit ? *c->controller_rate_limit : 0;
1877     oc->burst_limit = (c->controller_burst_limit
1878                        ? *c->controller_burst_limit : 0);
1879 }
1880
1881 /* Configures the IP stack for 'br''s local interface properly according to the
1882  * configuration in 'c'.  */
1883 static void
1884 bridge_configure_local_iface_netdev(struct bridge *br,
1885                                     struct ovsrec_controller *c)
1886 {
1887     struct netdev *netdev;
1888     struct in_addr mask, gateway;
1889
1890     struct iface *local_iface;
1891     struct in_addr ip;
1892
1893     /* If there's no local interface or no IP address, give up. */
1894     local_iface = iface_from_dp_ifidx(br, ODPP_LOCAL);
1895     if (!local_iface || !c->local_ip || !inet_aton(c->local_ip, &ip)) {
1896         return;
1897     }
1898
1899     /* Bring up the local interface. */
1900     netdev = local_iface->netdev;
1901     netdev_turn_flags_on(netdev, NETDEV_UP, true);
1902
1903     /* Configure the IP address and netmask. */
1904     if (!c->local_netmask
1905         || !inet_aton(c->local_netmask, &mask)
1906         || !mask.s_addr) {
1907         mask.s_addr = guess_netmask(ip.s_addr);
1908     }
1909     if (!netdev_set_in4(netdev, ip, mask)) {
1910         VLOG_INFO("bridge %s: configured IP address "IP_FMT", netmask "IP_FMT,
1911                   br->name, IP_ARGS(&ip.s_addr), IP_ARGS(&mask.s_addr));
1912     }
1913
1914     /* Configure the default gateway. */
1915     if (c->local_gateway
1916         && inet_aton(c->local_gateway, &gateway)
1917         && gateway.s_addr) {
1918         if (!netdev_add_router(netdev, gateway)) {
1919             VLOG_INFO("bridge %s: configured gateway "IP_FMT,
1920                       br->name, IP_ARGS(&gateway.s_addr));
1921         }
1922     }
1923 }
1924
1925 static void
1926 bridge_reconfigure_remotes(struct bridge *br,
1927                            const struct sockaddr_in *managers,
1928                            size_t n_managers)
1929 {
1930     const char *disable_ib_str, *queue_id_str;
1931     bool disable_in_band = false;
1932     int queue_id;
1933
1934     struct ovsrec_controller **controllers;
1935     size_t n_controllers;
1936     bool had_primary;
1937
1938     struct ofproto_controller *ocs;
1939     size_t n_ocs;
1940     size_t i;
1941
1942     /* Check if we should disable in-band control on this bridge. */
1943     disable_ib_str = bridge_get_other_config(br->cfg, "disable-in-band");
1944     if (disable_ib_str && !strcmp(disable_ib_str, "true")) {
1945         disable_in_band = true;
1946     }
1947
1948     /* Set OpenFlow queue ID for in-band control. */
1949     queue_id_str = bridge_get_other_config(br->cfg, "in-band-queue");
1950     queue_id = queue_id_str ? strtol(queue_id_str, NULL, 10) : -1;
1951     ofproto_set_in_band_queue(br->ofproto, queue_id);
1952
1953     if (disable_in_band) {
1954         ofproto_set_extra_in_band_remotes(br->ofproto, NULL, 0);
1955     } else {
1956         ofproto_set_extra_in_band_remotes(br->ofproto, managers, n_managers);
1957     }
1958     had_primary = ofproto_has_primary_controller(br->ofproto);
1959
1960     n_controllers = bridge_get_controllers(br, &controllers);
1961
1962     ocs = xmalloc((n_controllers + 1) * sizeof *ocs);
1963     n_ocs = 0;
1964
1965     bridge_ofproto_controller_for_mgmt(br, &ocs[n_ocs++]);
1966     for (i = 0; i < n_controllers; i++) {
1967         struct ovsrec_controller *c = controllers[i];
1968
1969         if (!strncmp(c->target, "punix:", 6)
1970             || !strncmp(c->target, "unix:", 5)) {
1971             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1972
1973             /* Prevent remote ovsdb-server users from accessing arbitrary Unix
1974              * domain sockets and overwriting arbitrary local files. */
1975             VLOG_ERR_RL(&rl, "%s: not adding Unix domain socket controller "
1976                         "\"%s\" due to possibility for remote exploit",
1977                         dpif_name(br->dpif), c->target);
1978             continue;
1979         }
1980
1981         bridge_configure_local_iface_netdev(br, c);
1982         bridge_ofproto_controller_from_ovsrec(c, &ocs[n_ocs]);
1983         if (disable_in_band) {
1984             ocs[n_ocs].band = OFPROTO_OUT_OF_BAND;
1985         }
1986         n_ocs++;
1987     }
1988
1989     ofproto_set_controllers(br->ofproto, ocs, n_ocs);
1990     free(ocs[0].target); /* From bridge_ofproto_controller_for_mgmt(). */
1991     free(ocs);
1992
1993     if (had_primary != ofproto_has_primary_controller(br->ofproto)) {
1994         ofproto_flush_flows(br->ofproto);
1995     }
1996
1997     /* If there are no controllers and the bridge is in standalone
1998      * mode, set up a flow that matches every packet and directs
1999      * them to OFPP_NORMAL (which goes to us).  Otherwise, the
2000      * switch is in secure mode and we won't pass any traffic until
2001      * a controller has been defined and it tells us to do so. */
2002     if (!n_controllers
2003         && ofproto_get_fail_mode(br->ofproto) == OFPROTO_FAIL_STANDALONE) {
2004         union ofp_action action;
2005         struct cls_rule rule;
2006
2007         memset(&action, 0, sizeof action);
2008         action.type = htons(OFPAT_OUTPUT);
2009         action.output.len = htons(sizeof action);
2010         action.output.port = htons(OFPP_NORMAL);
2011         cls_rule_init_catchall(&rule, 0);
2012         ofproto_add_flow(br->ofproto, &rule, &action, 1);
2013     }
2014 }
2015
2016 static void
2017 bridge_get_all_ifaces(const struct bridge *br, struct shash *ifaces)
2018 {
2019     struct port *port;
2020
2021     shash_init(ifaces);
2022     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2023         struct iface *iface;
2024
2025         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2026             shash_add_once(ifaces, iface->name, iface);
2027         }
2028         if (port->n_ifaces > 1 && port->cfg->bond_fake_iface) {
2029             shash_add_once(ifaces, port->name, NULL);
2030         }
2031     }
2032 }
2033
2034 /* For robustness, in case the administrator moves around datapath ports behind
2035  * our back, we re-check all the datapath port numbers here.
2036  *
2037  * This function will set the 'dp_ifidx' members of interfaces that have
2038  * disappeared to -1, so only call this function from a context where those
2039  * 'struct iface's will be removed from the bridge.  Otherwise, the -1
2040  * 'dp_ifidx'es will cause trouble later when we try to send them to the
2041  * datapath, which doesn't support UINT16_MAX+1 ports. */
2042 static void
2043 bridge_fetch_dp_ifaces(struct bridge *br)
2044 {
2045     struct dpif_port_dump dump;
2046     struct dpif_port dpif_port;
2047     struct port *port;
2048
2049     /* Reset all interface numbers. */
2050     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2051         struct iface *iface;
2052
2053         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2054             iface->dp_ifidx = -1;
2055         }
2056     }
2057     hmap_clear(&br->ifaces);
2058
2059     DPIF_PORT_FOR_EACH (&dpif_port, &dump, br->dpif) {
2060         struct iface *iface = iface_lookup(br, dpif_port.name);
2061         if (iface) {
2062             if (iface->dp_ifidx >= 0) {
2063                 VLOG_WARN("%s reported interface %s twice",
2064                           dpif_name(br->dpif), dpif_port.name);
2065             } else if (iface_from_dp_ifidx(br, dpif_port.port_no)) {
2066                 VLOG_WARN("%s reported interface %"PRIu16" twice",
2067                           dpif_name(br->dpif), dpif_port.port_no);
2068             } else {
2069                 iface->dp_ifidx = dpif_port.port_no;
2070                 hmap_insert(&br->ifaces, &iface->dp_ifidx_node,
2071                             hash_int(iface->dp_ifidx, 0));
2072             }
2073
2074             iface_set_ofport(iface->cfg,
2075                              (iface->dp_ifidx >= 0
2076                               ? odp_port_to_ofp_port(iface->dp_ifidx)
2077                               : -1));
2078         }
2079     }
2080 }
2081 \f
2082 /* Bridge packet processing functions. */
2083
2084 static bool
2085 set_dst(struct dst *dst, const struct flow *flow,
2086         const struct port *in_port, const struct port *out_port,
2087         tag_type *tags)
2088 {
2089     struct iface *iface;
2090     uint16_t vlan;
2091
2092     vlan = (out_port->vlan >= 0 ? OFP_VLAN_NONE
2093             : in_port->vlan >= 0 ? in_port->vlan
2094             : flow->vlan_tci == 0 ? OFP_VLAN_NONE
2095             : vlan_tci_to_vid(flow->vlan_tci));
2096
2097     iface = (!out_port->bond
2098              ? port_get_an_iface(out_port)
2099              : bond_choose_output_slave(out_port->bond, flow, vlan, tags));
2100     if (iface) {
2101         dst->vlan = vlan;
2102         dst->dp_ifidx = iface->dp_ifidx;
2103         return true;
2104     } else {
2105         return false;
2106     }
2107 }
2108
2109 static void
2110 swap_dst(struct dst *p, struct dst *q)
2111 {
2112     struct dst tmp = *p;
2113     *p = *q;
2114     *q = tmp;
2115 }
2116
2117 /* Moves all the dsts with vlan == 'vlan' to the front of the 'n_dsts' in
2118  * 'dsts'.  (This may help performance by reducing the number of VLAN changes
2119  * that we push to the datapath.  We could in fact fully sort the array by
2120  * vlan, but in most cases there are at most two different vlan tags so that's
2121  * possibly overkill.) */
2122 static void
2123 partition_dsts(struct dst_set *set, int vlan)
2124 {
2125     struct dst *first = set->dsts;
2126     struct dst *last = set->dsts + set->n;
2127
2128     while (first != last) {
2129         /* Invariants:
2130          *      - All dsts < first have vlan == 'vlan'.
2131          *      - All dsts >= last have vlan != 'vlan'.
2132          *      - first < last. */
2133         while (first->vlan == vlan) {
2134             if (++first == last) {
2135                 return;
2136             }
2137         }
2138
2139         /* Same invariants, plus one additional:
2140          *      - first->vlan != vlan.
2141          */
2142         while (last[-1].vlan != vlan) {
2143             if (--last == first) {
2144                 return;
2145             }
2146         }
2147
2148         /* Same invariants, plus one additional:
2149          *      - last[-1].vlan == vlan.*/
2150         swap_dst(first++, --last);
2151     }
2152 }
2153
2154 static int
2155 mirror_mask_ffs(mirror_mask_t mask)
2156 {
2157     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
2158     return ffs(mask);
2159 }
2160
2161 static void
2162 dst_set_init(struct dst_set *set)
2163 {
2164     set->dsts = set->builtin;
2165     set->n = 0;
2166     set->allocated = ARRAY_SIZE(set->builtin);
2167 }
2168
2169 static void
2170 dst_set_add(struct dst_set *set, const struct dst *dst)
2171 {
2172     if (set->n >= set->allocated) {
2173         size_t new_allocated;
2174         struct dst *new_dsts;
2175
2176         new_allocated = set->allocated * 2;
2177         new_dsts = xmalloc(new_allocated * sizeof *new_dsts);
2178         memcpy(new_dsts, set->dsts, set->n * sizeof *new_dsts);
2179
2180         dst_set_free(set);
2181
2182         set->dsts = new_dsts;
2183         set->allocated = new_allocated;
2184     }
2185     set->dsts[set->n++] = *dst;
2186 }
2187
2188 static void
2189 dst_set_free(struct dst_set *set)
2190 {
2191     if (set->dsts != set->builtin) {
2192         free(set->dsts);
2193     }
2194 }
2195
2196 static bool
2197 dst_is_duplicate(const struct dst_set *set, const struct dst *test)
2198 {
2199     size_t i;
2200     for (i = 0; i < set->n; i++) {
2201         if (set->dsts[i].vlan == test->vlan
2202             && set->dsts[i].dp_ifidx == test->dp_ifidx) {
2203             return true;
2204         }
2205     }
2206     return false;
2207 }
2208
2209 static bool
2210 port_trunks_vlan(const struct port *port, uint16_t vlan)
2211 {
2212     return (port->vlan < 0
2213             && (!port->trunks || bitmap_is_set(port->trunks, vlan)));
2214 }
2215
2216 static bool
2217 port_includes_vlan(const struct port *port, uint16_t vlan)
2218 {
2219     return vlan == port->vlan || port_trunks_vlan(port, vlan);
2220 }
2221
2222 static bool
2223 port_is_floodable(const struct port *port)
2224 {
2225     struct iface *iface;
2226
2227     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2228         if (!ofproto_port_is_floodable(port->bridge->ofproto,
2229                                        iface->dp_ifidx)) {
2230             return false;
2231         }
2232     }
2233     return true;
2234 }
2235
2236 /* Returns an arbitrary interface within 'port'. */
2237 static struct iface *
2238 port_get_an_iface(const struct port *port)
2239 {
2240     return CONTAINER_OF(list_front(&port->ifaces), struct iface, port_elem);
2241 }
2242
2243 static void
2244 compose_dsts(const struct bridge *br, const struct flow *flow, uint16_t vlan,
2245              const struct port *in_port, const struct port *out_port,
2246              struct dst_set *set, tag_type *tags, uint16_t *nf_output_iface)
2247 {
2248     mirror_mask_t mirrors = in_port->src_mirrors;
2249     struct dst dst;
2250     int flow_vlan;
2251
2252     flow_vlan = vlan_tci_to_vid(flow->vlan_tci);
2253     if (flow_vlan == 0) {
2254         flow_vlan = OFP_VLAN_NONE;
2255     }
2256
2257     if (out_port == FLOOD_PORT) {
2258         struct port *port;
2259
2260         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2261             if (port != in_port
2262                 && port_is_floodable(port)
2263                 && port_includes_vlan(port, vlan)
2264                 && !port->is_mirror_output_port
2265                 && set_dst(&dst, flow, in_port, port, tags)) {
2266                 mirrors |= port->dst_mirrors;
2267                 dst_set_add(set, &dst);
2268             }
2269         }
2270         *nf_output_iface = NF_OUT_FLOOD;
2271     } else if (out_port && set_dst(&dst, flow, in_port, out_port, tags)) {
2272         dst_set_add(set, &dst);
2273         *nf_output_iface = dst.dp_ifidx;
2274         mirrors |= out_port->dst_mirrors;
2275     }
2276
2277     while (mirrors) {
2278         struct mirror *m = br->mirrors[mirror_mask_ffs(mirrors) - 1];
2279         if (!m->n_vlans || vlan_is_mirrored(m, vlan)) {
2280             if (m->out_port) {
2281                 if (set_dst(&dst, flow, in_port, m->out_port, tags)
2282                     && !dst_is_duplicate(set, &dst)) {
2283                     dst_set_add(set, &dst);
2284                 }
2285             } else {
2286                 struct port *port;
2287
2288                 HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2289                     if (port_includes_vlan(port, m->out_vlan)
2290                         && set_dst(&dst, flow, in_port, port, tags))
2291                     {
2292                         if (port->vlan < 0) {
2293                             dst.vlan = m->out_vlan;
2294                         }
2295                         if (dst_is_duplicate(set, &dst)) {
2296                             continue;
2297                         }
2298
2299                         /* Use the vlan tag on the original flow instead of
2300                          * the one passed in the vlan parameter.  This ensures
2301                          * that we compare the vlan from before any implicit
2302                          * tagging tags place. This is necessary because
2303                          * dst->vlan is the final vlan, after removing implicit
2304                          * tags. */
2305                         if (port == in_port && dst.vlan == flow_vlan) {
2306                             /* Don't send out input port on same VLAN. */
2307                             continue;
2308                         }
2309                         dst_set_add(set, &dst);
2310                     }
2311                 }
2312             }
2313         }
2314         mirrors &= mirrors - 1;
2315     }
2316
2317     partition_dsts(set, flow_vlan);
2318 }
2319
2320 static void OVS_UNUSED
2321 print_dsts(const struct dst_set *set)
2322 {
2323     size_t i;
2324
2325     for (i = 0; i < set->n; i++) {
2326         const struct dst *dst = &set->dsts[i];
2327
2328         printf(">p%"PRIu16, dst->dp_ifidx);
2329         if (dst->vlan != OFP_VLAN_NONE) {
2330             printf("v%"PRIu16, dst->vlan);
2331         }
2332     }
2333 }
2334
2335 static void
2336 compose_actions(struct bridge *br, const struct flow *flow, uint16_t vlan,
2337                 const struct port *in_port, const struct port *out_port,
2338                 tag_type *tags, struct ofpbuf *actions,
2339                 uint16_t *nf_output_iface)
2340 {
2341     struct dst_set set;
2342     uint16_t cur_vlan;
2343     size_t i;
2344
2345     dst_set_init(&set);
2346     compose_dsts(br, flow, vlan, in_port, out_port, &set, tags,
2347                  nf_output_iface);
2348
2349     cur_vlan = vlan_tci_to_vid(flow->vlan_tci);
2350     if (cur_vlan == 0) {
2351         cur_vlan = OFP_VLAN_NONE;
2352     }
2353     for (i = 0; i < set.n; i++) {
2354         const struct dst *dst = &set.dsts[i];
2355         if (dst->vlan != cur_vlan) {
2356             if (dst->vlan == OFP_VLAN_NONE) {
2357                 nl_msg_put_flag(actions, ODP_ACTION_ATTR_STRIP_VLAN);
2358             } else {
2359                 ovs_be16 tci;
2360                 tci = htons(dst->vlan & VLAN_VID_MASK);
2361                 tci |= flow->vlan_tci & htons(VLAN_PCP_MASK);
2362                 nl_msg_put_be16(actions, ODP_ACTION_ATTR_SET_DL_TCI, tci);
2363             }
2364             cur_vlan = dst->vlan;
2365         }
2366         nl_msg_put_u32(actions, ODP_ACTION_ATTR_OUTPUT, dst->dp_ifidx);
2367     }
2368     dst_set_free(&set);
2369 }
2370
2371 /* Returns the effective vlan of a packet, taking into account both the
2372  * 802.1Q header and implicitly tagged ports.  A value of 0 indicates that
2373  * the packet is untagged and -1 indicates it has an invalid header and
2374  * should be dropped. */
2375 static int flow_get_vlan(struct bridge *br, const struct flow *flow,
2376                          struct port *in_port, bool have_packet)
2377 {
2378     int vlan = vlan_tci_to_vid(flow->vlan_tci);
2379     if (in_port->vlan >= 0) {
2380         if (vlan) {
2381             if (have_packet) {
2382                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2383                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
2384                              "packet received on port %s configured with "
2385                              "implicit VLAN %"PRIu16,
2386                              br->name, vlan, in_port->name, in_port->vlan);
2387             }
2388             return -1;
2389         }
2390         vlan = in_port->vlan;
2391     } else {
2392         if (!port_includes_vlan(in_port, vlan)) {
2393             if (have_packet) {
2394                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2395                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
2396                              "packet received on port %s not configured for "
2397                              "trunking VLAN %d",
2398                              br->name, vlan, in_port->name, vlan);
2399             }
2400             return -1;
2401         }
2402     }
2403
2404     return vlan;
2405 }
2406
2407 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
2408  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
2409  * indicate this; newer upstream kernels use gratuitous ARP requests. */
2410 static bool
2411 is_gratuitous_arp(const struct flow *flow)
2412 {
2413     return (flow->dl_type == htons(ETH_TYPE_ARP)
2414             && eth_addr_is_broadcast(flow->dl_dst)
2415             && (flow->nw_proto == ARP_OP_REPLY
2416                 || (flow->nw_proto == ARP_OP_REQUEST
2417                     && flow->nw_src == flow->nw_dst)));
2418 }
2419
2420 static void
2421 update_learning_table(struct bridge *br, const struct flow *flow, int vlan,
2422                       struct port *in_port)
2423 {
2424     struct mac_entry *mac;
2425
2426     if (!mac_learning_may_learn(br->ml, flow->dl_src, vlan)) {
2427         return;
2428     }
2429
2430     mac = mac_learning_insert(br->ml, flow->dl_src, vlan);
2431     if (is_gratuitous_arp(flow)) {
2432         /* We don't want to learn from gratuitous ARP packets that are
2433          * reflected back over bond slaves so we lock the learning table. */
2434         if (in_port->n_ifaces == 1) {
2435             mac_entry_set_grat_arp_lock(mac);
2436         } else if (mac_entry_is_grat_arp_locked(mac)) {
2437             return;
2438         }
2439     }
2440
2441     if (mac_entry_is_new(mac) || mac->port.p != in_port) {
2442         /* The log messages here could actually be useful in debugging,
2443          * so keep the rate limit relatively high. */
2444         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
2445         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
2446                     "on port %s in VLAN %d",
2447                     br->name, ETH_ADDR_ARGS(flow->dl_src),
2448                     in_port->name, vlan);
2449
2450         mac->port.p = in_port;
2451         ofproto_revalidate(br->ofproto, mac_learning_changed(br->ml, mac));
2452     }
2453 }
2454
2455 /* Determines whether packets in 'flow' within 'br' should be forwarded or
2456  * dropped.  Returns true if they may be forwarded, false if they should be
2457  * dropped.
2458  *
2459  * If 'have_packet' is true, it indicates that the caller is processing a
2460  * received packet.  If 'have_packet' is false, then the caller is just
2461  * revalidating an existing flow because configuration has changed.  Either
2462  * way, 'have_packet' only affects logging (there is no point in logging errors
2463  * during revalidation).
2464  *
2465  * Sets '*in_portp' to the input port.  This will be a null pointer if
2466  * flow->in_port does not designate a known input port (in which case
2467  * is_admissible() returns false).
2468  *
2469  * When returning true, sets '*vlanp' to the effective VLAN of the input
2470  * packet, as returned by flow_get_vlan().
2471  *
2472  * May also add tags to '*tags', although the current implementation only does
2473  * so in one special case.
2474  */
2475 static bool
2476 is_admissible(struct bridge *br, const struct flow *flow, bool have_packet,
2477               tag_type *tags, int *vlanp, struct port **in_portp)
2478 {
2479     struct iface *in_iface;
2480     struct port *in_port;
2481     int vlan;
2482
2483     /* Find the interface and port structure for the received packet. */
2484     in_iface = iface_from_dp_ifidx(br, flow->in_port);
2485     if (!in_iface) {
2486         /* No interface?  Something fishy... */
2487         if (have_packet) {
2488             /* Odd.  A few possible reasons here:
2489              *
2490              * - We deleted an interface but there are still a few packets
2491              *   queued up from it.
2492              *
2493              * - Someone externally added an interface (e.g. with "ovs-dpctl
2494              *   add-if") that we don't know about.
2495              *
2496              * - Packet arrived on the local port but the local port is not
2497              *   one of our bridge ports.
2498              */
2499             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2500
2501             VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
2502                          "interface %"PRIu16, br->name, flow->in_port);
2503         }
2504
2505         *in_portp = NULL;
2506         return false;
2507     }
2508     *in_portp = in_port = in_iface->port;
2509     *vlanp = vlan = flow_get_vlan(br, flow, in_port, have_packet);
2510     if (vlan < 0) {
2511         return false;
2512     }
2513
2514     /* Drop frames for reserved multicast addresses. */
2515     if (eth_addr_is_reserved(flow->dl_dst)) {
2516         return false;
2517     }
2518
2519     /* Drop frames on ports reserved for mirroring. */
2520     if (in_port->is_mirror_output_port) {
2521         if (have_packet) {
2522             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2523             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
2524                          "%s, which is reserved exclusively for mirroring",
2525                          br->name, in_port->name);
2526         }
2527         return false;
2528     }
2529
2530     if (in_port->bond) {
2531         struct mac_entry *mac;
2532
2533         switch (bond_check_admissibility(in_port->bond, in_iface,
2534                                          flow->dl_dst, tags)) {
2535         case BV_ACCEPT:
2536             break;
2537
2538         case BV_DROP:
2539             return false;
2540
2541         case BV_DROP_IF_MOVED:
2542             mac = mac_learning_lookup(br->ml, flow->dl_src, vlan, NULL);
2543             if (mac && mac->port.p != in_port &&
2544                 (!is_gratuitous_arp(flow)
2545                  || mac_entry_is_grat_arp_locked(mac))) {
2546                 return false;
2547             }
2548             break;
2549         }
2550     }
2551
2552     return true;
2553 }
2554
2555 /* If the composed actions may be applied to any packet in the given 'flow',
2556  * returns true.  Otherwise, the actions should only be applied to 'packet', or
2557  * not at all, if 'packet' was NULL. */
2558 static bool
2559 process_flow(struct bridge *br, const struct flow *flow,
2560              const struct ofpbuf *packet, struct ofpbuf *actions,
2561              tag_type *tags, uint16_t *nf_output_iface)
2562 {
2563     struct port *in_port;
2564     struct port *out_port;
2565     struct mac_entry *mac;
2566     int vlan;
2567
2568     /* Check whether we should drop packets in this flow. */
2569     if (!is_admissible(br, flow, packet != NULL, tags, &vlan, &in_port)) {
2570         out_port = NULL;
2571         goto done;
2572     }
2573
2574     /* Learn source MAC (but don't try to learn from revalidation). */
2575     if (packet) {
2576         update_learning_table(br, flow, vlan, in_port);
2577     }
2578
2579     /* Determine output port. */
2580     mac = mac_learning_lookup(br->ml, flow->dl_dst, vlan, tags);
2581     if (mac) {
2582         out_port = mac->port.p;
2583     } else if (!packet && !eth_addr_is_multicast(flow->dl_dst)) {
2584         /* If we are revalidating but don't have a learning entry then
2585          * eject the flow.  Installing a flow that floods packets opens
2586          * up a window of time where we could learn from a packet reflected
2587          * on a bond and blackhole packets before the learning table is
2588          * updated to reflect the correct port. */
2589         return false;
2590     } else {
2591         out_port = FLOOD_PORT;
2592     }
2593
2594     /* Don't send packets out their input ports. */
2595     if (in_port == out_port) {
2596         out_port = NULL;
2597     }
2598
2599 done:
2600     if (in_port) {
2601         compose_actions(br, flow, vlan, in_port, out_port, tags, actions,
2602                         nf_output_iface);
2603     }
2604
2605     return true;
2606 }
2607
2608 static bool
2609 bridge_normal_ofhook_cb(const struct flow *flow, const struct ofpbuf *packet,
2610                         struct ofpbuf *actions, tag_type *tags,
2611                         uint16_t *nf_output_iface, void *br_)
2612 {
2613     struct bridge *br = br_;
2614
2615     COVERAGE_INC(bridge_process_flow);
2616     return process_flow(br, flow, packet, actions, tags, nf_output_iface);
2617 }
2618
2619 static bool
2620 bridge_special_ofhook_cb(const struct flow *flow,
2621                          const struct ofpbuf *packet, void *br_)
2622 {
2623     struct iface *iface;
2624     struct bridge *br = br_;
2625
2626     iface = iface_from_dp_ifidx(br, flow->in_port);
2627
2628     if (flow->dl_type == htons(ETH_TYPE_LACP)) {
2629         if (iface && iface->port->bond && packet) {
2630             bond_process_lacp(iface->port->bond, iface, packet);
2631         }
2632         return false;
2633     }
2634
2635     return true;
2636 }
2637
2638 static void
2639 bridge_account_flow_ofhook_cb(const struct flow *flow, tag_type tags,
2640                               const struct nlattr *actions,
2641                               size_t actions_len,
2642                               uint64_t n_bytes, void *br_)
2643 {
2644     struct bridge *br = br_;
2645     const struct nlattr *a;
2646     struct port *in_port;
2647     tag_type dummy = 0;
2648     unsigned int left;
2649     int vlan;
2650
2651     /* Feed information from the active flows back into the learning table to
2652      * ensure that table is always in sync with what is actually flowing
2653      * through the datapath.
2654      *
2655      * We test that 'tags' is nonzero to ensure that only flows that include an
2656      * OFPP_NORMAL action are used for learning.  This works because
2657      * bridge_normal_ofhook_cb() always sets a nonzero tag value. */
2658     if (tags && is_admissible(br, flow, false, &dummy, &vlan, &in_port)) {
2659         update_learning_table(br, flow, vlan, in_port);
2660     }
2661
2662     /* Account for bond slave utilization. */
2663     if (!br->has_bonded_ports) {
2664         return;
2665     }
2666     NL_ATTR_FOR_EACH_UNSAFE (a, left, actions, actions_len) {
2667         if (nl_attr_type(a) == ODP_ACTION_ATTR_OUTPUT) {
2668             struct port *out_port = port_from_dp_ifidx(br, nl_attr_get_u32(a));
2669             if (out_port && out_port->bond) {
2670                 uint16_t vlan = (flow->vlan_tci
2671                                  ? vlan_tci_to_vid(flow->vlan_tci)
2672                                  : OFP_VLAN_NONE);
2673                 bond_account(out_port->bond, flow, vlan, n_bytes);
2674             }
2675         }
2676     }
2677 }
2678
2679 static void
2680 bridge_account_checkpoint_ofhook_cb(void *br_)
2681 {
2682     struct bridge *br = br_;
2683     struct port *port;
2684
2685     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2686         if (port->bond) {
2687             bond_rebalance(port->bond,
2688                            ofproto_get_revalidate_set(br->ofproto));
2689         }
2690     }
2691 }
2692
2693 static struct ofhooks bridge_ofhooks = {
2694     bridge_normal_ofhook_cb,
2695     bridge_special_ofhook_cb,
2696     bridge_account_flow_ofhook_cb,
2697     bridge_account_checkpoint_ofhook_cb,
2698 };
2699 \f
2700 /* Port functions. */
2701
2702 static void
2703 port_run(struct port *port)
2704 {
2705     if (port->bond) {
2706         bond_run(port->bond,
2707                  ofproto_get_revalidate_set(port->bridge->ofproto));
2708         if (bond_should_send_learning_packets(port->bond)) {
2709             port_send_learning_packets(port);
2710         }
2711     }
2712 }
2713
2714 static void
2715 port_wait(struct port *port)
2716 {
2717     if (port->bond) {
2718         bond_wait(port->bond);
2719     }
2720 }
2721
2722 static struct port *
2723 port_create(struct bridge *br, const char *name)
2724 {
2725     struct port *port;
2726
2727     port = xzalloc(sizeof *port);
2728     port->bridge = br;
2729     port->vlan = -1;
2730     port->trunks = NULL;
2731     port->name = xstrdup(name);
2732     list_init(&port->ifaces);
2733
2734     hmap_insert(&br->ports, &port->hmap_node, hash_string(port->name, 0));
2735
2736     VLOG_INFO("created port %s on bridge %s", port->name, br->name);
2737     bridge_flush(br);
2738
2739     return port;
2740 }
2741
2742 static const char *
2743 get_port_other_config(const struct ovsrec_port *port, const char *key,
2744                       const char *default_value)
2745 {
2746     const char *value;
2747
2748     value = get_ovsrec_key_value(&port->header_, &ovsrec_port_col_other_config,
2749                                  key);
2750     return value ? value : default_value;
2751 }
2752
2753 static const char *
2754 get_interface_other_config(const struct ovsrec_interface *iface,
2755                            const char *key, const char *default_value)
2756 {
2757     const char *value;
2758
2759     value = get_ovsrec_key_value(&iface->header_,
2760                                  &ovsrec_interface_col_other_config, key);
2761     return value ? value : default_value;
2762 }
2763
2764 static void
2765 port_del_ifaces(struct port *port, const struct ovsrec_port *cfg)
2766 {
2767     struct iface *iface, *next;
2768     struct sset new_ifaces;
2769     size_t i;
2770
2771     /* Collect list of new interfaces. */
2772     sset_init(&new_ifaces);
2773     for (i = 0; i < cfg->n_interfaces; i++) {
2774         const char *name = cfg->interfaces[i]->name;
2775         sset_add(&new_ifaces, name);
2776     }
2777
2778     /* Get rid of deleted interfaces. */
2779     LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
2780         if (!sset_contains(&new_ifaces, iface->name)) {
2781             iface_destroy(iface);
2782         }
2783     }
2784
2785     sset_destroy(&new_ifaces);
2786 }
2787
2788 /* Expires all MAC learning entries associated with 'port' and forces ofproto
2789  * to revalidate every flow. */
2790 static void
2791 port_flush_macs(struct port *port)
2792 {
2793     struct bridge *br = port->bridge;
2794     struct mac_learning *ml = br->ml;
2795     struct mac_entry *mac, *next_mac;
2796
2797     bridge_flush(br);
2798     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
2799         if (mac->port.p == port) {
2800             mac_learning_expire(ml, mac);
2801         }
2802     }
2803 }
2804
2805 static void
2806 port_reconfigure(struct port *port, const struct ovsrec_port *cfg)
2807 {
2808     struct sset new_ifaces;
2809     bool need_flush = false;
2810     unsigned long *trunks;
2811     int vlan;
2812     size_t i;
2813
2814     port->cfg = cfg;
2815
2816
2817     /* Add new interfaces and update 'cfg' member of existing ones. */
2818     sset_init(&new_ifaces);
2819     for (i = 0; i < cfg->n_interfaces; i++) {
2820         const struct ovsrec_interface *if_cfg = cfg->interfaces[i];
2821         struct iface *iface;
2822
2823         if (!sset_add(&new_ifaces, if_cfg->name)) {
2824             VLOG_WARN("port %s: %s specified twice as port interface",
2825                       port->name, if_cfg->name);
2826             iface_set_ofport(if_cfg, -1);
2827             continue;
2828         }
2829
2830         iface = iface_lookup(port->bridge, if_cfg->name);
2831         if (iface) {
2832             if (iface->port != port) {
2833                 VLOG_ERR("bridge %s: %s interface is on multiple ports, "
2834                          "removing from %s",
2835                          port->bridge->name, if_cfg->name, iface->port->name);
2836                 continue;
2837             }
2838             iface->cfg = if_cfg;
2839         } else {
2840             iface = iface_create(port, if_cfg);
2841         }
2842
2843         /* Determine interface type.  The local port always has type
2844          * "internal".  Other ports take their type from the database and
2845          * default to "system" if none is specified. */
2846         iface->type = (!strcmp(if_cfg->name, port->bridge->name) ? "internal"
2847                        : if_cfg->type[0] ? if_cfg->type
2848                        : "system");
2849     }
2850     sset_destroy(&new_ifaces);
2851
2852     /* Get VLAN tag. */
2853     vlan = -1;
2854     if (cfg->tag) {
2855         if (port->n_ifaces < 2) {
2856             vlan = *cfg->tag;
2857             if (vlan >= 0 && vlan <= 4095) {
2858                 VLOG_DBG("port %s: assigning VLAN tag %d", port->name, vlan);
2859             } else {
2860                 vlan = -1;
2861             }
2862         } else {
2863             /* It's possible that bonded, VLAN-tagged ports make sense.  Maybe
2864              * they even work as-is.  But they have not been tested. */
2865             VLOG_WARN("port %s: VLAN tags not supported on bonded ports",
2866                       port->name);
2867         }
2868     }
2869     if (port->vlan != vlan) {
2870         port->vlan = vlan;
2871         need_flush = true;
2872     }
2873
2874     /* Get trunked VLANs. */
2875     trunks = NULL;
2876     if (vlan < 0 && cfg->n_trunks) {
2877         size_t n_errors;
2878
2879         trunks = bitmap_allocate(4096);
2880         n_errors = 0;
2881         for (i = 0; i < cfg->n_trunks; i++) {
2882             int trunk = cfg->trunks[i];
2883             if (trunk >= 0) {
2884                 bitmap_set1(trunks, trunk);
2885             } else {
2886                 n_errors++;
2887             }
2888         }
2889         if (n_errors) {
2890             VLOG_ERR("port %s: invalid values for %zu trunk VLANs",
2891                      port->name, cfg->n_trunks);
2892         }
2893         if (n_errors == cfg->n_trunks) {
2894             VLOG_ERR("port %s: no valid trunks, trunking all VLANs",
2895                      port->name);
2896             bitmap_free(trunks);
2897             trunks = NULL;
2898         }
2899     } else if (vlan >= 0 && cfg->n_trunks) {
2900         VLOG_ERR("port %s: ignoring trunks in favor of implicit vlan",
2901                  port->name);
2902     }
2903     if (trunks == NULL
2904         ? port->trunks != NULL
2905         : port->trunks == NULL || !bitmap_equal(trunks, port->trunks, 4096)) {
2906         need_flush = true;
2907     }
2908     bitmap_free(port->trunks);
2909     port->trunks = trunks;
2910
2911     if (need_flush) {
2912         port_flush_macs(port);
2913     }
2914 }
2915
2916 static void
2917 port_destroy(struct port *port)
2918 {
2919     if (port) {
2920         struct bridge *br = port->bridge;
2921         struct iface *iface, *next;
2922         int i;
2923
2924         for (i = 0; i < MAX_MIRRORS; i++) {
2925             struct mirror *m = br->mirrors[i];
2926             if (m && m->out_port == port) {
2927                 mirror_destroy(m);
2928             }
2929         }
2930
2931         LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
2932             iface_destroy(iface);
2933         }
2934
2935         hmap_remove(&br->ports, &port->hmap_node);
2936
2937         VLOG_INFO("destroyed port %s on bridge %s", port->name, br->name);
2938
2939         port_flush_macs(port);
2940
2941         bitmap_free(port->trunks);
2942         free(port->name);
2943         free(port);
2944     }
2945 }
2946
2947 static struct port *
2948 port_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
2949 {
2950     struct iface *iface = iface_from_dp_ifidx(br, dp_ifidx);
2951     return iface ? iface->port : NULL;
2952 }
2953
2954 static struct port *
2955 port_lookup(const struct bridge *br, const char *name)
2956 {
2957     struct port *port;
2958
2959     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_string(name, 0),
2960                              &br->ports) {
2961         if (!strcmp(port->name, name)) {
2962             return port;
2963         }
2964     }
2965     return NULL;
2966 }
2967
2968 static bool
2969 enable_lacp(struct port *port, bool *activep)
2970 {
2971     if (!port->cfg->lacp) {
2972         /* XXX when LACP implementation has been sufficiently tested, enable by
2973          * default and make active on bonded ports. */
2974         return false;
2975     } else if (!strcmp(port->cfg->lacp, "off")) {
2976         return false;
2977     } else if (!strcmp(port->cfg->lacp, "active")) {
2978         *activep = true;
2979         return true;
2980     } else if (!strcmp(port->cfg->lacp, "passive")) {
2981         *activep = false;
2982         return true;
2983     } else {
2984         VLOG_WARN("port %s: unknown LACP mode %s",
2985                   port->name, port->cfg->lacp);
2986         return false;
2987     }
2988 }
2989
2990 static struct lacp_settings *
2991 port_reconfigure_bond_lacp(struct port *port, struct lacp_settings *s)
2992 {
2993     if (!enable_lacp(port, &s->active)) {
2994         return NULL;
2995     }
2996
2997     s->name = port->name;
2998     memcpy(s->id, port->bridge->ea, ETH_ADDR_LEN);
2999     s->priority = atoi(get_port_other_config(port->cfg, "lacp-system-priority",
3000                                              "0"));
3001     s->fast = !strcmp(get_port_other_config(port->cfg, "lacp-time", "slow"),
3002                       "fast");
3003
3004     if (s->priority <= 0 || s->priority > UINT16_MAX) {
3005         /* Prefer bondable links if unspecified. */
3006         s->priority = UINT16_MAX - (port->n_ifaces > 1);
3007     }
3008     return s;
3009 }
3010
3011 static void
3012 iface_reconfigure_bond(struct iface *iface)
3013 {
3014     struct lacp_slave_settings s;
3015     int priority;
3016
3017     s.name = iface->name;
3018     s.id = iface->dp_ifidx;
3019     priority = atoi(get_interface_other_config(
3020                         iface->cfg, "lacp-port-priority", "0"));
3021     s.priority = (priority >= 0 && priority <= UINT16_MAX
3022                   ? priority : UINT16_MAX);
3023     bond_slave_register(iface->port->bond, iface, iface->netdev, &s);
3024 }
3025
3026 static void
3027 port_reconfigure_bond(struct port *port)
3028 {
3029     struct lacp_settings lacp_settings;
3030     struct bond_settings s;
3031     const char *detect_s;
3032     struct iface *iface;
3033
3034     if (port->n_ifaces < 2) {
3035         /* Not a bonded port. */
3036         bond_destroy(port->bond);
3037         port->bond = NULL;
3038         return;
3039     }
3040
3041     port->bridge->has_bonded_ports = true;
3042
3043     s.name = port->name;
3044     s.balance = BM_SLB;
3045     if (port->cfg->bond_mode
3046         && !bond_mode_from_string(&s.balance, port->cfg->bond_mode)) {
3047         VLOG_WARN("port %s: unknown bond_mode %s, defaulting to %s",
3048                   port->name, port->cfg->bond_mode,
3049                   bond_mode_to_string(s.balance));
3050     }
3051
3052     s.detect = BLSM_CARRIER;
3053     detect_s = get_port_other_config(port->cfg, "bond-detect-mode", NULL);
3054     if (detect_s && !bond_detect_mode_from_string(&s.detect, detect_s)) {
3055         VLOG_WARN("port %s: unsupported bond-detect-mode %s, "
3056                   "defaulting to %s",
3057                   port->name, detect_s, bond_detect_mode_to_string(s.detect));
3058     }
3059
3060     s.miimon_interval = atoi(
3061         get_port_other_config(port->cfg, "bond-miimon-interval", "200"));
3062     if (s.miimon_interval < 100) {
3063         s.miimon_interval = 100;
3064     }
3065
3066     s.up_delay = MAX(0, port->cfg->bond_updelay);
3067     s.down_delay = MAX(0, port->cfg->bond_downdelay);
3068     s.rebalance_interval = atoi(
3069         get_port_other_config(port->cfg, "bond-rebalance-interval", "10000"));
3070     if (s.rebalance_interval < 1000) {
3071         s.rebalance_interval = 1000;
3072     }
3073
3074     s.fake_iface = port->cfg->bond_fake_iface;
3075     s.lacp = port_reconfigure_bond_lacp(port, &lacp_settings);
3076
3077     if (!port->bond) {
3078         port->bond = bond_create(&s);
3079     } else {
3080         bond_reconfigure(port->bond, &s);
3081     }
3082
3083     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
3084         iface_reconfigure_bond(iface);
3085     }
3086 }
3087
3088 static void
3089 port_send_learning_packets(struct port *port)
3090 {
3091     struct bridge *br = port->bridge;
3092     int error, n_packets, n_errors;
3093     struct mac_entry *e;
3094
3095     error = n_packets = n_errors = 0;
3096     LIST_FOR_EACH (e, lru_node, &br->ml->lrus) {
3097         if (e->port.p != port) {
3098             int ret = bond_send_learning_packet(port->bond, e->mac, e->vlan);
3099             if (ret) {
3100                 error = ret;
3101                 n_errors++;
3102             }
3103             n_packets++;
3104         }
3105     }
3106
3107     if (n_errors) {
3108         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3109         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
3110                      "packets, last error was: %s",
3111                      port->name, n_errors, n_packets, strerror(error));
3112     } else {
3113         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
3114                  port->name, n_packets);
3115     }
3116 }
3117 \f
3118 /* Interface functions. */
3119
3120 static struct iface *
3121 iface_create(struct port *port, const struct ovsrec_interface *if_cfg)
3122 {
3123     struct bridge *br = port->bridge;
3124     struct iface *iface;
3125     char *name = if_cfg->name;
3126
3127     iface = xzalloc(sizeof *iface);
3128     iface->port = port;
3129     iface->name = xstrdup(name);
3130     iface->dp_ifidx = -1;
3131     iface->tag = tag_create_random();
3132     iface->netdev = NULL;
3133     iface->cfg = if_cfg;
3134
3135     shash_add_assert(&br->iface_by_name, iface->name, iface);
3136
3137     list_push_back(&port->ifaces, &iface->port_elem);
3138     port->n_ifaces++;
3139
3140     VLOG_DBG("attached network device %s to port %s", iface->name, port->name);
3141
3142     bridge_flush(br);
3143
3144     return iface;
3145 }
3146
3147 static void
3148 iface_destroy(struct iface *iface)
3149 {
3150     if (iface) {
3151         struct port *port = iface->port;
3152         struct bridge *br = port->bridge;
3153
3154         if (port->bond) {
3155             bond_slave_unregister(port->bond, iface);
3156         }
3157
3158         shash_find_and_delete_assert(&br->iface_by_name, iface->name);
3159
3160         if (iface->dp_ifidx >= 0) {
3161             hmap_remove(&br->ifaces, &iface->dp_ifidx_node);
3162         }
3163
3164         list_remove(&iface->port_elem);
3165         port->n_ifaces--;
3166
3167         netdev_close(iface->netdev);
3168
3169         free(iface->name);
3170         free(iface);
3171
3172         bridge_flush(port->bridge);
3173     }
3174 }
3175
3176 static struct iface *
3177 iface_lookup(const struct bridge *br, const char *name)
3178 {
3179     return shash_find_data(&br->iface_by_name, name);
3180 }
3181
3182 static struct iface *
3183 iface_find(const char *name)
3184 {
3185     const struct bridge *br;
3186
3187     LIST_FOR_EACH (br, node, &all_bridges) {
3188         struct iface *iface = iface_lookup(br, name);
3189
3190         if (iface) {
3191             return iface;
3192         }
3193     }
3194     return NULL;
3195 }
3196
3197 static struct iface *
3198 iface_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
3199 {
3200     struct iface *iface;
3201
3202     HMAP_FOR_EACH_IN_BUCKET (iface, dp_ifidx_node,
3203                              hash_int(dp_ifidx, 0), &br->ifaces) {
3204         if (iface->dp_ifidx == dp_ifidx) {
3205             return iface;
3206         }
3207     }
3208     return NULL;
3209 }
3210
3211 /* Set Ethernet address of 'iface', if one is specified in the configuration
3212  * file. */
3213 static void
3214 iface_set_mac(struct iface *iface)
3215 {
3216     uint8_t ea[ETH_ADDR_LEN];
3217
3218     if (iface->cfg->mac && eth_addr_from_string(iface->cfg->mac, ea)) {
3219         if (eth_addr_is_multicast(ea)) {
3220             VLOG_ERR("interface %s: cannot set MAC to multicast address",
3221                      iface->name);
3222         } else if (iface->dp_ifidx == ODPP_LOCAL) {
3223             VLOG_ERR("ignoring iface.%s.mac; use bridge.%s.mac instead",
3224                      iface->name, iface->name);
3225         } else {
3226             int error = netdev_set_etheraddr(iface->netdev, ea);
3227             if (error) {
3228                 VLOG_ERR("interface %s: setting MAC failed (%s)",
3229                          iface->name, strerror(error));
3230             }
3231         }
3232     }
3233 }
3234
3235 /* Sets the ofport column of 'if_cfg' to 'ofport'. */
3236 static void
3237 iface_set_ofport(const struct ovsrec_interface *if_cfg, int64_t ofport)
3238 {
3239     if (if_cfg) {
3240         ovsrec_interface_set_ofport(if_cfg, &ofport, 1);
3241     }
3242 }
3243
3244 /* Adds the 'n' key-value pairs in 'keys' in 'values' to 'shash'.
3245  *
3246  * The value strings in '*shash' are taken directly from values[], not copied,
3247  * so the caller should not modify or free them. */
3248 static void
3249 shash_from_ovs_idl_map(char **keys, char **values, size_t n,
3250                        struct shash *shash)
3251 {
3252     size_t i;
3253
3254     shash_init(shash);
3255     for (i = 0; i < n; i++) {
3256         shash_add(shash, keys[i], values[i]);
3257     }
3258 }
3259
3260 /* Creates 'keys' and 'values' arrays from 'shash'.
3261  *
3262  * Sets 'keys' and 'values' to heap allocated arrays representing the key-value
3263  * pairs in 'shash'.  The caller takes ownership of 'keys' and 'values'.  They
3264  * are populated with with strings taken directly from 'shash' and thus have
3265  * the same ownership of the key-value pairs in shash.
3266  */
3267 static void
3268 shash_to_ovs_idl_map(struct shash *shash,
3269                      char ***keys, char ***values, size_t *n)
3270 {
3271     size_t i, count;
3272     char **k, **v;
3273     struct shash_node *sn;
3274
3275     count = shash_count(shash);
3276
3277     k = xmalloc(count * sizeof *k);
3278     v = xmalloc(count * sizeof *v);
3279
3280     i = 0;
3281     SHASH_FOR_EACH(sn, shash) {
3282         k[i] = sn->name;
3283         v[i] = sn->data;
3284         i++;
3285     }
3286
3287     *n      = count;
3288     *keys   = k;
3289     *values = v;
3290 }
3291
3292 struct iface_delete_queues_cbdata {
3293     struct netdev *netdev;
3294     const struct ovsdb_datum *queues;
3295 };
3296
3297 static bool
3298 queue_ids_include(const struct ovsdb_datum *queues, int64_t target)
3299 {
3300     union ovsdb_atom atom;
3301
3302     atom.integer = target;
3303     return ovsdb_datum_find_key(queues, &atom, OVSDB_TYPE_INTEGER) != UINT_MAX;
3304 }
3305
3306 static void
3307 iface_delete_queues(unsigned int queue_id,
3308                     const struct shash *details OVS_UNUSED, void *cbdata_)
3309 {
3310     struct iface_delete_queues_cbdata *cbdata = cbdata_;
3311
3312     if (!queue_ids_include(cbdata->queues, queue_id)) {
3313         netdev_delete_queue(cbdata->netdev, queue_id);
3314     }
3315 }
3316
3317 static void
3318 iface_update_qos(struct iface *iface, const struct ovsrec_qos *qos)
3319 {
3320     if (!qos || qos->type[0] == '\0') {
3321         netdev_set_qos(iface->netdev, NULL, NULL);
3322     } else {
3323         struct iface_delete_queues_cbdata cbdata;
3324         struct shash details;
3325         size_t i;
3326
3327         /* Configure top-level Qos for 'iface'. */
3328         shash_from_ovs_idl_map(qos->key_other_config, qos->value_other_config,
3329                                qos->n_other_config, &details);
3330         netdev_set_qos(iface->netdev, qos->type, &details);
3331         shash_destroy(&details);
3332
3333         /* Deconfigure queues that were deleted. */
3334         cbdata.netdev = iface->netdev;
3335         cbdata.queues = ovsrec_qos_get_queues(qos, OVSDB_TYPE_INTEGER,
3336                                               OVSDB_TYPE_UUID);
3337         netdev_dump_queues(iface->netdev, iface_delete_queues, &cbdata);
3338
3339         /* Configure queues for 'iface'. */
3340         for (i = 0; i < qos->n_queues; i++) {
3341             const struct ovsrec_queue *queue = qos->value_queues[i];
3342             unsigned int queue_id = qos->key_queues[i];
3343
3344             shash_from_ovs_idl_map(queue->key_other_config,
3345                                    queue->value_other_config,
3346                                    queue->n_other_config, &details);
3347             netdev_set_queue(iface->netdev, queue_id, &details);
3348             shash_destroy(&details);
3349         }
3350     }
3351 }
3352
3353 static void
3354 iface_update_cfm(struct iface *iface)
3355 {
3356     size_t i;
3357     struct cfm cfm;
3358     uint16_t *remote_mps;
3359     struct ovsrec_monitor *mon;
3360     uint8_t maid[CCM_MAID_LEN];
3361
3362     mon = iface->cfg->monitor;
3363
3364     if (!mon) {
3365         ofproto_iface_clear_cfm(iface->port->bridge->ofproto, iface->dp_ifidx);
3366         return;
3367     }
3368
3369     if (!cfm_generate_maid(mon->md_name, mon->ma_name, maid)) {
3370         VLOG_WARN("interface %s: Failed to generate MAID.", iface->name);
3371         return;
3372     }
3373
3374     cfm.mpid     = mon->mpid;
3375     cfm.interval = mon->interval ? *mon->interval : 1000;
3376
3377     memcpy(cfm.maid, maid, sizeof cfm.maid);
3378
3379     remote_mps = xzalloc(mon->n_remote_mps * sizeof *remote_mps);
3380     for(i = 0; i < mon->n_remote_mps; i++) {
3381         remote_mps[i] = mon->remote_mps[i]->mpid;
3382     }
3383
3384     ofproto_iface_set_cfm(iface->port->bridge->ofproto, iface->dp_ifidx,
3385                           &cfm, remote_mps, mon->n_remote_mps);
3386     free(remote_mps);
3387 }
3388
3389 /* Read carrier or miimon status directly from 'iface''s netdev, according to
3390  * how 'iface''s port is configured.
3391  *
3392  * Returns true if 'iface' is up, false otherwise. */
3393 static bool
3394 iface_get_carrier(const struct iface *iface)
3395 {
3396     /* XXX */
3397     return netdev_get_carrier(iface->netdev);
3398 }
3399 \f
3400 /* Port mirroring. */
3401
3402 static struct mirror *
3403 mirror_find_by_uuid(struct bridge *br, const struct uuid *uuid)
3404 {
3405     int i;
3406
3407     for (i = 0; i < MAX_MIRRORS; i++) {
3408         struct mirror *m = br->mirrors[i];
3409         if (m && uuid_equals(uuid, &m->uuid)) {
3410             return m;
3411         }
3412     }
3413     return NULL;
3414 }
3415
3416 static void
3417 mirror_reconfigure(struct bridge *br)
3418 {
3419     unsigned long *rspan_vlans;
3420     struct port *port;
3421     int i;
3422
3423     /* Get rid of deleted mirrors. */
3424     for (i = 0; i < MAX_MIRRORS; i++) {
3425         struct mirror *m = br->mirrors[i];
3426         if (m) {
3427             const struct ovsdb_datum *mc;
3428             union ovsdb_atom atom;
3429
3430             mc = ovsrec_bridge_get_mirrors(br->cfg, OVSDB_TYPE_UUID);
3431             atom.uuid = br->mirrors[i]->uuid;
3432             if (ovsdb_datum_find_key(mc, &atom, OVSDB_TYPE_UUID) == UINT_MAX) {
3433                 mirror_destroy(m);
3434             }
3435         }
3436     }
3437
3438     /* Add new mirrors and reconfigure existing ones. */
3439     for (i = 0; i < br->cfg->n_mirrors; i++) {
3440         struct ovsrec_mirror *cfg = br->cfg->mirrors[i];
3441         struct mirror *m = mirror_find_by_uuid(br, &cfg->header_.uuid);
3442         if (m) {
3443             mirror_reconfigure_one(m, cfg);
3444         } else {
3445             mirror_create(br, cfg);
3446         }
3447     }
3448
3449     /* Update port reserved status. */
3450     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
3451         port->is_mirror_output_port = false;
3452     }
3453     for (i = 0; i < MAX_MIRRORS; i++) {
3454         struct mirror *m = br->mirrors[i];
3455         if (m && m->out_port) {
3456             m->out_port->is_mirror_output_port = true;
3457         }
3458     }
3459
3460     /* Update flooded vlans (for RSPAN). */
3461     rspan_vlans = NULL;
3462     if (br->cfg->n_flood_vlans) {
3463         rspan_vlans = bitmap_allocate(4096);
3464
3465         for (i = 0; i < br->cfg->n_flood_vlans; i++) {
3466             int64_t vlan = br->cfg->flood_vlans[i];
3467             if (vlan >= 0 && vlan < 4096) {
3468                 bitmap_set1(rspan_vlans, vlan);
3469                 VLOG_INFO("bridge %s: disabling learning on vlan %"PRId64,
3470                           br->name, vlan);
3471             } else {
3472                 VLOG_ERR("bridge %s: invalid value %"PRId64 "for flood VLAN",
3473                          br->name, vlan);
3474             }
3475         }
3476     }
3477     if (mac_learning_set_flood_vlans(br->ml, rspan_vlans)) {
3478         bridge_flush(br);
3479         mac_learning_flush(br->ml);
3480     }
3481 }
3482
3483 static void
3484 mirror_create(struct bridge *br, struct ovsrec_mirror *cfg)
3485 {
3486     struct mirror *m;
3487     size_t i;
3488
3489     for (i = 0; ; i++) {
3490         if (i >= MAX_MIRRORS) {
3491             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
3492                       "cannot create %s", br->name, MAX_MIRRORS, cfg->name);
3493             return;
3494         }
3495         if (!br->mirrors[i]) {
3496             break;
3497         }
3498     }
3499
3500     VLOG_INFO("created port mirror %s on bridge %s", cfg->name, br->name);
3501     bridge_flush(br);
3502     mac_learning_flush(br->ml);
3503
3504     br->mirrors[i] = m = xzalloc(sizeof *m);
3505     m->bridge = br;
3506     m->idx = i;
3507     m->name = xstrdup(cfg->name);
3508     sset_init(&m->src_ports);
3509     sset_init(&m->dst_ports);
3510     m->vlans = NULL;
3511     m->n_vlans = 0;
3512     m->out_vlan = -1;
3513     m->out_port = NULL;
3514
3515     mirror_reconfigure_one(m, cfg);
3516 }
3517
3518 static void
3519 mirror_destroy(struct mirror *m)
3520 {
3521     if (m) {
3522         struct bridge *br = m->bridge;
3523         struct port *port;
3524
3525         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
3526             port->src_mirrors &= ~(MIRROR_MASK_C(1) << m->idx);
3527             port->dst_mirrors &= ~(MIRROR_MASK_C(1) << m->idx);
3528         }
3529
3530         sset_destroy(&m->src_ports);
3531         sset_destroy(&m->dst_ports);
3532         free(m->vlans);
3533
3534         m->bridge->mirrors[m->idx] = NULL;
3535         free(m->name);
3536         free(m);
3537
3538         bridge_flush(br);
3539         mac_learning_flush(br->ml);
3540     }
3541 }
3542
3543 static void
3544 mirror_collect_ports(struct mirror *m, struct ovsrec_port **ports, int n_ports,
3545                      struct sset *names)
3546 {
3547     size_t i;
3548
3549     for (i = 0; i < n_ports; i++) {
3550         const char *name = ports[i]->name;
3551         if (port_lookup(m->bridge, name)) {
3552             sset_add(names, name);
3553         } else {
3554             VLOG_WARN("bridge %s: mirror %s cannot match on nonexistent "
3555                       "port %s", m->bridge->name, m->name, name);
3556         }
3557     }
3558 }
3559
3560 static size_t
3561 mirror_collect_vlans(struct mirror *m, const struct ovsrec_mirror *cfg,
3562                      int **vlans)
3563 {
3564     size_t n_vlans;
3565     size_t i;
3566
3567     *vlans = xmalloc(sizeof **vlans * cfg->n_select_vlan);
3568     n_vlans = 0;
3569     for (i = 0; i < cfg->n_select_vlan; i++) {
3570         int64_t vlan = cfg->select_vlan[i];
3571         if (vlan < 0 || vlan > 4095) {
3572             VLOG_WARN("bridge %s: mirror %s selects invalid VLAN %"PRId64,
3573                       m->bridge->name, m->name, vlan);
3574         } else {
3575             (*vlans)[n_vlans++] = vlan;
3576         }
3577     }
3578     return n_vlans;
3579 }
3580
3581 static bool
3582 vlan_is_mirrored(const struct mirror *m, int vlan)
3583 {
3584     size_t i;
3585
3586     for (i = 0; i < m->n_vlans; i++) {
3587         if (m->vlans[i] == vlan) {
3588             return true;
3589         }
3590     }
3591     return false;
3592 }
3593
3594 static bool
3595 port_trunks_any_mirrored_vlan(const struct mirror *m, const struct port *p)
3596 {
3597     size_t i;
3598
3599     for (i = 0; i < m->n_vlans; i++) {
3600         if (port_trunks_vlan(p, m->vlans[i])) {
3601             return true;
3602         }
3603     }
3604     return false;
3605 }
3606
3607 static void
3608 mirror_reconfigure_one(struct mirror *m, struct ovsrec_mirror *cfg)
3609 {
3610     struct sset src_ports, dst_ports;
3611     mirror_mask_t mirror_bit;
3612     struct port *out_port;
3613     struct port *port;
3614     int out_vlan;
3615     size_t n_vlans;
3616     int *vlans;
3617
3618     /* Set name. */
3619     if (strcmp(cfg->name, m->name)) {
3620         free(m->name);
3621         m->name = xstrdup(cfg->name);
3622     }
3623
3624     /* Get output port. */
3625     if (cfg->output_port) {
3626         out_port = port_lookup(m->bridge, cfg->output_port->name);
3627         if (!out_port) {
3628             VLOG_ERR("bridge %s: mirror %s outputs to port not on bridge",
3629                      m->bridge->name, m->name);
3630             mirror_destroy(m);
3631             return;
3632         }
3633         out_vlan = -1;
3634
3635         if (cfg->output_vlan) {
3636             VLOG_ERR("bridge %s: mirror %s specifies both output port and "
3637                      "output vlan; ignoring output vlan",
3638                      m->bridge->name, m->name);
3639         }
3640     } else if (cfg->output_vlan) {
3641         out_port = NULL;
3642         out_vlan = *cfg->output_vlan;
3643     } else {
3644         VLOG_ERR("bridge %s: mirror %s does not specify output; ignoring",
3645                  m->bridge->name, m->name);
3646         mirror_destroy(m);
3647         return;
3648     }
3649
3650     sset_init(&src_ports);
3651     sset_init(&dst_ports);
3652     if (cfg->select_all) {
3653         HMAP_FOR_EACH (port, hmap_node, &m->bridge->ports) {
3654             sset_add(&src_ports, port->name);
3655             sset_add(&dst_ports, port->name);
3656         }
3657         vlans = NULL;
3658         n_vlans = 0;
3659     } else {
3660         /* Get ports, and drop duplicates and ports that don't exist. */
3661         mirror_collect_ports(m, cfg->select_src_port, cfg->n_select_src_port,
3662                              &src_ports);
3663         mirror_collect_ports(m, cfg->select_dst_port, cfg->n_select_dst_port,
3664                              &dst_ports);
3665
3666         /* Get all the vlans, and drop duplicate and invalid vlans. */
3667         n_vlans = mirror_collect_vlans(m, cfg, &vlans);
3668     }
3669
3670     /* Update mirror data. */
3671     if (!sset_equals(&m->src_ports, &src_ports)
3672         || !sset_equals(&m->dst_ports, &dst_ports)
3673         || m->n_vlans != n_vlans
3674         || memcmp(m->vlans, vlans, sizeof *vlans * n_vlans)
3675         || m->out_port != out_port
3676         || m->out_vlan != out_vlan) {
3677         bridge_flush(m->bridge);
3678         mac_learning_flush(m->bridge->ml);
3679     }
3680     sset_swap(&m->src_ports, &src_ports);
3681     sset_swap(&m->dst_ports, &dst_ports);
3682     free(m->vlans);
3683     m->vlans = vlans;
3684     m->n_vlans = n_vlans;
3685     m->out_port = out_port;
3686     m->out_vlan = out_vlan;
3687
3688     /* Update ports. */
3689     mirror_bit = MIRROR_MASK_C(1) << m->idx;
3690     HMAP_FOR_EACH (port, hmap_node, &m->bridge->ports) {
3691         if (sset_contains(&m->src_ports, port->name)
3692             || (m->n_vlans
3693                 && (!port->vlan
3694                     ? port_trunks_any_mirrored_vlan(m, port)
3695                     : vlan_is_mirrored(m, port->vlan)))) {
3696             port->src_mirrors |= mirror_bit;
3697         } else {
3698             port->src_mirrors &= ~mirror_bit;
3699         }
3700
3701         if (sset_contains(&m->dst_ports, port->name)) {
3702             port->dst_mirrors |= mirror_bit;
3703         } else {
3704             port->dst_mirrors &= ~mirror_bit;
3705         }
3706     }
3707
3708     /* Clean up. */
3709     sset_destroy(&src_ports);
3710     sset_destroy(&dst_ports);
3711 }