json: Move from lib to include/openvswitch.
[cascardo/ovs.git] / vswitchd / bridge.c
1 /* Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
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 <errno.h>
19 #include <inttypes.h>
20 #include <stdlib.h>
21
22 #include "async-append.h"
23 #include "bfd.h"
24 #include "bitmap.h"
25 #include "cfm.h"
26 #include "connectivity.h"
27 #include "coverage.h"
28 #include "daemon.h"
29 #include "dirs.h"
30 #include "dpif.h"
31 #include "hash.h"
32 #include "openvswitch/hmap.h"
33 #include "hmapx.h"
34 #include "if-notifier.h"
35 #include "jsonrpc.h"
36 #include "lacp.h"
37 #include "lib/netdev-dpdk.h"
38 #include "mac-learning.h"
39 #include "mcast-snooping.h"
40 #include "netdev.h"
41 #include "nx-match.h"
42 #include "ofproto/bond.h"
43 #include "ofproto/ofproto.h"
44 #include "openvswitch/dynamic-string.h"
45 #include "openvswitch/list.h"
46 #include "openvswitch/meta-flow.h"
47 #include "openvswitch/ofp-print.h"
48 #include "openvswitch/ofp-util.h"
49 #include "openvswitch/ofpbuf.h"
50 #include "openvswitch/vlog.h"
51 #include "ovs-lldp.h"
52 #include "ovs-numa.h"
53 #include "packets.h"
54 #include "poll-loop.h"
55 #include "seq.h"
56 #include "sflow_api.h"
57 #include "sha1.h"
58 #include "openvswitch/shash.h"
59 #include "smap.h"
60 #include "socket-util.h"
61 #include "stream.h"
62 #include "stream-ssl.h"
63 #include "sset.h"
64 #include "system-stats.h"
65 #include "timeval.h"
66 #include "util.h"
67 #include "unixctl.h"
68 #include "lib/vswitch-idl.h"
69 #include "xenserver.h"
70 #include "vlan-bitmap.h"
71
72 VLOG_DEFINE_THIS_MODULE(bridge);
73
74 COVERAGE_DEFINE(bridge_reconfigure);
75
76 struct iface {
77     /* These members are always valid.
78      *
79      * They are immutable: they never change between iface_create() and
80      * iface_destroy(). */
81     struct ovs_list port_elem;  /* Element in struct port's "ifaces" list. */
82     struct hmap_node name_node; /* In struct bridge's "iface_by_name" hmap. */
83     struct hmap_node ofp_port_node; /* In struct bridge's "ifaces" hmap. */
84     struct port *port;          /* Containing port. */
85     char *name;                 /* Host network device name. */
86     struct netdev *netdev;      /* Network device. */
87     ofp_port_t ofp_port;        /* OpenFlow port number. */
88     uint64_t change_seq;
89
90     /* These members are valid only within bridge_reconfigure(). */
91     const char *type;           /* Usually same as cfg->type. */
92     const char *netdev_type;    /* type that should be used for netdev_open. */
93     const struct ovsrec_interface *cfg;
94 };
95
96 struct mirror {
97     struct uuid uuid;           /* UUID of this "mirror" record in database. */
98     struct hmap_node hmap_node; /* In struct bridge's "mirrors" hmap. */
99     struct bridge *bridge;
100     char *name;
101     const struct ovsrec_mirror *cfg;
102 };
103
104 struct port {
105     struct hmap_node hmap_node; /* Element in struct bridge's "ports" hmap. */
106     struct bridge *bridge;
107     char *name;
108
109     const struct ovsrec_port *cfg;
110
111     /* An ordinary bridge port has 1 interface.
112      * A bridge port for bonding has at least 2 interfaces. */
113     struct ovs_list ifaces;    /* List of "struct iface"s. */
114 };
115
116 struct bridge {
117     struct hmap_node node;      /* In 'all_bridges'. */
118     char *name;                 /* User-specified arbitrary name. */
119     char *type;                 /* Datapath type. */
120     struct eth_addr ea;         /* Bridge Ethernet Address. */
121     struct eth_addr default_ea; /* Default MAC. */
122     const struct ovsrec_bridge *cfg;
123
124     /* OpenFlow switch processing. */
125     struct ofproto *ofproto;    /* OpenFlow switch. */
126
127     /* Bridge ports. */
128     struct hmap ports;          /* "struct port"s indexed by name. */
129     struct hmap ifaces;         /* "struct iface"s indexed by ofp_port. */
130     struct hmap iface_by_name;  /* "struct iface"s indexed by name. */
131
132     /* Port mirroring. */
133     struct hmap mirrors;        /* "struct mirror" indexed by UUID. */
134
135     /* Auto Attach */
136     struct hmap mappings;       /* "struct" indexed by UUID */
137
138     /* Used during reconfiguration. */
139     struct shash wanted_ports;
140
141     /* Synthetic local port if necessary. */
142     struct ovsrec_port synth_local_port;
143     struct ovsrec_interface synth_local_iface;
144     struct ovsrec_interface *synth_local_ifacep;
145 };
146
147 struct aa_mapping {
148     struct hmap_node hmap_node; /* In struct bridge's "mappings" hmap. */
149     struct bridge *bridge;
150     uint32_t isid;
151     uint16_t vlan;
152     char *br_name;
153 };
154
155 /* All bridges, indexed by name. */
156 static struct hmap all_bridges = HMAP_INITIALIZER(&all_bridges);
157
158 /* OVSDB IDL used to obtain configuration. */
159 static struct ovsdb_idl *idl;
160
161 /* We want to complete daemonization, fully detaching from our parent process,
162  * only after we have completed our initial configuration, committed our state
163  * to the database, and received confirmation back from the database server
164  * that it applied the commit.  This allows our parent process to know that,
165  * post-detach, ephemeral fields such as datapath-id and ofport are very likely
166  * to have already been filled in.  (It is only "very likely" rather than
167  * certain because there is always a slim possibility that the transaction will
168  * fail or that some other client has added new bridges, ports, etc. while
169  * ovs-vswitchd was configuring using an old configuration.)
170  *
171  * We only need to do this once for our initial configuration at startup, so
172  * 'initial_config_done' tracks whether we've already done it.  While we are
173  * waiting for a response to our commit, 'daemonize_txn' tracks the transaction
174  * itself and is otherwise NULL. */
175 static bool initial_config_done;
176 static struct ovsdb_idl_txn *daemonize_txn;
177
178 /* Most recently processed IDL sequence number. */
179 static unsigned int idl_seqno;
180
181 /* Track changes to port connectivity. */
182 static uint64_t connectivity_seqno = LLONG_MIN;
183
184 /* Status update to database.
185  *
186  * Some information in the database must be kept as up-to-date as possible to
187  * allow controllers to respond rapidly to network outages.  Those status are
188  * updated via the 'status_txn'.
189  *
190  * We use the global connectivity sequence number to detect the status change.
191  * Also, to prevent the status update from sending too much to the database,
192  * we check the return status of each update transaction and do not start new
193  * update if the previous transaction status is 'TXN_INCOMPLETE'.
194  *
195  * 'statux_txn' is NULL if there is no ongoing status update.
196  *
197  * If the previous database transaction was failed (is not 'TXN_SUCCESS',
198  * 'TXN_UNCHANGED' or 'TXN_INCOMPLETE'), 'status_txn_try_again' is set to true,
199  * which will cause the main thread wake up soon and retry the status update.
200  */
201 static struct ovsdb_idl_txn *status_txn;
202 static bool status_txn_try_again;
203
204 /* When the status update transaction returns 'TXN_INCOMPLETE', should register a
205  * timeout in 'STATUS_CHECK_AGAIN_MSEC' to check again. */
206 #define STATUS_CHECK_AGAIN_MSEC 100
207
208 /* Statistics update to database. */
209 static struct ovsdb_idl_txn *stats_txn;
210
211 /* Each time this timer expires, the bridge fetches interface and mirror
212  * statistics and pushes them into the database. */
213 static int stats_timer_interval;
214 static long long int stats_timer = LLONG_MIN;
215
216 /* Each time this timer expires, the bridge fetches the list of port/VLAN
217  * membership that has been modified by the AA.
218  */
219 #define AA_REFRESH_INTERVAL (1000) /* In milliseconds. */
220 static long long int aa_refresh_timer = LLONG_MIN;
221
222 /* Whenever system interfaces are added, removed or change state, the bridge
223  * will be reconfigured.
224  */
225 static struct if_notifier *ifnotifier;
226 static bool ifaces_changed = false;
227
228 static void add_del_bridges(const struct ovsrec_open_vswitch *);
229 static void bridge_run__(void);
230 static void bridge_create(const struct ovsrec_bridge *);
231 static void bridge_destroy(struct bridge *, bool del);
232 static struct bridge *bridge_lookup(const char *name);
233 static unixctl_cb_func bridge_unixctl_dump_flows;
234 static unixctl_cb_func bridge_unixctl_reconnect;
235 static size_t bridge_get_controllers(const struct bridge *br,
236                                      struct ovsrec_controller ***controllersp);
237 static void bridge_collect_wanted_ports(struct bridge *,
238                                         struct shash *wanted_ports);
239 static void bridge_delete_ofprotos(void);
240 static void bridge_delete_or_reconfigure_ports(struct bridge *);
241 static void bridge_del_ports(struct bridge *,
242                              const struct shash *wanted_ports);
243 static void bridge_add_ports(struct bridge *,
244                              const struct shash *wanted_ports);
245
246 static void bridge_configure_datapath_id(struct bridge *);
247 static void bridge_configure_netflow(struct bridge *);
248 static void bridge_configure_forward_bpdu(struct bridge *);
249 static void bridge_configure_mac_table(struct bridge *);
250 static void bridge_configure_mcast_snooping(struct bridge *);
251 static void bridge_configure_sflow(struct bridge *, int *sflow_bridge_number);
252 static void bridge_configure_ipfix(struct bridge *);
253 static void bridge_configure_spanning_tree(struct bridge *);
254 static void bridge_configure_tables(struct bridge *);
255 static void bridge_configure_dp_desc(struct bridge *);
256 static void bridge_configure_aa(struct bridge *);
257 static void bridge_aa_refresh_queued(struct bridge *);
258 static bool bridge_aa_need_refresh(struct bridge *);
259 static void bridge_configure_remotes(struct bridge *,
260                                      const struct sockaddr_in *managers,
261                                      size_t n_managers);
262 static void bridge_pick_local_hw_addr(struct bridge *, struct eth_addr *ea,
263                                       struct iface **hw_addr_iface);
264 static uint64_t bridge_pick_datapath_id(struct bridge *,
265                                         const struct eth_addr bridge_ea,
266                                         struct iface *hw_addr_iface);
267 static uint64_t dpid_from_hash(const void *, size_t nbytes);
268 static bool bridge_has_bond_fake_iface(const struct bridge *,
269                                        const char *name);
270 static bool port_is_bond_fake_iface(const struct port *);
271
272 static unixctl_cb_func qos_unixctl_show_types;
273 static unixctl_cb_func qos_unixctl_show;
274
275 static struct port *port_create(struct bridge *, const struct ovsrec_port *);
276 static void port_del_ifaces(struct port *);
277 static void port_destroy(struct port *);
278 static struct port *port_lookup(const struct bridge *, const char *name);
279 static void port_configure(struct port *);
280 static struct lacp_settings *port_configure_lacp(struct port *,
281                                                  struct lacp_settings *);
282 static void port_configure_bond(struct port *, struct bond_settings *);
283 static bool port_is_synthetic(const struct port *);
284
285 static void reconfigure_system_stats(const struct ovsrec_open_vswitch *);
286 static void run_system_stats(void);
287
288 static void bridge_configure_mirrors(struct bridge *);
289 static struct mirror *mirror_create(struct bridge *,
290                                     const struct ovsrec_mirror *);
291 static void mirror_destroy(struct mirror *);
292 static bool mirror_configure(struct mirror *);
293 static void mirror_refresh_stats(struct mirror *);
294
295 static void iface_configure_lacp(struct iface *, struct lacp_slave_settings *);
296 static bool iface_create(struct bridge *, const struct ovsrec_interface *,
297                          const struct ovsrec_port *);
298 static bool iface_is_internal(const struct ovsrec_interface *iface,
299                               const struct ovsrec_bridge *br);
300 static const char *iface_get_type(const struct ovsrec_interface *,
301                                   const struct ovsrec_bridge *);
302 static void iface_destroy(struct iface *);
303 static void iface_destroy__(struct iface *);
304 static struct iface *iface_lookup(const struct bridge *, const char *name);
305 static struct iface *iface_find(const char *name);
306 static struct iface *iface_from_ofp_port(const struct bridge *,
307                                          ofp_port_t ofp_port);
308 static void iface_set_mac(const struct bridge *, const struct port *, struct iface *);
309 static void iface_set_ofport(const struct ovsrec_interface *, ofp_port_t ofport);
310 static void iface_clear_db_record(const struct ovsrec_interface *if_cfg, char *errp);
311 static void iface_configure_qos(struct iface *, const struct ovsrec_qos *);
312 static void iface_configure_cfm(struct iface *);
313 static void iface_refresh_cfm_stats(struct iface *);
314 static void iface_refresh_stats(struct iface *);
315 static void iface_refresh_netdev_status(struct iface *);
316 static void iface_refresh_ofproto_status(struct iface *);
317 static bool iface_is_synthetic(const struct iface *);
318 static ofp_port_t iface_get_requested_ofp_port(
319     const struct ovsrec_interface *);
320 static ofp_port_t iface_pick_ofport(const struct ovsrec_interface *);
321
322
323 static void discover_types(const struct ovsrec_open_vswitch *cfg);
324
325 static void
326 bridge_init_ofproto(const struct ovsrec_open_vswitch *cfg)
327 {
328     struct shash iface_hints;
329     static bool initialized = false;
330     int i;
331
332     if (initialized) {
333         return;
334     }
335
336     shash_init(&iface_hints);
337
338     if (cfg) {
339         for (i = 0; i < cfg->n_bridges; i++) {
340             const struct ovsrec_bridge *br_cfg = cfg->bridges[i];
341             int j;
342
343             for (j = 0; j < br_cfg->n_ports; j++) {
344                 struct ovsrec_port *port_cfg = br_cfg->ports[j];
345                 int k;
346
347                 for (k = 0; k < port_cfg->n_interfaces; k++) {
348                     struct ovsrec_interface *if_cfg = port_cfg->interfaces[k];
349                     struct iface_hint *iface_hint;
350
351                     iface_hint = xmalloc(sizeof *iface_hint);
352                     iface_hint->br_name = br_cfg->name;
353                     iface_hint->br_type = br_cfg->datapath_type;
354                     iface_hint->ofp_port = iface_pick_ofport(if_cfg);
355
356                     shash_add(&iface_hints, if_cfg->name, iface_hint);
357                 }
358             }
359         }
360     }
361
362     ofproto_init(&iface_hints);
363
364     shash_destroy_free_data(&iface_hints);
365     initialized = true;
366 }
367
368 static void
369 if_change_cb(void *aux OVS_UNUSED)
370 {
371     ifaces_changed = true;
372 }
373 \f
374 /* Public functions. */
375
376 /* Initializes the bridge module, configuring it to obtain its configuration
377  * from an OVSDB server accessed over 'remote', which should be a string in a
378  * form acceptable to ovsdb_idl_create(). */
379 void
380 bridge_init(const char *remote)
381 {
382     /* Create connection to database. */
383     idl = ovsdb_idl_create(remote, &ovsrec_idl_class, true, true);
384     idl_seqno = ovsdb_idl_get_seqno(idl);
385     ovsdb_idl_set_lock(idl, "ovs_vswitchd");
386     ovsdb_idl_verify_write_only(idl);
387
388     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_cur_cfg);
389     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_statistics);
390     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_datapath_types);
391     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_iface_types);
392     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_external_ids);
393     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_ovs_version);
394     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_db_version);
395     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_system_type);
396     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_system_version);
397
398     ovsdb_idl_omit_alert(idl, &ovsrec_bridge_col_datapath_id);
399     ovsdb_idl_omit_alert(idl, &ovsrec_bridge_col_datapath_version);
400     ovsdb_idl_omit_alert(idl, &ovsrec_bridge_col_status);
401     ovsdb_idl_omit_alert(idl, &ovsrec_bridge_col_rstp_status);
402     ovsdb_idl_omit_alert(idl, &ovsrec_bridge_col_stp_enable);
403     ovsdb_idl_omit_alert(idl, &ovsrec_bridge_col_rstp_enable);
404     ovsdb_idl_omit(idl, &ovsrec_bridge_col_external_ids);
405
406     ovsdb_idl_omit_alert(idl, &ovsrec_port_col_status);
407     ovsdb_idl_omit_alert(idl, &ovsrec_port_col_rstp_status);
408     ovsdb_idl_omit_alert(idl, &ovsrec_port_col_rstp_statistics);
409     ovsdb_idl_omit_alert(idl, &ovsrec_port_col_statistics);
410     ovsdb_idl_omit_alert(idl, &ovsrec_port_col_bond_active_slave);
411     ovsdb_idl_omit(idl, &ovsrec_port_col_external_ids);
412     ovsdb_idl_omit_alert(idl, &ovsrec_port_col_trunks);
413     ovsdb_idl_omit_alert(idl, &ovsrec_port_col_vlan_mode);
414     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_admin_state);
415     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_duplex);
416     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_link_speed);
417     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_link_state);
418     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_link_resets);
419     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_mac_in_use);
420     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_ifindex);
421     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_mtu);
422     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_ofport);
423     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_statistics);
424     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_status);
425     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_cfm_fault);
426     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_cfm_fault_status);
427     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_cfm_remote_mpids);
428     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_cfm_flap_count);
429     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_cfm_health);
430     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_cfm_remote_opstate);
431     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_bfd_status);
432     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_lacp_current);
433     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_error);
434     ovsdb_idl_omit(idl, &ovsrec_interface_col_external_ids);
435
436     ovsdb_idl_omit_alert(idl, &ovsrec_controller_col_is_connected);
437     ovsdb_idl_omit_alert(idl, &ovsrec_controller_col_role);
438     ovsdb_idl_omit_alert(idl, &ovsrec_controller_col_status);
439     ovsdb_idl_omit(idl, &ovsrec_controller_col_external_ids);
440
441     ovsdb_idl_omit(idl, &ovsrec_qos_col_external_ids);
442
443     ovsdb_idl_omit(idl, &ovsrec_queue_col_external_ids);
444
445     ovsdb_idl_omit(idl, &ovsrec_mirror_col_external_ids);
446     ovsdb_idl_omit_alert(idl, &ovsrec_mirror_col_statistics);
447
448     ovsdb_idl_omit(idl, &ovsrec_netflow_col_external_ids);
449     ovsdb_idl_omit(idl, &ovsrec_sflow_col_external_ids);
450     ovsdb_idl_omit(idl, &ovsrec_ipfix_col_external_ids);
451     ovsdb_idl_omit(idl, &ovsrec_flow_sample_collector_set_col_external_ids);
452
453     ovsdb_idl_omit(idl, &ovsrec_manager_col_external_ids);
454     ovsdb_idl_omit(idl, &ovsrec_manager_col_inactivity_probe);
455     ovsdb_idl_omit(idl, &ovsrec_manager_col_is_connected);
456     ovsdb_idl_omit(idl, &ovsrec_manager_col_max_backoff);
457     ovsdb_idl_omit(idl, &ovsrec_manager_col_status);
458
459     ovsdb_idl_omit(idl, &ovsrec_ssl_col_external_ids);
460
461     /* Register unixctl commands. */
462     unixctl_command_register("qos/show-types", "interface", 1, 1,
463                              qos_unixctl_show_types, NULL);
464     unixctl_command_register("qos/show", "interface", 1, 1,
465                              qos_unixctl_show, NULL);
466     unixctl_command_register("bridge/dump-flows", "bridge", 1, 1,
467                              bridge_unixctl_dump_flows, NULL);
468     unixctl_command_register("bridge/reconnect", "[bridge]", 0, 1,
469                              bridge_unixctl_reconnect, NULL);
470     lacp_init();
471     bond_init();
472     cfm_init();
473     bfd_init();
474     ovs_numa_init();
475     stp_init();
476     lldp_init();
477     rstp_init();
478     ifnotifier = if_notifier_create(if_change_cb, NULL);
479 }
480
481 void
482 bridge_exit(void)
483 {
484     struct bridge *br, *next_br;
485
486     if_notifier_destroy(ifnotifier);
487     HMAP_FOR_EACH_SAFE (br, next_br, node, &all_bridges) {
488         bridge_destroy(br, false);
489     }
490     ovsdb_idl_destroy(idl);
491 }
492
493 /* Looks at the list of managers in 'ovs_cfg' and extracts their remote IP
494  * addresses and ports into '*managersp' and '*n_managersp'.  The caller is
495  * responsible for freeing '*managersp' (with free()).
496  *
497  * You may be asking yourself "why does ovs-vswitchd care?", because
498  * ovsdb-server is responsible for connecting to the managers, and ovs-vswitchd
499  * should not be and in fact is not directly involved in that.  But
500  * ovs-vswitchd needs to make sure that ovsdb-server can reach the managers, so
501  * it has to tell in-band control where the managers are to enable that.
502  * (Thus, only managers connected in-band and with non-loopback addresses
503  * are collected.)
504  */
505 static void
506 collect_in_band_managers(const struct ovsrec_open_vswitch *ovs_cfg,
507                          struct sockaddr_in **managersp, size_t *n_managersp)
508 {
509     struct sockaddr_in *managers = NULL;
510     size_t n_managers = 0;
511     struct sset targets;
512     size_t i;
513
514     /* Collect all of the potential targets from the "targets" columns of the
515      * rows pointed to by "manager_options", excluding any that are
516      * out-of-band. */
517     sset_init(&targets);
518     for (i = 0; i < ovs_cfg->n_manager_options; i++) {
519         struct ovsrec_manager *m = ovs_cfg->manager_options[i];
520
521         if (m->connection_mode && !strcmp(m->connection_mode, "out-of-band")) {
522             sset_find_and_delete(&targets, m->target);
523         } else {
524             sset_add(&targets, m->target);
525         }
526     }
527
528     /* Now extract the targets' IP addresses. */
529     if (!sset_is_empty(&targets)) {
530         const char *target;
531
532         managers = xmalloc(sset_count(&targets) * sizeof *managers);
533         SSET_FOR_EACH (target, &targets) {
534             union {
535                 struct sockaddr_storage ss;
536                 struct sockaddr_in in;
537             } sa;
538
539             /* Ignore loopback. */
540             if (stream_parse_target_with_default_port(target, OVSDB_PORT,
541                                                       &sa.ss)
542                 && sa.ss.ss_family == AF_INET
543                 && sa.in.sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
544                 managers[n_managers++] = sa.in;
545             }
546         }
547     }
548     sset_destroy(&targets);
549
550     *managersp = managers;
551     *n_managersp = n_managers;
552 }
553
554 static void
555 bridge_reconfigure(const struct ovsrec_open_vswitch *ovs_cfg)
556 {
557     struct sockaddr_in *managers;
558     struct bridge *br, *next;
559     int sflow_bridge_number;
560     size_t n_managers;
561
562     COVERAGE_INC(bridge_reconfigure);
563
564     ofproto_set_flow_limit(smap_get_int(&ovs_cfg->other_config, "flow-limit",
565                                         OFPROTO_FLOW_LIMIT_DEFAULT));
566     ofproto_set_max_idle(smap_get_int(&ovs_cfg->other_config, "max-idle",
567                                       OFPROTO_MAX_IDLE_DEFAULT));
568     ofproto_set_cpu_mask(smap_get(&ovs_cfg->other_config, "pmd-cpu-mask"));
569
570     ofproto_set_threads(
571         smap_get_int(&ovs_cfg->other_config, "n-handler-threads", 0),
572         smap_get_int(&ovs_cfg->other_config, "n-revalidator-threads", 0));
573
574     /* Destroy "struct bridge"s, "struct port"s, and "struct iface"s according
575      * to 'ovs_cfg', with only very minimal configuration otherwise.
576      *
577      * This is mostly an update to bridge data structures. Nothing is pushed
578      * down to ofproto or lower layers. */
579     add_del_bridges(ovs_cfg);
580     HMAP_FOR_EACH (br, node, &all_bridges) {
581         bridge_collect_wanted_ports(br, &br->wanted_ports);
582         bridge_del_ports(br, &br->wanted_ports);
583     }
584
585     /* Start pushing configuration changes down to the ofproto layer:
586      *
587      *   - Delete ofprotos that are no longer configured.
588      *
589      *   - Delete ports that are no longer configured.
590      *
591      *   - Reconfigure existing ports to their desired configurations, or
592      *     delete them if not possible.
593      *
594      * We have to do all the deletions before we can do any additions, because
595      * the ports to be added might require resources that will be freed up by
596      * deletions (they might especially overlap in name). */
597     bridge_delete_ofprotos();
598     HMAP_FOR_EACH (br, node, &all_bridges) {
599         if (br->ofproto) {
600             bridge_delete_or_reconfigure_ports(br);
601         }
602     }
603
604     /* Finish pushing configuration changes to the ofproto layer:
605      *
606      *     - Create ofprotos that are missing.
607      *
608      *     - Add ports that are missing. */
609     HMAP_FOR_EACH_SAFE (br, next, node, &all_bridges) {
610         if (!br->ofproto) {
611             int error;
612
613             error = ofproto_create(br->name, br->type, &br->ofproto);
614             if (error) {
615                 VLOG_ERR("failed to create bridge %s: %s", br->name,
616                          ovs_strerror(error));
617                 shash_destroy(&br->wanted_ports);
618                 bridge_destroy(br, true);
619             } else {
620                 /* Trigger storing datapath version. */
621                 seq_change(connectivity_seq_get());
622             }
623         }
624     }
625     HMAP_FOR_EACH (br, node, &all_bridges) {
626         bridge_add_ports(br, &br->wanted_ports);
627         shash_destroy(&br->wanted_ports);
628     }
629
630     reconfigure_system_stats(ovs_cfg);
631
632     /* Complete the configuration. */
633     sflow_bridge_number = 0;
634     collect_in_band_managers(ovs_cfg, &managers, &n_managers);
635     HMAP_FOR_EACH (br, node, &all_bridges) {
636         struct port *port;
637
638         /* We need the datapath ID early to allow LACP ports to use it as the
639          * default system ID. */
640         bridge_configure_datapath_id(br);
641
642         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
643             struct iface *iface;
644
645             port_configure(port);
646
647             LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
648                 iface_set_ofport(iface->cfg, iface->ofp_port);
649                 /* Clear eventual previous errors */
650                 ovsrec_interface_set_error(iface->cfg, NULL);
651                 iface_configure_cfm(iface);
652                 iface_configure_qos(iface, port->cfg->qos);
653                 iface_set_mac(br, port, iface);
654                 ofproto_port_set_bfd(br->ofproto, iface->ofp_port,
655                                      &iface->cfg->bfd);
656                 ofproto_port_set_lldp(br->ofproto, iface->ofp_port,
657                                       &iface->cfg->lldp);
658             }
659         }
660         bridge_configure_mirrors(br);
661         bridge_configure_forward_bpdu(br);
662         bridge_configure_mac_table(br);
663         bridge_configure_mcast_snooping(br);
664         bridge_configure_remotes(br, managers, n_managers);
665         bridge_configure_netflow(br);
666         bridge_configure_sflow(br, &sflow_bridge_number);
667         bridge_configure_ipfix(br);
668         bridge_configure_spanning_tree(br);
669         bridge_configure_tables(br);
670         bridge_configure_dp_desc(br);
671         bridge_configure_aa(br);
672     }
673     free(managers);
674
675     /* The ofproto-dpif provider does some final reconfiguration in its
676      * ->type_run() function.  We have to call it before notifying the database
677      * client that reconfiguration is complete, otherwise there is a very
678      * narrow race window in which e.g. ofproto/trace will not recognize the
679      * new configuration (sometimes this causes unit test failures). */
680     bridge_run__();
681 }
682
683 /* Delete ofprotos which aren't configured or have the wrong type.  Create
684  * ofprotos which don't exist but need to. */
685 static void
686 bridge_delete_ofprotos(void)
687 {
688     struct bridge *br;
689     struct sset names;
690     struct sset types;
691     const char *type;
692
693     /* Delete ofprotos with no bridge or with the wrong type. */
694     sset_init(&names);
695     sset_init(&types);
696     ofproto_enumerate_types(&types);
697     SSET_FOR_EACH (type, &types) {
698         const char *name;
699
700         ofproto_enumerate_names(type, &names);
701         SSET_FOR_EACH (name, &names) {
702             br = bridge_lookup(name);
703             if (!br || strcmp(type, br->type)) {
704                 ofproto_delete(name, type);
705             }
706         }
707     }
708     sset_destroy(&names);
709     sset_destroy(&types);
710 }
711
712 static ofp_port_t *
713 add_ofp_port(ofp_port_t port, ofp_port_t *ports, size_t *n, size_t *allocated)
714 {
715     if (*n >= *allocated) {
716         ports = x2nrealloc(ports, allocated, sizeof *ports);
717     }
718     ports[(*n)++] = port;
719     return ports;
720 }
721
722 static void
723 bridge_delete_or_reconfigure_ports(struct bridge *br)
724 {
725     struct ofproto_port ofproto_port;
726     struct ofproto_port_dump dump;
727
728     struct sset ofproto_ports;
729     struct port *port, *port_next;
730
731     /* List of "ofp_port"s to delete.  We make a list instead of deleting them
732      * right away because ofproto implementations aren't necessarily able to
733      * iterate through a changing list of ports in an entirely robust way. */
734     ofp_port_t *del;
735     size_t n, allocated;
736     size_t i;
737
738     del = NULL;
739     n = allocated = 0;
740     sset_init(&ofproto_ports);
741
742     /* Main task: Iterate over the ports in 'br->ofproto' and remove the ports
743      * that are not configured in the database.  (This commonly happens when
744      * ports have been deleted, e.g. with "ovs-vsctl del-port".)
745      *
746      * Side tasks: Reconfigure the ports that are still in 'br'.  Delete ports
747      * that have the wrong OpenFlow port number (and arrange to add them back
748      * with the correct OpenFlow port number). */
749     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, br->ofproto) {
750         ofp_port_t requested_ofp_port;
751         struct iface *iface;
752
753         sset_add(&ofproto_ports, ofproto_port.name);
754
755         iface = iface_lookup(br, ofproto_port.name);
756         if (!iface) {
757             /* No such iface is configured, so we should delete this
758              * ofproto_port.
759              *
760              * As a corner case exception, keep the port if it's a bond fake
761              * interface. */
762             if (bridge_has_bond_fake_iface(br, ofproto_port.name)
763                 && !strcmp(ofproto_port.type, "internal")) {
764                 continue;
765             }
766             goto delete;
767         }
768
769         if (strcmp(ofproto_port.type, iface->netdev_type)
770             || netdev_set_config(iface->netdev, &iface->cfg->options, NULL)) {
771             /* The interface is the wrong type or can't be configured.
772              * Delete it. */
773             goto delete;
774         }
775
776         /* If the requested OpenFlow port for 'iface' changed, and it's not
777          * already the correct port, then we might want to temporarily delete
778          * this interface, so we can add it back again with the new OpenFlow
779          * port number. */
780         requested_ofp_port = iface_get_requested_ofp_port(iface->cfg);
781         if (iface->ofp_port != OFPP_LOCAL &&
782             requested_ofp_port != OFPP_NONE &&
783             requested_ofp_port != iface->ofp_port) {
784             ofp_port_t victim_request;
785             struct iface *victim;
786
787             /* Check for an existing OpenFlow port currently occupying
788              * 'iface''s requested port number.  If there isn't one, then
789              * delete this port.  Otherwise we need to consider further. */
790             victim = iface_from_ofp_port(br, requested_ofp_port);
791             if (!victim) {
792                 goto delete;
793             }
794
795             /* 'victim' is a port currently using 'iface''s requested port
796              * number.  Unless 'victim' specifically requested that port
797              * number, too, then we can delete both 'iface' and 'victim'
798              * temporarily.  (We'll add both of them back again later with new
799              * OpenFlow port numbers.)
800              *
801              * If 'victim' did request port number 'requested_ofp_port', just
802              * like 'iface', then that's a configuration inconsistency that we
803              * can't resolve.  We might as well let it keep its current port
804              * number. */
805             victim_request = iface_get_requested_ofp_port(victim->cfg);
806             if (victim_request != requested_ofp_port) {
807                 del = add_ofp_port(victim->ofp_port, del, &n, &allocated);
808                 iface_destroy(victim);
809                 goto delete;
810             }
811         }
812
813         /* Keep it. */
814         continue;
815
816     delete:
817         iface_destroy(iface);
818         del = add_ofp_port(ofproto_port.ofp_port, del, &n, &allocated);
819     }
820     for (i = 0; i < n; i++) {
821         ofproto_port_del(br->ofproto, del[i]);
822     }
823     free(del);
824
825     /* Iterate over this module's idea of interfaces in 'br'.  Remove any ports
826      * that we didn't see when we iterated through the datapath, i.e. ports
827      * that disappeared underneath use.  This is an unusual situation, but it
828      * can happen in some cases:
829      *
830      *     - An admin runs a command like "ovs-dpctl del-port" (which is a bad
831      *       idea but could happen).
832      *
833      *     - The port represented a device that disappeared, e.g. a tuntap
834      *       device destroyed via "tunctl -d", a physical Ethernet device
835      *       whose module was just unloaded via "rmmod", or a virtual NIC for a
836      *       VM whose VM was just terminated. */
837     HMAP_FOR_EACH_SAFE (port, port_next, hmap_node, &br->ports) {
838         struct iface *iface, *iface_next;
839
840         LIST_FOR_EACH_SAFE (iface, iface_next, port_elem, &port->ifaces) {
841             if (!sset_contains(&ofproto_ports, iface->name)) {
842                 iface_destroy__(iface);
843             }
844         }
845
846         if (ovs_list_is_empty(&port->ifaces)) {
847             port_destroy(port);
848         }
849     }
850     sset_destroy(&ofproto_ports);
851 }
852
853 static void
854 bridge_add_ports__(struct bridge *br, const struct shash *wanted_ports,
855                    bool with_requested_port)
856 {
857     struct shash_node *port_node;
858
859     SHASH_FOR_EACH (port_node, wanted_ports) {
860         const struct ovsrec_port *port_cfg = port_node->data;
861         size_t i;
862
863         for (i = 0; i < port_cfg->n_interfaces; i++) {
864             const struct ovsrec_interface *iface_cfg = port_cfg->interfaces[i];
865             ofp_port_t requested_ofp_port;
866
867             requested_ofp_port = iface_get_requested_ofp_port(iface_cfg);
868             if ((requested_ofp_port != OFPP_NONE) == with_requested_port) {
869                 struct iface *iface = iface_lookup(br, iface_cfg->name);
870
871                 if (!iface) {
872                     iface_create(br, iface_cfg, port_cfg);
873                 }
874             }
875         }
876     }
877 }
878
879 static void
880 bridge_add_ports(struct bridge *br, const struct shash *wanted_ports)
881 {
882     /* First add interfaces that request a particular port number. */
883     bridge_add_ports__(br, wanted_ports, true);
884
885     /* Then add interfaces that want automatic port number assignment.
886      * We add these afterward to avoid accidentally taking a specifically
887      * requested port number. */
888     bridge_add_ports__(br, wanted_ports, false);
889 }
890
891 static void
892 port_configure(struct port *port)
893 {
894     const struct ovsrec_port *cfg = port->cfg;
895     struct bond_settings bond_settings;
896     struct lacp_settings lacp_settings;
897     struct ofproto_bundle_settings s;
898     struct iface *iface;
899
900     /* Get name. */
901     s.name = port->name;
902
903     /* Get slaves. */
904     s.n_slaves = 0;
905     s.slaves = xmalloc(ovs_list_size(&port->ifaces) * sizeof *s.slaves);
906     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
907         s.slaves[s.n_slaves++] = iface->ofp_port;
908     }
909
910     /* Get VLAN tag. */
911     s.vlan = -1;
912     if (cfg->tag && *cfg->tag >= 0 && *cfg->tag <= 4095) {
913         s.vlan = *cfg->tag;
914     }
915
916     /* Get VLAN trunks. */
917     s.trunks = NULL;
918     if (cfg->n_trunks) {
919         s.trunks = vlan_bitmap_from_array(cfg->trunks, cfg->n_trunks);
920     }
921
922     /* Get VLAN mode. */
923     if (cfg->vlan_mode) {
924         if (!strcmp(cfg->vlan_mode, "access")) {
925             s.vlan_mode = PORT_VLAN_ACCESS;
926         } else if (!strcmp(cfg->vlan_mode, "trunk")) {
927             s.vlan_mode = PORT_VLAN_TRUNK;
928         } else if (!strcmp(cfg->vlan_mode, "native-tagged")) {
929             s.vlan_mode = PORT_VLAN_NATIVE_TAGGED;
930         } else if (!strcmp(cfg->vlan_mode, "native-untagged")) {
931             s.vlan_mode = PORT_VLAN_NATIVE_UNTAGGED;
932         } else {
933             /* This "can't happen" because ovsdb-server should prevent it. */
934             VLOG_WARN("port %s: unknown VLAN mode %s, falling "
935                       "back to trunk mode", port->name, cfg->vlan_mode);
936             s.vlan_mode = PORT_VLAN_TRUNK;
937         }
938     } else {
939         if (s.vlan >= 0) {
940             s.vlan_mode = PORT_VLAN_ACCESS;
941             if (cfg->n_trunks) {
942                 VLOG_WARN("port %s: ignoring trunks in favor of implicit vlan",
943                           port->name);
944             }
945         } else {
946             s.vlan_mode = PORT_VLAN_TRUNK;
947         }
948     }
949     s.use_priority_tags = smap_get_bool(&cfg->other_config, "priority-tags",
950                                         false);
951
952     /* Get LACP settings. */
953     s.lacp = port_configure_lacp(port, &lacp_settings);
954     if (s.lacp) {
955         size_t i = 0;
956
957         s.lacp_slaves = xmalloc(s.n_slaves * sizeof *s.lacp_slaves);
958         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
959             iface_configure_lacp(iface, &s.lacp_slaves[i++]);
960         }
961     } else {
962         s.lacp_slaves = NULL;
963     }
964
965     /* Get bond settings. */
966     if (s.n_slaves > 1) {
967         s.bond = &bond_settings;
968         port_configure_bond(port, &bond_settings);
969     } else {
970         s.bond = NULL;
971         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
972             netdev_set_miimon_interval(iface->netdev, 0);
973         }
974     }
975
976     /* Register. */
977     ofproto_bundle_register(port->bridge->ofproto, port, &s);
978
979     /* Clean up. */
980     free(s.slaves);
981     free(s.trunks);
982     free(s.lacp_slaves);
983 }
984
985 /* Pick local port hardware address and datapath ID for 'br'. */
986 static void
987 bridge_configure_datapath_id(struct bridge *br)
988 {
989     struct eth_addr ea;
990     uint64_t dpid;
991     struct iface *local_iface;
992     struct iface *hw_addr_iface;
993     char *dpid_string;
994
995     bridge_pick_local_hw_addr(br, &ea, &hw_addr_iface);
996     local_iface = iface_from_ofp_port(br, OFPP_LOCAL);
997     if (local_iface) {
998         int error = netdev_set_etheraddr(local_iface->netdev, ea);
999         if (error) {
1000             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1001             VLOG_ERR_RL(&rl, "bridge %s: failed to set bridge "
1002                         "Ethernet address: %s",
1003                         br->name, ovs_strerror(error));
1004         }
1005     }
1006     br->ea = ea;
1007
1008     dpid = bridge_pick_datapath_id(br, ea, hw_addr_iface);
1009     if (dpid != ofproto_get_datapath_id(br->ofproto)) {
1010         VLOG_INFO("bridge %s: using datapath ID %016"PRIx64, br->name, dpid);
1011         ofproto_set_datapath_id(br->ofproto, dpid);
1012     }
1013
1014     dpid_string = xasprintf("%016"PRIx64, dpid);
1015     ovsrec_bridge_set_datapath_id(br->cfg, dpid_string);
1016     free(dpid_string);
1017 }
1018
1019 /* Returns a bitmap of "enum ofputil_protocol"s that are allowed for use with
1020  * 'br'. */
1021 static uint32_t
1022 bridge_get_allowed_versions(struct bridge *br)
1023 {
1024     if (!br->cfg->n_protocols) {
1025         return 0;
1026     }
1027
1028     return ofputil_versions_from_strings(br->cfg->protocols,
1029                                          br->cfg->n_protocols);
1030 }
1031
1032 /* Set NetFlow configuration on 'br'. */
1033 static void
1034 bridge_configure_netflow(struct bridge *br)
1035 {
1036     struct ovsrec_netflow *cfg = br->cfg->netflow;
1037     struct netflow_options opts;
1038
1039     if (!cfg) {
1040         ofproto_set_netflow(br->ofproto, NULL);
1041         return;
1042     }
1043
1044     memset(&opts, 0, sizeof opts);
1045
1046     /* Get default NetFlow configuration from datapath.
1047      * Apply overrides from 'cfg'. */
1048     ofproto_get_netflow_ids(br->ofproto, &opts.engine_type, &opts.engine_id);
1049     if (cfg->engine_type) {
1050         opts.engine_type = *cfg->engine_type;
1051     }
1052     if (cfg->engine_id) {
1053         opts.engine_id = *cfg->engine_id;
1054     }
1055
1056     /* Configure active timeout interval. */
1057     opts.active_timeout = cfg->active_timeout;
1058     if (!opts.active_timeout) {
1059         opts.active_timeout = -1;
1060     } else if (opts.active_timeout < 0) {
1061         VLOG_WARN("bridge %s: active timeout interval set to negative "
1062                   "value, using default instead (%d seconds)", br->name,
1063                   NF_ACTIVE_TIMEOUT_DEFAULT);
1064         opts.active_timeout = -1;
1065     }
1066
1067     /* Add engine ID to interface number to disambiguate bridgs? */
1068     opts.add_id_to_iface = cfg->add_id_to_interface;
1069     if (opts.add_id_to_iface) {
1070         if (opts.engine_id > 0x7f) {
1071             VLOG_WARN("bridge %s: NetFlow port mangling may conflict with "
1072                       "another vswitch, choose an engine id less than 128",
1073                       br->name);
1074         }
1075         if (hmap_count(&br->ports) > 508) {
1076             VLOG_WARN("bridge %s: NetFlow port mangling will conflict with "
1077                       "another port when more than 508 ports are used",
1078                       br->name);
1079         }
1080     }
1081
1082     /* Collectors. */
1083     sset_init(&opts.collectors);
1084     sset_add_array(&opts.collectors, cfg->targets, cfg->n_targets);
1085
1086     /* Configure. */
1087     if (ofproto_set_netflow(br->ofproto, &opts)) {
1088         VLOG_ERR("bridge %s: problem setting netflow collectors", br->name);
1089     }
1090     sset_destroy(&opts.collectors);
1091 }
1092
1093 /* Set sFlow configuration on 'br'. */
1094 static void
1095 bridge_configure_sflow(struct bridge *br, int *sflow_bridge_number)
1096 {
1097     const struct ovsrec_sflow *cfg = br->cfg->sflow;
1098     struct ovsrec_controller **controllers;
1099     struct ofproto_sflow_options oso;
1100     size_t n_controllers;
1101     size_t i;
1102
1103     if (!cfg) {
1104         ofproto_set_sflow(br->ofproto, NULL);
1105         return;
1106     }
1107
1108     memset(&oso, 0, sizeof oso);
1109
1110     sset_init(&oso.targets);
1111     sset_add_array(&oso.targets, cfg->targets, cfg->n_targets);
1112
1113     oso.sampling_rate = SFL_DEFAULT_SAMPLING_RATE;
1114     if (cfg->sampling) {
1115         oso.sampling_rate = *cfg->sampling;
1116     }
1117
1118     oso.polling_interval = SFL_DEFAULT_POLLING_INTERVAL;
1119     if (cfg->polling) {
1120         oso.polling_interval = *cfg->polling;
1121     }
1122
1123     oso.header_len = SFL_DEFAULT_HEADER_SIZE;
1124     if (cfg->header) {
1125         oso.header_len = *cfg->header;
1126     }
1127
1128     oso.sub_id = (*sflow_bridge_number)++;
1129     oso.agent_device = cfg->agent;
1130
1131     oso.control_ip = NULL;
1132     n_controllers = bridge_get_controllers(br, &controllers);
1133     for (i = 0; i < n_controllers; i++) {
1134         if (controllers[i]->local_ip) {
1135             oso.control_ip = controllers[i]->local_ip;
1136             break;
1137         }
1138     }
1139     ofproto_set_sflow(br->ofproto, &oso);
1140
1141     sset_destroy(&oso.targets);
1142 }
1143
1144 /* Returns whether a IPFIX row is valid. */
1145 static bool
1146 ovsrec_ipfix_is_valid(const struct ovsrec_ipfix *ipfix)
1147 {
1148     return ipfix && ipfix->n_targets > 0;
1149 }
1150
1151 /* Returns whether a Flow_Sample_Collector_Set row is valid. */
1152 static bool
1153 ovsrec_fscs_is_valid(const struct ovsrec_flow_sample_collector_set *fscs,
1154                      const struct bridge *br)
1155 {
1156     return ovsrec_ipfix_is_valid(fscs->ipfix) && fscs->bridge == br->cfg;
1157 }
1158
1159 /* Set IPFIX configuration on 'br'. */
1160 static void
1161 bridge_configure_ipfix(struct bridge *br)
1162 {
1163     const struct ovsrec_ipfix *be_cfg = br->cfg->ipfix;
1164     bool valid_be_cfg = ovsrec_ipfix_is_valid(be_cfg);
1165     const struct ovsrec_flow_sample_collector_set *fe_cfg;
1166     struct ofproto_ipfix_bridge_exporter_options be_opts;
1167     struct ofproto_ipfix_flow_exporter_options *fe_opts = NULL;
1168     size_t n_fe_opts = 0;
1169     const char *virtual_obs_id;
1170
1171     OVSREC_FLOW_SAMPLE_COLLECTOR_SET_FOR_EACH(fe_cfg, idl) {
1172         if (ovsrec_fscs_is_valid(fe_cfg, br)) {
1173             n_fe_opts++;
1174         }
1175     }
1176
1177     if (!valid_be_cfg && n_fe_opts == 0) {
1178         ofproto_set_ipfix(br->ofproto, NULL, NULL, 0);
1179         return;
1180     }
1181
1182     if (valid_be_cfg) {
1183         memset(&be_opts, 0, sizeof be_opts);
1184
1185         sset_init(&be_opts.targets);
1186         sset_add_array(&be_opts.targets, be_cfg->targets, be_cfg->n_targets);
1187
1188         if (be_cfg->sampling) {
1189             be_opts.sampling_rate = *be_cfg->sampling;
1190         } else {
1191             be_opts.sampling_rate = SFL_DEFAULT_SAMPLING_RATE;
1192         }
1193         if (be_cfg->obs_domain_id) {
1194             be_opts.obs_domain_id = *be_cfg->obs_domain_id;
1195         }
1196         if (be_cfg->obs_point_id) {
1197             be_opts.obs_point_id = *be_cfg->obs_point_id;
1198         }
1199         if (be_cfg->cache_active_timeout) {
1200             be_opts.cache_active_timeout = *be_cfg->cache_active_timeout;
1201         }
1202         if (be_cfg->cache_max_flows) {
1203             be_opts.cache_max_flows = *be_cfg->cache_max_flows;
1204         }
1205
1206         be_opts.enable_tunnel_sampling = smap_get_bool(&be_cfg->other_config,
1207                                              "enable-tunnel-sampling", true);
1208
1209         be_opts.enable_input_sampling = !smap_get_bool(&be_cfg->other_config,
1210                                               "enable-input-sampling", false);
1211
1212         be_opts.enable_output_sampling = !smap_get_bool(&be_cfg->other_config,
1213                                               "enable-output-sampling", false);
1214
1215         virtual_obs_id = smap_get(&be_cfg->other_config, "virtual_obs_id");
1216         be_opts.virtual_obs_id = nullable_xstrdup(virtual_obs_id);
1217     }
1218
1219     if (n_fe_opts > 0) {
1220         struct ofproto_ipfix_flow_exporter_options *opts;
1221         fe_opts = xcalloc(n_fe_opts, sizeof *fe_opts);
1222         opts = fe_opts;
1223         OVSREC_FLOW_SAMPLE_COLLECTOR_SET_FOR_EACH(fe_cfg, idl) {
1224             if (ovsrec_fscs_is_valid(fe_cfg, br)) {
1225                 opts->collector_set_id = fe_cfg->id;
1226                 sset_init(&opts->targets);
1227                 sset_add_array(&opts->targets, fe_cfg->ipfix->targets,
1228                                fe_cfg->ipfix->n_targets);
1229                 opts->cache_active_timeout = fe_cfg->ipfix->cache_active_timeout
1230                     ? *fe_cfg->ipfix->cache_active_timeout : 0;
1231                 opts->cache_max_flows = fe_cfg->ipfix->cache_max_flows
1232                     ? *fe_cfg->ipfix->cache_max_flows : 0;
1233                 opts->enable_tunnel_sampling = smap_get_bool(
1234                                                    &fe_cfg->ipfix->other_config,
1235                                                   "enable-tunnel-sampling", true);
1236                 virtual_obs_id = smap_get(&fe_cfg->ipfix->other_config,
1237                                           "virtual_obs_id");
1238                 opts->virtual_obs_id = nullable_xstrdup(virtual_obs_id);
1239                 opts++;
1240             }
1241         }
1242     }
1243
1244     ofproto_set_ipfix(br->ofproto, valid_be_cfg ? &be_opts : NULL, fe_opts,
1245                       n_fe_opts);
1246
1247     if (valid_be_cfg) {
1248         sset_destroy(&be_opts.targets);
1249         free(be_opts.virtual_obs_id);
1250     }
1251
1252     if (n_fe_opts > 0) {
1253         struct ofproto_ipfix_flow_exporter_options *opts = fe_opts;
1254         size_t i;
1255         for (i = 0; i < n_fe_opts; i++) {
1256             sset_destroy(&opts->targets);
1257             free(opts->virtual_obs_id);
1258             opts++;
1259         }
1260         free(fe_opts);
1261     }
1262 }
1263
1264 static void
1265 port_configure_stp(const struct ofproto *ofproto, struct port *port,
1266                    struct ofproto_port_stp_settings *port_s,
1267                    int *port_num_counter, unsigned long *port_num_bitmap)
1268 {
1269     const char *config_str;
1270     struct iface *iface;
1271
1272     if (!smap_get_bool(&port->cfg->other_config, "stp-enable", true)) {
1273         port_s->enable = false;
1274         return;
1275     } else {
1276         port_s->enable = true;
1277     }
1278
1279     /* STP over bonds is not supported. */
1280     if (!ovs_list_is_singleton(&port->ifaces)) {
1281         VLOG_ERR("port %s: cannot enable STP on bonds, disabling",
1282                  port->name);
1283         port_s->enable = false;
1284         return;
1285     }
1286
1287     iface = CONTAINER_OF(ovs_list_front(&port->ifaces), struct iface, port_elem);
1288
1289     /* Internal ports shouldn't participate in spanning tree, so
1290      * skip them. */
1291     if (!strcmp(iface->type, "internal")) {
1292         VLOG_DBG("port %s: disable STP on internal ports", port->name);
1293         port_s->enable = false;
1294         return;
1295     }
1296
1297     /* STP on mirror output ports is not supported. */
1298     if (ofproto_is_mirror_output_bundle(ofproto, port)) {
1299         VLOG_DBG("port %s: disable STP on mirror ports", port->name);
1300         port_s->enable = false;
1301         return;
1302     }
1303
1304     config_str = smap_get(&port->cfg->other_config, "stp-port-num");
1305     if (config_str) {
1306         unsigned long int port_num = strtoul(config_str, NULL, 0);
1307         int port_idx = port_num - 1;
1308
1309         if (port_num < 1 || port_num > STP_MAX_PORTS) {
1310             VLOG_ERR("port %s: invalid stp-port-num", port->name);
1311             port_s->enable = false;
1312             return;
1313         }
1314
1315         if (bitmap_is_set(port_num_bitmap, port_idx)) {
1316             VLOG_ERR("port %s: duplicate stp-port-num %lu, disabling",
1317                     port->name, port_num);
1318             port_s->enable = false;
1319             return;
1320         }
1321         bitmap_set1(port_num_bitmap, port_idx);
1322         port_s->port_num = port_idx;
1323     } else {
1324         if (*port_num_counter >= STP_MAX_PORTS) {
1325             VLOG_ERR("port %s: too many STP ports, disabling", port->name);
1326             port_s->enable = false;
1327             return;
1328         }
1329
1330         port_s->port_num = (*port_num_counter)++;
1331     }
1332
1333     config_str = smap_get(&port->cfg->other_config, "stp-path-cost");
1334     if (config_str) {
1335         port_s->path_cost = strtoul(config_str, NULL, 10);
1336     } else {
1337         enum netdev_features current;
1338         unsigned int mbps;
1339
1340         netdev_get_features(iface->netdev, &current, NULL, NULL, NULL);
1341         mbps = netdev_features_to_bps(current, 100 * 1000 * 1000) / 1000000;
1342         port_s->path_cost = stp_convert_speed_to_cost(mbps);
1343     }
1344
1345     config_str = smap_get(&port->cfg->other_config, "stp-port-priority");
1346     if (config_str) {
1347         port_s->priority = strtoul(config_str, NULL, 0);
1348     } else {
1349         port_s->priority = STP_DEFAULT_PORT_PRIORITY;
1350     }
1351 }
1352
1353 static void
1354 port_configure_rstp(const struct ofproto *ofproto, struct port *port,
1355         struct ofproto_port_rstp_settings *port_s, int *port_num_counter)
1356 {
1357     const char *config_str;
1358     struct iface *iface;
1359
1360     if (!smap_get_bool(&port->cfg->other_config, "rstp-enable", true)) {
1361         port_s->enable = false;
1362         return;
1363     } else {
1364         port_s->enable = true;
1365     }
1366
1367     /* RSTP over bonds is not supported. */
1368     if (!ovs_list_is_singleton(&port->ifaces)) {
1369         VLOG_ERR("port %s: cannot enable RSTP on bonds, disabling",
1370                 port->name);
1371         port_s->enable = false;
1372         return;
1373     }
1374
1375     iface = CONTAINER_OF(ovs_list_front(&port->ifaces), struct iface, port_elem);
1376
1377     /* Internal ports shouldn't participate in spanning tree, so
1378      * skip them. */
1379     if (!strcmp(iface->type, "internal")) {
1380         VLOG_DBG("port %s: disable RSTP on internal ports", port->name);
1381         port_s->enable = false;
1382         return;
1383     }
1384
1385     /* RSTP on mirror output ports is not supported. */
1386     if (ofproto_is_mirror_output_bundle(ofproto, port)) {
1387         VLOG_DBG("port %s: disable RSTP on mirror ports", port->name);
1388         port_s->enable = false;
1389         return;
1390     }
1391
1392     config_str = smap_get(&port->cfg->other_config, "rstp-port-num");
1393     if (config_str) {
1394         unsigned long int port_num = strtoul(config_str, NULL, 0);
1395         if (port_num < 1 || port_num > RSTP_MAX_PORTS) {
1396             VLOG_ERR("port %s: invalid rstp-port-num", port->name);
1397             port_s->enable = false;
1398             return;
1399         }
1400         port_s->port_num = port_num;
1401     } else {
1402         if (*port_num_counter >= RSTP_MAX_PORTS) {
1403             VLOG_ERR("port %s: too many RSTP ports, disabling", port->name);
1404             port_s->enable = false;
1405             return;
1406         }
1407         /* If rstp-port-num is not specified, use 0.
1408          * rstp_port_set_port_number() will look for the first free one. */
1409         port_s->port_num = 0;
1410     }
1411
1412     config_str = smap_get(&port->cfg->other_config, "rstp-path-cost");
1413     if (config_str) {
1414         port_s->path_cost = strtoul(config_str, NULL, 10);
1415     } else {
1416         enum netdev_features current;
1417         unsigned int mbps;
1418
1419         netdev_get_features(iface->netdev, &current, NULL, NULL, NULL);
1420         mbps = netdev_features_to_bps(current, 100 * 1000 * 1000) / 1000000;
1421         port_s->path_cost = rstp_convert_speed_to_cost(mbps);
1422     }
1423
1424     config_str = smap_get(&port->cfg->other_config, "rstp-port-priority");
1425     if (config_str) {
1426         port_s->priority = strtoul(config_str, NULL, 0);
1427     } else {
1428         port_s->priority = RSTP_DEFAULT_PORT_PRIORITY;
1429     }
1430
1431     config_str = smap_get(&port->cfg->other_config, "rstp-admin-p2p-mac");
1432     if (config_str) {
1433         port_s->admin_p2p_mac_state = strtoul(config_str, NULL, 0);
1434     } else {
1435         port_s->admin_p2p_mac_state = RSTP_ADMIN_P2P_MAC_FORCE_TRUE;
1436     }
1437
1438     port_s->admin_port_state = smap_get_bool(&port->cfg->other_config,
1439                                              "rstp-admin-port-state", true);
1440
1441     port_s->admin_edge_port = smap_get_bool(&port->cfg->other_config,
1442                                             "rstp-port-admin-edge", false);
1443     port_s->auto_edge = smap_get_bool(&port->cfg->other_config,
1444                                       "rstp-port-auto-edge", true);
1445     port_s->mcheck = smap_get_bool(&port->cfg->other_config,
1446                                    "rstp-port-mcheck", false);
1447 }
1448
1449 /* Set spanning tree configuration on 'br'. */
1450 static void
1451 bridge_configure_stp(struct bridge *br, bool enable_stp)
1452 {
1453     if (!enable_stp) {
1454         ofproto_set_stp(br->ofproto, NULL);
1455     } else {
1456         struct ofproto_stp_settings br_s;
1457         const char *config_str;
1458         struct port *port;
1459         int port_num_counter;
1460         unsigned long *port_num_bitmap;
1461
1462         config_str = smap_get(&br->cfg->other_config, "stp-system-id");
1463         if (config_str) {
1464             struct eth_addr ea;
1465
1466             if (eth_addr_from_string(config_str, &ea)) {
1467                 br_s.system_id = eth_addr_to_uint64(ea);
1468             } else {
1469                 br_s.system_id = eth_addr_to_uint64(br->ea);
1470                 VLOG_ERR("bridge %s: invalid stp-system-id, defaulting "
1471                          "to "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(br->ea));
1472             }
1473         } else {
1474             br_s.system_id = eth_addr_to_uint64(br->ea);
1475         }
1476
1477         config_str = smap_get(&br->cfg->other_config, "stp-priority");
1478         if (config_str) {
1479             br_s.priority = strtoul(config_str, NULL, 0);
1480         } else {
1481             br_s.priority = STP_DEFAULT_BRIDGE_PRIORITY;
1482         }
1483
1484         config_str = smap_get(&br->cfg->other_config, "stp-hello-time");
1485         if (config_str) {
1486             br_s.hello_time = strtoul(config_str, NULL, 10) * 1000;
1487         } else {
1488             br_s.hello_time = STP_DEFAULT_HELLO_TIME;
1489         }
1490
1491         config_str = smap_get(&br->cfg->other_config, "stp-max-age");
1492         if (config_str) {
1493             br_s.max_age = strtoul(config_str, NULL, 10) * 1000;
1494         } else {
1495             br_s.max_age = STP_DEFAULT_MAX_AGE;
1496         }
1497
1498         config_str = smap_get(&br->cfg->other_config, "stp-forward-delay");
1499         if (config_str) {
1500             br_s.fwd_delay = strtoul(config_str, NULL, 10) * 1000;
1501         } else {
1502             br_s.fwd_delay = STP_DEFAULT_FWD_DELAY;
1503         }
1504
1505         /* Configure STP on the bridge. */
1506         if (ofproto_set_stp(br->ofproto, &br_s)) {
1507             VLOG_ERR("bridge %s: could not enable STP", br->name);
1508             return;
1509         }
1510
1511         /* Users must either set the port number with the "stp-port-num"
1512          * configuration on all ports or none.  If manual configuration
1513          * is not done, then we allocate them sequentially. */
1514         port_num_counter = 0;
1515         port_num_bitmap = bitmap_allocate(STP_MAX_PORTS);
1516         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1517             struct ofproto_port_stp_settings port_s;
1518             struct iface *iface;
1519
1520             port_configure_stp(br->ofproto, port, &port_s,
1521                                &port_num_counter, port_num_bitmap);
1522
1523             /* As bonds are not supported, just apply configuration to
1524              * all interfaces. */
1525             LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1526                 if (ofproto_port_set_stp(br->ofproto, iface->ofp_port,
1527                                          &port_s)) {
1528                     VLOG_ERR("port %s: could not enable STP", port->name);
1529                     continue;
1530                 }
1531             }
1532         }
1533
1534         if (bitmap_scan(port_num_bitmap, 1, 0, STP_MAX_PORTS) != STP_MAX_PORTS
1535                     && port_num_counter) {
1536             VLOG_ERR("bridge %s: must manually configure all STP port "
1537                      "IDs or none, disabling", br->name);
1538             ofproto_set_stp(br->ofproto, NULL);
1539         }
1540         bitmap_free(port_num_bitmap);
1541     }
1542 }
1543
1544 static void
1545 bridge_configure_rstp(struct bridge *br, bool enable_rstp)
1546 {
1547     if (!enable_rstp) {
1548         ofproto_set_rstp(br->ofproto, NULL);
1549     } else {
1550         struct ofproto_rstp_settings br_s;
1551         const char *config_str;
1552         struct port *port;
1553         int port_num_counter;
1554
1555         config_str = smap_get(&br->cfg->other_config, "rstp-address");
1556         if (config_str) {
1557             struct eth_addr ea;
1558
1559             if (eth_addr_from_string(config_str, &ea)) {
1560                 br_s.address = eth_addr_to_uint64(ea);
1561             }
1562             else {
1563                 br_s.address = eth_addr_to_uint64(br->ea);
1564                 VLOG_ERR("bridge %s: invalid rstp-address, defaulting "
1565                         "to "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(br->ea));
1566             }
1567         }
1568         else {
1569             br_s.address = eth_addr_to_uint64(br->ea);
1570         }
1571
1572         config_str = smap_get(&br->cfg->other_config, "rstp-priority");
1573         if (config_str) {
1574             br_s.priority = strtoul(config_str, NULL, 0);
1575         } else {
1576             br_s.priority = RSTP_DEFAULT_PRIORITY;
1577         }
1578
1579         config_str = smap_get(&br->cfg->other_config, "rstp-ageing-time");
1580         if (config_str) {
1581             br_s.ageing_time = strtoul(config_str, NULL, 0);
1582         } else {
1583             br_s.ageing_time = RSTP_DEFAULT_AGEING_TIME;
1584         }
1585
1586         config_str = smap_get(&br->cfg->other_config,
1587                               "rstp-force-protocol-version");
1588         if (config_str) {
1589             br_s.force_protocol_version = strtoul(config_str, NULL, 0);
1590         } else {
1591             br_s.force_protocol_version = FPV_DEFAULT;
1592         }
1593
1594         config_str = smap_get(&br->cfg->other_config, "rstp-max-age");
1595         if (config_str) {
1596             br_s.bridge_max_age = strtoul(config_str, NULL, 10);
1597         } else {
1598             br_s.bridge_max_age = RSTP_DEFAULT_BRIDGE_MAX_AGE;
1599         }
1600
1601         config_str = smap_get(&br->cfg->other_config, "rstp-forward-delay");
1602         if (config_str) {
1603             br_s.bridge_forward_delay = strtoul(config_str, NULL, 10);
1604         } else {
1605             br_s.bridge_forward_delay = RSTP_DEFAULT_BRIDGE_FORWARD_DELAY;
1606         }
1607
1608         config_str = smap_get(&br->cfg->other_config,
1609                               "rstp-transmit-hold-count");
1610         if (config_str) {
1611             br_s.transmit_hold_count = strtoul(config_str, NULL, 10);
1612         } else {
1613             br_s.transmit_hold_count = RSTP_DEFAULT_TRANSMIT_HOLD_COUNT;
1614         }
1615
1616         /* Configure RSTP on the bridge. */
1617         if (ofproto_set_rstp(br->ofproto, &br_s)) {
1618             VLOG_ERR("bridge %s: could not enable RSTP", br->name);
1619             return;
1620         }
1621
1622         port_num_counter = 0;
1623         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1624             struct ofproto_port_rstp_settings port_s;
1625             struct iface *iface;
1626
1627             port_configure_rstp(br->ofproto, port, &port_s,
1628                     &port_num_counter);
1629
1630             /* As bonds are not supported, just apply configuration to
1631              * all interfaces. */
1632             LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1633                 if (ofproto_port_set_rstp(br->ofproto, iface->ofp_port,
1634                             &port_s)) {
1635                     VLOG_ERR("port %s: could not enable RSTP", port->name);
1636                     continue;
1637                 }
1638             }
1639         }
1640     }
1641 }
1642
1643 static void
1644 bridge_configure_spanning_tree(struct bridge *br)
1645 {
1646     bool enable_rstp = br->cfg->rstp_enable;
1647     bool enable_stp = br->cfg->stp_enable;
1648
1649     if (enable_rstp && enable_stp) {
1650         VLOG_WARN("%s: RSTP and STP are mutually exclusive but both are "
1651                   "configured; enabling RSTP", br->name);
1652         enable_stp = false;
1653     }
1654
1655     bridge_configure_stp(br, enable_stp);
1656     bridge_configure_rstp(br, enable_rstp);
1657 }
1658
1659 static bool
1660 bridge_has_bond_fake_iface(const struct bridge *br, const char *name)
1661 {
1662     const struct port *port = port_lookup(br, name);
1663     return port && port_is_bond_fake_iface(port);
1664 }
1665
1666 static bool
1667 port_is_bond_fake_iface(const struct port *port)
1668 {
1669     return port->cfg->bond_fake_iface && !ovs_list_is_short(&port->ifaces);
1670 }
1671
1672 static void
1673 add_del_bridges(const struct ovsrec_open_vswitch *cfg)
1674 {
1675     struct bridge *br, *next;
1676     struct shash_node *node;
1677     struct shash new_br;
1678     size_t i;
1679
1680     /* Collect new bridges' names and types. */
1681     shash_init(&new_br);
1682     for (i = 0; i < cfg->n_bridges; i++) {
1683         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1684         const struct ovsrec_bridge *br_cfg = cfg->bridges[i];
1685
1686         if (strchr(br_cfg->name, '/') || strchr(br_cfg->name, '\\')) {
1687             /* Prevent remote ovsdb-server users from accessing arbitrary
1688              * directories, e.g. consider a bridge named "../../../etc/".
1689              *
1690              * Prohibiting "\" is only necessary on Windows but it's no great
1691              * loss elsewhere. */
1692             VLOG_WARN_RL(&rl, "ignoring bridge with invalid name \"%s\"",
1693                          br_cfg->name);
1694         } else if (!shash_add_once(&new_br, br_cfg->name, br_cfg)) {
1695             VLOG_WARN_RL(&rl, "bridge %s specified twice", br_cfg->name);
1696         }
1697     }
1698
1699     /* Get rid of deleted bridges or those whose types have changed.
1700      * Update 'cfg' of bridges that still exist. */
1701     HMAP_FOR_EACH_SAFE (br, next, node, &all_bridges) {
1702         br->cfg = shash_find_data(&new_br, br->name);
1703         if (!br->cfg || strcmp(br->type, ofproto_normalize_type(
1704                                    br->cfg->datapath_type))) {
1705             bridge_destroy(br, true);
1706         }
1707     }
1708
1709     /* Add new bridges. */
1710     SHASH_FOR_EACH(node, &new_br) {
1711         const struct ovsrec_bridge *br_cfg = node->data;
1712         struct bridge *br = bridge_lookup(br_cfg->name);
1713         if (!br) {
1714             bridge_create(br_cfg);
1715         }
1716     }
1717
1718     shash_destroy(&new_br);
1719 }
1720
1721 /* Configures 'netdev' based on the "options" column in 'iface_cfg'.
1722  * Returns 0 if successful, otherwise a positive errno value. */
1723 static int
1724 iface_set_netdev_config(const struct ovsrec_interface *iface_cfg,
1725                         struct netdev *netdev, char **errp)
1726 {
1727     return netdev_set_config(netdev, &iface_cfg->options, errp);
1728 }
1729
1730 /* Opens a network device for 'if_cfg' and configures it.  Adds the network
1731  * device to br->ofproto and stores the OpenFlow port number in '*ofp_portp'.
1732  *
1733  * If successful, returns 0 and stores the network device in '*netdevp'.  On
1734  * failure, returns a positive errno value and stores NULL in '*netdevp'. */
1735 static int
1736 iface_do_create(const struct bridge *br,
1737                 const struct ovsrec_interface *iface_cfg,
1738                 ofp_port_t *ofp_portp, struct netdev **netdevp,
1739                 char **errp)
1740 {
1741     struct netdev *netdev = NULL;
1742     int error;
1743     const char *type;
1744
1745     if (netdev_is_reserved_name(iface_cfg->name)) {
1746         VLOG_WARN("could not create interface %s, name is reserved",
1747                   iface_cfg->name);
1748         error = EINVAL;
1749         goto error;
1750     }
1751
1752     type = ofproto_port_open_type(br->cfg->datapath_type,
1753                                   iface_get_type(iface_cfg, br->cfg));
1754     error = netdev_open(iface_cfg->name, type, &netdev);
1755     if (error) {
1756         VLOG_WARN_BUF(errp, "could not open network device %s (%s)",
1757                       iface_cfg->name, ovs_strerror(error));
1758         goto error;
1759     }
1760
1761     error = iface_set_netdev_config(iface_cfg, netdev, errp);
1762     if (error) {
1763         goto error;
1764     }
1765
1766     *ofp_portp = iface_pick_ofport(iface_cfg);
1767     error = ofproto_port_add(br->ofproto, netdev, ofp_portp);
1768     if (error) {
1769         goto error;
1770     }
1771
1772     VLOG_INFO("bridge %s: added interface %s on port %d",
1773               br->name, iface_cfg->name, *ofp_portp);
1774
1775     *netdevp = netdev;
1776     return 0;
1777
1778 error:
1779     *netdevp = NULL;
1780     netdev_close(netdev);
1781     return error;
1782 }
1783
1784 /* Creates a new iface on 'br' based on 'if_cfg'.  The new iface has OpenFlow
1785  * port number 'ofp_port'.  If ofp_port is OFPP_NONE, an OpenFlow port is
1786  * automatically allocated for the iface.  Takes ownership of and
1787  * deallocates 'if_cfg'.
1788  *
1789  * Return true if an iface is successfully created, false otherwise. */
1790 static bool
1791 iface_create(struct bridge *br, const struct ovsrec_interface *iface_cfg,
1792              const struct ovsrec_port *port_cfg)
1793 {
1794     struct netdev *netdev;
1795     struct iface *iface;
1796     ofp_port_t ofp_port;
1797     struct port *port;
1798     char *errp = NULL;
1799     int error;
1800
1801     /* Do the bits that can fail up front. */
1802     ovs_assert(!iface_lookup(br, iface_cfg->name));
1803     error = iface_do_create(br, iface_cfg, &ofp_port, &netdev, &errp);
1804     if (error) {
1805         iface_clear_db_record(iface_cfg, errp);
1806         free(errp);
1807         return false;
1808     }
1809
1810     /* Get or create the port structure. */
1811     port = port_lookup(br, port_cfg->name);
1812     if (!port) {
1813         port = port_create(br, port_cfg);
1814     }
1815
1816     /* Create the iface structure. */
1817     iface = xzalloc(sizeof *iface);
1818     ovs_list_push_back(&port->ifaces, &iface->port_elem);
1819     hmap_insert(&br->iface_by_name, &iface->name_node,
1820                 hash_string(iface_cfg->name, 0));
1821     iface->port = port;
1822     iface->name = xstrdup(iface_cfg->name);
1823     iface->ofp_port = ofp_port;
1824     iface->netdev = netdev;
1825     iface->type = iface_get_type(iface_cfg, br->cfg);
1826     iface->netdev_type = ofproto_port_open_type(br->cfg->datapath_type,
1827                                                 iface->type);
1828     iface->cfg = iface_cfg;
1829     hmap_insert(&br->ifaces, &iface->ofp_port_node,
1830                 hash_ofp_port(ofp_port));
1831
1832     /* Populate initial status in database. */
1833     iface_refresh_stats(iface);
1834     iface_refresh_netdev_status(iface);
1835
1836     /* Add bond fake iface if necessary. */
1837     if (port_is_bond_fake_iface(port)) {
1838         struct ofproto_port ofproto_port;
1839
1840         if (ofproto_port_query_by_name(br->ofproto, port->name,
1841                                        &ofproto_port)) {
1842             struct netdev *netdev;
1843             int error;
1844
1845             error = netdev_open(port->name, "internal", &netdev);
1846             if (!error) {
1847                 ofp_port_t fake_ofp_port = OFPP_NONE;
1848                 ofproto_port_add(br->ofproto, netdev, &fake_ofp_port);
1849                 netdev_close(netdev);
1850             } else {
1851                 VLOG_WARN("could not open network device %s (%s)",
1852                           port->name, ovs_strerror(error));
1853             }
1854         } else {
1855             /* Already exists, nothing to do. */
1856             ofproto_port_destroy(&ofproto_port);
1857         }
1858     }
1859
1860     return true;
1861 }
1862
1863 /* Set forward BPDU option. */
1864 static void
1865 bridge_configure_forward_bpdu(struct bridge *br)
1866 {
1867     ofproto_set_forward_bpdu(br->ofproto,
1868                              smap_get_bool(&br->cfg->other_config,
1869                                            "forward-bpdu",
1870                                            false));
1871 }
1872
1873 /* Set MAC learning table configuration for 'br'. */
1874 static void
1875 bridge_configure_mac_table(struct bridge *br)
1876 {
1877     const char *idle_time_str;
1878     int idle_time;
1879
1880     const char *mac_table_size_str;
1881     int mac_table_size;
1882
1883     idle_time_str = smap_get(&br->cfg->other_config, "mac-aging-time");
1884     idle_time = (idle_time_str && atoi(idle_time_str)
1885                  ? atoi(idle_time_str)
1886                  : MAC_ENTRY_DEFAULT_IDLE_TIME);
1887
1888     mac_table_size_str = smap_get(&br->cfg->other_config, "mac-table-size");
1889     mac_table_size = (mac_table_size_str && atoi(mac_table_size_str)
1890                       ? atoi(mac_table_size_str)
1891                       : MAC_DEFAULT_MAX);
1892
1893     ofproto_set_mac_table_config(br->ofproto, idle_time, mac_table_size);
1894 }
1895
1896 /* Set multicast snooping table configuration for 'br'. */
1897 static void
1898 bridge_configure_mcast_snooping(struct bridge *br)
1899 {
1900     if (!br->cfg->mcast_snooping_enable) {
1901         ofproto_set_mcast_snooping(br->ofproto, NULL);
1902     } else {
1903         struct port *port;
1904         struct ofproto_mcast_snooping_settings br_s;
1905         const char *idle_time_str;
1906         const char *max_entries_str;
1907
1908         idle_time_str = smap_get(&br->cfg->other_config,
1909                                  "mcast-snooping-aging-time");
1910         br_s.idle_time = (idle_time_str && atoi(idle_time_str)
1911                           ? atoi(idle_time_str)
1912                           : MCAST_ENTRY_DEFAULT_IDLE_TIME);
1913
1914         max_entries_str = smap_get(&br->cfg->other_config,
1915                                    "mcast-snooping-table-size");
1916         br_s.max_entries = (max_entries_str && atoi(max_entries_str)
1917                             ? atoi(max_entries_str)
1918                             : MCAST_DEFAULT_MAX_ENTRIES);
1919
1920         br_s.flood_unreg = !smap_get_bool(&br->cfg->other_config,
1921                                     "mcast-snooping-disable-flood-unregistered",
1922                                     false);
1923
1924         /* Configure multicast snooping on the bridge */
1925         if (ofproto_set_mcast_snooping(br->ofproto, &br_s)) {
1926             VLOG_ERR("bridge %s: could not enable multicast snooping",
1927                      br->name);
1928             return;
1929         }
1930
1931         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1932             struct ofproto_mcast_snooping_port_settings port_s;
1933             port_s.flood = smap_get_bool(&port->cfg->other_config,
1934                                        "mcast-snooping-flood", false);
1935             port_s.flood_reports = smap_get_bool(&port->cfg->other_config,
1936                                        "mcast-snooping-flood-reports", false);
1937             if (ofproto_port_set_mcast_snooping(br->ofproto, port, &port_s)) {
1938                 VLOG_ERR("port %s: could not configure mcast snooping",
1939                          port->name);
1940             }
1941         }
1942     }
1943 }
1944
1945 static void
1946 find_local_hw_addr(const struct bridge *br, struct eth_addr *ea,
1947                    const struct port *fake_br, struct iface **hw_addr_iface)
1948 {
1949     struct hmapx mirror_output_ports;
1950     struct port *port;
1951     bool found_addr = false;
1952     int error;
1953     int i;
1954
1955     /* Mirror output ports don't participate in picking the local hardware
1956      * address.  ofproto can't help us find out whether a given port is a
1957      * mirror output because we haven't configured mirrors yet, so we need to
1958      * accumulate them ourselves. */
1959     hmapx_init(&mirror_output_ports);
1960     for (i = 0; i < br->cfg->n_mirrors; i++) {
1961         struct ovsrec_mirror *m = br->cfg->mirrors[i];
1962         if (m->output_port) {
1963             hmapx_add(&mirror_output_ports, m->output_port);
1964         }
1965     }
1966
1967     /* Otherwise choose the minimum non-local MAC address among all of the
1968      * interfaces. */
1969     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1970         struct eth_addr iface_ea;
1971         struct iface *candidate;
1972         struct iface *iface;
1973
1974         /* Mirror output ports don't participate. */
1975         if (hmapx_contains(&mirror_output_ports, port->cfg)) {
1976             continue;
1977         }
1978
1979         /* Choose the MAC address to represent the port. */
1980         iface = NULL;
1981         if (port->cfg->mac && eth_addr_from_string(port->cfg->mac,
1982                                                    &iface_ea)) {
1983             /* Find the interface with this Ethernet address (if any) so that
1984              * we can provide the correct devname to the caller. */
1985             LIST_FOR_EACH (candidate, port_elem, &port->ifaces) {
1986                 struct eth_addr candidate_ea;
1987                 if (!netdev_get_etheraddr(candidate->netdev, &candidate_ea)
1988                     && eth_addr_equals(iface_ea, candidate_ea)) {
1989                     iface = candidate;
1990                 }
1991             }
1992         } else {
1993             /* Choose the interface whose MAC address will represent the port.
1994              * The Linux kernel bonding code always chooses the MAC address of
1995              * the first slave added to a bond, and the Fedora networking
1996              * scripts always add slaves to a bond in alphabetical order, so
1997              * for compatibility we choose the interface with the name that is
1998              * first in alphabetical order. */
1999             LIST_FOR_EACH (candidate, port_elem, &port->ifaces) {
2000                 if (!iface || strcmp(candidate->name, iface->name) < 0) {
2001                     iface = candidate;
2002                 }
2003             }
2004
2005             /* A port always has at least one interface. */
2006             ovs_assert(iface != NULL);
2007
2008             /* The local port doesn't count (since we're trying to choose its
2009              * MAC address anyway). */
2010             if (iface->ofp_port == OFPP_LOCAL) {
2011                 continue;
2012             }
2013
2014             /* For fake bridges we only choose from ports with the same tag */
2015             if (fake_br && fake_br->cfg && fake_br->cfg->tag) {
2016                 if (!port->cfg->tag) {
2017                     continue;
2018                 }
2019                 if (*port->cfg->tag != *fake_br->cfg->tag) {
2020                     continue;
2021                 }
2022             }
2023
2024             /* Grab MAC. */
2025             error = netdev_get_etheraddr(iface->netdev, &iface_ea);
2026             if (error) {
2027                 continue;
2028             }
2029         }
2030
2031         /* Compare against our current choice. */
2032         if (!eth_addr_is_multicast(iface_ea) &&
2033             !eth_addr_is_local(iface_ea) &&
2034             !eth_addr_is_reserved(iface_ea) &&
2035             !eth_addr_is_zero(iface_ea) &&
2036             (!found_addr || eth_addr_compare_3way(iface_ea, *ea) < 0))
2037         {
2038             *ea = iface_ea;
2039             *hw_addr_iface = iface;
2040             found_addr = true;
2041         }
2042     }
2043
2044     if (!found_addr) {
2045         *ea = br->default_ea;
2046         *hw_addr_iface = NULL;
2047     }
2048
2049     hmapx_destroy(&mirror_output_ports);
2050 }
2051
2052 static void
2053 bridge_pick_local_hw_addr(struct bridge *br, struct eth_addr *ea,
2054                           struct iface **hw_addr_iface)
2055 {
2056     const char *hwaddr;
2057     *hw_addr_iface = NULL;
2058
2059     /* Did the user request a particular MAC? */
2060     hwaddr = smap_get(&br->cfg->other_config, "hwaddr");
2061     if (hwaddr && eth_addr_from_string(hwaddr, ea)) {
2062         if (eth_addr_is_multicast(*ea)) {
2063             VLOG_ERR("bridge %s: cannot set MAC address to multicast "
2064                      "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(*ea));
2065         } else if (eth_addr_is_zero(*ea)) {
2066             VLOG_ERR("bridge %s: cannot set MAC address to zero", br->name);
2067         } else {
2068             return;
2069         }
2070     }
2071
2072     /* Find a local hw address */
2073     find_local_hw_addr(br, ea, NULL, hw_addr_iface);
2074 }
2075
2076 /* Choose and returns the datapath ID for bridge 'br' given that the bridge
2077  * Ethernet address is 'bridge_ea'.  If 'bridge_ea' is the Ethernet address of
2078  * an interface on 'br', then that interface must be passed in as
2079  * 'hw_addr_iface'; if 'bridge_ea' was derived some other way, then
2080  * 'hw_addr_iface' must be passed in as a null pointer. */
2081 static uint64_t
2082 bridge_pick_datapath_id(struct bridge *br,
2083                         const struct eth_addr bridge_ea,
2084                         struct iface *hw_addr_iface)
2085 {
2086     /*
2087      * The procedure for choosing a bridge MAC address will, in the most
2088      * ordinary case, also choose a unique MAC that we can use as a datapath
2089      * ID.  In some special cases, though, multiple bridges will end up with
2090      * the same MAC address.  This is OK for the bridges, but it will confuse
2091      * the OpenFlow controller, because each datapath needs a unique datapath
2092      * ID.
2093      *
2094      * Datapath IDs must be unique.  It is also very desirable that they be
2095      * stable from one run to the next, so that policy set on a datapath
2096      * "sticks".
2097      */
2098     const char *datapath_id;
2099     uint64_t dpid;
2100
2101     datapath_id = smap_get(&br->cfg->other_config, "datapath-id");
2102     if (datapath_id && dpid_from_string(datapath_id, &dpid)) {
2103         return dpid;
2104     }
2105
2106     if (!hw_addr_iface) {
2107         /*
2108          * A purely internal bridge, that is, one that has no non-virtual
2109          * network devices on it at all, is difficult because it has no
2110          * natural unique identifier at all.
2111          *
2112          * When the host is a XenServer, we handle this case by hashing the
2113          * host's UUID with the name of the bridge.  Names of bridges are
2114          * persistent across XenServer reboots, although they can be reused if
2115          * an internal network is destroyed and then a new one is later
2116          * created, so this is fairly effective.
2117          *
2118          * When the host is not a XenServer, we punt by using a random MAC
2119          * address on each run.
2120          */
2121         const char *host_uuid = xenserver_get_host_uuid();
2122         if (host_uuid) {
2123             char *combined = xasprintf("%s,%s", host_uuid, br->name);
2124             dpid = dpid_from_hash(combined, strlen(combined));
2125             free(combined);
2126             return dpid;
2127         }
2128     }
2129
2130     return eth_addr_to_uint64(bridge_ea);
2131 }
2132
2133 static uint64_t
2134 dpid_from_hash(const void *data, size_t n)
2135 {
2136     union {
2137         uint8_t bytes[SHA1_DIGEST_SIZE];
2138         struct eth_addr ea;
2139     } hash;
2140
2141     sha1_bytes(data, n, hash.bytes);
2142     eth_addr_mark_random(&hash.ea);
2143     return eth_addr_to_uint64(hash.ea);
2144 }
2145
2146 static void
2147 iface_refresh_netdev_status(struct iface *iface)
2148 {
2149     struct smap smap;
2150
2151     enum netdev_features current;
2152     enum netdev_flags flags;
2153     const char *link_state;
2154     struct eth_addr mac;
2155     int64_t bps, mtu_64, ifindex64, link_resets;
2156     int mtu, error;
2157
2158     if (iface_is_synthetic(iface)) {
2159         return;
2160     }
2161
2162     if (iface->change_seq == netdev_get_change_seq(iface->netdev)
2163         && !status_txn_try_again) {
2164         return;
2165     }
2166
2167     iface->change_seq = netdev_get_change_seq(iface->netdev);
2168
2169     smap_init(&smap);
2170
2171     if (!netdev_get_status(iface->netdev, &smap)) {
2172         ovsrec_interface_set_status(iface->cfg, &smap);
2173     } else {
2174         ovsrec_interface_set_status(iface->cfg, NULL);
2175     }
2176
2177     smap_destroy(&smap);
2178
2179     error = netdev_get_flags(iface->netdev, &flags);
2180     if (!error) {
2181         const char *state = flags & NETDEV_UP ? "up" : "down";
2182
2183         ovsrec_interface_set_admin_state(iface->cfg, state);
2184     } else {
2185         ovsrec_interface_set_admin_state(iface->cfg, NULL);
2186     }
2187
2188     link_state = netdev_get_carrier(iface->netdev) ? "up" : "down";
2189     ovsrec_interface_set_link_state(iface->cfg, link_state);
2190
2191     link_resets = netdev_get_carrier_resets(iface->netdev);
2192     ovsrec_interface_set_link_resets(iface->cfg, &link_resets, 1);
2193
2194     error = netdev_get_features(iface->netdev, &current, NULL, NULL, NULL);
2195     bps = !error ? netdev_features_to_bps(current, 0) : 0;
2196     if (bps) {
2197         ovsrec_interface_set_duplex(iface->cfg,
2198                                     netdev_features_is_full_duplex(current)
2199                                     ? "full" : "half");
2200         ovsrec_interface_set_link_speed(iface->cfg, &bps, 1);
2201     } else {
2202         ovsrec_interface_set_duplex(iface->cfg, NULL);
2203         ovsrec_interface_set_link_speed(iface->cfg, NULL, 0);
2204     }
2205
2206     error = netdev_get_mtu(iface->netdev, &mtu);
2207     if (!error) {
2208         mtu_64 = mtu;
2209         ovsrec_interface_set_mtu(iface->cfg, &mtu_64, 1);
2210     } else {
2211         ovsrec_interface_set_mtu(iface->cfg, NULL, 0);
2212     }
2213
2214     error = netdev_get_etheraddr(iface->netdev, &mac);
2215     if (!error) {
2216         char mac_string[ETH_ADDR_STRLEN + 1];
2217
2218         snprintf(mac_string, sizeof mac_string,
2219                  ETH_ADDR_FMT, ETH_ADDR_ARGS(mac));
2220         ovsrec_interface_set_mac_in_use(iface->cfg, mac_string);
2221     } else {
2222         ovsrec_interface_set_mac_in_use(iface->cfg, NULL);
2223     }
2224
2225     /* The netdev may return a negative number (such as -EOPNOTSUPP)
2226      * if there is no valid ifindex number. */
2227     ifindex64 = netdev_get_ifindex(iface->netdev);
2228     if (ifindex64 < 0) {
2229         ifindex64 = 0;
2230     }
2231     ovsrec_interface_set_ifindex(iface->cfg, &ifindex64, 1);
2232 }
2233
2234 static void
2235 iface_refresh_ofproto_status(struct iface *iface)
2236 {
2237     int current;
2238
2239     if (iface_is_synthetic(iface)) {
2240         return;
2241     }
2242
2243     current = ofproto_port_is_lacp_current(iface->port->bridge->ofproto,
2244                                            iface->ofp_port);
2245     if (current >= 0) {
2246         bool bl = current;
2247         ovsrec_interface_set_lacp_current(iface->cfg, &bl, 1);
2248     } else {
2249         ovsrec_interface_set_lacp_current(iface->cfg, NULL, 0);
2250     }
2251
2252     if (ofproto_port_cfm_status_changed(iface->port->bridge->ofproto,
2253                                         iface->ofp_port)
2254         || status_txn_try_again) {
2255         iface_refresh_cfm_stats(iface);
2256     }
2257
2258     if (ofproto_port_bfd_status_changed(iface->port->bridge->ofproto,
2259                                         iface->ofp_port)
2260         || status_txn_try_again) {
2261         struct smap smap;
2262
2263         smap_init(&smap);
2264         ofproto_port_get_bfd_status(iface->port->bridge->ofproto,
2265                                     iface->ofp_port, &smap);
2266         ovsrec_interface_set_bfd_status(iface->cfg, &smap);
2267         smap_destroy(&smap);
2268     }
2269 }
2270
2271 /* Writes 'iface''s CFM statistics to the database. 'iface' must not be
2272  * synthetic. */
2273 static void
2274 iface_refresh_cfm_stats(struct iface *iface)
2275 {
2276     const struct ovsrec_interface *cfg = iface->cfg;
2277     struct cfm_status status;
2278     int error;
2279
2280     error = ofproto_port_get_cfm_status(iface->port->bridge->ofproto,
2281                                         iface->ofp_port, &status);
2282     if (error > 0) {
2283         ovsrec_interface_set_cfm_fault(cfg, NULL, 0);
2284         ovsrec_interface_set_cfm_fault_status(cfg, NULL, 0);
2285         ovsrec_interface_set_cfm_remote_opstate(cfg, NULL);
2286         ovsrec_interface_set_cfm_flap_count(cfg, NULL, 0);
2287         ovsrec_interface_set_cfm_health(cfg, NULL, 0);
2288         ovsrec_interface_set_cfm_remote_mpids(cfg, NULL, 0);
2289     } else {
2290         const char *reasons[CFM_FAULT_N_REASONS];
2291         int64_t cfm_health = status.health;
2292         int64_t cfm_flap_count = status.flap_count;
2293         bool faulted = status.faults != 0;
2294         size_t i, j;
2295
2296         ovsrec_interface_set_cfm_fault(cfg, &faulted, 1);
2297
2298         j = 0;
2299         for (i = 0; i < CFM_FAULT_N_REASONS; i++) {
2300             int reason = 1 << i;
2301             if (status.faults & reason) {
2302                 reasons[j++] = cfm_fault_reason_to_str(reason);
2303             }
2304         }
2305         ovsrec_interface_set_cfm_fault_status(cfg, reasons, j);
2306
2307         ovsrec_interface_set_cfm_flap_count(cfg, &cfm_flap_count, 1);
2308
2309         if (status.remote_opstate >= 0) {
2310             const char *remote_opstate = status.remote_opstate ? "up" : "down";
2311             ovsrec_interface_set_cfm_remote_opstate(cfg, remote_opstate);
2312         } else {
2313             ovsrec_interface_set_cfm_remote_opstate(cfg, NULL);
2314         }
2315
2316         ovsrec_interface_set_cfm_remote_mpids(cfg,
2317                                               (const int64_t *)status.rmps,
2318                                               status.n_rmps);
2319         if (cfm_health >= 0) {
2320             ovsrec_interface_set_cfm_health(cfg, &cfm_health, 1);
2321         } else {
2322             ovsrec_interface_set_cfm_health(cfg, NULL, 0);
2323         }
2324
2325         free(status.rmps);
2326     }
2327 }
2328
2329 static void
2330 iface_refresh_stats(struct iface *iface)
2331 {
2332 #define IFACE_STATS                             \
2333     IFACE_STAT(rx_packets,              "rx_packets")               \
2334     IFACE_STAT(tx_packets,              "tx_packets")               \
2335     IFACE_STAT(rx_bytes,                "rx_bytes")                 \
2336     IFACE_STAT(tx_bytes,                "tx_bytes")                 \
2337     IFACE_STAT(rx_dropped,              "rx_dropped")               \
2338     IFACE_STAT(tx_dropped,              "tx_dropped")               \
2339     IFACE_STAT(rx_errors,               "rx_errors")                \
2340     IFACE_STAT(tx_errors,               "tx_errors")                \
2341     IFACE_STAT(rx_frame_errors,         "rx_frame_err")             \
2342     IFACE_STAT(rx_over_errors,          "rx_over_err")              \
2343     IFACE_STAT(rx_crc_errors,           "rx_crc_err")               \
2344     IFACE_STAT(collisions,              "collisions")               \
2345     IFACE_STAT(rx_1_to_64_packets,      "rx_1_to_64_packets")       \
2346     IFACE_STAT(rx_65_to_127_packets,    "rx_65_to_127_packets")     \
2347     IFACE_STAT(rx_128_to_255_packets,   "rx_128_to_255_packets")    \
2348     IFACE_STAT(rx_256_to_511_packets,   "rx_256_to_511_packets")    \
2349     IFACE_STAT(rx_512_to_1023_packets,  "rx_512_to_1023_packets")   \
2350     IFACE_STAT(rx_1024_to_1522_packets, "rx_1024_to_1518_packets")  \
2351     IFACE_STAT(rx_1523_to_max_packets,  "rx_1523_to_max_packets")   \
2352     IFACE_STAT(tx_1_to_64_packets,      "tx_1_to_64_packets")       \
2353     IFACE_STAT(tx_65_to_127_packets,    "tx_65_to_127_packets")     \
2354     IFACE_STAT(tx_128_to_255_packets,   "tx_128_to_255_packets")    \
2355     IFACE_STAT(tx_256_to_511_packets,   "tx_256_to_511_packets")    \
2356     IFACE_STAT(tx_512_to_1023_packets,  "tx_512_to_1023_packets")   \
2357     IFACE_STAT(tx_1024_to_1522_packets, "tx_1024_to_1518_packets")  \
2358     IFACE_STAT(tx_1523_to_max_packets,  "tx_1523_to_max_packets")   \
2359     IFACE_STAT(tx_multicast_packets,    "tx_multicast_packets")     \
2360     IFACE_STAT(rx_broadcast_packets,    "rx_broadcast_packets")     \
2361     IFACE_STAT(tx_broadcast_packets,    "tx_broadcast_packets")     \
2362     IFACE_STAT(rx_undersized_errors,    "rx_undersized_errors")     \
2363     IFACE_STAT(rx_oversize_errors,      "rx_oversize_errors")       \
2364     IFACE_STAT(rx_fragmented_errors,    "rx_fragmented_errors")     \
2365     IFACE_STAT(rx_jabber_errors,        "rx_jabber_errors")
2366
2367 #define IFACE_STAT(MEMBER, NAME) + 1
2368     enum { N_IFACE_STATS = IFACE_STATS };
2369 #undef IFACE_STAT
2370     int64_t values[N_IFACE_STATS];
2371     const char *keys[N_IFACE_STATS];
2372     int n;
2373
2374     struct netdev_stats stats;
2375
2376     if (iface_is_synthetic(iface)) {
2377         return;
2378     }
2379
2380     /* Intentionally ignore return value, since errors will set 'stats' to
2381      * all-1s, and we will deal with that correctly below. */
2382     netdev_get_stats(iface->netdev, &stats);
2383
2384     /* Copy statistics into keys[] and values[]. */
2385     n = 0;
2386 #define IFACE_STAT(MEMBER, NAME)                \
2387     if (stats.MEMBER != UINT64_MAX) {           \
2388         keys[n] = NAME;                         \
2389         values[n] = stats.MEMBER;               \
2390         n++;                                    \
2391     }
2392     IFACE_STATS;
2393 #undef IFACE_STAT
2394     ovs_assert(n <= N_IFACE_STATS);
2395
2396     ovsrec_interface_set_statistics(iface->cfg, keys, values, n);
2397 #undef IFACE_STATS
2398 }
2399
2400 static void
2401 br_refresh_datapath_info(struct bridge *br)
2402 {
2403     const char *version;
2404
2405     version = (br->ofproto && br->ofproto->ofproto_class->get_datapath_version
2406                ? br->ofproto->ofproto_class->get_datapath_version(br->ofproto)
2407                : NULL);
2408
2409     ovsrec_bridge_set_datapath_version(br->cfg,
2410                                        version ? version : "<unknown>");
2411 }
2412
2413 static void
2414 br_refresh_stp_status(struct bridge *br)
2415 {
2416     struct smap smap = SMAP_INITIALIZER(&smap);
2417     struct ofproto *ofproto = br->ofproto;
2418     struct ofproto_stp_status status;
2419
2420     if (ofproto_get_stp_status(ofproto, &status)) {
2421         return;
2422     }
2423
2424     if (!status.enabled) {
2425         ovsrec_bridge_set_status(br->cfg, NULL);
2426         return;
2427     }
2428
2429     smap_add_format(&smap, "stp_bridge_id", STP_ID_FMT,
2430                     STP_ID_ARGS(status.bridge_id));
2431     smap_add_format(&smap, "stp_designated_root", STP_ID_FMT,
2432                     STP_ID_ARGS(status.designated_root));
2433     smap_add_format(&smap, "stp_root_path_cost", "%d", status.root_path_cost);
2434
2435     ovsrec_bridge_set_status(br->cfg, &smap);
2436     smap_destroy(&smap);
2437 }
2438
2439 static void
2440 port_refresh_stp_status(struct port *port)
2441 {
2442     struct ofproto *ofproto = port->bridge->ofproto;
2443     struct iface *iface;
2444     struct ofproto_port_stp_status status;
2445     struct smap smap;
2446
2447     if (port_is_synthetic(port)) {
2448         return;
2449     }
2450
2451     /* STP doesn't currently support bonds. */
2452     if (!ovs_list_is_singleton(&port->ifaces)) {
2453         ovsrec_port_set_status(port->cfg, NULL);
2454         return;
2455     }
2456
2457     iface = CONTAINER_OF(ovs_list_front(&port->ifaces), struct iface, port_elem);
2458     if (ofproto_port_get_stp_status(ofproto, iface->ofp_port, &status)) {
2459         return;
2460     }
2461
2462     if (!status.enabled) {
2463         ovsrec_port_set_status(port->cfg, NULL);
2464         return;
2465     }
2466
2467     /* Set Status column. */
2468     smap_init(&smap);
2469     smap_add_format(&smap, "stp_port_id", STP_PORT_ID_FMT, status.port_id);
2470     smap_add(&smap, "stp_state", stp_state_name(status.state));
2471     smap_add_format(&smap, "stp_sec_in_state", "%u", status.sec_in_state);
2472     smap_add(&smap, "stp_role", stp_role_name(status.role));
2473     ovsrec_port_set_status(port->cfg, &smap);
2474     smap_destroy(&smap);
2475 }
2476
2477 static void
2478 port_refresh_stp_stats(struct port *port)
2479 {
2480     struct ofproto *ofproto = port->bridge->ofproto;
2481     struct iface *iface;
2482     struct ofproto_port_stp_stats stats;
2483     const char *keys[3];
2484     int64_t int_values[3];
2485
2486     if (port_is_synthetic(port)) {
2487         return;
2488     }
2489
2490     /* STP doesn't currently support bonds. */
2491     if (!ovs_list_is_singleton(&port->ifaces)) {
2492         return;
2493     }
2494
2495     iface = CONTAINER_OF(ovs_list_front(&port->ifaces), struct iface, port_elem);
2496     if (ofproto_port_get_stp_stats(ofproto, iface->ofp_port, &stats)) {
2497         return;
2498     }
2499
2500     if (!stats.enabled) {
2501         ovsrec_port_set_statistics(port->cfg, NULL, NULL, 0);
2502         return;
2503     }
2504
2505     /* Set Statistics column. */
2506     keys[0] = "stp_tx_count";
2507     int_values[0] = stats.tx_count;
2508     keys[1] = "stp_rx_count";
2509     int_values[1] = stats.rx_count;
2510     keys[2] = "stp_error_count";
2511     int_values[2] = stats.error_count;
2512
2513     ovsrec_port_set_statistics(port->cfg, keys, int_values,
2514                                ARRAY_SIZE(int_values));
2515 }
2516
2517 static void
2518 br_refresh_rstp_status(struct bridge *br)
2519 {
2520     struct smap smap = SMAP_INITIALIZER(&smap);
2521     struct ofproto *ofproto = br->ofproto;
2522     struct ofproto_rstp_status status;
2523
2524     if (ofproto_get_rstp_status(ofproto, &status)) {
2525         return;
2526     }
2527     if (!status.enabled) {
2528         ovsrec_bridge_set_rstp_status(br->cfg, NULL);
2529         return;
2530     }
2531     smap_add_format(&smap, "rstp_bridge_id", RSTP_ID_FMT,
2532                     RSTP_ID_ARGS(status.bridge_id));
2533     smap_add_format(&smap, "rstp_root_path_cost", "%"PRIu32,
2534                     status.root_path_cost);
2535     smap_add_format(&smap, "rstp_root_id", RSTP_ID_FMT,
2536                     RSTP_ID_ARGS(status.root_id));
2537     smap_add_format(&smap, "rstp_designated_id", RSTP_ID_FMT,
2538                     RSTP_ID_ARGS(status.designated_id));
2539     smap_add_format(&smap, "rstp_designated_port_id", RSTP_PORT_ID_FMT,
2540                     status.designated_port_id);
2541     smap_add_format(&smap, "rstp_bridge_port_id", RSTP_PORT_ID_FMT,
2542                     status.bridge_port_id);
2543     ovsrec_bridge_set_rstp_status(br->cfg, &smap);
2544     smap_destroy(&smap);
2545 }
2546
2547 static void
2548 port_refresh_rstp_status(struct port *port)
2549 {
2550     struct ofproto *ofproto = port->bridge->ofproto;
2551     struct iface *iface;
2552     struct ofproto_port_rstp_status status;
2553     const char *keys[4];
2554     int64_t int_values[4];
2555     struct smap smap;
2556
2557     if (port_is_synthetic(port)) {
2558         return;
2559     }
2560
2561     /* RSTP doesn't currently support bonds. */
2562     if (!ovs_list_is_singleton(&port->ifaces)) {
2563         ovsrec_port_set_rstp_status(port->cfg, NULL);
2564         return;
2565     }
2566
2567     iface = CONTAINER_OF(ovs_list_front(&port->ifaces), struct iface, port_elem);
2568     if (ofproto_port_get_rstp_status(ofproto, iface->ofp_port, &status)) {
2569         return;
2570     }
2571
2572     if (!status.enabled) {
2573         ovsrec_port_set_rstp_status(port->cfg, NULL);
2574         ovsrec_port_set_rstp_statistics(port->cfg, NULL, NULL, 0);
2575         return;
2576     }
2577     /* Set Status column. */
2578     smap_init(&smap);
2579
2580     smap_add_format(&smap, "rstp_port_id", RSTP_PORT_ID_FMT,
2581                     status.port_id);
2582     smap_add_format(&smap, "rstp_port_role", "%s",
2583                     rstp_port_role_name(status.role));
2584     smap_add_format(&smap, "rstp_port_state", "%s",
2585                     rstp_state_name(status.state));
2586     smap_add_format(&smap, "rstp_designated_bridge_id", RSTP_ID_FMT,
2587                     RSTP_ID_ARGS(status.designated_bridge_id));
2588     smap_add_format(&smap, "rstp_designated_port_id", RSTP_PORT_ID_FMT,
2589                     status.designated_port_id);
2590     smap_add_format(&smap, "rstp_designated_path_cost", "%"PRIu32,
2591                     status.designated_path_cost);
2592
2593     ovsrec_port_set_rstp_status(port->cfg, &smap);
2594     smap_destroy(&smap);
2595
2596     /* Set Statistics column. */
2597     keys[0] = "rstp_tx_count";
2598     int_values[0] = status.tx_count;
2599     keys[1] = "rstp_rx_count";
2600     int_values[1] = status.rx_count;
2601     keys[2] = "rstp_uptime";
2602     int_values[2] = status.uptime;
2603     keys[3] = "rstp_error_count";
2604     int_values[3] = status.error_count;
2605     ovsrec_port_set_rstp_statistics(port->cfg, keys, int_values,
2606             ARRAY_SIZE(int_values));
2607 }
2608
2609 static void
2610 port_refresh_bond_status(struct port *port, bool force_update)
2611 {
2612     struct eth_addr mac;
2613
2614     /* Return if port is not a bond */
2615     if (ovs_list_is_singleton(&port->ifaces)) {
2616         return;
2617     }
2618
2619     if (bond_get_changed_active_slave(port->name, &mac, force_update)) {
2620         struct ds mac_s;
2621
2622         ds_init(&mac_s);
2623         ds_put_format(&mac_s, ETH_ADDR_FMT, ETH_ADDR_ARGS(mac));
2624         ovsrec_port_set_bond_active_slave(port->cfg, ds_cstr(&mac_s));
2625         ds_destroy(&mac_s);
2626     }
2627 }
2628
2629 static bool
2630 enable_system_stats(const struct ovsrec_open_vswitch *cfg)
2631 {
2632     return smap_get_bool(&cfg->other_config, "enable-statistics", false);
2633 }
2634
2635 static void
2636 reconfigure_system_stats(const struct ovsrec_open_vswitch *cfg)
2637 {
2638     bool enable = enable_system_stats(cfg);
2639
2640     system_stats_enable(enable);
2641     if (!enable) {
2642         ovsrec_open_vswitch_set_statistics(cfg, NULL);
2643     }
2644 }
2645
2646 static void
2647 run_system_stats(void)
2648 {
2649     const struct ovsrec_open_vswitch *cfg = ovsrec_open_vswitch_first(idl);
2650     struct smap *stats;
2651
2652     stats = system_stats_run();
2653     if (stats && cfg) {
2654         struct ovsdb_idl_txn *txn;
2655         struct ovsdb_datum datum;
2656
2657         txn = ovsdb_idl_txn_create(idl);
2658         ovsdb_datum_from_smap(&datum, stats);
2659         ovsdb_idl_txn_write(&cfg->header_, &ovsrec_open_vswitch_col_statistics,
2660                             &datum);
2661         ovsdb_idl_txn_commit(txn);
2662         ovsdb_idl_txn_destroy(txn);
2663
2664         free(stats);
2665     }
2666 }
2667
2668 static const char *
2669 ofp12_controller_role_to_str(enum ofp12_controller_role role)
2670 {
2671     switch (role) {
2672     case OFPCR12_ROLE_EQUAL:
2673         return "other";
2674     case OFPCR12_ROLE_MASTER:
2675         return "master";
2676     case OFPCR12_ROLE_SLAVE:
2677         return "slave";
2678     case OFPCR12_ROLE_NOCHANGE:
2679     default:
2680         return "*** INVALID ROLE ***";
2681     }
2682 }
2683
2684 static void
2685 refresh_controller_status(void)
2686 {
2687     struct bridge *br;
2688     struct shash info;
2689     const struct ovsrec_controller *cfg;
2690
2691     shash_init(&info);
2692
2693     /* Accumulate status for controllers on all bridges. */
2694     HMAP_FOR_EACH (br, node, &all_bridges) {
2695         ofproto_get_ofproto_controller_info(br->ofproto, &info);
2696     }
2697
2698     /* Update each controller in the database with current status. */
2699     OVSREC_CONTROLLER_FOR_EACH(cfg, idl) {
2700         struct ofproto_controller_info *cinfo =
2701             shash_find_data(&info, cfg->target);
2702
2703         if (cinfo) {
2704             ovsrec_controller_set_is_connected(cfg, cinfo->is_connected);
2705             ovsrec_controller_set_role(cfg, ofp12_controller_role_to_str(
2706                                            cinfo->role));
2707             ovsrec_controller_set_status(cfg, &cinfo->pairs);
2708         } else {
2709             ovsrec_controller_set_is_connected(cfg, false);
2710             ovsrec_controller_set_role(cfg, NULL);
2711             ovsrec_controller_set_status(cfg, NULL);
2712         }
2713     }
2714
2715     ofproto_free_ofproto_controller_info(&info);
2716 }
2717 \f
2718 /* Update interface and mirror statistics if necessary. */
2719 static void
2720 run_stats_update(void)
2721 {
2722     const struct ovsrec_open_vswitch *cfg = ovsrec_open_vswitch_first(idl);
2723     int stats_interval;
2724
2725     if (!cfg) {
2726         return;
2727     }
2728
2729     /* Statistics update interval should always be greater than or equal to
2730      * 5000 ms. */
2731     stats_interval = MAX(smap_get_int(&cfg->other_config,
2732                                       "stats-update-interval",
2733                                       5000), 5000);
2734     if (stats_timer_interval != stats_interval) {
2735         stats_timer_interval = stats_interval;
2736         stats_timer = LLONG_MIN;
2737     }
2738
2739     if (time_msec() >= stats_timer) {
2740         enum ovsdb_idl_txn_status status;
2741
2742         /* Rate limit the update.  Do not start a new update if the
2743          * previous one is not done. */
2744         if (!stats_txn) {
2745             struct bridge *br;
2746
2747             stats_txn = ovsdb_idl_txn_create(idl);
2748             HMAP_FOR_EACH (br, node, &all_bridges) {
2749                 struct port *port;
2750                 struct mirror *m;
2751
2752                 HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2753                     struct iface *iface;
2754
2755                     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2756                         iface_refresh_stats(iface);
2757                     }
2758                     port_refresh_stp_stats(port);
2759                 }
2760                 HMAP_FOR_EACH (m, hmap_node, &br->mirrors) {
2761                     mirror_refresh_stats(m);
2762                 }
2763             }
2764             refresh_controller_status();
2765         }
2766
2767         status = ovsdb_idl_txn_commit(stats_txn);
2768         if (status != TXN_INCOMPLETE) {
2769             stats_timer = time_msec() + stats_timer_interval;
2770             ovsdb_idl_txn_destroy(stats_txn);
2771             stats_txn = NULL;
2772         }
2773     }
2774 }
2775
2776 static void
2777 stats_update_wait(void)
2778 {
2779     /* If the 'stats_txn' is non-null (transaction incomplete), waits for the
2780      * transaction to complete.  Otherwise, waits for the 'stats_timer'. */
2781     if (stats_txn) {
2782         ovsdb_idl_txn_wait(stats_txn);
2783     } else {
2784         poll_timer_wait_until(stats_timer);
2785     }
2786 }
2787
2788 /* Update bridge/port/interface status if necessary. */
2789 static void
2790 run_status_update(void)
2791 {
2792     if (!status_txn) {
2793         uint64_t seq;
2794
2795         /* Rate limit the update.  Do not start a new update if the
2796          * previous one is not done. */
2797         seq = seq_read(connectivity_seq_get());
2798         if (seq != connectivity_seqno || status_txn_try_again) {
2799             struct bridge *br;
2800
2801             connectivity_seqno = seq;
2802             status_txn = ovsdb_idl_txn_create(idl);
2803             HMAP_FOR_EACH (br, node, &all_bridges) {
2804                 struct port *port;
2805
2806                 br_refresh_stp_status(br);
2807                 br_refresh_rstp_status(br);
2808                 br_refresh_datapath_info(br);
2809                 HMAP_FOR_EACH (port, hmap_node, &br->ports) {
2810                     struct iface *iface;
2811
2812                     port_refresh_stp_status(port);
2813                     port_refresh_rstp_status(port);
2814                     port_refresh_bond_status(port, status_txn_try_again);
2815                     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2816                         iface_refresh_netdev_status(iface);
2817                         iface_refresh_ofproto_status(iface);
2818                     }
2819                 }
2820             }
2821         }
2822     }
2823
2824     /* Commit the transaction and get the status. If the transaction finishes,
2825      * then destroy the transaction. Otherwise, keep it so that we can check
2826      * progress the next time that this function is called. */
2827     if (status_txn) {
2828         enum ovsdb_idl_txn_status status;
2829
2830         status = ovsdb_idl_txn_commit(status_txn);
2831         if (status != TXN_INCOMPLETE) {
2832             ovsdb_idl_txn_destroy(status_txn);
2833             status_txn = NULL;
2834
2835             /* Sets the 'status_txn_try_again' if the transaction fails. */
2836             if (status == TXN_SUCCESS || status == TXN_UNCHANGED) {
2837                 status_txn_try_again = false;
2838             } else {
2839                 status_txn_try_again = true;
2840             }
2841         }
2842     }
2843
2844     /* Refresh AA port status if necessary. */
2845     if (time_msec() >= aa_refresh_timer) {
2846         struct bridge *br;
2847
2848         HMAP_FOR_EACH (br, node, &all_bridges) {
2849             if (bridge_aa_need_refresh(br)) {
2850                 struct ovsdb_idl_txn *txn;
2851
2852                 txn = ovsdb_idl_txn_create(idl);
2853                 bridge_aa_refresh_queued(br);
2854                 ovsdb_idl_txn_commit(txn);
2855                 ovsdb_idl_txn_destroy(txn);
2856             }
2857         }
2858
2859         aa_refresh_timer = time_msec() + AA_REFRESH_INTERVAL;
2860     }
2861 }
2862
2863 static void
2864 status_update_wait(void)
2865 {
2866     /* If the 'status_txn' is non-null (transaction incomplete), waits for the
2867      * transaction to complete.  If the status update to database needs to be
2868      * run again (transaction fails), registers a timeout in
2869      * 'STATUS_CHECK_AGAIN_MSEC'.  Otherwise, waits on the global connectivity
2870      * sequence number. */
2871     if (status_txn) {
2872         ovsdb_idl_txn_wait(status_txn);
2873     } else if (status_txn_try_again) {
2874         poll_timer_wait_until(time_msec() + STATUS_CHECK_AGAIN_MSEC);
2875     } else {
2876         seq_wait(connectivity_seq_get(), connectivity_seqno);
2877     }
2878 }
2879
2880 static void
2881 bridge_run__(void)
2882 {
2883     struct bridge *br;
2884     struct sset types;
2885     const char *type;
2886
2887     /* Let each datapath type do the work that it needs to do. */
2888     sset_init(&types);
2889     ofproto_enumerate_types(&types);
2890     SSET_FOR_EACH (type, &types) {
2891         ofproto_type_run(type);
2892     }
2893     sset_destroy(&types);
2894
2895     /* Let each bridge do the work that it needs to do. */
2896     HMAP_FOR_EACH (br, node, &all_bridges) {
2897         ofproto_run(br->ofproto);
2898     }
2899 }
2900
2901 void
2902 bridge_run(void)
2903 {
2904     static struct ovsrec_open_vswitch null_cfg;
2905     const struct ovsrec_open_vswitch *cfg;
2906
2907     ovsrec_open_vswitch_init(&null_cfg);
2908
2909     ovsdb_idl_run(idl);
2910
2911     if_notifier_run();
2912
2913     if (ovsdb_idl_is_lock_contended(idl)) {
2914         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
2915         struct bridge *br, *next_br;
2916
2917         VLOG_ERR_RL(&rl, "another ovs-vswitchd process is running, "
2918                     "disabling this process (pid %ld) until it goes away",
2919                     (long int) getpid());
2920
2921         HMAP_FOR_EACH_SAFE (br, next_br, node, &all_bridges) {
2922             bridge_destroy(br, false);
2923         }
2924         /* Since we will not be running system_stats_run() in this process
2925          * with the current situation of multiple ovs-vswitchd daemons,
2926          * disable system stats collection. */
2927         system_stats_enable(false);
2928         return;
2929     } else if (!ovsdb_idl_has_lock(idl)
2930                || !ovsdb_idl_has_ever_connected(idl)) {
2931         /* Returns if not holding the lock or not done retrieving db
2932          * contents. */
2933         return;
2934     }
2935     cfg = ovsrec_open_vswitch_first(idl);
2936
2937     if (cfg) {
2938         dpdk_init(&cfg->other_config);
2939     }
2940
2941     /* Initialize the ofproto library.  This only needs to run once, but
2942      * it must be done after the configuration is set.  If the
2943      * initialization has already occurred, bridge_init_ofproto()
2944      * returns immediately. */
2945     bridge_init_ofproto(cfg);
2946
2947     /* Once the value of flow-restore-wait is false, we no longer should
2948      * check its value from the database. */
2949     if (cfg && ofproto_get_flow_restore_wait()) {
2950         ofproto_set_flow_restore_wait(smap_get_bool(&cfg->other_config,
2951                                         "flow-restore-wait", false));
2952     }
2953
2954     bridge_run__();
2955
2956     /* Re-configure SSL.  We do this on every trip through the main loop,
2957      * instead of just when the database changes, because the contents of the
2958      * key and certificate files can change without the database changing.
2959      *
2960      * We do this before bridge_reconfigure() because that function might
2961      * initiate SSL connections and thus requires SSL to be configured. */
2962     if (cfg && cfg->ssl) {
2963         const struct ovsrec_ssl *ssl = cfg->ssl;
2964
2965         stream_ssl_set_key_and_cert(ssl->private_key, ssl->certificate);
2966         stream_ssl_set_ca_cert_file(ssl->ca_cert, ssl->bootstrap_ca_cert);
2967     }
2968
2969     if (ovsdb_idl_get_seqno(idl) != idl_seqno || ifaces_changed) {
2970         struct ovsdb_idl_txn *txn;
2971
2972         ifaces_changed = false;
2973
2974         idl_seqno = ovsdb_idl_get_seqno(idl);
2975         txn = ovsdb_idl_txn_create(idl);
2976         bridge_reconfigure(cfg ? cfg : &null_cfg);
2977
2978         if (cfg) {
2979             ovsrec_open_vswitch_set_cur_cfg(cfg, cfg->next_cfg);
2980             discover_types(cfg);
2981         }
2982
2983         /* If we are completing our initial configuration for this run
2984          * of ovs-vswitchd, then keep the transaction around to monitor
2985          * it for completion. */
2986         if (initial_config_done) {
2987             /* Always sets the 'status_txn_try_again' to check again,
2988              * in case that this transaction fails. */
2989             status_txn_try_again = true;
2990             ovsdb_idl_txn_commit(txn);
2991             ovsdb_idl_txn_destroy(txn);
2992         } else {
2993             initial_config_done = true;
2994             daemonize_txn = txn;
2995         }
2996     }
2997
2998     if (daemonize_txn) {
2999         enum ovsdb_idl_txn_status status = ovsdb_idl_txn_commit(daemonize_txn);
3000         if (status != TXN_INCOMPLETE) {
3001             ovsdb_idl_txn_destroy(daemonize_txn);
3002             daemonize_txn = NULL;
3003
3004             /* ovs-vswitchd has completed initialization, so allow the
3005              * process that forked us to exit successfully. */
3006             daemonize_complete();
3007
3008             vlog_enable_async();
3009
3010             VLOG_INFO_ONCE("%s (Open vSwitch) %s", program_name, VERSION);
3011         }
3012     }
3013
3014     run_stats_update();
3015     run_status_update();
3016     run_system_stats();
3017 }
3018
3019 void
3020 bridge_wait(void)
3021 {
3022     struct sset types;
3023     const char *type;
3024
3025     ovsdb_idl_wait(idl);
3026     if (daemonize_txn) {
3027         ovsdb_idl_txn_wait(daemonize_txn);
3028     }
3029
3030     if_notifier_wait();
3031     if (ifaces_changed) {
3032         poll_immediate_wake();
3033     }
3034
3035     sset_init(&types);
3036     ofproto_enumerate_types(&types);
3037     SSET_FOR_EACH (type, &types) {
3038         ofproto_type_wait(type);
3039     }
3040     sset_destroy(&types);
3041
3042     if (!hmap_is_empty(&all_bridges)) {
3043         struct bridge *br;
3044
3045         HMAP_FOR_EACH (br, node, &all_bridges) {
3046             ofproto_wait(br->ofproto);
3047         }
3048         stats_update_wait();
3049         status_update_wait();
3050     }
3051
3052     system_stats_wait();
3053 }
3054
3055 /* Adds some memory usage statistics for bridges into 'usage', for use with
3056  * memory_report(). */
3057 void
3058 bridge_get_memory_usage(struct simap *usage)
3059 {
3060     struct bridge *br;
3061     struct sset types;
3062     const char *type;
3063
3064     sset_init(&types);
3065     ofproto_enumerate_types(&types);
3066     SSET_FOR_EACH (type, &types) {
3067         ofproto_type_get_memory_usage(type, usage);
3068     }
3069     sset_destroy(&types);
3070
3071     HMAP_FOR_EACH (br, node, &all_bridges) {
3072         ofproto_get_memory_usage(br->ofproto, usage);
3073     }
3074 }
3075 \f
3076 /* QoS unixctl user interface functions. */
3077
3078 struct qos_unixctl_show_cbdata {
3079     struct ds *ds;
3080     struct iface *iface;
3081 };
3082
3083 static void
3084 qos_unixctl_show_queue(unsigned int queue_id,
3085                        const struct smap *details,
3086                        struct iface *iface,
3087                        struct ds *ds)
3088 {
3089     struct netdev_queue_stats stats;
3090     struct smap_node *node;
3091     int error;
3092
3093     ds_put_cstr(ds, "\n");
3094     if (queue_id) {
3095         ds_put_format(ds, "Queue %u:\n", queue_id);
3096     } else {
3097         ds_put_cstr(ds, "Default:\n");
3098     }
3099
3100     SMAP_FOR_EACH (node, details) {
3101         ds_put_format(ds, "\t%s: %s\n", node->key, node->value);
3102     }
3103
3104     error = netdev_get_queue_stats(iface->netdev, queue_id, &stats);
3105     if (!error) {
3106         if (stats.tx_packets != UINT64_MAX) {
3107             ds_put_format(ds, "\ttx_packets: %"PRIu64"\n", stats.tx_packets);
3108         }
3109
3110         if (stats.tx_bytes != UINT64_MAX) {
3111             ds_put_format(ds, "\ttx_bytes: %"PRIu64"\n", stats.tx_bytes);
3112         }
3113
3114         if (stats.tx_errors != UINT64_MAX) {
3115             ds_put_format(ds, "\ttx_errors: %"PRIu64"\n", stats.tx_errors);
3116         }
3117     } else {
3118         ds_put_format(ds, "\tFailed to get statistics for queue %u: %s",
3119                       queue_id, ovs_strerror(error));
3120     }
3121 }
3122
3123 static void
3124 qos_unixctl_show_types(struct unixctl_conn *conn, int argc OVS_UNUSED,
3125                        const char *argv[], void *aux OVS_UNUSED)
3126 {
3127     struct ds ds = DS_EMPTY_INITIALIZER;
3128     struct sset types = SSET_INITIALIZER(&types);
3129     struct iface *iface;
3130     const char * types_name;
3131     int error;
3132
3133     iface = iface_find(argv[1]);
3134     if (!iface) {
3135         unixctl_command_reply_error(conn, "no such interface");
3136         return;
3137     }
3138
3139     error = netdev_get_qos_types(iface->netdev, &types);
3140     if (!error) {
3141         if (!sset_is_empty(&types)) {
3142             SSET_FOR_EACH (types_name, &types) {
3143                 ds_put_format(&ds, "QoS type: %s\n", types_name);
3144             }
3145             unixctl_command_reply(conn, ds_cstr(&ds));
3146         } else {
3147             ds_put_format(&ds, "No QoS types supported for interface: %s\n",
3148                           iface->name);
3149             unixctl_command_reply(conn, ds_cstr(&ds));
3150         }
3151     } else {
3152         ds_put_format(&ds, "%s: failed to retrieve supported QoS types (%s)",
3153                       iface->name, ovs_strerror(error));
3154         unixctl_command_reply_error(conn, ds_cstr(&ds));
3155     }
3156
3157     sset_destroy(&types);
3158     ds_destroy(&ds);
3159 }
3160
3161 static void
3162 qos_unixctl_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
3163                  const char *argv[], void *aux OVS_UNUSED)
3164 {
3165     struct ds ds = DS_EMPTY_INITIALIZER;
3166     struct smap smap = SMAP_INITIALIZER(&smap);
3167     struct iface *iface;
3168     const char *type;
3169     struct smap_node *node;
3170     int error;
3171
3172     iface = iface_find(argv[1]);
3173     if (!iface) {
3174         unixctl_command_reply_error(conn, "no such interface");
3175         return;
3176     }
3177
3178     error = netdev_get_qos(iface->netdev, &type, &smap);
3179     if (!error) {
3180         if (*type != '\0') {
3181             struct netdev_queue_dump dump;
3182             struct smap details;
3183             unsigned int queue_id;
3184
3185             ds_put_format(&ds, "QoS: %s %s\n", iface->name, type);
3186
3187             SMAP_FOR_EACH (node, &smap) {
3188                 ds_put_format(&ds, "%s: %s\n", node->key, node->value);
3189             }
3190
3191             smap_init(&details);
3192             NETDEV_QUEUE_FOR_EACH (&queue_id, &details, &dump, iface->netdev) {
3193                 qos_unixctl_show_queue(queue_id, &details, iface, &ds);
3194             }
3195             smap_destroy(&details);
3196
3197             unixctl_command_reply(conn, ds_cstr(&ds));
3198         } else {
3199             ds_put_format(&ds, "QoS not configured on %s\n", iface->name);
3200             unixctl_command_reply_error(conn, ds_cstr(&ds));
3201         }
3202     } else {
3203         ds_put_format(&ds, "%s: failed to retrieve QOS configuration (%s)\n",
3204                       iface->name, ovs_strerror(error));
3205         unixctl_command_reply_error(conn, ds_cstr(&ds));
3206     }
3207
3208     smap_destroy(&smap);
3209     ds_destroy(&ds);
3210 }
3211 \f
3212 /* Bridge reconfiguration functions. */
3213 static void
3214 bridge_create(const struct ovsrec_bridge *br_cfg)
3215 {
3216     struct bridge *br;
3217
3218     ovs_assert(!bridge_lookup(br_cfg->name));
3219     br = xzalloc(sizeof *br);
3220
3221     br->name = xstrdup(br_cfg->name);
3222     br->type = xstrdup(ofproto_normalize_type(br_cfg->datapath_type));
3223     br->cfg = br_cfg;
3224
3225     /* Derive the default Ethernet address from the bridge's UUID.  This should
3226      * be unique and it will be stable between ovs-vswitchd runs.  */
3227     memcpy(&br->default_ea, &br_cfg->header_.uuid, ETH_ADDR_LEN);
3228     eth_addr_mark_random(&br->default_ea);
3229
3230     hmap_init(&br->ports);
3231     hmap_init(&br->ifaces);
3232     hmap_init(&br->iface_by_name);
3233     hmap_init(&br->mirrors);
3234
3235     hmap_init(&br->mappings);
3236     hmap_insert(&all_bridges, &br->node, hash_string(br->name, 0));
3237 }
3238
3239 static void
3240 bridge_destroy(struct bridge *br, bool del)
3241 {
3242     if (br) {
3243         struct mirror *mirror, *next_mirror;
3244         struct port *port, *next_port;
3245
3246         HMAP_FOR_EACH_SAFE (port, next_port, hmap_node, &br->ports) {
3247             port_destroy(port);
3248         }
3249         HMAP_FOR_EACH_SAFE (mirror, next_mirror, hmap_node, &br->mirrors) {
3250             mirror_destroy(mirror);
3251         }
3252
3253         hmap_remove(&all_bridges, &br->node);
3254         ofproto_destroy(br->ofproto, del);
3255         hmap_destroy(&br->ifaces);
3256         hmap_destroy(&br->ports);
3257         hmap_destroy(&br->iface_by_name);
3258         hmap_destroy(&br->mirrors);
3259         hmap_destroy(&br->mappings);
3260         free(br->name);
3261         free(br->type);
3262         free(br);
3263     }
3264 }
3265
3266 static struct bridge *
3267 bridge_lookup(const char *name)
3268 {
3269     struct bridge *br;
3270
3271     HMAP_FOR_EACH_WITH_HASH (br, node, hash_string(name, 0), &all_bridges) {
3272         if (!strcmp(br->name, name)) {
3273             return br;
3274         }
3275     }
3276     return NULL;
3277 }
3278
3279 /* Handle requests for a listing of all flows known by the OpenFlow
3280  * stack, including those normally hidden. */
3281 static void
3282 bridge_unixctl_dump_flows(struct unixctl_conn *conn, int argc OVS_UNUSED,
3283                           const char *argv[], void *aux OVS_UNUSED)
3284 {
3285     struct bridge *br;
3286     struct ds results;
3287
3288     br = bridge_lookup(argv[1]);
3289     if (!br) {
3290         unixctl_command_reply_error(conn, "Unknown bridge");
3291         return;
3292     }
3293
3294     ds_init(&results);
3295     ofproto_get_all_flows(br->ofproto, &results);
3296
3297     unixctl_command_reply(conn, ds_cstr(&results));
3298     ds_destroy(&results);
3299 }
3300
3301 /* "bridge/reconnect [BRIDGE]": makes BRIDGE drop all of its controller
3302  * connections and reconnect.  If BRIDGE is not specified, then all bridges
3303  * drop their controller connections and reconnect. */
3304 static void
3305 bridge_unixctl_reconnect(struct unixctl_conn *conn, int argc,
3306                          const char *argv[], void *aux OVS_UNUSED)
3307 {
3308     struct bridge *br;
3309     if (argc > 1) {
3310         br = bridge_lookup(argv[1]);
3311         if (!br) {
3312             unixctl_command_reply_error(conn,  "Unknown bridge");
3313             return;
3314         }
3315         ofproto_reconnect_controllers(br->ofproto);
3316     } else {
3317         HMAP_FOR_EACH (br, node, &all_bridges) {
3318             ofproto_reconnect_controllers(br->ofproto);
3319         }
3320     }
3321     unixctl_command_reply(conn, NULL);
3322 }
3323
3324 static size_t
3325 bridge_get_controllers(const struct bridge *br,
3326                        struct ovsrec_controller ***controllersp)
3327 {
3328     struct ovsrec_controller **controllers;
3329     size_t n_controllers;
3330
3331     controllers = br->cfg->controller;
3332     n_controllers = br->cfg->n_controller;
3333
3334     if (n_controllers == 1 && !strcmp(controllers[0]->target, "none")) {
3335         controllers = NULL;
3336         n_controllers = 0;
3337     }
3338
3339     if (controllersp) {
3340         *controllersp = controllers;
3341     }
3342     return n_controllers;
3343 }
3344
3345 static void
3346 bridge_collect_wanted_ports(struct bridge *br,
3347                             struct shash *wanted_ports)
3348 {
3349     size_t i;
3350
3351     shash_init(wanted_ports);
3352
3353     for (i = 0; i < br->cfg->n_ports; i++) {
3354         const char *name = br->cfg->ports[i]->name;
3355         if (!shash_add_once(wanted_ports, name, br->cfg->ports[i])) {
3356             VLOG_WARN("bridge %s: %s specified twice as bridge port",
3357                       br->name, name);
3358         }
3359     }
3360     if (bridge_get_controllers(br, NULL)
3361         && !shash_find(wanted_ports, br->name)) {
3362         VLOG_WARN("bridge %s: no port named %s, synthesizing one",
3363                   br->name, br->name);
3364
3365         ovsrec_interface_init(&br->synth_local_iface);
3366         ovsrec_port_init(&br->synth_local_port);
3367
3368         br->synth_local_port.interfaces = &br->synth_local_ifacep;
3369         br->synth_local_port.n_interfaces = 1;
3370         br->synth_local_port.name = br->name;
3371
3372         br->synth_local_iface.name = br->name;
3373         br->synth_local_iface.type = "internal";
3374
3375         br->synth_local_ifacep = &br->synth_local_iface;
3376
3377         shash_add(wanted_ports, br->name, &br->synth_local_port);
3378     }
3379 }
3380
3381 /* Deletes "struct port"s and "struct iface"s under 'br' which aren't
3382  * consistent with 'br->cfg'.  Updates 'br->if_cfg_queue' with interfaces which
3383  * 'br' needs to complete its configuration. */
3384 static void
3385 bridge_del_ports(struct bridge *br, const struct shash *wanted_ports)
3386 {
3387     struct shash_node *port_node;
3388     struct port *port, *next;
3389
3390     /* Get rid of deleted ports.
3391      * Get rid of deleted interfaces on ports that still exist. */
3392     HMAP_FOR_EACH_SAFE (port, next, hmap_node, &br->ports) {
3393         port->cfg = shash_find_data(wanted_ports, port->name);
3394         if (!port->cfg) {
3395             port_destroy(port);
3396         } else {
3397             port_del_ifaces(port);
3398         }
3399     }
3400
3401     /* Update iface->cfg and iface->type in interfaces that still exist. */
3402     SHASH_FOR_EACH (port_node, wanted_ports) {
3403         const struct ovsrec_port *port = port_node->data;
3404         size_t i;
3405
3406         for (i = 0; i < port->n_interfaces; i++) {
3407             const struct ovsrec_interface *cfg = port->interfaces[i];
3408             struct iface *iface = iface_lookup(br, cfg->name);
3409             const char *type = iface_get_type(cfg, br->cfg);
3410             const char *dp_type = br->cfg->datapath_type;
3411             const char *netdev_type = ofproto_port_open_type(dp_type, type);
3412
3413             if (iface) {
3414                 iface->cfg = cfg;
3415                 iface->type = type;
3416                 iface->netdev_type = netdev_type;
3417             } else if (!strcmp(type, "null")) {
3418                 VLOG_WARN_ONCE("%s: The null interface type is deprecated and"
3419                                " may be removed in February 2013. Please email"
3420                                " dev@openvswitch.org with concerns.",
3421                                cfg->name);
3422             } else {
3423                 /* We will add new interfaces later. */
3424             }
3425         }
3426     }
3427 }
3428
3429 /* Initializes 'oc' appropriately as a management service controller for
3430  * 'br'.
3431  *
3432  * The caller must free oc->target when it is no longer needed. */
3433 static void
3434 bridge_ofproto_controller_for_mgmt(const struct bridge *br,
3435                                    struct ofproto_controller *oc)
3436 {
3437     oc->target = xasprintf("punix:%s/%s.mgmt", ovs_rundir(), br->name);
3438     oc->max_backoff = 0;
3439     oc->probe_interval = 60;
3440     oc->band = OFPROTO_OUT_OF_BAND;
3441     oc->rate_limit = 0;
3442     oc->burst_limit = 0;
3443     oc->enable_async_msgs = true;
3444     oc->dscp = 0;
3445 }
3446
3447 /* Converts ovsrec_controller 'c' into an ofproto_controller in 'oc'.  */
3448 static void
3449 bridge_ofproto_controller_from_ovsrec(const struct ovsrec_controller *c,
3450                                       struct ofproto_controller *oc)
3451 {
3452     int dscp;
3453
3454     oc->target = c->target;
3455     oc->max_backoff = c->max_backoff ? *c->max_backoff / 1000 : 8;
3456     oc->probe_interval = c->inactivity_probe ? *c->inactivity_probe / 1000 : 5;
3457     oc->band = (!c->connection_mode || !strcmp(c->connection_mode, "in-band")
3458                 ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
3459     oc->rate_limit = c->controller_rate_limit ? *c->controller_rate_limit : 0;
3460     oc->burst_limit = (c->controller_burst_limit
3461                        ? *c->controller_burst_limit : 0);
3462     oc->enable_async_msgs = (!c->enable_async_messages
3463                              || *c->enable_async_messages);
3464     dscp = smap_get_int(&c->other_config, "dscp", DSCP_DEFAULT);
3465     if (dscp < 0 || dscp > 63) {
3466         dscp = DSCP_DEFAULT;
3467     }
3468     oc->dscp = dscp;
3469 }
3470
3471 /* Configures the IP stack for 'br''s local interface properly according to the
3472  * configuration in 'c'.  */
3473 static void
3474 bridge_configure_local_iface_netdev(struct bridge *br,
3475                                     struct ovsrec_controller *c)
3476 {
3477     struct netdev *netdev;
3478     struct in_addr mask, gateway;
3479
3480     struct iface *local_iface;
3481     struct in_addr ip;
3482
3483     /* If there's no local interface or no IP address, give up. */
3484     local_iface = iface_from_ofp_port(br, OFPP_LOCAL);
3485     if (!local_iface || !c->local_ip || !ip_parse(c->local_ip, &ip.s_addr)) {
3486         return;
3487     }
3488
3489     /* Bring up the local interface. */
3490     netdev = local_iface->netdev;
3491     netdev_turn_flags_on(netdev, NETDEV_UP, NULL);
3492
3493     /* Configure the IP address and netmask. */
3494     if (!c->local_netmask
3495         || !ip_parse(c->local_netmask, &mask.s_addr)
3496         || !mask.s_addr) {
3497         mask.s_addr = guess_netmask(ip.s_addr);
3498     }
3499     if (!netdev_set_in4(netdev, ip, mask)) {
3500         VLOG_INFO("bridge %s: configured IP address "IP_FMT", netmask "IP_FMT,
3501                   br->name, IP_ARGS(ip.s_addr), IP_ARGS(mask.s_addr));
3502     }
3503
3504     /* Configure the default gateway. */
3505     if (c->local_gateway
3506         && ip_parse(c->local_gateway, &gateway.s_addr)
3507         && gateway.s_addr) {
3508         if (!netdev_add_router(netdev, gateway)) {
3509             VLOG_INFO("bridge %s: configured gateway "IP_FMT,
3510                       br->name, IP_ARGS(gateway.s_addr));
3511         }
3512     }
3513 }
3514
3515 /* Returns true if 'a' and 'b' are the same except that any number of slashes
3516  * in either string are treated as equal to any number of slashes in the other,
3517  * e.g. "x///y" is equal to "x/y".
3518  *
3519  * Also, if 'b_stoplen' bytes from 'b' are found to be equal to corresponding
3520  * bytes from 'a', the function considers this success.  Specify 'b_stoplen' as
3521  * SIZE_MAX to compare all of 'a' to all of 'b' rather than just a prefix of
3522  * 'b' against a prefix of 'a'.
3523  */
3524 static bool
3525 equal_pathnames(const char *a, const char *b, size_t b_stoplen)
3526 {
3527     const char *b_start = b;
3528     for (;;) {
3529         if (b - b_start >= b_stoplen) {
3530             return true;
3531         } else if (*a != *b) {
3532             return false;
3533         } else if (*a == '/') {
3534             a += strspn(a, "/");
3535             b += strspn(b, "/");
3536         } else if (*a == '\0') {
3537             return true;
3538         } else {
3539             a++;
3540             b++;
3541         }
3542     }
3543 }
3544
3545 static void
3546 bridge_configure_remotes(struct bridge *br,
3547                          const struct sockaddr_in *managers, size_t n_managers)
3548 {
3549     bool disable_in_band;
3550
3551     struct ovsrec_controller **controllers;
3552     size_t n_controllers;
3553
3554     enum ofproto_fail_mode fail_mode;
3555
3556     struct ofproto_controller *ocs;
3557     size_t n_ocs;
3558     size_t i;
3559
3560     /* Check if we should disable in-band control on this bridge. */
3561     disable_in_band = smap_get_bool(&br->cfg->other_config, "disable-in-band",
3562                                     false);
3563
3564     /* Set OpenFlow queue ID for in-band control. */
3565     ofproto_set_in_band_queue(br->ofproto,
3566                               smap_get_int(&br->cfg->other_config,
3567                                            "in-band-queue", -1));
3568
3569     if (disable_in_band) {
3570         ofproto_set_extra_in_band_remotes(br->ofproto, NULL, 0);
3571     } else {
3572         ofproto_set_extra_in_band_remotes(br->ofproto, managers, n_managers);
3573     }
3574
3575     n_controllers = bridge_get_controllers(br, &controllers);
3576
3577     ocs = xmalloc((n_controllers + 1) * sizeof *ocs);
3578     n_ocs = 0;
3579
3580     bridge_ofproto_controller_for_mgmt(br, &ocs[n_ocs++]);
3581     for (i = 0; i < n_controllers; i++) {
3582         struct ovsrec_controller *c = controllers[i];
3583
3584         if (daemon_should_self_confine()
3585             && (!strncmp(c->target, "punix:", 6)
3586             || !strncmp(c->target, "unix:", 5))) {
3587             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3588             char *whitelist;
3589
3590             if (!strncmp(c->target, "unix:", 5)) {
3591                 /* Connect to a listening socket */
3592                 whitelist = xasprintf("unix:%s/", ovs_rundir());
3593                 if (strchr(c->target, '/') &&
3594                    !equal_pathnames(c->target, whitelist,
3595                      strlen(whitelist))) {
3596                     /* Absolute path specified, but not in ovs_rundir */
3597                     VLOG_ERR_RL(&rl, "bridge %s: Not connecting to socket "
3598                                   "controller \"%s\" due to possibility for "
3599                                   "remote exploit.  Instead, specify socket "
3600                                   "in whitelisted \"%s\" or connect to "
3601                                   "\"unix:%s/%s.mgmt\" (which is always "
3602                                   "available without special configuration).",
3603                                   br->name, c->target, whitelist,
3604                                   ovs_rundir(), br->name);
3605                     free(whitelist);
3606                     continue;
3607                 }
3608             } else {
3609                whitelist = xasprintf("punix:%s/%s.",
3610                                      ovs_rundir(), br->name);
3611                if (!equal_pathnames(c->target, whitelist, strlen(whitelist))
3612                    || strchr(c->target + strlen(whitelist), '/')) {
3613                    /* Prevent remote ovsdb-server users from accessing
3614                     * arbitrary Unix domain sockets and overwriting arbitrary
3615                     * local files. */
3616                    VLOG_ERR_RL(&rl, "bridge %s: Not adding Unix domain socket "
3617                                   "controller \"%s\" due to possibility of "
3618                                   "overwriting local files. Instead, specify "
3619                                   "path in whitelisted format \"%s*\" or "
3620                                   "connect to \"unix:%s/%s.mgmt\" (which is "
3621                                   "always available without special "
3622                                   "configuration).",
3623                                   br->name, c->target, whitelist,
3624                                   ovs_rundir(), br->name);
3625                    free(whitelist);
3626                    continue;
3627                }
3628             }
3629
3630             free(whitelist);
3631         }
3632
3633         bridge_configure_local_iface_netdev(br, c);
3634         bridge_ofproto_controller_from_ovsrec(c, &ocs[n_ocs]);
3635         if (disable_in_band) {
3636             ocs[n_ocs].band = OFPROTO_OUT_OF_BAND;
3637         }
3638         n_ocs++;
3639     }
3640
3641     ofproto_set_controllers(br->ofproto, ocs, n_ocs,
3642                             bridge_get_allowed_versions(br));
3643     free(ocs[0].target); /* From bridge_ofproto_controller_for_mgmt(). */
3644     free(ocs);
3645
3646     /* Set the fail-mode. */
3647     fail_mode = !br->cfg->fail_mode
3648                 || !strcmp(br->cfg->fail_mode, "standalone")
3649                     ? OFPROTO_FAIL_STANDALONE
3650                     : OFPROTO_FAIL_SECURE;
3651     ofproto_set_fail_mode(br->ofproto, fail_mode);
3652
3653     /* Configure OpenFlow controller connection snooping. */
3654     if (!ofproto_has_snoops(br->ofproto)) {
3655         struct sset snoops;
3656
3657         sset_init(&snoops);
3658         sset_add_and_free(&snoops, xasprintf("punix:%s/%s.snoop",
3659                                              ovs_rundir(), br->name));
3660         ofproto_set_snoops(br->ofproto, &snoops);
3661         sset_destroy(&snoops);
3662     }
3663 }
3664
3665 static void
3666 bridge_configure_tables(struct bridge *br)
3667 {
3668     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3669     int n_tables;
3670     int i, j, k;
3671
3672     n_tables = ofproto_get_n_tables(br->ofproto);
3673     j = 0;
3674     for (i = 0; i < n_tables; i++) {
3675         struct ofproto_table_settings s;
3676         bool use_default_prefixes = true;
3677
3678         s.name = NULL;
3679         s.max_flows = UINT_MAX;
3680         s.groups = NULL;
3681         s.enable_eviction = false;
3682         s.n_groups = 0;
3683         s.n_prefix_fields = 0;
3684         memset(s.prefix_fields, ~0, sizeof(s.prefix_fields));
3685
3686         if (j < br->cfg->n_flow_tables && i == br->cfg->key_flow_tables[j]) {
3687             struct ovsrec_flow_table *cfg = br->cfg->value_flow_tables[j++];
3688
3689             s.name = cfg->name;
3690             if (cfg->n_flow_limit && *cfg->flow_limit < UINT_MAX) {
3691                 s.max_flows = *cfg->flow_limit;
3692             }
3693
3694             s.enable_eviction = (cfg->overflow_policy
3695                                  && !strcmp(cfg->overflow_policy, "evict"));
3696             if (cfg->n_groups) {
3697                 s.groups = xmalloc(cfg->n_groups * sizeof *s.groups);
3698                 for (k = 0; k < cfg->n_groups; k++) {
3699                     const char *string = cfg->groups[k];
3700                     char *msg;
3701
3702                     msg = mf_parse_subfield__(&s.groups[k], &string);
3703                     if (msg) {
3704                         VLOG_WARN_RL(&rl, "bridge %s table %d: error parsing "
3705                                      "'groups' (%s)", br->name, i, msg);
3706                         free(msg);
3707                     } else if (*string) {
3708                         VLOG_WARN_RL(&rl, "bridge %s table %d: 'groups' "
3709                                      "element '%s' contains trailing garbage",
3710                                      br->name, i, cfg->groups[k]);
3711                     } else {
3712                         s.n_groups++;
3713                     }
3714                 }
3715             }
3716
3717             /* Prefix lookup fields. */
3718             s.n_prefix_fields = 0;
3719             for (k = 0; k < cfg->n_prefixes; k++) {
3720                 const char *name = cfg->prefixes[k];
3721                 const struct mf_field *mf;
3722
3723                 if (strcmp(name, "none") == 0) {
3724                     use_default_prefixes = false;
3725                     s.n_prefix_fields = 0;
3726                     break;
3727                 }
3728                 mf = mf_from_name(name);
3729                 if (!mf) {
3730                     VLOG_WARN("bridge %s: 'prefixes' with unknown field: %s",
3731                               br->name, name);
3732                     continue;
3733                 }
3734                 if (mf->flow_be32ofs < 0 || mf->n_bits % 32) {
3735                     VLOG_WARN("bridge %s: 'prefixes' with incompatible field: "
3736                               "%s", br->name, name);
3737                     continue;
3738                 }
3739                 if (s.n_prefix_fields >= ARRAY_SIZE(s.prefix_fields)) {
3740                     VLOG_WARN("bridge %s: 'prefixes' with too many fields, "
3741                               "field not used: %s", br->name, name);
3742                     continue;
3743                 }
3744                 use_default_prefixes = false;
3745                 s.prefix_fields[s.n_prefix_fields++] = mf->id;
3746             }
3747         }
3748         if (use_default_prefixes) {
3749             /* Use default values. */
3750             s.n_prefix_fields = ARRAY_SIZE(default_prefix_fields);
3751             memcpy(s.prefix_fields, default_prefix_fields,
3752                    sizeof default_prefix_fields);
3753         } else {
3754             int k;
3755             struct ds ds = DS_EMPTY_INITIALIZER;
3756             for (k = 0; k < s.n_prefix_fields; k++) {
3757                 if (k) {
3758                     ds_put_char(&ds, ',');
3759                 }
3760                 ds_put_cstr(&ds, mf_from_id(s.prefix_fields[k])->name);
3761             }
3762             if (s.n_prefix_fields == 0) {
3763                 ds_put_cstr(&ds, "none");
3764             }
3765             VLOG_INFO("bridge %s table %d: Prefix lookup with: %s.",
3766                       br->name, i, ds_cstr(&ds));
3767             ds_destroy(&ds);
3768         }
3769
3770         ofproto_configure_table(br->ofproto, i, &s);
3771
3772         free(s.groups);
3773     }
3774     for (; j < br->cfg->n_flow_tables; j++) {
3775         VLOG_WARN_RL(&rl, "bridge %s: ignoring configuration for flow table "
3776                      "%"PRId64" not supported by this datapath", br->name,
3777                      br->cfg->key_flow_tables[j]);
3778     }
3779 }
3780
3781 static void
3782 bridge_configure_dp_desc(struct bridge *br)
3783 {
3784     ofproto_set_dp_desc(br->ofproto,
3785                         smap_get(&br->cfg->other_config, "dp-desc"));
3786 }
3787
3788 static struct aa_mapping *
3789 bridge_aa_mapping_find(struct bridge *br, const int64_t isid)
3790 {
3791     struct aa_mapping *m;
3792
3793     HMAP_FOR_EACH_IN_BUCKET (m,
3794                              hmap_node,
3795                              hash_bytes(&isid, sizeof isid, 0),
3796                              &br->mappings) {
3797         if (isid == m->isid) {
3798             return m;
3799         }
3800     }
3801     return NULL;
3802 }
3803
3804 static struct aa_mapping *
3805 bridge_aa_mapping_create(struct bridge *br,
3806                          const int64_t isid,
3807                          const int64_t vlan)
3808 {
3809     struct aa_mapping *m;
3810
3811     m = xzalloc(sizeof *m);
3812     m->bridge = br;
3813     m->isid = isid;
3814     m->vlan = vlan;
3815     m->br_name = xstrdup(br->name);
3816     hmap_insert(&br->mappings,
3817                 &m->hmap_node,
3818                 hash_bytes(&isid, sizeof isid, 0));
3819
3820     return m;
3821 }
3822
3823 static void
3824 bridge_aa_mapping_destroy(struct aa_mapping *m)
3825 {
3826     if (m) {
3827         struct bridge *br = m->bridge;
3828
3829         if (br->ofproto) {
3830             ofproto_aa_mapping_unregister(br->ofproto, m);
3831         }
3832
3833         hmap_remove(&br->mappings, &m->hmap_node);
3834         if (m->br_name) {
3835             free(m->br_name);
3836         }
3837         free(m);
3838     }
3839 }
3840
3841 static bool
3842 bridge_aa_mapping_configure(struct aa_mapping *m)
3843 {
3844     struct aa_mapping_settings s;
3845
3846     s.isid = m->isid;
3847     s.vlan = m->vlan;
3848
3849     /* Configure. */
3850     ofproto_aa_mapping_register(m->bridge->ofproto, m, &s);
3851
3852     return true;
3853 }
3854
3855 static void
3856 bridge_configure_aa(struct bridge *br)
3857 {
3858     const struct ovsdb_datum *mc;
3859     struct ovsrec_autoattach *auto_attach = br->cfg->auto_attach;
3860     struct aa_settings aa_s;
3861     struct aa_mapping *m, *next;
3862     size_t i;
3863
3864     if (!auto_attach) {
3865         ofproto_set_aa(br->ofproto, NULL, NULL);
3866         return;
3867     }
3868
3869     memset(&aa_s, 0, sizeof aa_s);
3870     aa_s.system_description = auto_attach->system_description;
3871     aa_s.system_name = auto_attach->system_name;
3872     ofproto_set_aa(br->ofproto, NULL, &aa_s);
3873
3874     mc = ovsrec_autoattach_get_mappings(auto_attach,
3875                                         OVSDB_TYPE_INTEGER,
3876                                         OVSDB_TYPE_INTEGER);
3877     HMAP_FOR_EACH_SAFE (m, next, hmap_node, &br->mappings) {
3878         union ovsdb_atom atom;
3879
3880         atom.integer = m->isid;
3881         if (ovsdb_datum_find_key(mc, &atom, OVSDB_TYPE_UUID) == UINT_MAX) {
3882             VLOG_INFO("Deleting isid=%"PRIu32", vlan=%"PRIu16,
3883                       m->isid, m->vlan);
3884             bridge_aa_mapping_destroy(m);
3885         }
3886     }
3887
3888     /* Add new mappings and reconfigure existing ones. */
3889     for (i = 0; i < auto_attach->n_mappings; ++i) {
3890         struct aa_mapping *m =
3891             bridge_aa_mapping_find(br, auto_attach->key_mappings[i]);
3892
3893         if (!m) {
3894             VLOG_INFO("Adding isid=%"PRId64", vlan=%"PRId64,
3895                       auto_attach->key_mappings[i],
3896                       auto_attach->value_mappings[i]);
3897             m = bridge_aa_mapping_create(br,
3898                                          auto_attach->key_mappings[i],
3899                                          auto_attach->value_mappings[i]);
3900
3901             if (!bridge_aa_mapping_configure(m)) {
3902                 bridge_aa_mapping_destroy(m);
3903             }
3904         }
3905     }
3906 }
3907
3908 static bool
3909 bridge_aa_need_refresh(struct bridge *br)
3910 {
3911     return ofproto_aa_vlan_get_queue_size(br->ofproto) > 0;
3912 }
3913
3914 static void
3915 bridge_aa_update_trunks(struct port *port, struct bridge_aa_vlan *m)
3916 {
3917     int64_t *trunks = NULL;
3918     unsigned int i = 0;
3919     bool found = false, reconfigure = false;
3920
3921     for (i = 0; i < port->cfg->n_trunks; i++) {
3922         if (port->cfg->trunks[i] == m->vlan) {
3923             found = true;
3924             break;
3925         }
3926     }
3927
3928     switch (m->oper) {
3929         case BRIDGE_AA_VLAN_OPER_ADD:
3930             if (!found) {
3931                 trunks = xmalloc(sizeof *trunks * (port->cfg->n_trunks + 1));
3932
3933                 for (i = 0; i < port->cfg->n_trunks; i++) {
3934                     trunks[i] = port->cfg->trunks[i];
3935                 }
3936                 trunks[i++] = m->vlan;
3937                 reconfigure = true;
3938             }
3939
3940             break;
3941
3942         case BRIDGE_AA_VLAN_OPER_REMOVE:
3943             if (found) {
3944                 unsigned int j = 0;
3945
3946                 trunks = xmalloc(sizeof *trunks * (port->cfg->n_trunks - 1));
3947
3948                 for (i = 0; i < port->cfg->n_trunks; i++) {
3949                     if (port->cfg->trunks[i] != m->vlan) {
3950                         trunks[j++] = port->cfg->trunks[i];
3951                     }
3952                 }
3953                 i = j;
3954                 reconfigure = true;
3955             }
3956
3957             break;
3958
3959         case BRIDGE_AA_VLAN_OPER_UNDEF:
3960         default:
3961             VLOG_WARN("unrecognized operation %u", m->oper);
3962             break;
3963     }
3964
3965     if (reconfigure) {
3966         /* VLAN switching under trunk mode cause the trunk port to switch all
3967          * VLANs, see ovs-vswitchd.conf.db
3968          */
3969         if (i == 0)  {
3970             static char *vlan_mode_access = "access";
3971             ovsrec_port_set_vlan_mode(port->cfg, vlan_mode_access);
3972         }
3973
3974         if (i == 1) {
3975             static char *vlan_mode_trunk = "trunk";
3976             ovsrec_port_set_vlan_mode(port->cfg, vlan_mode_trunk);
3977         }
3978
3979         ovsrec_port_set_trunks(port->cfg, trunks, i);
3980
3981         /* Force reconfigure of the port. */
3982         port_configure(port);
3983     }
3984 }
3985
3986 static void
3987 bridge_aa_refresh_queued(struct bridge *br)
3988 {
3989     struct ovs_list *list = xmalloc(sizeof *list);
3990     struct bridge_aa_vlan *node, *next;
3991
3992     ovs_list_init(list);
3993     ofproto_aa_vlan_get_queued(br->ofproto, list);
3994
3995     LIST_FOR_EACH_SAFE (node, next, list_node, list) {
3996         struct port *port;
3997
3998         VLOG_INFO("ifname=%s, vlan=%u, oper=%u", node->port_name, node->vlan,
3999                   node->oper);
4000
4001         port = port_lookup(br, node->port_name);
4002         if (port) {
4003             bridge_aa_update_trunks(port, node);
4004         }
4005
4006         ovs_list_remove(&node->list_node);
4007         free(node->port_name);
4008         free(node);
4009     }
4010
4011     free(list);
4012 }
4013
4014 \f
4015 /* Port functions. */
4016
4017 static struct port *
4018 port_create(struct bridge *br, const struct ovsrec_port *cfg)
4019 {
4020     struct port *port;
4021
4022     port = xzalloc(sizeof *port);
4023     port->bridge = br;
4024     port->name = xstrdup(cfg->name);
4025     port->cfg = cfg;
4026     ovs_list_init(&port->ifaces);
4027
4028     hmap_insert(&br->ports, &port->hmap_node, hash_string(port->name, 0));
4029     return port;
4030 }
4031
4032 /* Deletes interfaces from 'port' that are no longer configured for it. */
4033 static void
4034 port_del_ifaces(struct port *port)
4035 {
4036     struct iface *iface, *next;
4037     struct sset new_ifaces;
4038     size_t i;
4039
4040     /* Collect list of new interfaces. */
4041     sset_init(&new_ifaces);
4042     for (i = 0; i < port->cfg->n_interfaces; i++) {
4043         const char *name = port->cfg->interfaces[i]->name;
4044         const char *type = port->cfg->interfaces[i]->type;
4045         if (strcmp(type, "null")) {
4046             sset_add(&new_ifaces, name);
4047         }
4048     }
4049
4050     /* Get rid of deleted interfaces. */
4051     LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
4052         if (!sset_contains(&new_ifaces, iface->name)) {
4053             iface_destroy(iface);
4054         }
4055     }
4056
4057     sset_destroy(&new_ifaces);
4058 }
4059
4060 static void
4061 port_destroy(struct port *port)
4062 {
4063     if (port) {
4064         struct bridge *br = port->bridge;
4065         struct iface *iface, *next;
4066
4067         if (br->ofproto) {
4068             ofproto_bundle_unregister(br->ofproto, port);
4069         }
4070
4071         LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
4072             iface_destroy__(iface);
4073         }
4074
4075         hmap_remove(&br->ports, &port->hmap_node);
4076         free(port->name);
4077         free(port);
4078     }
4079 }
4080
4081 static struct port *
4082 port_lookup(const struct bridge *br, const char *name)
4083 {
4084     struct port *port;
4085
4086     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_string(name, 0),
4087                              &br->ports) {
4088         if (!strcmp(port->name, name)) {
4089             return port;
4090         }
4091     }
4092     return NULL;
4093 }
4094
4095 static bool
4096 enable_lacp(struct port *port, bool *activep)
4097 {
4098     if (!port->cfg->lacp) {
4099         /* XXX when LACP implementation has been sufficiently tested, enable by
4100          * default and make active on bonded ports. */
4101         return false;
4102     } else if (!strcmp(port->cfg->lacp, "off")) {
4103         return false;
4104     } else if (!strcmp(port->cfg->lacp, "active")) {
4105         *activep = true;
4106         return true;
4107     } else if (!strcmp(port->cfg->lacp, "passive")) {
4108         *activep = false;
4109         return true;
4110     } else {
4111         VLOG_WARN("port %s: unknown LACP mode %s",
4112                   port->name, port->cfg->lacp);
4113         return false;
4114     }
4115 }
4116
4117 static struct lacp_settings *
4118 port_configure_lacp(struct port *port, struct lacp_settings *s)
4119 {
4120     const char *lacp_time, *system_id;
4121     int priority;
4122
4123     if (!enable_lacp(port, &s->active)) {
4124         return NULL;
4125     }
4126
4127     s->name = port->name;
4128
4129     system_id = smap_get(&port->cfg->other_config, "lacp-system-id");
4130     if (system_id) {
4131         if (!ovs_scan(system_id, ETH_ADDR_SCAN_FMT,
4132                       ETH_ADDR_SCAN_ARGS(s->id))) {
4133             VLOG_WARN("port %s: LACP system ID (%s) must be an Ethernet"
4134                       " address.", port->name, system_id);
4135             return NULL;
4136         }
4137     } else {
4138         s->id = port->bridge->ea;
4139     }
4140
4141     if (eth_addr_is_zero(s->id)) {
4142         VLOG_WARN("port %s: Invalid zero LACP system ID.", port->name);
4143         return NULL;
4144     }
4145
4146     /* Prefer bondable links if unspecified. */
4147     priority = smap_get_int(&port->cfg->other_config, "lacp-system-priority",
4148                             0);
4149     s->priority = (priority > 0 && priority <= UINT16_MAX
4150                    ? priority
4151                    : UINT16_MAX - !ovs_list_is_short(&port->ifaces));
4152
4153     lacp_time = smap_get(&port->cfg->other_config, "lacp-time");
4154     s->fast = lacp_time && !strcasecmp(lacp_time, "fast");
4155
4156     s->fallback_ab_cfg = smap_get_bool(&port->cfg->other_config,
4157                                        "lacp-fallback-ab", false);
4158
4159     return s;
4160 }
4161
4162 static void
4163 iface_configure_lacp(struct iface *iface, struct lacp_slave_settings *s)
4164 {
4165     int priority, portid, key;
4166
4167     portid = smap_get_int(&iface->cfg->other_config, "lacp-port-id", 0);
4168     priority = smap_get_int(&iface->cfg->other_config, "lacp-port-priority",
4169                             0);
4170     key = smap_get_int(&iface->cfg->other_config, "lacp-aggregation-key", 0);
4171
4172     if (portid <= 0 || portid > UINT16_MAX) {
4173         portid = ofp_to_u16(iface->ofp_port);
4174     }
4175
4176     if (priority <= 0 || priority > UINT16_MAX) {
4177         priority = UINT16_MAX;
4178     }
4179
4180     if (key < 0 || key > UINT16_MAX) {
4181         key = 0;
4182     }
4183
4184     s->name = iface->name;
4185     s->id = portid;
4186     s->priority = priority;
4187     s->key = key;
4188 }
4189
4190 static void
4191 port_configure_bond(struct port *port, struct bond_settings *s)
4192 {
4193     const char *detect_s;
4194     struct iface *iface;
4195     const char *mac_s;
4196     int miimon_interval;
4197
4198     s->name = port->name;
4199     s->balance = BM_AB;
4200     if (port->cfg->bond_mode) {
4201         if (!bond_mode_from_string(&s->balance, port->cfg->bond_mode)) {
4202             VLOG_WARN("port %s: unknown bond_mode %s, defaulting to %s",
4203                       port->name, port->cfg->bond_mode,
4204                       bond_mode_to_string(s->balance));
4205         }
4206     } else {
4207         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
4208
4209         /* XXX: Post version 1.5.*, the default bond_mode changed from SLB to
4210          * active-backup. At some point we should remove this warning. */
4211         VLOG_WARN_RL(&rl, "port %s: Using the default bond_mode %s. Note that"
4212                      " in previous versions, the default bond_mode was"
4213                      " balance-slb", port->name,
4214                      bond_mode_to_string(s->balance));
4215     }
4216     if (s->balance == BM_SLB && port->bridge->cfg->n_flood_vlans) {
4217         VLOG_WARN("port %s: SLB bonds are incompatible with flood_vlans, "
4218                   "please use another bond type or disable flood_vlans",
4219                   port->name);
4220     }
4221
4222     miimon_interval = smap_get_int(&port->cfg->other_config,
4223                                    "bond-miimon-interval", 0);
4224     if (miimon_interval <= 0) {
4225         miimon_interval = 200;
4226     }
4227
4228     detect_s = smap_get(&port->cfg->other_config, "bond-detect-mode");
4229     if (!detect_s || !strcmp(detect_s, "carrier")) {
4230         miimon_interval = 0;
4231     } else if (strcmp(detect_s, "miimon")) {
4232         VLOG_WARN("port %s: unsupported bond-detect-mode %s, "
4233                   "defaulting to carrier", port->name, detect_s);
4234         miimon_interval = 0;
4235     }
4236
4237     s->up_delay = MAX(0, port->cfg->bond_updelay);
4238     s->down_delay = MAX(0, port->cfg->bond_downdelay);
4239     s->basis = smap_get_int(&port->cfg->other_config, "bond-hash-basis", 0);
4240     s->rebalance_interval = smap_get_int(&port->cfg->other_config,
4241                                            "bond-rebalance-interval", 10000);
4242     if (s->rebalance_interval && s->rebalance_interval < 1000) {
4243         s->rebalance_interval = 1000;
4244     }
4245
4246     s->lacp_fallback_ab_cfg = smap_get_bool(&port->cfg->other_config,
4247                                        "lacp-fallback-ab", false);
4248
4249     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
4250         netdev_set_miimon_interval(iface->netdev, miimon_interval);
4251     }
4252
4253     mac_s = port->cfg->bond_active_slave;
4254     if (!mac_s || !ovs_scan(mac_s, ETH_ADDR_SCAN_FMT,
4255                             ETH_ADDR_SCAN_ARGS(s->active_slave_mac))) {
4256         /* OVSDB did not store the last active interface */
4257         s->active_slave_mac = eth_addr_zero;
4258     }
4259 }
4260
4261 /* Returns true if 'port' is synthetic, that is, if we constructed it locally
4262  * instead of obtaining it from the database. */
4263 static bool
4264 port_is_synthetic(const struct port *port)
4265 {
4266     return ovsdb_idl_row_is_synthetic(&port->cfg->header_);
4267 }
4268 \f
4269 /* Interface functions. */
4270
4271 static bool
4272 iface_is_internal(const struct ovsrec_interface *iface,
4273                   const struct ovsrec_bridge *br)
4274 {
4275     /* The local port and "internal" ports are always "internal". */
4276     return !strcmp(iface->type, "internal") || !strcmp(iface->name, br->name);
4277 }
4278
4279 /* Returns the correct network device type for interface 'iface' in bridge
4280  * 'br'. */
4281 static const char *
4282 iface_get_type(const struct ovsrec_interface *iface,
4283                const struct ovsrec_bridge *br)
4284 {
4285     const char *type;
4286
4287     /* The local port always has type "internal".  Other ports take
4288      * their type from the database and default to "system" if none is
4289      * specified. */
4290     if (iface_is_internal(iface, br)) {
4291         type = "internal";
4292     } else {
4293         type = iface->type[0] ? iface->type : "system";
4294     }
4295
4296     return type;
4297 }
4298
4299 static void
4300 iface_destroy__(struct iface *iface)
4301 {
4302     if (iface) {
4303         struct port *port = iface->port;
4304         struct bridge *br = port->bridge;
4305
4306         if (br->ofproto && iface->ofp_port != OFPP_NONE) {
4307             ofproto_port_unregister(br->ofproto, iface->ofp_port);
4308         }
4309
4310         if (iface->ofp_port != OFPP_NONE) {
4311             hmap_remove(&br->ifaces, &iface->ofp_port_node);
4312         }
4313
4314         ovs_list_remove(&iface->port_elem);
4315         hmap_remove(&br->iface_by_name, &iface->name_node);
4316
4317         /* The user is changing configuration here, so netdev_remove needs to be
4318          * used as opposed to netdev_close */
4319         netdev_remove(iface->netdev);
4320
4321         free(iface->name);
4322         free(iface);
4323     }
4324 }
4325
4326 static void
4327 iface_destroy(struct iface *iface)
4328 {
4329     if (iface) {
4330         struct port *port = iface->port;
4331
4332         iface_destroy__(iface);
4333         if (ovs_list_is_empty(&port->ifaces)) {
4334             port_destroy(port);
4335         }
4336     }
4337 }
4338
4339 static struct iface *
4340 iface_lookup(const struct bridge *br, const char *name)
4341 {
4342     struct iface *iface;
4343
4344     HMAP_FOR_EACH_WITH_HASH (iface, name_node, hash_string(name, 0),
4345                              &br->iface_by_name) {
4346         if (!strcmp(iface->name, name)) {
4347             return iface;
4348         }
4349     }
4350
4351     return NULL;
4352 }
4353
4354 static struct iface *
4355 iface_find(const char *name)
4356 {
4357     const struct bridge *br;
4358
4359     HMAP_FOR_EACH (br, node, &all_bridges) {
4360         struct iface *iface = iface_lookup(br, name);
4361
4362         if (iface) {
4363             return iface;
4364         }
4365     }
4366     return NULL;
4367 }
4368
4369 static struct iface *
4370 iface_from_ofp_port(const struct bridge *br, ofp_port_t ofp_port)
4371 {
4372     struct iface *iface;
4373
4374     HMAP_FOR_EACH_IN_BUCKET (iface, ofp_port_node, hash_ofp_port(ofp_port),
4375                              &br->ifaces) {
4376         if (iface->ofp_port == ofp_port) {
4377             return iface;
4378         }
4379     }
4380     return NULL;
4381 }
4382
4383 /* Set Ethernet address of 'iface', if one is specified in the configuration
4384  * file. */
4385 static void
4386 iface_set_mac(const struct bridge *br, const struct port *port, struct iface *iface)
4387 {
4388     struct eth_addr ea, *mac = NULL;
4389     struct iface *hw_addr_iface;
4390
4391     if (strcmp(iface->type, "internal")) {
4392         return;
4393     }
4394
4395     if (iface->cfg->mac && eth_addr_from_string(iface->cfg->mac, &ea)) {
4396         mac = &ea;
4397     } else if (port->cfg->fake_bridge) {
4398         /* Fake bridge and no MAC set in the configuration. Pick a local one. */
4399         find_local_hw_addr(br, &ea, port, &hw_addr_iface);
4400         mac = &ea;
4401     }
4402
4403     if (mac) {
4404         if (iface->ofp_port == OFPP_LOCAL) {
4405             VLOG_ERR("interface %s: ignoring mac in Interface record "
4406                      "(use Bridge record to set local port's mac)",
4407                      iface->name);
4408         } else if (eth_addr_is_multicast(*mac)) {
4409             VLOG_ERR("interface %s: cannot set MAC to multicast address",
4410                      iface->name);
4411         } else {
4412             int error = netdev_set_etheraddr(iface->netdev, *mac);
4413             if (error) {
4414                 VLOG_ERR("interface %s: setting MAC failed (%s)",
4415                          iface->name, ovs_strerror(error));
4416             }
4417         }
4418     }
4419 }
4420
4421 /* Sets the ofport column of 'if_cfg' to 'ofport'. */
4422 static void
4423 iface_set_ofport(const struct ovsrec_interface *if_cfg, ofp_port_t ofport)
4424 {
4425     if (if_cfg && !ovsdb_idl_row_is_synthetic(&if_cfg->header_)) {
4426         int64_t port = ofport == OFPP_NONE ? -1 : ofp_to_u16(ofport);
4427         ovsrec_interface_set_ofport(if_cfg, &port, 1);
4428     }
4429 }
4430
4431 /* Clears all of the fields in 'if_cfg' that indicate interface status, and
4432  * sets the "ofport" field to -1.
4433  *
4434  * This is appropriate when 'if_cfg''s interface cannot be created or is
4435  * otherwise invalid. */
4436 static void
4437 iface_clear_db_record(const struct ovsrec_interface *if_cfg, char *errp)
4438 {
4439     if (!ovsdb_idl_row_is_synthetic(&if_cfg->header_)) {
4440         iface_set_ofport(if_cfg, OFPP_NONE);
4441         ovsrec_interface_set_error(if_cfg, errp);
4442         ovsrec_interface_set_status(if_cfg, NULL);
4443         ovsrec_interface_set_admin_state(if_cfg, NULL);
4444         ovsrec_interface_set_duplex(if_cfg, NULL);
4445         ovsrec_interface_set_link_speed(if_cfg, NULL, 0);
4446         ovsrec_interface_set_link_state(if_cfg, NULL);
4447         ovsrec_interface_set_mac_in_use(if_cfg, NULL);
4448         ovsrec_interface_set_mtu(if_cfg, NULL, 0);
4449         ovsrec_interface_set_cfm_fault(if_cfg, NULL, 0);
4450         ovsrec_interface_set_cfm_fault_status(if_cfg, NULL, 0);
4451         ovsrec_interface_set_cfm_remote_mpids(if_cfg, NULL, 0);
4452         ovsrec_interface_set_lacp_current(if_cfg, NULL, 0);
4453         ovsrec_interface_set_statistics(if_cfg, NULL, NULL, 0);
4454         ovsrec_interface_set_ifindex(if_cfg, NULL, 0);
4455     }
4456 }
4457
4458 static bool
4459 queue_ids_include(const struct ovsdb_datum *queues, int64_t target)
4460 {
4461     union ovsdb_atom atom;
4462
4463     atom.integer = target;
4464     return ovsdb_datum_find_key(queues, &atom, OVSDB_TYPE_INTEGER) != UINT_MAX;
4465 }
4466
4467 static void
4468 iface_configure_qos(struct iface *iface, const struct ovsrec_qos *qos)
4469 {
4470     struct ofpbuf queues_buf;
4471
4472     ofpbuf_init(&queues_buf, 0);
4473
4474     if (!qos || qos->type[0] == '\0') {
4475         netdev_set_qos(iface->netdev, NULL, NULL);
4476     } else {
4477         const struct ovsdb_datum *queues;
4478         struct netdev_queue_dump dump;
4479         unsigned int queue_id;
4480         struct smap details;
4481         bool queue_zero;
4482         size_t i;
4483
4484         /* Configure top-level Qos for 'iface'. */
4485         netdev_set_qos(iface->netdev, qos->type, &qos->other_config);
4486
4487         /* Deconfigure queues that were deleted. */
4488         queues = ovsrec_qos_get_queues(qos, OVSDB_TYPE_INTEGER,
4489                                        OVSDB_TYPE_UUID);
4490         smap_init(&details);
4491         NETDEV_QUEUE_FOR_EACH (&queue_id, &details, &dump, iface->netdev) {
4492             if (!queue_ids_include(queues, queue_id)) {
4493                 netdev_delete_queue(iface->netdev, queue_id);
4494             }
4495         }
4496         smap_destroy(&details);
4497
4498         /* Configure queues for 'iface'. */
4499         queue_zero = false;
4500         for (i = 0; i < qos->n_queues; i++) {
4501             const struct ovsrec_queue *queue = qos->value_queues[i];
4502             unsigned int queue_id = qos->key_queues[i];
4503
4504             if (queue_id == 0) {
4505                 queue_zero = true;
4506             }
4507
4508             if (queue->n_dscp == 1) {
4509                 struct ofproto_port_queue *port_queue;
4510
4511                 port_queue = ofpbuf_put_uninit(&queues_buf,
4512                                                sizeof *port_queue);
4513                 port_queue->queue = queue_id;
4514                 port_queue->dscp = queue->dscp[0];
4515             }
4516
4517             netdev_set_queue(iface->netdev, queue_id, &queue->other_config);
4518         }
4519         if (!queue_zero) {
4520             struct smap details;
4521
4522             smap_init(&details);
4523             netdev_set_queue(iface->netdev, 0, &details);
4524             smap_destroy(&details);
4525         }
4526     }
4527
4528     if (iface->ofp_port != OFPP_NONE) {
4529         const struct ofproto_port_queue *port_queues = queues_buf.data;
4530         size_t n_queues = queues_buf.size / sizeof *port_queues;
4531
4532         ofproto_port_set_queues(iface->port->bridge->ofproto, iface->ofp_port,
4533                                 port_queues, n_queues);
4534     }
4535
4536     netdev_set_policing(iface->netdev,
4537                         MIN(UINT32_MAX, iface->cfg->ingress_policing_rate),
4538                         MIN(UINT32_MAX, iface->cfg->ingress_policing_burst));
4539
4540     ofpbuf_uninit(&queues_buf);
4541 }
4542
4543 static void
4544 iface_configure_cfm(struct iface *iface)
4545 {
4546     const struct ovsrec_interface *cfg = iface->cfg;
4547     const char *opstate_str;
4548     const char *cfm_ccm_vlan;
4549     struct cfm_settings s;
4550     struct smap netdev_args;
4551
4552     if (!cfg->n_cfm_mpid) {
4553         ofproto_port_clear_cfm(iface->port->bridge->ofproto, iface->ofp_port);
4554         return;
4555     }
4556
4557     s.check_tnl_key = false;
4558     smap_init(&netdev_args);
4559     if (!netdev_get_config(iface->netdev, &netdev_args)) {
4560         const char *key = smap_get(&netdev_args, "key");
4561         const char *in_key = smap_get(&netdev_args, "in_key");
4562
4563         s.check_tnl_key = (key && !strcmp(key, "flow"))
4564                            || (in_key && !strcmp(in_key, "flow"));
4565     }
4566     smap_destroy(&netdev_args);
4567
4568     s.mpid = *cfg->cfm_mpid;
4569     s.interval = smap_get_int(&iface->cfg->other_config, "cfm_interval", 0);
4570     cfm_ccm_vlan = smap_get(&iface->cfg->other_config, "cfm_ccm_vlan");
4571     s.ccm_pcp = smap_get_int(&iface->cfg->other_config, "cfm_ccm_pcp", 0);
4572
4573     if (s.interval <= 0) {
4574         s.interval = 1000;
4575     }
4576
4577     if (!cfm_ccm_vlan) {
4578         s.ccm_vlan = 0;
4579     } else if (!strcasecmp("random", cfm_ccm_vlan)) {
4580         s.ccm_vlan = CFM_RANDOM_VLAN;
4581     } else {
4582         s.ccm_vlan = atoi(cfm_ccm_vlan);
4583         if (s.ccm_vlan == CFM_RANDOM_VLAN) {
4584             s.ccm_vlan = 0;
4585         }
4586     }
4587
4588     s.extended = smap_get_bool(&iface->cfg->other_config, "cfm_extended",
4589                                false);
4590     s.demand = smap_get_bool(&iface->cfg->other_config, "cfm_demand", false);
4591
4592     opstate_str = smap_get(&iface->cfg->other_config, "cfm_opstate");
4593     s.opup = !opstate_str || !strcasecmp("up", opstate_str);
4594
4595     ofproto_port_set_cfm(iface->port->bridge->ofproto, iface->ofp_port, &s);
4596 }
4597
4598 /* Returns true if 'iface' is synthetic, that is, if we constructed it locally
4599  * instead of obtaining it from the database. */
4600 static bool
4601 iface_is_synthetic(const struct iface *iface)
4602 {
4603     return ovsdb_idl_row_is_synthetic(&iface->cfg->header_);
4604 }
4605
4606 static ofp_port_t
4607 iface_validate_ofport__(size_t n, int64_t *ofport)
4608 {
4609     return (n && *ofport >= 1 && *ofport < ofp_to_u16(OFPP_MAX)
4610             ? u16_to_ofp(*ofport)
4611             : OFPP_NONE);
4612 }
4613
4614 static ofp_port_t
4615 iface_get_requested_ofp_port(const struct ovsrec_interface *cfg)
4616 {
4617     return iface_validate_ofport__(cfg->n_ofport_request, cfg->ofport_request);
4618 }
4619
4620 static ofp_port_t
4621 iface_pick_ofport(const struct ovsrec_interface *cfg)
4622 {
4623     ofp_port_t requested_ofport = iface_get_requested_ofp_port(cfg);
4624     return (requested_ofport != OFPP_NONE
4625             ? requested_ofport
4626             : iface_validate_ofport__(cfg->n_ofport, cfg->ofport));
4627 }
4628 \f
4629 /* Port mirroring. */
4630
4631 static struct mirror *
4632 mirror_find_by_uuid(struct bridge *br, const struct uuid *uuid)
4633 {
4634     struct mirror *m;
4635
4636     HMAP_FOR_EACH_IN_BUCKET (m, hmap_node, uuid_hash(uuid), &br->mirrors) {
4637         if (uuid_equals(uuid, &m->uuid)) {
4638             return m;
4639         }
4640     }
4641     return NULL;
4642 }
4643
4644 static void
4645 bridge_configure_mirrors(struct bridge *br)
4646 {
4647     const struct ovsdb_datum *mc;
4648     unsigned long *flood_vlans;
4649     struct mirror *m, *next;
4650     size_t i;
4651
4652     /* Get rid of deleted mirrors. */
4653     mc = ovsrec_bridge_get_mirrors(br->cfg, OVSDB_TYPE_UUID);
4654     HMAP_FOR_EACH_SAFE (m, next, hmap_node, &br->mirrors) {
4655         union ovsdb_atom atom;
4656
4657         atom.uuid = m->uuid;
4658         if (ovsdb_datum_find_key(mc, &atom, OVSDB_TYPE_UUID) == UINT_MAX) {
4659             mirror_destroy(m);
4660         }
4661     }
4662
4663     /* Add new mirrors and reconfigure existing ones. */
4664     for (i = 0; i < br->cfg->n_mirrors; i++) {
4665         const struct ovsrec_mirror *cfg = br->cfg->mirrors[i];
4666         struct mirror *m = mirror_find_by_uuid(br, &cfg->header_.uuid);
4667         if (!m) {
4668             m = mirror_create(br, cfg);
4669         }
4670         m->cfg = cfg;
4671         if (!mirror_configure(m)) {
4672             mirror_destroy(m);
4673         }
4674     }
4675
4676     /* Update flooded vlans (for RSPAN). */
4677     flood_vlans = vlan_bitmap_from_array(br->cfg->flood_vlans,
4678                                          br->cfg->n_flood_vlans);
4679     ofproto_set_flood_vlans(br->ofproto, flood_vlans);
4680     bitmap_free(flood_vlans);
4681 }
4682
4683 static struct mirror *
4684 mirror_create(struct bridge *br, const struct ovsrec_mirror *cfg)
4685 {
4686     struct mirror *m;
4687
4688     m = xzalloc(sizeof *m);
4689     m->uuid = cfg->header_.uuid;
4690     hmap_insert(&br->mirrors, &m->hmap_node, uuid_hash(&m->uuid));
4691     m->bridge = br;
4692     m->name = xstrdup(cfg->name);
4693
4694     return m;
4695 }
4696
4697 static void
4698 mirror_destroy(struct mirror *m)
4699 {
4700     if (m) {
4701         struct bridge *br = m->bridge;
4702
4703         if (br->ofproto) {
4704             ofproto_mirror_unregister(br->ofproto, m);
4705         }
4706
4707         hmap_remove(&br->mirrors, &m->hmap_node);
4708         free(m->name);
4709         free(m);
4710     }
4711 }
4712
4713 static void
4714 mirror_collect_ports(struct mirror *m,
4715                      struct ovsrec_port **in_ports, int n_in_ports,
4716                      void ***out_portsp, size_t *n_out_portsp)
4717 {
4718     void **out_ports = xmalloc(n_in_ports * sizeof *out_ports);
4719     size_t n_out_ports = 0;
4720     size_t i;
4721
4722     for (i = 0; i < n_in_ports; i++) {
4723         const char *name = in_ports[i]->name;
4724         struct port *port = port_lookup(m->bridge, name);
4725         if (port) {
4726             out_ports[n_out_ports++] = port;
4727         } else {
4728             VLOG_WARN("bridge %s: mirror %s cannot match on nonexistent "
4729                       "port %s", m->bridge->name, m->name, name);
4730         }
4731     }
4732     *out_portsp = out_ports;
4733     *n_out_portsp = n_out_ports;
4734 }
4735
4736 static bool
4737 mirror_configure(struct mirror *m)
4738 {
4739     const struct ovsrec_mirror *cfg = m->cfg;
4740     struct ofproto_mirror_settings s;
4741
4742     /* Set name. */
4743     if (strcmp(cfg->name, m->name)) {
4744         free(m->name);
4745         m->name = xstrdup(cfg->name);
4746     }
4747     s.name = m->name;
4748
4749     /* Get output port or VLAN. */
4750     if (cfg->output_port) {
4751         s.out_bundle = port_lookup(m->bridge, cfg->output_port->name);
4752         if (!s.out_bundle) {
4753             VLOG_ERR("bridge %s: mirror %s outputs to port not on bridge",
4754                      m->bridge->name, m->name);
4755             return false;
4756         }
4757         s.out_vlan = UINT16_MAX;
4758
4759         if (cfg->output_vlan) {
4760             VLOG_ERR("bridge %s: mirror %s specifies both output port and "
4761                      "output vlan; ignoring output vlan",
4762                      m->bridge->name, m->name);
4763         }
4764     } else if (cfg->output_vlan) {
4765         /* The database should prevent invalid VLAN values. */
4766         s.out_bundle = NULL;
4767         s.out_vlan = *cfg->output_vlan;
4768     } else {
4769         VLOG_ERR("bridge %s: mirror %s does not specify output; ignoring",
4770                  m->bridge->name, m->name);
4771         return false;
4772     }
4773
4774     if (cfg->snaplen) {
4775         s.snaplen = *cfg->snaplen;
4776     } else {
4777         s.snaplen = 0;
4778     }
4779
4780     /* Get port selection. */
4781     if (cfg->select_all) {
4782         size_t n_ports = hmap_count(&m->bridge->ports);
4783         void **ports = xmalloc(n_ports * sizeof *ports);
4784         struct port *port;
4785         size_t i;
4786
4787         i = 0;
4788         HMAP_FOR_EACH (port, hmap_node, &m->bridge->ports) {
4789             ports[i++] = port;
4790         }
4791
4792         s.srcs = ports;
4793         s.n_srcs = n_ports;
4794
4795         s.dsts = ports;
4796         s.n_dsts = n_ports;
4797     } else {
4798         /* Get ports, dropping ports that don't exist.
4799          * The IDL ensures that there are no duplicates. */
4800         mirror_collect_ports(m, cfg->select_src_port, cfg->n_select_src_port,
4801                              &s.srcs, &s.n_srcs);
4802         mirror_collect_ports(m, cfg->select_dst_port, cfg->n_select_dst_port,
4803                              &s.dsts, &s.n_dsts);
4804     }
4805
4806     /* Get VLAN selection. */
4807     s.src_vlans = vlan_bitmap_from_array(cfg->select_vlan, cfg->n_select_vlan);
4808
4809     /* Configure. */
4810     ofproto_mirror_register(m->bridge->ofproto, m, &s);
4811
4812     /* Clean up. */
4813     if (s.srcs != s.dsts) {
4814         free(s.dsts);
4815     }
4816     free(s.srcs);
4817     free(s.src_vlans);
4818
4819     return true;
4820 }
4821
4822 \f
4823 static void
4824 mirror_refresh_stats(struct mirror *m)
4825 {
4826     struct ofproto *ofproto = m->bridge->ofproto;
4827     uint64_t tx_packets, tx_bytes;
4828     const char *keys[2];
4829     int64_t values[2];
4830     size_t stat_cnt = 0;
4831
4832     if (ofproto_mirror_get_stats(ofproto, m, &tx_packets, &tx_bytes)) {
4833         ovsrec_mirror_set_statistics(m->cfg, NULL, NULL, 0);
4834         return;
4835     }
4836
4837     if (tx_packets != UINT64_MAX) {
4838         keys[stat_cnt] = "tx_packets";
4839         values[stat_cnt] = tx_packets;
4840         stat_cnt++;
4841     }
4842     if (tx_bytes != UINT64_MAX) {
4843         keys[stat_cnt] = "tx_bytes";
4844         values[stat_cnt] = tx_bytes;
4845         stat_cnt++;
4846     }
4847
4848     ovsrec_mirror_set_statistics(m->cfg, keys, values, stat_cnt);
4849 }
4850
4851 /*
4852  * Add registered netdev and dpif types to ovsdb to allow external
4853  * applications to query the capabilities of the Open vSwitch instance
4854  * running on the node.
4855  */
4856 static void
4857 discover_types(const struct ovsrec_open_vswitch *cfg)
4858 {
4859     struct sset types;
4860
4861     /* Datapath types. */
4862     sset_init(&types);
4863     dp_enumerate_types(&types);
4864     const char **datapath_types = sset_array(&types);
4865     ovsrec_open_vswitch_set_datapath_types(cfg, datapath_types,
4866                                            sset_count(&types));
4867     free(datapath_types);
4868     sset_destroy(&types);
4869
4870     /* Port types. */
4871     sset_init(&types);
4872     netdev_enumerate_types(&types);
4873     const char **iface_types = sset_array(&types);
4874     ovsrec_open_vswitch_set_iface_types(cfg, iface_types, sset_count(&types));
4875     free(iface_types);
4876     sset_destroy(&types);
4877 }