cfm: Migrate cfm/show unixctl command to CFM module.
[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 <assert.h>
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <stdlib.h>
22 #include "bitmap.h"
23 #include "bond.h"
24 #include "cfm.h"
25 #include "coverage.h"
26 #include "daemon.h"
27 #include "dirs.h"
28 #include "dynamic-string.h"
29 #include "hash.h"
30 #include "hmap.h"
31 #include "jsonrpc.h"
32 #include "lacp.h"
33 #include "list.h"
34 #include "netdev.h"
35 #include "ofp-print.h"
36 #include "ofpbuf.h"
37 #include "ofproto/ofproto.h"
38 #include "poll-loop.h"
39 #include "sha1.h"
40 #include "shash.h"
41 #include "socket-util.h"
42 #include "stream-ssl.h"
43 #include "sset.h"
44 #include "system-stats.h"
45 #include "timeval.h"
46 #include "util.h"
47 #include "unixctl.h"
48 #include "vswitchd/vswitch-idl.h"
49 #include "xenserver.h"
50 #include "vlog.h"
51 #include "sflow_api.h"
52 #include "vlan-bitmap.h"
53
54 VLOG_DEFINE_THIS_MODULE(bridge);
55
56 COVERAGE_DEFINE(bridge_reconfigure);
57
58 struct iface {
59     /* These members are always valid. */
60     struct list port_elem;      /* Element in struct port's "ifaces" list. */
61     struct hmap_node name_node; /* In struct bridge's "iface_by_name" hmap. */
62     struct port *port;          /* Containing port. */
63     char *name;                 /* Host network device name. */
64     tag_type tag;               /* Tag associated with this interface. */
65
66     /* These members are valid only after bridge_reconfigure() causes them to
67      * be initialized. */
68     struct hmap_node ofp_port_node; /* In struct bridge's "ifaces" hmap. */
69     int ofp_port;               /* OpenFlow port number, -1 if unknown. */
70     struct netdev *netdev;      /* Network device. */
71     const char *type;           /* Usually same as cfg->type. */
72     const struct ovsrec_interface *cfg;
73 };
74
75 struct mirror {
76     struct uuid uuid;           /* UUID of this "mirror" record in database. */
77     struct hmap_node hmap_node; /* In struct bridge's "mirrors" hmap. */
78     struct bridge *bridge;
79     char *name;
80 };
81
82 struct port {
83     struct bridge *bridge;
84     struct hmap_node hmap_node; /* Element in struct bridge's "ports" hmap. */
85     char *name;
86
87     const struct ovsrec_port *cfg;
88
89     /* An ordinary bridge port has 1 interface.
90      * A bridge port for bonding has at least 2 interfaces. */
91     struct list ifaces;         /* List of "struct iface"s. */
92 };
93
94 struct bridge {
95     struct hmap_node node;      /* In 'all_bridges'. */
96     char *name;                 /* User-specified arbitrary name. */
97     char *type;                 /* Datapath type. */
98     uint8_t ea[ETH_ADDR_LEN];   /* Bridge Ethernet Address. */
99     uint8_t default_ea[ETH_ADDR_LEN]; /* Default MAC. */
100     const struct ovsrec_bridge *cfg;
101
102     /* OpenFlow switch processing. */
103     struct ofproto *ofproto;    /* OpenFlow switch. */
104
105     /* Bridge ports. */
106     struct hmap ports;          /* "struct port"s indexed by name. */
107     struct hmap ifaces;         /* "struct iface"s indexed by ofp_port. */
108     struct hmap iface_by_name;  /* "struct iface"s indexed by name. */
109
110     /* Port mirroring. */
111     struct hmap mirrors;        /* "struct mirror" indexed by UUID. */
112
113     /* Synthetic local port if necessary. */
114     struct ovsrec_port synth_local_port;
115     struct ovsrec_interface synth_local_iface;
116     struct ovsrec_interface *synth_local_ifacep;
117 };
118
119 /* All bridges, indexed by name. */
120 static struct hmap all_bridges = HMAP_INITIALIZER(&all_bridges);
121
122 /* OVSDB IDL used to obtain configuration. */
123 static struct ovsdb_idl *idl;
124
125 /* Each time this timer expires, the bridge fetches systems and interface
126  * statistics and pushes them into the database. */
127 #define STATS_INTERVAL (5 * 1000) /* In milliseconds. */
128 static long long int stats_timer = LLONG_MIN;
129
130 /* Stores the time after which rate limited statistics may be written to the
131  * database.  Only updated when changes to the database require rate limiting.
132  */
133 #define DB_LIMIT_INTERVAL (1 * 1000) /* In milliseconds. */
134 static long long int db_limiter = LLONG_MIN;
135
136 static void add_del_bridges(const struct ovsrec_open_vswitch *);
137 static void bridge_del_ofprotos(void);
138 static bool bridge_add_ofprotos(struct bridge *);
139 static void bridge_create(const struct ovsrec_bridge *);
140 static void bridge_destroy(struct bridge *);
141 static struct bridge *bridge_lookup(const char *name);
142 static unixctl_cb_func bridge_unixctl_dump_flows;
143 static unixctl_cb_func bridge_unixctl_reconnect;
144 static size_t bridge_get_controllers(const struct bridge *br,
145                                      struct ovsrec_controller ***controllersp);
146 static void bridge_add_del_ports(struct bridge *);
147 static void bridge_add_ofproto_ports(struct bridge *);
148 static void bridge_del_ofproto_ports(struct bridge *);
149 static void bridge_refresh_ofp_port(struct bridge *);
150 static void bridge_configure_datapath_id(struct bridge *);
151 static void bridge_configure_netflow(struct bridge *);
152 static void bridge_configure_sflow(struct bridge *, int *sflow_bridge_number);
153 static void bridge_configure_remotes(struct bridge *,
154                                      const struct sockaddr_in *managers,
155                                      size_t n_managers);
156 static void bridge_pick_local_hw_addr(struct bridge *,
157                                       uint8_t ea[ETH_ADDR_LEN],
158                                       struct iface **hw_addr_iface);
159 static uint64_t bridge_pick_datapath_id(struct bridge *,
160                                         const uint8_t bridge_ea[ETH_ADDR_LEN],
161                                         struct iface *hw_addr_iface);
162 static uint64_t dpid_from_hash(const void *, size_t nbytes);
163 static bool bridge_has_bond_fake_iface(const struct bridge *,
164                                        const char *name);
165 static bool port_is_bond_fake_iface(const struct port *);
166
167 static unixctl_cb_func qos_unixctl_show;
168
169 static struct port *port_create(struct bridge *, const struct ovsrec_port *);
170 static void port_add_ifaces(struct port *);
171 static void port_del_ifaces(struct port *);
172 static void port_destroy(struct port *);
173 static struct port *port_lookup(const struct bridge *, const char *name);
174 static void port_configure(struct port *);
175 static struct lacp_settings *port_configure_lacp(struct port *,
176                                                  struct lacp_settings *);
177 static void port_configure_bond(struct port *, struct bond_settings *,
178                                 uint32_t *bond_stable_ids);
179
180 static void bridge_configure_mirrors(struct bridge *);
181 static struct mirror *mirror_create(struct bridge *,
182                                     const struct ovsrec_mirror *);
183 static void mirror_destroy(struct mirror *);
184 static bool mirror_configure(struct mirror *, const struct ovsrec_mirror *);
185
186 static void iface_configure_lacp(struct iface *, struct lacp_slave_settings *);
187 static struct iface *iface_create(struct port *port,
188                                   const struct ovsrec_interface *if_cfg);
189 static void iface_destroy(struct iface *);
190 static struct iface *iface_lookup(const struct bridge *, const char *name);
191 static struct iface *iface_find(const char *name);
192 static struct iface *iface_from_ofp_port(const struct bridge *,
193                                          uint16_t ofp_port);
194 static void iface_set_mac(struct iface *);
195 static void iface_set_ofport(const struct ovsrec_interface *, int64_t ofport);
196 static void iface_configure_qos(struct iface *, const struct ovsrec_qos *);
197 static void iface_configure_cfm(struct iface *);
198 static bool iface_refresh_cfm_stats(struct iface *iface);
199 static bool iface_get_carrier(const struct iface *);
200 static bool iface_is_synthetic(const struct iface *);
201
202 static void shash_from_ovs_idl_map(char **keys, char **values, size_t n,
203                                    struct shash *);
204 static void shash_to_ovs_idl_map(struct shash *,
205                                  char ***keys, char ***values, size_t *n);
206 \f
207 /* Public functions. */
208
209 /* Initializes the bridge module, configuring it to obtain its configuration
210  * from an OVSDB server accessed over 'remote', which should be a string in a
211  * form acceptable to ovsdb_idl_create(). */
212 void
213 bridge_init(const char *remote)
214 {
215     /* Create connection to database. */
216     idl = ovsdb_idl_create(remote, &ovsrec_idl_class, true);
217
218     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_cur_cfg);
219     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_statistics);
220     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_external_ids);
221     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_ovs_version);
222     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_db_version);
223     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_system_type);
224     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_system_version);
225
226     ovsdb_idl_omit_alert(idl, &ovsrec_bridge_col_datapath_id);
227     ovsdb_idl_omit(idl, &ovsrec_bridge_col_external_ids);
228
229     ovsdb_idl_omit(idl, &ovsrec_port_col_external_ids);
230     ovsdb_idl_omit(idl, &ovsrec_port_col_fake_bridge);
231
232     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_admin_state);
233     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_duplex);
234     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_link_speed);
235     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_link_state);
236     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_mtu);
237     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_ofport);
238     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_statistics);
239     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_status);
240     ovsdb_idl_omit(idl, &ovsrec_interface_col_external_ids);
241
242     ovsdb_idl_omit_alert(idl, &ovsrec_controller_col_is_connected);
243     ovsdb_idl_omit_alert(idl, &ovsrec_controller_col_role);
244     ovsdb_idl_omit_alert(idl, &ovsrec_controller_col_status);
245     ovsdb_idl_omit(idl, &ovsrec_controller_col_external_ids);
246
247     ovsdb_idl_omit_alert(idl, &ovsrec_maintenance_point_col_fault);
248
249     ovsdb_idl_omit_alert(idl, &ovsrec_monitor_col_fault);
250
251     ovsdb_idl_omit(idl, &ovsrec_qos_col_external_ids);
252
253     ovsdb_idl_omit(idl, &ovsrec_queue_col_external_ids);
254
255     ovsdb_idl_omit(idl, &ovsrec_mirror_col_external_ids);
256
257     ovsdb_idl_omit(idl, &ovsrec_netflow_col_external_ids);
258
259     ovsdb_idl_omit(idl, &ovsrec_sflow_col_external_ids);
260
261     ovsdb_idl_omit(idl, &ovsrec_manager_col_external_ids);
262     ovsdb_idl_omit(idl, &ovsrec_manager_col_inactivity_probe);
263     ovsdb_idl_omit(idl, &ovsrec_manager_col_is_connected);
264     ovsdb_idl_omit(idl, &ovsrec_manager_col_max_backoff);
265     ovsdb_idl_omit(idl, &ovsrec_manager_col_status);
266
267     ovsdb_idl_omit(idl, &ovsrec_ssl_col_external_ids);
268
269     /* Register unixctl commands. */
270     unixctl_command_register("qos/show", qos_unixctl_show, NULL);
271     unixctl_command_register("bridge/dump-flows", bridge_unixctl_dump_flows,
272                              NULL);
273     unixctl_command_register("bridge/reconnect", bridge_unixctl_reconnect,
274                              NULL);
275     lacp_init();
276     bond_init();
277     cfm_init();
278 }
279
280 void
281 bridge_exit(void)
282 {
283     struct bridge *br, *next_br;
284
285     HMAP_FOR_EACH_SAFE (br, next_br, node, &all_bridges) {
286         bridge_destroy(br);
287     }
288     ovsdb_idl_destroy(idl);
289 }
290
291 /* Looks at the list of managers in 'ovs_cfg' and extracts their remote IP
292  * addresses and ports into '*managersp' and '*n_managersp'.  The caller is
293  * responsible for freeing '*managersp' (with free()).
294  *
295  * You may be asking yourself "why does ovs-vswitchd care?", because
296  * ovsdb-server is responsible for connecting to the managers, and ovs-vswitchd
297  * should not be and in fact is not directly involved in that.  But
298  * ovs-vswitchd needs to make sure that ovsdb-server can reach the managers, so
299  * it has to tell in-band control where the managers are to enable that.
300  * (Thus, only managers connected in-band are collected.)
301  */
302 static void
303 collect_in_band_managers(const struct ovsrec_open_vswitch *ovs_cfg,
304                          struct sockaddr_in **managersp, size_t *n_managersp)
305 {
306     struct sockaddr_in *managers = NULL;
307     size_t n_managers = 0;
308     struct sset targets;
309     size_t i;
310
311     /* Collect all of the potential targets from the "targets" columns of the
312      * rows pointed to by "manager_options", excluding any that are
313      * out-of-band. */
314     sset_init(&targets);
315     for (i = 0; i < ovs_cfg->n_manager_options; i++) {
316         struct ovsrec_manager *m = ovs_cfg->manager_options[i];
317
318         if (m->connection_mode && !strcmp(m->connection_mode, "out-of-band")) {
319             sset_find_and_delete(&targets, m->target);
320         } else {
321             sset_add(&targets, m->target);
322         }
323     }
324
325     /* Now extract the targets' IP addresses. */
326     if (!sset_is_empty(&targets)) {
327         const char *target;
328
329         managers = xmalloc(sset_count(&targets) * sizeof *managers);
330         SSET_FOR_EACH (target, &targets) {
331             struct sockaddr_in *sin = &managers[n_managers];
332
333             if ((!strncmp(target, "tcp:", 4)
334                  && inet_parse_active(target + 4, JSONRPC_TCP_PORT, sin)) ||
335                 (!strncmp(target, "ssl:", 4)
336                  && inet_parse_active(target + 4, JSONRPC_SSL_PORT, sin))) {
337                 n_managers++;
338             }
339         }
340     }
341     sset_destroy(&targets);
342
343     *managersp = managers;
344     *n_managersp = n_managers;
345 }
346
347 static void
348 bridge_reconfigure(const struct ovsrec_open_vswitch *ovs_cfg)
349 {
350     struct sockaddr_in *managers;
351     struct bridge *br, *next;
352     int sflow_bridge_number;
353     size_t n_managers;
354
355     COVERAGE_INC(bridge_reconfigure);
356
357     /* Create and destroy "struct bridge"s, "struct port"s, and "struct
358      * iface"s according to 'ovs_cfg', with only very minimal configuration
359      * otherwise.
360      *
361      * This is purely an update to bridge data structures.  Nothing is pushed
362      * down to ofproto or lower layers. */
363     add_del_bridges(ovs_cfg);
364     HMAP_FOR_EACH (br, node, &all_bridges) {
365         bridge_add_del_ports(br);
366     }
367
368     /* Delete all datapaths and datapath ports that are no longer configured.
369      *
370      * The kernel will reject any attempt to add a given port to a datapath if
371      * that port already belongs to a different datapath, so we must do all
372      * port deletions before any port additions.  A datapath always has a
373      * "local port" so we must delete not-configured datapaths too. */
374     bridge_del_ofprotos();
375     HMAP_FOR_EACH (br, node, &all_bridges) {
376         if (br->ofproto) {
377             bridge_del_ofproto_ports(br);
378         }
379     }
380
381     /* Create datapaths and datapath ports that are missing.
382      *
383      * After this is done, we have our final set of bridges, ports, and
384      * interfaces.  Every "struct bridge" has an ofproto, every "struct port"
385      * has at least one iface, every "struct iface" has a valid ofp_port and
386      * netdev. */
387     HMAP_FOR_EACH_SAFE (br, next, node, &all_bridges) {
388         if (!br->ofproto && !bridge_add_ofprotos(br)) {
389             bridge_destroy(br);
390         }
391     }
392     HMAP_FOR_EACH (br, node, &all_bridges) {
393         bridge_refresh_ofp_port(br);
394         bridge_add_ofproto_ports(br);
395     }
396
397     /* Complete the configuration. */
398     sflow_bridge_number = 0;
399     collect_in_band_managers(ovs_cfg, &managers, &n_managers);
400     HMAP_FOR_EACH (br, node, &all_bridges) {
401         struct port *port;
402
403         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
404             struct iface *iface;
405
406             port_configure(port);
407
408             HMAP_FOR_EACH (iface, ofp_port_node, &br->ifaces) {
409                 iface_configure_cfm(iface);
410                 iface_configure_qos(iface, port->cfg->qos);
411                 iface_set_mac(iface);
412             }
413         }
414         bridge_configure_mirrors(br);
415         bridge_configure_datapath_id(br);
416         bridge_configure_remotes(br, managers, n_managers);
417         bridge_configure_netflow(br);
418         bridge_configure_sflow(br, &sflow_bridge_number);
419     }
420     free(managers);
421
422     /* ovs-vswitchd has completed initialization, so allow the process that
423      * forked us to exit successfully. */
424     daemonize_complete();
425 }
426
427 /* Iterate over all ofprotos and delete any of them that do not have a
428  * configured bridge or that are the wrong type. */
429 static void
430 bridge_del_ofprotos(void)
431 {
432     struct sset names;
433     struct sset types;
434     const char *type;
435
436     sset_init(&names);
437     sset_init(&types);
438     ofproto_enumerate_types(&types);
439     SSET_FOR_EACH (type, &types) {
440         const char *name;
441
442         ofproto_enumerate_names(type, &names);
443         SSET_FOR_EACH (name, &names) {
444             struct bridge *br = bridge_lookup(name);
445             if (!br || strcmp(type, br->type)) {
446                 ofproto_delete(name, type);
447             }
448         }
449     }
450     sset_destroy(&names);
451     sset_destroy(&types);
452 }
453
454 static bool
455 bridge_add_ofprotos(struct bridge *br)
456 {
457     int error = ofproto_create(br->name, br->type, &br->ofproto);
458     if (error) {
459         VLOG_ERR("failed to create bridge %s: %s", br->name, strerror(error));
460         return false;
461     }
462     return true;
463 }
464
465 static void
466 port_configure(struct port *port)
467 {
468     const struct ovsrec_port *cfg = port->cfg;
469     struct bond_settings bond_settings;
470     struct lacp_settings lacp_settings;
471     struct ofproto_bundle_settings s;
472     struct iface *iface;
473
474     /* Get name. */
475     s.name = port->name;
476
477     /* Get slaves. */
478     s.n_slaves = 0;
479     s.slaves = xmalloc(list_size(&port->ifaces) * sizeof *s.slaves);
480     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
481         s.slaves[s.n_slaves++] = iface->ofp_port;
482     }
483
484     /* Get VLAN tag. */
485     s.vlan = -1;
486     if (cfg->tag) {
487         if (list_is_short(&port->ifaces)) {
488             if (*cfg->tag >= 0 && *cfg->tag <= 4095) {
489                 s.vlan = *cfg->tag;
490                 VLOG_DBG("port %s: assigning VLAN tag %d", port->name, s.vlan);
491             }
492         } else {
493             /* It's possible that bonded, VLAN-tagged ports make sense.  Maybe
494              * they even work as-is.  But they have not been tested. */
495             VLOG_WARN("port %s: VLAN tags not supported on bonded ports",
496                       port->name);
497         }
498     }
499
500     /* Get VLAN trunks. */
501     s.trunks = NULL;
502     if (s.vlan < 0 && cfg->n_trunks) {
503         s.trunks = vlan_bitmap_from_array(cfg->trunks, cfg->n_trunks);
504     } else if (s.vlan >= 0 && cfg->n_trunks) {
505         VLOG_ERR("port %s: ignoring trunks in favor of implicit vlan",
506                  port->name);
507     }
508
509     /* Get LACP settings. */
510     s.lacp = port_configure_lacp(port, &lacp_settings);
511     if (s.lacp) {
512         size_t i = 0;
513
514         s.lacp_slaves = xmalloc(s.n_slaves * sizeof *s.lacp_slaves);
515         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
516             iface_configure_lacp(iface, &s.lacp_slaves[i++]);
517         }
518     } else {
519         s.lacp_slaves = NULL;
520     }
521
522     /* Get bond settings. */
523     if (s.n_slaves > 1) {
524         s.bond = &bond_settings;
525         s.bond_stable_ids = xmalloc(s.n_slaves * sizeof *s.bond_stable_ids);
526         port_configure_bond(port, &bond_settings, s.bond_stable_ids);
527     } else {
528         s.bond = NULL;
529         s.bond_stable_ids = NULL;
530
531         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
532             netdev_set_miimon_interval(iface->netdev, 0);
533         }
534     }
535
536     /* Register. */
537     ofproto_bundle_register(port->bridge->ofproto, port, &s);
538
539     /* Clean up. */
540     free(s.trunks);
541     free(s.lacp_slaves);
542     free(s.bond_stable_ids);
543 }
544
545 /* Pick local port hardware address and datapath ID for 'br'. */
546 static void
547 bridge_configure_datapath_id(struct bridge *br)
548 {
549     uint8_t ea[ETH_ADDR_LEN];
550     uint64_t dpid;
551     struct iface *local_iface;
552     struct iface *hw_addr_iface;
553     char *dpid_string;
554
555     bridge_pick_local_hw_addr(br, ea, &hw_addr_iface);
556     local_iface = iface_from_ofp_port(br, OFPP_LOCAL);
557     if (local_iface) {
558         int error = netdev_set_etheraddr(local_iface->netdev, ea);
559         if (error) {
560             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
561             VLOG_ERR_RL(&rl, "bridge %s: failed to set bridge "
562                         "Ethernet address: %s",
563                         br->name, strerror(error));
564         }
565     }
566     memcpy(br->ea, ea, ETH_ADDR_LEN);
567
568     dpid = bridge_pick_datapath_id(br, ea, hw_addr_iface);
569     ofproto_set_datapath_id(br->ofproto, dpid);
570
571     dpid_string = xasprintf("%016"PRIx64, dpid);
572     ovsrec_bridge_set_datapath_id(br->cfg, dpid_string);
573     free(dpid_string);
574 }
575
576 /* Set NetFlow configuration on 'br'. */
577 static void
578 bridge_configure_netflow(struct bridge *br)
579 {
580     struct ovsrec_netflow *cfg = br->cfg->netflow;
581     struct netflow_options opts;
582
583     if (!cfg) {
584         ofproto_set_netflow(br->ofproto, NULL);
585         return;
586     }
587
588     memset(&opts, 0, sizeof opts);
589
590     /* Get default NetFlow configuration from datapath.
591      * Apply overrides from 'cfg'. */
592     ofproto_get_netflow_ids(br->ofproto, &opts.engine_type, &opts.engine_id);
593     if (cfg->engine_type) {
594         opts.engine_type = *cfg->engine_type;
595     }
596     if (cfg->engine_id) {
597         opts.engine_id = *cfg->engine_id;
598     }
599
600     /* Configure active timeout interval. */
601     opts.active_timeout = cfg->active_timeout;
602     if (!opts.active_timeout) {
603         opts.active_timeout = -1;
604     } else if (opts.active_timeout < 0) {
605         VLOG_WARN("bridge %s: active timeout interval set to negative "
606                   "value, using default instead (%d seconds)", br->name,
607                   NF_ACTIVE_TIMEOUT_DEFAULT);
608         opts.active_timeout = -1;
609     }
610
611     /* Add engine ID to interface number to disambiguate bridgs? */
612     opts.add_id_to_iface = cfg->add_id_to_interface;
613     if (opts.add_id_to_iface) {
614         if (opts.engine_id > 0x7f) {
615             VLOG_WARN("bridge %s: NetFlow port mangling may conflict with "
616                       "another vswitch, choose an engine id less than 128",
617                       br->name);
618         }
619         if (hmap_count(&br->ports) > 508) {
620             VLOG_WARN("bridge %s: NetFlow port mangling will conflict with "
621                       "another port when more than 508 ports are used",
622                       br->name);
623         }
624     }
625
626     /* Collectors. */
627     sset_init(&opts.collectors);
628     sset_add_array(&opts.collectors, cfg->targets, cfg->n_targets);
629
630     /* Configure. */
631     if (ofproto_set_netflow(br->ofproto, &opts)) {
632         VLOG_ERR("bridge %s: problem setting netflow collectors", br->name);
633     }
634     sset_destroy(&opts.collectors);
635 }
636
637 /* Set sFlow configuration on 'br'. */
638 static void
639 bridge_configure_sflow(struct bridge *br, int *sflow_bridge_number)
640 {
641     const struct ovsrec_sflow *cfg = br->cfg->sflow;
642     struct ovsrec_controller **controllers;
643     struct ofproto_sflow_options oso;
644     size_t n_controllers;
645     size_t i;
646
647     if (!cfg) {
648         ofproto_set_sflow(br->ofproto, NULL);
649         return;
650     }
651
652     memset(&oso, 0, sizeof oso);
653
654     sset_init(&oso.targets);
655     sset_add_array(&oso.targets, cfg->targets, cfg->n_targets);
656
657     oso.sampling_rate = SFL_DEFAULT_SAMPLING_RATE;
658     if (cfg->sampling) {
659         oso.sampling_rate = *cfg->sampling;
660     }
661
662     oso.polling_interval = SFL_DEFAULT_POLLING_INTERVAL;
663     if (cfg->polling) {
664         oso.polling_interval = *cfg->polling;
665     }
666
667     oso.header_len = SFL_DEFAULT_HEADER_SIZE;
668     if (cfg->header) {
669         oso.header_len = *cfg->header;
670     }
671
672     oso.sub_id = (*sflow_bridge_number)++;
673     oso.agent_device = cfg->agent;
674
675     oso.control_ip = NULL;
676     n_controllers = bridge_get_controllers(br, &controllers);
677     for (i = 0; i < n_controllers; i++) {
678         if (controllers[i]->local_ip) {
679             oso.control_ip = controllers[i]->local_ip;
680             break;
681         }
682     }
683     ofproto_set_sflow(br->ofproto, &oso);
684
685     sset_destroy(&oso.targets);
686 }
687
688 static bool
689 bridge_has_bond_fake_iface(const struct bridge *br, const char *name)
690 {
691     const struct port *port = port_lookup(br, name);
692     return port && port_is_bond_fake_iface(port);
693 }
694
695 static bool
696 port_is_bond_fake_iface(const struct port *port)
697 {
698     return port->cfg->bond_fake_iface && !list_is_short(&port->ifaces);
699 }
700
701 static void
702 add_del_bridges(const struct ovsrec_open_vswitch *cfg)
703 {
704     struct bridge *br, *next;
705     struct shash new_br;
706     size_t i;
707
708     /* Collect new bridges' names and types. */
709     shash_init(&new_br);
710     for (i = 0; i < cfg->n_bridges; i++) {
711         const struct ovsrec_bridge *br_cfg = cfg->bridges[i];
712         if (!shash_add_once(&new_br, br_cfg->name, br_cfg)) {
713             VLOG_WARN("bridge %s specified twice", br_cfg->name);
714         }
715     }
716
717     /* Get rid of deleted bridges or those whose types have changed.
718      * Update 'cfg' of bridges that still exist. */
719     HMAP_FOR_EACH_SAFE (br, next, node, &all_bridges) {
720         br->cfg = shash_find_data(&new_br, br->name);
721         if (!br->cfg || strcmp(br->type, ofproto_normalize_type(
722                                    br->cfg->datapath_type))) {
723             bridge_destroy(br);
724         }
725     }
726
727     /* Add new bridges. */
728     for (i = 0; i < cfg->n_bridges; i++) {
729         const struct ovsrec_bridge *br_cfg = cfg->bridges[i];
730         struct bridge *br = bridge_lookup(br_cfg->name);
731         if (!br) {
732             bridge_create(br_cfg);
733         }
734     }
735
736     shash_destroy(&new_br);
737 }
738
739 /* Delete each ofproto port on 'br' that doesn't have a corresponding "struct
740  * iface".
741  *
742  * The kernel will reject any attempt to add a given port to a datapath if that
743  * port already belongs to a different datapath, so we must do all port
744  * deletions before any port additions. */
745 static void
746 bridge_del_ofproto_ports(struct bridge *br)
747 {
748     struct ofproto_port_dump dump;
749     struct ofproto_port ofproto_port;
750
751     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, br->ofproto) {
752         const char *name = ofproto_port.name;
753         struct iface *iface;
754         const char *type;
755         int error;
756
757         /* Ignore the local port.  We can't change it anyhow. */
758         if (!strcmp(name, br->name)) {
759             continue;
760         }
761
762         /* Get the type that 'ofproto_port' should have (ordinarily the
763          * type of its corresponding iface) or NULL if it should be
764          * deleted. */
765         iface = iface_lookup(br, name);
766         type = (iface ? iface->type
767                 : bridge_has_bond_fake_iface(br, name) ? "internal"
768                 : NULL);
769
770         /* If it's the wrong type then delete the ofproto port. */
771         if (type
772             && !strcmp(ofproto_port.type, type)
773             && (!iface || !iface->netdev
774                 || !strcmp(netdev_get_type(iface->netdev), type))) {
775             continue;
776         }
777         error = ofproto_port_del(br->ofproto, ofproto_port.ofp_port);
778         if (error) {
779             VLOG_WARN("bridge %s: failed to remove %s interface (%s)",
780                       br->name, name, strerror(error));
781         }
782         if (iface) {
783             netdev_close(iface->netdev);
784             iface->netdev = NULL;
785         }
786     }
787 }
788
789 static void
790 iface_set_ofp_port(struct iface *iface, int ofp_port)
791 {
792     struct bridge *br = iface->port->bridge;
793
794     assert(iface->ofp_port < 0 && ofp_port >= 0);
795     iface->ofp_port = ofp_port;
796     hmap_insert(&br->ifaces, &iface->ofp_port_node, hash_int(ofp_port, 0));
797     iface_set_ofport(iface->cfg, ofp_port);
798 }
799
800 static void
801 bridge_refresh_ofp_port(struct bridge *br)
802 {
803     struct ofproto_port_dump dump;
804     struct ofproto_port ofproto_port;
805     struct port *port;
806
807     /* Clear all the "ofp_port"es. */
808     hmap_clear(&br->ifaces);
809     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
810         struct iface *iface;
811
812         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
813             iface->ofp_port = -1;
814         }
815     }
816
817     /* Obtain the correct "ofp_port"s from ofproto. */
818     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, br->ofproto) {
819         struct iface *iface = iface_lookup(br, ofproto_port.name);
820         if (iface) {
821             if (iface->ofp_port >= 0) {
822                 VLOG_WARN("bridge %s: interface %s reported twice",
823                           br->name, ofproto_port.name);
824             } else if (iface_from_ofp_port(br, ofproto_port.ofp_port)) {
825                 VLOG_WARN("bridge %s: interface %"PRIu16" reported twice",
826                           br->name, ofproto_port.ofp_port);
827             } else {
828                 iface_set_ofp_port(iface, ofproto_port.ofp_port);
829             }
830         }
831     }
832 }
833
834 /* Add an ofproto port for any "struct iface" that doesn't have one.
835  * Delete any "struct iface" for which this fails.
836  * Delete any "struct port" that thereby ends up with no ifaces. */
837 static void
838 bridge_add_ofproto_ports(struct bridge *br)
839 {
840     struct port *port, *next_port;
841
842     HMAP_FOR_EACH_SAFE (port, next_port, hmap_node, &br->ports) {
843         struct iface *iface, *next_iface;
844         struct ofproto_port ofproto_port;
845
846         LIST_FOR_EACH_SAFE (iface, next_iface, port_elem, &port->ifaces) {
847             struct shash args;
848             int error;
849
850             /* Open the netdev or reconfigure it. */
851             shash_init(&args);
852             shash_from_ovs_idl_map(iface->cfg->key_options,
853                                    iface->cfg->value_options,
854                                    iface->cfg->n_options, &args);
855             if (!iface->netdev) {
856                 struct netdev_options options;
857                 options.name = iface->name;
858                 options.type = iface->type;
859                 options.args = &args;
860                 options.ethertype = NETDEV_ETH_TYPE_NONE;
861                 error = netdev_open(&options, &iface->netdev);
862             } else {
863                 error = netdev_set_config(iface->netdev, &args);
864             }
865             shash_destroy(&args);
866             if (error) {
867                 VLOG_WARN("could not %s network device %s (%s)",
868                           iface->netdev ? "reconfigure" : "open",
869                           iface->name, strerror(error));
870             }
871
872             /* Add the port, if necessary. */
873             if (iface->netdev && iface->ofp_port < 0) {
874                 uint16_t ofp_port;
875                 int error;
876
877                 error = ofproto_port_add(br->ofproto, iface->netdev,
878                                          &ofp_port);
879                 if (!error) {
880                     iface_set_ofp_port(iface, ofp_port);
881                 } else {
882                     netdev_close(iface->netdev);
883                     iface->netdev = NULL;
884                 }
885             }
886
887             /* Delete the iface if  */
888             if (iface->netdev && iface->ofp_port >= 0) {
889                 VLOG_DBG("bridge %s: interface %s is on port %d",
890                          br->name, iface->name, iface->ofp_port);
891             } else {
892                 if (iface->netdev) {
893                     VLOG_ERR("bridge %s: missing %s interface, dropping",
894                              br->name, iface->name);
895                 } else {
896                     /* We already reported a related error, don't bother
897                      * duplicating it. */
898                 }
899                 iface_set_ofport(iface->cfg, -1);
900                 iface_destroy(iface);
901             }
902         }
903         if (list_is_empty(&port->ifaces)) {
904             VLOG_WARN("%s port has no interfaces, dropping", port->name);
905             port_destroy(port);
906             continue;
907         }
908
909         /* Add bond fake iface if necessary. */
910         if (port_is_bond_fake_iface(port)) {
911             if (ofproto_port_query_by_name(br->ofproto, port->name,
912                                            &ofproto_port)) {
913                 struct netdev_options options;
914                 struct netdev *netdev;
915                 int error;
916
917                 options.name = port->name;
918                 options.type = "internal";
919                 options.args = NULL;
920                 options.ethertype = NETDEV_ETH_TYPE_NONE;
921                 error = netdev_open(&options, &netdev);
922                 if (!error) {
923                     ofproto_port_add(br->ofproto, netdev, NULL);
924                     netdev_close(netdev);
925                 } else {
926                     VLOG_WARN("could not open network device %s (%s)",
927                               port->name, strerror(error));
928                 }
929             } else {
930                 /* Already exists, nothing to do. */
931                 ofproto_port_destroy(&ofproto_port);
932             }
933         }
934     }
935 }
936
937 static const char *
938 get_ovsrec_key_value(const struct ovsdb_idl_row *row,
939                      const struct ovsdb_idl_column *column,
940                      const char *key)
941 {
942     const struct ovsdb_datum *datum;
943     union ovsdb_atom atom;
944     unsigned int idx;
945
946     datum = ovsdb_idl_get(row, column, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
947     atom.string = (char *) key;
948     idx = ovsdb_datum_find_key(datum, &atom, OVSDB_TYPE_STRING);
949     return idx == UINT_MAX ? NULL : datum->values[idx].string;
950 }
951
952 static const char *
953 bridge_get_other_config(const struct ovsrec_bridge *br_cfg, const char *key)
954 {
955     return get_ovsrec_key_value(&br_cfg->header_,
956                                 &ovsrec_bridge_col_other_config, key);
957 }
958
959 static void
960 bridge_pick_local_hw_addr(struct bridge *br, uint8_t ea[ETH_ADDR_LEN],
961                           struct iface **hw_addr_iface)
962 {
963     const char *hwaddr;
964     struct port *port;
965     int error;
966
967     *hw_addr_iface = NULL;
968
969     /* Did the user request a particular MAC? */
970     hwaddr = bridge_get_other_config(br->cfg, "hwaddr");
971     if (hwaddr && eth_addr_from_string(hwaddr, ea)) {
972         if (eth_addr_is_multicast(ea)) {
973             VLOG_ERR("bridge %s: cannot set MAC address to multicast "
974                      "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
975         } else if (eth_addr_is_zero(ea)) {
976             VLOG_ERR("bridge %s: cannot set MAC address to zero", br->name);
977         } else {
978             return;
979         }
980     }
981
982     /* Otherwise choose the minimum non-local MAC address among all of the
983      * interfaces. */
984     memset(ea, 0xff, ETH_ADDR_LEN);
985     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
986         uint8_t iface_ea[ETH_ADDR_LEN];
987         struct iface *candidate;
988         struct iface *iface;
989
990         /* Mirror output ports don't participate. */
991         if (ofproto_is_mirror_output_bundle(br->ofproto, port)) {
992             continue;
993         }
994
995         /* Choose the MAC address to represent the port. */
996         iface = NULL;
997         if (port->cfg->mac && eth_addr_from_string(port->cfg->mac, iface_ea)) {
998             /* Find the interface with this Ethernet address (if any) so that
999              * we can provide the correct devname to the caller. */
1000             LIST_FOR_EACH (candidate, port_elem, &port->ifaces) {
1001                 uint8_t candidate_ea[ETH_ADDR_LEN];
1002                 if (!netdev_get_etheraddr(candidate->netdev, candidate_ea)
1003                     && eth_addr_equals(iface_ea, candidate_ea)) {
1004                     iface = candidate;
1005                 }
1006             }
1007         } else {
1008             /* Choose the interface whose MAC address will represent the port.
1009              * The Linux kernel bonding code always chooses the MAC address of
1010              * the first slave added to a bond, and the Fedora networking
1011              * scripts always add slaves to a bond in alphabetical order, so
1012              * for compatibility we choose the interface with the name that is
1013              * first in alphabetical order. */
1014             LIST_FOR_EACH (candidate, port_elem, &port->ifaces) {
1015                 if (!iface || strcmp(candidate->name, iface->name) < 0) {
1016                     iface = candidate;
1017                 }
1018             }
1019
1020             /* The local port doesn't count (since we're trying to choose its
1021              * MAC address anyway). */
1022             if (iface->ofp_port == OFPP_LOCAL) {
1023                 continue;
1024             }
1025
1026             /* Grab MAC. */
1027             error = netdev_get_etheraddr(iface->netdev, iface_ea);
1028             if (error) {
1029                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1030                 VLOG_ERR_RL(&rl, "failed to obtain Ethernet address of %s: %s",
1031                             iface->name, strerror(error));
1032                 continue;
1033             }
1034         }
1035
1036         /* Compare against our current choice. */
1037         if (!eth_addr_is_multicast(iface_ea) &&
1038             !eth_addr_is_local(iface_ea) &&
1039             !eth_addr_is_reserved(iface_ea) &&
1040             !eth_addr_is_zero(iface_ea) &&
1041             eth_addr_compare_3way(iface_ea, ea) < 0)
1042         {
1043             memcpy(ea, iface_ea, ETH_ADDR_LEN);
1044             *hw_addr_iface = iface;
1045         }
1046     }
1047     if (eth_addr_is_multicast(ea)) {
1048         memcpy(ea, br->default_ea, ETH_ADDR_LEN);
1049         *hw_addr_iface = NULL;
1050         VLOG_WARN("bridge %s: using default bridge Ethernet "
1051                   "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
1052     } else {
1053         VLOG_DBG("bridge %s: using bridge Ethernet address "ETH_ADDR_FMT,
1054                  br->name, ETH_ADDR_ARGS(ea));
1055     }
1056 }
1057
1058 /* Choose and returns the datapath ID for bridge 'br' given that the bridge
1059  * Ethernet address is 'bridge_ea'.  If 'bridge_ea' is the Ethernet address of
1060  * an interface on 'br', then that interface must be passed in as
1061  * 'hw_addr_iface'; if 'bridge_ea' was derived some other way, then
1062  * 'hw_addr_iface' must be passed in as a null pointer. */
1063 static uint64_t
1064 bridge_pick_datapath_id(struct bridge *br,
1065                         const uint8_t bridge_ea[ETH_ADDR_LEN],
1066                         struct iface *hw_addr_iface)
1067 {
1068     /*
1069      * The procedure for choosing a bridge MAC address will, in the most
1070      * ordinary case, also choose a unique MAC that we can use as a datapath
1071      * ID.  In some special cases, though, multiple bridges will end up with
1072      * the same MAC address.  This is OK for the bridges, but it will confuse
1073      * the OpenFlow controller, because each datapath needs a unique datapath
1074      * ID.
1075      *
1076      * Datapath IDs must be unique.  It is also very desirable that they be
1077      * stable from one run to the next, so that policy set on a datapath
1078      * "sticks".
1079      */
1080     const char *datapath_id;
1081     uint64_t dpid;
1082
1083     datapath_id = bridge_get_other_config(br->cfg, "datapath-id");
1084     if (datapath_id && dpid_from_string(datapath_id, &dpid)) {
1085         return dpid;
1086     }
1087
1088     if (hw_addr_iface) {
1089         int vlan;
1090         if (!netdev_get_vlan_vid(hw_addr_iface->netdev, &vlan)) {
1091             /*
1092              * A bridge whose MAC address is taken from a VLAN network device
1093              * (that is, a network device created with vconfig(8) or similar
1094              * tool) will have the same MAC address as a bridge on the VLAN
1095              * device's physical network device.
1096              *
1097              * Handle this case by hashing the physical network device MAC
1098              * along with the VLAN identifier.
1099              */
1100             uint8_t buf[ETH_ADDR_LEN + 2];
1101             memcpy(buf, bridge_ea, ETH_ADDR_LEN);
1102             buf[ETH_ADDR_LEN] = vlan >> 8;
1103             buf[ETH_ADDR_LEN + 1] = vlan;
1104             return dpid_from_hash(buf, sizeof buf);
1105         } else {
1106             /*
1107              * Assume that this bridge's MAC address is unique, since it
1108              * doesn't fit any of the cases we handle specially.
1109              */
1110         }
1111     } else {
1112         /*
1113          * A purely internal bridge, that is, one that has no non-virtual
1114          * network devices on it at all, is more difficult because it has no
1115          * natural unique identifier at all.
1116          *
1117          * When the host is a XenServer, we handle this case by hashing the
1118          * host's UUID with the name of the bridge.  Names of bridges are
1119          * persistent across XenServer reboots, although they can be reused if
1120          * an internal network is destroyed and then a new one is later
1121          * created, so this is fairly effective.
1122          *
1123          * When the host is not a XenServer, we punt by using a random MAC
1124          * address on each run.
1125          */
1126         const char *host_uuid = xenserver_get_host_uuid();
1127         if (host_uuid) {
1128             char *combined = xasprintf("%s,%s", host_uuid, br->name);
1129             dpid = dpid_from_hash(combined, strlen(combined));
1130             free(combined);
1131             return dpid;
1132         }
1133     }
1134
1135     return eth_addr_to_uint64(bridge_ea);
1136 }
1137
1138 static uint64_t
1139 dpid_from_hash(const void *data, size_t n)
1140 {
1141     uint8_t hash[SHA1_DIGEST_SIZE];
1142
1143     BUILD_ASSERT_DECL(sizeof hash >= ETH_ADDR_LEN);
1144     sha1_bytes(data, n, hash);
1145     eth_addr_mark_random(hash);
1146     return eth_addr_to_uint64(hash);
1147 }
1148
1149 static void
1150 iface_refresh_status(struct iface *iface)
1151 {
1152     struct shash sh;
1153
1154     enum netdev_flags flags;
1155     uint32_t current;
1156     int64_t bps;
1157     int mtu;
1158     int64_t mtu_64;
1159     int error;
1160
1161     if (iface_is_synthetic(iface)) {
1162         return;
1163     }
1164
1165     shash_init(&sh);
1166
1167     if (!netdev_get_status(iface->netdev, &sh)) {
1168         size_t n;
1169         char **keys, **values;
1170
1171         shash_to_ovs_idl_map(&sh, &keys, &values, &n);
1172         ovsrec_interface_set_status(iface->cfg, keys, values, n);
1173
1174         free(keys);
1175         free(values);
1176     } else {
1177         ovsrec_interface_set_status(iface->cfg, NULL, NULL, 0);
1178     }
1179
1180     shash_destroy_free_data(&sh);
1181
1182     error = netdev_get_flags(iface->netdev, &flags);
1183     if (!error) {
1184         ovsrec_interface_set_admin_state(iface->cfg, flags & NETDEV_UP ? "up" : "down");
1185     }
1186     else {
1187         ovsrec_interface_set_admin_state(iface->cfg, NULL);
1188     }
1189
1190     error = netdev_get_features(iface->netdev, &current, NULL, NULL, NULL);
1191     if (!error) {
1192         ovsrec_interface_set_duplex(iface->cfg,
1193                                     netdev_features_is_full_duplex(current)
1194                                     ? "full" : "half");
1195         /* warning: uint64_t -> int64_t conversion */
1196         bps = netdev_features_to_bps(current);
1197         ovsrec_interface_set_link_speed(iface->cfg, &bps, 1);
1198     }
1199     else {
1200         ovsrec_interface_set_duplex(iface->cfg, NULL);
1201         ovsrec_interface_set_link_speed(iface->cfg, NULL, 0);
1202     }
1203
1204     ovsrec_interface_set_link_state(iface->cfg,
1205                                     iface_get_carrier(iface) ? "up" : "down");
1206
1207     error = netdev_get_mtu(iface->netdev, &mtu);
1208     if (!error && mtu != INT_MAX) {
1209         mtu_64 = mtu;
1210         ovsrec_interface_set_mtu(iface->cfg, &mtu_64, 1);
1211     }
1212     else {
1213         ovsrec_interface_set_mtu(iface->cfg, NULL, 0);
1214     }
1215 }
1216
1217 /* Writes 'iface''s CFM statistics to the database.  Returns true if anything
1218  * changed, false otherwise. */
1219 static bool
1220 iface_refresh_cfm_stats(struct iface *iface)
1221 {
1222     const struct ovsrec_monitor *mon;
1223     const struct cfm *cfm;
1224     bool changed = false;
1225     size_t i;
1226
1227     mon = iface->cfg->monitor;
1228     cfm = ofproto_port_get_cfm(iface->port->bridge->ofproto, iface->ofp_port);
1229
1230     if (!cfm || !mon) {
1231         return false;
1232     }
1233
1234     for (i = 0; i < mon->n_remote_mps; i++) {
1235         const struct ovsrec_maintenance_point *mp;
1236         const struct remote_mp *rmp;
1237
1238         mp = mon->remote_mps[i];
1239         rmp = cfm_get_remote_mp(cfm, mp->mpid);
1240
1241         if (mp->n_fault != 1 || mp->fault[0] != rmp->fault) {
1242             ovsrec_maintenance_point_set_fault(mp, &rmp->fault, 1);
1243             changed = true;
1244         }
1245     }
1246
1247     if (mon->n_fault != 1 || mon->fault[0] != cfm->fault) {
1248         ovsrec_monitor_set_fault(mon, &cfm->fault, 1);
1249         changed = true;
1250     }
1251
1252     return changed;
1253 }
1254
1255 static bool
1256 iface_refresh_lacp_stats(struct iface *iface)
1257 {
1258     struct ofproto *ofproto = iface->port->bridge->ofproto;
1259     int old = iface->cfg->lacp_current ? *iface->cfg->lacp_current : -1;
1260     int new = ofproto_port_is_lacp_current(ofproto, iface->ofp_port);
1261
1262     if (old != new) {
1263         bool current = new;
1264         ovsrec_interface_set_lacp_current(iface->cfg, &current, new >= 0);
1265     }
1266     return old != new;
1267 }
1268
1269 static void
1270 iface_refresh_stats(struct iface *iface)
1271 {
1272     struct iface_stat {
1273         char *name;
1274         int offset;
1275     };
1276     static const struct iface_stat iface_stats[] = {
1277         { "rx_packets", offsetof(struct netdev_stats, rx_packets) },
1278         { "tx_packets", offsetof(struct netdev_stats, tx_packets) },
1279         { "rx_bytes", offsetof(struct netdev_stats, rx_bytes) },
1280         { "tx_bytes", offsetof(struct netdev_stats, tx_bytes) },
1281         { "rx_dropped", offsetof(struct netdev_stats, rx_dropped) },
1282         { "tx_dropped", offsetof(struct netdev_stats, tx_dropped) },
1283         { "rx_errors", offsetof(struct netdev_stats, rx_errors) },
1284         { "tx_errors", offsetof(struct netdev_stats, tx_errors) },
1285         { "rx_frame_err", offsetof(struct netdev_stats, rx_frame_errors) },
1286         { "rx_over_err", offsetof(struct netdev_stats, rx_over_errors) },
1287         { "rx_crc_err", offsetof(struct netdev_stats, rx_crc_errors) },
1288         { "collisions", offsetof(struct netdev_stats, collisions) },
1289     };
1290     enum { N_STATS = ARRAY_SIZE(iface_stats) };
1291     const struct iface_stat *s;
1292
1293     char *keys[N_STATS];
1294     int64_t values[N_STATS];
1295     int n;
1296
1297     struct netdev_stats stats;
1298
1299     if (iface_is_synthetic(iface)) {
1300         return;
1301     }
1302
1303     /* Intentionally ignore return value, since errors will set 'stats' to
1304      * all-1s, and we will deal with that correctly below. */
1305     netdev_get_stats(iface->netdev, &stats);
1306
1307     n = 0;
1308     for (s = iface_stats; s < &iface_stats[N_STATS]; s++) {
1309         uint64_t value = *(uint64_t *) (((char *) &stats) + s->offset);
1310         if (value != UINT64_MAX) {
1311             keys[n] = s->name;
1312             values[n] = value;
1313             n++;
1314         }
1315     }
1316
1317     ovsrec_interface_set_statistics(iface->cfg, keys, values, n);
1318 }
1319
1320 static void
1321 refresh_system_stats(const struct ovsrec_open_vswitch *cfg)
1322 {
1323     struct ovsdb_datum datum;
1324     struct shash stats;
1325
1326     shash_init(&stats);
1327     get_system_stats(&stats);
1328
1329     ovsdb_datum_from_shash(&datum, &stats);
1330     ovsdb_idl_txn_write(&cfg->header_, &ovsrec_open_vswitch_col_statistics,
1331                         &datum);
1332 }
1333
1334 static inline const char *
1335 nx_role_to_str(enum nx_role role)
1336 {
1337     switch (role) {
1338     case NX_ROLE_OTHER:
1339         return "other";
1340     case NX_ROLE_MASTER:
1341         return "master";
1342     case NX_ROLE_SLAVE:
1343         return "slave";
1344     default:
1345         return "*** INVALID ROLE ***";
1346     }
1347 }
1348
1349 static void
1350 bridge_refresh_controller_status(const struct bridge *br)
1351 {
1352     struct shash info;
1353     const struct ovsrec_controller *cfg;
1354
1355     ofproto_get_ofproto_controller_info(br->ofproto, &info);
1356
1357     OVSREC_CONTROLLER_FOR_EACH(cfg, idl) {
1358         struct ofproto_controller_info *cinfo =
1359             shash_find_data(&info, cfg->target);
1360
1361         if (cinfo) {
1362             ovsrec_controller_set_is_connected(cfg, cinfo->is_connected);
1363             ovsrec_controller_set_role(cfg, nx_role_to_str(cinfo->role));
1364             ovsrec_controller_set_status(cfg, (char **) cinfo->pairs.keys,
1365                                          (char **) cinfo->pairs.values,
1366                                          cinfo->pairs.n);
1367         } else {
1368             ovsrec_controller_set_is_connected(cfg, false);
1369             ovsrec_controller_set_role(cfg, NULL);
1370             ovsrec_controller_set_status(cfg, NULL, NULL, 0);
1371         }
1372     }
1373
1374     ofproto_free_ofproto_controller_info(&info);
1375 }
1376
1377 void
1378 bridge_run(void)
1379 {
1380     const struct ovsrec_open_vswitch *cfg;
1381
1382     bool datapath_destroyed;
1383     bool database_changed;
1384     struct bridge *br;
1385
1386     /* Let each bridge do the work that it needs to do. */
1387     datapath_destroyed = false;
1388     HMAP_FOR_EACH (br, node, &all_bridges) {
1389         int error = ofproto_run(br->ofproto);
1390         if (error) {
1391             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1392             VLOG_ERR_RL(&rl, "bridge %s: datapath was destroyed externally, "
1393                         "forcing reconfiguration", br->name);
1394             datapath_destroyed = true;
1395         }
1396     }
1397
1398     /* (Re)configure if necessary. */
1399     database_changed = ovsdb_idl_run(idl);
1400     cfg = ovsrec_open_vswitch_first(idl);
1401
1402     /* Re-configure SSL.  We do this on every trip through the main loop,
1403      * instead of just when the database changes, because the contents of the
1404      * key and certificate files can change without the database changing.
1405      *
1406      * We do this before bridge_reconfigure() because that function might
1407      * initiate SSL connections and thus requires SSL to be configured. */
1408     if (cfg && cfg->ssl) {
1409         const struct ovsrec_ssl *ssl = cfg->ssl;
1410
1411         stream_ssl_set_key_and_cert(ssl->private_key, ssl->certificate);
1412         stream_ssl_set_ca_cert_file(ssl->ca_cert, ssl->bootstrap_ca_cert);
1413     }
1414
1415     if (database_changed || datapath_destroyed) {
1416         if (cfg) {
1417             struct ovsdb_idl_txn *txn = ovsdb_idl_txn_create(idl);
1418
1419             bridge_reconfigure(cfg);
1420
1421             ovsrec_open_vswitch_set_cur_cfg(cfg, cfg->next_cfg);
1422             ovsdb_idl_txn_commit(txn);
1423             ovsdb_idl_txn_destroy(txn); /* XXX */
1424         } else {
1425             /* We still need to reconfigure to avoid dangling pointers to
1426              * now-destroyed ovsrec structures inside bridge data. */
1427             static const struct ovsrec_open_vswitch null_cfg;
1428
1429             bridge_reconfigure(&null_cfg);
1430         }
1431     }
1432
1433     /* Refresh system and interface stats if necessary. */
1434     if (time_msec() >= stats_timer) {
1435         if (cfg) {
1436             struct ovsdb_idl_txn *txn;
1437
1438             txn = ovsdb_idl_txn_create(idl);
1439             HMAP_FOR_EACH (br, node, &all_bridges) {
1440                 struct port *port;
1441
1442                 HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1443                     struct iface *iface;
1444
1445                     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1446                         iface_refresh_stats(iface);
1447                         iface_refresh_status(iface);
1448                     }
1449                 }
1450                 bridge_refresh_controller_status(br);
1451             }
1452             refresh_system_stats(cfg);
1453             ovsdb_idl_txn_commit(txn);
1454             ovsdb_idl_txn_destroy(txn); /* XXX */
1455         }
1456
1457         stats_timer = time_msec() + STATS_INTERVAL;
1458     }
1459
1460     if (time_msec() >= db_limiter) {
1461         struct ovsdb_idl_txn *txn;
1462         bool changed = false;
1463
1464         txn = ovsdb_idl_txn_create(idl);
1465         HMAP_FOR_EACH (br, node, &all_bridges) {
1466             struct port *port;
1467
1468             HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1469                 struct iface *iface;
1470
1471                 LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1472                     changed = iface_refresh_cfm_stats(iface) || changed;
1473                     changed = iface_refresh_lacp_stats(iface) || changed;
1474                 }
1475             }
1476         }
1477
1478         if (changed) {
1479             db_limiter = time_msec() + DB_LIMIT_INTERVAL;
1480         }
1481
1482         ovsdb_idl_txn_commit(txn);
1483         ovsdb_idl_txn_destroy(txn);
1484     }
1485 }
1486
1487 void
1488 bridge_wait(void)
1489 {
1490     struct bridge *br;
1491
1492     HMAP_FOR_EACH (br, node, &all_bridges) {
1493         ofproto_wait(br->ofproto);
1494     }
1495     ovsdb_idl_wait(idl);
1496     poll_timer_wait_until(stats_timer);
1497
1498     if (db_limiter > time_msec()) {
1499         poll_timer_wait_until(db_limiter);
1500     }
1501 }
1502 \f
1503 /* QoS unixctl user interface functions. */
1504
1505 struct qos_unixctl_show_cbdata {
1506     struct ds *ds;
1507     struct iface *iface;
1508 };
1509
1510 static void
1511 qos_unixctl_show_cb(unsigned int queue_id,
1512                     const struct shash *details,
1513                     void *aux)
1514 {
1515     struct qos_unixctl_show_cbdata *data = aux;
1516     struct ds *ds = data->ds;
1517     struct iface *iface = data->iface;
1518     struct netdev_queue_stats stats;
1519     struct shash_node *node;
1520     int error;
1521
1522     ds_put_cstr(ds, "\n");
1523     if (queue_id) {
1524         ds_put_format(ds, "Queue %u:\n", queue_id);
1525     } else {
1526         ds_put_cstr(ds, "Default:\n");
1527     }
1528
1529     SHASH_FOR_EACH (node, details) {
1530         ds_put_format(ds, "\t%s: %s\n", node->name, (char *)node->data);
1531     }
1532
1533     error = netdev_get_queue_stats(iface->netdev, queue_id, &stats);
1534     if (!error) {
1535         if (stats.tx_packets != UINT64_MAX) {
1536             ds_put_format(ds, "\ttx_packets: %"PRIu64"\n", stats.tx_packets);
1537         }
1538
1539         if (stats.tx_bytes != UINT64_MAX) {
1540             ds_put_format(ds, "\ttx_bytes: %"PRIu64"\n", stats.tx_bytes);
1541         }
1542
1543         if (stats.tx_errors != UINT64_MAX) {
1544             ds_put_format(ds, "\ttx_errors: %"PRIu64"\n", stats.tx_errors);
1545         }
1546     } else {
1547         ds_put_format(ds, "\tFailed to get statistics for queue %u: %s",
1548                       queue_id, strerror(error));
1549     }
1550 }
1551
1552 static void
1553 qos_unixctl_show(struct unixctl_conn *conn,
1554                  const char *args, void *aux OVS_UNUSED)
1555 {
1556     struct ds ds = DS_EMPTY_INITIALIZER;
1557     struct shash sh = SHASH_INITIALIZER(&sh);
1558     struct iface *iface;
1559     const char *type;
1560     struct shash_node *node;
1561     struct qos_unixctl_show_cbdata data;
1562     int error;
1563
1564     iface = iface_find(args);
1565     if (!iface) {
1566         unixctl_command_reply(conn, 501, "no such interface");
1567         return;
1568     }
1569
1570     netdev_get_qos(iface->netdev, &type, &sh);
1571
1572     if (*type != '\0') {
1573         ds_put_format(&ds, "QoS: %s %s\n", iface->name, type);
1574
1575         SHASH_FOR_EACH (node, &sh) {
1576             ds_put_format(&ds, "%s: %s\n", node->name, (char *)node->data);
1577         }
1578
1579         data.ds = &ds;
1580         data.iface = iface;
1581         error = netdev_dump_queues(iface->netdev, qos_unixctl_show_cb, &data);
1582
1583         if (error) {
1584             ds_put_format(&ds, "failed to dump queues: %s", strerror(error));
1585         }
1586         unixctl_command_reply(conn, 200, ds_cstr(&ds));
1587     } else {
1588         ds_put_format(&ds, "QoS not configured on %s\n", iface->name);
1589         unixctl_command_reply(conn, 501, ds_cstr(&ds));
1590     }
1591
1592     shash_destroy_free_data(&sh);
1593     ds_destroy(&ds);
1594 }
1595 \f
1596 /* Bridge reconfiguration functions. */
1597 static void
1598 bridge_create(const struct ovsrec_bridge *br_cfg)
1599 {
1600     struct bridge *br;
1601
1602     assert(!bridge_lookup(br_cfg->name));
1603     br = xzalloc(sizeof *br);
1604
1605     br->name = xstrdup(br_cfg->name);
1606     br->type = xstrdup(ofproto_normalize_type(br_cfg->datapath_type));
1607     br->cfg = br_cfg;
1608
1609     /* Derive the default Ethernet address from the bridge's UUID.  This should
1610      * be unique and it will be stable between ovs-vswitchd runs.  */
1611     memcpy(br->default_ea, &br_cfg->header_.uuid, ETH_ADDR_LEN);
1612     eth_addr_mark_random(br->default_ea);
1613
1614     hmap_init(&br->ports);
1615     hmap_init(&br->ifaces);
1616     hmap_init(&br->iface_by_name);
1617     hmap_init(&br->mirrors);
1618
1619     hmap_insert(&all_bridges, &br->node, hash_string(br->name, 0));
1620 }
1621
1622 static void
1623 bridge_destroy(struct bridge *br)
1624 {
1625     if (br) {
1626         struct mirror *mirror, *next_mirror;
1627         struct port *port, *next_port;
1628
1629         HMAP_FOR_EACH_SAFE (port, next_port, hmap_node, &br->ports) {
1630             port_destroy(port);
1631         }
1632         HMAP_FOR_EACH_SAFE (mirror, next_mirror, hmap_node, &br->mirrors) {
1633             mirror_destroy(mirror);
1634         }
1635         hmap_remove(&all_bridges, &br->node);
1636         ofproto_destroy(br->ofproto);
1637         hmap_destroy(&br->ifaces);
1638         hmap_destroy(&br->ports);
1639         hmap_destroy(&br->iface_by_name);
1640         hmap_destroy(&br->mirrors);
1641         free(br->name);
1642         free(br->type);
1643         free(br);
1644     }
1645 }
1646
1647 static struct bridge *
1648 bridge_lookup(const char *name)
1649 {
1650     struct bridge *br;
1651
1652     HMAP_FOR_EACH_WITH_HASH (br, node, hash_string(name, 0), &all_bridges) {
1653         if (!strcmp(br->name, name)) {
1654             return br;
1655         }
1656     }
1657     return NULL;
1658 }
1659
1660 /* Handle requests for a listing of all flows known by the OpenFlow
1661  * stack, including those normally hidden. */
1662 static void
1663 bridge_unixctl_dump_flows(struct unixctl_conn *conn,
1664                           const char *args, void *aux OVS_UNUSED)
1665 {
1666     struct bridge *br;
1667     struct ds results;
1668
1669     br = bridge_lookup(args);
1670     if (!br) {
1671         unixctl_command_reply(conn, 501, "Unknown bridge");
1672         return;
1673     }
1674
1675     ds_init(&results);
1676     ofproto_get_all_flows(br->ofproto, &results);
1677
1678     unixctl_command_reply(conn, 200, ds_cstr(&results));
1679     ds_destroy(&results);
1680 }
1681
1682 /* "bridge/reconnect [BRIDGE]": makes BRIDGE drop all of its controller
1683  * connections and reconnect.  If BRIDGE is not specified, then all bridges
1684  * drop their controller connections and reconnect. */
1685 static void
1686 bridge_unixctl_reconnect(struct unixctl_conn *conn,
1687                          const char *args, void *aux OVS_UNUSED)
1688 {
1689     struct bridge *br;
1690     if (args[0] != '\0') {
1691         br = bridge_lookup(args);
1692         if (!br) {
1693             unixctl_command_reply(conn, 501, "Unknown bridge");
1694             return;
1695         }
1696         ofproto_reconnect_controllers(br->ofproto);
1697     } else {
1698         HMAP_FOR_EACH (br, node, &all_bridges) {
1699             ofproto_reconnect_controllers(br->ofproto);
1700         }
1701     }
1702     unixctl_command_reply(conn, 200, NULL);
1703 }
1704
1705 static size_t
1706 bridge_get_controllers(const struct bridge *br,
1707                        struct ovsrec_controller ***controllersp)
1708 {
1709     struct ovsrec_controller **controllers;
1710     size_t n_controllers;
1711
1712     controllers = br->cfg->controller;
1713     n_controllers = br->cfg->n_controller;
1714
1715     if (n_controllers == 1 && !strcmp(controllers[0]->target, "none")) {
1716         controllers = NULL;
1717         n_controllers = 0;
1718     }
1719
1720     if (controllersp) {
1721         *controllersp = controllers;
1722     }
1723     return n_controllers;
1724 }
1725
1726 /* Adds and deletes "struct port"s and "struct iface"s under 'br' to match
1727  * those configured in 'br->cfg'. */
1728 static void
1729 bridge_add_del_ports(struct bridge *br)
1730 {
1731     struct port *port, *next;
1732     struct shash_node *node;
1733     struct shash new_ports;
1734     size_t i;
1735
1736     /* Collect new ports. */
1737     shash_init(&new_ports);
1738     for (i = 0; i < br->cfg->n_ports; i++) {
1739         const char *name = br->cfg->ports[i]->name;
1740         if (!shash_add_once(&new_ports, name, br->cfg->ports[i])) {
1741             VLOG_WARN("bridge %s: %s specified twice as bridge port",
1742                       br->name, name);
1743         }
1744     }
1745     if (bridge_get_controllers(br, NULL)
1746         && !shash_find(&new_ports, br->name)) {
1747         VLOG_WARN("bridge %s: no port named %s, synthesizing one",
1748                   br->name, br->name);
1749
1750         br->synth_local_port.interfaces = &br->synth_local_ifacep;
1751         br->synth_local_port.n_interfaces = 1;
1752         br->synth_local_port.name = br->name;
1753
1754         br->synth_local_iface.name = br->name;
1755         br->synth_local_iface.type = "internal";
1756
1757         br->synth_local_ifacep = &br->synth_local_iface;
1758
1759         shash_add(&new_ports, br->name, &br->synth_local_port);
1760     }
1761
1762     /* Get rid of deleted ports.
1763      * Get rid of deleted interfaces on ports that still exist.
1764      * Update 'cfg' of ports that still exist. */
1765     HMAP_FOR_EACH_SAFE (port, next, hmap_node, &br->ports) {
1766         port->cfg = shash_find_data(&new_ports, port->name);
1767         if (!port->cfg) {
1768             port_destroy(port);
1769         } else {
1770             port_del_ifaces(port);
1771         }
1772     }
1773
1774     /* Create new ports.
1775      * Add new interfaces to existing ports. */
1776     SHASH_FOR_EACH (node, &new_ports) {
1777         struct port *port = port_lookup(br, node->name);
1778         if (!port) {
1779             struct ovsrec_port *cfg = node->data;
1780             port = port_create(br, cfg);
1781         }
1782         port_add_ifaces(port);
1783         if (list_is_empty(&port->ifaces)) {
1784             VLOG_WARN("bridge %s: port %s has no interfaces, dropping",
1785                       br->name, port->name);
1786             port_destroy(port);
1787         }
1788     }
1789     shash_destroy(&new_ports);
1790 }
1791
1792 /* Initializes 'oc' appropriately as a management service controller for
1793  * 'br'.
1794  *
1795  * The caller must free oc->target when it is no longer needed. */
1796 static void
1797 bridge_ofproto_controller_for_mgmt(const struct bridge *br,
1798                                    struct ofproto_controller *oc)
1799 {
1800     oc->target = xasprintf("punix:%s/%s.mgmt", ovs_rundir(), br->name);
1801     oc->max_backoff = 0;
1802     oc->probe_interval = 60;
1803     oc->band = OFPROTO_OUT_OF_BAND;
1804     oc->rate_limit = 0;
1805     oc->burst_limit = 0;
1806 }
1807
1808 /* Converts ovsrec_controller 'c' into an ofproto_controller in 'oc'.  */
1809 static void
1810 bridge_ofproto_controller_from_ovsrec(const struct ovsrec_controller *c,
1811                                       struct ofproto_controller *oc)
1812 {
1813     oc->target = c->target;
1814     oc->max_backoff = c->max_backoff ? *c->max_backoff / 1000 : 8;
1815     oc->probe_interval = c->inactivity_probe ? *c->inactivity_probe / 1000 : 5;
1816     oc->band = (!c->connection_mode || !strcmp(c->connection_mode, "in-band")
1817                 ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
1818     oc->rate_limit = c->controller_rate_limit ? *c->controller_rate_limit : 0;
1819     oc->burst_limit = (c->controller_burst_limit
1820                        ? *c->controller_burst_limit : 0);
1821 }
1822
1823 /* Configures the IP stack for 'br''s local interface properly according to the
1824  * configuration in 'c'.  */
1825 static void
1826 bridge_configure_local_iface_netdev(struct bridge *br,
1827                                     struct ovsrec_controller *c)
1828 {
1829     struct netdev *netdev;
1830     struct in_addr mask, gateway;
1831
1832     struct iface *local_iface;
1833     struct in_addr ip;
1834
1835     /* If there's no local interface or no IP address, give up. */
1836     local_iface = iface_from_ofp_port(br, OFPP_LOCAL);
1837     if (!local_iface || !c->local_ip || !inet_aton(c->local_ip, &ip)) {
1838         return;
1839     }
1840
1841     /* Bring up the local interface. */
1842     netdev = local_iface->netdev;
1843     netdev_turn_flags_on(netdev, NETDEV_UP, true);
1844
1845     /* Configure the IP address and netmask. */
1846     if (!c->local_netmask
1847         || !inet_aton(c->local_netmask, &mask)
1848         || !mask.s_addr) {
1849         mask.s_addr = guess_netmask(ip.s_addr);
1850     }
1851     if (!netdev_set_in4(netdev, ip, mask)) {
1852         VLOG_INFO("bridge %s: configured IP address "IP_FMT", netmask "IP_FMT,
1853                   br->name, IP_ARGS(&ip.s_addr), IP_ARGS(&mask.s_addr));
1854     }
1855
1856     /* Configure the default gateway. */
1857     if (c->local_gateway
1858         && inet_aton(c->local_gateway, &gateway)
1859         && gateway.s_addr) {
1860         if (!netdev_add_router(netdev, gateway)) {
1861             VLOG_INFO("bridge %s: configured gateway "IP_FMT,
1862                       br->name, IP_ARGS(&gateway.s_addr));
1863         }
1864     }
1865 }
1866
1867 static void
1868 bridge_configure_remotes(struct bridge *br,
1869                          const struct sockaddr_in *managers, size_t n_managers)
1870 {
1871     const char *disable_ib_str, *queue_id_str;
1872     bool disable_in_band = false;
1873     int queue_id;
1874
1875     struct ovsrec_controller **controllers;
1876     size_t n_controllers;
1877
1878     enum ofproto_fail_mode fail_mode;
1879
1880     struct ofproto_controller *ocs;
1881     size_t n_ocs;
1882     size_t i;
1883
1884     /* Check if we should disable in-band control on this bridge. */
1885     disable_ib_str = bridge_get_other_config(br->cfg, "disable-in-band");
1886     if (disable_ib_str && !strcmp(disable_ib_str, "true")) {
1887         disable_in_band = true;
1888     }
1889
1890     /* Set OpenFlow queue ID for in-band control. */
1891     queue_id_str = bridge_get_other_config(br->cfg, "in-band-queue");
1892     queue_id = queue_id_str ? strtol(queue_id_str, NULL, 10) : -1;
1893     ofproto_set_in_band_queue(br->ofproto, queue_id);
1894
1895     if (disable_in_band) {
1896         ofproto_set_extra_in_band_remotes(br->ofproto, NULL, 0);
1897     } else {
1898         ofproto_set_extra_in_band_remotes(br->ofproto, managers, n_managers);
1899     }
1900
1901     n_controllers = bridge_get_controllers(br, &controllers);
1902
1903     ocs = xmalloc((n_controllers + 1) * sizeof *ocs);
1904     n_ocs = 0;
1905
1906     bridge_ofproto_controller_for_mgmt(br, &ocs[n_ocs++]);
1907     for (i = 0; i < n_controllers; i++) {
1908         struct ovsrec_controller *c = controllers[i];
1909
1910         if (!strncmp(c->target, "punix:", 6)
1911             || !strncmp(c->target, "unix:", 5)) {
1912             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1913
1914             /* Prevent remote ovsdb-server users from accessing arbitrary Unix
1915              * domain sockets and overwriting arbitrary local files. */
1916             VLOG_ERR_RL(&rl, "bridge %s: not adding Unix domain socket "
1917                         "controller \"%s\" due to possibility for remote "
1918                         "exploit", br->name, c->target);
1919             continue;
1920         }
1921
1922         bridge_configure_local_iface_netdev(br, c);
1923         bridge_ofproto_controller_from_ovsrec(c, &ocs[n_ocs]);
1924         if (disable_in_band) {
1925             ocs[n_ocs].band = OFPROTO_OUT_OF_BAND;
1926         }
1927         n_ocs++;
1928     }
1929
1930     ofproto_set_controllers(br->ofproto, ocs, n_ocs);
1931     free(ocs[0].target); /* From bridge_ofproto_controller_for_mgmt(). */
1932     free(ocs);
1933
1934     /* Set the fail-mode. */
1935     fail_mode = !br->cfg->fail_mode
1936                 || !strcmp(br->cfg->fail_mode, "standalone")
1937                     ? OFPROTO_FAIL_STANDALONE
1938                     : OFPROTO_FAIL_SECURE;
1939     ofproto_set_fail_mode(br->ofproto, fail_mode);
1940
1941     /* Configure OpenFlow controller connection snooping. */
1942     if (!ofproto_has_snoops(br->ofproto)) {
1943         struct sset snoops;
1944
1945         sset_init(&snoops);
1946         sset_add_and_free(&snoops, xasprintf("punix:%s/%s.snoop",
1947                                              ovs_rundir(), br->name));
1948         ofproto_set_snoops(br->ofproto, &snoops);
1949         sset_destroy(&snoops);
1950     }
1951 }
1952 \f
1953 /* Port functions. */
1954
1955 static struct port *
1956 port_create(struct bridge *br, const struct ovsrec_port *cfg)
1957 {
1958     struct port *port;
1959
1960     port = xzalloc(sizeof *port);
1961     port->bridge = br;
1962     port->name = xstrdup(cfg->name);
1963     port->cfg = cfg;
1964     list_init(&port->ifaces);
1965
1966     hmap_insert(&br->ports, &port->hmap_node, hash_string(port->name, 0));
1967
1968     VLOG_INFO("created port %s on bridge %s", port->name, br->name);
1969
1970     return port;
1971 }
1972
1973 static const char *
1974 get_port_other_config(const struct ovsrec_port *port, const char *key,
1975                       const char *default_value)
1976 {
1977     const char *value;
1978
1979     value = get_ovsrec_key_value(&port->header_, &ovsrec_port_col_other_config,
1980                                  key);
1981     return value ? value : default_value;
1982 }
1983
1984 static const char *
1985 get_interface_other_config(const struct ovsrec_interface *iface,
1986                            const char *key, const char *default_value)
1987 {
1988     const char *value;
1989
1990     value = get_ovsrec_key_value(&iface->header_,
1991                                  &ovsrec_interface_col_other_config, key);
1992     return value ? value : default_value;
1993 }
1994
1995 /* Deletes interfaces from 'port' that are no longer configured for it. */
1996 static void
1997 port_del_ifaces(struct port *port)
1998 {
1999     struct iface *iface, *next;
2000     struct sset new_ifaces;
2001     size_t i;
2002
2003     /* Collect list of new interfaces. */
2004     sset_init(&new_ifaces);
2005     for (i = 0; i < port->cfg->n_interfaces; i++) {
2006         const char *name = port->cfg->interfaces[i]->name;
2007         const char *type = port->cfg->interfaces[i]->name;
2008         if (strcmp(type, "null")) {
2009             sset_add(&new_ifaces, name);
2010         }
2011     }
2012
2013     /* Get rid of deleted interfaces. */
2014     LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
2015         if (!sset_contains(&new_ifaces, iface->name)) {
2016             iface_destroy(iface);
2017         }
2018     }
2019
2020     sset_destroy(&new_ifaces);
2021 }
2022
2023 /* Adds new interfaces to 'port' and updates 'type' and 'cfg' members of
2024  * existing ones. */
2025 static void
2026 port_add_ifaces(struct port *port)
2027 {
2028     struct shash new_ifaces;
2029     struct shash_node *node;
2030     size_t i;
2031
2032     /* Collect new ifaces. */
2033     shash_init(&new_ifaces);
2034     for (i = 0; i < port->cfg->n_interfaces; i++) {
2035         const struct ovsrec_interface *cfg = port->cfg->interfaces[i];
2036         if (strcmp(cfg->type, "null")
2037             && !shash_add_once(&new_ifaces, cfg->name, cfg)) {
2038             VLOG_WARN("port %s: %s specified twice as port interface",
2039                       port->name, cfg->name);
2040             iface_set_ofport(cfg, -1);
2041         }
2042     }
2043
2044     /* Create new interfaces.
2045      * Update interface types and 'cfg' members. */
2046     SHASH_FOR_EACH (node, &new_ifaces) {
2047         const struct ovsrec_interface *cfg = node->data;
2048         const char *iface_name = node->name;
2049         struct iface *iface;
2050
2051         iface = iface_lookup(port->bridge, iface_name);
2052         if (!iface) {
2053             iface = iface_create(port, cfg);
2054         } else {
2055             iface->cfg = cfg;
2056         }
2057
2058         /* Determine interface type.  The local port always has type
2059          * "internal".  Other ports take their type from the database and
2060          * default to "system" if none is specified. */
2061         iface->type = (!strcmp(iface_name, port->bridge->name) ? "internal"
2062                        : cfg->type[0] ? cfg->type
2063                        : "system");
2064     }
2065     shash_destroy(&new_ifaces);
2066 }
2067
2068 static void
2069 port_destroy(struct port *port)
2070 {
2071     if (port) {
2072         struct bridge *br = port->bridge;
2073         struct iface *iface, *next;
2074
2075         if (br->ofproto) {
2076             ofproto_bundle_unregister(br->ofproto, port);
2077         }
2078
2079         LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
2080             iface_destroy(iface);
2081         }
2082
2083         hmap_remove(&br->ports, &port->hmap_node);
2084
2085         VLOG_INFO("destroyed port %s on bridge %s", port->name, br->name);
2086
2087         free(port->name);
2088         free(port);
2089     }
2090 }
2091
2092 static struct port *
2093 port_lookup(const struct bridge *br, const char *name)
2094 {
2095     struct port *port;
2096
2097     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_string(name, 0),
2098                              &br->ports) {
2099         if (!strcmp(port->name, name)) {
2100             return port;
2101         }
2102     }
2103     return NULL;
2104 }
2105
2106 static bool
2107 enable_lacp(struct port *port, bool *activep)
2108 {
2109     if (!port->cfg->lacp) {
2110         /* XXX when LACP implementation has been sufficiently tested, enable by
2111          * default and make active on bonded ports. */
2112         return false;
2113     } else if (!strcmp(port->cfg->lacp, "off")) {
2114         return false;
2115     } else if (!strcmp(port->cfg->lacp, "active")) {
2116         *activep = true;
2117         return true;
2118     } else if (!strcmp(port->cfg->lacp, "passive")) {
2119         *activep = false;
2120         return true;
2121     } else {
2122         VLOG_WARN("port %s: unknown LACP mode %s",
2123                   port->name, port->cfg->lacp);
2124         return false;
2125     }
2126 }
2127
2128 static struct lacp_settings *
2129 port_configure_lacp(struct port *port, struct lacp_settings *s)
2130 {
2131     const char *lacp_time;
2132     long long int custom_time;
2133     int priority;
2134
2135     if (!enable_lacp(port, &s->active)) {
2136         return NULL;
2137     }
2138
2139     s->name = port->name;
2140     memcpy(s->id, port->bridge->ea, ETH_ADDR_LEN);
2141
2142     /* Prefer bondable links if unspecified. */
2143     priority = atoi(get_port_other_config(port->cfg, "lacp-system-priority",
2144                                           "0"));
2145     s->priority = (priority > 0 && priority <= UINT16_MAX
2146                    ? priority
2147                    : UINT16_MAX - !list_is_short(&port->ifaces));
2148
2149     s->heartbeat = !strcmp(get_port_other_config(port->cfg,
2150                                                  "lacp-heartbeat",
2151                                                  "false"), "true");
2152
2153
2154     lacp_time = get_port_other_config(port->cfg, "lacp-time", "slow");
2155     custom_time = atoi(lacp_time);
2156     if (!strcmp(lacp_time, "fast")) {
2157         s->lacp_time = LACP_TIME_FAST;
2158     } else if (!strcmp(lacp_time, "slow")) {
2159         s->lacp_time = LACP_TIME_SLOW;
2160     } else if (custom_time > 0) {
2161         s->lacp_time = LACP_TIME_CUSTOM;
2162         s->custom_time = custom_time;
2163     } else {
2164         s->lacp_time = LACP_TIME_SLOW;
2165     }
2166
2167     return s;
2168 }
2169
2170 static void
2171 iface_configure_lacp(struct iface *iface, struct lacp_slave_settings *s)
2172 {
2173     int priority, portid, key;
2174
2175     portid = atoi(get_interface_other_config(iface->cfg, "lacp-port-id", "0"));
2176     priority = atoi(get_interface_other_config(iface->cfg,
2177                                                "lacp-port-priority", "0"));
2178     key = atoi(get_interface_other_config(iface->cfg, "lacp-aggregation-key",
2179                                           "0"));
2180
2181     if (portid <= 0 || portid > UINT16_MAX) {
2182         portid = iface->ofp_port;
2183     }
2184
2185     if (priority <= 0 || priority > UINT16_MAX) {
2186         priority = UINT16_MAX;
2187     }
2188
2189     if (key < 0 || key > UINT16_MAX) {
2190         key = 0;
2191     }
2192
2193     s->name = iface->name;
2194     s->id = portid;
2195     s->priority = priority;
2196     s->key = key;
2197 }
2198
2199 static void
2200 port_configure_bond(struct port *port, struct bond_settings *s,
2201                     uint32_t *bond_stable_ids)
2202 {
2203     const char *detect_s;
2204     struct iface *iface;
2205     int miimon_interval;
2206     size_t i;
2207
2208     s->name = port->name;
2209     s->balance = BM_SLB;
2210     if (port->cfg->bond_mode
2211         && !bond_mode_from_string(&s->balance, port->cfg->bond_mode)) {
2212         VLOG_WARN("port %s: unknown bond_mode %s, defaulting to %s",
2213                   port->name, port->cfg->bond_mode,
2214                   bond_mode_to_string(s->balance));
2215     }
2216
2217     miimon_interval = atoi(get_port_other_config(port->cfg,
2218                                                  "bond-miimon-interval", "0"));
2219     if (miimon_interval <= 0) {
2220         miimon_interval = 200;
2221     }
2222
2223     detect_s = get_port_other_config(port->cfg, "bond-detect-mode", "carrier");
2224     if (!strcmp(detect_s, "carrier")) {
2225         miimon_interval = 0;
2226     } else if (strcmp(detect_s, "miimon")) {
2227         VLOG_WARN("port %s: unsupported bond-detect-mode %s, "
2228                   "defaulting to carrier", port->name, detect_s);
2229         miimon_interval = 0;
2230     }
2231
2232     s->up_delay = MAX(0, port->cfg->bond_updelay);
2233     s->down_delay = MAX(0, port->cfg->bond_downdelay);
2234     s->basis = atoi(get_port_other_config(port->cfg, "bond-hash-basis", "0"));
2235     s->rebalance_interval = atoi(
2236         get_port_other_config(port->cfg, "bond-rebalance-interval", "10000"));
2237     if (s->rebalance_interval < 1000) {
2238         s->rebalance_interval = 1000;
2239     }
2240
2241     s->fake_iface = port->cfg->bond_fake_iface;
2242
2243     i = 0;
2244     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2245         long long stable_id;
2246
2247         stable_id = atoll(get_interface_other_config(iface->cfg,
2248                                                      "bond-stable-id", "0"));
2249         if (stable_id <= 0 || stable_id >= UINT32_MAX) {
2250             stable_id = iface->ofp_port;
2251         }
2252         bond_stable_ids[i++] = stable_id;
2253
2254         netdev_set_miimon_interval(iface->netdev, miimon_interval);
2255     }
2256 }
2257 \f
2258 /* Interface functions. */
2259
2260 static struct iface *
2261 iface_create(struct port *port, const struct ovsrec_interface *if_cfg)
2262 {
2263     struct bridge *br = port->bridge;
2264     struct iface *iface;
2265     char *name = if_cfg->name;
2266
2267     iface = xzalloc(sizeof *iface);
2268     iface->port = port;
2269     iface->name = xstrdup(name);
2270     iface->ofp_port = -1;
2271     iface->tag = tag_create_random();
2272     iface->netdev = NULL;
2273     iface->cfg = if_cfg;
2274
2275     hmap_insert(&br->iface_by_name, &iface->name_node, hash_string(name, 0));
2276
2277     list_push_back(&port->ifaces, &iface->port_elem);
2278
2279     VLOG_DBG("attached network device %s to port %s", iface->name, port->name);
2280
2281     return iface;
2282 }
2283
2284 static void
2285 iface_destroy(struct iface *iface)
2286 {
2287     if (iface) {
2288         struct port *port = iface->port;
2289         struct bridge *br = port->bridge;
2290
2291         if (br->ofproto && iface->ofp_port >= 0) {
2292             ofproto_port_unregister(br->ofproto, iface->ofp_port);
2293         }
2294
2295         if (iface->ofp_port >= 0) {
2296             hmap_remove(&br->ifaces, &iface->ofp_port_node);
2297         }
2298
2299         list_remove(&iface->port_elem);
2300         hmap_remove(&br->iface_by_name, &iface->name_node);
2301
2302         netdev_close(iface->netdev);
2303
2304         free(iface->name);
2305         free(iface);
2306     }
2307 }
2308
2309 static struct iface *
2310 iface_lookup(const struct bridge *br, const char *name)
2311 {
2312     struct iface *iface;
2313
2314     HMAP_FOR_EACH_WITH_HASH (iface, name_node, hash_string(name, 0),
2315                              &br->iface_by_name) {
2316         if (!strcmp(iface->name, name)) {
2317             return iface;
2318         }
2319     }
2320
2321     return NULL;
2322 }
2323
2324 static struct iface *
2325 iface_find(const char *name)
2326 {
2327     const struct bridge *br;
2328
2329     HMAP_FOR_EACH (br, node, &all_bridges) {
2330         struct iface *iface = iface_lookup(br, name);
2331
2332         if (iface) {
2333             return iface;
2334         }
2335     }
2336     return NULL;
2337 }
2338
2339 static struct iface *
2340 iface_from_ofp_port(const struct bridge *br, uint16_t ofp_port)
2341 {
2342     struct iface *iface;
2343
2344     HMAP_FOR_EACH_IN_BUCKET (iface, ofp_port_node,
2345                              hash_int(ofp_port, 0), &br->ifaces) {
2346         if (iface->ofp_port == ofp_port) {
2347             return iface;
2348         }
2349     }
2350     return NULL;
2351 }
2352
2353 /* Set Ethernet address of 'iface', if one is specified in the configuration
2354  * file. */
2355 static void
2356 iface_set_mac(struct iface *iface)
2357 {
2358     uint8_t ea[ETH_ADDR_LEN];
2359
2360     if (!strcmp(iface->type, "internal")
2361         && iface->cfg->mac && eth_addr_from_string(iface->cfg->mac, ea)) {
2362         if (iface->ofp_port == OFPP_LOCAL) {
2363             VLOG_ERR("interface %s: ignoring mac in Interface record "
2364                      "(use Bridge record to set local port's mac)",
2365                      iface->name);
2366         } else if (eth_addr_is_multicast(ea)) {
2367             VLOG_ERR("interface %s: cannot set MAC to multicast address",
2368                      iface->name);
2369         } else {
2370             int error = netdev_set_etheraddr(iface->netdev, ea);
2371             if (error) {
2372                 VLOG_ERR("interface %s: setting MAC failed (%s)",
2373                          iface->name, strerror(error));
2374             }
2375         }
2376     }
2377 }
2378
2379 /* Sets the ofport column of 'if_cfg' to 'ofport'. */
2380 static void
2381 iface_set_ofport(const struct ovsrec_interface *if_cfg, int64_t ofport)
2382 {
2383     if (if_cfg && !ovsdb_idl_row_is_synthetic(&if_cfg->header_)) {
2384         ovsrec_interface_set_ofport(if_cfg, &ofport, 1);
2385     }
2386 }
2387
2388 /* Adds the 'n' key-value pairs in 'keys' in 'values' to 'shash'.
2389  *
2390  * The value strings in '*shash' are taken directly from values[], not copied,
2391  * so the caller should not modify or free them. */
2392 static void
2393 shash_from_ovs_idl_map(char **keys, char **values, size_t n,
2394                        struct shash *shash)
2395 {
2396     size_t i;
2397
2398     shash_init(shash);
2399     for (i = 0; i < n; i++) {
2400         shash_add(shash, keys[i], values[i]);
2401     }
2402 }
2403
2404 /* Creates 'keys' and 'values' arrays from 'shash'.
2405  *
2406  * Sets 'keys' and 'values' to heap allocated arrays representing the key-value
2407  * pairs in 'shash'.  The caller takes ownership of 'keys' and 'values'.  They
2408  * are populated with with strings taken directly from 'shash' and thus have
2409  * the same ownership of the key-value pairs in shash.
2410  */
2411 static void
2412 shash_to_ovs_idl_map(struct shash *shash,
2413                      char ***keys, char ***values, size_t *n)
2414 {
2415     size_t i, count;
2416     char **k, **v;
2417     struct shash_node *sn;
2418
2419     count = shash_count(shash);
2420
2421     k = xmalloc(count * sizeof *k);
2422     v = xmalloc(count * sizeof *v);
2423
2424     i = 0;
2425     SHASH_FOR_EACH(sn, shash) {
2426         k[i] = sn->name;
2427         v[i] = sn->data;
2428         i++;
2429     }
2430
2431     *n      = count;
2432     *keys   = k;
2433     *values = v;
2434 }
2435
2436 struct iface_delete_queues_cbdata {
2437     struct netdev *netdev;
2438     const struct ovsdb_datum *queues;
2439 };
2440
2441 static bool
2442 queue_ids_include(const struct ovsdb_datum *queues, int64_t target)
2443 {
2444     union ovsdb_atom atom;
2445
2446     atom.integer = target;
2447     return ovsdb_datum_find_key(queues, &atom, OVSDB_TYPE_INTEGER) != UINT_MAX;
2448 }
2449
2450 static void
2451 iface_delete_queues(unsigned int queue_id,
2452                     const struct shash *details OVS_UNUSED, void *cbdata_)
2453 {
2454     struct iface_delete_queues_cbdata *cbdata = cbdata_;
2455
2456     if (!queue_ids_include(cbdata->queues, queue_id)) {
2457         netdev_delete_queue(cbdata->netdev, queue_id);
2458     }
2459 }
2460
2461 static void
2462 iface_configure_qos(struct iface *iface, const struct ovsrec_qos *qos)
2463 {
2464     if (!qos || qos->type[0] == '\0' || qos->n_queues < 1) {
2465         netdev_set_qos(iface->netdev, NULL, NULL);
2466     } else {
2467         struct iface_delete_queues_cbdata cbdata;
2468         struct shash details;
2469         size_t i;
2470
2471         /* Configure top-level Qos for 'iface'. */
2472         shash_from_ovs_idl_map(qos->key_other_config, qos->value_other_config,
2473                                qos->n_other_config, &details);
2474         netdev_set_qos(iface->netdev, qos->type, &details);
2475         shash_destroy(&details);
2476
2477         /* Deconfigure queues that were deleted. */
2478         cbdata.netdev = iface->netdev;
2479         cbdata.queues = ovsrec_qos_get_queues(qos, OVSDB_TYPE_INTEGER,
2480                                               OVSDB_TYPE_UUID);
2481         netdev_dump_queues(iface->netdev, iface_delete_queues, &cbdata);
2482
2483         /* Configure queues for 'iface'. */
2484         for (i = 0; i < qos->n_queues; i++) {
2485             const struct ovsrec_queue *queue = qos->value_queues[i];
2486             unsigned int queue_id = qos->key_queues[i];
2487
2488             shash_from_ovs_idl_map(queue->key_other_config,
2489                                    queue->value_other_config,
2490                                    queue->n_other_config, &details);
2491             netdev_set_queue(iface->netdev, queue_id, &details);
2492             shash_destroy(&details);
2493         }
2494     }
2495
2496     netdev_set_policing(iface->netdev,
2497                         iface->cfg->ingress_policing_rate,
2498                         iface->cfg->ingress_policing_burst);
2499 }
2500
2501 static void
2502 iface_configure_cfm(struct iface *iface)
2503 {
2504     size_t i;
2505     struct cfm cfm;
2506     uint16_t *remote_mps;
2507     struct ovsrec_monitor *mon;
2508     uint8_t maid[CCM_MAID_LEN];
2509
2510     mon = iface->cfg->monitor;
2511
2512     if (!mon) {
2513         ofproto_port_clear_cfm(iface->port->bridge->ofproto, iface->ofp_port);
2514         return;
2515     }
2516
2517     if (!cfm_generate_maid(mon->md_name, mon->ma_name, maid)) {
2518         VLOG_WARN("interface %s: Failed to generate MAID.", iface->name);
2519         return;
2520     }
2521
2522     cfm.mpid     = mon->mpid;
2523     cfm.interval = mon->interval ? *mon->interval : 1000;
2524     cfm.name = iface->name;
2525
2526     memcpy(cfm.maid, maid, sizeof cfm.maid);
2527
2528     remote_mps = xzalloc(mon->n_remote_mps * sizeof *remote_mps);
2529     for(i = 0; i < mon->n_remote_mps; i++) {
2530         remote_mps[i] = mon->remote_mps[i]->mpid;
2531     }
2532
2533     ofproto_port_set_cfm(iface->port->bridge->ofproto, iface->ofp_port,
2534                          &cfm, remote_mps, mon->n_remote_mps);
2535     free(remote_mps);
2536 }
2537
2538 /* Read carrier or miimon status directly from 'iface''s netdev, according to
2539  * how 'iface''s port is configured.
2540  *
2541  * Returns true if 'iface' is up, false otherwise. */
2542 static bool
2543 iface_get_carrier(const struct iface *iface)
2544 {
2545     /* XXX */
2546     return netdev_get_carrier(iface->netdev);
2547 }
2548
2549 /* Returns true if 'iface' is synthetic, that is, if we constructed it locally
2550  * instead of obtaining it from the database. */
2551 static bool
2552 iface_is_synthetic(const struct iface *iface)
2553 {
2554     return ovsdb_idl_row_is_synthetic(&iface->cfg->header_);
2555 }
2556 \f
2557 /* Port mirroring. */
2558
2559 static struct mirror *
2560 mirror_find_by_uuid(struct bridge *br, const struct uuid *uuid)
2561 {
2562     struct mirror *m;
2563
2564     HMAP_FOR_EACH_IN_BUCKET (m, hmap_node, uuid_hash(uuid), &br->mirrors) {
2565         if (uuid_equals(uuid, &m->uuid)) {
2566             return m;
2567         }
2568     }
2569     return NULL;
2570 }
2571
2572 static void
2573 bridge_configure_mirrors(struct bridge *br)
2574 {
2575     const struct ovsdb_datum *mc;
2576     unsigned long *flood_vlans;
2577     struct mirror *m, *next;
2578     size_t i;
2579
2580     /* Get rid of deleted mirrors. */
2581     mc = ovsrec_bridge_get_mirrors(br->cfg, OVSDB_TYPE_UUID);
2582     HMAP_FOR_EACH_SAFE (m, next, hmap_node, &br->mirrors) {
2583         union ovsdb_atom atom;
2584
2585         atom.uuid = m->uuid;
2586         if (ovsdb_datum_find_key(mc, &atom, OVSDB_TYPE_UUID) == UINT_MAX) {
2587             mirror_destroy(m);
2588         }
2589     }
2590
2591     /* Add new mirrors and reconfigure existing ones. */
2592     for (i = 0; i < br->cfg->n_mirrors; i++) {
2593         const struct ovsrec_mirror *cfg = br->cfg->mirrors[i];
2594         struct mirror *m = mirror_find_by_uuid(br, &cfg->header_.uuid);
2595         if (!m) {
2596             m = mirror_create(br, cfg);
2597         }
2598         if (!mirror_configure(m, cfg)) {
2599             mirror_destroy(m);
2600         }
2601     }
2602
2603     /* Update flooded vlans (for RSPAN). */
2604     flood_vlans = vlan_bitmap_from_array(br->cfg->flood_vlans,
2605                                          br->cfg->n_flood_vlans);
2606     ofproto_set_flood_vlans(br->ofproto, flood_vlans);
2607     bitmap_free(flood_vlans);
2608 }
2609
2610 static struct mirror *
2611 mirror_create(struct bridge *br, const struct ovsrec_mirror *cfg)
2612 {
2613     struct mirror *m;
2614
2615     m = xzalloc(sizeof *m);
2616     m->uuid = cfg->header_.uuid;
2617     hmap_insert(&br->mirrors, &m->hmap_node, uuid_hash(&m->uuid));
2618     m->bridge = br;
2619     m->name = xstrdup(cfg->name);
2620
2621     return m;
2622 }
2623
2624 static void
2625 mirror_destroy(struct mirror *m)
2626 {
2627     if (m) {
2628         struct bridge *br = m->bridge;
2629
2630         if (br->ofproto) {
2631             ofproto_mirror_unregister(br->ofproto, m);
2632         }
2633
2634         hmap_remove(&br->mirrors, &m->hmap_node);
2635         free(m->name);
2636         free(m);
2637     }
2638 }
2639
2640 static void
2641 mirror_collect_ports(struct mirror *m,
2642                      struct ovsrec_port **in_ports, int n_in_ports,
2643                      void ***out_portsp, size_t *n_out_portsp)
2644 {
2645     void **out_ports = xmalloc(n_in_ports * sizeof *out_ports);
2646     size_t n_out_ports = 0;
2647     size_t i;
2648
2649     for (i = 0; i < n_in_ports; i++) {
2650         const char *name = in_ports[i]->name;
2651         struct port *port = port_lookup(m->bridge, name);
2652         if (port) {
2653             out_ports[n_out_ports++] = port;
2654         } else {
2655             VLOG_WARN("bridge %s: mirror %s cannot match on nonexistent "
2656                       "port %s", m->bridge->name, m->name, name);
2657         }
2658     }
2659     *out_portsp = out_ports;
2660     *n_out_portsp = n_out_ports;
2661 }
2662
2663 static bool
2664 mirror_configure(struct mirror *m, const struct ovsrec_mirror *cfg)
2665 {
2666     struct ofproto_mirror_settings s;
2667
2668     /* Set name. */
2669     if (strcmp(cfg->name, m->name)) {
2670         free(m->name);
2671         m->name = xstrdup(cfg->name);
2672     }
2673     s.name = m->name;
2674
2675     /* Get output port or VLAN. */
2676     if (cfg->output_port) {
2677         s.out_bundle = port_lookup(m->bridge, cfg->output_port->name);
2678         if (!s.out_bundle) {
2679             VLOG_ERR("bridge %s: mirror %s outputs to port not on bridge",
2680                      m->bridge->name, m->name);
2681             return false;
2682         }
2683         s.out_vlan = UINT16_MAX;
2684
2685         if (cfg->output_vlan) {
2686             VLOG_ERR("bridge %s: mirror %s specifies both output port and "
2687                      "output vlan; ignoring output vlan",
2688                      m->bridge->name, m->name);
2689         }
2690     } else if (cfg->output_vlan) {
2691         /* The database should prevent invalid VLAN values. */
2692         s.out_bundle = NULL;
2693         s.out_vlan = *cfg->output_vlan;
2694     } else {
2695         VLOG_ERR("bridge %s: mirror %s does not specify output; ignoring",
2696                  m->bridge->name, m->name);
2697         return false;
2698     }
2699
2700     /* Get port selection. */
2701     if (cfg->select_all) {
2702         size_t n_ports = hmap_count(&m->bridge->ports);
2703         void **ports = xmalloc(n_ports * sizeof *ports);
2704         struct port *port;
2705         size_t i;
2706
2707         i = 0;
2708         HMAP_FOR_EACH (port, hmap_node, &m->bridge->ports) {
2709             ports[i++] = port;
2710         }
2711
2712         s.srcs = ports;
2713         s.n_srcs = n_ports;
2714
2715         s.dsts = ports;
2716         s.n_dsts = n_ports;
2717     } else {
2718         /* Get ports, dropping ports that don't exist.
2719          * The IDL ensures that there are no duplicates. */
2720         mirror_collect_ports(m, cfg->select_src_port, cfg->n_select_src_port,
2721                              &s.srcs, &s.n_srcs);
2722         mirror_collect_ports(m, cfg->select_dst_port, cfg->n_select_dst_port,
2723                              &s.dsts, &s.n_dsts);
2724
2725     }
2726
2727     /* Get VLAN selection. */
2728     s.src_vlans = vlan_bitmap_from_array(cfg->select_vlan, cfg->n_select_vlan);
2729
2730     /* Configure. */
2731     ofproto_mirror_register(m->bridge->ofproto, m, &s);
2732
2733     /* Clean up. */
2734     if (s.srcs != s.dsts) {
2735         free(s.dsts);
2736     }
2737     free(s.srcs);
2738     free(s.src_vlans);
2739
2740     return true;
2741 }