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