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