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