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